id
int64 1
722k
| file_path
stringlengths 8
177
| funcs
stringlengths 1
35.8M
|
---|---|---|
101 | ./libzt/src/zt_uuid.c | #ifdef HAVE_CONFIG_H
# include "zt_config.h"
#endif /* HAVE_CONFIG_H */
#ifdef HAVE_STRING_H
# include <string.h>
#endif /* HAVE_STRING_H */
#include <stdio.h>
#include <math.h>
#include "zt.h"
#include "zt_internal.h"
zt_uuid_t NAMESPACE_DNS = { { { 0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8 } } };
zt_uuid_t NAMESPACE_URL = { { { 0x6b, 0xa7, 0xb8, 0x11, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8 } } };
zt_uuid_t NAMESPACE_OID = { { { 0x6b, 0xa7, 0xb8, 0x12, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8 } } };
zt_uuid_t NAMESPACE_X500 = { { { 0x6b, 0xa7, 0xb8, 0x14, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8 } } };
static int rand_initialized = 0;
#define _UUID_BASE62_SEGMENT UUID_BASE62_STR_LEN / 2
static const char base62_alphabet[63] = \
"0123456789"
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static int base62_encode_int64(uint64_t in, char * out, size_t olen);
static int base62_decode_int64(const char * in, size_t ilen, uint64_t * out);
void srandomdev(void);
#ifndef HAVE_SRANDOMDEV
#include <fcntl.h>
#include <time.h>
void
srandomdev(void) {
int fd;
uint32_t rand_data;
fd = open("/dev/urandom", O_RDONLY);
if (fd < 0 || read(fd, &rand_data,
sizeof(uint32_t)) != sizeof(uint32_t)) {
/* this is a shitty situation.... */
rand_data = (uint32_t)time(NULL);
}
if (fd >= 0) {
close(fd);
}
srandom(rand_data);
}
#endif /* ifndef HAVE_SRANDOMDEV */
int
zt_uuid4(zt_uuid_t * uuid) {
long v;
zt_assert(uuid);
if (rand_initialized == 0) {
srandomdev();
rand_initialized = 1;
}
v = random(), memcpy(&uuid->data.bytes, &v, 4);
v = random(), memcpy(&uuid->data.bytes[4], &v, 4);
v = random(), memcpy(&uuid->data.bytes[8], &v, 4);
v = random(), memcpy(&uuid->data.bytes[12], &v, 4);
/* set the version number */
uuid->data.bytes[UUID_VERSION_OFFT] = (uuid->data.bytes[UUID_VERSION_OFFT] & 0x0F) | (UUID_VER_PSEUDORANDOM << 4);
/* clear the clock bits */
uuid->data.bytes[UUID_CLOCK_SEQ_OFFT] = (uuid->data.bytes[UUID_CLOCK_SEQ_OFFT] & 0x3F) | 0x80;
return 0;
}
int
zt_uuid5(char * value, size_t vlen, zt_uuid_ns type, zt_uuid_t * uuid) {
zt_sha1_ctx ctx;
uint8_t digest[20];
zt_sha1_init(&ctx);
switch (type) {
case UUID_NS_DNS:
zt_sha1_update(&ctx, NAMESPACE_DNS.data.bytes, UUID_ALEN);
break;
case UUID_NS_URL:
zt_sha1_update(&ctx, NAMESPACE_URL.data.bytes, UUID_ALEN);
break;
case UUID_NS_OID:
zt_sha1_update(&ctx, NAMESPACE_OID.data.bytes, UUID_ALEN);
break;
case UUID_NS_X500:
zt_sha1_update(&ctx, NAMESPACE_X500.data.bytes, UUID_ALEN);
break;
default:
zt_log_printf(zt_log_err, "unknown namespace %d", type);
return -1;
}
zt_sha1_update(&ctx, (uint8_t*)value, vlen);
zt_sha1_finalize(&ctx, digest);
memcpy(uuid->data.bytes, digest, UUID_ALEN);
/* set the version number */
uuid->data.bytes[UUID_VERSION_OFFT] = (uuid->data.bytes[UUID_VERSION_OFFT] & 0x0F) | (UUID_VER_NAMESPACE_SHA1 << 4);
/* clear the clock bits */
uuid->data.bytes[UUID_CLOCK_SEQ_OFFT] = (uuid->data.bytes[UUID_CLOCK_SEQ_OFFT] & 0x3F) | 0x80;
return 0;
}
/*
* _flagToSize
*
* Internal function returning the minimun necessary buffersize for each of the valid formats.
* Returns zero on unknown format.
*/
size_t
_flagToSize(zt_uuid_flags_t flags) {
size_t oSz = 0;
switch (flags) {
case zt_uuid_std_fmt:
oSz = UUID_STR_LEN + 1;
break;
case zt_uuid_short_fmt:
oSz = UUID_SHORT_STR_LEN + 1;
break;
case zt_uuid_base62_hashable_fmt:
/* FALLTHRU */
case zt_uuid_base62_fmt:
oSz = UUID_BASE62_STR_LEN + 1;
break;
default:
zt_assert(false);
break;
}
return oSz;
}
/*
* _zt_uuid_fillstr
*
* Internal function that formats and copies into 'uuids' a represent of the 'uuid' as specified by 'flags'.
*
* Input:
* uuid - [Required] A pointer to a valid zt_uuid_t structure.
* uuids - [Required] A pointer to a character buffer in which to copy the string.
* uuids_size - [Required] Pointer to a size_t containing the number of bytes allocated
* in 'uuids'.
* flags - [Required] One of [zt_uuid_base62_fmt, zt_uuid_base62_hashable_fmt, zt_uuid_std_fmt, zt_uuid_short_fmt]
*
* Output:
* - Upon successful return, the function will return the number of characters copied into
* the param 'uuids', not including the terminating NULL byte.
* - A return value < 0 indicates an error.
*
*/
ssize_t
_zt_uuid_fillstr(zt_uuid_t* uuid, char* uuids, size_t uuids_size, zt_uuid_flags_t flags) {
int oLen = 0;
if ((flags == zt_uuid_base62_fmt) || (flags == zt_uuid_base62_hashable_fmt)) {
uint64_t v1 = 0;
uint64_t v2 = 0;
int x = 0;
int i = 0;
int ok1 = 0;
int ok2 = 0;
/* extract the 2 64 bit numbers in the uuid */
zt_assert(uuids_size <= UUID_BASE62_STR_LEN + 1);
for (i = 0; i < 8; i++) {
const int shift = (7 - i) * 8;
v1 |= ((uint64_t)uuid->data.bytes[i] << shift);
v2 |= ((uint64_t)uuid->data.bytes[i + 8] << shift);
}
if (flags == zt_uuid_base62_hashable_fmt) {
char t_uuids[_UUID_BASE62_SEGMENT];
ok1 = base62_encode_int64(v1, t_uuids, _UUID_BASE62_SEGMENT);
/* reverse the first _UUID_BASE62_SEGMENT bytes to move the less truncated bits forward */
for (x=0, i = _UUID_BASE62_SEGMENT-1; i >= 0; i--, x++) {
uuids[x] = t_uuids[i];
}
} else {
ok1 = base62_encode_int64(v1, uuids, _UUID_BASE62_SEGMENT);
}
ok2 = base62_encode_int64(v2, uuids + _UUID_BASE62_SEGMENT, _UUID_BASE62_SEGMENT);
if (ok1 >= 0 && ok2 >= 0) {
oLen = UUID_BASE62_STR_LEN;
uuids[oLen] = 0;
} else {
oLen = -1;
}
} else {
char uuids_hex[UUID_SHORT_STR_LEN];
const char * fmt = NULL;
zt_assert(flags == zt_uuid_std_fmt || flags == zt_uuid_short_fmt);
fmt = (flags == zt_uuid_std_fmt) ? "%8.8s-%4.4s-%4.4s-%4.4s-%12.12s" : "%8.8s%4.4s%4.4s%4.4s%12.12s";
zt_binary_to_hex(uuid->data.bytes, UUID_ALEN, uuids_hex, UUID_SHORT_STR_LEN);
oLen = snprintf(uuids, uuids_size, fmt,
uuids_hex,
&uuids_hex[8],
&uuids_hex[12],
&uuids_hex[16],
&uuids_hex[20]);
zt_assert(flags != zt_uuid_std_fmt || oLen == UUID_STR_LEN);
zt_assert(flags != zt_uuid_short_fmt || oLen == UUID_SHORT_STR_LEN);
}
return oLen;
} /* _zt_uuid_fillstr */
/*
* zt_uuid_tostr
*
* Allocates and returns a string in 'uuids' representing 'uuid' as specified by 'flags'.
*
* Input:
* uuid - [Required] A pointer to a valid zt_uuid_t structure.
* uuids - [Required] A pointer to a character buffer in which to copy the string.
* flags - [Required] One of [zt_uuid_base62_fmt, zt_uuid_base62_hashable_fmt, zt_uuid_std_fmt, zt_uuid_short_fmt]
*
* Output:
*
* - Upon successful return, '*uuids' will contain a pointer to a string containting a ASCII
* representation of 'uuid'. The function will return the number of characters copied into
* '*uuids'. The caller is responsible for deallocating the string with zt_free.
* - A return value < 0 indicates an error.
*
*/
ssize_t
zt_uuid_tostr(zt_uuid_t * uuid, char ** uuids, zt_uuid_flags_t flags) {
ssize_t oVal;
size_t sz = 0;
if (!uuid || !uuids) {
return -1;
}
*uuids = NULL;
sz = _flagToSize(flags);
if (!sz) {
return -1;
}
*uuids = zt_calloc(char, sz);
if (!*uuids) {
return -1;
}
oVal = _zt_uuid_fillstr(uuid, *uuids, sz, flags);
if (oVal < 0) {
zt_free(*uuids);
*uuids = NULL;
}
return oVal;
} /* zt_uuid_tostr */
/*
* zt_uuid_fillstr
*
* Formats and copies into 'uuids' a represent of the 'uuid' as specified by 'flags'.
*
* Input:
* uuid - [Optional] A pointer to a valid zt_uuid_t structure.
* uuids - [Optional] A pointer to a character buffer in which to copy the string.
* uuids_size - [Required] Pointer to a size_t containing the number of bytes allocated
* in 'uuids'.
* flags - [Required] One of [zt_uuid_base62_fmt, zt_uuid_base62_hashable_fmt, zt_uuid_std_fmt, zt_uuid_short_fmt]
*
* Output:
* - Upon successful return, the function will return the number of characters copied into
* the param 'uuids', not including the terminating NULL byte.
* - A return value < 0 indicates an error.
* - If either 'uuid' or 'uuids' is NULL, the function will set *uuids_size to the
* mininum of bytes required in 'uuids' given the param 'flags'. Will return 0.
* - If the buffer size passed in '*uuids_size' is inadequate, the function will set
* '*uuids_size' to the mininum of bytes required in 'uuids' and return 0.
*/
ssize_t
zt_uuid_fillstr(zt_uuid_t* uuid, char* uuids, size_t* uuids_size, zt_uuid_flags_t flags) {
size_t sizerequired = _flagToSize(flags);
if (!sizerequired || !uuids_size) {
return -1; /* Bad input */
}
/* User has asked how much data to allocate, or an inadequate string was passed in */
if (!uuid || !uuids || *uuids_size < sizerequired) {
*uuids_size = sizerequired;
return 0;
}
return _zt_uuid_fillstr(uuid, uuids, *uuids_size, flags);
} /* zt_uuid_fillstr */
int
zt_uuid_fromstr(char * uuidstr, zt_uuid_t * uuid, zt_uuid_flags_t flags) {
char uuid_hex[UUID_SHORT_STR_LEN + 1]; /* +1 for sscanf */
zt_assert(uuidstr);
zt_assert(uuid);
if (flags == zt_uuid_std_fmt) {
if (strlen(uuidstr) != UUID_STR_LEN) {
return -1;
}
sscanf(uuidstr, "%8s-%4s-%4s-%4s-%12s",
uuid_hex,
&uuid_hex[8],
&uuid_hex[12],
&uuid_hex[16],
&uuid_hex[20]);
zt_hex_to_binary(uuid_hex, UUID_SHORT_STR_LEN, uuid->data.bytes, UUID_ALEN);
} else if (flags == zt_uuid_short_fmt) {
if (strlen(uuidstr) != UUID_SHORT_STR_LEN) {
return -1;
}
memcpy(uuid_hex, uuidstr, UUID_SHORT_STR_LEN);
zt_hex_to_binary(uuid_hex, UUID_SHORT_STR_LEN, uuid->data.bytes, UUID_ALEN);
} else if ((flags == zt_uuid_base62_fmt) || (flags == zt_uuid_base62_hashable_fmt)) {
uint64_t v1 = 0;
uint64_t v2 = 0;
int i;
int x;
int ok1;
/* reverse the first _UUID_BASE62_SEGMENT bytes to move the less truncated bits forward */
if (flags == zt_uuid_base62_hashable_fmt) {
char t_uuidstr[_UUID_BASE62_SEGMENT];
for (x = 0, i = _UUID_BASE62_SEGMENT-1; i >= 0; i--, x++) {
t_uuidstr[x] = uuidstr[i];
}
ok1 = base62_decode_int64(t_uuidstr, _UUID_BASE62_SEGMENT, &v1);
} else {
ok1 = base62_decode_int64(uuidstr, _UUID_BASE62_SEGMENT, &v1);
}
if (ok1 != 0) {
return -1;
}
if (base62_decode_int64(uuidstr + _UUID_BASE62_SEGMENT, UUID_BASE62_STR_LEN, &v2) != 0) {
return -1;
}
for (i = 0; i < 8; i++) {
const int shift = (7 - i) * 8;
uuid->data.bytes[i] = (v1 >> shift) & 0xFF;
uuid->data.bytes[i + 8] = (v2 >> shift) & 0xFF;
}
} else {
zt_log_printf(zt_log_err, "unknown uuid format");
return -1;
}
return 0;
} /* zt_uuid_fromstr */
int
zt_uuid_cmp(zt_uuid_t * uuid, zt_uuid_t * uuid2) {
return memcmp(uuid->data.bytes, uuid2->data.bytes, UUID_ALEN);
}
#define VALID_CHARS "abcdefABCDEF0123456789"
int
zt_uuid_isvalid(char * uuid, zt_uuid_flags_t flags) {
size_t len;
size_t i;
if (uuid == NULL) {
return -1;
}
len = strlen(uuid);
switch (flags) {
case zt_uuid_std_fmt:
if (len != UUID_STR_LEN) {
return -1;
}
break;
case zt_uuid_short_fmt:
if (len != UUID_SHORT_STR_LEN) {
return -1;
}
break;
case zt_uuid_base62_hashable_fmt:
/* FALLTHRU */
case zt_uuid_base62_fmt:
if (len != UUID_BASE62_STR_LEN) {
return -1;
}
break;
default:
return -1;
}
/* 550e8400-e29b-41d4-a716-446655440000
* 550e8400 - e 2 9 b - 4 1 d 4 - a 7 1 6 - 446655440000
* 01234567 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 */
for (i = 0; i < len; i++) {
if (flags == zt_uuid_std_fmt) {
switch (i) {
case 8:
case 13:
case 18:
case 23:
if (uuid[i] != '-') {
return -1;
}
break;
default:
if (strchr(VALID_CHARS, uuid[i]) == NULL) {
return -1;
}
break;
}
} else if ((flags == zt_uuid_base62_fmt) || (flags == zt_uuid_base62_hashable_fmt)) {
if (strchr(base62_alphabet, uuid[i]) == NULL) {
return -1;
}
} else {
if (strchr(VALID_CHARS, uuid[i]) == NULL) {
return -1;
}
}
}
return 0;
} /* zt_uuid_isvalid */
static int
base62_encode_int64(uint64_t in, char * out, size_t olen) {
unsigned int i = _UUID_BASE62_SEGMENT;
int ret = 0;
if (!out || olen < _UUID_BASE62_SEGMENT) {
return -1;
}
while (in) {
const unsigned int v = (unsigned int)(in % 62);
out[--i] = base62_alphabet[v];
in /= 62;
}
ret = i;
while (i > 0) {
out[--i] = base62_alphabet[0];
}
if (olen > _UUID_BASE62_SEGMENT) {
out[_UUID_BASE62_SEGMENT] = 0;
}
return ret;
}
static int
base62_decode_int64(const char * in, size_t ilen, uint64_t * out) {
uint64_t v = 0;
const size_t tlen = (ilen > _UUID_BASE62_SEGMENT) ? _UUID_BASE62_SEGMENT : ilen;
size_t i;
if (!in || !out) {
return -1;
}
for (i = 0; i < tlen; i++) {
const char c = in[i];
int n;
/* shift back from our alphabet */
if (c >= '0' && c <= '9') {
n = c - '0';
} else if (c >= 'a' && c <= 'z') {
n = c - ('a' - 10); /* 10 = offset of 'a' in our alphabet */
} else if (c >= 'A' && c <= 'Z') {
n = c - ('A' - 36); /* 36 = offset of 'A' in our alphabet */
} else {
return -1; /* invalid character */
}
v += n * (uint64_t)(powl(62, tlen - i - 1));
}
*out = v;
return 0;
}
|
102 | ./libzt/src/zt_gc.c | #ifdef HAVE_CONFIG_H
# include "zt_config.h"
#endif /* HAVE_CONFIG_H */
#ifdef HAVE_STRING_H
# include <string.h>
#endif /* HAVE_STRING_H */
#include <stdio.h>
#define ZT_WITH_GC
#include "zt.h"
#include "zt_internal.h"
/*
* Implements a form of Baker's treadmill with 'write protection'
*
*/
static int one_is_white(zt_gc_collectable_t *mark)
{
return ZT_BIT_ISSET(mark->colour, colour); /* mark->colour == 1 ? 1 : 0; */
}
static void one_clear_white(zt_gc_collectable_t *mark)
{
ZT_BIT_UNSET(mark->colour, colour); /* mark->colour = 0; */
}
static void one_set_white(zt_gc_collectable_t *mark)
{
ZT_BIT_SET(mark->colour, colour); /* mark->colour = 1; */
}
static int zero_is_white(zt_gc_collectable_t *mark)
{
return ZT_BIT_ISUNSET(mark->colour, colour); /* mark->colour == 0 ? 1 : 0; */
}
static void zero_clear_white(zt_gc_collectable_t *mark)
{
ZT_BIT_SET(mark->colour, colour); /* mark->colour = 1; */
}
static void zero_set_white(zt_gc_collectable_t *mark)
{
ZT_BIT_UNSET(mark->colour, colour); /* mark->colour = 0; */
}
static int is_protected(zt_gc_collectable_t *mark)
{
return ZT_BIT_ISSET(mark->colour, protected);
}
void
zt_gc_protect(zt_gc_t *gc, void *value)
{
zt_gc_collectable_t * mark;
mark = (zt_gc_collectable_t *)value;
gc->clear_white(mark);
zt_elist_remove(&mark->list);
zt_elist_add(gc->grey, &mark->list);
ZT_BIT_SET(mark->colour, protected);
}
void
zt_gc_unprotect(zt_gc_t *gc UNUSED, void *value)
{
zt_gc_collectable_t * mark = value;
zt_assert(value);
ZT_BIT_UNSET(mark->colour, protected);
}
static void switch_white(zt_gc_t *gc)
{
if (gc->is_white == one_is_white) {
gc->is_white = zero_is_white;
gc->clear_white = zero_clear_white;
gc->set_white = zero_set_white;
} else {
gc->is_white = one_is_white;
gc->clear_white = one_clear_white;
gc->set_white = one_set_white;
}
}
static void
resize_rootset(zt_gc_t *gc, int new_size)
{
if (gc->rootset == NULL) {
gc->rootset = zt_calloc(zt_elist_t *, new_size);
gc->rootset_next = 0;
} else {
int diff = new_size - gc->rootset_size;
int i;
gc->rootset = zt_realloc(zt_elist_t *, gc->rootset, new_size);
for ( i = diff; i < new_size; i++) {
gc->rootset[i] = NULL;
}
}
gc->rootset_size = new_size;
}
static void
dump_elist(char *name, zt_elist_t *p)
{
zt_elist_t * tmp;
int c;
int count;
printf("%s %p [", name, (void *)p);
c = 1;
count = 0;
zt_elist_for_each(p, tmp) {
if (tmp->next == p) {
c = 0;
}
if (is_protected(zt_elist_data(tmp, zt_gc_collectable_t, list))) {
printf("p(%p)%s", (void *)tmp, c ? ", " : "");
} else {
printf("%p%s", (void *)tmp, c ? ", " : "");
}
if (++count >= 10) {
printf("\n" BLANK, INDENT_TO(strlen(name) + 2, 1, 0));
count = 0;
}
}
printf("]\n");
}
void
zt_gc_enable(zt_gc_t *gc)
{
gc->enabled++;
zt_assert(gc->enabled <= 0);
if (gc->enabled == 0 && gc->current_allocs >= gc->allocs_before_scan) {
zt_gc_scan(gc, 0);
}
}
void
zt_gc_disable(zt_gc_t *gc)
{
gc->enabled--;
}
void
zt_gc_init(zt_gc_t *gc,
void *private_data,
void (*mark_fn)(struct zt_gc *, void *, void *),
void (*release_fn)(struct zt_gc *, void *, void **),
int marks_per_scan,
int allocs_before_scan)
{
gc->enabled = 0;
zt_elist_reset(&gc->list_1);
zt_elist_reset(&gc->list_2);
zt_elist_reset(&gc->list_3);
gc->rootset = NULL;
resize_rootset(gc, 1024);
gc->black = &gc->list_1;
gc->grey = &gc->list_2;
gc->white = &gc->list_3;
gc->scan = gc->grey;
gc->marks_per_scan = marks_per_scan;
gc->allocs_before_scan = allocs_before_scan;
gc->current_allocs = 0;
/* initialize white */
gc->is_white = one_is_white;
gc->clear_white = one_clear_white;
gc->set_white = one_set_white;
gc->private_data = private_data;
gc->mark_fn = mark_fn;
gc->release_fn = release_fn;
}
void
zt_gc_destroy(zt_gc_t *gc)
{
zt_elist_t * elt;
zt_elist_t * dont_use;
if (gc->enabled != 0) {
printf("# Warning: destroying gc while gc is disabled\n");
gc->enabled = 0;
}
zt_gc_scan(gc, TRUE);
zt_elist_for_each_safe(gc->white, elt, dont_use) {
zt_elist_remove(elt);
gc->release_fn(gc, gc->private_data, (void **)&elt);
}
zt_elist_for_each_safe(gc->grey, elt, dont_use) {
zt_elist_remove(elt);
gc->release_fn(gc, gc->private_data, (void **)&elt);
}
zt_elist_for_each_safe(gc->black, elt, dont_use) {
zt_elist_remove(elt);
gc->release_fn(gc, gc->private_data, (void **)&elt);
}
/* clear the rootset, this should force us to clear all objects in
* the system
*/
/*
* for(i = 0; i < gc->rootset_next; i++){
* zt_gc_collectable_t * mark = (zt_gc_collectable_t *)gc->rootset[i];
* zt_elist_remove(&mark->list);
* /\* zt_elist_add(gc->white, &mark->list); *\/
* }
*/
zt_free(gc->rootset);
gc->rootset = NULL;
gc->rootset_next = 0;
gc->enabled = 1;
}
/*
* TODO: turn this into a wrapped list so that objects can be removed
* from the root set.
*/
void
zt_gc_register_root(zt_gc_t *gc, void *v)
{
zt_gc_collectable_t * mark = (zt_gc_collectable_t *)v;
zt_elist_reset(&mark->list);
zt_gc_protect(gc, v);
/*
* gc->clear_white(mark);
* zt_elist_add(gc->grey, &mark->list);
*/
/*
* gc->rootset[gc->rootset_next++] = &mark->list;
* if (gc->rootset_next >= gc->rootset_size) {
* resize_rootset(gc, gc->rootset_size + 1024);
* }
*/
}
void
zt_gc_prepare_value(zt_gc_t *gc UNUSED, void *v)
{
zt_gc_collectable_t * mark = (zt_gc_collectable_t *)v;
zt_elist_reset(&mark->list);
}
void
zt_gc_unregister_value(zt_gc_t *gc UNUSED, void *v)
{
zt_gc_collectable_t * mark = (zt_gc_collectable_t *)v;
zt_elist_remove(&mark->list);
}
void
zt_gc_register_value(zt_gc_t *gc, void *v)
{
zt_gc_collectable_t * mark = (zt_gc_collectable_t *)v;
zt_elist_reset(&mark->list);
gc->clear_white(mark);
/* The mutator is registering interest in this value so we must
* place it in the the grey list not the white.
*/
if (++gc->current_allocs >= gc->allocs_before_scan) {
zt_gc_scan(gc, 0);
}
/* rather then place the object in white and require the need for a
* write barrier we place the object in grey with the expectation that
* it is immediatly used. This means that we may hold a newly allocated
* object longer then necessary (one cycle).
*/
zt_elist_add_tail(gc->grey, &mark->list);
}
static void
zt_gc_free_white(zt_gc_t *gc)
{
zt_elist_t * elt = NULL;
zt_elist_t * dont_use = NULL;
zt_gc_collectable_t * mark;
if (zt_elist_empty(gc->white)) {
return;
}
zt_elist_for_each_safe(gc->white, elt, dont_use) {
/*
* if(is_protected((zt_gc_collectable_t *)elt)) {
* zt_elist_remove(elt);
* zt_elist_add(gc->grey, elt);
* } else {
*/
if (elt == gc->black || elt == gc->white || elt == gc->grey) {
/* zt_gc_print_heap(gc); */
zt_assert(elt != gc->grey);
zt_assert(elt != gc->white);
zt_assert(elt != gc->black);
}
mark = zt_elist_data(elt, zt_gc_collectable_t, list);
zt_assert(!is_protected(mark));
/* printf("Releasing: %p\n", (void *)elt); */
zt_elist_remove(elt);
gc->release_fn(gc, gc->private_data, (void **)&elt);
/* } */
}
/* printf("Done\n"); */
}
static void
zt_gc_switch(zt_gc_t *gc)
{
zt_elist_t * tmp_white;
/* in a traditional GC we would scan and reset the values here we
* free the white list and swap the white list with the black list
*/
gc->enabled--;
zt_gc_free_white(gc);
tmp_white = gc->white;
gc->white = gc->black;
gc->black = tmp_white;
switch_white(gc);
gc->enabled++;
}
void
zt_gc_scan(zt_gc_t *gc, int full_scan)
{
int current_marks = 0;
if (gc->enabled < 0 ||
(!full_scan && gc->current_allocs < gc->allocs_before_scan)) {
return;
}
gc->enabled--;
/* printf("Start Scan\n"); */
gc->current_allocs = 0;
if (gc->scan == gc->grey) {
/* beginning of a scan */
/*
* int i;
* for(i = 0; i < gc->rootset_next; i++) {
* /\* add each object in the rootset into the grey list *\/
* zt_gc_collectable_t * mark = (zt_gc_collectable_t *) gc->rootset[i];
* zt_elist_remove(&mark->list);
* zt_elist_add(gc->grey, &mark->list);
* }
*/
gc->scan = gc->scan->next;
}
while (gc->scan != gc->grey) {
/* move thru each object in the grey list moving it to the
* black list and marking it as we go.
*/
zt_elist_t * next;
zt_elist_t * elt;
zt_gc_collectable_t * mark;
elt = gc->scan;
mark = zt_elist_data(elt, zt_gc_collectable_t, list);
gc->clear_white(mark);
gc->mark_fn(gc, gc->private_data, elt);
next = gc->scan->next;
if (!is_protected(mark)) {
/* if it is protected leave it in the grey list */
zt_elist_remove(elt);
zt_elist_add(gc->black, elt);
}
gc->scan = next;
if (!full_scan && ++current_marks >= gc->marks_per_scan) {
if (gc->scan != gc->grey) {
/*
* zt_gc_print_heap(gc);
* printf("End Partial Scan\n");
*/
gc->enabled++;
return;
}
}
}
/*
* fprintf(stderr, "Completed Scan\n");
* zt_gc_print_heap(gc);
* printf("End Full Scan\n");
*/
gc->enabled++;
zt_gc_switch(gc);
} /* zt_gc_scan */
int
zt_gc_mark_value(zt_gc_t *gc, void *value)
{
zt_gc_collectable_t * mark = (zt_gc_collectable_t *)value;
zt_assert(value != NULL);
/*
* if (is_protected(mark)) {
* /\* printf("marking protected\n"); *\/
* gc->clear_white(mark);
* zt_elist_remove(&mark->list);
* zt_elist_add_tail(gc->grey, &mark->list);
* return TRUE;
* } else
*/
if (!is_protected(mark) && gc->is_white(mark)) {
gc->clear_white(mark);
zt_elist_remove(&mark->list);
zt_elist_add_tail(gc->grey, &mark->list);
return TRUE;
}
return FALSE;
}
void
zt_gc_print_heap(zt_gc_t *gc)
{
printf("Heap Dump\n============\n");
printf("l1: %p l2: %p l3: %p\nblack: %p grey: %p white: %p\nscan: %p\n",
(void *)&gc->list_1, (void *)&gc->list_2, (void *)&gc->list_3,
(void *)gc->black, (void *)gc->grey, (void *)gc->white, (void *)gc->scan);
dump_elist("Black", gc->black);
dump_elist("Grey", gc->grey);
dump_elist("White", gc->white);
}
void zt_gc_for_each(zt_gc_t * gc, void (*cb)(void * value, void * data, int ty), void * cb_data)
{
zt_elist_t * elt = NULL;
zt_elist_t * dont_use = NULL;
zt_gc_collectable_t * mark;
zt_elist_for_each_safe(gc->black, elt, dont_use) {
mark = zt_elist_data(elt, zt_gc_collectable_t, list);
cb(mark, cb_data, 0);
}
zt_elist_for_each_safe(gc->grey, elt, dont_use) {
mark = zt_elist_data(elt, zt_gc_collectable_t, list);
cb(mark, cb_data, 1);
}
zt_elist_for_each_safe(gc->white, elt, dont_use) {
mark = zt_elist_data(elt, zt_gc_collectable_t, list);
cb(mark, cb_data, 2);
}
}
|
103 | ./libzt/src/zt_ptr_array.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "zt.h"
#include "zt_stdint.h"
#include "zt_internal.h"
zt_ptr_array *
zt_ptr_array_init(void * args, zt_ptr_array_free_cb free_cb) {
zt_ptr_array * array;
if (!(array = zt_calloc(zt_ptr_array, 1))) {
return NULL;
}
array->size = ZT_PTR_ARRAY_DEFAULT_SIZE;
array->args = args;
array->free_cb = free_cb;
if (!(array->array = (void **)zt_malloc(void **, array->size))) {
zt_free(array);
return NULL;
}
return array;
}
int
zt_ptr_array_copy_data(zt_ptr_array * src, char ** dstbuf) {
int32_t i;
if (src == NULL || dstbuf == NULL) {
return -1;
}
for (i = 0; i < src->count; i++) {
dstbuf[i] = src->array[i];
}
return 0;
}
int
zt_ptr_array_resize(zt_ptr_array * array, int32_t expand) {
int32_t size;
char ** ndata;
if (array == NULL) {
return -1;
}
if (expand == 0) {
size = ZT_PTR_ARRAY_DEFAULT_SIZE;
} else {
size = expand;
}
if ((array->size + size) < array->size) {
/* error on overflow */
return -1;
}
if (!(ndata = zt_malloc(char *, (array->size + size)))) {
return -1;
}
if (zt_ptr_array_copy_data(array, ndata) < 0) {
return -1;
}
free(array->array);
array->array = (void **)ndata;
array->size += size;
return 0;
}
int
zt_ptr_array_move_idx_to_idx(zt_ptr_array * array, int32_t src_idx, int32_t dst_idx) {
if (src_idx > array->count) {
return -1;
}
if (dst_idx > array->count) {
return -1;
}
array->array[dst_idx] = array->array[src_idx];
return 0;
}
int
zt_ptr_array_del(zt_ptr_array * array, void * data) {
int32_t i;
if (array == NULL || data == NULL) {
return -1;
}
for (i = 0; i < array->count; i++) {
if (array->array[i] == data) {
zt_ptr_array_move_idx_to_idx(array, array->count - 1, i);
array->count--;
if (array->free_cb) {
array->free_cb(data);
}
}
}
return -1;
}
int
zt_ptr_array_cat(zt_ptr_array * dst, zt_ptr_array * src) {
int32_t i;
if (dst == NULL || src == NULL) {
return -1;
}
for (i = 0; i < src->count; i++) {
if (zt_ptr_array_add(dst, zt_ptr_array_get_idx(src, i))) {
return -1;
}
}
return 0;
}
int
zt_ptr_array_add(zt_ptr_array * array, void * data) {
if (data == NULL || array == NULL) {
return 0;
}
if (zt_ptr_array_is_full(array)) {
if (zt_ptr_array_resize(array, 0) < 0) {
return -1;
}
}
array->array[array->count] = data;
array->count++;
return 0;
}
int
zt_ptr_array_free(zt_ptr_array * array, int free_members) {
int32_t i;
if (array == NULL) {
return -1;
}
if (free_members > 0) {
for (i = 0; i < array->count; i++) {
void * memb;
if ((memb = array->array[i]) == NULL) {
continue;
}
if (array->free_cb) {
(array->free_cb)(memb);
} else {
zt_free(memb);
}
}
}
zt_free(array->array);
zt_free(array);
return 0;
}
void *
zt_ptr_array_get_idx(zt_ptr_array * array, int32_t idx) {
if (idx == -1) {
/* return the last element */
return array->array[array->count - 1];
}
if (idx >= array->count) {
return NULL;
}
return array->array[idx];
}
|
104 | ./libzt/src/zt_base.c | #include "zt_base.h"
typedef uint64_t _bits_t;
static zt_base_definition_t _base64_rfc = {
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/",
/* valid: alphanum, '+', '/'; allows CR,LF,'=',SP,TAB
* -1 (invalid) -2 (ignored)
*/
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -1, -1, -2, -1, -1, /* 0-15 */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 16-31 */
-2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* 32-47 */
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, /* 48-63 */
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 64-79 */
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* 80-95 */
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 96-111 */
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, /* 112-127 */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
},
64,
3,
4,
6,
'=',
zt_base_encode_with_padding
};
static zt_base_definition_t _base64_rfc_nopad = {
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/",
/* valid: alphanum, '+', '/'; allows CR,LF,'=',SP,TAB
* -1 (invalid) -2 (ignored)
*/
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -1, -1, -2, -1, -1, /* 0-15 */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 16-31 */
-2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* 32-47 */
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, /* 48-63 */
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 64-79 */
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* 80-95 */
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 96-111 */
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, /* 112-127 */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
},
64,
3,
4,
6,
'=',
0
};
static zt_base_definition_t _base64_uri = {
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789-_",
/* valid: alphanum, '-', '_'; ignores: CR,LF,'=',SP,TAB */
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -1, -1, -2, -1, -1, /* 0-15 */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 16-31 */
-2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, /* 32-47 */
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, /* 48-63 */
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 64-79 */
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63, /* 80-95 */
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 96-111 */
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, /* 112-127 */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
},
64,
3,
4,
6,
'=',
zt_base_encode_with_padding
};
zt_base_definition_t * zt_base64_rfc = &_base64_rfc;
zt_base_definition_t * zt_base64_rfc_nopad = &_base64_rfc_nopad;
zt_base_definition_t * zt_base64_uri = &_base64_uri;
static zt_base_definition_t _base32_rfc = {
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"234567",
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -1, -1, -2, -1, -1, /* 0-15 */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 16-31 */
-2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 32-47 */
-1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, -1, -2, -1, -1, /* 48-63 */
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 64-79 */
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* 80-95 */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 96-111 */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 112-127 */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
},
32,
5, /* in */
8, /* out */
5, /* bits */
'=',
zt_base_encode_with_padding
};
static zt_base_definition_t _base32_hex = {
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUV",
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -1, -1, -2, -1, -1, /* 0-15 */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 16-31 */
-2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 32-47 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -2, -1, -1, /* 48-63 */
-1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 64-79 */
25, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 80-95 */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 96-111 */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 112-127 */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
},
32,
5,
8,
5,
'=',
zt_base_encode_with_padding
};
zt_base_definition_t * zt_base32_rfc = &_base32_rfc;
zt_base_definition_t * zt_base32_hex = &_base32_hex;
static zt_base_definition_t _base16_rfc = {
"0123456789ABCDEF",
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -1, -1, -2, -1, -1, /* 0-15 */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 16-31 */
-2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 32-47 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -2, -1, -1, /* 48-63 */
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 64-79 */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 80-95 */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 96-111 */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 112-127 */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
},
16,
1,
2,
4,
'=',
0
};
zt_base_definition_t * zt_base16_rfc = &_base16_rfc;
static int
_valid_dictionary_p(zt_base_definition_t * def) {
if (!def) {
return 0;
}
if ( 8 * def->igroups != def->ogroups * def->obits) {
return 0;
}
/* can we overflow the bit container */
if ( def->igroups > sizeof(_bits_t)) {
return 0;
}
return 1;
}
static int
_encode64(zt_base_definition_t * def, const unsigned char * in, const size_t lcnt, const size_t mod, unsigned char * out) {
const char * alphabet = def->alphabet;
const char pad = def->pad;
size_t i = 0;
for (i=0; i < lcnt; i++) {
const unsigned int b0 = *in++;
const unsigned int b1 = *in++;
const unsigned int b2 = *in++;
/* b0 | b1 | b2
* 7 6 5 4 3 2 1 0 | 7 6 5 4 3 2 1 0 | 7 6 5 4 3 2 1 0
* |_________| |___________| |___________| |_________|
*/
*out++ = alphabet[ b0 >> 2 ];
*out++ = alphabet[ ((b0 & 0x03) << 4) | ((b1 & 0xF0) >> 4) ];
*out++ = alphabet[ ((b1 & 0x0F) << 2) | ((b2 & 0xC0) >> 6) ];
*out++ = alphabet[ b2 & 0x3F ];
}
if (mod > 0) {
const unsigned int b0 = *in++;
const unsigned int b1 = (mod > 1) ? *in++ : 0;
const unsigned int b2 = 0;
*out++ = alphabet[ b0 >> 2 ];
*out++ = alphabet[ ((b0 & 0x03) << 4) | ((b1 & 0xF0) >> 4) ];
if (mod > 1) {
*out++ = alphabet[ ((b1 & 0x0F) << 2) | ((b2 & 0xC0) >> 6) ];
}
if (ZT_BIT_ISSET(def->flags, zt_base_encode_with_padding)) {
for (i=0; i < (3 - mod); ++i) {
*out++ = pad;
}
}
}
return 0;
}
#define BUFSIZE_64 4
static int
_decode64(zt_base_definition_t * def, const unsigned char * in, const size_t bytes, unsigned char * out, size_t * out_bytes) {
size_t i;
const char * dictionary = def->dictionary;
unsigned int buf[BUFSIZE_64];
size_t cnt = 0;
size_t obytes = 0;
int result = 0;
for (i=0; i < bytes; i++) {
const int v = dictionary[*in++];
if (v >= 0) {
buf[cnt++] = v;
if (cnt == BUFSIZE_64) {
const unsigned int b0 = buf[0];
const unsigned int b1 = buf[1];
const unsigned int b2 = buf[2];
const unsigned int b3 = buf[3];
cnt = 0;
/* b0 | b1 | b2 | b4
* 7 6 5 4 3 2 | 1 0 7 6 5 4 | 3 2 1 0 7 6 | 5 4 3 2 1 0
* |_______________| |_______________| |_______________|
*/
*out++ = b0 << 2 | (b1 >> 4);
*out++ = (b1 & 0x0F) << 4 | (b2 >> 2);
*out++ = (b2 & 0x03) << 6 | b3;
obytes += 3;
}
} else if (v == -1) {
return -1;
}
}
if (cnt > 0) {
switch(cnt) {
case 1:
result = -1;
break;
case 2:
*out++ = buf[0] << 2 | (buf[1] >> 4);
break;
case 3:
*out++ = buf[0] << 2 | (buf[1] >> 4);
*out++ = (buf[1] & 0x0F) << 4 | (buf[2] >> 2);
break;
}
obytes += (cnt - 1);
}
*out_bytes = obytes;
return result;
}
static int
_encode32(zt_base_definition_t * def, const unsigned char * in, const size_t lcnt, const size_t mod, unsigned char * out) {
const char * alphabet = def->alphabet;
size_t i = 0;
for (i=0; i < lcnt; i++) {
const unsigned int b0 = *in++;
const unsigned int b1 = *in++;
const unsigned int b2 = *in++;
const unsigned int b3 = *in++;
const unsigned int b4 = *in++;
/* b0 | b1 | b2 | b3 | b4
* 7 6 5 4 3 2 1 0 | 7 6 5 4 3 2 1 0 | 7 6 5 4 3 2 1 0 | 7 6 5 4 3 2 1 0 | 7 6 5 4 3 2 1 0
* |_______| |_________| |_______| |_________| |_________| |_______| |_________| |_______|
*/
*out++ = alphabet[ b0 >> 3 ]; /* 5 bits out */
*out++ = alphabet[ ((b0 & 0x07) << 2) | ((b1 & 0xC0) >> 6) ];
*out++ = alphabet[ ((b1 & 0x3F) >> 1) ];
*out++ = alphabet[ ((b1 & 0x01) << 4) | ((b2 & 0xF0) >> 4) ];
*out++ = alphabet[ ((b2 & 0x0F) << 1) | ((b3 & 0x80) >> 7) ];
*out++ = alphabet[ ((b3 & 0x7C) >> 2) ];
*out++ = alphabet[ ((b3 & 0x03) << 3) | ((b4 & 0xE0) >> 5) ];
*out++ = alphabet[ b4 & 0x1F ];
}
if (mod > 0) {
const unsigned int b0 = *in++;
const unsigned int b1 = (mod > 1) ? *in++ : 0;
const unsigned int b2 = (mod > 2) ? *in++ : 0;
const unsigned int b3 = (mod > 3) ? *in++ : 0;
const unsigned int b4 = 0;
size_t pad;
*out++ = alphabet[ b0 >> 3 ]; /* 5 bits out */
*out++ = alphabet[ ((b0 & 0x07) << 2) | ((b1 & 0xC0) >> 6) ];
pad = 6;
if (mod > 1) {
*out++ = alphabet[ ((b1 & 0x3F) >> 1) ];
*out++ = alphabet[ ((b1 & 0x01) << 4) | ((b2 & 0xF0) >> 4) ];
pad = 4;
}
if (mod > 2) {
*out++ = alphabet[ ((b2 & 0x0F) << 1) | ((b3 & 0x80) >> 7) ];
pad = 3;
}
if (mod > 3) {
*out++ = alphabet[ ((b3 & 0x7C) >> 2) ];
*out++ = alphabet[ ((b3 & 0x03) << 3) | ((b4 & 0xE0) >> 5) ];
pad = 1;
}
/* *out++ = alphabet[ b4 & 0x1F ]; */
if (ZT_BIT_ISSET(def->flags, zt_base_encode_with_padding)) {
for (i=0; i < pad; ++i) {
*out++ = def->pad;
}
}
}
return 0;
}
#define BUFSIZE_32 8
static int
_decode32(zt_base_definition_t * def, const unsigned char * in, const size_t bytes, unsigned char * out, size_t * out_bytes) {
size_t i;
const char * dictionary = def->dictionary;
unsigned int buf[BUFSIZE_32];
size_t cnt = 0;
size_t obytes = 0;
int result = 0;
for (i=0; i < bytes; i++) {
const int v = dictionary[*in++];
if (v >= 0) {
buf[cnt++] = v;
if (cnt == BUFSIZE_32) {
const unsigned int b0 = buf[0];
const unsigned int b1 = buf[1];
const unsigned int b2 = buf[2];
const unsigned int b3 = buf[3];
const unsigned int b4 = buf[4];
const unsigned int b5 = buf[5];
const unsigned int b6 = buf[6];
const unsigned int b7 = buf[7];
cnt = 0;
/* b0 | b1 | b2 | b3 | b4 | b5 | b6 | b7
* 7 6 5 4 3 | 2 1 0 7 6 | 5 4 3 2 1 | 0 7 6 5 4 | 3 2 1 0 7 | 6 5 4 3 2 | 1 0 7 6 5 | 4 3 2 1 0
* |_______________| |_________________| |_______________| |_________________| |_______________|
*/
*out++ = b0 << 3 | b1 >> 2;
*out++ = b1 << 6 | b2 << 1 | b3 >> 4;
*out++ = b3 << 4 | b4 >> 1;
*out++ = b4 << 7 | b5 << 2 | b6 >> 3;
*out++ = b6 << 5 | b7;
obytes += 5;
}
} else if (v == -1) {
return -1;
}
}
if (cnt > 0) {
switch(cnt) {
case 1:
result = -1;
break;
case 2:
*out++ = buf[0] << 3 | buf[1] >> 2;
obytes += 1;
break;
case 3:
result = -1;
break;
case 4:
*out++ = buf[0] << 3 | buf[1] >> 2;
*out++ = buf[1] << 6 | buf[2] << 1 | buf[3] >> 4;
obytes += 2;
break;
case 5:
*out++ = buf[0] << 3 | buf[1] >> 2;
*out++ = buf[1] << 6 | buf[2] << 1 | buf[3] >> 4;
*out++ = buf[3] << 4 | buf[4] >> 1;
obytes += 3;
break;
case 6:
return -1;
break;
case 7:
*out++ = buf[0] << 3 | buf[1] >> 2;
*out++ = buf[1] << 6 | buf[2] << 1 | buf[3] >> 4;
*out++ = buf[3] << 4 | buf[4] >> 1;
*out++ = buf[4] << 7 | buf[5] << 2 | buf[6] >> 3;
obytes += 4;
break;
default:
result = -1;
break;
}
}
*out_bytes = obytes;
return result;
}
static int
_encode16(zt_base_definition_t * def, const unsigned char * in, const size_t lcnt, const size_t mod, unsigned char * out) {
const char * alphabet = def->alphabet;
size_t i = 0;
for (i=0; i < lcnt; i++) {
const unsigned int b0 = *in++;
/* IN: 1 * 8 bits (8 bits)
* OUT: 8 * 4 bits (8 bits)
*/
/* b0
* 7 6 5 4 3 2 1 0
* |_____| |_____|
*/
*out++ = alphabet[ b0 >> 4 ];
*out++ = alphabet[ b0 & 0x0F ];
}
return 0;
}
#define BUFSIZE_16 2
static int
_decode16(zt_base_definition_t * def, const unsigned char * in, const size_t bytes, unsigned char * out, size_t * out_bytes) {
size_t i;
const char * dictionary = def->dictionary;
unsigned int buf[BUFSIZE_16];
size_t cnt = 0;
size_t obytes = 0;
int result = 0;
for (i=0; i < bytes; i++) {
const int v = dictionary[*in++];
if (v >= 0) {
buf[cnt++] = v;
if (cnt == BUFSIZE_16) {
const unsigned int b0 = buf[0];
const unsigned int b1 = buf[1];
cnt = 0;
/* b0 | b1
* 7 6 5 4 | 3 2 1 0
* |_______________|
*/
*out++ = b0 << 4 | b1;
obytes += 1;
}
} else if (v == -1) {
return -1;
}
}
*out_bytes = obytes;
return result;
}
#define MAKE_MASK(x) ((1<<x)-1)
int
zt_base_encode(zt_base_definition_t * def, const void * in, size_t in_bytes, void **out, size_t *out_bytes) {
size_t ocount;
size_t lcount;
size_t mod;
size_t olen;
const unsigned char * inp = in;
unsigned char * outp = out ? *(unsigned char **)out : NULL;
if (! _valid_dictionary_p(def)) {
return -1;
}
/* if we are missing out_bytes then we cannot continue */
if (!out_bytes) {
return -1;
}
/* if there is no input then we cannot continue */
if(!in || !in_bytes) {
*out_bytes = 0;
return 0;
}
/* calculate the number of (N * 8-bit) input groups and remainder */
lcount = in_bytes / def->igroups; /* number of whole input groups */
mod = ((8 * (in_bytes % def->igroups)) / def->obits); /* portion of partial output groups */
ocount = (lcount * def->ogroups); /* number of whole output groups */
if (mod > 0) {
if ZT_BIT_ISSET(def->flags, zt_base_encode_with_padding) {
ocount += def->ogroups;
} else {
ocount += mod + 1;
}
}
if (out && outp == NULL && *out_bytes == 0) {
outp = zt_calloc(unsigned char, ocount);
*out = (void *)outp;
*out_bytes = ocount;
}
olen = *out_bytes;
*out_bytes = ocount;
/* if there is not enough space in the output then fail */
if (olen < ocount) {
return -2;
}
/* if there is no output then return just the size */
if (!out || !outp) {
return 0;
}
/* perform encoding */
switch(def->base) {
case 64:
return _encode64(def, inp, lcount, in_bytes % def->igroups, outp);
break;
case 32:
return _encode32(def, inp, lcount, in_bytes % def->igroups, outp);
break;
case 16:
return _encode16(def, inp, lcount, in_bytes % def->igroups, outp);
break;
default:
break;
}
return -1;
}
/*
* decodes the encoded data from void * in and writes the output to
* the void ** out pointer. If *out is NULL and *out_bytes is 0, *out is
* calloc'd and must be free()'d by the user.
*/
int
zt_base_decode(zt_base_definition_t * def, const void * in, size_t in_bytes, void ** out, size_t * out_bytes) {
const unsigned char * inp;
unsigned char * outp;
size_t lcount = 0;
size_t ocount = 0;
size_t mod = 0;
ssize_t i;
if (!_valid_dictionary_p(def)) {
return -1;
}
if (!out_bytes) {
return -1;
}
if (!in || !in_bytes) {
*out_bytes = 0;
return 0;
}
inp = (unsigned char *)in;
/* strip any follow on pad chars */
for (i=in_bytes-1; i > 0; i--) {
if (inp[i] != def->pad) {
i = in_bytes - 1 - i;
break;
}
}
lcount = (in_bytes-i) / def->ogroups; /* number of whole input groups */
mod = ((in_bytes-i) % def->ogroups); /* partial inputs */
ocount = (lcount * def->igroups) + mod; /* total output bytes */
if (out == NULL) {
*out_bytes = ocount;
return 0;
}
if (*out != NULL && *out_bytes < ocount) {
*out_bytes = ocount;
return -2;
}
outp = *((unsigned char **)out);
if ((outp == NULL && *out_bytes == 0)) {
/* dynamically allocate the buffer */
if (!(outp = zt_calloc(unsigned char, ocount+1))) {
return -1;
}
*out = outp;
*out_bytes = ocount;
}
switch(def->base) {
case 64:
return _decode64(def, inp, in_bytes, outp, out_bytes);
break;
case 32:
return _decode32(def, inp, in_bytes, outp, out_bytes);
break;
case 16:
return _decode16(def, inp, in_bytes, outp, out_bytes);
break;
default:
break;
}
return -1;
} /* zt_base_decode */
|
105 | ./libzt/src/zt_daemon.c | /*!
* Filename: zt_daemon.c
* Description: deamon tools
*
* Author: Jason L. Shiffer <jshiffer@zerotao.org>
* Copyright:
* Copyright (C) 2000-2010, Jason L. Shiffer.
* See file COPYING for details
*
* Notes:
*
*/
#ifdef HAVE_CONFIG_H
#include <zt_config.h>
#endif
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <limits.h>
#include "zt_internal.h"
#include "zt_log.h"
#include "zt_daemon.h"
/*!
* Name: zt_daemonize
*
* Description: deamonize a process following (for the most part) the
* rules defined by W. Richard Stevens "Advanced Programming in the UNIX
* Environment".
*
*/
int
zt_daemonize( char *root, mode_t mask, int options UNUSED)
{
pid_t pid;
pid_t pid2;
rlim_t i;
int status;
struct rlimit rlimits;
if ((pid = fork()) == (pid_t)(-1)) { /* first error */
zt_log_printf(zt_log_emerg, "failed to fork(): %s", strerror(errno));
exit(1);
} else if (pid == 0) { /* first child */
/* FIXME: Not everyone has setsid. Add support for them. */
if (setsid() == -1) {
zt_log_printf(zt_log_emerg, "faild to setsid(): %s", strerror(errno));
exit(1);
}
/* get the max number of open fd and close them */
memset(&rlimits, 0, sizeof(struct rlimit));
if (getrlimit(RLIMIT_NOFILE, &rlimits) == -1) {
zt_log_printf(zt_log_emerg, "faild to getlimit(): %s", strerror(errno));
exit(1);
}
for (i = 0; i < rlimits.rlim_cur; i++) {
if (i > INT_MAX) {
/* int cast protection */
i = INT_MAX;
}
close((int)i);
} /* Close all of the filehandles */
if ((pid2 = fork()) == (pid_t)(-1)) {
/* We can't produce an error here as we have already
* closed all of the file descriptors
*/
exit(1);
} else if (pid2 == 0) { /* second child */
int fd;
if (root != NULL) {
if(chdir(root) != 0) {
zt_log_printf(zt_log_crit, "Could not chdir %s", root);
exit(1);
}
}
umask(mask);
fd = open("/dev/null", O_RDWR); /* stdin */
/* we don't care about the results as we have no open pids at this point */
(void)dup(fd); /* stdout */
(void)dup(fd); /* stderr */
} else { /* second parent */
sleep(1);
exit(0);
}
} else { /* first parent */
/* wait here for the first child to exit */
wait(&status);
exit(0);
}
/* At this point we are in the second child properly forked and closed off */
return 0;
} /* zt_daemonize */
int
zt_writepid(const char* pidF) {
int oVal = -1;
int fd = -1;
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
if (!pidF) {
zt_log_strerror(zt_log_err, errno, "NULL pid file path.");
return -1;
}
fd = creat(pidF, mode);
if (fd != -1) {
const int bSize = 64;
char buf[bSize];
pid_t pid = getpid();
int sz = snprintf(buf, bSize, "%i\n", (int)pid);
if (sz > 0 && sz < bSize) {
ssize_t nBytes = write(fd, buf, sz);
while (nBytes == -1 && errno == EINTR) {
nBytes = write(fd, buf, sz);
}
if (nBytes == sz) {
oVal = 0;
} else {
zt_log_strerror(zt_log_err, errno, "Cannot write to pid file '%s'.", pidF);
}
} else {
zt_log_strerror(zt_log_err, errno, "Cannot format to pid file '%s'.", pidF);
}
int v = close(fd);
while (v == -1 && errno == EINTR) {
v = close(fd);
}
if (v) {
oVal = -1;
zt_log_strerror(zt_log_err, errno, "Cannot close pid fd '%s'.", pidF);
}
} else {
zt_log_strerror(zt_log_err, errno, "Cannot open pid file '%s' for writing.", pidF);
}
return oVal;
} /* zt_writepid */
|
106 | ./libzt/src/zt_bstream.c | #include "zt.h"
static size_t
_array_put(zt_array_t array, char *s, size_t offt, size_t len, int flip)
{
if (flip) {
s += len - 1;
while (len--) {
zt_array_put(array, offt++, s--);
}
} else {
while (len--) {
zt_array_put(array, offt++, s++);
}
}
return offt;
}
static size_t
_array_get(zt_array_t array, char *s, size_t offt, size_t len, int flip)
{
char *c;
if (flip) {
s += len - 1;
while (len--) {
c = zt_array_get(array, offt++);
*s-- = *c;
}
} else {
while (len--) {
c = zt_array_get(array, offt++);
*s++ = *c;
}
}
return offt;
}
int
zt_bstream_is_empty(zt_bstream_t bs)
{
zt_assert(bs);
return zt_array_length(bs->data) == 0;
}
size_t
zt_bstream_truncate(zt_bstream_t bs)
{
zt_assert(bs);
return zt_array_set_length(bs->data, 0);
}
void
zt_bstream_set_data(zt_bstream_t bs, char *data, int len, char copy)
{
zt_assert(bs);
zt_array_set_data(bs->data, data, len, sizeof(char), copy);
}
void
zt_bstream_set_array(zt_bstream_t bs, zt_array_t array, size_t offt)
{
zt_assert(bs);
zt_array_free(&bs->data);
bs->data = array;
bs->offt = offt;
}
size_t
zt_bstream_rewind(zt_bstream_t bs)
{
size_t oofft;
zt_assert(bs);
oofft = bs->offt;
bs->offt = 0;
return oofft;
}
zt_bstream_t
zt_bstream_new(void)
{
zt_bstream_t bs;
bs = zt_calloc(struct zt_bstream, 1);
bs->data = zt_array_new(0, sizeof(char));
return bs;
}
zt_bstream_t
zt_bstream_clone(zt_bstream_t bs)
{
zt_bstream_t clone;
zt_assert(bs);
clone = zt_calloc(struct zt_bstream, 1);
clone->data = zt_array_copy(bs->data, zt_array_length(bs->data));
clone->offt = bs->offt;
return clone;
}
void
zt_bstream_free(zt_bstream_t *bs)
{
zt_assert(bs);
zt_array_free(&(*bs)->data);
zt_free(*bs);
return;
}
size_t
zt_bstream_read(zt_bstream_t bs, char *buf, size_t len, char size, char tag UNUSED)
{
zt_assert(bs);
zt_assert(buf);
bs->offt = _array_get(bs->data, buf, bs->offt, (len * size), bs->flipendian);
return 0;
}
void
zt_bstream_read_byte(zt_bstream_t bs, char * data)
{
zt_bstream_read(bs, data, 1, sizeof(char), 0);
}
void
zt_bstream_read_uint8(zt_bstream_t bs, uint8_t * data)
{
zt_bstream_read(bs, (char *)data, 1, sizeof(uint8_t), 0);
}
void
zt_bstream_read_uint16(zt_bstream_t bs, uint16_t * data)
{
zt_bstream_read(bs, (char *)data, 1, sizeof(uint16_t), 0);
}
void
zt_bstream_read_uint32(zt_bstream_t bs, uint32_t * data)
{
zt_bstream_read(bs, (char *)data, 1, sizeof(uint32_t), 0);
}
void
zt_bstream_read_uint64(zt_bstream_t bs, uint64_t * data)
{
zt_bstream_read(bs, (char *)data, 1, sizeof(uint64_t), 0);
}
void
zt_bstream_read_float(zt_bstream_t bs, float * data)
{
zt_bstream_read(bs, (char *)data, 1, sizeof(float), 0);
}
void
zt_bstream_read_double(zt_bstream_t bs, double * data)
{
zt_bstream_read(bs, (char *)data, 1, sizeof(double), 0);
}
size_t
zt_bstream_write(zt_bstream_t bs, char *data, size_t len, char size, char tag UNUSED)
{
size_t tlen = len * size;
size_t alen = 0;
zt_assert(bs);
zt_assert(data);
alen = zt_array_length(bs->data);
if (tlen > alen - bs->offt) {
zt_array_resize(bs->data, (alen + tlen) * 2);
}
bs->offt = _array_put(bs->data, data, bs->offt, tlen, bs->flipendian);
return 0;
}
void
zt_bstream_write_byte(zt_bstream_t bs, char data)
{
zt_bstream_write(bs, &data, 1, sizeof(char), 0);
}
void
zt_bstream_write_uint8(zt_bstream_t bs, uint8_t data)
{
zt_bstream_write(bs, (char *)&data, 1, sizeof(uint8_t), 0);
}
void
zt_bstream_write_uint16(zt_bstream_t bs, uint16_t data)
{
zt_bstream_write(bs, (char *)&data, 1, sizeof(uint16_t), 0);
}
void
zt_bstream_write_uint32(zt_bstream_t bs, uint32_t data)
{
zt_bstream_write(bs, (char *)&data, 1, sizeof(uint32_t), 0);
}
void
zt_bstream_write_uint64(zt_bstream_t bs, uint64_t data)
{
zt_bstream_write(bs, (char *)&data, 1, sizeof(uint64_t), 0);
}
void
zt_bstream_write_float(zt_bstream_t bs, float data)
{
zt_bstream_write(bs, (char *)&data, 1, sizeof(float), 0);
}
void
zt_bstream_write_double(zt_bstream_t bs, double data)
{
zt_bstream_write(bs, (char *)&data, 1, sizeof(double), 0);
}
|
107 | ./libzt/src/zt_set.c | #include <errno.h>
#include "zt_set.h"
#include "zt_assert.h"
zt_set *
zt_set_init(int (*match)(const void *key1, size_t key1_size,
const void *key2, size_t key2_size, void *cdata),
void (*destroy)(void *data),
void *cdata)
{
zt_set * set;
set = zt_malloc(zt_set, 1);
set->tbl = zt_table_init(NULL, zt_table_hash_int, match, 128, 0, cdata);
set->match = match;
set->destroy = destroy;
set->length = 0;
return set;
}
static int
_destroy(void *key UNUSED, size_t key_size, void *datum, size_t datum_size, void *param)
{
void (*destroy)(void *) = ((zt_set *)param)->destroy;
if (destroy) {
destroy((void *)datum);
}
return 0;
}
void
zt_set_destroy(zt_set *set)
{
zt_assert(set);
zt_table_for_each(set->tbl, _destroy, set);
zt_table_destroy(set->tbl);
zt_free(set);
}
int
zt_set_insert(zt_set *set, const void *data, size_t len)
{
if (zt_set_is_member(set, data, len)) {
return 1;
}
set->length++;
return zt_table_set(set->tbl, (void *)data, len, (void *)data, len);
}
int zt_set_remove(zt_set *set, void **data)
{
*data = zt_table_del(set->tbl, *data, 0);
set->length--;
return 0;
}
struct _set_pair {
zt_set * s1;
zt_set * s2;
};
static int _union(void *key UNUSED, size_t key_len, void *datum, size_t datum_len, void *param)
{
struct _set_pair * p;
p = (struct _set_pair *)param;
return zt_set_insert(p->s2, datum, datum_len);
}
int zt_set_union(zt_set *setu, const zt_set *set1, const zt_set *set2)
{
struct _set_pair s = { NULL, NULL };
s.s2 = setu;
zt_table_for_each(set1->tbl, _union, &s);
zt_table_for_each(set2->tbl, _union, &s);
return 0;
}
static int _intersect(void *key UNUSED, size_t key_len, void *datum, size_t datum_len, void *param)
{
struct _set_pair * p;
p = (struct _set_pair *)param;
if (zt_set_is_member(p->s1, datum, datum_len)) {
return zt_set_insert(p->s2, datum, datum_len);
}
return 0;
}
int zt_set_intersection(zt_set *seti, const zt_set *set1, const zt_set *set2)
{
struct _set_pair p = { NULL, NULL };
p.s1 = (zt_set *)set2;
p.s2 = (zt_set *)seti;
return zt_table_for_each(set1->tbl, _intersect, &p);
}
static int _difference(void *key UNUSED, size_t key_len, void *datum, size_t datum_len, void *param)
{
struct _set_pair * p;
p = (struct _set_pair *)param;
if (!zt_set_is_member(p->s1, datum, datum_len)) {
return zt_set_insert(p->s2, datum, datum_len);
}
return 0;
}
int zt_set_difference(zt_set *setd, const zt_set *set1, const zt_set *set2)
{
struct _set_pair p = { NULL, NULL };
p.s1 = (zt_set *)set2;
p.s2 = (zt_set *)setd;
return zt_table_for_each(set1->tbl, _difference, &p);
}
int zt_set_is_member(const zt_set *set, const void *data, size_t len)
{
errno = 0;
if (zt_table_get(set->tbl, data, len) != NULL) {
return 1;
}
if (errno == 0) {
return 1;
}
return 0;
}
static int _is_subset(void *key UNUSED, size_t key_len, void *datum, size_t datum_len, void *param)
{
struct _set_pair * p = (struct _set_pair *)param;
if (zt_set_is_member(p->s1, datum, datum_len)) {
return 0;
}
return 1;
}
int zt_set_is_subset(const zt_set *set1, const zt_set *set2)
{
struct _set_pair p = { NULL, NULL };
p.s1 = (zt_set *)set2;
if (set1->length > set2->length) {
return 0;
}
return zt_table_for_each(set1->tbl, _is_subset, &p) == 0;
}
int zt_set_is_equal(const zt_set *set1, const zt_set *set2)
{
struct _set_pair p = { NULL, NULL };
p.s1 = (zt_set *)set2;
if (set1->length != set2->length) {
return 0;
}
return zt_table_for_each(set1->tbl, _is_subset, &p) == 0;
}
struct _iterator_data {
zt_set_iterator iterator;
void * param;
};
static int _table_to_set_iterator(void *key UNUSED, size_t key_len, void *data, size_t data_len, void *param)
{
struct _iterator_data * p = (struct _iterator_data *)param;
return p->iterator(data, p->param);
}
int
zt_set_for_each(zt_set *set, zt_set_iterator iterator, void *param)
{
struct _iterator_data d;
zt_assert(set);
zt_assert(iterator);
d.iterator = iterator;
d.param = param;
return zt_table_for_each(set->tbl, _table_to_set_iterator, &d);
}
|
108 | ./libzt/src/zt_int.c | #include "zt_int.h"
|
109 | ./libzt/src/zt_llist.c | /*
* Copyright (C) 2007 Jason L. Shiffer <jshiffer@zerotao.org>. All Rights Reserved.
* See file COPYING for details.
*/
#include <zt_llist.h>
|
110 | ./libzt/src/zt_win32.c |
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#include <Windows.h>
#include "zt_win32.h"
void srandom(unsigned int _Seed)
{
srand(_Seed);
}
long int random(void)
{
return rand();
}
int snprintf(char * s, size_t n, const char * format, ...)
{
int oVal = -1;
va_list args;
va_start(args, format);
oVal = vsprintf_s(s, n, format, args);
va_end(args);
return oVal;
}
int strcasecmp(const char *s1, const char *s2)
{
return _stricmp(s1, s2);
}
char *index(const char *s, int c)
{
return strchr(s,c);
}
char *strtok_r(char *str, const char *delim, char **saveptr)
{
return strtok_s(str, delim, saveptr);
}
void *alloca(size_t size)
{
return _alloca(size);
}
int strerror_r(int errnum, char *buf, size_t buflen)
{
return strerror_s(buf, buflen, errnum);
}
long sysconf(int name)
{
long oVal = -1;
if (name == _SC_PAGESIZE)
{
SYSTEM_INFO si;
GetSystemInfo(&si);
oVal = si.dwPageSize;
}
return oVal;
}
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
char *
strsep (char **stringp,
const char *delim)
{
register char *s;
register const char *spanp;
register int c, sc;
char *tok;
if ((s = *stringp) == NULL)
return (NULL);
for (tok = s;;) {
c = *s++;
spanp = delim;
do {
if ((sc = *spanp++) == c) {
if (c == 0)
s = NULL;
else
s[-1] = 0;
*stringp = s;
return (tok);
}
} while (sc != 0);
}
/* NOTREACHED */
}
|
111 | ./libzt/src/zt_assert.c | /*
* zt_assert.c ZeroTao Assertions
*
* Copyright (C) 2000-2006, Jason L. Shiffer <jshiffer@zerotao.com>. All Rights Reserved.
* See file COPYING for details.
*
* $Id: assert.c,v 1.1 2002/11/10 23:36:42 jshiffer Exp $
*
*/
/*
* Description:
*/
#ifdef HAVE_CONFIG_H
# include <zt_config.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include "zt_internal.h"
#include "zt_log.h"
#include "zt_cstr.h"
#include "zt_assert.h"
void
_zt_log_assertion(const char *s, const char *file, unsigned int line,
const char *func)
{
char bname[PATH_MAX];
if (!s) {
s = "no assertion given";
}
(void)zt_cstr_basename(bname, PATH_MAX, file, NULL);
if (func) {
zt_log_printf(zt_log_err, "Assertion Failed: \"%s\": %s[%d:%s]", s, bname, line, func);
} else {
zt_log_printf(zt_log_err, "Assertion Failed: \"%s\": %s[%d]", s, bname, line);
}
}
int
_zt_log_abort(const char *s, const char *file, unsigned int line,
const char *func)
{
char bname[PATH_MAX];
if (!s) {
s = "no message given";
}
(void)zt_cstr_basename(bname, PATH_MAX, file, NULL);
if (func) {
zt_log_printf(zt_log_crit, "Exiting: \"%s\": %s[%d:%s]", s, bname, line, func);
} else {
zt_log_printf(zt_log_crit, "Exiting: \"%s\": %s[%d]", s, bname, line);
}
return 0;
}
|
112 | ./libzt/src/zt_buf.c | #include <stdio.h>
#ifdef HAVE_CONFIG_H
# include "zt_config.h"
#endif /* HAVE_CONFIG_H */
#ifdef HAVE_STRING_H
# include <string.h>
#endif /* HAVE_STRING_H */
#include "zt.h"
struct zt_buf {
size_t len;
size_t max;
void * buf;
void * top;
};
zt_buf_t *
zt_buf_new(void) {
zt_buf_t * b;
if (!(b = zt_malloc(zt_buf_t, 1))) {
return NULL;
}
b->len = 0;
b->max = 0;
b->buf = NULL;
b->top = NULL;
return b;
}
void *
zt_buf_get(zt_buf_t * b) {
return b->len ? b->buf : NULL;
}
size_t
zt_buf_unused_sz(zt_buf_t * b) {
return (size_t)(b->max - b->len);
}
size_t
zt_buf_length(zt_buf_t * b) {
return b->len;
}
#define ZT_BUF_MIN 1024
int
zt_buf_expand(zt_buf_t * b, size_t len) {
size_t rlen;
if (len < ZT_BUF_MIN) {
rlen = ZT_BUF_MIN;
} else {
rlen = len;
}
if (b->top == NULL) {
b->top = b->buf;
}
b->buf = realloc(b->buf, b->len + rlen);
b->top = b->buf;
b->max = b->len + rlen;
return 0;
}
size_t
zt_buf_drain(zt_buf_t * b, size_t len) {
if (len == 0) {
return 0;
}
if (len < b->len) {
b->len -= len;
b->max -= (size_t)((char *)b->top - (char *)b->buf);
b->buf = ((char *)b->buf + len);
} else {
b->len = 0;
}
return b->len;
}
int
zt_buf_add(zt_buf_t * b, void * data, size_t len) {
if (len > zt_buf_unused_sz(b)) {
zt_buf_expand(b, len);
}
memcpy((void *)((char *)b->buf + b->len), data, len);
b->len += len;
return 0;
}
int
zt_buf_add_buf(zt_buf_t * a, zt_buf_t * b) {
zt_buf_add(a, b->buf, b->len);
zt_buf_drain(b, b->len);
return 0;
}
size_t
zt_buf_remove(zt_buf_t * b, void * out, size_t olen) {
if (olen > b->len) {
olen = b->len;
}
memcpy(out, b->buf, olen);
zt_buf_drain(b, olen);
return olen;
}
int
zt_buf_reserve(zt_buf_t * b, size_t len) {
if (len > zt_buf_unused_sz(b)) {
zt_buf_expand(b, len);
}
return 0;
}
size_t
zt_buf_iov_len(zt_iov_t * vec, int n_vec) {
int i;
size_t len;
len = 0;
for (i = 0; i < n_vec; i++) {
len += vec[i].iov_len;
}
return len;
}
int
zt_buf_iov_add(zt_buf_t * b, zt_iov_t * vec, int n_vec) {
int i;
size_t tlen;
tlen = zt_buf_iov_len(vec, n_vec);
zt_buf_reserve(b, tlen);
for (i = 0; i < n_vec; i++) {
zt_buf_add(b, vec[i].iov_data, vec[i].iov_len);
}
return 0;
}
void
zt_buf_free(zt_buf_t * b) {
if (!b) {
return;
}
zt_free(b->top);
zt_free(b);
}
|
113 | ./libzt/src/zt_array.c | #include <string.h>
#include "zt.h"
#include "zt_internal.h"
static void
arrayrep_init(zt_array_t array, size_t len, size_t size, void *ary)
{
zt_assert(array);
zt_assert((ary && len > 0) ||
(len == 0 && ary == NULL));
zt_assert(size > 0);
array->length = len;
array->size = size;
array->data = ary;
}
/* exported functions */
zt_array_t
zt_array_new(size_t len, size_t size)
{
zt_array_t array;
array = zt_malloc(struct zt_array, 1);
if (len > 0) {
arrayrep_init(array, len, size,
zt_calloc(char, len * size));
} else {
arrayrep_init(array, len, size, NULL);
}
return array;
}
void
zt_array_free(zt_array_t *array)
{
zt_assert(array && *array);
zt_free((*array)->data);
zt_free(*array);
}
void
zt_array_set_data(zt_array_t array, char *data,
size_t len, size_t size, int copy)
{
zt_assert(array);
if (copy) {
arrayrep_init(array, len, size,
zt_calloc(char, len * size));
memcpy(array->data, data, len * size);
} else {
arrayrep_init(array, len, size, data);
}
}
zt_array_t
zt_array_with(char *data, size_t len, size_t size, int copy)
{
zt_array_t array;
array = zt_calloc(struct zt_array, 1);
zt_array_set_data(array, data, len, size, copy);
return array;
}
zt_array_t
zt_array_with_cstr(char *str)
{
return zt_array_with((char *)str, strlen(str), sizeof(char), 1);
}
void
zt_array_resize(zt_array_t array, size_t len)
{
zt_assert(array);
zt_assert(len > 0);
if (array->length == 0) {
array->data = zt_calloc(char, len * array->size);
} else if (len > 0) {
array->data = zt_realloc(char, array->data, len * array->size);
/* lear the added space */
if(len > array->length) {
size_t rlen = len - array->length;
memset(&array->data[array->length*array->size], 0, rlen * array->size);
}
} else {
zt_free(array->data);
array->data = NULL;
}
array->length = len;
}
zt_array_t
zt_array_copy(zt_array_t array, size_t len)
{
zt_array_t copy;
zt_assert(array);
copy = zt_array_new(len, array->size);
if (array->length > 0 && copy->length > 0) {
memcpy(copy->data, array->data,
MIN(array->length, copy->length) * copy->size);
}
return copy;
}
size_t
zt_array_length(zt_array_t array)
{
zt_assert(array);
return array->length;
}
size_t
zt_array_set_length(zt_array_t array, size_t len)
{
size_t olen;
zt_assert(array);
olen = array->length;
array->length = len;
return olen;
}
size_t
zt_array_size(zt_array_t array)
{
zt_assert(array);
return array->size;
}
char *
zt_array_data(zt_array_t array)
{
zt_assert(array);
return array->data;
}
void *
zt_array_elem_copy(zt_array_t array, size_t offt, void *elem)
{
zt_assert(array);
zt_assert(offt < array->length);
zt_assert(elem);
memcpy(elem, array->data + offt * array->size, array->size);
return elem;
}
void *
zt_array_get(zt_array_t array, size_t offt)
{
zt_assert(array);
zt_assert(offt < array->length);
/*
* zt_assert(elem);
*
* memcpy(elem, array->data + offt * array->size, array->size);
* *elem = ;
*/
return array->data + offt * array->size; /* *elem; */
}
void *
zt_array_put(zt_array_t array, size_t offt, void *elem)
{
zt_assert(array);
zt_assert(offt < array->length);
zt_assert(elem);
memcpy(array->data + offt * array->size, elem, array->size);
return elem;
}
|
114 | ./libzt/src/zt_atexit.c | /*!
* Filename: zt_atexit.c
* Description: Hook to extend the system atexit
*
* Author: Jason L. Shiffer <jshiffer@zerotao.org>
* Copyright:
* Copyright (C) 2010, Jason L. Shiffer.
* See file COPYING for details
*
* Notes:
*
*/
#ifdef HAVE_CONFIG_H
# include "zt_config.h"
#endif
#ifdef HAVE_STDLIB_H
# include <stdlib.h>
#endif
#include "zt.h"
#include "zt_internal.h"
typedef struct zt_atexit_cb zt_atexit_cb;
struct zt_atexit_cb {
zt_stack_t member;
void (*fn)(void *data);
void * data;
};
/* FIXME: global needs thread safety */
static zt_stack(cb_stack);
static void
_atexit_call(void) {
zt_stack_t * se;
struct zt_atexit_cb * cb;
while(!zt_stack_empty(&cb_stack)) {
se = zt_stack_pop(&cb_stack);
cb = zt_stack_data(se, struct zt_atexit_cb, member);
if(cb && cb->fn) {
cb->fn(cb->data);
zt_free(cb);
}
}
}
void
zt_atexit(void (*fn)(void * data), void * data) {
struct zt_atexit_cb * cb;
zt_assert(fn);
cb = zt_calloc(struct zt_atexit_cb, 1);
if(zt_stack_empty(&cb_stack)) {
atexit(_atexit_call);
}
cb->fn = fn;
cb->data = data;
zt_stack_push(&cb_stack, &cb->member);
}
|
115 | ./libzt/src/zt_progname.c | /*
* zt_progname.c ZeroTao progname functions
*
* Copyright (C) 2000-2006, Jason L. Shiffer <jshiffer@zerotao.com>. All Rights Reserved.
* See file COPYING for details.
*
* $Id: progname.c,v 1.3 2003/06/09 16:55:09 jshiffer Exp $
*
*/
/*
* Description:
*/
#ifdef HAVE_CONFIG_H
#include <zt_config.h>
#endif
#include <stdlib.h>
#include <sys/stat.h>
#include <limits.h>
#include <string.h>
#include "zt.h"
#include "zt_internal.h"
/* #include "zt_cstr.h" */
/* #include "zt_progname.h" */
/* #include "zt_log.h" */
#if defined(__APPLE__)
# include <mach-o/dyld.h>
#endif /* APPLE */
#define UNKNOWN "*UNKNOWN*"
static char _progname[PATH_MAX+1] = UNKNOWN;
static char _progpath[PATH_MAX+1] = UNKNOWN;
char *
zt_progname(const char *name, int opts)
{
if (name && *name != '\0') {
memset(_progname, '\0', PATH_MAX);
if (opts == STRIP_DIR) {
zt_cstr_basename(_progname, PATH_MAX, name, NULL);
} else {
memcpy(_progname, name, MIN(PATH_MAX, strlen(name)));
}
}
return _progname;
}
#if defined(linux) || defined(__linux__) || (defined(sun) && defined(svr4)) || defined(BSD)
static ssize_t
_proc_get_path(char * result, size_t size) {
pid_t pid;
char path[PATH_MAX + 1];
pid = getpid();
/* FIXME: switch to "supported" definitions ie if defined(PROC_PID_PATH) ... */
# if defined(linux) || defined(__linux__)
/* check proc */
snprintf(path, PATH_MAX, "/proc/%d/exe", pid);
# elif defined(sun) && defined(svr4)
snprintf(path, PATH_MAX, "/proc/%d/path/a.out", pid);
# elif defined(BSD)
snprintf(path, PATH_MAX, "/proc/%d/file", pid);
# else
return -1;
# endif /* defined linux */
return readlink(path, result, size);
}
#endif
char *
zt_os_progpath() {
char * result = NULL;
if ((result = calloc(sizeof(char), PATH_MAX+1)) == NULL) {
return NULL;
}
/*
* OSX: _NSGetExecutablePath()
* Solaris: getexecname() or readlink /proc/<pid>/path/a.out
* Linux: readlink /proc/<pid>/exe
* FreeBSD: sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1
* BSD w/ Procfs: readlink /proc/curproc/file
* Windows: GetModuleFileName() with hModule = NULL
*/
#if defined(__APPLE__)
{
uint32_t size = PATH_MAX;
_NSGetExecutablePath(result, &size);
}
#elif defined(WIN32)
{
DWORD size = PATH_MAX;
GetModuleFileName(NULL, result, size);
}
#else
if (_proc_get_path(result, PATH_MAX) == -1) {
zt_log_printf(zt_log_err, "Could not get program path");
}
#endif
return result;
}
char *
zt_progpath(char *prog) {
/* If prog is !NULL then try to calculate the correct path.
* Otherwise just return the current path setting.
*/
if(prog && *prog != '\0') {
/* if the passed in path is not NULL */
memset(_progpath, '\0', PATH_MAX);
zt_cstr_dirname(_progpath, PATH_MAX, prog);
if(_progpath[0] == '\0' || strcmp(_progpath, ".") == 0) {
/* the passed in prog did not include a path */
char * path;
size_t offt = 0;
ssize_t base = 0;
size_t len;
char * tpath;
struct stat sbuf;
path = getenv("PATH");
if (!path) {
/* try to use system specific methods to get the path */
char * pp;
if ((pp = zt_os_progpath()) == NULL) {
return _progpath;
}
zt_cstr_dirname(_progpath, PATH_MAX, pp);
zt_free(pp);
return _progpath;
}
len = strlen(path);
while(offt < len) {
ssize_t sofft;
if ((sofft = zt_cstr_any(path, offt, -1, ENV_SEPERATOR)) < 0) {
break;
}
offt = (size_t)sofft;
tpath = zt_cstr_catv(path, base, offt-1,
PATH_SEPERATOR, 0, -1,
prog, 0, -1, NULL);
errno = 0;
if((stat(tpath, &sbuf) == 0)) {
zt_cstr_dirname(_progpath, PATH_MAX, tpath);
zt_free(tpath);
return _progpath;
}
zt_free(tpath);
base = offt+1;
offt++;
}
/* if still no path */
if (strcmp(_progpath, ".") == 0) {
/* just return the cwd */
char cwd[PATH_MAX+1];
if (getcwd(cwd, PATH_MAX) != NULL) {
zt_cstr_copy(cwd, 0, -1, _progpath, PATH_MAX);
}
}
} else {
/* the passed in path did include a path
* determine if it is relative
*/
char cwd[PATH_MAX+1];
if(getcwd(cwd, PATH_MAX) != NULL) {
if (_progpath[0] != '/') {
/* path is relative append and remove prog */
char * tpath;
char * pp = _progpath;
if(_progpath[0] == '.' && _progpath[1] == '/') {
/* if it starts with ./ then remove it */
pp += 2;
}
tpath = zt_cstr_path_append(cwd, pp);
zt_cstr_copy(tpath, 0, -1, _progpath, PATH_MAX);
zt_free(tpath);
}
}
}
}
return _progpath;
}
|
116 | ./libzt/src/zt_ipv4_tbl.c | #include "zt_internal.h"
#include "zt_mem.h"
#include "zt_ipv4_tbl.h"
#define DEFAULT_ELT_NUM 32
static uint32_t netmask_tbl[] = {
0x00000000, 0x80000000, 0xC0000000, 0xE0000000, 0xF0000000,
0xF8000000, 0xFC000000, 0xFE000000, 0xFF000000, 0xFF800000,
0xFFC00000, 0xFFE00000, 0xFFF00000, 0xFFF80000, 0xFFFC0000,
0xFFFE0000, 0xFFFF0000, 0xFFFF8000, 0xFFFFC000, 0xFFFFE000,
0xFFFFF000, 0xFFFFF800, 0xFFFFFC00, 0xFFFFFE00, 0xFFFFFF00,
0xFFFFFF80, 0xFFFFFFC0, 0xFFFFFFE0, 0xFFFFFFF0, 0xFFFFFFF8,
0xFFFFFFFC, 0xFFFFFFFE, 0xFFFFFFFF
};
void
zt_ipv4_tbl_destroy(zt_ipv4_tbl *tbl)
{
if (!tbl) {
return;
}
if (tbl->pools) {
zt_mem_pool_group_destroy(tbl->pools);
}
free(tbl);
}
zt_ipv4_tbl *
zt_ipv4_tbl_init(uint32_t size)
{
zt_ipv4_tbl * tbl;
uint32_t rsize = size ? size : 128;
static zt_mem_pool_desc pools[4];
memset(pools, 0, sizeof(pools));
pools[0].name = "zt_ipv4_node_hash";
pools[0].elts = 1;
pools[0].size = sizeof(zt_ipv4_node *) * rsize;
pools[1].name = "zt_ipv4_node";
pools[1].elts = 1;
pools[1].size = sizeof(zt_ipv4_node);
pools[2].name = "zt_ipv4_addr";
pools[2].elts = 1;
pools[2].size = sizeof(zt_ipv4_addr);
if (!(tbl = calloc(sizeof(zt_ipv4_tbl), 1))) {
return NULL;
}
if (!(tbl->pools = zt_mem_pool_group_init(pools, 3))) {
return NULL;
}
tbl->sz = rsize;
return tbl;
}
zt_ipv4_addr *
zt_ipv4_addr_frm_str(const char *netstr)
{
zt_ipv4_addr *addr = NULL;
zt_mem_pool *pool = NULL;
int bitlen = 32;
uint32_t ipaddr;
if (!netstr) {
return NULL;
}
if (!(pool = zt_mem_pool_get("zt_ipv4_addr"))) {
return NULL;
}
if (zt_ipv4_str2net(netstr, &ipaddr, &bitlen)) {
return NULL;
}
if (!(addr = zt_mem_pool_alloc(pool))) {
return NULL;
}
addr->addr = ipaddr;
addr->mask = netmask_tbl[bitlen];
addr->bitlen = bitlen;
addr->addr = addr->addr & addr->mask;
addr->broadcast = addr->addr | (0xFFFFFFFF & ~addr->mask);
return addr;
}
zt_ipv4_node *
zt_ipv4_node_str_init(const char *netstr)
{
zt_ipv4_node *node;
zt_ipv4_addr *addr;
zt_mem_pool *pool;
if (!netstr) {
return NULL;
}
if (!(pool = zt_mem_pool_get("zt_ipv4_node"))) {
return NULL;
}
if (!(node = zt_mem_pool_alloc(pool))) {
return NULL;
}
if (!(addr = zt_ipv4_addr_frm_str(netstr))) {
return NULL;
}
node->addr = addr;
node->next = NULL;
return node;
}
int
zt_ipv4_tbl_add_node(zt_ipv4_tbl * tbl, zt_ipv4_node * node)
{
zt_ipv4_node *node_slot;
zt_mem_pool *pool;
uint32_t key;
uint8_t blen;
int is_in;
int i;
if (!tbl || !node) {
return -1;
}
if (node->addr->bitlen == 0) {
/*
* this is a 0.0.0.0/0 network, set the any to this node
*/
tbl->any = node;
return 0;
}
if (!(pool = zt_mem_pool_get("zt_ipv4_node_hash"))) {
return -1;
}
is_in = 0;
blen = node->addr->bitlen - 1;
if (tbl->tbl[blen] == NULL) {
zt_ipv4_node **hash_entry;
if (!(hash_entry = zt_mem_pool_alloc(pool))) {
return -1;
}
memset(hash_entry, 0, sizeof(zt_ipv4_node *) * tbl->sz);
tbl->tbl[blen] = hash_entry;
}
key = node->addr->addr & (tbl->sz - 1);
node_slot = tbl->tbl[blen][key];
if (node_slot != NULL) {
node->next = node_slot;
}
tbl->tbl[blen][key] = node;
/*
* set our in array to this bitlen if it doesn't exist
* we use this to iterate through the prefixes.
*
* For example if the bitlen is /32 and we add one node
* tbl->in[0] would be 32.
*
* When we search for an address within our table the
* only work we have to do is checking bitlengths found
* within this in array
*/
for (i = 0; i < 32; i++) {
if (tbl->in[i] == 0) {
break;
}
if (tbl->in[i] == node->addr->bitlen) {
is_in = 1;
break;
}
}
/*
* the bitlen doesn't exist, so add it to the last
* open slot
*/
if (is_in == 0) {
tbl->in[i] = node->addr->bitlen;
}
return 0;
} /* zt_ipv4_tbl_add_node */
zt_ipv4_node *
zt_ipv4_tbl_add_frm_str(zt_ipv4_tbl * tbl, const char *netstr)
{
zt_ipv4_node *ipv4_node = NULL;
if (!tbl || !netstr) {
return NULL;
}
if (tbl->any) {
/*
* we had a 0.0.0.0/0, we don't need to insert anything more
*/
return tbl->any;
}
if (!(ipv4_node = zt_ipv4_node_str_init(netstr))) {
return NULL;
}
if (zt_ipv4_tbl_add_node(tbl, ipv4_node)) {
return NULL;
}
return ipv4_node;
}
int
ipv4_tbl_addr_cmp(zt_ipv4_addr * haystack, zt_ipv4_addr * needle)
{
if (!haystack || !needle) {
return 0;
}
if (needle->addr >= haystack->addr &&
needle->broadcast <= haystack->broadcast) {
return 1;
}
return 0;
}
zt_ipv4_node *
zt_ipv4_tbl_search_node(zt_ipv4_tbl * tbl, zt_ipv4_node * node)
{
int bit_iter;
int i = 0;
zt_ipv4_node *match = NULL;
if (tbl->any) {
return tbl->any;
}
while (1) {
uint32_t addr_masked;
uint32_t key;
bit_iter = tbl->in[i++];
if (!bit_iter) {
break;
}
addr_masked = node->addr->addr & netmask_tbl[bit_iter];
key = addr_masked & (tbl->sz - 1);
match = tbl->tbl[bit_iter - 1][key];
while (match) {
if (ipv4_tbl_addr_cmp(match->addr, node->addr)) {
return match;
}
match = match->next;
}
}
return NULL;
}
zt_ipv4_node *
zt_ipv4_tbl_search_from_str(zt_ipv4_tbl * tbl, const char *netstr)
{
zt_ipv4_node *ipv4_node = NULL;
zt_ipv4_node *matched = NULL;
if (!tbl || !netstr) {
return NULL;
}
if (!(ipv4_node = zt_ipv4_node_str_init(netstr))) {
return NULL;
}
matched = zt_ipv4_tbl_search_node(tbl, ipv4_node);
zt_mem_pool_release((void **)&ipv4_node);
return matched;
}
/*
* Helper functions
*/
#define MAXLINE 16
uint32_t
zt_ipv4_ip2int(const char *str)
{
return ntohl(inet_addr(str));
}
char *
zt_ipv4_int2ip(uint32_t addr)
{
struct in_addr a;
a.s_addr = ntohl(addr);
return strdup(inet_ntoa(a));
}
int
zt_ipv4_str2net(const char *str, uint32_t * outaddr, int *outbitlen)
{
char *save;
char *str_cp;
char *cp;
int bitlen = 32;
if (!str || !outaddr || !outbitlen) {
return -1;
}
if (!(str_cp = strdup(str))) {
return -1;
}
if (!(save = calloc(MAXLINE, 1))) {
free(str_cp);
return -1;
}
if ((cp = strchr(str_cp, '/')) != NULL) {
bitlen = atoi(cp + 1);
if ((cp - str_cp) > MAXLINE - 1) {
free(save);
free(str_cp);
return -1;
}
memcpy(save, str, cp - str_cp);
} else {
bitlen = 32;
memcpy(save, str, MAXLINE);
}
if (bitlen > 32) {
bitlen = 32;
}
*outaddr = ntohl(inet_addr(save));
*outbitlen = bitlen;
free(save);
free(str_cp);
return 0;
} /* zt_ipv4_str2net */
|
117 | ./libzt/src/zt_path.c | #ifdef HAVE_STRING_H
#include <string.h>
#endif /* HAVE_STRING_H */
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif /* HAVE_ERRNO_H */
#include "zt.h"
/* Create a directory, allowing for creation of intermediate directories as
* needed. Will leave directory structure partially created if intermediate
* directory creation fails.
*/
int
zt_mkdir(const char * path, mode_t mode, zt_mkdir_flags flags) {
ssize_t len;
char cpath[PATH_MAX + 1];
ssize_t offt;
struct stat sbuf;
ssize_t pslen;
errno = 0;
AGAIN:
if (mkdir(path, mode) != 0) {
if (errno == EEXIST) {
return 0;
}
if (!ZT_BIT_ISSET(flags, zt_mkdir_create_parent)) {
/* could not create dir and create parents not set */
zt_log_strerror(zt_log_err, errno, "could not create dir: %s", path);
return -1;
}
pslen = strlen(PATH_SEPERATOR);
len = strlen(path);
memset(cpath, 0, sizeof(cpath));
offt = 0;
while (len > offt) {
offt = zt_cstr_find(path, offt, -1, PATH_SEPERATOR);
if (offt == -1) {
/* end of path */
break;
}
memcpy(cpath, path, MIN(sizeof(cpath), (size_t)offt));
offt += pslen;
if (offt == pslen || stat(cpath, &sbuf) == 0) {
/* path exists or we are looking at the root */
continue;
}
if (mkdir(cpath, mode) != 0) {
/* Cannot proceed, return error */
return -1;
}
}
goto AGAIN;
}
return 0;
} /* zt_mkdir */
/* simple utility to remove the need for the local function to
* allocate a stat struct when existance is the only thing that matters
*/
int
zt_path_exists(const char * path) {
struct stat sbuf;
errno = 0;
if (stat(path, &sbuf) == 0) {
return 0;
}
return -1;
}
/* find the longest matching directory containing a specific file or directory.
* eg. the path /home/jshiffer/test/env and the trigger .ssh
* would return /home/jshiffer unless there was a .ssh in a higher directory (env or test).
*/
char *zt_find_basedir(const char * path, const char * trigger) {
struct stat sbuf;
size_t len;
ssize_t offt;
char * result = NULL;
char cpath[PATH_MAX + 1];
char lpath[PATH_MAX + 1];
len = strlen(path);
memset(lpath, 0, sizeof(lpath));
memcpy(lpath, path, MIN(len, sizeof(cpath)));
do {
memset(cpath, 0, sizeof(cpath));
snprintf(cpath, sizeof(cpath), "%s%s%s", lpath, PATH_SEPERATOR, trigger);
errno = 0;
if (stat(cpath, &sbuf) == 0) {
/* found it */
len = strlen(lpath) + strlen(PATH_SEPERATOR) + 1;
result = zt_callocs(sizeof(char), len);
snprintf(result, len, "%s%s", lpath, PATH_SEPERATOR);
break;
}
if ((strlen(lpath) == 0) ||
(offt = zt_cstr_rfind(lpath, 0, -1, PATH_SEPERATOR)) == -1) {
break;
}
lpath[offt] = '\0';
} while (1);
return result;
} /* zt_find_basedir */
|
118 | ./libzt/src/zt_malloc.c | /*
* zt_malloc.c wrappers for malloc et. el.
*
* Copyright (C) 2000-2005, Jason L. Shiffer <jshiffer@zerotao.com>. All Rights Reserved.
* See file COPYING for details.
*
* $Id: malloc.c,v 1.4 2003/06/09 16:55:09 jshiffer Exp $
*
*/
#include <string.h>
#include "zt_internal.h"
#include "zt_assert.h"
#include "zt_log.h"
void_p
zt_calloc_p(size_t num, size_t size)
{
void_p mem = NULL;
mem = (void_p)calloc((num), (size));
zt_assert_always(mem);
return mem;
}
void_p
zt_malloc_p(size_t num)
{
void_p mem = NULL;
mem = (void_p)malloc(num);
zt_assert_always(mem);
return mem;
}
void_p
zt_realloc_p(void_p p, size_t num)
{
void_p mem = NULL;
mem = (void_p)realloc(p, num);
zt_assert_always(mem);
return mem;
}
char *
zt_strdup_p(const char *string)
{
char * volatile new_string = NULL;
zt_assert_always(string);
new_string = strdup(string);
zt_assert_always(new_string);
return new_string;
}
|
119 | ./libzt/src/zt_log.c | /*!
* Filename: zt_log.c
* Description: generic logging interface
*
* Author: Jason L. Shiffer <jshiffer@zerotao.org>
* Copyright:
* Copyright (C) 2000-2010, Jason L. Shiffer.
* See file COPYING for details
*
* Notes:
*
*/
#ifdef HAVE_CONFIG_H
#include "zt_config.h"
#endif
#ifdef HAVE_STRING_H
# include <string.h>
#endif
#include "zt.h"
#include "zt_internal.h"
#include "zt_log.h"
#include "zt_log/log_private.h"
#include "zt_atexit.h"
static void
log_atexit(void * data) {
zt_log_ty * logp = data;
if (logp) {
zt_log_close(logp);
}
}
/* #undef HAVE_PTHREADS */
#ifdef HAVE_PTHREADS
static pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_key_t ctx_key;
static pthread_once_t ctx_key_once = PTHREAD_ONCE_INIT;
static void
make_ctx_key(void) {
(void)pthread_key_create(&ctx_key, free);
}
#define CTX_STATIC
#else /* ifdef HAVE_PTHREADS */
#define CTX_STATIC static
#endif /* HAVE_PTHREADS */
typedef struct zt_log_ctx_s zt_log_ctx_ty;
struct zt_log_ctx_s {
const char * file;
int line;
const char * function;
};
static zt_log_ty * log_default_ptr = NULL;
static int forced = 0;
static zt_log_ctx_ty *
zt_log_get_ctx(void) {
CTX_STATIC zt_log_ctx_ty * log_ctx_ptr = NULL;
if (!log_ctx_ptr) {
#ifdef HAVE_PTHREADS
(void)pthread_once(&ctx_key_once, make_ctx_key);
if ((log_ctx_ptr = pthread_getspecific(ctx_key)) == NULL) {
#endif /* HAVE_PTHREADS */
if ((log_ctx_ptr = zt_calloc(zt_log_ctx_ty, 1)) == NULL) {
fprintf(stderr, "Could not allocate memory for log context\n");
exit(1);
}
#ifdef HAVE_PTHREADS
pthread_setspecific(ctx_key, log_ctx_ptr);
}
#endif /* HAVE_PTHREADS */
}
return log_ctx_ptr;
}
static zt_log_ty *
zt_log_get_logger(void) {
if (!log_default_ptr) {
#ifdef HAVE_PTHREADS
pthread_mutex_lock(&log_mutex);
#endif
/* second check is just to avoid having to have a mutex lock
* around the default case of a logger being set
*/
if (!log_default_ptr) {
if ((log_default_ptr = zt_log_stderr(ZT_LOG_WITH_LEVEL)) == NULL) {
fprintf(stderr, "Could not allocate stderr for logging\n");
exit(1);
}
forced = 1;
zt_atexit(log_atexit, log_default_ptr);
}
#ifdef HAVE_PTHREADS
pthread_mutex_unlock(&log_mutex);
#endif
}
return log_default_ptr;
}
static zt_log_ty *
zt_log_set_logger(zt_log_ty * log) {
zt_log_ty * last;
#ifdef HAVE_PTHREADS
pthread_mutex_lock(&log_mutex);
#endif
last = log_default_ptr;
log_default_ptr = log;
#ifdef HAVE_PTHREADS
pthread_mutex_unlock(&log_mutex);
#endif
return last;
}
/* this function expects the traditional "If you allocated free it, if
* you didn't allocate it leave it the fsck alone" model */
zt_log_ty *
zt_log_logger(zt_log_ty * log) {
/* STATES:
* log == NULL AND default == NULL : create a new logger
* log == NULL AND default == <logger> : replace the current logger with log (NULL)
* log == <logger> AND default == NULL : replace the default logger with log
* log == <logger> AND default == <logger> : replace the default logger with log
*/
/* if log is NULL and there is no default get one */
if (log == NULL && log_default_ptr == NULL) {
return zt_log_get_logger();
}
return zt_log_set_logger(log);
}
zt_log_level
zt_log_set_level(zt_log_ty * log, zt_log_level level) {
zt_log_level olevel;
if (!log && ((log = zt_log_get_logger()) == NULL)) {
return 0;
}
olevel = log->level;
log->level = level;
return olevel;
}
zt_log_level
zt_log_get_level(zt_log_ty * log) {
if (!log && ((log = zt_log_get_logger()) == NULL)) {
return 0;
}
return log->level;
}
unsigned int
zt_log_set_opts(zt_log_ty * log, unsigned int opts) {
unsigned int oopts;
if (!log && ((log = zt_log_get_logger()) == NULL)) {
return 0;
}
oopts = log->opts;
log->opts = opts;
return oopts;
}
unsigned int
zt_log_get_opts(zt_log_ty * log) {
if (!log && ((log = zt_log_get_logger()) == NULL)) {
return 0;
}
return log->opts;
}
void
zt_log_set_debug_info(const char * file, int line, const char * func) {
zt_log_ctx_ty * ctx;
if ((ctx = zt_log_get_ctx()) == NULL) {
return;
}
ctx->file = (char*)file;
ctx->line = line;
ctx->function = (char*)func;
}
void
zt_log_get_debug_info(const char ** file, int * line, const char ** func) {
zt_log_ctx_ty * ctx = NULL;
if ((ctx = zt_log_get_ctx()) == NULL) {
*file = NULL;
*line = 0;
*func = NULL;
return;
}
*file = ctx->file;
*line = ctx->line;
*func = ctx->function;
}
void
zt_log_lprintf(zt_log_ty * log, zt_log_level level, const char * fmt, ...) {
va_list ap;
if (!log && ((log = zt_log_get_logger()) == NULL)) {
zt_log_set_debug_info(NULL, -1, NULL);
return;
}
if (level > log->level) {
zt_log_set_debug_info(NULL, -1, NULL);
return;
}
va_start(ap, fmt);
zt_log_lvprintf(log, level, fmt, ap);
va_end(ap);
}
void
zt_log_lvprintf(zt_log_ty * log, zt_log_level level, const char * fmt, va_list ap) {
if (!log && ((log = zt_log_get_logger()) == NULL)) {
goto EXIT;
}
if (level > log->level) {
goto EXIT;
}
if (log->vtbl->print) {
zt_log_ctx_ty * ctx = zt_log_get_ctx();
log->vtbl->print(log, level,
ctx ? ctx->file : NULL,
ctx ? ctx->line : 0,
ctx ? ctx->function : NULL,
fmt, ap);
}
EXIT:
/* debug info is only valid for a single call */
zt_log_set_debug_info(NULL, -1, NULL);
}
void
zt_log_lstrerror(zt_log_ty * log, zt_log_level level, int errnum, const char * fmt, ...) {
va_list ap;
size_t llen;
char * nfmt;
if (!log && ((log = zt_log_get_logger()) == NULL)) {
zt_log_set_debug_info(NULL, -1, NULL);
return;
}
if (level > log->level) {
zt_log_set_debug_info(NULL, -1, NULL);
return;
}
llen = strlen(fmt);
nfmt = (char*)malloc(llen + 256);
memcpy(nfmt, fmt, llen);
nfmt[llen] = ':';
nfmt[llen + 1] = ' ';
strerror_r(errnum, nfmt + (llen + 2), 255 - 2);
va_start(ap, fmt);
zt_log_lvprintf(log, level, nfmt, ap);
va_end(ap);
free(nfmt);
}
void
zt_log_close(zt_log_ty * log) {
if (!log) {
return;
}
if (log == log_default_ptr) {
zt_log_set_logger(NULL);
}
if (log->vtbl->destructor) {
log->vtbl->destructor(log);
}
}
|
120 | ./libzt/src/zt_hash.c | /*!
* Filename: zt_hash.h
* Description: this is an implementation of the FNV hashing algorithm as described at
* http://www.isthe.com/chongo/tech/comp/fnv/index.html
*
* Author: Jason L. Shiffer <jshiffer@zerotao.org>
* Copyright:
* as this is a measly import of the work done at isthe.com this file and
* the assoctiated zt_hash.c are in the public domain per their request.
*
* Notes:
*
*/
#include <stddef.h>
#include "zt_hash.h"
/*
* Other sources for hashing, testing hashes, etc:
* http://www.burtleburtle.net/bob/hash/hashfaq.html
*/
uint32_t
zt_hash32_buff(void *buf, size_t len, uint32_t hval)
{
unsigned char *bp = (unsigned char *)buf;
unsigned char *be = bp + len;
if (hval == 0) {
hval = ZT_HASH32_INIT;
}
while (bp < be) {
/* xor the bottom with the current octet */
hval ^= (uint32_t)*bp++;
/* multiply by the 32 bit FNV magic prime mod 2^32 */
hval *= ZT_HASH32_PRIME;
}
return hval;
}
uint32_t
zt_hash32_cstr(const uint8_t *str, uint32_t hval)
{
unsigned char *s = (unsigned char *)str; /* unsigned string */
if (hval == 0) {
hval = ZT_HASH32_INIT;
}
while (*s) {
/* xor the bottom with the current octet */
hval ^= (uint32_t)*s++;
/* multiply by the 32 bit FNV magic prime mod 2^32 */
hval *= ZT_HASH32_PRIME;
}
return hval;
}
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
uint64_t
zt_hash64_buff(void *buf, size_t len, uint64_t hval)
{
unsigned char *bp = (unsigned char *)buf;
unsigned char *be = bp + len;
if (hval == 0) {
hval = ZT_HASH64_INIT;
}
while (bp < be) {
/* xor the bottom with the current octet */
hval ^= (uint64_t)*bp++;
/* multiply by the 64 bit FNV magic prime mod 2^64 */
hval *= ZT_HASH64_PRIME;
}
return hval;
}
uint64_t
zt_hash64_cstr(const uint8_t *str, uint64_t hval)
{
unsigned char *s = (unsigned char *)str; /* unsigned string */
if (hval == 0) {
hval = ZT_HASH64_INIT;
}
while (*s) {
/* xor the bottom with the current octet */
hval ^= (uint64_t)*s++;
/* multiply by the 64 bit FNV magic prime mod 2^64 */
hval *= ZT_HASH64_PRIME;
}
return hval;
}
#endif /* __STDC_VERSION__ */
|
121 | ./libzt/src/zt_sha1.c | /*
* Copyright (C) 2008, Jason L. Shiffer <jshiffer@zerotao.org>.
* All Rights Reserved.
* See file COPYING for details.
*/
#ifdef HAVE_CONFIG_H
# include "zt_config.h"
#endif /* HAVE_CONFIG_H */
#ifdef HAVE_STRING_H
# include <string.h>
#endif /* HAVE_STRING_H */
/* SHA-1 origional by Steve Reid <steve@edmweb.com> */
#include <limits.h>
#include "zt_sha1.h"
#include "zt_cstr.h"
#include "zt_assert.h"
typedef union CHAR64LONG16 CHAR64LONG16;
union CHAR64LONG16 {
uint8_t c[64];
uint32_t l[16];
};
#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
static void _sha1_transform(uint32_t state[5], uint8_t buffer[64]);
#if HOST_BIGENDIAN
# define blk0(i) block->l[i]
#else
# define blk0(i) (block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) \
| (rol(block->l[i], 8) & 0x00FF00FF))
#endif
#define blk(i) (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
^ block->l[(i + 2) & 15] ^ block->l[i & 15], 1))
/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */
#define R0(v, w, x, y, z, i) z += ((w & (x ^ y)) ^ y) + blk0(i) + 0x5A827999 + rol(v, 5); w = rol(w, 30);
#define R1(v, w, x, y, z, i) z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); w = rol(w, 30);
#define R2(v, w, x, y, z, i) z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); w = rol(w, 30);
#define R3(v, w, x, y, z, i) z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); w = rol(w, 30);
#define R4(v, w, x, y, z, i) z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); w = rol(w, 30);
/* Hash a single 512-bit block. This is the core of the algorithm. */
static void
_sha1_transform(uint32_t state[5], uint8_t buffer[64])
{
uint32_t a;
uint32_t b;
uint32_t c;
uint32_t d;
uint32_t e;
CHAR64LONG16 * block;
/* uint32_t block[80]; */
block = (CHAR64LONG16 *)buffer;
a = state[0];
b = state[1];
c = state[2];
d = state[3];
e = state[4];
/* 4 rounds of 20 operations each. Loop unrolled. */
R0(a, b, c, d, e, 0); R0(e, a, b, c, d, 1); R0(d, e, a, b, c, 2); R0(c, d, e, a, b, 3);
R0(b, c, d, e, a, 4); R0(a, b, c, d, e, 5); R0(e, a, b, c, d, 6); R0(d, e, a, b, c, 7);
R0(c, d, e, a, b, 8); R0(b, c, d, e, a, 9); R0(a, b, c, d, e, 10); R0(e, a, b, c, d, 11);
R0(d, e, a, b, c, 12); R0(c, d, e, a, b, 13); R0(b, c, d, e, a, 14); R0(a, b, c, d, e, 15);
R1(e, a, b, c, d, 16); R1(d, e, a, b, c, 17); R1(c, d, e, a, b, 18); R1(b, c, d, e, a, 19);
R2(a, b, c, d, e, 20); R2(e, a, b, c, d, 21); R2(d, e, a, b, c, 22); R2(c, d, e, a, b, 23);
R2(b, c, d, e, a, 24); R2(a, b, c, d, e, 25); R2(e, a, b, c, d, 26); R2(d, e, a, b, c, 27);
R2(c, d, e, a, b, 28); R2(b, c, d, e, a, 29); R2(a, b, c, d, e, 30); R2(e, a, b, c, d, 31);
R2(d, e, a, b, c, 32); R2(c, d, e, a, b, 33); R2(b, c, d, e, a, 34); R2(a, b, c, d, e, 35);
R2(e, a, b, c, d, 36); R2(d, e, a, b, c, 37); R2(c, d, e, a, b, 38); R2(b, c, d, e, a, 39);
R3(a, b, c, d, e, 40); R3(e, a, b, c, d, 41); R3(d, e, a, b, c, 42); R3(c, d, e, a, b, 43);
R3(b, c, d, e, a, 44); R3(a, b, c, d, e, 45); R3(e, a, b, c, d, 46); R3(d, e, a, b, c, 47);
R3(c, d, e, a, b, 48); R3(b, c, d, e, a, 49); R3(a, b, c, d, e, 50); R3(e, a, b, c, d, 51);
R3(d, e, a, b, c, 52); R3(c, d, e, a, b, 53); R3(b, c, d, e, a, 54); R3(a, b, c, d, e, 55);
R3(e, a, b, c, d, 56); R3(d, e, a, b, c, 57); R3(c, d, e, a, b, 58); R3(b, c, d, e, a, 59);
R4(a, b, c, d, e, 60); R4(e, a, b, c, d, 61); R4(d, e, a, b, c, 62); R4(c, d, e, a, b, 63);
R4(b, c, d, e, a, 64); R4(a, b, c, d, e, 65); R4(e, a, b, c, d, 66); R4(d, e, a, b, c, 67);
R4(c, d, e, a, b, 68); R4(b, c, d, e, a, 69); R4(a, b, c, d, e, 70); R4(e, a, b, c, d, 71);
R4(d, e, a, b, c, 72); R4(c, d, e, a, b, 73); R4(b, c, d, e, a, 74); R4(a, b, c, d, e, 75);
R4(e, a, b, c, d, 76); R4(d, e, a, b, c, 77); R4(c, d, e, a, b, 78); R4(b, c, d, e, a, 79);
/* Add the working vars back into context.state[] */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
} /* _sha1_transform */
void
zt_sha1_init(zt_sha1_ctx *ctx)
{
/* SHA1 initialization constants */
ctx->state[0] = 0x67452301;
ctx->state[1] = 0xEFCDAB89;
ctx->state[2] = 0x98BADCFE;
ctx->state[3] = 0x10325476;
ctx->state[4] = 0xC3D2E1F0;
ctx->count[0] = ctx->count[1] = 0;
}
void
zt_sha1_update(zt_sha1_ctx *ctx, uint8_t *data, size_t len)
{
uint32_t i;
uint32_t j;
uint32_t llen;
/* FIXME: 64bit (or better unbounded) sha1_update */
zt_assert(len <= UINT_MAX-1);
llen = (uint32_t)len;
j = (ctx->count[0] >> 3) & 63;
if ((ctx->count[0] += llen << 3) < (llen << 3)) {
ctx->count[1]++;
}
ctx->count[1] += (llen >> 29);
if ((j + llen) > 63) {
memcpy(&ctx->buffer[j], data, (i = 64 - j));
_sha1_transform(ctx->state, ctx->buffer);
for (; i + 63 < llen; i += 64) {
_sha1_transform(ctx->state, &data[i]);
}
j = 0;
} else { i = 0; }
memcpy(&ctx->buffer[j], &data[i], llen - i);
}
void
zt_sha1_finalize(zt_sha1_ctx *ctx, uint8_t digest[20])
{
uint32_t i;
uint8_t finalcount[8];
for (i = 0; i < 8; i++) {
finalcount[i] = (uint8_t)((ctx->count[(i >= 4 ? 0 : 1)]
>> ((3 - (i & 3)) * 8) ) & 255); /* Endian independent */
}
zt_sha1_update(ctx, (uint8_t *)"\200", 1);
while ((ctx->count[0] & 504) != 448) {
zt_sha1_update(ctx, (uint8_t *)"\0", 1);
}
zt_sha1_update(ctx, finalcount, 8); /* Should cause a SHA1Transform() */
for (i = 0; i < 20; i++) {
digest[i] = (uint8_t)
((ctx->state[i >> 2] >> ((3 - (i & 3)) * 8) ) & 255);
}
memset(ctx->buffer, 0, 64);
memset(ctx->state, 0, 20);
memset(ctx->count, 0, 8);
memset(&finalcount, 0, 8);
}
void
zt_sha1_data(void *data, size_t len, uint8_t digest[20])
{
zt_sha1_ctx ctx;
zt_sha1_init(&ctx);
zt_sha1_update(&ctx, data, len);
zt_sha1_finalize(&ctx, digest);
}
char*
zt_sha1_tostr(uint8_t digest[20], char sha1[41])
{
zt_binary_to_hex(digest, 20, sha1, 41);
return sha1;
}
uint8_t *
zt_str_tosha1(char sha1[41], uint8_t digest[20])
{
zt_hex_to_binary(sha1, 40, digest, 20);
return digest;
}
|
122 | ./libzt/src/zt_tree.c | /*
* Copyright 2005 Jason L. Shiffer <jshiffer@zerotao.org>
*
* Altered from the BSD sys/tree.h for the most part only the
* red-black algorithm remains. It now uses an embedded type, similar
* if not the same as the embedded list api.
*
*/
/*
* Copyright 2002 Niels Provos <provos@citi.umich.edu>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <zt_internal.h>
#include "zt_tree.h"
static void zt_rbt_set(zt_rbt_node * e, zt_rbt_node *p);
static void zt_rbt_set_blackred(zt_rbt_node *black, zt_rbt_node *red);
static void zt_rbt_insert_colour(zt_rbt **head, zt_rbt_node *elt);
static void zt_rbt_remove_colour(zt_rbt **head, zt_rbt_node *parent, zt_rbt_node *elm);
static void
zt_rbt_set(zt_rbt_node * e, zt_rbt_node *p)
{
zt_rbt_parent(e) = p;
zt_rbt_left(e) = zt_rbt_right(e) = NULL;
zt_rbt_colour(e) = zt_rbt_red;
}
static void
zt_rbt_set_blackred(zt_rbt_node *black, zt_rbt_node *red)
{
zt_rbt_colour(black) = zt_rbt_black;
zt_rbt_colour(red) = zt_rbt_red;
}
#define zt_rbt_rotate_left(head, elm, tmp) do { \
(tmp) = zt_rbt_right(elm); \
if ((zt_rbt_right(elm) = zt_rbt_left(tmp))) { \
zt_rbt_parent(zt_rbt_left(tmp)) = (elm); \
} \
if ((zt_rbt_parent(tmp) = zt_rbt_parent(elm))) { \
if ((elm) == zt_rbt_left(zt_rbt_parent(elm))) { \
zt_rbt_left(zt_rbt_parent(elm)) = (tmp); } \
else { \
zt_rbt_right(zt_rbt_parent(elm)) = (tmp); } \
} else { \
*(head) = (tmp); } \
zt_rbt_left(tmp) = (elm); \
zt_rbt_parent(elm) = (tmp); \
} while (0)
#define zt_rbt_rotate_right(head, elm, tmp) do { \
(tmp) = zt_rbt_left(elm); \
if ((zt_rbt_left(elm) = zt_rbt_right(tmp))) { \
zt_rbt_parent(zt_rbt_right(tmp)) = (elm); \
} \
if ((zt_rbt_parent(tmp) = zt_rbt_parent(elm))) { \
if ((elm) == zt_rbt_left(zt_rbt_parent(elm))) { \
zt_rbt_left(zt_rbt_parent(elm)) = (tmp); } \
else { \
zt_rbt_right(zt_rbt_parent(elm)) = (tmp); } \
} else { \
*(head) = (tmp); } \
zt_rbt_right(tmp) = (elm); \
zt_rbt_parent(elm) = (tmp); \
} while (0)
static void
zt_rbt_insert_colour(zt_rbt **head, zt_rbt_node *elt)
{
zt_rbt_node * parent;
zt_rbt_node * gparent;
zt_rbt_node * tmp;
while ((parent = zt_rbt_parent(elt)) &&
zt_rbt_colour(parent) == zt_rbt_red) {
gparent = zt_rbt_parent(parent);
if (parent == zt_rbt_left(gparent)) {
tmp = zt_rbt_right(gparent);
if (tmp && zt_rbt_colour(tmp) == zt_rbt_red) {
zt_rbt_colour(tmp) = zt_rbt_black;
zt_rbt_set_blackred(parent, gparent);
elt = gparent;
continue;
}
if (zt_rbt_right(parent) == elt) {
zt_rbt_rotate_left(head, parent, tmp);
tmp = parent;
parent = elt;
elt = tmp;
}
zt_rbt_set_blackred(parent, gparent);
zt_rbt_rotate_right(head, gparent, tmp);
} else {
tmp = zt_rbt_left(gparent);
if (tmp && zt_rbt_colour(tmp) == zt_rbt_red) {
zt_rbt_colour(tmp) = zt_rbt_black;
zt_rbt_set_blackred(parent, gparent);
elt = gparent;
continue;
}
if (zt_rbt_left(parent) == elt) {
zt_rbt_rotate_right(head, parent, tmp);
tmp = parent;
parent = elt;
elt = tmp;
}
zt_rbt_set_blackred(parent, gparent);
zt_rbt_rotate_left(head, gparent, tmp);
}
}
zt_rbt_colour(*head) = zt_rbt_black;
} /* zt_rbt_insert_colour */
void
zt_rbt_remove_colour(zt_rbt **head, zt_rbt_node *parent, zt_rbt_node *elm)
{
zt_rbt_node * tmp;
while ((elm == NULL || zt_rbt_colour(elm) == zt_rbt_black) &&
elm != *head) {
if (zt_rbt_left(parent) == elm) {
tmp = zt_rbt_right(parent);
if (zt_rbt_colour(tmp) == zt_rbt_red) {
zt_rbt_set_blackred(tmp, parent);
zt_rbt_rotate_left(head, parent, tmp);
if ((tmp = zt_rbt_right(parent)) == NULL) {
zt_log_dprintf(zt_log_err, "Tree corruption error"), abort();
}
}
if ((zt_rbt_left(tmp) == NULL ||
zt_rbt_colour(zt_rbt_left(tmp)) == zt_rbt_black) &&
(zt_rbt_right(tmp) == NULL ||
zt_rbt_colour(zt_rbt_right(tmp)) == zt_rbt_black)) {
zt_rbt_colour(tmp) = zt_rbt_red;
elm = parent;
parent = zt_rbt_parent(elm);
} else {
if (zt_rbt_right(tmp) == NULL ||
zt_rbt_colour(zt_rbt_right(tmp)) == zt_rbt_black) {
zt_rbt_node * oleft;
if ((oleft = zt_rbt_left(tmp))) {
zt_rbt_colour(oleft) = zt_rbt_black;
}
zt_rbt_colour(tmp) = zt_rbt_red;
zt_rbt_rotate_right(head, tmp, oleft);
tmp = zt_rbt_right(parent);
}
zt_rbt_colour(tmp) = zt_rbt_colour(parent);
zt_rbt_colour(parent) = zt_rbt_black;
if (zt_rbt_right(tmp)) {
zt_rbt_colour(zt_rbt_right(tmp)) = zt_rbt_black;
}
zt_rbt_rotate_left(head, parent, tmp);
elm = *head;
break;
}
} else {
tmp = zt_rbt_left(parent);
if (zt_rbt_colour(tmp) == zt_rbt_red) {
zt_rbt_set_blackred(tmp, parent);
zt_rbt_rotate_right(head, parent, tmp);
if ((tmp = zt_rbt_left(parent)) == NULL) {
zt_log_dprintf(zt_log_err, "Tree corruption error"), abort();
}
}
if ((zt_rbt_left(tmp) == NULL ||
zt_rbt_colour(zt_rbt_left(tmp)) == zt_rbt_black) &&
(zt_rbt_right(tmp) == NULL ||
zt_rbt_colour(zt_rbt_right(tmp)) == zt_rbt_black)) {
zt_rbt_colour(tmp) = zt_rbt_red;
elm = parent;
parent = zt_rbt_parent(elm);
} else {
if (zt_rbt_left(tmp) == NULL ||
zt_rbt_colour(zt_rbt_left(tmp)) == zt_rbt_black) {
zt_rbt_node * oright;
if ((oright = zt_rbt_right(tmp))) {
zt_rbt_colour(oright) = zt_rbt_black;
}
zt_rbt_colour(tmp) = zt_rbt_red;
zt_rbt_rotate_left(head, tmp, oright);
tmp = zt_rbt_left(parent);
}
zt_rbt_colour(tmp) = zt_rbt_colour(parent);
zt_rbt_colour(parent) = zt_rbt_black;
if (zt_rbt_left(tmp)) {
zt_rbt_colour(zt_rbt_left(tmp)) = zt_rbt_black;
}
zt_rbt_rotate_right(head, parent, tmp);
elm = *head;
break;
}
}
}
if (elm) {
zt_rbt_colour(elm) = zt_rbt_black;
}
} /* zt_rbt_remove_colour */
zt_rbt_node *
zt_rbt_remove(zt_rbt **head, zt_rbt_node *elm)
{
zt_rbt_node * child;
zt_rbt_node * parent;
zt_rbt_node * old = elm;
int colour;
if (zt_rbt_left(elm) == NULL) {
child = zt_rbt_right(elm);
} else if (zt_rbt_right(elm) == NULL) {
child = zt_rbt_left(elm);
} else {
zt_rbt_node * left;
elm = zt_rbt_right(elm);
while ((left = zt_rbt_left(elm))) {
elm = left;
}
child = zt_rbt_right(elm);
parent = zt_rbt_parent(elm);
colour = zt_rbt_colour(elm);
if (child) {
zt_rbt_parent(child) = parent;
}
if (parent) {
if (zt_rbt_left(parent) == elm) {
zt_rbt_left(parent) = child;
} else {
zt_rbt_right(parent) = child;
}
} else {
*head = child;
}
if (zt_rbt_parent(elm) == old) {
parent = elm;
}
zt_rbt_left(elm) = zt_rbt_left(old);
zt_rbt_right(elm) = zt_rbt_right(old);
zt_rbt_parent(elm) = zt_rbt_parent(old);
zt_rbt_colour(elm) = zt_rbt_colour(old);
if (zt_rbt_parent(old)) {
if (zt_rbt_left(zt_rbt_parent(old)) == old) {
zt_rbt_left(zt_rbt_parent(old)) = elm;
} else {
zt_rbt_right(zt_rbt_parent(old)) = elm;
}
} else {
*head = elm;
}
zt_rbt_parent(zt_rbt_left(old)) = elm;
if (zt_rbt_right(old)) {
zt_rbt_parent(zt_rbt_right(old)) = elm;
}
/*
* if (parent) {
* left = parent;
* while ((left = zt_rbt_parent(left)));
* }
*/
goto colour;
}
parent = zt_rbt_parent(elm);
colour = zt_rbt_colour(elm);
if (child) {
zt_rbt_parent(child) = parent;
}
if (parent) {
if (zt_rbt_left(parent) == elm) {
zt_rbt_left(parent) = child;
} else {
zt_rbt_right(parent) = child;
}
} else {
*head = child;
}
colour:
if (colour == zt_rbt_black) {
zt_rbt_remove_colour(head, parent, child);
}
return old;
} /* zt_rbt_remove */
/* Inserts a node into the RB tree */
zt_rbt_node *
zt_rbt_insert(zt_rbt **head, zt_rbt_node *elm, int (*cmp)(zt_rbt_node *, zt_rbt_node *))
{
zt_rbt_node * tmp;
zt_rbt_node * parent = NULL;
int comp = 0;
tmp = *head;
while (tmp) {
parent = tmp;
comp = (cmp)(elm, parent);
if (comp < 0) {
tmp = zt_rbt_left(tmp);
} else if (comp > 0) {
tmp = zt_rbt_right(tmp);
} else {
return tmp;
}
}
zt_rbt_set(elm, parent);
if (parent != NULL) {
if (comp < 0) {
zt_rbt_left(parent) = elm;
} else {
zt_rbt_right(parent) = elm;
}
} else {
*head = elm;
}
zt_rbt_insert_colour(head, elm);
return NULL;
}
/* Finds the node with the same key as elm */
zt_rbt_node *
zt_rbt_find(zt_rbt **head, zt_rbt_node *elm, int (*cmp)(zt_rbt_node *, zt_rbt_node *))
{
zt_rbt_node *tmp = *head;
int comp;
while (tmp) {
comp = cmp(elm, tmp);
if (comp < 0) {
tmp = zt_rbt_left(tmp);
} else if (comp > 0) {
tmp = zt_rbt_right(tmp);
} else {
return tmp;
}
}
return NULL;
}
/* find first node greater than or equal to the search key */
zt_rbt_node *
zt_rbt_nfind(zt_rbt **head, zt_rbt_node *elm, int (*cmp)(zt_rbt_node *, zt_rbt_node *))
{
zt_rbt_node *tmp = *head;
zt_rbt_node *res = NULL;
int comp;
while (tmp) {
comp = cmp(elm, tmp);
if (comp < 0) {
res = tmp;
tmp = zt_rbt_left(tmp);
} else if (comp > 0) {
tmp = zt_rbt_right(tmp);
} else {
return tmp;
}
}
return res;
}
zt_rbt_node *
zt_rbt_next(zt_rbt_node *elm)
{
if (!elm) {
return NULL;
}
if (zt_rbt_right(elm)) {
elm = zt_rbt_right(elm);
while (zt_rbt_left(elm)) {
elm = zt_rbt_left(elm);
}
} else {
if (zt_rbt_parent(elm) &&
(elm == zt_rbt_left(zt_rbt_parent(elm)))) {
elm = zt_rbt_parent(elm);
} else {
while (zt_rbt_parent(elm) &&
(elm == zt_rbt_right(zt_rbt_parent(elm)))) {
elm = zt_rbt_parent(elm);
}
elm = zt_rbt_parent(elm);
}
}
return elm;
}
zt_rbt_node *
zt_rbt_minmax(zt_rbt **head, int val)
{
zt_rbt_node *tmp = *head;
zt_rbt_node *parent = NULL;
while (tmp) {
parent = tmp;
if (val < 0) {
tmp = zt_rbt_left(tmp);
} else {
tmp = zt_rbt_right(tmp);
}
}
return parent;
}
|
123 | ./libzt/src/zt_ez_mempool.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "zt.h"
#include "zt_stdint.h"
#include "zt_internal.h"
static void
chunk_append(zt_ez_mempool_chunk **head,
zt_ez_mempool_chunk *chunk) {
if (*head == NULL) {
*head = chunk;
return;
}
chunk->next = *head;
*head = chunk;
}
static zt_ez_mempool_chunk *
zt_ez_mempool_chunk_init(const size_t size, zt_ez_mempool_free_cb free_cb) {
zt_ez_mempool_chunk *chunk;
chunk = zt_malloc(zt_ez_mempool_chunk, 1);
chunk->sz = size;
chunk->data = zt_callocs(size, 1);
chunk->free_cb = free_cb;
chunk->next = NULL;
return chunk;
}
static void
pool_append(zt_ez_mempool **head,
zt_ez_mempool *pool) {
if (*head == NULL) {
*head = pool;
return;
}
pool->next = *head;
*head = pool;
}
zt_ez_mempool *
zt_ez_mempool_init(zt_ez_mempool *parent) {
zt_ez_mempool *pool;
pool = zt_calloc(zt_ez_mempool, 1);
if (pool == NULL) {
return NULL;
}
if (parent != NULL) {
pool_append(&parent->subpools, pool);
pool->parent = parent;
}
return pool;
}
static void
free_chunks(zt_ez_mempool_chunk *chunks) {
zt_ez_mempool_chunk *chunk_ptr;
chunk_ptr = chunks;
while (chunk_ptr != NULL) {
zt_ez_mempool_chunk *tofree;
tofree = chunk_ptr;
if (chunk_ptr->free_cb) {
chunk_ptr->free_cb(chunk_ptr->data);
} else {
zt_free(chunk_ptr->data);
}
chunk_ptr = chunk_ptr->next;
zt_free(tofree);
}
}
void
zt_ez_mempool_destroy(zt_ez_mempool *pool) {
zt_ez_mempool *pool_ptr;
pool_ptr = pool->subpools;
if (pool->parent != NULL) {
pool->parent->subpools = NULL;
}
free_chunks(pool->chunks);
while (pool_ptr != NULL) {
zt_ez_mempool *next = pool_ptr->next;
zt_ez_mempool_destroy(pool_ptr);
pool_ptr = next;
}
zt_free(pool);
}
void *
zt_ez_mempool_alloc(zt_ez_mempool *pool, size_t size, zt_ez_mempool_free_cb free_cb) {
zt_ez_mempool_chunk *chunk;
chunk = zt_ez_mempool_chunk_init(size, free_cb);
if (chunk == NULL) {
return NULL;
}
chunk_append(&pool->chunks, chunk);
return chunk->data;
}
char *
zt_ez_mempool_strdup(zt_ez_mempool *pool, const char *s) {
char *ret = zt_strdup(s);
zt_ez_mempool_add_buffer(pool, (void *)ret, strlen(ret), free);
return ret;
}
int
zt_ez_mempool_add_buffer(zt_ez_mempool *pool, void *data, size_t size,
zt_ez_mempool_free_cb free_cb) {
zt_ez_mempool_chunk *chunk;
if (data == NULL || size == 0) {
return -1;
}
if (!(chunk = zt_malloc(zt_ez_mempool_chunk, 1))) {
perror("malloc");
return -1;
}
chunk->sz = size;
chunk->data = data;
chunk->next = NULL;
chunk->free_cb = free_cb;
chunk_append(&pool->chunks, chunk);
return 0;
}
|
124 | ./libzt/src/zt_cfg.c | /*!
* Filename: zt_cfg.h
* Description: config file abstraction
*
* Author: Jason L. Shiffer <jshiffer@zerotao.org>
* Copyright:
* Copyright (C) 2000-2010, Jason L. Shiffer.
* See file COPYING for details
*
* Notes:
*
*/
#ifdef HAVE_CONFIG_H
#include <zt_config.h>
#endif
#include "zt.h"
#include "zt_cfg.h"
#include "zt_cfg/cfg_private.h"
#undef zt_cfg_close
void zt_cfg_close( zt_cfg_ty *cfg )
{
if (cfg && cfg->vtbl->destructor) {
cfg->vtbl->destructor(cfg);
}
return;
}
#undef zt_cfg_get
int
zt_cfg_get( zt_cfg_ty *cfg, char *block, char *name, void * value, zt_cfg_type type )
{
if (cfg && cfg->vtbl->get) {
return cfg->vtbl->get(cfg, block, name, value, type);
}
return 0;
}
#undef zt_cfg_set
int zt_cfg_set( zt_cfg_ty *cfg, char *block, char *name, void *value, zt_cfg_type type )
{
if (cfg && cfg->vtbl->set) {
return cfg->vtbl->set(cfg, block, name, value, type);
}
return 0;
}
|
125 | ./libzt/src/zt_time.c | /*!
* Filename: zt_time.c
* Description: time manipulation functions
*
* Author: Jason L. Shiffer <jshiffer@zerotao.org>
* Copyright:
* Copyright (C) 2000-2010, Jason L. Shiffer.
* See file COPYING for details
*
* Notes:
*
*/
#ifndef WIN32
#include <sys/resource.h>
#endif
#include "zt_time.h"
#include "zt_log.h"
#include "zt_assert.h"
struct timeval *
zt_add_time(struct timeval *at, struct timeval *t1, struct timeval *t2)
{
at->tv_sec = t1->tv_sec + t2->tv_sec;
at->tv_usec = t1->tv_usec + t2->tv_usec;
while (at->tv_usec >= 1000000) {
at->tv_sec++;
at->tv_usec -= 1000000;
}
return at;
}
struct timeval *
zt_sub_time(struct timeval *st, struct timeval *t1, struct timeval *t2)
{
st->tv_sec = t1->tv_sec - t2->tv_sec;
st->tv_usec = t1->tv_usec - t2->tv_usec;
while (st->tv_usec < 0) {
st->tv_sec--;
st->tv_usec += 1000000;
}
return st;
}
struct timeval *
zt_diff_time(struct timeval *dt, struct timeval *t1, struct timeval *t2)
{
dt->tv_sec = t2->tv_sec - t1->tv_sec;
dt->tv_usec = t2->tv_usec - t1->tv_usec;
while (dt->tv_usec < 0) {
dt->tv_usec += 1000000;
dt->tv_sec -= 1;
}
return dt;
}
/* <0, 0, >0
* t1 <, =, > t2
*/
long
zt_cmp_time(struct timeval *t1,
struct timeval *t2)
{
long t = t1->tv_sec - t2->tv_sec;
if (t) {
return t;
}
return t1->tv_usec - t2->tv_usec;
}
/*!
* Name: zt_time_result_to_elapsed
* Description:
* calculates the time in float of result and returns the results in usr, sys, total
* the calculation used is specific to how zt_time calculates it's information.
*/
void
zt_time_result_to_elapsed(struct time_result *result, float *usr, float *sys, float *total)
{
zt_assert(result);
zt_assert(usr);
zt_assert(sys);
zt_assert(total);
*usr = (float) (result->usr_time.tv_sec + result->usr_time.tv_usec / 1000000.0);
*sys = (float) (result->sys_time.tv_sec + result->sys_time.tv_usec / 1000000.0);
*total = *usr + *sys;
}
static struct time_result _calibration_time = { { 0, 0 }, { 0, 0 } };
void
zt_time_calibrate(void)
{
zt_time(0, &_calibration_time, NULL, NULL);
}
/*!
* Name: zt_time
* Description:
* returns a struct time_result specifing how long the function test took when called
* with data. If n is 0 then test does not need to be set (ie test the zt_time overhead).
* returns the last result of calling test (or NULL if n = 0).
*/
void *
zt_time(int n, struct time_result *tv, void *(*test)(void *), void *data)
{
#ifndef WIN32
struct rusage rafter;
struct rusage rbefore;
int i;
void * ret = NULL;
zt_assert(tv);
getrusage(RUSAGE_SELF, &rbefore);
if (test && n) {
for (i = 0; i <= n; i++) {
ret = test(data);
}
}
getrusage(RUSAGE_SELF, &rafter);
zt_diff_time(&tv->usr_time, &rbefore.ru_utime, &rafter.ru_utime);
zt_diff_time(&tv->sys_time, &rbefore.ru_stime, &rafter.ru_stime);
zt_sub_time(&tv->usr_time, &tv->usr_time, &_calibration_time.usr_time);
zt_sub_time(&tv->sys_time, &tv->sys_time, &_calibration_time.sys_time);
return ret;
#else
return NULL; // TODO
#endif
}
void
zt_time_print_result(struct time_result *tr, char *name, int n)
{
float usr;
float sys;
float total;
zt_assert(tr);
zt_assert(name);
zt_time_result_to_elapsed(tr, &usr, &sys, &total);
if (n <= 1) {
zt_log_printf(zt_log_info, "%s took: %4.2fs user %4.2fs system %4.2fs total", name, usr, sys, total);
} else {
zt_log_printf(zt_log_info, "%d calls of %s took: %4.2fs user %4.2fs system %4.2fs total", n, name, usr, sys, total);
}
}
|
126 | ./libzt/src/zt_threads.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#include <sys/queue.h>
#include <unistd.h>
#include <zt.h>
#include <zt_threads.h>
static void * _zt_threadpool_iput_loop(void *args);
static void * _zt_threadpool_oput_loop(void *args);
struct zt_threads_lock_callbacks _zt_threads_lock_cbs = {
NULL, NULL, NULL, NULL
};
struct zt_threads_cond_callbacks _zt_threads_cond_cbs = {
NULL, NULL, NULL, NULL
};
struct zt_threads_cntrl_callbacks _zt_threads_cntrl_cbs = {
NULL, NULL, NULL, NULL, NULL, NULL
};
struct zt_threadpool_callbacks _zt_threadpool_cbs = {
_zt_threadpool_iput_loop, _zt_threadpool_oput_loop, NULL, NULL, NULL, NULL
};
zt_threads_thread * (*zt_threads_alloc_thread)(void);
int
zt_threads_set_lock_callbacks(struct zt_threads_lock_callbacks *cbs) {
struct zt_threads_lock_callbacks *t = &_zt_threads_lock_cbs;
if (cbs == NULL) {
memset(t, 0, sizeof(_zt_threads_lock_cbs));
return 0;
}
if (cbs->alloc && cbs->free && cbs->lock && cbs->unlock) {
memcpy(t, cbs, sizeof(_zt_threads_lock_cbs));
return 0;
}
return -1;
}
int
zt_threads_set_cond_callbacks(struct zt_threads_cond_callbacks *cbs) {
struct zt_threads_cond_callbacks *t = &_zt_threads_cond_cbs;
if (cbs == NULL) {
memset(t, 0, sizeof(_zt_threads_cond_cbs));
return 0;
}
if (cbs->alloc && cbs->free && cbs->signal && cbs->wait) {
memcpy(t, cbs, sizeof(_zt_threads_cond_cbs));
return 0;
}
return -1;
}
int
zt_threads_set_cntrl_callbacks(struct zt_threads_cntrl_callbacks *cbs) {
struct zt_threads_cntrl_callbacks *t = &_zt_threads_cntrl_cbs;
if (cbs == NULL) {
memset(t, 0, sizeof(_zt_threads_cntrl_cbs));
return 0;
}
if (cbs->start && cbs->end) {
memcpy(t, cbs, sizeof(_zt_threads_cntrl_cbs));
return 0;
}
return -1;
}
zt_threads_mutex *
zt_threads_alloc_lock(int type) {
if (_zt_threads_lock_cbs.alloc) {
return _zt_threads_lock_cbs.alloc(type);
}
return NULL;
}
void
zt_threads_free_lock(zt_threads_mutex * lock, int locktype) {
if (_zt_threads_lock_cbs.free) {
_zt_threads_lock_cbs.free(lock, locktype);
} else {
return;
}
}
int
zt_threads_lock(int mode, zt_threads_mutex *lock) {
if (_zt_threads_lock_cbs.lock) {
return _zt_threads_lock_cbs.lock(mode, lock);
}
return 0;
}
int
zt_threads_unlock(int mode, zt_threads_mutex *lock) {
if (_zt_threads_lock_cbs.unlock) {
return _zt_threads_lock_cbs.unlock(mode, lock);
}
return 0;
}
zt_threads_cond *
zt_threads_cond_alloc(int type) {
if (_zt_threads_cond_cbs.alloc) {
return _zt_threads_cond_cbs.alloc(type);
}
return NULL;
}
void
zt_threads_cond_free(zt_threads_cond *cond) {
if (_zt_threads_cond_cbs.free) {
_zt_threads_cond_cbs.free(cond);
}
}
int
zt_threads_cond_signal(zt_threads_cond *cond, int broadcast) {
if (_zt_threads_cond_cbs.signal) {
return _zt_threads_cond_cbs.signal(cond, broadcast);
}
return 0;
}
int
zt_threads_cond_wait(zt_threads_cond *cond, zt_threads_mutex *lock, struct timeval *timeout) {
if (_zt_threads_cond_cbs.wait) {
return _zt_threads_cond_cbs.wait(cond, lock, timeout);
}
return 0;
}
int
zt_threads_start(zt_threads_thread *thread, zt_threads_cond *attr, void * (*cb)(void*), void *args) {
if (_zt_threads_cntrl_cbs.start) {
return _zt_threads_cntrl_cbs.start(thread, attr, cb, args);
}
return 0;
}
void
zt_threads_end(void *args) {
if (_zt_threads_cntrl_cbs.end) {
_zt_threads_cntrl_cbs.end(args);
}
}
int
zt_threads_kill(zt_threads_thread *thread) {
if (_zt_threads_cntrl_cbs.kill) {
return _zt_threads_cntrl_cbs.kill(thread);
}
return 0;
}
int
zt_threads_join(zt_threads_thread *thread, void **data) {
if (_zt_threads_cntrl_cbs.join) {
return _zt_threads_cntrl_cbs.join(thread, data);
}
return 0;
}
unsigned long int
zt_threads_id(void) {
if (_zt_threads_cntrl_cbs.id) {
return _zt_threads_cntrl_cbs.id();
}
return 0;
}
int
zt_threads_detach(zt_threads_thread *thread) {
if (_zt_threads_cntrl_cbs.detach) {
return _zt_threads_cntrl_cbs.detach(thread);
}
return -1;
}
/*****************************************************************
* threadpool defs
*****************************************************************/
void
zt_threadpool_disable_iput_loop(void) {
_zt_threadpool_cbs.iput_loop = NULL;
}
void
zt_threadpool_disable_oput_loop(void) {
_zt_threadpool_cbs.oput_loop = NULL;
}
int
zt_threadpool_set_callbacks(struct zt_threadpool_callbacks *cbs) {
if (cbs == NULL) {
/* set our defaults */
_zt_threadpool_cbs.iput_loop = _zt_threadpool_iput_loop;
_zt_threadpool_cbs.oput_loop = _zt_threadpool_oput_loop;
_zt_threadpool_cbs.init = NULL;
_zt_threadpool_cbs.iput_worker = NULL;
_zt_threadpool_cbs.oput_worker = NULL;
return 0;
}
if (cbs->iput_loop) {
_zt_threadpool_cbs.iput_loop = cbs->iput_loop;
}
if (cbs->oput_loop) {
_zt_threadpool_cbs.oput_loop = cbs->oput_loop;
}
if (cbs->init) {
_zt_threadpool_cbs.init = cbs->init;
}
if (cbs->iput_worker) {
_zt_threadpool_cbs.iput_worker = cbs->iput_worker;
}
if (cbs->oput_worker) {
_zt_threadpool_cbs.oput_worker = cbs->oput_worker;
}
if (cbs->finalize) {
_zt_threadpool_cbs.finalize = cbs->finalize;
}
return 0;
} /* zt_threadpool_set_callbacks */
static void *
_zt_threadpool_oput_loop(void *args) {
zt_threadpool *tpool;
void *init_data = NULL;
tpool = (zt_threadpool*)args;
if (_zt_threadpool_cbs.init) {
init_data = _zt_threadpool_cbs.init(args);
}
while (1) {
zt_threadpool_entry *entry = NULL;
if (zt_threads_lock(0, tpool->oput_mutex)) {
zt_threads_end(NULL);
}
if (TAILQ_EMPTY(&tpool->oput_queue)) {
if (tpool->kill) {
zt_threads_unlock(0, tpool->oput_mutex);
zt_threads_end(NULL);
return NULL;
}
zt_threads_cond_wait(tpool->oput_cond, tpool->oput_mutex, NULL);
zt_threads_unlock(0, tpool->oput_mutex);
continue;
} else {
entry = TAILQ_FIRST(&tpool->oput_queue);
TAILQ_REMOVE(&tpool->oput_queue, entry, next);
}
if (entry == NULL) {
if (tpool->kill == 1) {
zt_threads_unlock(0, tpool->oput_mutex);
zt_threads_end(NULL);
return NULL;
}
zt_threads_unlock(0, tpool->oput_mutex);
continue;
}
zt_threads_unlock(0, tpool->oput_mutex);
if (_zt_threadpool_cbs.oput_worker) {
void *input;
input = _zt_threadpool_cbs.oput_worker(init_data, entry->data);
if (input != NULL) {
if (_zt_threadpool_cbs.finalize) {
_zt_threadpool_cbs.finalize(init_data, input);
}
}
}
if (entry != NULL) {
free(entry);
}
}
return NULL;
} /* _zt_threadpool_loop */
static void *
_zt_threadpool_iput_loop(void *args) {
zt_threadpool *tpool;
void *init_data = NULL;
tpool = (zt_threadpool*)args;
if (_zt_threadpool_cbs.init) {
init_data = _zt_threadpool_cbs.init(args);
}
while (1) {
zt_threadpool_entry *entry = NULL;
if (zt_threads_lock(0, tpool->iput_mutex)) {
zt_threads_end(NULL);
}
if (TAILQ_EMPTY(&tpool->iput_queue)) {
if (tpool->kill) {
zt_threads_unlock(0, tpool->iput_mutex);
zt_threads_end(NULL);
return NULL;
}
zt_threads_cond_wait(tpool->iput_cond, tpool->iput_mutex, NULL);
zt_threads_unlock(0, tpool->iput_mutex);
continue;
} else {
entry = TAILQ_FIRST(&tpool->iput_queue);
TAILQ_REMOVE(&tpool->iput_queue, entry, next);
}
if (entry == NULL) {
if (tpool->kill == 1) {
zt_threads_unlock(0, tpool->iput_mutex);
zt_threads_end(NULL);
return NULL;
}
zt_threads_unlock(0, tpool->iput_mutex);
continue;
}
zt_threads_unlock(0, tpool->iput_mutex);
if (_zt_threadpool_cbs.iput_worker) {
void *input;
input = _zt_threadpool_cbs.iput_worker(init_data, entry->data);
if (input != NULL) {
zt_threadpool_insert_oput(tpool, input);
}
}
if (entry != NULL) {
free(entry);
}
}
return NULL;
} /* _zt_threadpool_loop */
int
zt_threadpool_insert_iput(zt_threadpool *tpool, void *data) {
zt_threadpool_entry *entry;
int i = 0;
int ret = 0;
entry = calloc(sizeof(zt_threadpool_entry), 1);
entry->data = data;
zt_threads_lock(0, tpool->iput_mutex);
{
TAILQ_INSERT_TAIL(&tpool->iput_queue, entry, next);
zt_threads_cond_signal(tpool->iput_cond, 0);
if (tpool->iput_fd_sigs[1] >= 0) {
if (write(tpool->iput_fd_sigs[1], &i, 1) < 0) {
ret = -1;
}
}
}
zt_threads_unlock(0, tpool->iput_mutex);
return ret;
}
int
zt_threadpool_insert_oput(zt_threadpool *tpool, void *data) {
zt_threadpool_entry *entry;
int i = 0;
int ret = 0;
entry = calloc(sizeof(zt_threadpool_entry), 1);
entry->data = data;
zt_threads_lock(0, tpool->oput_mutex);
{
TAILQ_INSERT_TAIL(&tpool->oput_queue, entry, next);
zt_threads_cond_signal(tpool->oput_cond, 0);
if (tpool->oput_fd_sigs[1] >= 0) {
if (write(tpool->oput_fd_sigs[1], &i, 1) < 0) {
ret = -1;
}
}
}
zt_threads_unlock(0, tpool->oput_mutex);
return ret;
}
void *
zt_threadpool_get_oput(zt_threadpool *tpool) {
zt_threadpool_entry *entry = NULL;
void *data;
zt_threads_lock(0, tpool->oput_mutex);
do {
if (TAILQ_EMPTY(&tpool->oput_queue)) {
break;
}
entry = TAILQ_FIRST(&tpool->oput_queue);
TAILQ_REMOVE(&tpool->oput_queue, entry, next);
} while (0);
zt_threads_unlock(0, tpool->oput_mutex);
if (entry == NULL) {
return NULL;
}
data = entry->data;
free(entry);
return data;
}
int
zt_threadpool_start(zt_threadpool *tpool) {
int i;
if (_zt_threadpool_cbs.iput_loop) {
for (i = 0; i < tpool->min_threads; i++) {
tpool->iput_threads[i] = zt_threads_alloc_thread();
zt_threads_start(tpool->iput_threads[i], NULL,
_zt_threadpool_cbs.iput_loop, (void*)tpool);
}
}
if (_zt_threadpool_cbs.oput_loop) {
for (i = 0; i < tpool->min_threads; i++) {
tpool->oput_threads[i] = zt_threads_alloc_thread();
zt_threads_start(tpool->oput_threads[i], NULL,
_zt_threadpool_cbs.oput_loop, (void*)tpool);
}
}
return 0;
}
int
zt_threadpool_iput_fd_reader(zt_threadpool *tpool) {
return tpool->iput_fd_sigs[0];
}
int
zt_threadpool_iput_fd_writer(zt_threadpool *tpool) {
return tpool->iput_fd_sigs[1];
}
int
zt_threadpool_oput_fd_reader(zt_threadpool *tpool) {
return tpool->oput_fd_sigs[0];
}
int
zt_threadpool_oput_fd_writer(zt_threadpool *tpool) {
return tpool->oput_fd_sigs[1];
}
int
zt_threadpool_kill(zt_threadpool *tpool) {
int i;
int k = 1;
int ret = 0;
tpool->kill = 1;
/* signal all threads, and let them die */
zt_threads_cond_signal(tpool->iput_cond, 1);
zt_threads_cond_signal(tpool->oput_cond, 1);
for (i = 0; i < tpool->min_threads; i++) {
if (_zt_threadpool_cbs.iput_loop) {
zt_threads_join(tpool->iput_threads[i], NULL);
}
if (_zt_threadpool_cbs.oput_loop) {
zt_threads_join(tpool->oput_threads[i], NULL);
}
}
if (tpool->oput_fd_sigs[1] >= 0) {
if (write(tpool->oput_fd_sigs[1], &k, 1) < 0) {
ret = -1;
}
}
if (tpool->iput_fd_sigs[1] >= 0) {
if (write(tpool->iput_fd_sigs[1], &i, 1) < 0) {
ret = -1;
}
}
return ret;
}
zt_threadpool *
zt_threadpool_init(int min_threads, int max_threads, int pipe_iput, int pipe_oput) {
zt_threadpool *tpool;
tpool = calloc(sizeof(zt_threadpool), 1);
tpool->min_threads = min_threads;
tpool->max_threads = max_threads;
tpool->thread_count = min_threads;
if (pipe_iput) {
if (pipe(tpool->iput_fd_sigs) < 0) {
free(tpool);
return NULL;
}
} else {
tpool->iput_fd_sigs[0] = -1;
tpool->iput_fd_sigs[1] = -1;
}
if (pipe_oput) {
if (pipe(tpool->oput_fd_sigs) < 0) {
if (pipe_iput) {
close(tpool->oput_fd_sigs[0]);
close(tpool->oput_fd_sigs[1]);
}
free(tpool);
return NULL;
}
} else {
tpool->oput_fd_sigs[0] = -1;
tpool->oput_fd_sigs[1] = -1;
}
tpool->iput_threads = calloc(sizeof(zt_threads_thread *), min_threads);
tpool->iput_mutex = zt_threads_alloc_lock(0);
tpool->oput_mutex = zt_threads_alloc_lock(0);
tpool->iput_cond = zt_threads_cond_alloc(0);
tpool->oput_cond = zt_threads_cond_alloc(0);
if (_zt_threadpool_cbs.oput_loop) {
tpool->oput_threads = calloc(sizeof(zt_threads_thread *), min_threads);
}
TAILQ_INIT(&tpool->iput_queue);
TAILQ_INIT(&tpool->oput_queue);
return tpool;
} /* zt_threadpool_init */
|
127 | ./libzt/src/zt_mem.c | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "zt.h"
#include "zt_internal.h"
#include "zt_assert.h"
#include "zt_list.h"
#include "zt_mem.h"
#include "zt_atexit.h"
/*
* FIXME: threads will need these wrapped
*/
static struct {
void *(* alloc)(size_t);
void (* dealloc)(void *);
void *(* realloc)(void *, size_t);
} GLOBAL_zmt = { malloc, free, realloc };
static zt_elist(pools);
static zt_elist(sets);
static int mem_atexit = 0;
/* static long x_sys_page_size = 0; */
typedef struct zt_mem_elt zt_mem_elt;
struct zt_mem_elt {
zt_elist_t free_elt_list;
struct zt_mem_page * parent_page;
unsigned long data[];
};
struct zt_mem_heap {
char * name;
size_t size;
unsigned long heap[];
};
typedef struct zt_mem_page zt_mem_page;
struct zt_mem_page {
zt_elist_t page_list;
struct zt_mem_pool * parent_pool;
unsigned long num_free_elts;
unsigned long data[];
};
struct zt_mem_pool {
zt_elist_t pool_list;
char * name;
size_t rcache; /* requested elements in cache */
size_t ncache; /* actual elements in cache */
size_t pcache; /* pages in cache */
size_t nfree_pages; /* number of free pages */
size_t npages; /* total pages */
size_t elts_per_page; /* elements per page */
size_t elt_size; /* element size */
size_t page_size; /* page size */
size_t page_allocs; /* number of page allocs */
size_t page_frees; /* number of page frees */
zt_page_release_test release_test_cb;
void * release_test_cb_data;
int flags;
zt_elist_t page_list;
zt_elist_t free_elt_list;
};
struct zt_mem_pool_group {
zt_elist_t group_list;
size_t npools;
zt_mem_pool **pools;
};
struct zt_mem_set_elt {
zt_elist_t elt_list;
void * elt;
};
struct zt_mem_set {
zt_elist_t set_list;
char * name;
zt_elist_t elt_list;
};
/* forward declarations */
static char *zt_mem_strdup(char *str);
static void zt_mem_page_display(int, zt_mem_page *);
static int zt_mem_page_destroy(zt_mem_page *page);
static zt_mem_page *zt_mem_page_alloc(zt_mem_pool *);
static void zt_mem_elt_list_display(int offset, zt_elist_t *head);
static int zt_default_release_test(size_t total_pages, size_t free_pages, size_t cache_size, int flags, void *cb_data);
static void zt_mem_release(void * data);
/* exported functions */
zt_mem_heap*
zt_mem_heap_init(char *name, size_t size)
{
zt_mem_heap * heap;
if ((heap = GLOBAL_zmt.alloc(sizeof(zt_mem_heap) + size)) == NULL) {
return NULL;
}
heap->name = zt_mem_strdup(name ? name : "*unknown*");
heap->size = size;
return heap;
}
void
zt_mem_heap_destroy(zt_mem_heap **heap)
{
if (!heap) {
return;
}
GLOBAL_zmt.dealloc((*heap)->name);
(*heap)->name = 0;
(*heap)->size = 0;
GLOBAL_zmt.dealloc(*heap);
*heap = 0;
}
void *
zt_mem_heap_get_data(zt_mem_heap *heap)
{
return (void *)heap->heap;
}
char *
zt_mem_heap_get_name(zt_mem_heap *heap)
{
if (heap) {
return heap->name;
}
return 0;
}
static int
x_calculate_page_data(ssize_t elts, size_t size, size_t *page_size, size_t *epp, size_t *npages)
{
static size_t sys_page_size = 0;
size_t usable_page_size = 0;
if (sys_page_size == 0) {
sys_page_size = sysconf(_SC_PAGESIZE);
}
usable_page_size = sys_page_size - sizeof(zt_mem_page);
/* This algorithm is pretty stupid it mearly tries to
* calculate if I can fit a reasonable number of elements into
* a system memory page.
* if (the element size is < 1/2 (system page size - overhead))
* use a system page for page size
* else
* page size is elts * size + overhead
*/
if (size < (usable_page_size / 2)) {
*epp = usable_page_size / (sizeof(zt_mem_elt) + size);
*page_size = sys_page_size;
if (elts > (ssize_t)*epp) {
*npages = elts / *epp;
} else {
*npages = 1;
}
} else {
*epp = elts;
*page_size = (elts * (sizeof(zt_mem_elt) + size)) + sizeof(zt_mem_page);
*npages = 1;
}
return 0;
}
zt_mem_pool*
zt_mem_pool_init(char *name, ssize_t elts,
size_t size, zt_page_release_test release_test,
void *cb_data, int flags)
{
zt_mem_pool * pool;
zt_mem_page * page;
size_t epp;
size_t npage_size;
size_t npages;
size_t pcache;
x_calculate_page_data(elts ? elts : 1, size, &npage_size, &epp, &npages);
if (!mem_atexit) {
zt_atexit(zt_mem_release, NULL);
mem_atexit = 1;
}
if (elts > 0) {
if (elts < (ssize_t)epp) {
pcache = 1;
} else {
ssize_t tmp = elts % epp;
pcache = elts / epp;
if (tmp > 0) {
pcache++;
}
}
} else {
/* will be 1 with the current algorithm */
pcache = npages;
}
if ((pool = GLOBAL_zmt.alloc(sizeof(zt_mem_pool))) == 0) {
return NULL;
}
zt_elist_reset(&pool->pool_list);
pool->name = zt_mem_strdup(name ? name : "*unknown*");
pool->rcache = elts;
pool->ncache = pcache * epp;
pool->pcache = pcache;
/* > 0 ? cache : 0; */ /* cache should never be negative*/
pool->nfree_pages = 0;
pool->npages = 0;
/* pool->elts_per_page = elts; */
pool->elts_per_page = epp;
pool->elt_size = size;
pool->page_size = npage_size;
pool->page_allocs = 0;
pool->page_frees = 0;
pool->release_test_cb = release_test ? release_test : zt_default_release_test;
pool->release_test_cb_data = cb_data ? cb_data : NULL;
pool->flags = flags;
/* printf("page size calculated: %ld\npage size actual: %ld\n", */
/* pool->page_size, */
/* sizeof(zt_mem_page) + (pool->elts_per_page * (sizeof(zt_mem_elt) + pool->elt_size))); */
zt_elist_reset(&pool->page_list);
zt_elist_reset(&pool->free_elt_list);
if (npages > 0) {
/* fill the cache */
while (npages--) {
page = zt_mem_page_alloc(pool);
zt_elist_add_tail(&pool->page_list, &page->page_list);
pool->page_allocs++;
}
}
zt_elist_add_tail(&pools, &pool->pool_list);
return pool;
} /* zt_mem_pool_init */
void *
zt_mem_pool_alloc(zt_mem_pool *pool)
{
zt_elist_t * tmp;
zt_mem_elt * elt;
if (pool == 0) {
return 0;
}
/* if the free elt list is empty get a new page */
if (zt_elist_empty(&pool->free_elt_list) == 1) {
/* alloc a new page */
zt_mem_page *page;
page = zt_mem_page_alloc(pool);
/* */
zt_elist_add_tail(&pool->page_list, &page->page_list);
pool->page_allocs++;
}
tmp = zt_elist_get_next(&pool->free_elt_list);
zt_elist_remove(tmp);
elt = zt_elist_data(tmp, zt_mem_elt, free_elt_list);
--elt->parent_page->num_free_elts;
/* if we have used the first elt then decrement the free pages */
if (elt->parent_page->num_free_elts == pool->elts_per_page - 1) {
--pool->nfree_pages;
}
return (void *)&elt->data;
}
void
zt_mem_pool_release(void **data)
{
zt_mem_elt * elt;
zt_mem_pool * pool;
zt_mem_page * page;
elt = zt_elist_data(*data, zt_mem_elt, data);
page = elt->parent_page;
if (page == NULL) {
/* this element was allocated by zt_alloc and should just be freed */
zt_free(*data);
return;
}
pool = page->parent_pool;
/* add the element to the pools free elt list */
page->num_free_elts++;
zt_elist_add(&pool->free_elt_list, &elt->free_elt_list);
/* if all of the pages elements are free */
if (page->num_free_elts == pool->elts_per_page) {
pool->nfree_pages++;
}
if (page->num_free_elts == pool->elts_per_page) {
if (pool->release_test_cb(pool->rcache,
pool->ncache * pool->nfree_pages,
pool->ncache * (pool->npages - pool->nfree_pages),
pool->flags,
pool->release_test_cb_data)) {
/* release the page */
zt_mem_page_destroy(page);
pool->page_frees++;
}
}
}
int
zt_mem_pool_release_free_pages(zt_mem_pool *pool)
{
zt_elist_t * pages;
zt_elist_t * tpage;
zt_mem_page * page;
zt_elist_for_each_safe(&(pool)->page_list, pages, tpage) {
page = zt_elist_data(pages, zt_mem_page, page_list);
if (page->num_free_elts == pool->elts_per_page) {
zt_mem_page_destroy(page);
}
}
return 0;
}
int
zt_mem_pool_destroy(zt_mem_pool **pool)
{
zt_elist_t * tmp;
zt_elist_t * ptmp;
zt_mem_page * page;
zt_elist_for_each_safe(&(*pool)->page_list, tmp, ptmp) {
page = zt_elist_data(tmp, zt_mem_page, page_list);
/* sanity checking */
if (page->num_free_elts < (*pool)->elts_per_page) {
return -1;
} else {
zt_mem_page_destroy(page);
}
}
zt_elist_remove(&(*pool)->pool_list);
GLOBAL_zmt.dealloc((*pool)->name);
(*pool)->name = NULL;
GLOBAL_zmt.dealloc((*pool));
*pool = NULL;
return 0;
}
int
zt_mem_pool_get_stats(zt_mem_pool *pool, zt_mem_pool_stats *stats)
{
if (!pool || !stats) {
return ZT_FAIL;
}
stats->requested_elts = pool->rcache;
stats->actual_elts = pool->ncache;
stats->cached_pages = pool->pcache;
stats->free_pages = pool->nfree_pages;
stats->pages = pool->npages;
stats->elts_per_page = pool->elts_per_page;
stats->elt_size = pool->elt_size;
stats->page_size = pool->page_size;
stats->page_allocs = pool->page_allocs;
stats->page_frees = pool->page_frees;
stats->flags = pool->flags;
return ZT_PASS;
}
void
zt_mem_pool_display(int offset, zt_mem_pool *pool, int flags)
{
zt_elist_t * tmp;
zt_mem_page * page;
long felts = 0;
zt_elist_for_each(&pool->page_list, tmp) {
page = zt_elist_data(tmp, zt_mem_page, page_list);
felts += page->num_free_elts;
}
printf(BLANK "pool: \"%s\" [%p] {\n"
BLANK "elements: {\n"
BLANK "elt cache requested: %" PRIsize_t " elements\n"
BLANK "elt cache actual: %" PRIsize_t " elements\n"
BLANK "total elts: %" PRIsize_t "\n"
BLANK "free elts: %ld\n"
BLANK "}\n"
BLANK "pages: {\n"
BLANK "page cache: %" PRIsize_t " page(s)\n"
BLANK "free pages: %" PRIsize_t"\n"
BLANK "page size: %" PRIsize_t "\n"
BLANK "pages in use: %" PRIsize_t "\n"
BLANK "total pages: %" PRIsize_t "\n"
BLANK "elements per page: %" PRIsize_t "\n"
BLANK "page allocs: %" PRIsize_t "\n"
BLANK "page frees: %" PRIsize_t "\n"
BLANK "}\n"
BLANK "overall: {\n"
BLANK "element size: %" PRIsize_t " bytes + overhead = %" PRIsize_t " bytes \n"
BLANK "page usage (num elts * elt size): %" PRIsize_t" bytes\n"
BLANK "page memory (page size * total pages): %" PRIsize_t" bytes\n"
BLANK "}\n",
INDENT(offset), pool->name, (void *)pool,
INDENT(offset + 1),
INDENT(offset + 2), pool->rcache,
INDENT(offset + 2), pool->ncache,
INDENT(offset + 2), (pool->elts_per_page * pool->npages),
INDENT(offset + 2), felts,
INDENT(offset + 1), INDENT(offset + 1),
INDENT(offset + 2), pool->pcache,
INDENT(offset + 2), pool->nfree_pages,
INDENT(offset + 2), pool->page_size,
INDENT(offset + 2), (pool->npages - pool->nfree_pages),
INDENT(offset + 2), pool->npages,
INDENT(offset + 2), pool->elts_per_page,
INDENT(offset + 2), pool->page_allocs,
INDENT(offset + 2), pool->page_frees,
INDENT(offset + 1), INDENT(offset + 1),
INDENT(offset + 2), pool->elt_size, sizeof(zt_mem_elt) + pool->elt_size,
INDENT(offset + 2), (sizeof(zt_mem_elt) + pool->elt_size) * pool->elts_per_page,
INDENT(offset + 2), pool->page_size * pool->npages,
INDENT(offset + 1));
if (flags & DISPLAY_POOL_FREE_LIST) {
printf(BLANK "free_list {\n", INDENT(offset + 1));
zt_mem_elt_list_display(offset + 2, &pool->free_elt_list);
printf("\n" BLANK "}\n", INDENT(offset + 1));
}
if (flags & DISPLAY_POOL_PAGES) {
printf(BLANK "pages {\n", INDENT(offset + 1));
zt_elist_for_each(&pool->page_list, tmp) {
page = zt_elist_data(tmp, zt_mem_page, page_list);
zt_mem_page_display(offset + 2, page);
}
printf(BLANK "}\n", INDENT(offset + 1));
}
printf(BLANK "}\n", INDENT(offset));
} /* zt_mem_pool_display */
void
zt_mem_pools_display(int offset, int flags)
{
zt_elist_t * tmp;
zt_mem_pool * pool;
printf(BLANK "Pools { \n", INDENT(offset));
zt_elist_for_each(&pools, tmp) {
pool = zt_elist_data(tmp, zt_mem_pool, pool_list);
zt_mem_pool_display(offset + 1, pool, flags);
}
printf(BLANK "}\n", INDENT(offset));
}
static void
zt_mem_release(void * data UNUSED)
{
zt_elist_t * tmp;
zt_elist_t * tmp2;
zt_mem_pool * pool;
zt_elist_for_each_safe(&pools, tmp, tmp2) {
pool = zt_elist_data(tmp, zt_mem_pool, pool_list);
zt_mem_pool_destroy(&pool);
}
}
void
zt_mem_pool_group_display(int offset, zt_mem_pool_group *group, int flags)
{
size_t len;
size_t i;
len = group->npools;
printf(BLANK "Group {\n", INDENT(offset));
for (i = 0; i < len; i++) {
zt_mem_pool_display(offset + 1, group->pools[i], flags);
}
printf(BLANK "}\n", INDENT(offset));
}
zt_mem_pool *
zt_mem_pool_get(char *name)
{
size_t nlen;
zt_elist_t * tmp;
if (!name) {
return 0;
}
nlen = strlen(name);
zt_elist_for_each(&pools, tmp) {
zt_mem_pool * pool;
size_t olen;
pool = zt_elist_data(tmp, zt_mem_pool, pool_list);
olen = strlen(pool->name);
if (olen == nlen && (strncmp(name, pool->name, nlen) == 0)) {
return pool;
}
}
return 0;
}
zt_mem_pool_group *
zt_mem_pool_group_init(zt_mem_pool_desc *group, size_t len)
{
zt_mem_pool_group * ngroup;
size_t i;
if ((ngroup = zt_calloc(zt_mem_pool_group, 1)) == NULL) {
return 0;
}
if ((ngroup->pools = zt_calloc(zt_mem_pool *, len)) == NULL) {
return 0;
}
zt_elist_reset(&ngroup->group_list);
ngroup->npools = len;
for (i = 0; i < len && group[i].name; i++) {
ngroup->pools[i] = zt_mem_pool_init(group[i].name,
group[i].elts,
group[i].size,
group[i].release_test,
group[i].cb_data,
group[i].flags);
if (!ngroup->pools[i]) {
while (--i) {
zt_mem_pool_destroy(&ngroup->pools[i]);
}
return 0;
}
}
return ngroup;
}
void *
zt_mem_pool_group_alloc(zt_mem_pool_group *group, size_t size)
{
size_t len;
size_t i;
len = group->npools;
for (i = 0; i < len; i++) {
if (size <= group->pools[i]->elt_size) {
return zt_mem_pool_alloc(group->pools[i]);
}
}
zt_assert(0);
return NULL; /* never reached if exceptions are enabled */
}
int
zt_mem_pool_group_destroy(zt_mem_pool_group * group)
{
size_t len;
size_t i;
int ret = 0;
len = group->npools;
for (i = 0; i < len; i++) {
if (zt_mem_pool_destroy(&group->pools[i]) != 0) {
ret = -1;
}
}
zt_free(group->pools);
zt_free(group);
return ret;
}
zt_mem_set *
zt_mem_set_init(char *name)
{
zt_mem_set * set;
if ((set = GLOBAL_zmt.alloc(sizeof(zt_mem_set))) == 0) {
return NULL;
}
zt_elist_reset(&set->set_list);
zt_elist_reset(&set->elt_list);
set->name = zt_mem_strdup(name ? name : "*unknown*");
return set;
}
int
zt_mem_set_add(zt_mem_set *set UNUSED, void *d UNUSED)
{
/* struct zt_mem_set_elt * elt; */
/* alloc a new elt wrapper
* assign d to the data element
* return true
*/
return -1;
}
int
zt_mem_set_release(zt_mem_set *set UNUSED)
{
/*
* release the elt and release the wrapper
*/
return 0;
}
/* static functions */
static char *
zt_mem_strdup(char *str)
{
char * tmp = "*unknown*";
if (str) {
size_t len = strlen(str);
if((tmp = GLOBAL_zmt.alloc(len + 1 * sizeof(char))) == NULL) {
return NULL;
}
memcpy(tmp, str, len);
tmp[len] = '\0';
}
return tmp;
}
static int
zt_mem_page_destroy(zt_mem_page *page)
{
zt_mem_elt * elt;
unsigned long i;
size_t size;
if (page->num_free_elts < page->parent_pool->elts_per_page) {
printf("error: %s called when elements are still in use!\n", __FUNCTION__);
return 1;
}
page->parent_pool->npages--;
page->parent_pool->nfree_pages--;
size = sizeof(zt_mem_elt) + page->parent_pool->elt_size;
elt = (zt_mem_elt *)page->data;
/* remove the elements from the free element list */
for (i = 0; i < page->num_free_elts; i++) {
if (zt_elist_empty(&elt->free_elt_list) == 0) {
zt_elist_remove(&elt->free_elt_list);
}
elt = (zt_mem_elt *)((unsigned long)elt + size);
}
/* remove the page from the page list */
if (zt_elist_empty(&page->page_list) == 0) {
zt_elist_remove(&page->page_list);
}
GLOBAL_zmt.dealloc(page);
return 0;
}
static zt_mem_page *
zt_mem_page_alloc(zt_mem_pool *pool)
{
zt_mem_page * page;
zt_mem_elt * head;
zt_mem_elt * elt;
size_t size;
size_t i;
size_t epp;
size = sizeof(zt_mem_elt) + pool->elt_size;
/* sizeof(zt_mem_page) + (pool->elts_per_page * size)) */
if ((page = GLOBAL_zmt.alloc(pool->page_size)) == 0) {
return 0;
}
page->num_free_elts = 0;
page->parent_pool = pool;
zt_elist_reset(&page->page_list);
/* pointer to the first element */
head = (zt_mem_elt *)page->data;
/* add the first element to the free list*/
zt_elist_add_tail(&pool->free_elt_list, &head->free_elt_list);
head->parent_page = page;
page->num_free_elts++;
epp = pool->elts_per_page;
elt = head;
for (i = 1; i < epp; i++) {
elt = (zt_mem_elt *)((unsigned long)elt + size);
zt_elist_reset(&elt->free_elt_list);
elt->parent_page = page;
zt_elist_add_tail(&pool->free_elt_list, &elt->free_elt_list);
page->num_free_elts++;
}
pool->npages++;
pool->nfree_pages++;
return page;
}
static void
zt_mem_elt_list_display(int offset, zt_elist_t *head)
{
zt_elist_t * tmp;
zt_mem_elt * elt;
int i;
i = 0;
zt_elist_for_each(head, tmp) {
elt = zt_elist_data(tmp, zt_mem_elt, free_elt_list);
if (i) {
printf("\n");
}
printf(BLANK "elt: %p parent_page: %p data: %p", INDENT(offset), (void *)elt, (void *)elt->parent_page, (void *)elt->data);
i = 1;
}
}
static void
zt_mem_page_display(int offset, zt_mem_page *page)
{
printf(BLANK "page: %p {\n", INDENT(offset), (void *)page);
printf(BLANK "num_free_elts: %ld\n", INDENT(offset + 1), page->num_free_elts);
printf(BLANK "parent pool: %p\n", INDENT(offset + 1), (void *)page->parent_pool);
printf(BLANK "}\n", INDENT(offset));
}
static int
zt_default_release_test(size_t req_elts UNUSED, size_t free_elts UNUSED, size_t used_elts UNUSED, int flags, void *cb_data UNUSED)
{
if (flags & POOL_NEVER_FREE) {
return 0;
}
return 1;
}
|
128 | ./libzt/src/zt_unit.c | #include <string.h>
#define ZT_WITH_UNIT
#include "zt.h"
#include "zt_internal.h"
#define yaml_dict(name, offt) \
printf(BLANK "%s:\n", INDENT_TO(offt, 2, 0), name)
#define yaml_list_elt(value, fmt, offt) \
printf(BLANK "- " fmt "\n", INDENT_TO(offt, 2, 0), value)
#define yaml_value(name, offt_1, value_fmt, value) \
do { \
int offt; \
offt = printf(BLANK "%s", INDENT_TO(offt_1, 2, 0), name); \
printf(BLANK ": " value_fmt "\n", INDENT_TO(30, 2, offt), value); \
} while (0)
int zt_unit_printf(char **strp, const char *fmt, ...) {
va_list ap;
int result;
va_start(ap, fmt);
result = vasprintf(strp, fmt, ap);
va_end(ap);
return result;
}
void
zt_unit_test_add_exception(struct zt_unit_test *test) {
test->exceptions++;
}
void
zt_unit_test_add_assertion(struct zt_unit_test *test)
{
test->assertions++;
}
struct zt_unit *
zt_unit_init(void)
{
struct zt_unit * unit = zt_calloc(struct zt_unit, 1);
zt_elist_reset(&unit->suites);
unit->failures = 0;
unit->successes = 0;
return unit;
}
void
zt_unit_release(struct zt_unit **unit)
{
zt_elist_t * ignore;
zt_elist_t * tmp;
zt_assert(unit);
zt_assert(*unit);
zt_elist_for_each_safe(&(*unit)->suites, tmp, ignore) {
struct zt_unit_suite * tsuite = zt_elist_data(tmp, struct zt_unit_suite, suite);
zt_unit_release_suite(&tsuite);
}
zt_free(*unit);
*unit = NULL;
}
struct zt_unit_suite *
zt_unit_register_suite_(struct zt_unit * unit,
const char * name,
zt_unit_setup_fn setup_fn,
zt_unit_teardown_fn teardown_fn,
void * data,
zt_unit_try_fn try_fn)
{
size_t len;
struct zt_unit_suite * suite = zt_calloc(struct zt_unit_suite, 1);
zt_assert(name != NULL);
len = strlen(name);
suite->name = zt_calloc(char, len + 1);
strncpy(suite->name, name, len);
suite->setup_fn = setup_fn;
suite->try_fn = try_fn;
suite->teardown_fn = teardown_fn;
suite->data = data;
suite->succeeded = 0;
suite->failed = 0;
zt_elist_reset(&suite->tests);
zt_elist_add_tail(&unit->suites, &suite->suite);
return suite;
}
void
zt_unit_release_suite(struct zt_unit_suite **suite)
{
zt_elist_t * ignore;
zt_elist_t * tmp;
zt_assert(suite);
zt_assert(*suite);
zt_assert((*suite)->name);
zt_elist_for_each_safe(&(*suite)->tests, tmp, ignore) {
struct zt_unit_test * ttest = zt_elist_data(tmp, struct zt_unit_test, test);
zt_unit_release_test(&ttest);
}
zt_elist_remove(&(*suite)->suite);
zt_free((*suite)->name);
zt_free(*suite);
*suite = NULL;
}
struct zt_unit_test *
zt_unit_register_test(struct zt_unit_suite * suite,
const char * name,
zt_unit_test_fn test_fn)
{
struct zt_unit_test * test = zt_calloc(struct zt_unit_test, 1);
size_t len;
zt_assert(suite);
zt_assert(name);
len = strlen(name);
test->name = zt_calloc(char, len + 1);
strncpy(test->name, name, len);
test->success = -1;
test->test_fn = test_fn;
test->assertions = 0;
zt_elist_add_tail(&suite->tests, &test->test);
return test;
}
void
zt_unit_release_test(struct zt_unit_test **test)
{
zt_assert(test);
zt_assert(*test);
zt_assert((*test)->name);
zt_elist_remove(&(*test)->test);
zt_free((*test)->name);
if ((*test)->error) {
zt_free((*test)->error);
}
zt_free(*test);
}
int
zt_unit_run(struct zt_unit * unit)
{
zt_elist_t * tmp;
struct zt_unit_suite * unit_suite;
int result = 0;
zt_elist_for_each(&unit->suites, tmp) {
unit_suite = zt_elist_data(tmp, struct zt_unit_suite, suite);
if (zt_unit_run_suite(unit, unit_suite) < 0) {
result = -1;
}
}
return result;
}
int
zt_unit_run_suite(struct zt_unit * unit,
struct zt_unit_suite * suite)
{
zt_elist_t * tmp;
struct zt_unit_test * unit_test;
int result;
/* int len; */
suite->failed = 0;
suite->succeeded = 0;
printf("---\n%s:\n", suite->name);
yaml_dict("Tests", 2);
zt_elist_for_each(&suite->tests, tmp) {
unit_test = zt_elist_data(tmp, struct zt_unit_test, test);
result = zt_unit_run_test(unit, suite, unit_test);
if (result != TRUE) {
suite->failed += 1;
unit->failures += 1;
} else {
unit->successes += 1;
suite->succeeded += 1;
}
}
if (suite->failed != 0) {
yaml_dict("Errors", 2);
zt_elist_for_each(&suite->tests, tmp) {
unit_test = zt_elist_data(tmp, struct zt_unit_test, test);
if (unit_test->success != TRUE) {
yaml_value(unit_test->name, 4, "'%s'", unit_test->error ? unit_test->error : "No Error Text");
}
}
}
return 0;
}
static void
test_passed(struct zt_unit_test *test)
{
zt_assert(test);
test->success = TRUE;
}
int
zt_unit_try_c(struct zt_unit_suite * suite,
struct zt_unit_test * test) {
if (setjmp(test->env) == 0) {
test->test_fn(test, suite->data);
return 1;
}
return 0;
}
int
zt_unit_run_test(struct zt_unit * unit UNUSED,
struct zt_unit_suite * suite,
struct zt_unit_test * test)
{
zt_assert(test);
test->success = FALSE;
yaml_dict(test->name, 4);
if (suite->setup_fn) {
suite->setup_fn(suite->data);
}
if(suite->try_fn(suite, test)) {
test_passed(test);
}
if (suite->teardown_fn) {
suite->teardown_fn(suite->data);
}
yaml_value("assertions", 6, "%ld", test->assertions);
if (test->exceptions) {
yaml_value("unhandled_exceptions", 6, "%ld", test->exceptions);
}
yaml_value("result", 6, "%s", test->success == TRUE ? "success" : "failure");
return test->success;
}
#include <string.h>
char **str_split(char *str, char * delim, int *elts)
{
char * p1;
char **ap;
char **argv;
int argc;
char * tmp;
size_t memsize;
if (str == NULL || delim == NULL) {
return NULL;
}
argc = 1;
p1 = str;
while ((p1 = strpbrk(p1, delim)) != NULL) {
++p1;
argc += 1;
if (p1 == '\0') {
break;
}
}
/* calculate the size of the char *vector then add the string to
* the end of that (includeing null space for the empty vector
* spot and the NUL char
*/
memsize = (sizeof(char *) * (argc + 1)) + (sizeof(char) * (strlen(str) + 1));
argv = (char **)zt_malloc(char, memsize);
memset(argv, '\0', memsize);
tmp = (char *)argv + (sizeof(char *) * (argc + 1));
strncpy(tmp, str, strlen(str));
*elts = argc;
for (ap = argv; (*ap = strsep(&tmp, delim)) != NULL; ) {
if (**ap != '\0') {
++ap;
if (--argc <= 0) {
break;
}
}
}
return argv;
} /* str_split */
void str_split_free(char ***argv)
{
zt_free(*argv);
}
int
zt_unit_run_by_name(struct zt_unit * unit,
char * name)
{
int count;
char **targetv;
struct zt_unit_suite * unit_suite = NULL;
struct zt_unit_test * unit_test = NULL;
zt_elist_t * tmp;
int result = 0;
size_t len;
targetv = str_split(name, ".", &count);
if (count <= 0 || count > 2) {
result = -1;
goto done;
}
len = strlen(targetv[0]);
zt_elist_for_each(&unit->suites, tmp) {
unit_suite = zt_elist_data(tmp, struct zt_unit_suite, suite);
if (len == strlen(unit_suite->name)) {
if (strncmp(unit_suite->name, targetv[0], len) == 0) {
break;
}
}
unit_suite = NULL;
}
if (unit_suite == NULL) {
result = -1;
goto done;
}
if (count == 1) {
result = zt_unit_run_suite(unit, unit_suite);
goto done;
}
len = strlen(targetv[1]);
zt_elist_for_each(&unit_suite->tests, tmp) {
unit_test = zt_elist_data(tmp, struct zt_unit_test, test);
if (len == strlen(unit_test->name)) {
if (strncmp(unit_test->name, targetv[1], len) == 0) {
break;
}
}
unit_test = NULL;
}
if (unit_test == NULL) {
result = -1;
goto done;
}
if (zt_unit_run_test(unit, unit_suite, unit_test) == FALSE) {
unit->failures += 1;
} else {
unit->successes += 1;
}
done:
str_split_free(&targetv);
return result;
} /* zt_unit_run_by_name */
void
zt_unit_list(struct zt_unit *unit)
{
zt_elist_t * tmp;
zt_elist_t * tmp2;
struct zt_unit_suite * unit_suite;
struct zt_unit_test * unit_test;
yaml_dict("Test Suites", 0);
zt_elist_for_each(&unit->suites, tmp) {
unit_suite = zt_elist_data(tmp, struct zt_unit_suite, suite);
yaml_dict(unit_suite->name, 2);
zt_elist_for_each(&unit_suite->tests, tmp2) {
unit_test = zt_elist_data(tmp2, struct zt_unit_test, test);
yaml_list_elt(unit_test->name, "%s", 4);
}
}
}
int
zt_unit_main(struct zt_unit * unit,
int argc,
char * argv[])
{
int i;
int result = 0;
char * msg = "[options] <suite | suite.test> ..."NL
""NL
"Options:"NL
" -h, --help This help text"NL
" -l, --list list suites and test (default disabled)"NL;
for(i=1; i < argc; i++) {
if(strcmp(argv[i], "-h") == 0 ||
strcmp(argv[i], "--help") == 0) {
printf("%s %s", argv[0], msg);
return 0;
} else if(strcmp(argv[i], "-l") == 0 ||
strcmp(argv[i], "--list") == 0) {
zt_unit_list(unit);
return 0;
}
}
if (argc > 1) {
for (i = 1; i < argc; i++) {
if (zt_unit_run_by_name(unit, argv[i]) < 0) {
printf("Suite or Test \"%s\" not found\n", argv[i]);
result = -1;
}
}
} else {
if ((result = zt_unit_run(unit)) < 0) {
return result;
}
}
if (result == 0) {
if (unit->failures > 0) {
result = -1;
}
}
return result;
} /* zt_unit_main */
|
129 | ./libzt/src/zt_table.c | /*
* zt_table.c ZeroTao Tablees
*
* Copyright (C) 2002-2005, Jason L. Shiffer <jshiffer@zerotao.org>. All Rights Reserved.
* See file COPYING for details.
*
* $Id$
*/
#include <errno.h>
#include "zt.h"
#include "zt_internal.h"
#define DEFAULT_BUCKETS 512
static uint8_t
nbits(size_t val)
{
uint8_t nbits;
for (nbits = 1; (val = val >> 1); nbits++) {
;
}
return nbits;
}
unsigned long powers_of_2[] = { 2, 4, 8,
16, 32, 64,
128, 256, 512,
1024, 2048, 4096,
8192, 16384, 32768,
65535, 131072, 262144,
524288, 1048576, 2097152,
4194304, 8388608, 16777216,
33554432, 67108864, 134217728,
268435456, 536870912, 1073741824,
2147483648UL, UINT_MAX };
struct table_node {
void * datum;
size_t datum_len;
void * key;
size_t key_len;
unsigned long hash_key;
struct table_node * next;
};
struct zt_table {
char * name;
zt_table_compare_cb cmp;
zt_table_hash_func_cb func;
void * cdata;
uint8_t nbits;
int flags;
size_t num_buckets;
unsigned int filled;
zt_mem_pool * node_pool;
zt_mem_heap * table_heap;
struct table_node **buckets;
};
#define ZT_DEFAULT_TABLE_POOL "zt.table.pool"
zt_mem_pool *
zt_table_pool_init(long elts)
{
zt_mem_pool * table_mem_pool;
table_mem_pool = zt_mem_pool_init(ZT_DEFAULT_TABLE_POOL, elts, sizeof(zt_table), NULL, NULL, 0);
return table_mem_pool;
}
zt_table *
zt_table_init(char *name, zt_table_hash_func_cb func,
zt_table_compare_cb cmp, size_t hint, int flags,
void *cdata)
{
zt_table * table;
size_t nbuckets = 0;
char tname[1024];
zt_mem_pool * table_mem_pool;
if ( (func == NULL) ||
(cmp == NULL)) {
return NULL;
}
table_mem_pool = zt_mem_pool_get(ZT_DEFAULT_TABLE_POOL);
if (table_mem_pool == NULL) {
table_mem_pool = zt_table_pool_init(2);
}
if ( (table = (zt_table *)zt_mem_pool_alloc(table_mem_pool)) == NULL) {
return NULL;
}
table->flags = flags;
table->cdata = cdata;
if (flags & ZT_TABLE_SIZE_USE_HINT) {
nbuckets = hint;
} else {
int i = 0;
int len = sizeof_array(powers_of_2);
for (i = 0; i < len; i++) {
if (powers_of_2[i] > hint) {
nbuckets = powers_of_2[i];
break;
}
}
}
table->nbits = nbits(nbuckets - 1);
table->table_heap = zt_mem_heap_init(0, nbuckets * sizeof(struct table_node *));
table->buckets = zt_mem_heap_get_data(table->table_heap);
memset(table->buckets, 0, nbuckets * sizeof(struct table_node *));
if (name) {
table->name = zt_strdup(name);
} else {
table->name = zt_strdup("anonymous");
}
snprintf(tname, sizeof_array(tname), "%s (table node pool)", name);
table->node_pool = zt_mem_pool_init(tname, nbuckets,
sizeof(struct table_node), NULL, NULL, 0);
table->num_buckets = nbuckets;
table->cmp = cmp;
table->func = func;
return table;
} /* zt_table_init */
void
zt_table_destroy(zt_table *h)
{
size_t i;
for (i = 0; i < h->num_buckets; i++) {
struct table_node *node = h->buckets[i];
while (node) {
struct table_node *tmp = node->next;
zt_mem_pool_release((void **)&node);
node = tmp;
}
}
if (h->name) {
zt_free(h->name);
}
zt_mem_pool_destroy(&h->node_pool);
zt_mem_heap_destroy(&h->table_heap);
zt_mem_pool_release((void **)&h);
}
int
zt_table_set(zt_table *h, const void *key, size_t key_len, const void *datum, size_t datum_len)
{
unsigned long nkey = h->func(key, key_len, h->cdata);
unsigned long skey = nkey;
struct table_node * node;
struct table_node * nn;
ZT_HASH_SUB32_MASK(nkey, h->nbits);
/* ZT_LOG_XDEBUG("for key %d hash key is: %d", (int)key, nkey); */
nn = h->buckets[nkey];
if (!(h->flags & ZT_TABLE_ALLOW_DUP_KEYS)) {
while (nn) {
if (nn->hash_key == skey) {
if (h->cmp((void *)nn->key, nn->key_len, key, key_len, h->cdata)) {
return 1;
}
}
nn = nn->next;
}
}
node = (struct table_node *)zt_mem_pool_alloc(h->node_pool);
node->next = h->buckets[nkey];
node->hash_key = skey;
h->buckets[nkey] = node;
node->key = (void *)key;
node->key_len = key_len;
node->datum = (void *)datum;
node->datum_len = datum_len;
return 0;
}
void *
zt_table_get(zt_table *h, const void *key, size_t key_len)
{
struct table_node *node;
unsigned long nkey;
unsigned long skey;
nkey = h->func(key, key_len, h->cdata);
skey = nkey;
ZT_HASH_SUB32_MASK(nkey, h->nbits);
node = h->buckets[nkey];
while (node) {
if (node->hash_key == skey) {
if (h->cmp((void *)node->key, node->key_len, key, key_len, h->cdata)) {
return node->datum;
}
}
node = node->next;
}
errno = ENOENT;
return NULL;
}
void *
zt_table_del(zt_table *h, const void *key, size_t key_len)
{
struct table_node * node;
struct table_node * prev;
unsigned long nkey = h->func(key, key_len, h->cdata);
unsigned long skey = nkey;
ZT_HASH_SUB32_MASK(nkey, h->nbits);
prev = node = h->buckets[nkey];
while (node) {
if (node->hash_key == skey) {
if (h->cmp((void *)node->key, node->key_len, key, key_len, h->cdata)) {
void * datum = node->datum;
if (prev == node) {
h->buckets[nkey] = node->next;
} else {
prev->next = node->next;
}
zt_mem_pool_release((void **)&node);
return datum;
}
}
node = node->next;
}
errno = ENOENT;
return NULL;
}
int
zt_table_copy(zt_table *t1, zt_table *t2)
{
unsigned long i;
int any = 0;
for (i = 0; i < t1->num_buckets; i++) {
struct table_node *node = t1->buckets[i];
while (node) {
any = 1;
/* if(!table_get(t2, node->key)) { */
zt_table_set(t2, node->key, node->key_len, node->datum, node->datum_len);
node = node->next;
}
}
return any;
}
int
zt_table_for_each(zt_table *h, zt_table_iterator_cb iterator, void *param)
{
unsigned long i;
int res;
for (i = 0; i < h->num_buckets; i++) {
struct table_node *tn;
tn = h->buckets[i];
while (tn) {
struct table_node *next = tn->next;
if ((res = iterator(tn->key, tn->key_len, tn->datum, tn->datum_len, param)) != 0) {
return res;
}
tn = next;
}
}
return 0;
}
/* common hash functions */
unsigned long
zt_table_hash_int(const void *key, size_t key_len, void *cdata UNUSED)
{
unsigned char * skey = (unsigned char *)key;
unsigned long nkey = zt_hash32_buff(&skey, key_len, ZT_HASH32_INIT);
return nkey;
}
int
zt_table_compare_int(const void *lhs, size_t lhs_len, const void *rhs, size_t rhs_len, void *cdata UNUSED)
{
if (lhs_len == rhs_len) {
if (memcmp(&lhs, &rhs, lhs_len) == 0) {
return 1;
}
}
return 0;
}
unsigned long
zt_table_hash_string(const void *key, size_t key_len UNUSED, void *cdata UNUSED)
{
unsigned char * skey = (unsigned char *)key;
unsigned long nkey = zt_hash32_cstr(skey, ZT_HASH32_INIT);
return nkey;
}
int
zt_table_compare_string(const void *lhs, size_t lhs_len, const void *rhs, size_t rhs_len, void *cdata UNUSED)
{
if(lhs_len == rhs_len) {
if (strncmp((char *)lhs, (char *)rhs, lhs_len) == 0) {
return 1;
}
}
return 0;
}
int
zt_table_compare_string_case(const void *lhs, size_t lhs_len, const void *rhs, size_t rhs_len, void *cdata UNUSED)
{
if (strcasecmp((char *)lhs, (char *)rhs) == 0) {
return 1;
}
return 0;
}
unsigned long
zt_table_hash_buff(const void *key, size_t key_len, void *cdata UNUSED)
{
unsigned char * skey = (unsigned char *)key;
unsigned long nkey = zt_hash32_buff(skey, key_len, ZT_HASH32_INIT);
return nkey;
}
int
zt_table_compare_buff(const void *lhs, size_t lhs_len, const void *rhs, size_t rhs_len, void *cdata UNUSED)
{
if(lhs_len == rhs_len) {
if (strncmp((char *)lhs, (char *)rhs, lhs_len) == 0) {
return 1;
}
}
return 0;
}
|
130 | ./libzt/src/zt_format.c | #include <limits.h>
#include <ctype.h>
#include <float.h>
#include <string.h>
#include "zt.h"
#include "zt_internal.h"
struct zt_fmt_obuf {
char * buf;
char * bp;
size_t size;
};
#define pad(n, c, tlen) \
do { \
ssize_t nn = (n); \
while (nn-- > 0) { \
tlen += put((c), cl); \
} \
} while (0)
char * zt_fmt_flags = "+- 0#";
static size_t cvt_c(int code, void * value,
zt_fmt_put_f put, void * cl,
unsigned char flags[],
ssize_t width, ssize_t precision);
static size_t cvt_d(int code, void * value,
zt_fmt_put_f put, void * cl,
unsigned char flags[],
ssize_t width, ssize_t precision);
static size_t cvt_f(int code, void * value,
zt_fmt_put_f put, void * cl,
unsigned char flags[],
ssize_t width, ssize_t precision);
static size_t cvt_o(int code, void * value,
zt_fmt_put_f put, void * cl,
unsigned char flags[],
ssize_t width, ssize_t precision);
static size_t cvt_p(int code, void * value,
zt_fmt_put_f put, void * cl,
unsigned char flags[],
ssize_t width, ssize_t precision);
static size_t cvt_s(int code, void * value,
zt_fmt_put_f put, void * cl,
unsigned char flags[],
ssize_t width, ssize_t precision);
static size_t cvt_u(int code, void * value,
zt_fmt_put_f put, void * cl,
unsigned char flags[],
ssize_t width, ssize_t precision);
static size_t cvt_x(int code, void * value,
zt_fmt_put_f put, void * cl,
unsigned char flags[],
ssize_t width, ssize_t precision);
static int zt_fmt_outc(int c, void *cl);
static int zt_fmt_insert(int c, void *cl);
static int zt_fmt_append(int c, void *cl);
/* conversion codes define what type is read (va_arg) from the argument list for this formatter
* i int
* u unsigned int
* d double
* p void *
* s char *
* c char
* C unsigned char
* */
struct _format_control {
zt_fmt_ty f;
char t;
} cvt[256] = {
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, /* 0 - 7 */
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, /* 8 - 15 */
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, /* 16 - 23 */
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, /* 24 - 31 */
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, /* 32 - 39 */
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, /* 40 - 47 */
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, /* 48 - 55 */
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, /* 56 - 63 */
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, /* 64 - 71 */
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, /* 72 - 79 */
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, /* 80 - 87 */
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, /* 88 - 95 */
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { cvt_c, 'i' }, { cvt_d, 'i' }, { cvt_f, 'd' }, { cvt_f, 'd' }, { cvt_f, 'd' }, /* 96 - 103 */
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { cvt_o, 'u' }, /* 104 - 111 */
{ cvt_p, 'p' }, { 0, 0 }, { 0, 0 }, { cvt_s, 's' }, { 0, 0 }, { cvt_u, 'u' }, { 0, 0 }, { 0, 0 }, /* 112 - 119 */
{ cvt_x, 'u' }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, /* 120 - 127 */
};
/* exported functions */
size_t
zt_fmt_format(zt_fmt_put_f put, void *cl,
const char *fmt, ...)
{
va_list ap;
size_t tlen = 0;
va_start(ap, fmt);
tlen = zt_fmt_vformat(put, cl, fmt, ap);
va_end(ap);
return tlen;
}
size_t
zt_fmt_printf(const char *fmt, ...)
{
size_t tlen = 0;
va_list ap;
va_start(ap, fmt);
tlen = zt_fmt_vformat(zt_fmt_outc, stdout, fmt, ap);
va_end(ap);
return tlen;
}
size_t
zt_fmt_fprintf(FILE *stream, const char *fmt, ...)
{
size_t tlen = 0;
va_list ap;
va_start(ap, fmt);
tlen = zt_fmt_vformat(zt_fmt_outc, stream, fmt, ap);
va_end(ap);
return tlen;
}
size_t
zt_fmt_sprintf(char *buf, size_t size, const char *fmt, ...)
{
size_t tlen = 0;
va_list ap;
va_start(ap, fmt);
tlen = zt_fmt_vsprintf(buf, size, fmt, ap);
va_end(ap);
return tlen;
}
size_t
zt_fmt_vsprintf(char *buf, size_t size, const char *fmt, va_list ap)
{
struct zt_fmt_obuf cl;
zt_assert(buf);
zt_assert(size > 0);
zt_assert(fmt);
cl.buf = cl.bp = buf;
cl.size = size;
zt_fmt_vformat(zt_fmt_insert, &cl, fmt, ap);
zt_fmt_insert(0, &cl);
return cl.bp - cl.buf - 1;
}
char * zt_fmt_strprintf(const char *fmt, ...)
{
char * str;
va_list ap;
zt_assert(fmt);
va_start(ap, fmt);
str = zt_fmt_vstrprintf(fmt, ap);
va_end(ap);
return str;
}
char * zt_fmt_vstrprintf(const char *fmt, va_list ap)
{
struct zt_fmt_obuf cl;
zt_assert(fmt);
cl.size = 256;
cl.buf = cl.bp = zt_malloc(char, cl.size);
zt_fmt_vformat(zt_fmt_append, &cl, fmt, ap);
zt_fmt_append(0, &cl);
return zt_realloc(char, cl.buf, cl.bp - cl.buf);
}
size_t zt_fmt_vformat(zt_fmt_put_f put, void *cl,
const char *fmt, va_list ap)
{
size_t tlen = 0;
zt_assert(put);
zt_assert(fmt);
while (*fmt) {
/* both % and ~ are control chars */
if ((*fmt != '%' && *fmt != '~') ||
(++fmt && (*fmt == '%' || *fmt == '~'))) {
tlen += put((unsigned char)*fmt++, cl);
} else {
unsigned char c, flags[256];
ssize_t width = INT_MIN;
ssize_t precision = INT_MIN;
memset(flags, '\0', sizeof(flags));
if (zt_fmt_flags) {
unsigned char c = *fmt;
for (; c && strchr(zt_fmt_flags, c); c = *++fmt) {
zt_assert(flags[c] < 255);
flags[c]++;
}
}
if (*fmt == '*' || isdigit(*fmt)) {
int n;
if (*fmt == '*') {
n = va_arg(ap, int);
zt_assert(n != INT_MIN);
fmt++;
} else {
for (n = 0; isdigit(*fmt); fmt++) {
int d = *fmt - '0';
zt_assert(n <= (INT_MAX - d) / 10);
n = 10 * n + d;
}
}
width = n;
}
if (*fmt == '.' &&
(*++fmt == '*' || isdigit(*fmt))) {
int n;
if (*fmt == '*') {
n = va_arg(ap, int);
zt_assert(n != INT_MIN);
fmt++;
} else {
for (n = 0; isdigit(*fmt); fmt++) {
int d = *fmt - '0';
zt_assert(n <= (INT_MAX - d) / 10);
n = 10 * n + d;
}
}
precision = n;
}
c = *fmt++;
zt_assert(cvt[c].f && cvt[c].t);
{
union {
int i;
unsigned int u;
double d;
void * p;
char * s;
} value;
void * vp = NULL;
switch (cvt[c].t) {
case 'i':
value.i = va_arg(ap, int);
vp = &value.i;
break;
case 'u':
value.u = va_arg(ap, unsigned int);
vp = &value.u;
break;
case 'd':
value.d = va_arg(ap, double);
vp = &value.d;
break;
case 'p':
value.p = va_arg(ap, void *);
vp = &value.p;
break;
case 's':
value.s = va_arg(ap, char *);
vp = &value.s;
break;
default:
break;
}
tlen += (*cvt[c].f)(c, vp, put, cl, flags, width, precision);
}
}
}
return tlen;
} /* zt_fmt_vformat */
#define NORMALIZE_WIDTH(width, flags) \
if (width == INT_MIN) { \
width = 0; \
} else if (width < 0) { \
flags['-'] = 1; \
width = -width; \
}
#define NORMALIZE_WIDTH_AND_FLAGS(width, flags, precision) \
NORMALIZE_WIDTH(width, flags) \
if (precision >= 0) { \
flags['0'] = 0; \
}
#define EMIT_STR(str, len, cl, tlen) \
do { \
size_t i; \
for (i = 0; i < len; i++) { \
tlen += put((unsigned char)*str++, cl); \
} \
} while (0)
size_t
zt_fmt_puts(const char *str, size_t len,
zt_fmt_put_f put, void *cl,
unsigned char flags[256],
ssize_t width, ssize_t precision)
{
size_t tlen = 0;
zt_assert(str);
zt_assert(flags);
NORMALIZE_WIDTH_AND_FLAGS(width, flags, precision);
if (precision >= 0 &&
precision < (ssize_t)len) {
len = precision;
}
if (!flags['-']) {
pad(width - len, ' ', tlen);
}
EMIT_STR(str, len, cl, tlen);
return tlen;
}
size_t
zt_fmt_putd(const char *str, size_t len,
zt_fmt_put_f put, void *cl,
unsigned char flags[256],
ssize_t width, ssize_t precision)
{
int sign;
size_t tlen = 0;
ssize_t n;
zt_assert(str);
zt_assert(flags);
NORMALIZE_WIDTH_AND_FLAGS(width, flags, precision);
if (len > 0 &&
(*str == '-' ||
*str == '+')) {
sign = *str++;
len--;
} else if (flags[' ']) {
sign = ' ';
} else {
sign = 0;
}
/* justify */
if (precision < 0) {
precision = 1;
}
if ((ssize_t)len < precision) {
n = precision;
} else if (precision == 0 &&
len == 1 &&
str[0] == '0') {
n = 0;
} else {
n = len;
}
if (sign) {
n++;
}
if (flags['-']) {
if (sign) {
tlen += put(sign, cl);
}
} else if (flags['0']) {
if (sign) {
tlen += put(sign, cl);
}
pad(width - n, '0', tlen);
} else {
if (sign) {
tlen += put(sign, cl);
}
pad(width - n, ' ', tlen);
}
pad(precision - len, '0', tlen);
EMIT_STR(str, len, cl, tlen);
if (flags['-']) {
pad(width - n, ' ', tlen);
}
return tlen;
} /* zt_fmt_putd */
zt_fmt_ty
zt_fmt_register(int code, zt_fmt_ty newcvt, unsigned char type)
{
zt_fmt_ty old;
zt_assert(0 < code && code < (int)sizeof_array(cvt));
old = cvt[code].f;
cvt[code].t = type;
cvt[code].f = newcvt;
return old;
}
/* local funcs */
int
zt_fmt_outc(int c, void *cl)
{
FILE *f = cl;
return putc(c, f);
}
static size_t
cvt_c(int code UNUSED, void * value,
zt_fmt_put_f put, void * cl,
unsigned char flags[],
ssize_t width, ssize_t precision UNUSED)
{
size_t tlen = 0;
char c = *(unsigned int *)value;
NORMALIZE_WIDTH(width, flags);
if (!flags['-']) {
pad(width - 1, ' ', tlen);
}
tlen += put(c, cl);
if (flags['-']) {
pad(width - 1, ' ', tlen);
}
return tlen;
}
static size_t
cvt_d(int code UNUSED, void * value,
zt_fmt_put_f put, void * cl,
unsigned char flags[],
ssize_t width, ssize_t precision)
{
int val = *(int *)value;
unsigned int m;
char buf[43];
char * p = buf + sizeof(buf);
if (val == INT_MAX) {
m = INT_MAX + 1U; /* -1 */
} else if (val < 0) {
m = -val;
} else {
m = val;
}
do {
*--p = m % 10 + '0';
} while ((m /= 10) > 0);
if (val < 0) {
*--p = '-';
}
return zt_fmt_putd(p, (buf + sizeof(buf)) - p, put, cl,
flags, width, precision);
}
static size_t
cvt_f(int code, void * value,
zt_fmt_put_f put, void * cl,
unsigned char flags[],
ssize_t width, ssize_t precision)
{
char buf[DBL_MAX_10_EXP + 1 + 1 + 99 + 1];
static char fmt[] = "%.dd?";
if (precision < 0) {
precision = 6;
}
if (code == 'g' && precision == 0) {
precision = 1;
}
zt_assert(precision <= 99);
fmt[4] = code;
fmt[3] = precision % 10 + '0';
fmt[2] = (precision / 10) % 10 + '0';
sprintf(buf, fmt, *(double *)value);
return zt_fmt_putd(buf, strlen(buf), put, cl,
flags, width, precision);
}
static size_t
cvt_o(int code UNUSED, void * value,
zt_fmt_put_f put, void * cl,
unsigned char flags[],
ssize_t width, ssize_t precision)
{
unsigned int m = *(unsigned int *)value;
char buf[43];
char * p = buf + sizeof(buf);
do {
*--p = (m & 0x7) + '0';
} while ((m >>= 3) != 0);
return zt_fmt_putd(p, (buf + sizeof(buf)) - p,
put, cl, flags, width, precision);
}
static size_t
cvt_p(int code UNUSED, void * value,
zt_fmt_put_f put, void * cl,
unsigned char flags[],
ssize_t width, ssize_t precision)
{
size_t m = (size_t)*(void **)value;
char buf[64];
char * p = buf + sizeof(buf);
precision = INT_MIN;
do {
*--p = "0123456789abcdef"[m & 0xf];
} while ((m >>= 4) != 0);
return zt_fmt_putd(p, (buf + sizeof(buf)) - p,
put, cl, flags, width, precision);
}
static size_t
cvt_s(int code UNUSED, void * value,
zt_fmt_put_f put, void * cl,
unsigned char flags[],
ssize_t width, ssize_t precision)
{
size_t lstr;
char * str = *(char **) value;
zt_assert(str != NULL);
if (flags['#']) {
if (width != INT_MIN) {
ssize_t i = width;
if (i < 0) {
i = -i;
}
lstr = strlen(str);
zt_assert(lstr < INT_MAX);
if (i < (int)lstr) {
str = str + i;
}
width = INT_MIN;
}
}
return zt_fmt_puts(str, strlen(str), put, cl, flags, width, precision);
}
static size_t
cvt_u(int code UNUSED, void * value,
zt_fmt_put_f put, void * cl,
unsigned char flags[],
ssize_t width, ssize_t precision)
{
unsigned int m = *(unsigned int *)value;
char buf[43];
char * p = buf + sizeof(buf);
do {
*--p = m % 10 + '0';
} while ((m /= 10) > 0);
return zt_fmt_putd(p, (buf + sizeof(buf)) - p,
put, cl, flags, width, precision);
}
static size_t
cvt_x(int code UNUSED, void * value,
zt_fmt_put_f put, void * cl,
unsigned char flags[],
ssize_t width, ssize_t precision)
{
unsigned int m = *(unsigned int *)value;
char buf[43];
char * p = buf + sizeof(buf);
do {
*--p = "0123456789abcdef"[m & 0xf];
} while ((m >>= 4) != 0);
return zt_fmt_putd(p, (buf + sizeof(buf)) - p,
put, cl, flags, width, precision);
}
static int
zt_fmt_insert(int c, void *cl)
{
struct zt_fmt_obuf * p = cl;
zt_assert(p->bp < p->buf + p->size);
/* if (p->bp >= p->buf + p->size) { */
/* TRY_THROW(zt_exception.format.overflow); */
/* } */
*p->bp++ = c;
return c;
}
static int
zt_fmt_append(int c, void *cl)
{
struct zt_fmt_obuf * p = (struct zt_fmt_obuf *)cl;
if (p->bp >= p->buf + p->size) {
p->buf = zt_realloc(char, p->buf, p->size * 2);
p->bp = p->buf + p->size;
p->size *= 2;
}
*p->bp++ = c;
return c;
}
|
131 | ./libzt/src/zt_opts.c | /*
* opts.c option parsing routines
*
* Copyright (C) 2000-2011, Jason L. Shiffer <jshiffer@zerotao.com>. All Rights Reserved.
* See file COPYING for details.
*
* $Id: opts.c,v 1.7 2003/11/26 17:37:16 jshiffer Exp $
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
#ifdef HAVE_STRING_H
# include <string.h> /* memset, strdup */
#endif
#ifdef HAVE_LIBGEN_H
# include <libgen.h> /* basename */
#endif
#ifdef HAVE_INTTYPES_H
# include <inttypes.h>
#endif
/* #include <getopt.h> [> getopt, getopt_long <] */
#include "zt.h"
#include "zt_opts.h"
char *
zt_opt_error_str(int code, char * fmt, ...) {
char * ret;
va_list ap;
va_start(ap, fmt);
ret = zt_opt_verror_str(code, fmt, ap);
va_end(ap);
return ret;
}
char *
zt_opt_verror_str(int code, char * fmt, va_list ap) {
char * msg = NULL;
char * user_message = NULL;
char * final = NULL;
asprintf(&msg, "error: { code: %d, string: \"%s", code, code ? strerror(code) : "");
if (fmt) {
vasprintf(&user_message, fmt, ap);
}
asprintf(&final, "%s: %s\" }", msg, user_message);
zt_free(user_message);
zt_free(msg);
return final;
}
int
zt_opt_verror_default(int code, char * fmt, va_list ap) {
char * msg = NULL;
if (!code && !fmt) {
/* no code or format equates to calling exit */
return -1;
}
msg = zt_opt_verror_str(code, fmt, ap);
fprintf(stderr, "%s\n", msg);
zt_free(msg);
return code;
}
int
zt_opt_error_default(int code, char * fmt, ...) {
int ret;
va_list ap;
va_start(ap, fmt);
ret = zt_opt_verror_default(code, fmt, ap);
va_end(ap);
return ret;
}
char *
zt_opt_get_value(int argn, int defn, char ** argv, zt_opt_def_t * def, int *args_consumed, zt_opt_error error) {
char * p = argv[argn];
char * pp = NULL;
char * result = NULL;
char * lopt = def[defn].lopt;
*args_consumed = 0;
/* skip past any leading '-' */
while(*p == '-') { p++; }
pp = p;
do {
if (*pp == '=') {
result = ++pp;
break;
}
} while (*pp++);
if (!result) {
pp = p;
/* there was no '=' embedded
* try matching the long opt name
*/
if (strcmp(lopt, pp) == 0) {
result = argv[argn + 1]; /* default to the next option */
*args_consumed = 1;
} else {
/* short opt */
pp++;
if(*pp) {
result = pp;
} else {
result = argv[argn + 1];
*args_consumed = 1;
}
}
}
if (!result) {
error(EINVAL, "while processing arg '%s'", argv[argn]);
}
return result;
}
int
zt_opt_null(int argn, int defn, int * argc, char ** argv, zt_opt_def_t * def, zt_opt_error error) {
return 0;
}
#ifdef HAVE_INTTYPES_H
int
zt_opt_intmax(int argn, int defn, int * argc, char ** argv, zt_opt_def_t * def, zt_opt_error error) {
intmax_t result;
char * end = NULL;
int args_consumed = 0;
char * arg = zt_opt_get_value(argn, defn, argv, def, &args_consumed, error);
errno = 0;
result = strtoimax(arg, &end, 0);
if (errno) {
/* check errno */
error(errno, "invalid number '%s'", arg);
}
if (end && *end) {
/* invalid character */
error(EINVAL, "'%s' is not a number", arg);
}
if (def[defn].cb_data) {
*(intmax_t *)def[defn].cb_data = result;
}
return args_consumed;
}
#endif /* HAVE_INTTYPES_H */
int
zt_opt_long(int argn, int defn, int * argc, char ** argv, zt_opt_def_t * def, zt_opt_error error) {
long result;
char * end = NULL;
int args_consumed = 0;
char * arg = zt_opt_get_value(argn, defn, argv, def, &args_consumed, error);
errno = 0;
result = strtol(arg, &end, 0);
if (errno) {
/* check errno */
error(errno, "invalid number '%s'", arg);
}
if (end && *end) {
/* invalid character */
error(EINVAL, "'%s' is not a number", arg);
}
if (def[defn].cb_data) {
*(long *)def[defn].cb_data = result;
}
return args_consumed;
}
int
zt_opt_bool_int(int argn, int defn, int * argc, char ** argv, zt_opt_def_t * def, zt_opt_error error) {
int result;
size_t len;
int args_consumed = 0;
char * arg = zt_opt_get_value(argn, defn, argv, def, &args_consumed, error);
len = strlen(arg);
if (len == 1) {
switch (*arg) {
case 't':
case 'T':
case 'y':
case 'Y':
result = 1;
break;
case 'f':
case 'F':
case 'n':
case 'N':
result = 0;
break;
default:
error(EINVAL, "'%s' is not a boolean expression", argv[argn]);
return 0;
}
} else {
if (strcasecmp(arg, "true") == 0 ||
strcasecmp(arg, "yes") == 0) {
result = 1;
} else if (strcasecmp(arg, "false") == 0 ||
strcasecmp(arg, "no") == 0) {
result = 0;
} else {
error(EINVAL, "'%s' is not a boolean expression", argv[argn]);
return 0;
}
}
if (def[defn].cb_data) {
*(int *)def[defn].cb_data = result;
}
return args_consumed;
} /* zt_opt_bool_int */
int
zt_opt_flag_int(int argn, int defn, int * argc, char ** argv, zt_opt_def_t * def, zt_opt_error error) {
if (def[defn].cb_data) {
*(int *)def[defn].cb_data += 1;
}
return 0;
}
int
zt_opt_string(int argn, int defn, int * argc, char ** argv, zt_opt_def_t * def, zt_opt_error error) {
int args_consumed = 0;
char * arg = zt_opt_get_value(argn, defn, argv, def, &args_consumed, error);
if (arg) {
*(char **)def[defn].cb_data = (void *)strdup(arg);
}
return args_consumed;
}
static int
_zt_opt_help_stdout_printer(zt_opt_def_t * def) {
char sopt = def->sopt;
char * lopt = def->lopt;
if (sopt != ZT_OPT_NSO || lopt != ZT_OPT_NLO) {
int depth = 0;
depth = printf(" %c%c%c %s%s",
sopt != ZT_OPT_NSO ? '-' : ' ',
sopt != ZT_OPT_NSO ? sopt : ' ',
sopt != ZT_OPT_NSO && lopt != ZT_OPT_NLO ? ',' : ' ',
lopt != ZT_OPT_NLO ? "--" : " ",
lopt != ZT_OPT_NLO ? lopt : "");
printf(BLANK "%s\n", INDENT_TO(25, 1, depth), def->help);
} else {
return -1;
}
return 0;
}
int
zt_opt_help_stdout(int argn, int defn, int * argc, char ** argv, zt_opt_def_t * def, zt_opt_error error) {
int i;
char * help = def[defn].cb_data;
printf("Usage: %s %s\nOptions:\n", argv[0], help ? help : "");
for (i = 0; def[i].cb; i++) {
if (_zt_opt_help_stdout_printer(&def[i]) < 0) {
error(0, "Programmer Error: must have a short or long opt at least", NULL);
return -1;
}
}
error(0, NULL);
return 0;
}
int
zt_opt_usage(const char * name, const char * help, zt_opt_def_t * opts) {
int i;
printf("Usage: %s %s\nOptions:\n", name, help ? help : "");
for (i = 0; opts[i].cb != NULL; i++) {
if (_zt_opt_help_stdout_printer(&opts[i]) < 0) {
return -1;
}
}
return 0;
}
void
zt_opt_validate_default(zt_opt_def_t * args, zt_opt_error error) {
int i;
int x;
for (i = 0; args[i].cb; i++) {
if (args[i].sopt == ZT_OPT_NSO && args[i].lopt == ZT_OPT_NLO) {
error(EINVAL, "Invalid argdef initialization #%d (must include at least one of short opt or long opt)", i);
}
if (!args[i].help) {
error(EINVAL, "Invalid argdef initialization #%d (must include help definition)", i);
}
if (args[i].sopt != ZT_OPT_NSO &&
((args[i].sopt < '0' || args[i].sopt > '9') && /* 0x30-0x39 */
(args[i].sopt < 'A' || args[i].sopt > 'Z') && /* 0x41-0x5A */
(args[i].sopt < 'a' || args[i].sopt > 'z'))) { /* 0x61-0x7A */
error(EINVAL, "Invalid short option definition #%d (char must be [0-9A-Za-z] not '0x%x')", i, args[i].sopt);
}
/* slow and does extra work but functional */
for (x = 0; args[x].cb; x++) {
if (x == i) {
continue;
}
if (args[x].sopt != ZT_OPT_NSO && args[x].sopt == args[i].sopt) {
error(EINVAL, "Duplicate short options: #%d and #%d", i, x);
}
if (args[x].lopt != ZT_OPT_NLO && args[i].lopt != ZT_OPT_NLO &&
(strcmp(args[x].lopt, args[i].lopt) == 0)) {
error(EINVAL, "Duplicate long options: #%d and #%d", i, x);
}
}
}
}
static int
_zt_opt_error_wrapper(int code, char * fmt, ...) {
int ret;
va_list ap;
va_start(ap, fmt);
ret = zt_opt_verror_default(code, fmt, ap);
va_end(ap);
if (ret != 0) {
exit(ret);
}
return ret;
}
int
zt_opt_process_args(int * argc, char ** argv, zt_opt_def_t * args, zt_opt_validate validate, zt_opt_error error) {
int i;
error = error ? error : _zt_opt_error_wrapper;
validate = validate ? validate : zt_opt_validate_default;
validate(args, error);
for (i = 1; i < *argc; i++) {
if (argv[i][0] == '-') {
unsigned int x;
size_t len = 0;
char * p = &argv[i][1];
int combined_opt = 0;
int found = 0;
int long_opt = 0;
if (*p == '-') { /* long opt */
long_opt = 1;
++p;
for (len = 0; p[len] != '\0' && p[len] != '='; len++) {
;
}
if (p[len] == '=') {
combined_opt = 1;
}
}
AGAIN:
for (x = 0; args[x].cb; x++) {
if ((len == 0 && args[x].sopt != ZT_OPT_NSO && *p == args[x].sopt) || /* short opt */
/* long opt */
(args[x].lopt != ZT_OPT_NLO && strlen(args[x].lopt) == len &&
strncmp(p, args[x].lopt, len) == 0)) {
int consumed = 0;
found = 1;
if ((consumed = args[x].cb(i, x, argc, argv, args, error)) < 0) {
/* error */
return consumed;
}
if (!combined_opt) {
i += consumed;
}
if(!consumed && !long_opt && *(++p)) {
/* if we did not consume extra args AND
* we are a short option AND
* there are more short options to consume
*/
goto AGAIN;
}
break;
}
}
if (!found) {
error(EINVAL, "'%.*s'", len ? len : 1, p);
}
} else {
break;
}
}
*argc = i;
return 0;
} /* zt_opt_process_args */
|
132 | ./libzt/src/zt_cfg/cfg_ini.c | /*
* Interface to ini style config files
*
* Copyright (C) 2000-2002, 2004, Jason L. Shiffer <jshiffer@zerotao.com>. All Rights Reserved.
* See file COPYING for details.
*
* $Id: ini.c,v 1.2 2003/06/09 13:42:12 jshiffer Exp $
*
*/
#include "cfg_private.h"
#include <stdio.h>
#include <string.h>
#include "../zt_internal.h"
#include "../zt_log.h"
#include "../zt_assert.h"
#define BUFMAX 1024
static char* valid_variable_name = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
static int parse_cfg(zt_cfg_ty* cfg);
static int parse_file(zt_cfg_ty* cfg, FILE* file);
static int parse_line(FILE* file, struct cfg_bvv_ty* bvv);
static int parse_block(FILE* file, struct cfg_bvv_ty* bvv);
/* component data */
static zt_cfg_vtbl_ty vtbl = {
sizeof(zt_cfg_ty),
0,
zt_cfg_priv_destructor,
zt_cfg_priv_get,
zt_cfg_priv_set
};
zt_cfg_ty *
zt_cfg_ini(char *file, int opts )
{
zt_cfg_ty *cfg = zt_cfg_new(&vtbl);
cfg->filename = strdup(file);
cfg->opts = opts;
if (parse_cfg(cfg) < 0) {
free(cfg->filename);
free(cfg);
cfg = NULL;
}
return cfg;
}
int parse_cfg(zt_cfg_ty* cfg)
{
int ret = 0;
FILE * file;
if ((file = fopen(cfg->filename, "r")) == NULL) {
return -1;
}
ret = parse_file(cfg, file);
fclose(file);
return ret;
}
static int parse_block(FILE* file, struct cfg_bvv_ty* bvv)
{
char buff[BUFMAX];
int c;
int i = 0;
memset(buff, '\0', BUFMAX);
zt_assert(file);
zt_assert(bvv);
while (((c = fgetc(file)) != EOF) && (i < BUFMAX)) {
if (c == ']') {
break;
}
buff[i] = (char)c;
i++;
}
if (i >= BUFMAX) {
/* errno = EOVERFLOW; */
return -1;
}
/* Otherwize we have a block name in buff */
bvv->block = strdup(buff);
if (bvv->block == NULL) {
return -1;
}
return 0;
}
static int parse_line(FILE* file, struct cfg_bvv_ty* bvv)
{
char buff[BUFMAX];
size_t end;
char * var;
char * val;
char * tok;
size_t len;
size_t vallen;
size_t i;
int c;
memset(buff, '\0', BUFMAX);
if (fgets(buff, BUFMAX, file) == NULL) {
return 0;
}
val = strstr(buff, "=");
if (!val) {
/* errno = EPROTO; */
return 0;
}
len = strlen(buff) - 1;
if (buff[len] == '\n') {
buff[len] = '\0'; /* get rid of that pesky \n */
} else { /* No \n but maybe we are at the EOF */
c = fgetc(file);
ungetc(c, file);
if (c != EOF) {
/* errno = EPROTO; */ /* Nope no EOF so some sort of protocol error */
return 0;
}
}
val++; /* val points to the beginning of value + any white space*/
var = buff; /* var points to the beginning of variable */
end = strspn(buff, valid_variable_name);
tok = buff + end;
*tok = '\0'; /* chop any invalid characters from variable*/
end = strspn(val, " \t");
val = val + end; /* Now val points to the beginning of value - any leading white space */
vallen = strlen(val);
for (i = 0; i < vallen; i++) {
if ((val[i] == ';') || (val[i] == '#')) {
val[i] = '\0';
break;
}
}
vallen = strlen(val);
/* strip trailing whitespace */
for (i = vallen - 1; i > 0; i--) {
if ((val[i] == ' ') || (val[i] == '\t')) {
val[i] = '\0';
} else {
break;
}
}
if (val >= buff + len) {
/* errno = EPROTO; */
return 0;
}
bvv->variable = strdup(var);
bvv->value = strdup(val);
return 1;
} /* parse_line */
static int parse_file(zt_cfg_ty* cfg, FILE* file)
{
int c;
char block[BUFMAX];
struct cfg_bvv_ty bvv;
int numents = 0;
int line = 1;
zt_assert(cfg);
memset(&bvv, '\0', sizeof(struct cfg_bvv_ty));
sprintf(block, "Global"); /* default blockname */
bvv.block = strdup(block);
while ((c = fgetc(file)) != EOF) {
switch (c) {
case '\n':
break;
case '[': /* begin a block */
memset(block, '\0', BUFMAX);
if (bvv.block) {
free(bvv.block);
bvv.block = NULL;
}
parse_block(file, &bvv);
cfg_discard_line(file);
break;
case ';':
/* FALL-THRU */
case '#': /* comment */
while (((c = fgetc(file)) != EOF) && (c != '\n')) {
;
}
break;
case ' ':
/* FALL-TRHU */
case '\t': /* whitespace */
cfg_discard_whitespace(file);
break;
default:
ungetc(c, file);
if (!(parse_line(file, &bvv))) {
zt_log_printf(zt_log_err, "Syntax error in config file at line: %d\n", line);
return -1;
}
cfg_insert_bvv(cfg, &bvv);
free(bvv.variable);
free(bvv.value);
numents++;
break;
} /* switch */
line++;
}
free(bvv.block);
cfg->numentries = numents;
return 0;
} /* parse_file */
|
133 | ./libzt/src/zt_cfg/cfg_private.c | /* private interface to cfg
*
* Copyright (C) 2000-2004, Jason L. Shiffer <jshiffer@zerotao.com>. All Rights Reserved.
* See file COPYING for details.
*
* $Id: cfg_private.c,v 1.5 2003/11/26 17:47:29 jshiffer Exp $
*
*/
#ifdef HAVE_CONFIG_H
#include <zt_config.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#include "../zt_internal.h"
#include "../zt_log.h"
#include "cfg_private.h"
struct zt_cfg_block_ty* get_block(struct zt_cfg_block_ty* head, char* name);
struct zt_cfg_block_ty* add_block(struct zt_cfg_ty* cfg, char* name);
struct zt_cfg_value_ty* get_variable(struct zt_cfg_value_ty* head, char*vname);
struct zt_cfg_value_ty* add_variable(struct zt_cfg_block_ty* block, char *name);
zt_cfg_type get_type(char* value, void* nvalue);
zt_cfg_ty*
zt_cfg_new(zt_cfg_vtbl_ty *vptr)
{
zt_cfg_ty * result;
result = zt_callocs(vptr->size, 1);
result->vtbl = vptr;
return result;
}
void cfg_discard_line(FILE* file)
{
int c = 0;
while ((c = fgetc(file)) != EOF) {
if (c == '\n') {
break;
}
}
}
void cfg_discard_whitespace(FILE* file)
{
int c = 0;
while ((c = fgetc(file)) != EOF) {
if ((c != ' ') && (c != '\t')) {
ungetc(c, file);
break;
}
}
}
struct zt_cfg_block_ty*
get_block(struct zt_cfg_block_ty* head, char* name)
{
while (head) {
if (!strcmp(name, head->name)) {
break;
}
head = head->next;
}
return head;
}
struct zt_cfg_block_ty*
add_block(struct zt_cfg_ty* cfg, char* name)
{
struct zt_cfg_block_ty* head = cfg->head;
struct zt_cfg_block_ty* new = head;
if (head) {
new = get_block(head, name);
}
if (!new) {
new = zt_calloc(struct zt_cfg_block_ty, 1);
new->name = strdup(name);
new->next = cfg->head;
cfg->head = new;
}
return new;
}
struct zt_cfg_value_ty*
get_variable(struct zt_cfg_value_ty* head, char*vname)
{
while (head) {
if (!strcmp(head->name, vname)) {
break;
}
head = head->next;
}
return head;
}
struct zt_cfg_value_ty*
add_variable(struct zt_cfg_block_ty* block, char *name)
{
struct zt_cfg_value_ty* head = block->head;
struct zt_cfg_value_ty* new = head;
if (head) {
new = get_variable(head, name);
}
if (!new) {
new = zt_calloc(struct zt_cfg_value_ty, 1);
new->name = strdup(name);
new->next = block->head;
block->head = new;
}
return new;
}
zt_cfg_type
get_type(char* value, void* nvalue)
{
char * endptr = NULL;
char * pvalue = value;
/* check for int/long */
*(long *)nvalue = strtol(pvalue, &endptr, 0);
if (((*pvalue != '\0') && (*endptr == '\0'))) {
return zt_cfg_int;
}
pvalue = value;
*(double *)nvalue = strtod(pvalue, &endptr);
if (((*pvalue != '\0') && (*endptr == '\0'))) {
return zt_cfg_float;
}
pvalue = value;
if ((!strcasecmp(pvalue, "yes")) ||
(!strcasecmp(pvalue, "true"))) {
*(int*)nvalue = 1;
return zt_cfg_bool;
} else if ((!strcasecmp(pvalue, "no")) ||
(!strcasecmp(pvalue, "false"))) {
*(int*)nvalue = 0;
return zt_cfg_bool;
}
if (value[0] == '\'' || value[0] == '\"') {
size_t len = strlen(&value[1]);
if (value[len] != '\'' || value[len] != '\"') {
/* error */
}
value[len] = '\0';
*(char **)nvalue = strdup(&value[1]);
} else {
*(char **)nvalue = strdup(value);
}
return zt_cfg_string;
}
int
cfg_insert_bvv(struct zt_cfg_ty* cfg, struct cfg_bvv_ty* bvv)
{
struct zt_cfg_block_ty * block_head = NULL;
struct zt_cfg_value_ty * value = NULL;
char * variable = NULL;
block_head = add_block(cfg, bvv->block);
value = add_variable(block_head, bvv->variable);
if (value->v.s != NULL) {
value->altered = 1;
}
value->type = get_type(bvv->value, &value->v);
/* Check for refrences */
if (value->type == zt_cfg_string) {
variable = strchr(value->v.s, '.');
if (((variable) && (*variable == '.'))) {
struct zt_cfg_value_ty* v = NULL;
struct zt_cfg_block_ty* b = NULL;
char *block = zt_calloc(char, strlen(value->v.s) + 1);
strncpy(block, value->v.s, (variable - value->v.s));
variable++; /* move past the '.' */
if ((b = get_block(cfg->head, block))) {
if ((v = get_variable(b->head, variable))) {
free(value->v.s); /* we had to be a string to get here */
value->v.r = v;
value->type = zt_cfg_ref;
}
}
free(block);
}
}
return 0;
}
#define BUFMAX 1024
int
zt_cfg_priv_set(zt_cfg_ty *cfg, char *block_name,
char *variable_name, void *var, zt_cfg_type type)
{
struct cfg_bvv_ty bvv;
bvv.block = strdup(block_name);
bvv.variable = strdup(variable_name);
bvv.value = zt_calloc(char, BUFMAX);
switch (type) {
case zt_cfg_int:
snprintf(bvv.value, BUFMAX, "%ld", *(long *)var);
break;
case zt_cfg_float:
snprintf(bvv.value, BUFMAX, "%f", *(double *)var);
break;
case zt_cfg_bool:
if ((*(int *)var == 1) || (*(int *)var == 0)) {
zt_log_printf(zt_log_err, "Invalid value for type zt_cfg_bool in zt_cfg_set! Must be a string of (true|yes|no|false).");
return -1;
}
/* FALLTHRU */
case zt_cfg_string:
snprintf(bvv.value, BUFMAX, "%s", *(char **)var);
break;
default:
zt_log_printf(zt_log_err, "Unknown type in cfg variable list");
return -1;
}
cfg_insert_bvv(cfg, &bvv);
free(bvv.block);
free(bvv.variable);
free(bvv.value);
return 1;
}
int
zt_cfg_priv_get(zt_cfg_ty *cfg, char *block_name,
char *variable_name, void *var, zt_cfg_type type)
{
struct zt_cfg_block_ty* block = NULL;
struct zt_cfg_value_ty* value = NULL;
block = get_block(cfg->head, block_name);
if (!block) {
return -1;
}
value = get_variable(block->head, variable_name);
if (!value) {
return -1;
}
while (value->type == zt_cfg_ref) {
value = value->v.r;
}
if (value->type != type) {
return -1;
}
switch (value->type) {
case zt_cfg_bool:
*(int *)var = value->v.b;
break;
case zt_cfg_int:
*(long *)var = value->v.i;
break;
case zt_cfg_float:
*(double *)var = value->v.f;
break;
case zt_cfg_string:
*(char **)var = value->v.s;
break;
default:
zt_log_printf(zt_log_err, "Unknown type in cfg variable list");
return -1;
}
return value->type;
} /* zt_cfg_priv_get */
void
zt_cfg_priv_destructor( zt_cfg_ty *cfg)
{
struct zt_cfg_block_ty * block = cfg->head;
struct zt_cfg_block_ty * blk_next = NULL;
struct zt_cfg_value_ty * value = NULL;
struct zt_cfg_value_ty * val_next = NULL;
while (block) {
blk_next = block->next;
value = block->head;
while (value) {
val_next = value->next;
if (value->type == zt_cfg_string) {
zt_free(value->v.s); value->v.s = NULL;
}
if (value->name) {
zt_free(value->name); value->name = NULL;
}
zt_free(value); value = NULL;
value = val_next;
}
if (block->name) {
zt_free(block->name); block->name = NULL;
}
zt_free(block);
block = blk_next;
}
if (cfg->filename != NULL) {
zt_free(cfg->filename);
}
zt_free(cfg);
return;
}
|
134 | ./libzt/src/replace/basename.c | /* basename.c Replacement version of basename
* Copyright (C) 2000, Jason L. Shiffer <jshiffer@zerotao.com>. All Rights Reserved.
* See file COPYING for details.
*
* $Id: basename.c,v 1.1 2002/11/10 23:36:59 jshiffer Exp $
*
* $Log: basename.c,v $
* Revision 1.1 2002/11/10 23:36:59 jshiffer
* Initial revision
*
* Revision 1.1.1.1 2002/01/21 01:03:15 jshiffer
* Base Import
*
* Revision 1.1.1.1 2001/11/08 17:02:34 jshiffer
* base import
*
* Revision 1.1.1.1 2001/07/30 14:32:20 jshiffer
* base Import
*
* Revision 1.1.1.1 2001/07/03 01:46:23 jshiffer
* Base import new deve server
*
* Revision 1.1.1.1 2001/02/12 03:54:30 jshiffer
* Base Import libzt
*
*
* History: -jshiffer 12/20/00 11:49am: Created.
*/
#ifdef HAVE_CONFIG_H
# include <zt_config.h>
#endif
#if defined(HAVE_STRING_H)
# include <string.h>
#elif HAVE_STRINGS_H
# include <strings.h>
#endif
#if !defined(HAVE_STRRCHR)
# ifndef strrchr
# define strrchr rindex
# endif
#endif
char*
basename( char *path )
{
char *basename = strrchr(path, '/');
return basename ? ++basename : path;
}
|
135 | ./libzt/src/replace/asprintf.c | /*
* Copyright (c) 2004 Darren Tucker.
*
* Based originally on asprintf.c from OpenBSD:
* Copyright (c) 1997 Todd C. Miller <Todd.Miller@courtesan.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef HAVE_VASPRINTF
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#ifndef VA_COPY
# ifdef HAVE_VA_COPY
# define VA_COPY(dest, src) va_copy(dest, src)
# else
# ifdef HAVE___VA_COPY
# define VA_COPY(dest, src) __va_copy(dest, src)
# else
# define VA_COPY(dest, src) (dest) = (src)
# endif
# endif
#endif
#define INIT_SZ 128
int
vasprintf(char **str, const char *fmt, va_list ap)
{
int ret = -1;
va_list ap2;
char *string, *newstr;
size_t len;
VA_COPY(ap2, ap);
if ((string = malloc(INIT_SZ)) == NULL)
goto fail;
ret = vsnprintf(string, INIT_SZ, fmt, ap2);
if (ret >= 0 && ret < INIT_SZ) { /* succeeded with initial alloc */
*str = string;
} else if (ret == INT_MAX || ret < 0) { /* Bad length */
free(string);
goto fail;
} else { /* bigger than initial, realloc allowing for nul */
len = (size_t)ret + 1;
if ((newstr = realloc(string, len)) == NULL) {
free(string);
goto fail;
} else {
va_end(ap2);
VA_COPY(ap2, ap);
ret = vsnprintf(newstr, len, fmt, ap2);
if (ret >= 0 && (size_t)ret < len) {
*str = newstr;
} else { /* failed with realloc'ed string, give up */
free(newstr);
goto fail;
}
}
}
va_end(ap2);
return (ret);
fail:
*str = NULL;
errno = ENOMEM;
va_end(ap2);
return (-1);
}
#endif
#ifndef HAVE_ASPRINTF
int asprintf(char **str, const char *fmt, ...)
{
va_list ap;
int ret;
*str = NULL;
va_start(ap, fmt);
ret = vasprintf(str, fmt, ap);
va_end(ap);
return ret;
}
#endif
|
136 | ./libzt/src/replace/vsyslog.c | #ifdef HAVE_CONFIG_H
# include <zt_config.h>
#endif
#include <zt_internal.h>
#include <zt_assert.h>
#ifdef HAVE_SYSLOG_H
# include <syslog.h>
#endif
#ifdef HAVE_STRING_H
# include <string.h>
#elif HAVE_STRINGS_H
# include <strings.h>
#endif
#include <stdarg.h>
#include <errno.h>
#include <limits.h>
#ifndef HAS_SYS_ERRLIST
extern char *sys_errlist[];
extern int sys_nerr;
#endif
static char*
percent_m(char *obuf, int len, char *ibuf)
{
char * bp = obuf;
char * cp = ibuf;
while ((bp - obuf < len) && (*bp = *cp)) {
if (*cp == '%' && cp[1] == 'm') {
if (errno < sys_nerr && errno > 0) {
strcpy(bp, sys_errlist[errno]);
} else {
sprintf(bp, "Unknown Error %d", errno);
}
bp += strlen(bp);
cp += 2;
} else {
bp++;
cp++;
}
}
return obuf;
}
void
vsyslog(int severity, char *format, va_list ap)
{
char * fbuf;
char * obuf;
char * ftmp;
int len;
int flen;
int olen;
zt_assert(format);
len = strlen(format);
flen = len * 2;
olen = flen * 3;
fbuf = zt_calloc(char, flen + 1);
obuf = zt_calloc(char, olen + 1);
if ((ftmp = percent_m(fbuf, flen, format)) == NULL) {
return;
}
vsprintf(obuf, ftmp, ap);
syslog(severity, "%s", obuf);
free(fbuf);
free(obuf);
}
|
137 | ./libzt/src/zt_threads/zt_threads_pthreads.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <errno.h>
#include <pthread.h>
#include <sys/time.h>
#include <zt.h>
#include <zt_threads.h>
zt_threads_mutex *
zt_threads_pthreads_lock_alloc(int locktype UNUSED) {
pthread_mutex_t *lock;
if ((lock = calloc(sizeof(pthread_mutex_t), 1)) == NULL) {
return NULL;
}
if (pthread_mutex_init(lock, NULL)) {
free(lock);
return NULL;
}
return lock;
}
void
zt_threads_pthreads_lock_free(zt_threads_mutex *_lock, int locktype UNUSED) {
pthread_mutex_t *lock;
lock = (pthread_mutex_t *)_lock;
pthread_mutex_destroy(lock);
free(lock);
}
int
zt_threads_pthreads_lock(int mode, zt_threads_mutex *_lock) {
pthread_mutex_t *lock;
lock = (pthread_mutex_t *)_lock;
if (mode & ZT_THREADS_LOCK_NONBLOCKING) {
return pthread_mutex_trylock(lock);
}
return pthread_mutex_lock(lock);
}
int
zt_threads_pthreads_unlock(int mode UNUSED, zt_threads_mutex *_lock) {
pthread_mutex_t *lock;
lock = (pthread_mutex_t *)_lock;
return pthread_mutex_unlock(lock);
}
zt_threads_cond *
zt_threads_pthreads_cond_alloc(int condtype UNUSED) {
pthread_cond_t *cond;
if ((cond = calloc(sizeof(pthread_cond_t), 1)) == NULL) {
return NULL;
}
if (pthread_cond_init(cond, NULL)) {
free(cond);
return NULL;
}
return cond;
}
void
zt_threads_pthreads_cond_free(zt_threads_cond *_cond) {
pthread_cond_t *cond;
cond = (pthread_cond_t *)_cond;
pthread_cond_destroy(cond);
free(cond);
}
int
zt_threads_pthreads_cond_signal(zt_threads_cond *_cond, int broadcast) {
pthread_cond_t *cond;
int status;
cond = (pthread_cond_t *)_cond;
if (broadcast) {
status = pthread_cond_broadcast(cond);
} else {
status = pthread_cond_signal(cond);
}
return status ? -1 : 0;
}
int
zt_threads_pthreads_cond_wait(zt_threads_cond *_cond, zt_threads_mutex *_lock, struct timeval *tv) {
int status;
pthread_cond_t *cond;
pthread_mutex_t *lock;
cond = (pthread_cond_t *)_cond;
lock = (pthread_mutex_t *)_lock;
if (tv != NULL) {
struct timeval now;
struct timeval abstime;
struct timespec ts;
/* timeradd(tvp, uvp, vvp) timeradd((tvp), (uvp), (vvp)) */
gettimeofday(&now, NULL);
zt_add_time(&abstime, &now, tv);
ts.tv_sec = abstime.tv_sec;
ts.tv_nsec = abstime.tv_usec * 1000;
status = pthread_cond_timedwait(cond, lock, &ts);
if (status == ETIMEDOUT) {
return 1;
}
if (status) {
return -1;
}
return 0;
}
status = pthread_cond_wait(cond, lock);
return status ? -1 : 0;
}
int
zt_threads_pthreads_start(zt_threads_thread *_thread, zt_threads_attr *_attr,
void * (*start_cb)(void *), void *args) {
pthread_t *thread;
pthread_attr_t *attr;
int status;
thread = (pthread_t *)_thread;
attr = (pthread_attr_t *)_attr;
status = pthread_create(thread, attr, start_cb, args);
return status ? -1 : 0;
}
void
zt_threads_pthreads_end(void *args) {
pthread_exit(args);
}
zt_threads_thread *
zt_threads_pthreads_alloc_thread(void) {
return calloc(sizeof(pthread_t), 1);
}
int
zt_threads_pthreads_kill(zt_threads_thread *_thread) {
pthread_t *thread;
thread = (pthread_t *)_thread;
return pthread_cancel(*thread);
}
unsigned long int
zt_threads_pthread_id(void) {
return (unsigned long int)pthread_self();
}
int
zt_threads_pthread_join(zt_threads_thread *_thread, void **data) {
pthread_t *thread;
thread = (pthread_t *)_thread;
return pthread_join(*thread, data);
}
int zt_threads_pthread_detach(zt_threads_thread *thread) {
pthread_t *t = (pthread_t *)thread;
return pthread_detach(*t);
}
int
zt_threads_use_pthreads(void) {
struct zt_threads_lock_callbacks cbs = {
zt_threads_pthreads_lock_alloc,
zt_threads_pthreads_lock_free,
zt_threads_pthreads_lock,
zt_threads_pthreads_unlock
};
struct zt_threads_cond_callbacks cond_cbs = {
zt_threads_pthreads_cond_alloc,
zt_threads_pthreads_cond_free,
zt_threads_pthreads_cond_signal,
zt_threads_pthreads_cond_wait
};
struct zt_threads_cntrl_callbacks cntrl_cbs = {
zt_threads_pthreads_start,
zt_threads_pthreads_end,
zt_threads_pthreads_kill,
zt_threads_pthread_id,
zt_threads_pthread_join,
zt_threads_pthread_detach
};
zt_threads_set_lock_callbacks(&cbs);
zt_threads_set_cond_callbacks(&cond_cbs);
zt_threads_set_cntrl_callbacks(&cntrl_cbs);
zt_threads_alloc_thread = zt_threads_pthreads_alloc_thread;
return 0;
}
|
138 | ./libzt/src/zt_log/log_file.c | /*
* file.c ZeroTao logging to a file
*
* Copyright (C) 2000, 2002, 2003, Jason L. Shiffer <jshiffer@zerotao.com>. All Rights Reserved.
* See file COPYING for details.
*
* $Id: file.c,v 1.4 2003/11/26 05:05:30 jshiffer Exp $
*
*/
/*
* Description:
*/
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include "log_private.h"
typedef struct zt_log_file_ty zt_log_file_ty;
struct zt_log_file_ty {
zt_log_ty inherited;
FILE * file;
};
static void
destructor(zt_log_ty * log) {
zt_log_file_ty * this = (zt_log_file_ty*)log;
#ifdef WITH_THREADS
pthread_mutex_lock(&log->mutex);
#endif /* WITH_THREADS */
fflush(this->file);
fclose(this->file);
#ifdef WITH_THREADS
pthread_mutex_unlock(&log->mutex);
pthread_mutex_destroy(&log->mutex);
#endif /* WITH_THREADS */
zt_free(this);
}
static void
print(zt_log_ty * log, zt_log_level level, const char * file, int line, const char * func, const char * fmt, va_list ap) {
char * nfmt = NULL;
zt_log_file_ty * this = (zt_log_file_ty*)log;
nfmt = zt_log_gen_fmt(log, fmt, file, line, func, level, log->opts);
#ifdef WITH_THREADS
pthread_mutex_lock(&log->mutex);
#endif /* WITH_THREADS */
vfprintf(this->file, nfmt, ap);
#ifdef WITH_THREADS
pthread_mutex_unlock(&log->mutex);
#endif /* WITH_THREADS */
free(nfmt);
}
/* component data */
static zt_log_vtbl_ty vtbl = {
sizeof(zt_log_file_ty),
destructor,
print,
};
zt_log_ty *
zt_log_file(char * file, int fopts, int lopts) {
zt_log_file_ty * this;
zt_log_ty * result;
result = zt_log_new(&vtbl, lopts);
this = (zt_log_file_ty*)result;
if (fopts == ZT_LOG_FILE_APPEND) {
this->file = fopen(file, "a");
} else {
this->file = fopen(file, "w");
}
if (!this->file) {
fprintf(stderr, "Could not open file %s: %s\n", file, strerror(errno));
return NULL;
}
#ifdef WITH_THREADS
pthread_mutex_init(&result->mutex, NULL);
#endif /* WITH_THREADS */
return result;
} |
139 | ./libzt/src/zt_log/log_private.c | /*
* private.c ZeroTao private definitions for logging
*
* Copyright (C) 2000-2004, Jason L. Shiffer <jshiffer@zerotao.com>. All Rights Reserved.
* See file COPYING for details.
*
* $Id: zt_log_private.c,v 1.4 2003/11/26 17:47:29 jshiffer Exp $
*
*/
/*
* Description:
*/
#ifdef HAVE_CONFIG_H
#include <zt_config.h>
#endif
#include <stdio.h>
#include <time.h>
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "../zt_internal.h"
#include "../zt_progname.h"
#include "log_private.h"
zt_log_level_desc_ty zt_log_level_desc[] = {
{ zt_log_emerg, "Emergency" },
{ zt_log_alert, "Alert" },
{ zt_log_crit, "Critical" },
{ zt_log_err, "Error" },
{ zt_log_warning, "Warning" },
{ zt_log_notice, "Notice" },
{ zt_log_info, "Info" },
{ zt_log_debug, "Debug" },
{ -1, NULL },
};
zt_log_ty *
zt_log_new(zt_log_vtbl_ty * vptr, unsigned int opts) {
zt_log_ty * result;
result = zt_callocs(vptr->size, 1);
if (!result) {
fprintf(stderr, "Unable to calloc memory for log vtable\n");
exit(1);
}
result->vtbl = vptr;
result->opts = opts;
result->level = zt_log_max;
return result;
}
char*
zt_log_gen_fmt(zt_log_ty * log, const char * fmt, const char * file, int line, const char * function, zt_log_level level, unsigned int opts) {
size_t len = 0;
char * buff = NULL;
len = strlen(fmt) + 4; /* format + seperator + "\n" + null */
buff = (char*)zt_calloc(char, len); /* mem_calloc(len, sizeof(char)); */
if (opts & ZT_LOG_WITH_DATE) {
char sbuf[255];
time_t tt = time(NULL);
len += strftime(sbuf, 254, "%b %d %H:%M:%S ", localtime(&tt));
buff = zt_realloc(char, buff, len);
sprintf(buff, "%s", sbuf);
}
if (opts & ZT_LOG_WITH_SYSNAME) {
char sbuf[255];
char * t = NULL;
if (gethostname(sbuf, 254) == -1) {
sprintf(sbuf, "*hostname*");
}
t = strchr(sbuf, '.');
if (t) {
*t = '\0';
}
len += strlen(sbuf) + 1; /* sbuf + space */
buff = zt_realloc(char, buff, len);
strcat(buff, sbuf);
if ((opts > ZT_LOG_WITH_SYSNAME)) {
strcat(buff, " ");
}
}
if (opts & ZT_LOG_WITH_PROGNAME) {
len += strlen(zt_progname(NULL, 0)); /* progname */
buff = zt_realloc(char, buff, len);
strcat(buff, zt_progname(NULL, 0));
}
if (opts & ZT_LOG_WITH_PID) {
char sbuf[10 + 3]; /* pid + [] + null */
pid_t pid = getpid();
sprintf(sbuf, "[%u]", pid);
len += strlen(sbuf);
buff = zt_realloc(char, buff, len);
strcat(buff, sbuf);
}
if (opts & ZT_LOG_WITH_LEVEL) {
if ((level < zt_log_max) && ((int)level >= zt_log_emerg)) {
len += strlen(zt_log_level_desc[level].desc) + 2; /* ': ' + level desc */
buff = zt_realloc(char, buff, len);
if (opts != ZT_LOG_WITH_LEVEL) {
strcat(buff, ": ");
}
strcat(buff, zt_log_level_desc[level].desc);
}
}
if (opts != ZT_LOG_RAW) {
strcat(buff, ": ");
}
strcat(buff, fmt);
if (((file) && (line > -1) && (function))) {
char * nbuff = NULL;
size_t nlen = 13; /* ': in at (:)' + null */
nlen += strlen(file);
nlen += strlen(function);
nlen += 10; /* length of a int to str */
nbuff = zt_calloc(char, nlen); /* mem_calloc(nlen, sizeof(char)); */
sprintf(nbuff, ": in %s at (%s:%d)", function, file, line);
len += nlen;
buff = zt_realloc(char, buff, len);
strcat(buff, nbuff);
zt_free(nbuff);
}
strcat(buff, "\n");
return buff;
} /* zt_log_gen_fmt */
|
140 | ./libzt/src/zt_log/log_stderr.c | /*
* stderr.c ZeroTao logging to stderr
*
* Copyright (C) 2000-2004, Jason L. Shiffer <jshiffer@zerotao.com>. All Rights Reserved.
* See file COPYING for details.
*
* $Id: stderr.c,v 1.3 2003/06/10 04:00:48 jshiffer Exp $
*
*/
/*
* Description:
*/
#include <stdio.h>
#include "../zt_internal.h"
#include "log_private.h"
static void
destructor(zt_log_ty * log) {
#ifdef WITH_THREADS
pthread_mutex_destroy(&log->mutex);
#endif /* WITH_THREADS */
zt_free(log);
return;
}
static void
print(zt_log_ty * log, zt_log_level level, const char * file, int line, const char * function, const char * fmt, va_list ap) {
char * nfmt = zt_log_gen_fmt( log, fmt, file, line, function, level, log->opts);
#ifdef WITH_THREADS
pthread_mutex_lock(&log->mutex);
#endif /* WITH_THREADS */
vfprintf(stderr, nfmt, ap);
#ifdef WITH_THREADS
pthread_mutex_unlock(&log->mutex);
#endif /* WITH_THREADS */
zt_free(nfmt);
}
/* component data */
static zt_log_vtbl_ty vtbl = {
sizeof(zt_log_ty),
destructor,
print,
};
zt_log_ty *
zt_log_stderr(unsigned int opts) {
zt_log_ty * log;
log = zt_log_new(&vtbl, opts);
#ifdef WITH_THREADS
pthread_mutex_init(&log->mutex, NULL);
#endif /* WITH_THREADS */
return log;
} |
141 | ./libzt/src/zt_log/log_syslog.c | /*
* syslog.c ZeroTao logging to syslog
*
* Copyright (C) 2000-2004, Jason L. Shiffer <jshiffer@zerotao.com>. All Rights Reserved.
* See file COPYING for details.
*
* $Id: syslog.c,v 1.3 2003/06/10 04:15:55 jshiffer Exp $
*
*/
/*
* Description:
*/
#ifdef HAVE_SYSLOG_H
#include <syslog.h>
#endif
#include "log_private.h"
#include "log_syslog.h"
#if HAVE_SYSLOG
static void
destructor(zt_log_ty * log) {
closelog();
zt_free(log);
return;
}
static void
print(zt_log_ty * log, zt_log_level level, const char * file, int line, const char * function, const char * fmt, va_list ap) {
char * nfmt = NULL;
int syslog_level = 0;
unsigned int level_flag = 0;
switch (level) {
case zt_log_emerg:
syslog_level = LOG_EMERG;
break;
case zt_log_alert:
syslog_level = LOG_ALERT;
break;
case zt_log_crit:
syslog_level = LOG_CRIT;
break;
case zt_log_err:
syslog_level = LOG_ERR;
break;
case zt_log_warning:
syslog_level = LOG_WARNING;
break;
case zt_log_notice:
syslog_level = LOG_NOTICE;
break;
case zt_log_info:
syslog_level = LOG_INFO;
break;
case zt_log_debug:
syslog_level = LOG_DEBUG;
break;
default:
syslog_level = LOG_ERR;
break;
} /* switch */
/* honor level flag if it is set in the logger opts. for the rest of the
* zt flags, defer to syslog settings */
level_flag = (log->opts & ZT_LOG_WITH_LEVEL) ? ZT_LOG_WITH_LEVEL : 0;
nfmt = zt_log_gen_fmt(log, fmt, file, line, function, level, level_flag);
vsyslog(syslog_level, nfmt, ap);
zt_free(nfmt);
} /* print */
/* component data */
static zt_log_vtbl_ty vtbl = {
sizeof(zt_log_ty),
destructor,
print,
};
#endif /* HAVE_SYSLOG */
zt_log_ty *
zt_log_syslog(void) {
return zt_log_syslog2(ZT_LOG_WITH_PID, LOG_USER);
}
zt_log_ty *
zt_log_syslog2(int opt, int facility) {
#if HAVE_SYSLOG
char * name = zt_progname(0, 0);
int sysopts = 0;
if (opt & ZT_LOG_WITH_PID) {
sysopts |= LOG_PID;
}
openlog(name ? name : "Set name with progname call", sysopts, facility);
return zt_log_new(&vtbl, 0);
#else /* if HAVE_SYSLOG */
zt_log_ty * logger = zt_log_stderr(ZT_LOG_EMU_SYSLOG);
zt_log_printf(zt_log_crit, "Syslog not supported on this platform: falling back to zt_log_stderr");
return logger;
#endif /* HAVE_SYSLOG */
} |
142 | ./spacefm/src/main-window.c | /*
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <libintl.h>
#include "pcmanfm.h"
#include "private.h"
#include <gtk/gtk.h>
#include <glib.h>
#include <glib/gstdio.h>
#include <glib-object.h>
#include <gdk/gdk.h>
#include <gdk/gdkkeysyms.h>
#include <gdk/gdkx.h> // XGetWindowProperty
#include <X11/Xatom.h> // XA_CARDINAL
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <stdlib.h>
#include "ptk-location-view.h"
#include "exo-tree-view.h"
#include "ptk-file-browser.h"
#include "main-window.h"
#include "ptk-utils.h"
#include "pref-dialog.h"
#include "ptk-bookmarks.h"
#include "edit-bookmarks.h"
#include "ptk-file-properties.h"
#include "ptk-path-entry.h"
#include "settings.h"
#include "find-files.h"
#ifdef HAVE_STATVFS
/* FIXME: statvfs support should be moved to src/vfs */
#include <sys/statvfs.h>
#endif
#include "vfs-app-desktop.h"
#include "vfs-execute.h"
#include "vfs-utils.h" /* for vfs_sudo() */
#include "go-dialog.h"
#include "vfs-file-task.h"
#include "ptk-location-view.h"
#include "ptk-clipboard.h"
#include "gtk2-compat.h"
void rebuild_menus( FMMainWindow* main_window );
static void fm_main_window_class_init( FMMainWindowClass* klass );
static void fm_main_window_init( FMMainWindow* main_window );
static void fm_main_window_finalize( GObject *obj );
static void fm_main_window_get_property ( GObject *obj,
guint prop_id,
GValue *value,
GParamSpec *pspec );
static void fm_main_window_set_property ( GObject *obj,
guint prop_id,
const GValue *value,
GParamSpec *pspec );
static gboolean fm_main_window_delete_event ( GtkWidget *widget,
GdkEvent *event );
#if 0
static void fm_main_window_destroy ( GtkObject *object );
#endif
//static gboolean fm_main_window_key_press_event ( GtkWidget *widget,
// GdkEventKey *event );
static gboolean fm_main_window_window_state_event ( GtkWidget *widget,
GdkEventWindowState *event );
static void fm_main_window_next_tab ( FMMainWindow* widget );
static void fm_main_window_prev_tab ( FMMainWindow* widget );
static void on_folder_notebook_switch_pape ( GtkNotebook *notebook,
GtkWidget *page,
guint page_num,
gpointer user_data );
//static void on_close_tab_activate ( GtkMenuItem *menuitem,
// gpointer user_data );
//static void on_file_browser_before_chdir( PtkFileBrowser* file_browser,
// const char* path, gboolean* cancel,
// FMMainWindow* main_window );
//static void on_file_browser_begin_chdir( PtkFileBrowser* file_browser,
// FMMainWindow* main_window );
static void on_file_browser_open_item( PtkFileBrowser* file_browser,
const char* path, PtkOpenAction action,
FMMainWindow* main_window );
static void on_file_browser_after_chdir( PtkFileBrowser* file_browser,
FMMainWindow* main_window );
static void on_file_browser_content_change( PtkFileBrowser* file_browser,
FMMainWindow* main_window );
static void on_file_browser_sel_change( PtkFileBrowser* file_browser,
FMMainWindow* main_window );
//static void on_file_browser_pane_mode_change( PtkFileBrowser* file_browser,
// FMMainWindow* main_window );
void on_file_browser_panel_change( PtkFileBrowser* file_browser,
FMMainWindow* main_window );
static void on_file_browser_splitter_pos_change( PtkFileBrowser* file_browser,
GParamSpec *param,
FMMainWindow* main_window );
static gboolean on_tab_drag_motion ( GtkWidget *widget,
GdkDragContext *drag_context,
gint x,
gint y,
guint time,
PtkFileBrowser* file_browser );
static gboolean on_main_window_focus( GtkWidget* main_window,
GdkEventFocus *event,
gpointer user_data );
static gboolean on_main_window_keypress( FMMainWindow* widget,
GdkEventKey* event, gpointer data);
//static gboolean on_main_window_keyrelease( FMMainWindow* widget,
// GdkEventKey* event, gpointer data);
static gboolean on_window_button_press_event( GtkWidget* widget,
GdkEventButton *event,
FMMainWindow* main_window ); //sfm
static void on_new_window_activate ( GtkMenuItem *menuitem,
gpointer user_data );
GtkWidget* create_bookmarks_menu ( FMMainWindow* main_window );
static void fm_main_window_close( FMMainWindow* main_window );
GtkWidget* main_task_view_new( FMMainWindow* main_window );
void main_task_add_menu( FMMainWindow* main_window, GtkMenu* menu,
GtkAccelGroup* accel_group );
void on_task_popup_show( GtkMenuItem* item, FMMainWindow* main_window, char* name2 );
gboolean main_tasks_running( FMMainWindow* main_window );
void on_task_stop( GtkMenuItem* item, GtkWidget* view, XSet* set2,
PtkFileTask* task2 );
void on_preference_activate ( GtkMenuItem *menuitem, gpointer user_data );
void main_task_prepare_menu( FMMainWindow* main_window, GtkWidget* menu,
GtkAccelGroup* accel_group );
void on_task_columns_changed( GtkWidget *view, gpointer user_data );
PtkFileTask* get_selected_task( GtkWidget* view );
static void fm_main_window_update_status_bar( FMMainWindow* main_window,
PtkFileBrowser* file_browser );
void set_window_title( FMMainWindow* main_window, PtkFileBrowser* file_browser );
void on_task_column_selected( GtkMenuItem* item, GtkWidget* view );
void on_task_popup_errset( GtkMenuItem* item, FMMainWindow* main_window, char* name2 );
void show_task_dialog( GtkWidget* widget, GtkWidget* view );
void on_about_activate ( GtkMenuItem *menuitem, gpointer user_data );
void on_main_help_activate ( GtkMenuItem *menuitem, FMMainWindow* main_window );
void on_main_faq ( GtkMenuItem *menuitem, FMMainWindow* main_window );
void on_homepage_activate ( GtkMenuItem *menuitem, FMMainWindow* main_window );
void on_news_activate ( GtkMenuItem *menuitem, FMMainWindow* main_window );
void on_getplug_activate ( GtkMenuItem *menuitem, FMMainWindow* main_window );
void update_window_title( GtkMenuItem* item, FMMainWindow* main_window );
void on_toggle_panelbar( GtkWidget* widget, FMMainWindow* main_window );
void on_fullscreen_activate ( GtkMenuItem *menuitem, FMMainWindow* main_window );
static gboolean delayed_focus( GtkWidget* widget );
static gboolean delayed_focus_file_browser( PtkFileBrowser* file_browser );
static GtkWindowClass *parent_class = NULL;
static int n_windows = 0;
static GList* all_windows = NULL;
static guint theme_change_notify = 0;
// Drag & Drop/Clipboard targets
static GtkTargetEntry drag_targets[] = {
{"text/uri-list", 0 , 0 }
};
GType fm_main_window_get_type()
{
static GType type = G_TYPE_INVALID;
if ( G_UNLIKELY ( type == G_TYPE_INVALID ) )
{
static const GTypeInfo info =
{
sizeof ( FMMainWindowClass ),
NULL,
NULL,
( GClassInitFunc ) fm_main_window_class_init,
NULL,
NULL,
sizeof ( FMMainWindow ),
0,
( GInstanceInitFunc ) fm_main_window_init,
NULL,
};
type = g_type_register_static ( GTK_TYPE_WINDOW, "FMMainWindow", &info, 0 );
}
return type;
}
void fm_main_window_class_init( FMMainWindowClass* klass )
{
GObjectClass * object_class;
GtkWidgetClass *widget_class;
object_class = ( GObjectClass * ) klass;
parent_class = g_type_class_peek_parent ( klass );
object_class->set_property = fm_main_window_set_property;
object_class->get_property = fm_main_window_get_property;
object_class->finalize = fm_main_window_finalize;
widget_class = GTK_WIDGET_CLASS ( klass );
widget_class->delete_event = (gpointer) fm_main_window_delete_event;
//widget_class->key_press_event = on_main_window_keypress; //fm_main_window_key_press_event;
widget_class->window_state_event = fm_main_window_window_state_event;
/* this works but desktop_window doesn't
g_signal_new ( "task-notify",
G_TYPE_FROM_CLASS ( klass ),
G_SIGNAL_RUN_FIRST,
0,
NULL, NULL,
g_cclosure_marshal_VOID__POINTER,
G_TYPE_NONE, 1, G_TYPE_POINTER );
*/
}
gboolean on_window_configure_event( GtkWindow *window,
GdkEvent *event, FMMainWindow* main_window )
{
if ( evt_win_move->s || evt_win_move->ob2_data )
main_window_event( main_window, evt_win_move, "evt_win_move", 0, 0,
NULL, 0, 0, 0, TRUE );
return FALSE;
}
void on_bookmark_item_activate ( GtkMenuItem* menu, gpointer user_data )
{
FMMainWindow * main_window = FM_MAIN_WINDOW( user_data );
char* path = ( char* ) g_object_get_data( G_OBJECT( menu ), "path" );
if ( !path )
return ;
PtkFileBrowser* file_browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
if ( g_str_has_prefix( path, "//" ) || strstr( path, ":/" ) )
{
if ( file_browser )
mount_network( file_browser, path, xset_get_b( "book_newtab" ) );
}
else
{
if ( !xset_get_b( "book_newtab" ) )
{
if ( file_browser )
ptk_file_browser_chdir( file_browser, path, PTK_FB_CHDIR_ADD_HISTORY );
}
else
fm_main_window_add_new_tab( main_window, path );
}
}
void on_bookmarks_change( PtkBookmarks* bookmarks, FMMainWindow* main_window )
{
main_window->book_menu = create_bookmarks_menu( main_window );
/* FIXME: We have to popupdown the menu first, if it's showed on screen.
* Otherwise, it's rare but possible that we try to replace the menu while it's in use.
* In that way, gtk+ will hang. So some dirty hack is used here.
* We popup down the old menu, if it's currently shown.
*/
GtkMenu* menu = (GtkMenu*)gtk_menu_item_get_submenu ( GTK_MENU_ITEM (
main_window->book_menu_item ) );
if ( menu )
gtk_menu_popdown( menu );
gtk_menu_item_set_submenu ( GTK_MENU_ITEM ( main_window->book_menu_item ),
GTK_WIDGET( main_window->book_menu ) );
}
void main_window_update_bookmarks()
{
GList* l;
for ( l = all_windows; l; l = l->next )
{
on_bookmarks_change( NULL, (FMMainWindow*)l->data );
}
}
GtkWidget* create_bookmarks_menu_item ( FMMainWindow* main_window,
const char* item )
{
GtkWidget * folder_image = NULL;
GtkWidget* menu_item;
const char* path;
menu_item = gtk_image_menu_item_new_with_label( item );
path = ptk_bookmarks_item_get_path( item );
g_object_set_data( G_OBJECT( menu_item ), "path", (gpointer) path );
//folder_image = gtk_image_new_from_icon_name( "gnome-fs-directory",
// GTK_ICON_SIZE_MENU );
XSet* set = xset_get( "book_icon" );
if ( set->icon )
folder_image = xset_get_image( set->icon, GTK_ICON_SIZE_MENU );
if ( !folder_image )
folder_image = xset_get_image( "gtk-directory", GTK_ICON_SIZE_MENU );
if ( folder_image )
gtk_image_menu_item_set_image ( GTK_IMAGE_MENU_ITEM ( menu_item ),
folder_image );
g_signal_connect( menu_item, "activate",
G_CALLBACK( on_bookmark_item_activate ), main_window );
return menu_item;
}
void add_bookmark( GtkWidget* item, FMMainWindow* main_window )
{
PtkFileBrowser* file_browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
ptk_file_browser_add_bookmark( NULL, file_browser );
}
void show_bookmarks( GtkWidget* item, FMMainWindow* main_window )
{
PtkFileBrowser* file_browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
if ( !file_browser )
return;
if ( !file_browser->side_book )
{
xset_set_panel( file_browser->mypanel, "show_book", "b", "1" );
update_views_all_windows( NULL, file_browser );
}
if ( file_browser->side_book )
gtk_widget_grab_focus( GTK_WIDGET( file_browser->side_book ) );
}
GtkWidget* create_bookmarks_menu ( FMMainWindow* main_window )
{
GtkWidget * bookmark_menu;
GtkWidget* menu_item;
GList* l;
/* this won't update with xset change so don't bother with it
XSet* set_add = xset_get( "book_new" );
XSet* set_show = xset_get( "panel1_show_book" );
GtkAccelGroup* accel_group = gtk_accel_group_new();
PtkMenuItemEntry fm_bookmarks_menu[] = {
PTK_IMG_MENU_ITEM( N_( "_Add" ), "gtk-add", add_bookmark, set_add->key, set_add->keymod ),
PTK_IMG_MENU_ITEM( N_( "_Show" ), "gtk-edit", show_bookmarks, set_show->key, set_show->keymod ),
PTK_SEPARATOR_MENU_ITEM,
PTK_MENU_END
};
bookmark_menu = ptk_menu_new_from_data( fm_bookmarks_menu, main_window,
accel_group );
*/
XSet* set = xset_get( "tool_book" );
char* book_icon = set->icon;
// ptk_menu_new_from_data only accept stock icons - is it?
if ( book_icon && !g_str_has_prefix( book_icon, "gtk-" ) )
book_icon = NULL;
if ( !book_icon )
book_icon = "gtk-jump-to";
PtkMenuItemEntry fm_bookmarks_menu[] = {
PTK_IMG_MENU_ITEM( N_( "_Show" ), book_icon, show_bookmarks, 0, 0 ),
PTK_IMG_MENU_ITEM( N_( "_Add" ), "gtk-add", add_bookmark, 0, 0 ),
PTK_SEPARATOR_MENU_ITEM,
PTK_MENU_END
};
bookmark_menu = ptk_menu_new_from_data( fm_bookmarks_menu, main_window,
main_window->accel_group );
int count = 0;
for ( l = app_settings.bookmarks->list; l; l = l->next )
{
menu_item = create_bookmarks_menu_item( main_window,
( char* ) l->data );
gtk_menu_shell_append ( GTK_MENU_SHELL( bookmark_menu ), menu_item );
if ( ++count > 200 )
break;
}
gtk_widget_show_all( bookmark_menu );
return bookmark_menu;
}
void on_plugin_install( GtkMenuItem* item, FMMainWindow* main_window, XSet* set2 )
{
XSet* set;
char* path = NULL;
char* deffolder;
char* plug_dir;
char* msg;
int type = 0;
int job = 0;
if ( !item )
set = set2;
else
set = (XSet*)g_object_get_data( G_OBJECT(item), "set" );
if ( !set )
return;
if ( g_str_has_suffix( set->name, "cfile" ) || g_str_has_suffix( set->name, "curl" ) )
job = 1; // copy
if ( g_str_has_suffix( set->name, "file" ) )
{
// get file path
XSet* save = xset_get( "plug_ifile" );
if ( save->s ) //&& g_file_test( save->s, G_FILE_TEST_IS_DIR )
deffolder = save->s;
else
{
if ( !( deffolder = xset_get_s( "go_set_default" ) ) )
deffolder = "/";
}
path = xset_file_dialog( GTK_WIDGET( main_window ),
GTK_FILE_CHOOSER_ACTION_OPEN,
_("Choose Plugin File"),
deffolder, NULL );
if ( !path )
return;
if ( save->s )
g_free( save->s );
save->s = g_path_get_dirname( path );
}
else
{
// get url
if ( !xset_text_dialog( GTK_WIDGET( main_window ), _("Enter Plugin URL"), NULL, FALSE, _("Enter SpaceFM Plugin URL:\n\n(wget will be used to download the plugin file)"), NULL, NULL, &path, NULL, FALSE, job == 0 ? "#plugins-install" : "#plugins-copy" ) || !path || path[0] == '\0' )
return;
type = 1; //url
}
if ( job == 0 )
{
// install job
char* filename = g_path_get_basename( path );
char* ext = strstr( filename, ".spacefm-plugin" );
if ( !ext )
ext = strstr( filename, ".tar.gz" );
if ( ext )
ext[0] = '\0';
char* plug_dir_name = plain_ascii_name( filename );
if ( ext )
ext[0] = '.';
g_free( filename );
if ( plug_dir_name[0] == '\0' )
{
msg = g_strdup_printf( _("This plugin's filename is invalid. Please rename it using alpha-numeric ASCII characters and try again.") );
xset_msg_dialog( GTK_WIDGET( main_window ), GTK_MESSAGE_ERROR,
_("Invalid Plugin Filename"), NULL,
0, msg, NULL, "#plugins-install" );
{
g_free( plug_dir_name );
g_free( path );
g_free( msg );
return;
}
}
if ( DATADIR )
plug_dir = g_build_filename( DATADIR, "spacefm", "plugins",
plug_dir_name, NULL );
else if ( !g_file_test( "/usr/share/spacefm/plugins", G_FILE_TEST_IS_DIR ) &&
g_file_test( "/usr/local/share/spacefm/plugins", G_FILE_TEST_IS_DIR ) )
plug_dir = g_build_filename( "/usr/local/share/spacefm/plugins",
plug_dir_name, NULL );
else
plug_dir = g_build_filename( "/usr/share/spacefm/plugins",
plug_dir_name, NULL );
if ( g_file_test( plug_dir, G_FILE_TEST_EXISTS ) )
{
msg = g_strdup_printf( _("There is already a plugin installed as '%s'. Overwrite ?\n\nTip: You can also rename this plugin file to install it under a different name."), plug_dir_name );
if ( xset_msg_dialog( GTK_WIDGET( main_window ), GTK_MESSAGE_WARNING,
_("Overwrite Plugin ?"), NULL,
GTK_BUTTONS_YES_NO,
msg, NULL, "#plugins-install" ) != GTK_RESPONSE_YES )
{
g_free( plug_dir_name );
g_free( plug_dir );
g_free( path );
g_free( msg );
return;
}
g_free( msg );
}
g_free( plug_dir_name );
}
else
{
// copy job
const char* user_tmp = xset_get_user_tmp_dir();
if ( !user_tmp )
{
xset_msg_dialog( GTK_WIDGET( main_window ), GTK_MESSAGE_ERROR,
_("Error Creating Temp Directory"), NULL, 0,
_("Unable to create temporary directory"), NULL,
NULL );
g_free( path );
return;
}
char* hex8;
plug_dir = NULL;
while ( !plug_dir || ( plug_dir && g_file_test( plug_dir, G_FILE_TEST_EXISTS ) ) )
{
hex8 = randhex8();
if ( plug_dir )
g_free( plug_dir );
plug_dir = g_build_filename( user_tmp, hex8, NULL );
g_free( hex8 );
}
}
install_plugin_file( main_window, path, plug_dir, type, job );
g_free( path );
g_free( plug_dir );
}
GtkWidget* create_plugins_menu( FMMainWindow* main_window )
{
GtkWidget* plug_menu;
GtkWidget* item;
GList* l;
GList* plugins = NULL;
XSet* set;
PtkFileBrowser* file_browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
GtkAccelGroup* accel_group = gtk_accel_group_new ();
plug_menu = gtk_menu_new();
if ( !file_browser )
return plug_menu;
set = xset_set_cb( "plug_ifile", on_plugin_install, main_window );
xset_set_ob1( set, "set", set );
set = xset_set_cb( "plug_iurl", on_plugin_install, main_window );
xset_set_ob1( set, "set", set );
set = xset_set_cb( "plug_cfile", on_plugin_install, main_window );
xset_set_ob1( set, "set", set );
set = xset_set_cb( "plug_curl", on_plugin_install, main_window );
xset_set_ob1( set, "set", set );
set = xset_get( "plug_install" );
xset_add_menuitem( NULL, file_browser, plug_menu, accel_group, set );
set = xset_get( "plug_copy" );
xset_add_menuitem( NULL, file_browser, plug_menu, accel_group, set );
item = gtk_separator_menu_item_new();
gtk_menu_shell_append( GTK_MENU_SHELL( plug_menu ), item );
set = xset_get( "plug_inc" );
item = xset_add_menuitem( NULL, file_browser, plug_menu, accel_group, set );
if ( item )
{
GtkWidget* inc_menu = gtk_menu_item_get_submenu( GTK_MENU_ITEM ( item ) );
plugins = xset_get_plugins( TRUE );
for ( l = plugins; l; l = l->next )
xset_add_menuitem( NULL, file_browser, inc_menu, accel_group,
(XSet*)l->data );
}
set->disable = !plugins;
if ( plugins )
g_list_free( plugins );
plugins = xset_get_plugins( FALSE );
for ( l = plugins; l; l = l->next )
xset_add_menuitem( NULL, file_browser, plug_menu, accel_group,
(XSet*)l->data );
if ( plugins )
g_list_free( plugins );
gtk_widget_show_all( plug_menu );
if ( set->disable )
gtk_widget_hide( item ); // temporary until included available
return plug_menu;
}
/* don't use this method because menu must be updated just after user opens it
* due to file_browser value in xsets
void main_window_on_plugins_change( FMMainWindow* main_window )
{
if ( main_window )
{
main_window->plug_menu = create_plugins_menu( main_window );
// FIXME: We have to popupdown the menu first, if it's showed on screen.
// Otherwise, it's rare but possible that we try to replace the menu while it's in use.
gtk_menu_popdown( (GtkMenu*)gtk_menu_item_get_submenu ( GTK_MENU_ITEM (
main_window->plug_menu_item ) ) );
gtk_menu_item_set_submenu ( GTK_MENU_ITEM ( main_window->plug_menu_item ),
main_window->plug_menu );
}
else
{
// all windows
FMMainWindow* a_window;
GList* l;
for ( l = all_windows; l; l = l->next )
{
a_window = (FMMainWindow*)l->data;
a_window->plug_menu = create_plugins_menu( a_window );
gtk_menu_popdown( (GtkMenu*)gtk_menu_item_get_submenu ( GTK_MENU_ITEM (
a_window->plug_menu_item ) ) );
gtk_menu_item_set_submenu ( GTK_MENU_ITEM ( a_window->plug_menu_item ),
a_window->plug_menu );
}
}
}
*/
void import_all_plugins( FMMainWindow* main_window )
{
GDir* dir;
const char* name;
char* plug_dir;
char* plug_file;
int i;
gboolean found = FALSE;
gboolean found_plugins = FALSE;
// get potential locations
char* path;
GList* locations = NULL;
if ( DATADIR )
{
locations = g_list_append( locations, g_build_filename( DATADIR,
"spacefm", "included", NULL ) );
locations = g_list_append( locations, g_build_filename( DATADIR,
"spacefm", "plugins", NULL ) );
}
const gchar* const * sdir = g_get_system_data_dirs();
for( ; *sdir; ++sdir )
{
path = g_build_filename( *sdir, "spacefm", "included", NULL );
if ( !g_list_find_custom( locations, path, (GCompareFunc)g_strcmp0 ) )
locations = g_list_append( locations, path );
else
g_free( path );
path = g_build_filename( *sdir, "spacefm", "plugins", NULL );
if ( !g_list_find_custom( locations, path, (GCompareFunc)g_strcmp0 ) )
locations = g_list_append( locations, path );
else
g_free( path );
}
if ( !g_list_find_custom( locations, "/usr/local/share/spacefm/included", (GCompareFunc)g_strcmp0 ) )
locations = g_list_append( locations, g_strdup( "/usr/local/share/spacefm/included" ) );
if ( !g_list_find_custom( locations, "/usr/share/spacefm/included", (GCompareFunc)g_strcmp0 ) )
locations = g_list_append( locations, g_strdup( "/usr/share/spacefm/included" ) );
if ( !g_list_find_custom( locations, "/usr/local/share/spacefm/plugins", (GCompareFunc)g_strcmp0 ) )
locations = g_list_append( locations, g_strdup( "/usr/local/share/spacefm/plugins" ) );
if ( !g_list_find_custom( locations, "/usr/share/spacefm/plugins", (GCompareFunc)g_strcmp0 ) )
locations = g_list_append( locations, g_strdup( "/usr/share/spacefm/plugins" ) );
GList* l;
for ( l = locations; l; l = l->next )
{
dir = g_dir_open( (char*)l->data, 0, NULL );
if ( dir )
{
while ( ( name = g_dir_read_name( dir ) ) )
{
plug_file = g_build_filename( (char*)l->data, name, "plugin", NULL );
if ( g_file_test( plug_file, G_FILE_TEST_EXISTS ) )
{
plug_dir = g_build_filename( (char*)l->data, name, NULL );
if ( xset_import_plugin( plug_dir ) )
{
found = TRUE;
if ( i == 1 )
found_plugins = TRUE;
}
else
printf( "Invalid Plugin Ignored: %s/\n", plug_dir );
g_free( plug_dir );
}
g_free( plug_file );
}
g_dir_close( dir );
}
}
g_list_foreach( locations, (GFunc)g_free, NULL );
g_list_free( locations );
clean_plugin_mirrors();
}
void on_devices_show( GtkMenuItem* item, FMMainWindow* main_window )
{
PtkFileBrowser* file_browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
if ( !file_browser )
return;
if ( !file_browser->side_dev )
{
xset_set_panel( file_browser->mypanel, "show_devmon", "b", "1" );
update_views_all_windows( NULL, file_browser );
}
if ( file_browser->side_dev )
gtk_widget_grab_focus( GTK_WIDGET( file_browser->side_dev ) );
}
GtkWidget* create_devices_menu( FMMainWindow* main_window )
{
GtkWidget* dev_menu;
GtkWidget* item;
XSet* set;
PtkFileBrowser* file_browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
GtkAccelGroup* accel_group = gtk_accel_group_new();
dev_menu = gtk_menu_new();
if ( !file_browser )
return dev_menu;
set = xset_set_cb( "main_dev", on_devices_show, main_window );
xset_add_menuitem( NULL, file_browser, dev_menu, accel_group, set );
set = xset_get( "main_dev_sep" );
xset_add_menuitem( NULL, file_browser, dev_menu, accel_group, set );
ptk_location_view_dev_menu( GTK_WIDGET( main_window ), dev_menu );
#ifndef HAVE_HAL
set = xset_get( "sep_dm3" );
xset_add_menuitem( NULL, file_browser, dev_menu, accel_group, set );
set = xset_get( "dev_menu_settings" );
xset_add_menuitem( NULL, file_browser, dev_menu, accel_group, set );
#endif
gtk_widget_show_all( dev_menu );
return dev_menu;
}
void on_save_session( GtkWidget* widget, FMMainWindow* main_window )
{
// disable autosave timer
if ( xset_autosave_timer )
{
g_source_remove( xset_autosave_timer );
xset_autosave_timer = 0;
}
char* err_msg = save_settings( main_window );
if ( err_msg )
{
char* msg = g_strdup_printf( _("Error: Unable to save session file\n\n( %s )"), err_msg );
g_free( err_msg );
xset_msg_dialog( GTK_WIDGET( main_window ), GTK_MESSAGE_ERROR, _("Save Session Error"),
NULL, 0, msg, NULL,
"#programfiles-home-session" );
g_free( msg );
}
}
void on_find_file_activate ( GtkMenuItem *menuitem, gpointer user_data )
{
FMMainWindow * main_window = FM_MAIN_WINDOW( user_data );
const char* cwd;
const char* dirs[2];
PtkFileBrowser* file_browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
cwd = ptk_file_browser_get_cwd( file_browser );
dirs[0] = cwd;
dirs[1] = NULL;
fm_find_files( dirs );
}
void on_open_current_folder_as_root ( GtkMenuItem *menuitem,
gpointer user_data )
{
FMMainWindow * main_window = FM_MAIN_WINDOW( user_data );
PtkFileBrowser* file_browser =
PTK_FILE_BROWSER( fm_main_window_get_current_file_browser(
main_window ) );
if ( !file_browser )
return;
// root task
PtkFileTask* task = ptk_file_exec_new( _("Open Root Window"),
ptk_file_browser_get_cwd( file_browser ),
GTK_WIDGET( file_browser ), file_browser->task_view );
char* prog = g_find_program_in_path( g_get_prgname() );
if ( !prog )
prog = g_strdup( g_get_prgname() );
if ( !prog )
prog = g_strdup( "spacefm" );
char* cwd = bash_quote( ptk_file_browser_get_cwd( file_browser ) );
task->task->exec_command = g_strdup_printf( "%s %s", prog, cwd );
g_free( prog );
g_free( cwd );
task->task->exec_as_user = g_strdup( "root" );
task->task->exec_sync = FALSE;
task->task->exec_export = FALSE;
task->task->exec_browser = NULL;
ptk_file_task_run( task );
}
void main_window_open_terminal( FMMainWindow* main_window, gboolean as_root )
{
PtkFileBrowser* file_browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
if ( !file_browser )
return;
GtkWidget* parent = gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) );
char* main_term = xset_get_s( "main_terminal" );
if ( !main_term || main_term[0] == '\0' )
{
ptk_show_error( GTK_WINDOW( parent ),
_("Terminal Not Available"),
_( "Please set your terminal program in View|Preferences|Advanced" ) );
fm_edit_preference( (GtkWindow*)parent, PREF_ADVANCED );
main_term = xset_get_s( "main_terminal" );
if ( !main_term || main_term[0] == '\0' )
return;
}
// task
char* terminal = g_find_program_in_path( main_term );
if ( !terminal )
terminal = g_strdup( main_term );
PtkFileTask* task = ptk_file_exec_new( _("Open Terminal"),
ptk_file_browser_get_cwd( file_browser ),
GTK_WIDGET( file_browser ), file_browser->task_view );\
task->task->exec_command = terminal;
task->task->exec_as_user = as_root ? g_strdup( "root" ) : NULL;
task->task->exec_sync = FALSE;
task->task->exec_export = TRUE;
task->task->exec_browser = file_browser;
ptk_file_task_run( task );
}
void on_open_terminal_activate ( GtkMenuItem *menuitem,
gpointer user_data )
{
FMMainWindow * main_window = FM_MAIN_WINDOW( user_data );
main_window_open_terminal( main_window, FALSE );
}
void on_open_root_terminal_activate ( GtkMenuItem *menuitem,
gpointer user_data )
{
FMMainWindow * main_window = FM_MAIN_WINDOW( user_data );
main_window_open_terminal( main_window, TRUE );
}
void on_quit_activate( GtkMenuItem *menuitem, gpointer user_data )
{
fm_main_window_delete_event( user_data, NULL );
//fm_main_window_close( GTK_WIDGET( user_data ) );
}
void main_window_rubberband_all()
{
GList* l;
FMMainWindow* main_window;
PtkFileBrowser* a_browser;
int num_pages, i, p;
GtkWidget* notebook;
for ( l = all_windows; l; l = l->next )
{
main_window = (FMMainWindow*)l->data;
for ( p = 1; p < 5; p++ )
{
notebook = main_window->panel[p-1];
num_pages = gtk_notebook_get_n_pages( GTK_NOTEBOOK( notebook ) );
for ( i = 0; i < num_pages; i++ )
{
a_browser = PTK_FILE_BROWSER( gtk_notebook_get_nth_page(
GTK_NOTEBOOK( notebook ), i ) );
if ( a_browser->view_mode == PTK_FB_LIST_VIEW )
{
gtk_tree_view_set_rubber_banding( (GtkTreeView*)a_browser->folder_view,
xset_get_b( "rubberband" ) );
}
}
}
}
}
void main_window_refresh_all()
{
GList* l;
FMMainWindow* main_window;
PtkFileBrowser* a_browser;
int num_pages, i, p;
GtkWidget* notebook;
for ( l = all_windows; l; l = l->next )
{
main_window = (FMMainWindow*)l->data;
for ( p = 1; p < 5; p++ )
{
notebook = main_window->panel[p-1];
num_pages = gtk_notebook_get_n_pages( GTK_NOTEBOOK( notebook ) );
for ( i = 0; i < num_pages; i++ )
{
a_browser = PTK_FILE_BROWSER( gtk_notebook_get_nth_page(
GTK_NOTEBOOK( notebook ), i ) );
ptk_file_browser_refresh( NULL, a_browser );
}
}
}
}
void main_window_root_bar_all()
{
if ( geteuid() != 0 )
return;
GList* l;
FMMainWindow* a_window;
GdkColor color;
//GdkColor color_white;
if ( xset_get_b( "root_bar" ) )
{
color.pixel = 0;
color.red = 30000;
color.blue = 1000;
color.green = 0;
//gdk_color_parse( "#ffffff", &color_white );
for ( l = all_windows; l; l = l->next )
{
a_window = (FMMainWindow*)l->data;
gtk_widget_modify_bg( GTK_WIDGET( a_window ), GTK_STATE_NORMAL, &color );
gtk_widget_modify_bg( GTK_WIDGET( a_window->menu_bar ),
GTK_STATE_NORMAL, &color );
gtk_widget_modify_bg( GTK_WIDGET( a_window->panelbar ),
GTK_STATE_NORMAL, &color );
// how to change menu bar text color?
//gtk_widget_modify_fg( GTK_MENU_ITEM( a_window->file_menu_item ), GTK_STATE_NORMAL, &color_white );
}
}
else
{
for ( l = all_windows; l; l = l->next )
{
a_window = (FMMainWindow*)l->data;
gtk_widget_modify_bg( GTK_WIDGET( a_window ), GTK_STATE_NORMAL, NULL );
gtk_widget_modify_bg( GTK_WIDGET( a_window->menu_bar ),
GTK_STATE_NORMAL, NULL );
gtk_widget_modify_bg( GTK_WIDGET( a_window->panelbar ),
GTK_STATE_NORMAL, NULL );
//gtk_widget_modify_fg( a_window->menu_bar, GTK_STATE_NORMAL, NULL );
}
}
}
void main_update_fonts( GtkWidget* widget, PtkFileBrowser* file_browser )
{
PtkFileBrowser* a_browser;
int i;
char* fontname;
PangoFontDescription* font_desc;
GList* l;
FMMainWindow* main_window;
int num_pages;
GtkWidget* label;
GtkContainer* hbox;
GtkLabel* text;
GList* children;
GtkImage* icon;
GtkWidget* tab_label;
XSet* set;
char* icon_name;
int p = file_browser->mypanel;
// all windows/panel p/all browsers
for ( l = all_windows; l; l = l->next )
{
main_window = (FMMainWindow*)l->data;
set = xset_get_panel( p, "icon_status" );
if ( set->icon && set->icon[0] != '\0' )
icon_name = set->icon;
else
icon_name = "gtk-yes";
num_pages = gtk_notebook_get_n_pages( GTK_NOTEBOOK( main_window->panel[p-1] ) );
for ( i = 0; i < num_pages; i++ )
{
a_browser = PTK_FILE_BROWSER( gtk_notebook_get_nth_page(
GTK_NOTEBOOK( main_window->panel[p-1] ), i ) );
// file list / tree
fontname = xset_get_s_panel( p, "font_file" );
if ( fontname )
{
font_desc = pango_font_description_from_string( fontname );
gtk_widget_modify_font( GTK_WIDGET( a_browser->folder_view ),
font_desc );
/*
if ( a_browser->view_mode != PTK_FB_LIST_VIEW )
{
//FIXME: need to trigger update of exo icon view for gtk2 for current tab
// or font is not updated for current tab
gtk_widget_queue_draw( GTK_WIDGET( a_browser->folder_view ) );
}
*/
if ( a_browser->side_dir )
gtk_widget_modify_font( GTK_WIDGET( a_browser->side_dir ),
font_desc );
pango_font_description_free( font_desc );
}
else
{
gtk_widget_modify_font( GTK_WIDGET( a_browser->folder_view ), NULL );
if ( a_browser->side_dir )
gtk_widget_modify_font( GTK_WIDGET( a_browser->side_dir ), NULL );
}
// devices
if ( a_browser->side_dev )
{
fontname = xset_get_s_panel( p, "font_dev" );
if ( fontname )
{
font_desc = pango_font_description_from_string( fontname );
gtk_widget_modify_font( GTK_WIDGET( a_browser->side_dev ),
font_desc );
pango_font_description_free( font_desc );
}
else
gtk_widget_modify_font( GTK_WIDGET( a_browser->side_dev ), NULL );
}
// bookmarks
if ( a_browser->side_book )
{
fontname = xset_get_s_panel( p, "font_book" );
if ( fontname )
{
font_desc = pango_font_description_from_string( fontname );
gtk_widget_modify_font( GTK_WIDGET( a_browser->side_book ),
font_desc );
pango_font_description_free( font_desc );
}
else
gtk_widget_modify_font( GTK_WIDGET( a_browser->side_book ),
NULL );
}
// pathbar
if ( a_browser->path_bar )
{
fontname = xset_get_s_panel( p, "font_path" );
if ( fontname )
{
font_desc = pango_font_description_from_string( fontname );
gtk_widget_modify_font( GTK_WIDGET( a_browser->path_bar ),
font_desc );
pango_font_description_free( font_desc );
}
else
gtk_widget_modify_font( GTK_WIDGET( a_browser->path_bar ),
NULL );
}
// status bar font and icon
if ( a_browser->status_label )
{
fontname = xset_get_s_panel( p, "font_status" );
if ( fontname )
{
font_desc = pango_font_description_from_string( fontname );
gtk_widget_modify_font( GTK_WIDGET( a_browser->status_label ),
font_desc );
pango_font_description_free( font_desc );
}
else
gtk_widget_modify_font( GTK_WIDGET( a_browser->status_label ),
NULL );
gtk_image_set_from_icon_name( GTK_IMAGE( a_browser->status_image ),
icon_name, GTK_ICON_SIZE_MENU );
}
// tabs
// need to recreate to change icon
tab_label = fm_main_window_create_tab_label( main_window,
a_browser );
gtk_notebook_set_tab_label( GTK_NOTEBOOK( main_window->panel[p-1] ),
GTK_WIDGET(a_browser), tab_label );
// not needed?
//fm_main_window_update_tab_label( main_window, a_browser,
// a_browser->dir->disp_path );
}
// tasks
fontname = xset_get_s( "font_task" );
if ( fontname )
{
font_desc = pango_font_description_from_string( fontname );
gtk_widget_modify_font( GTK_WIDGET( main_window->task_view ), font_desc );
pango_font_description_free( font_desc );
}
else
gtk_widget_modify_font( GTK_WIDGET( main_window->task_view ), NULL );
// panelbar
gtk_image_set_from_icon_name( GTK_IMAGE( main_window->panel_image[p-1] ),
icon_name, GTK_ICON_SIZE_MENU );
}
}
void update_window_icon( GtkWindow* window, GtkIconTheme* theme )
{
GdkPixbuf* icon;
char* name;
XSet* set = xset_get( "main_icon" );
if ( set->icon )
name = set->icon;
else if ( geteuid() == 0 )
name = "spacefm-root";
else
name = "spacefm";
icon = gtk_icon_theme_load_icon( theme, name, 48, 0, NULL );
if ( icon )
{
gtk_window_set_icon( window, icon );
g_object_unref( icon );
}
}
static void update_window_icons( GtkIconTheme* theme, GtkWindow* window )
{
g_list_foreach( all_windows, (GFunc)update_window_icon, theme );
}
void on_main_icon()
{
GList* l;
FMMainWindow* a_window;
for ( l = all_windows; l; l = l->next )
{
a_window = (FMMainWindow*)l->data;
update_window_icon( GTK_WINDOW( a_window ), gtk_icon_theme_get_default() );
}
}
void main_design_mode( GtkMenuItem *menuitem, FMMainWindow* main_window )
{
xset_msg_dialog( GTK_WIDGET( main_window ), 0, _("Design Mode Help"), NULL, 0, _("Design Mode allows you to change the name, shortcut key and icon of menu items, show help for an item, and add your own custom commands to most menus.\n\nTo open the design menu, simply right-click on a menu item.\n\nTo use Design Mode on a submenu, you must first close the submenu (by clicking on it). The Bookmarks menu does not support Design Mode.\n\nTo modify a toolbar, click the leftmost tool icon to open the toolbar config menu and select Help."), NULL, "#designmode" );
}
void rebuild_toolbar_all_windows( int job, PtkFileBrowser* file_browser )
{
GList* l;
FMMainWindow* a_window;
PtkFileBrowser* a_browser;
GtkWidget* notebook;
int cur_tabx, p;
int pages;
char* disp_path;
//printf("rebuild_toolbar_all_windows\n");
// do this browser first
if ( file_browser )
{
if ( job == 0 && xset_get_b_panel( file_browser->mypanel, "show_toolbox" ) )
{
ptk_file_browser_rebuild_toolbox( NULL, file_browser );
disp_path = g_filename_display_name( ptk_file_browser_get_cwd( file_browser ) );
gtk_entry_set_text( GTK_ENTRY( file_browser->path_bar ), disp_path );
g_free( disp_path );
}
else if ( job == 1 && xset_get_b_panel( file_browser->mypanel, "show_sidebar" ) )
ptk_file_browser_rebuild_side_toolbox( NULL, file_browser );
}
// do all windows all panels all tabs
for ( l = all_windows; l; l = l->next )
{
a_window = (FMMainWindow*)l->data;
for ( p = 1; p < 5; p++ )
{
notebook = a_window->panel[p-1];
pages = gtk_notebook_get_n_pages( GTK_NOTEBOOK( notebook ) );
for ( cur_tabx = 0; cur_tabx < pages; cur_tabx++ )
{
a_browser = PTK_FILE_BROWSER( gtk_notebook_get_nth_page(
GTK_NOTEBOOK( notebook ), cur_tabx ) );
if ( a_browser != file_browser )
{
if ( job == 0 && a_browser->toolbar )
{
ptk_file_browser_rebuild_toolbox( NULL, a_browser );
disp_path = g_filename_display_name( ptk_file_browser_get_cwd( a_browser ) );
gtk_entry_set_text( GTK_ENTRY( a_browser->path_bar ), disp_path );
g_free( disp_path );
}
else if ( job == 1 && a_browser->side_toolbar )
ptk_file_browser_rebuild_side_toolbox( NULL, a_browser );
}
}
}
}
xset_autosave( file_browser );
}
void update_views_all_windows( GtkWidget* item, PtkFileBrowser* file_browser )
{
GList* l;
FMMainWindow* a_window;
PtkFileBrowser* a_browser;
GtkWidget* notebook;
int cur_tabx, p;
//printf("update_views_all_windows\n");
// do this browser first
p = file_browser->mypanel;
// PROBLEM: this may allow close events to destroy fb, so make sure its
// still a widget after this
ptk_file_browser_update_views( NULL, file_browser );
// do other windows
for ( l = all_windows; l; l = l->next )
{
a_window = (FMMainWindow*)l->data;
if ( gtk_widget_get_visible( a_window->panel[p-1] ) )
{
notebook = a_window->panel[p-1];
cur_tabx = gtk_notebook_get_current_page( GTK_NOTEBOOK( notebook ) );
if ( cur_tabx != -1 )
{
a_browser = PTK_FILE_BROWSER( gtk_notebook_get_nth_page(
GTK_NOTEBOOK( notebook ), cur_tabx ) );
if ( a_browser != file_browser )
{
ptk_file_browser_update_views( NULL, a_browser );
}
}
}
}
xset_autosave( file_browser );
}
void focus_panel( GtkMenuItem* item, gpointer mw, int p )
{
int panel, hidepanel;
int panel_num;
FMMainWindow* main_window = (FMMainWindow*)mw;
if ( item )
panel_num = GPOINTER_TO_INT( g_object_get_data( G_OBJECT( item ),
"panel_num" ) );
else
panel_num = p;
if ( panel_num == -1 ) // prev
{
panel = main_window->curpanel - 1;
do
{
if ( panel < 1 )
panel = 4;
if ( xset_get_b_panel( panel, "show" ) )
break;
panel--;
} while ( panel != main_window->curpanel - 1 );
}
else if ( panel_num == -2 ) // next
{
panel = main_window->curpanel + 1;
do
{
if ( panel > 4 )
panel = 1;
if ( xset_get_b_panel( panel, "show" ) )
break;
panel++;
} while ( panel != main_window->curpanel + 1 );
}
else if ( panel_num == -3 ) // hide
{
hidepanel = main_window->curpanel;
panel = main_window->curpanel + 1;
do
{
if ( panel > 4 )
panel = 1;
if ( xset_get_b_panel( panel, "show" ) )
break;
panel++;
} while ( panel != hidepanel );
if ( panel == hidepanel )
panel = 0;
}
else
panel = panel_num;
if ( panel > 0 && panel < 5 )
{
if ( gtk_widget_get_visible( main_window->panel[panel-1] ) )
{
gtk_widget_grab_focus( GTK_WIDGET( main_window->panel[panel-1] ) );
main_window->curpanel = panel;
main_window->notebook = main_window->panel[panel-1];
PtkFileBrowser* file_browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
if ( file_browser )
{
gtk_widget_grab_focus( GTK_WIDGET( file_browser->folder_view ) );
set_panel_focus( main_window, file_browser );
}
}
else if ( panel_num != -3 )
{
xset_set_b_panel( panel, "show", TRUE );
show_panels_all_windows( NULL, main_window );
gtk_widget_grab_focus( GTK_WIDGET( main_window->panel[panel-1] ) );
main_window->curpanel = panel;
main_window->notebook = main_window->panel[panel-1];
PtkFileBrowser* file_browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
if ( file_browser )
{
gtk_widget_grab_focus( GTK_WIDGET( file_browser->folder_view ) );
set_panel_focus( main_window, file_browser );
}
}
if ( panel_num == -3 )
{
xset_set_b_panel( hidepanel, "show", FALSE );
show_panels_all_windows( NULL, main_window );
}
}
}
void show_panels_all_windows( GtkMenuItem* item, FMMainWindow* main_window )
{
GList* l;
FMMainWindow* a_window;
// do this window first
show_panels( NULL, main_window );
// do other windows
for ( l = all_windows; l; l = l->next )
{
a_window = (FMMainWindow*)l->data;
if ( main_window != a_window )
show_panels( NULL, a_window );
}
PtkFileBrowser* file_browser =
(PtkFileBrowser*)fm_main_window_get_current_file_browser( main_window );
xset_autosave( file_browser );
}
void show_panels( GtkMenuItem* item, FMMainWindow* main_window )
{
int p, cur_tabx, i;
const char* folder_path;
XSet* set;
char* tabs;
char* end;
char* tab_dir;
char* tabs_add;
gboolean tab_added;
PtkFileBrowser* file_browser;
// show panelbar
if ( !!gtk_widget_get_visible( main_window->panelbar ) != !!xset_get_b( "main_pbar" ) )
{
if ( xset_get_b( "main_pbar" ) )
gtk_widget_show( GTK_WIDGET( main_window->panelbar ) );
else
gtk_widget_hide( GTK_WIDGET( main_window->panelbar ) );
}
// all panels hidden?
for ( p = 1 ; p < 5; p++ )
{
if ( xset_get_b_panel( p, "show" ) )
break;
}
if ( p == 5 )
xset_set_b_panel( 1, "show", TRUE );
for ( p = 1 ; p < 5; p++ )
{
if ( xset_get_b_panel( p, "show" ) )
{
if ( !gtk_notebook_get_n_pages( GTK_NOTEBOOK( main_window->panel[p-1] ) ) )
{
main_window->notebook = main_window->panel[p-1];
main_window->curpanel = p;
// load saved tabs
tab_added = FALSE;
set = xset_get_panel( p, "show" );
if ( ( set->s && app_settings.load_saved_tabs ) || set->ob1 )
{
// set->ob1 is preload path
tabs_add = g_strdup_printf( "%s%s%s",
set->s && app_settings.load_saved_tabs ? set->s : "",
set->ob1 ? "///" : "",
set->ob1 ? set->ob1 : "" );
tabs = tabs_add;
while ( tabs && !strncmp( tabs, "///", 3 ) )
{
tabs += 3;
if ( !strncmp( tabs, "////", 4 ) )
{
tab_dir = g_strdup( "/" );
tabs++;
}
else if ( end = strstr( tabs, "///" ) )
{
end[0] = '\0';
tab_dir = g_strdup( tabs );
end[0] = '/';
tabs = end;
}
else
{
tab_dir = g_strdup( tabs );
tabs = NULL;
}
if ( tab_dir[0] != '\0' )
{
// open saved tab
if ( g_file_test( tab_dir, G_FILE_TEST_IS_DIR ) )
folder_path = tab_dir;
else if ( !( folder_path = xset_get_s( "go_set_default" ) ) )
{
if ( geteuid() != 0 )
folder_path = g_get_home_dir();
else
folder_path = "/";
}
fm_main_window_add_new_tab( main_window, folder_path );
tab_added = TRUE;
}
g_free( tab_dir );
}
if ( set->x && !set->ob1 )
{
// set current tab
cur_tabx = atoi( set->x );
if ( cur_tabx >= 0 && cur_tabx < gtk_notebook_get_n_pages(
GTK_NOTEBOOK( main_window->panel[p-1] ) ) )
{
gtk_notebook_set_current_page( GTK_NOTEBOOK(
main_window->panel[p-1] ), cur_tabx );
file_browser = PTK_FILE_BROWSER(
gtk_notebook_get_nth_page(
GTK_NOTEBOOK( main_window->panel[p-1] ),
cur_tabx ) );
//if ( file_browser->folder_view )
// gtk_widget_grab_focus( file_browser->folder_view );
//printf("call delayed (showpanels) #%d %#x window=%#x\n", cur_tabx, file_browser->folder_view, main_window);
g_idle_add( ( GSourceFunc ) delayed_focus, file_browser->folder_view );
}
}
g_free( set->ob1 );
set->ob1 = NULL;
g_free( tabs_add );
}
if ( !tab_added )
{
// open default tab
if ( !( folder_path = xset_get_s( "go_set_default" ) ) )
{
if ( geteuid() != 0 )
folder_path = g_get_home_dir();
else
folder_path = "/";
}
fm_main_window_add_new_tab( main_window, folder_path );
}
}
if ( ( evt_pnl_show->s || evt_pnl_show->ob2_data ) &&
!gtk_widget_get_visible( GTK_WIDGET( main_window->panel[p-1] ) ) )
main_window_event( main_window, evt_pnl_show, "evt_pnl_show", p,
0, NULL, 0, 0, 0, TRUE );
gtk_widget_show( GTK_WIDGET( main_window->panel[p-1] ) );
if ( !gtk_toggle_tool_button_get_active(
GTK_TOGGLE_TOOL_BUTTON( main_window->panel_btn[p-1] ) ) )
{
g_signal_handlers_block_matched( main_window->panel_btn[p-1],
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_toggle_panelbar, NULL );
gtk_toggle_tool_button_set_active(
GTK_TOGGLE_TOOL_BUTTON( main_window->panel_btn[p-1] ), TRUE );
g_signal_handlers_unblock_matched( main_window->panel_btn[p-1],
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_toggle_panelbar, NULL );
}
}
else
{
if ( ( evt_pnl_show->s || evt_pnl_show->ob2_data ) &&
gtk_widget_get_visible( GTK_WIDGET( main_window->panel[p-1] ) ) )
main_window_event( main_window, evt_pnl_show, "evt_pnl_show", p,
0, NULL, 0, 0, 0, FALSE );
gtk_widget_hide( GTK_WIDGET( main_window->panel[p-1] ) );
if ( gtk_toggle_tool_button_get_active(
GTK_TOGGLE_TOOL_BUTTON( main_window->panel_btn[p-1] ) ) )
{
g_signal_handlers_block_matched( main_window->panel_btn[p-1],
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_toggle_panelbar, NULL );
gtk_toggle_tool_button_set_active(
GTK_TOGGLE_TOOL_BUTTON( main_window->panel_btn[p-1] ), FALSE );
g_signal_handlers_unblock_matched( main_window->panel_btn[p-1],
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_toggle_panelbar, NULL );
}
}
}
if ( xset_get_b_panel( 1, "show" ) || xset_get_b_panel( 2, "show" ) )
gtk_widget_show( GTK_WIDGET( main_window->hpane_top ) );
else
gtk_widget_hide( GTK_WIDGET( main_window->hpane_top ) );
if ( xset_get_b_panel( 3, "show" ) || xset_get_b_panel( 4, "show" ) )
gtk_widget_show( GTK_WIDGET( main_window->hpane_bottom ) );
else
gtk_widget_hide( GTK_WIDGET( main_window->hpane_bottom ) );
// current panel hidden?
if ( !xset_get_b_panel( main_window->curpanel, "show" ) )
{
p = main_window->curpanel + 1;
if ( p > 4 )
p = 1;
while ( p != main_window->curpanel )
{
if ( xset_get_b_panel( p, "show" ) )
{
main_window->curpanel = p;
main_window->notebook = main_window->panel[p-1];
cur_tabx = gtk_notebook_get_current_page( GTK_NOTEBOOK(
main_window->notebook ) );
file_browser = (PtkFileBrowser*)
gtk_notebook_get_nth_page( GTK_NOTEBOOK(
main_window->notebook ),
cur_tabx );
gtk_widget_grab_focus( file_browser->folder_view );
break;
}
p++;
if ( p > 4 )
p = 1;
}
}
set_panel_focus( main_window, NULL );
}
void on_toggle_panelbar( GtkWidget* widget, FMMainWindow* main_window )
{
//printf("on_toggle_panelbar\n" );
int i;
for ( i = 0; i < 4; i++ )
{
if ( widget == main_window->panel_btn[i] )
{
xset_set_b_panel( i+1, "show",
gtk_toggle_tool_button_get_active( GTK_TOGGLE_TOOL_BUTTON( widget ) ) );
break;
}
}
show_panels_all_windows( NULL, main_window );
}
static gboolean on_menu_bar_event( GtkWidget* widget, GdkEvent* event,
FMMainWindow* main_window )
{
rebuild_menus( main_window );
return FALSE;
}
void rebuild_menus( FMMainWindow* main_window )
{
GtkWidget* newmenu;
GtkWidget* submenu;
GtkMenuItem* item;
char* menu_elements;
GtkAccelGroup* accel_group = gtk_accel_group_new();
XSet* set;
//printf("rebuild_menus\n");
PtkFileBrowser* file_browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
if ( !file_browser )
return;
XSetContext* context = xset_context_new();
main_context_fill( file_browser, context );
// File
newmenu = gtk_menu_new();
xset_set_cb( "main_new_window", on_new_window_activate, main_window );
xset_set_cb( "main_root_window", on_open_current_folder_as_root, main_window );
xset_set_cb( "main_search", on_find_file_activate, main_window );
xset_set_cb( "main_terminal", on_open_terminal_activate, main_window );
xset_set_cb( "main_root_terminal", on_open_root_terminal_activate, main_window );
xset_set_cb( "main_save_session", on_save_session, main_window );
xset_set_cb( "main_exit", on_quit_activate, main_window );
menu_elements = g_strdup_printf( "main_search main_terminal main_root_terminal sep_f1 main_new_window main_root_window sep_f2 main_save_session main_save_tabs sep_f3 main_exit" );
xset_add_menu( NULL, file_browser, newmenu, accel_group, menu_elements );
g_free( menu_elements );
gtk_widget_show_all( GTK_WIDGET(newmenu) );
g_signal_connect( newmenu, "key-press-event",
G_CALLBACK( xset_menu_keypress ), NULL );
gtk_menu_item_set_submenu( GTK_MENU_ITEM( main_window->file_menu_item ), newmenu );
// View
newmenu = gtk_menu_new();
xset_set_cb( "main_prefs", on_preference_activate, main_window );
xset_set_cb( "font_task", main_update_fonts, file_browser );
xset_set_cb( "main_full", on_fullscreen_activate, main_window );
xset_set_cb( "main_design_mode", main_design_mode, main_window );
xset_set_cb( "main_icon", on_main_icon, NULL );
xset_set_cb( "main_title", update_window_title, main_window );
menu_elements = g_strdup_printf( "panel1_show panel2_show panel3_show panel4_show main_pbar main_focus_panel sep_v1 main_tasks main_auto sep_v2 main_title main_icon sep_v3 main_full main_design_mode main_prefs" );
int p;
int vis_count = 0;
for ( p = 1 ; p < 5; p++ )
{
if ( xset_get_b_panel( p, "show" ) )
vis_count++;
}
if ( !vis_count )
{
xset_set_b_panel( 1, "show", TRUE );
vis_count++;
}
set = xset_set_cb( "panel1_show", show_panels_all_windows, main_window );
set->disable = ( main_window->curpanel == 1 && vis_count == 1 );
set = xset_set_cb( "panel2_show", show_panels_all_windows, main_window );
set->disable = ( main_window->curpanel == 2 && vis_count == 1 );
set = xset_set_cb( "panel3_show", show_panels_all_windows, main_window );
set->disable = ( main_window->curpanel == 3 && vis_count == 1 );
set = xset_set_cb( "panel4_show", show_panels_all_windows, main_window );
set->disable = ( main_window->curpanel == 4 && vis_count == 1 );
xset_set_cb( "main_pbar", show_panels_all_windows, main_window );
set = xset_set_cb( "panel_prev", focus_panel, main_window );
xset_set_ob1_int( set, "panel_num", -1 );
set->disable = ( vis_count == 1 );
set = xset_set_cb( "panel_next", focus_panel, main_window );
xset_set_ob1_int( set, "panel_num", -2 );
set->disable = ( vis_count == 1 );
set = xset_set_cb( "panel_hide", focus_panel, main_window );
xset_set_ob1_int( set, "panel_num", -3 );
set->disable = ( vis_count == 1 );
set = xset_set_cb( "panel_1", focus_panel, main_window );
xset_set_ob1_int( set, "panel_num", 1 );
set->disable = ( main_window->curpanel == 1 );
set = xset_set_cb( "panel_2", focus_panel, main_window );
xset_set_ob1_int( set, "panel_num", 2 );
set->disable = ( main_window->curpanel == 2 );
set = xset_set_cb( "panel_3", focus_panel, main_window );
xset_set_ob1_int( set, "panel_num", 3 );
set->disable = ( main_window->curpanel == 3 );
set = xset_set_cb( "panel_4", focus_panel, main_window );
xset_set_ob1_int( set, "panel_num", 4 );
set->disable = ( main_window->curpanel == 4 );
main_task_prepare_menu( main_window, newmenu, accel_group );
xset_add_menu( NULL, file_browser, newmenu, accel_group, menu_elements );
g_free( menu_elements );
gtk_widget_show_all( GTK_WIDGET(newmenu) );
g_signal_connect( newmenu, "key-press-event",
G_CALLBACK( xset_menu_keypress ), NULL );
gtk_menu_item_set_submenu( GTK_MENU_ITEM( main_window->view_menu_item ), newmenu );
// Devices
main_window->dev_menu = create_devices_menu( main_window );
gtk_menu_item_set_submenu( GTK_MENU_ITEM( main_window->dev_menu_item ),
main_window->dev_menu );
// Bookmarks
if ( !main_window->book_menu )
{
main_window->book_menu = create_bookmarks_menu( main_window );
gtk_menu_item_set_submenu( GTK_MENU_ITEM( main_window->book_menu_item ),
main_window->book_menu );
}
// Plugins
main_window->plug_menu = create_plugins_menu( main_window );
gtk_menu_item_set_submenu( GTK_MENU_ITEM( main_window->plug_menu_item ),
main_window->plug_menu );
g_signal_connect( main_window->plug_menu, "key-press-event",
G_CALLBACK( xset_menu_keypress ), NULL );
// Tool
XSet* child_set;
newmenu = gtk_menu_new();
set = xset_get( "main_tool" );
if ( !set->child )
{
child_set = xset_custom_new();
child_set->menu_label = g_strdup_printf( _("New _Command") );
child_set->parent = g_strdup_printf( "main_tool" );
set->child = g_strdup( child_set->name );
}
else
child_set = xset_get( set->child );
xset_add_menuitem( NULL, file_browser, newmenu, accel_group, child_set );
gtk_widget_show_all( GTK_WIDGET(newmenu) );
g_signal_connect( newmenu, "key-press-event",
G_CALLBACK( xset_menu_keypress ), NULL );
gtk_menu_item_set_submenu( GTK_MENU_ITEM( main_window->tool_menu_item ), newmenu );
// Help
newmenu = gtk_menu_new();
xset_set_cb( "main_faq", on_main_faq, main_window );
xset_set_cb( "main_about", on_about_activate, main_window );
xset_set_cb( "main_help", on_main_help_activate, main_window );
xset_set_cb( "main_homepage", on_homepage_activate, main_window );
xset_set_cb( "main_news", on_news_activate, main_window );
xset_set_cb( "main_getplug", on_getplug_activate, main_window );
menu_elements = g_strdup_printf( "main_faq main_help sep_h1 main_homepage main_news main_getplug sep_h2 main_help_opt sep_h3 main_about" );
xset_add_menu( NULL, file_browser, newmenu, accel_group, menu_elements );
g_free( menu_elements );
gtk_widget_show_all( GTK_WIDGET(newmenu) );
g_signal_connect( newmenu, "key-press-event",
G_CALLBACK( xset_menu_keypress ), NULL );
gtk_menu_item_set_submenu( GTK_MENU_ITEM( main_window->help_menu_item ), newmenu );
//printf("rebuild_menus DONE\n");
}
void fm_main_window_init( FMMainWindow* main_window )
{
GtkWidget *bookmark_menu;
//GtkWidget *view_menu_item;
GtkWidget *edit_menu_item, *edit_menu, *history_menu;
GtkToolItem *toolitem;
GtkWidget *hbox;
GtkLabel *label;
GtkAccelGroup *edit_accel_group;
GClosure* closure;
int i;
char* icon_name;
XSet* set;
/* this is used to limit the scope of gtk_grab and modal dialogs */
main_window->wgroup = gtk_window_group_new();
gtk_window_group_add_window( main_window->wgroup, (GtkWindow*)main_window );
/* Add to total window count */
++n_windows;
all_windows = g_list_prepend( all_windows, main_window );
pcmanfm_ref();
//g_signal_connect( G_OBJECT( main_window ), "task-notify",
// G_CALLBACK( ptk_file_task_notify_handler ), NULL );
/* Start building GUI */
/*
NOTE: gtk_window_set_icon_name doesn't work under some WMs, such as IceWM.
gtk_window_set_icon_name( GTK_WINDOW( main_window ),
"gnome-fs-directory" ); */
if( 0 == theme_change_notify )
{
theme_change_notify = g_signal_connect( gtk_icon_theme_get_default(), "changed",
G_CALLBACK(update_window_icons), NULL );
}
update_window_icon( (GtkWindow*)main_window, gtk_icon_theme_get_default() );
main_window->main_vbox = gtk_vbox_new ( FALSE, 0 );
gtk_container_add ( GTK_CONTAINER ( main_window ), main_window->main_vbox );
// Create menu bar
main_window->accel_group = gtk_accel_group_new ();
main_window->menu_bar = gtk_menu_bar_new();
//gtk_box_pack_start ( GTK_BOX ( main_window->main_vbox ),
// main_window->menu_bar, FALSE, FALSE, 0 );
GtkWidget* menu_hbox = gtk_hbox_new ( FALSE, 0 );
gtk_box_pack_start ( GTK_BOX ( menu_hbox ),
main_window->menu_bar, TRUE, TRUE, 0 );
// panelbar
main_window->panelbar = gtk_toolbar_new();
#if GTK_CHECK_VERSION (3, 0, 0)
GtkStyleContext *style_ctx = gtk_widget_get_style_context( main_window->panelbar );
gtk_style_context_add_class (style_ctx, GTK_STYLE_CLASS_MENUBAR);
gtk_style_context_remove_class (style_ctx, GTK_STYLE_CLASS_TOOLBAR);
#endif
gtk_toolbar_set_show_arrow( GTK_TOOLBAR( main_window->panelbar ), FALSE );
gtk_toolbar_set_style( GTK_TOOLBAR( main_window->panelbar ), GTK_TOOLBAR_ICONS );
gtk_toolbar_set_icon_size( GTK_TOOLBAR( main_window->panelbar ), GTK_ICON_SIZE_MENU );
// set pbar background to menu bar background
//gtk_widget_modify_bg( main_window->panelbar, GTK_STATE_NORMAL,
// >K_WIDGET( main_window )
// ->style->bg[ GTK_STATE_NORMAL ] );
for ( i = 0; i < 4; i++ )
{
main_window->panel_btn[i] = GTK_WIDGET( gtk_toggle_tool_button_new() );
icon_name = g_strdup_printf( _("Show Panel %d"), i + 1 );
gtk_tool_button_set_label( GTK_TOOL_BUTTON( main_window->panel_btn[i] ),
icon_name );
g_free( icon_name );
set = xset_get_panel( i + 1, "icon_status" );
if ( set->icon && set->icon[0] != '\0' )
icon_name = set->icon;
else
icon_name = "gtk-yes";
main_window->panel_image[i] = xset_get_image( icon_name, GTK_ICON_SIZE_MENU );
gtk_tool_button_set_icon_widget( GTK_TOOL_BUTTON( main_window->panel_btn[i] ),
main_window->panel_image[i] );
gtk_toolbar_insert( GTK_TOOLBAR( main_window->panelbar ),
GTK_TOOL_ITEM( main_window->panel_btn[i] ), -1 );
g_signal_connect( main_window->panel_btn[i], "toggled",
G_CALLBACK( on_toggle_panelbar ), main_window );
if ( i == 1 )
{
GtkToolItem* sep = gtk_separator_tool_item_new();
gtk_separator_tool_item_set_draw( GTK_SEPARATOR_TOOL_ITEM( sep ), TRUE );
gtk_toolbar_insert( GTK_TOOLBAR( main_window->panelbar ), sep, -1 );
}
}
gtk_box_pack_start ( GTK_BOX ( menu_hbox ),
main_window->panelbar, TRUE, TRUE, 0 );
gtk_box_pack_start ( GTK_BOX ( main_window->main_vbox ),
menu_hbox, FALSE, FALSE, 0 );
main_window->file_menu_item = gtk_menu_item_new_with_mnemonic( _("_File") );
gtk_menu_shell_append( GTK_MENU_SHELL( main_window->menu_bar ), main_window->file_menu_item );
main_window->view_menu_item = gtk_menu_item_new_with_mnemonic( _("_View") );
gtk_menu_shell_append( GTK_MENU_SHELL( main_window->menu_bar ), main_window->view_menu_item );
main_window->dev_menu_item = gtk_menu_item_new_with_mnemonic( _("_Devices") );
gtk_menu_shell_append( GTK_MENU_SHELL( main_window->menu_bar ), main_window->dev_menu_item );
main_window->dev_menu = NULL;
main_window->book_menu_item = gtk_menu_item_new_with_mnemonic( _("_Bookmarks") );
gtk_menu_shell_append( GTK_MENU_SHELL( main_window->menu_bar ), main_window->book_menu_item );
main_window->book_menu = NULL;
// Set a monitor for changes of the bookmarks
ptk_bookmarks_add_callback( ( GFunc ) on_bookmarks_change, main_window );
main_window->plug_menu_item = gtk_menu_item_new_with_mnemonic( _("_Plugins") );
gtk_menu_shell_append( GTK_MENU_SHELL( main_window->menu_bar ), main_window->plug_menu_item );
main_window->plug_menu = NULL;
main_window->tool_menu_item = gtk_menu_item_new_with_mnemonic( _("_Tools") );
gtk_menu_shell_append( GTK_MENU_SHELL( main_window->menu_bar ), main_window->tool_menu_item );
main_window->help_menu_item = gtk_menu_item_new_with_mnemonic( _("_Help") );
gtk_menu_shell_append( GTK_MENU_SHELL( main_window->menu_bar ), main_window->help_menu_item );
rebuild_menus( main_window );
/*
#ifdef SUPER_USER_CHECKS
// Create warning bar for super user
if ( geteuid() == 0 ) // Run as super user!
{
main_window->status_bar = gtk_event_box_new();
gtk_widget_modify_bg( main_window->status_bar, GTK_STATE_NORMAL,
&main_window->status_bar->style->bg[ GTK_STATE_SELECTED ] );
label = GTK_LABEL( gtk_label_new ( _( "Warning: You are in super user mode" ) ) );
gtk_misc_set_padding( GTK_MISC( label ), 0, 2 );
gtk_widget_modify_fg( GTK_WIDGET( label ), GTK_STATE_NORMAL,
>K_WIDGET( label ) ->style->fg[ GTK_STATE_SELECTED ] );
gtk_container_add( GTK_CONTAINER( main_window->status_bar ), GTK_WIDGET( label ) );
gtk_box_pack_start ( GTK_BOX ( main_window->main_vbox ),
main_window->status_bar, FALSE, FALSE, 2 );
}
#endif
*/
/* Create client area */
main_window->task_vpane = gtk_vpaned_new();
main_window->vpane = gtk_vpaned_new();
main_window->hpane_top = gtk_hpaned_new();
main_window->hpane_bottom = gtk_hpaned_new();
for ( i = 0; i < 4; i++ )
{
main_window->panel[i] = gtk_notebook_new();
gtk_notebook_set_show_border( GTK_NOTEBOOK( main_window->panel[i] ), FALSE );
gtk_notebook_set_scrollable ( GTK_NOTEBOOK( main_window->panel[i] ), TRUE );
g_signal_connect ( main_window->panel[i], "switch-page",
G_CALLBACK ( on_folder_notebook_switch_pape ), main_window );
// create dynamic copies of panel slider positions
main_window->panel_slide_x[i] = xset_get_int_panel( i + 1,
"slider_positions", "x" );
main_window->panel_slide_y[i] = xset_get_int_panel( i + 1,
"slider_positions", "y" );
main_window->panel_slide_s[i] = xset_get_int_panel( i + 1,
"slider_positions", "s" );
}
main_window->task_scroll = gtk_scrolled_window_new( NULL, NULL );
gtk_paned_pack1( GTK_PANED(main_window->hpane_top), main_window->panel[0],
TRUE, TRUE );
gtk_paned_pack2( GTK_PANED(main_window->hpane_top), main_window->panel[1],
TRUE, TRUE );
gtk_paned_pack1( GTK_PANED(main_window->hpane_bottom), main_window->panel[2],
TRUE, TRUE );
gtk_paned_pack2( GTK_PANED(main_window->hpane_bottom), main_window->panel[3],
TRUE, TRUE );
gtk_paned_pack1( GTK_PANED(main_window->vpane), main_window->hpane_top,
TRUE, TRUE );
gtk_paned_pack2( GTK_PANED(main_window->vpane), main_window->hpane_bottom,
TRUE, TRUE );
gtk_paned_pack1( GTK_PANED(main_window->task_vpane), main_window->vpane,
TRUE, TRUE );
gtk_paned_pack2( GTK_PANED(main_window->task_vpane), main_window->task_scroll,
TRUE, TRUE );
gtk_box_pack_start ( GTK_BOX ( main_window->main_vbox ),
GTK_WIDGET( main_window->task_vpane ), TRUE, TRUE, 0 );
int pos = xset_get_int( "panel_sliders", "x" );
if ( pos < 150 ) pos = -1;
gtk_paned_set_position( GTK_PANED( main_window->hpane_top ), pos );
pos = xset_get_int( "panel_sliders", "y" );
if ( pos < 150 ) pos = -1;
gtk_paned_set_position( GTK_PANED( main_window->hpane_bottom ), pos );
pos = xset_get_int( "panel_sliders", "s" );
if ( pos < 200 ) pos = -1;
gtk_paned_set_position( GTK_PANED( main_window->vpane ), pos );
pos = xset_get_int( "panel_sliders", "z" );
if ( pos < 200 ) pos = 300;
gtk_paned_set_position( GTK_PANED( main_window->task_vpane ), pos );
main_window->notebook = main_window->panel[0];
main_window->curpanel = 1;
/* GTK_NOTEBOOK( gtk_notebook_new() );
gtk_notebook_set_show_border( main_window->notebook, FALSE );
gtk_notebook_set_scrollable ( main_window->notebook, TRUE );
gtk_box_pack_start ( GTK_BOX ( main_window->main_vbox ), GTK_WIDGET( main_window->notebook ), TRUE, TRUE, 0 );
*/
/*
// Create Status bar
main_window->status_bar = gtk_statusbar_new ();
gtk_box_pack_start ( GTK_BOX ( main_window->main_vbox ),
main_window->status_bar, FALSE, FALSE, 0 );
*/
// Task View
gtk_scrolled_window_set_policy ( GTK_SCROLLED_WINDOW ( main_window->task_scroll ),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC );
main_window->task_view = main_task_view_new( main_window );
gtk_container_add( GTK_CONTAINER( main_window->task_scroll ),
GTK_WIDGET( main_window->task_view ) );
gtk_window_set_role( GTK_WINDOW( main_window ), "file_manager" );
gtk_widget_show_all( main_window->main_vbox );
g_signal_connect( G_OBJECT( main_window->file_menu_item ), "button-press-event",
G_CALLBACK( on_menu_bar_event ), main_window );
g_signal_connect( G_OBJECT( main_window->view_menu_item ), "button-press-event",
G_CALLBACK( on_menu_bar_event ), main_window );
g_signal_connect( G_OBJECT( main_window->dev_menu_item ), "button-press-event",
G_CALLBACK( on_menu_bar_event ), main_window );
g_signal_connect( G_OBJECT( main_window->book_menu_item ), "button-press-event",
G_CALLBACK( on_menu_bar_event ), main_window );
g_signal_connect( G_OBJECT( main_window->plug_menu_item ), "button-press-event",
G_CALLBACK( on_menu_bar_event ), main_window );
g_signal_connect( G_OBJECT( main_window->tool_menu_item ), "button-press-event",
G_CALLBACK( on_menu_bar_event ), main_window );
g_signal_connect( G_OBJECT( main_window->help_menu_item ), "button-press-event",
G_CALLBACK( on_menu_bar_event ), main_window );
// use this OR widget_class->key_press_event = on_main_window_keypress;
g_signal_connect( G_OBJECT( main_window ), "key-press-event",
G_CALLBACK( on_main_window_keypress ), NULL );
g_signal_connect ( main_window, "focus-in-event",
G_CALLBACK ( on_main_window_focus ), NULL );
g_signal_connect( G_OBJECT(main_window), "configure-event",
G_CALLBACK(on_window_configure_event), main_window );
g_signal_connect ( G_OBJECT(main_window), "button-press-event",
G_CALLBACK ( on_window_button_press_event ), main_window );
import_all_plugins( main_window );
on_task_popup_show( NULL, main_window, NULL );
show_panels( NULL, main_window );
main_window_root_bar_all();
main_window_event( main_window, NULL, "evt_win_new", 0, 0, NULL, 0, 0, 0, TRUE );
}
void fm_main_window_finalize( GObject *obj )
{
all_windows = g_list_remove( all_windows, obj );
--n_windows;
g_object_unref( ((FMMainWindow*)obj)->wgroup );
pcmanfm_unref();
/* Remove the monitor for changes of the bookmarks */
// ptk_bookmarks_remove_callback( ( GFunc ) on_bookmarks_change, obj );
if ( 0 == n_windows )
{
g_signal_handler_disconnect( gtk_icon_theme_get_default(), theme_change_notify );
theme_change_notify = 0;
}
G_OBJECT_CLASS( parent_class ) ->finalize( obj );
}
void fm_main_window_get_property ( GObject *obj,
guint prop_id,
GValue *value,
GParamSpec *pspec )
{}
void fm_main_window_set_property ( GObject *obj,
guint prop_id,
const GValue *value,
GParamSpec *pspec )
{}
static void fm_main_window_close( FMMainWindow* main_window )
{
/*
printf("DISC=%d\n", g_signal_handlers_disconnect_by_func(
G_OBJECT( main_window ),
G_CALLBACK( ptk_file_task_notify_handler ), NULL ) );
*/
if ( evt_win_close->s || evt_win_close->ob2_data )
main_window_event( main_window, evt_win_close, "evt_win_close", 0, 0,
NULL, 0, 0, 0, FALSE );
gtk_widget_destroy( GTK_WIDGET( main_window ) );
}
void on_abort_tasks_response( GtkDialog* dlg, int response, GtkWidget* main_window )
{
fm_main_window_close( (FMMainWindow*)main_window );
}
gboolean fm_main_window_delete_event ( GtkWidget *widget,
GdkEvent *event )
{
//printf("fm_main_window_delete_event\n");
FMMainWindow* main_window = (FMMainWindow*)widget;
// store width/height + sliders
int pos;
char* posa;
GtkAllocation allocation;
gtk_widget_get_allocation ( GTK_WIDGET( main_window ) , &allocation );
// fullscreen?
if ( !xset_get_b( "main_full" ) )
{
app_settings.width = allocation.width;
app_settings.height = allocation.height;
if ( GTK_IS_PANED( main_window->hpane_top ) )
{
pos = gtk_paned_get_position( GTK_PANED( main_window->hpane_top ) );
if ( pos )
{
posa = g_strdup_printf( "%d", pos );
xset_set( "panel_sliders", "x", posa );
g_free( posa );
}
pos = gtk_paned_get_position( GTK_PANED( main_window->hpane_bottom ) );
if ( pos )
{
posa = g_strdup_printf( "%d", pos );
xset_set( "panel_sliders", "y", posa );
g_free( posa );
}
pos = gtk_paned_get_position( GTK_PANED( main_window->vpane ) );
if ( pos )
{
posa = g_strdup_printf( "%d", pos );
xset_set( "panel_sliders", "s", posa );
g_free( posa );
}
pos = gtk_paned_get_position( GTK_PANED( main_window->task_vpane ) );
if ( pos )
{
posa = g_strdup_printf( "%d", pos );
xset_set( "panel_sliders", "z", posa );
g_free( posa );
}
}
// store task columns
on_task_columns_changed( main_window->task_view, NULL );
// store fb columns
int p, page_x;
PtkFileBrowser* a_browser;
for ( p = 1; p < 5; p++ )
{
page_x = gtk_notebook_get_current_page( GTK_NOTEBOOK( main_window->panel[p-1] ) );
if ( page_x != -1 )
{
a_browser = PTK_FILE_BROWSER( gtk_notebook_get_nth_page(
GTK_NOTEBOOK( main_window->panel[p-1] ),
page_x ) );
if ( a_browser && a_browser->view_mode == PTK_FB_LIST_VIEW )
on_folder_view_columns_changed(
GTK_TREE_VIEW( a_browser->folder_view ), a_browser );
}
}
}
// save settings
if ( xset_autosave_timer )
{
g_source_remove( xset_autosave_timer );
xset_autosave_timer = 0;
}
char* err_msg = save_settings( main_window );
if ( err_msg )
{
char* msg = g_strdup_printf( _("Error: Unable to save session file. Do you want to exit without saving?\n\n( %s )"), err_msg );
g_free( err_msg );
GtkWidget* dlg = gtk_message_dialog_new( GTK_WINDOW( widget ), GTK_DIALOG_MODAL,
GTK_MESSAGE_ERROR,
GTK_BUTTONS_YES_NO,
msg, NULL );
g_free( msg );
gtk_dialog_set_default_response( GTK_DIALOG( dlg ), GTK_RESPONSE_NO );
gtk_widget_show_all( dlg );
gtk_window_set_title( GTK_WINDOW( dlg ), _("SpaceFM Error") );
if ( gtk_dialog_run( GTK_DIALOG( dlg ) ) == GTK_RESPONSE_NO )
{
gtk_widget_destroy( dlg );
return TRUE;
}
gtk_widget_destroy( dlg );
}
// tasks running?
if ( main_tasks_running( main_window ) )
{
GtkWidget* dlg = gtk_message_dialog_new( GTK_WINDOW( widget ),
GTK_DIALOG_MODAL,
GTK_MESSAGE_QUESTION,
GTK_BUTTONS_YES_NO,
_( "Stop all tasks running in this window?" ) );
gtk_dialog_set_default_response( GTK_DIALOG( dlg ), GTK_RESPONSE_NO );
if ( gtk_dialog_run( GTK_DIALOG( dlg ) ) == GTK_RESPONSE_YES )
{
gtk_widget_destroy( dlg );
dlg = gtk_message_dialog_new( GTK_WINDOW( widget ),
GTK_DIALOG_MODAL,
GTK_MESSAGE_INFO,
GTK_BUTTONS_CLOSE,
_( "Aborting tasks..." ) );
g_signal_connect( dlg, "response",
G_CALLBACK( on_abort_tasks_response ), widget );
g_signal_connect( dlg, "destroy",
G_CALLBACK( gtk_widget_destroy ), dlg );
gtk_widget_show_all( dlg );
on_task_stop( NULL, main_window->task_view, xset_get( "task_stop_all" ),
NULL );
while ( main_tasks_running( main_window ) )
{
while( gtk_events_pending() )
gtk_main_iteration();
}
}
else
{
gtk_widget_destroy( dlg );
return TRUE;
}
}
fm_main_window_close( main_window );
return TRUE;
}
static gboolean fm_main_window_window_state_event ( GtkWidget *widget,
GdkEventWindowState *event )
{
app_settings.maximized = ((event->new_window_state & GDK_WINDOW_STATE_MAXIMIZED) != 0);
return TRUE;
}
char* main_window_get_tab_cwd( PtkFileBrowser* file_browser, int tab_num )
{
if ( !file_browser )
return NULL;
int page_x;
FMMainWindow* main_window = (FMMainWindow*)file_browser->main_window;
GtkWidget* notebook = main_window->panel[file_browser->mypanel - 1];
int pages = gtk_notebook_get_n_pages( GTK_NOTEBOOK( notebook ) );
int page_num = gtk_notebook_page_num( GTK_NOTEBOOK( notebook ),
GTK_WIDGET( file_browser ) );
if ( tab_num == -1 ) // prev
page_x = page_num - 1;
else if ( tab_num == -2 ) // next
page_x = page_num + 1;
else
page_x = tab_num - 1; // tab_num starts counting at 1
if ( page_x > -1 && page_x < pages )
{
return g_strdup( ptk_file_browser_get_cwd( PTK_FILE_BROWSER(
gtk_notebook_get_nth_page( GTK_NOTEBOOK( notebook ),
page_x ) ) ) );
}
else
return NULL;
}
char* main_window_get_panel_cwd( PtkFileBrowser* file_browser, int panel_num )
{
if ( !file_browser )
return NULL;
FMMainWindow* main_window = (FMMainWindow*)file_browser->main_window;
int panel_x = file_browser->mypanel;
if ( panel_num == -1 ) // prev
{
do
{
if ( --panel_x < 1 )
panel_x = 4;
if ( panel_x == file_browser->mypanel )
return NULL;
} while ( !gtk_widget_get_visible( main_window->panel[panel_x - 1] ) );
}
else if ( panel_num == -2 ) // next
{
do
{
if ( ++panel_x > 4 )
panel_x = 1;
if ( panel_x == file_browser->mypanel )
return NULL;
} while ( !gtk_widget_get_visible( main_window->panel[panel_x - 1] ) );
}
else
{
panel_x = panel_num;
if ( !gtk_widget_get_visible( main_window->panel[panel_x - 1] ) )
return NULL;
}
GtkWidget* notebook = main_window->panel[panel_x - 1];
int page_x = gtk_notebook_get_current_page( GTK_NOTEBOOK( notebook ) );
return g_strdup( ptk_file_browser_get_cwd( PTK_FILE_BROWSER( gtk_notebook_get_nth_page(
GTK_NOTEBOOK( notebook ), page_x ) ) ) );
}
void main_window_open_in_panel( PtkFileBrowser* file_browser, int panel_num,
char* file_path )
{
if ( !file_browser )
return;
FMMainWindow* main_window = (FMMainWindow*)file_browser->main_window;
int panel_x = file_browser->mypanel;
if ( panel_num == -1 ) // prev
{
do
{
if ( --panel_x < 1 )
panel_x = 4;
if ( panel_x == file_browser->mypanel )
return;
} while ( !gtk_widget_get_visible( main_window->panel[panel_x - 1] ) );
}
else if ( panel_num == -2 ) // next
{
do
{
if ( ++panel_x > 4 )
panel_x = 1;
if ( panel_x == file_browser->mypanel )
return;
} while ( !gtk_widget_get_visible( main_window->panel[panel_x - 1] ) );
}
else
{
panel_x = panel_num;
}
if ( panel_x < 1 || panel_x > 4 )
return;
// show panel
if ( !gtk_widget_get_visible( main_window->panel[panel_x - 1] ) )
{
xset_set_b_panel( panel_x, "show", TRUE );
show_panels_all_windows( NULL, main_window );
}
// open in tab in panel
int save_curpanel = main_window->curpanel;
main_window->curpanel = panel_x;
main_window->notebook = main_window->panel[panel_x - 1];
fm_main_window_add_new_tab( main_window, file_path );
main_window->curpanel = save_curpanel;
main_window->notebook = main_window->panel[main_window->curpanel - 1];
// focus original panel
//while( gtk_events_pending() )
// gtk_main_iteration();
//gtk_widget_grab_focus( GTK_WIDGET( main_window->notebook ) );
//gtk_widget_grab_focus( GTK_WIDGET( file_browser->folder_view ) );
g_idle_add( ( GSourceFunc ) delayed_focus_file_browser, file_browser );
}
gboolean main_window_panel_is_visible( PtkFileBrowser* file_browser, int panel )
{
if ( panel < 1 || panel > 4 )
return FALSE;
FMMainWindow* main_window = (FMMainWindow*)file_browser->main_window;
return gtk_widget_get_visible( main_window->panel[panel - 1] );
}
void main_window_get_counts( PtkFileBrowser* file_browser, int* panel_count,
int* tab_count, int* tab_num )
{
if ( !file_browser )
return;
FMMainWindow* main_window = (FMMainWindow*)file_browser->main_window;
GtkWidget* notebook = main_window->panel[file_browser->mypanel - 1];
*tab_count = gtk_notebook_get_n_pages( GTK_NOTEBOOK( notebook ) );
// tab_num starts counting from 1
*tab_num = gtk_notebook_page_num( GTK_NOTEBOOK( notebook ),
GTK_WIDGET( file_browser ) ) + 1;
int count = 0;
int i;
for ( i = 0; i < 4; i++ )
{
if ( gtk_widget_get_visible( main_window->panel[i] ) )
count++;
}
*panel_count = count;
}
void on_close_notebook_page( GtkButton* btn, PtkFileBrowser* file_browser )
{
//printf( "\n============== on_close_notebook_page fb=%#x\n", file_browser );
if ( !GTK_IS_WIDGET( file_browser ) )
return;
GtkNotebook* notebook = GTK_NOTEBOOK(
gtk_widget_get_ancestor( GTK_WIDGET( file_browser ),
GTK_TYPE_NOTEBOOK ) );
FMMainWindow* main_window = (FMMainWindow*)file_browser->main_window;
main_window->curpanel = file_browser->mypanel;
main_window->notebook = main_window->panel[main_window->curpanel - 1];
if ( evt_tab_close->s || evt_tab_close->ob2_data )
main_window_event( main_window, evt_tab_close, "evt_tab_close",
file_browser->mypanel,
gtk_notebook_page_num(
GTK_NOTEBOOK( main_window->notebook ),
GTK_WIDGET( file_browser ) ) + 1,
NULL, 0, 0, 0, FALSE );
// save slider positions of tab to be closed
ptk_file_browser_slider_release( NULL, NULL, file_browser );
// without this signal blocked, on_close_notebook_page is called while
// ptk_file_browser_update_views is still in progress causing segfault
g_signal_handlers_block_matched( main_window->notebook,
G_SIGNAL_MATCH_FUNC, 0, 0, NULL, on_folder_notebook_switch_pape, NULL );
// remove page can also be used to destroy - same result
//gtk_notebook_remove_page( notebook, gtk_notebook_get_current_page( notebook ) );
gtk_widget_destroy( GTK_WIDGET( file_browser ) );
if ( !app_settings.always_show_tabs )
{
if ( gtk_notebook_get_n_pages ( notebook ) == 1 )
gtk_notebook_set_show_tabs( notebook, FALSE );
}
if ( gtk_notebook_get_n_pages ( notebook ) == 0 )
{
const char* path = xset_get_s( "go_set_default" );
if ( !( path && path[0] != '\0' ) )
{
if ( geteuid() != 0 )
path = g_get_home_dir();
else
path = "/";
}
fm_main_window_add_new_tab( main_window, path );
goto _done_close;
}
// update view of new current tab
int cur_tabx = gtk_notebook_get_current_page( GTK_NOTEBOOK( main_window->notebook ) );
if ( cur_tabx != -1 )
{
PtkFileBrowser* a_browser = PTK_FILE_BROWSER( gtk_notebook_get_nth_page(
GTK_NOTEBOOK( notebook ), cur_tabx ) );
// PROBLEM: this may allow close events to destroy fb, so make sure its
// still a widget after this
ptk_file_browser_update_views( NULL, a_browser );
if ( GTK_IS_WIDGET( a_browser ) )
{
fm_main_window_update_status_bar( main_window, a_browser );
g_idle_add( ( GSourceFunc ) delayed_focus, a_browser->folder_view );
}
if ( evt_tab_focus->s || evt_tab_focus->ob2_data )
main_window_event( main_window, evt_tab_focus, "evt_tab_focus",
main_window->curpanel,
cur_tabx + 1, NULL, 0, 0, 0, FALSE );
}
_done_close:
g_signal_handlers_unblock_matched( main_window->notebook,
G_SIGNAL_MATCH_FUNC, 0, 0, NULL, on_folder_notebook_switch_pape, NULL );
update_window_title( NULL, main_window );
}
gboolean notebook_clicked (GtkWidget* widget, GdkEventButton * event,
PtkFileBrowser* file_browser) //MOD added
{
on_file_browser_panel_change( file_browser,
(FMMainWindow*)file_browser->main_window );
if ( ( evt_win_click->s || evt_win_click->ob2_data ) &&
main_window_event( file_browser->main_window, evt_win_click, "evt_win_click",
0, 0, "tabbar", 0, event->button, event->state, TRUE ) )
return TRUE;
// middle-click on tab closes
if (event->type == GDK_BUTTON_PRESS)
{
if ( event->button == 2 )
{
on_close_notebook_page( NULL, file_browser );
return TRUE;
}
else if ( event->button == 3 )
{
GtkWidget* popup = gtk_menu_new();
GtkAccelGroup* accel_group = gtk_accel_group_new();
XSetContext* context = xset_context_new();
main_context_fill( file_browser, context );
XSet* set = xset_set_cb( "tab_close",
on_close_notebook_page, file_browser );
xset_add_menuitem( NULL, file_browser, popup, accel_group, set );
set = xset_set_cb( "tab_new", on_shortcut_new_tab_activate, file_browser );
xset_add_menuitem( NULL, file_browser, popup, accel_group, set );
set = xset_set_cb( "tab_new_here", on_shortcut_new_tab_here, file_browser );
xset_add_menuitem( NULL, file_browser, popup, accel_group, set );
set = xset_get( "sep_tab" );
xset_add_menuitem( NULL, file_browser, popup, accel_group, set );
set = xset_set_cb_panel( file_browser->mypanel, "icon_tab",
main_update_fonts, file_browser );
xset_add_menuitem( NULL, file_browser, popup, accel_group, set );
set = xset_set_cb_panel( file_browser->mypanel, "font_tab",
main_update_fonts, file_browser );
xset_add_menuitem( NULL, file_browser, popup, accel_group, set );
gtk_widget_show_all( GTK_WIDGET( popup ) );
g_signal_connect( popup, "selection-done",
G_CALLBACK( gtk_widget_destroy ), NULL );
g_signal_connect( popup, "key-press-event",
G_CALLBACK( xset_menu_keypress ), NULL );
gtk_menu_popup( GTK_MENU( popup ), NULL, NULL,
NULL, NULL, event->button, event->time );
return TRUE;
}
}
return FALSE;
}
void on_file_browser_after_chdir( PtkFileBrowser* file_browser,
FMMainWindow* main_window )
{
//fm_main_window_stop_busy_task( main_window );
if ( fm_main_window_get_current_file_browser( main_window ) == GTK_WIDGET( file_browser ) )
{
set_window_title( main_window, file_browser );
//gtk_entry_set_text( main_window->address_bar, file_browser->dir->disp_path );
//gtk_statusbar_push( GTK_STATUSBAR( main_window->status_bar ), 0, "" );
//fm_main_window_update_command_ui( main_window, file_browser );
}
//fm_main_window_update_tab_label( main_window, file_browser, file_browser->dir->disp_path );
if ( file_browser->inhibit_focus )
{
// complete ptk_file_browser.c ptk_file_browser_seek_path()
file_browser->inhibit_focus = FALSE;
if ( file_browser->seek_name )
{
ptk_file_browser_seek_path( file_browser, NULL, file_browser->seek_name );
g_free( file_browser->seek_name );
file_browser->seek_name = NULL;
}
}
else
{
ptk_file_browser_select_last( file_browser ); //MOD restore last selections
gtk_widget_grab_focus( GTK_WIDGET( file_browser->folder_view ) ); //MOD
}
}
GtkWidget* fm_main_window_create_tab_label( FMMainWindow* main_window,
PtkFileBrowser* file_browser )
{
GtkEventBox * evt_box;
GtkWidget* tab_label;
GtkWidget* tab_text;
GtkWidget* tab_icon = NULL;
GtkWidget* close_btn;
GtkWidget* close_icon;
GdkPixbuf* pixbuf = NULL;
GtkIconTheme* icon_theme = gtk_icon_theme_get_default();
/* Create tab label */
evt_box = GTK_EVENT_BOX( gtk_event_box_new () );
gtk_event_box_set_visible_window ( GTK_EVENT_BOX( evt_box ), FALSE );
tab_label = gtk_hbox_new( FALSE, 0 );
XSet* set = xset_get_panel( file_browser->mypanel, "icon_tab" );
if ( set->icon )
{
pixbuf = vfs_load_icon( icon_theme, set->icon, 16 );
if ( pixbuf )
{
tab_icon = gtk_image_new_from_pixbuf( pixbuf );
g_object_unref( pixbuf );
}
else
tab_icon = xset_get_image( set->icon, GTK_ICON_SIZE_MENU );
}
if ( !tab_icon )
tab_icon = gtk_image_new_from_icon_name ( "gtk-directory",
GTK_ICON_SIZE_MENU );
gtk_box_pack_start( GTK_BOX( tab_label ),
tab_icon, FALSE, FALSE, 4 );
if ( ptk_file_browser_get_cwd( file_browser ) )
{
char* name = g_path_get_basename( ptk_file_browser_get_cwd( file_browser ) );
if ( name )
{
tab_text = gtk_label_new( name );
g_free( name );
}
}
else
tab_text = gtk_label_new( "" );
// set font
char* fontname = xset_get_s_panel( file_browser->mypanel, "font_tab" );
if ( fontname )
{
PangoFontDescription* font_desc = pango_font_description_from_string( fontname );
gtk_widget_modify_font( tab_text, font_desc );
pango_font_description_free( font_desc );
}
gtk_label_set_ellipsize( GTK_LABEL( tab_text ), PANGO_ELLIPSIZE_MIDDLE );
#if GTK_CHECK_VERSION (3, 0, 0)
if (strlen( gtk_label_get_text( GTK_LABEL( tab_text ) ) ) < 30)
{
gtk_label_set_ellipsize( GTK_LABEL( tab_text ), PANGO_ELLIPSIZE_NONE );
gtk_label_set_width_chars( GTK_LABEL( tab_text ), -1 );
}
else
gtk_label_set_width_chars( GTK_LABEL( tab_text ), 30 );
#endif
gtk_label_set_max_width_chars( GTK_LABEL( tab_text ), 30 );
gtk_box_pack_start( GTK_BOX( tab_label ),
tab_text, FALSE, FALSE, 4 );
if ( !app_settings.hide_close_tab_buttons ) {
close_btn = gtk_button_new ();
gtk_button_set_focus_on_click ( GTK_BUTTON ( close_btn ), FALSE );
gtk_button_set_relief( GTK_BUTTON ( close_btn ), GTK_RELIEF_NONE );
pixbuf = vfs_load_icon( icon_theme, GTK_STOCK_CLOSE, 16 );
if ( pixbuf )
{
close_icon = gtk_image_new_from_pixbuf( pixbuf );
g_object_unref( pixbuf );
//shorten tab since we have a 16 icon
gtk_widget_set_size_request ( close_btn, 24, 20 );
#if GTK_CHECK_VERSION (3, 0, 0)
/* Code modified from gedit: gedit-close-button.c */
static const gchar button_style[] =
"* {\n"
"-GtkButton-default-border : 0;\n"
"-GtkButton-default-outside-border : 0;\n"
"-GtkButton-inner-border: 0;\n"
"-GtkWidget-focus-line-width : 0;\n"
"-GtkWidget-focus-padding : 0;\n"
"padding: 0;\n"
"}";
GtkCssProvider *css_prov = gtk_css_provider_new ();
gtk_css_provider_load_from_data(css_prov, button_style, -1, NULL);
GtkStyleContext *ctx = gtk_widget_get_style_context( close_btn );
gtk_style_context_add_provider( ctx, GTK_STYLE_PROVIDER( css_prov ), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION );
#endif
}
else
{
close_icon = gtk_image_new_from_stock( GTK_STOCK_CLOSE, GTK_ICON_SIZE_MENU );
}
gtk_container_add ( GTK_CONTAINER ( close_btn ), close_icon );
gtk_box_pack_end ( GTK_BOX( tab_label ),
close_btn, FALSE, FALSE, 0 );
g_signal_connect( G_OBJECT( close_btn ), "clicked",
G_CALLBACK( on_close_notebook_page ), file_browser );
}
gtk_container_add ( GTK_CONTAINER ( evt_box ), tab_label );
gtk_widget_set_events ( GTK_WIDGET( evt_box ), GDK_ALL_EVENTS_MASK );
gtk_drag_dest_set ( GTK_WIDGET( evt_box ), GTK_DEST_DEFAULT_ALL,
drag_targets,
sizeof( drag_targets ) / sizeof( GtkTargetEntry ),
GDK_ACTION_DEFAULT | GDK_ACTION_COPY | GDK_ACTION_MOVE | GDK_ACTION_LINK );
g_signal_connect ( ( gpointer ) evt_box, "drag-motion",
G_CALLBACK ( on_tab_drag_motion ),
file_browser );
//MOD middle-click to close tab
g_signal_connect(G_OBJECT(evt_box), "button-press-event",
G_CALLBACK(notebook_clicked), file_browser);
gtk_widget_show_all( GTK_WIDGET( evt_box ) );
if ( !set->icon )
gtk_widget_hide( tab_icon );
return GTK_WIDGET( evt_box );
}
void fm_main_window_update_tab_label( FMMainWindow* main_window,
PtkFileBrowser* file_browser,
const char * path )
{
GtkWidget * label;
GtkContainer* hbox;
GtkImage* icon;
GtkLabel* text;
GList* children;
gchar* name;
label = gtk_notebook_get_tab_label ( GTK_NOTEBOOK( main_window->notebook ),
GTK_WIDGET( file_browser ) );
if ( label )
{
hbox = GTK_CONTAINER( gtk_bin_get_child ( GTK_BIN( label ) ) );
children = gtk_container_get_children( hbox );
icon = GTK_IMAGE( children->data );
text = GTK_LABEL( children->next->data );
// TODO: Change the icon
name = g_path_get_basename( path );
gtk_label_set_text( text, name );
#if GTK_CHECK_VERSION (3, 0, 0)
gtk_label_set_ellipsize( text, PANGO_ELLIPSIZE_MIDDLE );
if (strlen( name ) < 30)
{
gtk_label_set_ellipsize( text, PANGO_ELLIPSIZE_NONE );
gtk_label_set_width_chars( text, -1 );
}
else
gtk_label_set_width_chars( text, 30 );
#endif
g_free( name );
g_list_free( children ); //sfm 0.6.0 enabled
}
}
void fm_main_window_add_new_tab( FMMainWindow* main_window,
const char* folder_path )
{
GtkWidget * tab_label;
gint idx;
GtkWidget* notebook = main_window->notebook;
PtkFileBrowser* curfb = PTK_FILE_BROWSER( fm_main_window_get_current_file_browser
( main_window ) );
if ( GTK_IS_WIDGET( curfb ) )
{
// save sliders of current fb ( new tab while task manager is shown changes vals )
ptk_file_browser_slider_release( NULL, NULL, curfb );
// save column widths of fb so new tab has same
on_folder_view_columns_changed( GTK_TREE_VIEW( curfb->folder_view ), curfb );
}
int i = main_window->curpanel -1;
PtkFileBrowser* file_browser = (PtkFileBrowser*)ptk_file_browser_new(
main_window->curpanel, notebook,
main_window->task_view, main_window,
&main_window->panel_slide_x[i],
&main_window->panel_slide_y[i],
&main_window->panel_slide_s[i] );
if ( !file_browser )
return;
//printf( "++++++++++++++fm_main_window_add_new_tab fb=%#x\n", file_browser );
ptk_file_browser_set_single_click( file_browser, app_settings.single_click );
// FIXME: this shouldn't be hard-code
ptk_file_browser_set_single_click_timeout( file_browser, SINGLE_CLICK_TIMEOUT );
ptk_file_browser_show_thumbnails( file_browser,
app_settings.show_thumbnail ? app_settings.max_thumb_size : 0 );
ptk_file_browser_set_sort_order( file_browser,
xset_get_int_panel( file_browser->mypanel, "list_detailed", "x" ) );
ptk_file_browser_set_sort_type( file_browser,
xset_get_int_panel( file_browser->mypanel, "list_detailed", "y" ) );
gtk_widget_show( GTK_WIDGET( file_browser ) );
/*
g_signal_connect( file_browser, "before-chdir",
G_CALLBACK( on_file_browser_before_chdir ), main_window );
g_signal_connect( file_browser, "begin-chdir",
G_CALLBACK( on_file_browser_begin_chdir ), main_window );
*/
g_signal_connect( file_browser, "content-change",
G_CALLBACK( on_file_browser_content_change ), main_window );
g_signal_connect( file_browser, "after-chdir",
G_CALLBACK( on_file_browser_after_chdir ), main_window );
g_signal_connect( file_browser, "open-item",
G_CALLBACK( on_file_browser_open_item ), main_window );
g_signal_connect( file_browser, "sel-change",
G_CALLBACK( on_file_browser_sel_change ), main_window );
g_signal_connect( file_browser, "pane-mode-change",
G_CALLBACK( on_file_browser_panel_change ), main_window );
tab_label = fm_main_window_create_tab_label( main_window, file_browser );
idx = gtk_notebook_append_page( GTK_NOTEBOOK( notebook ),
GTK_WIDGET( file_browser ), tab_label );
gtk_notebook_set_tab_reorderable( GTK_NOTEBOOK( notebook ), GTK_WIDGET( file_browser ), TRUE );
gtk_notebook_set_current_page ( GTK_NOTEBOOK( notebook ), idx );
if (app_settings.always_show_tabs)
gtk_notebook_set_show_tabs( GTK_NOTEBOOK( notebook ), TRUE );
else
if ( gtk_notebook_get_n_pages ( GTK_NOTEBOOK( notebook ) ) > 1 )
gtk_notebook_set_show_tabs( GTK_NOTEBOOK( notebook ), TRUE );
else
gtk_notebook_set_show_tabs( GTK_NOTEBOOK( notebook ), FALSE );
if ( !ptk_file_browser_chdir( file_browser, folder_path, PTK_FB_CHDIR_ADD_HISTORY ) )
ptk_file_browser_chdir( file_browser, "/", PTK_FB_CHDIR_ADD_HISTORY );
if ( evt_tab_new->s || evt_tab_new->ob2_data )
main_window_event( main_window, evt_tab_new, "evt_tab_new", 0, 0, NULL,
0, 0, 0, TRUE );
set_panel_focus( main_window, file_browser );
// while( gtk_events_pending() ) // wait for chdir to grab focus
// gtk_main_iteration();
//gtk_widget_grab_focus( GTK_WIDGET( file_browser->folder_view ) );
//printf("focus browser #%d %d\n", idx, file_browser->folder_view );
//printf("call delayed (newtab) #%d %#x\n", idx, file_browser->folder_view);
// g_idle_add( ( GSourceFunc ) delayed_focus, file_browser->folder_view );
}
GtkWidget* fm_main_window_new()
{
return ( GtkWidget* ) g_object_new ( FM_TYPE_MAIN_WINDOW, NULL );
}
GtkWidget* fm_main_window_get_current_file_browser ( FMMainWindow* main_window )
{
if ( main_window->notebook )
{
gint idx = gtk_notebook_get_current_page( GTK_NOTEBOOK( main_window->notebook ) );
if ( idx >= 0 )
return gtk_notebook_get_nth_page( GTK_NOTEBOOK( main_window->notebook ), idx );
}
return NULL;
}
void
on_preference_activate ( GtkMenuItem *menuitem,
gpointer user_data )
{
FMMainWindow * main_window = FM_MAIN_WINDOW( user_data );
fm_main_window_preference( main_window );
}
void fm_main_window_preference( FMMainWindow* main_window )
{
fm_edit_preference( (GtkWindow*)main_window, PREF_GENERAL );
}
#if 0
void
on_file_assoc_activate ( GtkMenuItem *menuitem,
gpointer user_data )
{
GtkWindow * main_window = GTK_WINDOW( user_data );
edit_file_associations( main_window );
}
#endif
/* callback used to open default browser when URLs got clicked */
static void open_url( GtkAboutDialog *dlg, const gchar *url, gpointer data)
{
xset_open_url( GTK_WIDGET( dlg ), url );
#if 0
/* FIXME: is there any better way to do this? */
char* programs[] = { "xdg-open", "gnome-open" /* Sorry, KDE users. :-P */, "exo-open" };
int i;
for( i = 0; i < G_N_ELEMENTS(programs); ++i)
{
char* open_cmd = NULL;
if( (open_cmd = g_find_program_in_path( programs[i] )) )
{
char* cmd = g_strdup_printf( "%s \'%s\'", open_cmd, url );
g_spawn_command_line_async( cmd, NULL );
g_free( cmd );
g_free( open_cmd );
break;
}
}
#endif
}
void on_main_help_activate ( GtkMenuItem *menuitem, FMMainWindow* main_window )
{
const char* help;
PtkFileBrowser* browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
if ( browser && browser->path_bar && gtk_widget_has_focus(
GTK_WIDGET( browser->path_bar ) ) )
help = "#gui-pathbar";
else if ( browser && browser->side_dev && gtk_widget_has_focus(
GTK_WIDGET( browser->side_dev ) ) )
help = "#devices";
else if ( main_window->task_view &&
gtk_widget_has_focus( GTK_WIDGET( main_window->task_view ) ) )
help = "#tasks-man";
else
help = NULL;
xset_show_help( GTK_WIDGET( main_window ), NULL, help );
}
void on_main_faq ( GtkMenuItem *menuitem, FMMainWindow* main_window )
{
xset_show_help( GTK_WIDGET( main_window ), NULL, "#quickstart-faq" );
}
void on_homepage_activate ( GtkMenuItem *menuitem, FMMainWindow* main_window )
{
xset_open_url( GTK_WIDGET( main_window ), NULL );
}
void on_news_activate ( GtkMenuItem *menuitem, FMMainWindow* main_window )
{
xset_open_url( GTK_WIDGET( main_window ), "http://ignorantguru.github.com/spacefm/news.html" );
}
void on_getplug_activate ( GtkMenuItem *menuitem, FMMainWindow* main_window )
{
xset_open_url( GTK_WIDGET( main_window ), "https://github.com/IgnorantGuru/spacefm/wiki/plugins/" );
}
void
on_about_activate ( GtkMenuItem *menuitem,
gpointer user_data )
{
static GtkWidget * about_dlg = NULL;
GtkBuilder* builder = gtk_builder_new();
if( ! about_dlg )
{
GtkBuilder* builder;
pcmanfm_ref();
builder = _gtk_builder_new_from_file( PACKAGE_UI_DIR "/about-dlg.ui", NULL );
about_dlg = GTK_WIDGET( gtk_builder_get_object( builder, "dlg" ) );
g_object_unref( builder );
gtk_about_dialog_set_version ( GTK_ABOUT_DIALOG ( about_dlg ), VERSION );
char* name;
XSet* set = xset_get( "main_icon" );
if ( set->icon )
name = set->icon;
else if ( geteuid() == 0 )
name = "spacefm-root";
else
name = "spacefm";
gtk_about_dialog_set_logo_icon_name( GTK_ABOUT_DIALOG ( about_dlg ), name );
g_object_add_weak_pointer( G_OBJECT(about_dlg), (gpointer)&about_dlg );
g_signal_connect( about_dlg, "response", G_CALLBACK(gtk_widget_destroy), NULL );
g_signal_connect( about_dlg, "destroy", G_CALLBACK(pcmanfm_unref), NULL );
g_signal_connect( about_dlg, "activate-link", G_CALLBACK(open_url), NULL );
}
gtk_window_set_transient_for( GTK_WINDOW( about_dlg ), GTK_WINDOW( user_data ) );
gtk_window_present( (GtkWindow*)about_dlg );
}
#if 0
gboolean
on_back_btn_popup_menu ( GtkWidget *widget,
gpointer user_data )
{
//GtkWidget* file_browser = fm_main_window_get_current_file_browser( widget );
return FALSE;
}
#endif
#if 0
gboolean
on_forward_btn_popup_menu ( GtkWidget *widget,
gpointer user_data )
{
//GtkWidget* file_browser = fm_main_window_get_current_file_browser( widget );
return FALSE;
}
#endif
void fm_main_window_add_new_window( FMMainWindow* main_window )
{
GtkWidget * new_win = fm_main_window_new();
GtkAllocation allocation;
gtk_widget_get_allocation ( GTK_WIDGET( main_window ), &allocation);
gtk_window_set_default_size( GTK_WINDOW( new_win ),
allocation.width,
allocation.height );
gtk_widget_show( new_win );
}
void
on_new_window_activate ( GtkMenuItem *menuitem,
gpointer user_data )
{
int cur_tabx, p;
PtkFileBrowser* a_browser;
XSet* set;
FMMainWindow* main_window = FM_MAIN_WINDOW( user_data );
save_settings( main_window );
/* this works - enable if desired
// open active tabs only
for ( p = 1; p < 5; p++ )
{
set = xset_get_panel( p, "show" );
if ( set->b == XSET_B_TRUE )
{
// set preload tab to current
cur_tabx = gtk_notebook_get_current_page( GTK_NOTEBOOK( main_window->panel[p-1] ) );
a_browser = PTK_FILE_BROWSER( gtk_notebook_get_nth_page(
GTK_NOTEBOOK( main_window->panel[p-1] ), cur_tabx ) );
if ( GTK_IS_WIDGET( a_browser ) )
set->ob1 = g_strdup( ptk_file_browser_get_cwd( a_browser ) );
// clear other saved tabs
g_free( set->s );
set->s = NULL;
}
}
*/
fm_main_window_add_new_window( main_window );
}
static gboolean delayed_focus( GtkWidget* widget )
{
if ( GTK_IS_WIDGET( widget ) )
{
///gdk_threads_enter();
//printf( "delayed_focus %#x\n", widget);
if ( GTK_IS_WIDGET( widget ) )
gtk_widget_grab_focus( widget );
///gdk_threads_leave();
}
return FALSE;
}
static gboolean delayed_focus_file_browser( PtkFileBrowser* file_browser )
{
if ( GTK_IS_WIDGET( file_browser ) && GTK_IS_WIDGET( file_browser->folder_view ) )
{
///gdk_threads_enter();
//printf( "delayed_focus_file_browser fb=%#x\n", file_browser );
if ( GTK_IS_WIDGET( file_browser ) && GTK_IS_WIDGET( file_browser->folder_view ) )
{
gtk_widget_grab_focus( file_browser->folder_view );
set_panel_focus( NULL, file_browser );
}
///gdk_threads_leave();
}
return FALSE;
}
void set_panel_focus( FMMainWindow* main_window, PtkFileBrowser* file_browser )
{
int p, pages, cur_tabx;
GtkWidget* notebook;
PtkFileBrowser* a_browser;
if ( !file_browser && !main_window )
return;
FMMainWindow* mw = main_window;
if ( !mw )
mw = (FMMainWindow*)file_browser->main_window;
if ( file_browser )
ptk_file_browser_status_change( file_browser,
file_browser->mypanel == mw->curpanel );
for ( p = 1; p < 5; p++ )
{
notebook = mw->panel[p-1];
pages = gtk_notebook_get_n_pages( GTK_NOTEBOOK( notebook ) );
for ( cur_tabx = 0; cur_tabx < pages; cur_tabx++ )
{
a_browser = PTK_FILE_BROWSER(
gtk_notebook_get_nth_page( GTK_NOTEBOOK( notebook ), cur_tabx ) );
if ( a_browser != file_browser )
ptk_file_browser_status_change( a_browser, p == mw->curpanel );
}
gtk_widget_set_sensitive( mw->panel_image[p-1],
p == mw->curpanel );
}
update_window_title( NULL, mw );
if ( evt_pnl_focus->s || evt_pnl_focus->ob2_data )
main_window_event( main_window, evt_pnl_focus, "evt_pnl_focus",
mw->curpanel, 0, NULL, 0, 0, 0, TRUE );
}
void on_fullscreen_activate ( GtkMenuItem *menuitem, FMMainWindow* main_window )
{
if ( xset_get_b( "main_full" ) )
{
gtk_widget_hide( main_window->menu_bar );
gtk_widget_hide( main_window->panelbar );
gtk_window_fullscreen( GTK_WINDOW( main_window ) );
}
else
{
gtk_window_unfullscreen( GTK_WINDOW( main_window ) );
gtk_widget_show( main_window->menu_bar );
if ( xset_get_b( "main_pbar" ) )
gtk_widget_show( main_window->panelbar );
}
}
void set_window_title( FMMainWindow* main_window, PtkFileBrowser* file_browser )
{
char* disp_path;
char* disp_name;
char* tab_count = NULL;
char* tab_num = NULL;
char* panel_count = NULL;
char* panel_num = NULL;
char* s;
if ( !file_browser || !main_window )
return;
if ( file_browser->dir && file_browser->dir->disp_path )
{
disp_path = g_strdup( file_browser->dir->disp_path );
disp_name = g_path_get_basename( disp_path );
}
else
{
const char* path = ptk_file_browser_get_cwd( file_browser );
if ( path )
{
disp_path = g_filename_display_name( path );
disp_name = g_path_get_basename( disp_path );
}
else
{
disp_name = g_strdup( "" );
disp_path = g_strdup( "" );
}
}
char* orig_fmt = xset_get_s( "main_title" );
char* fmt = g_strdup( orig_fmt );
if ( !fmt )
fmt = g_strdup( "%d" );
if ( strstr( fmt, "%t" ) || strstr( fmt, "%T" ) || strstr( fmt, "%p" )
|| strstr( fmt, "%P" ) )
{
// get panel/tab info
int ipanel_count = 0, itab_count = 0, itab_num = 0;
main_window_get_counts( file_browser, &ipanel_count, &itab_count, &itab_num );
panel_count = g_strdup_printf( "%d", ipanel_count );
tab_count = g_strdup_printf( "%d", itab_count );
tab_num = g_strdup_printf( "%d", itab_num );
panel_count = g_strdup_printf( "%d", ipanel_count );
panel_num = g_strdup_printf( "%d", main_window->curpanel );
s = replace_string( fmt, "%t", tab_num, FALSE );
g_free( fmt );
fmt = replace_string( s, "%T", tab_count, FALSE );
g_free( s );
s = replace_string( fmt, "%p", panel_num, FALSE );
g_free( fmt );
fmt = replace_string( s, "%P", panel_count, FALSE );
g_free( panel_count );
g_free( tab_count );
g_free( tab_num );
g_free( panel_num );
}
if ( strchr( fmt, '*' ) && !main_tasks_running( main_window ) )
{
s = fmt;
fmt = replace_string( s, "*", "", FALSE );
g_free( s );
}
if ( strstr( fmt, "%n" ) )
{
s = fmt;
fmt = replace_string( s, "%n", disp_name, FALSE );
g_free( s );
}
if ( orig_fmt && strstr( orig_fmt, "%d" ) )
{
s = fmt;
fmt = replace_string( s, "%d", disp_path, FALSE );
g_free( s );
}
g_free( disp_name );
g_free( disp_path );
gtk_window_set_title( GTK_WINDOW( main_window ), fmt );
g_free( fmt );
/*
if ( file_browser->dir && ( disp_path = file_browser->dir->disp_path ) )
{
disp_name = g_path_get_basename( disp_path );
//gtk_entry_set_text( main_window->address_bar, disp_path );
gtk_window_set_title( GTK_WINDOW( main_window ), disp_name );
g_free( disp_name );
}
else
{
char* path = ptk_file_browser_get_cwd( file_browser );
if ( path )
{
disp_path = g_filename_display_name( path );
//gtk_entry_set_text( main_window->address_bar, disp_path );
disp_name = g_path_get_basename( disp_path );
g_free( disp_path );
gtk_window_set_title( GTK_WINDOW( main_window ), disp_name );
g_free( disp_name );
}
}
*/
}
void update_window_title( GtkMenuItem* item, FMMainWindow* main_window )
{
PtkFileBrowser* file_browser = PTK_FILE_BROWSER( fm_main_window_get_current_file_browser
( main_window ) );
if ( file_browser )
set_window_title( main_window, file_browser );
}
void
on_folder_notebook_switch_pape ( GtkNotebook *notebook,
GtkWidget *page,
guint page_num,
gpointer user_data )
{
FMMainWindow * main_window = FM_MAIN_WINDOW( user_data );
PtkFileBrowser* file_browser;
const char* path;
char* disp_path;
// save sliders of current fb ( new tab while task manager is shown changes vals )
PtkFileBrowser* curfb = PTK_FILE_BROWSER( fm_main_window_get_current_file_browser
( main_window ) );
if ( curfb )
ptk_file_browser_slider_release( NULL, NULL, curfb );
file_browser = PTK_FILE_BROWSER( gtk_notebook_get_nth_page( notebook, page_num ) );
//printf("on_folder_notebook_switch_pape fb=%#x panel=%d page=%d\n", file_browser, file_browser->mypanel, page_num );
main_window->curpanel = file_browser->mypanel;
main_window->notebook = main_window->panel[main_window->curpanel - 1];
fm_main_window_update_status_bar( main_window, file_browser );
set_window_title( main_window, file_browser );
if ( evt_tab_focus->ob2_data || evt_tab_focus->s )
main_window_event( main_window, evt_tab_focus, "evt_tab_focus",
main_window->curpanel,
page_num + 1, NULL, 0, 0, 0, TRUE );
// block signal in case tab is being closed due to main iteration in update views
// g_signal_handlers_block_matched( main_window->panel[file_browser->mypanel - 1],
// G_SIGNAL_MATCH_FUNC, 0, 0, NULL, on_folder_notebook_switch_pape, NULL );
// PROBLEM: this may allow close events to destroy fb, so make sure its
// still a widget after this
ptk_file_browser_update_views( NULL, file_browser );
// g_signal_handlers_unblock_matched( main_window->panel[file_browser->mypanel - 1],
// G_SIGNAL_MATCH_FUNC, 0, 0, NULL, on_folder_notebook_switch_pape, NULL );
if ( GTK_IS_WIDGET( file_browser ) )
g_idle_add( ( GSourceFunc ) delayed_focus, file_browser->folder_view );
}
void main_window_open_path_in_current_tab( FMMainWindow* main_window, const char* path )
{
PtkFileBrowser* file_browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
if ( !file_browser )
return;
ptk_file_browser_chdir( file_browser, path, PTK_FB_CHDIR_ADD_HISTORY );
}
void main_window_open_network( FMMainWindow* main_window, const char* path,
gboolean new_tab )
{
PtkFileBrowser* file_browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
if ( !file_browser )
return;
char* str = g_strdup( path );
mount_network( file_browser, str, new_tab );
g_free( str );
}
void on_file_browser_open_item( PtkFileBrowser* file_browser,
const char* path, PtkOpenAction action,
FMMainWindow* main_window )
{
if ( G_LIKELY( path ) )
{
switch ( action )
{
case PTK_OPEN_DIR:
ptk_file_browser_chdir( file_browser, path, PTK_FB_CHDIR_ADD_HISTORY );
break;
case PTK_OPEN_NEW_TAB:
//file_browser = PTK_FILE_BROWSER( fm_main_window_get_current_file_browser( main_window ) );
fm_main_window_add_new_tab( main_window, path );
break;
case PTK_OPEN_NEW_WINDOW:
//file_browser = PTK_FILE_BROWSER( fm_main_window_get_current_file_browser( main_window ) );
//fm_main_window_add_new_window( main_window, path,
// file_browser->show_side_pane,
// file_browser->side_pane_mode );
break;
case PTK_OPEN_TERMINAL:
//fm_main_window_open_terminal( GTK_WINDOW(main_window), path );
break;
case PTK_OPEN_FILE:
//fm_main_window_start_busy_task( main_window );
//g_timeout_add( 1000, ( GSourceFunc ) fm_main_window_stop_busy_task, main_window );
break;
}
}
}
void fm_main_window_update_status_bar( FMMainWindow* main_window,
PtkFileBrowser* file_browser )
{
int num_sel, num_vis, num_hid, num_hidx;
guint64 total_size;
char *msg;
char size_str[ 64 ];
char free_space[100];
#ifdef HAVE_STATVFS
struct statvfs fs_stat = {0};
#endif
if ( !( GTK_IS_WIDGET( file_browser ) && GTK_IS_STATUSBAR( file_browser->status_bar ) ) )
return;
//file_browser = PTK_FILE_BROWSER( fm_main_window_get_current_file_browser( main_window ) );
if ( file_browser->status_bar_custom )
{
gtk_statusbar_push( GTK_STATUSBAR( file_browser->status_bar ), 0,
file_browser->status_bar_custom );
return;
}
free_space[0] = '\0';
#ifdef HAVE_STATVFS
// FIXME: statvfs support should be moved to src/vfs
if( statvfs( ptk_file_browser_get_cwd(file_browser), &fs_stat ) == 0 )
{
char total_size_str[ 64 ];
// calc free space
vfs_file_size_to_string_format( size_str,
fs_stat.f_bsize * fs_stat.f_bavail, NULL );
// calc total space
vfs_file_size_to_string_format( total_size_str,
fs_stat.f_frsize * fs_stat.f_blocks, NULL );
g_snprintf( free_space, G_N_ELEMENTS(free_space),
_(" %s free / %s "), size_str, total_size_str ); //MOD
}
#endif
// note: total size won't include content changes since last selection change
num_sel = ptk_file_browser_get_n_sel( file_browser, &total_size );
num_vis = ptk_file_browser_get_n_visible_files( file_browser );
char* link_info = NULL; //MOD added
if ( num_sel > 0 )
{
if ( num_sel == 1 ) //MOD added
// display file name or symlink info in status bar if one file selected
{
GList* files;
VFSFileInfo* file;
struct stat results;
char buf[ 64 ];
char* lsize;
files = ptk_file_browser_get_selected_files( file_browser );
if ( files )
{
const char* cwd = ptk_file_browser_get_cwd( file_browser );
file = vfs_file_info_ref( ( VFSFileInfo* ) files->data );
g_list_foreach( files, ( GFunc ) vfs_file_info_unref, NULL );
g_list_free( files );
if ( file )
{
if ( vfs_file_info_is_symlink( file ) )
{
char* full_target = NULL;
char* target_path;
char* file_path = g_build_filename( cwd,
vfs_file_info_get_name( file ), NULL );
char* target = g_file_read_link( file_path, NULL );
if ( target )
{
//printf("LINK: %s\n", file_path );
if ( target[0] != '/' )
{
// relative link
full_target = g_build_filename( cwd, target, NULL );
target_path = full_target;
}
else
target_path = target;
if ( vfs_file_info_is_dir( file ) )
{
if ( g_file_test( target_path, G_FILE_TEST_EXISTS ) )
{
if ( !strcmp( target, "/" ) )
link_info = g_strdup_printf( _(" Link → %s"), target );
else
link_info = g_strdup_printf( _(" Link → %s/"), target );
}
else
link_info = g_strdup_printf( _(" !Link → %s/ (missing)"), target );
}
else
{
if ( stat( target_path, &results ) == 0 )
{
vfs_file_size_to_string( buf, results.st_size );
lsize = g_strdup( buf );
link_info = g_strdup_printf( _(" Link → %s (%s)"), target, lsize );
}
else
link_info = g_strdup_printf( _(" !Link → %s (missing)"), target );
}
g_free( target );
if ( full_target )
g_free( full_target );
}
else
link_info = g_strdup_printf( _(" !Link → ( error reading target )") );
g_free( file_path );
}
else
link_info = g_strdup_printf( " %s", vfs_file_info_get_name( file ) );
vfs_file_info_unref( file );
}
}
}
if ( ! link_info )
link_info = g_strdup( "" );
vfs_file_size_to_string( size_str, total_size );
msg = g_strdup_printf( "%s%d / %d (%s)%s", free_space, num_sel, num_vis,
size_str, link_info );
//msg = g_strdup_printf( ngettext( _("%s%d sel (%s)%s"), //MOD
// _("%s%d sel (%s)"), num_sel ), free_space, num_sel,
// size_str, link_info ); //MOD
}
else
{
// cur dir is link ? canonicalize
char* dirmsg;
const char* cwd = ptk_file_browser_get_cwd( file_browser );
char buf[ PATH_MAX + 1 ];
char* canon = realpath( cwd, buf );
if ( !canon || !g_strcmp0( canon, cwd ) )
dirmsg = g_strdup_printf( "%s", cwd );
else
dirmsg = g_strdup_printf( "./ → %s", canon );
// MOD add count for .hidden files
char* xhidden;
num_hid = ptk_file_browser_get_n_all_files( file_browser ) - num_vis;
if ( num_hid < 0 ) num_hid = 0; // needed due to bug in get_n_visible_files?
num_hidx = file_browser->dir ? file_browser->dir->xhidden_count : 0;
//VFSDir* xdir = file_browser->dir;
if ( num_hid || num_hidx )
{
if ( num_hidx )
xhidden = g_strdup_printf( "+%d", num_hidx );
else
xhidden = g_strdup( "" );
char hidden[128];
char *hnc = NULL;
char* hidtext = ngettext( "hidden", "hidden", num_hid);
g_snprintf( hidden, 127, g_strdup_printf( "%d%s %s", num_hid,
xhidden, hidtext ), num_hid );
msg = g_strdup_printf( ngettext( "%s%d visible (%s) %s",
"%s%d visible (%s) %s", num_vis ),
free_space, num_vis, hidden, dirmsg );
}
else
msg = g_strdup_printf( ngettext( "%s%d item %s",
"%s%d items %s", num_vis ),
free_space, num_vis, dirmsg );
g_free( dirmsg );
}
gtk_statusbar_push( GTK_STATUSBAR( file_browser->status_bar ), 0, msg );
g_free( msg );
}
void on_file_browser_panel_change( PtkFileBrowser* file_browser,
FMMainWindow* main_window )
{
//printf("panel_change panel %d\n", file_browser->mypanel );
main_window->curpanel = file_browser->mypanel;
main_window->notebook = main_window->panel[main_window->curpanel - 1];
//set_window_title( main_window, file_browser );
set_panel_focus( main_window, file_browser );
}
void on_file_browser_sel_change( PtkFileBrowser* file_browser,
FMMainWindow* main_window )
{
//printf("sel_change panel %d\n", file_browser->mypanel );
if ( ( evt_pnl_sel->ob2_data || evt_pnl_sel->s ) &&
main_window_event( main_window, evt_pnl_sel, "evt_pnl_sel", 0, 0, NULL,
0, 0, 0, TRUE ) )
return;
fm_main_window_update_status_bar( main_window, file_browser );
/*
int i = gtk_notebook_get_current_page( main_window->panel[
file_browser->mypanel - 1 ] );
if ( i != -1 )
{
if ( file_browser == (PtkFileBrowser*)gtk_notebook_get_nth_page(
main_window->panel[ file_browser->mypanel - 1 ], i ) )
fm_main_window_update_status_bar( main_window, file_browser );
}
*/
// main_window->curpanel = file_browser->mypanel;
// main_window->notebook = main_window->panel[main_window->curpanel - 1];
// if ( fm_main_window_get_current_file_browser( main_window ) == GTK_WIDGET( file_browser ) )
}
void on_file_browser_content_change( PtkFileBrowser* file_browser,
FMMainWindow* main_window )
{
//printf("content_change panel %d\n", file_browser->mypanel );
fm_main_window_update_status_bar( main_window, file_browser );
}
gboolean on_tab_drag_motion ( GtkWidget *widget,
GdkDragContext *drag_context,
gint x,
gint y,
guint time,
PtkFileBrowser* file_browser )
{
GtkNotebook * notebook;
gint idx;
notebook = GTK_NOTEBOOK( gtk_widget_get_parent( GTK_WIDGET( file_browser ) ) );
// TODO: Add a timeout here and don't set current page immediately
idx = gtk_notebook_page_num ( notebook, GTK_WIDGET( file_browser ) );
gtk_notebook_set_current_page( notebook, idx );
return FALSE;
}
gboolean on_window_button_press_event( GtkWidget* widget, GdkEventButton *event,
FMMainWindow* main_window ) //sfm
{
if ( event->type != GDK_BUTTON_PRESS )
return FALSE;
// handle mouse back/forward buttons anywhere in the main window
if ( event->button > 3 && event->button < 10 )
{
PtkFileBrowser* file_browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
if ( !file_browser )
return FALSE;
if ( event->button == 4 || event->button == 6 || event->button == 8 )
ptk_file_browser_go_back( NULL, file_browser );
else
ptk_file_browser_go_forward( NULL, file_browser );
return TRUE;
}
return FALSE;
}
gboolean on_main_window_focus( GtkWidget* main_window,
GdkEventFocus *event,
gpointer user_data )
{
//this causes a widget not realized loop by running rebuild_menus while
//rebuild_menus is already running
// but this unneeded anyway? cross-window menu changes seem to work ok
//rebuild_menus( main_window ); // xset may change in another window
GList * active;
if ( all_windows->data != ( gpointer ) main_window )
{
active = g_list_find( all_windows, main_window );
if ( active )
{
all_windows = g_list_remove_link( all_windows, active );
all_windows->prev = active;
active->next = all_windows;
all_windows = active;
}
}
if ( evt_win_focus->s || evt_win_focus->ob2_data )
main_window_event( (FMMainWindow*)main_window, evt_win_focus,
"evt_win_focus", 0, 0, NULL, 0, 0, 0, TRUE );
return FALSE;
}
static gboolean on_main_window_keypress( FMMainWindow* main_window, GdkEventKey* event,
gpointer user_data)
{
//MOD intercept xset key
//printf("main_keypress %d %d\n", event->keyval, event->state );
GList* l;
XSet* set;
PtkFileBrowser* browser;
if ( event->keyval == 0 )
return FALSE;
int keymod = ( event->state & ( GDK_SHIFT_MASK | GDK_CONTROL_MASK |
GDK_MOD1_MASK | GDK_SUPER_MASK | GDK_HYPER_MASK | GDK_META_MASK ) );
if ( ( event->keyval == GDK_KEY_Home && ( keymod == 0 ||
keymod == GDK_SHIFT_MASK ) )
|| ( event->keyval == GDK_KEY_End && ( keymod == 0 ||
keymod == GDK_SHIFT_MASK ) )
|| ( event->keyval == GDK_KEY_Delete && keymod == 0 )
|| ( event->keyval == GDK_KEY_Tab && keymod == 0 )
|| ( event->keyval == GDK_KEY_Left && ( keymod == 0 ||
keymod == GDK_SHIFT_MASK ) )
|| ( event->keyval == GDK_KEY_Right && ( keymod == 0 ||
keymod == GDK_SHIFT_MASK ) )
|| ( event->keyval == GDK_KEY_BackSpace && keymod == 0 )
|| ( keymod == 0 && event->keyval != GDK_KEY_Escape &&
gdk_keyval_to_unicode( event->keyval ) ) ) // visible char
{
browser = PTK_FILE_BROWSER( fm_main_window_get_current_file_browser( main_window ) );
if ( browser && browser->path_bar && gtk_widget_has_focus(
GTK_WIDGET( browser->path_bar ) ) )
return FALSE; // send to pathbar
}
if ( ( evt_win_key->s || evt_win_key->ob2_data ) &&
main_window_event( main_window, evt_win_key, "evt_win_key", 0, 0, NULL,
event->keyval, 0, keymod, TRUE ) )
return TRUE;
for ( l = xsets; l; l = l->next )
{
if ( ((XSet*)l->data)->shared_key )
{
// set has shared key
set = xset_get( ((XSet*)l->data)->shared_key );
if ( set->key == event->keyval && set->keymod == keymod )
{
// shared key match
if ( g_str_has_prefix( set->name, "panel" ) )
{
// use current panel's set
browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
if ( browser )
{
char* new_set_name = g_strdup_printf( "panel%d%s",
browser->mypanel, set->name + 6 );
set = xset_get( new_set_name );
g_free( new_set_name );
}
else
return FALSE; // failsafe
}
goto _key_found; // for speed
}
else
continue;
}
if ( ((XSet*)l->data)->key == event->keyval
&& ((XSet*)l->data)->keymod == keymod )
{
set = (XSet*)l->data;
_key_found:
browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
if ( !browser )
return TRUE;
char* xname;
int i;
// special edit items
if ( !strcmp( set->name, "edit_cut" )
|| !strcmp( set->name, "edit_copy" )
|| !strcmp( set->name, "edit_delete" )
|| !strcmp( set->name, "select_all" ) )
{
if ( !gtk_widget_is_focus( browser->folder_view ) )
return FALSE;
}
else if ( !strcmp( set->name, "edit_paste" ) )
{
gboolean side_dir_focus = ( browser->side_dir
&& gtk_widget_is_focus(
GTK_WIDGET( browser->side_dir ) ) );
if ( !gtk_widget_is_focus( GTK_WIDGET( browser->folder_view ) )
&& !side_dir_focus )
return FALSE;
}
// run menu_cb
if ( set->menu_style < XSET_MENU_SUBMENU )
{
set->browser = browser;
xset_menu_cb( NULL, set ); // also does custom activate
}
if ( !set->lock )
return TRUE;
// handlers
if ( g_str_has_prefix( set->name, "dev_" ) )
#ifndef HAVE_HAL
ptk_location_view_on_action( GTK_WIDGET( browser->side_dev ), set );
#else
g_warning( _("Device manager key shortcuts are disabled in HAL mode") );
#endif
else if ( g_str_has_prefix( set->name, "main_" ) )
{
xname = set->name + 5;
if ( !strcmp( xname, "new_window" ) )
on_new_window_activate( NULL, main_window );
else if ( !strcmp( xname, "root_window" ) )
on_open_current_folder_as_root( NULL, main_window );
else if ( !strcmp( xname, "search" ) )
on_find_file_activate( NULL, main_window );
else if ( !strcmp( xname, "terminal" ) )
on_open_terminal_activate( NULL, main_window );
else if ( !strcmp( xname, "root_terminal" ) )
on_open_root_terminal_activate( NULL, main_window );
else if ( !strcmp( xname, "save_session" ) )
on_save_session( NULL, main_window );
else if ( !strcmp( xname, "exit" ) )
on_quit_activate( NULL, main_window );
else if ( !strcmp( xname, "full" ) )
on_fullscreen_activate( NULL, main_window );
else if ( !strcmp( xname, "prefs" ) )
on_preference_activate( NULL, main_window );
else if ( !strcmp( xname, "design_mode" ) )
main_design_mode( NULL, main_window );
else if ( !strcmp( xname, "pbar" ) )
show_panels_all_windows( NULL, main_window );
else if ( !strcmp( xname, "icon" ) )
on_main_icon();
else if ( !strcmp( xname, "title" ) )
update_window_title( NULL, main_window );
else if ( !strcmp( xname, "about" ) )
on_about_activate( NULL, main_window );
else if ( !strcmp( xname, "help" ) )
on_main_help_activate( NULL, main_window );
else if ( !strcmp( xname, "faq" ) )
on_main_faq( NULL, main_window );
else if ( !strcmp( xname, "homepage" ) )
on_homepage_activate( NULL, main_window );
else if ( !strcmp( xname, "news" ) )
on_news_activate( NULL, main_window );
else if ( !strcmp( xname, "getplug" ) )
on_getplug_activate( NULL, main_window );
}
else if ( g_str_has_prefix( set->name, "panel_" ) )
{
xname = set->name + 6;
if ( !strcmp( xname, "prev" ) )
i = -1;
else if ( !strcmp( xname, "next" ) )
i = -2;
else if ( !strcmp( xname, "hide" ) )
i = -3;
else
i = atoi( xname );
focus_panel( NULL, main_window, i );
}
else if ( g_str_has_prefix( set->name, "plug_" ) )
on_plugin_install( NULL, main_window, set );
else if ( g_str_has_prefix( set->name, "task_" ) )
{
xname = set->name + 5;
if ( strstr( xname, "_manager" ) )
on_task_popup_show( NULL, main_window, set->name );
else if ( !strcmp( xname, "col_reorder" ) )
on_reorder( NULL, GTK_WIDGET( browser->task_view ) );
else if ( g_str_has_prefix( xname, "col_" ) )
on_task_column_selected( NULL, browser->task_view );
else if ( g_str_has_prefix( xname, "stop" )
|| g_str_has_prefix( xname, "pause" )
|| g_str_has_prefix( xname, "que_" )
|| !strcmp( xname, "que" )
|| g_str_has_prefix( xname, "resume" ) )
{
PtkFileTask* ptask = get_selected_task( browser->task_view );
on_task_stop( NULL, browser->task_view, set, ptask );
}
else if ( !strcmp( xname, "showout" ) )
show_task_dialog( NULL, browser->task_view );
else if ( g_str_has_prefix( xname, "err_" ) )
on_task_popup_errset( NULL, main_window, set->name );
}
else if ( !strcmp( set->name, "font_task" ) )
main_update_fonts( NULL, browser );
else if ( !strcmp( set->name, "rubberband" ) )
main_window_rubberband_all();
else
ptk_file_browser_on_action( browser, set->name );
return TRUE;
}
}
if ( ( event->state & GDK_MOD1_MASK ) )
rebuild_menus( main_window );
return FALSE;
}
FMMainWindow* fm_main_window_get_last_active()
{
return all_windows ? FM_MAIN_WINDOW( all_windows->data ) : NULL;
}
const GList* fm_main_window_get_all()
{
return all_windows;
}
static long get_desktop_index( GtkWindow* win )
{
long desktop = -1;
GdkDisplay* display;
GdkWindow* window = NULL;
if ( win )
{
// get desktop of win
display = gtk_widget_get_display( GTK_WIDGET( win ) );
window = gtk_widget_get_window( GTK_WIDGET( win ) );
}
else
{
// get current desktop
display = gdk_display_get_default();
if ( display )
window = gdk_x11_window_lookup_for_display( display,
gdk_x11_get_default_root_xwindow() );
}
if ( !( GDK_IS_DISPLAY( display ) && GDK_IS_WINDOW( window ) ) )
return desktop;
// find out what desktop (workspace) window is on #include <gdk/gdkx.h>
Atom type;
gint format;
gulong nitems;
gulong bytes_after;
guchar *data;
const gchar* atom_name = win ? "_NET_WM_DESKTOP" : "_NET_CURRENT_DESKTOP";
Atom net_wm_desktop = gdk_x11_get_xatom_by_name_for_display ( display, atom_name );
if ( net_wm_desktop == None )
fprintf( stderr, "spacefm: %s atom not found\n", atom_name );
else if ( XGetWindowProperty( GDK_DISPLAY_XDISPLAY( display ),
GDK_WINDOW_XID( window ),
net_wm_desktop, 0, 1,
False, XA_CARDINAL, (Atom*)&type,
&format, &nitems, &bytes_after,
&data ) != Success || type == None || data == NULL )
{
if ( type == None )
fprintf( stderr, "spacefm: No such property from XGetWindowProperty() %s\n",
atom_name );
else if ( data == NULL )
fprintf( stderr, "spacefm: No data returned from XGetWindowProperty() %s\n",
atom_name );
else
fprintf( stderr, "spacefm: XGetWindowProperty() %s failed\n",
atom_name );
}
else
{
desktop = *data;
XFree( data );
}
return desktop;
}
FMMainWindow* fm_main_window_get_on_current_desktop()
{ // find the last used spacefm window on the current desktop
long desktop;
long cur_desktop = get_desktop_index( NULL );
//printf("current_desktop = %ld\n", cur_desktop );
if ( cur_desktop == -1 )
return fm_main_window_get_last_active(); // revert to dumb if no current
GList* l;
gboolean invalid = FALSE;
for ( l = all_windows; l; l = l->next )
{
desktop = get_desktop_index( GTK_WINDOW( (FMMainWindow*)l->data ) );
//printf( " test win %p = %ld\n", (FMMainWindow*)l->data, desktop );
if ( desktop == cur_desktop || desktop > 254 /* 255 == all desktops */ )
return (FMMainWindow*)l->data;
else if ( desktop == -1 && !invalid )
invalid = TRUE;
}
// revert to dumb if one or more window desktops unreadable
return invalid ? fm_main_window_get_last_active() : NULL;
}
enum {
TASK_COL_STATUS,
TASK_COL_COUNT,
TASK_COL_PATH,
TASK_COL_FILE,
TASK_COL_TO,
TASK_COL_PROGRESS,
TASK_COL_TOTAL,
TASK_COL_STARTED,
TASK_COL_ELAPSED,
TASK_COL_CURSPEED,
TASK_COL_CUREST,
TASK_COL_AVGSPEED,
TASK_COL_AVGEST,
TASK_COL_STARTTIME,
TASK_COL_ICON,
TASK_COL_DATA
};
const char* task_titles[] =
{
// If you change "Status", also change it in on_task_button_press_event
N_( "Status" ), N_( "#" ), N_( "Folder" ), N_( "Item" ),
N_( "To" ), N_( "Progress" ), N_( "Total" ),
N_( "Started" ), N_( "Elapsed" ), N_( "Current" ), N_( "CRemain" ),
N_( "Average" ), N_( "Remain" ), "StartTime"
};
const char* task_names[] =
{
"task_col_status", "task_col_count",
"task_col_path", "task_col_file", "task_col_to",
"task_col_progress", "task_col_total", "task_col_started",
"task_col_elapsed", "task_col_curspeed", "task_col_curest",
"task_col_avgspeed", "task_col_avgest"
};
void on_reorder( GtkWidget* item, GtkWidget* parent )
{
xset_msg_dialog( parent, 0, _("Reorder Columns Help"), NULL, 0, _("To change the order of the columns, drag the column header to the desired location."), NULL, NULL );
}
void main_context_fill( PtkFileBrowser* file_browser, XSetContext* c )
{
PtkFileBrowser* a_browser;
VFSFileInfo* file;
VFSMimeType* mime_type;
GtkClipboard* clip = NULL;
GList* sel_files;
int no_write_access = 0, no_read_access = 0;
VFSVolume* vol;
PtkFileTask* ptask;
char* path;
GtkTreeModel* model;
GtkTreeModel* model_task;
GtkTreeIter it;
c->valid = FALSE;
if ( !GTK_IS_WIDGET( file_browser ) )
return;
FMMainWindow* main_window = (FMMainWindow*)file_browser->main_window;
if ( !main_window )
return;
if ( !c->var[CONTEXT_NAME] )
{
// if name is set, assume we don't need all selected files info
c->var[CONTEXT_DIR] = g_strdup( ptk_file_browser_get_cwd( file_browser ) );
if ( !c->var[CONTEXT_DIR] )
c->var[CONTEXT_DIR] = g_strdup( "" );
else
{
c->var[CONTEXT_WRITE_ACCESS] = ptk_file_browser_no_access(
c->var[CONTEXT_DIR], NULL ) ?
g_strdup( "false" ) : g_strdup( "true" );
}
if ( sel_files = ptk_file_browser_get_selected_files( file_browser ) )
file = vfs_file_info_ref( (VFSFileInfo*)sel_files->data );
else
file = NULL;
if ( !file )
{
c->var[CONTEXT_NAME] = g_strdup( "" );
c->var[CONTEXT_IS_DIR] = g_strdup( "false" );
c->var[CONTEXT_IS_TEXT] = g_strdup( "false" );
c->var[CONTEXT_IS_LINK] = g_strdup( "false" );
c->var[CONTEXT_MIME] = g_strdup( "" );
c->var[CONTEXT_MUL_SEL] = g_strdup( "false" );
}
else
{
c->var[CONTEXT_NAME] = g_strdup( vfs_file_info_get_name( file ) );
path = g_build_filename( c->var[CONTEXT_DIR],
c->var[CONTEXT_NAME], NULL );
c->var[CONTEXT_IS_DIR] = path &&
g_file_test( path, G_FILE_TEST_IS_DIR ) ?
g_strdup( "true" ) : g_strdup( "false" );
c->var[CONTEXT_IS_TEXT] = vfs_file_info_is_text( file, path ) ?
g_strdup( "true" ) : g_strdup( "false" );
c->var[CONTEXT_IS_LINK] = vfs_file_info_is_symlink( file ) ?
g_strdup( "true" ) : g_strdup( "false" );
mime_type = vfs_file_info_get_mime_type( file );
if ( mime_type )
{
c->var[CONTEXT_MIME] = g_strdup( vfs_mime_type_get_type( mime_type ) );
vfs_mime_type_unref( mime_type );
}
else
c->var[CONTEXT_MIME] = g_strdup( "" );
c->var[CONTEXT_MUL_SEL] = sel_files->next ?
g_strdup( "true" ) : g_strdup( "false" );
vfs_file_info_unref( file );
g_free( path );
}
if ( sel_files )
{
g_list_foreach( sel_files, ( GFunc ) vfs_file_info_unref, NULL );
g_list_free( sel_files );
}
}
if ( !c->var[CONTEXT_IS_ROOT] )
c->var[CONTEXT_IS_ROOT] = geteuid() == 0 ?
g_strdup( "true" ) : g_strdup( "false" );
if ( !c->var[CONTEXT_CLIP_FILES] )
{
clip = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD );
if ( ! gtk_clipboard_wait_is_target_available ( clip,
gdk_atom_intern( "x-special/gnome-copied-files", FALSE ) ) &&
! gtk_clipboard_wait_is_target_available ( clip,
gdk_atom_intern( "text/uri-list", FALSE ) ) )
c->var[CONTEXT_CLIP_FILES] = g_strdup( "false" );
else
c->var[CONTEXT_CLIP_FILES] = g_strdup( "true" );
}
if ( !c->var[CONTEXT_CLIP_TEXT] )
{
if ( !clip )
clip = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD );
c->var[CONTEXT_CLIP_TEXT] = gtk_clipboard_wait_is_text_available( clip ) ?
g_strdup( "true" ) : g_strdup( "false" );
}
// hack - Due to ptk_file_browser_update_views main iteration, fb tab may be destroyed
// asynchronously - common if gui thread is blocked on stat
if ( !GTK_IS_WIDGET( file_browser ) )
return;
if ( file_browser->side_book )
{
if ( !GTK_IS_WIDGET( file_browser->side_book ) )
return;
c->var[CONTEXT_BOOKMARK] = g_strdup( ptk_bookmark_view_get_selected_dir(
GTK_TREE_VIEW( file_browser->side_book ) ) );
}
if ( !c->var[CONTEXT_BOOKMARK] )
c->var[CONTEXT_BOOKMARK] = g_strdup( "" );
#ifndef HAVE_HAL
// device
if ( file_browser->side_dev &&
( vol = ptk_location_view_get_selected_vol(
GTK_TREE_VIEW( file_browser->side_dev ) ) ) )
{
c->var[CONTEXT_DEVICE] = g_strdup( vol->device_file );
if ( !c->var[CONTEXT_DEVICE] )
c->var[CONTEXT_DEVICE] = g_strdup( "" );
c->var[CONTEXT_DEVICE_LABEL] = g_strdup( vol->label );
if ( !c->var[CONTEXT_DEVICE_LABEL] )
c->var[CONTEXT_DEVICE_LABEL] = g_strdup( "" );
c->var[CONTEXT_DEVICE_MOUNT_POINT] = g_strdup( vol->mount_point );
if ( !c->var[CONTEXT_DEVICE_MOUNT_POINT] )
c->var[CONTEXT_DEVICE_MOUNT_POINT] = g_strdup( "" );
c->var[CONTEXT_DEVICE_UDI] = g_strdup( vol->udi );
if ( !c->var[CONTEXT_DEVICE_UDI] )
c->var[CONTEXT_DEVICE_UDI] = g_strdup( "" );
c->var[CONTEXT_DEVICE_FSTYPE] = g_strdup( vol->fs_type );
if ( !c->var[CONTEXT_DEVICE_FSTYPE] )
c->var[CONTEXT_DEVICE_FSTYPE] = g_strdup( "" );
char* flags = g_strdup( "" );
char* old_flags;
if ( vol->is_removable )
{ old_flags = flags; flags = g_strdup_printf( "%s removable", flags ); g_free( old_flags ); }
else
{ old_flags = flags; flags = g_strdup_printf( "%s internal", flags ); g_free( old_flags ); }
if ( vol->requires_eject )
{ old_flags = flags; flags = g_strdup_printf( "%s ejectable", flags ); g_free( old_flags ); }
if ( vol->is_optical )
{ old_flags = flags; flags = g_strdup_printf( "%s optical", flags ); g_free( old_flags ); }
if ( vol->is_table )
{ old_flags = flags; flags = g_strdup_printf( "%s table", flags ); g_free( old_flags ); }
if ( vol->is_floppy )
{ old_flags = flags; flags = g_strdup_printf( "%s floppy", flags ); g_free( old_flags ); }
if ( !vol->is_user_visible )
{ old_flags = flags; flags = g_strdup_printf( "%s policy_hide", flags ); g_free( old_flags ); }
if ( vol->nopolicy )
{ old_flags = flags; flags = g_strdup_printf( "%s policy_noauto", flags ); g_free( old_flags ); }
if ( vol->is_mounted )
{ old_flags = flags; flags = g_strdup_printf( "%s mounted", flags ); g_free( old_flags ); }
else if ( vol->is_mountable && !vol->is_table )
{ old_flags = flags; flags = g_strdup_printf( "%s mountable", flags ); g_free( old_flags ); }
else
{ old_flags = flags; flags = g_strdup_printf( "%s no_media", flags ); g_free( old_flags ); }
if ( vol->is_blank )
{ old_flags = flags; flags = g_strdup_printf( "%s blank", flags ); g_free( old_flags ); }
if ( vol->is_audiocd )
{ old_flags = flags; flags = g_strdup_printf( "%s audiocd", flags ); g_free( old_flags ); }
if ( vol->is_dvd )
{ old_flags = flags; flags = g_strdup_printf( "%s dvd", flags ); g_free( old_flags ); }
c->var[CONTEXT_DEVICE_PROP] = flags;
}
else
{
#endif
c->var[CONTEXT_DEVICE] = g_strdup( "" );
c->var[CONTEXT_DEVICE_LABEL] = g_strdup( "" );
c->var[CONTEXT_DEVICE_MOUNT_POINT] = g_strdup( "" );
c->var[CONTEXT_DEVICE_UDI] = g_strdup( "" );
c->var[CONTEXT_DEVICE_FSTYPE] = g_strdup( "" );
c->var[CONTEXT_DEVICE_PROP] = g_strdup( "" );
#ifndef HAVE_HAL
}
#endif
// panels
int i, p;
int panel_count = 0;
for ( p = 1; p < 5; p++ )
{
if ( !xset_get_b_panel( p, "show" ) )
continue;
i = gtk_notebook_get_current_page( GTK_NOTEBOOK( main_window->panel[p-1] ) );
if ( i != -1 )
{
a_browser = (PtkFileBrowser*)
gtk_notebook_get_nth_page( GTK_NOTEBOOK(
main_window->panel[p-1] ), i );
}
else
continue;
if ( !a_browser || !gtk_widget_get_visible( GTK_WIDGET( a_browser ) ) )
continue;
panel_count++;
c->var[CONTEXT_PANEL1_DIR + p - 1] = g_strdup( ptk_file_browser_get_cwd(
a_browser ) );
#ifndef HAVE_HAL
if ( a_browser->side_dev &&
( vol = ptk_location_view_get_selected_vol(
GTK_TREE_VIEW( a_browser->side_dev ) ) ) )
c->var[CONTEXT_PANEL1_DEVICE + p - 1] = g_strdup( vol->device_file );
#endif
// panel has files selected?
if ( a_browser->view_mode == PTK_FB_ICON_VIEW ||
a_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
sel_files = folder_view_get_selected_items( a_browser, &model );
if ( sel_files )
c->var[CONTEXT_PANEL1_SEL + p - 1] = g_strdup( "true" );
else
c->var[CONTEXT_PANEL1_SEL + p - 1] = g_strdup( "false" );
g_list_foreach( sel_files, (GFunc)gtk_tree_path_free, NULL );
g_list_free( sel_files );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
GtkTreeSelection* tree_sel = gtk_tree_view_get_selection(
GTK_TREE_VIEW( a_browser->folder_view ) );
if ( gtk_tree_selection_count_selected_rows( tree_sel ) > 0 )
c->var[CONTEXT_PANEL1_SEL + p - 1] = g_strdup( "true" );
else
c->var[CONTEXT_PANEL1_SEL + p - 1] = g_strdup( "false" );
}
else
c->var[CONTEXT_PANEL1_SEL + p - 1] = g_strdup( "false" );
if ( file_browser == a_browser )
{
c->var[CONTEXT_TAB] = g_strdup_printf( "%d", i + 1 );
c->var[CONTEXT_TAB_COUNT] = g_strdup_printf( "%d",
gtk_notebook_get_n_pages( GTK_NOTEBOOK(
main_window->panel[p-1] ) ) );
}
}
c->var[CONTEXT_PANEL_COUNT] = g_strdup_printf( "%d", panel_count );
c->var[CONTEXT_PANEL] = g_strdup_printf( "%d", file_browser->mypanel );
if ( !c->var[CONTEXT_TAB] )
c->var[CONTEXT_TAB] = g_strdup( "" );
if ( !c->var[CONTEXT_TAB_COUNT] )
c->var[CONTEXT_TAB_COUNT] = g_strdup( "" );
for ( p = 1; p < 5; p++ )
{
if ( !c->var[CONTEXT_PANEL1_DIR + p - 1] )
c->var[CONTEXT_PANEL1_DIR + p - 1] = g_strdup( "" );
if ( !c->var[CONTEXT_PANEL1_SEL + p - 1] )
c->var[CONTEXT_PANEL1_SEL + p - 1] = g_strdup( "false" );
if ( !c->var[CONTEXT_PANEL1_DEVICE + p - 1] )
c->var[CONTEXT_PANEL1_DEVICE + p - 1] = g_strdup( "" );
}
// tasks
const char* job_titles[] =
{
"move",
"copy",
"trash",
"delete",
"link",
"change",
"run"
};
if ( ptask = get_selected_task( file_browser->task_view ) )
{
c->var[CONTEXT_TASK_TYPE] = g_strdup( job_titles[ptask->task->type] );
if ( ptask->task->type == VFS_FILE_TASK_EXEC )
{
c->var[CONTEXT_TASK_NAME] = g_strdup( ptask->task->current_file );
c->var[CONTEXT_TASK_DIR] = g_strdup( ptask->task->dest_dir );
}
else
{
c->var[CONTEXT_TASK_NAME] = g_strdup( "" );
g_mutex_lock( ptask->task->mutex );
if ( ptask->task->current_file )
c->var[CONTEXT_TASK_DIR] = g_path_get_dirname( ptask->task->current_file );
else
c->var[CONTEXT_TASK_DIR] = g_strdup( "" );
g_mutex_unlock( ptask->task->mutex );
}
}
else
{
c->var[CONTEXT_TASK_TYPE] = g_strdup( "" );
c->var[CONTEXT_TASK_NAME] = g_strdup( "" );
c->var[CONTEXT_TASK_DIR] = g_strdup( "" );
}
if ( !main_window->task_view || !GTK_IS_TREE_VIEW( main_window->task_view ) )
c->var[CONTEXT_TASK_COUNT] = g_strdup( "0" );
else
{
model_task = gtk_tree_view_get_model( GTK_TREE_VIEW( main_window->task_view ) );
int task_count = 0;
if ( gtk_tree_model_get_iter_first( model_task, &it ) )
{
task_count++;
while ( gtk_tree_model_iter_next( model_task, &it ) );
task_count++;
}
c->var[CONTEXT_TASK_COUNT] = g_strdup_printf( "%d", task_count );
}
c->valid = TRUE;
}
FMMainWindow* get_task_view_window( GtkWidget* view )
{
FMMainWindow* a_window;
GList* l;
for ( l = all_windows; l; l = l->next )
{
if ( ((FMMainWindow*)l->data)->task_view == view )
return (FMMainWindow*)l->data;
}
return NULL;
}
gboolean main_write_exports( VFSFileTask* vtask, const char* value, FILE* file )
{
int result, p, num_pages, i;
const char* cwd;
char* path;
char* esc_path;
GList* sel_files;
GList* l;
PtkFileBrowser* a_browser;
VFSVolume* vol;
PtkFileTask* ptask;
if ( !vtask->exec_browser )
return FALSE;
PtkFileBrowser* file_browser = (PtkFileBrowser*)vtask->exec_browser;
FMMainWindow* main_window = (FMMainWindow*)file_browser->main_window;
XSet* set = (XSet*)vtask->exec_set;
if ( !file )
return FALSE;
result = fputs( "# source\n\n", file );
if ( result < 0 ) return FALSE;
write_src_functions( file );
// panels
for ( p = 1; p < 5; p++ )
{
if ( !xset_get_b_panel( p, "show" ) )
continue;
i = gtk_notebook_get_current_page( GTK_NOTEBOOK( main_window->panel[p-1] ) );
if ( i != -1 )
{
a_browser = PTK_FILE_BROWSER( gtk_notebook_get_nth_page(
GTK_NOTEBOOK( main_window->panel[p-1] ), i ) );
}
else
continue;
if ( !a_browser || !gtk_widget_get_visible( GTK_WIDGET( a_browser ) ) )
continue;
// cwd
gboolean cwd_needs_quote;
cwd = ptk_file_browser_get_cwd( a_browser );
if ( cwd_needs_quote = !!strchr( cwd, '\'' ) )
{
path = bash_quote( cwd );
fprintf( file, "\nfm_pwd_panel[%d]=%s\n", p, path );
g_free( path );
}
else
fprintf( file, "\nfm_pwd_panel[%d]='%s'\n", p, cwd );
fprintf( file, "\nfm_tab_panel[%d]=%d\n", p, i + 1 );
// selected files
sel_files = ptk_file_browser_get_selected_files( a_browser );
if ( sel_files )
{
fprintf( file, "fm_panel%d_files=(\n", p );
for ( l = sel_files; l; l = l->next )
{
path = (char*)vfs_file_info_get_name( (VFSFileInfo*)l->data );
if ( G_LIKELY( !cwd_needs_quote && !strchr( path, '\'' ) ) )
fprintf( file, "'%s%s%s'\n", cwd,
( cwd[0] != '\0' && cwd[1] == '\0' ) ? "" : "/",
path );
else
{
path = g_build_filename( cwd, path, NULL );
esc_path = bash_quote( path );
fprintf( file, "%s\n", esc_path );
g_free( esc_path );
g_free( path );
}
}
fputs( ")\n", file );
if ( file_browser == a_browser )
{
fprintf( file, "fm_filenames=(\n" );
for ( l = sel_files; l; l = l->next )
{
path = (char*)vfs_file_info_get_name( (VFSFileInfo*)l->data );
if ( G_LIKELY( !strchr( path, '\'' ) ) )
fprintf( file, "'%s'\n", path );
else
{
esc_path = bash_quote( path );
fprintf( file, "%s\n", esc_path );
g_free( esc_path );
}
}
fputs( ")\n", file );
}
g_list_foreach( sel_files, ( GFunc ) vfs_file_info_unref, NULL );
g_list_free( sel_files );
}
/*
// cwd
cwd = ptk_file_browser_get_cwd( a_browser );
path = bash_quote( cwd );
fprintf( file, "\nfm_panel%d_pwd=%s\n", p, path );
g_free( path );
// selected files
sel_files = ptk_file_browser_get_selected_files( a_browser );
if ( sel_files )
{
fprintf( file, "fm_panel%d_files=(\n", p );
for ( l = sel_files; l; l = l->next )
{
path = g_build_filename( cwd,
vfs_file_info_get_name( (VFSFileInfo*)l->data ), NULL );
esc_path = bash_quote( path );
fprintf( file, "%s\n", esc_path );
g_free( esc_path );
g_free( path );
}
fputs( ")\n", file );
if ( file_browser == a_browser )
{
fprintf( file, "fm_filenames=(\n", p );
for ( l = sel_files; l; l = l->next )
{
esc_path = bash_quote( vfs_file_info_get_name( (VFSFileInfo*)l->data ) );
fprintf( file, "%s\n", esc_path );
g_free( esc_path );
}
fputs( ")\n", file );
}
g_list_foreach( sel_files, ( GFunc ) vfs_file_info_unref, NULL );
g_list_free( sel_files );
}
*/
// bookmark
if ( a_browser->side_book )
{
path = ptk_bookmark_view_get_selected_dir( GTK_TREE_VIEW(
a_browser->side_book ) );
if ( path )
{
esc_path = bash_quote( path );
if ( file_browser == a_browser )
fprintf( file, "fm_bookmark=%s\n", esc_path );
fprintf( file, "fm_panel%d_bookmark=%s\n", p, esc_path );
g_free( esc_path );
}
}
#ifndef HAVE_HAL
// device
if ( a_browser->side_dev )
{
vol = ptk_location_view_get_selected_vol(
GTK_TREE_VIEW( a_browser->side_dev ) );
if ( vol )
{
if ( file_browser == a_browser )
{
fprintf( file, "fm_device='%s'\n", vol->device_file );
if ( vol->udi )
{
esc_path = bash_quote( vol->udi );
fprintf( file, "fm_device_udi=%s\n", esc_path );
g_free( esc_path );
}
if ( vol->mount_point )
{
esc_path = bash_quote( vol->mount_point );
fprintf( file, "fm_device_mount_point=%s\n",
esc_path );
g_free( esc_path );
}
if ( vol->label )
{
esc_path = bash_quote( vol->label );
fprintf( file, "fm_device_label=%s\n", esc_path );
g_free( esc_path );
}
if ( vol->fs_type )
fprintf( file, "fm_device_fstype='%s'\n", vol->fs_type );
fprintf( file, "fm_device_size=\"%lu\"\n", vol->size );
if ( vol->disp_name )
{
esc_path = bash_quote( vol->disp_name );
fprintf( file, "fm_device_display_name=%s\n", esc_path );
g_free( esc_path );
}
fprintf( file, "fm_device_icon='%s'\n", vol->icon );
fprintf( file, "fm_device_is_mounted=%d\n",
vol->is_mounted ? 1 : 0 );
fprintf( file, "fm_device_is_optical=%d\n",
vol->is_optical ? 1 : 0 );
fprintf( file, "fm_device_is_table=%d\n",
vol->is_table ? 1 : 0 );
fprintf( file, "fm_device_is_floppy=%d\n",
vol->is_floppy ? 1 : 0 );
fprintf( file, "fm_device_is_removable=%d\n",
vol->is_removable ? 1 : 0 );
fprintf( file, "fm_device_is_audiocd=%d\n",
vol->is_audiocd ? 1 : 0 );
fprintf( file, "fm_device_is_dvd=%d\n",
vol->is_dvd ? 1 : 0 );
fprintf( file, "fm_device_is_blank=%d\n",
vol->is_blank ? 1 : 0 );
fprintf( file, "fm_device_is_mountable=%d\n",
vol->is_mountable ? 1 : 0 );
fprintf( file, "fm_device_nopolicy=%d\n",
vol->nopolicy ? 1 : 0 );
}
fprintf( file, "fm_panel%d_device='%s'\n", p, vol->device_file );
if ( vol->udi )
{
esc_path = bash_quote( vol->udi );
fprintf( file, "fm_panel%d_device_udi=%s\n", p, esc_path );
g_free( esc_path );
}
if ( vol->mount_point )
{
esc_path = bash_quote( vol->mount_point );
fprintf( file, "fm_panel%d_device_mount_point=%s\n",
p, esc_path );
g_free( esc_path );
}
if ( vol->label )
{
esc_path = bash_quote( vol->label );
fprintf( file, "fm_panel%d_device_label=%s\n", p, esc_path );
g_free( esc_path );
}
if ( vol->fs_type )
fprintf( file, "fm_panel%d_device_fstype='%s'\n", p,
vol->fs_type );
fprintf( file, "fm_panel%d_device_size=\"%lu\"\n", p, vol->size );
if ( vol->disp_name )
{
esc_path = bash_quote( vol->disp_name );
fprintf( file, "fm_panel%d_device_display_name=%s\n", p,
esc_path );
g_free( esc_path );
}
fprintf( file, "fm_panel%d_device_icon='%s'\n", p, vol->icon );
fprintf( file, "fm_panel%d_device_is_mounted=%d\n",
p, vol->is_mounted ? 1 : 0 );
fprintf( file, "fm_panel%d_device_is_optical=%d\n",
p, vol->is_optical ? 1 : 0 );
fprintf( file, "fm_panel%d_device_is_table=%d\n",
p, vol->is_table ? 1 : 0 );
fprintf( file, "fm_panel%d_device_is_floppy=%d\n",
p, vol->is_floppy ? 1 : 0 );
fprintf( file, "fm_panel%d_device_is_removable=%d\n",
p, vol->is_removable ? 1 : 0 );
fprintf( file, "fm_panel%d_device_is_audiocd=%d\n",
p, vol->is_audiocd ? 1 : 0 );
fprintf( file, "fm_panel%d_device_is_dvd=%d\n",
p, vol->is_dvd ? 1 : 0 );
fprintf( file, "fm_panel%d_device_is_blank=%d\n",
p, vol->is_blank ? 1 : 0 );
fprintf( file, "fm_panel%d_device_is_mountable=%d\n",
p, vol->is_mountable ? 1 : 0 );
fprintf( file, "fm_panel%d_device_nopolicy=%d\n",
p, vol->nopolicy ? 1 : 0 );
}
}
#endif
// tabs
PtkFileBrowser* t_browser;
num_pages = gtk_notebook_get_n_pages( GTK_NOTEBOOK( main_window->panel[p-1] ) );
for ( i = 0; i < num_pages; i++ )
{
t_browser = PTK_FILE_BROWSER( gtk_notebook_get_nth_page(
GTK_NOTEBOOK( main_window->panel[p-1] ), i ) );
path = bash_quote( ptk_file_browser_get_cwd( t_browser ) );
fprintf( file, "fm_pwd_panel%d_tab[%d]=%s\n", p, i + 1, path );
if ( p == file_browser->mypanel )
{
fprintf( file, "fm_pwd_tab[%d]=%s\n", i + 1, path );
}
if ( file_browser == t_browser )
{
// my browser
fprintf( file, "fm_pwd=%s\n", path );
fprintf( file, "fm_panel=%d\n", p );
fprintf( file, "fm_tab=%d\n", i + 1 );
//if ( i > 0 )
// fprintf( file, "fm_tab_prev=%d\n", i );
//if ( i < num_pages - 1 )
// fprintf( file, "fm_tab_next=%d\n", i + 2 );
}
g_free( path );
}
}
// my selected files
fprintf( file, "\nfm_files=(\"${fm_panel%d_files[@]}\")\n",
file_browser->mypanel );
fprintf( file, "fm_file=\"${fm_panel%d_files[0]}\"\n",
file_browser->mypanel );
fprintf( file, "fm_filename=\"${fm_filenames[0]}\"\n" );
// command
if ( vtask->exec_command )
{
esc_path = bash_quote( vtask->exec_command );
fprintf( file, "fm_command=%s\n", esc_path );
g_free( esc_path );
}
// user
const char* this_user = g_get_user_name();
if ( this_user )
{
esc_path = bash_quote( this_user );
fprintf( file, "fm_user=%s\n", esc_path );
g_free( esc_path );
//g_free( this_user ); DON'T
}
// variable value
if ( value )
{
esc_path = bash_quote( value );
fprintf( file, "fm_value=%s\n", esc_path );
g_free( esc_path );
}
if ( vtask->exec_ptask )
{
fprintf( file, "fm_my_task=%p\n", vtask->exec_ptask );
fprintf( file, "fm_my_task_id=%p\n", vtask->exec_ptask );
}
fprintf( file, "fm_my_window=%p\n", main_window );
fprintf( file, "fm_my_window_id=%p\n", main_window );
// utils
esc_path = bash_quote( xset_get_s( "editor" ) );
fprintf( file, "fm_editor=%s\n", esc_path );
g_free( esc_path );
fprintf( file, "fm_editor_terminal=%d\n", xset_get_b( "editor" ) ? 1 : 0 );
// set
if ( set )
{
// cmd_dir
if ( set->plugin )
{
path = g_build_filename( set->plug_dir, "files", NULL );
if ( !g_file_test( path, G_FILE_TEST_EXISTS ) )
{
g_free( path );
path = g_build_filename( set->plug_dir, set->plug_name, NULL );
}
}
else
{
path = g_build_filename( xset_get_config_dir(), "scripts",
set->name, NULL );
}
esc_path = bash_quote( path );
fprintf( file, "fm_cmd_dir=%s\n", esc_path );
g_free( esc_path );
g_free( path );
// cmd_data
if ( set->plugin )
{
XSet* mset = xset_get_plugin_mirror( set );
path = g_build_filename( xset_get_config_dir(), "plugin-data",
mset->name, NULL );
}
else
path = g_build_filename( xset_get_config_dir(), "plugin-data",
set->name, NULL );
esc_path = bash_quote( path );
fprintf( file, "fm_cmd_data=%s\n", esc_path );
g_free( esc_path );
g_free( path );
// plugin_dir
if ( set->plugin )
{
esc_path = bash_quote( set->plug_dir );
fprintf( file, "fm_plugin_dir=%s\n", esc_path );
g_free( esc_path );
}
// cmd_name
if ( set->menu_label )
{
esc_path = bash_quote( set->menu_label );
fprintf( file, "fm_cmd_name=%s\n", esc_path );
g_free( esc_path );
}
}
// tmp
if ( geteuid() != 0 && vtask->exec_as_user
&& !strcmp( vtask->exec_as_user, "root" ) )
fprintf( file, "fm_tmp_dir=%s\n", xset_get_shared_tmp_dir() );
else
fprintf( file, "fm_tmp_dir=%s\n", xset_get_user_tmp_dir() );
// tasks
const char* job_titles[] =
{
"move",
"copy",
"trash",
"delete",
"link",
"change",
"run"
};
if ( ptask = get_selected_task( file_browser->task_view ) )
{
fprintf( file, "\nfm_task_type='%s'\n", job_titles[ptask->task->type] );
if ( ptask->task->type == VFS_FILE_TASK_EXEC )
{
esc_path = bash_quote( ptask->task->dest_dir );
fprintf( file, "fm_task_pwd=%s\n", esc_path );
g_free( esc_path );
esc_path = bash_quote( ptask->task->current_file );
fprintf( file, "fm_task_name=%s\n", esc_path );
g_free( esc_path );
esc_path = bash_quote( ptask->task->exec_command );
fprintf( file, "fm_task_command=%s\n", esc_path );
g_free( esc_path );
if ( ptask->task->exec_as_user )
fprintf( file, "fm_task_user='%s'\n", ptask->task->exec_as_user );
if ( ptask->task->exec_icon )
fprintf( file, "fm_task_icon='%s'\n", ptask->task->exec_icon );
if ( ptask->task->exec_pid )
fprintf( file, "fm_task_pid=%d\n", ptask->task->exec_pid );
}
else
{
esc_path = bash_quote( ptask->task->dest_dir );
fprintf( file, "fm_task_dest_dir=%s\n", esc_path );
g_free( esc_path );
esc_path = bash_quote( ptask->task->current_file );
fprintf( file, "fm_task_current_src_file=%s\n", esc_path );
g_free( esc_path );
esc_path = bash_quote( ptask->task->current_dest );
fprintf( file, "fm_task_current_dest_file=%s\n", esc_path );
g_free( esc_path );
}
fprintf( file, "fm_task_id=%p\n", ptask );
if ( ptask->task_view &&
( main_window = get_task_view_window( ptask->task_view ) ) )
{
fprintf( file, "fm_task_window=%p\n", main_window );
fprintf( file, "fm_task_window_id=%p\n", main_window );
}
}
result = fputs( "\n", file );
return result >= 0;
}
void on_task_columns_changed( GtkWidget *view, gpointer user_data )
{
const char* title;
char* pos;
XSet* set = NULL;
int i, j, width;
GtkTreeViewColumn* col;
gboolean fullscreen = xset_get_b( "main_full" );
if ( !view )
return;
for ( i = 0; i < 13; i++ )
{
col = gtk_tree_view_get_column( GTK_TREE_VIEW( view ), i );
if ( !col )
return;
title = gtk_tree_view_column_get_title( col );
for ( j = 0; j < 13; j++ )
{
if ( !strcmp( title, _(task_titles[j]) ) )
break;
}
if ( j != 13 )
{
set = xset_get( task_names[j] );
// save column position
pos = g_strdup_printf( "%d", i );
xset_set_set( set, "x", pos );
g_free( pos );
if ( !fullscreen )
{
width = gtk_tree_view_column_get_width( col );
if ( width ) // manager unshown, all widths are zero
{
// save column width
pos = g_strdup_printf( "%d", width );
xset_set_set( set, "y", pos );
g_free( pos );
}
}
// set column visibility
gtk_tree_view_column_set_visible( col, xset_get_b( task_names[j] ) );
}
}
}
void on_task_destroy( GtkWidget *view, gpointer user_data )
{
guint id = g_signal_lookup ("columns-changed", G_TYPE_FROM_INSTANCE(view) );
if ( id )
{
gulong hand = g_signal_handler_find( ( gpointer ) view, G_SIGNAL_MATCH_ID,
id, 0, NULL, NULL, NULL );
if ( hand )
g_signal_handler_disconnect( ( gpointer ) view, hand );
}
on_task_columns_changed( view, NULL ); // save widths
}
void on_task_column_selected( GtkMenuItem* item, GtkWidget* view )
{
on_task_columns_changed( view, NULL );
}
gboolean main_tasks_running( FMMainWindow* main_window )
{
GtkTreeIter it;
if ( !main_window->task_view || !GTK_IS_TREE_VIEW( main_window->task_view ) )
return FALSE;
GtkTreeModel* model = gtk_tree_view_get_model(
GTK_TREE_VIEW( main_window->task_view ) );
gboolean ret = gtk_tree_model_get_iter_first( model, &it );
return ret;
}
void main_task_pause_all_queued( PtkFileTask* ptask )
{
PtkFileTask* qtask;
GtkTreeIter it;
if ( !ptask->task_view )
return;
GtkTreeModel* model = gtk_tree_view_get_model( GTK_TREE_VIEW( ptask->task_view ) );
if ( gtk_tree_model_get_iter_first( model, &it ) )
{
do
{
gtk_tree_model_get( model, &it, TASK_COL_DATA, &qtask, -1 );
if ( qtask && qtask != ptask && qtask->task && !qtask->complete &&
qtask->task->state_pause == VFS_FILE_TASK_QUEUE )
ptk_file_task_pause( qtask, VFS_FILE_TASK_PAUSE );
}
while ( gtk_tree_model_iter_next( model, &it ) );
}
}
void main_task_start_queued( GtkWidget* view, PtkFileTask* new_task )
{
GtkTreeModel* model;
GtkTreeIter it;
PtkFileTask* qtask;
PtkFileTask* rtask;
GSList* running = NULL;
GSList* queued = NULL;
gboolean smart;
#ifdef HAVE_HAL
smart = FALSE;
#else
smart = xset_get_b( "task_q_smart" );
#endif
if ( !GTK_IS_TREE_VIEW( view ) )
return;
model = gtk_tree_view_get_model( GTK_TREE_VIEW( view ) );
if ( gtk_tree_model_get_iter_first( model, &it ) )
{
do
{
gtk_tree_model_get( model, &it, TASK_COL_DATA, &qtask, -1 );
if ( qtask && qtask->task && !qtask->complete &&
qtask->task->state == VFS_FILE_TASK_RUNNING )
{
if ( qtask->task->state_pause == VFS_FILE_TASK_QUEUE )
queued = g_slist_append( queued, qtask );
else if ( qtask->task->state_pause == VFS_FILE_TASK_RUNNING )
running = g_slist_append( running, qtask );
}
}
while ( gtk_tree_model_iter_next( model, &it ) );
}
if ( new_task && new_task->task && !new_task->complete &&
new_task->task->state_pause == VFS_FILE_TASK_QUEUE &&
new_task->task->state == VFS_FILE_TASK_RUNNING )
queued = g_slist_append( queued, new_task );
if ( !queued || ( !smart && running ) )
goto _done;
if ( !smart )
{
ptk_file_task_pause( (PtkFileTask*)queued->data, VFS_FILE_TASK_RUNNING );
goto _done;
}
// smart
GSList* d;
GSList* r;
GSList* q;
for ( q = queued; q; q = q->next )
{
qtask = (PtkFileTask*)q->data;
if ( !qtask->task->devs )
{
// qtask has no devices so run it
running = g_slist_append( running, qtask );
ptk_file_task_pause( qtask, VFS_FILE_TASK_RUNNING );
continue;
}
// does qtask have running devices?
for ( r = running; r; r = r->next )
{
rtask = (PtkFileTask*)r->data;
for ( d = qtask->task->devs; d; d = d->next )
{
if ( g_slist_find( rtask->task->devs, d->data ) )
break;
}
if ( d )
break;
}
if ( !r )
{
// qtask has no running devices so run it
running = g_slist_append( running, qtask );
ptk_file_task_pause( qtask, VFS_FILE_TASK_RUNNING );
continue;
}
}
_done:
g_slist_free( queued );
g_slist_free( running );
}
void on_task_stop( GtkMenuItem* item, GtkWidget* view, XSet* set2,
PtkFileTask* task2 )
{
GtkTreeModel* model = NULL;
GtkTreeIter it;
PtkFileTask* ptask;
XSet* set;
int job;
enum { JOB_STOP, JOB_PAUSE, JOB_QUEUE, JOB_RESUME };
if ( item )
set = (XSet*)g_object_get_data( G_OBJECT( item ), "set" );
else
set = set2;
if ( !set || !g_str_has_prefix( set->name, "task_" ) )
return;
char* name = set->name + 5;
if ( g_str_has_prefix( name, "stop" ) )
job = JOB_STOP;
else if ( g_str_has_prefix( name, "pause" ) )
job = JOB_PAUSE;
else if ( g_str_has_prefix( name, "que" ) )
job = JOB_QUEUE;
else if ( g_str_has_prefix( name, "resume" ) )
job = JOB_RESUME;
else
return;
gboolean all = ( g_str_has_suffix( name, "_all" ) );
if ( all )
{
model = gtk_tree_view_get_model( GTK_TREE_VIEW( view ) );
ptask = NULL;
}
else
{
if ( item )
ptask = ( PtkFileTask* ) g_object_get_data( G_OBJECT( item ),
"task" );
else
ptask = task2;
if ( !ptask )
return;
}
if ( !model || ( model && gtk_tree_model_get_iter_first( model, &it ) ) )
{
do
{
if ( model )
gtk_tree_model_get( model, &it, TASK_COL_DATA, &ptask, -1 );
if ( ptask && ptask->task && !ptask->complete &&
( ptask->task->type != VFS_FILE_TASK_EXEC
|| ptask->task->exec_pid || job == JOB_STOP ) )
{
switch ( job )
{
case JOB_STOP:
ptk_file_task_cancel( ptask );
break;
case JOB_PAUSE:
ptk_file_task_pause( ptask, VFS_FILE_TASK_PAUSE );
break;
case JOB_QUEUE:
ptk_file_task_pause( ptask, VFS_FILE_TASK_QUEUE );
break;
case JOB_RESUME:
ptk_file_task_pause( ptask, VFS_FILE_TASK_RUNNING );
break;
}
}
}
while ( model && gtk_tree_model_iter_next( model, &it ) );
}
main_task_start_queued( view, NULL );
}
void on_task_popup_show( GtkMenuItem* item, FMMainWindow* main_window, char* name2 )
{
GtkTreeModel* model = NULL;
GtkTreeIter it;
char* name = NULL;
if ( item )
name = ( char* ) g_object_get_data( G_OBJECT( item ), "name" );
else
name = name2;
if ( name )
{
if ( !strcmp( name, "task_show_manager" ) )
{
if ( xset_get_b( "task_show_manager" ) )
xset_set_b("task_hide_manager", FALSE );
else
{
xset_set_b("task_hide_manager", TRUE );
xset_set_b("task_show_manager", FALSE );
}
}
else
{
if ( xset_get_b( "task_hide_manager" ) )
xset_set_b("task_show_manager", FALSE );
else
{
xset_set_b("task_hide_manager", FALSE );
xset_set_b("task_show_manager", TRUE );
}
}
}
if ( xset_get_b( "task_show_manager" ) )
gtk_widget_show( main_window->task_scroll );
else
{
model = gtk_tree_view_get_model( GTK_TREE_VIEW( main_window->task_view ) );
if ( gtk_tree_model_get_iter_first( model, &it ) )
gtk_widget_show( GTK_WIDGET( main_window->task_scroll ) );
else
{
if ( xset_get_b( "task_hide_manager" ) )
{
gboolean tasks_has_focus = gtk_widget_is_focus(
GTK_WIDGET( main_window->task_view ) );
gtk_widget_hide( GTK_WIDGET( main_window->task_scroll ) );
if ( tasks_has_focus )
{
// focus the file list
PtkFileBrowser* file_browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
if ( file_browser )
gtk_widget_grab_focus( file_browser->folder_view );
}
}
}
}
}
void on_task_popup_errset( GtkMenuItem* item, FMMainWindow* main_window, char* name2 )
{
char* name;
if ( item )
name = ( char* ) g_object_get_data( G_OBJECT( item ), "name" );
else
name = name2;
if ( !name )
return;
if ( !strcmp( name, "task_err_first" ) )
{
if ( xset_get_b( "task_err_first" ) )
{
xset_set_b("task_err_any", FALSE );
xset_set_b("task_err_cont", FALSE );
}
else
{
xset_set_b("task_err_any", FALSE );
xset_set_b("task_err_cont", TRUE );
}
}
else if ( !strcmp( name, "task_err_any" ) )
{
if ( xset_get_b( "task_err_any" ) )
{
xset_set_b("task_err_first", FALSE );
xset_set_b("task_err_cont", FALSE );
}
else
{
xset_set_b("task_err_first", FALSE );
xset_set_b("task_err_cont", TRUE );
}
}
else
{
if ( xset_get_b( "task_err_cont" ) )
{
xset_set_b("task_err_first", FALSE );
xset_set_b("task_err_any", FALSE );
}
else
{
xset_set_b("task_err_first", TRUE );
xset_set_b("task_err_any", FALSE );
}
}
}
void main_task_prepare_menu( FMMainWindow* main_window, GtkWidget* menu,
GtkAccelGroup* accel_group )
{
XSet* set;
XSet* set_radio;
GtkWidget* parent = main_window->task_view;
set = xset_set_cb( "task_show_manager", on_task_popup_show, main_window );
xset_set_ob1( set, "name", set->name );
xset_set_ob2( set, NULL, NULL );
set_radio = set;
set = xset_set_cb( "task_hide_manager", on_task_popup_show, main_window );
xset_set_ob1( set, "name", set->name );
xset_set_ob2( set, NULL, set_radio );
xset_set_cb( "task_col_count", on_task_column_selected, parent );
xset_set_cb( "task_col_path", on_task_column_selected, parent );
xset_set_cb( "task_col_file", on_task_column_selected, parent );
xset_set_cb( "task_col_to", on_task_column_selected, parent );
xset_set_cb( "task_col_progress", on_task_column_selected, parent );
xset_set_cb( "task_col_total", on_task_column_selected, parent );
xset_set_cb( "task_col_started", on_task_column_selected, parent );
xset_set_cb( "task_col_elapsed", on_task_column_selected, parent );
xset_set_cb( "task_col_curspeed", on_task_column_selected, parent );
xset_set_cb( "task_col_curest", on_task_column_selected, parent );
xset_set_cb( "task_col_avgspeed", on_task_column_selected, parent );
xset_set_cb( "task_col_avgest", on_task_column_selected, parent );
xset_set_cb( "task_col_reorder", on_reorder, parent );
set = xset_set_cb( "task_err_first", on_task_popup_errset, main_window );
xset_set_ob1( set, "name", set->name );
xset_set_ob2( set, NULL, NULL );
set_radio = set;
set = xset_set_cb( "task_err_any", on_task_popup_errset, main_window );
xset_set_ob1( set, "name", set->name );
xset_set_ob2( set, NULL, set_radio );
set = xset_set_cb( "task_err_cont", on_task_popup_errset, main_window );
xset_set_ob1( set, "name", set->name );
xset_set_ob2( set, NULL, set_radio );
}
PtkFileTask* get_selected_task( GtkWidget* view )
{
GtkTreeModel* model;
GtkTreeSelection* tree_sel;
GtkTreeViewColumn* col = NULL;
GtkTreeIter it;
PtkFileTask* ptask = NULL;
if ( !view )
return NULL;
FMMainWindow* main_window = get_task_view_window( view );
if ( !main_window )
return NULL;
model = gtk_tree_view_get_model( GTK_TREE_VIEW( view ) );
tree_sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( view ) );
if ( gtk_tree_selection_get_selected( tree_sel, NULL, &it ) )
{
gtk_tree_model_get( model, &it, TASK_COL_DATA, &ptask, -1 );
}
return ptask;
}
void show_task_dialog( GtkWidget* widget, GtkWidget* view )
{
PtkFileTask* ptask = get_selected_task( view );
if ( !ptask )
return;
g_mutex_lock( ptask->task->mutex );
ptk_file_task_progress_open( ptask );
if ( ptask->task->state_pause != VFS_FILE_TASK_RUNNING )
{
// update dlg
ptask->pause_change = TRUE;
ptask->progress_count = 50; // trigger fast display
}
if ( ptask->progress_dlg )
gtk_window_present( GTK_WINDOW( ptask->progress_dlg ) );
g_mutex_unlock( ptask->task->mutex );
}
gboolean on_task_button_press_event( GtkWidget* view, GdkEventButton *event,
FMMainWindow* main_window )
{
GtkTreeModel* model = NULL;
GtkTreePath* tree_path;
GtkTreeViewColumn* col = NULL;
GtkTreeIter it;
GtkTreeSelection* tree_sel;
PtkFileTask* ptask = NULL;
XSet* set;
gboolean is_tasks;
if ( event->type != GDK_BUTTON_PRESS )
return FALSE;
if ( ( evt_win_click->s || evt_win_click->ob2_data ) &&
main_window_event( main_window, evt_win_click, "evt_win_click", 0, 0,
"tasklist", 0, event->button, event->state, TRUE ) )
return FALSE;
if ( event->button == 3 ) // right click
{
// get selected task
model = gtk_tree_view_get_model( GTK_TREE_VIEW( view ) );
if ( is_tasks = gtk_tree_model_get_iter_first( model, &it ) )
{
if ( gtk_tree_view_get_path_at_pos( GTK_TREE_VIEW( view ), event->x,
event->y, &tree_path, &col, NULL, NULL ) )
{
if ( tree_path && gtk_tree_model_get_iter( model, &it, tree_path ) )
gtk_tree_model_get( model, &it, TASK_COL_DATA, &ptask, -1 );
gtk_tree_path_free( tree_path );
}
}
// build popup
PtkFileBrowser* file_browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
if ( !file_browser )
return FALSE;
GtkWidget* popup = gtk_menu_new();
GtkAccelGroup* accel_group = gtk_accel_group_new();
XSetContext* context = xset_context_new();
main_context_fill( file_browser, context );
set = xset_set_cb( "task_stop", on_task_stop, view );
xset_set_ob1( set, "task", ptask );
set->disable = !ptask;
set = xset_set_cb( "task_pause", on_task_stop, view );
xset_set_ob1( set, "task", ptask );
set->disable = ( !ptask || ptask->task->state_pause == VFS_FILE_TASK_PAUSE
|| ( ptask->task->type == VFS_FILE_TASK_EXEC &&
!ptask->task->exec_pid ) );
set = xset_set_cb( "task_que", on_task_stop, view );
xset_set_ob1( set, "task", ptask );
set->disable = ( !ptask || ptask->task->state_pause == VFS_FILE_TASK_QUEUE
|| ( ptask->task->type == VFS_FILE_TASK_EXEC &&
!ptask->task->exec_pid ) );
set = xset_set_cb( "task_resume", on_task_stop, view );
xset_set_ob1( set, "task", ptask );
set->disable = ( !ptask || ptask->task->state_pause == VFS_FILE_TASK_RUNNING
|| ( ptask->task->type == VFS_FILE_TASK_EXEC &&
!ptask->task->exec_pid ) );
xset_set_cb( "task_stop_all", on_task_stop, view );
xset_set_cb( "task_pause_all", on_task_stop, view );
xset_set_cb( "task_que_all", on_task_stop, view );
xset_set_cb( "task_resume_all", on_task_stop, view );
set = xset_get( "task_all" );
set->disable = !is_tasks;
#ifdef HAVE_HAL
set = xset_get( "task_q_smart" );
set->disable = TRUE;
#endif
const char* showout = "";
if ( ptask && ptask->pop_handler )
{
xset_set_cb( "task_showout", show_task_dialog, view );
showout = " task_showout";
}
main_task_prepare_menu( main_window, popup, accel_group );
xset_set_cb( "font_task", main_update_fonts, file_browser );
char* menu_elements = g_strdup_printf( "task_stop sep_t3 task_pause task_que task_resume%s task_all sep_t4 task_show_manager task_hide_manager sep_t5 task_columns task_popups task_errors task_queue", showout );
xset_add_menu( NULL, file_browser, popup, accel_group, menu_elements );
g_free( menu_elements );
gtk_widget_show_all( GTK_WIDGET( popup ) );
g_signal_connect( popup, "selection-done",
G_CALLBACK( gtk_widget_destroy ), NULL );
g_signal_connect( popup, "key_press_event",
G_CALLBACK( xset_menu_keypress ), NULL );
gtk_menu_popup( GTK_MENU( popup ), NULL, NULL, NULL, NULL, event->button,
event->time );
}
else if ( event->button == 1 || event->button == 2 ) // left or middle click
{
// get selected task
model = gtk_tree_view_get_model( GTK_TREE_VIEW( view ) );
//printf("x = %lf y = %lf \n", event->x, event->y );
// due to bug in gtk_tree_view_get_path_at_pos (gtk 2.24), a click
// on the column header resize divider registers as a click on the
// first row first column. So if event->x < 7 ignore
if ( event->x < 7 )
return FALSE;
if ( !gtk_tree_view_get_path_at_pos( GTK_TREE_VIEW( view ), event->x,
event->y, &tree_path, &col, NULL, NULL ) )
return FALSE;
if ( tree_path && gtk_tree_model_get_iter( model, &it, tree_path ) )
gtk_tree_model_get( model, &it, TASK_COL_DATA, &ptask, -1 );
gtk_tree_path_free( tree_path );
if ( !ptask )
return FALSE;
if ( event->button == 1 && g_strcmp0( gtk_tree_view_column_get_title( col ),
_("Status") ) )
return FALSE;
char* sname;
switch ( ptask->task->state_pause )
{
case VFS_FILE_TASK_PAUSE:
sname = "task_que";
break;
case VFS_FILE_TASK_QUEUE:
sname = "task_resume";
break;
default:
sname = "task_pause";
}
set = xset_get( sname );
on_task_stop( NULL, view, set, ptask );
return TRUE;
}
return FALSE;
}
void on_task_row_activated( GtkWidget* view, GtkTreePath* tree_path,
GtkTreeViewColumn *col, gpointer user_data )
{
GtkTreeModel* model;
GtkTreeIter it;
PtkFileTask* ptask;
FMMainWindow* main_window = get_task_view_window( view );
if ( !main_window )
return;
model = gtk_tree_view_get_model( GTK_TREE_VIEW( view ) );
if ( !gtk_tree_model_get_iter( model, &it, tree_path ) )
return;
gtk_tree_model_get( model, &it, TASK_COL_DATA, &ptask, -1 );
if ( ptask )
{
if ( ptask->pop_handler )
{
// show custom dialog
char* argv[4];
argv[0] = g_strdup( "bash" );
argv[1] = g_strdup( "-c" );
argv[2] = g_strdup( ptask->pop_handler );
argv[3] = NULL;
printf( "TASK_POPUP >>> %s\n", argv[2] );
g_spawn_async( NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
NULL, NULL );
}
else
{
// show normal dialog
show_task_dialog( NULL, view );
}
}
}
void main_task_view_remove_task( PtkFileTask* ptask )
{
PtkFileTask* ptaskt = NULL;
GtkWidget* view;
GtkTreeModel* model;
GtkTreeIter it;
//printf("main_task_view_remove_task ptask=%d\n", ptask);
view = ptask->task_view;
if ( !view )
return;
FMMainWindow* main_window = get_task_view_window( view );
if ( !main_window )
return;
model = gtk_tree_view_get_model( GTK_TREE_VIEW( view ) );
if ( gtk_tree_model_get_iter_first( model, &it ) )
{
do
{
gtk_tree_model_get( model, &it, TASK_COL_DATA, &ptaskt, -1 );
}
while ( ptaskt != ptask && gtk_tree_model_iter_next( model, &it ) );
}
if ( ptaskt == ptask )
gtk_list_store_remove( GTK_LIST_STORE( model ), &it );
if ( !gtk_tree_model_get_iter_first( model, &it ) )
{
if ( xset_get_b( "task_hide_manager" ) )
{
gboolean tasks_has_focus = gtk_widget_is_focus( GTK_WIDGET( view ) );
gtk_widget_hide( gtk_widget_get_parent( GTK_WIDGET( view ) ) );
if ( tasks_has_focus )
{
// focus the file list
PtkFileBrowser* file_browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
if ( file_browser )
gtk_widget_grab_focus( file_browser->folder_view );
}
}
}
update_window_title( NULL, main_window );
//printf("main_task_view_remove_task DONE ptask=%d\n", ptask);
}
void main_task_view_update_task( PtkFileTask* ptask )
{
PtkFileTask* ptaskt = NULL;
GtkWidget* view;
GtkTreeModel* model;
GtkTreeIter it;
GdkPixbuf* pixbuf;
char* dest_dir;
char* path = NULL;
char* file = NULL;
XSet* set;
//printf("main_task_view_update_task ptask=%d\n", ptask);
const char* job_titles[] =
{
N_( "moving" ),
N_( "copying" ),
N_( "trashing" ),
N_( "deleting" ),
N_( "linking" ),
N_( "changing" ),
N_( "running" )
};
if ( !ptask )
return;
view = ptask->task_view;
if ( !view )
return;
FMMainWindow* main_window = get_task_view_window( view );
if ( !main_window )
return;
if ( ptask->task->type != VFS_FILE_TASK_EXEC )
dest_dir = ptask->task->dest_dir;
else
dest_dir = NULL;
model = gtk_tree_view_get_model( GTK_TREE_VIEW( view ) );
if ( gtk_tree_model_get_iter_first( model, &it ) )
{
do
{
gtk_tree_model_get( model, &it, TASK_COL_DATA, &ptaskt, -1 );
}
while ( ptaskt != ptask && gtk_tree_model_iter_next( model, &it ) );
}
if ( ptaskt != ptask )
{
// new row
char buf[ 64 ];
strftime( buf, sizeof( buf ), "%H:%M", localtime( &ptask->task->start_time ) );
char* started = g_strdup( buf );
gtk_list_store_insert_with_values( GTK_LIST_STORE( model ), &it, 0,
TASK_COL_TO, dest_dir,
TASK_COL_STARTED, started,
TASK_COL_STARTTIME, (gint64)ptask->task->start_time,
TASK_COL_DATA, ptask,
-1 );
g_free( started );
}
if ( ptask->task->state_pause == VFS_FILE_TASK_RUNNING || ptask->pause_change_view )
{
ptask->pause_change_view = FALSE;
// update row
int percent = ptask->task->percent;
if ( percent < 0 )
percent = 0;
else if ( percent > 100 )
percent = 100;
if ( ptask->task->type != VFS_FILE_TASK_EXEC )
{
if ( ptask->task->current_file )
{
path = g_path_get_dirname( ptask->task->current_file );
file = g_path_get_basename( ptask->task->current_file );
}
}
else
{
path = g_strdup( ptask->task->dest_dir ); //cwd
file = g_strdup_printf( "( %s )", ptask->task->current_file );
}
// icon
char* iname;
if ( ptask->task->state_pause == VFS_FILE_TASK_PAUSE )
{
set = xset_get( "task_pause" );
iname = g_strdup( set->icon ? set->icon : GTK_STOCK_MEDIA_PAUSE );
}
else if ( ptask->task->state_pause == VFS_FILE_TASK_QUEUE )
{
set = xset_get( "task_que" );
iname = g_strdup( set->icon ? set->icon : GTK_STOCK_ADD );
}
else if ( ptask->err_count && ptask->task->type != VFS_FILE_TASK_EXEC )
iname = g_strdup_printf( "error" );
else if ( ptask->task->type == 0 || ptask->task->type == 1 || ptask->task->type == 4 )
iname = g_strdup_printf( "stock_copy" );
else if ( ptask->task->type == 2 || ptask->task->type == 3 )
iname = g_strdup_printf( "stock_delete" );
else if ( ptask->task->type == VFS_FILE_TASK_EXEC && ptask->task->exec_icon )
iname = g_strdup( ptask->task->exec_icon );
else
iname = g_strdup_printf( "gtk-execute" );
pixbuf = gtk_icon_theme_load_icon( gtk_icon_theme_get_default(), iname,
app_settings.small_icon_size, GTK_ICON_LOOKUP_USE_BUILTIN, NULL );
g_free( iname );
if ( !pixbuf )
pixbuf = gtk_icon_theme_load_icon( gtk_icon_theme_get_default(), "gtk-execute",
app_settings.small_icon_size, GTK_ICON_LOOKUP_USE_BUILTIN, NULL );
// status
const char* status;
char* status2 = NULL;
char* status3;
if ( ptask->task->type != VFS_FILE_TASK_EXEC )
{
if ( !ptask->err_count )
status = _(job_titles[ ptask->task->type ]);
else
{
status2 = g_strdup_printf( "%d error%s %s", ptask->err_count,
ptask->err_count > 1 ? "s" : "", _(job_titles[ ptask->task->type ]) );
status = status2;
}
}
else
{
// exec task
if ( ptask->task->exec_action )
status = ptask->task->exec_action;
else
status = _(job_titles[ ptask->task->type ]);
}
if ( ptask->task->state_pause == VFS_FILE_TASK_PAUSE )
status3 = g_strdup_printf( "%s %s", _("paused"), status );
else if ( ptask->task->state_pause == VFS_FILE_TASK_QUEUE )
status3 = g_strdup_printf( "%s %s", _("queued"), status );
else
status3 = g_strdup( status );
if ( ptask->task->type != VFS_FILE_TASK_EXEC || ptaskt != ptask /* new task */ )
{
gtk_list_store_set( GTK_LIST_STORE( model ), &it,
TASK_COL_ICON, pixbuf,
TASK_COL_STATUS, status3,
TASK_COL_COUNT, ptask->dsp_file_count,
TASK_COL_PATH, path,
TASK_COL_FILE, file,
TASK_COL_PROGRESS, percent,
TASK_COL_TOTAL, ptask->dsp_size_tally,
TASK_COL_ELAPSED, ptask->dsp_elapsed,
TASK_COL_CURSPEED, ptask->dsp_curspeed,
TASK_COL_CUREST, ptask->dsp_curest,
TASK_COL_AVGSPEED, ptask->dsp_avgspeed,
TASK_COL_AVGEST, ptask->dsp_avgest,
-1 );
}
else
gtk_list_store_set( GTK_LIST_STORE( model ), &it,
TASK_COL_ICON, pixbuf,
TASK_COL_STATUS, status3,
TASK_COL_PROGRESS, percent,
TASK_COL_ELAPSED, ptask->dsp_elapsed,
-1 );
g_free( file );
g_free( path );
g_free( status2 );
g_free( status3 );
if ( !gtk_widget_get_visible( gtk_widget_get_parent( GTK_WIDGET( view ) ) ) )
gtk_widget_show( gtk_widget_get_parent( GTK_WIDGET( view ) ) );
update_window_title( NULL, main_window );
}
else
{
// task is paused
gtk_list_store_set( GTK_LIST_STORE( model ), &it,
TASK_COL_TOTAL, ptask->dsp_size_tally,
TASK_COL_ELAPSED, ptask->dsp_elapsed,
TASK_COL_CURSPEED, ptask->dsp_curspeed,
TASK_COL_CUREST, ptask->dsp_curest,
TASK_COL_AVGSPEED, ptask->dsp_avgspeed,
TASK_COL_AVGEST, ptask->dsp_avgest,
-1 );
}
//printf("DONE main_task_view_update_task\n");
}
GtkWidget* main_task_view_new( FMMainWindow* main_window )
{
char* elements;
char* space;
char* name;
int i, j, width;
GtkTreeViewColumn* col;
GtkCellRenderer* renderer;
GtkCellRenderer* pix_renderer;
int cols[] = {
TASK_COL_STATUS,
TASK_COL_COUNT,
TASK_COL_PATH,
TASK_COL_FILE,
TASK_COL_TO,
TASK_COL_PROGRESS,
TASK_COL_TOTAL,
TASK_COL_STARTED,
TASK_COL_ELAPSED,
TASK_COL_CURSPEED,
TASK_COL_CUREST,
TASK_COL_AVGSPEED,
TASK_COL_AVGEST,
TASK_COL_STARTTIME,
TASK_COL_ICON,
TASK_COL_DATA
};
int num_cols = G_N_ELEMENTS( cols );
// Model
GtkListStore* list = gtk_list_store_new( num_cols, G_TYPE_STRING,
G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING,
G_TYPE_STRING, G_TYPE_INT, G_TYPE_STRING,
G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING,
G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING,
G_TYPE_INT64, GDK_TYPE_PIXBUF, G_TYPE_POINTER );
// View
GtkWidget* view = exo_tree_view_new();
gtk_tree_view_set_model( GTK_TREE_VIEW( view ), GTK_TREE_MODEL( list ) );
exo_tree_view_set_single_click( (ExoTreeView*)view, TRUE );
gtk_tree_view_set_enable_search( GTK_TREE_VIEW( view ), FALSE );
//exo_tree_view_set_single_click_timeout( (ExoTreeView*)view, SINGLE_CLICK_TIMEOUT );
// Columns
for ( i = 0; i < 13; i++ )
{
col = gtk_tree_view_column_new();
gtk_tree_view_column_set_resizable( col, TRUE );
// column order
for ( j = 0; j < 13; j++ )
{
if ( xset_get_int( task_names[j], "x" ) == i )
break;
}
if ( j == 13 )
j = i; // failsafe
else
{
width = xset_get_int( task_names[j], "y" );
if ( width )
{
gtk_tree_view_column_set_sizing( col, GTK_TREE_VIEW_COLUMN_FIXED );
gtk_tree_view_column_set_min_width( col, 20 );
gtk_tree_view_column_set_fixed_width ( col, width );
}
}
if ( cols[j] == TASK_COL_STATUS )
{
// Icon and Text
renderer = gtk_cell_renderer_text_new();
//g_object_set( G_OBJECT( renderer ),
/* "editable", TRUE, */
// "ellipsize", PANGO_ELLIPSIZE_END, NULL );
pix_renderer = gtk_cell_renderer_pixbuf_new();
gtk_tree_view_column_pack_start( col, pix_renderer, FALSE );
gtk_tree_view_column_pack_end( col, renderer, TRUE );
gtk_tree_view_column_set_attributes( col, pix_renderer,
"pixbuf", TASK_COL_ICON, NULL );
gtk_tree_view_column_set_attributes( col, renderer,
"text", TASK_COL_STATUS, NULL );
gtk_tree_view_column_set_expand ( col, FALSE );
gtk_tree_view_column_set_sizing( col, GTK_TREE_VIEW_COLUMN_FIXED );
gtk_tree_view_column_set_min_width( col, 60 );
}
else if ( cols[j] == TASK_COL_PROGRESS )
{
// Progress Bar
renderer = gtk_cell_renderer_progress_new();
gtk_tree_view_column_pack_start( col, renderer, TRUE );
gtk_tree_view_column_set_attributes( col, renderer,
"value", cols[j], NULL );
}
else
{
// Text Column
renderer = gtk_cell_renderer_text_new();
gtk_tree_view_column_pack_start( col, renderer, TRUE );
gtk_tree_view_column_set_attributes( col, renderer,
"text", cols[j], NULL );
// ellipsize some columns
if ( cols[j] == TASK_COL_FILE || cols[j] == TASK_COL_PATH
|| cols[j] == TASK_COL_TO )
{
/* wrap to multiple lines
GValue val = G_VALUE_INIT;
g_value_init (&val, G_TYPE_CHAR);
g_value_set_char (&val, 100); // set to width of cell?
g_object_set_property (G_OBJECT (renderer), "wrap-width", &val);
g_value_unset (&val);
*/
GValue val = { 0 }; // G_VALUE_INIT (glib>=2.30) caused to slackware issue ?
g_value_init (&val, G_TYPE_CHAR);
g_value_set_char (&val, PANGO_ELLIPSIZE_MIDDLE);
g_object_set_property (G_OBJECT (renderer), "ellipsize", &val);
g_value_unset (&val);
}
}
gtk_tree_view_append_column ( GTK_TREE_VIEW( view ), col );
gtk_tree_view_column_set_title( col, _( task_titles[j] ) );
gtk_tree_view_column_set_reorderable( col, TRUE );
gtk_tree_view_column_set_visible( col, xset_get_b( task_names[j] ) );
if ( j == TASK_COL_FILE ) //|| j == TASK_COL_PATH || j == TASK_COL_TO
{
gtk_tree_view_column_set_sizing( col, GTK_TREE_VIEW_COLUMN_FIXED );
gtk_tree_view_column_set_min_width( col, 20 );
gtk_tree_view_column_set_expand ( col, TRUE );
}
}
// invisible Starttime col for sorting
col = gtk_tree_view_column_new();
gtk_tree_view_column_set_resizable ( col, TRUE );
renderer = gtk_cell_renderer_text_new();
gtk_tree_view_column_pack_start( col, renderer, TRUE );
gtk_tree_view_column_set_attributes( col, renderer,
"text", TASK_COL_STARTTIME, NULL );
gtk_tree_view_append_column ( GTK_TREE_VIEW( view ), col );
gtk_tree_view_column_set_title( col, "StartTime" );
gtk_tree_view_column_set_reorderable( col, FALSE );
gtk_tree_view_column_set_visible( col, FALSE );
// Sort
if ( GTK_IS_TREE_SORTABLE( list ) )
gtk_tree_sortable_set_sort_column_id( GTK_TREE_SORTABLE( list ),
TASK_COL_STARTTIME, GTK_SORT_ASCENDING );
gtk_tree_view_set_rules_hint ( GTK_TREE_VIEW( view ), TRUE );
g_signal_connect( view, "row-activated", G_CALLBACK( on_task_row_activated ), NULL );
g_signal_connect( view, "columns-changed",
G_CALLBACK ( on_task_columns_changed ), NULL );
g_signal_connect( view, "destroy", G_CALLBACK ( on_task_destroy ), NULL );
g_signal_connect ( view, "button-press-event",
G_CALLBACK ( on_task_button_press_event ), main_window );
// set font
if ( xset_get_s( "font_task" ) )
{
PangoFontDescription* font_desc = pango_font_description_from_string(
xset_get_s( "font_task" ) );
gtk_widget_modify_font( view, font_desc );
pango_font_description_free( font_desc );
}
return view;
}
// ============== socket commands
gboolean bool( const char* value )
{
return ( !( value && value[0] ) || !strcmp( value, "1") ||
!strcmp( value, "true") ||
!strcmp( value, "True") || !strcmp( value, "TRUE") ||
!strcmp( value, "yes") || !strcmp( value, "Yes") ||
!strcmp( value, "YES") );
}
static gboolean delayed_show_menu( GtkWidget* menu )
{
FMMainWindow* main_window = fm_main_window_get_last_active();
if ( main_window )
gtk_window_present( GTK_WINDOW( main_window ) );
gtk_widget_show_all( GTK_WIDGET( menu ) );
gtk_menu_popup( GTK_MENU( menu ), NULL, NULL, NULL, NULL, 0,
gtk_get_current_event_time() );
g_signal_connect( G_OBJECT( menu ), "key-press-event",
G_CALLBACK( xset_menu_keypress ), NULL );
g_signal_connect( menu, "selection-done",
G_CALLBACK( gtk_widget_destroy ), NULL );
return FALSE;
}
char main_window_socket_command( char* argv[], char** reply )
{
int i, j;
int panel = 0, tab = 0;
char* window = NULL;
char* str;
FMMainWindow* main_window;
PtkFileBrowser* file_browser;
GList* l;
int height, width;
GtkWidget* widget;
// from ptk-file-browser.c on_folder_view_columns_changed titles[]
const char* col_titles[] =
{
N_( "Name" ), N_( "Size" ), N_( "Type" ),
N_( "Permission" ), N_( "Owner" ), N_( "Modified" )
};
*reply = NULL;
if ( !( argv && argv[0] ) )
{
*reply = g_strdup( _("spacefm: invalid socket command\n") );
return 1;
}
// cmd options
i = 1;
while ( argv[i] && argv[i][0] == '-' )
{
if ( !strcmp( argv[i], "--window" ) )
{
if ( !argv[i + 1] ) goto _missing_arg;
window = argv[i + 1];
i += 2;
continue;
}
else if ( !strcmp( argv[i], "--panel" ) )
{
if ( !argv[i + 1] ) goto _missing_arg;
panel = atoi( argv[i + 1] );
i += 2;
continue;
}
else if ( !strcmp( argv[i], "--tab" ) )
{
if ( !argv[i + 1] ) goto _missing_arg;
tab = atoi( argv[i + 1] );
i += 2;
continue;
}
*reply = g_strdup_printf( _("spacefm: invalid option '%s'\n"), argv[i] );
return 1;
_missing_arg:
*reply = g_strdup_printf( _("spacefm: option %s requires an argument\n"),
argv[i] );
return 1;
}
// window
if ( !window )
{
if ( !( main_window = fm_main_window_get_last_active() ) )
{
*reply = g_strdup( _("spacefm: invalid window\n") );
return 2;
}
}
else
{
main_window = NULL;
for ( l = all_windows; l; l = l->next )
{
str = g_strdup_printf( "%p", l->data );
if ( !strcmp( str, window ) )
{
main_window = (FMMainWindow*)l->data;
g_free( str );
break;
}
g_free( str );
}
if ( !main_window )
{
*reply = g_strdup_printf( _("spacefm: invalid window %s\n"), window );
return 2;
}
}
// panel
if ( !panel )
panel = main_window->curpanel;
if ( panel < 1 || panel > 4 )
{
*reply = g_strdup_printf( _("spacefm: invalid panel %d\n"), panel );
return 2;
}
if ( !xset_get_b_panel( panel, "show" ) ||
gtk_notebook_get_current_page(
GTK_NOTEBOOK( main_window->panel[panel-1] ) ) == -1 )
{
*reply = g_strdup_printf( _("spacefm: panel %d is not visible\n"), panel );
return 2;
}
// tab
if ( !tab )
{
tab = gtk_notebook_get_current_page(
GTK_NOTEBOOK( main_window->panel[panel-1] ) ) + 1;
}
if ( tab < 1 || tab > gtk_notebook_get_n_pages(
GTK_NOTEBOOK( main_window->panel[panel-1] ) ) )
{
*reply = g_strdup_printf( _("spacefm: invalid tab %d\n"), tab );
return 2;
}
file_browser = PTK_FILE_BROWSER( gtk_notebook_get_nth_page(
GTK_NOTEBOOK( main_window->panel[panel-1] ),
tab - 1 ) );
// command
if ( !strcmp( argv[0], "set" ) )
{
if ( !argv[i] )
{
*reply = g_strdup( _("spacefm: command set requires an argument\n") );
return 1;
}
if ( !strcmp( argv[i], "window_size" ) || !strcmp( argv[i], "window_position" ) )
{
height = width = 0;
if ( argv[i+1] )
{
str = strchr( argv[i+1], 'x' );
if ( !str )
{
if ( argv[i+2] )
{
width = atoi( argv[i+1] );
height = atoi( argv[i+2] );
}
}
else
{
str[0] = '\0';
width = atoi( argv[i+1] );
height = atoi( str + 1 );
}
}
if ( height < 1 || width < 1 )
{
*reply = g_strdup_printf( _("spacefm: invalid %s value\n"), argv[i] );
return 2;
}
if ( !strcmp( argv[i], "window_size" ) )
gtk_window_resize( GTK_WINDOW( main_window ), width, height );
else
gtk_window_move( GTK_WINDOW( main_window ), width, height );
}
else if ( !strcmp( argv[i], "window_maximized" ) )
{
if ( bool( argv[i+1] ) )
gtk_window_maximize( GTK_WINDOW( main_window ) );
else
gtk_window_unmaximize( GTK_WINDOW( main_window ) );
}
else if ( !strcmp( argv[i], "window_fullscreen" ) )
{
xset_set_b( "main_full", bool( argv[i+1] ) );
on_fullscreen_activate( NULL, main_window );
}
else if ( !strcmp( argv[i], "screen_size" ) )
{
}
else if ( !strcmp( argv[i], "window_vslider_top" ) ||
!strcmp( argv[i], "window_vslider_bottom" ) ||
!strcmp( argv[i], "window_hslider" ) ||
!strcmp( argv[i], "window_tslider" ) )
{
width = -1;
if ( argv[i+1] )
width = atoi( argv[i+1] );
if ( width < 0 )
{
*reply = g_strdup( _("spacefm: invalid slider value\n") );
return 2;
}
if ( !strcmp( argv[i] + 7, "vslider_top" ) )
widget = main_window->hpane_top;
else if ( !strcmp( argv[i] + 7, "vslider_bottom" ) )
widget = main_window->hpane_bottom;
else if ( !strcmp( argv[i] + 7, "hslider" ) )
widget = main_window->vpane;
else
widget = main_window->task_vpane;
gtk_paned_set_position( GTK_PANED( widget ), width );
}
else if ( !strcmp( argv[i], "focused_panel" ) )
{
width = 0;
if ( argv[i+1] )
{
if ( !strcmp( argv[i+1], "prev" ) )
width = -1;
else if ( !strcmp( argv[i+1], "next" ) )
width = -2;
else if ( !strcmp( argv[i+1], "hide" ) )
width = -3;
else
width = atoi( argv[i+1] );
}
if ( width == 0 || width < -3 || width > 4 )
{
*reply = g_strdup( _("spacefm: invalid panel number\n") );
return 2;
}
focus_panel( NULL, (gpointer)main_window, width );
}
else if ( !strcmp( argv[i], "focused_pane" ) )
{
widget = NULL;
if ( argv[i+1] )
{
if ( !strcmp( argv[i+1], "filelist" ) )
widget = file_browser->folder_view;
else if ( !strcmp( argv[i+1], "devices" ) )
widget = file_browser->side_dev;
else if ( !strcmp( argv[i+1], "bookmarks" ) )
widget = file_browser->side_book;
else if ( !strcmp( argv[i+1], "dirtree" ) )
widget = file_browser->side_dir;
else if ( !strcmp( argv[i+1], "pathbar" ) )
widget = file_browser->path_bar;
}
if ( GTK_IS_WIDGET( widget ) )
gtk_widget_grab_focus( widget );
}
else if ( !strcmp( argv[i], "current_tab" ) )
{
width = 0;
if ( argv[i+1] )
{
if ( !strcmp( argv[i+1], "prev" ) )
width = -1;
else if ( !strcmp( argv[i+1], "next" ) )
width = -2;
else if ( !strcmp( argv[i+1], "close" ) )
width = -3;
else
width = atoi( argv[i+1] );
}
if ( width == 0 || width < -3 || width > gtk_notebook_get_n_pages(
GTK_NOTEBOOK( main_window->panel[panel-1] ) ) )
{
*reply = g_strdup( _("spacefm: invalid tab number\n") );
return 2;
}
ptk_file_browser_go_tab( NULL, file_browser, width );
}
else if ( !strcmp( argv[i], "tab_count" ) )
{}
else if ( !strcmp( argv[i], "new_tab" ) )
{
focus_panel( NULL, (gpointer)main_window, panel );
if ( !( argv[i+1] && g_file_test( argv[i+1], G_FILE_TEST_IS_DIR ) ) )
on_shortcut_new_tab_activate( NULL, file_browser );
else
fm_main_window_add_new_tab( main_window, argv[i+1] );
main_window_get_counts( file_browser, &i, &tab, &j );
*reply = g_strdup_printf( "#!/bin/bash\nnew_tab_window=%p\nnew_tab_panel=%d\nnew_tab_number=%d\n",
main_window, panel, tab );
}
else if ( g_str_has_suffix( argv[i], "_visible" ) )
{
if ( g_str_has_prefix( argv[i], "devices_" ) )
str = "show_devmon";
else if ( g_str_has_prefix( argv[i], "bookmarks_" ) )
str = "show_book";
else if ( g_str_has_prefix( argv[i], "dirtree_" ) )
str = "show_dirtree";
else if ( g_str_has_prefix( argv[i], "toolbar_" ) )
str = "show_toolbox";
else if ( g_str_has_prefix( argv[i], "sidetoolbar_" ) )
str = "show_sidebar";
else if ( g_str_has_prefix( argv[i], "hidden_files_" ) )
str = "show_hidden";
else if ( g_str_has_prefix( argv[i], "panel" ) )
{
j = argv[i][5] - 48;
if ( j < 1 || j > 4 )
{
*reply = g_strdup_printf( _("spacefm: invalid property %s\n"),
argv[i] );
return 2;
}
xset_set_b_panel( j, "show", bool( argv[i+1] ) );
show_panels_all_windows( NULL, main_window );
return 0;
}
else
str = NULL;
if ( !str )
goto _invalid_set;
xset_set_b_panel( panel, str, bool( argv[i+1] ) );
update_views_all_windows( NULL, file_browser );
}
else if ( !strcmp( argv[i], "panel_hslider_top" ) ||
!strcmp( argv[i], "panel_hslider_bottom" ) ||
!strcmp( argv[i], "panel_vslider" ) )
{
width = -1;
if ( argv[i+1] )
width = atoi( argv[i+1] );
if ( width < 0 )
{
*reply = g_strdup( _("spacefm: invalid slider value\n") );
return 2;
}
if ( !strcmp( argv[i] + 6, "hslider_top" ) )
widget = file_browser->side_vpane_top;
else if ( !strcmp( argv[i] + 6, "hslider_bottom" ) )
widget = file_browser->side_vpane_bottom;
else
widget = file_browser->hpane;
gtk_paned_set_position( GTK_PANED( widget ), width );
ptk_file_browser_slider_release( NULL, NULL, file_browser );
update_views_all_windows( NULL, file_browser );
}
else if ( !strcmp( argv[i], "column_width" ) )
{ // COLUMN WIDTH
width = 0;
if ( argv[i+1] && argv[i+2] )
width = atoi( argv[i+2] );
if ( width < 1 )
{
*reply = g_strdup( _("spacefm: invalid column width\n") );
return 2;
}
if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
GtkTreeViewColumn* col;
for ( j = 0; j < 6; j++ )
{
col = gtk_tree_view_get_column( GTK_TREE_VIEW(
file_browser->folder_view ), j );
if ( !col )
continue;
str = (char*)gtk_tree_view_column_get_title( col );
if ( !g_strcmp0( argv[i+1], str ) )
break;
if ( !g_strcmp0( argv[i+1], "name" ) &&
!g_strcmp0( str, _(col_titles[0]) ) )
break;
else if ( !g_strcmp0( argv[i+1], "size" ) &&
!g_strcmp0( str, _(col_titles[1]) ) )
break;
else if ( !g_strcmp0( argv[i+1], "type" ) &&
!g_strcmp0( str, _(col_titles[2]) ) )
break;
else if ( !g_strcmp0( argv[i+1], "permission" ) &&
!g_strcmp0( str, _(col_titles[3]) ) )
break;
else if ( !g_strcmp0( argv[i+1], "owner" ) &&
!g_strcmp0( str, _(col_titles[4]) ) )
break;
else if ( !g_strcmp0( argv[i+1], "modified" ) &&
!g_strcmp0( str, _(col_titles[5]) ) )
break;
}
if ( j == 6 )
{
*reply = g_strdup_printf( _("spacefm: invalid column name '%s'\n"),
argv[i+1] );
return 2;
}
gtk_tree_view_column_set_fixed_width( col, width );
}
}
else if ( !strcmp( argv[i], "sort_by" ) )
{ // COLUMN
j = -10;
if ( !argv[i+1] )
{}
else if ( !strcmp( argv[i+1], "name" ) )
j = PTK_FB_SORT_BY_NAME;
else if ( !strcmp( argv[i+1], "size" ) )
j = PTK_FB_SORT_BY_SIZE;
else if ( !strcmp( argv[i+1], "type" ) )
j = PTK_FB_SORT_BY_TYPE;
else if ( !strcmp( argv[i+1], "permission" ) )
j = PTK_FB_SORT_BY_PERM;
else if ( !strcmp( argv[i+1], "owner" ) )
j = PTK_FB_SORT_BY_OWNER;
else if ( !strcmp( argv[i+1], "modified" ) )
j = PTK_FB_SORT_BY_MTIME;
if ( j == -10 )
{
*reply = g_strdup_printf( _("spacefm: invalid column name '%s'\n"),
argv[i+1] );
return 2;
}
ptk_file_browser_set_sort_order( file_browser, j );
}
else if ( g_str_has_prefix( argv[i], "sort_" ) )
{
if ( !strcmp( argv[i] + 5, "ascend" ) )
{
ptk_file_browser_set_sort_type( file_browser, bool( argv[i+1] ) ?
GTK_SORT_ASCENDING : GTK_SORT_DESCENDING );
return 0;
}
else if ( !strcmp( argv[i] + 5, "natural" ) )
{
str = "sortx_natural";
xset_set_b( str, bool( argv[i+1] ) );
}
else if ( !strcmp( argv[i] + 5, "case" ) )
{
str = "sortx_case";
xset_set_b( str, bool( argv[i+1] ) );
}
else if ( !strcmp( argv[i] + 5, "hidden_first" ) )
{
str = bool( argv[i+1] ) ? "sortx_hidfirst" : "sortx_hidlast";
xset_set_b( str, TRUE );
}
else if ( !strcmp( argv[i] + 5, "first" ) )
{
if ( !g_strcmp0( argv[i+1], "files" ) )
str = "sortx_files";
else if ( !g_strcmp0( argv[i+1], "folders" ) )
str = "sortx_folders";
else if ( !g_strcmp0( argv[i+1], "mixed" ) )
str = "sortx_mix";
else
{
*reply = g_strdup_printf( _("spacefm: invalid %s value\n"), argv[i] );
return 2;
}
}
else
goto _invalid_set;
ptk_file_browser_set_sort_extra( file_browser, str );
}
else if ( !strcmp( argv[i], "statusbar_text" ) )
{
if ( !( argv[i+1] && argv[i+1][0] ) )
{
g_free( file_browser->status_bar_custom );
file_browser->status_bar_custom = NULL;
}
else
{
g_free( file_browser->status_bar_custom );
file_browser->status_bar_custom = g_strdup( argv[i+1] );
}
fm_main_window_update_status_bar( main_window, file_browser );
}
else if ( !strcmp( argv[i], "pathbar_text" ) )
{ // TEXT [[SELSTART] SELEND]
if ( !GTK_IS_WIDGET( file_browser->path_bar ) )
return 0;
if ( !( argv[i+1] && argv[i+1][0] ) )
{
gtk_entry_set_text( GTK_ENTRY( file_browser->path_bar ), "" );
}
else
{
gtk_entry_set_text( GTK_ENTRY( file_browser->path_bar ),
argv[i+1] );
if ( !argv[i+2] )
{
width = 0;
height = -1;
}
else
{
width = atoi( argv[i+2] );
height = argv[i+3] ? atoi( argv[i+3] ) : -1;
}
gtk_editable_set_position( GTK_EDITABLE(
file_browser->path_bar ), -1 );
gtk_editable_select_region( GTK_EDITABLE(
file_browser->path_bar ), width, height );
gtk_widget_grab_focus( file_browser->path_bar );
}
}
else if ( !strcmp( argv[i], "clipboard_text" ) ||
!strcmp( argv[i], "clipboard_primary_text" ) )
{
if ( argv[i+1] && !g_utf8_validate( argv[i+1], -1, NULL ) )
{
*reply = g_strdup( _("spacefm: text is not valid UTF-8\n") );
return 2;
}
GtkClipboard * clip = gtk_clipboard_get(
!strcmp( argv[i], "clipboard_text" ) ?
GDK_SELECTION_CLIPBOARD :
GDK_SELECTION_PRIMARY );
str = unescape( argv[i+1] ? argv[i+1] : "" );
gtk_clipboard_set_text( clip, str, -1 );
g_free( str );
}
else if ( !strcmp( argv[i], "clipboard_from_file" ) ||
!strcmp( argv[i], "clipboard_primary_from_file" ) )
{
if ( !argv[i+1] )
{
*reply = g_strdup_printf(
_("spacefm: %s requires a file path\n"), argv[i] );
return 1;
}
if ( !g_file_get_contents( argv[i+1], &str, NULL, NULL ) )
{
*reply = g_strdup_printf(
_("spacefm: error reading file '%s'\n"), argv[i+1] );
return 2;
}
if ( !g_utf8_validate( str, -1, NULL ) )
{
*reply = g_strdup_printf(
_("spacefm: file '%s' does not contain valid UTF-8 text\n"),
argv[i+1] );
g_free( str );
return 2;
}
GtkClipboard * clip = gtk_clipboard_get(
!strcmp( argv[i], "clipboard_from_file" ) ?
GDK_SELECTION_CLIPBOARD :
GDK_SELECTION_PRIMARY );
gtk_clipboard_set_text( clip, str, -1 );
g_free( str );
}
else if ( !strcmp( argv[i], "clipboard_cut_files" ) ||
!strcmp( argv[i], "clipboard_copy_files" ) )
{
ptk_clipboard_copy_file_list( argv + i + 1,
!strcmp( argv[i], "clipboard_copy_files" ) );
}
else if ( !strcmp( argv[i], "selected_filenames" ) ||
!strcmp( argv[i], "selected_files" ) )
{
if ( !argv[i+1] || argv[i+1][0] == '\0' )
// unselect all
ptk_file_browser_select_file_list( file_browser, NULL, FALSE );
else
ptk_file_browser_select_file_list( file_browser, argv + i + 1,
TRUE );
}
else if ( !strcmp( argv[i], "selected_pattern" ) )
{
if ( !argv[i+1] )
// unselect all
ptk_file_browser_select_file_list( file_browser, NULL, FALSE );
else
ptk_file_browser_select_pattern( NULL, file_browser, argv[i+1] );
}
else if ( !strcmp( argv[i], "current_dir" ) )
{
if ( !argv[i+1] )
{
*reply = g_strdup_printf(
_("spacefm: %s requires a directory path\n"), argv[i] );
return 1;
}
if ( !g_file_test( argv[i+1], G_FILE_TEST_IS_DIR ) )
{
*reply = g_strdup_printf(
_("spacefm: directory '%s' does not exist\n"), argv[i+1] );
return 1;
}
ptk_file_browser_chdir( file_browser, argv[i+1],
PTK_FB_CHDIR_ADD_HISTORY );
}
else if ( !strcmp( argv[i], "edit_file" ) ) // deprecated >= 0.8.7
{
if ( ( argv[i+1] && argv[i+1][0] ) &&
g_file_test( argv[i+1], G_FILE_TEST_IS_REGULAR ) )
xset_edit( GTK_WIDGET( file_browser ), argv[i+1], FALSE, TRUE );
}
else if ( !strcmp( argv[i], "run_in_terminal" ) ) // deprecated >= 0.8.7
{
if ( ( argv[i+1] && argv[i+1][0] ) )
{
str = g_strjoinv( " ", &argv[i+1] );
if ( str && str[0] )
{
// async task
PtkFileTask* task = ptk_file_exec_new( "Run In Terminal",
ptk_file_browser_get_cwd( file_browser ),
GTK_WIDGET( file_browser ),
main_window->task_view );
task->task->exec_command = str;
task->task->exec_terminal = TRUE;
task->task->exec_sync = FALSE;
task->task->exec_export = FALSE;
ptk_file_task_run( task );
}
else
g_free( str );
}
}
else
{
_invalid_set:
*reply = g_strdup_printf( _("spacefm: invalid property %s\n"), argv[i] );
return 1;
}
}
else if ( !strcmp( argv[0], "get" ) )
{
// get
if ( !argv[i] )
{
*reply = g_strdup_printf( _("spacefm: command %s requires an argument\n"),
argv[0] );
return 1;
}
if ( !strcmp( argv[i], "window_size" ) || !strcmp( argv[i], "window_position" ) )
{
if ( !strcmp( argv[i], "window_size" ) )
gtk_window_get_size( GTK_WINDOW( main_window ), &width, &height );
else
gtk_window_get_position( GTK_WINDOW( main_window ), &width, &height );
*reply = g_strdup_printf( "%dx%d\n", width, height );
}
else if ( !strcmp( argv[i], "window_maximized" ) )
{
*reply = g_strdup_printf( "%d\n", !!app_settings.maximized );
}
else if ( !strcmp( argv[i], "window_fullscreen" ) )
{
*reply = g_strdup_printf( "%d\n", !!xset_get_b( "main_full" ) );
}
else if ( !strcmp( argv[i], "screen_size" ) )
{
width = gdk_screen_get_width(
gtk_widget_get_screen( (GtkWidget*)main_window ) );
height = gdk_screen_get_height(
gtk_widget_get_screen( (GtkWidget*)main_window ) );
*reply = g_strdup_printf( "%dx%d\n", width, height );
}
else if ( !strcmp( argv[i], "window_vslider_top" ) ||
!strcmp( argv[i], "window_vslider_bottom" ) ||
!strcmp( argv[i], "window_hslider" ) ||
!strcmp( argv[i], "window_tslider" ) )
{
if ( !strcmp( argv[i] + 7, "vslider_top" ) )
widget = main_window->hpane_top;
else if ( !strcmp( argv[i] + 7, "vslider_bottom" ) )
widget = main_window->hpane_bottom;
else if ( !strcmp( argv[i] + 7, "hslider" ) )
widget = main_window->vpane;
else
widget = main_window->task_vpane;
*reply = g_strdup_printf( "%d\n",
gtk_paned_get_position( GTK_PANED( widget ) ) );
}
else if ( !strcmp( argv[i], "focused_panel" ) )
{
*reply = g_strdup_printf( "%d\n", main_window->curpanel );
}
else if ( !strcmp( argv[i], "focused_pane" ) )
{
if ( file_browser->folder_view &&
gtk_widget_is_focus( file_browser->folder_view ) )
str = "filelist";
else if ( file_browser->side_dev &&
gtk_widget_is_focus( file_browser->side_dev ) )
str = "devices";
else if ( file_browser->side_book &&
gtk_widget_is_focus( file_browser->side_book ) )
str = "bookmarks";
else if ( file_browser->side_dir &&
gtk_widget_is_focus( file_browser->side_dir ) )
str = "dirtree";
else if ( file_browser->path_bar &&
gtk_widget_is_focus( file_browser->path_bar ) )
str = "pathbar";
else
str = NULL;
if ( str )
*reply = g_strdup_printf( "%s\n", str );
}
else if ( !strcmp( argv[i], "current_tab" ) )
{
*reply = g_strdup_printf( "%d\n", gtk_notebook_page_num (
GTK_NOTEBOOK( main_window->panel[panel-1] ),
GTK_WIDGET( file_browser ) ) + 1 );
}
else if ( !strcmp( argv[i], "tab_count" ) )
{
main_window_get_counts( file_browser, &panel, &tab, &j );
*reply = g_strdup_printf( "%d\n", tab );
}
else if ( !strcmp( argv[i], "new_tab" ) )
{}
else if ( g_str_has_suffix( argv[i], "_visible" ) )
{
if ( g_str_has_prefix( argv[i], "devices_" ) )
str = "show_devmon";
else if ( g_str_has_prefix( argv[i], "bookmarks_" ) )
str = "show_book";
else if ( g_str_has_prefix( argv[i], "dirtree_" ) )
str = "show_dirtree";
else if ( g_str_has_prefix( argv[i], "toolbar_" ) )
str = "show_toolbox";
else if ( g_str_has_prefix( argv[i], "sidetoolbar_" ) )
str = "show_sidebar";
else if ( g_str_has_prefix( argv[i], "hidden_files_" ) )
str = "show_hidden";
else if ( g_str_has_prefix( argv[i], "panel" ) )
{
j = argv[i][5] - 48;
if ( j < 1 || j > 4 )
{
*reply = g_strdup_printf( _("spacefm: invalid property %s\n"),
argv[i] );
return 2;
}
*reply = g_strdup_printf( "%d\n", xset_get_b_panel( j, "show" ) );
return 0;
}
else
str = NULL;
if ( !str )
goto _invalid_get;
*reply = g_strdup_printf( "%d\n", !!xset_get_b_panel( panel, str ) );
}
else if ( !strcmp( argv[i], "panel_hslider_top" ) ||
!strcmp( argv[i], "panel_hslider_bottom" ) ||
!strcmp( argv[i], "panel_vslider" ) )
{
if ( !strcmp( argv[i] + 6, "hslider_top" ) )
widget = file_browser->side_vpane_top;
else if ( !strcmp( argv[i] + 6, "hslider_bottom" ) )
widget = file_browser->side_vpane_bottom;
else
widget = file_browser->hpane;
*reply = g_strdup_printf( "%d\n",
gtk_paned_get_position( GTK_PANED( widget ) ) );
}
else if ( !strcmp( argv[i], "column_width" ) )
{ // COLUMN
if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
GtkTreeViewColumn* col;
for ( j = 0; j < 6; j++ )
{
col = gtk_tree_view_get_column( GTK_TREE_VIEW(
file_browser->folder_view ), j );
if ( !col )
continue;
str = (char*)gtk_tree_view_column_get_title( col );
if ( !g_strcmp0( argv[i+1], str ) )
break;
if ( !g_strcmp0( argv[i+1], "name" ) &&
!g_strcmp0( str, _(col_titles[0]) ) )
break;
else if ( !g_strcmp0( argv[i+1], "size" ) &&
!g_strcmp0( str, _(col_titles[1]) ) )
break;
else if ( !g_strcmp0( argv[i+1], "type" ) &&
!g_strcmp0( str, _(col_titles[2]) ) )
break;
else if ( !g_strcmp0( argv[i+1], "permission" ) &&
!g_strcmp0( str, _(col_titles[3]) ) )
break;
else if ( !g_strcmp0( argv[i+1], "owner" ) &&
!g_strcmp0( str, _(col_titles[4]) ) )
break;
else if ( !g_strcmp0( argv[i+1], "modified" ) &&
!g_strcmp0( str, _(col_titles[5]) ) )
break;
}
if ( j == 6 )
{
*reply = g_strdup_printf( _("spacefm: invalid column name '%s'\n"),
argv[i+1] );
return 2;
}
*reply = g_strdup_printf( "%d\n",
gtk_tree_view_column_get_width( col ) );
}
}
else if ( !strcmp( argv[i], "sort_by" ) )
{ // COLUMN
switch ( file_browser->sort_order ) {
case PTK_FB_SORT_BY_NAME:
str = "name";
break;
case PTK_FB_SORT_BY_SIZE:
str = "size";
break;
case PTK_FB_SORT_BY_TYPE:
str = "type";
break;
case PTK_FB_SORT_BY_PERM:
str = "permission";
break;
case PTK_FB_SORT_BY_OWNER:
str = "owner";
break;
case PTK_FB_SORT_BY_MTIME:
str = "modified";
break;
default:
return 0;
}
*reply = g_strdup_printf( "%s\n", str );
}
else if ( g_str_has_prefix( argv[i], "sort_" ) )
{
if ( !strcmp( argv[i] + 5, "ascend" ) )
*reply = g_strdup_printf( "%d\n",
file_browser->sort_type == GTK_SORT_ASCENDING ? 1 : 0 );
else if ( !strcmp( argv[i] + 5, "natural" ) )
*reply = g_strdup_printf( "%d\n",
xset_get_b_panel( file_browser->mypanel, "sort_extra" ) ?
1 : 0 );
else if ( !strcmp( argv[i] + 5, "case" ) )
*reply = g_strdup_printf( "%d\n",
xset_get_b_panel( file_browser->mypanel, "sort_extra" ) &&
xset_get_int_panel( file_browser->mypanel, "sort_extra",
"x" ) == XSET_B_TRUE ? 1 : 0 );
else if ( !strcmp( argv[i] + 5, "hidden_first" ) )
*reply = g_strdup_printf( "%d\n",
xset_get_int_panel( file_browser->mypanel, "sort_extra",
"z" ) == XSET_B_TRUE ? 1 : 0 );
else if ( !strcmp( argv[i] + 5, "first" ) )
{
switch ( xset_get_int_panel( file_browser->mypanel, "sort_extra",
"y" ) ) {
case 0:
str = "mixed";
break;
case 1:
str = "folders";
break;
case 2:
str = "files";
break;
default:
return 0; //failsafe for known
}
*reply = g_strdup_printf( "%s\n", str );
}
else
goto _invalid_get;
}
else if ( !strcmp( argv[i], "statusbar_text" ) )
{
*reply = g_strdup_printf( "%s\n", gtk_label_get_text(
GTK_LABEL( file_browser->status_label ) ) );
}
else if ( !strcmp( argv[i], "pathbar_text" ) )
{
if ( GTK_IS_WIDGET( file_browser->path_bar ) )
*reply = g_strdup_printf( "%s\n", gtk_entry_get_text(
GTK_ENTRY( file_browser->path_bar ) ) );
}
else if ( !strcmp( argv[i], "clipboard_text" ) ||
!strcmp( argv[i], "clipboard_primary_text" ) )
{
GtkClipboard * clip = gtk_clipboard_get(
!strcmp( argv[i], "clipboard_text" ) ?
GDK_SELECTION_CLIPBOARD :
GDK_SELECTION_PRIMARY );
*reply = gtk_clipboard_wait_for_text( clip );
}
else if ( !strcmp( argv[i], "clipboard_from_file" ) ||
!strcmp( argv[i], "clipboard_primary_from_file" ) )
{
}
else if ( !strcmp( argv[i], "clipboard_cut_files" ) ||
!strcmp( argv[i], "clipboard_copy_files" ) )
{
GtkClipboard * clip = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD );
GdkAtom gnome_target;
GdkAtom uri_list_target;
GtkSelectionData* sel_data;
gnome_target = gdk_atom_intern( "x-special/gnome-copied-files", FALSE );
sel_data = gtk_clipboard_wait_for_contents( clip, gnome_target );
if ( !sel_data )
{
uri_list_target = gdk_atom_intern( "text/uri-list", FALSE );
sel_data = gtk_clipboard_wait_for_contents( clip, uri_list_target );
if ( !sel_data )
return 0;
}
if ( gtk_selection_data_get_length( sel_data ) <= 0 ||
gtk_selection_data_get_format( sel_data ) != 8 )
{
gtk_selection_data_free( sel_data );
return 0;
}
if ( 0 == strncmp( ( char* )
gtk_selection_data_get_data( sel_data ), "cut", 3 ) )
{
if ( !strcmp( argv[i], "clipboard_copy_files" ) )
{
gtk_selection_data_free( sel_data );
return 0;
}
}
else if ( !strcmp( argv[i], "clipboard_cut_files" ) )
{
gtk_selection_data_free( sel_data );
return 0;
}
str = gtk_clipboard_wait_for_text( clip );
gtk_selection_data_free( sel_data );
if ( !( str && str[0] ) )
{
g_free( str );
return 0;
}
// build bash array
char** pathv = g_strsplit( str, "\n", 0 );
g_free( str );
GString* gstr = g_string_new( "(" );
j = 0;
while ( pathv[j] )
{
if ( pathv[j][0] )
{
str = bash_quote( pathv[j] );
g_string_append_printf( gstr, "%s ", str );
g_free( str );
}
j++;
}
g_strfreev( pathv );
g_string_append_printf( gstr, ")\n" );
*reply = g_string_free( gstr, FALSE );
}
else if ( !strcmp( argv[i], "selected_filenames" ) ||
!strcmp( argv[i], "selected_files" ) )
{
GList* sel_files;
VFSFileInfo* file;
sel_files = ptk_file_browser_get_selected_files( file_browser );
if ( !sel_files )
return 0;
// build bash array
GString* gstr = g_string_new( "(" );
for ( l = sel_files; l; l = l->next )
{
file = vfs_file_info_ref( (VFSFileInfo*)l->data );
if ( file )
{
str = bash_quote( vfs_file_info_get_name( file ) );
g_string_append_printf( gstr, "%s ", str );
g_free( str );
vfs_file_info_unref( file );
}
}
vfs_file_info_list_free( sel_files );
g_string_append_printf( gstr, ")\n" );
*reply = g_string_free( gstr, FALSE );
}
else if ( !strcmp( argv[i], "selected_pattern" ) )
{
}
else if ( !strcmp( argv[i], "current_dir" ) )
{
*reply = g_strdup_printf( "%s\n",
ptk_file_browser_get_cwd( file_browser ) );
}
else if ( !strcmp( argv[i], "edit_file" ) )
{ }
else if ( !strcmp( argv[i], "run_in_terminal" ) )
{ }
else
{
_invalid_get:
*reply = g_strdup_printf( _("spacefm: invalid property %s\n"), argv[i] );
return 1;
}
}
else if ( !strcmp( argv[0], "set-task" ) )
{ // TASKNUM PROPERTY [VALUE]
if ( !( argv[i] && argv[i+1] ) )
{
*reply = g_strdup_printf( _("spacefm: %s requires two arguments\n"),
argv[0] );
return 1;
}
// find task
GtkTreeIter it;
PtkFileTask* ptask = NULL;
GtkTreeModel* model = gtk_tree_view_get_model(
GTK_TREE_VIEW( main_window->task_view ) );
if ( gtk_tree_model_get_iter_first( model, &it ) )
{
do
{
gtk_tree_model_get( model, &it, TASK_COL_DATA, &ptask, -1 );
str = g_strdup_printf( "%p", ptask );
if ( !strcmp( str, argv[i] ) )
{
g_free( str );
break;
}
g_free( str );
ptask= NULL;
}
while ( gtk_tree_model_iter_next( model, &it ) );
}
if ( !ptask )
{
*reply = g_strdup_printf( _("spacefm: invalid task '%s'\n"), argv[i] );
return 2;
}
if ( ptask->task->type != VFS_FILE_TASK_EXEC )
{
*reply = g_strdup_printf( _("spacefm: internal task %s is read-only\n"),
argv[i] );
return 2;
}
// set model value
if ( !strcmp( argv[i+1], "icon" ) )
{
g_mutex_lock( ptask->task->mutex );
g_free( ptask->task->exec_icon );
ptask->task->exec_icon = g_strdup( argv[i+2] );
ptask->pause_change_view = ptask->pause_change = TRUE;
g_mutex_unlock( ptask->task->mutex );
return 0;
}
else if ( !strcmp( argv[i+1], "count" ) )
j = TASK_COL_COUNT;
else if ( !strcmp( argv[i+1], "folder" ) || !strcmp( argv[i+1], "from" ) )
j = TASK_COL_PATH;
else if ( !strcmp( argv[i+1], "item" ) )
j = TASK_COL_FILE;
else if ( !strcmp( argv[i+1], "to" ) )
j = TASK_COL_TO;
else if ( !strcmp( argv[i+1], "progress" ) )
{
if ( !argv[i+2] )
ptask->task->percent = 50;
else
{
j = atoi( argv[i+2] );
if ( j < 0 ) j = 0;
if ( j > 100 ) j = 100;
ptask->task->percent = j;
}
ptask->task->custom_percent = !!argv[i+2];
ptask->pause_change_view = ptask->pause_change = TRUE;
return 0;
}
else if ( !strcmp( argv[i+1], "total" ) )
j = TASK_COL_TOTAL;
else if ( !strcmp( argv[i+1], "curspeed" ) )
j = TASK_COL_CURSPEED;
else if ( !strcmp( argv[i+1], "curremain" ) )
j = TASK_COL_CUREST;
else if ( !strcmp( argv[i+1], "avgspeed" ) )
j = TASK_COL_AVGSPEED;
else if ( !strcmp( argv[i+1], "avgremain" ) )
j = TASK_COL_AVGEST;
else if ( !strcmp( argv[i+1], "elapsed" ) ||
!strcmp( argv[i+1], "started" ) ||
!strcmp( argv[i+1], "status" ) )
{
*reply = g_strdup_printf( _("spacefm: task property '%s' is read-only\n"),
argv[i+1] );
return 2;
}
else if ( !strcmp( argv[i+1], "queue_state" ) )
{
if ( !argv[i+2] || !g_strcmp0( argv[i+2], "run" ) )
ptk_file_task_pause( ptask, VFS_FILE_TASK_RUNNING );
else if ( !strcmp( argv[i+2], "pause" ) )
ptk_file_task_pause( ptask, VFS_FILE_TASK_PAUSE );
else if ( !strcmp( argv[i+2], "queue" ) || !strcmp( argv[i+2], "queued" ) )
ptk_file_task_pause( ptask, VFS_FILE_TASK_QUEUE );
else if ( !strcmp( argv[i+2], "stop" ) )
on_task_stop( NULL, main_window->task_view,
xset_get( "task_stop_all" ), NULL );
else
{
*reply = g_strdup_printf( _("spacefm: invalid queue_state '%s'\n"),
argv[i+2] );
return 2;
}
main_task_start_queued( main_window->task_view, NULL );
return 0;
}
else if ( !strcmp( argv[i+1], "popup_handler" ) )
{
g_free( ptask->pop_handler );
if ( argv[i+2] && argv[i+2][0] != '\0' )
ptask->pop_handler = g_strdup( argv[i+2] );
else
ptask->pop_handler = NULL;
return 0;
}
else
{
*reply = g_strdup_printf( _("spacefm: invalid task property '%s'\n"),
argv[i+1] );
return 2;
}
gtk_list_store_set( GTK_LIST_STORE( model ), &it, j, argv[i+2], -1 );
}
else if ( !strcmp( argv[0], "get-task" ) )
{ // TASKNUM PROPERTY
if ( !( argv[i] && argv[i+1] ) )
{
*reply = g_strdup_printf( _("spacefm: %s requires two arguments\n"),
argv[0] );
return 1;
}
// find task
GtkTreeIter it;
PtkFileTask* ptask = NULL;
GtkTreeModel* model = gtk_tree_view_get_model(
GTK_TREE_VIEW( main_window->task_view ) );
if ( gtk_tree_model_get_iter_first( model, &it ) )
{
do
{
gtk_tree_model_get( model, &it, TASK_COL_DATA, &ptask, -1 );
str = g_strdup_printf( "%p", ptask );
if ( !strcmp( str, argv[i] ) )
{
g_free( str );
break;
}
g_free( str );
ptask= NULL;
}
while ( gtk_tree_model_iter_next( model, &it ) );
}
if ( !ptask )
{
*reply = g_strdup_printf( _("spacefm: invalid task '%s'\n"), argv[i] );
return 2;
}
// get model value
if ( !strcmp( argv[i+1], "icon" ) )
{
g_mutex_lock( ptask->task->mutex );
if ( ptask->task->exec_icon )
*reply = g_strdup_printf( "%s\n", ptask->task->exec_icon );
g_mutex_unlock( ptask->task->mutex );
return 0;
}
else if ( !strcmp( argv[i+1], "count" ) )
j = TASK_COL_COUNT;
else if ( !strcmp( argv[i+1], "folder" ) || !strcmp( argv[i+1], "from" ) )
j = TASK_COL_PATH;
else if ( !strcmp( argv[i+1], "item" ) )
j = TASK_COL_FILE;
else if ( !strcmp( argv[i+1], "to" ) )
j = TASK_COL_TO;
else if ( !strcmp( argv[i+1], "progress" ) )
{
*reply = g_strdup_printf( "%d\n", ptask->task->percent );
return 0;
}
else if ( !strcmp( argv[i+1], "total" ) )
j = TASK_COL_TOTAL;
else if ( !strcmp( argv[i+1], "curspeed" ) )
j = TASK_COL_CURSPEED;
else if ( !strcmp( argv[i+1], "curremain" ) )
j = TASK_COL_CUREST;
else if ( !strcmp( argv[i+1], "avgspeed" ) )
j = TASK_COL_AVGSPEED;
else if ( !strcmp( argv[i+1], "avgremain" ) )
j = TASK_COL_AVGEST;
else if ( !strcmp( argv[i+1], "elapsed" ) )
j = TASK_COL_ELAPSED;
else if ( !strcmp( argv[i+1], "started" ) )
j = TASK_COL_STARTED;
else if ( !strcmp( argv[i+1], "status" ) )
j = TASK_COL_STATUS;
else if ( !strcmp( argv[i+1], "queue_state" ) )
{
if ( ptask->task->state_pause == VFS_FILE_TASK_RUNNING )
str = "run";
else if ( ptask->task->state_pause == VFS_FILE_TASK_PAUSE )
str = "pause";
else if ( ptask->task->state_pause == VFS_FILE_TASK_QUEUE )
str = "queue";
else
str = "stop"; // failsafe
*reply = g_strdup_printf( "%s\n", str );
return 0;
}
else if ( !strcmp( argv[i+1], "popup_handler" ) )
{
if ( ptask->pop_handler )
*reply = g_strdup_printf( "%s\n", ptask->pop_handler );
return 0;
}
else
{
*reply = g_strdup_printf( _("spacefm: invalid task property '%s'\n"),
argv[i+1] );
return 2;
}
gtk_tree_model_get( model, &it, j, &str, -1 );
if ( str )
*reply = g_strdup_printf( "%s\n", str );
g_free( str );
}
else if ( !strcmp( argv[0], "run-task" ) )
{ // TYPE [OPTIONS] ...
if ( !( argv[i] && argv[i+1] ) )
{
*reply = g_strdup_printf( _("spacefm: %s requires two arguments\n"),
argv[0] );
return 1;
}
if ( !strcmp( argv[i], "cmd" ) || !strcmp( argv[i], "command" ) )
{
// custom command task
// cmd [--task [--popup] [--scroll]] [--terminal]
// [--user USER] [--title TITLE]
// [--icon ICON] [--dir DIR] COMMAND
// get opts
gboolean opt_task = FALSE;
gboolean opt_popup = FALSE;
gboolean opt_scroll = FALSE;
gboolean opt_terminal = FALSE;
const char* opt_user = NULL;
const char* opt_title = NULL;
const char* opt_icon = NULL;
const char* opt_cwd = NULL;
for ( j = i + 1; argv[j] && argv[j][0] == '-'; j++ )
{
if ( !strcmp( argv[j], "--task" ) )
opt_task = TRUE;
else if ( !strcmp( argv[j], "--popup" ) )
opt_popup = opt_task = TRUE;
else if ( !strcmp( argv[j], "--scroll" ) )
opt_scroll = opt_task = TRUE;
else if ( !strcmp( argv[j], "--terminal" ) )
opt_terminal = TRUE;
/* disabled due to potential misuse of password caching su programs
else if ( !strcmp( argv[j], "--user" ) )
opt_user = argv[++j];
*/
else if ( !strcmp( argv[j], "--title" ) )
opt_title = argv[++j];
else if ( !strcmp( argv[j], "--icon" ) )
opt_icon = argv[++j];
else if ( !strcmp( argv[j], "--dir" ) )
{
opt_cwd = argv[++j];
if ( !( opt_cwd && opt_cwd[0] == '/' &&
g_file_test( opt_cwd, G_FILE_TEST_IS_DIR ) ) )
{
*reply = g_strdup_printf( _("spacefm: no such directory '%s'\n"),
opt_cwd );
return 2;
}
}
else
{
*reply = g_strdup_printf( _("spacefm: invalid %s task option '%s'\n"),
argv[i], argv[j] );
return 2;
}
}
if ( !argv[j] )
{
*reply = g_strdup_printf( _("spacefm: %s requires two arguments\n"),
argv[0] );
return 1;
}
GString* gcmd = g_string_new( argv[j] );
while ( argv[++j] )
g_string_append_printf( gcmd, " %s", argv[j] );
PtkFileTask* ptask = ptk_file_exec_new( opt_title ? opt_title : gcmd->str,
opt_cwd ? opt_cwd :
ptk_file_browser_get_cwd( file_browser ),
GTK_WIDGET( file_browser ),
file_browser->task_view );
ptask->task->exec_browser = file_browser;
ptask->task->exec_command = g_string_free( gcmd, FALSE );
ptask->task->exec_as_user = g_strdup( opt_user );
ptask->task->exec_icon = g_strdup( opt_icon );
ptask->task->exec_terminal = opt_terminal;
ptask->task->exec_keep_terminal = FALSE;
ptask->task->exec_sync = opt_task;
ptask->task->exec_popup = opt_popup;
ptask->task->exec_show_output = opt_popup;
ptask->task->exec_show_error = TRUE;
ptask->task->exec_scroll_lock = !opt_scroll;
ptask->task->exec_export = TRUE;
if ( opt_popup )
gtk_window_present( GTK_WINDOW( main_window ) );
ptk_file_task_run( ptask );
if ( opt_task )
*reply = g_strdup_printf( "#!/bin/bash\n# Note: $new_task_id not valid until approx one half second after task start\nnew_task_window=%p\nnew_task_id=%p\n",
main_window, ptask );
}
else if ( !strcmp( argv[i], "edit" ) || !strcmp( argv[i], "web" ) )
{
// edit or web
// edit [--as-root] FILE
// web URL
gboolean opt_root = FALSE;
for ( j = i + 1; argv[j] && argv[j][0] == '-'; j++ )
{
if ( !strcmp( argv[i], "edit" ) && !strcmp( argv[j], "--as-root" ) )
opt_root = TRUE;
else
{
*reply = g_strdup_printf( _("spacefm: invalid %s task option '%s'\n"),
argv[i], argv[j] );
return 2;
}
}
if ( !argv[j] )
{
*reply = g_strdup_printf( _("spacefm: %s requires two arguments\n"),
argv[0] );
return 1;
}
if ( !strcmp( argv[i], "edit" ) )
{
if ( !( argv[j][0] == '/' &&
g_file_test( argv[j], G_FILE_TEST_EXISTS ) ) )
{
*reply = g_strdup_printf( _("spacefm: no such file '%s'\n"),
argv[j] );
return 2;
}
xset_edit( GTK_WIDGET( file_browser ), argv[j], opt_root, !opt_root );
}
else
xset_open_url( GTK_WIDGET( file_browser ), argv[j] );
}
else if ( !strcmp( argv[i], "copy" ) || !strcmp( argv[i], "move" )
|| !strcmp( argv[i], "link" )
|| !strcmp( argv[i], "delete" ) )
{
// built-in task
// copy SOURCE FILENAME [...] TARGET
// move SOURCE FILENAME [...] TARGET
// link SOURCE FILENAME [...] TARGET
// delete SOURCE FILENAME [...]
// get opts
const char* opt_cwd = NULL;
for ( j = i + 1; argv[j] && argv[j][0] == '-'; j++ )
{
if ( !strcmp( argv[j], "--dir" ) )
{
opt_cwd = argv[++j];
if ( !( opt_cwd && opt_cwd[0] == '/' &&
g_file_test( opt_cwd, G_FILE_TEST_IS_DIR ) ) )
{
*reply = g_strdup_printf( _("spacefm: no such directory '%s'\n"),
opt_cwd );
return 2;
}
}
else
{
*reply = g_strdup_printf( _("spacefm: invalid %s task option '%s'\n"),
argv[i], argv[j] );
return 2;
}
}
l = NULL; // file list
char* target_dir = NULL;
for ( ; argv[j]; j++ )
{
if ( strcmp( argv[i], "delete" ) && !argv[j+1] )
{
// last argument - use as TARGET
if ( argv[j][0] != '/' ||
!g_file_test( argv[j], G_FILE_TEST_IS_DIR ) )
{
*reply = g_strdup_printf( _("spacefm: no such directory '%s'\n"),
argv[j] );
g_list_foreach( l, (GFunc)g_free, NULL );
g_list_free( l );
return 2;
}
target_dir = argv[j];
break;
}
else
{
if ( argv[j][0] == '/' )
// absolute path
str = g_strdup( argv[j] );
else
{
// relative path
if ( !opt_cwd )
{
*reply = g_strdup_printf( _("spacefm: relative path '%s' requires %s option --dir DIR\n"),
argv[j], argv[i] );
g_list_foreach( l, (GFunc)g_free, NULL );
g_list_free( l );
return 2;
}
str = g_build_filename( opt_cwd, argv[j], NULL );
}
if ( !g_file_test( str, G_FILE_TEST_EXISTS ) )
{
*reply = g_strdup_printf( _("spacefm: no such file '%s'\n"),
str );
g_free( str );
g_list_foreach( l, (GFunc)g_free, NULL );
g_list_free( l );
return 2;
}
l = g_list_prepend( l, str );
}
}
if ( !l || ( strcmp( argv[i], "delete" ) && !target_dir ) )
{
*reply = g_strdup_printf( _("spacefm: task type %s requires FILE argument(s)\n"),
argv[i] );
return 2;
}
l = g_list_reverse( l );
if ( !strcmp( argv[i], "copy" ) )
j = VFS_FILE_TASK_COPY;
else if ( !strcmp( argv[i], "move" ) )
j = VFS_FILE_TASK_MOVE;
else if ( !strcmp( argv[i], "link" ) )
j = VFS_FILE_TASK_LINK;
else if ( !strcmp( argv[i], "delete" ) )
j = VFS_FILE_TASK_DELETE;
else
return 1; // failsafe
PtkFileTask* ptask = ptk_file_task_new( j, l, target_dir,
GTK_WINDOW( gtk_widget_get_toplevel(
GTK_WIDGET( file_browser ) ) ),
file_browser->task_view );
ptk_file_task_run( ptask );
*reply = g_strdup_printf( "#!/bin/bash\n# Note: $new_task_id not valid until approx one half second after task start\nnew_task_window=%p\nnew_task_id=%p\n",
main_window, ptask );
}
else
{
*reply = g_strdup_printf( _("spacefm: invalid task type '%s'\n"),
argv[i] );
return 2;
}
}
else if ( !strcmp( argv[0], "emit-key" ) )
{ // KEYCODE [KEYMOD]
if ( !argv[i] )
{
*reply = g_strdup_printf( _("spacefm: command %s requires an argument\n"),
argv[0] );
return 1;
}
// this only handles keys assigned to menu items
GdkEventKey* event = (GdkEventKey*)gdk_event_new(GDK_KEY_PRESS);
event->keyval = (guint)strtol( argv[i], NULL, 0 );
event->state = argv[i+1] ? (guint)strtol( argv[i+1], NULL, 0 ) : 0;
if ( event->keyval )
{
gtk_window_present( GTK_WINDOW( main_window ) );
on_main_window_keypress( main_window, event, NULL );
}
else
{
*reply = g_strdup_printf( _("spacefm: invalid keycode '%s'\n"),
argv[i] );
gdk_event_free( (GdkEvent*)event );
return 2;
}
gdk_event_free( (GdkEvent*)event );
}
else if ( !strcmp( argv[0], "show-menu" ) )
{
if ( !argv[i] )
{
*reply = g_strdup_printf( _("spacefm: command %s requires an argument\n"),
argv[0] );
return 1;
}
XSet* set = xset_find_menu( argv[i] );
if ( !set )
{
*reply = g_strdup_printf( _("spacefm: custom submenu '%s' not found\n"),
argv[i] );
return 2;
}
XSetContext* context = xset_context_new();
main_context_fill( file_browser, context );
if ( context && context->valid )
{
if ( !xset_get_b( "context_dlg" ) &&
xset_context_test( set->context, FALSE ) != CONTEXT_SHOW )
{
*reply = g_strdup_printf( _("spacefm: menu '%s' context hidden or disabled\n"),
argv[i] );
return 2;
}
}
set = xset_get( set->child );
widget = gtk_menu_new();
GtkAccelGroup* accel_group = gtk_accel_group_new();
xset_add_menuitem( NULL, file_browser, GTK_WIDGET( widget ), accel_group,
set );
g_idle_add( (GSourceFunc)delayed_show_menu, widget );
}
else if ( !strcmp( argv[0], "add-event" ) ||
!strcmp( argv[0], "replace-event" ) ||
!strcmp( argv[0], "remove-event" ) )
{
XSet* set;
if ( !( argv[i] && argv[i+1] ) )
{
*reply = g_strdup_printf( _("spacefm: %s requires two arguments\n"),
argv[0] );
return 1;
}
if ( !( set = xset_is( argv[i] ) ) )
{
*reply = g_strdup_printf( _("spacefm: invalid event name '%s'\n"),
argv[i] );
return 2;
}
// build command
GString* gstr = g_string_new( !strcmp( argv[0], "replace-event" ) ? "*" : "" );
for ( j = i + 1; argv[j]; j++ )
g_string_append_printf( gstr, "%s%s", j == i + 1 ? "" : " ", argv[j] );
str = g_string_free( gstr, FALSE );
// modify list
if ( !strcmp( argv[0], "remove-event" ) )
{
l = g_list_find_custom( (GList*)set->ob2_data, str,
(GCompareFunc)g_strcmp0 );
if ( !l )
{
// remove replace event
char* str2 = str;
str = g_strdup_printf( "*%s", str2 );
g_free( str2 );
l = g_list_find_custom( (GList*)set->ob2_data, str,
(GCompareFunc)g_strcmp0 );
}
g_free( str );
if ( !l )
{
*reply = g_strdup_printf( _("spacefm: event handler not found\n") );
return 2;
}
l = g_list_remove( (GList*)set->ob2_data, l->data );
}
else
l = g_list_append( (GList*)set->ob2_data, str );
set->ob2_data = (gpointer)l;
}
else
{
*reply = g_strdup_printf( _("spacefm: invalid socket method '%s'\n"),
argv[0] );
return 1;
}
return 0;
}
gboolean run_event( FMMainWindow* main_window, PtkFileBrowser* file_browser,
XSet* preset, const char* event,
int panel, int tab, const char* focus,
int keyval, int button, int state,
gboolean visible, XSet* set, char* ucmd )
{
char* cmd;
gboolean inhibit;
char* argv[4];
gint exit_status;
if ( !ucmd )
return FALSE;
if ( ucmd[0] == '*' )
{
ucmd++;
inhibit = TRUE;
}
else
inhibit = FALSE;
if ( !preset && ( !strcmp( event, "evt_start" ) ||
!strcmp( event, "evt_exit" ) ||
!strcmp( event, "evt_device" ) ) )
{
cmd = replace_string( ucmd, "%e", event, FALSE );
if ( !strcmp( event, "evt_device" ) )
{
if ( !focus )
return FALSE;
char* str = cmd;
cmd = replace_string( str, "%f", focus, FALSE );
g_free( str );
char* change;
if ( state == VFS_VOLUME_ADDED )
change = "added";
else if ( state == VFS_VOLUME_REMOVED )
change = "removed";
else
change = "changed";
str = cmd;
cmd = replace_string( str, "%v", change, FALSE );
g_free( str );
}
argv[0] = g_strdup( "bash" );
argv[1] = g_strdup( "-c" );
argv[2] = cmd;
argv[3] = NULL;
printf( "EVENT %s >>> %s\n", event, argv[2] );
//g_spawn_command_line_async( cmd, NULL );
//system( cmd );
g_spawn_async( NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
NULL, NULL );
return FALSE;
}
if ( !main_window )
return FALSE;
// replace vars
char* replace = "ewpt";
if ( set == evt_win_click )
{
replace = "ewptfbm";
state = ( state & ( GDK_SHIFT_MASK | GDK_CONTROL_MASK |
GDK_MOD1_MASK | GDK_SUPER_MASK | GDK_HYPER_MASK | GDK_META_MASK ) );
}
else if ( set == evt_win_key )
replace = "ewptkm";
else if ( set == evt_pnl_show )
replace = "ewptfv";
char* str;
char* rep;
char var[3];
var[0] = '%';
var[2] = '\0';
int i = 0;
cmd = NULL;
while ( replace[i] )
{
/*
%w windowid
%p panel
%t tab
%f focus
%e event
%k keycode
%m modifier
%b button
%v visible
*/
var[1] = replace[i];
str = cmd;
if ( var[1] == 'e' )
cmd = replace_string( ucmd, var, event, FALSE );
else if ( strstr( str, var ) )
{
if ( var[1] == 'f' )
{
if ( !focus )
{
rep = g_strdup_printf( "panel%d", panel );
cmd = replace_string( str, var, rep, FALSE );
g_free( rep );
}
else
cmd = replace_string( str, var, focus, FALSE );
}
else if ( var[1] == 'w' )
{
rep = g_strdup_printf( "%p", main_window );
cmd = replace_string( str, var, rep, FALSE );
g_free( rep );
}
else if ( var[1] == 'p' )
{
rep = g_strdup_printf( "%d", panel );
cmd = replace_string( str, var, rep, FALSE );
g_free( rep );
}
else if ( var[1] == 't' )
{
rep = g_strdup_printf( "%d", tab );
cmd = replace_string( str, var, rep, FALSE );
g_free( rep );
}
else if ( var[1] == 'v' )
cmd = replace_string( str, var, visible ? "1" : "0", FALSE );
else if ( var[1] == 'k' )
{
rep = g_strdup_printf( "%#x", keyval );
cmd = replace_string( str, var, rep, FALSE );
g_free( rep );
}
else if ( var[1] == 'b' )
{
rep = g_strdup_printf( "%d", button );
cmd = replace_string( str, var, rep, FALSE );
g_free( rep );
}
else if ( var[1] == 'm' )
{
rep = g_strdup_printf( "%#x", state );
cmd = replace_string( str, var, rep, FALSE );
g_free( rep );
}
else
{
// failsafe
g_free( str );
g_free( cmd );
return FALSE;
}
g_free( str );
}
i++;
}
if ( !inhibit )
{
printf( "\nEVENT %s >>> %s\n", event, cmd );
if ( !strcmp( event, "evt_tab_close" ) )
{
// file_browser becomes invalid so spawn
argv[0] = g_strdup( "bash" );
argv[1] = g_strdup( "-c" );
argv[2] = cmd;
argv[3] = NULL;
g_spawn_async( NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
NULL, NULL );
}
else
{
// task
PtkFileTask* task = ptk_file_exec_new( event,
ptk_file_browser_get_cwd( file_browser ),
GTK_WIDGET( file_browser ),
main_window->task_view );
task->task->exec_browser = file_browser;
task->task->exec_command = cmd;
task->task->exec_icon = g_strdup( set->icon );
task->task->exec_sync = FALSE;
task->task->exec_export = TRUE;
ptk_file_task_run( task );
}
return FALSE;
}
argv[0] = g_strdup( "bash" );
argv[1] = g_strdup( "-c" );
argv[2] = cmd;
argv[3] = NULL;
printf( "REPLACE_EVENT %s >>> %s\n", event, argv[2] );
inhibit = FALSE;
if ( g_spawn_sync( NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
NULL, NULL, &exit_status, NULL ) )
{
if ( WIFEXITED( exit_status ) && WEXITSTATUS( exit_status ) == 0 )
inhibit = TRUE;
}
printf( "REPLACE_EVENT ? %s\n", inhibit ? "TRUE" : "FALSE" );
return inhibit;
}
gboolean main_window_event( gpointer mw, XSet* preset, const char* event,
int panel, int tab, const char* focus,
int keyval, int button, int state,
gboolean visible )
{
XSet* set;
gboolean inhibit = FALSE;
//printf("main_window_event %s\n", event );
// get set
if ( preset )
set = preset;
else
{
set = xset_get( event );
if ( !set->s && !set->ob2_data )
return FALSE;
}
// get main_window, panel, and tab
FMMainWindow* main_window;
PtkFileBrowser* file_browser;
if ( !mw )
main_window = fm_main_window_get_last_active();
else
main_window = (FMMainWindow*)mw;
if ( main_window )
{
file_browser = PTK_FILE_BROWSER(
fm_main_window_get_current_file_browser( main_window ) );
if ( !file_browser )
return FALSE;
if ( !panel )
panel = main_window->curpanel;
if ( !tab )
{
tab = gtk_notebook_page_num(
GTK_NOTEBOOK( main_window->panel[file_browser->mypanel - 1] ),
GTK_WIDGET( file_browser ) ) + 1;
}
}
else
file_browser = NULL;
// dynamic handlers
if ( set->ob2_data )
{
GList* l;
for ( l = (GList*)set->ob2_data; l; l = l->next )
{
if ( run_event( main_window, file_browser, preset, event, panel,
tab, focus, keyval, button, state,
visible, set, (char*)l->data ) )
inhibit = TRUE;
}
}
// Events menu handler
return ( run_event( main_window, file_browser, preset, event, panel,
tab, focus, keyval, button, state,
visible, set, set->s ) || inhibit );
}
|
143 | ./spacefm/src/cust-dialog.c | /*
* cust-dialog.c
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <gdk/gdk.h>
#include <gdk/gdkkeysyms.h>
#include <gdk-pixbuf/gdk-pixbuf.h>
#include <gtk/gtk.h>
#include <glib/gi18n.h>
#include <glib-object.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include "settings.h"
#include "cust-dialog.h"
#include "gtk2-compat.h"
#define DEFAULT_TITLE "SpaceFM Dialog"
#define DEFAULT_ICON "spacefm-48-pyramid-blue"
#define DEFAULT_PAD 4
#define DEFAULT_WIDTH 450
#define DEFAULT_HEIGHT 100
#define DEFAULT_LARGE_WIDTH 600
#define DEFAULT_LARGE_HEIGHT 400
#define MAX_LIST_COLUMNS 32
#define BASH_VALID "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"
#define DEFAULT_MANUAL "http://ignorantguru.github.com/spacefm/spacefm-manual-en.html#dialog"
static void update_element( CustomElement* el, GtkWidget* box, GSList** radio,
int pad );
static char* replace_vars( CustomElement* el, char* value, char* xvalue );
static void fill_buffer_from_file( CustomElement* el, GtkTextBuffer* buf,
char* path, gboolean watch );
static void write_source( GtkWidget* dlg, CustomElement* el_pressed,
FILE* out );
static gboolean destroy_dlg( GtkWidget* dlg );
static void on_button_clicked( GtkButton *button, CustomElement* el );
void on_combo_changed( GtkComboBox* box, CustomElement* el );
static gboolean on_timeout_timer( CustomElement* el );
static gboolean press_last_button( GtkWidget* dlg );
static void on_dlg_close( GtkDialog* dlg );
static gboolean on_progress_timer( CustomElement* el );
GtkWidget* signal_dialog = NULL; // make this a list if supporting multiple dialogs
static void set_font( GtkWidget* w, const char* font )
{
if ( w && font )
{
PangoFontDescription* font_desc = pango_font_description_from_string( font );
gtk_widget_modify_font( w, font_desc );
pango_font_description_free( font_desc );
}
}
static void dlg_warn( const char* msg, const char* a, const char* b )
{
char* str = g_strdup_printf( "** spacefm-dialog: %s\n", msg );
fprintf( stderr, str, a, b );
g_free( str );
}
static void get_window_size( GtkWidget* dlg, int* width, int* height )
{
GtkAllocation allocation;
gtk_widget_get_allocation( dlg, &allocation );
*width = allocation.width;
*height = allocation.height;
}
static void get_width_height_pad( char* val, int* width, int* height, int* pad )
{ // modifies val
char* str;
char* sep;
int i;
*width = *height = -1;
if ( val )
{
if ( sep = strchr( val, 'x' ) )
sep[0] = '\0';
else if ( sep = strchr( val, ' ' ) )
sep[0] = '\0';
*width = atoi( val );
if ( sep )
{
sep[0] = 'x';
str = sep + 1;
if ( sep = strchr( str, 'x' ) )
sep[0] = '\0';
else if ( sep = strchr( str, ' ' ) )
sep[0] = '\0';
*height = atoi( str );
if ( sep )
{
sep[0] = ' ';
i = atoi( sep + 1 );
// ignore pad == -1
if ( i != -1 && pad )
{
*pad = i;
if ( *pad < 0 ) *pad = 0;
}
}
}
}
if ( *width <= 0 ) *width = -1;
if ( *height <= 0 ) *height = -1;
}
static void fill_combo_box( CustomElement* el, GList* arglist )
{
GList* l;
GList* args;
char* arg;
char* str;
GtkTreeIter iter;
GtkTreeModel* model;
char* default_value = NULL;
int default_row = -1;
int set_default = -1;
if ( !el->widgets->next )
return;
GtkWidget* combo = (GtkWidget*)el->widgets->next->data;
if ( !GTK_IS_COMBO_BOX( combo ) )
return;
// prepare default value
if ( el->val )
{
if ( el->val[0] == '+' && atoi( el->val + 1 ) >= 0 )
default_row = atoi( el->val + 1 );
else
default_value = el->val;
}
// clear list
model = gtk_combo_box_get_model( GTK_COMBO_BOX( combo ) );
while ( gtk_tree_model_get_iter_first( model, &iter ) )
gtk_list_store_remove( GTK_LIST_STORE( model ), &iter );
if ( el->type == CDLG_COMBO )
gtk_entry_set_text( GTK_ENTRY( gtk_bin_get_child( GTK_BIN( combo ) ) ),
"" );
// fill list
args = arglist;
int row = 0;
while ( args )
{
arg = (char*)args->data;
args = args->next;
if ( !strcmp( arg, "--" ) )
break;
gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( combo ), arg );
if ( row == default_row || !g_strcmp0( arg, default_value ) )
set_default = row;
row++;
}
// set default
if ( set_default != -1 )
{
if ( el->type == CDLG_DROP )
g_signal_handlers_block_matched( el->widgets->next->data,
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_combo_changed, el );
gtk_combo_box_set_active( GTK_COMBO_BOX( combo ), set_default );
if ( el->type == CDLG_DROP )
g_signal_handlers_unblock_matched( el->widgets->next->data,
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_combo_changed, el );
}
else if ( default_value && el->type == CDLG_COMBO )
gtk_entry_set_text( GTK_ENTRY( gtk_bin_get_child( GTK_BIN( combo ) ) ),
default_value );
}
static void select_in_combo_box( CustomElement* el, const char* value )
{
GtkTreeIter iter;
GtkTreeModel* model;
char* str;
if ( !el->widgets->next )
return;
GtkWidget* combo = (GtkWidget*)el->widgets->next->data;
if ( !GTK_IS_COMBO_BOX( combo ) )
return;
model = gtk_combo_box_get_model( GTK_COMBO_BOX( combo ) );
if ( !model )
return;
if ( !gtk_tree_model_get_iter_first( model, &iter ) )
return;
do
{
gtk_tree_model_get( model, &iter, 0, &str, -1 );
if ( !g_strcmp0( str, value ) )
{
gtk_combo_box_set_active_iter( GTK_COMBO_BOX( combo ), &iter );
g_free( str );
break;
}
g_free( str );
}
while ( gtk_tree_model_iter_next( model, &iter ) );
}
char* get_column_value( GtkTreeModel* model, GtkTreeIter* iter, int col_index )
{
char* str = NULL;
gint64 i64;
gdouble d;
int i;
switch ( gtk_tree_model_get_column_type( model, col_index ) )
{
case G_TYPE_INT64:
gtk_tree_model_get( model, iter, col_index, &i64, -1 );
str = g_strdup_printf( "%ld", i64 );
break;
case G_TYPE_INT:
gtk_tree_model_get( model, iter, col_index, &i, -1 );
str = g_strdup_printf( "%d", i );
break;
case G_TYPE_DOUBLE:
gtk_tree_model_get( model, iter, col_index, &d, -1 );
str = g_strdup_printf( "%lf", d );
break;
case G_TYPE_STRING:
gtk_tree_model_get( model, iter, col_index, &str, -1 );
}
return str;
}
char* get_tree_view_selected( CustomElement* el, const char* prefix )
{
GtkTreeIter iter;
GtkTreeModel* model;
GtkTreeSelection* tree_sel;
GtkTreePath* tree_path;
char* selected = NULL;
char* indices = NULL;
char* str;
if ( !el->widgets->next )
goto _return_value;
GtkWidget* view = (GtkWidget*)el->widgets->next->data;
if ( !GTK_IS_TREE_VIEW( view ) )
goto _return_value;
tree_sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( view ) );
model = gtk_tree_view_get_model( GTK_TREE_VIEW( view ) );
if ( !GTK_IS_TREE_MODEL( model ) )
goto _return_value;
int row = -1;
char* value;
gboolean valid_iter = gtk_tree_model_get_iter_first( model, &iter );
while ( valid_iter )
{
row++;
if ( gtk_tree_selection_iter_is_selected( tree_sel, &iter ) )
{
str = get_column_value( model, &iter, 0 );
value = bash_quote( str );
g_free( str );
str = selected;
selected = g_strdup_printf( "%s%s%s",
str ? str : "",
prefix ? ( str ? "\n" : "" ) : " ",
value );
g_free( value );
g_free( str );
str = indices;
indices = g_strdup_printf( "%s%s%d",
str ? str : "",
str ? " " : "",
row );
g_free( str );
if ( el->type == CDLG_LIST )
break;
}
valid_iter = gtk_tree_model_iter_next( model, &iter );
}
_return_value:
if ( !prefix )
{
g_free( indices );
return selected ? selected : g_strdup( "" );
}
if ( !selected )
str = g_strdup_printf( "%s_%s=''\n%s_%s_index='%s'\n",
prefix, el->name,
prefix, el->name,
el->type == CDLG_LIST ? "-1" : "" );
else if ( el->type == CDLG_LIST )
str = g_strdup_printf( "%s_%s=%s\n%s_%s_index=%s\n",
prefix, el->name,
selected,
prefix, el->name,
indices );
else
str = g_strdup_printf( "%s_%s=(\n%s )\n%s_%s_index=( %s )\n",
prefix, el->name,
selected,
prefix, el->name,
indices );
g_free( selected );
g_free( indices );
return str;
}
static void fill_tree_view( CustomElement* el, GList* arglist )
{
GList* l;
GList* args;
char* arg;
char* sep;
char* str;
GtkTreeIter iter;
GtkListStore* list;
GtkTreeModel* model;
GtkTreeViewColumn* col;
GtkCellRenderer *renderer;
GType coltypes[MAX_LIST_COLUMNS];
int colcount;
int i;
gboolean headers = FALSE;
if ( !el->widgets->next )
return;
GtkWidget* view = (GtkWidget*)el->widgets->next->data;
if ( !GTK_IS_TREE_VIEW( view ) )
return;
// clear list
model = gtk_tree_view_get_model( GTK_TREE_VIEW( view ) );
if ( model )
gtk_list_store_clear( GTK_LIST_STORE( model ) );
// remove columns
args = gtk_tree_view_get_columns( GTK_TREE_VIEW( view ) );
for ( l = args; l; l = l->next )
{
gtk_tree_view_remove_column( GTK_TREE_VIEW( view ),
GTK_TREE_VIEW_COLUMN( (GtkTreeViewColumn*)l->data ) );
}
g_list_free( args );
// fill list
args = arglist;
col = NULL;
colcount = 0;
while ( args )
{
arg = (char*)args->data;
args = args->next;
if ( !strcmp( arg, "--" ) )
{
el->cmd_args = args;
break;
}
if ( g_str_has_prefix( arg, "--colwidth" ) )
{
str = NULL;
if ( g_str_has_prefix( arg, "--colwidth=" ) )
str = arg + strlen( "--colwidth=" );
else if ( !strcmp( arg, "--colwidth" ) && args )
{
str = (char*)args->data; // next argument
args = args->next; // skip next argument
}
if ( col && str && ( i = atoi( str ) ) > 0 )
gtk_tree_view_column_set_fixed_width( col, i );
continue;
}
if ( arg[0] == '^' || !col )
{
// new column start
if ( colcount == MAX_LIST_COLUMNS )
{
str = g_strdup_printf( _("Too many columns (>%d) in %s"),
MAX_LIST_COLUMNS, el->name );
dlg_warn( str, NULL, NULL );
g_free( str );
break;
}
col = gtk_tree_view_column_new();
gtk_tree_view_column_set_sort_indicator( col, TRUE );
gtk_tree_view_column_set_sort_column_id( col, colcount );
gtk_tree_view_append_column( GTK_TREE_VIEW( view ), col );
//if ( colcount == 0 )
gtk_tree_view_column_set_expand ( col, TRUE );
gtk_tree_view_column_set_sizing( col, GTK_TREE_VIEW_COLUMN_FIXED );
gtk_tree_view_column_set_resizable( col, TRUE );
gtk_tree_view_column_set_min_width( col, 50 );
colcount++;
coltypes[colcount - 1] = G_TYPE_STRING;
if ( arg[0] == '^' )
{
// column header
sep = strrchr( arg, ':' );
if ( sep && sep[1] == '\0' )
sep = NULL;
if ( sep )
sep[0] = '\0';
gtk_tree_view_column_set_title( col, arg + 1 );
if ( !strcmp( arg + 1, "HIDE" ) && colcount == 1 )
gtk_tree_view_column_set_visible( col, FALSE );
if ( sep )
{
sep[0] = ':';
sep++;
if ( !strcmp( sep, "progress" )
&& gtk_tree_view_column_get_visible( col ) )
coltypes[colcount - 1] = G_TYPE_INT;
else if ( !strcmp( sep, "int" ) )
coltypes[colcount - 1] = G_TYPE_INT64;
else if ( !strcmp( sep, "double" ) )
coltypes[colcount - 1] = G_TYPE_DOUBLE;
}
headers = TRUE;
}
// pack renderer
switch ( coltypes[colcount - 1] )
{
case G_TYPE_STRING:
case G_TYPE_INT64:
case G_TYPE_DOUBLE:
renderer = gtk_cell_renderer_text_new();
gtk_tree_view_column_pack_start( col, renderer, TRUE );
gtk_tree_view_column_set_attributes( col, renderer,
"text", colcount - 1, NULL );
g_object_set( G_OBJECT( renderer ),
/*"editable", TRUE,*/
"ellipsize", PANGO_ELLIPSIZE_END, NULL );
break;
case G_TYPE_INT:
renderer = gtk_cell_renderer_progress_new();
gtk_tree_view_column_pack_start( col, renderer, TRUE );
gtk_tree_view_column_set_attributes( col, renderer,
"value", colcount - 1, NULL );
}
}
}
gtk_tree_view_set_headers_visible( GTK_TREE_VIEW( view ), headers );
if ( colcount == 0 )
return;
// list store
list = gtk_list_store_newv( colcount, coltypes );
gtk_tree_view_set_model( GTK_TREE_VIEW( view ),
GTK_TREE_MODEL( list ) );
int colx = 0;
gboolean start = FALSE;
gboolean valid_iter = FALSE;
args = arglist;
while ( args )
{
arg = (char*)args->data;
args = args->next;
if ( !strcmp( arg, "--" ) )
break;
if ( arg[0] == '^' )
{
// new column start
if ( start )
{
if ( colx == MAX_LIST_COLUMNS - 1 )
break;
colx++;
// set iter to first row - false if no rows
valid_iter = gtk_tree_model_get_iter_first(
GTK_TREE_MODEL( list ), &iter );
}
}
else if ( g_str_has_prefix( arg, "--colwidth=" ) )
continue;
else if ( g_str_has_prefix( arg, "--colwidth" ) )
{
args = args->next;
continue;
}
else
{
if ( colx == 0 )
{
// first column - add row
start = TRUE;
gtk_list_store_append( list, &iter );
}
else
{
// non-first column - add row if needed
if ( !valid_iter )
{
// no row for this data, so add a row
// non-first column was longer than first column
gtk_list_store_append( list, &iter );
}
}
// set row data
if ( coltypes[colx] == G_TYPE_INT )
{
i = atoi( arg );
if ( i < 0 ) i = 0;
if ( i > 100 ) i = 100;
gtk_list_store_set( list, &iter, colx, i, -1 );
}
else if ( coltypes[colx] == G_TYPE_INT64 )
gtk_list_store_set( list, &iter, colx, atoi( arg ), -1 );
else if ( coltypes[colx] == G_TYPE_DOUBLE )
gtk_list_store_set( list, &iter, colx, strtod( arg, NULL ), -1 );
else
gtk_list_store_set( list, &iter, colx, arg, -1 );
if ( colx != 0 )
valid_iter = gtk_tree_model_iter_next( GTK_TREE_MODEL( list ), &iter );
}
}
// resize columns - none of this seems to do anything
gtk_tree_view_columns_autosize( GTK_TREE_VIEW( view ) ); // doc: only works after realize
/*
args = gtk_tree_view_get_columns( GTK_TREE_VIEW( view ) );
for ( l = args; l; l = l->next )
{
gtk_tree_view_column_queue_resize(
GTK_TREE_VIEW_COLUMN( (GtkTreeViewColumn*)l->data ) );
}
g_list_free( args );
*/
}
static void select_in_tree_view( CustomElement* el, const char* value,
gboolean select )
{
GtkTreeModel* model;
GtkTreePath* tree_path;
GtkTreeIter iter;
GtkTreeSelection* tree_sel;
char* str;
if ( !el || !el->widgets->next || !value )
return;
GtkWidget* view = (GtkWidget*)el->widgets->next->data;
if ( !GTK_IS_TREE_VIEW( view ) )
return;
model = gtk_tree_view_get_model( GTK_TREE_VIEW( view ) );
if ( !model )
return;
tree_sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( view ) );
if ( value[0] == '\0' )
{
if ( select )
{
if ( el->type == CDLG_MLIST )
gtk_tree_selection_select_all( tree_sel );
else if ( gtk_tree_model_get_iter_first( model, &iter ) )
{
// select first
tree_path = gtk_tree_model_get_path( model, &iter );
gtk_tree_selection_select_path( tree_sel, tree_path );
gtk_tree_view_set_cursor( GTK_TREE_VIEW( view ),
tree_path, NULL, FALSE);
gtk_tree_view_scroll_to_cell( GTK_TREE_VIEW( view ),
tree_path, NULL, TRUE, .25, 0 );
}
}
else
gtk_tree_selection_unselect_all( tree_sel );
return;
}
if ( !gtk_tree_model_get_iter_first( model, &iter ) )
return;
do
{
str = get_column_value( model, &iter, 0 );
if ( !g_strcmp0( str, value ) )
{
if ( !!gtk_tree_selection_iter_is_selected( tree_sel, &iter )
!= !!select )
{
tree_path = gtk_tree_model_get_path( model, &iter );
if ( select )
{
gtk_tree_selection_select_path( tree_sel, tree_path );
// scroll and set cursor
if ( el->type == CDLG_LIST )
gtk_tree_view_set_cursor( GTK_TREE_VIEW( view ),
tree_path, NULL, FALSE);
gtk_tree_view_scroll_to_cell( GTK_TREE_VIEW( view ),
tree_path, NULL, TRUE, .25, 0 );
}
else
gtk_tree_selection_unselect_path( tree_sel, tree_path );
}
g_free( str );
break;
}
g_free( str );
}
while ( gtk_tree_model_iter_next( model, &iter ) );
}
GList* args_from_file( const char* path )
{
char line[ 2048 ];
GList* args = NULL;
FILE* file = fopen( path, "r" );
if ( !file )
{
dlg_warn( _("error reading file %s: %s"), path,
g_strerror( errno ) );
return NULL;
}
while ( fgets( line, sizeof( line ), file ) )
{
if ( !g_utf8_validate( line, -1, NULL ) )
{
dlg_warn( _("file '%s' contents are not valid UTF-8"), path, NULL );
g_list_foreach( args, (GFunc)g_free, NULL );
g_list_free( args );
return NULL;
}
strtok( line, "\r\n" );
if ( !strcmp( line, "--" ) )
break;
args = g_list_prepend( args, g_strdup( line ) );
}
fclose( file );
return ( args = g_list_reverse( args ) );
}
static CustomElement* el_from_name( CustomElement* el, const char* name )
{
GList* l;
if ( !el || !name )
return NULL;
GList* elements = (GList*)g_object_get_data( G_OBJECT( el->widgets->data ),
"elements" );
CustomElement* el_name = NULL;
for ( l = elements; l; l = l->next )
{
if ( !strcmp( ((CustomElement*)l->data)->name, name ) )
{
el_name = (CustomElement*)l->data;
break;
}
}
return el_name;
}
static void set_element_value( CustomElement* el, const char* name,
char* value )
{
GtkWidget* dlg = (GtkWidget*)el->widgets->data;
GtkWidget* w;
GdkPixbuf* pixbuf;
GtkWidget* image_box;
GtkTextBuffer* buf;
char* sep;
char* str;
int i, width, height;
GList* l;
if ( !el || !name || !value )
return;
CustomElement* el_name = el_from_name( el, name );
if ( !el_name )
{
dlg_warn( _("Cannot set missing element '%s'"), name, NULL );
return;
}
switch ( el_name->type )
{
case CDLG_TITLE:
gtk_window_set_title( GTK_WINDOW( dlg ), value );
g_free( el_name->val );
el_name->val = g_strdup( value );
break;
case CDLG_WINDOW_ICON:
if ( value[0] != '\0' )
pixbuf = gtk_icon_theme_load_icon( gtk_icon_theme_get_default(),
value, 16, GTK_ICON_LOOKUP_USE_BUILTIN, NULL );
else
pixbuf = NULL;
gtk_window_set_icon( GTK_WINDOW( dlg ), pixbuf );
g_free( el_name->val );
el_name->val = g_strdup( value );
break;
case CDLG_LABEL:
if ( el_name->widgets->next
&& ( w = GTK_WIDGET( el_name->widgets->next->data ) ) )
{
g_free( el_name->val );
el_name->val = unescape( value );
if ( el_name->val[0] == '~' )
gtk_label_set_markup_with_mnemonic( GTK_LABEL( w ),
el_name->val + 1 );
else
gtk_label_set_text( GTK_LABEL( w ), el_name->val );
}
break;
case CDLG_BUTTON:
case CDLG_FREE_BUTTON:
if ( el_name->widgets->next
&& ( w = GTK_WIDGET( el_name->widgets->next->data ) ) )
{
g_free( el_name->val );
el_name->val = unescape( value );
if ( sep = strrchr( el_name->val, ':' ) )
sep[0] = '\0';
else
sep = NULL;
gtk_button_set_image( GTK_BUTTON( w ), NULL );
if ( !sep && ( !g_strcmp0( el_name->val, "ok" )
|| !g_strcmp0( el_name->val, "cancel" )
|| !g_strcmp0( el_name->val, "close" )
|| !g_strcmp0( el_name->val, "open" )
|| !g_strcmp0( el_name->val, "yes" )
|| !g_strcmp0( el_name->val, "no" )
|| !g_strcmp0( el_name->val, "apply" )
|| !g_strcmp0( el_name->val, "delete" )
|| !g_strcmp0( el_name->val, "edit" )
|| !g_strcmp0( el_name->val, "save" )
|| !g_strcmp0( el_name->val, "help" )
|| !g_strcmp0( el_name->val, "stop" ) ) )
{
// stock button
gtk_button_set_use_stock( GTK_BUTTON( w ), TRUE );
str = g_strdup_printf( "gtk-%s", el_name->val );
gtk_button_set_label( GTK_BUTTON( w ), str );
g_free( str );
}
else
{
// custom button
gtk_button_set_use_stock( GTK_BUTTON( w ), FALSE );
gtk_button_set_label( GTK_BUTTON( w ), el_name->val );
}
// set icon
if ( sep && sep[1] != '\0' )
gtk_button_set_image( GTK_BUTTON( w ), xset_get_image( sep + 1,
GTK_ICON_SIZE_BUTTON ) );
if ( sep )
sep[0] = ':';
}
break;
case CDLG_ICON:
case CDLG_IMAGE:
// destroy old image
if ( el_name->widgets->next && el_name->widgets->next->next &&
( w = GTK_WIDGET( el_name->widgets->next->next->data ) ) )
{
gtk_widget_destroy( w );
el_name->widgets = g_list_remove( el_name->widgets, w );
}
// add image
if ( el_name->widgets->next && !el_name->widgets->next->next && value &&
( image_box = GTK_WIDGET( el_name->widgets->next->data ) ) )
{
if ( el_name->type == CDLG_IMAGE )
w = gtk_image_new_from_file( value );
else
w = gtk_image_new_from_icon_name( value, GTK_ICON_SIZE_DIALOG );
gtk_container_add( GTK_CONTAINER( image_box ), GTK_WIDGET( w ) );
el_name->widgets = g_list_append( el_name->widgets, w );
gtk_widget_show( w );
g_free( el_name->val );
el_name->val = g_strdup( value );
}
break;
case CDLG_INPUT:
case CDLG_INPUT_LARGE:
case CDLG_PASSWORD:
if ( el_name->type == CDLG_INPUT_LARGE )
{
gtk_text_buffer_set_text( gtk_text_view_get_buffer(
GTK_TEXT_VIEW( el_name->widgets->next->data ) ),
value, -1 );
multi_input_select_region( el_name->widgets->next->data, 0, -1 );
}
else
{
gtk_entry_set_text( GTK_ENTRY( el_name->widgets->next->data ), value );
gtk_editable_select_region(
GTK_EDITABLE( el_name->widgets->next->data ),
0, -1 );
}
g_free( el_name->val );
el_name->val = g_strdup( value );
break;
case CDLG_VIEWER:
case CDLG_EDITOR:
if ( !g_file_test( value, G_FILE_TEST_IS_REGULAR ) )
{
dlg_warn( _("file '%s' is not a regular file"), value, NULL );
break;
}
if ( el_name->type == CDLG_VIEWER && el_name->widgets->next )
{
// viewer
buf = gtk_text_view_get_buffer(
GTK_TEXT_VIEW( el_name->widgets->next->data ) );
// update viewer from file
fill_buffer_from_file( el_name, buf, value, FALSE );
// scroll
if ( el_name->option )
{
//scroll to end if scrollbar is mostly down or new
GtkAdjustment* adj = gtk_scrolled_window_get_vadjustment(
GTK_SCROLLED_WINDOW( el_name->widgets->next->next->data ) );
if ( gtk_adjustment_get_upper( adj ) - gtk_adjustment_get_value( adj ) < gtk_adjustment_get_page_size( adj ) + 40 )
gtk_text_view_scroll_to_mark( GTK_TEXT_VIEW(
el_name->widgets->next->data ),
gtk_text_buffer_get_mark( buf, "end" ),
0.0, FALSE, 0, 0 );
}
g_free( el_name->val );
el_name->val = g_strdup( value );
}
else if ( el_name->type == CDLG_EDITOR && el_name->widgets->next )
{
// new editor
buf = gtk_text_view_get_buffer(
GTK_TEXT_VIEW( el_name->widgets->next->data ) );
fill_buffer_from_file( el_name, buf, value, FALSE );
g_free( el_name->val );
el_name->val = g_strdup( value );
}
break;
case CDLG_CHECKBOX:
case CDLG_RADIO:
if ( el_name->widgets->next )
{
if ( !strcmp( value, "1") || !strcmp( value, "true" ) )
gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON(
el_name->widgets->next->data ), TRUE );
else if ( !strcmp( value, "0") || !strcmp( value, "false" ) )
gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON(
el_name->widgets->next->data ), FALSE );
else
{
// update option label
str = unescape( value );
gtk_button_set_label( GTK_BUTTON( el_name->widgets->next->data ),
str );
g_free( str );
}
}
break;
case CDLG_DROP:
case CDLG_COMBO:
if ( el_name->widgets->next )
{
if ( g_file_test( value, G_FILE_TEST_IS_REGULAR ) )
{
l = args_from_file( value );
// fill list from args
fill_combo_box( el_name, l );
// free temp args
g_list_foreach( l, (GFunc)g_free, NULL );
g_list_free( l );
}
else if ( el_name->type == CDLG_COMBO )
gtk_entry_set_text( GTK_ENTRY( gtk_bin_get_child( GTK_BIN(
el_name->widgets->next->data ) ) ), value );
else
select_in_combo_box( el_name, value );
}
break;
case CDLG_LIST:
case CDLG_MLIST:
if ( el_name->widgets->next )
{
if ( g_file_test( value, G_FILE_TEST_IS_REGULAR ) )
{
l = args_from_file( value );
// fill list from args
fill_tree_view( el_name, l );
// free temp args
g_list_foreach( l, (GFunc)g_free, NULL );
g_list_free( l );
}
else
dlg_warn( _("file '%s' is not a regular file"), value, NULL );
}
break;
/*
if ( el_name->widgets->next )
{
gtk_statusbar_push( GTK_STATUSBAR( el_name->widgets->next->data ), 0,
* value );
}
break;
*/
case CDLG_PROGRESS:
if ( el_name->widgets->next )
{
if ( !g_strcmp0( value, "pulse" ) )
{
if ( el_name->timeout )
{
g_source_remove( el_name->timeout );
el_name->timeout = 0;
}
gtk_progress_bar_pulse( GTK_PROGRESS_BAR(
el_name->widgets->next->data ) );
}
else if ( !g_strcmp0( value, "auto-pulse" ) )
{
if ( !el_name->timeout )
el_name->timeout = g_timeout_add( 200,
(GSourceFunc)on_progress_timer, el_name );
}
else
{
i = value ? atoi( value ) : 0;
if ( i < 0 ) i = 0;
if ( i > 100 ) i = 100;
if ( i != 0 || ( value && value[0] == '0' ) )
{
if ( el_name->timeout )
{
g_source_remove( el_name->timeout );
el_name->timeout = 0;
}
gtk_progress_bar_set_fraction(
GTK_PROGRESS_BAR( el_name->widgets->next->data ),
(gdouble)i / 100 );
}
str = value;
while ( str && str[0] )
{
if ( !g_ascii_isdigit( str[0] ) )
{
gtk_progress_bar_set_text(
GTK_PROGRESS_BAR( el_name->widgets->next->data ),
value );
break;
}
str++;
}
if ( !( str && str[0] ) )
{
if ( i != 0 || ( value && value[0] == '0' ) )
str = g_strdup_printf( "%d %%", i );
else
str = g_strdup( " " );
gtk_progress_bar_set_text(
GTK_PROGRESS_BAR( el_name->widgets->next->data ),
str );
g_free( str );
}
}
}
break;
case CDLG_WINDOW_SIZE:
width = -1;
height = -1;
get_width_height_pad( value, &width, &height, NULL );
if ( width > 0 && height > 0 )
{
gtk_window_resize( GTK_WINDOW( dlg ), width, height );
gtk_window_set_position( GTK_WINDOW( dlg ),
GTK_WIN_POS_CENTER );
}
else
dlg_warn( _("Dynamic resize requires width and height > 0"), NULL, NULL );
break;
case CDLG_TIMEOUT:
if ( el_name->widgets->next && el_name->timeout )
{
g_source_remove( el_name->timeout );
el_name->option = atoi( value ) + 1;
if ( el_name->option <= 1 )
el_name->option = 21;
on_timeout_timer( el_name );
el_name->timeout = g_timeout_add( 1000, (GSourceFunc)on_timeout_timer,
el_name );
}
break;
case CDLG_CHOOSER:
if ( el_name->widgets->next )
{
i = gtk_file_chooser_get_action( GTK_FILE_CHOOSER(
el_name->widgets->next->data ) );
if ( i == GTK_FILE_CHOOSER_ACTION_SAVE ||
i == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER )
{
if ( strchr( value, '/' ) )
{
str = g_path_get_dirname( value );
gtk_file_chooser_set_current_folder(
GTK_FILE_CHOOSER( el_name->widgets->next->data ),
str );
g_free( str );
str = g_path_get_basename( value );
gtk_file_chooser_set_current_name(
GTK_FILE_CHOOSER( el_name->widgets->next->data ),
str );
g_free( str );
}
else
gtk_file_chooser_set_current_name(
GTK_FILE_CHOOSER( el_name->widgets->next->data ),
value );
}
else if ( g_file_test( value, G_FILE_TEST_IS_DIR ) )
gtk_file_chooser_set_current_folder(
GTK_FILE_CHOOSER( el_name->widgets->next->data ),
value );
else
gtk_file_chooser_set_filename(
GTK_FILE_CHOOSER( el_name->widgets->next->data ),
value );
}
break;
}
}
static char* get_element_value( CustomElement* el, const char* name )
{
int width, height, pad;
char* str;
char* str2;
GList* l;
CustomElement* el_name;
if ( !g_strcmp0( el->name, name ) )
el_name = el;
else
el_name = el_from_name( el, name );
if ( !el_name )
return g_strdup( "" );
char* ret = NULL;
switch ( el_name->type )
{
case CDLG_PREFIX:
ret = g_strdup( el_name->args ? el_name->args->data : "dialog" );
break;
case CDLG_TITLE:
case CDLG_WINDOW_ICON:
case CDLG_LABEL:
case CDLG_IMAGE:
case CDLG_ICON:
case CDLG_BUTTON:
case CDLG_FREE_BUTTON:
case CDLG_VIEWER:
case CDLG_EDITOR:
ret = g_strdup( el_name->val );
break;
case CDLG_TIMEOUT:
ret = g_strdup_printf( "%d", el_name->option );
break;
case CDLG_INPUT:
case CDLG_INPUT_LARGE:
case CDLG_PASSWORD:
if ( el_name->type == CDLG_INPUT_LARGE )
ret = multi_input_get_text( el_name->widgets->next->data );
else
ret = g_strdup( gtk_entry_get_text(
GTK_ENTRY( el_name->widgets->next->data ) ) );
break;
case CDLG_CHECKBOX:
case CDLG_RADIO:
ret = g_strdup( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(
el_name->widgets->next->data ) ) ?
"1" : "0" );
break;
case CDLG_DROP:
case CDLG_COMBO:
// write text value
ret = gtk_combo_box_text_get_active_text(
GTK_COMBO_BOX_TEXT( el_name->widgets->next->data ) );
break;
case CDLG_LIST:
case CDLG_MLIST:
ret = get_tree_view_selected( el_name, NULL );
break;
case CDLG_PROGRESS:
ret = g_strdup( gtk_progress_bar_get_text(
GTK_PROGRESS_BAR( el_name->widgets->next->data ) ) );
break;
case CDLG_WINDOW_SIZE:
pad = -1;
get_width_height_pad( el_name->val, &width, &height, &pad ); // get pad
get_window_size( el_name->widgets->data, &width, &height );
if ( pad == -1 )
ret = g_strdup_printf( "%dx%d", width, height );
else
ret = g_strdup_printf( "%dx%d %d", width, height, pad );
break;
case CDLG_CHOOSER:
if ( gtk_file_chooser_get_select_multiple( GTK_FILE_CHOOSER (
el_name->widgets->next->data ) ) )
{
GSList* files = gtk_file_chooser_get_filenames( GTK_FILE_CHOOSER(
el_name->widgets->next->data ) );
GSList* sl;
if ( files )
{
for ( sl = files; sl; sl = sl->next )
{
str = ret;
str2 = bash_quote( (char*)sl->data );
ret = g_strdup_printf( "%s%s%s", str ? str : "",
str ? " " : "",
str2 );
g_free( str );
g_free( str2 );
g_free( sl->data );
}
g_slist_free( files );
}
}
else
ret = g_strdup( gtk_file_chooser_get_filename( GTK_FILE_CHOOSER (
el_name->widgets->next->data ) ) );
break;
}
return ret ? ret : g_strdup( "" );
}
static char* get_command_value( CustomElement* el, char* cmdline, char* xvalue )
{
char* stdout = NULL;
gboolean ret;
gint exit_status;
GError* error = NULL;
char* argv[4];
char* line = replace_vars( el, cmdline, xvalue );
if ( line[0] == '\0' )
return line;
//fprintf( stderr, "spacefm-dialog: SYNC=%s\n", line );
argv[0] = g_strdup( "bash" );
argv[1] = g_strdup( "-c" );
argv[2] = line;
argv[3] = NULL;
ret = g_spawn_sync( NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
&stdout, NULL, NULL, &error );
if ( !ret && error )
{
dlg_warn( "%s", error->message, NULL );
g_error_free( error );
}
return ret && stdout ? stdout : g_strdup( "" );
}
static char* replace_vars( CustomElement* el, char* value, char* xvalue )
{
char* str;
char* str2;
char* str3;
char* ptr;
char* sep;
char c;
if ( !el || !value )
return g_strdup( value );
char* newval = NULL;
ptr = value;
while ( sep = strchr( ptr, '%' ) )
{
sep[0] = '\0';
if ( ptr[0] != '\0' )
{
str = newval;
newval = g_strdup_printf( "%s%s", str ? str : "", ptr );
g_free( str );
}
sep[0] = '%';
str = sep + 1;
while ( str[0] != '\0' && strchr( BASH_VALID, str[0] ) )
str++;
if ( sep[1] == '%' )
{
// %%
ptr = sep + 2;
str2 = newval;
newval = g_strdup_printf( "%s%s", str2 ? str2 : "", "%" );
g_free( str2 );
}
else if ( sep[1] == '(' )
{
// %(line)
ptr = strrchr( sep, ')' );
if ( !ptr )
break;
ptr[0] = '\0';
str3 = get_command_value( el, sep + 2, xvalue );
ptr[0] = ')';
ptr++;
str2 = newval;
newval = g_strdup_printf( "%s%s", str2 ? str2 : "", str3 );
g_free( str2 );
g_free( str3 );
}
else if ( str == sep + 1 )
{
// %
ptr = sep + 1;
str2 = newval;
newval = g_strdup_printf( "%s%s", str2 ? str2 : "", "%" );
g_free( str2 );
}
else
{
// %VAR
ptr = str;
c = str[0];
str[0] = '\0';
if ( !strcmp( sep + 1, "n" ) )
{
// %n
str2 = newval;
newval = g_strdup_printf( "%s%s", str2 ? str2 : "", el->name );
g_free( str2 );
}
else
{
if ( !strcmp( sep + 1, "v" ) )
// %v
str3 = xvalue ? g_strdup( xvalue ) :
get_element_value( el, el->name );
else
// %NAME
str3 = xvalue ? g_strdup( xvalue ) :
get_element_value( el, sep + 1 );
str2 = newval;
newval = g_strdup_printf( "%s%s", str2 ? str2 : "", str3 );
g_free( str2 );
g_free( str3 );
}
str[0] = c;
}
}
str = newval;
newval = g_strdup_printf( "%s%s", str ? str : "", ptr );
g_free( str );
return newval;
}
static void internal_command( CustomElement* el, int icmd, GList* args, char* xvalue )
{
char* cname = NULL;
char* cvalue = NULL;
CustomElement* el_name = NULL;
FILE* out;
gboolean reverse = FALSE;
if ( args->next )
{
if ( icmd == CMD_CLOSE )
{
if ( strcmp( (char*)args->next->data, "--" ) )
cvalue = replace_vars( el, (char*)args->next->data, xvalue );
}
else
{
cname = replace_vars( el, (char*)args->next->data, xvalue );
if ( args->next->next && strcmp( (char*)args->next->next->data, "--" ) )
cvalue = replace_vars( el, (char*)args->next->next->data, xvalue );
}
if ( cvalue && ( cvalue[0] == '\0' || !strcmp( cvalue, "0" )
|| !strcmp( cvalue, "false" ) ) )
reverse = TRUE;
}
if ( icmd != CMD_NOOP && icmd != CMD_CLOSE && icmd != CMD_SOURCE &&
icmd != CMD_FOCUS && icmd != CMD_SHOW && !cname )
{
dlg_warn( _("internal command %s requires an argument"),
cdlg_cmd[icmd*3], NULL );
return;
}
if ( !cvalue )
cvalue = g_strdup( "" );
if ( icmd == CMD_SET && ( !strcmp( cname, "title" )
|| !strcmp( cname, "windowtitle" )
|| !strcmp( cname, "windowsize" )
|| !strcmp( cname, "windowicon" ) ) )
{
// generic - no element
if ( !strcmp( cname, "title" ) || !strcmp( cname, "windowtitle" ) )
gtk_window_set_title( GTK_WINDOW( el->widgets->data ), cvalue );
else if ( !strcmp( cname, "windowsize" ) )
{
int width = -1, height = -1;
get_width_height_pad( cvalue, &width, &height, NULL );
if ( width > 0 && height > 0 )
{
gtk_window_resize( GTK_WINDOW( el->widgets->data ), width, height );
gtk_window_set_position( GTK_WINDOW( el->widgets->data ),
GTK_WIN_POS_CENTER );
}
else
dlg_warn( _("Dynamic resize requires width and height > 0"),
NULL, NULL );
}
else if ( !strcmp( cname, "windowicon" ) )
{
GdkPixbuf* pixbuf;
if ( cvalue[0] != '\0' )
pixbuf = gtk_icon_theme_load_icon( gtk_icon_theme_get_default(),
cvalue, 16, GTK_ICON_LOOKUP_USE_BUILTIN, NULL );
else
pixbuf = NULL;
gtk_window_set_icon( GTK_WINDOW( el->widgets->data ), pixbuf );
}
g_free( cname );
g_free( cvalue );
return;
}
if ( icmd != CMD_NOOP && icmd != CMD_SOURCE && icmd != CMD_CLOSE && cname
&& !( el_name = el_from_name( el, cname ) ) )
{
if ( cname[0] != '\0' )
dlg_warn( _("element '%s' does not exist"), cname, NULL );
g_free( cname );
g_free( cvalue );
return;
}
// reversal of function
if ( reverse )
{
switch ( icmd )
{
case CMD_FOCUS:
case CMD_CLOSE:
icmd = -1;
break;
case CMD_HIDE:
icmd = CMD_SHOW;
break;
case CMD_SHOW:
icmd = CMD_HIDE;
break;
case CMD_DISABLE:
icmd = CMD_ENABLE;
break;
case CMD_ENABLE:
icmd = CMD_DISABLE;
break;
}
}
//fprintf( stderr, "spacefm-dialog: INTERNAL=%s %s %s\n", cdlg_cmd[icmd*3],
// cname, cvalue );
switch ( icmd )
{
case CMD_CLOSE:
write_source( el->widgets->data, NULL, stdout );
g_idle_add( (GSourceFunc)destroy_dlg, el->widgets->data );
break;
case CMD_SET:
set_element_value( el, cname, cvalue );
break;
case CMD_PRESS:
if ( el_name->type == CDLG_BUTTON || el_name->type == CDLG_FREE_BUTTON )
on_button_clicked( NULL, el_name );
else
dlg_warn( _("internal command press is invalid for non-button %s"),
cname, NULL );
break;
case CMD_SELECT:
case CMD_UNSELECT:
if ( el_name->type == CDLG_LIST || el_name->type == CDLG_MLIST )
select_in_tree_view( el_name, cvalue, icmd == CMD_SELECT );
else if ( el_name->type == CDLG_DROP )
{
if ( icmd == CMD_SELECT )
select_in_combo_box( el_name, cvalue );
else
gtk_combo_box_set_active( GTK_COMBO_BOX(
el_name->widgets->next->data ), -1 );
}
else if ( el_name->type == CDLG_COMBO )
{
if ( icmd == CMD_SELECT )
gtk_entry_set_text( GTK_ENTRY( gtk_bin_get_child( GTK_BIN(
el_name->widgets->next->data ) ) ), cvalue );
else
gtk_entry_set_text( GTK_ENTRY( gtk_bin_get_child( GTK_BIN(
el_name->widgets->next->data ) ) ), "" );
}
else if ( el_name->type == CDLG_CHOOSER )
{
if ( icmd == CMD_SELECT )
gtk_file_chooser_select_filename( GTK_FILE_CHOOSER(
el_name->widgets->next->data ), cvalue );
else
gtk_file_chooser_unselect_filename( GTK_FILE_CHOOSER(
el_name->widgets->next->data ), cvalue );
}
else
dlg_warn( _("internal command un/select is invalid for %s"),
cdlg_option[el_name->type * 3], NULL );
break;
case CMD_HIDE:
if ( el_name->widgets->next )
gtk_widget_hide( el_name->widgets->next->data );
break;
case CMD_SHOW:
if ( el_name && el_name->widgets->next )
gtk_widget_show( el_name->widgets->next->data );
else
gtk_window_present( GTK_WINDOW( el->widgets->data ) );
break;
case CMD_FOCUS:
if ( el_name && el_name->widgets->next )
gtk_widget_grab_focus( el_name->widgets->next->data );
else
gtk_window_present( GTK_WINDOW( el->widgets->data ) );
break;
case CMD_DISABLE:
if ( el_name->widgets->next )
gtk_widget_set_sensitive( el_name->widgets->next->data, FALSE );
break;
case CMD_ENABLE:
if ( el_name->widgets->next )
gtk_widget_set_sensitive( el_name->widgets->next->data, TRUE );
break;
case CMD_SOURCE:
if ( !cname || ( cname && cname[0] == '\0' ) )
out = stderr;
else
out = fopen( cname, "w" );
if ( !out )
{
dlg_warn( _("error writing file %s: %s"), cname,
g_strerror( errno ) );
break;
}
write_source( el->widgets->data, NULL, out );
if ( out != stderr )
fclose( out );
break;
}
g_free( cname );
g_free( cvalue );
}
static void run_command( CustomElement* el, GList* argslist, char* xvalue )
{
char* str;
char* line;
char* arg;
GList* l;
int i, icmd = -1;
GList* args;
GError* error;
if ( !argslist )
return;
args = argslist;
while ( args )
{
icmd = -1;
for ( i = 0; i < G_N_ELEMENTS( cdlg_cmd ) / 3; i++ )
{
if ( !strcmp( (char*)args->data, cdlg_cmd[i*3] ) )
{
icmd = i;
break;
}
}
if ( icmd == -1 )
{
// external command
gchar* argv[g_list_length( args ) + 1];
int a = 0;
while ( args && strcmp( (char*)args->data, "--" ) )
{
if ( a == 0 )
{
if ( ((char*)args->data)[0] == '\0' )
break;
argv[a++] = g_strdup( (char*)args->data );
}
else
argv[a++] = replace_vars( el, (char*)args->data, xvalue );
args = args->next;
}
if ( a != 0 )
{
argv[a++] = NULL;
/*
fprintf( stderr, "spacefm-dialog: ASYNC=" );
for ( i = 0; i < a - 1; i++ )
fprintf( stderr, "%s%s", i == 0 ? "" : " ", argv[i] );
fprintf( stderr, "\n" );
*/
error = NULL;
if ( !g_spawn_async( NULL, argv, NULL,
G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL,
NULL, NULL, NULL, &error ) )
{
dlg_warn( "%s", error->message, NULL );
g_error_free( error );
}
}
}
else
{
// internal command
internal_command( el, icmd, args, xvalue );
while ( args && strcmp( (char*)args->data, "--" ) )
args = args->next;
}
while ( args && !strcmp( (char*)args->data, "--" ) )
args = args->next;
}
}
static void run_command_line( CustomElement* el, char* line )
{
char* sep;
GList* args = NULL;
char* str = line;
int i = 0;
// read internal command line into temp args
while ( str )
{
if ( i < 2 )
{
if ( sep = strchr( str, ' ' ) )
sep[0] = '\0';
args = g_list_append( args, g_strdup( str ) );
if ( sep )
{
sep[0] = ' ';
str = sep + 1;
}
else
str = NULL;
}
else
{
args = g_list_append( args, g_strdup( str ) );
str = NULL;
}
i++;
}
if ( args )
{
int icmd = -1;
for ( i = 0; i < G_N_ELEMENTS( cdlg_cmd ) / 3; i++ )
{
if ( !strcmp( (char*)args->data, cdlg_cmd[i*3] ) )
{
icmd = i;
break;
}
}
if ( icmd != -1 )
run_command( el, args, NULL );
else
dlg_warn( _("'%s' is not an internal command"), (char*)args->data,
NULL );
g_list_foreach( args, (GFunc)g_free, NULL );
g_list_free( args );
}
}
static void write_file_value( const char* path, const char* val )
{
int f;
int add = 0;
if ( path[0] == '@' )
add = 1;
if ( ( f = open( path + add, O_CREAT | O_WRONLY | O_TRUNC,
S_IRUSR | S_IWUSR ) ) == -1 )
{
dlg_warn( _("error writing file %s: %s"), path + add,
g_strerror( errno ) );
return;
}
if ( val && write( f, val, strlen( val ) ) < strlen( val ) )
dlg_warn( _("error writing file %s: %s"), path + add,
g_strerror( errno ) );
if ( !strchr( val, '\n' ) )
write( f, "\n", 1 );
close( f );
}
static char* read_file_value( const char* path, gboolean multi )
{
FILE* file;
int f, bytes;
const gchar* end;
if ( !g_file_test( path, G_FILE_TEST_EXISTS ) )
{
// create file
if ( ( f = open( path, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR ) ) == -1 )
{
dlg_warn( _("error creating file %s: %s"), path,
g_strerror( errno ) );
return NULL;
}
close( f );
}
// read file
char line[ 4096 ];
if ( multi )
{
// read up to 4K of file
if ( ( f = open( path, O_RDONLY ) ) == -1 )
{
dlg_warn( _("error reading file %s: %s"), path,
g_strerror( errno ) );
return NULL;
}
bytes = read( f, line, sizeof( line ) - 1 );
close(f);
line[bytes] = '\0';
}
else
{
// read first line of file
file = fopen( path, "r" );
if ( !file )
{
dlg_warn( _("error reading file %s: %s"), path,
g_strerror( errno ) );
return NULL;
}
if ( !fgets( line, sizeof( line ), file ) )
{
fclose( file );
return NULL;
}
fclose( file );
strtok( line, "\r\n" );
if ( line[0] == '\n' )
line[0] = '\0';
}
if ( !g_utf8_validate( line, -1, &end ) )
{
if ( multi && end > line )
((char*)end)[0] = '\0';
else
{
dlg_warn( _("file '%s' contents are not valid UTF-8"), path, NULL );
return NULL;
}
}
return line[0] != '\0' ? g_strdup( line ) : NULL;
}
static gboolean cb_pipe_watch( GIOChannel *channel, GIOCondition cond,
CustomElement* el )
{
/*
fprintf( stderr, "cb_pipe_watch %d\n", channel);
if ( cond & G_IO_IN )
fprintf( stderr, " G_IO_IN\n");
if ( cond & G_IO_OUT )
fprintf( stderr, " G_IO_OUT\n");
if ( cond & G_IO_PRI )
fprintf( stderr, " G_IO_PRI\n");
if ( cond & G_IO_ERR )
fprintf( stderr, " G_IO_ERR\n");
if ( cond & G_IO_HUP )
fprintf( stderr, " G_IO_HUP\n");
if ( cond & G_IO_NVAL )
fprintf( stderr, " G_IO_NVAL\n");
if ( !( cond & G_IO_NVAL ) )
{
gint fd = g_io_channel_unix_get_fd( channel );
fprintf( stderr, " fd=%d\n", fd);
if ( fcntl(fd, F_GETFL) != -1 || errno != EBADF )
{
int flags = g_io_channel_get_flags( channel );
if ( flags & G_IO_FLAG_IS_READABLE )
fprintf( stderr, " G_IO_FLAG_IS_READABLE\n");
}
else
fprintf( stderr, " Invalid FD\n");
}
*/
if ( ( cond & G_IO_NVAL ) )
{
g_io_channel_unref( channel );
return FALSE;
}
else if ( !( cond & G_IO_IN ) )
{
if ( ( cond & G_IO_HUP ) )
{
g_io_channel_unref( channel );
return FALSE;
}
else
return TRUE;
}
else if ( !( fcntl( g_io_channel_unix_get_fd( channel ), F_GETFL ) != -1
|| errno != EBADF ) )
{
// bad file descriptor
g_io_channel_unref( channel );
return FALSE;
}
//GError *error = NULL;
gsize size;
gchar line[2048];
if ( g_io_channel_read_chars( channel, line, sizeof( line ), &size, NULL ) ==
G_IO_STATUS_NORMAL && size > 0 )
{
if ( !g_utf8_validate( line, size, NULL ) )
dlg_warn( _("pipe '%s' data is not valid UTF-8"),
(char*)el->args->data, NULL );
else if ( el->type == CDLG_VIEWER && el->widgets->next )
{
GtkTextIter iter, siter;
GtkTextBuffer* buf = gtk_text_view_get_buffer(
GTK_TEXT_VIEW( el->widgets->next->data ) );
gtk_text_buffer_get_end_iter( buf, &iter);
gtk_text_buffer_insert( buf, &iter, line, size );
//scroll
if ( el->option )
{
GtkAdjustment* adj = gtk_scrolled_window_get_vadjustment(
GTK_SCROLLED_WINDOW( el->widgets->next->next->data ) );
if ( gtk_adjustment_get_upper( adj ) - gtk_adjustment_get_value( adj ) < gtk_adjustment_get_page_size( adj ) + 40 )
gtk_text_view_scroll_to_mark( GTK_TEXT_VIEW( el->widgets->next->data ),
gtk_text_buffer_get_mark( buf, "end" ),
0.0, FALSE, 0, 0 );
}
// trim
if ( gtk_text_buffer_get_char_count( buf ) > 64000 ||
gtk_text_buffer_get_line_count( buf ) > 800 )
{
if ( gtk_text_buffer_get_char_count( buf ) > 64000 )
{
// trim to 50000 characters - handles single line flood
gtk_text_buffer_get_iter_at_offset( buf, &iter,
gtk_text_buffer_get_char_count( buf ) - 50000 );
}
else
// trim to 700 lines
gtk_text_buffer_get_iter_at_line( buf, &iter,
gtk_text_buffer_get_line_count( buf ) - 700 );
gtk_text_buffer_get_start_iter( buf, &siter );
gtk_text_buffer_delete( buf, &siter, &iter );
gtk_text_buffer_get_start_iter( buf, &siter );
gtk_text_buffer_insert( buf, &siter, _("[ SNIP - additional output above has been trimmed from this log ]\n"), -1 );
}
}
else if ( el->type == CDLG_COMMAND )
{
char* str = g_strndup( line, size );
char* sep;
char* ptr = str;
while ( ptr && ptr[0] != '\0' )
{
sep = strchr( ptr, '\n' );
if ( sep )
sep[0] = '\0';
run_command_line( el, ptr );
ptr = sep ? sep + 1 : NULL;
}
g_free( str );
}
}
else
g_warning( "cb_pipe_watch: g_io_channel_read_chars != G_IO_STATUS_NORMAL" );
return TRUE;
}
static gboolean delayed_update_false( CustomElement* el )
{
if ( el->update_timeout )
{
g_source_remove( el->update_timeout );
el->update_timeout = 0;
}
return FALSE;
}
static gboolean delayed_update( CustomElement* el )
{
if ( el->update_timeout )
{
g_source_remove( el->update_timeout );
el->update_timeout = 0;
}
update_element( el, NULL, NULL, 0 );
return FALSE;
}
static void cb_file_value_change( VFSFileMonitor* fm,
VFSFileMonitorEvent event,
const char* file_name,
CustomElement* el )
{
//printf( "cb_file_value_change %d %s\n", event, file_name );
switch( event )
{
case VFS_FILE_MONITOR_DELETE:
//printf (" DELETE\n");
if ( el->monitor )
vfs_file_monitor_remove( el->monitor, el->callback, el );
el->monitor = NULL;
// update_element will add a new monitor if file re-created
// use low priority since cb_file_value_change is called from another thread
// otherwise segfault in vfs-file-monitor.c:351
break;
case VFS_FILE_MONITOR_CHANGE:
case VFS_FILE_MONITOR_CREATE:
default:
//printf (" CREATE/CHANGE\n");
break;
}
if ( !el->update_timeout )
{
// don't update element more than once every 50ms - when a file is
// changed multiple events are reported
el->update_timeout = g_timeout_add_full( G_PRIORITY_DEFAULT_IDLE,
50,
(GSourceFunc)delayed_update,
el, NULL );
}
}
static void fill_buffer_from_file( CustomElement* el, GtkTextBuffer* buf,
char* path, gboolean watch )
{
char line[ 4096 ];
FILE* file;
char* pathx = path;
if ( pathx[0] == '@' )
pathx++;
gtk_text_buffer_set_text( buf, "", -1 );
file = fopen( pathx, "r" );
if ( !file )
{
dlg_warn( _("error reading file %s: %s"), pathx,
g_strerror( errno ) );
return;
}
// read file one line at a time to prevent splitting UTF-8 characters
while ( fgets( line, sizeof( line ), file ) )
{
if ( !g_utf8_validate( line, -1, NULL ) )
{
fclose( file );
if ( watch )
gtk_text_buffer_set_text( buf, _("( file contents are not valid UTF-8 )"), -1 );
else
gtk_text_buffer_set_text( buf, "", -1 );
dlg_warn( _("file '%s' contents are not valid UTF-8"), pathx, NULL );
return;
}
gtk_text_buffer_insert_at_cursor( buf, line, -1 );
}
fclose( file );
if ( watch && !el->monitor )
{
// start monitoring file
el->callback = (VFSFileMonitorCallback)cb_file_value_change;
el->monitor = vfs_file_monitor_add( pathx, FALSE,
el->callback, el );
}
}
static void get_text_value( CustomElement* el, const char* val, gboolean multi,
gboolean watch )
{
if ( !val )
return;
if ( val[0] == '@' )
{
// get value from file
g_free( el->val );
el->val = read_file_value( val + 1, multi );
if ( multi )
// strip trailing linefeeds
while ( g_str_has_suffix( el->val, "\n" ) )
el->val[strlen( el->val ) - 1] = '\0';
if ( watch && !el->monitor && g_file_test( val + 1, G_FILE_TEST_IS_REGULAR ) )
{
// start monitoring file
el->callback = (VFSFileMonitorCallback)cb_file_value_change;
el->monitor = vfs_file_monitor_add( (char*)val + 1, FALSE,
el->callback, el );
el->watch_file = val + 1;
}
}
else
{
// get static value
if ( !el->val )
el->val = g_strdup( val );
}
}
static void free_elements( GList* elements )
{
GList* l;
CustomElement* el;
for ( l = elements; l; l = l->next )
{
el = (CustomElement*)l->data;
g_free( el->name );
g_free( el->val );
if ( el->monitor )
vfs_file_monitor_remove( el->monitor, el->callback, el );
g_list_free( el->widgets );
g_list_free( el->args );
}
g_list_free( elements );
}
static gboolean destroy_dlg( GtkWidget* dlg )
{
GList* elements = (GList*)g_object_get_data( G_OBJECT( dlg ), "elements" );
// remove destroy signal connect
g_signal_handlers_disconnect_by_func( G_OBJECT( dlg ),
G_CALLBACK( on_dlg_close ), NULL );
gtk_widget_destroy( GTK_WIDGET( dlg ) );
free_elements( elements );
gtk_main_quit();
return FALSE;
}
static void write_value( FILE* file, const char* prefix, const char* name,
const char* sub, const char* val )
{
char* str;
char* quoted = bash_quote( val );
if ( strchr( quoted, '\n' ) )
{
str = quoted;
quoted = replace_string( str, "\n", "'$'\\n''", FALSE );
g_free( str );
}
if ( strchr( quoted, '\t' ) )
{
str = quoted;
quoted = replace_string( str, "\t", "'$'\\t''", FALSE );
g_free( str );
}
fprintf( file, "%s_%s%s%s=%s\n", prefix, name, sub ? "_" : "", sub ? sub : "",
quoted );
g_free( quoted );
}
static void write_source( GtkWidget* dlg, CustomElement* el_pressed,
FILE* out )
{
GList* l;
CustomElement* el;
char* str;
char* prefix = "dialog";
int width, height, pad = -1;
GList* elements = (GList*)g_object_get_data( G_OBJECT( dlg ), "elements" );
// get custom prefix
for ( l = elements; l; l = l->next )
{
if ( ((CustomElement*)l->data)->type == CDLG_PREFIX )
{
el = (CustomElement*)l->data;
if ( el->args )
{
get_text_value( el, (char*)el->args->data, FALSE, FALSE );
if ( el->val && el->val[0] != '\0' )
{
str = g_strdup( el->val );
g_strcanon( str, BASH_VALID, ' ' );
if ( strcmp( str, el->val ) )
dlg_warn( _("prefix '%s' is not a valid variable name"),
el->val, NULL );
else
prefix = el->val;
g_free( str );
}
}
break;
}
}
// write values
int button_count = 0;
fprintf( out, "#!/bin/bash\n# SpaceFM Dialog source output - execute this output to set variables\n# Example: eval \"`spacefm --dialog --label \"Message\" --button ok`\"\n\n" );
if ( !el_pressed )
{
// no button press caused dialog closure
write_value( out, prefix, "pressed", NULL, NULL );
write_value( out, prefix, "pressed", "index", "-2" );
write_value( out, prefix, "pressed", "label", NULL );
}
for ( l = elements; l; l = l->next )
{
el = (CustomElement*)l->data;
switch ( el->type )
{
case CDLG_TITLE:
case CDLG_WINDOW_ICON:
case CDLG_LABEL:
case CDLG_IMAGE:
case CDLG_ICON:
case CDLG_COMMAND:
write_value( out, prefix, el->name, NULL, el->val );
break;
case CDLG_BUTTON:
button_count++;
case CDLG_FREE_BUTTON:
case CDLG_TIMEOUT:
if ( el == el_pressed )
{
// dialog was closed by user pressing this button
if ( el->type == CDLG_BUTTON )
{
write_value( out, prefix, "pressed", NULL, el->name );
str = g_strdup_printf( "%d", button_count - 1 );
write_value( out, prefix, "pressed", "index", str );
g_free( str );
write_value( out, prefix, "pressed", "label", el->val );
}
else if ( el->type == CDLG_TIMEOUT )
{
write_value( out, prefix, "pressed", NULL, el->name );
write_value( out, prefix, "pressed", "index", "-3" );
write_value( out, prefix, "pressed", "label", NULL );
}
else
{
write_value( out, prefix, "pressed", NULL, el->name );
write_value( out, prefix, "pressed", "index", "-1" );
write_value( out, prefix, "pressed", "label", el->val );
}
}
if ( el->type == CDLG_TIMEOUT )
{
str = g_strdup_printf( "%d", el->option );
write_value( out, prefix, el->name, NULL, str );
g_free( str );
}
else
write_value( out, prefix, el->name, NULL, el->val );
break;
case CDLG_INPUT:
case CDLG_INPUT_LARGE:
case CDLG_PASSWORD:
if ( el->type == CDLG_INPUT_LARGE )
str = multi_input_get_text( el->widgets->next->data );
else
// do not free
str = (char*)gtk_entry_get_text( GTK_ENTRY( el->widgets->next->data ) );
if ( el->args && ((char*)el->args->data)[0] == '@' )
{
// save file
// skip detection of updates while saving file
if ( el->update_timeout )
g_source_remove( el->update_timeout );
el->update_timeout = g_timeout_add_full( G_PRIORITY_DEFAULT_IDLE,
300,
(GSourceFunc)delayed_update_false,
el, NULL );
write_file_value( (char*)el->args->data, str );
}
write_value( out, prefix, el->name, "default",
el->args ? (char*)el->args->data : NULL );
write_value( out, prefix, el->name, NULL, str );
if ( el->type == CDLG_INPUT_LARGE )
g_free( str );
break;
case CDLG_VIEWER:
case CDLG_EDITOR:
write_value( out, prefix, el->name, NULL, el->val );
if ( el->args && el->args->next )
{
// save file
write_value( out, prefix, el->name, "saved",
(char*)el->args->next->data );
GtkTextIter iter, siter;
GtkTextBuffer* buf = gtk_text_view_get_buffer(
GTK_TEXT_VIEW( el->widgets->next->data ) );
gtk_text_buffer_get_start_iter( buf, &siter );
gtk_text_buffer_get_end_iter( buf, &iter );
str = gtk_text_buffer_get_text( buf, &siter, &iter, FALSE );
write_file_value( (char*)el->args->next->data, str );
g_free( str );
}
else
write_value( out, prefix, el->name, "saved", NULL );
break;
case CDLG_CHECKBOX:
case CDLG_RADIO:
write_value( out, prefix, el->name, "label", gtk_button_get_label(
GTK_BUTTON( el->widgets->next->data ) ) );
write_value( out, prefix, el->name, NULL,
gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(
el->widgets->next->data ) ) ?
"1" : "0" );
// save file
if ( el->args && el->args->next
&& ((char*)el->args->next->data)[0] == '@' )
{
write_file_value( (char*)el->args->next->data + 1,
gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(
el->widgets->next->data ) ) ?
"1" : "0" );
write_value( out, prefix, el->name, "saved",
(char*)el->args->next->data + 1 );
}
break;
case CDLG_DROP:
case CDLG_COMBO:
// write text value
str = gtk_combo_box_text_get_active_text(
GTK_COMBO_BOX_TEXT( el->widgets->next->data ) );
write_value( out, prefix, el->name, NULL, str );
if ( el->def_val && el->def_val[0] == '@' )
{
// save file
write_file_value( el->def_val + 1, str );
write_value( out, prefix, el->name, "saved", el->def_val + 1 );
}
g_free( str );
// write index
str = g_strdup_printf( "%d",
gtk_combo_box_get_active( GTK_COMBO_BOX(
el->widgets->next->data ) ) );
write_value( out, prefix, el->name, "index", str );
g_free( str );
break;
case CDLG_LIST:
case CDLG_MLIST:
str = get_tree_view_selected( el, prefix );
fprintf( out, str, NULL );
g_free( str );
break;
case CDLG_PROGRESS:
write_value( out, prefix, el->name, NULL,
gtk_progress_bar_get_text(
GTK_PROGRESS_BAR( el->widgets->next->data ) ) );
break;
case CDLG_WINDOW_SIZE:
get_width_height_pad( el->val, &width, &height, &pad ); // get pad
if ( el->args && el->args->next
&& atoi( (char*)el->args->next->data ) > 0 )
pad = atoi( (char*)el->args->next->data );
if ( el->args && ((char*)el->args->data)[0] == '@' )
{
// save file
get_window_size( el->widgets->data, &width, &height );
if ( pad == -1 )
str = g_strdup_printf( "%dx%d", width, height );
else
str = g_strdup_printf( "%dx%d %d", width, height, pad );
// skip detection of updates while saving file
if ( el->update_timeout )
g_source_remove( el->update_timeout );
el->update_timeout = g_timeout_add_full( G_PRIORITY_DEFAULT_IDLE,
300,
(GSourceFunc)delayed_update_false,
el, NULL );
write_file_value( (char*)el->args->data + 1, str );
write_value( out, prefix, el->name, "saved",
(char*)el->args->data + 1 );
g_free( str );
}
break;
case CDLG_CHOOSER:
if ( gtk_file_chooser_get_select_multiple( GTK_FILE_CHOOSER (
el->widgets->next->data ) ) )
{
GSList* files = gtk_file_chooser_get_filenames( GTK_FILE_CHOOSER(
el->widgets->next->data ) );
GSList* sl;
if ( !files )
fprintf( out, "%s_%s=''\n", prefix, el->name );
else
{
fprintf( out, "%s_%s=(", prefix, el->name );
for ( sl = files; sl; sl = sl->next )
{
str = bash_quote( (char*)sl->data );
fprintf( out, "\n%s", str );
g_free( str );
g_free( sl->data );
}
fprintf( out, ")\n" );
g_slist_free( files );
}
}
else
{
str = gtk_file_chooser_get_filename( GTK_FILE_CHOOSER (
el->widgets->next->data ) );
write_value( out, prefix, el->name, NULL, str );
g_free( str );
}
str = gtk_file_chooser_get_current_folder( GTK_FILE_CHOOSER (
el->widgets->next->data ) );
write_value( out, prefix, el->name, "dir", str );
if ( el->args && ((char*)el->args->data)[0] == '@' )
{
// save file
write_value( out, prefix, el->name, "saved",
(char*)el->args->data + 1 );
// skip detection of updates while saving file
if ( el->update_timeout )
g_source_remove( el->update_timeout );
el->update_timeout = g_timeout_add_full( G_PRIORITY_DEFAULT_IDLE,
300,
(GSourceFunc)delayed_update_false,
el, NULL );
write_file_value( (char*)el->args->data + 1, str );
}
g_free( str );
break;
}
}
// write window size
get_window_size( dlg, &width, &height );
if ( pad == -1 )
str = g_strdup_printf( "%dx%d", width, height );
else
str = g_strdup_printf( "%dx%d %d", width, height, pad );
write_value( out, prefix, "windowsize", NULL, str );
g_free( str );
}
static void on_dlg_close( GtkDialog* dlg )
{
write_source( GTK_WIDGET( dlg ), NULL, stdout );
destroy_dlg( GTK_WIDGET( dlg ) );
}
static gboolean on_progress_timer( CustomElement* el )
{
gtk_progress_bar_pulse( GTK_PROGRESS_BAR( el->widgets->next->data ) );
return TRUE;
}
static gboolean on_timeout_timer( CustomElement* el )
{
el->option--;
if ( el->option <= 0 )
{
write_source( el->widgets->data, el, stdout );
g_idle_add( (GSourceFunc)destroy_dlg, el->widgets->data );
return FALSE;
}
g_free( el->val );
el->val = g_strdup_printf( "%s %d", _("Pause"), el->option );
gtk_button_set_label( GTK_BUTTON( el->widgets->next->data ), el->val );
return TRUE;
}
/*
static gboolean on_status_button_press( GtkWidget *widget,
GdkEventButton *evt,
CustomElement* el )
{
if ( evt->type == GDK_BUTTON_PRESS && evt->button < 4 && el->args
&& el->args->next )
{
char* num = g_strdup_printf( "%d", evt->button );
run_command( el->args->next, el->name, num );
g_free( num );
return TRUE;
}
return TRUE;
}
*/
void on_combo_changed( GtkComboBox* box, CustomElement* el )
{
if ( el->type != CDLG_DROP || !el->cmd_args )
return;
run_command( el, el->cmd_args, NULL );
}
/*
gboolean on_list_button_press( GtkTreeView* view, GdkEventButton* evt,
CustomElement* el )
{
printf("on_list_button_press\n");
if ( evt->type == GDK_2BUTTON_PRESS && evt->button == 1 )
{
gtk_tree_view_row_activated( view, NULL, NULL );
return TRUE;
}
return FALSE;
}
*/
static void on_list_row_activated( GtkTreeView *view,
GtkTreePath *tree_path,
GtkTreeViewColumn* col,
CustomElement* el )
{
GtkTreeIter iter;
if ( !el->cmd_args )
{
press_last_button( el->widgets->data );
return;
}
// get iter
GtkTreeModel* model = gtk_tree_view_get_model( GTK_TREE_VIEW( view ) );
if ( !gtk_tree_model_get_iter( model, &iter, tree_path ) )
return;
/*
// get clicked column index
int colx = 0;
int x = -1;
GList* l;
GList* cols = gtk_tree_view_get_columns( GTK_TREE_VIEW( view ) );
for ( l = cols; l; l = l->next )
{
if ( l->data == col )
{
x = colx;
break;
}
colx++;
}
g_list_free( cols );
if ( x == -1 )
return;
*/
run_command( el, el->cmd_args, NULL );
}
static gboolean on_widget_button_press_event( GtkWidget *widget,
GdkEventButton *evt,
CustomElement* el )
{
if ( evt->type == GDK_BUTTON_PRESS )
{
if ( evt->button < 4 && el->cmd_args )
{
char* num = g_strdup_printf( "%d %dx%d", evt->button, (uint)evt->x,
(uint)evt->y );
run_command( el, el->cmd_args, num );
g_free( num );
return TRUE;
}
}
return FALSE;
}
void on_option_toggled( GtkToggleButton *togglebutton, CustomElement* el )
{
if ( el->type == CDLG_TIMEOUT )
{
if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(
el->widgets->next->data ) ) )
{
if ( el->timeout )
{
g_source_remove( el->timeout );
el->timeout = 0;
}
}
else
{
if ( !el->timeout )
el->timeout = g_timeout_add( 1000, (GSourceFunc)on_timeout_timer, el );
}
}
else if ( el->cmd_args )
{
if ( el->type == CDLG_RADIO )
{
if ( gtk_toggle_button_get_active( togglebutton ) )
run_command( el, el->cmd_args, "1" );
}
else if ( el->type == CDLG_CHECKBOX )
{
run_command( el, el->cmd_args,
gtk_toggle_button_get_active( togglebutton ) ? "1" : "0" );
}
}
}
static void on_button_clicked( GtkButton *button, CustomElement* el )
{
if ( el->cmd_args )
// button has a command
run_command( el, el->cmd_args, NULL );
else
{
// no command
write_source( el->widgets->data, el, stdout );
g_idle_add( (GSourceFunc)destroy_dlg, el->widgets->data );
}
}
static gboolean press_last_button( GtkWidget* dlg )
{
// find last (default) button and press it
GList* elements = (GList*)g_object_get_data( G_OBJECT( dlg ),
"elements" );
if ( !elements )
return FALSE;
GList* l;
CustomElement* el;
CustomElement* el_button = NULL;
for ( l = elements; l; l = l->next )
{
el = (CustomElement*)l->data;
if ( el->type == CDLG_BUTTON )
el_button = el;
}
if ( el_button )
{
on_button_clicked( NULL, el_button );
return TRUE;
}
return FALSE;
}
void on_chooser_activated( GtkFileChooser* chooser, CustomElement* el )
{
if ( el->cmd_args )
{
char* str = gtk_file_chooser_get_filename( chooser );
if ( str )
run_command( el, el->cmd_args, str );
g_free( str );
}
else
press_last_button( el->widgets->data );
}
gboolean on_window_delete( GtkWidget *widget, GdkEvent *event, CustomElement* el )
{
if ( el && el->cmd_args )
{
run_command( el, el->cmd_args, NULL );
return TRUE;
}
return FALSE; // allow window close
}
static gboolean on_dlg_key_press( GtkWidget *entry, GdkEventKey* evt,
CustomElement* el )
{
int keymod = ( evt->state & ( GDK_SHIFT_MASK | GDK_CONTROL_MASK |
GDK_MOD1_MASK | GDK_SUPER_MASK | GDK_HYPER_MASK | GDK_META_MASK ) );
int keycode = strtol( (char*)el->args->data, NULL, 0 );
int modifier = strtol( (char*)el->args->next->data, NULL, 0 );
if ( keycode == evt->keyval && modifier == keymod )
{
char* str = g_strdup_printf( "%s %s", (char*)el->args->data,
(char*)el->args->next->data );
run_command( el, el->cmd_args, str );
g_free( str );
return TRUE;
}
return FALSE;
}
static gboolean on_input_key_press( GtkWidget *entry, GdkEventKey* evt,
CustomElement* el )
{
int keymod = ( evt->state & ( GDK_SHIFT_MASK | GDK_CONTROL_MASK |
GDK_MOD1_MASK | GDK_SUPER_MASK | GDK_HYPER_MASK | GDK_META_MASK ) );
if ( !( !keymod && ( evt->keyval == GDK_KEY_Return || evt->keyval == GDK_KEY_KP_Enter ) ) )
return FALSE; // Enter key not pressed
if ( ( el->type == CDLG_INPUT || el->type == CDLG_INPUT_LARGE )
&& el->cmd_args )
{
// input has a command
if ( el->type == CDLG_INPUT_LARGE )
run_command( el, el->cmd_args, NULL );
else if ( el->type == CDLG_INPUT )
run_command( el, el->cmd_args, NULL );
return TRUE;
}
else if ( el->type == CDLG_COMBO && el->cmd_args )
{
run_command( el, el->cmd_args, NULL );
return TRUE;
}
else if ( el->type == CDLG_PASSWORD && el->cmd_args )
{
// password has a command
run_command( el, el->cmd_args, NULL );
return TRUE;
}
else
{
// no command - find last (default) button and press it
return press_last_button( (GtkWidget*)el->widgets->data );
}
return FALSE;
}
static void update_element( CustomElement* el, GtkWidget* box, GSList** radio,
int pad )
{
GtkWidget* w;
GdkPixbuf* pixbuf;
GtkWidget* dlg = (GtkWidget*)el->widgets->data;
char* str;
char* sep;
struct stat64 statbuf;
GtkTextBuffer* buf;
GtkTextIter iter;
int i;
GList* l;
char* font = NULL;
gboolean viewer_scroll = FALSE;
gboolean chooser_save = FALSE;
gboolean chooser_dir = FALSE;
gboolean chooser_multi = FALSE;
GList* chooser_filters = NULL;
gboolean compact = FALSE;
gboolean expand = FALSE;
gboolean wrap = FALSE;
gboolean nowrap = FALSE;
int selstart = -1;
int selend = -1;
GList* args = el->args;
// get element options
while ( args && g_str_has_prefix( (char*)args->data, "--" ) )
{
if ( !strcmp( (char*)args->data, "--font" ) )
{
if ( args->next && !g_str_has_prefix( (char*)args->next->data, "--" ) )
{
args = args->next;
font = (char*)args->data;
}
}
else if ( !strcmp( (char*)args->data, "--compact" ) )
compact = TRUE;
else if ( !strcmp( (char*)args->data, "--expand" ) )
expand = TRUE;
else if ( ( el->type == CDLG_INPUT || el->type == CDLG_INPUT_LARGE )
&& !strcmp( (char*)args->data, "--select" )
&& args->next )
{
args = args->next;
sep = strchr( (char*)args->data, ':' );
if ( !sep )
sep = strchr( (char*)args->data, ' ' );
if ( sep )
sep[0] = '\0';
selstart = atoi( (char*)args->data );
if ( sep )
{
selend = atoi( sep + 1 );
if ( selend > 0 ) selend++;
sep[0] = ':';
}
}
else if ( el->type == CDLG_VIEWER
&& !strcmp( (char*)args->data, "--scroll" ) )
viewer_scroll = TRUE;
else if ( el->type == CDLG_LABEL
&& !strcmp( (char*)args->data, "--wrap" ) )
wrap = TRUE;
else if ( el->type == CDLG_LABEL
&& !strcmp( (char*)args->data, "--nowrap" ) )
nowrap = TRUE;
else if ( el->type == CDLG_CHOOSER )
{
if ( !strcmp( (char*)args->data, "--save" ) )
chooser_save = TRUE;
else if ( !strcmp( (char*)args->data, "--dir" ) )
chooser_dir = TRUE;
else if ( !strcmp( (char*)args->data, "--multi" ) )
chooser_multi = TRUE;
else if ( !strcmp( (char*)args->data, "--filter" ) )
{
if ( args->next && !g_str_has_prefix( (char*)args->next->data, "--" ) )
{
args = args->next;
chooser_filters = g_list_append( chooser_filters,
(char*)args->data );
}
}
}
args = args->next;
}
el->args = args; // only parse options once
switch ( el->type )
{
case CDLG_TITLE:
if ( args )
{
get_text_value( el, (char*)args->data, FALSE, TRUE );
if ( el->val )
gtk_window_set_title( GTK_WINDOW( dlg ), el->val );
else
gtk_window_set_title( GTK_WINDOW( dlg ), DEFAULT_TITLE );
}
break;
case CDLG_WINDOW_ICON:
if ( args )
{
get_text_value( el, (char*)args->data, FALSE, TRUE );
if ( el->val )
pixbuf = gtk_icon_theme_load_icon( gtk_icon_theme_get_default(),
el->val, 16, GTK_ICON_LOOKUP_USE_BUILTIN, NULL );
else
pixbuf = NULL;
gtk_window_set_icon( GTK_WINDOW( dlg ), pixbuf );
el->cmd_args = el->args->next;
}
break;
case CDLG_LABEL:
if ( args )
{
get_text_value( el, (char*)args->data, TRUE, TRUE );
str = el->val;
el->val = unescape( str );
g_free( str );
}
// add label
if ( !el->widgets->next && box )
{
w = gtk_label_new( NULL );
if ( wrap || nowrap )
gtk_label_set_line_wrap( GTK_LABEL( w ), wrap );
else
{
#if GTK_CHECK_VERSION (3, 0, 0)
// gtk3 wraps labels at one char and doesn't allocate a usable width
// if in an hbox
gtk_label_set_line_wrap( GTK_LABEL( w ), !GTK_IS_HBOX( box ) );
if ( !GTK_IS_HBOX( box ) )
gtk_label_set_width_chars( GTK_LABEL( w ), 20 );
//else
// gtk_label_set_ellipsize( GTK_LABEL( w ), PANGO_ELLIPSIZE_MIDDLE );
#else
gtk_label_set_line_wrap( GTK_LABEL( w ), TRUE );
#endif
}
gtk_label_set_line_wrap_mode( GTK_LABEL( w ), PANGO_WRAP_WORD_CHAR );
gtk_misc_set_alignment( GTK_MISC ( w ), 0.0, 0.5 );
gtk_label_set_selectable( GTK_LABEL( w ), TRUE );
set_font( w, font );
el->widgets = g_list_append( el->widgets, w );
gtk_box_pack_start( GTK_BOX( box ), GTK_WIDGET( w ), expand, TRUE, pad );
if ( radio ) *radio = NULL;
//if ( args )
// el->cmd_args = el->args->next;
}
// set label
if ( el->widgets->next && ( w = GTK_WIDGET( el->widgets->next->data ) ) )
{
if ( el->val && el->val[0] == '~' )
gtk_label_set_markup_with_mnemonic( GTK_LABEL( w ), el->val + 1 );
else
gtk_label_set_text( GTK_LABEL( w ), el->val );
/* just an experiment
if ( el->val && g_utf8_strlen( el->val, -1 ) > 20 )
gtk_label_set_line_wrap( GTK_LABEL( w ), TRUE );
else
gtk_label_set_line_wrap( GTK_LABEL( w ),
!GTK_IS_HBOX( gtk_widget_get_parent( w ) ) );
*/
}
break;
case CDLG_BUTTON:
case CDLG_FREE_BUTTON:
if ( args )
{
get_text_value( el, (char*)args->data, FALSE, TRUE );
str = el->val;
el->val = unescape( str );
g_free( str );
}
// add button
if ( !el->widgets->next )
{
w = gtk_button_new();
gtk_button_set_use_underline( GTK_BUTTON( w ), TRUE );
gtk_button_set_focus_on_click( GTK_BUTTON( w ), FALSE );
el->widgets = g_list_append( el->widgets, w );
if ( el->type == CDLG_BUTTON )
{
gtk_box_pack_start( GTK_BOX( gtk_dialog_get_action_area( GTK_DIALOG( dlg ) ) ),
GTK_WIDGET( w ), expand, TRUE, pad );
gtk_widget_grab_focus( w );
}
else
gtk_box_pack_start( GTK_BOX( box ),
GTK_WIDGET( w ), expand, TRUE, pad );
g_signal_connect( G_OBJECT( w ), "clicked",
G_CALLBACK( on_button_clicked ), el );
if ( radio ) *radio = NULL;
if ( args )
el->cmd_args = el->args->next;
}
// set label and icon
if ( el->widgets->next && ( w = GTK_WIDGET( el->widgets->next->data ) ) )
{
if ( el->val && ( sep = strrchr( el->val, ':' ) ) )
sep[0] = '\0';
else
sep = NULL;
gtk_button_set_image( GTK_BUTTON( w ), NULL );
if ( !sep && ( !g_strcmp0( el->val, "ok" )
|| !g_strcmp0( el->val, "cancel" )
|| !g_strcmp0( el->val, "close" )
|| !g_strcmp0( el->val, "open" )
|| !g_strcmp0( el->val, "yes" )
|| !g_strcmp0( el->val, "no" )
|| !g_strcmp0( el->val, "apply" )
|| !g_strcmp0( el->val, "delete" )
|| !g_strcmp0( el->val, "edit" )
|| !g_strcmp0( el->val, "save" )
|| !g_strcmp0( el->val, "help" )
|| !g_strcmp0( el->val, "stop" ) ) )
{
// stock button
gtk_button_set_use_stock( GTK_BUTTON( w ), TRUE );
str = g_strdup_printf( "gtk-%s", el->val );
gtk_button_set_label( GTK_BUTTON( w ), str );
g_free( str );
}
else
{
// custom button
gtk_button_set_use_stock( GTK_BUTTON( w ), FALSE );
gtk_button_set_label( GTK_BUTTON( w ), el->val );
}
// set icon
if ( sep && sep[1] != '\0' )
gtk_button_set_image( GTK_BUTTON( w ), xset_get_image( sep + 1,
GTK_ICON_SIZE_BUTTON ) );
if ( sep )
sep[0] = ':';
}
break;
case CDLG_ICON:
case CDLG_IMAGE:
if ( args )
{
str = g_strdup( el->val );
get_text_value( el, (char*)args->data, FALSE, TRUE );
// if no change, don't update image if image_box present
if ( !g_strcmp0( str, el->val ) && el->widgets->next )
{
g_free( str );
break;
}
g_free( str );
}
// add event to hold image widget and get events
GtkWidget* image_box;
if ( !el->widgets->next && box )
{
image_box = gtk_event_box_new();
el->widgets = g_list_append( el->widgets, image_box );
gtk_box_pack_start( GTK_BOX( box ), GTK_WIDGET( image_box ),
expand, TRUE, pad );
g_signal_connect ( G_OBJECT( image_box ), "button-press-event",
G_CALLBACK ( on_widget_button_press_event ),
el );
if ( radio ) *radio = NULL;
if ( args )
el->cmd_args = el->args->next;
}
// destroy old image
if ( el->widgets->next && el->widgets->next->next &&
( w = GTK_WIDGET( el->widgets->next->next->data ) ) )
{
gtk_widget_destroy( w );
el->widgets = g_list_remove( el->widgets, w );
}
// add image
if ( el->widgets->next && !el->widgets->next->next && el->val &&
( image_box = GTK_WIDGET( el->widgets->next->data ) ) )
{
if ( el->type == CDLG_IMAGE )
w = gtk_image_new_from_file( el->val );
else
w = gtk_image_new_from_icon_name( el->val, GTK_ICON_SIZE_DIALOG );
gtk_container_add( GTK_CONTAINER( image_box ), GTK_WIDGET( w ) );
el->widgets = g_list_append( el->widgets, w );
gtk_widget_show( w );
}
break;
case CDLG_INPUT:
case CDLG_INPUT_LARGE:
case CDLG_PASSWORD:
if ( !el->widgets->next && box )
{
el->option = -1;
// add input
if ( args )
{
// default text
get_text_value( el, (char*)args->data, FALSE, TRUE );
el->cmd_args = args->next;
}
if ( el->type == CDLG_INPUT_LARGE )
{
// multi-input
GtkWidget* scroll = gtk_scrolled_window_new( NULL, NULL );
w = GTK_WIDGET( multi_input_new( GTK_SCROLLED_WINDOW( scroll ),
el->val, FALSE ) );
set_font( w, font );
if ( selstart >= 0 )
multi_input_select_region( w, selstart, selend );
gtk_box_pack_start( GTK_BOX( box ), GTK_WIDGET( scroll ),
!compact, TRUE, pad );
}
else
{
// entry
w = gtk_entry_new();
gtk_entry_set_visibility( GTK_ENTRY( w ), el->type != CDLG_PASSWORD );
set_font( w, font );
if ( el->val )
{
gtk_entry_set_text( GTK_ENTRY( w ), el->val );
if ( selstart >= 0 && el->type != CDLG_PASSWORD )
{
gtk_editable_select_region( GTK_EDITABLE( w ), selstart, selend );
el->option = selstart;
el->option2 = selend;
}
else
gtk_editable_select_region( GTK_EDITABLE( w ), 0, -1 );
}
gtk_box_pack_start( GTK_BOX( box ), GTK_WIDGET( w ), !compact, TRUE, pad );
}
el->widgets = g_list_append( el->widgets, w );
g_signal_connect( G_OBJECT( w ), "key-press-event",
G_CALLBACK( on_input_key_press), el );
if ( radio ) *radio = NULL;
}
else if ( el->widgets->next && args && ((char*)args->data)[0] == '@' )
{
// update from file
str = g_strdup( el->val );
get_text_value( el, (char*)args->data, FALSE, TRUE );
if ( g_strcmp0( str, el->val ) )
{
// value has changed from initial default, so update contents
if ( el->type == CDLG_INPUT_LARGE )
{
gtk_text_buffer_set_text( gtk_text_view_get_buffer(
GTK_TEXT_VIEW( el->widgets->next->data ) ),
el->val ? el->val : "", -1 );
multi_input_select_region( el->widgets->next->data, 0, -1 );
}
else
{
gtk_entry_set_text( GTK_ENTRY( el->widgets->next->data ), el->val );
gtk_editable_select_region(
GTK_EDITABLE( el->widgets->next->data ),
0, -1 );
}
}
g_free( str );
}
break;
case CDLG_VIEWER:
case CDLG_EDITOR:
selstart = 0;
// add text box
if ( !el->widgets->next && box )
{
GtkWidget* scroll = gtk_scrolled_window_new( NULL, NULL );
gtk_scrolled_window_set_policy ( GTK_SCROLLED_WINDOW ( scroll ),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC );
w = gtk_text_view_new();
gtk_text_view_set_wrap_mode( GTK_TEXT_VIEW( w ), GTK_WRAP_WORD_CHAR );
gtk_text_view_set_editable( GTK_TEXT_VIEW( w ), el->type == CDLG_EDITOR );
set_font( w, font );
gtk_container_add ( GTK_CONTAINER ( scroll ), w );
el->widgets = g_list_append( el->widgets, w );
el->widgets = g_list_append( el->widgets, scroll );
gtk_box_pack_start( GTK_BOX( box ), GTK_WIDGET( scroll ), !compact, TRUE, pad );
// place mark at end
buf = gtk_text_view_get_buffer( GTK_TEXT_VIEW( w ) );
gtk_text_buffer_get_end_iter( buf, &iter);
gtk_text_buffer_create_mark( buf, "end", &iter, FALSE );
el->option = viewer_scroll ? 1 : 0;
selstart = 1; // indicates new
if ( radio ) *radio = NULL;
}
if ( args && ((char*)args->data)[0] != '\0' && el->type == CDLG_VIEWER
&& el->widgets->next )
{
// viewer
buf = gtk_text_view_get_buffer(
GTK_TEXT_VIEW( el->widgets->next->data ) );
if ( selstart && stat64( (char*)args->data, &statbuf ) != -1
&& S_ISFIFO( statbuf.st_mode ) )
{
// watch pipe
GIOChannel* channel = g_io_channel_new_file( (char*)args->data,
"r+", NULL );
if ( channel )
{
gint fd = g_io_channel_unix_get_fd( channel );
//int fd = fcntl( g_io_channel_unix_get_fd( channel ), F_GETFL );
if ( fd > 0 )
{
fcntl( fd, F_SETFL,O_NONBLOCK );
g_io_add_watch_full( channel, G_PRIORITY_LOW,
G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
(GIOFunc)cb_pipe_watch, el, NULL );
g_free( el->val );
el->val = g_strdup( (char*)args->data );
}
}
}
else if ( g_file_test( (char*)args->data, G_FILE_TEST_IS_REGULAR ) )
{
// update viewer from file
fill_buffer_from_file( el, buf, (char*)args->data, TRUE );
g_free( el->val );
el->val = g_strdup( (char*)args->data );
}
else
{
dlg_warn( _("file '%s' is not a regular file or a pipe"),
(char*)args->data, NULL );
}
// scroll
if ( el->option )
{
//scroll to end if scrollbar is mostly down or new
GtkAdjustment* adj = gtk_scrolled_window_get_vadjustment(
GTK_SCROLLED_WINDOW( el->widgets->next->next->data ) );
if ( selstart || gtk_adjustment_get_upper( adj ) - gtk_adjustment_get_value( adj ) < gtk_adjustment_get_page_size( adj ) + 40 )
gtk_text_view_scroll_to_mark( GTK_TEXT_VIEW( el->widgets->next->data ),
gtk_text_buffer_get_mark( buf, "end" ),
0.0, FALSE, 0, 0 );
}
}
else if ( args && ((char*)args->data)[0] != '\0' && selstart &&
el->type == CDLG_EDITOR && el->widgets->next )
{
// new editor
buf = gtk_text_view_get_buffer(
GTK_TEXT_VIEW( el->widgets->next->data ) );
fill_buffer_from_file( el, buf, (char*)args->data, FALSE );
g_free( el->val );
el->val = g_strdup( (char*)args->data );
}
break;
case CDLG_COMMAND:
if ( !el->option && args )
{
if ( ((char*)args->data)[0] != '\0'
&& stat64( (char*)args->data, &statbuf ) != -1
&& S_ISFIFO( statbuf.st_mode ) )
{
// watch pipe
GIOChannel* channel = g_io_channel_new_file( (char*)args->data,
"r+", NULL );
if ( channel )
{
gint fd = g_io_channel_unix_get_fd( channel );
//int fd = fcntl( g_io_channel_unix_get_fd( channel ), F_GETFL );
if ( fd > 0 )
{
fcntl( fd, F_SETFL,O_NONBLOCK );
g_io_add_watch_full( channel, G_PRIORITY_LOW,
G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
(GIOFunc)cb_pipe_watch, el, NULL );
g_free( el->val );
el->val = g_strdup( (char*)args->data );
}
}
}
else if ( ((char*)args->data)[0] != '\0' )
{
if ( ((char*)args->data)[0] == '@' )
str = g_strdup( (char*)args->data );
else
str = g_strdup_printf( "@%s", (char*)args->data );
get_text_value( el, str, FALSE, TRUE );
g_free( str );
}
el->option = 1;
// init COMMAND
el->cmd_args = args->next;
}
else if ( el->option && args )
{
if ( ((char*)args->data)[0] == '@' )
str = g_strdup( (char*)args->data );
else
str = g_strdup_printf( "@%s", (char*)args->data );
get_text_value( el, str, FALSE, TRUE );
g_free( str );
run_command_line( el, el->val );
}
break;
case CDLG_CHECKBOX:
case CDLG_RADIO:
// add item
if ( !el->widgets->next && box && radio )
{
str = unescape( el->args ? (char*)el->args->data : "" );
if ( el->type == CDLG_CHECKBOX )
{
w = gtk_check_button_new_with_mnemonic( str );
*radio = NULL;
}
else
{
/*
GSList* l;
printf("LIST-BEFORE %#x\n", *radio );
for ( l = *radio; l; l = l->next )
printf( " button=%#x\n", l->data );
*/
w = gtk_radio_button_new_with_mnemonic( *radio, str );
*radio = gtk_radio_button_get_group( GTK_RADIO_BUTTON( w ) );
//printf("BUTTON=%#x\n", w );
/*
printf("LIST-AFTER %#x\n", *radio );
for ( l = *radio; l; l = l->next )
printf( " button=%#x\n", l->data );
*/
}
g_free( str );
gtk_button_set_focus_on_click( GTK_BUTTON( w ), FALSE );
// set font of label
l = gtk_container_get_children( GTK_CONTAINER( w ) );
if ( l )
set_font( GTK_WIDGET( l->data ), font );
g_list_free( l );
el->widgets = g_list_append( el->widgets, w );
gtk_box_pack_start( GTK_BOX( box ), GTK_WIDGET( w ), expand, TRUE, pad );
// default value
if ( args && args->next )
{
get_text_value( el, (char*)args->next->data, FALSE, TRUE );
if ( !g_strcmp0( el->val, "1" ) ||
!g_strcmp0( el->val, "true" ) )
gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( w ), TRUE );
el->cmd_args = el->args->next->next;
}
g_signal_connect( G_OBJECT( w ), "toggled",
G_CALLBACK( on_option_toggled ), el );
}
else if ( el->widgets->next && args && args->next )
{
get_text_value( el, (char*)args->next->data, FALSE, TRUE );
if ( !g_strcmp0( el->val, "1") || !g_strcmp0( el->val, "true" ) )
gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON(
el->widgets->next->data ), TRUE );
else if ( !g_strcmp0( el->val, "0") || !g_strcmp0( el->val, "false" ) )
gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON(
el->widgets->next->data ), FALSE );
}
break;
case CDLG_DROP:
case CDLG_COMBO:
// add list widget
if ( !el->widgets->next && box )
{
if ( el->type == CDLG_DROP )
{
w = gtk_combo_box_text_new();
g_signal_connect( G_OBJECT( w ), "changed",
G_CALLBACK( on_combo_changed ), el );
}
else
{
w = gtk_combo_box_text_new_with_entry();
g_signal_connect( G_OBJECT( gtk_bin_get_child( GTK_BIN( w ) ) ),
"key-press-event",
G_CALLBACK( on_input_key_press ), el );
}
gtk_combo_box_set_focus_on_click( GTK_COMBO_BOX( w ), FALSE );
set_font( w, font );
gtk_box_pack_start( GTK_BOX( box ), w, expand, TRUE, pad );
el->widgets = g_list_append( el->widgets, w );
if ( radio ) *radio = NULL;
}
if ( el->widgets->next && args )
{
if ( ((char*)args->data)[0] == '@' )
{
// list from file
if ( args->next )
{
// get default value and command
if ( !strcmp( (char*)args->next->data, "--" ) )
{
// forgive extra --
if ( args->next->next )
{
// default value
el->def_val = (char*)args->next->next->data;
el->cmd_args = args->next->next->next;
}
}
else
{
// default value
el->def_val = (char*)args->next->data;
el->cmd_args = args->next->next;
}
if ( el->def_val )
get_text_value( el, el->def_val, FALSE, FALSE );
}
// read file into temp args
str = (char*)args->data + 1;
args = args_from_file( (char*)args->data + 1 );
// fill combo from args
fill_combo_box( el, args );
if ( !el->monitor && args )
{
// start monitoring file
el->callback = (VFSFileMonitorCallback)cb_file_value_change;
el->monitor = vfs_file_monitor_add( str, FALSE,
el->callback, el );
}
// free temp args
g_list_foreach( args, (GFunc)g_free, NULL );
g_list_free( args );
}
else
{
// get default value
l = args;
while ( l )
{
if ( !strcmp( (char*)l->data, "--" ) )
{
if ( l->next )
{
// default value
el->def_val = (char*)l->next->data;
get_text_value( el, el->def_val, FALSE, FALSE );
el->cmd_args = l->next->next;
}
break;
}
l = l->next;
}
// fill combo from args
fill_combo_box( el, args );
}
}
break;
case CDLG_LIST:
case CDLG_MLIST:
if ( !el->widgets->next && box )
{
w = gtk_tree_view_new();
gtk_tree_view_set_rules_hint ( GTK_TREE_VIEW( w ), TRUE );
gtk_tree_view_set_enable_search( GTK_TREE_VIEW( w ), TRUE );
set_font( w, font );
GtkTreeSelection* tree_sel = gtk_tree_view_get_selection(
GTK_TREE_VIEW( w ) );
gtk_tree_selection_set_mode( tree_sel,
el->type == CDLG_MLIST ?
GTK_SELECTION_MULTIPLE : GTK_SELECTION_SINGLE );
GtkWidget* scroll = gtk_scrolled_window_new( NULL, NULL );
gtk_scrolled_window_set_policy ( GTK_SCROLLED_WINDOW ( scroll ),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC );
gtk_container_add ( GTK_CONTAINER ( scroll ), w );
gtk_box_pack_start( GTK_BOX( box ), GTK_WIDGET( scroll ), !compact, TRUE, pad );
el->widgets = g_list_append( el->widgets, w );
el->widgets = g_list_append( el->widgets, scroll );
g_signal_connect ( G_OBJECT( w ), "row-activated",
G_CALLBACK ( on_list_row_activated ),
el ); // renderer cannot be editable
if ( radio ) *radio = NULL;
}
if ( el->widgets->next && args )
{
if ( ((char*)args->data)[0] == '@' )
{
// list from file
if ( args->next )
{
// set command args
if ( !strcmp( (char*)args->next->data, "--" ) )
// forgive extra --
el->cmd_args = args->next->next;
else
el->cmd_args = args->next;
}
// read file into temp args
str = (char*)args->data + 1;
args = args_from_file( (char*)args->data + 1 );
// fill list from args
fill_tree_view( el, args );
if ( !el->monitor && args )
{
// start monitoring file
el->callback = (VFSFileMonitorCallback)cb_file_value_change;
el->monitor = vfs_file_monitor_add( str, FALSE,
el->callback, el );
}
// free temp args
g_list_foreach( args, (GFunc)g_free, NULL );
g_list_free( args );
}
else
// fill list from args
fill_tree_view( el, args );
}
break;
/*
case CDLG_STATUS:
if ( !el->widgets->next && box )
{
w = gtk_statusbar_new();
//gtk_box_pack_start( GTK_BOX( GTK_DIALOG( dlg )->action_area ),
// GTK_WIDGET( w ), TRUE, TRUE, pad );
gtk_box_pack_start( GTK_BOX( box ), w, FALSE, FALSE, pad );
el->widgets = g_list_append( el->widgets, w );
GList* children = gtk_container_get_children(
GTK_CONTAINER( gtk_statusbar_get_message_area(
GTK_STATUSBAR( w ) ) ) );
w = children->data; // status bar label
el->widgets = g_list_append( el->widgets, w );
g_list_free( children );
gtk_label_set_selectable( GTK_LABEL( w ), TRUE ); // required for button event
gtk_widget_set_can_focus( w, FALSE );
g_signal_connect( G_OBJECT( w ), "button-press-event",
G_CALLBACK( on_status_button_press ), el );
//g_signal_connect( G_OBJECT( w ), "populate-popup",
// G_CALLBACK( on_status_bar_popup ), el );
}
if ( el->widgets->next && args )
{
get_text_value( el, (char*)args->data, FALSE, TRUE );
gtk_statusbar_push( GTK_STATUSBAR( el->widgets->next->data ), 0, el->val );
}
break;
*/
case CDLG_PROGRESS:
if ( !el->widgets->next && box )
{
w = gtk_progress_bar_new();
gtk_progress_bar_set_pulse_step( GTK_PROGRESS_BAR( w ), 0.08 );
#if GTK_CHECK_VERSION (3, 0, 0)
gtk_progress_bar_set_show_text( GTK_PROGRESS_BAR( w ), TRUE );
#endif
set_font( w, font );
gtk_box_pack_start( GTK_BOX( box ), w, expand, TRUE, pad );
el->widgets = g_list_append( el->widgets, w );
if ( !args || ( args && ( !strcmp( (char*)args->data, "pulse" ) ||
!strcmp( (char*)args->data, "auto-pulse" ) ) ) )
{
if ( !strcmp( (char*)args->data, "pulse" ) )
args = NULL; // treat pulse as auto-pulse
gtk_progress_bar_set_text(
GTK_PROGRESS_BAR( el->widgets->next->data ),
" " );
el->timeout = g_timeout_add( 200, (GSourceFunc)on_progress_timer, el );
}
if ( radio ) *radio = NULL;
}
if ( el->widgets->next && args )
{
get_text_value( el, (char*)args->data, FALSE, TRUE );
if ( !g_strcmp0( el->val, "pulse" ) )
{
if ( el->timeout )
{
g_source_remove( el->timeout );
el->timeout = 0;
}
gtk_progress_bar_pulse( GTK_PROGRESS_BAR( el->widgets->next->data ) );
}
else if ( !g_strcmp0( el->val, "auto-pulse" ) )
{
if ( !el->timeout )
el->timeout = g_timeout_add( 200, (GSourceFunc)on_progress_timer,
el );
}
else
{
i = el->val ? atoi( el->val ) : 0;
if ( i < 0 ) i = 0;
if ( i > 100 ) i = 100;
if ( i != 0 || ( el->val && el->val[0] == '0' ) )
{
if ( el->timeout )
{
g_source_remove( el->timeout );
el->timeout = 0;
}
gtk_progress_bar_set_fraction(
GTK_PROGRESS_BAR( el->widgets->next->data ),
(gdouble)i / 100 );
}
str = el->val;
while ( str && str[0] )
{
if ( !g_ascii_isdigit( str[0] ) )
{
gtk_progress_bar_set_text(
GTK_PROGRESS_BAR( el->widgets->next->data ),
el->val );
break;
}
str++;
}
if ( !( str && str[0] ) )
{
if ( i != 0 || ( el->val && el->val[0] == '0' ) )
str = g_strdup_printf( "%d %%", i );
else
str = g_strdup( " " );
gtk_progress_bar_set_text(
GTK_PROGRESS_BAR( el->widgets->next->data ),
str );
g_free( str );
}
}
}
break;
case CDLG_HSEP:
case CDLG_VSEP:
if ( !el->widgets->next && box )
{
if ( el->type == CDLG_HSEP )
w = gtk_hseparator_new();
else
w = gtk_vseparator_new();
gtk_box_pack_start( GTK_BOX( box ), w, expand, TRUE, pad );
el->widgets = g_list_append( el->widgets, w );
if ( radio ) *radio = NULL;
}
break;
case CDLG_HBOX:
case CDLG_VBOX:
if ( !el->widgets->next && box )
{
if ( args )
get_text_value( el, (char*)args->data, FALSE, FALSE );
if ( el->val )
i = atoi( el->val );
else
i = 0;
if ( i < 0 ) i = 0;
if ( i > 400 ) i = 400;
if ( el->type == CDLG_HBOX )
w = gtk_hbox_new( FALSE, i );
else
w = gtk_vbox_new( FALSE, i );
gtk_box_pack_start( GTK_BOX( box ), w, !compact, TRUE, pad );
el->widgets = g_list_append( el->widgets, w );
if ( radio ) *radio = NULL;
}
break;
case CDLG_WINDOW_SIZE:
if ( el->option && args && ((char*)args->data)[0] == '@' )
{
int width = -1, height = -1;
get_text_value( el, (char*)args->data, FALSE, TRUE );
get_width_height_pad( el->val, &width, &height, NULL );
if ( width > 0 && height > 0 )
{
gtk_window_resize( GTK_WINDOW( el->widgets->data ), width, height );
gtk_window_set_position( GTK_WINDOW( el->widgets->data ),
GTK_WIN_POS_CENTER );
}
else
dlg_warn( _("Dynamic resize requires width and height > 0"),
NULL, NULL );
}
break;
case CDLG_TIMEOUT:
if ( !el->widgets->next && box )
{
if ( args )
get_text_value( el, (char*)args->data, FALSE, FALSE );
el->option = el->val ? atoi( el->val ) : 20;
if ( el->option <= 0 )
el->option = 20;
}
break;
case CDLG_CHOOSER:
if ( !el->widgets->next && box )
{
if ( chooser_dir )
i = chooser_save ? GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER :
GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER;
else if ( chooser_save )
i = GTK_FILE_CHOOSER_ACTION_SAVE;
else
i = GTK_FILE_CHOOSER_ACTION_OPEN;
w = gtk_file_chooser_widget_new( i );
if ( chooser_multi )
gtk_file_chooser_set_select_multiple( GTK_FILE_CHOOSER( w ),
TRUE );
gtk_box_pack_start( GTK_BOX( box ), w, !compact, TRUE, pad );
el->widgets = g_list_append( el->widgets, w );
g_signal_connect( G_OBJECT( w ), "file-activated",
G_CALLBACK( on_chooser_activated ), el );
if ( radio ) *radio = NULL;
if ( args && args->next )
el->cmd_args = args->next;
// filters
if ( chooser_filters )
{
for ( l = chooser_filters; l; l = l->next )
{
GtkFileFilter* filter = gtk_file_filter_new();
str = (char*)l->data;
while ( str )
{
if ( sep = strchr( str, ':' ) )
sep[0] = '\0';
if ( strchr( str, '/' ) )
gtk_file_filter_add_mime_type( filter, str );
else
gtk_file_filter_add_pattern( filter, str );
if ( sep )
{
sep[0] = ':';
str = sep + 1;
}
else
str = NULL;
}
gtk_file_filter_set_name( filter, (char*)l->data );
gtk_file_chooser_add_filter( GTK_FILE_CHOOSER( w ), filter );
if ( l == chooser_filters )
// note: set_filter only works if gtk_file_chooser_set_filename
// is NOT used
gtk_file_chooser_set_filter( GTK_FILE_CHOOSER( w ), filter );
}
g_list_free( chooser_filters );
}
}
// change dir/file
if ( args && el->widgets->next )
{
get_text_value( el, (char*)args->data, FALSE, TRUE );
if ( el->val )
{
if ( chooser_save && ( chooser_dir ||
!g_file_test( el->val, G_FILE_TEST_IS_DIR ) ) )
{
if ( strchr( el->val, '/' ) )
{
str = g_path_get_dirname( el->val );
gtk_file_chooser_set_current_folder(
GTK_FILE_CHOOSER( el->widgets->next->data ),
str );
g_free( str );
str = g_path_get_basename( el->val );
gtk_file_chooser_set_current_name(
GTK_FILE_CHOOSER( el->widgets->next->data ),
str );
g_free( str );
}
else
gtk_file_chooser_set_current_name(
GTK_FILE_CHOOSER( el->widgets->next->data ),
el->val );
}
else if ( g_file_test( el->val, G_FILE_TEST_IS_DIR ) )
gtk_file_chooser_set_current_folder(
GTK_FILE_CHOOSER( el->widgets->next->data ),
el->val );
else
gtk_file_chooser_set_filename(
GTK_FILE_CHOOSER( el->widgets->next->data ),
el->val );
}
}
break;
case CDLG_KEYPRESS:
if ( !el->cmd_args && args && args->next && args->next->next )
{
int keycode = strtol( args->data, NULL, 0 );
int modifier = strtol( args->next->data, NULL, 0 );
if ( keycode != 0 )
g_signal_connect( G_OBJECT( el->widgets->data ), "key-press-event",
G_CALLBACK( on_dlg_key_press), el );
el->cmd_args = args->next->next;
if ( radio ) *radio = NULL;
}
break;
}
}
static void build_dialog( GList* elements )
{
GList* l;
GtkWidget* dlg;
CustomElement* el;
CustomElement* focus_el = NULL;
char* str;
char* sep;
GSList* radio = NULL;
GtkWidget* box;
int pad = DEFAULT_PAD;
int width = DEFAULT_WIDTH;
int height = DEFAULT_HEIGHT;
gboolean timeout_added = FALSE;
gboolean is_sized = FALSE;
gboolean is_large = FALSE;
// create dialog
dlg = gtk_dialog_new();
gtk_window_set_default_size( GTK_WINDOW( dlg ), width, height );
gtk_window_set_title( GTK_WINDOW( dlg ), DEFAULT_TITLE );
gtk_window_set_position( GTK_WINDOW( dlg ), GTK_WIN_POS_CENTER );
GdkPixbuf* pixbuf = gtk_icon_theme_load_icon( gtk_icon_theme_get_default(),
DEFAULT_ICON, 16, GTK_ICON_LOOKUP_USE_BUILTIN, NULL );
if ( pixbuf )
gtk_window_set_icon( GTK_WINDOW( dlg ), pixbuf );
g_object_set_data( G_OBJECT( dlg ), "elements", elements );
g_signal_connect( G_OBJECT( dlg ), "destroy", G_CALLBACK( on_dlg_close ), NULL );
// pack some boxes to create horizonal padding at edges of window
GtkWidget* hbox = gtk_hbox_new( FALSE, 0 );
gtk_box_pack_start( GTK_BOX( gtk_dialog_get_content_area( GTK_DIALOG( dlg ) ) ), hbox, TRUE, TRUE, 0 );
box = gtk_vbox_new( FALSE, 0 );
gtk_box_pack_start( GTK_BOX( hbox ), box, TRUE, TRUE, 8 ); // <- hpad
GList* boxes = g_list_append( NULL, box );
// pack timeout button first
GtkWidget* timeout_toggle = gtk_toggle_button_new_with_label( _("Pause") );
gtk_box_pack_start( GTK_BOX( gtk_dialog_get_action_area( GTK_DIALOG( dlg ) ) ),
timeout_toggle, FALSE, FALSE, pad );
gtk_button_set_image( GTK_BUTTON( timeout_toggle ),
xset_get_image( "GTK_STOCK_MEDIA_PAUSE",
GTK_ICON_SIZE_BUTTON ) );
gtk_button_set_focus_on_click( GTK_BUTTON( timeout_toggle ), FALSE );
// add elements
for ( l = elements; l; l = l->next )
{
el = (CustomElement*)l->data;
el->widgets = g_list_append( NULL, dlg );
update_element( el, box, &radio, pad );
if ( !focus_el && ( el->type == CDLG_INPUT
|| el->type == CDLG_INPUT_LARGE
|| el->type == CDLG_EDITOR
|| el->type == CDLG_COMBO
|| el->type == CDLG_PASSWORD ) )
focus_el = el;
else if ( ( el->type == CDLG_HBOX || el->type == CDLG_VBOX )
&& el->widgets->next )
{
box = el->widgets->next->data;
boxes = g_list_append( boxes, box );
}
else if ( el->type == CDLG_CLOSE_BOX && g_list_length( boxes ) > 1 )
{
box = g_list_last( boxes )->prev->data;
boxes = g_list_delete_link( boxes, g_list_last( boxes ) );
}
else if ( el->type == CDLG_WINDOW_SIZE && el->args )
{
get_text_value( el, (char*)el->args->data, FALSE, TRUE );
get_width_height_pad( el->val, &width, &height, &pad );
if ( el->args->next && atoi( (char*)el->args->next->data ) > 0 )
pad = atoi( (char*)el->args->next->data );
gtk_window_set_default_size( GTK_WINDOW( dlg ), width, height );
el->option = 1; // activates auto resize from @FILE
is_sized = TRUE;
}
else if ( el->type == CDLG_WINDOW_CLOSE && el->args )
{
el->cmd_args = el->args;
g_signal_connect( G_OBJECT( dlg ), "delete-event",
G_CALLBACK( on_window_delete ), el );
}
else if ( el->type == CDLG_TIMEOUT && el->option && !el->widgets->next
&& !timeout_added )
{
el->widgets = g_list_append( el->widgets, timeout_toggle );
el->timeout = g_timeout_add( 1000, (GSourceFunc)on_timeout_timer, el );
g_signal_connect( G_OBJECT( timeout_toggle ), "toggled",
G_CALLBACK( on_option_toggled ), el );
g_free( el->val );
el->val = g_strdup_printf( "%s %d", _("Pause"), el->option );
gtk_button_set_label( GTK_BUTTON( el->widgets->next->data ), el->val );
timeout_added = TRUE;
}
if ( !is_large && el->widgets->next && (
el->type == CDLG_CHOOSER ||
el->type == CDLG_MLIST ||
el->type == CDLG_EDITOR ||
el->type == CDLG_VIEWER ||
el->type == CDLG_LIST ) )
is_large = TRUE;
}
g_list_free( boxes );
// resize window
if ( is_large && !is_sized )
gtk_window_set_default_size( GTK_WINDOW( dlg ), DEFAULT_LARGE_WIDTH,
DEFAULT_LARGE_HEIGHT );
// show dialog
gtk_widget_show_all( dlg );
if ( !timeout_added )
gtk_widget_hide( timeout_toggle );
// focus input
if ( focus_el && focus_el->widgets->next )
{
gtk_widget_grab_focus( focus_el->widgets->next->data );
if ( focus_el->type == CDLG_INPUT && focus_el->option >= 0 )
{
// grab_focus causes all text to be selected, so re-select
gtk_editable_select_region(
GTK_EDITABLE( focus_el->widgets->next->data ),
focus_el->option, focus_el->option2 );
}
}
signal_dialog = dlg;
// run init COMMMAND(s)
for ( l = elements; l; l = l->next )
{
if ( ((CustomElement*)l->data)->type == CDLG_COMMAND
&& ((CustomElement*)l->data)->cmd_args )
run_command( (CustomElement*)l->data,
((CustomElement*)l->data)->cmd_args, NULL );
}
}
static void show_help()
{
int i, j;
FILE* f = stdout;
fprintf( f, _("SpaceFM Dialog creates a custom GTK dialog based on the GUI elements you\nspecify on the command line, features run-time internal/external commands which\ncan modify elements, and outputs evaluatable/parsable results.\n") );
fprintf( f, _("Usage:\n") );
fprintf( f, _(" spacefm --dialog|-g {ELEMENT [OPTIONS] [ARGUMENTS...]} ...\n") );
fprintf( f, _("Example:\n") );
fprintf( f, _(" spacefm -g --label \"A message\" --button ok\n") );
fprintf( f, _("\nELEMENT: OPTIONS & ARGUMENTS:\n") );
fprintf( f, _( "-------- --------------------\n") );
for ( i = 0; i < G_N_ELEMENTS( cdlg_option ) / 3; i++ )
{
fprintf( f, "--%s", cdlg_option[i*3] );
for ( j = 1; j <= 13 - strlen( cdlg_option[i*3] ); j++ )
fprintf( f, " " );
fprintf( f, "%s\n", cdlg_option[i*3 + 1] );
fprintf( f, " %s\n", _( cdlg_option[i*3 + 2] ) );
}
fprintf( f, _("\nThe following arguments may be used as shown above:\n") );
fprintf( f, _(" STOCK %s\n"), "ok|cancel|close|open|yes|no|apply|delete|edit|help|save|stop" );
fprintf( f, _(" ICON An icon name, eg: gtk-open\n") );
fprintf( f, _(" @FILE A text file from which to read a value. In some cases this file\n is monitored, so writing a new value to the file will update the\n element. In other cases, the file specifies an initial value.\n") );
fprintf( f, _(" SAVEFILE A viewer's or editor's contents are saved to this file.\n") );
fprintf( f, _(" COMMAND An internal command or executable followed by arguments. Separate\n multiple commands with a -- argument.\n The following substitutions may be used in COMMANDs:\n %%n Name of the current element\n %%v Value of the current element\n %%NAME Value of element named NAME (eg: %%input1)\n %%(command) stdout from a bash command line\n %%%% %%\n") );
fprintf( f, _(" LABEL The following escape sequences in LABEL are unescaped:\n \\n newline\n \\t tab\n \\\" \"\n \\\\ \\\n In --label elements only, if the first character in LABEL is a\n tilde (~), pango markup may be used. For example:\n --label '~This is plain. <b>This is bold.</b>'\n") );
fprintf( f, _("\nIn addition to the OPTIONS listed above, --compact or --expand options may be\nadded to any element. Also, a --font option may be used with most element\ntypes to change the element's font and font size. For example:\n --input --font \"Times New Roman 16\" \"Default Text\"\n") );
fprintf( f, _("\nINTERNAL COMMANDS:\n") );
for ( i = 0; i < G_N_ELEMENTS( cdlg_cmd ) / 3; i++ )
{
fprintf( f, " %s", cdlg_cmd[i*3] );
for ( j = 1; j <= 11 - strlen( cdlg_cmd[i*3] ); j++ )
fprintf( f, " " );
fprintf( f, "%s\n", cdlg_cmd[i*3 + 1] );
fprintf( f, " %s\n", _( cdlg_cmd[i*3 + 2] ) );
}
fprintf( f, _("\nEXAMPLE WITH COMMANDS:\n") );
fprintf( f, _(" spacefm -g --label \"Enter some text and press Enter:\" \\\n --input \"\" set label2 %%v -- echo '# %%n = %%v' \\\n --label \\\n --button ok\n") );
fprintf( f, _("\nEXAMPLE SCRIPT:\n") );
fprintf( f, _(" #!/bin/bash\n # This script shows a Yes/No dialog\n # Use QUOTED eval to read variables output by SpaceFM Dialog:\n eval \"`spacefm -g --label \"Are you sure?\" --button yes --button no`\"\n if [[ \"$dialog_pressed\" == \"button1\" ]]; then\n echo \"User pressed Yes - take some action\"\n else\n echo \"User did NOT press Yes - abort\"\n fi\n") );
fprintf( f, _("\nFor full documentation and examples see the SpaceFM User's Manual:\n") );
fprintf( f, " %s\n\n", DEFAULT_MANUAL );
}
void signal_handler()
{
if ( signal_dialog )
{
write_source( signal_dialog, NULL, stdout );
destroy_dlg( signal_dialog );
}
}
int custom_dialog_init( int argc, char *argv[] )
{
int ac, i, j;
GList* elements = NULL;
CustomElement* el = NULL;
GList* l;
char* num;
char* str;
int type_count[ G_N_ELEMENTS( cdlg_option ) / 3 ] = { 0 };
for ( ac = 2; ac < argc; ac++ )
{
if ( !g_utf8_validate( argv[ac], -1, NULL ) )
{
fprintf( stderr, _("spacefm: argument is not valid UTF-8\n") );
free_elements( elements );
return 1;
}
else if ( ac == 2 && ( !strcmp( argv[ac], "--help" )
|| !strcmp( argv[ac], "help" ) ) )
{
show_help();
return -1;
}
else if ( g_str_has_prefix( argv[ac], "--" ) )
{
j = 0;
for ( i = 0; i < G_N_ELEMENTS( cdlg_option ); i += 3 )
{
if ( !strcmp( argv[ac] + 2, cdlg_option[i] ) )
{
el = g_slice_new( CustomElement );
el->type = j;
type_count[j]++;
num = g_strdup_printf( "%d", type_count[j] );
str = replace_string( cdlg_option[i], "-", "", FALSE );
el->name = g_strdup_printf( "%s%s", str,
num ? num : "" );
g_free( num );
g_free( str );
el->args = NULL;
el->def_val = NULL;
el->cmd_args = NULL;
el->val = NULL;
el->widgets = NULL;
el->monitor = NULL;
el->callback = NULL;
el->timeout = 0;
el->update_timeout = 0;
el->watch_file = NULL;
el->option = 0;
elements = g_list_append( elements, el );
break;
}
j++;
}
if ( i < G_N_ELEMENTS( cdlg_option ) )
continue;
}
if ( !el )
{
fprintf( stderr, "spacefm: %s '%s'\n", _("invalid dialog option"), argv[ac] );
return 1;
}
el->args = g_list_append( el->args, argv[ac] );
}
build_dialog( elements );
signal( SIGHUP, signal_handler );
signal( SIGINT, signal_handler );
signal( SIGTERM, signal_handler );
signal( SIGQUIT, signal_handler );
return 0;
}
|
144 | ./spacefm/src/settings.c | /*
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#ifndef _GNU_SOURCE
#define _GNU_SOURCE // euidaccess
#endif
#include "settings.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include "glib-utils.h" /* for g_mkdir_with_parents() */
#include <gtk/gtk.h>
#include "desktop.h"
#include <gdk/gdkkeysyms.h>
#include "ptk-utils.h"
#include <errno.h>
#include <fcntl.h>
#include "main-window.h"
#include "vfs-app-desktop.h"
#include "exo-tree-view.h"
#include <glib/gi18n.h>
#include "gtk2-compat.h"
/* Dirty hack: check whether we are under LXDE or not */
#define is_under_LXDE() (g_getenv( "_LXSESSION_PID" ) != NULL)
AppSettings app_settings = {0};
/* const gboolean singleInstance_default = TRUE; */
const gboolean show_hidden_files_default = FALSE;
const gboolean show_side_pane_default = TRUE;
const int side_pane_mode_default = PTK_FB_SIDE_PANE_BOOKMARKS;
const gboolean show_thumbnail_default = FALSE;
const int max_thumb_size_default = 4 << 20;
const int big_icon_size_default = 48;
const int small_icon_size_default = 22;
const int tool_icon_size_default = 0;
const gboolean single_click_default = FALSE;
const gboolean show_location_bar_default = TRUE;
/* FIXME: temporarily disable trash since it's not finished */
const gboolean use_trash_can_default = FALSE;
//const int open_bookmark_method_default = 1;
const int view_mode_default = PTK_FB_ICON_VIEW;
const int sort_order_default = PTK_FB_SORT_BY_NAME;
const int sort_type_default = GTK_SORT_ASCENDING;
//gboolean show_desktop_default = FALSE;
const gboolean show_wallpaper_default = FALSE;
const WallpaperMode wallpaper_mode_default=WPM_STRETCH;
const GdkColor desktop_bg1_default={0};
const GdkColor desktop_bg2_default={0};
const GdkColor desktop_text_default={0, 65535, 65535, 65535};
const GdkColor desktop_shadow_default={0};
const int desktop_sort_by_default = DW_SORT_BY_MTIME;
const int desktop_sort_type_default = GTK_SORT_ASCENDING;
const gboolean show_wm_menu_default = FALSE;
/* Default values of interface settings */
const gboolean always_show_tabs_default = TRUE;
const gboolean hide_close_tab_buttons_default = FALSE;
const gboolean hide_side_pane_buttons_default = FALSE;
//const gboolean hide_folder_content_border_default = FALSE;
// MOD settings
void xset_write( FILE* file );
void xset_parse( char* line );
void read_root_settings();
void xset_defaults();
const gboolean use_si_prefix_default = FALSE;
GList* xsets = NULL;
GList* keysets = NULL;
XSet* set_clipboard = NULL;
gboolean clipboard_is_cut;
XSet* set_last;
char* settings_config_dir = NULL;
char* settings_tmp_dir = NULL;
char* settings_shared_tmp_dir = NULL;
char* settings_user_tmp_dir = NULL;
XSetContext* xset_context = NULL;
typedef void ( *SettingsParseFunc ) ( char* line );
static void color_from_str( GdkColor* ret, const char* value );
static void save_color( FILE* file, const char* name,
GdkColor* color );
void xset_free_all();
char* xset_font_dialog( GtkWidget* parent, char* title, char* preview, char* deffont );
void xset_custom_delete( XSet* set, gboolean delete_next );
void xset_default_keys();
int xset_context_test( char* rules, gboolean def_disable );
char* clean_label( const char* menu_label, gboolean kill_special, gboolean convert_amp );
char* xset_color_dialog( GtkWidget* parent, char* title, char* defcolor );
GtkWidget* xset_design_additem( GtkWidget* menu, char* label, gchar* stock_icon,
int job, XSet* set );
gboolean xset_design_cb( GtkWidget* item, GdkEventButton * event, XSet* set );
const char* user_manual_url = "http://ignorantguru.github.com/spacefm/spacefm-manual-en.html";
const char* homepage = "http://ignorantguru.github.com/spacefm/"; //also in aboutdlg.ui
const char* enter_command_line = N_("Enter program or bash command line:\n\nUse:\n\t%%F\tselected files or %%f first selected file\n\t%%N\tselected filenames or %%n first selected filename\n\t%%d\tcurrent directory\n\t%%v\tselected device (eg /dev/sda1)\n\t%%m\tdevice mount point (eg /media/dvd); %%l device label\n\t%%b\tselected bookmark\n\t%%t\tselected task directory; %%p task pid\n\t%%a\tmenu item value\n\t$fm_panel, $fm_tab, $fm_command, etc");
const char* icon_desc = N_("Enter an icon name, icon file path, or stock item name:\n\nNot all icons may work due to various issues.");
const char* enter_menu_name = N_("Enter menu item name:\n\nPrecede a character with an underscore (_) to underline that character as a shortcut key if desired.");
const char* enter_menu_name_new = N_("Enter new menu item name:\n\nPrecede a character with an underscore (_) to underline that character as a shortcut key if desired.\n\nTIP: To change this menu item later, right-click on the menu item to open the design menu.");
static const char* context_sub[] =
{
N_("MIME Type"),
N_("Filename"),
N_("Directory"),
N_("Dir Write Access"),
N_("File Is Text"),
N_("File Is Dir"),
N_("File Is Link"),
N_("User Is Root"),
N_("Multiple Selected"),
N_("Clipboard Has Files"),
N_("Clipboard Has Text"),
N_("Current Panel"),
N_("Panel Count"),
N_("Current Tab"),
N_("Tab Count"),
N_("Bookmark"),
N_("Device"),
N_("Device Mount Point"),
N_("Device Label"),
N_("Device FSType"),
N_("Device UDI"),
N_("Device Properties"),
N_("Task Count"),
N_("Task Directory"),
N_("Task Type"),
N_("Task Name"),
N_("Panel 1 Directory"),
N_("Panel 2 Directory"),
N_("Panel 3 Directory"),
N_("Panel 4 Directory"),
N_("Panel 1 Has Sel"),
N_("Panel 2 Has Sel"),
N_("Panel 3 Has Sel"),
N_("Panel 4 Has Sel"),
N_("Panel 1 Device"),
N_("Panel 2 Device"),
N_("Panel 3 Device"),
N_("Panel 4 Device")
};
static const char* context_sub_list[] =
{
"4%%%%%application/%%%%%audio/%%%%%audio/ || video/%%%%%image/%%%%%inode/directory%%%%%text/%%%%%video/%%%%%application/x-bzip||application/x-bzip-compressed-tar||application/x-gzip||application/zip||application/x-7z-compressed||application/x-bzip2||application/x-bzip2-compressed-tar||application/x-xz-compressed-tar||application/x-compressed-tar||application/x-rar", //"MIME Type",
"6%%%%%archive_types || .gz || .bz2 || .7z || .xz || .txz || .tgz || .zip || .rar || .tar || .tar.gz || .tar.xz || .tar.bz2 || .tar.7z%%%%%audio_types || .mp3 || .MP3 || .m3u || .wav || .wma || .aac || .ac3 || .flac || .ram || .m4a || .ogg%%%%%image_types || .jpg || .jpeg || .gif || .png || .xpm%%%%%video_types || .mp4 || .MP4 || .avi || .AVI || .mkv || .mpeg || .mpg || .flv || .vob || .asf || .rm || .m2ts || .mov", //"Filename",
"0%%%%%", //"Dir",
"0%%%%%false%%%%%true", //"Dir Write Access",
"0%%%%%false%%%%%true", //"File Is Text",
"0%%%%%false%%%%%true", //"File Is Dir",
"0%%%%%false%%%%%true", //"File Is Link",
"0%%%%%false%%%%%true", //"User Is Root",
"0%%%%%false%%%%%true", //"Multiple Selected",
"0%%%%%false%%%%%true", //"Clipboard Has Files",
"0%%%%%false%%%%%true", //"Clipboard Has Text",
"0%%%%%1%%%%%2%%%%%3%%%%%4", //"Current Panel",
"0%%%%%1%%%%%2%%%%%3%%%%%4", //"Panel Count",
"0%%%%%1%%%%%2%%%%%3%%%%%4%%%%%5%%%%%6", //"Current Tab",
"0%%%%%1%%%%%2%%%%%3%%%%%4%%%%%5%%%%%6", //"Tab Count",
"0%%%%%", //"Bookmark",
"0%%%%%/dev/sdb1%%%%%/dev/sdc1%%%%%/dev/sdd1%%%%%/dev/sr0", //"Device",
"0%%%%%", //"Device Mount Point",
"0%%%%%", //"Device Label",
"0%%%%%btrfs%%%%%ext2%%%%%ext3%%%%%ext4%%%%%ext2 || ext3 || ext4%%%%%ntfs%%%%%reiser4%%%%%reiserfs%%%%%swap%%%%%ufs%%%%%vfat%%%%%xfs", //Device FSType",
"0%%%%%", //"Device UDI",
"2%%%%%audiocd%%%%%blank%%%%%dvd%%%%%dvd && blank%%%%%ejectable%%%%%floppy%%%%%internal%%%%%mountable%%%%%mounted%%%%%no_media%%%%%optical%%%%%optical && blank%%%%%optical && mountable%%%%%optical && mounted%%%%%removable%%%%%removable && mountable%%%%%removable && mounted%%%%%removable || optical%%%%%table%%%%%policy_hide%%%%%policy_noauto", //"Device Properties",
"8%%%%%0%%%%%1%%%%%2", //"Task Count",
"0%%%%%", //"Task Dir",
"0%%%%%change%%%%%copy%%%%%delete%%%%%link%%%%%move%%%%%run%%%%%trash", //"Task Type",
"0%%%%%", //"Task Name",
"0%%%%%", //"Panel 1 Dir",
"0%%%%%", //"Panel 2 Dir",
"0%%%%%", //"Panel 3 Dir",
"0%%%%%", //"Panel 4 Dir",
"0%%%%%false%%%%%true", //"Panel 1 Has Sel",
"0%%%%%false%%%%%true", //"Panel 2 Has Sel",
"0%%%%%false%%%%%true", //"Panel 3 Has Sel",
"0%%%%%false%%%%%true", //"Panel 4 Has Sel",
"0%%%%%dev/sdb1%%%%%/dev/sdc1%%%%%/dev/sdd1%%%%%/dev/sr0", //"Panel 1 Device",
"0%%%%%dev/sdb1%%%%%/dev/sdc1%%%%%/dev/sdd1%%%%%/dev/sr0", //"Panel 2 Device",
"0%%%%%dev/sdb1%%%%%/dev/sdc1%%%%%/dev/sdd1%%%%%/dev/sr0", //"Panel 3 Device",
"0%%%%%dev/sdb1%%%%%/dev/sdc1%%%%%/dev/sdd1%%%%%/dev/sr0" //"Panel 4 Device"
};
enum {
CONTEXT_COMP_EQUALS,
CONTEXT_COMP_NEQUALS,
CONTEXT_COMP_CONTAINS,
CONTEXT_COMP_NCONTAINS,
CONTEXT_COMP_BEGINS,
CONTEXT_COMP_NBEGINS,
CONTEXT_COMP_ENDS,
CONTEXT_COMP_NENDS,
CONTEXT_COMP_LESS,
CONTEXT_COMP_GREATER
};
static const char* context_comp[] =
{
N_("equals"),
N_("doesn't equal"),
N_("contains"),
N_("doesn't contain"),
N_("begins with"),
N_("doesn't begin with"),
N_("ends with"),
N_("doesn't end with"),
N_("is less than"),
N_("is greater than")
};
static void parse_general_settings( char* line )
{
char * sep = strstr( line, "=" );
char* name;
char* value;
if ( !sep )
return ;
name = line;
value = sep + 1;
*sep = '\0';
if ( 0 == strcmp( name, "encoding" ) )
strcpy( app_settings.encoding, value );
//else if ( 0 == strcmp( name, "show_hidden_files" ) )
// app_settings.show_hidden_files = atoi( value );
//else if ( 0 == strcmp( name, "show_side_pane" ) )
// app_settings.show_side_pane = atoi( value );
//else if ( 0 == strcmp( name, "side_pane_mode" ) )
// app_settings.side_pane_mode = atoi( value );
else if ( 0 == strcmp( name, "show_thumbnail" ) )
app_settings.show_thumbnail = atoi( value );
else if ( 0 == strcmp( name, "max_thumb_size" ) )
app_settings.max_thumb_size = atoi( value ) << 10;
else if ( 0 == strcmp( name, "big_icon_size" ) )
{
app_settings.big_icon_size = atoi( value );
if( app_settings.big_icon_size <= 0 || app_settings.big_icon_size > 128 )
app_settings.big_icon_size = big_icon_size_default;
}
else if ( 0 == strcmp( name, "small_icon_size" ) )
{
app_settings.small_icon_size = atoi( value );
if( app_settings.small_icon_size <= 0 || app_settings.small_icon_size > 128 )
app_settings.small_icon_size = small_icon_size_default;
}
else if ( 0 == strcmp( name, "tool_icon_size" ) )
{
app_settings.tool_icon_size = atoi( value );
if( app_settings.tool_icon_size < 0 ||
app_settings.tool_icon_size > GTK_ICON_SIZE_DIALOG )
app_settings.tool_icon_size = tool_icon_size_default;
}
/* FIXME: temporarily disable trash since it's not finished */
#if 0
else if ( 0 == strcmp( name, "use_trash_can" ) )
app_settings.use_trash_can = atoi(value);
#endif
else if ( 0 == strcmp( name, "single_click" ) )
app_settings.single_click = atoi(value);
//else if ( 0 == strcmp( name, "view_mode" ) )
// app_settings.view_mode = atoi( value );
else if ( 0 == strcmp( name, "sort_order" ) )
app_settings.sort_order = atoi( value );
else if ( 0 == strcmp( name, "sort_type" ) )
app_settings.sort_type = atoi( value );
else if ( 0 == strcmp( name, "open_bookmark_method" ) )
//app_settings.open_bookmark_method = atoi( value );
xset_set_b( "book_newtab", atoi( value ) != 1 ); //sfm backwards compat
/*
else if ( 0 == strcmp( name, "iconTheme" ) )
{
if ( value && *value )
app_settings.iconTheme = strdup( value );
}
*/
else if ( 0 == strcmp( name, "terminal" ) ) //MOD backwards compat
{
if ( value && *value )
xset_set( "main_terminal", "s", value );
//app_settings.terminal = strdup( value );
}
else if ( 0 == strcmp( name, "use_si_prefix" ) )
app_settings.use_si_prefix = atoi( value );
else if ( 0 == strcmp( name, "no_execute" ) )
app_settings.no_execute = atoi( value ); //MOD
else if ( 0 == strcmp( name, "home_folder" ) )
{
// backwards compat
if ( value && *value )
xset_set( "go_set_default", "s", value );
}
else if ( 0 == strcmp( name, "no_confirm" ) )
app_settings.no_confirm = atoi( value ); //MOD
/*
else if ( 0 == strcmp( name, "singleInstance" ) )
app_settings.singleInstance = atoi( value );
*/
/* else if ( 0 == strcmp( name, "show_location_bar" ) )
app_settings.show_location_bar = atoi( value );
*/
}
static void color_from_str( GdkColor* ret, const char* value )
{
sscanf( value, "%hu,%hu,%hu",
&ret->red, &ret->green, &ret->blue );
}
static void save_color( FILE* file, const char* name, GdkColor* color )
{
fprintf( file, "%s=%d,%d,%d\n", name,
color->red, color->green, color->blue );
}
static void parse_window_state( char* line )
{
char * sep = strstr( line, "=" );
char* name;
char* value;
int v;
if ( !sep )
return ;
name = line;
value = sep + 1;
*sep = '\0';
//if ( 0 == strcmp( name, "splitter_pos" ) )
//{
// v = atoi( value );
// app_settings.splitter_pos = ( v > 0 ? v : 160 );
//}
if ( 0 == strcmp( name, "width" ) )
{
v = atoi( value );
app_settings.width = ( v > 0 ? v : 640 );
}
if ( 0 == strcmp( name, "height" ) )
{
v = atoi( value );
app_settings.height = ( v > 0 ? v : 480 );
}
if ( 0 == strcmp( name, "maximized" ) )
{
app_settings.maximized = atoi( value );
}
}
static void parse_desktop_settings( char* line )
{
char * sep = strstr( line, "=" );
char* name;
char* value;
if ( !sep )
return ;
name = line;
value = sep + 1;
*sep = '\0';
//if ( 0 == strcmp( name, "show_desktop" ) )
// app_settings.show_desktop = atoi( value );
if ( 0 == strcmp( name, "show_wallpaper" ) )
app_settings.show_wallpaper = atoi( value );
else if ( 0 == strcmp( name, "wallpaper" ) )
app_settings.wallpaper = g_strdup( value );
else if ( 0 == strcmp( name, "wallpaper_mode" ) )
app_settings.wallpaper_mode = atoi( value );
else if ( 0 == strcmp( name, "bg1" ) )
color_from_str( &app_settings.desktop_bg1, value );
else if ( 0 == strcmp( name, "bg2" ) )
color_from_str( &app_settings.desktop_bg2, value );
else if ( 0 == strcmp( name, "text" ) )
color_from_str( &app_settings.desktop_text, value );
else if ( 0 == strcmp( name, "shadow" ) )
color_from_str( &app_settings.desktop_shadow, value );
else if ( 0 == strcmp( name, "sort_by" ) )
app_settings.desktop_sort_by = atoi( value );
else if ( 0 == strcmp( name, "sort_type" ) )
app_settings.desktop_sort_type = atoi( value );
else if ( 0 == strcmp( name, "show_wm_menu" ) )
app_settings.show_wm_menu = atoi( value );
}
static void parse_interface_settings( char* line )
{
char * sep = strstr( line, "=" );
char* name;
char* value;
if ( !sep )
return ;
name = line;
value = sep + 1;
*sep = '\0';
if ( 0 == strcmp( name, "always_show_tabs" ) )
app_settings.always_show_tabs = atoi( value );
else if ( 0 == strcmp( name, "show_close_tab_buttons" ) )
app_settings.hide_close_tab_buttons = !atoi( value );
//else if ( 0 == strcmp( name, "hide_side_pane_buttons" ) )
// app_settings.hide_side_pane_buttons = atoi( value );
//else if ( 0 == strcmp( name, "hide_folder_content_border" ) )
// app_settings.hide_folder_content_border = atoi( value );
}
static void parse_conf( char* line )
{
char * sep = strstr( line, "=" );
char* name;
char* value;
if ( !sep )
return ;
name = line;
value = sep + 1;
*sep = '\0';
char* sname = g_strstrip( name );
if ( !strcmp( sname, "tmp_dir" ) )
{
settings_tmp_dir = g_strdup( g_strstrip( value ) );
if ( settings_tmp_dir && settings_tmp_dir[0] == '\0' )
{
g_free( settings_tmp_dir );
settings_tmp_dir = NULL;
}
else if ( settings_tmp_dir && strpbrk( settings_tmp_dir, " $%\\()&#|:;?<>{}[]*\"'" ) )
{
g_free( settings_tmp_dir );
settings_tmp_dir = NULL;
g_warning( _("custom tmp_dir contains invalid chars - reverting to /tmp") );
}
else if ( settings_tmp_dir && !g_file_test( settings_tmp_dir, G_FILE_TEST_IS_DIR ) )
{
g_free( settings_tmp_dir );
settings_tmp_dir = NULL;
g_warning( _("custom tmp_dir does not exist - reverting to /tmp") );
}
}
}
void load_conf()
{
// load spacefm.conf
char line[ 2048 ];
FILE* file = fopen( "/etc/spacefm/spacefm.conf", "r" );
if ( file )
{
while ( fgets( line, sizeof( line ), file ) )
parse_conf( line );
fclose( file );
}
// set tmp dirs
if ( !settings_tmp_dir )
settings_tmp_dir = g_strdup( "/tmp" );
}
void load_settings( char* config_dir )
{
FILE * file;
gchar* path = NULL;
char line[ 2048 ];
char* section_name;
SettingsParseFunc func = NULL;
XSet* set;
char* str;
xset_cmd_history = NULL;
xset_autosave_timer = 0;
app_settings.load_saved_tabs = TRUE;
if ( config_dir )
settings_config_dir = config_dir;
else
settings_config_dir = g_build_filename( g_get_user_config_dir(), "spacefm", NULL );
/* set default value */
/* General */
/* app_settings.show_desktop = show_desktop_default; */
app_settings.show_wallpaper = show_wallpaper_default;
app_settings.wallpaper = NULL;
app_settings.desktop_bg1 = desktop_bg1_default;
app_settings.desktop_bg2 = desktop_bg2_default;
app_settings.desktop_text = desktop_text_default;
app_settings.desktop_sort_by = desktop_sort_by_default;
app_settings.desktop_sort_type = desktop_sort_type_default;
app_settings.show_wm_menu = show_wm_menu_default;
app_settings.encoding[ 0 ] = '\0';
//app_settings.show_hidden_files = show_hidden_files_default;
//app_settings.show_side_pane = show_side_pane_default;
//app_settings.side_pane_mode = side_pane_mode_default;
app_settings.show_thumbnail = show_thumbnail_default;
app_settings.max_thumb_size = max_thumb_size_default;
app_settings.big_icon_size = big_icon_size_default;
app_settings.small_icon_size = small_icon_size_default;
app_settings.tool_icon_size = tool_icon_size_default;
app_settings.use_trash_can = use_trash_can_default;
//app_settings.view_mode = view_mode_default;
//app_settings.open_bookmark_method = open_bookmark_method_default;
/* app_settings.iconTheme = NULL; */
//app_settings.terminal = NULL;
app_settings.use_si_prefix = use_si_prefix_default;
//app_settings.show_location_bar = show_location_bar_default;
//app_settings.home_folder = NULL; //MOD
app_settings.no_execute = TRUE; //MOD
app_settings.no_confirm = FALSE; //MOD
app_settings.date_format = NULL; //MOD
/* Interface */
app_settings.always_show_tabs = always_show_tabs_default;
app_settings.hide_close_tab_buttons = hide_close_tab_buttons_default;
//app_settings.hide_side_pane_buttons = hide_side_pane_buttons_default;
//app_settings.hide_folder_content_border = hide_folder_content_border_default;
/* Window State */
//app_settings.splitter_pos = 160;
app_settings.width = 640;
app_settings.height = 480;
// MOD extra settings
xset_defaults();
/* load settings */ //MOD
/* Dirty hacks for LXDE */
/*
if( is_under_LXDE() )
{
show_desktop_default = app_settings.show_desktop = TRUE; // show the desktop by default
}
*/
// set tmp dirs
if ( !settings_tmp_dir )
settings_tmp_dir = g_strdup( "/tmp" );
// shared tmp
settings_shared_tmp_dir = g_build_filename( settings_tmp_dir, "spacefm.tmp", NULL );
if ( geteuid() == 0 )
{
if ( !g_file_test( settings_shared_tmp_dir, G_FILE_TEST_EXISTS ) )
g_mkdir_with_parents( settings_shared_tmp_dir,
S_IRWXU | S_IRWXG | S_IRWXO | S_ISVTX );
chown( settings_shared_tmp_dir, 0, 0 );
chmod( settings_shared_tmp_dir, S_IRWXU | S_IRWXG | S_IRWXO | S_ISVTX );
}
// copy /etc/xdg/spacefm
if ( !g_file_test( settings_config_dir, G_FILE_TEST_EXISTS )
&& g_file_test( "/etc/xdg/spacefm", G_FILE_TEST_IS_DIR ) )
{
char* command = g_strdup_printf( "cp -r /etc/xdg/spacefm '%s'",
settings_config_dir );
printf( "COMMAND=%s\n", command );
g_spawn_command_line_sync( command, NULL, NULL, NULL, NULL );
g_free( command );
chmod( settings_config_dir, S_IRWXU );
}
// load session
int x = 0;
do
{
if ( path )
g_free ( path );
path = NULL;
switch ( x )
{
case 0:
path = g_build_filename( settings_config_dir, "session", NULL );
break;
case 1:
path = g_build_filename( settings_config_dir, "session-last", NULL );
break;
case 2:
path = g_build_filename( settings_config_dir, "session-prior", NULL );
break;
case 3:
path = g_build_filename( settings_config_dir, "main.lxde", NULL );
break;
case 4:
path = g_build_filename( settings_config_dir, "main", NULL );
break;
case 5:
path = g_build_filename( g_get_user_config_dir(), "pcmanfm",
"main.lxde", NULL );
break;
case 6:
path = g_build_filename( g_get_user_config_dir(), "pcmanfm",
"main", NULL );
break;
default:
path = NULL;
}
x++;
} while ( path && !g_file_test( path, G_FILE_TEST_EXISTS ) );
if ( x == 1 )
{
// copy session to session-last
char* last = g_build_filename( settings_config_dir, "session-last", NULL );
char* prior = g_build_filename( settings_config_dir, "session-prior", NULL );
if ( g_file_test( last, G_FILE_TEST_EXISTS ) )
{
unlink( prior );
rename( last, prior );
}
xset_copy_file( path, last );
chmod( last, S_IRUSR | S_IWUSR );
g_free( last );
g_free( prior );
}
if ( path )
{
file = fopen( path, "r" );
g_free( path );
}
else
file = NULL;
if ( file )
{
while ( fgets( line, sizeof( line ), file ) )
{
strtok( line, "\r\n" );
if ( ! line[ 0 ] )
continue;
if ( line[ 0 ] == '[' )
{
section_name = strtok( line, "]" );
if ( 0 == strcmp( line + 1, "General" ) )
func = &parse_general_settings;
else if ( 0 == strcmp( line + 1, "Window" ) )
func = &parse_window_state;
else if ( 0 == strcmp( line + 1, "Interface" ) )
func = &parse_interface_settings;
else if ( 0 == strcmp( line + 1, "Desktop" ) )
func = &parse_desktop_settings;
else if ( 0 == strcmp( line + 1, "MOD" ) ) //MOD
func = &xset_parse;
else
func = NULL;
continue;
}
if ( func )
( *func ) ( line );
}
fclose( file );
}
if ( app_settings.encoding[ 0 ] )
{
setenv( "G_FILENAME_ENCODING", app_settings.encoding, 1 );
}
//MOD turn off fullscreen
xset_set_b( "main_full", FALSE );
//MOD date_format
app_settings.date_format = g_strdup( xset_get_s( "date_format" ) );
if ( !app_settings.date_format || app_settings.date_format[0] == '\0' )
{
if ( app_settings.date_format )
g_free( app_settings.date_format );
app_settings.date_format = g_strdup_printf( "%%Y-%%m-%%d %%H:%%M" );
xset_set( "date_format", "s", "%Y-%m-%d %H:%M" );
}
//MOD su and gsu command discovery (sets default)
char* set_su = get_valid_su();
if ( set_su )
g_free( set_su );
set_su = get_valid_gsu();
if ( set_su )
g_free( set_su );
//MOD terminal discovery
int i;
char* term;
char* terminal = xset_get_s( "main_terminal" );
if ( !terminal || terminal[0] == '\0' )
{
for ( i = 0; i < G_N_ELEMENTS( terminal_programs ); i++ )
{
if ( term = g_find_program_in_path( terminal_programs[i] ) )
{
xset_set( "main_terminal", "s", terminal_programs[i] );
xset_set_b( "main_terminal", TRUE ); // discovery
g_free( term );
break;
}
}
}
//MOD editor discovery
char* app_name = xset_get_s( "editor" );
if ( !app_name || app_name[0] == '\0' )
{
VFSMimeType* mime_type = vfs_mime_type_get_from_type( "text/plain" );
if ( mime_type )
{
app_name = vfs_mime_type_get_default_action( mime_type );
vfs_mime_type_unref( mime_type );
//int app_len = strlen( app_name );
//if ( app_len > 8 && !strcmp( app_name + app_len - 8, ".desktop" ) )
if ( app_name )
{
VFSAppDesktop* app = vfs_app_desktop_new( app_name );
if ( app )
{
if ( app->exec )
xset_set( "editor", "s", app->exec );
vfs_app_desktop_unref( app );
}
}
}
}
// get root-protected settings
read_root_settings();
// set default keys
xset_default_keys();
/* Load bookmarks */
/* Don't load bookmarks here since we won't use it in some cases */
/* app_settings.bookmarks = ptk_bookmarks_get(); */
// cache event handlers
evt_win_focus = xset_get( "evt_win_focus" );
evt_win_move = xset_get( "evt_win_move" );
evt_win_click = xset_get( "evt_win_click" );
evt_win_key = xset_get( "evt_win_key" );
evt_win_close = xset_get( "evt_win_close" );
evt_pnl_show = xset_get( "evt_pnl_show" );
evt_pnl_focus = xset_get( "evt_pnl_focus" );
evt_pnl_sel = xset_get( "evt_pnl_sel" );
evt_tab_new = xset_get( "evt_tab_new" );
evt_tab_focus = xset_get( "evt_tab_focus" );
evt_tab_close = xset_get( "evt_tab_close" );
evt_device = xset_get( "evt_device" );
// config conversions
int ver = xset_get_int( "config_version", "s" );
if ( ver == 0 )
return;
if ( ver < 3 ) // < 0.5.3
{
set = xset_get( "toolbar_left" );
if ( set->menu_label && !strcmp( set->menu_label, "_Left" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( "_Left Toolbar" );
}
set = xset_get( "toolbar_right" );
if ( set->menu_label && !strcmp( set->menu_label, "_Right" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( "_Right Toolbar" );
}
set = xset_get( "toolbar_side" );
if ( set->menu_label && !strcmp( set->menu_label, "_Side" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( "_Side Toolbar" );
}
for ( i = 1; i < 5; i++ )
{
set = xset_get_panel( i, "show_sidebar" );
if ( set->menu_label && !strcmp( set->menu_label, "_Sidebar" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( "_Side Toolbar" );
}
}
set = xset_get( "focus_path_bar" );
if ( set->menu_label && !strcmp( set->menu_label, "_Smart Bar" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( "_Smartbar" );
}
}
if ( ver < 4 ) // < 0.5.4
{
set = xset_get( "task_err_first" );
if ( set->menu_label && !strcmp( set->menu_label, "Stop On _First" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( "Stop If _First" );
}
}
if ( ver < 6 ) // < 0.6.3
{
set = xset_get( "dev_show_internal_drives" );
if ( set->menu_label && !strcmp( set->menu_label, "Show _Internal Drives" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( "_Internal Drives" );
}
set = xset_get( "dev_show_partition_tables" );
if ( set->menu_label && !strcmp( set->menu_label, "Show _Partition Tables" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( "_Partition Tables" );
}
set = xset_get( "dev_ignore_udisks_hide" );
if ( set->menu_label && !strcmp( set->menu_label, "Ignore Udisks _Hide Policy" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( "Ignore _Hide Policy" );
}
set = xset_get( "dev_show_hide_volumes" );
if ( set->menu_label && !strcmp( set->menu_label, "Show _Volumes..." ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( "_Volumes..." );
}
set = xset_get( "dev_show_empty" ); //new
if ( set->b == XSET_B_UNSET )
set->b = XSET_B_TRUE;
}
if ( ver < 7 ) // < 0.7.0
{
// custom separators ->next xset have invalid prev
XSet* set_next;
GList* l;
for ( l = xsets; l; l = l->next )
{
set = l->data;
if ( !set->lock && set->menu_style == XSET_MENU_SEP && set->next )
{
set_next = xset_get( set->next );
if ( set_next->prev )
g_free( set_next->prev );
set_next->prev = g_strdup( set->name );
}
}
}
if ( ver < 8 ) // < 0.7.2
{
if ( app_settings.small_icon_size == 20 )
app_settings.small_icon_size = 22;
if ( app_settings.big_icon_size == 20 )
app_settings.big_icon_size = 22;
}
if ( ver < 9 ) // < 0.7.3
{
for ( i = 1; i < 5; i++ )
{
set = xset_get_panel( i, "show_toolbox" );
if ( set->menu_label && !strcmp( set->menu_label, "_Toolbox" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( "_Toolbar" );
}
}
set = xset_get( "focus_path_bar" );
if ( set->menu_label && !strcmp( set->menu_label, "_Smartbar" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( "_Path Bar" );
}
set = xset_get( "path_help" );
if ( set->menu_label && !strcmp( set->menu_label, "_Smartbar Help" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( "_Path Bar Help" );
}
}
if ( ver < 10 ) // < 0.7.5
{
set = xset_get( "dev_ignore_udisks_hide" );
if ( set->menu_label && !strcmp( set->menu_label, "Ignore Udisks _Hide" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( _("Ignore _Hide Policy") );
}
set = xset_get( "dev_ignore_udisks_nopolicy" );
if ( set->menu_label && !strcmp( set->menu_label, "Ignore Udisks _No Policy" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( _("Ignore _No Policy") );
}
}
if ( ver < 11 ) // < 0.7.7+
{
set = xset_get( "main_faq" );
if ( set->menu_label && !strcmp( set->menu_label, "How do I... (_FAQ)" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( _("_FAQ") );
}
}
if ( ver < 15 ) // < 0.8.1
{
set = xset_get( "task_stop" );
if ( set->menu_label && !strcmp( set->menu_label, "_Stop Task" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( _("_Stop") );
}
set = xset_get( "task_stop_all" );
g_free( set->menu_label );
set->menu_label = g_strdup( _("_Stop") );
set = xset_get( "task_show_manager" );
if ( set->menu_label && !strcmp( set->menu_label, "_Show Manager" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( _("Show _Manager") );
}
set = xset_get( "task_hide_manager" );
if ( set->menu_label && !strcmp( set->menu_label, "_Auto-Hide Manager" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( _("Auto-_Hide Manager") );
}
set = xset_get( "task_errors" );
if ( set->menu_label && !strcmp( set->menu_label, "_Errors" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( _("Err_ors") );
}
set = xset_get( "task_col_curest" );
if ( set->menu_label && !strcmp( set->menu_label, "Current Esti_mate" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( _("Current Re_main") );
}
set = xset_get( "task_col_avgest" );
if ( set->menu_label && !strcmp( set->menu_label, "A_verage Estimate" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( _("A_verage Remain") );
}
set = xset_get( "task_col_path" );
if ( set->menu_label && !strcmp( set->menu_label, "_Path" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( _("_Folder") );
}
set = xset_get( "dev_root_mount" );
if ( !g_strcmp0( set->icon, "gtk-add" ) )
string_copy_free( &set->icon, "drive-removable-media" );
set = xset_get( "iso_mount" );
if ( !g_strcmp0( set->icon, "gtk-cdrom" ) )
string_copy_free( &set->icon, "drive-removable-media" );
set = xset_get( "stool_mount" );
if ( !g_strcmp0( set->icon, "gtk-add" ) )
string_copy_free( &set->icon, "drive-removable-media" );
set = xset_get( "dev_menu_mount" );
if ( !g_strcmp0( set->icon, "gtk-add" ) )
string_copy_free( &set->icon, "drive-removable-media" );
set = xset_get( "task_pop_detail" );
if ( !g_strcmp0( set->menu_label, "_Detailed Status" ) )
string_copy_free( &set->menu_label, _("_Detailed Stats") );
if ( app_settings.small_icon_size == 20 )
app_settings.small_icon_size = 22;
if ( app_settings.big_icon_size == 20 )
app_settings.big_icon_size = 22;
}
if ( ver < 16 ) // < 0.8.3
{
set = xset_get( "dev_menu_remove" );
if ( set->menu_label && !strcmp( set->menu_label, "Remo_ve" ) )
{
g_free( set->menu_label );
set->menu_label = g_strdup( _("Remo_ve / Eject") );
}
}
}
char* save_settings( gpointer main_window_ptr )
{
FILE * file;
gchar* path;
int result, p, pages, g;
char* err_msg = NULL;
XSet* set;
PtkFileBrowser* file_browser;
char* tabs;
char* old_tabs;
FMMainWindow* main_window;
//printf("save_settings\n");
xset_set( "config_version", "s", "17" ); // 0.8.7
// save tabs
if ( main_window_ptr && xset_get_b( "main_save_tabs" ) )
{
main_window = (FMMainWindow*)main_window_ptr;
for ( p = 1; p < 5; p++ )
{
set = xset_get_panel( p, "show" );
pages = gtk_notebook_get_n_pages( GTK_NOTEBOOK( main_window->panel[p-1] ) );
if ( pages ) // panel was shown
{
if ( set->s )
{
g_free( set->s );
set->s = NULL;
}
tabs = g_strdup( "" );
for ( g = 0; g < pages; g++ )
{
file_browser = PTK_FILE_BROWSER( gtk_notebook_get_nth_page(
GTK_NOTEBOOK( main_window->panel[p-1] ), g ) );
old_tabs = tabs;
tabs = g_strdup_printf( "%s///%s", old_tabs,
ptk_file_browser_get_cwd( file_browser ) );
g_free( old_tabs );
}
if ( tabs[0] != '\0' )
set->s = tabs;
else
g_free( tabs );
// save current tab
if ( set->x )
g_free( set->x );
set->x = g_strdup_printf( "%d", gtk_notebook_get_current_page(
GTK_NOTEBOOK( main_window->panel[p-1] ) ) );
}
}
}
else
{
// clear saved tabs
for ( p = 1; p < 5; p++ )
{
set = xset_get_panel( p, "show" );
if ( set->s )
{
g_free( set->s );
set->s = NULL;
}
if ( set->x )
{
g_free( set->x );
set->x = NULL;
}
}
}
/* save settings */
if ( ! g_file_test( settings_config_dir, G_FILE_TEST_EXISTS ) )
g_mkdir_with_parents( settings_config_dir, 0700 );
if ( ! g_file_test( settings_config_dir, G_FILE_TEST_EXISTS ) )
goto _save_error;
path = g_build_filename( settings_config_dir, "session.tmp", NULL );
/* Dirty hacks for LXDE */
file = fopen( path, "w" );
if ( file )
{
/* General */
result = fputs( _("# SpaceFM Session File\n\n# THIS FILE IS NOT DESIGNED TO BE EDITED - it will be read and OVERWRITTEN\n\n# If you delete all session* files, SpaceFM will be reset to factory defaults.\n\n"), file );
if ( result < 0 )
goto _save_error;
fputs( "[General]\n", file );
/*
if ( app_settings.singleInstance != singleInstance_default )
fprintf( file, "singleInstance=%d\n", !!app_settings.singleInstance );
*/
if ( app_settings.encoding[ 0 ] )
fprintf( file, "encoding=%s\n", app_settings.encoding );
//if ( app_settings.show_hidden_files != show_hidden_files_default )
// fprintf( file, "show_hidden_files=%d\n", !!app_settings.show_hidden_files );
//if ( app_settings.show_side_pane != show_side_pane_default )
// fprintf( file, "show_side_pane=%d\n", app_settings.show_side_pane );
//if ( app_settings.side_pane_mode != side_pane_mode_default )
// fprintf( file, "side_pane_mode=%d\n", app_settings.side_pane_mode );
if ( app_settings.show_thumbnail != show_thumbnail_default )
fprintf( file, "show_thumbnail=%d\n", !!app_settings.show_thumbnail );
if ( app_settings.max_thumb_size != max_thumb_size_default )
fprintf( file, "max_thumb_size=%d\n", app_settings.max_thumb_size >> 10 );
if ( app_settings.big_icon_size != big_icon_size_default )
fprintf( file, "big_icon_size=%d\n", app_settings.big_icon_size );
if ( app_settings.small_icon_size != small_icon_size_default )
fprintf( file, "small_icon_size=%d\n", app_settings.small_icon_size );
if ( app_settings.tool_icon_size != tool_icon_size_default )
fprintf( file, "tool_icon_size=%d\n", app_settings.tool_icon_size );
/* FIXME: temporarily disable trash since it's not finished */
#if 0
if ( app_settings.use_trash_can != use_trash_can_default )
fprintf( file, "use_trash_can=%d\n", app_settings.use_trash_can );
#endif
if ( app_settings.single_click != single_click_default )
fprintf( file, "single_click=%d\n", app_settings.single_click );
//if ( app_settings.view_mode != view_mode_default )
// fprintf( file, "view_mode=%d\n", app_settings.view_mode );
if ( app_settings.sort_order != sort_order_default )
fprintf( file, "sort_order=%d\n", app_settings.sort_order );
if ( app_settings.sort_type != sort_type_default )
fprintf( file, "sort_type=%d\n", app_settings.sort_type );
//if ( app_settings.open_bookmark_method != open_bookmark_method_default )
// fprintf( file, "open_bookmark_method=%d\n", app_settings.open_bookmark_method );
/*
if ( app_settings.iconTheme )
fprintf( file, "iconTheme=%s\n", app_settings.iconTheme );
*/
//if ( app_settings.terminal )
// fprintf( file, "terminal=%s\n", app_settings.terminal );
if ( app_settings.use_si_prefix != use_si_prefix_default )
fprintf( file, "use_si_prefix=%d\n", !!app_settings.use_si_prefix );
// if ( app_settings.show_location_bar != show_location_bar_default )
// fprintf( file, "show_location_bar=%d\n", app_settings.show_location_bar );
/* if ( app_settings.home_folder )
fprintf( file, "home_folder=%s\n", app_settings.home_folder ); //MOD
*/ if ( !app_settings.no_execute )
fprintf( file, "no_execute=%d\n", !!app_settings.no_execute ); //MOD
if ( app_settings.no_confirm )
fprintf( file, "no_confirm=%d\n", !!app_settings.no_confirm ); //MOD
fputs( "\n[Window]\n", file );
fprintf( file, "width=%d\n", app_settings.width );
fprintf( file, "height=%d\n", app_settings.height );
//fprintf( file, "splitter_pos=%d\n", app_settings.splitter_pos );
fprintf( file, "maximized=%d\n", app_settings.maximized );
/* Desktop */
fputs( "\n[Desktop]\n", file );
//if ( app_settings.show_desktop != show_desktop_default )
// fprintf( file, "show_desktop=%d\n", !!app_settings.show_desktop );
if ( app_settings.show_wallpaper != show_wallpaper_default )
fprintf( file, "show_wallpaper=%d\n", !!app_settings.show_wallpaper );
if ( app_settings.wallpaper && app_settings.wallpaper[ 0 ] )
fprintf( file, "wallpaper=%s\n", app_settings.wallpaper );
if ( app_settings.wallpaper_mode != wallpaper_mode_default )
fprintf( file, "wallpaper_mode=%d\n", app_settings.wallpaper_mode );
if ( app_settings.desktop_sort_by != desktop_sort_by_default )
fprintf( file, "sort_by=%d\n", app_settings.desktop_sort_by );
if ( app_settings.desktop_sort_type != desktop_sort_type_default )
fprintf( file, "sort_type=%d\n", app_settings.desktop_sort_type );
if ( app_settings.show_wm_menu != show_wm_menu_default )
fprintf( file, "show_wm_menu=%d\n", app_settings.show_wm_menu );
if ( ! gdk_color_equal( &app_settings.desktop_bg1,
&desktop_bg1_default ) )
save_color( file, "bg1",
&app_settings.desktop_bg1 );
if ( ! gdk_color_equal( &app_settings.desktop_bg2,
&desktop_bg2_default ) )
save_color( file, "bg2",
&app_settings.desktop_bg2 );
if ( ! gdk_color_equal( &app_settings.desktop_text,
&desktop_text_default ) )
save_color( file, "text",
&app_settings.desktop_text );
if ( ! gdk_color_equal( &app_settings.desktop_shadow,
&desktop_shadow_default ) )
save_color( file, "shadow",
&app_settings.desktop_shadow );
/* Interface */
fputs( "\n[Interface]\n", file );
if ( app_settings.always_show_tabs != always_show_tabs_default )
fprintf( file, "always_show_tabs=%d\n", app_settings.always_show_tabs );
if ( app_settings.hide_close_tab_buttons != hide_close_tab_buttons_default )
fprintf( file, "show_close_tab_buttons=%d\n", !app_settings.hide_close_tab_buttons );
//if ( app_settings.hide_side_pane_buttons != hide_side_pane_buttons_default )
// fprintf( file, "hide_side_pane_buttons=%d\n", app_settings.hide_side_pane_buttons );
//if ( app_settings.hide_folder_content_border != hide_folder_content_border_default )
// fprintf( file, "hide_folder_content_border=%d\n", app_settings.hide_folder_content_border );
// MOD extra settings
fputs( "\n[MOD]\n", file );
xset_write( file );
result = fputs( "\n", file );
if ( result < 0 )
goto _save_error;
result = fclose( file );
if ( result )
goto _save_error;
}
else
goto _save_error;
// move
char* session = g_build_filename( settings_config_dir, "session", NULL );
unlink( session );
if ( g_file_test( session, G_FILE_TEST_EXISTS ) )
goto _save_error;
result = rename( path, session );
g_free( path );
if ( result == -1 )
goto _save_error;
if ( !g_file_test( session, G_FILE_TEST_EXISTS ) )
goto _save_error;
g_free( session );
/* Save bookmarks */
ptk_bookmarks_save();
return NULL;
_save_error:
if ( errno )
{
err_msg = (char*)g_strerror( errno );
if ( err_msg )
err_msg = g_strdup( err_msg );
}
if ( !err_msg )
err_msg = g_strdup_printf( _("Error saving file") );
ptk_bookmarks_save();
return err_msg;
}
void free_settings()
{
/*
if ( app_settings.iconTheme )
g_free( app_settings.iconTheme );
*/
//g_free( app_settings.terminal );
g_free( app_settings.wallpaper );
ptk_bookmarks_unref();
if ( xset_cmd_history )
{
g_list_foreach( xset_cmd_history, (GFunc)g_free, NULL );
g_list_free( xset_cmd_history );
xset_cmd_history = NULL;
}
xset_free_all();
}
const char* xset_get_config_dir()
{
return settings_config_dir;
}
const char* xset_get_tmp_dir()
{
return settings_tmp_dir;
}
const char* xset_get_shared_tmp_dir()
{
if ( !g_file_test( settings_shared_tmp_dir, G_FILE_TEST_EXISTS ) )
{
g_mkdir_with_parents( settings_shared_tmp_dir,
S_IRWXU | S_IRWXG | S_IRWXO | S_ISVTX );
chmod( settings_shared_tmp_dir,
S_IRWXU | S_IRWXG | S_IRWXO | S_ISVTX );
}
return settings_shared_tmp_dir;
}
const char* xset_get_user_tmp_dir()
{
if ( settings_user_tmp_dir &&
g_file_test( settings_user_tmp_dir, G_FILE_TEST_EXISTS ) )
return settings_user_tmp_dir;
char* rand;
char* name;
int count = 0;
int ret;
do
{
g_free( settings_user_tmp_dir );
rand = randhex8();
name = g_strdup_printf( "spacefm-%s-%s.tmp", g_get_user_name(), rand );
g_free( rand );
settings_user_tmp_dir = g_build_filename( settings_tmp_dir, name, NULL );
g_free( name );
count++;
} while ( count < 1000 && ( ret = mkdir( settings_user_tmp_dir,
S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH ) != 0 ) );
if ( ret != 0 )
{
g_free( settings_user_tmp_dir );
settings_user_tmp_dir = NULL;
g_warning( "Unable to create temporary directory in %s", settings_tmp_dir );
}
return settings_user_tmp_dir;
}
gboolean on_autosave_timer( gpointer main_window )
{
//printf("AUTOSAVE on_timer\n" );
char* err_msg = save_settings( main_window );
if ( err_msg )
{
printf( _("SpaceFM Error: Unable to autosave session file ( %s )\n"), err_msg );
g_free( err_msg );
}
if ( xset_autosave_timer )
{
g_source_remove( xset_autosave_timer );
xset_autosave_timer = 0;
}
return FALSE;
}
void xset_autosave( PtkFileBrowser* file_browser )
{
gpointer mw = NULL;
if ( file_browser )
mw = file_browser->main_window;
if ( xset_autosave_timer )
{
// autosave timer is already running, so ignore request
//printf("AUTOSAVE already set\n" );
return;
}
// autosave settings in 10 seconds
xset_autosave_timer = g_timeout_add_seconds( 10,
( GSourceFunc ) on_autosave_timer, mw );
//printf("AUTOSAVE timer started\n" );
}
/////////////////////////////////////////////////////////////////////////////
//MOD extra settings below
char* get_valid_su() // may return NULL
{
char* set_su = NULL;
int i;
if ( xset_get_s( "su_command" ) )
set_su = g_strdup( xset_get_s( "su_command" ) );
if ( set_su )
{
// is set_su valid su command?
for ( i = 0; i < G_N_ELEMENTS( su_commands ); i++ )
{
if ( !strcmp( su_commands[i], set_su ) )
break;
}
if ( i == G_N_ELEMENTS( su_commands ) )
{
// invalid
g_free( set_su );
set_su = NULL;
}
}
if ( !set_su )
{
// discovery
for ( i = 0; i < G_N_ELEMENTS( su_commands ); i++ )
{
if ( set_su = g_find_program_in_path( su_commands[i] ) )
break;
}
if ( !set_su )
set_su = g_strdup( su_commands[0] );
xset_set( "su_command", "s", set_su );
}
char* str = g_find_program_in_path( set_su );
g_free( set_su );
return str;
}
char* get_valid_gsu() // may return NULL
{
int i;
char* set_gsu = NULL;
char* custom_gsu = NULL;
if ( xset_get_s( "gsu_command" ) )
set_gsu = g_strdup( xset_get_s( "gsu_command" ) );
#ifdef PREFERABLE_SUDO_PROG
custom_gsu = g_find_program_in_path( PREFERABLE_SUDO_PROG );
#endif
if ( custom_gsu )
{
if ( !set_gsu || set_gsu[0] == '\0' )
{
xset_set( "gsu_command", "s", custom_gsu );
if ( set_gsu )
g_free( set_gsu );
set_gsu = g_strdup( custom_gsu );
}
}
if ( set_gsu )
{
if ( !custom_gsu || strcmp( custom_gsu, set_gsu ) )
{
// is set_gsu valid gsu command?
for ( i = 0; i < G_N_ELEMENTS( gsu_commands ); i++ )
{
if ( !strcmp( gsu_commands[i], set_gsu ) )
break;
}
if ( i == G_N_ELEMENTS( gsu_commands ) )
{
// invalid
g_free( set_gsu );
set_gsu = NULL;
}
}
}
if ( !set_gsu )
{
// discovery
for ( i = 0; i < G_N_ELEMENTS( gsu_commands ); i++ )
{
// don't automatically select gksudo
if ( strcmp( gsu_commands[i], "/usr/bin/gksudo" ) )
{
if ( set_gsu = g_find_program_in_path( gsu_commands[i] ) )
break;
}
}
if ( !set_gsu )
set_gsu = g_strdup( gsu_commands[0] );
xset_set( "gsu_command", "s", set_gsu );
}
if ( custom_gsu )
g_free( custom_gsu );
char* str = g_find_program_in_path( set_gsu );
if ( !str && !strcmp( set_gsu, "/usr/bin/kdesu" ) )
{
// kdesu may be in libexec path
char* stdout;
if ( g_spawn_command_line_sync( "kde4-config --path libexec",
&stdout, NULL, NULL, NULL )
&& stdout && stdout[0] != '\0' )
{
if ( str = strchr( stdout, '\n' ) )
str[0] = '\0';
str = g_build_filename( stdout, "kdesu", NULL );
g_free( stdout );
if ( !g_file_test( str, G_FILE_TEST_EXISTS ) )
{
g_free( str );
str = NULL;
}
}
}
g_free( set_gsu );
return str;
}
char* randhex8()
{
char hex[9];
uint n;
n = rand();
sprintf(hex, "%08x", n);
return g_strdup( hex );
}
char* replace_line_subs( const char* line )
{
char* old_s;
char* s;
int i;
const char* perc[] = { "%f", "%F", "%n", "%N", "%d", "%D", "%v", "%l", "%m", "%y", "%b", "%t", "%p", "%a" };
const char* var[] =
{
"\"${fm_file}\"",
"\"${fm_files[@]}\"",
"\"${fm_filename}\"",
"\"${fm_filenames[@]}\"",
"\"${fm_pwd}\"",
"\"${fm_pwd}\"",
"\"${fm_device}\"",
"\"${fm_device_label}\"",
"\"${fm_device_mount_point}\"",
"\"${fm_device_fstype}\"",
"\"${fm_bookmark}\"",
"\"${fm_task_pwd}\"",
"\"${fm_task_pid}\"",
"\"${fm_value}\""
};
s = g_strdup( line );
int num = G_N_ELEMENTS( perc );
for ( i = 0; i < num; i++ )
{
if ( strstr( line, perc[i] ) )
{
old_s = s;
s = replace_string( old_s, perc[i], var[i], FALSE );
g_free( old_s );
}
}
return s;
}
char* replace_desktop_subs( const char* line )
{
char* old_s;
char* s;
int i;
const char* perc[] = { "%f", "%F", "%u", "%U", "%d", "%D" };
const char* var[] =
{
"\"${fm_file}\"",
"\"${fm_files[@]}\"",
"\"${fm_file}\"",
"\"${fm_files[@]}\"",
"\"${fm_pwd}\"",
"\"${fm_pwd}\""
};
s = g_strdup( line );
int num = G_N_ELEMENTS( perc );
for ( i = 0; i < num; i++ )
{
if ( strstr( line, perc[i] ) )
{
old_s = s;
s = replace_string( old_s, perc[i], var[i], FALSE );
g_free( old_s );
}
}
return s;
}
gboolean is_alphanum( char* str )
{
char* ptr = str;
while ( ptr[0] != '\0' )
{
if ( !g_ascii_isalnum( ptr[0] ) )
return FALSE;
ptr++;
}
return TRUE;
}
char* get_name_extension( char* full_name, gboolean is_dir, char** ext )
{
char* dot;
char* str;
char* final_ext;
char* full;
full = g_strdup( full_name );
// get last dot
if ( is_dir || !( dot = strrchr( full, '.' ) ) || dot == full )
{
// dir or no dots or one dot first
*ext = NULL;
return full;
}
dot[0] = '\0';
final_ext = dot + 1;
// get previous dot
dot = strrchr( full, '.' );
uint final_ext_len = strlen( final_ext );
if ( dot && !strcmp( dot + 1, "tar" ) && final_ext_len < 11 && final_ext_len )
{
// double extension
final_ext[-1] = '.';
*ext = g_strdup( dot + 1 );
dot[0] = '\0';
str = g_strdup( full );
g_free( full );
return str;
}
// single extension, one or more dots
if ( final_ext_len < 11 && final_ext[0] )
{
*ext = g_strdup( final_ext );
str = g_strdup( full );
g_free( full );
return str;
}
else
{
// extension too long, probably part of name
final_ext[-1] = '.';
*ext = NULL;
return full;
}
}
/*
char* get_name_extension( char* full_name, gboolean is_dir, char** ext )
{
char* dot = strchr( full_name, '.' );
if ( !dot || is_dir )
{
*ext = NULL;
return g_strdup( full_name );
}
char* name = NULL;
char* old_name;
char* old_extension;
char* segment;
char* extension = NULL;
char* seg_start = full_name;
while ( seg_start )
{
if ( dot )
segment = g_strndup( seg_start, dot - seg_start );
else
segment = g_strdup( seg_start );
if ( ( seg_start == full_name || g_utf8_strlen( segment, -1 ) > 5
|| !is_alphanum( segment ) )
&& !( seg_start != full_name && !strcmp( segment, "desktop" ) ) )
{
// segment and thus all prior segments are part of name
old_name = name;
//printf("part of name\n");
if ( !extension )
{
if ( !old_name )
name = g_strdup( segment );
else
name = g_strdup_printf( "%s.%s", old_name, segment );
//printf("\told_name=%s\n\tsegment=%s\n\tname=%s\n", old_name, segment, name );
}
else
{
name = g_strdup_printf( "%s.%s.%s", old_name, extension, segment );
//printf("\told_name=%s\n\text=%s\n\tsegment=%s\n\tname=%s\n", old_name, extension, segment, name );
g_free( extension );
extension = NULL;
}
g_free( old_name );
}
else
{
// segment is part of extension
//printf("part of extension\n");
if ( !extension )
{
extension = g_strdup( segment );
//printf ("\tsegment=%s\n\text=%s\n", segment, extension );
}
else
{
old_extension = extension;
extension = g_strdup_printf( "%s.%s", old_extension, segment );
//printf ("\told_extension=%s\n\tsegment=%s\n\text=%s\n", old_extension, segment, extension );
g_free( old_extension );
}
}
g_free( segment );
if ( dot )
{
seg_start = ++dot;
dot = strchr( seg_start, '.' );
}
else
seg_start = NULL;
}
*ext = extension;
return name;
}
*/
void xset_free_all()
{
XSet* set;
GList* l;
for ( l = xsets; l; l = l->next )
{
set = l->data;
if ( set->ob2_data && g_str_has_prefix( set->name, "evt_" ) )
{
g_list_foreach( (GList*)set->ob2_data, (GFunc)g_free, NULL );
g_list_free( (GList*)set->ob2_data );
}
if ( set->name )
g_free( set->name );
if ( set->s )
g_free( set->s );
if ( set->x )
g_free( set->x );
if ( set->y )
g_free( set->y );
if ( set->z )
g_free( set->z );
if ( set->menu_label )
g_free( set->menu_label );
if ( set->shared_key )
g_free( set->shared_key );
if ( set->icon )
g_free( set->icon );
if ( set->desc )
g_free( set->desc );
if ( set->title )
g_free( set->title );
if ( set->next )
g_free( set->next );
if ( set->parent )
g_free( set->parent );
if ( set->child )
g_free( set->child );
if ( set->prev )
g_free( set->prev );
if ( set->line )
g_free( set->line );
if ( set->plugin )
{
if ( set->plug_dir )
g_free( set->plug_dir );
if ( set->plug_name )
g_free( set->plug_name );
}
g_slice_free( XSet, set );
}
g_list_free( xsets );
xsets = NULL;
set_last = NULL;
if ( xset_context )
{
xset_context_new();
g_slice_free( XSetContext, xset_context );
xset_context = NULL;
}
}
void xset_free( XSet* set )
{
if ( set->name )
g_free( set->name );
if ( set->s )
g_free( set->s );
if ( set->x )
g_free( set->x );
if ( set->y )
g_free( set->y );
if ( set->z )
g_free( set->z );
if ( set->menu_label )
g_free( set->menu_label );
if ( set->shared_key )
g_free( set->shared_key );
if ( set->icon )
g_free( set->icon );
if ( set->desc )
g_free( set->desc );
if ( set->title )
g_free( set->title );
if ( set->next )
g_free( set->next );
if ( set->parent )
g_free( set->parent );
if ( set->child )
g_free( set->child );
if ( set->prev )
g_free( set->prev );
if ( set->line )
g_free( set->line );
if ( set->plugin )
{
if ( set->plug_dir )
g_free( set->plug_dir );
if ( set->plug_name )
g_free( set->plug_name );
}
xsets = g_list_remove( xsets, set );
g_slice_free( XSet, set );
set_last = NULL;
}
XSet* xset_new( const char* name )
{
XSet* set = g_slice_new( XSet );
set->name = g_strdup( name );
set->b = XSET_B_UNSET;
set->s = NULL;
set->x = NULL;
set->y = NULL;
set->z = NULL;
set->disable = FALSE;
set->menu_label = NULL;
set->menu_style = XSET_MENU_NORMAL;
set->cb_func = NULL;
set->cb_data = NULL;
set->ob1 = NULL;
set->ob1_data = NULL;
set->ob2 = NULL;
set->ob2_data = NULL;
set->key = 0;
set->keymod = 0;
set->shared_key = NULL;
set->icon = NULL;
set->desc = NULL;
set->title = NULL;
set->next = NULL;
set->context = NULL;
set->tool = XSET_B_UNSET;
set->lock = TRUE;
set->plugin = FALSE;
// custom ( !lock )
set->prev = NULL;
set->parent = NULL;
set->child = NULL;
set->line = NULL;
set->task = XSET_B_UNSET;
set->task_pop = XSET_B_UNSET;
set->task_err = XSET_B_UNSET;
set->task_out = XSET_B_UNSET;
set->in_terminal = XSET_B_UNSET;
set->keep_terminal = XSET_B_UNSET;
set->scroll_lock = XSET_B_UNSET;
return set;
}
XSet* xset_get( const char* name )
{
GList* l;
if ( !name )
return NULL;
for ( l = xsets; l; l = l->next )
{
if ( !strcmp( name, ((XSet*)l->data)->name ) )
{
// existing xset
return l->data;
}
}
// add new
xsets = g_list_prepend( xsets, xset_new( name ) );
return xsets->data;
}
XSet* xset_get_panel( int panel, const char* name )
{
XSet* set;
char* fullname = g_strdup_printf( "panel%d_%s", panel, name );
set = xset_get( fullname );
g_free( fullname );
return set;
}
char* xset_get_s( const char* name )
{
XSet* set = xset_get( name );
if ( set )
return set->s;
else
return NULL;
}
char* xset_get_s_panel( int panel, const char* name )
{
char* fullname = g_strdup_printf( "panel%d_%s", panel, name );
char* s = xset_get_s( fullname );
g_free( fullname );
return s;
}
gboolean xset_get_b( const char* name )
{
XSet* set = xset_get( name );
return ( set->b == XSET_B_TRUE );
}
gboolean xset_get_b_panel( int panel, const char* name )
{
char* fullname = g_strdup_printf( "panel%d_%s", panel, name );
gboolean b = xset_get_b( fullname );
g_free( fullname );
return b;
}
gboolean xset_get_b_set( XSet* set )
{
return ( set->b == XSET_B_TRUE );
}
XSet* xset_is( const char* name )
{
XSet* set;
GList* l;
if ( !name )
return NULL;
for ( l = xsets; l; l = l->next )
{
if ( !strcmp( name, ((XSet*)l->data)->name ) )
{
// existing xset
return l->data;
}
}
return NULL;
}
XSet* xset_set_b( const char* name, gboolean bval )
{
XSet* set = xset_get( name );
if ( bval )
set->b = XSET_B_TRUE;
else
set->b = XSET_B_FALSE;
return set;
}
XSet* xset_set_b_panel( int panel, const char* name, gboolean bval )
{
char* fullname = g_strdup_printf( "panel%d_%s", panel, name );
XSet* set = xset_set_b( fullname, bval );
g_free( fullname );
return set;
}
gboolean xset_get_bool( const char* name, const char* var )
{
XSet* set = xset_get( name );
if ( !strcmp( var, "b" ) )
return ( set->b == XSET_B_TRUE );
if ( !strcmp( var, "disable" ) )
return set->disable;
if ( !strcmp( var, "style" ) )
return !!set->menu_style;
char* varstring = NULL;
if ( !strcmp( var, "x" ) )
varstring = set->x;
else if ( !strcmp( var, "y" ) )
varstring = set->y;
else if ( !strcmp( var, "z" ) )
varstring = set->z;
else if ( !strcmp( var, "s" ) )
varstring = set->s;
else if ( !strcmp( var, "desc" ) )
varstring = set->desc;
else if ( !strcmp( var, "title" ) )
varstring = set->title;
else if ( !strcmp( var, "label" ) )
varstring = set->menu_label;
else if ( !set->lock )
{
if ( !strcmp( var, "task" ) )
return ( set->task == XSET_B_TRUE );
if ( !strcmp( var, "task_pop" ) )
return ( set->task_pop == XSET_B_TRUE );
if ( !strcmp( var, "task-err" ) )
return ( set->task_err == XSET_B_TRUE );
if ( !strcmp( var, "task_out" ) )
return ( set->task_out == XSET_B_TRUE );
}
if ( !varstring )
return FALSE;
return !!atoi( varstring );
}
gboolean xset_get_bool_panel( int panel, const char* name, const char* var )
{
char* fullname = g_strdup_printf( "panel%d_%s", panel, name );
gboolean bool = xset_get_bool( fullname, var );
g_free( fullname );
return bool;
}
int xset_get_int( const char* name, const char* var )
{
XSet* set = xset_get( name );
char* varstring = NULL;
if ( !strcmp( var, "key" ) )
return set->key;
else if ( !strcmp( var, "keymod" ) )
return set->keymod;
else if ( !strcmp( var, "x" ) )
varstring = set->x;
else if ( !strcmp( var, "y" ) )
varstring = set->y;
else if ( !strcmp( var, "z" ) )
varstring = set->z;
else if ( !strcmp( var, "s" ) )
varstring = set->s;
if ( !varstring )
return 0;
return atoi( varstring );
}
int xset_get_int_panel( int panel, const char* name, const char* var )
{
char* fullname = g_strdup_printf( "panel%d_%s", panel, name );
int i = xset_get_int( fullname, var );
g_free( fullname );
return i;
}
static void xset_write_set( FILE* file, XSet* set )
{
if ( set->plugin )
return;
if ( set->s )
fprintf( file, "%s-s=%s\n", set->name, set->s );
if ( set->x )
fprintf( file, "%s-x=%s\n", set->name, set->x );
if ( set->y )
fprintf( file, "%s-y=%s\n", set->name, set->y );
if ( set->z )
fprintf( file, "%s-z=%s\n", set->name, set->z );
if ( set->key )
fprintf( file, "%s-key=%d\n", set->name, set->key );
if ( set->keymod )
fprintf( file, "%s-keymod=%d\n", set->name, set->keymod );
if ( set->icon )
fprintf( file, "%s-icon=%s\n", set->name, set->icon );
if ( set->menu_label )
fprintf( file, "%s-label=%s\n", set->name, set->menu_label );
if ( set->next )
fprintf( file, "%s-next=%s\n", set->name, set->next );
if ( set->child )
fprintf( file, "%s-child=%s\n", set->name, set->child );
if ( set->context )
fprintf( file, "%s-cxt=%s\n", set->name, set->context );
if ( set->b != XSET_B_UNSET )
fprintf( file, "%s-b=%d\n", set->name, set->b );
if ( set->tool != XSET_B_UNSET )
fprintf( file, "%s-tool=%d\n", set->name, set->tool );
if ( !set->lock )
{
if ( set->menu_style )
fprintf( file, "%s-style=%d\n", set->name, set->menu_style );
if ( set->desc )
fprintf( file, "%s-desc=%s\n", set->name, set->desc );
if ( set->title )
fprintf( file, "%s-title=%s\n", set->name, set->title );
if ( set->prev )
fprintf( file, "%s-prev=%s\n", set->name, set->prev );
if ( set->parent )
fprintf( file, "%s-parent=%s\n", set->name, set->parent );
if ( set->line )
fprintf( file, "%s-line=%s\n", set->name, set->line );
if ( set->task != XSET_B_UNSET )
fprintf( file, "%s-task=%d\n", set->name, set->task );
if ( set->task_pop != XSET_B_UNSET )
fprintf( file, "%s-task_pop=%d\n", set->name, set->task_pop );
if ( set->task_err != XSET_B_UNSET )
fprintf( file, "%s-task_err=%d\n", set->name, set->task_err );
if ( set->task_out != XSET_B_UNSET )
fprintf( file, "%s-task_out=%d\n", set->name, set->task_out );
if ( set->in_terminal != XSET_B_UNSET )
fprintf( file, "%s-term=%d\n", set->name, set->in_terminal );
if ( set->keep_terminal != XSET_B_UNSET )
fprintf( file, "%s-keep=%d\n", set->name, set->keep_terminal );
if ( set->scroll_lock != XSET_B_UNSET )
fprintf( file, "%s-scroll=%d\n", set->name, set->scroll_lock );
}
}
void xset_write( FILE* file )
{
GList* l;
if ( !file )
return;
for ( l = g_list_last( xsets ); l; l = l->prev )
xset_write_set( file, (XSet*)l->data );
}
void xset_parse( char* line )
{
char* sep = strchr( line, '=' );
char* name;
char* value;
if ( !sep )
return ;
name = line;
value = sep + 1;
*sep = '\0';
sep = strchr( name, '-' );
if ( !sep )
return ;
char* var = sep + 1;
*sep = '\0';
if ( !strncmp( name, "cstm_", 5 ) )
{
// custom
if ( !strcmp( set_last->name, name ) )
xset_set_set( set_last, var, value );
else
{
set_last = xset_set( name, var, value );
if ( set_last->lock )
set_last->lock = FALSE;
}
}
else
{
// normal
if ( !strcmp( set_last->name, name ) )
xset_set_set( set_last, var, value );
else
set_last = xset_set( name, var, value );
}
}
XSet* xset_set_cb( const char* name, void (*cb_func) (), gpointer cb_data )
{
XSet* set = xset_get( name );
set->cb_func = cb_func;
set->cb_data = cb_data;
return set;
}
XSet* xset_set_cb_panel( int panel, const char* name, void (*cb_func) (), gpointer cb_data )
{
char* fullname = g_strdup_printf( "panel%d_%s", panel, name );
XSet* set = xset_set_cb( fullname, cb_func, cb_data );
g_free( fullname );
return set;
}
XSet* xset_set_ob1_int( XSet* set, const char* ob1, int ob1_int )
{
if ( set->ob1 )
g_free( set->ob1 );
set->ob1 = g_strdup( ob1 );
set->ob1_data = GINT_TO_POINTER( ob1_int );
return set;
}
XSet* xset_set_ob1( XSet* set, const char* ob1, gpointer ob1_data )
{
if ( set->ob1 )
g_free( set->ob1 );
set->ob1 = g_strdup( ob1 );
set->ob1_data = ob1_data;
return set;
}
XSet* xset_set_ob2( XSet* set, const char* ob2, gpointer ob2_data )
{
if ( set->ob2 )
g_free( set->ob2 );
set->ob2 = g_strdup( ob2 );
set->ob2_data = ob2_data;
return set;
}
XSet* xset_set_set( XSet* set, const char* var, const char* value )
{
if ( !set )
return NULL;
if ( !strcmp( var, "label" ) )
{
if ( set->menu_label )
g_free( set->menu_label );
set->menu_label = g_strdup( value );
}
else if ( !strcmp( var, "style" ) )
{
set->menu_style = atoi( value );
}
else if ( !strcmp( var, "desc" ) )
{
if ( set->desc )
g_free( set->desc );
set->desc = g_strdup( value );
}
else if ( !strcmp( var, "title" ) )
{
if ( set->title )
g_free( set->title );
set->title = g_strdup( value );
}
else if ( !strcmp( var, "key" ) )
set->key = atoi( value );
else if ( !strcmp( var, "keymod" ) )
set->keymod = atoi( value );
else if ( !strcmp( var, "icon" ) )
{
if ( set->icon )
g_free( set->icon );
set->icon = g_strdup( value );
}
else if ( !strcmp( var, "s" ) )
{
if ( set->s )
g_free( set->s );
set->s = g_strdup( value );
}
else if ( !strcmp( var, "b" ) )
{
if ( !strcmp( value, "1" ) )
set->b = XSET_B_TRUE;
else
set->b = XSET_B_FALSE;
}
else if ( !strcmp( var, "x" ) )
{
if ( set->x )
g_free( set->x );
set->x = g_strdup( value );
}
else if ( !strcmp( var, "y" ) )
{
if ( set->y )
g_free( set->y );
set->y = g_strdup( value );
}
else if ( !strcmp( var, "z" ) )
{
if ( set->z )
g_free( set->z );
set->z = g_strdup( value );
}
else if ( !strcmp( var, "shared_key" ) )
{
if ( set->shared_key )
g_free( set->shared_key );
set->shared_key = g_strdup( value );
}
else if ( !strcmp( var, "next" ) )
{
if ( set->next )
g_free( set->next );
set->next = g_strdup( value );
}
else if ( !strcmp( var, "prev" ) )
{
if ( set->prev )
g_free( set->prev );
set->prev = g_strdup( value );
}
else if ( !strcmp( var, "parent" ) )
{
if ( set->parent )
g_free( set->parent );
set->parent = g_strdup( value );
}
else if ( !strcmp( var, "child" ) )
{
if ( set->child )
g_free( set->child );
set->child = g_strdup( value );
}
else if ( !strcmp( var, "cxt" ) )
{
if ( set->context )
g_free( set->context );
set->context = g_strdup( value );
}
else if ( !strcmp( var, "line" ) )
{
if ( set->line )
g_free( set->line );
set->line = g_strdup( value );
}
else if ( !strcmp( var, "tool" ) )
{
set->tool = atoi( value );
}
else if ( !strcmp( var, "task" ) )
{
if ( !strcmp( value, "1" ) )
set->task = XSET_B_TRUE;
else
set->task = XSET_B_UNSET;
}
else if ( !strcmp( var, "task_pop" ) )
{
if ( !strcmp( value, "1" ) )
set->task_pop = XSET_B_TRUE;
else
set->task_pop = XSET_B_UNSET;
}
else if ( !strcmp( var, "task_err" ) )
{
if ( !strcmp( value, "1" ) )
set->task_err = XSET_B_TRUE;
else
set->task_err = XSET_B_UNSET;
}
else if ( !strcmp( var, "task_out" ) )
{
if ( !strcmp( value, "1" ) )
set->task_out = XSET_B_TRUE;
else
set->task_out = XSET_B_UNSET;
}
else if ( !strcmp( var, "term" ) )
{
if ( !strcmp( value, "1" ) )
set->in_terminal = XSET_B_TRUE;
else
set->in_terminal = XSET_B_UNSET;
}
else if ( !strcmp( var, "keep" ) )
{
if ( !strcmp( value, "1" ) )
set->keep_terminal = XSET_B_TRUE;
else
set->keep_terminal = XSET_B_UNSET;
}
else if ( !strcmp( var, "scroll" ) )
{
if ( !strcmp( value, "1" ) )
set->scroll_lock = XSET_B_TRUE;
else
set->scroll_lock = XSET_B_UNSET;
}
else if ( !strcmp( var, "disable" ) )
{
if ( !strcmp( value, "1" ) )
set->disable = TRUE;
else
set->disable = FALSE;
}
return set;
}
XSet* xset_set( const char* name, const char* var, const char* value )
{
XSet* set = xset_get( name );
if ( !set->lock || ( strcmp( var, "style" ) && strcmp( var, "desc" )
&& strcmp( var, "title" ) && strcmp( var, "shared_key" ) ) )
return xset_set_set( set, var, value );
else
return set;
}
XSet* xset_set_panel( int panel, const char* name, const char* var, const char* value )
{
XSet* set;
char* fullname = g_strdup_printf( "panel%d_%s", panel, name );
set = xset_set( fullname, var, value );
g_free( fullname );
return set;
}
XSet* xset_find_menu( const char* menu_name )
{
XSet* set;
GList* l;
char* str;
char* name = clean_label( menu_name, TRUE, FALSE );
for ( l = xsets; l; l = l->next )
{
set = l->data;
if ( !set->lock && set->menu_style == XSET_MENU_SUBMENU && set->child )
{
str = clean_label( set->menu_label, TRUE, FALSE );
if ( !g_strcmp0( str, name ) )
{
g_free( str );
g_free( name );
return set;
}
g_free( str );
}
}
g_free( name );
return NULL;
}
void write_root_saver( FILE* file, const char* path, const char* name,
const char* var, const char* value )
{
if ( !value )
return;
char* save = g_strdup_printf( "%s-%s=%s", name, var, value );
char* qsave = bash_quote( save );
fprintf( file, "echo %s >> \"%s\"\n", qsave, path );
g_free( save );
g_free( qsave );
}
gboolean write_root_settings( FILE* file, const char* path )
{
GList* l;
XSet* set;
if ( !file )
return FALSE;
fprintf( file, "\n# save root settings\nmkdir -p /etc/spacefm\necho -e '# SpaceFM As-Root Session File\\n\\n# THIS FILE IS NOT DESIGNED TO BE EDITED\\n\\n' > '%s'\n", path );
for ( l = xsets ; l; l = l->next )
{
set = l->data;
if ( set )
{
if ( !strcmp( set->name, "root_editor" )
|| !strcmp( set->name, "dev_back_fsarc" )
|| !strcmp( set->name, "dev_back_part" )
|| !strcmp( set->name, "dev_rest_file" )
|| !strcmp( set->name, "dev_root_check" )
|| !strcmp( set->name, "dev_root_mount" )
|| !strcmp( set->name, "dev_root_unmount" )
|| !strcmp( set->name, "main_terminal" )
|| !strncmp( set->name, "dev_fmt_", 8 )
|| !strncmp( set->name, "label_cmd_", 8 ) )
{
write_root_saver( file, path, set->name, "s", set->s );
write_root_saver( file, path, set->name, "x", set->x );
write_root_saver( file, path, set->name, "y", set->y );
if ( set->b != XSET_B_UNSET )
fprintf( file, "echo '%s-b=%d' >> \"%s\"\n",
set->name, set->b, path );
}
}
}
// create spacefm.conf
if ( !g_file_test( "/etc/spacefm/spacefm.conf", G_FILE_TEST_EXISTS ) )
{
fprintf( file, "echo \"# spacefm.conf\" >> /etc/spacefm/spacefm.conf\n" );
fprintf( file, "echo >> /etc/spacefm/spacefm.conf\n" );
fprintf( file, "echo \"# tmp_dir should be a root-protected user-writable dir like /tmp\" >> /etc/spacefm/spacefm.conf\n" );
fprintf( file, "echo \"# tmp_dir must NOT contain spaces or special chars - keep it simple\" >> /etc/spacefm/spacefm.conf\n" );
fprintf( file, "echo \"# tmp_dir=/tmp\" >> /etc/spacefm/spacefm.conf\n" );
}
fprintf( file, "chmod -R go-w+rX /etc/spacefm\n\n" );
return TRUE;
}
void read_root_settings()
{
GList* l;
XSet* set;
FILE* file;
char line[ 2048 ];
if ( geteuid() == 0 )
return;
char* root_set_path= g_strdup_printf(
"/etc/spacefm/%s-as-root", g_get_user_name() );
if ( !g_file_test( root_set_path, G_FILE_TEST_EXISTS ) )
{
g_free( root_set_path );
root_set_path= g_strdup_printf(
"/etc/spacefm/%d-as-root", geteuid() );
}
file = fopen( root_set_path, "r" );
if ( !file )
{
if ( g_file_test( root_set_path, G_FILE_TEST_EXISTS ) )
g_warning( _("Error reading root settings from /etc/spacefm/ Commands run as root may present a security risk") );
else
g_warning( _("No root settings found in /etc/spacefm/ Setting a root editor in Preferences should remove this warning on startup. Otherwise commands run as root may present a security risk.") );
g_free( root_set_path );
return;
}
g_free( root_set_path );
// clear settings
for ( l = xsets ; l; l = l->next )
{
set = l->data;
if ( set )
{
if ( !strcmp( set->name, "root_editor" )
|| !strcmp( set->name, "dev_back_fsarc" )
|| !strcmp( set->name, "dev_back_part" )
|| !strcmp( set->name, "dev_rest_file" )
|| !strcmp( set->name, "dev_root_check" )
|| !strcmp( set->name, "dev_root_mount" )
|| !strcmp( set->name, "dev_root_unmount" )
|| !strncmp( set->name, "dev_fmt_", 8 )
|| !strncmp( set->name, "label_cmd_", 8 ) )
{
if ( set->s ) { g_free( set->s ); set->s = NULL; }
if ( set->x ) { g_free( set->x ); set->x = NULL; }
if ( set->y ) { g_free( set->y ); set->y = NULL; }
set->b = XSET_B_UNSET;
}
}
}
while ( fgets( line, sizeof( line ), file ) )
{
strtok( line, "\r\n" );
if ( !line[ 0 ] )
continue;
xset_parse( line );
}
fclose( file );
}
void write_src_functions( FILE* file )
{
fputs( "\nfm_randhex4() # generate a four digit random hex number\n{\n fm_rand1=$RANDOM\n fm_rand2=$RANDOM\n (( fm_rand = fm_rand1 + fm_rand2 ))\n let \"fm_rand \%= 65536\"\n fm_randhex=`printf \"\%04X\" $fm_rand | tr A-Z a-z`\n if [ \"$fm_randhex\" = \"\" ]; then\n fm_randhex=$RANDOM # failsafe\n fi\n}\n\nfm_new_tmp()\n{\n fm_randhex4\n fm_tmp1=\"$fm_tmp_dir/$$-$fm_randhex.tmp\"\n fm_count1=0\n while ! mkdir \"$fm_tmp1\" 2>/dev/null; do\n fm_randhex4\n fm_tmp1=\"$fm_tmp_dir/$$-$fm_randhex.tmp\"\n if (( fm_count1++ > 1000 )); then\n echo 'spacefm: error creating temporary directory' 1>&2\n unset fm_tmp1 fm_randhex fm_count1\n echo \"\"\n return 1\n fi\n done\n echo \"$fm_tmp1\"\n unset fm_tmp1 fm_randhex fm_count1\n}\n\nfm_edit()\n{\n spacefm -s set edit_file \"$1\"\n}\n\n", file );
}
GtkWidget* xset_get_image( const char* icon, int icon_size )
{
/*
GTK_ICON_SIZE_MENU,
GTK_ICON_SIZE_SMALL_TOOLBAR,
GTK_ICON_SIZE_LARGE_TOOLBAR,
GTK_ICON_SIZE_BUTTON,
GTK_ICON_SIZE_DND,
GTK_ICON_SIZE_DIALOG
*/
GtkWidget* image = NULL;
gchar* stockid = NULL;
const char* icontail;
if ( !icon || icon[0] == '\0' )
return NULL;
if ( !icon_size )
icon_size = GTK_ICON_SIZE_MENU;
if ( g_str_has_prefix( icon, "gtk-" ) )
image = gtk_image_new_from_stock( icon, icon_size );
else if ( !strncmp( icon, "GTK_STOCK_", 10 ) )
{
icontail = icon + 10;
if ( !strcmp( icontail, "ABOUT" ) )
stockid = GTK_STOCK_ABOUT;
else if ( !strcmp( icontail, "ADD" ) )
stockid = GTK_STOCK_ADD;
else if ( !strcmp( icontail, "APPLY" ) )
stockid = GTK_STOCK_APPLY;
else if ( !strcmp( icontail, "BOLD" ) )
stockid = GTK_STOCK_BOLD;
else if ( !strcmp( icontail, "CANCEL" ) )
stockid = GTK_STOCK_CANCEL;
else if ( !strcmp( icontail, "CDROM" ) )
stockid = GTK_STOCK_CDROM;
else if ( !strcmp( icontail, "CLEAR" ) )
stockid = GTK_STOCK_CLEAR;
else if ( !strcmp( icontail, "CLOSE" ) )
stockid = GTK_STOCK_CLOSE;
else if ( !strcmp( icontail, "CONVERT" ) )
stockid = GTK_STOCK_CONVERT;
else if ( !strcmp( icontail, "CONNECT" ) )
stockid = GTK_STOCK_CONNECT;
else if ( !strcmp( icontail, "COPY" ) )
stockid = GTK_STOCK_COPY;
else if ( !strcmp( icontail, "CUT" ) )
stockid = GTK_STOCK_CUT;
else if ( !strcmp( icontail, "DELETE" ) )
stockid = GTK_STOCK_DELETE;
else if ( !strcmp( icontail, "DIALOG_ERROR" ) )
stockid = GTK_STOCK_DIALOG_ERROR;
else if ( !strcmp( icontail, "DIALOG_INFO" ) )
stockid = GTK_STOCK_DIALOG_INFO;
else if ( !strcmp( icontail, "DIALOG_QUESTION" ) )
stockid = GTK_STOCK_DIALOG_QUESTION;
else if ( !strcmp( icontail, "DIALOG_WARNING" ) )
stockid = GTK_STOCK_DIALOG_WARNING;
else if ( !strcmp( icontail, "DIRECTORY" ) )
stockid = GTK_STOCK_DIRECTORY;
else if ( !strcmp( icontail, "DISCARD" ) )
stockid = GTK_STOCK_DISCARD;
else if ( !strcmp( icontail, "DISCONNECT" ) )
stockid = GTK_STOCK_DISCONNECT;
else if ( !strcmp( icontail, "DND" ) )
stockid = GTK_STOCK_DND;
else if ( !strcmp( icontail, "DND_MULTIPLE" ) )
stockid = GTK_STOCK_DND_MULTIPLE;
else if ( !strcmp( icontail, "EDIT" ) )
stockid = GTK_STOCK_EDIT;
else if ( !strcmp( icontail, "EXECUTE" ) )
stockid = GTK_STOCK_EXECUTE;
else if ( !strcmp( icontail, "FILE" ) )
stockid = GTK_STOCK_FILE;
else if ( !strcmp( icontail, "FIND" ) )
stockid = GTK_STOCK_FIND;
else if ( !strcmp( icontail, "FIND_AND_REPLACE" ) )
stockid = GTK_STOCK_FIND_AND_REPLACE;
else if ( !strcmp( icontail, "FLOPPY" ) )
stockid = GTK_STOCK_FLOPPY;
else if ( !strcmp( icontail, "FULLSCREEN" ) )
stockid = GTK_STOCK_FULLSCREEN;
else if ( !strcmp( icontail, "GOTO_BOTTOM" ) )
stockid = GTK_STOCK_GOTO_BOTTOM;
else if ( !strcmp( icontail, "GOTO_FIRST" ) )
stockid = GTK_STOCK_GOTO_FIRST;
else if ( !strcmp( icontail, "GOTO_LAST" ) )
stockid = GTK_STOCK_GOTO_LAST;
else if ( !strcmp( icontail, "GOTO_TOP" ) )
stockid = GTK_STOCK_GOTO_TOP;
else if ( !strcmp( icontail, "GO_BACK" ) )
stockid = GTK_STOCK_GO_BACK;
else if ( !strcmp( icontail, "GO_DOWN" ) )
stockid = GTK_STOCK_GO_DOWN;
else if ( !strcmp( icontail, "GO_FORWARD" ) )
stockid = GTK_STOCK_GO_FORWARD;
else if ( !strcmp( icontail, "GO_UP" ) )
stockid = GTK_STOCK_GO_UP;
else if ( !strcmp( icontail, "HARDDISK" ) )
stockid = GTK_STOCK_HARDDISK;
else if ( !strcmp( icontail, "HELP" ) )
stockid = GTK_STOCK_HELP;
else if ( !strcmp( icontail, "HOME" ) )
stockid = GTK_STOCK_HOME;
else if ( !strcmp( icontail, "INDENT" ) )
stockid = GTK_STOCK_INDENT;
else if ( !strcmp( icontail, "INDEX" ) )
stockid = GTK_STOCK_INDEX;
else if ( !strcmp( icontail, "INFO" ) )
stockid = GTK_STOCK_INFO;
else if ( !strcmp( icontail, "ITALIC" ) )
stockid = GTK_STOCK_ITALIC;
else if ( !strcmp( icontail, "JUMP_TO" ) )
stockid = GTK_STOCK_JUMP_TO;
else if ( !strcmp( icontail, "MEDIA_FORWARD" ) )
stockid = GTK_STOCK_MEDIA_FORWARD;
else if ( !strcmp( icontail, "MEDIA_NEXT" ) )
stockid = GTK_STOCK_MEDIA_NEXT;
else if ( !strcmp( icontail, "MEDIA_PAUSE" ) )
stockid = GTK_STOCK_MEDIA_PAUSE;
else if ( !strcmp( icontail, "MEDIA_PLAY" ) )
stockid = GTK_STOCK_MEDIA_PLAY;
else if ( !strcmp( icontail, "MEDIA_PREVIOUS" ) )
stockid = GTK_STOCK_MEDIA_PREVIOUS;
else if ( !strcmp( icontail, "MEDIA_RECORD" ) )
stockid = GTK_STOCK_MEDIA_RECORD;
else if ( !strcmp( icontail, "MEDIA_REWIND" ) )
stockid = GTK_STOCK_MEDIA_REWIND;
else if ( !strcmp( icontail, "MEDIA_STOP" ) )
stockid = GTK_STOCK_MEDIA_STOP;
else if ( !strcmp( icontail, "NETWORK" ) )
stockid = GTK_STOCK_NETWORK;
else if ( !strcmp( icontail, "NEW" ) )
stockid = GTK_STOCK_NEW;
else if ( !strcmp( icontail, "NO" ) )
stockid = GTK_STOCK_NO;
else if ( !strcmp( icontail, "OK" ) )
stockid = GTK_STOCK_OK;
else if ( !strcmp( icontail, "OPEN" ) )
stockid = GTK_STOCK_OPEN;
else if ( !strcmp( icontail, "PAGE_SETUP" ) )
stockid = GTK_STOCK_PAGE_SETUP;
else if ( !strcmp( icontail, "PASTE" ) )
stockid = GTK_STOCK_PASTE;
else if ( !strcmp( icontail, "PREFERENCES" ) )
stockid = GTK_STOCK_PREFERENCES;
else if ( !strcmp( icontail, "PRINT" ) )
stockid = GTK_STOCK_PRINT;
else if ( !strcmp( icontail, "PROPERTIES" ) )
stockid = GTK_STOCK_PROPERTIES;
else if ( !strcmp( icontail, "QUIT" ) )
stockid = GTK_STOCK_QUIT;
else if ( !strcmp( icontail, "REDO" ) )
stockid = GTK_STOCK_REDO;
else if ( !strcmp( icontail, "REFRESH" ) )
stockid = GTK_STOCK_REFRESH;
else if ( !strcmp( icontail, "REMOVE" ) )
stockid = GTK_STOCK_REMOVE;
else if ( !strcmp( icontail, "REVERT_TO_SAVED" ) )
stockid = GTK_STOCK_REVERT_TO_SAVED;
else if ( !strcmp( icontail, "SAVE" ) )
stockid = GTK_STOCK_SAVE;
else if ( !strcmp( icontail, "SAVE_AS" ) )
stockid = GTK_STOCK_SAVE_AS;
else if ( !strcmp( icontail, "SELECT_ALL" ) )
stockid = GTK_STOCK_SELECT_ALL;
else if ( !strcmp( icontail, "SELECT_COLOR" ) )
stockid = GTK_STOCK_SELECT_COLOR;
else if ( !strcmp( icontail, "SELECT_FONT" ) )
stockid = GTK_STOCK_SELECT_FONT;
else if ( !strcmp( icontail, "SORT_ASCENDING" ) )
stockid = GTK_STOCK_SORT_ASCENDING;
else if ( !strcmp( icontail, "SORT_DESCENDING" ) )
stockid = GTK_STOCK_SORT_DESCENDING;
else if ( !strcmp( icontail, "SPELL_CHECK" ) )
stockid = GTK_STOCK_SPELL_CHECK;
else if ( !strcmp( icontail, "STOP" ) )
stockid = GTK_STOCK_STOP;
else if ( !strcmp( icontail, "STRIKETHROUGH" ) )
stockid = GTK_STOCK_STRIKETHROUGH;
else if ( !strcmp( icontail, "UNDELETE" ) )
stockid = GTK_STOCK_UNDELETE;
else if ( !strcmp( icontail, "UNDERLINE" ) )
stockid = GTK_STOCK_UNDERLINE;
else if ( !strcmp( icontail, "UNDO" ) )
stockid = GTK_STOCK_UNDO;
else if ( !strcmp( icontail, "UNINDENT" ) )
stockid = GTK_STOCK_UNINDENT;
else if ( !strcmp( icontail, "YES" ) )
stockid = GTK_STOCK_YES;
else if ( !strcmp( icontail, "ZOOM_100" ) )
stockid = GTK_STOCK_ZOOM_100;
else if ( !strcmp( icontail, "ZOOM_FIT" ) )
stockid = GTK_STOCK_ZOOM_FIT;
else if ( !strcmp( icontail, "ZOOM_IN" ) )
stockid = GTK_STOCK_ZOOM_IN;
else if ( !strcmp( icontail, "ZOOM_OUT" ) )
stockid = GTK_STOCK_ZOOM_OUT;
else if ( !strcmp( icontail, "DIALOG_AUTHENTICATION" ) )
stockid = GTK_STOCK_DIALOG_AUTHENTICATION;
else
stockid = NULL;
if ( stockid )
image = gtk_image_new_from_stock( stockid, icon_size );
}
else if ( icon[0] == '/' )
image = gtk_image_new_from_file( icon );
else
image = gtk_image_new_from_icon_name( icon, icon_size );
return image;
}
void xset_add_menu( DesktopWindow* desktop, PtkFileBrowser* file_browser,
GtkWidget* menu, GtkAccelGroup *accel_group, char* elements )
{
char* space;
XSet* set;
if ( !elements )
return;
while ( elements[0] == ' ' )
elements++;
while ( elements && elements[0] != '\0' )
{
space = strchr( elements, ' ' );
if ( space )
space[0] = '\0';
set = xset_get( elements );
if ( space )
space[0] = ' ';
elements = space;
xset_add_menuitem( desktop, file_browser, menu, accel_group, set );
if ( elements )
{
while ( elements[0] == ' ' )
elements++;
}
}
}
GtkWidget* xset_new_menuitem( const char* label, const char* icon )
{
GtkWidget* image = NULL;
GtkWidget* item;
if ( !icon || icon[0] == '\0' )
return gtk_image_menu_item_new_with_mnemonic( label );
image = xset_get_image( icon, GTK_ICON_SIZE_MENU );
if ( !image )
return gtk_image_menu_item_new_with_mnemonic( label );
item = gtk_image_menu_item_new_with_mnemonic( label );
gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM(item), image );
return item;
}
/*
gboolean xset_design_event_cb (GtkWidget *widget, GdkEvent *gdk_event , XSet* set)
{
GdkEventButton* event = (GdkEventButton*)gdk_event;
printf("xset_design_event_cb type=%d button=%d state=%d\n", event->type, event->button, event->state );
if ( event->type == 10 )
{
//return TRUE;
}
else if ( event->type == GDK_BUTTON_PRESS )
{
// printf(" button_press\n");
if ( ((GdkEventButton*)event)->state & GDK_CONTROL_MASK
|| ((GdkEventButton*)event)->button == 2 )
{
printf(" DESIGN\n");
return TRUE;
}
}
return FALSE; // pass through
}
*/
/*
void xset_design_activate_item( GtkMenuItem* item, XSet* set )
{
if ( design_mode )
{
g_signal_stop_emission_by_name( item, "activate" );
//g_signal_stop_emission_by_name( item, "activate-item" );
printf("design_mode_activate\n");
}
}
*/
GtkWidget* xset_add_menuitem( DesktopWindow* desktop, PtkFileBrowser* file_browser,
GtkWidget* menu, GtkAccelGroup *accel_group,
XSet* set )
{
GtkWidget* item = NULL;
GtkWidget* submenu;
XSet* keyset;
XSet* set_next;
char* icon_name = NULL;
char* context = NULL;
int context_action = CONTEXT_SHOW;
XSet* mset;
char* icon_file = NULL;
//printf("xset_add_menuitem %s\n", set->name );
// plugin?
mset = xset_get_plugin_mirror( set );
if ( set->plugin && set->shared_key )
{
icon_name = mset->icon;
context = mset->context;
}
if ( !icon_name )
icon_name = set->icon;
if ( !icon_name )
{
if ( set->plugin )
icon_file = g_build_filename( set->plug_dir, set->plug_name, "icon",
NULL );
else
icon_file = g_build_filename( settings_config_dir, "scripts",
set->name, "icon", NULL );
if ( !g_file_test( icon_file, G_FILE_TEST_EXISTS ) )
{
g_free( icon_file );
icon_file = NULL;
}
else
icon_name = icon_file;
}
if ( !context )
context = set->context;
// context?
if ( context && !set->tool && xset_context && xset_context->valid &&
!xset_get_b( "context_dlg" ) )
context_action = xset_context_test( context, set->disable );
if ( context_action != CONTEXT_HIDE )
{
if ( set->tool && set->menu_style != XSET_MENU_SUBMENU )
{
item = xset_new_menuitem( set->menu_label, icon_name );
}
else if ( set->menu_style )
{
if ( set->menu_style == XSET_MENU_CHECK )
{
item = gtk_check_menu_item_new_with_mnemonic( set->menu_label );
gtk_check_menu_item_set_active( GTK_CHECK_MENU_ITEM( item ),
mset->b == XSET_B_TRUE );
}
else if ( set->menu_style == XSET_MENU_RADIO )
{
XSet* set_radio;
if ( set->ob2_data )
set_radio = (XSet*)set->ob2_data;
else
set_radio = set;
item = gtk_radio_menu_item_new_with_mnemonic(
(GSList*)set_radio->ob2_data,
set->menu_label );
set_radio->ob2_data = (gpointer)gtk_radio_menu_item_get_group(
GTK_RADIO_MENU_ITEM( item ) );
gtk_check_menu_item_set_active( GTK_CHECK_MENU_ITEM( item ),
mset->b == XSET_B_TRUE );
}
else if ( set->menu_style == XSET_MENU_SUBMENU )
{
submenu = gtk_menu_new();
item = xset_new_menuitem( set->menu_label, icon_name );
gtk_menu_item_set_submenu( GTK_MENU_ITEM( item ), submenu );
g_signal_connect( submenu, "key-press-event",
G_CALLBACK( xset_menu_keypress ), NULL );
if ( set->lock )
xset_add_menu( desktop, file_browser, submenu, accel_group, set->desc );
else if ( set->child )
{
set_next = xset_get( set->child );
xset_add_menuitem( desktop, file_browser, submenu, accel_group, set_next );
GList* l = gtk_container_get_children( GTK_CONTAINER( submenu ) );
if ( l )
g_list_free( l );
else
{
// Nothing was added to the menu (all items likely have
// invisible context) so destroy (hide) - issue #215
gtk_widget_destroy( item );
goto _next_item;
}
}
}
else if ( set->menu_style == XSET_MENU_SEP )
{
item = gtk_separator_menu_item_new();
}
}
if ( !item )
item = xset_new_menuitem( set->menu_label, icon_name );
if ( set->tool && set->tool == XSET_B_TRUE )
{
char* ml = g_strdup_printf( "%s *", set->menu_label );
gtk_menu_item_set_label( GTK_MENU_ITEM( item ), ml );
g_free( ml );
}
set->desktop = desktop;
set->browser = file_browser;
g_object_set_data( G_OBJECT( item ), "menu", menu );
g_object_set_data( G_OBJECT( item ), "set", set );
if ( set->ob1 )
g_object_set_data( G_OBJECT( item ), set->ob1, set->ob1_data );
if ( set->menu_style != XSET_MENU_RADIO && set->ob2 )
g_object_set_data( G_OBJECT( item ), set->ob2, set->ob2_data );
if ( set->menu_style < XSET_MENU_SUBMENU )
{
// activate callback
if ( !set->cb_func || set->menu_style )
{
// use xset menu callback
//if ( !design_mode )
//{
g_signal_connect( item, "activate", G_CALLBACK( xset_menu_cb ), set );
g_object_set_data( G_OBJECT(item), "cb_func", set->cb_func );
g_object_set_data( G_OBJECT(item), "cb_data", set->cb_data );
//}
}
else if ( set->cb_func )
{
// use custom callback directly
//if ( !design_mode )
g_signal_connect( item, "activate", G_CALLBACK( set->cb_func ), set->cb_data );
}
// key accel
if ( set->shared_key )
keyset = xset_get( set->shared_key );
else
keyset = set;
if ( keyset->key > 0 && accel_group )
gtk_widget_add_accelerator( item, "activate", accel_group,
keyset->key, keyset->keymod, GTK_ACCEL_VISIBLE);
}
// design mode callback
g_signal_connect( item, "button-press-event", G_CALLBACK( xset_design_cb ), set );
g_signal_connect( item, "button-release-event", G_CALLBACK( xset_design_cb ), set );
gtk_widget_set_sensitive( item, context_action != CONTEXT_DISABLE &&
!set->disable );
gtk_menu_shell_append( GTK_MENU_SHELL(menu), item );
}
_next_item:
if ( icon_file )
g_free( icon_file );
// next item
if ( set->next )
{
set_next = xset_get( set->next );
xset_add_menuitem( desktop, file_browser, menu, accel_group, set_next );
}
return item;
}
char* xset_custom_get_script( XSet* set, gboolean create )
{
char* path;
char* old_path;
char* cscript;
if ( strncmp( set->name, "cstm_", 5 ) || ( create && set->plugin ) )
return NULL;
if ( create )
{
path = g_build_filename( settings_config_dir, "scripts", set->name, NULL );
if ( !g_file_test( path, G_FILE_TEST_EXISTS ) )
{
g_mkdir_with_parents( path, 0700 );
chmod( path, 0700 );
}
g_free( path );
}
if ( set->plugin )
{
path = g_build_filename( set->plug_dir, set->plug_name, "exec.sh", NULL );
}
else
{
path = g_build_filename( settings_config_dir, "scripts", set->name,
"exec.sh", NULL );
}
if ( !g_file_test( path, G_FILE_TEST_EXISTS ) )
{
// backwards compatible < 0.7.0
if ( set->plugin )
{
cscript = g_strdup_printf( "%s.sh", set->plug_name );
old_path = g_build_filename( set->plug_dir, "files", cscript, NULL );
g_free( cscript );
g_free( path );
return old_path;
}
else
{
cscript = g_strdup_printf( "%s.sh", set->name );
old_path = g_build_filename( settings_config_dir, "scripts",
cscript, NULL );
}
g_free( cscript );
if ( g_file_test( old_path, G_FILE_TEST_EXISTS ) )
{
// copy old location to new
char* new_dir = g_build_filename( settings_config_dir, "scripts",
set->name, NULL );
if ( !g_file_test( new_dir, G_FILE_TEST_EXISTS ) )
{
g_mkdir_with_parents( new_dir, 0700 );
chmod( new_dir, 0700 );
}
g_free( new_dir );
xset_copy_file( old_path, path );
chmod( path, S_IRUSR | S_IWUSR | S_IXUSR );
}
g_free( old_path );
}
if ( create && !g_file_test( path, G_FILE_TEST_EXISTS ) )
{
old_path = g_build_filename( settings_config_dir, "scripts",
"default-script", NULL );
if ( g_file_test( old_path, G_FILE_TEST_EXISTS ) )
xset_copy_file( old_path, path );
else
{
FILE* file;
int i;
const char* script_default_head = "#!/bin/bash\n$fm_import # import file manager variables (scroll down for info)\n#\n# Enter your commands here: ( then save this file )\n";
const char* script_default_tail = "exit $?\n# Example variables available for use: (imported by $fm_import)\n# These variables represent the state of the file manager when command is run.\n# These variables can also be used in command lines and in the Path Bar.\n\n# \"${fm_files[@]}\" selected files ( same as %F )\n# \"$fm_file\" first selected file ( same as %f )\n# \"${fm_files[2]}\" third selected file\n\n# \"${fm_filenames[@]}\" selected filenames ( same as %N )\n# \"$fm_filename\" first selected filename ( same as %n )\n\n# \"$fm_pwd\" current directory ( same as %d )\n# \"${fm_pwd_tab[4]}\" current directory of tab 4\n# $fm_panel current panel number (1-4)\n# $fm_tab current tab number\n\n# \"${fm_panel3_files[@]}\" selected files in panel 3\n# \"${fm_pwd_panel[3]}\" current directory in panel 3\n# \"${fm_pwd_panel3_tab[2]}\" current directory in panel 3 tab 2\n# ${fm_tab_panel[3]} current tab number in panel 3\n\n# \"${fm_desktop_files[@]}\" selected files on desktop (when run from desktop)\n# \"$fm_desktop_pwd\" desktop directory (eg '/home/user/Desktop')\n\n# \"$fm_device\" selected device (eg /dev/sr0) ( same as %v )\n# \"$fm_device_udi\" device ID\n# \"$fm_device_mount_point\" device mount point if mounted (eg /media/dvd) (%m)\n# \"$fm_device_label\" device volume label ( same as %l )\n# \"$fm_device_fstype\" device fs_type (eg vfat)\n# \"$fm_device_size\" device volume size in bytes\n# \"$fm_device_display_name\" device display name\n# \"$fm_device_icon\" icon currently shown for this device\n# $fm_device_is_mounted device is mounted (0=no or 1=yes)\n# $fm_device_is_optical device is an optical drive (0 or 1)\n# $fm_device_is_table a partition table (usually a whole device)\n# $fm_device_is_floppy device is a floppy drive (0 or 1)\n# $fm_device_is_removable device appears to be removable (0 or 1)\n# $fm_device_is_audiocd optical device contains an audio CD (0 or 1)\n# $fm_device_is_dvd optical device contains a DVD (0 or 1)\n# $fm_device_is_blank device contains blank media (0 or 1)\n# $fm_device_is_mountable device APPEARS to be mountable (0 or 1)\n# $fm_device_nopolicy policy_noauto set (no automount) (0 or 1)\n\n# \"$fm_panel3_device\" panel 3 selected device (eg /dev/sdd1)\n# \"$fm_panel3_device_udi\" panel 3 device ID\n# ... (all these are the same as above for each panel)\n\n# \"fm_bookmark\" selected bookmark directory ( same as %b )\n# \"fm_panel3_bookmark\" panel 3 selected bookmark directory\n\n# \"fm_task_type\" currently SELECTED task type (eg 'run','copy')\n# \"fm_task_name\" selected task name (custom menu item name)\n# \"fm_task_pwd\" selected task working directory ( same as %t )\n# \"fm_task_pid\" selected task pid ( same as %p )\n# \"fm_task_command\" selected task command\n# \"fm_task_id\" selected task id\n# \"fm_task_window\" selected task window id\n\n# \"$fm_command\" current command\n# \"$fm_value\" menu item value ( same as %a )\n# \"$fm_user\" original user who ran this command\n# \"$fm_my_task\" current task's id (see 'spacefm -s help')\n# \"$fm_my_window\" current task's window id\n# \"$fm_cmd_name\" menu name of current command\n# \"$fm_cmd_dir\" command files directory (for read only)\n# \"$fm_cmd_data\" command data directory (must create)\n# To create: mkdir -p \"$fm_cmd_data\"\n# \"$fm_plugin_dir\" top plugin directory\n# tmp=\"$(fm_new_tmp)\" makes new temp directory (destroy when done)\n# To destroy: rm -rf \"$tmp\"\n# fm_edit \"FILE\" open FILE in user's configured editor\n\n# $fm_import command to import above variables (this\n# variable is exported so you can use it in any\n# script run from this script)\n\n\n# Script Example 1:\n\n# # show MD5 sums of selected files\n# md5sum \"${fm_files[@]}\"\n\n\n# Script Example 2:\n\n# # Show a confirmation dialog using SpaceFM Dialog:\n# # http://ignorantguru.github.com/spacefm/spacefm-manual-en.html#dialog\n# # Use QUOTED eval to read variables output by SpaceFM Dialog:\n# eval \"`spacefm -g --label \"Are you sure?\" --button yes --button no`\"\n# if [[ \"$dialog_pressed\" == \"button1\" ]]; then\n# echo \"User pressed Yes - take some action\"\n# else\n# echo \"User did NOT press Yes - abort\"\n# fi\n\n\n# Script Example 3:\n\n# # Build list of filenames in panel 4:\n# i=0\n# for f in \"${fm_panel4_files[@]}\"; do\n# panel4_names[$i]=\"$(basename \"$f\")\"\n# (( i++ ))\n# done\n# echo \"${panel4_names[@]}\"\n\n\n# Script Example 4:\n\n# # Copy selected files to panel 2\n# # make sure panel 2 is visible ?\n# # and files are selected ?\n# # and current panel isn't 2 ?\n# if [ \"${fm_pwd_panel[2]}\" != \"\" ] \\\n# && [ \"${fm_files[0]}\" != \"\" ] \\\n# && [ \"$fm_panel\" != 2 ]; then\n# cp \"${fm_files[@]}\" \"${fm_pwd_panel[2]}\"\n# else\n# echo \"Can't copy to panel 2\"\n# exit 1 # shows error if 'Popup Error' enabled\n# fi\n\n\n# Script Example 5:\n\n# # Keep current time in task manager list Item column\n# # See http://ignorantguru.github.com/spacefm/spacefm-manual-en.html#sockets\n# while (( 1 )); do\n# sleep 0.7\n# spacefm -s set-task $fm_my_task item \"$(date)\"\n# done\n\n\n# Bash Scripting Guide: http://www.tldp.org/LDP/abs/html/index.html\n\n# NOTE: Additional variables or examples may be available in future versions.\n# To see the latest list, create a new command script or see:\n# http://ignorantguru.github.com/spacefm/spacefm-manual-en.html#exvar\n\n";
file = fopen( path, "w" );
if ( file )
{
// write default script
fputs( script_default_head, file );
for ( i = 0; i < 26; i++ )
fputs( "\n", file );
fputs( script_default_tail, file );
fclose( file );
}
}
chmod( path, S_IRUSR | S_IWUSR | S_IXUSR );
g_free( old_path );
}
return path;
}
char* xset_custom_get_help( XSet* set )
{
char* dir;
char* path;
if ( !set || ( set && strncmp( set->name, "cstm_", 5 ) ) )
return NULL;
if ( set->plugin )
dir = g_build_filename( set->plug_dir, set->plug_name, NULL );
else
{
dir = g_build_filename( settings_config_dir, "scripts", set->name, NULL );
if ( !g_file_test( dir, G_FILE_TEST_EXISTS ) )
{
g_mkdir_with_parents( dir, 0700 );
chmod( dir, 0700 );
}
}
char* names[] = { "README", "readme", "README.TXT", "README.txt", "readme.txt", "README.MKD", "README.mkd", "readme.mkd" };
int i;
for ( i = 0; i < G_N_ELEMENTS( names ); ++i )
{
path = g_build_filename( dir, names[i], NULL );
if ( g_file_test( path, G_FILE_TEST_EXISTS ) )
break;
g_free( path );
path = NULL;
}
if ( !path )
{
if ( set->plugin )
{
g_free( dir );
return NULL;
}
// create
path = g_build_filename( dir, names[0], NULL );
FILE* file = fopen( path, "w" );
if ( file )
{
// write default readme
fputs( "README\n------\n\nFill this text file with detailed information about this command. For\ncontext-sensitive help within SpaceFM, this file must be named README,\nREADME.txt, or README.mkd.\n\nIf you plan to distribute this command as a plugin, the following information\nis recommended:\n\n\nCommand Name: \n\nRelease Version and Date: \n\nPlugin Homepage or Download Link: \n\nAuthor's Contact Information or Feedback Instructions: \n\nDependencies or Requirements: \n\nDescription: \n\nInstructions For Use: \n\nCopyright and License Information: (for example)\n\n Copyright (C) YEAR AUTHOR <EMAIL>\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n", file );
fclose( file );
}
chmod( path, S_IRUSR | S_IWUSR );
}
g_free( dir );
if ( g_file_test( path, G_FILE_TEST_EXISTS ) )
return path;
g_free( path );
return NULL;
}
gboolean xset_copy_file( char* src, char* dest )
{ // overwrites!
int inF, ouF, bytes;
char line[ 1024 ];
if ( !g_file_test( src, G_FILE_TEST_EXISTS ) )
return FALSE;
if ( ( inF = open( src, O_RDONLY ) ) == -1 )
return FALSE;
unlink( dest );
if ( ( ouF = open( dest, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR ) ) == -1 )
{
close(inF);
return FALSE;
}
while ( ( bytes = read( inF, line, sizeof( line ) ) ) > 0 )
{
if ( write(ouF, line, bytes) <= 0 )
{
close(inF);
close(ouF);
unlink( dest );
return FALSE;
}
}
close(inF);
close(ouF);
return TRUE;
}
char* xset_custom_new_name()
{
char* hex8 = NULL;
char* setname;
char* path1;
char* path2;
char* path3;
char* str;
do
{
if ( hex8 )
g_free( hex8 );
hex8 = randhex8();
setname = g_strdup_printf( "cstm_%s", hex8 );
if ( xset_is( setname ) )
{
g_free( setname );
setname = NULL;
}
else
{
path1 = g_build_filename( settings_config_dir, "scripts", setname, NULL );
str = g_strdup_printf( "%s.sh", setname ); //backwards compat < 0.7.0
path2 = g_build_filename( settings_config_dir, "scripts", str, NULL );
g_free( str );
path3 = g_build_filename( settings_config_dir, "plugin-data", setname, NULL );
if ( g_file_test( path1, G_FILE_TEST_EXISTS )
|| g_file_test( path2, G_FILE_TEST_EXISTS )
|| g_file_test( path3, G_FILE_TEST_EXISTS ) )
{
g_free( setname );
setname = NULL;
}
g_free( path1 );
g_free( path2 );
g_free( path3 );
}
}
while ( !setname );
return setname;
}
void xset_custom_copy_files( XSet* src, XSet* dest )
{
char* cscript;
char* path_src;
char* path_dest;
char* command = NULL;
char* stdout = NULL;
char* stderr = NULL;
char* msg;
gboolean ret;
gint exit_status;
//printf("xset_custom_copy_files( %s, %s )\n", src->name, dest->name );
// copy command dir
// do this for backwards compat - will copy old script
cscript = xset_custom_get_script( src, FALSE );
if ( cscript )
g_free( cscript );
if ( src->plugin )
path_src = g_build_filename( src->plug_dir, src->plug_name, NULL );
else
path_src = g_build_filename( settings_config_dir, "scripts", src->name, NULL );
//printf(" path_src=%s\n", path_src );
if ( !g_file_test( path_src, G_FILE_TEST_EXISTS ) )
{
//printf(" path_src !EXISTS\n");
if ( !src->plugin )
{
command = NULL;
}
else
{
// plugin backwards compat ?
cscript = xset_custom_get_script( src, FALSE );
if ( cscript && g_file_test( cscript, G_FILE_TEST_EXISTS ) )
{
path_dest = g_build_filename( settings_config_dir, "scripts",
dest->name, NULL );
g_mkdir_with_parents( path_dest, 0700 );
chmod( path_dest, 0700 );
g_free( path_dest );
path_dest = g_build_filename( settings_config_dir, "scripts",
dest->name, "exec.sh", NULL );
command = g_strdup_printf( "cp %s %s", cscript, path_dest );
g_free( cscript );
}
else
{
if ( cscript )
g_free( cscript );
command = NULL;
}
}
}
else
{
//printf(" path_src EXISTS\n");
path_dest = g_build_filename( settings_config_dir, "scripts", NULL );
g_mkdir_with_parents( path_dest, 0700 );
chmod( path_dest, 0700 );
g_free( path_dest );
path_dest = g_build_filename( settings_config_dir, "scripts", dest->name, NULL );
command = g_strdup_printf( "cp -a %s %s", path_src, path_dest );
}
g_free( path_src );
if ( command )
{
//printf(" path_dest=%s\n", path_dest );
printf( "COMMAND=%s\n", command );
ret = g_spawn_command_line_sync( command, &stdout, &stderr, &exit_status, NULL );
g_free( command );
printf( "%s%s", stdout, stderr );
if ( !ret || ( exit_status && WIFEXITED( exit_status ) ) )
{
msg = g_strdup_printf( _("An error occured copying command files\n\n%s"),
stderr ? stderr : "" );
xset_msg_dialog( NULL, GTK_MESSAGE_ERROR, _("Copy Command Error"), NULL,
0, msg, NULL, NULL );
g_free( msg );
}
if ( stderr )
g_free( stderr );
if ( stdout )
g_free( stdout );
stderr = stdout = NULL;
command = g_strdup_printf( "chmod -R go-rwx %s", path_dest );
printf( "COMMAND=%s\n", command );
g_spawn_command_line_sync( command, NULL, NULL, NULL, NULL );
g_free( command );
g_free( path_dest );
}
// copy data dir
XSet* mset = xset_get_plugin_mirror( src );
path_src = g_build_filename( settings_config_dir, "plugin-data",
mset->name, NULL );
if ( g_file_test( path_src, G_FILE_TEST_IS_DIR ) )
{
path_dest = g_build_filename( settings_config_dir, "plugin-data",
dest->name, NULL );
command = g_strdup_printf( "cp -a %s %s", path_src, path_dest );
g_free( path_src );
stderr = stdout = NULL;
printf( "COMMAND=%s\n", command );
ret = g_spawn_command_line_sync( command, &stdout, &stderr, &exit_status, NULL );
g_free( command );
printf( "%s%s", stdout, stderr );
if ( !ret || ( exit_status && WIFEXITED( exit_status ) ) )
{
msg = g_strdup_printf( _("An error occured copying command data files\n\n%s"),
stderr ? stderr : "" );
xset_msg_dialog( NULL, GTK_MESSAGE_ERROR, _("Copy Command Error"), NULL,
0, msg, NULL, NULL );
g_free( msg );
}
if ( stderr )
g_free( stderr );
if ( stdout )
g_free( stdout );
stderr = stdout = NULL;
command = g_strdup_printf( "chmod -R go-rwx %s", path_dest );
g_free( path_dest );
printf( "COMMAND=%s\n", command );
g_spawn_command_line_sync( command, NULL, NULL, NULL, NULL );
g_free( command );
}
}
XSet* xset_custom_copy( XSet* set, gboolean copy_next )
{
//printf("\nxset_custom_copy( %s, %d )\n", set->name, copy_next );
XSet* mset = set;
if ( set->plugin && set->shared_key )
mset = xset_get_plugin_mirror( set );
XSet* newset = xset_custom_new();
newset->menu_label = g_strdup( set->menu_label );
newset->s = g_strdup( set->s );
newset->x = g_strdup( set->x );
newset->y = g_strdup( set->y );
newset->z = g_strdup( set->z );
newset->desc = g_strdup( set->desc );
newset->title = g_strdup( set->title );
newset->b = set->b;
newset->menu_style = set->menu_style;
newset->context = g_strdup( mset->context );
newset->line = g_strdup( set->line );
newset->task = mset->task;
newset->task_pop = mset->task_pop;
newset->task_err = mset->task_err;
newset->task_out = mset->task_out;
newset->in_terminal = mset->in_terminal;
newset->keep_terminal = mset->keep_terminal;
newset->scroll_lock = mset->scroll_lock;
if ( !mset->icon && set->plugin )
newset->icon = g_strdup( set->icon );
else
newset->icon = g_strdup( mset->icon );
xset_custom_copy_files( set, newset );
if ( set->tool )
{
newset->tool = XSET_B_TRUE;
if ( !newset->icon )
newset->icon = g_strdup_printf( "gtk-execute" );
}
if ( set->menu_style == XSET_MENU_SUBMENU && set->child )
{
XSet* set_child = xset_get( set->child );
//printf(" copy submenu %s\n", set_child->name );
XSet* newchild = xset_custom_copy( set_child, TRUE );
newset->child = g_strdup( newchild->name );
newchild->parent = g_strdup( newset->name );
}
if ( copy_next && set->next )
{
XSet* set_next = xset_get( set->next );
//printf(" copy next %s\n", set_next->name );
XSet* newnext = xset_custom_copy( set_next, TRUE );
newnext->prev = g_strdup( newset->name );
newset->next = g_strdup( newnext->name );
}
return newset;
}
void clean_plugin_mirrors()
{ // remove plugin mirrors for non-existent plugins
GList* l;
XSet* set;
gboolean redo = TRUE;
while ( redo )
{
redo = FALSE;
for ( l = xsets; l; l = l->next )
{
if ( ((XSet*)l->data)->desc &&
!strcmp( ((XSet*)l->data)->desc, "@plugin@mirror@" ) )
{
set = (XSet*)l->data;
if ( !set->shared_key )
{
xset_free( set );
redo = TRUE;
break;
}
else if ( !xset_is( set->shared_key ) )
{
xset_free( set );
redo = TRUE;
break;
}
}
}
}
// remove plugin-data for non-existent xsets
const char* name;
char* command;
char* stdout;
char* stderr;
GDir* dir;
char* path = g_build_filename( settings_config_dir, "plugin-data", NULL );
_redo:
dir = g_dir_open( path, 0, NULL );
if ( dir )
{
while ( name = g_dir_read_name( dir ) )
{
if ( strlen( name ) == 13 && g_str_has_prefix( name, "cstm_" )
&& !xset_is( name ) )
{
g_dir_close( dir );
command = g_strdup_printf( "rm -rf %s/%s", path, name );
stderr = stdout = NULL;
printf( "COMMAND=%s\n", command );
g_spawn_command_line_sync( command, NULL, NULL, NULL, NULL );
g_free( command );
if ( stderr )
g_free( stderr );
if ( stdout )
g_free( stdout );
goto _redo;
}
}
g_dir_close( dir );
}
g_free( path );
}
void xset_set_plugin_mirror( XSet* pset )
{
XSet* set;
GList* l;
for ( l = xsets; l; l = l->next )
{
if ( ((XSet*)l->data)->desc &&
!strcmp( ((XSet*)l->data)->desc, "@plugin@mirror@" ) )
{
set = (XSet*)l->data;
if ( set->parent && set->child )
{
if ( !strcmp( set->child, pset->plug_name ) &&
!strcmp( set->parent, pset->plug_dir ) )
{
if ( set->shared_key )
g_free( set->shared_key );
set->shared_key = g_strdup( pset->name );
if ( pset->shared_key )
g_free( pset->shared_key );
pset->shared_key = g_strdup( set->name );
return;
}
}
}
}
}
XSet* xset_get_plugin_mirror( XSet* set )
{
// plugin mirrors are custom xsets that save the user's key, icon
// and run prefs for the plugin, if any
if ( !set->plugin )
return set;
if ( set->shared_key )
return xset_get( set->shared_key );
XSet* newset = xset_custom_new();
newset->desc = g_strdup( "@plugin@mirror@" );
newset->parent = g_strdup( set->plug_dir );
newset->child = g_strdup( set->plug_name );
newset->shared_key = g_strdup( set->name ); // this will not be saved
newset->task = set->task;
newset->task_pop = set->task_pop;
newset->task_err = set->task_err;
newset->task_out = set->task_out;
newset->in_terminal = set->in_terminal;
newset->keep_terminal = set->keep_terminal;
newset->scroll_lock = set->scroll_lock;
newset->context = g_strdup( set->context );
newset->b = set->b;
newset->s = g_strdup( set->s );
set->shared_key = g_strdup( newset->name );
return newset;
}
gint compare_plugin_sets( XSet* a, XSet* b )
{
return g_utf8_collate( a->menu_label, b->menu_label );
}
GList* xset_get_plugins( gboolean included )
{ // return list of plugin sets (included or not ) sorted by menu_label
GList* l;
GList* plugins = NULL;
XSet* set;
for ( l = xsets; l; l = l->next )
{
if ( ((XSet*)l->data)->plugin && ((XSet*)l->data)->plugin_top &&
((XSet*)l->data)->plug_dir )
{
set = (XSet*)l->data;
if ( strstr( set->plug_dir, "/included/" ) )
{
if ( included )
plugins = g_list_prepend( plugins, l->data );
}
else if ( !included )
plugins = g_list_prepend( plugins, l->data );
}
}
plugins = g_list_sort( plugins, (GCompareFunc)compare_plugin_sets );
return plugins;
}
XSet* xset_get_by_plug_name( const char* plug_dir, const char* plug_name )
{
GList* l;
if ( !plug_name )
return NULL;
for ( l = xsets; l; l = l->next )
{
if ( ((XSet*)l->data)->plugin
&& !strcmp( plug_name, ((XSet*)l->data)->plug_name )
&& !strcmp( plug_dir, ((XSet*)l->data)->plug_dir ) )
return l->data;
}
// add new
XSet* set = xset_new( xset_custom_new_name() );
set->plug_dir = g_strdup( plug_dir );
set->plug_name = g_strdup( plug_name );
set->plugin = TRUE;
set->lock = FALSE;
xsets = g_list_append( xsets, set );
return set;
}
void xset_parse_plugin( const char* plug_dir, char* line )
{
char* sep = strchr( line, '=' );
char* name;
char* value;
XSet* set;
XSet* set2;
if ( !sep )
return ;
name = line;
value = sep + 1;
*sep = '\0';
sep = strchr( name, '-' );
if ( !sep )
return ;
char* var = sep + 1;
*sep = '\0';
if ( !strncmp( name, "cstm_", 5 ) )
{
set = xset_get_by_plug_name( plug_dir, name );
xset_set_set( set, var, value );
// map plug names to new set names
if ( set->prev && !strcmp( var, "prev" ) )
{
if ( !strncmp( set->prev, "cstm_", 5 ) )
{
set2 = xset_get_by_plug_name( plug_dir, set->prev );
g_free( set->prev );
set->prev = g_strdup( set2->name );
}
else
{
g_free( set->prev );
set->prev = NULL;
}
}
else if ( set->next && !strcmp( var, "next" ) )
{
if ( !strncmp( set->next, "cstm_", 5 ) )
{
set2 = xset_get_by_plug_name( plug_dir, set->next );
g_free( set->next );
set->next = g_strdup( set2->name );
}
else
{
g_free( set->next );
set->next = NULL;
}
}
else if ( set->parent && !strcmp( var, "parent" ) )
{
if ( !strncmp( set->parent, "cstm_", 5 ) )
{
set2 = xset_get_by_plug_name( plug_dir, set->parent );
g_free( set->parent );
set->parent = g_strdup( set2->name );
}
else
{
g_free( set->parent );
set->parent = NULL;
}
}
else if ( set->child && !strcmp( var, "child" ) )
{
if ( !strncmp( set->child, "cstm_", 5 ) )
{
set2 = xset_get_by_plug_name( plug_dir, set->child );
g_free( set->child );
set->child = g_strdup( set2->name );
}
else
{
g_free( set->child );
set->child = NULL;
}
}
}
}
XSet* xset_import_plugin( const char* plug_dir )
{
char line[ 2048 ];
char* section_name;
gboolean func;
GList* l;
XSet* set;
// clear all existing plugin sets with this plug_dir
// ( keep the mirrors to retain user prefs )
gboolean redo = TRUE;
while ( redo )
{
redo = FALSE;
for ( l = xsets; l; l = l->next )
{
if ( ((XSet*)l->data)->plugin
&& !strcmp( plug_dir, ((XSet*)l->data)->plug_dir ) )
{
xset_free( (XSet*)l->data );
redo = TRUE; // search list from start again due to changed list
break;
}
}
}
// read plugin file into xsets
gboolean plugin_good = FALSE;
char* plugin = g_build_filename( plug_dir, "plugin", NULL );
FILE* file = fopen( plugin, "r" );
if ( !file )
{
g_warning( _("Error reading plugin file %s"), plugin );
return NULL;
}
while ( fgets( line, sizeof( line ), file ) )
{
strtok( line, "\r\n" );
if ( ! line[ 0 ] )
continue;
if ( line[ 0 ] == '[' )
{
section_name = strtok( line, "]" );
if ( 0 == strcmp( line + 1, "Plugin" ) )
func = TRUE;
else
func = FALSE;
continue;
}
if ( func )
{
xset_parse_plugin( plug_dir, line );
if ( !plugin_good )
plugin_good = TRUE;
}
}
fclose( file );
// clean plugin sets, set type
gboolean top = TRUE;
XSet* rset = NULL;
for ( l = xsets; l; l = l->next )
{
if ( ((XSet*)l->data)->plugin
&& !strcmp( plug_dir, ((XSet*)l->data)->plug_dir ) )
{
set = (XSet*)l->data;
set->key = set->keymod = set->tool = 0;
xset_set_plugin_mirror( set );
if ( set->plugin_top = top )
{
top = FALSE;
rset = set;
}
}
}
return plugin_good ? rset : NULL;
}
typedef struct _PluginData
{
FMMainWindow* main_window;
char* plug_dir;
XSet* set;
int job;
}PluginData;
void on_install_plugin_cb( VFSFileTask* task, PluginData* plugin_data )
{
XSet* set;
char* msg;
//printf("on_install_plugin_cb\n");
if ( plugin_data->job == 2 ) // uninstall
{
if ( !g_file_test( plugin_data->plug_dir, G_FILE_TEST_EXISTS ) )
{
xset_custom_delete( plugin_data->set, FALSE );
clean_plugin_mirrors();
//main_window_on_plugins_change( NULL );
}
}
else
{
char* plugin = g_build_filename( plugin_data->plug_dir, "plugin", NULL );
if ( g_file_test( plugin, G_FILE_TEST_EXISTS ) )
{
set = xset_import_plugin( plugin_data->plug_dir );
if ( !set )
{
msg = g_strdup_printf( _("The imported plugin folder does not contain a valid plugin.\n\n(%s/)"), plugin_data->plug_dir );
xset_msg_dialog( GTK_WIDGET( plugin_data->main_window ), GTK_MESSAGE_ERROR, "Invalid Plugin",
NULL, 0, msg, NULL, NULL );
g_free( msg );
}
else if ( plugin_data->job == 1 )
{
// copy
set->plugin_top = FALSE; // don't show tmp plugin in Plugins menu
set_clipboard = set;
clipboard_is_cut = FALSE;
if ( xset_get_b( "plug_cverb" ) )
{
char* label = clean_label( set->menu_label, FALSE, FALSE );
if ( geteuid() == 0 )
msg = g_strdup_printf( _("The '%s' plugin has been copied to the design clipboard. Use View|Design Mode to paste it into a menu.\n\nBecause it has not been installed, this plugin will not appear in the Plugins menu."), label );
else
msg = g_strdup_printf( _("The '%s' plugin has been copied to the design clipboard. Use View|Design Mode to paste it into a menu.\n\nBecause it has not been installed, this plugin will not appear in the Plugins menu, and its contents are not protected by root (once pasted it will be saved with normal ownership).\n\nIf this plugin contains su commands or will be run as root, installing it to and running it only from the Plugins menu is recommended to improve your system security."), label );
g_free( label );
GDK_THREADS_ENTER(); // due to dialog run causes low level thread lock
xset_msg_dialog( GTK_WIDGET( plugin_data->main_window ),
0, "Copy Plugin",
NULL, 0, msg, NULL, NULL );
GDK_THREADS_LEAVE();
g_free( msg );
}
}
}
g_free( plugin );
}
g_free( plugin_data->plug_dir );
g_slice_free( PluginData, plugin_data );
}
void xset_remove_plugin( GtkWidget* parent, PtkFileBrowser* file_browser, XSet* set )
{
char* msg;
if ( !file_browser || !set || !set->plugin_top || !set->plug_dir )
return;
if ( strstr( set->plug_dir, "/included/" ) )
return; // failsafe - don't allow removal of included
if ( !app_settings.no_confirm )
{
char* label = clean_label( set->menu_label, FALSE, FALSE );
msg = g_strdup_printf( _("Uninstall the '%s' plugin?\n\n( %s )"), label,
set->plug_dir );
g_free( label );
if ( xset_msg_dialog( parent, GTK_MESSAGE_WARNING, _("Uninstall Plugin"),
NULL, GTK_BUTTONS_YES_NO, msg, NULL, NULL ) != GTK_RESPONSE_YES )
{
g_free( msg );
return;
}
g_free( msg );
}
PtkFileTask* task = ptk_file_exec_new( _("Uninstall Plugin"), NULL, parent,
file_browser->task_view );
char* plug_dir_q = bash_quote( set->plug_dir );
task->task->exec_command = g_strdup_printf( "rm -rf %s", plug_dir_q );
g_free( plug_dir_q );
task->task->exec_sync = TRUE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE;
task->task->exec_export = FALSE;
task->task->exec_as_user = g_strdup( "root" );
PluginData* plugin_data = g_slice_new0( PluginData );
plugin_data->main_window = NULL;
plugin_data->plug_dir = g_strdup( set->plug_dir );
plugin_data->set = set;
plugin_data->job = 2;
task->complete_notify = (GFunc)on_install_plugin_cb;
task->user_data = plugin_data;
ptk_file_task_run( task );
}
void install_plugin_file( gpointer main_win, const char* path, const char* plug_dir,
int type, int job )
{
char* wget;
char* file_path;
char* file_path_q;
char* own;
char* rem = g_strdup( "" );
char* compression = "z";
FMMainWindow* main_window = (FMMainWindow*)main_win;
// task
PtkFileTask* task = ptk_file_exec_new( _("Install Plugin"), NULL,
GTK_WIDGET( main_window ),
main_window->task_view );
char* plug_dir_q = bash_quote( plug_dir );
if ( type == 0 )
{
// file
wget = g_strdup( "" );
if ( g_str_has_suffix( path, ".tar.xz" ) )
compression = "J";
file_path_q = bash_quote( path );
}
else
{
// url
if ( g_str_has_suffix( path, ".tar.xz" ) )
{
file_path = g_build_filename( plug_dir, "plugin-tmp.tar.xz", NULL );
compression = "J";
}
else
file_path = g_build_filename( plug_dir, "plugin-tmp.tar.gz", NULL );
file_path_q = bash_quote( file_path );
g_free( file_path );
char* url_q = bash_quote( path );
wget = g_strdup_printf( "&& wget --tries=1 --connect-timeout=30 -O %s %s ",
file_path_q, url_q );
g_free( url_q );
g_free( rem );
rem = g_strdup_printf( "; rm -f %s", file_path_q );
}
if ( job == 0 )
{
// install
own = g_strdup_printf( "chown -R root:root %s && chmod -R go+rX-w %s",
plug_dir_q, plug_dir_q );
task->task->exec_as_user = g_strdup( "root" );
}
else
{
// copy
own = g_strdup_printf( "chmod -R go+rX-w %s", plug_dir_q );
}
task->task->exec_command = g_strdup_printf( "rm -rf %s ; mkdir -p %s && cd %s %s&& tar --exclude='/*' --keep-old-files -x%sf %s ; err=$?; if [ $err -ne 0 ] || [ ! -e plugin ]; then rm -rf %s ; echo 'Error installing plugin (invalid plugin file?)'; exit 1 ; fi ; %s %s",
plug_dir_q, plug_dir_q, plug_dir_q,
wget, compression, file_path_q, plug_dir_q, own, rem );
g_free( plug_dir_q );
g_free( file_path_q );
g_free( own );
g_free( rem );
task->task->exec_sync = TRUE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE;
task->task->exec_export = FALSE;
PluginData* plugin_data = g_slice_new0( PluginData );
plugin_data->main_window = main_window;
plugin_data->plug_dir = g_strdup( plug_dir );
plugin_data->job = job;
task->complete_notify = (GFunc)on_install_plugin_cb;
task->user_data = plugin_data;
ptk_file_task_run( task );
}
gboolean xset_custom_export_files( XSet* set, char* plug_dir )
{
char* cscript;
char* path_src;
char* path_dest;
char* command;
char* stdout = NULL;
char* stderr = NULL;
// do this for backwards compat - will copy old script
cscript = xset_custom_get_script( set, FALSE );
if ( cscript )
g_free( cscript );
if ( set->plugin )
{
path_src = g_build_filename( set->plug_dir, set->plug_name, NULL );
path_dest = g_build_filename( plug_dir, set->plug_name, NULL );
}
else
{
path_src = g_build_filename( settings_config_dir, "scripts", set->name, NULL );
path_dest = g_build_filename( plug_dir, set->name, NULL );
}
if ( !g_file_test( path_src, G_FILE_TEST_EXISTS ) )
{
g_mkdir_with_parents( path_dest, 0755 );
if ( !g_file_test( path_dest, G_FILE_TEST_EXISTS ) )
{
g_free( path_src );
g_free( path_dest );
return FALSE;
}
chmod( path_dest, 0755 );
if ( !set->plugin )
{
g_free( path_src );
g_free( path_dest );
return TRUE;
}
// plugin backwards compat ?
cscript = xset_custom_get_script( set, FALSE );
if ( cscript && g_file_test( cscript, G_FILE_TEST_EXISTS ) )
{
command = g_strdup_printf( "cp -a %s %s/", cscript, path_dest );
g_free( cscript );
}
else
{
if ( cscript )
g_free( cscript );
g_free( path_src );
g_free( path_dest );
return TRUE;
}
}
else
{
command = g_strdup_printf( "cp -a %s %s", path_src, path_dest );
}
g_free( path_src );
g_free( path_dest );
printf( "COMMAND=%s\n", command );
gboolean ret = g_spawn_command_line_sync( command, NULL, NULL, NULL, NULL );
g_free( command );
if ( stderr )
g_free( stderr );
if ( stdout )
g_free( stdout );
return ret;
}
gboolean xset_custom_export_write( FILE* file, XSet* set, char* plug_dir )
{ // recursively write set, submenu sets, and next sets
xset_write_set( file, set );
if ( !xset_custom_export_files( set, plug_dir ) )
return FALSE;
if ( set->menu_style == XSET_MENU_SUBMENU && set->child )
{
if ( !xset_custom_export_write( file, xset_get( set->child ), plug_dir ) )
return FALSE;
}
if ( set->next )
{
if ( !xset_custom_export_write( file, xset_get( set->next ), plug_dir ) )
return FALSE;
}
return TRUE;
}
void xset_custom_export( GtkWidget* parent, PtkFileBrowser* file_browser,
XSet* set )
{
char* deffolder;
char* deffile;
char* s1;
char* s2;
if ( !file_browser )
return;
// get new plugin filename
XSet* save = xset_get( "plug_ifile" );
if ( save->s ) //&& g_file_test( save->s, G_FILE_TEST_IS_DIR )
deffolder = save->s;
else
{
if ( !( deffolder = xset_get_s( "go_set_default" ) ) )
deffolder = "/";
}
if ( !set->plugin )
{
s1 = clean_label( set->menu_label, TRUE, FALSE );
s2 = plain_ascii_name( s1 );
if ( s2[0] == '\0' )
{
g_free( s2 );
s2 = g_strdup( "Plugin" );
}
deffile = g_strdup_printf( "%s.spacefm-plugin.tar.gz", s2 );
g_free( s1 );
g_free( s2 );
}
else
{
s1 = g_path_get_basename( set->plug_dir );
deffile = g_strdup_printf( "%s.spacefm-plugin.tar.gz", s1 );
g_free( s1 );
}
char* path = xset_file_dialog( parent, GTK_FILE_CHOOSER_ACTION_SAVE,
_("Save As Plugin File"), deffolder, deffile );
g_free( deffile );
if ( !path )
return;
if ( save->s )
g_free( save->s );
save->s = g_path_get_dirname( path );
// get or create tmp plugin dir
char* plug_dir = NULL;
char* hex8;
if ( !set->plugin )
{
s1 = (char*)xset_get_user_tmp_dir();
if ( !s1 )
goto _export_error;
while ( !plug_dir || g_file_test( plug_dir, G_FILE_TEST_EXISTS ) )
{
hex8 = randhex8();
if ( plug_dir )
g_free( plug_dir );
plug_dir = g_build_filename( s1, hex8, NULL );
g_free( hex8 );
}
g_mkdir_with_parents( plug_dir, 0700 );
chmod( plug_dir, 0700 );
// Create plugin file
s1 = g_build_filename( plug_dir, "plugin", NULL );
FILE* file = fopen( s1, "w" );
g_free( s1 );
if ( !file )
goto _rmtmp_error;
int result = fputs( "# SpaceFM Plugin File\n\n# THIS FILE IS NOT DESIGNED TO BE EDITED\n\n", file );
if ( result < 0 )
{
fclose( file );
goto _rmtmp_error;
}
fputs( "[Plugin]\n", file );
xset_write_set( file, xset_get( "config_version" ) );
char* s_prev = set->prev;
char* s_next = set->next;
char* s_parent = set->parent;
set->prev = set->next = set->parent = NULL;
xset_write_set( file, set );
set->prev = s_prev;
set->next = s_next;
set->parent = s_parent;
if ( !xset_custom_export_files( set, plug_dir ) )
goto _rmtmp_error;
if ( set->menu_style == XSET_MENU_SUBMENU && set->child )
{
if ( !xset_custom_export_write( file, xset_get( set->child ), plug_dir ) )
goto _rmtmp_error;
}
result = fputs( "\n", file );
fclose( file );
if ( result < 0 )
goto _rmtmp_error;
}
else
plug_dir = g_strdup( set->plug_dir );
// tar and delete tmp files
// task
PtkFileTask* task = ptk_file_exec_new( _("Export Plugin"), plug_dir, parent,
file_browser->task_view );
char* plug_dir_q = bash_quote( plug_dir );
char* path_q = bash_quote( path );
if ( !set->plugin )
task->task->exec_command = g_strdup_printf( "tar --numeric-owner -czf %s * ; err=$? ; rm -rf %s ; if [ $err -ne 0 ]; then rm -f %s; fi; exit $err", path_q, plug_dir_q, path_q );
else
task->task->exec_command = g_strdup_printf( "tar --numeric-owner -czf %s * ; err=$? ; if [ $err -ne 0 ]; then rm -f %s; fi; exit $err", path_q, path_q );
g_free( plug_dir_q );
g_free( path_q );
task->task->exec_sync = TRUE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE;
task->task->exec_export = FALSE;
task->task->exec_browser = file_browser;
ptk_file_task_run( task );
g_free( path );
g_free( plug_dir );
return;
_rmtmp_error:
if ( !set->plugin )
{
s2 = bash_quote( plug_dir );
s1 = g_strdup_printf( "rm -rf %s", s2 );
g_spawn_command_line_sync( s1, NULL, NULL, NULL, NULL );
g_free( s1 );
g_free( s2 );
}
_export_error:
g_free( plug_dir );
g_free( path );
xset_msg_dialog( parent, GTK_MESSAGE_ERROR, _("Export Error"), NULL, 0,
_("Unable to create temporary files"), NULL, NULL );
}
void xset_custom_activate( GtkWidget* item, XSet* set )
{
GtkWidget* parent;
GtkWidget* task_view = NULL;
const char* cwd;
char* command;
char* s;
char* value = NULL;
XSet* mset;
// plugin?
mset = xset_get_plugin_mirror( set );
if ( set->browser )
{
parent = GTK_WIDGET( set->browser );
task_view = set->browser->task_view;
cwd = ptk_file_browser_get_cwd( set->browser );
}
else
{
parent = GTK_WIDGET( set->desktop );
cwd = vfs_get_desktop_dir();
}
// name
if ( !set->plugin )
{
if ( !set->menu_label || ( set->menu_label && set->menu_label[0] == '\0' )
|| ( set->menu_label && !strcmp( set->menu_label, _("New _Command") ) ) )
{
if ( !xset_text_dialog( parent, _("Change Menu Name"), NULL, FALSE, _(enter_menu_name_new),
NULL, set->menu_label, &set->menu_label,
NULL, FALSE, "#designmode-designmenu-new" ) )
return;
}
}
// variable value
if ( set->menu_style == XSET_MENU_CHECK )
value = g_strdup_printf( "%d", mset->b == XSET_B_TRUE ? 1 : 0 );
else if ( set->menu_style == XSET_MENU_STRING )
value = g_strdup( mset->s );
else
value = g_strdup( set->menu_label );
// command
if ( !set->x )
set->x = g_strdup_printf( "0" );
if ( atoi( set->x ) == 0 )
{
// line
if ( !set->line || set->line[0] == '\0' )
{
if ( set->plugin )
return;
if ( !xset_text_dialog( parent, _("Set Command Line"), NULL, TRUE,
_(enter_command_line), NULL, set->line, &set->line,
NULL, FALSE,
"#designmode-command-line" )
|| !set->line || set->line[0] == '\0' )
return;
}
command = replace_line_subs( set->line );
}
else if ( atoi( set->x ) == 1 )
{
// script
command = xset_custom_get_script( set, FALSE );
if ( !command )
return;
}
else if ( atoi( set->x ) == 2 )
{
// custom
if ( !set->z || !g_file_test( set->z, G_FILE_TEST_EXISTS ) )
{
if ( set->plugin )
return;
char* folder;
char* file;
char* custom_file;
if ( set->z && set->z[0] != '\0' )
{
folder = g_path_get_dirname( set->z );
file = g_path_get_basename( set->z );
}
else
{
folder = g_strdup_printf( "/usr/bin" );
file = NULL;
}
if ( custom_file = xset_file_dialog( parent, GTK_FILE_CHOOSER_ACTION_OPEN,
_("Choose Custom Executable"), folder, file ) )
{
xset_set_set( set, "z", custom_file );
g_free( custom_file );
}
else
{
g_free( file );
g_free( folder );
return;
}
g_free( file );
g_free( folder );
}
if ( g_str_has_suffix( set->z, ".desktop" ) )
{
VFSAppDesktop* app = vfs_app_desktop_new( set->z );
if ( app && app->exec && app->exec[0] != '\0' )
{
// should we also insert files even if no %* ?
command = replace_desktop_subs( app->exec );
vfs_app_desktop_unref( app );
}
else
command = bash_quote( set->z );
}
else
command = bash_quote( set->z );
}
// task
char* task_name = clean_label( set->menu_label, FALSE, FALSE );
PtkFileTask* task = ptk_file_exec_new( task_name, cwd, parent,
task_view );
g_free( task_name );
// don't free cwd!
task->task->exec_browser = set->browser;
task->task->exec_desktop = set->desktop;
task->task->exec_command = command;
task->task->exec_set = set;
if ( set->y && set->y[0] != '\0' )
task->task->exec_as_user = g_strdup( set->y );
if ( set->plugin && set->shared_key && mset->icon )
task->task->exec_icon = g_strdup( mset->icon );
if ( !task->task->exec_icon && set->icon )
task->task->exec_icon = g_strdup( set->icon );
task->task->current_dest = value; // temp storage
task->task->exec_terminal = ( mset->in_terminal == XSET_B_TRUE );
task->task->exec_keep_terminal = ( mset->keep_terminal == XSET_B_TRUE );
task->task->exec_sync = ( mset->task == XSET_B_TRUE );
task->task->exec_popup = ( mset->task_pop == XSET_B_TRUE );
task->task->exec_show_output = ( mset->task_out == XSET_B_TRUE );
task->task->exec_show_error = ( mset->task_err == XSET_B_TRUE );
task->task->exec_scroll_lock = ( mset->scroll_lock == XSET_B_TRUE );
task->task->exec_export = TRUE;
//task->task->exec_keep_tmp = TRUE;
ptk_file_task_run( task );
}
void xset_custom_delete( XSet* set, gboolean delete_next )
{
char* cscript;
char* path1;
char* path2;
char* path3;
char* command;
char* stdout = NULL;
char* stderr = NULL;
if ( set->menu_style == XSET_MENU_SUBMENU && set->child )
{
XSet* set_child = xset_get( set->child );
xset_custom_delete( set_child, TRUE );
}
if ( delete_next && set->next )
{
XSet* set_next = xset_get( set->next );
xset_custom_delete( set_next, TRUE );
}
if ( set == set_clipboard )
set_clipboard = NULL;
cscript = g_strdup_printf( "%s.sh", set->name ); //backwards compat
path1 = g_build_filename( settings_config_dir, "scripts", cscript, NULL );
path2 = g_build_filename( settings_config_dir, "scripts", set->name, NULL );
path3 = g_build_filename( settings_config_dir, "plugin-data", set->name, NULL );
command = g_strdup_printf( "rm -rf %s %s %s", path1, path2, path3 );
g_free( path1 );
g_free( path2 );
g_free( path3 );
g_free( cscript );
printf( "COMMAND=%s\n", command );
g_spawn_command_line_sync( command, NULL, NULL, NULL, NULL );
g_free( command );
if ( stderr )
g_free( stderr );
if ( stdout )
g_free( stdout );
xset_free( set );
}
void xset_custom_remove( XSet* set )
{
XSet* set_prev;
XSet* set_next;
XSet* set_parent;
XSet* set_child;
/*
printf("xset_custom_remove %s (%s)\n", set->name, set->menu_label );
printf(" set->parent = %s\n", set->parent );
printf(" set->prev = %s\n", set->prev );
printf(" set->next = %s\n", set->next );
*/
if ( set->prev )
{
set_prev = xset_get( set->prev );
//printf(" set->prev = %s (%s)\n", set_prev->name, set_prev->menu_label );
if ( set_prev->next )
g_free( set_prev->next );
if ( set->next )
set_prev->next = g_strdup( set->next );
else
set_prev->next = NULL;
}
if ( set->next )
{
set_next = xset_get( set->next );
if ( set_next->prev )
g_free( set_next->prev );
if ( set->prev )
set_next->prev = g_strdup( set->prev );
else
{
set_next->prev = NULL;
if ( set->parent )
{
set_parent = xset_get( set->parent );
if ( set_parent->child )
g_free( set_parent->child );
set_parent->child = g_strdup( set_next->name );
set_next->parent = g_strdup( set->parent );
}
}
}
if ( !set->prev && !set->next && set->parent )
{
set_parent = xset_get( set->parent );
set_child = xset_custom_new();
if ( set_parent->child )
g_free( set_parent->child );
set_parent->child = g_strdup( set_child->name );
set_child->parent = g_strdup( set->parent );
set_child->menu_label = g_strdup( _("New _Command") );
}
}
gboolean xset_clipboard_in_set( XSet* set )
{ // look upward to see if clipboard is in set's tree
if ( !set_clipboard || set->lock )
return FALSE;
if ( set == set_clipboard )
return TRUE;
if ( set->parent )
{
XSet* set_parent = xset_get( set->parent );
if ( xset_clipboard_in_set( set_parent ) )
return TRUE;
}
if ( set->prev )
{
XSet* set_prev = xset_get( set->prev );
while ( set_prev )
{
if ( set_prev->parent )
{
XSet* set_prev_parent = xset_get( set_prev->parent );
if ( xset_clipboard_in_set( set_prev_parent ) )
return TRUE;
set_prev = NULL;
}
else if ( set_prev->prev )
set_prev = xset_get( set_prev->prev );
else
set_prev = NULL;
}
}
return FALSE;
}
XSet* xset_custom_new()
{
char* setname;
XSet* set;
setname = xset_custom_new_name();
// create set
set = xset_get( setname );
g_free( setname );
set->lock = FALSE;
set->keep_terminal = XSET_B_TRUE;
set->task = XSET_B_TRUE;
set->task_err = XSET_B_TRUE;
set->task_out = XSET_B_TRUE;
set->x = g_strdup_printf( "0" );
return set;
}
gboolean have_x_access( const char* path )
{
#if defined(HAVE_EUIDACCESS)
return ( euidaccess( path, R_OK | X_OK ) == 0 );
#elif defined(HAVE_EACCESS)
return ( eaccess( path, R_OK | X_OK ) == 0 );
#else
struct stat results;
stat( path, &results );
if ( ( results.st_mode & S_IXOTH ) )
return TRUE;
if ( ( results.st_mode & S_IXUSR ) && ( geteuid() == results.st_uid ) )
return TRUE;
if ( ( results.st_mode & S_IXGRP ) && ( getegid() == results.st_gid ) )
return TRUE;
return FALSE;
#endif
}
gboolean have_rw_access( const char* path )
{
#if defined(HAVE_EUIDACCESS)
return ( euidaccess( path, R_OK | W_OK ) == 0 );
#elif defined(HAVE_EACCESS)
return ( eaccess( path, R_OK | W_OK ) == 0 );
#else
struct stat results;
stat( path, &results );
if ( ( results.st_mode & S_IROTH ) && ( results.st_mode & S_IWOTH ) )
return TRUE;
if ( ( results.st_mode & S_IRUSR ) && ( results.st_mode & S_IWUSR )
&& ( geteuid() == results.st_uid ) )
return TRUE;
if ( ( results.st_mode & S_IRGRP ) && ( results.st_mode & S_IWGRP )
&& ( getegid() == results.st_gid ) )
return TRUE;
return FALSE;
#endif
}
gboolean dir_has_files( const char* path )
{
GDir* dir;
gboolean ret = FALSE;
if ( !( path && g_file_test( path, G_FILE_TEST_IS_DIR ) ) )
return FALSE;
dir = g_dir_open( path, 0, NULL );
if ( dir )
{
if ( g_dir_read_name( dir ) )
ret = TRUE;
g_dir_close( dir );
}
return ret;
}
void xset_edit( GtkWidget* parent, const char* path, gboolean force_root, gboolean no_root )
{
gboolean as_root = FALSE;
gboolean terminal;
char* editor;
char* quoted_path;
GtkWidget* dlgparent = NULL;
if ( !path )
return;
if ( force_root && no_root )
return;
if ( parent )
dlgparent = gtk_widget_get_toplevel( GTK_WIDGET( parent ) );
if ( geteuid() != 0 && !force_root && ( no_root || have_rw_access( path ) ) )
{
editor = xset_get_s( "editor" );
if ( !editor || editor[0] == '\0' )
{
ptk_show_error( GTK_WINDOW( dlgparent ), _("Editor Not Set"),
_("Please set your editor in View|Preferences|Advanced") );
return;
}
terminal = xset_get_b( "editor" );
}
else
{
editor = xset_get_s( "root_editor" );
if ( !editor || editor[0] == '\0' )
{
ptk_show_error( GTK_WINDOW( dlgparent ), _("Root Editor Not Set"),
_("Please set root's editor in View|Preferences|Advanced") );
return;
}
as_root = TRUE;
terminal = xset_get_b( "root_editor" );
}
// replacements
quoted_path = bash_quote( path );
if ( strstr( editor, "%f" ) )
editor = replace_string( editor, "%f", quoted_path, FALSE );
else if ( strstr( editor, "%F" ) )
editor = replace_string( editor, "%F", quoted_path, FALSE );
else if ( strstr( editor, "%u" ) )
editor = replace_string( editor, "%u", quoted_path, FALSE );
else if ( strstr( editor, "%U" ) )
editor = replace_string( editor, "%U", quoted_path, FALSE );
else
editor = g_strdup_printf( "%s %s", editor, quoted_path );
g_free( quoted_path );
// task
char* task_name = g_strdup_printf( _("Edit %s"), path );
char* cwd = g_path_get_dirname( path );
PtkFileTask* task = ptk_file_exec_new( task_name, cwd, dlgparent, NULL );
g_free( task_name );
g_free( cwd );
task->task->exec_command = editor;
task->task->exec_sync = FALSE;
task->task->exec_terminal = terminal;
if ( as_root )
task->task->exec_as_user = g_strdup_printf( "root" );
ptk_file_task_run( task );
}
void xset_open_url( GtkWidget* parent, const char* url )
{
const char* browser;
char* command = NULL;
if ( !url )
url = homepage;
browser = xset_get_s( "main_help_browser" );
if ( browser )
{
if ( strstr( browser, "%u" ) )
command = replace_string( browser, "%u", url, TRUE );
else
command = g_strdup_printf( "%s '%s'", browser, url );
}
else
{
browser = g_getenv( "BROWSER" );
if ( browser && browser[0] != '\0' )
command = g_strdup_printf( "%s '%s'", browser, url );
else
{
int ii = 0;
char* program;
if ( g_str_has_prefix( url, "file://" )
|| g_str_has_prefix( url, "/" ) )
ii = 3; // xdg,gnome,exo-open use editor for html files so skip at start
char* programs[] = { "xdg-open", "gnome-open", "exo-open", "firefox", "iceweasel", "arora", "konqueror", "opera", "epiphany", "midori", "chrome", "xdg-open", "gnome-open", "exo-open" };
int i;
for( i = ii; i < G_N_ELEMENTS(programs); ++i)
{
if ( ( program = g_find_program_in_path( programs[i] ) ) )
{
command = g_strdup_printf( "%s '%s'", program, url );
g_free( program );
break;
}
}
}
}
if ( !command )
{
XSet* set = xset_get( "main_help_browser" );
if ( !xset_text_dialog( parent, set->title, NULL, TRUE,
set->desc, NULL, set->s, &set->s, NULL, FALSE, NULL ) || !set->s )
return;
xset_open_url( parent, url );
return;
}
// task
PtkFileTask* task = ptk_file_exec_new( "Open URL", "/", parent, NULL );
task->task->exec_command = command;
task->task->exec_sync = FALSE;
task->task->exec_export = FALSE;
ptk_file_task_run( task );
}
char* xset_get_manual_url()
{
char* path;
char* url;
url = xset_get_s( "main_help_url" );
if ( url )
{
if ( url[0] == '/' )
return g_strdup_printf( "file://%s", url );
return g_strdup( url );
}
// get user's locale
const char* locale = NULL;
const char* const * langs = g_get_language_names();
char* dot = strchr( langs[0], '.' );
if( dot )
locale = g_strndup( langs[0], (size_t)(dot - langs[0]) );
else
locale = langs[0];
if ( !locale || locale[0] == '\0' )
locale = "en";
char* l = g_strdup( locale );
char* ll = strchr( l, '_' );
if ( ll )
ll[0] = '\0';
// get potential filenames
GList* names = NULL;
if ( locale && locale[0] != '\0' )
names = g_list_append( names, g_strdup_printf( "spacefm-manual-%s.html",
locale ) );
if ( l && l[0] != '\0' && g_strcmp0( l, locale ) )
names = g_list_append( names, g_strdup_printf( "spacefm-manual-%s.html", l ) );
if ( g_strcmp0( l, "en" ) )
names = g_list_append( names, g_strdup( "spacefm-manual-en.html" ) );
names = g_list_append( names, g_strdup( "spacefm-manual.html" ) );
g_free( l );
// get potential locations
GList* locations = NULL;
if ( HTMLDIR )
locations = g_list_append( locations, g_strdup( HTMLDIR ) );
if ( DATADIR )
locations = g_list_append( locations, g_build_filename( DATADIR,
"spacefm", NULL ) );
const gchar* const * dir = g_get_system_data_dirs();
for( ; *dir; ++dir )
{
path = g_build_filename( *dir, "spacefm", NULL );
if ( !g_list_find_custom( locations, path, (GCompareFunc)g_strcmp0 ) )
locations = g_list_append( locations, path );
else
g_free( path );
}
if ( !g_list_find_custom( locations, "/usr/local/share/spacefm",
(GCompareFunc)g_strcmp0 ) )
locations = g_list_append( locations, g_strdup( "/usr/local/share/spacefm" ) );
if ( !g_list_find_custom( locations, "/usr/share/spacefm",
(GCompareFunc)g_strcmp0 ) )
locations = g_list_append( locations, g_strdup( "/usr/share/spacefm" ) );
GList* loc;
GList* ln;
for ( loc = locations; loc && !url; loc = loc->next )
{
for ( ln = names; ln; ln = ln->next )
{
path = g_build_filename( (char*)loc->data, (char*)ln->data, NULL );
if ( g_file_test( path, G_FILE_TEST_EXISTS ) )
{
url = path;
break;
}
g_free( path );
}
}
g_list_foreach( names, (GFunc)g_free, NULL );
g_list_foreach( locations, (GFunc)g_free, NULL );
g_list_free( names );
g_list_free( locations );
if ( !url )
return NULL;
path = g_strdup_printf( "file://%s", url );
g_free( url );
return path;
}
XSetContext* xset_context_new()
{
int i;
if ( !xset_context )
{
xset_context = g_slice_new0( XSetContext );
xset_context->valid = FALSE;
for ( i = 0; i < G_N_ELEMENTS( xset_context->var ); i++ )
xset_context->var[i] = NULL;
}
else
{
xset_context->valid = FALSE;
for ( i = 0; i < G_N_ELEMENTS( xset_context->var ); i++ )
{
if ( xset_context->var[i] )
g_free( xset_context->var[i] );
xset_context->var[i] = NULL;
}
}
return xset_context;
}
enum {
CONTEXT_COL_DISP,
CONTEXT_COL_SUB,
CONTEXT_COL_COMP,
CONTEXT_COL_VALUE
};
typedef struct
{
GtkWidget* dlg;
GtkWidget* parent;
GtkWidget* view;
GtkButton* btn_remove;
GtkButton* btn_add;
GtkButton* btn_apply;
GtkButton* btn_ok;
GtkWidget* box_sub;
GtkWidget* box_comp;
GtkWidget* box_value;
GtkWidget* box_match;
GtkWidget* box_action;
GtkLabel* current_value;
GtkLabel* test;
GtkWidget* hbox_match;
GtkFrame* frame;
} ContextData;
static char* get_element_next( char** s )
{
char* ret;
if ( !*s )
return NULL;
char* sep = strstr( *s, "%%%%%" );
if ( !sep )
{
if ( *s[0] == '\0' )
return ( *s = NULL );
ret = g_strdup( *s );
*s = NULL;
return ret;
}
ret = g_strndup( *s, sep - *s );
*s = sep + 5;
return ret;
}
gboolean get_rule_next( char** s, int* sub, int* comp, char** value )
{
char* vs;
vs = get_element_next( s );
if ( !vs )
return FALSE;
*sub = atoi( vs );
g_free( vs );
if ( *sub < 0 || *sub >= G_N_ELEMENTS( context_sub ) )
return FALSE;
vs = get_element_next( s );
*comp = atoi( vs );
g_free( vs );
if ( *comp < 0 || *comp >= G_N_ELEMENTS( context_comp ) )
return FALSE;
if ( !( *value = get_element_next( s ) ) )
*value = g_strdup( "" );
return TRUE;
}
int xset_context_test( char* rules, gboolean def_disable )
{
// assumes valid xset_context and rules != NULL and no global ignore
int i, sep_type, sub, comp;
char* value;
int match, action;
char* s;
char* eleval;
char* sep;
gboolean test;
enum { ANY, ALL, NANY, NALL };
// get valid action and match
char* elements = rules;
if ( !( s = get_element_next( &elements ) ) )
return 0;
action = atoi( s );
g_free( s );
if ( action < 0 || action > 3 )
return 0;
if ( !( s = get_element_next( &elements ) ) )
return 0;
match = atoi( s );
g_free( s );
if ( match < 0 || match > 3 )
return 0;
if ( action != CONTEXT_HIDE && action != CONTEXT_SHOW && def_disable )
return CONTEXT_DISABLE;
// parse rules
gboolean is_rules = FALSE;
gboolean all_match = TRUE;
gboolean no_match = TRUE;
gboolean any_match = FALSE;
while ( get_rule_next( &elements, &sub, &comp, &value ) )
{
is_rules = TRUE;
eleval = value;
do
{
if ( sep = strstr( eleval, "||" ) )
sep_type = 1;
else if ( sep = strstr( eleval, "&&" ) )
sep_type = 2;
if ( sep )
{
sep[0] = '\0';
i = -1;
// remove trailing spaces from eleval
while ( sep + i >= eleval && sep[i] == ' ' )
{
sep[i] = '\0';
i--;
}
}
switch ( comp )
{
case CONTEXT_COMP_EQUALS:
test = !strcmp( xset_context->var[sub], eleval );
break;
case CONTEXT_COMP_NEQUALS:
test = strcmp( xset_context->var[sub], eleval );
break;
case CONTEXT_COMP_CONTAINS:
test = !!strstr( xset_context->var[sub], eleval );
break;
case CONTEXT_COMP_NCONTAINS:
test = !strstr( xset_context->var[sub], eleval );
break;
case CONTEXT_COMP_BEGINS:
test = g_str_has_prefix( xset_context->var[sub], eleval );
break;
case CONTEXT_COMP_NBEGINS:
test = !g_str_has_prefix( xset_context->var[sub], eleval );
break;
case CONTEXT_COMP_ENDS:
test = g_str_has_suffix( xset_context->var[sub], eleval );
break;
case CONTEXT_COMP_NENDS:
test = !g_str_has_suffix( xset_context->var[sub], eleval );
break;
case CONTEXT_COMP_LESS:
test = atoi( xset_context->var[sub] ) < atoi( eleval );
break;
case CONTEXT_COMP_GREATER:
test = atoi( xset_context->var[sub] ) > atoi( eleval );
break;
default:
test = match == NANY || match == NALL; //failsafe
}
if ( sep )
{
if ( test )
{
if ( sep_type == 1 ) // ||
break;
}
else
{
if ( sep_type == 2 ) // &&
break;
}
eleval = sep + 2;
while ( eleval[0] == ' ' )
eleval++;
}
else
eleval[0] = '\0';
} while ( eleval[0] != '\0' );
g_free( value );
if ( test )
{
any_match = TRUE;
no_match = FALSE;
if ( match == ANY || match == NANY || match == NALL )
break;
}
else
{
all_match = FALSE;
if ( match == ALL )
break;
}
}
if ( !is_rules )
return CONTEXT_SHOW;
gboolean is_match;
if ( match == ALL )
is_match = all_match;
else if ( match == NALL )
is_match = !any_match;
else if ( match == NANY )
is_match = no_match;
else // ANY
is_match = !no_match;
if ( action == CONTEXT_SHOW )
return is_match ? CONTEXT_SHOW : CONTEXT_HIDE;
if ( action == CONTEXT_ENABLE )
return is_match ? CONTEXT_SHOW : CONTEXT_DISABLE;
if ( action == CONTEXT_DISABLE )
return is_match ? CONTEXT_DISABLE : CONTEXT_SHOW;
// CONTEXT_HIDE
if ( is_match )
return CONTEXT_HIDE;
return def_disable ? CONTEXT_DISABLE : CONTEXT_SHOW;
}
char* context_build( ContextData* ctxt )
{
GtkTreeIter it;
char* value;
int sub, comp;
char* new_context = NULL;
char* old_context;
GtkTreeModel* model = gtk_tree_view_get_model( GTK_TREE_VIEW( ctxt->view ) );
if ( gtk_tree_model_get_iter_first( model, &it ) )
{
new_context = g_strdup_printf( "%d%%%%%%%%%%%d",
gtk_combo_box_get_active( GTK_COMBO_BOX( ctxt->box_action ) ),
gtk_combo_box_get_active( GTK_COMBO_BOX( ctxt->box_match ) ) );
do
{
gtk_tree_model_get( model, &it,
CONTEXT_COL_VALUE, &value,
CONTEXT_COL_SUB, &sub,
CONTEXT_COL_COMP, &comp,
-1 );
old_context = new_context;
new_context = g_strdup_printf( "%s%%%%%%%%%%%d%%%%%%%%%%%d%%%%%%%%%%%s",
old_context, sub, comp, value );
g_free( old_context );
}
while ( gtk_tree_model_iter_next( model, &it ) );
}
return new_context;
}
void enable_context( ContextData* ctxt )
{
GtkTreeIter it;
gboolean is_sel = gtk_tree_selection_get_selected(
gtk_tree_view_get_selection( GTK_TREE_VIEW( ctxt->view ) ),
NULL, NULL );
gtk_widget_set_sensitive( GTK_WIDGET( ctxt->btn_remove ), is_sel );
gtk_widget_set_sensitive( GTK_WIDGET( ctxt->btn_apply ), is_sel );
gtk_widget_set_sensitive( GTK_WIDGET( ctxt->hbox_match ),
gtk_tree_model_get_iter_first(
gtk_tree_view_get_model( GTK_TREE_VIEW( ctxt->view ) ), &it ) );
if ( xset_context && xset_context->valid )
{
char* rules = context_build( ctxt );
char* text = _("Current: Show");
if ( rules )
{
int action = xset_context_test( rules, FALSE );
if ( action == CONTEXT_HIDE )
text = _("Current: Hide");
else if ( action == CONTEXT_DISABLE )
text = _("Current: Disable");
}
gtk_label_set_text( ctxt->test, text );
}
}
void on_context_action_changed( GtkComboBox* box, ContextData* ctxt )
{
enable_context( ctxt );
}
char* context_display( int sub, int comp, char* value )
{
char* disp;
if ( value[0] == '\0' || value[0] == ' ' || g_str_has_suffix( value, " " ) )
disp = g_strdup_printf( "%s %s \"%s\"", _(context_sub[sub]), _(context_comp[comp]),
value );
else
disp = g_strdup_printf( "%s %s %s", _(context_sub[sub]), _(context_comp[comp]),
value );
return disp;
}
void on_context_button_press( GtkWidget* widget, ContextData* ctxt )
{
GtkTreeIter it;
GtkTreeSelection* tree_sel;
GtkTreeModel* model;
if ( widget == GTK_WIDGET( ctxt->btn_add ) ||
widget == GTK_WIDGET( ctxt->btn_apply ) )
{
int sub = gtk_combo_box_get_active( GTK_COMBO_BOX( ctxt->box_sub ) );
int comp = gtk_combo_box_get_active( GTK_COMBO_BOX( ctxt->box_comp ) );
if ( sub < 0 || comp < 0 )
return;
model = gtk_tree_view_get_model( GTK_TREE_VIEW( ctxt->view ) );
if ( widget == GTK_WIDGET( ctxt->btn_add ) )
gtk_list_store_append( GTK_LIST_STORE( model ), &it );
else
{
tree_sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( ctxt->view ) );
if ( !gtk_tree_selection_get_selected( tree_sel, NULL, &it ) )
return;
}
char* value = gtk_combo_box_text_get_active_text(
GTK_COMBO_BOX_TEXT( ctxt->box_value ) );
char* disp = context_display( sub, comp, value );
gtk_list_store_set( GTK_LIST_STORE( model ), &it,
CONTEXT_COL_DISP, disp,
CONTEXT_COL_SUB, sub,
CONTEXT_COL_COMP, comp,
CONTEXT_COL_VALUE, value,
-1 );
g_free( disp );
g_free( value );
gtk_widget_set_sensitive( GTK_WIDGET( ctxt->btn_ok ), TRUE );
if ( widget == GTK_WIDGET( ctxt->btn_add ) )
gtk_tree_selection_select_iter( gtk_tree_view_get_selection(
GTK_TREE_VIEW( ctxt->view ) ), &it );
enable_context( ctxt );
return;
}
//remove
model = gtk_tree_view_get_model( GTK_TREE_VIEW( ctxt->view ) );
tree_sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( ctxt->view ) );
if ( gtk_tree_selection_get_selected( tree_sel, NULL, &it ) )
gtk_list_store_remove( GTK_LIST_STORE( model ), &it );
enable_context( ctxt );
}
void on_context_sub_changed( GtkComboBox* box, ContextData* ctxt )
{
GtkTreeIter it;
char* value;
GtkTreeModel* model = gtk_combo_box_get_model( GTK_COMBO_BOX( ctxt->box_value ) );
while ( gtk_tree_model_get_iter_first( model, &it ) )
gtk_list_store_remove( GTK_LIST_STORE( model ), &it );
int sub = gtk_combo_box_get_active( GTK_COMBO_BOX( ctxt->box_sub ) );
if ( sub < 0 )
return;
char* elements = (char*)context_sub_list[sub];
char* def_comp = get_element_next( &elements );
if ( def_comp )
{
gtk_combo_box_set_active( GTK_COMBO_BOX( ctxt->box_comp ), atoi( def_comp ) );
g_free( def_comp );
}
while ( value = get_element_next( &elements ) )
{
gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( ctxt->box_value ), value );
g_free( value );
}
gtk_entry_set_text( GTK_ENTRY( gtk_bin_get_child( GTK_BIN( ctxt->box_value ) ) ), "" );
if ( xset_context && xset_context->valid )
gtk_label_set_text( ctxt->current_value, xset_context->var[sub] );
}
void on_context_row_activated( GtkTreeView* view, GtkTreePath* tree_path,
GtkTreeViewColumn* col, ContextData* ctxt )
{
GtkTreeIter it;
char* value;
int sub, comp;
GtkTreeModel* model = gtk_tree_view_get_model( GTK_TREE_VIEW( ctxt->view ) );
if ( !gtk_tree_model_get_iter( model, &it, tree_path ) )
return;
gtk_tree_model_get( model, &it,
CONTEXT_COL_VALUE, &value,
CONTEXT_COL_SUB, &sub,
CONTEXT_COL_COMP, &comp,
-1 );
gtk_combo_box_set_active( GTK_COMBO_BOX( ctxt->box_sub ), sub );
gtk_combo_box_set_active( GTK_COMBO_BOX( ctxt->box_comp ), comp );
gtk_entry_set_text( GTK_ENTRY( gtk_bin_get_child( GTK_BIN( ctxt->box_value ) ) ), value );
gtk_widget_grab_focus( ctxt->box_value );
//enable_context( ctxt );
}
gboolean on_current_value_button_press( GtkWidget *widget,
GdkEventButton *event,
ContextData* ctxt )
{
if ( event->type == GDK_2BUTTON_PRESS && event->button == 1 )
{
gtk_entry_set_text( GTK_ENTRY(
gtk_bin_get_child( GTK_BIN( ctxt->box_value ) ) ),
gtk_label_get_text( ctxt->current_value ) );
gtk_widget_grab_focus( ctxt->box_value );
return TRUE;
}
return FALSE;
}
void on_context_entry_insert( GtkEntryBuffer *buf, guint position, gchar *chars,
guint n_chars, gpointer user_data )
{ // remove linefeeds from pasted text
if ( !strchr( gtk_entry_buffer_get_text( buf ), '\n' ) )
return;
char* new_text = replace_string( gtk_entry_buffer_get_text( buf ), "\n", "", FALSE );
gtk_entry_buffer_set_text( buf, new_text, -1 );
g_free( new_text );
}
gboolean on_context_selection_change( GtkTreeSelection* tree_sel,
ContextData* ctxt )
{
enable_context( ctxt );
return FALSE;
}
static gboolean on_context_entry_keypress( GtkWidget *entry, GdkEventKey* event,
ContextData* ctxt )
{
if ( event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_KP_Enter )
{
if ( gtk_widget_get_sensitive( GTK_WIDGET( ctxt->btn_apply ) ) )
on_context_button_press( GTK_WIDGET( ctxt->btn_apply ), ctxt );
else
on_context_button_press( GTK_WIDGET( ctxt->btn_add ), ctxt );
return TRUE;
}
return FALSE;
}
void xset_context_dlg( XSet* set )
{
GtkTreeViewColumn* col;
GtkCellRenderer* renderer;
int i;
ContextData* ctxt = g_slice_new0( ContextData );
ctxt->parent = NULL;
if ( set->browser )
ctxt->parent = gtk_widget_get_toplevel( GTK_WIDGET( set->browser ) );
else if ( set->desktop )
ctxt->parent = gtk_widget_get_toplevel( GTK_WIDGET( set->desktop ) );
ctxt->dlg = gtk_dialog_new_with_buttons( _("Context Rules"),
GTK_WINDOW( ctxt->parent ),
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
NULL, NULL );
xset_set_window_icon( GTK_WINDOW( ctxt->dlg ) );
gtk_window_set_role( GTK_WINDOW( ctxt->dlg ), "context_dialog" );
int width = xset_get_int( "context_dlg", "x" );
int height = xset_get_int( "context_dlg", "y" );
if ( width && height )
gtk_window_set_default_size( GTK_WINDOW( ctxt->dlg ), width, height );
gtk_button_set_focus_on_click( GTK_BUTTON( gtk_dialog_add_button(
GTK_DIALOG( ctxt->dlg ),
GTK_STOCK_HELP,
GTK_RESPONSE_HELP ) ), FALSE );
gtk_dialog_add_button( GTK_DIALOG( ctxt->dlg ), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL );
ctxt->btn_ok = GTK_BUTTON( gtk_dialog_add_button( GTK_DIALOG( ctxt->dlg ),
GTK_STOCK_OK, GTK_RESPONSE_OK ) );
GtkListStore* list = gtk_list_store_new( 4, G_TYPE_STRING, G_TYPE_INT,
G_TYPE_INT, G_TYPE_STRING );
// Listview
ctxt->view = exo_tree_view_new();
gtk_tree_view_set_model( GTK_TREE_VIEW( ctxt->view ), GTK_TREE_MODEL( list ) );
exo_tree_view_set_single_click( (ExoTreeView*)ctxt->view, TRUE );
gtk_tree_view_set_headers_visible( GTK_TREE_VIEW( ctxt->view ), FALSE );
GtkWidget* scroll = gtk_scrolled_window_new( NULL, NULL );
gtk_scrolled_window_set_policy ( GTK_SCROLLED_WINDOW ( scroll ),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC );
gtk_container_add( GTK_CONTAINER( scroll ), ctxt->view );
g_signal_connect( G_OBJECT( ctxt->view ), "row-activated",
G_CALLBACK( on_context_row_activated ), ctxt );
g_signal_connect( G_OBJECT( gtk_tree_view_get_selection(
GTK_TREE_VIEW( ctxt->view ) ) ),
"changed",
G_CALLBACK( on_context_selection_change ), ctxt );
// col display
col = gtk_tree_view_column_new();
gtk_tree_view_column_set_sizing( col, GTK_TREE_VIEW_COLUMN_AUTOSIZE );
renderer = gtk_cell_renderer_text_new();
gtk_tree_view_column_pack_start( col, renderer, TRUE );
gtk_tree_view_column_set_attributes( col, renderer,
"text", CONTEXT_COL_DISP, NULL );
gtk_tree_view_append_column ( GTK_TREE_VIEW( ctxt->view ), col );
gtk_tree_view_column_set_expand ( col, TRUE );
// list buttons
ctxt->btn_remove = GTK_BUTTON( gtk_button_new_with_mnemonic( _("_Remove") ) );
gtk_button_set_image( ctxt->btn_remove, xset_get_image( "GTK_STOCK_REMOVE",
GTK_ICON_SIZE_BUTTON ) );
gtk_button_set_focus_on_click( ctxt->btn_remove, FALSE );
g_signal_connect( G_OBJECT( ctxt->btn_remove ), "clicked",
G_CALLBACK( on_context_button_press ), ctxt );
ctxt->btn_add = GTK_BUTTON( gtk_button_new_with_mnemonic( _("_Add") ) );
gtk_button_set_image( ctxt->btn_add, xset_get_image( "GTK_STOCK_ADD",
GTK_ICON_SIZE_BUTTON ) );
gtk_button_set_focus_on_click( ctxt->btn_add, FALSE );
g_signal_connect( G_OBJECT( ctxt->btn_add ), "clicked",
G_CALLBACK( on_context_button_press ), ctxt );
ctxt->btn_apply = GTK_BUTTON( gtk_button_new_with_mnemonic( _("A_pply") ) );
gtk_button_set_image( ctxt->btn_apply, xset_get_image( "GTK_STOCK_APPLY",
GTK_ICON_SIZE_BUTTON ) );
gtk_button_set_focus_on_click( ctxt->btn_apply, FALSE );
g_signal_connect( G_OBJECT( ctxt->btn_apply ), "clicked",
G_CALLBACK( on_context_button_press ), ctxt );
// boxes
ctxt->box_sub = gtk_combo_box_text_new();
gtk_combo_box_set_focus_on_click( GTK_COMBO_BOX( ctxt->box_sub ), FALSE );
for ( i = 0; i < G_N_ELEMENTS( context_sub ); i++ )
gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( ctxt->box_sub ), _(context_sub[i]) );
g_signal_connect( G_OBJECT( ctxt->box_sub ), "changed",
G_CALLBACK( on_context_sub_changed ), ctxt );
ctxt->box_comp = gtk_combo_box_text_new();
gtk_combo_box_set_focus_on_click( GTK_COMBO_BOX( ctxt->box_comp ), FALSE );
for ( i = 0; i < G_N_ELEMENTS( context_comp ); i++ )
gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( ctxt->box_comp ),
_(context_comp[i]) );
ctxt->box_value = gtk_combo_box_text_new_with_entry();
gtk_combo_box_set_focus_on_click( GTK_COMBO_BOX( ctxt->box_value ), FALSE );
#if GTK_CHECK_VERSION (3, 0, 0)
// see https://github.com/IgnorantGuru/spacefm/issues/43
// this seems to have no effect
gtk_combo_box_set_popup_fixed_width( GTK_COMBO_BOX( ctxt->box_value ), TRUE );
#endif
ctxt->box_match = gtk_combo_box_text_new();
gtk_combo_box_set_focus_on_click( GTK_COMBO_BOX( ctxt->box_match ), FALSE );
gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( ctxt->box_match ),
_("matches any rule:") );
gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( ctxt->box_match ),
_("matches all rules:") );
gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( ctxt->box_match ),
_("doesn't match any rule:") );
gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( ctxt->box_match ),
_("doesn't match all rules:") );
g_signal_connect( G_OBJECT( ctxt->box_match ), "changed",
G_CALLBACK( on_context_action_changed ), ctxt );
ctxt->box_action = gtk_combo_box_text_new();
gtk_combo_box_set_focus_on_click( GTK_COMBO_BOX( ctxt->box_action ), FALSE );
gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( ctxt->box_action ),
_("Show") );
gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( ctxt->box_action ),
_("Enable") );
gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( ctxt->box_action ),
_("Hide") );
gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( ctxt->box_action ),
_("Disable") );
g_signal_connect( G_OBJECT( ctxt->box_action ), "changed",
G_CALLBACK( on_context_action_changed ), ctxt );
ctxt->current_value = GTK_LABEL( gtk_label_new( NULL ) );
gtk_label_set_ellipsize( ctxt->current_value, PANGO_ELLIPSIZE_MIDDLE );
gtk_label_set_selectable( ctxt->current_value, TRUE );
gtk_misc_set_alignment( GTK_MISC( ctxt->current_value ), 0, 0 );
g_signal_connect( G_OBJECT( ctxt->current_value ), "button-press-event",
G_CALLBACK( on_current_value_button_press ), ctxt );
g_signal_connect_after( G_OBJECT( gtk_entry_get_buffer( GTK_ENTRY(
gtk_bin_get_child(
GTK_BIN( ctxt->box_value ) ) ) ) ),
"inserted-text",
G_CALLBACK( on_context_entry_insert ), NULL );
g_signal_connect( G_OBJECT( GTK_ENTRY(
gtk_bin_get_child( GTK_BIN( ctxt->box_value ) ) ) ),
"key-press-event",
G_CALLBACK( on_context_entry_keypress ), ctxt );
ctxt->test = GTK_LABEL( gtk_label_new( NULL ) );
//PACK
gtk_container_set_border_width( GTK_CONTAINER ( ctxt->dlg ), 10 );
ctxt->hbox_match = gtk_hbox_new( FALSE, 4 );
gtk_box_pack_start( GTK_BOX( ctxt->hbox_match ),
GTK_WIDGET( ctxt->box_action ), FALSE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX( ctxt->hbox_match ),
GTK_WIDGET( gtk_label_new( _("item if context") ) ), FALSE,
TRUE, 4 );
gtk_box_pack_start( GTK_BOX( ctxt->hbox_match ),
GTK_WIDGET( ctxt->box_match ), FALSE, TRUE, 4 );
gtk_box_pack_start( GTK_BOX( gtk_dialog_get_content_area (GTK_DIALOG( ctxt->dlg )) ),
GTK_WIDGET( ctxt->hbox_match ), FALSE, TRUE, 4 );
// GtkLabel* label = gtk_label_new( "Rules:" );
// gtk_misc_set_alignment( label, 0, 1 );
// gtk_box_pack_start( GTK_BOX( GTK_DIALOG( ctxt->dlg )->vbox ),
// GTK_WIDGET( label ), FALSE, TRUE, 8 );
gtk_box_pack_start( GTK_BOX( gtk_dialog_get_content_area (GTK_DIALOG( ctxt->dlg )) ),
GTK_WIDGET( scroll ), TRUE, TRUE, 4 );
GtkWidget* hbox_btns = gtk_hbox_new( FALSE, 4 );
gtk_box_pack_start( GTK_BOX( hbox_btns ),
GTK_WIDGET( ctxt->btn_remove ), FALSE, TRUE, 4 );
gtk_box_pack_start( GTK_BOX( hbox_btns ),
GTK_WIDGET( gtk_vseparator_new() ), FALSE, TRUE, 4 );
gtk_box_pack_start( GTK_BOX( hbox_btns ),
GTK_WIDGET( ctxt->btn_add ), FALSE, TRUE, 4 );
gtk_box_pack_start( GTK_BOX( hbox_btns ),
GTK_WIDGET( ctxt->btn_apply ), FALSE, TRUE, 4 );
gtk_box_pack_start( GTK_BOX( hbox_btns ),
GTK_WIDGET( ctxt->test ), TRUE, TRUE, 4 );
gtk_box_pack_start( GTK_BOX( gtk_dialog_get_content_area (GTK_DIALOG( ctxt->dlg )) ),
GTK_WIDGET( hbox_btns ), FALSE, TRUE, 4 );
ctxt->frame = GTK_FRAME( gtk_frame_new( _("Edit Rule") ) );
GtkWidget* vbox_frame = gtk_vbox_new( FALSE, 4 );
gtk_container_add ( GTK_CONTAINER ( ctxt->frame ), vbox_frame );
GtkWidget* hbox_frame = gtk_hbox_new( FALSE, 4 );
gtk_box_pack_start( GTK_BOX( hbox_frame ),
GTK_WIDGET( ctxt->box_sub ), FALSE, TRUE, 8 );
gtk_box_pack_start( GTK_BOX( hbox_frame ),
GTK_WIDGET( ctxt->box_comp ), FALSE, TRUE, 4 );
gtk_box_pack_start( GTK_BOX( vbox_frame ),
GTK_WIDGET( hbox_frame ), FALSE, TRUE, 4 );
GtkWidget* hbox = gtk_hbox_new( FALSE, 4 );
gtk_box_pack_start( GTK_BOX( hbox ),
GTK_WIDGET( ctxt->box_value ), TRUE, TRUE, 8 );
gtk_box_pack_start( GTK_BOX( vbox_frame ),
GTK_WIDGET( hbox ), TRUE, TRUE, 4 );
hbox = gtk_hbox_new( FALSE, 0 );
gtk_box_pack_start( GTK_BOX( hbox ),
GTK_WIDGET( gtk_label_new( _("Value:") ) ), FALSE, TRUE, 8 );
gtk_box_pack_start( GTK_BOX( hbox ),
GTK_WIDGET( ctxt->current_value ), TRUE, TRUE, 2 );
gtk_box_pack_start( GTK_BOX( vbox_frame ),
GTK_WIDGET( hbox ), TRUE, TRUE, 4 );
gtk_box_pack_start( GTK_BOX( gtk_dialog_get_content_area (GTK_DIALOG( ctxt->dlg )) ),
GTK_WIDGET( ctxt->frame ), FALSE, TRUE, 16 );
//gtk_box_pack_start( GTK_BUTTON_BOX ( GTK_DIALOG( ctxt->dlg )->action_area ),
// GTK_WIDGET( ctxt->test ), FALSE, TRUE, 16 );
/*
ctxt->hbox_match = gtk_hbox_new( FALSE, 4 );
gtk_box_pack_start( GTK_BOX( ctxt->hbox_match ),
GTK_WIDGET( gtk_label_new( "If context" ) ), FALSE, TRUE, 4 );
gtk_box_pack_start( GTK_BOX( ctxt->hbox_match ),
GTK_WIDGET( ctxt->box_match ), FALSE, TRUE, 4 );
gtk_box_pack_start( GTK_BOX( ctxt->hbox_match ),
GTK_WIDGET( gtk_label_new( "then" ) ), FALSE, TRUE, 4 );
gtk_box_pack_start( GTK_BOX( ctxt->hbox_match ),
GTK_WIDGET( ctxt->box_action ), FALSE, TRUE, 4 );
gtk_box_pack_start( GTK_BOX( GTK_DIALOG( ctxt->dlg )->vbox ),
GTK_WIDGET( ctxt->hbox_match ), FALSE, TRUE, 4 );
*/
// plugin?
XSet* mset = xset_get_plugin_mirror( set );
// set match / action
char* elements = mset->context;
char* action = get_element_next( &elements );
char* match = get_element_next( &elements );
if ( match && action )
{
i = atoi( match );
if ( i < 0 || i > 3 )
i = 0;
gtk_combo_box_set_active( GTK_COMBO_BOX( ctxt->box_match ), i );
i = atoi( action );
if ( i < 0 || i > 3 )
i = 0;
gtk_combo_box_set_active( GTK_COMBO_BOX( ctxt->box_action ), i );
g_free( match );
g_free( action );
}
else
{
gtk_combo_box_set_active( GTK_COMBO_BOX( ctxt->box_match ), 0 );
gtk_combo_box_set_active( GTK_COMBO_BOX( ctxt->box_action ), 0 );
if ( match )
g_free( match );
if ( action )
g_free( action );
}
// set rules
int sub, comp;
char* value;
char* disp;
GtkTreeIter it;
gboolean is_rules = FALSE;
while ( get_rule_next( &elements, &sub, &comp, &value ) )
{
disp = context_display( sub, comp, value );
gtk_list_store_append( GTK_LIST_STORE( list ), &it );
gtk_list_store_set( GTK_LIST_STORE( list ), &it,
CONTEXT_COL_DISP, disp,
CONTEXT_COL_SUB, sub,
CONTEXT_COL_COMP, comp,
CONTEXT_COL_VALUE, value,
-1 );
g_free( disp );
if ( value )
g_free( value );
is_rules = TRUE;
}
gtk_combo_box_set_active( GTK_COMBO_BOX( ctxt->box_sub ), 0 );
gtk_widget_set_sensitive( GTK_WIDGET( ctxt->btn_ok ), is_rules );
// run
gtk_widget_show_all( GTK_WIDGET( ctxt->dlg ) );
enable_context( ctxt );
int response;
while ( response = gtk_dialog_run( GTK_DIALOG( ctxt->dlg ) ) )
{
if ( response == GTK_RESPONSE_OK )
{
if ( mset->context )
g_free( mset->context );
mset->context = context_build( ctxt );
break;
}
else if ( response == GTK_RESPONSE_HELP )
xset_show_help( ctxt->dlg, NULL, "#designmode-style-context" );
else
break;
}
GtkAllocation allocation;
gtk_widget_get_allocation (GTK_WIDGET(ctxt->dlg), &allocation);
width = allocation.width;
height = allocation.height;
if ( width && height )
{
char* str = g_strdup_printf( "%d", width );
xset_set( "context_dlg", "x", str );
g_free( str );
str = g_strdup_printf( "%d", height );
xset_set( "context_dlg", "y", str );
g_free( str );
}
gtk_widget_destroy( ctxt->dlg );
g_slice_free( ContextData, ctxt );
}
void xset_show_help( GtkWidget* parent, XSet* set, const char* anchor )
{
GtkWidget* dlgparent = NULL;
char* url;
char* manual = NULL;
if ( parent )
dlgparent = parent;
else if ( set )
dlgparent = set->browser ? GTK_WIDGET( set->browser ) : GTK_WIDGET( set->desktop );
if ( !set || ( set && set->lock ) )
{
manual = xset_get_manual_url();
if ( !manual )
{
if ( xset_msg_dialog( dlgparent, GTK_MESSAGE_QUESTION,
_("User's Manual Not Found"), NULL,
GTK_BUTTONS_YES_NO,
_("Read the user's manual online?\n\nThe local copy of the SpaceFM user's manual was not found. Click Yes to read it online, or click No and then set the correct location in Help|Options|Manual Location."), NULL, NULL ) != GTK_RESPONSE_YES )
return;
manual = g_strdup( user_manual_url );
xset_set( "main_help_url", "s", manual );
}
}
if ( set )
{
if ( set->lock )
{
// built-in command
if ( set->line )
{
url = g_strdup_printf( "%s%s", manual, set->line );
xset_open_url( dlgparent, url );
g_free( url );
}
else
{
g_free( manual );
return;
}
}
else
{
// custom command or plugin
url = xset_custom_get_help( set );
if ( !url )
{
if ( set->plugin )
xset_msg_dialog( dlgparent, 0, _("Help Not Available"), NULL, 0, _("This plugin does not include a README file."), NULL, NULL );
else
xset_msg_dialog( dlgparent, 0, _("Creation Failed"), NULL, 0, _("An error occured creating a README file for this command."), NULL, NULL );
}
xset_edit( dlgparent, url, FALSE, TRUE );
g_free( url );
return;
}
}
else if ( anchor )
{
url = g_strdup_printf( "%s%s", manual, anchor );
xset_open_url( dlgparent, url );
g_free( url );
}
else
// just show the manual
xset_open_url( dlgparent, manual );
if ( manual )
g_free( manual );
if ( !xset_get_b( "main_help" ) )
{
xset_msg_dialog( dlgparent, 0, _("Manual Opened ?"), NULL, 0, _("The SpaceFM user's manual should have opened in your browser. If it didn't open, or if you would like to use a different browser, set your browser in Help|Options|Browser.\n\nThis message will not repeat."), NULL, NULL );
xset_set_b( "main_help", TRUE );
}
}
gboolean xset_design_setkey( GtkWidget *widget, GdkEventKey *event, GtkWidget* dlg )
{
GList* l;
int* newkey = (int*)g_object_get_data( G_OBJECT(dlg), "newkey" );
int* newkeymod = (int*)g_object_get_data( G_OBJECT(dlg), "newkeymod" );
GtkWidget* btn = (GtkWidget*)g_object_get_data( G_OBJECT(dlg), "btn" );
XSet* set = (XSet*)g_object_get_data( G_OBJECT(dlg), "set" );
XSet* set2;
XSet* keyset = NULL;
int keymod = ( event->state & ( GDK_SHIFT_MASK | GDK_CONTROL_MASK |
GDK_MOD1_MASK | GDK_SUPER_MASK | GDK_HYPER_MASK | GDK_META_MASK ) );
if ( !event->keyval ) // || ( event->keyval < 1000 && !keymod ) )
{
*newkey = 0;
*newkeymod = 0;
gtk_widget_set_sensitive( btn, FALSE );
gtk_message_dialog_format_secondary_text( GTK_MESSAGE_DIALOG( dlg ), NULL );
return TRUE;
}
gtk_widget_set_sensitive( btn, TRUE );
if ( *newkey != 0 && keymod == 0 )
{
if ( event->keyval == GDK_KEY_Return ||
event->keyval == GDK_KEY_KP_Enter )
{
// user pressed Enter after selecting a key, so click Set
gtk_button_clicked( GTK_BUTTON( btn ) );
return TRUE;
}
else if ( event->keyval == GDK_KEY_Escape && *newkey == GDK_KEY_Escape )
{
// user pressed Escape twice so click Unset
GtkWidget* btn_unset = (GtkWidget*)g_object_get_data( G_OBJECT(dlg),
"btn_unset" );
gtk_button_clicked( GTK_BUTTON( btn_unset ) );
return TRUE;
}
}
*newkey = 0;
*newkeymod = 0;
if ( set->shared_key )
keyset = xset_get( set->shared_key );
for ( l = xsets; l; l = l->next )
{
set2 = l->data;
if ( set2 && set2 != set && set2->key > 0 && set2->key == event->keyval
&& set2->keymod == keymod && set2 != keyset )
{
char* name;
if ( set2->desc && !strcmp( set2->desc, "@plugin@mirror@" )
&& set2->shared_key )
{
// set2 is plugin mirror
XSet* rset = xset_get( set2->shared_key );
if ( rset->menu_label )
name = clean_label( rset->menu_label, FALSE, FALSE );
else
name = g_strdup( "( no name )" );
}
else if ( set2->menu_label )
name = clean_label( set2->menu_label, FALSE, FALSE );
else
name = g_strdup( "( no name )" );
gtk_message_dialog_format_secondary_text( GTK_MESSAGE_DIALOG( dlg ), _(" Keycode: %#4x Modifier: %#x\n\nThis key combination is already assigned to '%s'.\n\nPress a different key or click Set to replace the current key assignment."), event->keyval, keymod, name );
g_free( name );
*newkey = event->keyval;
*newkeymod = keymod;
return TRUE;
}
}
gtk_message_dialog_format_secondary_text( GTK_MESSAGE_DIALOG( dlg ), _(" Keycode: %#4x Modifier: %#x"),
event->keyval, keymod );
*newkey = event->keyval;
*newkeymod = keymod;
return TRUE;
}
void xset_design_job( GtkWidget* item, XSet* set )
{
char* keymsg;
GtkWidget* vbox;
int newkey = 0, newkeymod = 0;
XSet* keyset;
XSet* newset;
XSet* mset;
XSet* childset;
XSet* set_next;
char* msg;
int response;
char* folder;
char* file;
char* custom_file;
char* cscript;
char* name;
char* prog;
char* command;
int buttons;
GtkWidget* dlgparent = NULL;
GtkWidget* dlg;
GtkClipboard* clip;
GtkWidget* parent = NULL;
if ( set->browser )
parent = gtk_widget_get_toplevel( GTK_WIDGET( set->browser ) );
else if ( set->desktop )
parent = gtk_widget_get_toplevel( GTK_WIDGET( set->desktop ) );
int job = GPOINTER_TO_INT( g_object_get_data( G_OBJECT(item), "job" ) );
//printf("activate job %d %s\n", job, set->name);
switch ( job ) {
case XSET_JOB_KEY:
if ( set->menu_label )
name = clean_label( set->menu_label, FALSE, TRUE );
else if ( g_str_has_prefix( set->name, "open_all_type_" ) )
{
keyset = xset_get( "open_all" );
name = clean_label( keyset->menu_label, FALSE, TRUE );
if ( set->shared_key )
g_free( set->shared_key );
set->shared_key = g_strdup( "open_all" );
}
else
name = g_strdup( "( no name )" );
keymsg = g_strdup_printf( _("Press your key combination for menu item '%s' then click Set. To remove the current key assignment, click Unset."), name );
g_free( name );
if ( parent )
dlgparent = gtk_widget_get_toplevel( parent );
dlg = gtk_message_dialog_new_with_markup( GTK_WINDOW( dlgparent ),
GTK_DIALOG_MODAL,
GTK_MESSAGE_QUESTION,
GTK_BUTTONS_NONE,
keymsg, NULL );
xset_set_window_icon( GTK_WINDOW( dlg ) );
GtkWidget* btn_cancel = gtk_button_new_from_stock( GTK_STOCK_CANCEL );
gtk_button_set_label( GTK_BUTTON( btn_cancel ), _("Cancel") );
gtk_button_set_image( GTK_BUTTON( btn_cancel ), xset_get_image( "GTK_STOCK_CANCEL",
GTK_ICON_SIZE_BUTTON ) );
gtk_dialog_add_action_widget( GTK_DIALOG( dlg ), btn_cancel, GTK_RESPONSE_CANCEL);
GtkWidget* btn_unset = gtk_button_new_from_stock( GTK_STOCK_NO );
gtk_button_set_label( GTK_BUTTON( btn_unset ), _("Unset") );
gtk_button_set_image( GTK_BUTTON( btn_unset ), xset_get_image( "GTK_STOCK_REMOVE",
GTK_ICON_SIZE_BUTTON ) );
gtk_dialog_add_action_widget( GTK_DIALOG( dlg ), btn_unset, GTK_RESPONSE_NO);
if ( set->shared_key )
keyset = xset_get( set->shared_key );
else
keyset = set;
if ( keyset->key <= 0 )
gtk_widget_set_sensitive( btn_unset, FALSE );
GtkWidget* btn = gtk_button_new_from_stock( GTK_STOCK_APPLY );
gtk_button_set_label( GTK_BUTTON( btn ), _("Set") );
gtk_button_set_image( GTK_BUTTON( btn ), xset_get_image( "GTK_STOCK_YES",
GTK_ICON_SIZE_BUTTON ) );
gtk_dialog_add_action_widget( GTK_DIALOG( dlg ), btn, GTK_RESPONSE_OK);
gtk_widget_set_sensitive( btn, FALSE );
g_object_set_data( G_OBJECT(dlg), "set", set );
g_object_set_data( G_OBJECT(dlg), "newkey", &newkey );
g_object_set_data( G_OBJECT(dlg), "newkeymod", &newkeymod );
g_object_set_data( G_OBJECT(dlg), "btn", btn );
g_object_set_data( G_OBJECT(dlg), "btn_unset", btn_unset );
g_signal_connect ( dlg, "key_press_event",
G_CALLBACK ( xset_design_setkey ), dlg );
gtk_widget_show_all( dlg );
gtk_window_set_title( GTK_WINDOW( dlg ), _("Set Key") );
response = gtk_dialog_run( GTK_DIALOG( dlg ) );
gtk_widget_destroy( dlg );
if ( response == GTK_RESPONSE_OK || response == GTK_RESPONSE_NO )
{
if ( response == GTK_RESPONSE_OK && ( newkey || newkeymod ) )
{
// clear duplicate key assignments
GList* l;
XSet* set2;
for ( l = xsets; l; l = l->next )
{
set2 = l->data;
if ( set2 && set2->key > 0 && set2->key == newkey
&& set2->keymod == newkeymod )
{
set2->key = 0;
set2->keymod = 0;
}
}
}
else if ( response == GTK_RESPONSE_NO )
{
newkey = -1; // unset
newkeymod = 0;
}
// plugin? set shared_key to mirror if not
if ( set->plugin && !set->shared_key )
xset_get_plugin_mirror( set );
// set new key
if ( set->shared_key )
keyset = xset_get( set->shared_key );
else
keyset = set;
keyset->key = newkey;
keyset->keymod = newkeymod;
}
break;
case XSET_JOB_ICON:
mset = xset_get_plugin_mirror( set );
xset_text_dialog( parent, _("Change Icon"), NULL, FALSE, _(icon_desc), NULL,
mset->icon, &mset->icon,
NULL, FALSE, "#designmode-designmenu-icon" );
break;
case XSET_JOB_LABEL:
if ( g_str_has_prefix( set->name, "open_all_type_" ) )
keyset = xset_get( "open_all" );
else
keyset = set;
xset_text_dialog( parent, _("Change Menu Name"), NULL, FALSE, _(enter_menu_name),
NULL, keyset->menu_label, &keyset->menu_label,
NULL, FALSE, "#designmode-designmenu-name" );
break;
case XSET_JOB_EDIT:
if ( atoi( set->x ) == 0 )
{
// line
xset_text_dialog( parent, _("Edit Command Line"), NULL, TRUE,
_(enter_command_line), NULL, set->line, &set->line,
NULL, FALSE, "#designmode-command-line" );
}
else if ( atoi( set->x ) == 1 )
{
// script
cscript = xset_custom_get_script( set, !set->plugin );
if ( !cscript )
break;
xset_edit( parent, cscript, FALSE, TRUE );
g_free( cscript );
}
else if ( atoi( set->x ) == 2 )
{
// custom
if ( !set->z || !g_file_test( set->z, G_FILE_TEST_EXISTS ) )
goto _XSET_JOB_CUSTOM;
if ( mime_type_is_text_file( set->z, NULL ) )
xset_edit( parent, set->z, FALSE, TRUE );
else
goto _XSET_JOB_CUSTOM;
}
break;
case XSET_JOB_EDIT_ROOT:
if ( atoi( set->x ) == 1 )
{
// script
cscript = xset_custom_get_script( set, !set->plugin );
if ( !cscript )
break;
xset_edit( parent, cscript, TRUE, FALSE );
g_free( cscript );
}
else if ( atoi( set->x ) == 2 )
{
// custom
if ( !set->z || !g_file_test( set->z, G_FILE_TEST_EXISTS ) )
goto _XSET_JOB_CUSTOM;
if ( mime_type_is_text_file( set->z, NULL ) )
xset_edit( parent, set->z, TRUE, FALSE );
else
goto _XSET_JOB_CUSTOM;
}
break;
case XSET_JOB_COPYNAME:
clip = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD );
if ( atoi( set->x ) == 0 )
{
// line
gtk_clipboard_set_text ( clip, set->line , -1 );
}
else if ( atoi( set->x ) == 1 )
{
// script
cscript = xset_custom_get_script( set, TRUE );
if ( !cscript )
break;
gtk_clipboard_set_text ( clip, cscript , -1 );
g_free( cscript );
}
else if ( atoi( set->x ) == 2 )
{
// custom
gtk_clipboard_set_text ( clip, set->z , -1 );
}
break;
case XSET_JOB_LINE:
if ( xset_text_dialog( parent, _("Edit Command Line"), NULL, TRUE,
_(enter_command_line), NULL, set->line, &set->line,
NULL, FALSE, "#designmode-command-line" ) )
xset_set_set( set, "x", "0" );
break;
case XSET_JOB_SCRIPT:
xset_set_set( set, "x", "1" );
cscript = xset_custom_get_script( set, TRUE );
if ( !cscript )
break;
xset_edit( parent, cscript, FALSE, FALSE );
g_free( cscript );
break;
case XSET_JOB_CUSTOM:
_XSET_JOB_CUSTOM:
if ( set->z && set->z[0] != '\0' )
{
folder = g_path_get_dirname( set->z );
file = g_path_get_basename( set->z );
}
else
{
folder = g_strdup_printf( "/usr/bin" );
file = NULL;
}
if ( custom_file = xset_file_dialog( parent, GTK_FILE_CHOOSER_ACTION_OPEN,
_("Choose Custom Executable"), folder, file ) )
{
xset_set_set( set, "x", "2" );
xset_set_set( set, "z", custom_file );
g_free( custom_file );
}
g_free( file );
g_free( folder );
break;
case XSET_JOB_USER:
if ( !set->plugin )
xset_text_dialog( parent, _("Run As User"), NULL, FALSE, _("Run this command as username:\n\n( Leave blank for current user )"), NULL, set->y, &set->y, NULL, FALSE, "#designmode-command-user" );
break;
case XSET_JOB_COMMAND:
if ( g_str_has_prefix( set->name, "open_all_type_" ) )
{
name = set->name + 14;
msg = g_strdup_printf( _("You are adding a custom command to the Default menu item. This item will automatically have a pre-context - it will only appear when the MIME type of the first selected file matches the current type '%s'.\n\nAdd commands or menus here which you only want to appear for this one MIME type."), name[0] == '\0' ? "(none)" : name );
if ( xset_msg_dialog( parent, 0, _("New Context Command"), NULL,
GTK_BUTTONS_OK_CANCEL, msg, NULL, NULL ) != GTK_RESPONSE_OK )
{
g_free( msg );
break;
}
g_free( msg );
}
name = g_strdup_printf( _("New _Command") );
if ( !xset_text_dialog( parent, _("Set Menu Name"), NULL, FALSE, _(enter_menu_name_new),
NULL, name, &name,
NULL, FALSE,
"#designmode-designmenu-new" ) )
{
g_free( name );
break;
}
char* line = g_strdup( "" );
if ( !xset_text_dialog( parent, _("Set Command Line"), NULL, TRUE,
_(enter_command_line), NULL, line, &line,
NULL, FALSE, "#designmode-command-line" ) )
{
g_free( line );
break;
}
newset = xset_custom_new();
newset->prev = g_strdup( set->name );
newset->next = set->next;
if ( set->next )
{
set_next = xset_get( set->next );
if ( set_next->prev )
g_free( set_next->prev );
set_next->prev = g_strdup( newset->name );
}
set->next = g_strdup( newset->name );
newset->menu_label = name;
newset->line = line;
if ( set->tool )
{
newset->tool = XSET_B_TRUE;
newset->icon = g_strdup_printf( "gtk-execute" );
}
break;
case XSET_JOB_SUBMENU:
if ( g_str_has_prefix( set->name, "open_all_type_" ) )
{
name = set->name + 14;
msg = g_strdup_printf( _("You are adding a custom submenu to the Default menu item. This item will automatically have a pre-context - it will only appear when the MIME type of the first selected file matches the current type '%s'.\n\nAdd commands or menus here which you only want to appear for this one MIME type."), name[0] == '\0' ? _("(none)") : name );
if ( xset_msg_dialog( parent, 0, "New Context Submenu", NULL, GTK_BUTTONS_OK_CANCEL, msg, NULL, NULL ) != GTK_RESPONSE_OK )
{
g_free( msg );
break;
}
g_free( msg );
}
name = NULL;
if ( !xset_text_dialog( parent, _("Set Submenu Name"), NULL, FALSE, _("Enter submenu name:\n\nPrecede a character with an underscore (_) to underline that character as a shortcut key if desired."), NULL, _("New _Submenu"), &name, NULL, FALSE, "#designmode-designmenu-name" ) || !name )
break;
newset = xset_custom_new();
newset->prev = g_strdup( set->name );
newset->next = set->next;
if ( set->next )
{
set_next = xset_get( set->next );
if ( set_next->prev )
g_free( set_next->prev );
set_next->prev = g_strdup( newset->name );
}
set->next = g_strdup( newset->name );
newset->menu_label = name;
newset->menu_style = XSET_MENU_SUBMENU;
if ( set->tool )
{
newset->tool = XSET_B_TRUE;
newset->icon = g_strdup_printf( "gtk-execute" );
}
if ( newset->tool )
newset->icon = g_strdup_printf( "gtk-execute" );
childset = xset_custom_new();
newset->child = g_strdup( childset->name );
childset->parent = g_strdup( newset->name );
childset->menu_label = g_strdup_printf( _("New _Command") );
if ( set->tool )
{
childset->tool = XSET_B_TRUE;
childset->icon = g_strdup_printf( "gtk-execute" );
}
break;
case XSET_JOB_SEP:
newset = xset_custom_new();
newset->prev = g_strdup( set->name );
newset->next = set->next;
if ( set->next )
{
set_next = xset_get( set->next );
if ( set_next->prev )
g_free( set_next->prev );
set_next->prev = g_strdup( newset->name );
}
set->next = g_strdup( newset->name );
newset->menu_style = XSET_MENU_SEP;
if ( set->tool )
newset->tool = XSET_B_TRUE;
break;
case XSET_JOB_CUT:
set_clipboard = set;
clipboard_is_cut = TRUE;
break;
case XSET_JOB_COPY:
set_clipboard = set;
clipboard_is_cut = FALSE;
break;
case XSET_JOB_PASTE:
if ( !set_clipboard )
break;
if ( clipboard_is_cut )
{
xset_custom_remove( set_clipboard );
set_clipboard->prev = g_strdup( set->name );
set_clipboard->next = set->next; //swap string
if ( set->next )
{
set_next = xset_get( set->next );
if ( set_next->prev )
g_free( set_next->prev );
set_next->prev = g_strdup( set_clipboard->name );
}
set->next = g_strdup( set_clipboard->name );
if ( set->tool )
{
set_clipboard->tool = XSET_B_TRUE;
if ( !set_clipboard->icon )
set_clipboard->icon = g_strdup_printf( "gtk-execute" );
}
else
set_clipboard->tool = XSET_B_UNSET;
set_clipboard = NULL;
}
else
{
newset = xset_custom_copy( set_clipboard, FALSE );
newset->prev = g_strdup( set->name );
newset->next = set->next;
if ( set->next )
{
set_next = xset_get( set->next );
if ( set_next->prev )
g_free( set_next->prev );
set_next->prev = g_strdup( newset->name );
}
set->next = g_strdup( newset->name );
if ( set->tool )
{
newset->tool = XSET_B_TRUE;
if ( !newset->icon )
newset->icon = g_strdup_printf( "gtk-execute" );
}
else
newset->tool = XSET_B_UNSET;
}
break;
case XSET_JOB_REMOVE:
if ( set->plugin )
{
xset_remove_plugin( parent, set->browser, set );
break;
}
if ( set->menu_label )
{
name = clean_label( set->menu_label, FALSE, FALSE );
}
else
name = g_strdup( _("( no name )") );
if ( set->child && set->menu_style == XSET_MENU_SUBMENU )
{
msg = g_strdup_printf( _("Permanently remove the '%s' SUBMENU AND ALL COMMANDS WITHIN IT?\n\nThis action will delete all settings and files associated with these items."), name );
buttons = GTK_BUTTONS_YES_NO;
}
else
{
msg = g_strdup_printf( _("Permanently remove the '%s' command?\n\nThis action will delete all settings and files associated with this command."), name );
buttons = GTK_BUTTONS_OK_CANCEL;
}
g_free( name );
if ( set->menu_style != XSET_MENU_SEP && !app_settings.no_confirm )
{
if ( parent )
dlgparent = gtk_widget_get_toplevel( parent );
dlg = gtk_message_dialog_new( GTK_WINDOW( dlgparent ),
GTK_DIALOG_MODAL,
GTK_MESSAGE_WARNING,
buttons,
msg, NULL );
xset_set_window_icon( GTK_WINDOW( dlg ) );
gtk_window_set_title( GTK_WINDOW( dlg ), _("Confirm Remove") );
gtk_widget_show_all( dlg );
response = gtk_dialog_run( GTK_DIALOG( dlg ) );
gtk_widget_destroy( dlg );
if ( response == GTK_RESPONSE_CANCEL )
break;
}
g_free( msg );
xset_custom_remove( set );
xset_custom_delete( set, FALSE );
break;
case XSET_JOB_EXPORT:
if ( !set->lock )
xset_custom_export( parent, set->browser, set );
break;
case XSET_JOB_NORMAL:
set->menu_style = XSET_MENU_NORMAL;
break;
case XSET_JOB_CHECK:
set->menu_style = XSET_MENU_CHECK;
break;
case XSET_JOB_CONFIRM:
if ( !set->desc )
set->desc = g_strdup( _("Are you sure?") );
if ( xset_text_dialog( parent, _("Dialog Message"), NULL, TRUE, _("Enter the message to be displayed in this dialog:\n\nUse:\n\t\\n\tnewline\n\t\\t\ttab"), NULL, set->desc, &set->desc, NULL, FALSE, "#designmode-style-input" ) )
set->menu_style = XSET_MENU_CONFIRM;
break;
case XSET_JOB_DIALOG:
if ( xset_text_dialog( parent, _("Dialog Message"), NULL, TRUE, _("Enter the message to be displayed in this dialog:\n\nUse:\n\t\\n\tnewline\n\t\\t\ttab"), NULL, set->desc, &set->desc, NULL, FALSE, "#designmode-style-input" ) )
set->menu_style = XSET_MENU_STRING;
break;
case XSET_JOB_MESSAGE:
xset_text_dialog( parent, _("Dialog Message"), NULL, TRUE, _("Enter the message to be displayed in this dialog:\n\nUse:\n\t\\n\tnewline\n\t\\t\ttab"), NULL, set->desc, &set->desc, NULL, FALSE, "#designmode-style-message" );
break;
case XSET_JOB_CONTEXT:
xset_context_dlg( set );
break;
case XSET_JOB_IGNORE_CONTEXT:
xset_set_b( "context_dlg", !xset_get_b( "context_dlg" ) );
break;
case XSET_JOB_HELP:
if ( parent )
dlgparent = gtk_widget_get_toplevel( parent );
xset_show_help( dlgparent, set, NULL );
break;
case XSET_JOB_BROWSE_FILES:
if ( set->plugin )
{
folder = g_build_filename( set->plug_dir, "files", NULL );
if ( !g_file_test( folder, G_FILE_TEST_EXISTS ) )
{
g_free( folder );
folder = g_build_filename( set->plug_dir, set->plug_name, NULL );
}
}
else
{
cscript = xset_custom_get_script( set, FALSE ); //backwards compat copy
if ( cscript )
g_free( cscript );
folder = g_build_filename( settings_config_dir, "scripts",
set->name, NULL );
}
if ( !g_file_test( folder, G_FILE_TEST_EXISTS ) && !set->plugin )
{
g_mkdir_with_parents( folder, 0700 );
chmod( folder, 0700 );
}
if ( set->browser )
{
ptk_file_browser_emit_open( set->browser, folder, PTK_OPEN_DIR );
}
else if ( set->desktop )
{
prog = g_find_program_in_path( g_get_prgname() );
if ( !prog )
prog = g_strdup( g_get_prgname() );
if ( !prog )
prog = g_strdup( "spacefm" );
command = g_strdup_printf( "%s %s", prog, folder );
g_spawn_command_line_sync( command, NULL, NULL, NULL, NULL );
g_free( prog );
g_free( command );
g_free( folder );
}
break;
case XSET_JOB_BROWSE_DATA:
if ( set->plugin )
{
mset = xset_get_plugin_mirror( set );
folder = g_build_filename( settings_config_dir, "plugin-data",
mset->name, NULL );
}
else
folder = g_build_filename( settings_config_dir, "plugin-data",
set->name, NULL );
if ( !g_file_test( folder, G_FILE_TEST_EXISTS ) )
{
g_mkdir_with_parents( folder, 0700 );
chmod( folder, 0700 );
}
if ( set->browser )
{
ptk_file_browser_emit_open( set->browser, folder, PTK_OPEN_DIR );
}
else if ( set->desktop )
{
prog = g_find_program_in_path( g_get_prgname() );
if ( !prog )
prog = g_strdup( g_get_prgname() );
if ( !prog )
prog = g_strdup( "spacefm" );
command = g_strdup_printf( "%s %s", prog, folder );
g_spawn_command_line_sync( command, NULL, NULL, NULL, NULL );
g_free( prog );
g_free( command );
g_free( folder );
}
break;
case XSET_JOB_BROWSE_PLUGIN:
if ( set->plugin && set->plug_dir )
{
if ( set->browser )
{
ptk_file_browser_emit_open( set->browser, set->plug_dir, PTK_OPEN_DIR );
}
else if ( set->desktop ) // should never happen in current version
{
prog = g_find_program_in_path( g_get_prgname() );
if ( !prog )
prog = g_strdup( g_get_prgname() );
if ( !prog )
prog = g_strdup( "spacefm" );
command = g_strdup_printf( "%s %s", prog, set->plug_dir );
g_spawn_command_line_sync( command, NULL, NULL, NULL, NULL );
g_free( prog );
g_free( command );
}
}
break;
case XSET_JOB_TERM:
mset = xset_get_plugin_mirror( set );
if ( mset->in_terminal == XSET_B_TRUE )
mset->in_terminal = XSET_B_UNSET;
else
{
mset->in_terminal = XSET_B_TRUE;
mset->task = XSET_B_FALSE;
}
break;
case XSET_JOB_KEEP:
mset = xset_get_plugin_mirror( set );
if ( mset->keep_terminal == XSET_B_TRUE )
mset->keep_terminal = XSET_B_UNSET;
else
mset->keep_terminal = XSET_B_TRUE;
break;
case XSET_JOB_TASK:
mset = xset_get_plugin_mirror( set );
if ( mset->task == XSET_B_TRUE )
mset->task = XSET_B_UNSET;
else
mset->task = XSET_B_TRUE;
break;
case XSET_JOB_POP:
mset = xset_get_plugin_mirror( set );
if ( mset->task_pop == XSET_B_TRUE )
mset->task_pop = XSET_B_UNSET;
else
mset->task_pop = XSET_B_TRUE;
break;
case XSET_JOB_ERR:
mset = xset_get_plugin_mirror( set );
if ( mset->task_err == XSET_B_TRUE )
mset->task_err = XSET_B_UNSET;
else
mset->task_err = XSET_B_TRUE;
break;
case XSET_JOB_OUT:
mset = xset_get_plugin_mirror( set );
if ( mset->task_out == XSET_B_TRUE )
mset->task_out = XSET_B_UNSET;
else
mset->task_out = XSET_B_TRUE;
break;
case XSET_JOB_SCROLL:
mset = xset_get_plugin_mirror( set );
if ( mset->scroll_lock == XSET_B_TRUE )
mset->scroll_lock = XSET_B_UNSET;
else
mset->scroll_lock = XSET_B_TRUE;
break;
case XSET_JOB_SHOW:
if ( gtk_check_menu_item_get_active( GTK_CHECK_MENU_ITEM( item ) ) )
set->tool = XSET_B_TRUE;
else
set->tool = XSET_B_FALSE;
break;
}
//if ( set->plugin )
// main_window_on_plugins_change( NULL );
// autosave
xset_autosave( set->browser );
}
void on_design_radio_toggled( GtkCheckMenuItem* item, XSet* set )
{
if ( gtk_check_menu_item_get_active( GTK_CHECK_MENU_ITEM( item ) ) )
xset_design_job( GTK_WIDGET( item ), set );
}
gboolean xset_job_is_valid( XSet* set, int job )
{
gboolean no_remove = FALSE;
gboolean toolexecsub = FALSE;
gboolean no_paste = FALSE;
gboolean open_all = FALSE;
XSet* sett;
if ( !set )
return FALSE;
if ( set->plugin )
{
if ( !set->plug_dir )
return FALSE;
if ( !set->plugin_top || strstr( set->plug_dir, "/included/" ) )
no_remove = TRUE;
}
// only first level custom tool submenu is executable
if ( set->tool && !set->lock && set->menu_style == XSET_MENU_SUBMENU )
{
sett = set;
while ( sett->prev )
{
sett = xset_get( sett->prev );
if ( sett->lock )
{
toolexecsub = TRUE;
break;
}
}
if ( !toolexecsub && sett->parent )
{
sett = xset_get( sett->parent );
if ( sett->lock )
toolexecsub = TRUE;
}
}
if ( set == set_clipboard )
{
if ( clipboard_is_cut )
// don't allow cut paste to self
no_paste = TRUE;
}
else if ( set_clipboard && set_clipboard->menu_style == XSET_MENU_SUBMENU )
// don't allow paste of submenu to self or below
no_paste = xset_clipboard_in_set( set );
// control open_all item
if ( g_str_has_prefix( set->name, "open_all_type_" ) )
open_all = TRUE;
switch ( job ) {
case XSET_JOB_KEY:
return ( set->menu_style < XSET_MENU_SUBMENU || toolexecsub );
case XSET_JOB_ICON:
return ( ( set->menu_style == XSET_MENU_NORMAL
|| set->menu_style == XSET_MENU_STRING
|| set->menu_style == XSET_MENU_FONTDLG
|| set->menu_style == XSET_MENU_COLORDLG
|| set->menu_style == XSET_MENU_SUBMENU
|| set->tool ) && !open_all );
case XSET_JOB_EDIT:
return ( !set->lock && (
set->menu_style < XSET_MENU_SUBMENU || toolexecsub ) );
case XSET_JOB_COMMAND:
return !set->plugin;
case XSET_JOB_CUT:
return ( !set->lock && !set->plugin );
case XSET_JOB_COPY:
return !set->lock;
case XSET_JOB_PASTE:
return ( set_clipboard && !no_paste && !set->plugin
&& !( set->tool && set_clipboard->menu_style ==
XSET_MENU_SUBMENU ) );
case XSET_JOB_REMOVE:
return ( !set->lock && !no_remove );
case XSET_JOB_CONTEXT:
return ( xset_context && xset_context->valid && !open_all );
case XSET_JOB_HELP:
return ( !set->lock || ( set->lock && set->line ) );
}
return FALSE;
}
gboolean xset_design_menu_keypress( GtkWidget* widget, GdkEventKey* event,
XSet* set )
{
int job = -1;
GtkWidget* item = gtk_menu_shell_get_selected_item( GTK_MENU_SHELL( widget ) );
if ( !item )
return FALSE;
int keymod = ( event->state & ( GDK_SHIFT_MASK | GDK_CONTROL_MASK |
GDK_MOD1_MASK | GDK_SUPER_MASK | GDK_HYPER_MASK | GDK_META_MASK ) );
if ( keymod == 0 )
{
if ( event->keyval == GDK_KEY_F1 )
{
char* help = NULL;
job = GPOINTER_TO_INT( g_object_get_data( G_OBJECT(item), "job" ) );
switch ( job ) {
case XSET_JOB_KEY:
help = "#designmode-designmenu-key";
break;
case XSET_JOB_ICON:
help = "#designmode-designmenu-icon";
break;
case XSET_JOB_LABEL:
help = "#designmode-designmenu-name";
break;
case XSET_JOB_EDIT:
help = "#designmode-command-edit";
break;
case XSET_JOB_EDIT_ROOT:
help = "#designmode-command-edit";
break;
case XSET_JOB_COPYNAME:
help = "#designmode-command-copy";
break;
case XSET_JOB_LINE:
help = "#designmode-command-line";
break;
case XSET_JOB_SCRIPT:
help = "#designmode-command-script";
break;
case XSET_JOB_CUSTOM:
help = "#designmode-command-custom";
break;
case XSET_JOB_USER:
help = "#designmode-command-user";
break;
case XSET_JOB_COMMAND:
help = "#designmode-designmenu-new";
break;
case XSET_JOB_SUBMENU:
help = "#designmode-designmenu-submenu";
break;
case XSET_JOB_SEP:
help = "#designmode-designmenu-separator";
break;
case XSET_JOB_CUT:
help = "#designmode-designmenu-cut";
break;
case XSET_JOB_COPY:
help = "#designmode-designmenu-copy";
break;
case XSET_JOB_PASTE:
help = "#designmode-designmenu-paste";
break;
case XSET_JOB_REMOVE:
help = "#designmode-designmenu-remove";
break;
case XSET_JOB_EXPORT:
help = "#designmode-designmenu-export";
break;
case XSET_JOB_NORMAL:
help = "#designmode-style-normal";
break;
case XSET_JOB_CHECK:
help = "#designmode-style-checkbox";
break;
case XSET_JOB_CONFIRM:
help = "#designmode-style-confirm";
break;
case XSET_JOB_DIALOG:
help = "#designmode-style-input";
break;
case XSET_JOB_MESSAGE:
help = "#designmode-style-message";
break;
case XSET_JOB_CONTEXT:
help = "#designmode-style-context";
break;
case XSET_JOB_IGNORE_CONTEXT:
help = "#designmode-style-ignorecontext";
break;
case XSET_JOB_HELP:
help = "#designmode-designmenu-help";
break;
case XSET_JOB_HELP_STYLE:
help = "#designmode-style";
break;
case XSET_JOB_HELP_COMMAND:
help = "#designmode-command";
break;
case XSET_JOB_HELP_BROWSE:
help = "#designmode-command-browse";
break;
case XSET_JOB_BROWSE_FILES:
help = "#designmode-command-browse-files";
break;
case XSET_JOB_BROWSE_DATA:
help = "#designmode-command-browse-data";
break;
case XSET_JOB_BROWSE_PLUGIN:
help = "#designmode-command-browse-plugin";
break;
case XSET_JOB_TERM:
help = "#designmode-command-terminal";
break;
case XSET_JOB_KEEP:
help = "#designmode-command-keep";
break;
case XSET_JOB_TASK:
help = "#designmode-command-task";
break;
case XSET_JOB_POP:
help = "#designmode-command-popup";
break;
case XSET_JOB_ERR:
help = "#designmode-command-poperr";
break;
case XSET_JOB_OUT:
help = "#designmode-command-popout";
break;
case XSET_JOB_SCROLL:
help = "#designmode-command-scroll";
break;
case XSET_JOB_SHOW:
help = "#designmode-designmenu-show";
break;
}
if ( !help )
help = "#designmode";
gtk_menu_shell_deactivate( GTK_MENU_SHELL( widget ) );
xset_show_help( NULL, NULL, help );
return TRUE;
}
else if ( event->keyval == GDK_KEY_F3 )
job = XSET_JOB_CONTEXT;
else if ( event->keyval == GDK_KEY_F4 )
job = XSET_JOB_EDIT;
else if ( event->keyval == GDK_KEY_Delete )
job = XSET_JOB_REMOVE;
else if ( event->keyval == GDK_KEY_Insert )
job = XSET_JOB_COMMAND;
}
else if ( keymod == GDK_CONTROL_MASK )
{
if ( event->keyval == GDK_KEY_c )
job = XSET_JOB_COPY;
else if ( event->keyval == GDK_KEY_x )
job = XSET_JOB_CUT;
else if ( event->keyval == GDK_KEY_v )
job = XSET_JOB_PASTE;
else if ( event->keyval == GDK_KEY_e )
{
if ( set->lock )
{
return FALSE;
}
else
job = XSET_JOB_EDIT;
}
else if ( event->keyval == GDK_KEY_k )
job = XSET_JOB_KEY;
else if ( event->keyval == GDK_KEY_i )
job = XSET_JOB_ICON;
}
if ( job != -1 )
{
if ( xset_job_is_valid( set, job ) )
{
gtk_menu_shell_deactivate( GTK_MENU_SHELL( widget ) );
g_object_set_data( G_OBJECT( item ), "job", GINT_TO_POINTER( job ) );
xset_design_job( item, set );
return TRUE;
}
}
return FALSE;
}
void xset_design_destroy( GtkWidget* item, GtkWidget* design_menu )
{
//printf( "xset_design_destroy\n");
// close design_menu if menu deactivated
gtk_widget_set_sensitive( item, TRUE );
gtk_menu_shell_deactivate( GTK_MENU_SHELL( design_menu ) );
}
void on_menu_hide(GtkWidget *widget, GtkWidget* design_menu )
{
gtk_widget_set_sensitive( widget, TRUE );
gtk_menu_shell_deactivate( GTK_MENU_SHELL( design_menu ) );
}
static void set_check_menu_item_block( GtkWidget* item )
{
g_signal_handlers_block_matched( item, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
xset_design_job, NULL );
gtk_check_menu_item_set_active( GTK_CHECK_MENU_ITEM( item ), TRUE );
g_signal_handlers_unblock_matched( item, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
xset_design_job, NULL );
}
GtkWidget* xset_design_additem( GtkWidget* menu, char* label, gchar* stock_icon,
int job, XSet* set )
{
GtkWidget* item;
if ( stock_icon )
{
if ( !strcmp( stock_icon, "@check" ) )
item = gtk_check_menu_item_new_with_mnemonic( label );
else
{
item = gtk_image_menu_item_new_with_mnemonic( label );
GtkWidget* image = gtk_image_new_from_stock( stock_icon,
GTK_ICON_SIZE_MENU );
if ( image )
gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM( item ),
image );
}
}
else
item = gtk_menu_item_new_with_mnemonic( label );
g_object_set_data( G_OBJECT(item), "job", GINT_TO_POINTER( job ) );
gtk_container_add ( GTK_CONTAINER ( menu ), item );
g_signal_connect( item, "activate", G_CALLBACK( xset_design_job ), set );
return item;
}
static void xset_design_show_menu( GtkWidget* menu, XSet* set, guint button, guint32 time )
{
GtkWidget* newitem;
GtkWidget* newitem2;
GtkWidget* newitem3;
GtkWidget* newitem4;
GtkWidget* submenu;
GtkWidget* submenu2;
GSList* radio_group;
char* label;
char* path;
gboolean no_remove = FALSE;
gboolean toolexecsub = FALSE;
gboolean toolshow = FALSE;
gboolean no_paste = FALSE;
gboolean open_all = FALSE;
XSet* sett;
XSet* mset;
if ( set->plugin && set->shared_key )
mset = xset_get_plugin_mirror( set );
else
mset = set;
if ( set->plugin )
{
if ( set->plug_dir )
{
if ( !set->plugin_top || strstr( set->plug_dir, "/included/" ) )
no_remove = TRUE;
}
else
no_remove = TRUE;
}
// only first level custom tool submenu is executable
if ( set->tool && !set->lock && set->menu_style == XSET_MENU_SUBMENU )
{
sett = set;
while ( sett->prev )
{
sett = xset_get( sett->prev );
if ( sett->lock )
{
toolexecsub = TRUE;
break;
}
}
if ( !toolexecsub && sett->parent )
{
sett = xset_get( sett->parent );
if ( sett->lock )
toolexecsub = TRUE;
}
}
// show "Show"?
if ( set->tool )
{
if ( set->lock )
toolshow = TRUE;
else
{
sett = set;
while ( sett->prev )
{
sett = xset_get( sett->prev );
if ( sett->lock )
{
toolshow = TRUE;
break;
}
}
}
}
if ( set == set_clipboard )
{
if ( clipboard_is_cut )
// don't allow cut paste to self
no_paste = TRUE;
}
else if ( set_clipboard && set_clipboard->menu_style == XSET_MENU_SUBMENU )
// don't allow paste of submenu to self or below
no_paste = xset_clipboard_in_set( set );
// control open_all item
if ( g_str_has_prefix( set->name, "open_all_type_" ) )
open_all = TRUE;
GtkWidget* design_menu = gtk_menu_new();
GtkAccelGroup* accel_group = gtk_accel_group_new();
if ( toolshow )
{
// Show Tool
newitem = gtk_check_menu_item_new_with_mnemonic( _("S_how") );
gtk_container_add ( GTK_CONTAINER ( design_menu ), newitem );
g_object_set_data( G_OBJECT(newitem), "job", GINT_TO_POINTER( XSET_JOB_SHOW ) );
gtk_check_menu_item_set_active( GTK_CHECK_MENU_ITEM( newitem ),
( set->tool == XSET_B_TRUE ) );
g_signal_connect( newitem, "activate", G_CALLBACK( xset_design_job ), set );
// Separator
gtk_container_add ( GTK_CONTAINER (design_menu ), gtk_separator_menu_item_new() );
}
// Name
newitem = xset_design_additem( design_menu, _("_Name"),
GTK_STOCK_PROPERTIES, XSET_JOB_LABEL, set );
gtk_widget_set_sensitive( newitem, ( set->menu_style <= XSET_MENU_SUBMENU
&& !set->plugin ) );
// Key
newitem = xset_design_additem( design_menu, _("_Key"),
GTK_STOCK_PROPERTIES, XSET_JOB_KEY, set );
gtk_widget_set_sensitive( newitem, ( set->menu_style < XSET_MENU_SUBMENU
|| toolexecsub ) );
gtk_widget_add_accelerator( newitem, "activate", accel_group,
GDK_KEY_k, GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);
// Icon
newitem = xset_design_additem( design_menu, _("_Icon"),
GTK_STOCK_PROPERTIES, XSET_JOB_ICON, set );
gtk_widget_set_sensitive( newitem, ( set->menu_style == XSET_MENU_NORMAL
|| set->menu_style == XSET_MENU_STRING
|| set->menu_style == XSET_MENU_FONTDLG
|| set->menu_style == XSET_MENU_COLORDLG
|| set->menu_style == XSET_MENU_SUBMENU
|| set->tool ) && !open_all );
gtk_widget_add_accelerator( newitem, "activate", accel_group,
GDK_KEY_i, GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);
//// Style submenu
newitem = gtk_image_menu_item_new_with_mnemonic( _("_Style") );
submenu = gtk_menu_new();
gtk_menu_item_set_submenu( GTK_MENU_ITEM( newitem ), submenu );
gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM( newitem ),
gtk_image_new_from_stock( GTK_STOCK_ITALIC, GTK_ICON_SIZE_MENU ) );
gtk_container_add ( GTK_CONTAINER ( design_menu ), newitem );
gtk_widget_set_sensitive( newitem, ( !set->plugin && !set->lock &&
set->menu_style < XSET_MENU_SUBMENU ) ||
( xset_context && xset_context->valid && !open_all ) );
g_object_set_data( G_OBJECT( newitem ), "job", GINT_TO_POINTER( XSET_JOB_HELP_STYLE ) );
g_signal_connect( submenu, "key_press_event",
G_CALLBACK( xset_design_menu_keypress ), set );
// Normal
radio_group = NULL;
newitem = gtk_radio_menu_item_new_with_mnemonic( radio_group, _("_Normal") );
radio_group = gtk_radio_menu_item_get_group( GTK_RADIO_MENU_ITEM( newitem ) );
gtk_container_add ( GTK_CONTAINER ( submenu ), newitem );
g_object_set_data( G_OBJECT(newitem), "job", GINT_TO_POINTER( XSET_JOB_NORMAL ) );
gtk_check_menu_item_set_active( GTK_CHECK_MENU_ITEM( newitem ),
( set->menu_style == XSET_MENU_NORMAL ) );
gtk_widget_set_sensitive( newitem, !set->plugin && !set->lock &&
set->menu_style < XSET_MENU_SUBMENU );
// Check
newitem2 = gtk_radio_menu_item_new_with_mnemonic( radio_group, _("_Checkbox") );
radio_group = gtk_radio_menu_item_get_group( GTK_RADIO_MENU_ITEM( newitem2 ) );
gtk_container_add ( GTK_CONTAINER ( submenu ), newitem2 );
g_object_set_data( G_OBJECT(newitem2), "job", GINT_TO_POINTER( XSET_JOB_CHECK ) );
gtk_check_menu_item_set_active( GTK_CHECK_MENU_ITEM( newitem2 ),
( set->menu_style == XSET_MENU_CHECK ) );
gtk_widget_set_sensitive( newitem2, !set->plugin && !set->lock &&
set->menu_style < XSET_MENU_SUBMENU );
// Confirmation
newitem3 = gtk_radio_menu_item_new_with_mnemonic( radio_group, _("Con_firmation") );
radio_group = gtk_radio_menu_item_get_group( GTK_RADIO_MENU_ITEM( newitem3 ) );
gtk_container_add ( GTK_CONTAINER ( submenu ), newitem3 );
g_object_set_data( G_OBJECT(newitem3), "job", GINT_TO_POINTER( XSET_JOB_CONFIRM ) );
gtk_check_menu_item_set_active( GTK_CHECK_MENU_ITEM( newitem3 ),
( set->menu_style == XSET_MENU_CONFIRM ) );
gtk_widget_set_sensitive( newitem3, !set->plugin && !set->lock &&
set->menu_style < XSET_MENU_SUBMENU );
// Dialog
newitem4 = gtk_radio_menu_item_new_with_mnemonic( radio_group, _("_Input") );
radio_group = gtk_radio_menu_item_get_group( GTK_RADIO_MENU_ITEM( newitem4 ) );
gtk_container_add ( GTK_CONTAINER ( submenu ), newitem4 );
g_object_set_data( G_OBJECT(newitem4), "job", GINT_TO_POINTER( XSET_JOB_DIALOG ) );
gtk_check_menu_item_set_active( GTK_CHECK_MENU_ITEM( newitem4 ),
( set->menu_style == XSET_MENU_STRING ) );
gtk_widget_set_sensitive( newitem4, !set->plugin && !set->lock &&
set->menu_style < XSET_MENU_SUBMENU );
g_signal_connect( newitem, "toggled", G_CALLBACK( on_design_radio_toggled ), set );
g_signal_connect( newitem2, "toggled", G_CALLBACK( on_design_radio_toggled ), set );
g_signal_connect( newitem3, "toggled", G_CALLBACK( on_design_radio_toggled ), set );
g_signal_connect( newitem4, "toggled", G_CALLBACK( on_design_radio_toggled ), set );
// Description
newitem = xset_design_additem( submenu, _("_Message"),
GTK_STOCK_EDIT, XSET_JOB_MESSAGE, set );
gtk_widget_set_sensitive( newitem, ( set->menu_style == XSET_MENU_STRING
|| set->menu_style == XSET_MENU_CONFIRM )
&& !set->plugin && !set->lock );
// Separator
gtk_container_add ( GTK_CONTAINER ( submenu ), gtk_separator_menu_item_new() );
// Context
newitem = xset_design_additem( submenu, _("Con_text"),
GTK_STOCK_EDIT, XSET_JOB_CONTEXT, set );
gtk_widget_set_sensitive( newitem, xset_context && xset_context->valid
&& !open_all );
gtk_widget_add_accelerator( newitem, "activate", accel_group,
GDK_KEY_F3, 0, GTK_ACCEL_VISIBLE);
newitem = xset_design_additem( submenu, _("Ign_ore Context (global)"),
"@check", XSET_JOB_IGNORE_CONTEXT, set );
if ( xset_get_b( "context_dlg" ) )
set_check_menu_item_block( newitem );
//// Command submenu
newitem = gtk_image_menu_item_new_with_mnemonic( _("C_ommand") );
submenu = gtk_menu_new();
gtk_menu_item_set_submenu( GTK_MENU_ITEM( newitem ), submenu );
gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM( newitem ),
gtk_image_new_from_stock( GTK_STOCK_EXECUTE, GTK_ICON_SIZE_MENU ) );
gtk_container_add ( GTK_CONTAINER ( design_menu ), newitem );
gtk_widget_set_sensitive( newitem, !set->lock && (
set->menu_style < XSET_MENU_SUBMENU || toolexecsub ) );
g_object_set_data( G_OBJECT( newitem ), "job", GINT_TO_POINTER( XSET_JOB_HELP_COMMAND ) );
g_signal_connect( submenu, "key_press_event",
G_CALLBACK( xset_design_menu_keypress ), set );
// Edit
newitem = xset_design_additem( submenu, _("_Edit"),
GTK_STOCK_EDIT, XSET_JOB_EDIT, set );
gtk_widget_add_accelerator( newitem, "activate", accel_group,
GDK_KEY_F4, 0, GTK_ACCEL_VISIBLE);
if ( !set->lock && geteuid() != 0 && atoi( set->x ) != 0 )
{
gboolean edit_as_root = TRUE;
if ( atoi( set->x ) == 2 )
{
// custom
if ( !set->z || !g_file_test( set->z, G_FILE_TEST_EXISTS ) )
edit_as_root = FALSE;
else if ( !mime_type_is_text_file( set->z, NULL ) )
edit_as_root = FALSE;
}
if ( set->plugin && set->plug_dir && strstr( set->plug_dir, "/included/" ) )
edit_as_root = FALSE;
if ( edit_as_root )
newitem = xset_design_additem( submenu, _("E_dit As Root"),
GTK_STOCK_DIALOG_WARNING, XSET_JOB_EDIT_ROOT, set );
}
// Copy (Script)
newitem = xset_design_additem( submenu, _("_Copy"),
GTK_STOCK_COPY,
XSET_JOB_COPYNAME,
set );
//// Browse submenu
newitem = gtk_image_menu_item_new_with_mnemonic( _("_Browse") );
submenu2 = gtk_menu_new();
gtk_menu_item_set_submenu( GTK_MENU_ITEM( newitem ), submenu2 );
gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM( newitem ),
gtk_image_new_from_stock( GTK_STOCK_OPEN, GTK_ICON_SIZE_MENU ) );
gtk_container_add ( GTK_CONTAINER ( submenu ), newitem );
gtk_widget_set_sensitive( newitem, !set->lock );
g_object_set_data( G_OBJECT( newitem ), "job", GINT_TO_POINTER( XSET_JOB_HELP_BROWSE ) );
g_signal_connect( submenu2, "key_press_event",
G_CALLBACK( xset_design_menu_keypress ), set );
if ( set->plugin )
path = g_build_filename( set->plug_dir, set->plug_name, NULL );
else
path = g_build_filename( settings_config_dir, "scripts",
set->name, NULL );
if ( dir_has_files( path ) )
newitem = xset_design_additem( submenu2, _("_Files"),
NULL, XSET_JOB_BROWSE_FILES, set );
else
newitem = xset_design_additem( submenu2, _("_Files (none)"),
NULL, XSET_JOB_BROWSE_FILES, set );
g_free( path );
if ( set->plugin )
{
mset = xset_get_plugin_mirror( set );
path = g_build_filename( settings_config_dir, "plugin-data",
mset->name, NULL );
}
else
path = g_build_filename( settings_config_dir, "plugin-data",
set->name, NULL );
if ( dir_has_files( path ) )
newitem = xset_design_additem( submenu2, _("_Data"),
NULL, XSET_JOB_BROWSE_DATA, set );
else
newitem = xset_design_additem( submenu2, _("_Data (none)"),
NULL, XSET_JOB_BROWSE_DATA, set );
g_free( path );
newitem = xset_design_additem( submenu2, _("_Plugin"),
NULL, XSET_JOB_BROWSE_PLUGIN, set );
gtk_widget_set_sensitive( newitem, set->plugin );
// Separator
gtk_container_add ( GTK_CONTAINER ( submenu ), gtk_separator_menu_item_new() );
radio_group = NULL;
if ( !set->lock && !set->x )
set->x = g_strdup_printf("0");
if ( set->x )
{
// Line
newitem = gtk_radio_menu_item_new_with_mnemonic( radio_group, _("_Line") );
radio_group = gtk_radio_menu_item_get_group( GTK_RADIO_MENU_ITEM( newitem ) );
gtk_container_add ( GTK_CONTAINER ( submenu ), newitem );
g_object_set_data( G_OBJECT(newitem), "job", GINT_TO_POINTER( XSET_JOB_LINE ) );
gtk_check_menu_item_set_active( GTK_CHECK_MENU_ITEM( newitem ),
( atoi( set->x ) == 0 ) );
gtk_widget_set_sensitive( newitem, !set->plugin );
// Script
newitem2 = gtk_radio_menu_item_new_with_mnemonic( radio_group, _("_Script") );
radio_group = gtk_radio_menu_item_get_group( GTK_RADIO_MENU_ITEM( newitem2 ) );
gtk_container_add ( GTK_CONTAINER ( submenu ), newitem2 );
g_object_set_data( G_OBJECT(newitem2), "job", GINT_TO_POINTER( XSET_JOB_SCRIPT ) );
gtk_check_menu_item_set_active( GTK_CHECK_MENU_ITEM( newitem2 ),
( atoi( set->x ) == 1 ) );
gtk_widget_set_sensitive( newitem2, !set->plugin );
// Custom
if ( ( atoi( set->x ) == 2 ) && ( set->z && set->z[0] != '\0' ) )
{
char* s = g_path_get_basename( set->z );
if ( strlen( s ) < 20 )
label = g_strdup_printf( _("Custo_m (%s)"), s );
else
label = g_strdup( _("Custo_m (...)") );
g_free( s );
}
else
label = g_strdup_printf( _("Custo_m") );
newitem3 = gtk_radio_menu_item_new_with_mnemonic( radio_group, label );
radio_group = gtk_radio_menu_item_get_group( GTK_RADIO_MENU_ITEM( newitem3 ) );
g_free( label );
gtk_container_add ( GTK_CONTAINER ( submenu ), newitem3 );
g_object_set_data( G_OBJECT(newitem3), "job", GINT_TO_POINTER( XSET_JOB_CUSTOM ) );
gtk_check_menu_item_set_active( GTK_CHECK_MENU_ITEM( newitem3 ),
( atoi( set->x ) == 2 ) );
gtk_widget_set_sensitive( newitem3, !set->plugin );
g_signal_connect( newitem, "toggled", G_CALLBACK( on_design_radio_toggled ), set );
g_signal_connect( newitem2, "toggled", G_CALLBACK( on_design_radio_toggled ), set );
g_signal_connect( newitem3, "toggled", G_CALLBACK( on_design_radio_toggled ), set );
}
// Separator
gtk_container_add ( GTK_CONTAINER ( submenu ), gtk_separator_menu_item_new() );
// Run In Terminal
newitem = xset_design_additem( submenu, _("Run _In Terminal"),
"@check", XSET_JOB_TERM, set );
if ( mset->in_terminal == XSET_B_TRUE )
set_check_menu_item_block( newitem );
// Keep Terminal
newitem = xset_design_additem( submenu, _("_Keep Terminal"),
"@check", XSET_JOB_KEEP, set );
if ( mset->keep_terminal == XSET_B_TRUE )
set_check_menu_item_block( newitem );
gtk_widget_set_sensitive( newitem, ( mset->in_terminal == XSET_B_TRUE ) );
// Separator
gtk_container_add ( GTK_CONTAINER ( submenu ), gtk_separator_menu_item_new() );
// Run As User
if ( set->y && set->y[0] != '\0' && strlen( set->y ) < 20 )
{
label = g_strdup_printf( _("Run As _User... (%s)"), set->y );
newitem = xset_design_additem( submenu, label,
GTK_STOCK_DIALOG_WARNING, XSET_JOB_USER, set );
g_free( label );
}
else
newitem = xset_design_additem( submenu, _("Run As _User..."),
NULL, XSET_JOB_USER, set );
gtk_widget_set_sensitive( newitem, !set->plugin );
// Separator
gtk_container_add ( GTK_CONTAINER ( submenu ), gtk_separator_menu_item_new() );
// Run As Task
newitem = xset_design_additem( submenu, _("Run As _Task"),
"@check", XSET_JOB_TASK, set );
if ( mset->task == XSET_B_TRUE )
set_check_menu_item_block( newitem );
// Popup Task
newitem = xset_design_additem( submenu, _("_Popup Task"),
"@check", XSET_JOB_POP, set );
if ( mset->task_pop == XSET_B_TRUE )
set_check_menu_item_block( newitem );
gtk_widget_set_sensitive( newitem, ( mset->task == XSET_B_TRUE ) );
// Popup Error
newitem = xset_design_additem( submenu, _("Popup E_rror"),
"@check", XSET_JOB_ERR, set );
if ( mset->task_err == XSET_B_TRUE )
set_check_menu_item_block( newitem );
gtk_widget_set_sensitive( newitem, ( mset->task == XSET_B_TRUE ) );
// Popup Output
newitem = xset_design_additem( submenu, _("Popup _Output"),
"@check", XSET_JOB_OUT, set );
if ( mset->task_out == XSET_B_TRUE )
set_check_menu_item_block( newitem );
gtk_widget_set_sensitive( newitem, ( mset->task == XSET_B_TRUE ) );
// Scroll
newitem = xset_design_additem( submenu, _("_Scroll"),
"@check", XSET_JOB_SCROLL, set );
if ( mset->scroll_lock != XSET_B_TRUE )
set_check_menu_item_block( newitem );
gtk_widget_set_sensitive( newitem, ( mset->task == XSET_B_TRUE ) );
// Help
newitem = xset_design_additem( design_menu, _("_Help"),
GTK_STOCK_HELP, XSET_JOB_HELP, set );
gtk_widget_set_sensitive( newitem, !set->lock || ( set->lock && set->line ) );
gtk_widget_add_accelerator( newitem, "activate", accel_group,
GDK_KEY_F1, 0, GTK_ACCEL_VISIBLE);
// Separator
gtk_container_add ( GTK_CONTAINER ( design_menu ), gtk_separator_menu_item_new() );
// Cut
newitem = xset_design_additem( design_menu, _("Cu_t"),
GTK_STOCK_CUT, XSET_JOB_CUT, set );
gtk_widget_set_sensitive( newitem, !set->lock && !set->plugin );
gtk_widget_add_accelerator( newitem, "activate", accel_group,
GDK_KEY_x, GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);
// Copy
newitem = xset_design_additem( design_menu, _("_Copy"),
GTK_STOCK_COPY, XSET_JOB_COPY, set );
gtk_widget_set_sensitive( newitem, !set->lock );
gtk_widget_add_accelerator( newitem, "activate", accel_group,
GDK_KEY_c, GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);
// Paste
newitem = xset_design_additem( design_menu, _("_Paste"),
GTK_STOCK_PASTE, XSET_JOB_PASTE, set );
gtk_widget_set_sensitive( newitem, set_clipboard && !no_paste
&& !set->plugin
&& !( set->tool && set_clipboard->menu_style ==
XSET_MENU_SUBMENU ) );
gtk_widget_add_accelerator( newitem, "activate", accel_group,
GDK_KEY_v, GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);
// Remove
newitem = xset_design_additem( design_menu, _("_Remove"),
GTK_STOCK_REMOVE, XSET_JOB_REMOVE, set );
gtk_widget_set_sensitive( newitem, !set->lock && !no_remove );
gtk_widget_add_accelerator( newitem, "activate", accel_group,
GDK_KEY_Delete, 0, GTK_ACCEL_VISIBLE);
// Export
newitem = xset_design_additem( design_menu, _("E_xport"),
GTK_STOCK_SAVE, XSET_JOB_EXPORT, set );
gtk_widget_set_sensitive( newitem, !set->lock
&& set->menu_style < XSET_MENU_SEP );
// Separator
gtk_container_add ( GTK_CONTAINER ( design_menu ),
gtk_separator_menu_item_new() );
// New > Command
newitem = xset_design_additem( design_menu, _("Ne_w"),
GTK_STOCK_ADD, XSET_JOB_COMMAND, set );
gtk_widget_set_sensitive( newitem, !set->plugin );
gtk_widget_add_accelerator( newitem, "activate", accel_group,
GDK_KEY_Insert, 0, GTK_ACCEL_VISIBLE);
// New > Submenu
newitem = xset_design_additem( design_menu, _("Sub_menu"),
GTK_STOCK_ADD, XSET_JOB_SUBMENU, set );
gtk_widget_set_sensitive( newitem, !set->plugin && !set->tool );
// New > Separator
newitem = xset_design_additem( design_menu, _("S_eparator"),
GTK_STOCK_ADD, XSET_JOB_SEP, set );
gtk_widget_set_sensitive( newitem, !set->plugin );
gtk_widget_show_all( GTK_WIDGET( design_menu ) );
gtk_menu_popup( GTK_MENU( design_menu ), GTK_WIDGET( menu ), NULL, NULL,
NULL, button, time );
gtk_widget_set_sensitive( GTK_WIDGET( menu ), FALSE );
g_signal_connect( menu, "hide", G_CALLBACK( on_menu_hide ),
design_menu );
//g_signal_connect( menu, "deactivate", //doesn't work for menubar
// G_CALLBACK( xset_design_destroy), design_menu );
g_signal_connect( design_menu, "selection-done",
G_CALLBACK( gtk_widget_destroy ), NULL );
g_signal_connect( design_menu, "key_press_event",
G_CALLBACK( xset_design_menu_keypress ), set );
}
gboolean xset_design_cb( GtkWidget* item, GdkEventButton* event, XSet* set )
{
int job = -1;
//printf("xset_design_cb\n");
GtkWidget* menu = (GtkWidget*)g_object_get_data( G_OBJECT(item), "menu" );
int keymod = ( event->state & ( GDK_SHIFT_MASK | GDK_CONTROL_MASK |
GDK_MOD1_MASK | GDK_SUPER_MASK | GDK_HYPER_MASK | GDK_META_MASK ) );
if ( event->type == GDK_BUTTON_RELEASE )
{
if ( event->button == 1 && keymod == 0 )
{
// user released left button - due to an apparent gtk bug, activate
// doesn't always fire on this event so handle it ourselves
// see also ptk-file-menu.c on_app_button_press()
// test: gtk2 Crux theme with touchpad on Edit|Copy To|Location
// https://github.com/IgnorantGuru/spacefm/issues/31
// https://github.com/IgnorantGuru/spacefm/issues/228
if ( set && set->tool )
{
// is in a toolbar config menu - show the design menu
xset_design_show_menu( menu, set, event->button, event->time );
}
else
{
if ( menu )
gtk_menu_shell_deactivate( GTK_MENU_SHELL( menu ) );
gtk_menu_item_activate( GTK_MENU_ITEM( item ) );
}
return TRUE;
}
return FALSE;
}
else if ( event->type != GDK_BUTTON_PRESS )
return FALSE;
if ( event->button == 1 || event->button == 3 )
{
// left or right click
if ( keymod == 0 )
{
// no modifier
if ( event->button == 3 )
{
// right
xset_design_show_menu( menu, set, event->button, event->time );
return TRUE;
}
}
else if ( keymod == GDK_CONTROL_MASK )
{
// ctrl
job = XSET_JOB_COPY;
}
else if ( keymod == GDK_MOD1_MASK )
{
// alt
job = XSET_JOB_CUT;
}
else if ( keymod == GDK_SHIFT_MASK )
{
// shift
job = XSET_JOB_PASTE;
}
else if ( keymod == ( GDK_CONTROL_MASK | GDK_SHIFT_MASK ) )
{
// ctrl + shift
job = XSET_JOB_COMMAND;
}
}
else if ( event->button == 2 )
{
// middle click
if ( keymod == 0 )
{
// no modifier
if ( set->lock )
{
xset_design_show_menu( menu, set, event->button, event->time );
return TRUE;
}
else
job = XSET_JOB_EDIT;
}
else if ( keymod == GDK_CONTROL_MASK )
{
// ctrl
job = XSET_JOB_KEY;
}
else if ( keymod == GDK_MOD1_MASK )
{
// alt
job = XSET_JOB_HELP;
}
else if ( keymod == GDK_SHIFT_MASK )
{
// shift
job = XSET_JOB_ICON;
}
else if ( keymod == ( GDK_CONTROL_MASK | GDK_SHIFT_MASK ) )
{
// ctrl + shift
job = XSET_JOB_REMOVE;
}
else if ( keymod == ( GDK_CONTROL_MASK | GDK_MOD1_MASK ) )
{
// ctrl + alt
job = XSET_JOB_CONTEXT;
}
}
if ( job != -1 )
{
if ( xset_job_is_valid( set, job ) )
{
if ( menu )
gtk_menu_shell_deactivate( GTK_MENU_SHELL( menu ) );
g_object_set_data( G_OBJECT( item ), "job", GINT_TO_POINTER( job ) );
xset_design_job( item, set );
}
else
xset_design_show_menu( menu, set, event->button, event->time );
return TRUE;
}
return FALSE; // TRUE won't stop activate on button-press (will on release)
}
gboolean xset_menu_keypress( GtkWidget* widget, GdkEventKey* event,
gpointer user_data )
{
int job = -1;
XSet* set;
GtkWidget* item = gtk_menu_shell_get_selected_item( GTK_MENU_SHELL( widget ) );
if ( item )
{
set = g_object_get_data( G_OBJECT( item ), "set" );
if ( !set )
return FALSE;
}
else
return FALSE;
int keymod = ( event->state & ( GDK_SHIFT_MASK | GDK_CONTROL_MASK |
GDK_MOD1_MASK | GDK_SUPER_MASK | GDK_HYPER_MASK | GDK_META_MASK ) );
if ( keymod == 0 )
{
if ( event->keyval == GDK_KEY_F1 )
{
job = XSET_JOB_HELP;
}
else if ( event->keyval == GDK_KEY_F2 )
{
xset_design_show_menu( widget, set, 0, event->time );
return TRUE;
}
else if ( event->keyval == GDK_KEY_F3 )
job = XSET_JOB_CONTEXT;
else if ( event->keyval == GDK_KEY_F4 )
job = XSET_JOB_EDIT;
else if ( event->keyval == GDK_KEY_Delete )
job = XSET_JOB_REMOVE;
else if ( event->keyval == GDK_KEY_Insert )
job = XSET_JOB_COMMAND;
}
else if ( keymod == GDK_CONTROL_MASK )
{
if ( event->keyval == GDK_KEY_c )
job = XSET_JOB_COPY;
else if ( event->keyval == GDK_KEY_x )
job = XSET_JOB_CUT;
else if ( event->keyval == GDK_KEY_v )
job = XSET_JOB_PASTE;
else if ( event->keyval == GDK_KEY_e )
{
if ( set->lock )
{
xset_design_show_menu( widget, set, 0, event->time );
return TRUE;
}
else
job = XSET_JOB_EDIT;
}
else if ( event->keyval == GDK_KEY_k )
job = XSET_JOB_KEY;
else if ( event->keyval == GDK_KEY_i )
job = XSET_JOB_ICON;
}
if ( job != -1 )
{
if ( xset_job_is_valid( set, job ) )
{
gtk_menu_shell_deactivate( GTK_MENU_SHELL( widget ) );
g_object_set_data( G_OBJECT( item ), "job", GINT_TO_POINTER( job ) );
xset_design_job( item, set );
}
else
xset_design_show_menu( widget, set, 0, event->time );
return TRUE;
}
return FALSE;
}
void xset_menu_cb( GtkWidget* item, XSet* set )
{
GtkWidget* parent;
void (*cb_func) () = NULL;
gpointer cb_data = NULL;
char* title;
XSet* mset; // mirror set or set
XSet* rset; // real set
if ( item )
{
if ( set->lock && set->menu_style == XSET_MENU_RADIO &&
!gtk_check_menu_item_get_active( GTK_CHECK_MENU_ITEM( item ) ) )
return;
cb_func = (void *)g_object_get_data( G_OBJECT(item), "cb_func" );
cb_data = g_object_get_data( G_OBJECT(item), "cb_data" );
}
parent = set->browser ? GTK_WIDGET( set->browser ) : GTK_WIDGET( set->desktop );
if ( set->plugin )
{
// set is plugin
mset = xset_get_plugin_mirror( set );
rset = set;
}
else if ( !set->lock && set->desc && !strcmp( set->desc, "@plugin@mirror@" )
&& set->shared_key )
{
// set is plugin mirror
mset = set;
rset = xset_get( set->shared_key );
rset->browser = set->browser;
rset->desktop = set->desktop;
}
else
{
mset = set;
rset = set;
}
if ( !rset->menu_style )
{
if ( cb_func )
(*cb_func) ( item, cb_data );
else if ( !rset->lock )
xset_custom_activate( item, rset );
}
else if ( rset->menu_style == XSET_MENU_CHECK )
{
if ( mset->b == XSET_B_TRUE )
mset->b = XSET_B_FALSE;
else
mset->b = XSET_B_TRUE;
if ( cb_func )
(*cb_func) ( item, cb_data );
else if ( !rset->lock )
xset_custom_activate( item, rset );
}
else if ( rset->menu_style == XSET_MENU_STRING ||
rset->menu_style == XSET_MENU_CONFIRM )
{
char* msg;
char* help;
char* default_str = NULL;
if ( rset->title && rset->lock )
title = g_strdup( rset->title );
else
title = clean_label( rset->menu_label, FALSE, FALSE );
if ( rset->lock )
{
msg = rset->desc;
default_str = rset->z;
help = set->line;
}
else
{
char* newline = g_strdup_printf( "\n" );
char* tab = g_strdup_printf( "\t" );
char* msg1 = replace_string( rset->desc, "\\n", newline, FALSE );
msg = replace_string( msg1, "\\t", tab, FALSE );
g_free( msg1 );
g_free( newline );
g_free( tab );
help = set->name;
}
if ( rset->menu_style == XSET_MENU_CONFIRM )
{
if ( xset_msg_dialog( parent, GTK_MESSAGE_QUESTION, title, NULL,
GTK_BUTTONS_OK_CANCEL,
msg, NULL, help ) == GTK_RESPONSE_OK )
{
if ( cb_func )
(*cb_func) ( item, cb_data );
else if ( !set->lock )
xset_custom_activate( item, rset );
}
}
else if ( xset_text_dialog( parent, title, NULL, TRUE, msg, NULL, mset->s,
&mset->s, default_str,
FALSE, help ) )
{
if ( cb_func )
(*cb_func) ( item, cb_data );
else if ( !set->lock )
xset_custom_activate( item, rset );
}
if ( !rset->lock )
g_free( msg );
g_free( title );
}
else if ( rset->menu_style == XSET_MENU_RADIO )
{
if ( mset->b != XSET_B_TRUE )
mset->b = XSET_B_TRUE;
if ( cb_func )
(*cb_func) ( item, cb_data );
else if ( !rset->lock )
xset_custom_activate( item, rset );
}
else if ( rset->menu_style == XSET_MENU_FONTDLG )
{
char* fontname = xset_font_dialog( parent, rset->title, rset->desc, rset->s );
if ( fontname )
{
if ( fontname[0] != '\0' )
{
xset_set_set( rset, "s", fontname );
}
else
{
if ( rset->s )
g_free( rset->s );
rset->s = NULL;
}
g_free( fontname );
if ( cb_func )
(*cb_func) ( item, cb_data );
}
}
else if ( rset->menu_style == XSET_MENU_FILEDLG )
{
// test purpose only
char* file = xset_file_dialog( parent, GTK_FILE_CHOOSER_ACTION_SAVE,
rset->title, rset->s, "foobar.xyz" );
//printf("file=%s\n", file );
}
else if ( rset->menu_style == XSET_MENU_ICON )
{
if ( xset_text_dialog( parent, rset->title ? rset->title : _("Set Icon"),
NULL, FALSE,
rset->desc? rset->desc : _(icon_desc), NULL,
rset->icon, &rset->icon,
NULL, FALSE, NULL ) )
{
if ( cb_func )
(*cb_func) ( item, cb_data );
}
}
else if ( rset->menu_style == XSET_MENU_COLORDLG )
{
char* scolor = xset_color_dialog( parent, rset->title, rset->s );
if ( rset->s )
g_free( rset->s );
rset->s = scolor;
if ( cb_func )
(*cb_func) ( item, cb_data );
}
else if ( cb_func )
(*cb_func) ( item, cb_data );
else if ( !set->lock )
xset_custom_activate( item, rset );
if ( rset->menu_style )
xset_autosave( rset->browser );
}
int xset_msg_dialog( GtkWidget* parent, int action, const char* title, GtkWidget* image,
int buttons, const char* msg1, const char* msg2,
const char* help )
{
/* action=
GTK_MESSAGE_INFO,
GTK_MESSAGE_WARNING,
GTK_MESSAGE_QUESTION,
GTK_MESSAGE_ERROR
*/
GtkWidget* dlgparent = NULL;
if ( parent )
dlgparent = gtk_widget_get_toplevel( parent );
if ( !buttons )
buttons = GTK_BUTTONS_OK;
if ( action == 0 )
action = GTK_MESSAGE_INFO;
GtkWidget* dlg = gtk_message_dialog_new( GTK_WINDOW( dlgparent ),
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
action,
buttons,
msg1, NULL );
xset_set_window_icon( GTK_WINDOW( dlg ) );
gtk_window_set_role( GTK_WINDOW( dlg ), "msg_dialog" );
if ( msg2 )
gtk_message_dialog_format_secondary_text( GTK_MESSAGE_DIALOG( dlg ), msg2, NULL );
if ( image )
gtk_message_dialog_set_image( GTK_MESSAGE_DIALOG( dlg ), image );
if ( title )
gtk_window_set_title( GTK_WINDOW( dlg ), title );
if ( help )
{
GtkWidget* btn_help = gtk_button_new_with_mnemonic( _("_Help") );
gtk_dialog_add_action_widget( GTK_DIALOG( dlg ), btn_help, GTK_RESPONSE_HELP );
gtk_button_set_image( GTK_BUTTON( btn_help ), xset_get_image( "GTK_STOCK_HELP",
GTK_ICON_SIZE_BUTTON ) );
gtk_button_set_focus_on_click( GTK_BUTTON( btn_help ), FALSE );
gtk_widget_set_can_focus( btn_help, FALSE );
}
gtk_widget_show_all( dlg );
int response;
while ( response = gtk_dialog_run( GTK_DIALOG( dlg ) ) )
{
if ( response == GTK_RESPONSE_HELP )
{
// btn_help clicked
if ( help )
{
if ( help[0] == '#' )
{
// as anchor
xset_show_help( dlg, NULL, help );
}
else if ( xset_is( help ) )
{
// as set name
xset_show_help( dlg, xset_get( help ), NULL );
}
}
}
else
break;
}
gtk_widget_destroy( dlg );
return response;
}
void on_multi_input_insert( GtkTextBuffer *buf )
{ // remove linefeeds from pasted text
GtkTextIter iter, siter;
//gboolean changed = FALSE;
int x;
// buffer contains linefeeds?
gtk_text_buffer_get_start_iter( buf, &siter );
gtk_text_buffer_get_end_iter( buf, &iter );
char* all = gtk_text_buffer_get_text( buf, &siter, &iter, FALSE );
if ( !strchr( all, '\n' ) )
{
g_free( all );
return;
}
g_free( all );
// delete selected text that was pasted over
if ( gtk_text_buffer_get_selection_bounds( buf, &siter, &iter ) )
gtk_text_buffer_delete( buf, &siter, &iter );
GtkTextMark* insert = gtk_text_buffer_get_insert( buf );
gtk_text_buffer_get_iter_at_mark( buf, &iter, insert );
gtk_text_buffer_get_start_iter( buf, &siter );
char* b = gtk_text_buffer_get_text( buf, &siter, &iter, FALSE );
gtk_text_buffer_get_end_iter( buf, &siter );
char* a = gtk_text_buffer_get_text( buf, &iter, &siter, FALSE );
if ( strchr( b, '\n' ) )
{
x = 0;
while ( b[x] != '\0' )
{
if ( b[x] == '\n' )
b[x] = ' ';
x++;
}
}
if ( strchr( a, '\n' ) )
{
x = 0;
while ( a[x] != '\0' )
{
if ( a[x] == '\n' )
a[x] = ' ';
x++;
}
}
g_signal_handlers_block_matched( buf, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_multi_input_insert, NULL );
gtk_text_buffer_set_text( buf, b, -1 );
gtk_text_buffer_get_end_iter( buf, &iter );
GtkTextMark* mark = gtk_text_buffer_create_mark( buf, NULL, &iter, TRUE );
gtk_text_buffer_get_end_iter( buf, &iter );
gtk_text_buffer_insert( buf, &iter, a, -1 );
gtk_text_buffer_get_iter_at_mark( buf, &iter, mark );
gtk_text_buffer_place_cursor( buf, &iter );
g_signal_handlers_unblock_matched( buf, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_multi_input_insert, NULL );
g_free( a );
g_free( b );
}
void on_multi_input_font_change( GtkMenuItem* item, GtkTextView *input )
{
char* fontname = xset_get_s( "input_font" );
if ( fontname )
{
PangoFontDescription* font_desc = pango_font_description_from_string( fontname );
gtk_widget_modify_font( GTK_WIDGET( input ), font_desc );
pango_font_description_free( font_desc );
}
else
gtk_widget_modify_font( GTK_WIDGET( input ), NULL );
}
void on_multi_input_popup( GtkTextView *input, GtkMenu *menu, gpointer user_data )
{
GtkAccelGroup* accel_group = gtk_accel_group_new();
XSet* set = xset_get( "sep_multi" );
set->menu_style = XSET_MENU_SEP;
set->browser = NULL;
set->desktop = NULL;
xset_add_menuitem( NULL, NULL, GTK_WIDGET( menu ), accel_group, set );
set = xset_set_cb( "input_font", on_multi_input_font_change, input );
set->browser = NULL;
set->desktop = NULL;
xset_add_menuitem( NULL, NULL, GTK_WIDGET( menu ), accel_group, set );
gtk_widget_show_all( GTK_WIDGET( menu ) );
g_signal_connect( G_OBJECT( menu ), "key-press-event",
G_CALLBACK( xset_menu_keypress ), NULL );
}
char* multi_input_get_text( GtkWidget* input )
{ // returns a new allocated string or NULL if input is empty
GtkTextIter iter, siter;
if ( !GTK_IS_TEXT_VIEW( input ) )
return NULL;
GtkTextBuffer* buf = gtk_text_view_get_buffer( GTK_TEXT_VIEW( input ) );
gtk_text_buffer_get_start_iter( buf, &siter );
gtk_text_buffer_get_end_iter( buf, &iter );
char* ret = gtk_text_buffer_get_text( buf, &siter, &iter, FALSE );
if ( ret && ret[0] == '\0' )
{
g_free( ret );
ret = NULL;
}
return ret;
}
void multi_input_select_region( GtkWidget* input, int start, int end )
{
GtkTextIter iter, siter;
if ( start < 0 || !GTK_IS_TEXT_VIEW( input ) )
return;
GtkTextBuffer* buf = gtk_text_view_get_buffer( GTK_TEXT_VIEW( input ) );
gtk_text_buffer_get_iter_at_offset( buf, &siter, start );
if ( end < 0 )
gtk_text_buffer_get_end_iter( buf, &iter );
else
gtk_text_buffer_get_iter_at_offset( buf, &iter, end );
gtk_text_buffer_select_range( buf, &iter, &siter );
}
GtkTextView* multi_input_new( GtkScrolledWindow* scrolled, const char* text,
gboolean def_font )
{
GtkTextIter iter;
gtk_scrolled_window_set_policy ( GTK_SCROLLED_WINDOW ( scrolled ),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC );
GtkTextView* input = GTK_TEXT_VIEW( gtk_text_view_new() );
// ubuntu shows input too small so use mininum height
gtk_widget_set_size_request( GTK_WIDGET( input ), -1, 50 );
gtk_widget_set_size_request( GTK_WIDGET( scrolled ), -1, 50 );
gtk_container_add ( GTK_CONTAINER ( scrolled ), GTK_WIDGET( input ) );
GtkTextBuffer* buf = gtk_text_view_get_buffer( input );
gtk_text_view_set_wrap_mode( input, GTK_WRAP_CHAR ); //GTK_WRAP_WORD_CHAR
if ( text )
gtk_text_buffer_set_text( buf, text, -1 );
gtk_text_buffer_get_end_iter( buf, &iter );
gtk_text_buffer_place_cursor( buf, &iter );
GtkTextMark* insert = gtk_text_buffer_get_insert( buf );
gtk_text_view_scroll_to_mark( input, insert, 0.0, FALSE, 0, 0 );
gtk_text_view_set_accepts_tab( input, FALSE );
g_signal_connect_after( G_OBJECT( buf ), "insert-text",
G_CALLBACK( on_multi_input_insert ), NULL );
if ( def_font )
{
on_multi_input_font_change( NULL, input );
g_signal_connect_after( G_OBJECT( input ), "populate-popup",
G_CALLBACK( on_multi_input_popup ), NULL );
}
return input;
}
static gboolean on_input_keypress ( GtkWidget *widget, GdkEventKey *event, GtkWidget* dlg )
{
if ( event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_KP_Enter )
{
gtk_dialog_response( GTK_DIALOG( dlg ), GTK_RESPONSE_OK );
return TRUE;
}
return FALSE;
}
gboolean xset_text_dialog( GtkWidget* parent, const char* title, GtkWidget* image,
gboolean large, const char* msg1, const char* msg2,
const char* defstring, char** answer, const char* defreset,
gboolean edit_care, const char* help )
{
GtkTextIter iter, siter;
int width, height;
GtkWidget* dlgparent = NULL;
if ( parent )
dlgparent = gtk_widget_get_toplevel( parent );
GtkWidget* dlg = gtk_message_dialog_new( GTK_WINDOW( dlgparent ),
GTK_DIALOG_MODAL,
GTK_MESSAGE_QUESTION,
GTK_BUTTONS_NONE,
msg1, NULL );
xset_set_window_icon( GTK_WINDOW( dlg ) );
gtk_window_set_role( GTK_WINDOW( dlg ), "text_dialog" );
if ( large )
{
width = xset_get_int( "text_dlg", "s" );
height = xset_get_int( "text_dlg", "z" );
if ( width && height )
gtk_window_set_default_size( GTK_WINDOW( dlg ), width, height );
else
gtk_window_set_default_size( GTK_WINDOW( dlg ), 600, 400 );
//gtk_widget_set_size_request( GTK_WIDGET( dlg ), 600, 400 );
}
else
{
width = xset_get_int( "text_dlg", "x" );
height = xset_get_int( "text_dlg", "y" );
if ( width && height )
gtk_window_set_default_size( GTK_WINDOW( dlg ), width, -1 );
else
gtk_window_set_default_size( GTK_WINDOW( dlg ), 500, -1 );
//gtk_widget_set_size_request( GTK_WIDGET( dlg ), 500, 300 );
}
gtk_window_set_resizable( GTK_WINDOW( dlg ), TRUE );
if ( msg2 )
gtk_message_dialog_format_secondary_text( GTK_MESSAGE_DIALOG( dlg ), msg2, NULL );
if ( image )
gtk_message_dialog_set_image( GTK_MESSAGE_DIALOG( dlg ), image );
// input view
GtkScrolledWindow* scroll_input = GTK_SCROLLED_WINDOW( gtk_scrolled_window_new(
NULL, NULL ) );
GtkTextView* input = multi_input_new( scroll_input, defstring, TRUE );
GtkTextBuffer* buf = gtk_text_view_get_buffer( input );
gtk_box_pack_start( GTK_BOX( gtk_dialog_get_content_area ( GTK_DIALOG( dlg ) ) ), GTK_WIDGET( scroll_input ),
TRUE, TRUE, 4 );
g_signal_connect( G_OBJECT( input ), "key-press-event",
G_CALLBACK( on_input_keypress ), dlg );
// buttons
GtkWidget* btn_edit;
GtkWidget* btn_help = NULL;
GtkWidget* btn_default = NULL;
if ( help )
{
btn_help = gtk_button_new_with_mnemonic( _("_Help") );
gtk_dialog_add_action_widget( GTK_DIALOG( dlg ), btn_help, GTK_RESPONSE_HELP );
gtk_button_set_image( GTK_BUTTON( btn_help ), xset_get_image( "GTK_STOCK_HELP",
GTK_ICON_SIZE_BUTTON ) );
gtk_button_set_focus_on_click( GTK_BUTTON( btn_help ), FALSE );
}
if ( edit_care )
{
btn_edit = gtk_toggle_button_new_with_mnemonic( _("_Edit") );
gtk_dialog_add_action_widget( GTK_DIALOG( dlg ), btn_edit, GTK_RESPONSE_YES );
gtk_button_set_image( GTK_BUTTON( btn_edit ), xset_get_image( "GTK_STOCK_DIALOG_WARNING",
GTK_ICON_SIZE_BUTTON ) );
gtk_button_set_focus_on_click( GTK_BUTTON( btn_edit ), FALSE );
gtk_text_view_set_editable( input, FALSE );
}
if ( defreset )
{
btn_default = gtk_button_new_with_mnemonic( _("_Default") );
gtk_dialog_add_action_widget( GTK_DIALOG( dlg ), btn_default, GTK_RESPONSE_NO );
gtk_button_set_image( GTK_BUTTON( btn_default ),
xset_get_image( "GTK_STOCK_REVERT_TO_SAVED",
GTK_ICON_SIZE_BUTTON ) );
gtk_button_set_focus_on_click( GTK_BUTTON( btn_default ), FALSE );
}
GtkWidget* btn_cancel = gtk_button_new_from_stock( GTK_STOCK_CANCEL );
gtk_dialog_add_action_widget( GTK_DIALOG( dlg ), btn_cancel, GTK_RESPONSE_CANCEL);
GtkWidget* btn_ok = gtk_button_new_from_stock( GTK_STOCK_OK );
gtk_dialog_add_action_widget( GTK_DIALOG( dlg ), btn_ok, GTK_RESPONSE_OK);
// show
gtk_widget_show_all( dlg );
if ( title )
gtk_window_set_title( GTK_WINDOW( dlg ), title );
if ( edit_care )
{
gtk_widget_grab_focus( btn_ok );
if ( btn_default )
gtk_widget_set_sensitive( btn_default, FALSE );
}
char* ans;
char* trim_ans;
int response;
gboolean ret = FALSE;
while ( response = gtk_dialog_run( GTK_DIALOG( dlg ) ) )
{
if ( response == GTK_RESPONSE_OK )
{
gtk_text_buffer_get_start_iter( buf, &siter );
gtk_text_buffer_get_end_iter( buf, &iter );
ans = gtk_text_buffer_get_text( buf, &siter, &iter, FALSE );
if ( strchr( ans, '\n' ) )
{
ptk_show_error( GTK_WINDOW( dlgparent ), _("Error"),
_("Your input is invalid because it contains linefeeds") );
}
else
{
if ( *answer )
g_free( *answer );
trim_ans = g_strdup( ans );
trim_ans = g_strstrip( trim_ans );
if ( ans && trim_ans[0] != '\0' )
*answer = g_filename_from_utf8( trim_ans, -1, NULL, NULL, NULL );
else
*answer = NULL;
if ( ans )
{
g_free( trim_ans );
g_free( ans );
}
ret = TRUE;
break;
}
}
else if ( response == GTK_RESPONSE_YES )
{
// btn_edit clicked
gtk_text_view_set_editable( input,
gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( btn_edit ) ) );
if ( btn_default )
gtk_widget_set_sensitive( btn_default,
gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( btn_edit ) ) );
}
else if ( response == GTK_RESPONSE_NO )
{
// btn_default clicked
gtk_text_buffer_set_text( buf, defreset, -1 );
}
else if ( response == GTK_RESPONSE_HELP )
{
// btn_help clicked
if ( help )
{
if ( help[0] == '#' )
{
// as anchor
xset_show_help( dlg, NULL, help );
}
else if ( xset_is( help ) )
{
// as set name
xset_show_help( dlg, xset_get( help ), NULL );
}
}
}
else if ( response == GTK_RESPONSE_CANCEL
|| response == GTK_RESPONSE_DELETE_EVENT )
break;
}
GtkAllocation allocation;
gtk_widget_get_allocation( GTK_WIDGET( dlg ), &allocation );
width = allocation.width;
height = allocation.height;
if ( width && height )
{
char* str = g_strdup_printf( "%d", width );
if ( large )
xset_set( "text_dlg", "s", str );
else
xset_set( "text_dlg", "x", str );
g_free( str );
str = g_strdup_printf( "%d", height );
if ( large )
xset_set( "text_dlg", "z", str );
else
xset_set( "text_dlg", "y", str );
g_free( str );
}
gtk_widget_destroy( dlg );
return ret;
}
/*
gboolean xset_text_dialog_old( GtkWidget* parent, gint width, char* title, char* message,
char* defstring, char** answer )
{
GtkWidget* dlgparent = gtk_widget_get_toplevel( parent );
GtkWidget* dlg = gtk_message_dialog_new( GTK_WINDOW( dlgparent ),
GTK_DIALOG_MODAL,
GTK_MESSAGE_QUESTION,
GTK_BUTTONS_OK_CANCEL,
message );
//gtk_window_set_resizable( GTK_WINDOW( dlg ), TRUE );
gtk_widget_set_size_request( GTK_WINDOW( dlg ), width, -1 );
GtkEntry* entry = ( GtkEntry* ) gtk_entry_new();
if ( defstring )
gtk_entry_set_text( entry, defstring );
gtk_box_pack_start( GTK_BOX( GTK_DIALOG( dlg ) ->vbox ), GTK_WIDGET( entry ),
TRUE, TRUE, 4 );
g_signal_connect (G_OBJECT (entry), "activate",
G_CALLBACK( xset_text_dialog_activate ), dlg );
gtk_widget_show_all( dlg );
gtk_editable_select_region( GTK_EDITABLE(entry), 0, 0 );
gtk_editable_set_position( GTK_EDITABLE(entry), -1 );
if ( title )
gtk_window_set_title( GTK_WINDOW( dlg ), title );
int response = gtk_dialog_run( GTK_DIALOG( dlg ) );
if ( response == GTK_RESPONSE_OK )
{
if ( *answer )
g_free( *answer );
*answer = g_filename_from_utf8( gtk_entry_get_text( entry ),
- 1, NULL, NULL, NULL );
gtk_widget_destroy( dlg );
return TRUE;
}
gtk_widget_destroy( dlg );
return FALSE;
}
void xset_text_dialog_activate( GtkEntry* entry, GtkDialog* dlg )
{
// User pressed enter in dialog
gtk_dialog_response( dlg, GTK_RESPONSE_OK );
}
*/
static gboolean on_fontdlg_keypress ( GtkWidget *widget, GdkEventKey *event,
GtkWidget* dlg )
{
if ( event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_KP_Enter )
{
gtk_dialog_response( GTK_DIALOG( dlg ), GTK_RESPONSE_YES );
return TRUE;
}
return FALSE;
}
char* xset_font_dialog( GtkWidget* parent, char* title, char* preview, char* deffont )
{
char* fontname = NULL;
GtkWidget* image;
GtkWidget* dlg = gtk_font_selection_dialog_new( title );
xset_set_window_icon( GTK_WINDOW( dlg ) );
gtk_window_set_role( GTK_WINDOW( dlg ), "font_dialog" );
if ( deffont )
gtk_font_selection_dialog_set_font_name( GTK_FONT_SELECTION_DIALOG( dlg ),
deffont );
if ( title )
gtk_window_set_title( GTK_WINDOW( dlg ), title );
if ( preview )
gtk_font_selection_dialog_set_preview_text( GTK_FONT_SELECTION_DIALOG( dlg ),
preview );
int width = xset_get_int( "font_dlg", "x" );
int height = xset_get_int( "font_dlg", "y" );
if ( width && height )
gtk_window_set_default_size( GTK_WINDOW( dlg ), width, height );
// add default button, rename OK
GtkButton* btn = GTK_BUTTON( gtk_button_new_from_stock( GTK_STOCK_YES ) );
gtk_dialog_add_action_widget( GTK_DIALOG(dlg), GTK_WIDGET( btn ),
GTK_RESPONSE_YES);
gtk_widget_show( GTK_WIDGET( btn ) );
GtkButton* ok = GTK_BUTTON( gtk_font_selection_dialog_get_ok_button(
GTK_FONT_SELECTION_DIALOG( dlg ) ) );
gtk_button_set_label( ok, _("_Default") );
image = xset_get_image( "GTK_STOCK_YES", GTK_ICON_SIZE_BUTTON );
gtk_button_set_image( ok, image );
gtk_button_set_label( btn, _("_OK") );
image = xset_get_image( "GTK_STOCK_OK", GTK_ICON_SIZE_BUTTON );
gtk_button_set_image( btn, image );
g_signal_connect( G_OBJECT( dlg ), "key-press-event",
G_CALLBACK( on_fontdlg_keypress ), dlg );
gint response = gtk_dialog_run(GTK_DIALOG(dlg));
GtkAllocation allocation;
gtk_widget_get_allocation( GTK_WIDGET( dlg ), &allocation );
width = allocation.width;
height = allocation.height;
if ( width && height )
{
char* str = g_strdup_printf( "%d", width );
xset_set( "font_dlg", "x", str );
g_free( str );
str = g_strdup_printf( "%d", height );
xset_set( "font_dlg", "y", str );
g_free( str );
}
if( response == GTK_RESPONSE_YES )
{
char* fontname2 = gtk_font_selection_dialog_get_font_name(
GTK_FONT_SELECTION_DIALOG( dlg ) );
char* trim_fontname = g_strstrip( fontname2 );
fontname = g_strdup( trim_fontname );
g_free( fontname2 );
}
else if( response == GTK_RESPONSE_OK )
{
// default font
fontname = g_strdup( "" );
}
gtk_widget_destroy( dlg );
return fontname;
}
char* xset_file_dialog( GtkWidget* parent, GtkFileChooserAction action,
const char* title, const char* deffolder, const char* deffile )
{
char* path;
/* Actions:
* GTK_FILE_CHOOSER_ACTION_OPEN
* GTK_FILE_CHOOSER_ACTION_SAVE
* GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER
* GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER */
GtkWidget* dlgparent = gtk_widget_get_toplevel( parent );
GtkWidget* dlg = gtk_file_chooser_dialog_new( title,
GTK_WINDOW( dlgparent ), action,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
GTK_STOCK_OK, GTK_RESPONSE_OK, NULL );
//gtk_file_chooser_set_action( GTK_FILE_CHOOSER(dlg), GTK_FILE_CHOOSER_ACTION_SAVE );
gtk_file_chooser_set_do_overwrite_confirmation( GTK_FILE_CHOOSER(dlg), TRUE );
xset_set_window_icon( GTK_WINDOW( dlg ) );
gtk_window_set_role( GTK_WINDOW( dlg ), "file_dialog" );
if ( deffolder )
gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dlg), deffolder );
else
{
path = xset_get_s( "go_set_default" );
if ( path && path[0] != '\0' )
gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dlg), path );
else
{
path = (char*)g_get_home_dir();
gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dlg), path );
}
}
if ( deffile )
{
if ( action == GTK_FILE_CHOOSER_ACTION_SAVE
|| action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER )
gtk_file_chooser_set_current_name( GTK_FILE_CHOOSER(dlg), deffile );
else
{
path = g_build_filename( deffolder, deffile, NULL );
gtk_file_chooser_set_filename( GTK_FILE_CHOOSER (dlg), path );
g_free( path );
}
}
int width = xset_get_int( "file_dlg", "x" );
int height = xset_get_int( "file_dlg", "y" );
if ( width && height )
{
// filechooser won't honor default size or size request ?
gtk_widget_show_all( dlg );
gtk_window_set_position( GTK_WINDOW( dlg ), GTK_WIN_POS_CENTER_ALWAYS );
gtk_window_resize( GTK_WINDOW( dlg ), width, height );
while( gtk_events_pending() )
gtk_main_iteration();
gtk_window_set_position( GTK_WINDOW( dlg ), GTK_WIN_POS_CENTER );
}
gint response = gtk_dialog_run(GTK_DIALOG(dlg));
GtkAllocation allocation;
gtk_widget_get_allocation( GTK_WIDGET( dlg ), &allocation );
width = allocation.width;
height = allocation.height;
if ( width && height )
{
char* str = g_strdup_printf( "%d", width );
xset_set( "file_dlg", "x", str );
g_free( str );
str = g_strdup_printf( "%d", height );
xset_set( "file_dlg", "y", str );
g_free( str );
}
if( response == GTK_RESPONSE_OK )
{
char* dest = gtk_file_chooser_get_filename ( GTK_FILE_CHOOSER ( dlg ) );
gtk_widget_destroy( dlg );
return dest;
}
gtk_widget_destroy( dlg );
return NULL;
}
char* xset_color_dialog( GtkWidget* parent, char* title, char* defcolor )
{
GdkColor color;
char* scolor = NULL;
GtkWidget* dlgparent = gtk_widget_get_toplevel( parent );
GtkWidget* dlg = gtk_color_selection_dialog_new( title );
GtkWidget* color_sel;
GtkWidget* help_button;
g_object_get ( G_OBJECT ( dlg ), "help-button", &help_button, NULL);
gtk_button_set_label( GTK_BUTTON( help_button ), _("_Unset") );
gtk_button_set_image( GTK_BUTTON( help_button ), xset_get_image( "GTK_STOCK_REMOVE", GTK_ICON_SIZE_BUTTON ) );
xset_set_window_icon( GTK_WINDOW( dlg ) );
gtk_window_set_role( GTK_WINDOW( dlg ), "color_dialog" );
if ( defcolor && defcolor[0] != '\0' )
{
if ( gdk_color_parse( defcolor, &color ) )
{
//printf( " gdk_color_to_string = %s\n", gdk_color_to_string( &color ) );
color_sel = gtk_color_selection_dialog_get_color_selection(
GTK_COLOR_SELECTION_DIALOG( dlg ) );
gtk_color_selection_set_current_color( GTK_COLOR_SELECTION( color_sel ),
&color );
}
}
gtk_widget_show_all( dlg );
gint response = gtk_dialog_run( GTK_DIALOG( dlg ) );
if ( response == GTK_RESPONSE_OK )
{
// color_sel must be set directly before get_current_color
color_sel = gtk_color_selection_dialog_get_color_selection(
GTK_COLOR_SELECTION_DIALOG( dlg ) );
gtk_color_selection_get_current_color( GTK_COLOR_SELECTION( color_sel ),
&color );
scolor = gdk_color_to_string( &color );
}
else if ( response == GTK_RESPONSE_HELP )
scolor = NULL;
else // cancel, delete_event
scolor = g_strdup( defcolor );
gtk_widget_destroy( dlg );
return scolor;
}
GtkWidget* xset_add_toolitem( GtkWidget* parent, PtkFileBrowser* file_browser,
GtkWidget* toolbar, int icon_size, XSet* set )
{
GtkWidget* image = NULL;
GtkWidget* btn;
XSet* set_next;
if ( set->tool == XSET_B_TRUE )
{
// button
image = xset_get_image( set->icon, icon_size );
if ( !set->menu_style || set->menu_style == XSET_MENU_STRING )
{
btn = GTK_WIDGET( gtk_tool_button_new( image, set->menu_label ) );
// pass btn back to add_toolbar caller
set->ob2_data = btn;
// ob2 in use ?
if ( set->ob2 )
{
g_free( set->ob2 );
set->ob2 = NULL;
g_warning( "add_toolbar_item style normal set->ob2 != NULL" );
}
}
else if ( set->menu_style == XSET_MENU_CHECK )
{
btn = GTK_WIDGET( gtk_toggle_tool_button_new() );
gtk_tool_button_set_icon_widget( GTK_TOOL_BUTTON( btn ), image );
gtk_tool_button_set_label( GTK_TOOL_BUTTON( btn ), set->menu_label );
gtk_toggle_tool_button_set_active( GTK_TOGGLE_TOOL_BUTTON( btn ),
xset_get_b_set( set ) );
// pass btn back to add_toolbar caller
set->ob2_data = btn;
// ob2 in use ?
if ( set->ob2 )
{
g_free( set->ob2 );
set->ob2 = NULL;
g_warning( "add_toolbar_item style check set->ob2 != NULL" );
}
}
else if ( set->menu_style == XSET_MENU_SUBMENU )
{
btn = GTK_WIDGET( gtk_menu_tool_button_new( image, set->menu_label ) );
if ( set->lock )
{
// Create initial menu for btn
gtk_menu_tool_button_set_menu( GTK_MENU_TOOL_BUTTON( btn ),
gtk_menu_new() );
// pass btn back to add_toolbar caller
set->ob2_data = btn;
// ob2 in use ?
if ( set->ob2 )
{
g_free( set->ob2 );
set->ob2 = NULL;
g_warning( "add_toolbar_item style submenu set->ob2 != NULL" );
}
}
else if ( set->child )
{
GtkWidget* submenu = gtk_menu_new();
GtkAccelGroup* accel_group = gtk_accel_group_new();
XSet* set_child = xset_get( set->child );
xset_add_menuitem( NULL, file_browser, submenu, accel_group, set_child );
gtk_menu_tool_button_set_menu( GTK_MENU_TOOL_BUTTON( btn ), submenu );
gtk_widget_show_all( submenu );
}
}
else if ( set-> menu_style == XSET_MENU_SEP )
{
btn = GTK_WIDGET( gtk_separator_tool_item_new() );
gtk_separator_tool_item_set_draw( GTK_SEPARATOR_TOOL_ITEM( btn ), TRUE );
}
else
return NULL;
g_object_set_data( G_OBJECT( btn ), "toolbar", toolbar );
if ( set->ob1 )
g_object_set_data( G_OBJECT( btn ), set->ob1, set->ob1_data );
if ( set->ob2 )
g_object_set_data( G_OBJECT( btn ), set->ob2, set->ob2_data );
set->browser = file_browser;
// callback
if ( set->menu_style <= XSET_MENU_SUBMENU )
{
if ( set->lock )
{
if ( set->cb_func )
{
if ( set->menu_style == XSET_MENU_CHECK )
g_signal_connect( btn, "toggled", G_CALLBACK( set->cb_func ),
set->cb_data);
else
g_signal_connect( btn, "clicked", G_CALLBACK( set->cb_func ),
set->cb_data);
}
}
else
{ // cb_func is always unset for !lock???? this can be trimmed?
set->cb_func = NULL;
set->cb_data = NULL;
if ( !set->cb_func || set->menu_style )
{
// use xset menu callback
if ( set->menu_style == XSET_MENU_CHECK )
g_signal_connect( btn, "toggled", G_CALLBACK( xset_menu_cb ),
set );
else
g_signal_connect( btn, "clicked", G_CALLBACK( xset_menu_cb ),
set );
g_object_set_data( G_OBJECT(btn), "cb_func", set->cb_func );
g_object_set_data( G_OBJECT(btn), "cb_data", set->cb_data );
}
else if ( set->cb_func )
{
// use custom callback directly
if ( set->menu_style == XSET_MENU_CHECK )
g_signal_connect( btn, "toggled", G_CALLBACK( set->cb_func ),
set->cb_data );
else
g_signal_connect( btn, "clicked", G_CALLBACK( set->cb_func ),
set->cb_data );
}
}
}
// tooltip
//if ( set->x )
// gtk_tool_item_set_tooltip( GTK_TOOL_ITEM( btn ), tooltips, set->x, NULL);
gtk_toolbar_insert( GTK_TOOLBAR( toolbar ), GTK_TOOL_ITEM( btn ), -1 );
}
// next toolitem
if ( set->next )
{
set_next = xset_get( set->next );
xset_add_toolitem( parent, file_browser, toolbar, icon_size, set_next );
}
return btn;
}
void xset_add_toolbar( GtkWidget* parent, PtkFileBrowser* file_browser,
GtkWidget* toolbar, const char* elements )
{
char* space;
XSet* set;
if ( !elements )
return;
GtkIconSize icon_size = gtk_toolbar_get_icon_size( GTK_TOOLBAR( toolbar ) );
while ( elements[0] == ' ' )
elements++;
while ( elements && elements[0] != '\0' )
{
space = strchr( elements, ' ' );
if ( space )
space[0] = '\0';
set = xset_get( elements );
if ( space )
space[0] = ' ';
elements = space;
xset_add_toolitem( parent, file_browser, toolbar, icon_size, set );
if ( elements )
{
while ( elements[0] == ' ' )
elements++;
}
}
}
void open_in_prog( const char* path )
{
char* prog = g_find_program_in_path( g_get_prgname() );
if ( !prog )
prog = g_strdup( g_get_prgname() );
if ( !prog )
prog = g_strdup( "spacefm" );
char* qpath = bash_quote( path );
char* line = g_strdup_printf( "%s %s", prog, qpath );
g_spawn_command_line_async( line, NULL );
g_free( qpath );
g_free( line );
}
void xset_set_window_icon( GtkWindow* win )
{
char* name;
XSet* set = xset_get( "main_icon" );
if ( set->icon )
name = set->icon;
else if ( geteuid() == 0 )
name = "spacefm-root";
else
name = "spacefm";
GtkIconTheme* theme = gtk_icon_theme_get_default();
if ( !theme )
return;
GdkPixbuf* icon = gtk_icon_theme_load_icon( theme, name, 48, 0, NULL );
if ( icon )
{
gtk_window_set_icon( GTK_WINDOW( win ), icon );
g_object_unref( icon );
}
}
char *replace_string( const char* orig, const char* str, const char* replace,
gboolean quote )
{ // replace all occurrences of str in orig with replace, optionally quoting
char* rep;
const char* cur;
char* result = NULL;
char* old_result;
char* s;
if ( !orig || !( s = strstr( orig, str ) ) )
return g_strdup( orig ); // str not in orig
if ( !replace )
{
if ( quote )
rep = g_strdup( "''" );
else
rep = g_strdup( "" );
}
else if ( quote )
rep = g_strdup_printf( "'%s'", replace );
else
rep = g_strdup( replace );
cur = orig;
do
{
if ( result )
{
old_result = result;
result = g_strdup_printf( "%s%s%s", old_result,
g_strndup( cur, s - cur ), rep );
g_free( old_result );
}
else
result = g_strdup_printf( "%s%s", g_strndup( cur, s - cur ), rep );
cur = s + strlen( str );
s = strstr( cur, str );
} while ( s );
old_result = result;
result = g_strdup_printf( "%s%s", old_result, cur );
g_free( old_result );
g_free( rep );
return result;
/*
// replace first occur of str in orig with rep
char* buffer;
char* buffer2;
char *p;
char* rep_good;
if ( !( p = strstr( orig, str ) ) )
return g_strdup( orig ); // str not in orig
if ( !rep )
rep_good = g_strdup_printf( "" );
else
rep_good = g_strdup( rep );
buffer = g_strndup( orig, p - orig );
if ( quote )
buffer2 = g_strdup_printf( "%s'%s'%s", buffer, rep_good, p + strlen( str ) );
else
buffer2 = g_strdup_printf( "%s%s%s", buffer, rep_good, p + strlen( str ) );
g_free( buffer );
g_free( rep_good );
return buffer2;
*/
}
char* bash_quote( const char* str )
{
if ( !str )
return g_strdup( "''" );
char* s1 = replace_string( str, "'", "'\\''", FALSE );
char* s2 = g_strdup_printf( "'%s'", s1 );
g_free( s1 );
return s2;
}
char* plain_ascii_name( const char* orig_name )
{
if ( !orig_name )
return g_strdup( "" );
char* orig = g_strdup( orig_name );
g_strcanon( orig, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_", ' ' );
char* s = replace_string( orig, " ", "", FALSE );
g_free( orig );
return s;
}
char* clean_label( const char* menu_label, gboolean kill_special, gboolean convert_amp )
{
char* s1;
char* s2;
s1 = replace_string( menu_label, "_", "", FALSE );
if ( kill_special )
{
s2 = replace_string( s1, "&", "", FALSE );
g_free( s1 );
s1 = replace_string( s2, " ", "-", FALSE );
g_free( s2 );
}
else if ( convert_amp )
{
s2 = replace_string( s1, "&", "&", FALSE );
g_free( s1 );
s1 = s2;
}
return s1;
}
void string_copy_free( char** s, const char* src )
{
char* discard = *s;
*s = g_strdup( src );
g_free( discard );
}
char* unescape( const char* t )
{
if ( !t )
return NULL;
char* s = g_strdup( t );
int i = 0, j = 0;
while ( t[i] )
{
switch ( t[i] )
{
case '\\':
switch( t[++i] )
{
case 'n':
s[j] = '\n';
break;
case 't':
s[j] = '\t';
break;
case '\\':
s[j] = '\\';
break;
case '\"':
s[j] = '\"';
break;
default:
// copy
s[j++] = '\\';
s[j] = t[i];
}
break;
default:
s[j] = t[i];
}
++i;
++j;
}
s[j] = t[i]; // null char
return s;
}
void xset_defaults()
{
XSet* set;
srand( (unsigned int)time( 0 ) + getpid() );
// set_last must be set (to anything)
set_last = xset_get( "separator" );
set_last->menu_style = XSET_MENU_SEP;
// toolbars
set = xset_get( "sep_tool1" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_tool2" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_tool3" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_tool4" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "toolbar_left", "label", _("_Left Toolbar") );
xset_set_set( set, "desc", "tool_device tool_book tool_dirtree tool_newtab tool_newtabhere tool_back tool_backmenu tool_forward tool_forwardmenu tool_up tool_home tool_default tool_refresh" );
set->menu_style = XSET_MENU_SUBMENU;
set = xset_set( "toolbar_right", "label", _("_Right Toolbar") );
xset_set_set( set, "desc", "rtool_device rtool_book rtool_dirtree rtool_newtab rtool_newtabhere rtool_back rtool_backmenu rtool_forward rtool_forwardmenu rtool_up rtool_refresh rtool_home rtool_default" );
set->menu_style = XSET_MENU_SUBMENU;
set = xset_set( "toolbar_side", "label", _("_Side Toolbar") );
xset_set_set( set, "desc", "stool_device stool_book stool_dirtree stool_newtab stool_newtabhere stool_back stool_backmenu stool_forward stool_forwardmenu stool_up stool_refresh stool_home stool_default" ); // stool_mount stool_mountopen stool_eject
set->menu_style = XSET_MENU_SUBMENU;
set = xset_set( "toolbar_hide", "label", _("_Hide") );
xset_set_set( set, "shared_key", "panel1_show_toolbox" );
set = xset_set( "toolbar_hide_side", "label", _("_Hide") );
xset_set_set( set, "shared_key", "panel1_show_sidebar" );
set = xset_set( "toolbar_config", "label", _("Configure Toolbar") );
xset_set_set( set, "icon", "gtk-properties" );
set->tool = XSET_B_TRUE;
set = xset_set( "toolbar_help", "label", _("H_elp") );
xset_set_set( set, "icon", "gtk-help" );
// toolitems left
set = xset_set( "tool_dirtree", "label", _("Tree") );
xset_set_set( set, "icon", "gtk-directory" );
set->menu_style = XSET_MENU_CHECK;
set->tool = XSET_B_TRUE;
xset_set_set( set, "shared_key", "panel1_show_dirtree" );
set = xset_set( "tool_book", "label", _("Bookmarks") );
xset_set_set( set, "icon", "gtk-jump-to" );
set->menu_style = XSET_MENU_CHECK;
set->tool = XSET_B_TRUE;
xset_set_set( set, "shared_key", "panel1_show_book" );
set = xset_set( "tool_device", "label", _("Devices") );
xset_set_set( set, "icon", "gtk-harddisk" );
set->menu_style = XSET_MENU_CHECK;
set->tool = XSET_B_TRUE;
xset_set_set( set, "shared_key", "panel1_show_devmon" );
set = xset_set( "tool_newtab", "label", _("New Tab") );
xset_set_set( set, "icon", "gtk-add" );
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "tab_new" );
set = xset_set( "tool_newtabhere", "label", _("New Tab Here") );
xset_set_set( set, "icon", "gtk-add" );
set->tool = XSET_B_TRUE;
xset_set_set( set, "shared_key", "tab_new_here" );
set = xset_set( "tool_back", "label", _("Back") );
xset_set_set( set, "icon", "gtk-go-back" );
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "go_back" );
set = xset_set( "tool_backmenu", "label", _("Back Menu") );
xset_set_set( set, "icon", "gtk-go-back" );
set->menu_style = XSET_MENU_SUBMENU;
set->tool = XSET_B_TRUE;
set = xset_set( "tool_forward", "label", _("Forward") );
xset_set_set( set, "icon", "gtk-go-forward" );
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "go_forward" );
set = xset_set( "tool_forwardmenu", "label", _("Forward Menu") );
xset_set_set( set, "icon", "gtk-go-forward" );
set->menu_style = XSET_MENU_SUBMENU;
set->tool = XSET_B_TRUE;
set = xset_set( "tool_up", "label", _("Up") );
xset_set_set( set, "icon", "gtk-go-up" );
set->tool = XSET_B_TRUE;
xset_set_set( set, "shared_key", "go_up" );
set = xset_set( "tool_refresh", "label", _("Refresh") );
xset_set_set( set, "icon", "gtk-refresh" );
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "view_refresh" );
set = xset_set( "tool_home", "label", _("Home") );
xset_set_set( set, "icon", "gtk-home" );
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "go_home" );
set = xset_set( "tool_default", "label", _("Default") );
xset_set_set( set, "icon", "gtk-home" );
set->tool = XSET_B_TRUE;
xset_set_set( set, "shared_key", "go_default" );
// toolitems right
set = xset_set( "rtool_dirtree", "label", _("Tree") );
xset_set_set( set, "icon", "gtk-directory" );
set->menu_style = XSET_MENU_CHECK;
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "panel1_show_dirtree" );
set = xset_set( "rtool_book", "label", _("Bookmarks") );
xset_set_set( set, "icon", "gtk-jump-to" );
set->menu_style = XSET_MENU_CHECK;
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "panel1_show_book" );
set = xset_set( "rtool_device", "label", _("Devices") );
xset_set_set( set, "icon", "gtk-harddisk" );
set->menu_style = XSET_MENU_CHECK;
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "panel1_show_devmon" );
set = xset_set( "rtool_newtab", "label", _("New Tab") );
xset_set_set( set, "icon", "gtk-add" );
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "tab_new" );
set = xset_set( "rtool_newtabhere", "label", _("New Tab Here") );
xset_set_set( set, "icon", "gtk-add" );
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "tab_new_here" );
set = xset_set( "rtool_back", "label", _("Back") );
xset_set_set( set, "icon", "gtk-go-back" );
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "go_back" );
set = xset_set( "rtool_backmenu", "label", _("Back Menu") );
xset_set_set( set, "icon", "gtk-go-back" );
set->menu_style = XSET_MENU_SUBMENU;
set->tool = XSET_B_FALSE;
set = xset_set( "rtool_forward", "label", _("Forward") );
xset_set_set( set, "icon", "gtk-go-forward" );
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "go_forward" );
set = xset_set( "rtool_forwardmenu", "label", _("Forward Menu") );
xset_set_set( set, "icon", "gtk-go-forward" );
set->menu_style = XSET_MENU_SUBMENU;
set->tool = XSET_B_FALSE;
set = xset_set( "rtool_up", "label", _("Up") );
xset_set_set( set, "icon", "gtk-go-up" );
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "go_up" );
set = xset_set( "rtool_refresh", "label", _("Refresh") );
xset_set_set( set, "icon", "gtk-refresh" );
set->tool = XSET_B_TRUE;
xset_set_set( set, "shared_key", "view_refresh" );
set = xset_set( "rtool_home", "label", _("Home") );
xset_set_set( set, "icon", "gtk-home" );
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "go_home" );
set = xset_set( "rtool_default", "label", _("Default") );
xset_set_set( set, "icon", "gtk-home" );
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "go_default" );
// toolitems side
set = xset_set( "stool_dirtree", "label", _("Tree") );
xset_set_set( set, "icon", "gtk-directory" );
set->menu_style = XSET_MENU_CHECK;
set->tool = XSET_B_TRUE;
xset_set_set( set, "shared_key", "panel1_show_dirtree" );
set = xset_set( "stool_book", "label", _("Bookmarks") );
xset_set_set( set, "icon", "gtk-jump-to" );
set->menu_style = XSET_MENU_CHECK;
set->tool = XSET_B_TRUE;
xset_set_set( set, "shared_key", "panel1_show_book" );
set = xset_set( "stool_device", "label", _("Devices") );
xset_set_set( set, "icon", "gtk-harddisk" );
set->menu_style = XSET_MENU_CHECK;
set->tool = XSET_B_TRUE;
xset_set_set( set, "shared_key", "panel1_show_devmon" );
set = xset_set( "stool_newtab", "label", _("New Tab") );
xset_set_set( set, "icon", "gtk-add" );
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "tab_new" );
set = xset_set( "stool_newtabhere", "label", _("New Tab Here") );
xset_set_set( set, "icon", "gtk-add" );
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "tab_new_here" );
set = xset_set( "stool_back", "label", _("Back") );
xset_set_set( set, "icon", "gtk-go-back" );
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "go_back" );
set = xset_set( "stool_backmenu", "label", _("Back Menu") );
xset_set_set( set, "icon", "gtk-go-back" );
set->menu_style = XSET_MENU_SUBMENU;
set->tool = XSET_B_FALSE;
set = xset_set( "stool_forward", "label", _("Forward") );
xset_set_set( set, "icon", "gtk-go-forward" );
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "go_forward" );
set = xset_set( "stool_forwardmenu", "label", _("Forward Menu") );
xset_set_set( set, "icon", "gtk-go-forward" );
set->menu_style = XSET_MENU_SUBMENU;
set->tool = XSET_B_FALSE;
set = xset_set( "stool_up", "label", _("Up") );
xset_set_set( set, "icon", "gtk-go-up" );
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "go_up" );
set = xset_set( "stool_refresh", "label", _("Refresh") );
xset_set_set( set, "icon", "gtk-refresh" );
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "view_refresh" );
set = xset_set( "stool_home", "label", _("Home") );
xset_set_set( set, "icon", "gtk-home" );
set->tool = XSET_B_FALSE;
set = xset_set( "stool_default", "label", _("Default") );
xset_set_set( set, "icon", "gtk-home" );
set->tool = XSET_B_FALSE;
xset_set_set( set, "shared_key", "go_default" );
set = xset_set( "stool_mount", "label", _("Mount") );//not added
xset_set_set( set, "icon", "drive-removable-media" );
set->tool = XSET_B_FALSE;
set = xset_set( "stool_mountopen", "label", _("Mount & Open") );//not added
xset_set_set( set, "icon", "gtk-open" );
set->tool = XSET_B_TRUE;
set = xset_set( "stool_eject", "label", _("Remove") );//not added
xset_set_set( set, "icon", "gtk-disconnect" );
set->tool = XSET_B_TRUE;
// dev menu
set = xset_get( "sep_dm1" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_dm2" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_dm3" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_dm4" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_dm5" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "dev_menu_remove", "label", _("Remo_ve / Eject") );
xset_set_set( set, "icon", "gtk-disconnect" );
set->line = g_strdup( "#devices-menu-remove" );
set = xset_set( "dev_menu_unmount", "label", _("_Unmount") );
xset_set_set( set, "icon", "gtk-remove" );
set->line = g_strdup( "#devices-menu-unmount" );
set = xset_set( "dev_menu_reload", "label", _("Re_load") );
xset_set_set( set, "icon", "gtk-disconnect" );
set->line = g_strdup( "#devices-menu-reload" );
set = xset_set( "dev_menu_sync", "label", _("_Sync") );
xset_set_set( set, "icon", "gtk-save" );
set->line = g_strdup( "#devices-menu-sync" );
set = xset_set( "dev_menu_open", "label", _("_Open") );
xset_set_set( set, "icon", "gtk-open" );
set->line = g_strdup( "#devices-menu-open" );
set = xset_set( "dev_menu_tab", "label", C_("Devices|Open|", "_Tab") );
xset_set_set( set, "icon", "gtk-add" );
set->line = g_strdup( "#devices-menu-tab" );
set = xset_set( "dev_menu_mount", "label", _("_Mount") );
xset_set_set( set, "icon", "drive-removable-media" );
set->line = g_strdup( "#devices-menu-mount" );
set = xset_set( "dev_menu_remount", "label", _("Re_/mount") );
xset_set_set( set, "icon", "gtk-redo" );
set->line = g_strdup( "#devices-menu-remount" );
set = xset_set( "dev_menu_mark", "label", _("_Bookmark") );
xset_set_set( set, "icon", "gtk-add" );
set->line = g_strdup( "#devices-menu-bookmark" );
set = xset_get( "sep_mr1" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_mr2" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_mr3" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "dev_menu_root", "label", _("_Root") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "dev_root_unmount dev_root_mount sep_mr1 dev_root_label sep_mr2 dev_root_check dev_menu_format dev_menu_backup dev_menu_restore sep_mr3 dev_root_fstab dev_root_udevil" );
xset_set_set( set, "icon", "gtk-dialog-warning" );
set->line = g_strdup( "#devices-root" );
set = xset_set( "dev_root_mount", "label", _("_Mount") );
xset_set_set( set, "icon", "drive-removable-media" );
xset_set_set( set, "z", "/usr/bin/udisks --mount %v --mount-options %o" );
set->line = g_strdup( "#devices-root-mount" );
set = xset_set( "dev_root_unmount", "label", _("_Unmount") );
xset_set_set( set, "icon", "gtk-remove" );
xset_set_set( set, "z", "/usr/bin/udisks --unmount %v" );
set->line = g_strdup( "#devices-root-unmount" );
set = xset_set( "dev_root_label", "label", _("_Label") );
xset_set_set( set, "icon", "gtk-edit" );
set->line = g_strdup( "#devices-root-label" );
// set->y contains current remove label command
// set->z contains current set label command
// set->desc contains default remove label command
// set->title contains default set label command
// ext2,3,4
set = xset_get( "label_cmd_ext" );
xset_set_set( set, "desc", "/sbin/tune2fs -L %l %v" );
xset_set_set( set, "title", set->desc );
set->line = g_strdup( "#devices-root-label" );
set = xset_get( "label_cmd_vfat" );
xset_set_set( set, "desc", "mlabel -c -i %v ::" );
xset_set_set( set, "title", "mlabel -i %v ::%l" );
set->line = g_strdup( "#devices-root-label" );
set = xset_get( "label_cmd_msdos" );
xset_set_set( set, "desc", "mlabel -c -i %v ::" );
xset_set_set( set, "title", "mlabel -i %v ::%l" );
set->line = g_strdup( "#devices-root-label" );
set = xset_get( "label_cmd_fat16" );
xset_set_set( set, "desc", "mlabel -c -i %v ::" );
xset_set_set( set, "title", "mlabel -i %v ::%l" );
set->line = g_strdup( "#devices-root-label" );
set = xset_get( "label_cmd_fat32" );
xset_set_set( set, "desc", "mlabel -c -i %v ::" );
xset_set_set( set, "title", "mlabel -i %v ::%l" );
set->line = g_strdup( "#devices-root-label" );
set = xset_get( "label_cmd_ntfs" );
xset_set_set( set, "desc", "/sbin/ntfslabel -f %v %l" );
xset_set_set( set, "title", set->desc );
set->line = g_strdup( "#devices-root-label" );
set = xset_get( "label_cmd_btrfs" );
xset_set_set( set, "desc", "/sbin/btrfs filesystem label %v %l" );
xset_set_set( set, "title", set->desc );
set->line = g_strdup( "#devices-root-label" );
set = xset_get( "label_cmd_reiserfs" );
xset_set_set( set, "desc", "/sbin/reiserfstune -l %l %v" );
xset_set_set( set, "title", set->desc );
set->line = g_strdup( "#devices-root-label" );
set = xset_set( "dev_root_check", "label", _("_Check") );
xset_set_set( set, "desc", "/sbin/fsck %v" );
set->line = g_strdup( "#devices-root-check" );
set = xset_set( "dev_root_fstab", "label", _("_Edit fstab") );
xset_set_set( set, "icon", "gtk-edit" );
set->line = g_strdup( "#devices-root-fstab" );
set = xset_set( "dev_root_udevil", "label", _("Edit u_devil.conf") );
xset_set_set( set, "icon", "gtk-edit" );
set->line = g_strdup( "#devices-root-udevil" );
set = xset_set( "dev_menu_format", "label", _("_Format") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "dev_fmt_vfat dev_fmt_ntfs dev_fmt_ext2 dev_fmt_ext3 dev_fmt_ext4 dev_fmt_btrfs dev_fmt_reis dev_fmt_reis4 dev_fmt_swap dev_fmt_zero dev_fmt_urand" );
set->line = g_strdup( "#devices-root-format" );
set = xset_set( "dev_fmt_vfat", "label", "_vfat" );
xset_set_set( set, "desc", "vfat" );
xset_set_set( set, "title", "/sbin/mkfs -t vfat %v" );
set->line = g_strdup( "#devices-root-format" );
set = xset_set( "dev_fmt_ntfs", "label", "_ntfs" );
xset_set_set( set, "desc", "ntfs" );
xset_set_set( set, "title", "/sbin/mkfs -t ntfs %v" );
set->line = g_strdup( "#devices-root-format" );
set = xset_set( "dev_fmt_ext2", "label", "ext_2" );
xset_set_set( set, "desc", "ext2" );
xset_set_set( set, "title", "/sbin/mkfs -t ext2 %v" );
set->line = g_strdup( "#devices-root-format" );
set = xset_set( "dev_fmt_ext3", "label", "ext_3" );
xset_set_set( set, "desc", "ext3" );
xset_set_set( set, "title", "/sbin/mkfs -t ext3 %v" );
set->line = g_strdup( "#devices-root-format" );
set = xset_set( "dev_fmt_ext4", "label", "ext_4" );
xset_set_set( set, "desc", "ext4" );
xset_set_set( set, "title", "/sbin/mkfs -t ext4 %v" );
set->line = g_strdup( "#devices-root-format" );
set = xset_set( "dev_fmt_btrfs", "label", "_btrfs" );
xset_set_set( set, "desc", "btrfs" );
xset_set_set( set, "title", "/sbin/mkfs -t btrfs %v" );
set->line = g_strdup( "#devices-root-format" );
set = xset_set( "dev_fmt_reis", "label", "_reiserfs" );
xset_set_set( set, "desc", "reiserfs" );
xset_set_set( set, "title", "/sbin/mkfs -t reiserfs %v" );
set->line = g_strdup( "#devices-root-format" );
set = xset_set( "dev_fmt_reis4", "label", "r_eiser4" );
xset_set_set( set, "desc", "reiser4" );
xset_set_set( set, "title", "/sbin/mkfs -t reiser4 %v" );
set->line = g_strdup( "#devices-root-format" );
set = xset_set( "dev_fmt_swap", "label", "_swap" );
xset_set_set( set, "desc", "swap" );
xset_set_set( set, "title", "/sbin/mkswap %v" );
set->line = g_strdup( "#devices-root-format" );
set = xset_set( "dev_fmt_zero", "label", "_zero" );
xset_set_set( set, "desc", "zero" );
xset_set_set( set, "title", "dd if=/dev/zero of=%v" );
set->line = g_strdup( "#devices-root-format" );
set = xset_set( "dev_fmt_urand", "label", "_urandom" );
xset_set_set( set, "desc", "urandom" );
xset_set_set( set, "title", "dd if=/dev/urandom of=%v" );
set->line = g_strdup( "#devices-root-format" );
set = xset_set( "dev_menu_backup", "label", _("_Backup") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "dev_back_fsarc dev_back_part dev_back_mbr" );
set->line = g_strdup( "#devices-root-fsarc" );
set = xset_set( "dev_back_fsarc", "label", "_FSArchiver" );
xset_set_set( set, "desc", "FSArchiver" );
xset_set_set( set, "title", "/usr/sbin/fsarchiver -vo -z 7 savefs %s %v" );
set->line = g_strdup( "#devices-root-fsarc" );
set = xset_set( "dev_back_part", "label", "_Partimage" );
xset_set_set( set, "desc", "Partimage" );
xset_set_set( set, "title", "/usr/sbin/partimage -dbo -V 4050 save %v %s" );
set->line = g_strdup( "#devices-root-parti" );
set = xset_set( "dev_back_mbr", "label", "_MBR" );
xset_set_set( set, "desc", "MBR" );
set->line = g_strdup( "#devices-root-mbr" );
set = xset_get( "sep_mr4" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "dev_menu_restore", "label", _("_Restore") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "dev_rest_file sep_mr4 dev_rest_info" );
set->line = g_strdup( "#devices-root-resfile" );
set = xset_set( "dev_rest_file", "label", _("_From File") );
xset_set_set( set, "desc", "/usr/sbin/fsarchiver -v restfs %s id=0,dest=%v" );
xset_set_set( set, "title", "/usr/sbin/partimage -b restore %v %s" );
set->line = g_strdup( "#devices-root-resfile" );
set = xset_set( "dev_rest_info", "label", _("File _Info") );
set->line = g_strdup( "#devices-root-resinfo" );
set = xset_set( "dev_prop", "label", _("_Properties") );
set->line = g_strdup( "#devices-menu-properties" );
set = xset_set( "dev_menu_settings", "label", _("Setti_ngs") );
xset_set_set( set, "icon", "gtk-properties" );
set->menu_style = XSET_MENU_SUBMENU;
set->line = g_strdup( "#devices-settings" );
// dev settings
set = xset_set( "dev_show", "label", _("S_how") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "dev_show_internal_drives dev_show_empty dev_show_partition_tables dev_show_net dev_show_file dev_ignore_udisks_hide dev_show_hide_volumes dev_dispname" );
set->line = g_strdup( "#devices-settings-internal" );
set = xset_set( "dev_show_internal_drives", "label", _("_Internal Drives") );
set->menu_style = XSET_MENU_CHECK;
set->b = geteuid() == 0 ? XSET_B_TRUE : XSET_B_FALSE;
set->line = g_strdup( "#devices-settings-internal" );
set = xset_set( "dev_show_empty", "label", _("_Empty Drives") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE; //geteuid() == 0 ? XSET_B_TRUE : XSET_B_UNSET;
set->line = g_strdup( "#devices-settings-empty" );
set = xset_set( "dev_show_partition_tables", "label", _("_Partition Tables") );
set->menu_style = XSET_MENU_CHECK;
set->line = g_strdup( "#devices-settings-table" );
set = xset_set( "dev_show_net", "label", _("Mounted _Networks") );
set->menu_style = XSET_MENU_CHECK;
set->line = g_strdup( "#devices-settings-net" );
set->b = XSET_B_TRUE;
set = xset_set( "dev_show_file", "label", _("Mounted _Files") );
set->menu_style = XSET_MENU_CHECK;
set->line = g_strdup( "#devices-settings-files" );
set->b = XSET_B_TRUE;
set = xset_set( "dev_show_hide_volumes", "label", _("_Volumes...") );
xset_set_set( set, "title", _("Show/Hide Volumes") );
xset_set_set( set, "desc", _("To force showing or hiding of some volumes, overriding other settings, you can specify the devices, volume labels, or device IDs in the space-separated list below.\n\nExample: +/dev/sdd1 -Label With Space +ata-OCZ-part4\nThis would cause /dev/sdd1 and the OCZ device to be shown, and the volume with label \"Label With Space\" to be hidden.\n\nThere must be a space between entries and a plus or minus sign directly before each item. This list is case-sensitive.\n\n") );
set->line = g_strdup( "#devices-settings-vol" );
set = xset_set( "dev_ignore_udisks_hide", "label", _("Ignore _Hide Policy") );
set->menu_style = XSET_MENU_CHECK;
set->line = g_strdup( "#devices-settings-hide" );
set = xset_set( "dev_dispname", "label", _("_Display Name") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Set Display Name Format") );
xset_set_set( set, "desc", _("Enter device display name format:\n\nUse:\n\t%%v\tdevice filename (eg sdd1)\n\t%%s\ttotal size (eg 800G)\n\t%%t\tfstype (eg ext4)\n\t%%l\tvolume label (eg Label or [no media])\n\t%%m\tmount point if mounted, or ---\n\t%%i\tdevice ID\n") );
xset_set_set( set, "s", "%v %s %l %m" );
xset_set_set( set, "z", "%v %s %l %m" );
xset_set_set( set, "icon", "gtk-edit" );
set->line = g_strdup( "#devices-settings-name" );
set = xset_set( "dev_menu_auto", "label", _("_Auto Mount") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "dev_automount_optical dev_automount_removable dev_ignore_udisks_nopolicy dev_automount_volumes dev_auto_open dev_unmount_quit" );
set->line = g_strdup( "#devices-settings-optical" );
set = xset_set( "dev_automount_optical", "label", _("Mount _Optical") );
set->b = geteuid() == 0 ? XSET_B_FALSE : XSET_B_TRUE;
set->menu_style = XSET_MENU_CHECK;
set->line = g_strdup( "#devices-settings-optical" );
set = xset_set( "dev_automount_removable", "label", _("_Mount Removable") );
set->b = geteuid() == 0 ? XSET_B_FALSE : XSET_B_TRUE;
set->menu_style = XSET_MENU_CHECK;
set->line = g_strdup( "#devices-settings-remove" );
set = xset_set( "dev_auto_open", "label", _("Open _Tab") );
set->b = XSET_B_TRUE;
set->menu_style = XSET_MENU_CHECK;
set->line = g_strdup( "#devices-settings-tab" );
set = xset_set( "dev_unmount_quit", "label", _("_Unmount On Exit") );
set->b = XSET_B_UNSET;
set->menu_style = XSET_MENU_CHECK;
set->line = g_strdup( "#devices-settings-exit" );
set = xset_get( "sep_ar1" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "dev_exec", "label", _("Auto _Run") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "dev_exec_fs dev_exec_audio dev_exec_video sep_ar1 dev_exec_insert dev_exec_unmount dev_exec_remove" );
xset_set_set( set, "icon", "gtk-execute" );
set->line = g_strdup( "#devices-settings-runm" );
set = xset_set( "dev_exec_fs", "label", _("On _Mount") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Auto Run On Mount") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically after a removable drive or data disc is auto-mounted:\n\nUse:\n\t%%v\tdevice (eg /dev/sda1)\n\t%%l\tdevice label\n\t%%m\tdevice mount point (eg /media/disk)") );
set->line = g_strdup( "#devices-settings-runm" );
set = xset_set( "dev_exec_audio", "label", _("On _Audio CD") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Auto Run On Audio CD") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically when an audio CD is inserted in a qualified device:\n\nUse:\n\t%%v\tdevice (eg /dev/sda1)\n\t%%l\tdevice label\n\t%%m\tdevice mount point (eg /media/disk)") );
set->line = g_strdup( "#devices-settings-runa" );
set = xset_set( "dev_exec_video", "label", _("On _Video DVD") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Auto Run On Video DVD") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically when a video DVD is auto-mounted:\n\nUse:\n\t%%v\tdevice (eg /dev/sda1)\n\t%%l\tdevice label\n\t%%m\tdevice mount point (eg /media/disk)") );
set->line = g_strdup( "#devices-settings-runv" );
set = xset_set( "dev_exec_insert", "label", _("On _Insert") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Auto Run On Insert") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically when any device is inserted:\n\nUse:\n\t%%v\tdevice added (eg /dev/sda1)\n\t%%l\tdevice label\n\t%%m\tdevice mount point (eg /media/disk)") );
set->line = g_strdup( "#devices-settings-runi" );
set = xset_set( "dev_exec_unmount", "label", _("On _Unmount") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Auto Run On Unmount") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically when any device is unmounted by any means:\n\nUse:\n\t%%v\tdevice unmounted (eg /dev/sda1)\n\t%%l\tdevice label\n\t%%m\tdevice mount point (eg /media/disk)") );
set->line = g_strdup( "#devices-settings-runu" );
set = xset_set( "dev_exec_remove", "label", _("On _Remove") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Auto Run On Remove") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically when any device is removed (ejection of media does not qualify):\n\nUse:\n\t%%v\tdevice removed (eg /dev/sda1)\n\t%%l\tdevice label\n\t%%m\tdevice mount point (eg /media/disk)") );
set->line = g_strdup( "#devices-settings-runr" );
set = xset_set( "dev_ignore_udisks_nopolicy", "label", _("Ignore _No Policy") );
set->menu_style = XSET_MENU_CHECK;
set->line = g_strdup( "#devices-settings-nopolicy" );
set = xset_set( "dev_automount_volumes", "label", _("Mount _Volumes...") );
xset_set_set( set, "title", _("Auto-Mount Volumes") );
xset_set_set( set, "desc", _("To force or prevent automounting of some volumes, overriding other settings, you can specify the devices, volume labels, or device IDs in the space-separated list below.\n\nExample: +/dev/sdd1 -Label With Space +ata-OCZ-part4\nThis would cause /dev/sdd1 and the OCZ device to be auto-mounted when detected, and the volume with label \"Label With Space\" to be ignored.\n\nThere must be a space between entries and a plus or minus sign directly before each item. This list is case-sensitive.\n\n") );
set->line = g_strdup( "#devices-settings-mvol" );
set = xset_set( "dev_mount_options", "label", _("_Mount Options") );
xset_set_set( set, "desc", _("Enter your comma- or space-separated list of default mount options below (to be used for all mounts).\n\nIn addition to regular options, you can also specify options to be added or removed for a specific filesystem type by using the form OPTION+FSTYPE or OPTION-FSTYPE.\n\nExample: nosuid, sync+vfat, sync+ntfs, noatime, noatime-ext4\nThis will add nosuid and noatime for all filesystem types, add sync for vfat and ntfs only, and remove noatime for ext4.\n\nNote: Some options, such as nosuid, may be added by the mount program even if you don't include them. Options in fstab take precedence. pmount ignores options set here.") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Default Mount Options") );
xset_set_set( set, "s", "noexec, nosuid, noatime" );
xset_set_set( set, "z", "noexec, nosuid, noatime" );
xset_set_set( set, "icon", "gtk-edit" );
set->line = g_strdup( "#devices-settings-opts" );
set = xset_set( "dev_remount_options", "z", "noexec, nosuid, noatime" );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Re/mount With Options") );
xset_set_set( set, "desc", _("Device will be (re)mounted using the options below.\n\nIn addition to regular options, you can also specify options to be added or removed for a specific filesystem type by using the form OPTION+FSTYPE or OPTION-FSTYPE.\n\nExample: nosuid, sync+vfat, sync+ntfs, noatime, noatime-ext4\nThis will add nosuid and noatime for all filesystem types, add sync for vfat and ntfs only, and remove noatime for ext4.\n\nNote: Some options, such as nosuid, may be added by the mount program even if you don't include them. Options in fstab take precedence. pmount ignores options set here.") );
xset_set_set( set, "s", "noexec, nosuid, noatime" );
set->line = g_strdup( "#devices-menu-remount" );
set = xset_set( "dev_mount_cmd", "label", _("Mount _Command") );
xset_set_set( set, "desc", _("Enter the command to mount a device:\n\nUse:\n\t%%v\tdevice file ( eg /dev/sda5 )\n\t%%o\tvolume-specific mount options\n\nudevil:\t/usr/bin/udevil mount -o %%o %%v\npmount:\t/usr/bin/pmount %%v\nUdisks2:\t/usr/bin/udisksctl mount -b %%v -o %%o\nUdisks1:\t/usr/bin/udisks --mount %%v --mount-options %%o\n\nLeave blank for auto-detection.") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Mount Command") );
xset_set_set( set, "icon", "gtk-edit" );
set->line = g_strdup( "#devices-settings-mcmd" );
set = xset_set( "dev_unmount_cmd", "label", _("_Unmount Command") );
xset_set_set( set, "desc", _("Enter the command to unmount a device:\n\nUse:\n\t%%v\tdevice file ( eg /dev/sda5 )\n\nudevil:\t/usr/bin/udevil umount %%v\npmount:\t/usr/bin/pumount %%v\nUdisks1:\t/usr/bin/udisks --unmount %%v\nUdisks2:\t/usr/bin/udisksctl unmount -b %%v\n\nLeave blank for auto-detection.") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Unmount Command") );
xset_set_set( set, "icon", "gtk-edit" );
set->line = g_strdup( "#devices-settings-ucmd" );
// dev icons
set = xset_get( "sep_i1" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_i2" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_i3" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_i4" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "dev_icon", "label", _("_Icon") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "dev_icon_internal_mounted dev_icon_internal_unmounted sep_i1 dev_icon_remove_mounted dev_icon_remove_unmounted sep_i2 dev_icon_optical_mounted dev_icon_optical_media dev_icon_optical_nomedia dev_icon_audiocd sep_i3 dev_icon_floppy_mounted dev_icon_floppy_unmounted sep_i4 dev_icon_network dev_icon_file" );
set->line = g_strdup( "#devices-settings-icon" );
set = xset_set( "dev_icon_audiocd", "label", _("Audio CD") );
set->menu_style = XSET_MENU_ICON;
xset_set_set( set, "icon", "gtk-cdrom" );
set->line = g_strdup( "" );
set->line = g_strdup( "#devices-settings-icon" );
set = xset_set( "dev_icon_optical_mounted", "label", _("Optical Mounted") );
set->menu_style = XSET_MENU_ICON;
xset_set_set( set, "icon", "gtk-cdrom" );
set->line = g_strdup( "#devices-settings-icon" );
set = xset_set( "dev_icon_optical_media", "label", _("Optical Has Media") );
set->menu_style = XSET_MENU_ICON;
xset_set_set( set, "icon", "gtk-cdrom" );
set->line = g_strdup( "#devices-settings-icon" );
set = xset_set( "dev_icon_optical_nomedia", "label", _("Optical No Media") );
set->menu_style = XSET_MENU_ICON;
xset_set_set( set, "icon", "gtk-cdrom" );
set->line = g_strdup( "#devices-settings-icon" );
set = xset_set( "dev_icon_floppy_mounted", "label", _("Floppy Mounted") );
set->menu_style = XSET_MENU_ICON;
xset_set_set( set, "icon", "gtk-floppy" );
set->line = g_strdup( "#devices-settings-icon" );
set = xset_set( "dev_icon_floppy_unmounted", "label", _("Floppy Unmounted") );
set->menu_style = XSET_MENU_ICON;
xset_set_set( set, "icon", "gtk-floppy" );
set->line = g_strdup( "#devices-settings-icon" );
set = xset_set( "dev_icon_remove_mounted", "label", _("Removable Mounted") );
set->menu_style = XSET_MENU_ICON;
xset_set_set( set, "icon", "gtk-harddisk" );
set->line = g_strdup( "#devices-settings-icon" );
set = xset_set( "dev_icon_remove_unmounted", "label", _("Removable Unmounted") );
set->menu_style = XSET_MENU_ICON;
xset_set_set( set, "icon", "gtk-harddisk" );
set->line = g_strdup( "#devices-settings-icon" );
set = xset_set( "dev_icon_internal_mounted", "label", _("Internal Mounted") );
set->menu_style = XSET_MENU_ICON;
xset_set_set( set, "icon", "gtk-harddisk" );
set->line = g_strdup( "#devices-settings-icon" );
set = xset_set( "dev_icon_internal_unmounted", "label", _("Internal Unmounted") );
set->menu_style = XSET_MENU_ICON;
xset_set_set( set, "icon", "gtk-harddisk" );
set->line = g_strdup( "#devices-settings-icon" );
set = xset_set( "dev_icon_network", "label", _("Mounted Network") );
set->menu_style = XSET_MENU_ICON;
xset_set_set( set, "icon", "gtk-network" );
set->line = g_strdup( "#devices-settings-icon" );
set = xset_set( "dev_icon_file", "label", _("Mounted File") );
set->menu_style = XSET_MENU_ICON;
xset_set_set( set, "icon", "gtk-file" );
set->line = g_strdup( "#devices-settings-icon" );
// Bookmark list
set = xset_get( "sep_bk1" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_bk2" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "book_new", "label", _("_New") );
xset_set_set( set, "icon", "gtk-new" );
set = xset_set( "book_rename", "label", _("_Rename") );
xset_set_set( set, "icon", "gtk-edit" );
set = xset_set( "book_edit", "label", _("_Edit") );
xset_set_set( set, "icon", "gtk-edit" );
set = xset_set( "book_remove", "label", _("Re_move") );
xset_set_set( set, "icon", "gtk-remove" );
set = xset_set( "book_open", "label", _("_Open") );
xset_set_set( set, "icon", "gtk-open" );
set = xset_set( "book_tab", "label", C_("Bookmarks|Open|", "_Tab") );
xset_set_set( set, "icon", "gtk-add" );
set = xset_set( "book_settings", "label", _("_Settings") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "icon", "gtk-properties" );
set = xset_set( "book_icon", "label", _("_Icon") );
set->menu_style = XSET_MENU_ICON;
// do not set a default icon for book_icon
// Rename/Move Dialog
set = xset_set( "move_name", "label", _("_Name") );
set->menu_style = XSET_MENU_CHECK;
set = xset_set( "move_filename", "label", _("_Filename") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set = xset_set( "move_parent", "label", _("_Parent") );
set->menu_style = XSET_MENU_CHECK;
set = xset_set( "move_path", "label", _("P_ath") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set = xset_set( "move_type", "label", _("_Type") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set = xset_set( "move_target", "label", _("_Target") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set = xset_set( "move_template", "label", _("_Template") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set = xset_set( "move_option", "label", _("_Option") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "move_copy move_link move_copyt move_linkt move_as_root" );
set = xset_set( "move_copy", "label", _("_Copy") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set = xset_set( "move_link", "label", _("_Link") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set = xset_set( "move_copyt", "label", _("Copy _Target") );
set->menu_style = XSET_MENU_CHECK;
set = xset_set( "move_linkt", "label", _("Lin_k Target") );
set->menu_style = XSET_MENU_CHECK;
set = xset_set( "move_as_root", "label", _("_As Root") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set = xset_set( "move_dlg_font", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Move Dialog Font") );
xset_set_set( set, "desc", _("/home/user/Example Filename.ext") );
set = xset_set( "move_dlg_help", "label", _("T_ips") );
xset_set_set( set, "icon", "gtk-help" );
set = xset_set( "move_dlg_confirm_create", "label", _("_Confirm Create") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
// status bar
set = xset_get( "sep_bar1" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "status_border", "label", _("Highlight _Bar") );
xset_set_set( set, "title", _("Status Bar Highlight Color") );
xset_set_set( set, "icon", "GTK_STOCK_SELECT_COLOR" );
set->menu_style = XSET_MENU_COLORDLG;
set = xset_set( "status_text", "label", _("Highlight _Text") );
xset_set_set( set, "title", _("Status Bar Text Highlight Color") );
xset_set_set( set, "icon", "GTK_STOCK_SELECT_COLOR" );
set->menu_style = XSET_MENU_COLORDLG;
set = xset_set( "status_middle", "label", _("_Middle Click") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "status_name status_path status_info status_hide" );
set = xset_set( "status_name", "label", _("Copy _Name") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "status_path", "label", _("Copy _Path") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "status_info", "label", _("File _Info") );
set->menu_style = XSET_MENU_RADIO;
set->b = XSET_B_TRUE;
set = xset_set( "status_hide", "label", _("_Hide Panel") );
set->menu_style = XSET_MENU_RADIO;
// MAIN WINDOW MENUS
// File
set = xset_get( "sep_f1" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_f2" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_f3" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "main_new_window", "label", _("New _Window") );
xset_set_set( set, "icon", "spacefm" );
set = xset_set( "main_root_window", "label", _("R_oot Window") );
xset_set_set( set, "icon", "gtk-dialog-warning" );
set = xset_set( "main_search", "label", _("_File Search") );
xset_set_set( set, "icon", "gtk-find" );
set = xset_set( "main_terminal", "label", _("_Terminal") );
set->b = XSET_B_UNSET; // discovery notification
set = xset_set( "main_root_terminal", "label", _("_Root Terminal") );
xset_set_set( set, "icon", "gtk-dialog-warning" );
set = xset_set( "main_save_session", "label", _("_Save Session") );
xset_set_set( set, "icon", "gtk-save" );
set = xset_set( "main_save_tabs", "label", _("Save Ta_bs") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set = xset_set( "main_exit", "label", _("E_xit") );
xset_set_set( set, "icon", "gtk-quit" );
// View
set = xset_get( "sep_v1" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_v2" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_v3" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_v4" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_v5" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_v6" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_v7" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_v8" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_v9" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "panel1_show", "label", _("Panel _1") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set = xset_set( "panel2_show", "label", _("Panel _2") );
set->menu_style = XSET_MENU_CHECK;
set = xset_set( "panel3_show", "label", _("Panel _3") );
set->menu_style = XSET_MENU_CHECK;
set = xset_set( "panel4_show", "label", _("Panel _4") );
set->menu_style = XSET_MENU_CHECK;
set = xset_set( "main_pbar", "label", _("Panel _Bar") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set = xset_set( "main_focus_panel", "label", _("_Go") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "panel_prev panel_next panel_hide panel_1 panel_2 panel_3 panel_4" );
xset_set_set( set, "icon", "gtk-go-forward" );
xset_set( "panel_prev", "label", _("_Prev") );
xset_set( "panel_next", "label", _("_Next") );
/*
xset_set( "panel_left", "label", _("_Left") );
xset_set( "panel_right", "label", _("_Right") );
xset_set( "panel_top", "label", _("_Top") );
xset_set( "panel_bottom", "label", _("_Bottom") );
*/
xset_set( "panel_hide", "label", _("_Hide") );
xset_set( "panel_1", "label", _("Panel _1") );
xset_set( "panel_2", "label", _("Panel _2") );
xset_set( "panel_3", "label", _("Panel _3") );
xset_set( "panel_4", "label", _("Panel _4") );
set = xset_set( "main_auto", "label", _("_Events") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "auto_inst auto_win auto_pnl auto_tab evt_device" );
xset_set_set( set, "icon", "gtk-execute" );
set->line = g_strdup( "#sockets-menu" );
set = xset_set( "auto_inst", "label", _("_Instance") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "evt_start evt_exit" );
set->line = g_strdup( "#sockets-menu" );
set = xset_set( "evt_start", "label", _("_Startup") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Set Instance Startup Command") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically when a SpaceFM instance starts:\n\nUse:\n\t%%e\tevent type (evt_start)\n") );
set->line = g_strdup( "#sockets-events-start" );
set = xset_set( "evt_exit", "label", _("_Exit") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Set Instance Exit Command") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically when a SpaceFM instance exits:\n\nUse:\n\t%%e\tevent type (evt_exit)\n") );
set->line = g_strdup( "#sockets-events-exit" );
set = xset_set( "auto_win", "label", _("_Window") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "evt_win_new evt_win_focus evt_win_move evt_win_click evt_win_key evt_win_close" );
set->line = g_strdup( "#sockets-menu" );
set = xset_set( "evt_win_new", "label", _("_New") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Set New Window Command") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically whenever a new SpaceFM window is opened:\n\nUse:\n\t%%e\tevent type (evt_win_new)\n\t%%w\twindow id (see spacefm -s help)\n\t%%p\tpanel\n\t%%t\ttab\n\nExported bash variables (eg $fm_pwd, etc) can be used in this command.") );
set->line = g_strdup( "#sockets-events-winnew" );
set = xset_set( "evt_win_focus", "label", _("_Focus") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Set Window Focus Command") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically whenever a SpaceFM window gets focus:\n\nUse:\n\t%%e\tevent type (evt_win_focus)\n\t%%w\twindow id (see spacefm -s help)\n\t%%p\tpanel\n\t%%t\ttab\n\nExported bash variables (eg $fm_pwd, etc) can be used in this command.") );
set->line = g_strdup( "#sockets-events-winfoc" );
set = xset_set( "evt_win_move", "label", _("_Move/Resize") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Set Window Move/Resize Command") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically whenever a SpaceFM window is moved or resized:\n\nUse:\n\t%%e\tevent type (evt_win_move)\n\t%%w\twindow id (see spacefm -s help)\n\t%%p\tpanel\n\t%%t\ttab\n\nExported bash variables (eg $fm_pwd, etc) can be used in this command.\n\nNote: This command may be run multiple times during resize.") );
set->line = g_strdup( "#sockets-events-winmov" );
set = xset_set( "evt_win_click", "label", _("_Click") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Set Click Command") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically whenever the mouse is clicked:\n\nUse:\n\t%%e\tevent type (evt_win_click)\n\t%%w\twindow id (see spacefm -s help)\n\t%%p\tpanel\n\t%%t\ttab\n\t%%b\tbutton (mouse button pressed)\n\t%%m\tmodifier (modifier keys)\n\t%%f\tfocus (element which received the click)\n\nExported bash variables (eg $fm_pwd, etc) can be used in this command when no asterisk prefix is used.\n\nPrefix your command with an asterisk (*) and conditionally return exit status 0 to inhibit the default handler. For example:\n*if [ \"%%b\" != \"2\" ]; then exit 1; fi; spacefm -g --label \"\\nMiddle button was clicked in %%f\" --button ok &") );
set->line = g_strdup( "#sockets-events-winclk" );
set = xset_set( "evt_win_key", "label", _("_Keypress") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Set Window Keypress Command") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically whenever a key is pressed:\n\nUse:\n\t%%e\tevent type (evt_win_key)\n\t%%w\twindow id (see spacefm -s help)\n\t%%p\tpanel\n\t%%t\ttab\n\t%%k\tkey code (key pressed)\n\t%%m\tmodifier (modifier keys)\n\nExported bash variables (eg $fm_pwd, etc) can be used in this command when no asterisk prefix is used.\n\nPrefix your command with an asterisk (*) and conditionally return exit status 0 to inhibit the default handler. For example:\n*if [ \"%%k\" != \"0xffc5\" ]; then exit 1; fi; spacefm -g --label \"\\nKey F8 was pressed.\" --button ok &") );
set->line = g_strdup( "#sockets-events-winkey" );
set = xset_set( "evt_win_close", "label", _("Cl_ose") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Set Window Close Command") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically whenever a SpaceFM window is closed:\n\nUse:\n\t%%e\tevent type (evt_win_close)\n\t%%w\twindow id (see spacefm -s help)\n\t%%p\tpanel\n\t%%t\ttab\n\nExported bash variables (eg $fm_pwd, etc) can be used in this command.") );
set->line = g_strdup( "#sockets-events-wincls" );
set = xset_set( "auto_pnl", "label", _("_Panel") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "evt_pnl_focus evt_pnl_show evt_pnl_sel" );
set->line = g_strdup( "#sockets-menu" );
set = xset_set( "evt_pnl_focus", "label", _("_Focus") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Set Panel Focus Command") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically whenever a panel gets focus:\n\nUse:\n\t%%e\tevent type (evt_pnl_focus)\n\t%%w\twindow id (see spacefm -s help)\n\t%%p\tpanel\n\t%%t\ttab\n\nExported bash variables (eg $fm_pwd, etc) can be used in this command.") );
set->line = g_strdup( "#sockets-events-pnlfoc" );
set = xset_set( "evt_pnl_show", "label", _("_Show") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Set Panel Show Command") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically whenever a panel or panel element is shown or hidden:\n\nUse:\n\t%%e\tevent type (evt_pnl_show)\n\t%%w\twindow id (see spacefm -s help)\n\t%%p\tpanel\n\t%%t\ttab\n\t%%f\tfocus (element shown or hidden)\n\t%%v\tvisible (1 or 0)\n\nExported bash variables (eg $fm_pwd, etc) can be used in this command.") );
set->line = g_strdup( "#sockets-events-pnlshw" );
set = xset_set( "evt_pnl_sel", "label", _("S_elect") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Set Panel Select Command") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically whenever the file selection changes:\n\nUse:\n\t%%e\tevent type (evt_pnl_sel)\n\t%%w\twindow id (see spacefm -s help)\n\t%%p\tpanel\n\t%%t\ttab\n\nExported bash variables (eg $fm_pwd, etc) can be used in this command.\n\nPrefix your command with an asterisk (*) and conditionally return exit status 0 to inhibit the default handler.") );
set->line = g_strdup( "#sockets-events-pnlsel" );
set = xset_set( "auto_tab", "label", C_("View|Events|", "_Tab") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "evt_tab_new evt_tab_focus evt_tab_close" );
set->line = g_strdup( "#sockets-menu" );
set = xset_set( "evt_tab_new", "label", _("_New") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Set New Tab Command") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically whenever a new tab is opened:\n\nUse:\n\t%%e\tevent type (evt_tab_new)\n\t%%w\twindow id (see spacefm -s help)\n\t%%p\tpanel\n\t%%t\ttab\n\nExported bash variables (eg $fm_pwd, etc) can be used in this command.") );
set->line = g_strdup( "#sockets-events-tabnew" );
set = xset_set( "evt_tab_focus", "label", _("_Focus") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Set Tab Focus Command") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically whenever a tab gets focus:\n\nUse:\n\t%%e\tevent type (evt_tab_focus)\n\t%%w\twindow id (see spacefm -s help)\n\t%%p\tpanel\n\t%%t\ttab\n\nExported bash variables (eg $fm_pwd, etc) can be used in this command.") );
set->line = g_strdup( "#sockets-events-tabfoc" );
set = xset_set( "evt_tab_close", "label", _("_Close") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Set Tab Close Command") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically whenever a tab is closed:\n\nUse:\n\t%%e\tevent type (evt_tab_close)\n\t%%w\twindow id (see spacefm -s help)\n\t%%p\tpanel\n\t%%t\tclosed tab") );
set->line = g_strdup( "#sockets-events-tabcls" );
set = xset_set( "evt_device", "label", _("_Device") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Set Device Command") );
xset_set_set( set, "desc", _("Enter program or bash command line to be run automatically whenever a device state changes:\n\nUse:\n\t%%e\tevent type (evt_device)\n\t%%f\tdevice file\n\t%%v\tchange (added|removed|changed)\n") );
set->line = g_strdup( "#sockets-events-device" );
set = xset_set( "main_title", "label", _("Wi_ndow Title") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Set Window Title Format") );
xset_set_set( set, "desc", _("Set window title format:\n\nUse:\n\t%%n\tcurrent folder name (eg bin)\n\t%%d\tcurrent folder path (eg /usr/bin)\n\t%%p\tcurrent panel number (1-4)\n\t%%t\tcurrent tab number\n\t%%P\ttotal number of panels visible\n\t%%T\ttotal number of tabs in current panel\n\t*\tasterisk shown if tasks running in window") );
xset_set_set( set, "s", "%d" );
xset_set_set( set, "z", "%d" );
set = xset_set( "main_icon", "label", _("_Window Icon") );
set->menu_style = XSET_MENU_ICON;
set->title = g_strdup( _("Set Window Icon") );
set->desc = g_strdup( _("Enter an icon name, icon file path, or stock item name:\n\nNot all icons may work due to various issues.\n\nProvided alternate SpaceFM icons:\n\tspacefm-[48|128]-[cube|pyramid]-[blue|green|red]\n\tspacefm-48-folder-[blue|red]\n\nFor example: spacefm-48-pyramid-green") );
set = xset_set( "main_full", "label", _("_Fullscreen") );
set->menu_style = XSET_MENU_CHECK;
set = xset_set( "main_design_mode", "label", _("_Design Mode") );
xset_set_set( set, "icon", "gtk-help" );
set = xset_set( "main_prefs", "label", _("_Preferences") );
xset_set_set( set, "icon", "gtk-preferences" );
set = xset_set( "main_tool", "label", _("_Tool") );
set->menu_style = XSET_MENU_SUBMENU;
set = xset_get( "root_bar" ); // in Preferences
set->b = XSET_B_TRUE;
// Plugins
set = xset_set( "plug_install", "label", _("_Install") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "plug_ifile plug_iurl" );
xset_set_set( set, "icon", "gtk-add" );
set->line = g_strdup( "#plugins-install" );
set = xset_set( "plug_ifile", "label", _("_File") );
xset_set_set( set, "icon", "gtk-file" );
set->line = g_strdup( "#plugins-install" );
set = xset_set( "plug_iurl", "label", _("_URL") );
xset_set_set( set, "icon", "gtk-network" );
set->line = g_strdup( "#plugins-install" );
set = xset_get( "sep_p1" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "plug_copy", "label", _("_Copy") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "plug_cfile plug_curl sep_p1 plug_cverb" );
xset_set_set( set, "icon", "gtk-copy" );
set->line = g_strdup( "#plugins-copy" );
set = xset_set( "plug_cfile", "label", _("_File") );
xset_set_set( set, "icon", "gtk-file" );
set->line = g_strdup( "#plugins-copy" );
set = xset_set( "plug_curl", "label", _("_URL") );
xset_set_set( set, "icon", "gtk-network" );
set->line = g_strdup( "#plugins-copy" );
set = xset_set( "plug_cverb", "label", _("_Verbose") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->line = g_strdup( "#plugins-copy" );
set = xset_set( "plug_browse", "label", _("_Browse") );
set = xset_set( "plug_inc", "label", _("In_cluded") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "icon", "gtk-media-play" );
// Help
set = xset_get( "sep_h1" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_h2" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_h3" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "main_help", "label", _("_User's Manual") );
xset_set_set( set, "icon", "gtk-help" );
set = xset_set( "main_faq", "label", _("_FAQ") );
xset_set_set( set, "icon", "gtk-help" );
set = xset_set( "main_homepage", "label", _("_Homepage") );
xset_set_set( set, "icon", "spacefm" );
set = xset_set( "main_news", "label", _("SpaceFM _News") );
xset_set_set( set, "icon", "spacefm" );
set = xset_set( "main_getplug", "label", _("_Get Plugins") );
xset_set_set( set, "icon", "spacefm" );
set = xset_set( "main_help_opt", "label", _("_Options") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "main_help_browser main_help_url" );
xset_set_set( set, "icon", "gtk-properties" );
set = xset_set( "main_help_browser", "label", _("_Browser") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Choose HTML Browser") );
xset_set_set( set, "desc", _("Enter browser name or bash command line to be used to display HTML files and URLs:\n\nUse:\n\t%%u\turl\n\n(Leave blank for automatic browser detection)") );
xset_set_set( set, "icon", "gtk-edit" );
set = xset_set( "main_help_url", "label", _("_Manual Location") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Choose User's Manual Location") );
xset_set_set( set, "desc", _("Enter local file path or remote URL for the SpaceFM User's Manual:\n\n(Leave blank for default)\n") );
xset_set_set( set, "icon", "gtk-edit" );
set = xset_set( "main_about", "label", _("_About") );
xset_set_set( set, "icon", "gtk-about" );
set = xset_set( "main_dev", "label", _("_Show") );
xset_set_set( set, "icon", "gtk-harddisk" );
set = xset_get( "main_dev_sep" );
set->menu_style = XSET_MENU_SEP;
// Tasks
set = xset_get( "sep_t1" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_t2" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_t3" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_t4" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_t5" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_t6" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "main_tasks", "label", _("_Tasks") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "task_show_manager task_hide_manager sep_t1 task_columns task_popups task_errors task_queue" );
set->line = g_strdup( "#tasks" );
set = xset_set( "task_col_status", "label", _("_Status") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup( "0" ); // column position
set->y = g_strdup( "130" ); // column width
set = xset_set( "task_col_count", "label", _("_Count") );
set->menu_style = XSET_MENU_CHECK;
set->x = g_strdup_printf( "%d", 1 );
set->line = g_strdup( "#tasks-menu-col" );
set = xset_set( "task_col_path", "label", _("_Folder") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 2 );
set->line = g_strdup( "#tasks-menu-col" );
set = xset_set( "task_col_file", "label", _("_Item") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 3 );
set->line = g_strdup( "#tasks-menu-col" );
set = xset_set( "task_col_to", "label", _("_To") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 4 );
set->line = g_strdup( "#tasks-menu-col" );
set = xset_set( "task_col_progress", "label", _("_Progress") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 5 );
set->y = g_strdup( "100" );
set->line = g_strdup( "#tasks-menu-col" );
set = xset_set( "task_col_total", "label", _("T_otal") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 6 );
set->y = g_strdup( "120" );
set->line = g_strdup( "#tasks-menu-col" );
set = xset_set( "task_col_started", "label", _("Sta_rted") );
set->menu_style = XSET_MENU_CHECK;
set->x = g_strdup_printf( "%d", 7 );
set->line = g_strdup( "#tasks-menu-col" );
set = xset_set( "task_col_elapsed", "label", _("_Elapsed") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 8 );
set->y = g_strdup( "70" );
set->line = g_strdup( "#tasks-menu-col" );
set = xset_set( "task_col_curspeed", "label", _("C_urrent Speed") );
set->menu_style = XSET_MENU_CHECK;
set->x = g_strdup_printf( "%d", 9 );
set->line = g_strdup( "#tasks-menu-col" );
set = xset_set( "task_col_curest", "label", _("Current Re_main") );
set->menu_style = XSET_MENU_CHECK;
set->x = g_strdup_printf( "%d", 10 );
set->line = g_strdup( "#tasks-menu-col" );
set = xset_set( "task_col_avgspeed", "label", _("_Average Speed") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 11 );
set->y = g_strdup( "60" );
set->line = g_strdup( "#tasks-menu-col" );
set = xset_set( "task_col_avgest", "label", _("A_verage Remain") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 12 );
set->y = g_strdup( "65" );
set->line = g_strdup( "#tasks-menu-col" );
set = xset_set( "task_col_reorder", "label", _("Reor_der") );
set->line = g_strdup( "#tasks-menu-col" );
set = xset_set( "task_stop", "label", _("_Stop") );
xset_set_set( set, "icon", "gtk-stop" );
set->line = g_strdup( "#tasks-menu-stop" );
set = xset_set( "task_pause", "label", _("Pa_use") );
xset_set_set( set, "icon", "gtk-media-pause" );
set->line = g_strdup( "#tasks-menu-pause" );
set = xset_set( "task_que", "label", _("_Queue") );
xset_set_set( set, "icon", "gtk-add" );
set->line = g_strdup( "#tasks-menu-queue" );
set = xset_set( "task_resume", "label", _("_Resume") );
xset_set_set( set, "icon", "gtk-media-play" );
set->line = g_strdup( "#tasks-menu-resume" );
set = xset_set( "task_showout", "label", _("Sho_w Output") );
set->line = g_strdup( "#tasks-menu-showout" );
set = xset_set( "task_all", "label", _("_All Tasks") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "task_stop_all task_pause_all task_que_all task_resume_all" );
set->line = g_strdup( "#tasks-menu-all" );
set = xset_set( "task_stop_all", "label", _("_Stop") );
xset_set_set( set, "icon", "gtk-stop" );
set->line = g_strdup( "#tasks-menu-all" );
set = xset_set( "task_pause_all", "label", _("Pa_use") );
xset_set_set( set, "icon", "gtk-media-pause" );
set->line = g_strdup( "#tasks-menu-all" );
set = xset_set( "task_que_all", "label", _("_Queue") );
xset_set_set( set, "icon", "gtk-add" );
set->line = g_strdup( "#tasks-menu-all" );
set = xset_set( "task_resume_all", "label", _("_Resume") );
xset_set_set( set, "icon", "gtk-media-play" );
set->line = g_strdup( "#tasks-menu-all" );
set = xset_set( "task_show_manager", "label", _("Show _Manager") );
set->menu_style = XSET_MENU_RADIO;
set->b = XSET_B_FALSE;
set->line = g_strdup( "#tasks-menu-show" );
set = xset_set( "task_hide_manager", "label", _("Auto-_Hide Manager") );
set->menu_style = XSET_MENU_RADIO;
set->b = XSET_B_TRUE;
set->line = g_strdup( "#tasks-menu-auto" );
set = xset_set( "font_task", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Task Manager Font") );
xset_set_set( set, "desc", _("copying File 1:15 65.2 M 30.2 M/s") );
set->line = g_strdup( "#tasks-menu-col" );
set = xset_set( "task_columns", "label", _("_Columns") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "task_col_count task_col_path task_col_file task_col_to task_col_progress task_col_total task_col_started task_col_elapsed task_col_curspeed task_col_curest task_col_avgspeed task_col_avgest sep_t2 task_col_reorder font_task" );
set->line = g_strdup( "#tasks-menu-col" );
set = xset_set( "task_popups", "label", _("_Popups") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "task_pop_all task_pop_top task_pop_above task_pop_stick sep_t6 task_pop_detail task_pop_over task_pop_err task_pop_font" );
set->line = g_strdup( "#tasks-menu-popall" );
set = xset_set( "task_pop_all", "label", _("Popup _All Tasks") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_FALSE;
set->line = g_strdup( "#tasks-menu-popall" );
set = xset_set( "task_pop_top", "label", _("Stay On _Top") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_FALSE;
set->line = g_strdup( "#tasks-menu-poptop" );
set = xset_set( "task_pop_above", "label", _("A_bove Others") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_FALSE;
set->line = g_strdup( "#tasks-menu-popabove" );
set = xset_set( "task_pop_stick", "label", _("All _Workspaces") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_FALSE;
set->line = g_strdup( "#tasks-menu-popstick" );
set = xset_set( "task_pop_detail", "label", _("_Detailed Stats") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_FALSE;
set->line = g_strdup( "#tasks-menu-popdet" );
set = xset_set( "task_pop_over", "label", _("_Overwrite Option") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->line = g_strdup( "#tasks-menu-popover" );
set = xset_set( "task_pop_err", "label", _("_Error Option") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->line = g_strdup( "#tasks-menu-poperropt" );
set = xset_set( "task_pop_font", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Task Popup Font (affects new tasks)") );
xset_set_set( set, "desc", _("Example Output 0123456789") );
set->line = g_strdup( "#tasks-menu-popfont" );
set = xset_set( "task_errors", "label", _("Err_ors") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "task_err_first task_err_any task_err_cont" );
set->line = g_strdup( "#tasks-menu-poperr" );
set = xset_set( "task_err_first", "label", _("Stop If _First") );
set->menu_style = XSET_MENU_RADIO;
set->b = XSET_B_TRUE;
set->line = g_strdup( "#tasks-menu-poperr" );
set = xset_set( "task_err_any", "label", _("Stop On _Any") );
set->menu_style = XSET_MENU_RADIO;
set->b = XSET_B_FALSE;
set->line = g_strdup( "#tasks-menu-poperr" );
set = xset_set( "task_err_cont", "label", _("_Continue") );
set->menu_style = XSET_MENU_RADIO;
set->b = XSET_B_FALSE;
set->line = g_strdup( "#tasks-menu-poperr" );
set = xset_set( "task_queue", "label", _("Qu_eue") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "task_q_new task_q_smart task_q_pause" );
set->line = g_strdup( "#tasks-menu-new" );
set = xset_set( "task_q_new", "label", _("_Queue New Tasks") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->line = g_strdup( "#tasks-menu-new" );
set = xset_set( "task_q_smart", "label", _("_Smart Queue") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->line = g_strdup( "#tasks-menu-smart" );
set = xset_set( "task_q_pause", "label", _("_Pause On Error") );
set->menu_style = XSET_MENU_CHECK;
set->line = g_strdup( "#tasks-menu-qpause" );
// Desktop
set = xset_get( "sep_desk1" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_desk2" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "desk_icons", "label", _("Arrange _Icons") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "icon", "gtk-sort-ascending" );
xset_set_set( set, "desc", "desk_sort_name desk_sort_type desk_sort_date desk_sort_size sep_desk1 desk_sort_ascend desk_sort_descend" );
set = xset_set( "desk_sort_name", "label", _("By _Name") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "desk_sort_type", "label", _("By _Type") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "desk_sort_date", "label", _("By _Date") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "desk_sort_size", "label", _("By _Size") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "desk_sort_ascend", "label", _("_Ascending") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "desk_sort_descend", "label", _("D_escending") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "desk_pref", "label", _("Desktop _Settings") );
xset_set_set( set, "icon", "gtk-preferences" );
set = xset_set( "desk_dev", "label", _("De_vices") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "icon", "gtk-harddisk" );
set = xset_set( "desk_book", "label", _("_Bookmarks") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "icon", "gtk-jump-to" );
// PANELS COMMON
set = xset_get( "sep_new" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_edit" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_tab" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_entry" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_mopt1" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_mopt2" );
set->menu_style = XSET_MENU_SEP;
xset_set( "date_format", "s", "%Y-%m-%d %H:%M" );
set = xset_set( "input_font", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Input Font") );
xset_set_set( set, "desc", _("Example Input 0123456789") );
set = xset_set( "con_open", "label", _("_Open") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "icon", "gtk-open" );
set = xset_set( "open_execute", "label", _("E_xecute") );
xset_set_set( set, "icon", "gtk-execute" );
set = xset_set( "open_edit", "label", _("Edi_t") );
xset_set_set( set, "icon", "gtk-edit" );
set = xset_set( "open_edit_root", "label", _("Edit As _Root") );
xset_set_set( set, "icon", "gtk-dialog-warning" );
set = xset_set( "open_other", "label", _("_Choose...") );
xset_set_set( set, "icon", "gtk-open" );
set = xset_set( "open_all", "label", _("_Default") );//virtual
set = xset_set( "open_in_tab", "label", _("In _Tab") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "opentab_new opentab_prev opentab_next opentab_1 opentab_2 opentab_3 opentab_4 opentab_5 opentab_6 opentab_7 opentab_8 opentab_9 opentab_10" );
xset_set( "opentab_new", "label", _("N_ew") );
xset_set( "opentab_prev", "label", _("_Prev") );
xset_set( "opentab_next", "label", _("_Next") );
xset_set( "opentab_1", "label", _("Tab _1") );
xset_set( "opentab_2", "label", _("Tab _2") );
xset_set( "opentab_3", "label", _("Tab _3") );
xset_set( "opentab_4", "label", _("Tab _4") );
xset_set( "opentab_5", "label", _("Tab _5") );
xset_set( "opentab_6", "label", _("Tab _6") );
xset_set( "opentab_7", "label", _("Tab _7") );
xset_set( "opentab_8", "label", _("Tab _8") );
xset_set( "opentab_9", "label", _("Tab _9") );
xset_set( "opentab_10", "label", _("Tab 1_0") );
set = xset_set( "open_in_panel", "label", _("In _Panel") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "open_in_panelprev open_in_panelnext open_in_panel1 open_in_panel2 open_in_panel3 open_in_panel4" );
xset_set( "open_in_panelprev", "label", _("_Prev") );
xset_set( "open_in_panelnext", "label", _("_Next") );
xset_set( "open_in_panel1", "label", _("Panel _1") );
xset_set( "open_in_panel2", "label", _("Panel _2") );
xset_set( "open_in_panel3", "label", _("Panel _3") );
xset_set( "open_in_panel4", "label", _("Panel _4") );
set = xset_set( "arc_extract", "label", _("_Extract") );
xset_set_set( set, "icon", "gtk-convert" );
set = xset_set( "arc_extractto", "label", _("Extract _To") );
xset_set_set( set, "icon", "gtk-convert" );
set = xset_set( "arc_list", "label", _("_List Contents") );
xset_set_set( set, "icon", "gtk-file" );
set = xset_get( "sep_arc1" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "arc_default", "label", _("_Archive Default") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "arc_def_open arc_def_ex arc_def_exto arc_def_list sep_arc1 arc_def_parent arc_def_write" );
set = xset_set( "arc_def_open", "label", _("_Open With App") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "arc_def_ex", "label", _("_Extract") );
set->menu_style = XSET_MENU_RADIO;
set->b = XSET_B_TRUE;
set = xset_set( "arc_def_exto", "label", _("Extract _To") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "arc_def_list", "label", _("_List Contents") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "arc_def_parent", "label", _("_Create Subfolder") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set = xset_set( "arc_def_write", "label", _("_Write Access") );
set->menu_style = XSET_MENU_CHECK;
set = xset_set( "iso_mount", "label", _("_Mount ISO") );
xset_set_set( set, "icon", "gtk-cdrom" );
set = xset_set( "iso_auto", "label", _("_Auto-Mount ISO") );
set->menu_style = XSET_MENU_CHECK;
set = xset_get( "sep_o1" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "open_new", "label", _("_New") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "new_file new_folder new_link new_archive sep_o1 tab_new tab_new_here new_bookmark" );
xset_set_set( set, "icon", "gtk-new" );
set = xset_set( "new_file", "label", _("_File") );
xset_set_set( set, "icon", "gtk-file" );
set = xset_set( "new_folder", "label", _("Fol_der") );
xset_set_set( set, "icon", "gtk-directory" );
set = xset_set( "new_link", "label", _("_Link") );
xset_set_set( set, "icon", "gtk-file" );
set = xset_set( "new_bookmark", "label", C_("New|", "_Bookmark") );
xset_set_set( set, "shared_key", "book_new" );
xset_set_set( set, "icon", "gtk-jump-to" );
set = xset_set( "new_archive", "label", _("_Archive") );
xset_set_set( set, "icon", "gtk-save-as" );
set = xset_get( "arc_dlg" );
set->b = XSET_B_TRUE;
xset_set_set( set, "s", "1" );
set = xset_set( "tab_new", "label", C_("New|", "_Tab") );
xset_set_set( set, "icon", "gtk-add" );
set = xset_set( "tab_new_here", "label", _("Tab _Here") );
xset_set_set( set, "icon", "gtk-add" );
set = xset_set( "new_app", "label", _("_Desktop Application") );
xset_set_set( set, "icon", "gtk-add" );
set = xset_get( "sep_g1" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "con_go", "label", _("_Go") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "go_back go_forward go_up go_home go_default go_set_default edit_canon sep_g1 go_tab go_focus" );
xset_set_set( set, "icon", "gtk-go-forward" );
set = xset_set( "go_back", "label", _("_Back") );
xset_set_set( set, "icon", "gtk-go-back" );
set = xset_set( "go_forward", "label", _("_Forward") );
xset_set_set( set, "icon", "gtk-go-forward" );
set = xset_set( "go_up", "label", _("_Up") );
xset_set_set( set, "icon", "gtk-go-up" );
set = xset_set( "go_home", "label", _("_Home") );
xset_set_set( set, "icon", "gtk-home" );
set = xset_set( "go_default", "label", _("_Default") );
xset_set_set( set, "icon", "gtk-home" );
set = xset_set( "go_set_default", "label", _("_Set Default") );
xset_set_set( set, "icon", "gtk-save" );
set = xset_set( "edit_canon", "label", _("Re_al Path") );
set = xset_set( "go_focus", "label", _("Fo_cus") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "focus_path_bar focus_filelist focus_dirtree focus_book focus_device" );
set = xset_set( "focus_path_bar", "label", _("_Path Bar") );
xset_set_set( set, "icon", "gtk-dialog-question" );
set = xset_set( "focus_filelist", "label", _("_File List") );
xset_set_set( set, "icon", "gtk-file" );
set = xset_set( "focus_dirtree", "label", _("_Tree") );
xset_set_set( set, "icon", "gtk-directory" );
set = xset_set( "focus_book", "label", _("_Bookmarks") );
xset_set_set( set, "icon", "gtk-jump-to" );
set = xset_set( "focus_device", "label", _("De_vices") );
xset_set_set( set, "icon", "gtk-harddisk" );
set = xset_set( "go_tab", "label", C_("Go|", "_Tab") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "tab_prev tab_next tab_close tab_1 tab_2 tab_3 tab_4 tab_5 tab_6 tab_7 tab_8 tab_9 tab_10" );
xset_set( "tab_prev", "label", _("_Prev") );
xset_set( "tab_next", "label", _("_Next") );
set = xset_set( "tab_close", "label", _("_Close") );
xset_set_set( set, "icon", "gtk-close" );
xset_set( "tab_1", "label", _("Tab _1") );
xset_set( "tab_2", "label", _("Tab _2") );
xset_set( "tab_3", "label", _("Tab _3") );
xset_set( "tab_4", "label", _("Tab _4") );
xset_set( "tab_5", "label", _("Tab _5") );
xset_set( "tab_6", "label", _("Tab _6") );
xset_set( "tab_7", "label", _("Tab _7") );
xset_set( "tab_8", "label", _("Tab _8") );
xset_set( "tab_9", "label", _("Tab _9") );
xset_set( "tab_10", "label", _("Tab 1_0") );
set = xset_set( "con_view", "label", _("_View") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "icon", "gtk-preferences" );
set = xset_set( "view_list_style", "label", _("Styl_e") );
set->menu_style = XSET_MENU_SUBMENU;
set = xset_set( "view_columns", "label", _("C_olumns") );
set->menu_style = XSET_MENU_SUBMENU;
set = xset_set( "view_reorder_col", "label", _("_Reorder") );
set = xset_set( "rubberband", "label", _("_Rubberband Select") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set = xset_get( "sep_s1" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_s2" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_s3" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_s4" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "view_sortby", "label", _("_Sort") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "sortby_name sortby_size sortby_type sortby_perm sortby_owner sortby_date sep_s1 sortby_ascend sortby_descend sep_s2 sortx_natural sortx_case sep_s3 sortx_folders sortx_files sortx_mix sep_s4 sortx_hidfirst sortx_hidlast" );
set = xset_set( "sortby_name", "label", _("_Name") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "sortby_size", "label", _("_Size") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "sortby_type", "label", _("_Type") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "sortby_perm", "label", _("_Permission") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "sortby_owner", "label", _("_Owner") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "sortby_date", "label", _("_Modified") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "sortby_ascend", "label", _("_Ascending") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "sortby_descend", "label", _("_Descending") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "sortx_natural", "label", _("Nat_ural") );
set->menu_style = XSET_MENU_CHECK;
set = xset_set( "sortx_case", "label", _("_Case Sensitive") );
set->menu_style = XSET_MENU_CHECK;
set = xset_set( "sortx_folders", "label", _("Folders Fi_rst") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "sortx_files", "label", _("F_iles First") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "sortx_mix", "label", _("Mi_xed") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "sortx_hidfirst", "label", _("_Hidden First") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "sortx_hidlast", "label", _("Hidden _Last") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "view_refresh", "label", _("Re_fresh") );
xset_set_set( set, "icon", "gtk-refresh" );
set = xset_set( "path_seek", "label", _("Auto See_k") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->line = g_strdup( "#gui-pathbar-seek" );
set = xset_set( "path_hand", "label", _("P_rotocol Handler...") );
set->menu_style = XSET_MENU_STRING;
xset_set_set( set, "title", _("Set Protocol Handler") );
xset_set_set( set, "desc", _("Enter command to be used to mount or open protocols (such as nfs://, smb://, etc):\n\nIf this setting is empty, SpaceFM will open protocols using 'udevil mount'.\n\nTIP: To unmount networks, install udevil or set Unmount Command to a command which handles network protocols.\n") );
xset_set_set( set, "icon", "gtk-execute" );
set->line = g_strdup( "#gui-pathbar-protohand" );
set = xset_set( "path_help", "label", _("Path Bar _Help") );
xset_set_set( set, "icon", "gtk-help" );
// EDIT
set = xset_set( "edit_cut", "label", _("Cu_t") );
xset_set_set( set, "icon", "gtk-cut" );
set = xset_set( "edit_copy", "label", _("_Copy") );
xset_set_set( set, "icon", "gtk-copy" );
set = xset_set( "edit_paste", "label", _("_Paste") );
xset_set_set( set, "icon", "gtk-paste" );
set = xset_set( "edit_rename", "label", _("_Rename") );
xset_set_set( set, "icon", "gtk-edit" );
set = xset_set( "edit_delete", "label", _("_Delete") );
xset_set_set( set, "icon", "gtk-delete" );
set = xset_get( "sep_e1" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_e2" );
set->menu_style = XSET_MENU_SEP;
set = xset_get( "sep_e3" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "edit_submenu", "label", _("_Edit") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "copy_name copy_parent copy_path sep_e1 paste_link paste_target paste_as sep_e2 copy_to move_to edit_root edit_hide sep_e3 select_all select_patt select_invert select_un" );
xset_set_set( set, "icon", "gtk-edit" );
set = xset_set( "copy_name", "label", _("Copy _Name") );
xset_set_set( set, "icon", "gtk-copy" );
set = xset_set( "copy_path", "label", _("Copy _Path") );
xset_set_set( set, "icon", "gtk-copy" );
set = xset_set( "copy_parent", "label", _("Copy Pa_rent") );
xset_set_set( set, "icon", "gtk-copy" );
set = xset_set( "paste_link", "label", _("Paste _Link") );
xset_set_set( set, "icon", "gtk-paste" );
set = xset_set( "paste_target", "label", _("Paste _Target") );
xset_set_set( set, "icon", "gtk-paste" );
set = xset_set( "paste_as", "label", _("Paste _As") );
xset_set_set( set, "icon", "gtk-paste" );
set = xset_get( "sep_c1" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "copy_to", "label", _("_Copy To") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "copy_loc copy_loc_last sep_c1 copy_tab copy_panel" );
set = xset_set( "copy_loc", "label", _("L_ocation") );
set = xset_set( "copy_loc_last", "label", _("L_ast Location") );
xset_set_set( set, "icon", "gtk-redo" );
set = xset_set( "copy_tab", "label", C_("Edit|CopyTo|", "_Tab") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "copy_tab_prev copy_tab_next copy_tab_1 copy_tab_2 copy_tab_3 copy_tab_4 copy_tab_5 copy_tab_6 copy_tab_7 copy_tab_8 copy_tab_9 copy_tab_10" );
xset_set( "copy_tab_prev", "label", _("_Prev") );
xset_set( "copy_tab_next", "label", _("_Next") );
xset_set( "copy_tab_1", "label", _("Tab _1") );
xset_set( "copy_tab_2", "label", _("Tab _2") );
xset_set( "copy_tab_3", "label", _("Tab _3") );
xset_set( "copy_tab_4", "label", _("Tab _4") );
xset_set( "copy_tab_5", "label", _("Tab _5") );
xset_set( "copy_tab_6", "label", _("Tab _6") );
xset_set( "copy_tab_7", "label", _("Tab _7") );
xset_set( "copy_tab_8", "label", _("Tab _8") );
xset_set( "copy_tab_9", "label", _("Tab _9") );
xset_set( "copy_tab_10", "label", _("Tab 1_0") );
set = xset_set( "copy_panel", "label", C_("Edit|CopyTo|", "_Panel") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "copy_panel_prev copy_panel_next copy_panel_1 copy_panel_2 copy_panel_3 copy_panel_4" );
xset_set( "copy_panel_prev", "label", _("_Prev") );
xset_set( "copy_panel_next", "label", _("_Next") );
xset_set( "copy_panel_1", "label", _("Panel _1") );
xset_set( "copy_panel_2", "label", _("Panel _2") );
xset_set( "copy_panel_3", "label", _("Panel _3") );
xset_set( "copy_panel_4", "label", _("Panel _4") );
set = xset_get( "sep_c2" );
set->menu_style = XSET_MENU_SEP;
set = xset_set( "move_to", "label", _("_Move To") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "move_loc move_loc_last sep_c2 move_tab move_panel" );
set = xset_set( "move_loc", "label", _("_Location") );
set = xset_set( "move_loc_last", "label", _("L_ast Location") );
xset_set_set( set, "icon", "gtk-redo" );
set = xset_set( "move_tab", "label", C_("Edit|MoveTo|", "_Tab") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "move_tab_prev move_tab_next move_tab_1 move_tab_2 move_tab_3 move_tab_4 move_tab_5 move_tab_6 move_tab_7 move_tab_8 move_tab_9 move_tab_10" );
xset_set( "move_tab_prev", "label", _("_Prev") );
xset_set( "move_tab_next", "label", _("_Next") );
xset_set( "move_tab_1", "label", _("Tab _1") );
xset_set( "move_tab_2", "label", _("Tab _2") );
xset_set( "move_tab_3", "label", _("Tab _3") );
xset_set( "move_tab_4", "label", _("Tab _4") );
xset_set( "move_tab_5", "label", _("Tab _5") );
xset_set( "move_tab_6", "label", _("Tab _6") );
xset_set( "move_tab_7", "label", _("Tab _7") );
xset_set( "move_tab_8", "label", _("Tab _8") );
xset_set( "move_tab_9", "label", _("Tab _9") );
xset_set( "move_tab_10", "label", _("Tab 1_0") );
set = xset_set( "move_panel", "label", C_("Edit|MoveTo|", "_Panel") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "move_panel_prev move_panel_next move_panel_1 move_panel_2 move_panel_3 move_panel_4" );
xset_set( "move_panel_prev", "label", _("_Prev") );
xset_set( "move_panel_next", "label", _("_Next") );
xset_set( "move_panel_1", "label", _("Panel _1") );
xset_set( "move_panel_2", "label", _("Panel _2") );
xset_set( "move_panel_3", "label", _("Panel _3") );
xset_set( "move_panel_4", "label", _("Panel _4") );
set = xset_set( "edit_hide", "label", _("_Hide") );
set = xset_set( "select_all", "label", _("_Select All") );
xset_set_set( set, "icon", "gtk-select-all" );
set = xset_set( "select_un", "label", _("_Unselect All") );
set = xset_set( "select_invert", "label", _("_Invert Selection") );
set = xset_set( "select_patt", "label", _("S_elect By Pattern") );
set = xset_set( "edit_root", "label", _("R_oot") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "root_copy_loc root_move2 root_delete" );
xset_set_set( set, "icon", "gtk-dialog-warning" );
set = xset_set( "root_copy_loc", "label", _("_Copy To") );
set = xset_set( "root_move2", "label", _("Move _To") );
set = xset_set( "root_delete", "label", _("_Delete") );
xset_set_set( set, "icon", "gtk-delete" );
// Properties
set = xset_set( "con_prop", "label", _("Propert_ies") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "" );
xset_set_set( set, "icon", "gtk-properties" );
set = xset_set( "prop_info", "label", _("_Info") );
xset_set_set( set, "icon", "gtk-dialog-info" );
set = xset_set( "prop_perm", "label", _("_Permissions") );
xset_set_set( set, "icon", "GTK_STOCK_DIALOG_AUTHENTICATION" );
set = xset_set( "prop_quick", "label", _("_Quick") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "perm_r perm_rw perm_rwx perm_r_r perm_rw_r perm_rw_rw perm_rwxr_x perm_rwxrwx perm_r_r_r perm_rw_r_r perm_rw_rw_rw perm_rwxr_r perm_rwxr_xr_x perm_rwxrwxrwx perm_rwxrwxrwt perm_unstick perm_stick perm_recurs" );
xset_set( "perm_r", "label", "r--------" );
xset_set( "perm_rw", "label", "rw-------" );
xset_set( "perm_rwx", "label", "rwx------" );
xset_set( "perm_r_r", "label", "r--r-----" );
xset_set( "perm_rw_r", "label", "rw-r-----" );
xset_set( "perm_rw_rw", "label", "rw-rw----" );
xset_set( "perm_rwxr_x", "label", "rwxr-x---" );
xset_set( "perm_rwxrwx", "label", "rwxrwx---" );
xset_set( "perm_r_r_r", "label", "r--r--r--" );
xset_set( "perm_rw_r_r", "label", "rw-r--r--" );
xset_set( "perm_rw_rw_rw", "label", "rw-rw-rw-" );
xset_set( "perm_rwxr_r", "label", "rwxr--r--" );
xset_set( "perm_rwxr_xr_x", "label", "rwxr-xr-x" );
xset_set( "perm_rwxrwxrwx", "label", "rwxrwxrwx" );
xset_set( "perm_rwxrwxrwt", "label", "rwxrwxrwt" );
xset_set( "perm_unstick", "label", "-t" );
xset_set( "perm_stick", "label", "+t" );
set = xset_set( "perm_recurs", "label", _("_Recursive") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "perm_go_w perm_go_rwx perm_ugo_w perm_ugo_rx perm_ugo_rwx" );
xset_set( "perm_go_w", "label", "go-w" );
xset_set( "perm_go_rwx", "label", "go-rwx" );
xset_set( "perm_ugo_w", "label", "ugo+w" );
xset_set( "perm_ugo_rx", "label", "ugo+rX" );
xset_set( "perm_ugo_rwx", "label", "ugo+rwX" );
set = xset_set( "prop_root", "label", _("_Root") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "rperm_rw rperm_rwx rperm_rw_r rperm_rw_rw rperm_rwxr_x rperm_rwxrwx rperm_rw_r_r rperm_rw_rw_rw rperm_rwxr_r rperm_rwxr_xr_x rperm_rwxrwxrwx rperm_rwxrwxrwt rperm_unstick rperm_stick rperm_recurs rperm_own" );
xset_set_set( set, "icon", "gtk-dialog-warning" );
xset_set( "rperm_rw", "label", "rw-------" );
xset_set( "rperm_rwx", "label", "rwx------" );
xset_set( "rperm_rw_r", "label", "rw-r-----" );
xset_set( "rperm_rw_rw", "label", "rw-rw----" );
xset_set( "rperm_rwxr_x", "label", "rwxr-x---" );
xset_set( "rperm_rwxrwx", "label", "rwxrwx---" );
xset_set( "rperm_rw_r_r", "label", "rw-r--r--" );
xset_set( "rperm_rw_rw_rw", "label", "rw-rw-rw-" );
xset_set( "rperm_rwxr_r", "label", "rwxr--r--" );
xset_set( "rperm_rwxr_xr_x", "label", "rwxr-xr-x" );
xset_set( "rperm_rwxrwxrwx", "label", "rwxrwxrwx" );
xset_set( "rperm_rwxrwxrwt", "label", "rwxrwxrwt" );
xset_set( "rperm_unstick", "label", "-t" );
xset_set( "rperm_stick", "label", "+t" );
set = xset_set( "rperm_recurs", "label", _("_Recursive") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "rperm_go_w rperm_go_rwx rperm_ugo_w rperm_ugo_rx rperm_ugo_rwx" );
xset_set( "rperm_go_w", "label", "go-w" );
xset_set( "rperm_go_rwx", "label", "go-rwx" );
xset_set( "rperm_ugo_w", "label", "ugo+w" );
xset_set( "rperm_ugo_rx", "label", "ugo+rX" );
xset_set( "rperm_ugo_rwx", "label", "ugo+rwX" );
set = xset_set( "rperm_own", "label", _("_Owner") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "own_myuser own_myuser_users own_user1 own_user1_users own_user2 own_user2_users own_root own_root_users own_root_myuser own_root_user1 own_root_user2 own_recurs" );
xset_set( "own_myuser", "label", "myuser" );
xset_set( "own_myuser_users", "label", "myuser:users" );
xset_set( "own_user1", "label", "user1" );
xset_set( "own_user1_users", "label", "user1:users" );
xset_set( "own_user2", "label", "user2" );
xset_set( "own_user2_users", "label", "user2:users" );
xset_set( "own_root", "label", "root" );
xset_set( "own_root_users", "label", "root:users" );
xset_set( "own_root_myuser", "label", "root:myuser" );
xset_set( "own_root_user1", "label", "root:user1" );
xset_set( "own_root_user2", "label", "root:user2" );
set = xset_set( "own_recurs", "label", _("_Recursive") );
set->menu_style = XSET_MENU_SUBMENU;
xset_set_set( set, "desc", "rown_myuser rown_myuser_users rown_user1 rown_user1_users rown_user2 rown_user2_users rown_root rown_root_users rown_root_myuser rown_root_user1 rown_root_user2" );
xset_set( "rown_myuser", "label", "myuser" );
xset_set( "rown_myuser_users", "label", "myuser:users" );
xset_set( "rown_user1", "label", "user1" );
xset_set( "rown_user1_users", "label", "user1:users" );
xset_set( "rown_user2", "label", "user2" );
xset_set( "rown_user2_users", "label", "user2:users" );
xset_set( "rown_root", "label", "root" );
xset_set( "rown_root_users", "label", "root:users" );
xset_set( "rown_root_myuser", "label", "root:myuser" );
xset_set( "rown_root_user1", "label", "root:user1" );
xset_set( "rown_root_user2", "label", "root:user2" );
// PANEL ONE
set = xset_set( "panel1_show_toolbox", "label", _("_Toolbar") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set = xset_set( "panel1_show_devmon", "label", _("_Devices") );
set->menu_style = XSET_MENU_CHECK;
set = xset_set( "panel1_show_dirtree", "label", _("T_ree") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set = xset_set( "panel1_show_book", "label", _("_Bookmarks") );
set->menu_style = XSET_MENU_CHECK;
set = xset_set( "panel1_show_sidebar", "label", _("_Side Toolbar") );
set->menu_style = XSET_MENU_CHECK;
set = xset_set( "panel1_list_detailed", "label", _("_Detailed") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "panel1_list_icons", "label", _("_Icons") );
set->menu_style = XSET_MENU_RADIO;
set = xset_set( "panel1_list_compact", "label", _("_Compact") );
set->menu_style = XSET_MENU_RADIO;
set->b = XSET_B_TRUE;
set = xset_set( "panel1_show_hidden", "label", _("_Hidden Files") );
set->menu_style = XSET_MENU_CHECK;
set = xset_set( "panel1_font_file", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("File List Font (Panel 1)") );
xset_set_set( set, "desc", _("Example 1.1 M file -rwxr--r-- user:group 2011-01-01 01:11") );
set = xset_set( "panel1_font_dev", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Devices Font (Panel 1)") );
xset_set_set( set, "desc", _("sr0 [no media] :EXAMPLE") );
set->line = g_strdup( "#devices-settings-font" );
set = xset_set( "panel1_font_book", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Bookmarks Font (Panel 1)") );
xset_set_set( set, "desc", _("Example Bookmark Name") );
set = xset_set( "panel1_font_path", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Path Bar Font (Panel 1)") );
xset_set_set( set, "desc", _("$ cat /home/user/example") );
set->line = g_strdup( "#gui-pathbar-font" );
set = xset_set( "panel1_font_tab", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Tab Font (Panel 1)") );
xset_set_set( set, "desc", "/usr/bin" );
set = xset_set( "panel1_icon_tab", "label", _("_Icon") );
set->menu_style = XSET_MENU_ICON;
xset_set_set( set, "icon", "gtk-directory" );
set = xset_set( "panel1_font_status", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Status Bar Font (Panel 1)") );
xset_set_set( set, "desc", _("12 G free / 200 G 52 items") );
set = xset_set( "panel1_icon_status", "label", _("_Icon") );
set->menu_style = XSET_MENU_ICON;
xset_set_set( set, "icon", "gtk-yes" );
set = xset_set( "panel1_detcol_name", "label", _("_Name") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE; // visible
set->x = g_strdup_printf( "%d", 0 ); // position
set = xset_set( "panel1_detcol_size", "label", _("_Size") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 1 );
set = xset_set( "panel1_detcol_type", "label", _("_Type") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 2 );
set = xset_set( "panel1_detcol_perm", "label", _("_Permission") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 3 );
set = xset_set( "panel1_detcol_owner", "label", _("_Owner") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 4 );
set = xset_set( "panel1_detcol_date", "label", _("_Modified") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 5 );
set = xset_get( "panel1_sort_extra" );
set->b = XSET_B_TRUE; //sort_natural
set->x = g_strdup_printf( "%d", XSET_B_FALSE ); // sort_case
set->y = g_strdup( "1" ); //PTK_LIST_SORT_DIR_FIRST from ptk-file-list.h
set->z = g_strdup_printf( "%d", XSET_B_TRUE ); // sort_hidden_first
// PANEL TWO
set = xset_set( "panel2_show_toolbox", "label", _("_Toolbar") );
set->menu_style = XSET_MENU_CHECK;
xset_set_set( set, "shared_key", "panel1_show_toolbox" );
set->b = XSET_B_TRUE;
set = xset_set( "panel2_show_devmon", "label", _("_Devices") );
set->menu_style = XSET_MENU_CHECK;
xset_set_set( set, "shared_key", "panel1_show_devmon" );
set = xset_set( "panel2_show_dirtree", "label", _("T_ree") );
set->menu_style = XSET_MENU_CHECK;
xset_set_set( set, "shared_key", "panel1_show_dirtree" );
set = xset_set( "panel2_show_book", "label", _("_Bookmarks") );
set->menu_style = XSET_MENU_CHECK;
xset_set_set( set, "shared_key", "panel1_show_book" );
set = xset_set( "panel2_show_sidebar", "label", _("_Side Toolbar") );
set->menu_style = XSET_MENU_CHECK;
xset_set_set( set, "shared_key", "panel1_show_sidebar" );
set = xset_set( "panel2_list_detailed", "label", _("_Detailed") );
set->menu_style = XSET_MENU_RADIO;
xset_set_set( set, "shared_key", "panel1_list_detailed" );
set = xset_set( "panel2_list_icons", "label", _("_Icons") );
set->menu_style = XSET_MENU_RADIO;
xset_set_set( set, "shared_key", "panel1_list_icons" );
set = xset_set( "panel2_list_compact", "label", _("_Compact") );
set->menu_style = XSET_MENU_RADIO;
xset_set_set( set, "shared_key", "panel1_list_compact" );
set->b = XSET_B_TRUE;
set = xset_set( "panel2_show_hidden", "label", _("_Hidden Files") );
set->menu_style = XSET_MENU_CHECK;
xset_set_set( set, "shared_key", "panel1_show_hidden" );
set = xset_set( "panel2_font_file", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("File List Font (Panel 2)") );
xset_set_set( set, "desc", _("Example 2.2 M file -rwxr--r-- user:group 2011-02-02 02:22") );
set = xset_set( "panel2_font_dev", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Devices Font (Panel 2)") );
xset_set_set( set, "desc", _("sr0 [no media] :EXAMPLE") );
set->line = g_strdup( "#devices-settings-font" );
set = xset_set( "panel2_font_book", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Bookmarks Font (Panel 2)") );
xset_set_set( set, "desc", _("Example Bookmark Name") );
set = xset_set( "panel2_font_path", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Path Bar Font (Panel 2)") );
xset_set_set( set, "desc", _("$ cat /home/user/example") );
set->line = g_strdup( "#gui-pathbar-font" );
set = xset_set( "panel2_font_tab", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Tab Font (Panel 2)") );
xset_set_set( set, "desc", "/usr/bin" );
set = xset_set( "panel2_icon_tab", "label", _("_Icon") );
set->menu_style = XSET_MENU_ICON;
xset_set_set( set, "icon", "gtk-directory" );
set = xset_set( "panel2_font_status", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Status Bar Font (Panel 2)") );
xset_set_set( set, "desc", _("12 G free / 200 G 52 items") );
xset_set_set( set, "shared_key", "panel1_font_status" );
set = xset_set( "panel2_icon_status", "label", _("_Icon") );
set->menu_style = XSET_MENU_ICON;
xset_set_set( set, "icon", "gtk-yes" );
xset_set_set( set, "shared_key", "panel1_icon_status" );
set = xset_set( "panel2_detcol_name", "label", _("_Name") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE; // visible
set->x = g_strdup_printf( "%d", 0 ); // position
set = xset_set( "panel2_detcol_size", "label", _("_Size") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 1 );
xset_set_set( set, "shared_key", "panel1_detcol_size" );
set = xset_set( "panel2_detcol_type", "label", _("_Type") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 2 );
xset_set_set( set, "shared_key", "panel1_detcol_type" );
set = xset_set( "panel2_detcol_perm", "label", _("_Permission") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 3 );
xset_set_set( set, "shared_key", "panel1_detcol_perm" );
set = xset_set( "panel2_detcol_owner", "label", _("_Owner") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 4 );
xset_set_set( set, "shared_key", "panel1_detcol_owner" );
set = xset_set( "panel2_detcol_date", "label", _("_Modified") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 5 );
xset_set_set( set, "shared_key", "panel1_detcol_date" );
set = xset_get( "panel2_sort_extra" );
set->b = XSET_B_TRUE; //sort_natural
set->x = g_strdup_printf( "%d", XSET_B_FALSE ); // sort_case
set->y = g_strdup( "1" ); //PTK_LIST_SORT_DIR_FIRST from ptk-file-list.h
set->z = g_strdup_printf( "%d", XSET_B_TRUE ); // sort_hidden_first
// PANEL THREE
set = xset_set( "panel3_show_toolbox", "label", _("_Toolbar") );
set->menu_style = XSET_MENU_CHECK;
xset_set_set( set, "shared_key", "panel1_show_toolbox" );
set->b = XSET_B_TRUE;
set = xset_set( "panel3_show_devmon", "label", _("_Devices") );
set->menu_style = XSET_MENU_CHECK;
xset_set_set( set, "shared_key", "panel1_show_devmon" );
set = xset_set( "panel3_show_dirtree", "label", _("T_ree") );
set->menu_style = XSET_MENU_CHECK;
xset_set_set( set, "shared_key", "panel1_show_dirtree" );
set = xset_set( "panel3_show_book", "label", _("_Bookmarks") );
set->menu_style = XSET_MENU_CHECK;
xset_set_set( set, "shared_key", "panel1_show_book" );
set = xset_set( "panel3_show_sidebar", "label", _("_Side Toolbar") );
set->menu_style = XSET_MENU_CHECK;
xset_set_set( set, "shared_key", "panel1_show_sidebar" );
set = xset_set( "panel3_list_detailed", "label", _("_Detailed") );
set->menu_style = XSET_MENU_RADIO;
xset_set_set( set, "shared_key", "panel1_list_detailed" );
set = xset_set( "panel3_list_icons", "label", _("_Icons") );
set->menu_style = XSET_MENU_RADIO;
xset_set_set( set, "shared_key", "panel1_list_icons" );
set = xset_set( "panel3_list_compact", "label", _("_Compact") );
set->menu_style = XSET_MENU_RADIO;
xset_set_set( set, "shared_key", "panel1_list_compact" );
set->b = XSET_B_TRUE;
set = xset_set( "panel3_show_hidden", "label", _("_Hidden Files") );
set->menu_style = XSET_MENU_CHECK;
xset_set_set( set, "shared_key", "panel1_show_hidden" );
set = xset_set( "panel3_font_file", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("File List Font (Panel 3)") );
xset_set_set( set, "desc", _("Example 3.3 M file -rwxr--r-- user:group 2011-03-03 03:33") );
set = xset_set( "panel3_font_dev", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Devices Font (Panel 3)") );
xset_set_set( set, "desc", _("sr0 [no media] :EXAMPLE") );
set->line = g_strdup( "#devices-settings-font" );
set = xset_set( "panel3_font_book", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Bookmarks Font (Panel 3)") );
xset_set_set( set, "desc", _("Example Bookmark Name") );
set = xset_set( "panel3_font_path", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Path Bar Font (Panel 3)") );
xset_set_set( set, "desc", _("$ cat /home/user/example") );
set->line = g_strdup( "#gui-pathbar-font" );
set = xset_set( "panel3_font_tab", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Tab Font (Panel 3)") );
xset_set_set( set, "desc", "/usr/bin" );
set = xset_set( "panel3_icon_tab", "label", _("_Icon") );
set->menu_style = XSET_MENU_ICON;
xset_set_set( set, "icon", "gtk-directory" );
set = xset_set( "panel3_font_status", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Status Bar Font (Panel 3)") );
xset_set_set( set, "desc", _("12 G free / 200 G 52 items") );
xset_set_set( set, "shared_key", "panel1_font_status" );
set = xset_set( "panel3_icon_status", "label", _("_Icon") );
set->menu_style = XSET_MENU_ICON;
xset_set_set( set, "icon", "gtk-yes" );
xset_set_set( set, "shared_key", "panel1_icon_status" );
set = xset_set( "panel3_detcol_name", "label", _("_Name") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE; // visible
set->x = g_strdup_printf( "%d", 0 ); // position
set = xset_set( "panel3_detcol_size", "label", _("_Size") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 1 );
xset_set_set( set, "shared_key", "panel1_detcol_size" );
set = xset_set( "panel3_detcol_type", "label", _("_Type") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 2 );
xset_set_set( set, "shared_key", "panel1_detcol_type" );
set = xset_set( "panel3_detcol_perm", "label", _("_Permission") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 3 );
xset_set_set( set, "shared_key", "panel1_detcol_perm" );
set = xset_set( "panel3_detcol_owner", "label", _("_Owner") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 4 );
xset_set_set( set, "shared_key", "panel1_detcol_owner" );
set = xset_set( "panel3_detcol_date", "label", _("_Modified") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 5 );
xset_set_set( set, "shared_key", "panel1_detcol_date" );
set = xset_get( "panel3_sort_extra" );
set->b = XSET_B_TRUE; //sort_natural
set->x = g_strdup_printf( "%d", XSET_B_FALSE ); // sort_case
set->y = g_strdup( "1" ); //PTK_LIST_SORT_DIR_FIRST from ptk-file-list.h
set->z = g_strdup_printf( "%d", XSET_B_TRUE ); // sort_hidden_first
// PANEL FOUR
set = xset_set( "panel4_show_toolbox", "label", _("_Toolbar") );
set->menu_style = XSET_MENU_CHECK;
xset_set_set( set, "shared_key", "panel1_show_toolbox" );
set->b = XSET_B_TRUE;
set = xset_set( "panel4_show_devmon", "label", _("_Devices") );
set->menu_style = XSET_MENU_CHECK;
xset_set_set( set, "shared_key", "panel1_show_devmon" );
set = xset_set( "panel4_show_dirtree", "label", _("T_ree") );
set->menu_style = XSET_MENU_CHECK;
xset_set_set( set, "shared_key", "panel1_show_dirtree" );
set = xset_set( "panel4_show_book", "label", _("_Bookmarks") );
set->menu_style = XSET_MENU_CHECK;
xset_set_set( set, "shared_key", "panel1_show_book" );
set = xset_set( "panel4_show_sidebar", "label", _("_Side Toolbar") );
set->menu_style = XSET_MENU_CHECK;
xset_set_set( set, "shared_key", "panel1_show_sidebar" );
set = xset_set( "panel4_list_detailed", "label", _("_Detailed") );
set->menu_style = XSET_MENU_RADIO;
xset_set_set( set, "shared_key", "panel1_list_detailed" );
set = xset_set( "panel4_list_icons", "label", _("_Icons") );
set->menu_style = XSET_MENU_RADIO;
xset_set_set( set, "shared_key", "panel1_list_icons" );
set = xset_set( "panel4_list_compact", "label", _("_Compact") );
set->menu_style = XSET_MENU_RADIO;
xset_set_set( set, "shared_key", "panel1_list_compact" );
set->b = XSET_B_TRUE;
set = xset_set( "panel4_show_hidden", "label", _("_Hidden Files") );
set->menu_style = XSET_MENU_CHECK;
xset_set_set( set, "shared_key", "panel1_show_hidden" );
set = xset_set( "panel4_font_file", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("File List Font (Panel 4)") );
xset_set_set( set, "desc", _("Example 4.4 M file -rwxr--r-- user:group 2011-04-04 04:44") );
set = xset_set( "panel4_font_dev", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Devices Font (Panel 4)") );
xset_set_set( set, "desc", _("sr0 [no media] :EXAMPLE") );
set->line = g_strdup( "#devices-settings-font" );
set = xset_set( "panel4_font_book", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Bookmarks Font (Panel 4)") );
xset_set_set( set, "desc", _("Example Bookmark Name") );
set = xset_set( "panel4_font_path", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Path Bar Font (Panel 4)") );
xset_set_set( set, "desc", _("$ cat /home/user/example") );
set->line = g_strdup( "#gui-pathbar-font" );
set = xset_set( "panel4_font_tab", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Tab Font (Panel 4)") );
xset_set_set( set, "desc", "/usr/bin" );
set = xset_set( "panel4_icon_tab", "label", _("_Icon") );
set->menu_style = XSET_MENU_ICON;
xset_set_set( set, "icon", "gtk-directory" );
set = xset_set( "panel4_font_status", "label", _("_Font") );
set->menu_style = XSET_MENU_FONTDLG;
xset_set_set( set, "icon", "gtk-select-font" );
xset_set_set( set, "title", _("Status Bar Font (Panel 4)") );
xset_set_set( set, "desc", _("12 G free / 200 G 52 items") );
xset_set_set( set, "shared_key", "panel1_font_status" );
set = xset_set( "panel4_icon_status", "label", _("_Icon") );
set->menu_style = XSET_MENU_ICON;
xset_set_set( set, "icon", "gtk-yes" );
xset_set_set( set, "shared_key", "panel1_icon_status" );
set = xset_set( "panel4_detcol_name", "label", _("_Name") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE; // visible
set->x = g_strdup_printf( "%d", 0 ); // position
set = xset_set( "panel4_detcol_size", "label", _("_Size") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 1 );
xset_set_set( set, "shared_key", "panel1_detcol_size" );
set = xset_set( "panel4_detcol_type", "label", _("_Type") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 2 );
xset_set_set( set, "shared_key", "panel1_detcol_type" );
set = xset_set( "panel4_detcol_perm", "label", _("_Permission") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 3 );
xset_set_set( set, "shared_key", "panel1_detcol_perm" );
set = xset_set( "panel4_detcol_owner", "label", _("_Owner") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 4 );
xset_set_set( set, "shared_key", "panel1_detcol_owner" );
set = xset_set( "panel4_detcol_date", "label", _("_Modified") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->x = g_strdup_printf( "%d", 5 );
xset_set_set( set, "shared_key", "panel1_detcol_date" );
set = xset_get( "panel4_sort_extra" );
set->b = XSET_B_TRUE; //sort_natural
set->x = g_strdup_printf( "%d", XSET_B_FALSE ); // sort_case
set->y = g_strdup( "1" ); //PTK_LIST_SORT_DIR_FIRST from ptk-file-list.h
set->z = g_strdup_printf( "%d", XSET_B_TRUE ); // sort_hidden_first
//speed
set = xset_set( "book_newtab", "label", _("_New Tab") );
set->menu_style = XSET_MENU_CHECK;
set = xset_set( "book_single", "label", _("_Single Click") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set = xset_set( "dev_newtab", "label", _("_New Tab") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->line = g_strdup( "#devices-settings-newtab" );
set = xset_set( "dev_single", "label", _("_Single Click") );
set->menu_style = XSET_MENU_CHECK;
set->b = XSET_B_TRUE;
set->line = g_strdup( "#devices-settings-single" );
}
void def_key( char* name, int key, int keymod )
{
XSet* set = xset_get( name );
// key already set or unset?
if ( set->key != 0 || key == 0 )
return;
// key combo already in use?
GList* l;
for ( l = keysets; l; l = l->next )
{
if ( ((XSet*)l->data)->key == key && ((XSet*)l->data)->keymod == keymod )
return;
}
set->key = key;
set->keymod = keymod;
}
void xset_default_keys()
{
XSet* set;
GList* l;
// read all currently set or unset keys
keysets = NULL;
for ( l = xsets; l; l = l->next )
{
if ( ((XSet*)l->data)->key )
keysets = g_list_prepend( keysets, (XSet*)l->data );
}
def_key( "tab_prev", 65056, 5 ); // ctrl-tab or use ctrl-pgdn??
def_key( "tab_next", 65289, 4 );
def_key( "tab_close", 119, 4 );
def_key( "tab_new", 116, 4 );
def_key( "tab_1", 0x31, 8 ); // Alt-1
def_key( "tab_2", 0x32, 8 );
def_key( "tab_3", 0x33, 8 );
def_key( "tab_4", 0x34, 8 );
def_key( "tab_5", 0x35, 8 );
def_key( "tab_6", 0x36, 8 );
def_key( "tab_7", 0x37, 8 );
def_key( "tab_8", 0x38, 8 );
def_key( "tab_9", 0x39, 8 ); // Alt-9
def_key( "tab_10", 0x30, 8 ); // Alt-0
def_key( "edit_cut", 120, 4 );
def_key( "edit_copy", 99, 4 );
def_key( "edit_paste", 118, 4 );
def_key( "edit_rename", 65471, 0 );
def_key( "edit_delete", 65535, 0 );
def_key( "copy_name", 67, 9 );
def_key( "copy_path", 67, 5 );
def_key( "paste_link", 86, 5 );
def_key( "paste_as", 65, 5 );
def_key( "select_all", 97, 4 );
def_key( "main_terminal", 65473, 0 ); //F4
def_key( "go_default", 65307, 0 );
def_key( "go_back", 65361, 8 );
def_key( "go_forward", 65363, 8 );
def_key( "go_up", 65362, 8 );
def_key( "focus_path_bar", 0x6c, 4 ); // Ctrl-L
def_key( "view_refresh", 65474, 0 );
def_key( "prop_info", 0xff0d, 8 );
def_key( "prop_perm", 112, 4 );
def_key( "panel1_show_hidden", 104, 4 );
def_key( "book_new", 100, 4 );
def_key( "new_folder", 102, 4 );
def_key( "new_file", 70, 5 );
def_key( "main_new_window", 110, 4 );
def_key( "open_all", 65475, 0 ); //F6
def_key( "main_full", 0xffc8, 0 ); //F11
def_key( "panel1_show", 0x31, 4 );
def_key( "panel2_show", 0x32, 4 );
def_key( "panel3_show", 0x33, 4 );
def_key( "panel4_show", 0x34, 4 );
def_key( "main_help", 0xffbe, 0 ); //F1
def_key( "main_exit", 0x71, 4 ); // Ctrl-Q
if ( keysets )
g_list_free( keysets );
}
|
145 | ./spacefm/src/main.c | /*
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
/* turn on to debug GDK_THREADS_ENTER/GDK_THREADS_LEAVE related deadlocks */
#undef _DEBUG_THREAD
#include "private.h"
#include <gtk/gtk.h>
#include <glib.h>
#include <stdlib.h>
#include <string.h>
/* socket is used to keep single instance */
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <signal.h>
#include <unistd.h> /* for getcwd */
#include <locale.h>
#include "main-window.h"
#include "vfs-file-info.h"
#include "vfs-mime-type.h"
#include "vfs-app-desktop.h"
#include "vfs-file-monitor.h"
#include "vfs-volume.h"
#include "vfs-thumbnail-loader.h"
#include "ptk-utils.h"
#include "ptk-app-chooser.h"
#include "ptk-file-properties.h"
#include "ptk-file-menu.h"
#include "find-files.h"
#include "pref-dialog.h"
#include "settings.h"
#include "desktop.h"
#include "cust-dialog.h"
//gboolean startup_mode = TRUE; //MOD
//gboolean design_mode = TRUE; //MOD
char* run_cmd = NULL; //MOD
typedef enum{
CMD_OPEN = 1,
CMD_OPEN_TAB,
CMD_REUSE_TAB,
CMD_DAEMON_MODE,
CMD_PREF,
CMD_WALLPAPER,
CMD_FIND_FILES,
CMD_OPEN_PANEL1,
CMD_OPEN_PANEL2,
CMD_OPEN_PANEL3,
CMD_OPEN_PANEL4,
CMD_PANEL1,
CMD_PANEL2,
CMD_PANEL3,
CMD_PANEL4,
CMD_DESKTOP,
CMD_NO_TABS,
CMD_SOCKET_CMD,
SOCKET_RESPONSE_OK,
SOCKET_RESPONSE_ERROR,
SOCKET_RESPONSE_DATA
}SocketEvent;
static gboolean folder_initialized = FALSE;
static gboolean desktop_or_deamon_initialized = FALSE;
static int sock;
GIOChannel* io_channel = NULL;
gboolean daemon_mode = FALSE;
static char* default_files[2] = {NULL, NULL};
static char** files = NULL;
static gboolean no_desktop = FALSE;
static gboolean old_show_desktop = FALSE;
static gboolean new_tab = TRUE;
static gboolean reuse_tab = FALSE; //sfm
static gboolean no_tabs = FALSE; //sfm
static gboolean new_window = FALSE;
static gboolean desktop_pref = FALSE; //MOD
static gboolean desktop = FALSE; //MOD
static gboolean profile = FALSE; //MOD
static gboolean custom_dialog = FALSE; //sfm
static gboolean socket_cmd = FALSE; //sfm
static gboolean version_opt = FALSE; //sfm
static gboolean sdebug = FALSE; //sfm
static int show_pref = 0;
static int panel = -1;
static gboolean set_wallpaper = FALSE;
static gboolean find_files = FALSE;
static char* config_dir = NULL;
#ifdef HAVE_HAL
static char* mount = NULL;
static char* umount = NULL;
static char* eject = NULL;
#endif
static int n_pcmanfm_ref = 0;
static GOptionEntry opt_entries[] =
{
{ "new-tab", 't', 0, G_OPTION_ARG_NONE, &new_tab, N_("Open folders in new tab of last window (default)"), NULL },
{ "reuse-tab", 'r', 0, G_OPTION_ARG_NONE, &reuse_tab, N_("Open folder in current tab of last used window"), NULL },
{ "no-saved-tabs", 'n', 0, G_OPTION_ARG_NONE, &no_tabs, N_("Don't load saved tabs"), NULL },
{ "new-window", 'w', 0, G_OPTION_ARG_NONE, &new_window, N_("Open folders in new window"), NULL },
{ "panel", 'p', 0, G_OPTION_ARG_INT, &panel, N_("Open folders in panel 'P' (1-4)"), "P" },
{ "desktop", '\0', 0, G_OPTION_ARG_NONE, &desktop, N_("Launch desktop manager daemon"), NULL },
{ "desktop-pref", '\0', 0, G_OPTION_ARG_NONE, &desktop_pref, N_("Show desktop settings"), NULL },
{ "show-pref", '\0', 0, G_OPTION_ARG_INT, &show_pref, N_("Show Preferences ('N' is the Pref tab number)"), "N" },
{ "daemon-mode", 'd', 0, G_OPTION_ARG_NONE, &daemon_mode, N_("Run as a daemon"), NULL },
{ "config-dir", 'c', 0, G_OPTION_ARG_STRING, &config_dir, N_("Use DIR as configuration directory"), "DIR" },
{ "find-files", 'f', 0, G_OPTION_ARG_NONE, &find_files, N_("Show File Search"), NULL },
/*
{ "query-type", '\0', 0, G_OPTION_ARG_STRING, &query_type, N_("Query mime-type of the specified file."), NULL },
{ "query-default", '\0', 0, G_OPTION_ARG_STRING, &query_default, N_("Query default application of the specified mime-type."), NULL },
{ "set-default", '\0', 0, G_OPTION_ARG_STRING, &set_default, N_("Set default application of the specified mime-type."), NULL },
*/
#ifdef DESKTOP_INTEGRATION
{ "set-wallpaper", '\0', 0, G_OPTION_ARG_NONE, &set_wallpaper, N_("Set desktop wallpaper to FILE"), NULL },
#endif
{ "dialog", 'g', 0, G_OPTION_ARG_NONE, &custom_dialog, N_("Show a custom dialog (See -g help)"), NULL },
{ "socket-cmd", 's', 0, G_OPTION_ARG_NONE, &socket_cmd, N_("Send a socket command (See -s help)"), NULL },
{ "profile", '\0', 0, G_OPTION_ARG_STRING, &profile, N_("No function - for compatibility only"), "PROFILE" },
{ "no-desktop", '\0', 0, G_OPTION_ARG_NONE, &no_desktop, N_("No function - for compatibility only"), NULL },
{ "version", '\0', 0, G_OPTION_ARG_NONE, &version_opt, N_("Show version information"), NULL },
{ "sdebug", '\0', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &sdebug, NULL, NULL },
#ifdef HAVE_HAL
/* hidden arguments used to mount volumes */
{ "mount", 'm', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &mount, NULL, NULL },
{ "umount", 'u', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &umount, NULL, NULL },
{ "eject", 'e', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &eject, NULL, NULL },
#endif
{G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &files, NULL, N_("[DIR | FILE | URL]...")},
{ NULL }
};
static gboolean single_instance_check();
static void single_instance_finalize();
static void get_socket_name( char* buf, int len );
static gboolean on_socket_event( GIOChannel* ioc, GIOCondition cond, gpointer data );
static void init_folder();
static void init_daemon_or_desktop();
static void check_icon_theme();
static gboolean handle_parsed_commandline_args();
static FMMainWindow* create_main_window();
static void open_file( const char* path );
static GList* get_file_info_list( char** files );
static char* dup_to_absolute_file_path( char** file );
void receive_socket_command( int client, GString* args ); //sfm
char* get_inode_tag()
{
struct stat stat_buf;
const char* path = g_get_home_dir();
if ( !path || stat( path, &stat_buf ) == -1 )
return g_strdup_printf( "%d=", getuid() );
return g_strdup_printf( "%d=%d:%d-%ld", getuid(),
major( stat_buf.st_dev ),
minor( stat_buf.st_dev ),
stat_buf.st_ino );
}
gboolean on_socket_event( GIOChannel* ioc, GIOCondition cond, gpointer data )
{
int client, r;
socklen_t addr_len = 0;
struct sockaddr_un client_addr ={ 0 };
static char buf[ 1024 ];
GString* args;
char** file;
SocketEvent cmd;
if ( cond & G_IO_IN )
{
client = accept( g_io_channel_unix_get_fd( ioc ), (struct sockaddr *)&client_addr, &addr_len );
if ( client != -1 )
{
args = g_string_new_len( NULL, 2048 );
while( (r = read( client, buf, sizeof(buf) )) > 0 )
{
g_string_append_len( args, buf, r);
if ( args->str[0] == CMD_SOCKET_CMD && args->len > 1 &&
args->str[args->len - 2] == '\n' &&
args->str[args->len - 1] == '\n' )
// because CMD_SOCKET_CMD doesn't immediately close the socket
// data is terminated by two linefeeds to prevent read blocking
break;
}
if ( args->str[0] == CMD_SOCKET_CMD )
receive_socket_command( client, args );
shutdown( client, 2 );
close( client );
new_tab = TRUE;
panel = 0;
reuse_tab = FALSE;
no_tabs = FALSE;
int argx = 0;
if ( args->str[argx] == CMD_NO_TABS )
{
reuse_tab = FALSE;
no_tabs = TRUE;
argx++; //another command follows CMD_NO_TABS
}
if ( args->str[argx] == CMD_REUSE_TAB )
{
reuse_tab = TRUE;
new_tab = FALSE;
argx++; //another command follows CMD_REUSE_TAB
}
switch( args->str[argx] )
{
case CMD_PANEL1:
panel = 1;
break;
case CMD_PANEL2:
panel = 2;
break;
case CMD_PANEL3:
panel = 3;
break;
case CMD_PANEL4:
panel = 4;
break;
case CMD_OPEN:
new_tab = FALSE;
break;
case CMD_OPEN_PANEL1:
new_tab = FALSE;
panel = 1;
break;
case CMD_OPEN_PANEL2:
new_tab = FALSE;
panel = 2;
break;
case CMD_OPEN_PANEL3:
new_tab = FALSE;
panel = 3;
break;
case CMD_OPEN_PANEL4:
new_tab = FALSE;
panel = 4;
break;
case CMD_DAEMON_MODE:
daemon_mode = TRUE;
g_string_free( args, TRUE );
return TRUE;
case CMD_DESKTOP:
desktop = TRUE;
break;
case CMD_PREF:
GDK_THREADS_ENTER();
fm_edit_preference( NULL, (unsigned char)args->str[1] - 1 );
GDK_THREADS_LEAVE();
g_string_free( args, TRUE );
return TRUE;
case CMD_WALLPAPER:
set_wallpaper = TRUE;
break;
case CMD_FIND_FILES:
find_files = TRUE;
break;
case CMD_SOCKET_CMD:
g_string_free( args, TRUE );
return TRUE;
break;
}
if( args->str[ argx + 1 ] )
files = g_strsplit( args->str + argx + 1, "\n", 0 );
else
files = NULL;
g_string_free( args, TRUE );
GDK_THREADS_ENTER();
if( files )
{
for( file = files; *file; ++file )
{
if( ! **file ) /* remove empty string at tail */
*file = NULL;
}
}
handle_parsed_commandline_args();
app_settings.load_saved_tabs = TRUE;
GDK_THREADS_LEAVE();
}
}
return TRUE;
}
void get_socket_name_nogdk( char* buf, int len )
{
char* dpy = g_strdup( g_getenv( "DISPLAY" ) );
if ( dpy && !strcmp( dpy, ":0.0" ) )
{
// treat :0.0 as :0 to prevent multiple instances on screen 0
g_free( dpy );
dpy = g_strdup( ":0" );
}
g_snprintf( buf, len, "%s/.spacefm-socket%s-%s", xset_get_tmp_dir(),
dpy,
g_get_user_name() );
g_free( dpy );
}
void get_socket_name( char* buf, int len )
{
char* dpy = gdk_get_display();
if ( dpy && !strcmp( dpy, ":0.0" ) )
{
// treat :0.0 as :0 to prevent multiple instances on screen 0
g_free( dpy );
dpy = g_strdup( ":0" );
}
g_snprintf( buf, len, "%s/.spacefm-socket%s-%s", xset_get_tmp_dir(),
dpy,
g_get_user_name() );
g_free( dpy );
}
gboolean single_instance_check()
{
struct sockaddr_un addr;
int addr_len;
int ret;
int reuse;
if ( ( sock = socket( AF_UNIX, SOCK_STREAM, 0 ) ) == -1 )
{
ret = 1;
goto _exit;
}
addr.sun_family = AF_UNIX;
get_socket_name( addr.sun_path, sizeof( addr.sun_path ) );
#ifdef SUN_LEN
addr_len = SUN_LEN( &addr );
#else
addr_len = strlen( addr.sun_path ) + sizeof( addr.sun_family );
#endif
/* try to connect to existing instance */
if ( connect( sock, ( struct sockaddr* ) & addr, addr_len ) == 0 )
{
/* connected successfully */
char** file;
char cmd = CMD_OPEN_TAB;
if ( no_tabs )
{
cmd = CMD_NO_TABS;
write( sock, &cmd, sizeof(char) );
// another command always follows CMD_NO_TABS
cmd = CMD_OPEN_TAB;
}
if ( reuse_tab )
{
cmd = CMD_REUSE_TAB;
write( sock, &cmd, sizeof(char) );
// another command always follows CMD_REUSE_TAB
cmd = CMD_OPEN;
}
if( daemon_mode )
cmd = CMD_DAEMON_MODE;
else if( desktop )
cmd = CMD_DESKTOP;
else if( new_window )
{
if ( panel > 0 && panel < 5 )
cmd = CMD_OPEN_PANEL1 + panel - 1;
else
cmd = CMD_OPEN;
}
else if( show_pref > 0 )
cmd = CMD_PREF;
else if ( desktop_pref ) //MOD
{
cmd = CMD_PREF;
show_pref = 3;
}
else if( set_wallpaper )
cmd = CMD_WALLPAPER;
else if( find_files )
cmd = CMD_FIND_FILES;
else if ( panel > 0 && panel < 5 )
cmd = CMD_PANEL1 + panel - 1;
// open a new window if no file spec
if ( cmd == CMD_OPEN_TAB && !files )
cmd = CMD_OPEN;
write( sock, &cmd, sizeof(char) );
if( G_UNLIKELY( show_pref > 0 ) )
{
cmd = (unsigned char)show_pref;
write( sock, &cmd, sizeof(char) );
}
else
{
if( files )
{
for( file = files; *file; ++file )
{
char *real_path;
if ( ( *file[0] != '/' && strstr( *file, ":/" ) )
|| g_str_has_prefix( *file, "//" ) )
real_path = g_strdup( *file );
else
{
/* We send absolute paths because with different
$PWDs resolution would not work. */
real_path = dup_to_absolute_file_path( file );
}
write( sock, real_path, strlen( real_path ) );
g_free( real_path );
write( sock, "\n", 1 );
}
}
}
if ( config_dir )
g_warning( _("Option --config-dir ignored - an instance is already running") );
shutdown( sock, 2 );
close( sock );
ret = 0;
goto _exit;
}
/* There is no existing server, and we are in the first instance. */
unlink( addr.sun_path ); /* delete old socket file if it exists. */
reuse = 1;
ret = setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof( reuse ) );
if ( bind( sock, ( struct sockaddr* ) & addr, addr_len ) == -1 )
{
ret = 1;
goto _exit;
}
io_channel = g_io_channel_unix_new( sock );
g_io_channel_set_encoding( io_channel, NULL, NULL );
g_io_channel_set_buffered( io_channel, FALSE );
g_io_add_watch( io_channel, G_IO_IN,
( GIOFunc ) on_socket_event, NULL );
if ( listen( sock, 5 ) == -1 )
{
ret = 1;
goto _exit;
}
// custom config-dir
if ( config_dir && strpbrk( config_dir, " $%\\()&#|:;?<>{}[]*\"'" ) )
{
g_warning( _("Option --config-dir contains invalid chars - cannot start") );
ret = 1;
goto _exit;
}
return TRUE;
_exit:
gdk_notify_startup_complete();
exit( ret );
}
void single_instance_finalize()
{
char lock_file[ 256 ];
shutdown( sock, 2 );
g_io_channel_unref( io_channel );
close( sock );
get_socket_name( lock_file, sizeof( lock_file ) );
unlink( lock_file );
}
void receive_socket_command( int client, GString* args ) //sfm
{
char** argv;
char** arg;
char cmd;
char* reply = NULL;
if ( args->str[1] )
{
if ( g_str_has_suffix( args->str, "\n\n" ) )
{
// remove empty strings at tail
args->str[args->len - 1] = '\0';
args->str[args->len - 2] = '\0';
}
argv = g_strsplit( args->str + 1, "\n", 0 );
}
else
argv = NULL;
/*
if ( argv )
{
printf( "receive:\n");
for ( arg = argv; *arg; ++arg )
{
if ( ! **arg ) // skip empty string
{
printf( " (skipped empty)\n");
continue;
}
printf( " %s\n", *arg );
}
}
*/
// check inode tag - was socket command sent from the same filesystem?
// eg this helps deter use of socket commands sent from a chroot jail
// or from another user or system
char* inode_tag = get_inode_tag();
if ( argv && strcmp( inode_tag, argv[0] ) )
{
reply = g_strdup( "spacefm: invalid socket command user\n" );
cmd = 1;
g_warning( "invalid socket command user" );
}
else
{
// process command and get reply
gdk_threads_enter();
cmd = main_window_socket_command( argv ? argv + 1 : NULL, &reply );
gdk_threads_leave();
}
g_strfreev( argv );
g_free( inode_tag );
// send response
write( client, &cmd, sizeof(char) ); // send exit status
if ( reply && reply[0] )
write( client, reply, strlen( reply ) ); // send reply or error msg
g_free( reply );
}
int send_socket_command( int argc, char* argv[], char** reply ) //sfm
{
struct sockaddr_un addr;
int addr_len;
int ret;
*reply = NULL;
if ( argc < 3 )
{
fprintf( stderr, _("spacefm: --socket-cmd requires an argument\n") );
return 1;
}
// create socket
if ( ( sock = socket( AF_UNIX, SOCK_STREAM, 0 ) ) == -1 )
{
fprintf( stderr, _("spacefm: could not create socket\n") );
return 1;
}
// open socket
addr.sun_family = AF_UNIX;
get_socket_name_nogdk( addr.sun_path, sizeof( addr.sun_path ) );
#ifdef SUN_LEN
addr_len = SUN_LEN( &addr );
#else
addr_len = strlen( addr.sun_path ) + sizeof( addr.sun_family );
#endif
if ( connect( sock, ( struct sockaddr* ) & addr, addr_len ) != 0 )
{
fprintf( stderr, _("spacefm: could not connect to socket (not running? or DISPLAY not set?)\n") );
return 1;
}
// send command
char cmd = CMD_SOCKET_CMD;
write( sock, &cmd, sizeof(char) );
// send inode tag
char* inode_tag = get_inode_tag();
write( sock, inode_tag, strlen( inode_tag ) );
write( sock, "\n", 1 );
g_free( inode_tag );
// send arguments
int i;
for ( i = 2; i < argc; i++ )
{
write( sock, argv[i], strlen( argv[i] ) );
write( sock, "\n", 1 );
}
write( sock, "\n", 1 );
// get response
GString* sock_reply = g_string_new_len( NULL, 2048 );
int r;
static char buf[ 1024 ];
while( ( r = read( sock, buf, sizeof( buf ) ) ) > 0 )
g_string_append_len( sock_reply, buf, r);
// close socket
shutdown( sock, 2 );
close( sock );
// set reply
if ( sock_reply->len != 0 )
{
*reply = g_strdup( sock_reply->str + 1 );
ret = sock_reply->str[0];
}
else
{
fprintf( stderr, _("spacefm: invalid response from socket\n") );
ret = 1;
}
g_string_free( sock_reply, TRUE );
return ret;
}
void show_socket_help()
{
printf( "%s\n", _("SpaceFM socket commands permit external processes (such as command scripts)") );
printf( "%s\n", _("to read and set GUI property values and execute methods inside running SpaceFM") );
printf( "%s\n", _("windows. To handle events see View|Events in the main menu bar.") );
printf( "\n%s\n", _("Usage:") );
printf( " spacefm --socket-cmd|-s METHOD [OPTIONS] [ARGUMENT...]\n" );
printf( "%s\n", _("Example:") );
printf( " spacefm -s set window_size 800x600\n" );
printf( "\n%s\n", _("METHODS\n-------") );
printf( "spacefm -s set [OPTIONS] PROPERTY [VALUE...]\n" );
printf( " %s\n", _("Sets a property") );
printf( "\nspacefm -s get [OPTIONS] PROPERTY\n" );
printf( " %s\n", _("Gets a property") );
printf( "\nspacefm -s set-task [OPTIONS] TASKID TASKPROPERTY [VALUE...]\n" );
printf( " %s\n", _("Sets a task property") );
printf( "\nspacefm -s get-task [OPTIONS] TASKID TASKPROPERTY\n" );
printf( " %s\n", _("Gets a task property") );
printf( "\nspacefm -s run-task [OPTIONS] TASKTYPE ARGUMENTS\n" );
printf( " %s\n", _("Starts a new task") );
printf( "\nspacefm -s emit-key [OPTIONS] KEYCODE [MODIFIER]\n" );
printf( " %s\n", _("Activates a menu item by emitting its shortcut key") );
printf( "\nspacefm -s show-menu [OPTIONS] MENUNAME\n" );
printf( " %s\n", _("Shows custom submenu named MENUNAME as a popup menu") );
printf( "\nspacefm -s add-event EVENT COMMAND...\n" );
printf( " %s\n", _("Add asynchronous handler COMMAND to EVENT") );
printf( "\nspacefm -s replace-event EVENT COMMAND...\n" );
printf( " %s\n", _("Add synchronous handler COMMAND to EVENT, replacing default handler") );
printf( "\nspacefm -s remove-event EVENT COMMAND...\n" );
printf( " %s\n", _("Remove handler COMMAND from EVENT") );
printf( "\nspacefm -s help|--help\n" );
printf( " %s\n", _("Shows this help reference. (Also see manual link below.)") );
printf( "\n%s\n", _("OPTIONS\n-------") );
printf( "%s\n", _("Add options after METHOD to specify a specific window, panel, and/or tab.") );
printf( "%s\n", _("Otherwise the current tab of the current panel in the last window is used.") );
printf( "\n--window WINDOWID\n" );
printf( " %s spacefm -s set --window 0x104ca80 window_size 800x600\n", _("Specify window. eg:") );
printf( "--panel PANEL\n" );
printf( " %s spacefm -s set --panel 2 bookmarks_visible true\n", _("Specify panel 1-4. eg:") );
printf( "--tab TAB\n" );
printf( " %s spacefm -s set --tab 3 selected_filenames fstab\n", _("Specify tab 1-... eg:") );
printf( "\n%s\n", _("PROPERTIES\n----------") );
printf( "%s\n", _("Set properties with METHOD 'set', or get the value with 'get'.") );
printf( "\nwindow_size eg '800x600'\n" );
printf( "window_position eg '100x50'\n" );
printf( "window_maximized 1|true|yes|0|false|no\n" );
printf( "window_fullscreen 1|true|yes|0|false|no\n" );
printf( "screen_size eg '1024x768' (read-only)\n" );
printf( "window_vslider_top eg '100'\n" );
printf( "window_vslider_bottom eg '100'\n" );
printf( "window_hslider eg '100'\n" );
printf( "window_tslider eg '100'\n" );
printf( "focused_panel 1|2|3|4|prev|next|hide\n" );
printf( "focused_pane filelist|devices|bookmarks|dirtree|pathbar\n" );
printf( "current_tab 1|2|...|prev|next|close\n" );
printf( "tab_count 1|2|...\n" );
printf( "new_tab [DIR] %s\n", _("Open DIR or default in a new tab") );
printf( "devices_visible 1|true|yes|0|false|no\n" );
printf( "bookmarks_visible 1|true|yes|0|false|no\n" );
printf( "dirtree_visible 1|true|yes|0|false|no\n" );
printf( "toolbar_visible 1|true|yes|0|false|no\n" );
printf( "sidetoolbar_visible 1|true|yes|0|false|no\n" );
printf( "hidden_files_visible 1|true|yes|0|false|no\n" );
printf( "panel1_visible 1|true|yes|0|false|no\n" );
printf( "panel2_visible 1|true|yes|0|false|no\n" );
printf( "panel3_visible 1|true|yes|0|false|no\n" );
printf( "panel4_visible 1|true|yes|0|false|no\n" );
printf( "panel_hslider_top eg '100'\n" );
printf( "panel_hslider_bottom eg '100'\n" );
printf( "panel_vslider eg '100'\n" );
printf( "column_width name|size|type|permission|owner|modified WIDTH\n" );
printf( "sort_by name|size|type|permission|owner|modified\n" );
printf( "sort_ascend 1|true|yes|0|false|no\n" );
printf( "sort_natural 1|true|yes|0|false|no\n" );
printf( "sort_case 1|true|yes|0|false|no\n" );
printf( "sort_hidden_first 1|true|yes|0|false|no\n" );
printf( "sort_first files|folders|mixed\n" );
printf( "statusbar_text %s\n", _("eg 'Current Status: Example'") );
printf( "pathbar_text [TEXT [SELSTART [SELEND]]]\n" );
printf( "current_dir %s\n", _("DIR eg '/etc'") );
printf( "selected_filenames %s\n", _("[FILENAME...]") );
printf( "selected_pattern %s\n", _("[PATTERN] eg '*.jpg'") );
printf( "clipboard_text %s\n", _("eg 'Some\\nlines\\nof text'") );
printf( "clipboard_primary_text %s\n", _("eg 'Some\\nlines\\nof text'") );
printf( "clipboard_from_file %s\n", _("eg '~/copy-file-contents-to-clipboard.txt'") );
printf( "clipboard_primary_from_file %s\n", _("eg '~/copy-file-contents-to-clipboard.txt'") );
printf( "clipboard_copy_files %s\n", _("FILE... Files copied to clipboard") );
printf( "clipboard_cut_files %s\n", _("FILE... Files cut to clipboard") );
printf( "\n%s\n", _("TASK PROPERTIES\n---------------") );
printf( "status %s\n", _("contents of Status task column (read-only)") );
printf( "icon %s\n", _("eg 'gtk-open'") );
printf( "count %s\n", _("text to show in Count task column") );
printf( "folder %s\n", _("text to show in Folder task column") );
printf( "item %s\n", _("text to show in Item task column") );
printf( "to %s\n", _("text to show in To task column") );
printf( "progress %s\n", _("Progress percent (1..100) or '' to pulse") );
printf( "total %s\n", _("text to show in Total task column") );
printf( "curspeed %s\n", _("text to show in Current task column") );
printf( "curremain %s\n", _("text to show in CRemain task column") );
printf( "avgspeed %s\n", _("text to show in Average task column") );
printf( "avgremain %s\n", _("text to show in Remain task column") );
printf( "elapsed %s\n", _("contents of Elapsed task column (read-only)") );
printf( "started %s\n", _("contents of Started task column (read-only)") );
printf( "queue_state run|pause|queue|stop\n" );
printf( "popup_handler %s\n", _("COMMAND command to show a custom task dialog\n") );
printf( "\n%s\n", _("TASK TYPES\n----------") );
printf( "cmd [--task] [--popup] [--scroll] [--terminal] [--icon ICON] \\\n" );
printf( " [--dir DIR] COMMAND... %s\n", _("Run COMMAND as USER in DIR") );
printf( "copy|move|link [--dir DIR] FILE|DIR... TARGET\n" );
printf( " %s\n", _("Copy|Move|Link FILE(s) or DIR(s) to TARGET dir") );
printf( "delete [--dir DIR] FILE|DIR... %s\n", _("Recursively delete FILE(s) or DIR(s)" ) );
printf( "edit [--as-root] FILE %s\n", _("Open FILE in user's or root's text editor") );
printf( "web URL %s\n", _("Open URL in user's web browser") );
printf( "\n%s\n", _("EVENTS\n------") );
printf( "evt_start %s\n", _("Instance start %e") );
printf( "evt_exit %s\n", _("Instance exit %e") );
printf( "evt_win_new %s\n", _("Window new %e %w %p %t") );
printf( "evt_win_focus %s\n", _("Window focus %e %w %p %t") );
printf( "evt_win_move %s\n", _("Window move/resize %e %w %p %t") );
printf( "evt_win_click %s\n", _("Mouse click %e %w %p %t %b %m %f") );
printf( "evt_win_key %s\n", _("Window keypress %e %w %p %t %k %m") );
printf( "evt_win_close %s\n", _("Window close %e %w %p %t") );
printf( "evt_pnl_focus %s\n", _("Panel focus %e %w %p %t") );
printf( "evt_pnl_show %s\n", _("Panel show/hide %e %w %p %t %f %v") );
printf( "evt_pnl_sel %s\n", _("Selection changed %e %w %p %t") );
printf( "evt_tab_new %s\n", _("Tab new %e %w %p %t") );
printf( "evt_tab_focus %s\n", _("Tab focus %e %w %p %t") );
printf( "evt_tab_close %s\n", _("Tab close %e %w %p %t") );
printf( "evt_device %s\n", _("Device change %e %f %v") );
printf( "\n%s\n", _("Event COMMAND Substitution Variables:") );
printf( "%%e %s\n", _("event name (evt_start|evt_exit|...)") );
printf( "%%w %s\n", _("window ID") );
printf( "%%p %s\n", _("panel number (1-4)") );
printf( "%%t %s\n", _("tab number (1-...)") );
printf( "%%b %s\n", _("mouse button (0=double 1=left 2=middle 3=right ...") );
printf( "%%k %s\n", _("key code (eg 0x63)") );
printf( "%%m %s\n", _("modifier key (eg 0x4 used with clicks and keypresses)") );
printf( "%%f %s\n", _("focus element (panelN|filelist|devices|bookmarks|dirtree|pathbar)") );
printf( "%%v %s\n", _("focus element is visible (0 or 1, or device state change)") );
printf( "\n%s:\n\n", _("Examples") );
printf( " window_size=\"$(spacefm -s get window_size)\"\n" );
printf( " spacefm -s set window_size 1024x768\n" );
printf( " spacefm -s set column_width name 100\n" );
printf( " spacefm -s set-task $fm_my_task progress 25\n" );
printf( " spacefm -s run-task --window $fm_my_window cmd --task --popup ls /etc\n" );
printf( " spacefm -s run-task copy --dir /etc fstab hosts /destdir\n" );
printf( " spacefm -r /etc; sleep 0.3; spacefm -s set selected_filenames fstab hosts\n" );
printf( " spacefm -s set clipboard_copy_files /etc/fstab /etc/hosts\n" );
printf( " spacefm -s emit-key 0xffbe 0 # press F1 to show Help\n" );
printf( " spacefm -s show-menu --window $fm_my_window \"Custom Menu\"\n" );
printf( " spacefm -s add-event evt_pnl_sel 'spacefm -s set statusbar_text \"$fm_file\"'\n\n" );
printf( " #!/bin/bash\n" );
printf( " eval copied_files=\"$(spacefm -s get clipboard_copy_files)\"\n" );
printf( " echo \"%s:\"\n", _("These files have been copied to the clipboard") );
printf( " i=0\n" );
printf( " while [ \"${copied_files[i]}\" != \"\" ]; do\n" );
printf( " echo \" ${copied_files[i]}\"\n" );
printf( " (( i++ ))\n" );
printf( " done\n" );
printf( " if (( i != 0 )); then\n" );
printf( " echo \"MD5SUMS:\"\n" );
printf( " md5sum \"${copied_files[@]}\"\n" );
printf( " fi\n" );
printf( "\n%s\n http://ignorantguru.github.com/spacefm/spacefm-manual-en.html#sockets\n", _("For full documentation and examples see the SpaceFM User's Manual:") );
}
FMMainWindow* create_main_window()
{
FMMainWindow * main_window = FM_MAIN_WINDOW(fm_main_window_new ());
gtk_window_set_default_size( GTK_WINDOW( main_window ),
app_settings.width, app_settings.height );
if ( app_settings.maximized )
{
gtk_window_maximize( GTK_WINDOW( main_window ) );
}
gtk_widget_show ( GTK_WIDGET( main_window ) );
return main_window;
}
/*
void check_icon_theme()
{
GtkSettings * settings;
char* theme;
const char* title = N_( "GTK+ icon theme is not properly set" );
const char* error_msg =
N_( "<big><b>%s</b></big>\n\n"
"This usually means you don't have an XSETTINGS manager running. "
"Desktop environment like GNOME or XFCE automatically execute their "
"XSETTING managers like gnome-settings-daemon or xfce-mcs-manager.\n\n"
"<b>If you don't use these desktop environments, "
"you have two choices:\n"
"1. run an XSETTINGS manager, or\n"
"2. simply specify an icon theme in ~/.gtkrc-2.0.</b>\n"
"For example to use the Tango icon theme add a line:\n"
"<i><b>gtk-icon-theme-name=\"Tango\"</b></i> in your ~/.gtkrc-2.0. (create it if no such file)\n\n"
"<b>NOTICE: The icon theme you choose should be compatible with GNOME, "
"or the file icons cannot be displayed correctly.</b> "
"Due to the differences in icon naming of GNOME and KDE, KDE themes cannot be used. "
"Currently there is no standard for this, but it will be solved by freedesktop.org in the future." );
settings = gtk_settings_get_default();
g_object_get( settings, "gtk-icon-theme-name", &theme, NULL );
// No icon theme available
if ( !theme || !*theme || 0 == strcmp( theme, "hicolor" ) )
{
GtkWidget * dlg;
dlg = gtk_message_dialog_new_with_markup( NULL,
GTK_DIALOG_MODAL,
GTK_MESSAGE_ERROR,
GTK_BUTTONS_OK,
_( error_msg ), _( title ) );
gtk_window_set_title( GTK_WINDOW( dlg ), _( title ) );
gtk_dialog_run( GTK_DIALOG( dlg ) );
gtk_widget_destroy( dlg );
}
g_free( theme );
}
*/
#ifdef _DEBUG_THREAD
G_LOCK_DEFINE(gdk_lock);
void debug_gdk_threads_enter (const char* message)
{
g_debug( "Thread %p tries to get GDK lock: %s", g_thread_self (), message );
G_LOCK(gdk_lock);
g_debug( "Thread %p got GDK lock: %s", g_thread_self (), message );
}
static void _debug_gdk_threads_enter ()
{
debug_gdk_threads_enter( "called from GTK+ internal" );
}
void debug_gdk_threads_leave( const char* message )
{
g_debug( "Thread %p tries to release GDK lock: %s", g_thread_self (), message );
G_LOCK(gdk_lock);
g_debug( "Thread %p released GDK lock: %s", g_thread_self (), message );
}
static void _debug_gdk_threads_leave()
{
debug_gdk_threads_leave( "called from GTK+ internal" );
}
#endif
void init_folder()
{
if( G_LIKELY(folder_initialized) )
return;
app_settings.bookmarks = ptk_bookmarks_get();
vfs_volume_init();
vfs_thumbnail_init();
vfs_mime_type_set_icon_size( app_settings.big_icon_size,
app_settings.small_icon_size );
vfs_file_info_set_thumbnail_size( app_settings.big_icon_size,
app_settings.small_icon_size );
//check_icon_theme(); //sfm seems to run okay without gtk theme
folder_initialized = TRUE;
}
static void init_daemon_or_desktop()
{
if( desktop )
fm_turn_on_desktop_icons();
}
#ifdef HAVE_HAL
/* FIXME: Currently, this cannot be supported without HAL */
static int handle_mount( char** argv )
{
gboolean success;
vfs_volume_init();
if( mount )
success = vfs_volume_mount_by_udi( mount, NULL );
else if( umount )
success = vfs_volume_umount_by_udi( umount, NULL );
else /* if( eject ) */
success = vfs_volume_eject_by_udi( eject, NULL );
vfs_volume_finalize();
return success ? 0 : 1;
}
#endif
GList* get_file_info_list( char** file_paths )
{
GList* file_list = NULL;
char** file;
VFSFileInfo* fi;
for( file = file_paths; *file; ++file )
{
fi = vfs_file_info_new();
if( vfs_file_info_get( fi, *file, NULL ) )
file_list = g_list_append( file_list, fi );
else
vfs_file_info_unref( fi );
}
return file_list;
}
gboolean delayed_popup( GtkWidget* popup )
{
GDK_THREADS_ENTER();
gtk_menu_popup( GTK_MENU( popup ), NULL, NULL,
NULL, NULL, 0, gtk_get_current_event_time() );
GDK_THREADS_LEAVE();
return FALSE;
}
static void init_desktop_or_daemon()
{
init_folder();
signal( SIGPIPE, SIG_IGN );
signal( SIGHUP, (void*)gtk_main_quit );
signal( SIGINT, (void*)gtk_main_quit );
signal( SIGTERM, (void*)gtk_main_quit );
if( desktop )
fm_turn_on_desktop_icons();
desktop_or_deamon_initialized = TRUE;
}
char* dup_to_absolute_file_path(char** file)
{
char* file_path, *real_path, *cwd_path;
const size_t cwd_size = PATH_MAX;
if( g_str_has_prefix( *file, "file:" ) ) /* It's a URI */
{
file_path = g_filename_from_uri( *file, NULL, NULL );
g_free( *file );
*file = file_path;
}
else
file_path = *file;
cwd_path = malloc( cwd_size );
if( cwd_path )
{
getcwd( cwd_path, cwd_size );
}
real_path = vfs_file_resolve_path( cwd_path, file_path );
free( cwd_path );
cwd_path = NULL;
return real_path; /* To free with g_free */
}
static void open_in_tab( FMMainWindow** main_window, const char* real_path )
{
XSet* set;
int p;
// create main window if needed
if( G_UNLIKELY( !*main_window ) )
{
// initialize things required by folder view
if( G_UNLIKELY( ! daemon_mode ) )
init_folder();
// preload panel?
if ( panel > 0 && panel < 5 )
// user specified panel
p = panel;
else
{
// use first visible panel
for ( p = 1; p < 5; p++ )
{
if ( xset_get_b_panel( p, "show" ) )
break;
}
}
if ( p == 5 )
p = 1; // no panels were visible (unlikely)
// set panel to load real_path on window creation
set = xset_get_panel( p, "show" );
set->ob1 = g_strdup( real_path );
set->b = XSET_B_TRUE;
// create new window
*main_window = create_main_window();
}
else
{
// existing window
gboolean tab_added = FALSE;
if ( panel > 0 && panel < 5 )
{
// change to user-specified panel
if ( !gtk_notebook_get_n_pages(
GTK_NOTEBOOK( (*main_window)->panel[panel-1] ) ) )
{
// set panel to load real_path on panel load
set = xset_get_panel( panel, "show" );
set->ob1 = g_strdup( real_path );
tab_added = TRUE;
set->b = XSET_B_TRUE;
show_panels_all_windows( NULL, *main_window );
}
else if ( !gtk_widget_get_visible( (*main_window)->panel[panel-1] ) )
{
// show panel
set = xset_get_panel( panel, "show" );
set->b = XSET_B_TRUE;
show_panels_all_windows( NULL, *main_window );
}
(*main_window)->curpanel = panel;
(*main_window)->notebook = (*main_window)->panel[panel-1];
}
if ( !tab_added )
{
if ( reuse_tab )
{
main_window_open_path_in_current_tab( *main_window,
real_path );
reuse_tab = FALSE;
}
else
fm_main_window_add_new_tab( *main_window, real_path );
}
}
gtk_window_present( GTK_WINDOW( *main_window ) );
}
gboolean handle_parsed_commandline_args()
{
FMMainWindow * main_window = NULL;
char** file;
gboolean ret = TRUE;
XSet* set;
int p;
app_settings.load_saved_tabs = !no_tabs;
// If no files are specified, open home dir by defualt.
if( G_LIKELY( ! files ) )
{
files = default_files;
//files[0] = (char*)g_get_home_dir();
}
// get the last active window on this desktop, if available
if( new_tab || reuse_tab )
{
main_window = fm_main_window_get_on_current_desktop();
//printf(" fm_main_window_get_on_current_desktop = %p %s %s\n", main_window,
// new_tab ? "new_tab" : "",
// reuse_tab ? "reuse_tab" : "" );
}
if ( desktop_pref ) //MOD
show_pref = 3;
if( show_pref > 0 ) /* show preferences dialog */
{
/* We should initialize desktop support here.
* Otherwise, if the user turn on the desktop support
* in the pref dialog, the newly loaded desktop will be uninitialized.
*/
//init_desktop_or_daemon();
fm_edit_preference( GTK_WINDOW( main_window ), show_pref - 1 );
show_pref = 0;
}
else if( find_files ) /* find files */
{
init_folder();
fm_find_files( (const char**)files );
find_files = FALSE;
}
#ifdef DESKTOP_INTEGRATION
else if( set_wallpaper ) /* change wallpaper */
{
set_wallpaper = FALSE;
char* file = files ? files[0] : NULL;
char* path;
if( ! file )
return FALSE;
if( g_str_has_prefix( file, "file:" ) ) /* URI */
{
path = g_filename_from_uri( file, NULL, NULL );
g_free( file );
file = path;
}
else
file = g_strdup( file );
if( g_file_test( file, G_FILE_TEST_IS_REGULAR ) )
{
g_free( app_settings.wallpaper );
app_settings.wallpaper = file;
app_settings.show_wallpaper = TRUE;
if ( xset_autosave_timer )
{
g_source_remove( xset_autosave_timer );
xset_autosave_timer = 0;
}
char* err_msg = save_settings( NULL );
if ( err_msg )
printf( _("spacefm: Error: Unable to save session\n %s\n"), err_msg );
if( desktop && app_settings.show_wallpaper )
{
if( desktop_or_deamon_initialized )
fm_desktop_update_wallpaper();
}
}
else
g_free( file );
ret = ( daemon_mode || ( desktop && desktop_or_deamon_initialized) );
goto out;
}
#endif
else /* open files/folders */
{
if( (daemon_mode || desktop) && ! desktop_or_deamon_initialized )
{
init_desktop_or_daemon();
}
else if ( files != default_files )
{
/* open files passed in command line arguments */
ret = FALSE;
for( file = files; *file; ++file )
{
char *real_path;
if( ! **file ) /* skip empty string */
continue;
real_path = dup_to_absolute_file_path( file );
if( g_file_test( real_path, G_FILE_TEST_IS_DIR ) )
{
open_in_tab( &main_window, real_path );
ret = TRUE;
}
else if ( g_file_test( real_path, G_FILE_TEST_EXISTS ) )
open_file( real_path );
else if ( ( *file[0] != '/' && strstr( *file, ":/" ) )
|| g_str_has_prefix( *file, "//" ) )
{
if ( main_window )
main_window_open_network( main_window, *file, TRUE );
else
{
open_in_tab( &main_window, "/" );
main_window_open_network( main_window, *file, FALSE );
}
ret = TRUE;
gtk_window_present( GTK_WINDOW( main_window ) );
}
else
{
char* err_msg = g_strdup_printf( "%s:\n\n%s", _( "File doesn't exist" ),
real_path );
ptk_show_error( NULL, _("Error"), err_msg );
g_free( err_msg );
}
g_free( real_path );
}
}
else
{
// no files specified, just create window with default tabs
if( G_UNLIKELY( ! main_window ) )
{
// initialize things required by folder view
if( G_UNLIKELY( ! daemon_mode ) )
init_folder();
main_window = create_main_window();
}
gtk_window_present( GTK_WINDOW( main_window ) );
if ( panel > 0 && panel < 5 )
{
// user specified a panel with no file, let's show the panel
if ( !gtk_widget_get_visible( main_window->panel[panel-1] ) )
{
// show panel
set = xset_get_panel( panel, "show" );
set->b = XSET_B_TRUE;
show_panels_all_windows( NULL, main_window );
}
focus_panel( NULL, (gpointer)main_window, panel );
}
}
}
//printf(" handle_parsed_commandline_args mw = %p\n\n", main_window );
out:
if( files != default_files )
g_strfreev( files );
files = NULL;
return ret;
}
void tmp_clean()
{
char* cmd = g_strdup_printf( "rm -rf %s", xset_get_user_tmp_dir() );
g_spawn_command_line_async( cmd, NULL );
g_free( cmd );
}
int main ( int argc, char *argv[] )
{
gboolean run = FALSE;
GError* err = NULL;
#ifdef ENABLE_NLS
bindtextdomain ( GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR );
bind_textdomain_codeset ( GETTEXT_PACKAGE, "UTF-8" );
textdomain ( GETTEXT_PACKAGE );
#endif
// load spacefm.conf
load_conf();
// separate instance options
if ( argc > 1 )
{
// dialog mode?
if ( !strcmp( argv[1], "-g" ) || !strcmp( argv[1], "--dialog" ) )
{
g_thread_init( NULL );
gdk_threads_init ();
/* initialize the file alteration monitor */
if( G_UNLIKELY( ! vfs_file_monitor_init() ) )
{
#ifdef USE_INOTIFY
ptk_show_error( NULL, _("Error"), _("Error: Unable to initialize inotify file change monitor.\n\nDo you have an inotify-capable kernel?") );
#else
ptk_show_error( NULL, _("Error"), _("Error: Unable to establish connection with FAM.\n\nDo you have \"FAM\" or \"Gamin\" installed and running?") );
#endif
vfs_file_monitor_clean();
return 1;
}
gtk_init (&argc, &argv);
int ret = custom_dialog_init( argc, argv );
if ( ret != 0 )
{
vfs_file_monitor_clean();
return ret == -1 ? 0 : ret;
}
gtk_main();
vfs_file_monitor_clean();
return 0;
}
// socket_command?
if ( !strcmp( argv[1], "-s" ) || !strcmp( argv[1], "--socket-cmd" ) )
{
#ifdef ENABLE_NLS
// initialize gettext since gtk_init is not run here
setlocale( LC_ALL, "" );
bindtextdomain( GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR );
textdomain( GETTEXT_PACKAGE );
#endif
if ( argv[2] && ( !strcmp( argv[2], "help" ) ||
!strcmp( argv[2], "--help" ) ) )
{
show_socket_help();
return 0;
}
char* reply = NULL;
int ret = send_socket_command( argc, argv, &reply );
if ( reply && reply[0] )
fprintf( ret ? stderr : stdout, "%s", reply );
g_free( reply );
return ret;
}
}
/* initialize GTK+ and parse the command line arguments */
if( G_UNLIKELY( ! gtk_init_with_args( &argc, &argv, "", opt_entries, GETTEXT_PACKAGE, &err ) ) )
{
printf( "spacefm: %s\n", err->message );
g_error_free( err );
return 1;
}
// dialog mode with other options?
if ( custom_dialog )
{
fprintf( stderr, "spacefm: %s\n", _("--dialog must be first option") );
return 1;
}
// socket command with other options?
if ( socket_cmd )
{
fprintf( stderr, "spacefm: %s\n", _("--socket-cmd must be first option") );
return 1;
}
// --desktop with no desktop build?
#ifndef DESKTOP_INTEGRATION
if ( desktop )
{
fprintf( stderr, "spacefm: %s\n", _("This build of SpaceFM has desktop integration disabled") );
return 1;
}
#endif
// --version
if ( version_opt )
{
printf( "spacefm %s\n", VERSION );
#if GTK_CHECK_VERSION (3, 0, 0)
printf( "GTK3 " );
#else
printf( "GTK2 " );
#endif
#ifdef HAVE_HAL
printf( "HAL " );
#else
printf( "UDEV " );
#endif
#ifdef USE_INOTIFY
printf( "INOTIFY " );
#else
printf( "FAM " );
#endif
#ifdef DESKTOP_INTEGRATION
printf( "DESKTOP " );
#endif
#ifdef HAVE_SN
printf( "SNOTIFY " );
#endif
printf( "\n" );
return 0;
}
/* Initialize multithreading //sfm moved below parse arguments
No matter we use threads or not, it's safer to initialize this earlier. */
#ifdef _DEBUG_THREAD
gdk_threads_set_lock_functions(_debug_gdk_threads_enter, _debug_gdk_threads_leave);
#endif
g_thread_init( NULL );
gdk_threads_init ();
#if HAVE_HAL
/* If the user wants to mount/umount/eject a device */
if( G_UNLIKELY( mount || umount || eject ) )
return handle_mount( argv );
#endif
/* ensure that there is only one instance of spacefm.
if there is an existing instance, command line arguments
will be passed to the existing instance, and exit() will be called here. */
single_instance_check();
/* initialize the file alteration monitor */
if( G_UNLIKELY( ! vfs_file_monitor_init() ) )
{
#ifdef USE_INOTIFY
ptk_show_error( NULL, _("Error"), _("Error: Unable to initialize inotify file change monitor.\n\nDo you have an inotify-capable kernel?") );
#else
ptk_show_error( NULL, _("Error"), _("Error: Unable to establish connection with FAM.\n\nDo you have \"FAM\" or \"Gamin\" installed and running?") );
#endif
vfs_file_monitor_clean();
//free_settings();
return 1;
}
/* check if the filename encoding is UTF-8 */
vfs_file_info_set_utf8_filename( g_get_filename_charsets( NULL ) );
/* Initialize our mime-type system */
vfs_mime_type_init();
load_settings( config_dir ); /* load config file */ //MOD was before vfs_file_monitor_init
app_settings.sdebug = sdebug;
/*
// temporarily turn off desktop if needed
if( G_LIKELY( no_desktop ) )
{
// No matter what the value of show_desktop is, we don't showdesktop icons
// if --no-desktop argument is passed by the users.
old_show_desktop = app_settings.show_desktop;
// This config value will be restored before saving config files, if needed.
app_settings.show_desktop = FALSE;
}
*/
/* If we reach this point, we are the first instance.
* Subsequent processes will exit() inside single_instance_check and won't reach here.
*/
main_window_event( NULL, NULL, "evt_start", 0, 0, NULL, 0, 0, 0, FALSE );
/* handle the parsed result of command line args */
run = handle_parsed_commandline_args();
app_settings.load_saved_tabs = TRUE;
if( run ) /* run the main loop */
gtk_main();
main_window_event( NULL, NULL, "evt_exit", 0, 0, NULL, 0, 0, 0, FALSE );
single_instance_finalize();
if( desktop && desktop_or_deamon_initialized ) // desktop was app_settings.show_desktop
fm_turn_off_desktop_icons();
/*
if( no_desktop ) // desktop icons is temporarily supressed
{
if( old_show_desktop ) // restore original settings
{
old_show_desktop = app_settings.show_desktop;
app_settings.show_desktop = TRUE;
}
}
*/
/*
if( run && xset_get_b( "main_save_exit" ) )
{
char* err_msg = save_settings();
if ( err_msg )
printf( "spacefm: Error: Unable to save session\n %s\n", err_msg );
}
*/
vfs_volume_finalize();
vfs_mime_type_clean();
vfs_file_monitor_clean();
tmp_clean();
free_settings();
return 0;
}
void open_file( const char* path )
{
GError * err;
char *msg, *error_msg;
VFSFileInfo* file;
VFSMimeType* mime_type;
gboolean opened;
char* app_name;
file = vfs_file_info_new();
vfs_file_info_get( file, path, NULL );
mime_type = vfs_file_info_get_mime_type( file );
opened = FALSE;
err = NULL;
app_name = vfs_mime_type_get_default_action( mime_type );
if ( app_name )
{
opened = vfs_file_info_open_file( file, path, &err );
g_free( app_name );
}
else
{
VFSAppDesktop* app;
GList* files;
app_name = (char *) ptk_choose_app_for_mime_type( NULL, mime_type, FALSE );
if ( app_name )
{
app = vfs_app_desktop_new( app_name );
if ( ! vfs_app_desktop_get_exec( app ) )
app->exec = g_strdup( app_name ); /* This is a command line */
files = g_list_prepend( NULL, (gpointer) path );
opened = vfs_app_desktop_open_files( gdk_screen_get_default(),
NULL, app, files, &err );
g_free( files->data );
g_list_free( files );
vfs_app_desktop_unref( app );
g_free( app_name );
}
else
opened = TRUE;
}
if ( !opened )
{
char * disp_path;
if ( err && err->message )
{
error_msg = err->message;
}
else
error_msg = _( "Don't know how to open the file" );
disp_path = g_filename_display_name( path );
msg = g_strdup_printf( _( "Unable to open file:\n\"%s\"\n%s" ), disp_path, error_msg );
g_free( disp_path );
ptk_show_error( NULL, _("Error"), msg );
g_free( msg );
if ( err )
g_error_free( err );
}
vfs_mime_type_unref( mime_type );
vfs_file_info_unref( file );
}
/* After opening any window/dialog/tool, this should be called. */
void pcmanfm_ref()
{
++n_pcmanfm_ref;
}
/* After closing any window/dialog/tool, this should be called.
* If the last window is closed and we are not a deamon, pcmanfm will quit.
*/
gboolean pcmanfm_unref()
{
--n_pcmanfm_ref;
if( 0 == n_pcmanfm_ref && ! daemon_mode && !desktop )
gtk_main_quit();
return FALSE;
}
|
146 | ./spacefm/src/go-dialog.c | #ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <string.h>
#include <gtk/gtk.h>
#include <stdlib.h>
#include <string.h>
#include "go-dialog.h"
#include "main-window.h"
#include "ptk-file-browser.h"
#include "ptk-path-entry.h"
#include "ptk-utils.h"
static const char * chosen_path;
static gboolean show_go_dialog( GtkWindow* parent, char * initial_path )
{
GtkBuilder* builder = _gtk_builder_new_from_file( PACKAGE_UI_DIR "/godlg.ui", NULL );
GtkDialog* dlg = GTK_DIALOG(gtk_builder_get_object( builder, "godlg" ));
GtkEntry* path_entry = ( GtkEntry* ) ptk_path_entry_new ( NULL );
gtk_entry_set_activates_default( path_entry, TRUE );
gtk_entry_set_text( path_entry, initial_path );
gtk_container_add( GTK_CONTAINER( gtk_dialog_get_content_area( dlg ) ), GTK_WIDGET( path_entry ) );
gtk_widget_show_all( gtk_dialog_get_content_area( dlg ) );
gtk_widget_grab_focus( GTK_WIDGET( path_entry ) );
gboolean ret = ( gtk_dialog_run( GTK_DIALOG( dlg ) ) == GTK_RESPONSE_OK );
if ( ret )
{
chosen_path = strdup( gtk_entry_get_text( path_entry ) );
}
gtk_widget_destroy( GTK_WIDGET( dlg ) );
return ret;
}
gboolean fm_go( FMMainWindow* main_window )
{
int i = gtk_notebook_get_current_page( GTK_NOTEBOOK( main_window->notebook ) );
PtkFileBrowser* file_browser = PTK_FILE_BROWSER( gtk_notebook_get_nth_page(
GTK_NOTEBOOK( main_window->notebook ), i ) );
if( file_browser->dir )
{
char* disp_path = file_browser->dir->disp_path;
if( disp_path )
{
if( show_go_dialog( GTK_WINDOW( main_window ), disp_path ) )
{
char* dir_path = g_filename_from_utf8( chosen_path , -1, NULL, NULL, NULL );
free( (char*)chosen_path );
char* final_path = vfs_file_resolve_path( ptk_file_browser_get_cwd(file_browser), dir_path );
g_free( dir_path );
ptk_file_browser_chdir( file_browser, final_path, PTK_FB_CHDIR_ADD_HISTORY );
g_free( final_path );
gtk_widget_grab_focus( GTK_WIDGET( file_browser->folder_view ) );
}
}
}
return TRUE;
}
|
147 | ./spacefm/src/edit-bookmarks.c | /*
*
* NOTE: This file is retained for reference purposes only - it is no longer
* included in the build system.
*
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "pcmanfm.h"
#include "edit-bookmarks.h"
#include "ptk-bookmarks.h"
#include "private.h"
#include <gtk/gtk.h>
#include <glib.h>
#include <string.h>
enum{
COL_ICON = 0,
COL_NAME,
COL_DIRPATH,
NUM_COLS
};
static void on_add( GtkButton* btn, gpointer data )
{
GtkWindow* parent = GTK_WINDOW(data);
GtkTreeViewColumn* col;
GtkTreeIter it, new_it, *pit;
GtkTreePath* tree_path;
GtkTreeView* view = (GtkTreeView*)g_object_get_data( G_OBJECT(data),
"list_view" );
GtkTreeModel* model;
GtkTreeSelection* sel = gtk_tree_view_get_selection( view );
GdkPixbuf* icon = gtk_icon_theme_load_icon( gtk_icon_theme_get_default(),
"gnome-fs-directory",
20, 0, NULL );
GtkWidget* dlg;
char *path = NULL, *basename = NULL;
if( gtk_tree_selection_get_selected ( sel, &model, &it ) )
{
tree_path = gtk_tree_model_get_path( model, &it );
gtk_tree_path_next( tree_path );
pit = ⁢
}
else
{
tree_path = gtk_tree_path_new_first();
pit = NULL;
}
dlg = gtk_file_chooser_dialog_new( NULL, parent,
GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
GTK_STOCK_OK, GTK_RESPONSE_OK, NULL );
if( gtk_dialog_run( (GtkDialog*) dlg ) == GTK_RESPONSE_OK )
{
path = gtk_file_chooser_get_filename( (GtkFileChooser*)dlg );
basename = g_filename_display_basename( path );
}
gtk_widget_destroy( dlg );
col = gtk_tree_view_get_column( view, 1 );
gtk_list_store_insert_after( GTK_LIST_STORE(model), &new_it, pit );
gtk_list_store_set( GTK_LIST_STORE(model), &new_it,
COL_ICON, icon,
COL_NAME, basename ? basename : _("New Item"),
COL_DIRPATH, path, -1);
g_free( path );
g_free( basename );
if( tree_path )
{
gtk_tree_view_set_cursor_on_cell( view, tree_path, col, NULL, TRUE );
gtk_tree_path_free( tree_path );
}
if( icon )
g_object_unref( icon );
}
static void on_delete( GtkButton* btn, gpointer data )
{
GtkTreeIter it;
GtkTreeView* view = (GtkTreeView*)g_object_get_data( G_OBJECT(data),
"list_view" );
GtkTreeModel* model;
GtkTreeSelection* sel = gtk_tree_view_get_selection( view );
if( gtk_tree_selection_get_selected ( sel, &model, &it ) )
{
gtk_list_store_remove( GTK_LIST_STORE(model), &it );
}
gtk_widget_grab_focus( GTK_WIDGET(view) );
}
static void on_name_edited (GtkCellRendererText *cell,
gchar *path_string,
gchar *new_text,
GtkListStore* list )
{
GtkTreeIter it;
gtk_tree_model_get_iter_from_string(GTK_TREE_MODEL(list),
&it, path_string );
if( new_text && *new_text )
gtk_list_store_set(list, &it, COL_NAME, new_text, -1);
}
static void on_path_edited (GtkCellRendererText *cell,
gchar *path_string,
gchar *new_text,
GtkListStore* list )
{
GtkTreeIter it;
gtk_tree_model_get_iter_from_string(GTK_TREE_MODEL(list),
&it, path_string );
if( new_text && *new_text )
gtk_list_store_set(list, &it, COL_DIRPATH, new_text, -1);
}
gboolean edit_bookmarks( GtkWindow* parent )
{
GList* l;
GtkWidget* dlg;
GtkWidget* btn_box;
GtkWidget* add_btn;
GtkWidget* delete_btn;
GtkWidget* scroll;
GtkWidget* list_view;
GtkListStore* list;
GtkTreeViewColumn* col;
GtkTreeIter it;
GtkTreeSelection* sel;
gchar *name, *path, *item;
gboolean ret = FALSE;
PtkBookmarks* bookmarks;
GtkCellRenderer *renderer, *icon_renderer;
GdkPixbuf* icon;
dlg = gtk_dialog_new_with_buttons ( _("Edit Bookmarks"),
parent,
GTK_DIALOG_MODAL,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
GTK_STOCK_OK, GTK_RESPONSE_OK,
NULL );
gtk_dialog_set_alternative_button_order( GTK_DIALOG(dlg), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1 );
list = gtk_list_store_new( NUM_COLS, GDK_TYPE_PIXBUF, G_TYPE_STRING, G_TYPE_STRING );
icon = gtk_icon_theme_load_icon( gtk_icon_theme_get_default(),
"gnome-fs-directory",
20, 0, NULL );
bookmarks = ptk_bookmarks_get();
for( l = bookmarks->list; l; l = l->next )
{
gtk_list_store_append( list, &it );
gtk_list_store_set( list, &it,
COL_ICON, icon,
COL_NAME, l->data,
COL_DIRPATH, ptk_bookmarks_item_get_path((char*)l->data),
-1);
}
if( icon )
g_object_unref( icon );
scroll = gtk_scrolled_window_new(NULL, NULL);
gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW(scroll),
GTK_SHADOW_IN);
list_view = gtk_tree_view_new_with_model( GTK_TREE_MODEL(list) );
g_object_set_data( G_OBJECT(dlg), "list_view", list_view );
sel = gtk_tree_view_get_selection( GTK_TREE_VIEW(list_view) );
gtk_tree_selection_set_mode( sel, GTK_SELECTION_BROWSE );
if( gtk_tree_model_get_iter_first ( GTK_TREE_MODEL(list), &it ) )
{
gtk_tree_selection_select_iter( sel, &it );
}
icon_renderer = gtk_cell_renderer_pixbuf_new();
renderer = gtk_cell_renderer_text_new();
g_object_set( G_OBJECT(renderer), "editable", TRUE, NULL );
g_signal_connect( renderer, "edited", G_CALLBACK(on_name_edited), list );
col = gtk_tree_view_column_new_with_attributes(NULL, icon_renderer, "pixbuf", COL_ICON, NULL );
gtk_tree_view_append_column( GTK_TREE_VIEW(list_view), col );
col = gtk_tree_view_column_new_with_attributes(_("Name"), renderer, "text", COL_NAME, NULL);
gtk_tree_view_column_set_resizable(col, TRUE);
gtk_tree_view_column_set_fixed_width(col, 160);
gtk_tree_view_column_set_sizing(col, GTK_TREE_VIEW_COLUMN_FIXED);
gtk_tree_view_append_column( GTK_TREE_VIEW(list_view), col );
renderer = gtk_cell_renderer_text_new();
g_object_set( G_OBJECT(renderer), "editable", TRUE, NULL );
g_signal_connect( renderer, "edited", G_CALLBACK(on_path_edited), list );
col = gtk_tree_view_column_new_with_attributes(_("Path"),
renderer, "text", COL_DIRPATH, NULL);
gtk_tree_view_column_set_resizable(col, TRUE);
gtk_tree_view_append_column( GTK_TREE_VIEW(list_view), col );
gtk_tree_view_set_reorderable ( GTK_TREE_VIEW(list_view), TRUE );
gtk_container_add( GTK_CONTAINER(scroll), list_view);
btn_box = gtk_hbutton_box_new();
gtk_button_box_set_layout ( GTK_BUTTON_BOX(btn_box), GTK_BUTTONBOX_START );
add_btn = gtk_button_new_from_stock ( GTK_STOCK_ADD );
g_signal_connect( add_btn, "clicked", G_CALLBACK(on_add), dlg );
gtk_box_pack_start ( GTK_BOX(btn_box), add_btn, TRUE, TRUE, 0 );
delete_btn = gtk_button_new_from_stock ( GTK_STOCK_DELETE );
g_signal_connect( delete_btn, "clicked", G_CALLBACK(on_delete), dlg );
gtk_box_pack_start ( GTK_BOX(btn_box), delete_btn, TRUE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX(gtk_dialog_get_content_area ( GTK_DIALOG(dlg) )), btn_box,
FALSE, FALSE, 4 );
gtk_box_pack_start( GTK_BOX(gtk_dialog_get_content_area ( GTK_DIALOG(dlg) )), scroll, TRUE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX(gtk_dialog_get_content_area ( GTK_DIALOG(dlg) )),
gtk_label_new(_("Use drag & drop to sort the items")),
FALSE, FALSE, 4 );
gtk_window_set_default_size ( GTK_WINDOW(dlg), 480, 400 );
gtk_widget_show_all( dlg );
gtk_widget_grab_focus( list_view );
pcmanfm_ref();
if( gtk_dialog_run( GTK_DIALOG(dlg) ) == GTK_RESPONSE_OK )
{
l = NULL;
if( gtk_tree_model_get_iter_first( GTK_TREE_MODEL(list), &it ) )
{
do
{
gtk_tree_model_get( GTK_TREE_MODEL(list), &it,
COL_NAME, &name,
COL_DIRPATH, &path,
-1 );
if( ! name )
name = g_path_get_basename( path );
item = ptk_bookmarks_item_new( name, strlen(name),
path ? path : "", path ? strlen(path) : 0 );
l = g_list_append( l, item );
g_free(name);
g_free(path);
}
while( gtk_tree_model_iter_next( GTK_TREE_MODEL(list), &it) );
}
ptk_bookmarks_set( l );
ret = TRUE;
}
ptk_bookmarks_unref();
gtk_widget_destroy( dlg );
pcmanfm_unref();
return ret;
}
|
148 | ./spacefm/src/xml-purge.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define IS_BLANK(ch) strchr(" \t\n\r", ch)
static void purge_file( const char* file )
{
struct stat statbuf;
int fd;
char* buf, *pbuf;
int in_tag = 0, in_quote = 0;
FILE* fo;
fd = open( file, O_RDONLY );
if( fd == -1 )
return;
if( fstat( fd, &statbuf) == -1 )
return;
if( buf = (char*)malloc( statbuf.st_size + 1 ) )
{
if( read( fd, buf, statbuf.st_size) == -1 )
{
free( buf );
return;
}
buf[ statbuf.st_size ] = '\0';
}
close( fd );
fo = fopen( file, "w" );
if( ! fo )
goto error;
for( pbuf = buf; *pbuf; ++pbuf )
{
if( in_tag > 0 )
{
if( in_quote )
{
if( *pbuf == '\"' )
in_quote = 0;
}
else
{
if( *pbuf == '\"' )
++in_quote;
if( ! in_quote && IS_BLANK(*pbuf) ) /* skip unnecessary blanks */
{
do{
++pbuf;
}while( IS_BLANK( *pbuf ) );
if( *pbuf != '>' )
fputc( ' ', fo );
--pbuf;
continue;
}
}
if( *pbuf == '>' )
--in_tag;
fputc( *pbuf, fo );
}
else
{
if( *pbuf == '<' )
{
if( 0 == strncmp( pbuf, "<!--", 4 ) ) /* skip comments */
{
pbuf = strstr( pbuf, "-->" );
if( ! pbuf )
goto error;
pbuf += 2;
continue;
}
++in_tag;
fputc( '<', fo );
}
else
{
char* tmp = pbuf;
while( *tmp && IS_BLANK( *tmp ) && *tmp != '<' )
++tmp;
if( *tmp == '<' ) /* all cdata are blank characters */
pbuf = tmp - 1;
else /* not blank, keep the cdata */
{
if( tmp == pbuf )
fputc( *pbuf, fo );
else
{
fwrite( pbuf, 1, tmp - pbuf, fo );
pbuf = tmp - 1;
}
}
}
}
}
fclose( fo );
error:
free( buf );
}
int main( int argc, char** argv )
{
int i;
if( argc < 2 )
return 1;
for( i = 1; i < argc; ++i )
purge_file( argv[ i] );
return 0;
}
|
149 | ./spacefm/src/pref-dialog.c | /*
* C Implementation: pref_dialog
*
* Description:
*
*
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "pcmanfm.h"
#include <string.h>
#include <gtk/gtk.h>
#include <stdlib.h>
#include <string.h>
#include "glib-utils.h"
#include <glib/gi18n.h>
#include "pref-dialog.h"
#include "settings.h"
#include "ptk-utils.h"
#include "main-window.h"
#include "ptk-file-browser.h"
#include "desktop.h"
#include "ptk-location-view.h"
#include "gtk2-compat.h"
typedef struct _FMPrefDlg FMPrefDlg;
struct _FMPrefDlg
{
GtkWidget* dlg;
GtkWidget* notebook;
GtkWidget* encoding;
GtkWidget* bm_open_method;
GtkWidget* max_thumb_size;
GtkWidget* show_thumbnail;
GtkWidget* thumb_label1;
GtkWidget* thumb_label2;
GtkWidget* terminal;
GtkWidget* big_icon_size;
GtkWidget* small_icon_size;
GtkWidget* tool_icon_size;
GtkWidget* single_click;
GtkWidget* use_si_prefix;
//GtkWidget* rubberband;
GtkWidget* root_bar;
GtkWidget* drag_action;
/* Interface tab */
GtkWidget* always_show_tabs;
GtkWidget* hide_close_tab_buttons;
//GtkWidget* hide_folder_content_border;
//GtkWidget* show_desktop;
GtkWidget* show_wallpaper;
GtkWidget* wallpaper;
GtkWidget* wallpaper_mode;
GtkWidget* img_preview;
GtkWidget* show_wm_menu;
GtkWidget* bg_color1;
GtkWidget* text_color;
GtkWidget* shadow_color;
//MOD
GtkWidget* confirm_delete;
GtkWidget* click_exec;
GtkWidget* su_command;
GtkWidget* gsu_command;
GtkWidget* date_format;
GtkWidget* date_display;
GtkWidget* editor;
GtkWidget* editor_terminal;
GtkWidget* root_editor;
GtkWidget* root_editor_terminal;
};
extern gboolean daemon_mode; /* defined in main.c */
static FMPrefDlg* data = NULL;
static const int tool_icon_sizes[] = {
0,
GTK_ICON_SIZE_MENU,
GTK_ICON_SIZE_SMALL_TOOLBAR,
GTK_ICON_SIZE_LARGE_TOOLBAR,
GTK_ICON_SIZE_BUTTON,
GTK_ICON_SIZE_DND,
GTK_ICON_SIZE_DIALOG };
static const int big_icon_sizes[] = { 96, 72, 64, 48, 36, 32, 24, 22 };
static const int small_icon_sizes[] = { 48, 36, 32, 24, 22, 16, 12 };
static const char* date_formats[] =
{
"%Y-%m-%d %H:%M",
"%Y-%m-%d",
"%Y-%m-%d %H:%M:%S"
};
static const int drag_actions[] = { 0, 1, 2, 3 };
/*
static void
on_show_desktop_toggled( GtkToggleButton* show_desktop, GtkWidget* desktop_page )
{
gtk_container_foreach( GTK_CONTAINER(desktop_page),
(GtkCallback) gtk_widget_set_sensitive,
(gpointer) gtk_toggle_button_get_active( show_desktop ) );
gtk_widget_set_sensitive( GTK_WIDGET(show_desktop), TRUE );
}
*/
static void set_preview_image( GtkImage* img, const char* file )
{
GdkPixbuf* pix = NULL;
pix = gdk_pixbuf_new_from_file_at_scale( file, 128, 128, TRUE, NULL );
if( pix )
{
gtk_image_set_from_pixbuf( img, pix );
g_object_unref( pix );
}
}
static void on_update_img_preview( GtkFileChooser *chooser, GtkImage* img )
{
char* file = gtk_file_chooser_get_preview_filename( chooser );
if( file )
{
set_preview_image( img, file );
g_free( file );
}
else
{
gtk_image_clear( img );
}
}
static void
dir_unload_thumbnails( const char* path, VFSDir* dir, gpointer user_data )
{
vfs_dir_unload_thumbnails( dir, GPOINTER_TO_INT( user_data ) );
}
static void on_response( GtkDialog* dlg, int response, FMPrefDlg* user_data )
{
int i, n;
gboolean b;
int ibig_icon = -1, ismall_icon = -1, itool_icon = -1;
const char* filename_encoding;
int max_thumb;
gboolean show_thumbnail;
int big_icon;
int small_icon;
int tool_icon;
//gboolean show_desktop;
gboolean show_wallpaper;
gboolean single_click;
//gboolean rubberband;
gboolean root_bar;
gboolean root_set_change = FALSE;
WallpaperMode wallpaper_mode;
GdkColor bg1;
GdkColor bg2;
GdkColor text;
GdkColor shadow;
char* wallpaper;
const GList* l;
PtkFileBrowser* file_browser;
gboolean use_si_prefix;
GtkNotebook* notebook;
int cur_tabx, p;
FMMainWindow* a_window;
char* str;
GtkWidget * tab_label;
/* interface settings */
gboolean always_show_tabs;
gboolean hide_close_tab_buttons;
//gboolean hide_folder_content_border;
/* built-in response codes of GTK+ are all negative */
if( response >= 0 )
return;
if ( response == GTK_RESPONSE_OK )
{
/* file name encoding */
//filename_encoding = gtk_entry_get_text( GTK_ENTRY( data->encoding ) );
//if ( filename_encoding
// && g_ascii_strcasecmp ( filename_encoding, "UTF-8" ) )
//{
// strcpy( app_settings.encoding, filename_encoding );
// setenv( "G_FILENAME_ENCODING", app_settings.encoding, 1 );
//}
//else
//{
// app_settings.encoding[ 0 ] = '\0';
// unsetenv( "G_FILENAME_ENCODING" );
//}
//app_settings.open_bookmark_method = gtk_combo_box_get_active( GTK_COMBO_BOX( data->bm_open_method ) ) + 1;
show_thumbnail = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( data->show_thumbnail ) );
max_thumb = ( ( int ) gtk_spin_button_get_value( GTK_SPIN_BUTTON( data->max_thumb_size ) ) ) << 10;
/* interface settings */
always_show_tabs = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( data->always_show_tabs ) );
if ( always_show_tabs != app_settings.always_show_tabs )
{
app_settings.always_show_tabs = always_show_tabs;
// update all windows/all panels
for ( l = fm_main_window_get_all(); l; l = l->next )
{
a_window = FM_MAIN_WINDOW( l->data );
for ( p = 1; p < 5; p++ )
{
notebook = GTK_NOTEBOOK( a_window->panel[p-1] );
n = gtk_notebook_get_n_pages( notebook );
if ( always_show_tabs )
gtk_notebook_set_show_tabs( notebook, TRUE );
else if ( n == 1 )
gtk_notebook_set_show_tabs( notebook, FALSE );
}
}
}
hide_close_tab_buttons = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( data->hide_close_tab_buttons ) );
if ( hide_close_tab_buttons != app_settings.hide_close_tab_buttons )
{
app_settings.hide_close_tab_buttons = hide_close_tab_buttons;
// update all windows/all panels/all browsers
for ( l = fm_main_window_get_all(); l; l = l->next )
{
a_window = FM_MAIN_WINDOW( l->data );
for ( p = 1; p < 5; p++ )
{
notebook = GTK_NOTEBOOK( a_window->panel[p-1] );
n = gtk_notebook_get_n_pages( notebook );
for ( i = 0; i < n; ++i )
{
file_browser = PTK_FILE_BROWSER( gtk_notebook_get_nth_page(
notebook, i ) );
tab_label = fm_main_window_create_tab_label( a_window,
file_browser );
gtk_notebook_set_tab_label( notebook, GTK_WIDGET(file_browser),
tab_label );
fm_main_window_update_tab_label( a_window, file_browser,
file_browser->dir->disp_path );
}
}
}
}
/*
hide_folder_content_border = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( data->hide_folder_content_border ) );
if ( hide_folder_content_border != app_settings.hide_folder_content_border )
{
app_settings.hide_folder_content_border = hide_folder_content_border;
// update all windows/all panels/all browsers
for ( l = fm_main_window_get_all(); l; l = l->next )
{
a_window = FM_MAIN_WINDOW( l->data );
for ( p = 1; p < 5; p++ )
{
notebook = a_window->panel[p-1];
n = gtk_notebook_get_n_pages( notebook );
for ( i = 0; i < n; ++i )
{
file_browser = PTK_FILE_BROWSER( gtk_notebook_get_nth_page(
notebook, i ) );
if ( hide_folder_content_border )
ptk_file_browser_hide_shadow( file_browser );
else
ptk_file_browser_show_shadow( file_browser );
}
}
}
}
*/
/* hide_side_pane_buttons = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( data->hide_side_pane_buttons ) );
if ( hide_side_pane_buttons != app_settings.hide_side_pane_buttons )
{
app_settings.hide_side_pane_buttons = hide_side_pane_buttons;
for ( l = fm_main_window_get_all(); l; l = l->next )
{
FMMainWindow* main_window = FM_MAIN_WINDOW( l->data );
GtkNotebook* notebook = main_window->notebook;
n = gtk_notebook_get_n_pages( notebook );
for ( i = 0; i < n; ++i )
{
file_browser = PTK_FILE_BROWSER( gtk_notebook_get_nth_page( notebook, i ) );
if ( hide_side_pane_buttons)
{
ptk_file_browser_hide_side_pane_buttons( file_browser );
}
else
{
ptk_file_browser_show_side_pane_buttons( file_browser );
}
}
}
}
*/
/* desktop settings */
//show_desktop = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( data->show_desktop ) );
show_wallpaper = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( data->show_wallpaper ) );
wallpaper = gtk_file_chooser_get_filename( GTK_FILE_CHOOSER( data->wallpaper ) );
wallpaper_mode = gtk_combo_box_get_active( (GtkComboBox*)data->wallpaper_mode );
app_settings.show_wm_menu = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( data->show_wm_menu ) );
gtk_color_button_get_color(GTK_COLOR_BUTTON(data->bg_color1), &bg1);
gtk_color_button_get_color(GTK_COLOR_BUTTON(data->text_color), &text);
gtk_color_button_get_color(GTK_COLOR_BUTTON(data->shadow_color), &shadow);
/*
if( show_desktop != app_settings.show_desktop )
{
app_settings.show_wallpaper = show_wallpaper;
g_free( app_settings.wallpaper );
app_settings.wallpaper = wallpaper;
app_settings.wallpaper_mode = wallpaper_mode;
app_settings.desktop_bg1 = bg1;
app_settings.desktop_bg2 = bg2;
app_settings.desktop_text = text;
app_settings.desktop_shadow = shadow;
app_settings.show_desktop = show_desktop;
if ( app_settings.show_desktop )
fm_turn_on_desktop_icons();
else
fm_turn_off_desktop_icons();
}
else if ( app_settings.show_desktop )
{
*/
gboolean need_update_bg = FALSE;
/* desktop colors are changed */
if ( !gdk_color_equal( &bg1, &app_settings.desktop_bg1 ) ||
!gdk_color_equal( &bg2, &app_settings.desktop_bg2 ) ||
!gdk_color_equal( &text, &app_settings.desktop_text ) ||
!gdk_color_equal( &shadow, &app_settings.desktop_shadow ) )
{
app_settings.desktop_bg1 = bg1;
app_settings.desktop_bg2 = bg2;
app_settings.desktop_text = text;
app_settings.desktop_shadow = shadow;
fm_desktop_update_colors();
if( wallpaper_mode == WPM_CENTER || !show_wallpaper )
need_update_bg = TRUE;
}
/* wallpaper settings are changed */
if( need_update_bg ||
wallpaper_mode != app_settings.wallpaper_mode ||
show_wallpaper != app_settings.show_wallpaper ||
( g_strcmp0( wallpaper, app_settings.wallpaper ) ) )
{
app_settings.wallpaper_mode = wallpaper_mode;
app_settings.show_wallpaper = show_wallpaper;
g_free( app_settings.wallpaper );
app_settings.wallpaper = wallpaper;
fm_desktop_update_wallpaper();
}
// }
/* thumbnail settings are changed */
if( app_settings.show_thumbnail != show_thumbnail || app_settings.max_thumb_size != max_thumb )
{
app_settings.show_thumbnail = show_thumbnail;
app_settings.max_thumb_size = max_thumb;
// update all windows/all panels/all browsers
for ( l = fm_main_window_get_all(); l; l = l->next )
{
a_window = FM_MAIN_WINDOW( l->data );
for ( p = 1; p < 5; p++ )
{
notebook = GTK_NOTEBOOK( a_window->panel[p-1] );
n = gtk_notebook_get_n_pages( notebook );
for ( i = 0; i < n; ++i )
{
file_browser = PTK_FILE_BROWSER( gtk_notebook_get_nth_page(
notebook, i ) );
ptk_file_browser_show_thumbnails( file_browser,
app_settings.show_thumbnail ?
app_settings.max_thumb_size : 0 );
}
}
}
//if ( desktop )
fm_desktop_update_thumbnails();
}
/* icon sizes are changed? */
ibig_icon = gtk_combo_box_get_active( GTK_COMBO_BOX( data->big_icon_size ) );
big_icon = ibig_icon >= 0 ? big_icon_sizes[ ibig_icon ] : app_settings.big_icon_size;
ismall_icon = gtk_combo_box_get_active( GTK_COMBO_BOX( data->small_icon_size ) );
small_icon = ismall_icon >= 0 ? small_icon_sizes[ ismall_icon ] : app_settings.small_icon_size;
itool_icon = gtk_combo_box_get_active( GTK_COMBO_BOX( data->tool_icon_size ) );
if ( itool_icon >= 0 && itool_icon <= GTK_ICON_SIZE_DIALOG )
tool_icon = tool_icon_sizes[ itool_icon ];
if ( big_icon != app_settings.big_icon_size
|| small_icon != app_settings.small_icon_size )
{
vfs_mime_type_set_icon_size( big_icon, small_icon );
vfs_file_info_set_thumbnail_size( big_icon, small_icon );
/* unload old thumbnails (icons of *.desktop files will be unloaded here, too) */
if( big_icon != app_settings.big_icon_size )
vfs_dir_foreach( (GHFunc)dir_unload_thumbnails, GINT_TO_POINTER( 1 ) );
if( small_icon != app_settings.small_icon_size )
vfs_dir_foreach( (GHFunc)dir_unload_thumbnails, GINT_TO_POINTER( 0 ) );
// update all windows/all panels/all browsers
for ( l = fm_main_window_get_all(); l; l = l->next )
{
a_window = FM_MAIN_WINDOW( l->data );
for ( p = 1; p < 5; p++ )
{
notebook = GTK_NOTEBOOK( a_window->panel[p-1] );
n = gtk_notebook_get_n_pages( notebook );
for ( i = 0; i < n; ++i )
{
file_browser = PTK_FILE_BROWSER( gtk_notebook_get_nth_page(
notebook, i ) );
ptk_file_browser_update_display( file_browser );
if ( file_browser->side_dir )
{
gtk_widget_destroy( file_browser->side_dir );
file_browser->side_dir = NULL;
ptk_file_browser_update_views( NULL, file_browser );
}
}
}
}
// update desktop icons
if ( big_icon != app_settings.big_icon_size )
{
app_settings.big_icon_size = big_icon;
fm_desktop_update_icons();
}
app_settings.big_icon_size = big_icon;
app_settings.small_icon_size = small_icon;
update_bookmark_icons();
update_volume_icons();
}
if ( tool_icon != app_settings.tool_icon_size )
{
app_settings.tool_icon_size = tool_icon;
rebuild_toolbar_all_windows( 0, NULL );
rebuild_toolbar_all_windows( 1, NULL );
}
/* unit settings changed? */
gboolean need_refresh = FALSE;
use_si_prefix = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( data->use_si_prefix ) );
if( use_si_prefix != app_settings.use_si_prefix )
{
app_settings.use_si_prefix = use_si_prefix;
need_refresh = TRUE;
}
// date format
char* etext = g_strdup( gtk_entry_get_text( GTK_ENTRY( gtk_bin_get_child(
GTK_BIN( data->date_format ) ) ) ) );
if ( g_strcmp0( etext, xset_get_s( "date_format" ) ) )
{
if ( etext[0] == '\0' )
xset_set( "date_format", "s", "%Y-%m-%d %H:%M" );
else
xset_set( "date_format", "s", etext );
g_free( etext );
if ( app_settings.date_format )
g_free( app_settings.date_format );
app_settings.date_format = g_strdup( xset_get_s( "date_format" ) );
need_refresh = TRUE;
}
if ( need_refresh )
main_window_refresh_all();
/* single click changed? */
single_click = gtk_toggle_button_get_active( (GtkToggleButton*)data->single_click );
if( single_click != app_settings.single_click )
{
app_settings.single_click = single_click;
// update all windows/all panels/all browsers
for ( l = fm_main_window_get_all(); l; l = l->next )
{
a_window = FM_MAIN_WINDOW( l->data );
for ( p = 1; p < 5; p++ )
{
notebook = GTK_NOTEBOOK( a_window->panel[p-1] );
n = gtk_notebook_get_n_pages( notebook );
for ( i = 0; i < n; ++i )
{
file_browser = PTK_FILE_BROWSER( gtk_notebook_get_nth_page(
notebook, i ) );
ptk_file_browser_set_single_click( file_browser, app_settings.single_click );
/* ptk_file_browser_set_single_click_timeout( file_browser, SINGLE_CLICK_TIMEOUT ); */
}
}
}
fm_desktop_set_single_click( app_settings.single_click );
}
//MOD
app_settings.no_execute = !gtk_toggle_button_get_active(
(GtkToggleButton*)data->click_exec );
app_settings.no_confirm = !gtk_toggle_button_get_active(
(GtkToggleButton*)data->confirm_delete );
/*
rubberband = gtk_toggle_button_get_active(
(GtkToggleButton*)data->rubberband );
if ( !!rubberband != !!xset_get_b( "rubberband" ) )
{
xset_set_b( "rubberband", rubberband );
main_window_rubberband_all();
}
*/
root_bar = gtk_toggle_button_get_active(
(GtkToggleButton*)data->root_bar );
if ( !!root_bar != !!xset_get_b( "root_bar" ) )
{
xset_set_b( "root_bar", root_bar );
main_window_root_bar_all();
}
char* s = g_strdup_printf( "%d",
gtk_combo_box_get_active( GTK_COMBO_BOX( data->drag_action ) ) );
xset_set( "drag_action", "x", s );
g_free( s );
//MOD su command
char* custom_su = NULL;
int set_x = gtk_combo_box_get_active( GTK_COMBO_BOX( data->su_command ) );
if ( set_x > -1 )
{
if ( custom_su )
{
if ( set_x == 0 )
xset_set( "su_command", "s", custom_su );
else
xset_set( "su_command", "s", su_commands[set_x - 1] );
g_free( custom_su );
}
else
xset_set( "su_command", "s", su_commands[set_x] );
}
//MOD gsu command
char* custom_gsu = NULL;
set_x = gtk_combo_box_get_active( GTK_COMBO_BOX( data->gsu_command ) );
#ifdef PREFERABLE_SUDO_PROG
custom_gsu = g_find_program_in_path( PREFERABLE_SUDO_PROG );
#endif
if ( set_x > -1 )
{
if ( custom_gsu )
{
if ( set_x == 0 )
xset_set( "gsu_command", "s", custom_gsu );
else
xset_set( "gsu_command", "s", gsu_commands[set_x - 1] );
g_free( custom_gsu );
}
else
xset_set( "gsu_command", "s", gsu_commands[set_x] );
}
//MOD editors
xset_set( "editor", "s", gtk_entry_get_text( GTK_ENTRY( data->editor ) ) );
xset_set_b( "editor", gtk_toggle_button_get_active(
(GtkToggleButton*)data->editor_terminal ) );
const char* root_editor = gtk_entry_get_text( GTK_ENTRY( data->root_editor ) );
const char* old_root_editor = xset_get_s( "root_editor" );
if ( !old_root_editor )
{
if ( root_editor[0] != '\0' )
{
xset_set( "root_editor", "s", root_editor );
root_set_change = TRUE;
}
}
else if ( strcmp( root_editor, old_root_editor ) )
{
xset_set( "root_editor", "s", root_editor );
root_set_change = TRUE;
}
if ( !!gtk_toggle_button_get_active(
(GtkToggleButton*)data->root_editor_terminal )
!= !!xset_get_b( "root_editor" ) )
{
xset_set_b( "root_editor", gtk_toggle_button_get_active(
(GtkToggleButton*)data->root_editor_terminal ) );
root_set_change = TRUE;
}
//MOD terminal
char* old_terminal = xset_get_s( "main_terminal" );
char* terminal = gtk_combo_box_text_get_active_text( GTK_COMBO_BOX_TEXT( data->terminal ) );
g_strstrip( terminal );
if ( g_strcmp0( terminal, old_terminal ) )
{
xset_set( "main_terminal", "s", terminal[0] == '\0' ? NULL : terminal );
root_set_change = TRUE;
}
// report missing terminal
if ( str = strchr( terminal, ' ' ) )
str[0] = '\0';
str = g_find_program_in_path( terminal );
if ( !str )
{
str = g_strdup_printf( "Unable to find terminal program '%s'", terminal );
ptk_show_error( GTK_WINDOW( dlg ), "Error", str );
}
g_free( str );
g_free( terminal );
/* save to config file */
char* err_msg = save_settings( NULL );
if ( err_msg )
{
char* msg = g_strdup_printf( "Error: Unable to save session file.\n\n%s",
err_msg );
ptk_show_error( GTK_WINDOW( dlg ), "Error", msg );
g_free( msg );
g_free( err_msg );
}
if ( xset_get_b( "main_terminal" ) )
{
root_set_change = TRUE;
xset_set_b( "main_terminal", FALSE );
}
// root settings saved?
if ( geteuid() != 0 )
{
/*
char* root_set_path= g_strdup_printf(
"/etc/spacefm/%s-as-root", g_get_user_name() );
if ( !g_file_test( root_set_path, G_FILE_TEST_EXISTS ) )
{
g_free( root_set_path );
root_set_path= g_strdup_printf(
"/etc/spacefm/%d-as-root", geteuid() );
if ( !g_file_test( root_set_path, G_FILE_TEST_EXISTS ) )
root_set_change = TRUE;
}
*/
if ( root_set_change )
{
// task
xset_msg_dialog( GTK_WIDGET( dlg ), 0, _("Save Root Settings"), NULL, 0, _("You will now be asked for your root password to save the root settings for this user to a file in /etc/spacefm/ Supplying the password in the next window is recommended. Because SpaceFM runs some commands as root via su, these settings are best protected by root."), NULL, NULL );
PtkFileTask* task = ptk_file_exec_new( _("Save Root Settings"), NULL, NULL,
NULL );
task->task->exec_command = g_strdup_printf( "echo" );
task->task->exec_as_user = g_strdup_printf( "root" );
task->task->exec_sync = FALSE;
task->task->exec_export = FALSE;
task->task->exec_write_root = TRUE;
ptk_file_task_run( task );
}
}
}
gtk_widget_destroy( GTK_WIDGET( dlg ) );
g_free( data );
data = NULL;
pcmanfm_unref();
}
void on_date_format_changed( GtkComboBox *widget, FMPrefDlg* data )
{
char buf[ 128 ];
const char* etext;
time_t now = time( NULL );
etext = gtk_entry_get_text( GTK_ENTRY( gtk_bin_get_child( GTK_BIN( data->date_format ) ) ) );
strftime( buf, sizeof( buf ), etext, localtime( &now ) );
gtk_label_set_text( GTK_LABEL( data->date_display ), buf );
}
void on_show_thumbnail_toggled( GtkWidget* widget, FMPrefDlg* data )
{
gtk_widget_set_sensitive( data->max_thumb_size,
gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( data->show_thumbnail ) ) );
gtk_widget_set_sensitive( data->thumb_label1,
gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( data->show_thumbnail ) ) );
gtk_widget_set_sensitive( data->thumb_label2,
gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( data->show_thumbnail ) ) );
}
gboolean fm_edit_preference( GtkWindow* parent, int page )
{
const char* filename_encoding;
int i;
int ibig_icon = -1, ismall_icon = -1, itool_icon = -1;
GtkWidget* img_preview;
GtkWidget* dlg;
if( ! data )
{
GtkTreeModel* model;
// this invokes GVFS-RemoteVolumeMonitor via IsSupported
#if GTK_CHECK_VERSION(2, 24, 0)
GtkBuilder* builder = _gtk_builder_new_from_file( PACKAGE_UI_DIR "/prefdlg2.ui", NULL );
#else
GtkBuilder* builder = _gtk_builder_new_from_file( PACKAGE_UI_DIR "/prefdlg.ui", NULL );
#endif
if ( !builder )
return FALSE;
pcmanfm_ref();
data = g_new0( FMPrefDlg, 1 );
dlg = (GtkWidget*)gtk_builder_get_object( builder, "dlg" );
if ( parent )
gtk_window_set_transient_for( GTK_WINDOW( dlg ), parent );
xset_set_window_icon( GTK_WINDOW( dlg ) );
ptk_dialog_fit_small_screen( GTK_DIALOG( dlg ) );
data->dlg = dlg;
data->notebook = (GtkWidget*)gtk_builder_get_object( builder, "notebook" );
gtk_dialog_set_alternative_button_order( GTK_DIALOG( dlg ), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1 );
/* Setup 'General' tab */
data->encoding = (GtkWidget*)gtk_builder_get_object( builder, "filename_encoding" );
data->bm_open_method = (GtkWidget*)gtk_builder_get_object( builder, "bm_open_method" );
data->show_thumbnail = (GtkWidget*)gtk_builder_get_object( builder, "show_thumbnail" );
data->thumb_label1 = (GtkWidget*)gtk_builder_get_object( builder, "thumb_label1" );
data->thumb_label2 = (GtkWidget*)gtk_builder_get_object( builder, "thumb_label2" );
data->max_thumb_size = (GtkWidget*)gtk_builder_get_object( builder, "max_thumb_size" );
data->terminal = (GtkWidget*)gtk_builder_get_object( builder, "terminal" );
data->big_icon_size = (GtkWidget*)gtk_builder_get_object( builder, "big_icon_size" );
data->small_icon_size = (GtkWidget*)gtk_builder_get_object( builder, "small_icon_size" );
data->tool_icon_size = (GtkWidget*)gtk_builder_get_object( builder, "tool_icon_size" );
data->single_click = (GtkWidget*)gtk_builder_get_object( builder, "single_click" );
data->use_si_prefix = (GtkWidget*)gtk_builder_get_object( builder, "use_si_prefix" );
//data->rubberband = (GtkWidget*)gtk_builder_get_object( builder, "rubberband" );
data->root_bar = (GtkWidget*)gtk_builder_get_object( builder, "root_bar" );
data->drag_action = (GtkWidget*)gtk_builder_get_object( builder, "drag_action" );
model = GTK_TREE_MODEL( gtk_list_store_new( 1, G_TYPE_STRING ) );
gtk_combo_box_set_model( GTK_COMBO_BOX( data->terminal ), model );
gtk_combo_box_set_entry_text_column( GTK_COMBO_BOX( data->terminal ), 0 );
g_object_unref( model );
//if ( '\0' == ( char ) app_settings.encoding[ 0 ] )
// gtk_entry_set_text( GTK_ENTRY( data->encoding ), "UTF-8" );
//else
// gtk_entry_set_text( GTK_ENTRY( data->encoding ), app_settings.encoding );
/*
if ( app_settings.open_bookmark_method >= 1 &&
app_settings.open_bookmark_method <= 2 )
{
gtk_combo_box_set_active( GTK_COMBO_BOX( data->bm_open_method ),
app_settings.open_bookmark_method - 1 );
}
else
{
gtk_combo_box_set_active( GTK_COMBO_BOX( data->bm_open_method ), 0 );
}
*/
gtk_spin_button_set_value ( GTK_SPIN_BUTTON( data->max_thumb_size ),
app_settings.max_thumb_size >> 10 );
gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON( data->show_thumbnail ),
app_settings.show_thumbnail );
g_signal_connect( data->show_thumbnail, "toggled",
G_CALLBACK( on_show_thumbnail_toggled ), data );
gtk_widget_set_sensitive( data->max_thumb_size, app_settings.show_thumbnail );
gtk_widget_set_sensitive( data->thumb_label1, app_settings.show_thumbnail );
gtk_widget_set_sensitive( data->thumb_label2, app_settings.show_thumbnail );
for ( i = 0; i < G_N_ELEMENTS( terminal_programs ); ++i )
{
gtk_combo_box_text_append_text ( GTK_COMBO_BOX_TEXT( data->terminal ), terminal_programs[ i ] );
}
char* terminal = xset_get_s( "main_terminal" );
if ( terminal )
{
for ( i = 0; i < G_N_ELEMENTS( terminal_programs ); ++i )
{
if ( 0 == strcmp( terminal_programs[ i ], terminal ) )
break;
}
if ( i >= G_N_ELEMENTS( terminal_programs ) )
{ /* Found */
gtk_combo_box_text_prepend_text ( GTK_COMBO_BOX_TEXT( data->terminal ), terminal );
i = 0;
}
gtk_combo_box_set_active( GTK_COMBO_BOX( data->terminal ), i );
}
for ( i = 0; i < G_N_ELEMENTS( big_icon_sizes ); ++i )
{
if ( big_icon_sizes[ i ] == app_settings.big_icon_size )
{
ibig_icon = i;
break;
}
}
gtk_combo_box_set_active( GTK_COMBO_BOX( data->big_icon_size ), ibig_icon );
for ( i = 0; i < G_N_ELEMENTS( small_icon_sizes ); ++i )
{
if ( small_icon_sizes[ i ] == app_settings.small_icon_size )
{
ismall_icon = i;
break;
}
}
gtk_combo_box_set_active( GTK_COMBO_BOX( data->small_icon_size ), ismall_icon );
//sfm
itool_icon = 0;
for ( i = 0; i < G_N_ELEMENTS( tool_icon_sizes ); ++i )
{
if ( tool_icon_sizes[ i ] == app_settings.tool_icon_size )
{
itool_icon = i;
break;
}
}
gtk_combo_box_set_active( GTK_COMBO_BOX( data->tool_icon_size ), itool_icon );
gtk_toggle_button_set_active( (GtkToggleButton*)data->single_click, app_settings.single_click );
/* Setup 'Interface' tab */
data->always_show_tabs = (GtkWidget*)gtk_builder_get_object( builder, "always_show_tabs" );
gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON( data->always_show_tabs ),
app_settings.always_show_tabs );
data->hide_close_tab_buttons = (GtkWidget*)gtk_builder_get_object( builder,
"hide_close_tab_buttons" );
gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON( data->hide_close_tab_buttons ),
app_settings.hide_close_tab_buttons );
/* data->hide_side_pane_buttons = (GtkWidget*)gtk_builder_get_object( builder, "hide_side_pane_buttons" );
gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON( data->hide_side_pane_buttons ),
app_settings.hide_side_pane_buttons );
*/
//data->hide_folder_content_border = (GtkWidget*)gtk_builder_get_object( builder, "hide_folder_content_border" );
//gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON( data->hide_folder_content_border ),
// app_settings.hide_folder_content_border );
//MOD Interface
data->confirm_delete = (GtkWidget*)gtk_builder_get_object( builder,
"confirm_delete" );
gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON( data->confirm_delete ),
!app_settings.no_confirm );
data->click_exec = (GtkWidget*)gtk_builder_get_object( builder,
"click_exec" );
gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON( data->click_exec ),
!app_settings.no_execute );
//gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON( data->rubberband ),
// xset_get_b( "rubberband" ) );
gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON( data->root_bar ),
xset_get_b( "root_bar" ) );
gtk_widget_set_sensitive( data->root_bar, geteuid() == 0 );
int drag_action = xset_get_int( "drag_action", "x" );
int drag_action_set = 0;
for ( i = 0; i < G_N_ELEMENTS( drag_actions ); ++i )
{
if ( drag_actions[ i ] == drag_action )
{
drag_action_set = i;
break;
}
}
gtk_combo_box_set_active( GTK_COMBO_BOX( data->drag_action ), drag_action_set );
/* Setup 'Desktop' tab */
gtk_toggle_button_set_active( (GtkToggleButton*)data->use_si_prefix, app_settings.use_si_prefix );
/*
data->show_desktop = (GtkWidget*)gtk_builder_get_object( builder, "show_desktop" );
g_signal_connect( data->show_desktop, "toggled",
G_CALLBACK(on_show_desktop_toggled), gtk_builder_get_object( builder, "desktop_page" ) );
gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( data->show_desktop ),
app_settings.show_desktop );
*/
data->show_wallpaper = (GtkWidget*)gtk_builder_get_object( builder, "show_wallpaper" );
gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( data->show_wallpaper ),
app_settings.show_wallpaper );
data->wallpaper = (GtkWidget*)gtk_builder_get_object( builder, "wallpaper" );
img_preview = gtk_image_new();
gtk_widget_set_size_request( img_preview, 128, 128 );
gtk_file_chooser_set_preview_widget( (GtkFileChooser*)data->wallpaper, img_preview );
g_signal_connect( data->wallpaper, "update-preview", G_CALLBACK(on_update_img_preview), img_preview );
if ( app_settings.wallpaper )
{
/* FIXME: GTK+ has a known bug here. Sometimes it doesn't update the preview... */
set_preview_image( GTK_IMAGE( img_preview ), app_settings.wallpaper ); /* so, we do it manually */
gtk_file_chooser_set_filename( GTK_FILE_CHOOSER( data->wallpaper ),
app_settings.wallpaper );
}
data->wallpaper_mode = (GtkWidget*)gtk_builder_get_object( builder, "wallpaper_mode" );
gtk_combo_box_set_active( (GtkComboBox*)data->wallpaper_mode, app_settings.wallpaper_mode );
data->show_wm_menu = (GtkWidget*)gtk_builder_get_object( builder, "show_wm_menu" );
gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( data->show_wm_menu ),
app_settings.show_wm_menu );
data->bg_color1 = (GtkWidget*)gtk_builder_get_object( builder, "bg_color1" );
data->text_color = (GtkWidget*)gtk_builder_get_object( builder, "text_color" );
data->shadow_color = (GtkWidget*)gtk_builder_get_object( builder, "shadow_color" );
gtk_color_button_set_color(GTK_COLOR_BUTTON(data->bg_color1),
&app_settings.desktop_bg1);
gtk_color_button_set_color(GTK_COLOR_BUTTON(data->text_color),
&app_settings.desktop_text);
gtk_color_button_set_color(GTK_COLOR_BUTTON(data->shadow_color),
&app_settings.desktop_shadow);
//MOD Advanced
// su
int set_x;
GtkTreeIter it;
char* custom_su = NULL;
char* set_su;
data->su_command = (GtkWidget*)gtk_builder_get_object( builder,
"su_command" );
set_su = xset_get_s( "su_command" );
if ( !set_su )
set_x = 0;
else
{
for ( i = 0; i < G_N_ELEMENTS( su_commands ); i++ )
{
if ( !strcmp( su_commands[i], set_su ) )
break;
}
if ( i == G_N_ELEMENTS( su_commands ) )
set_x = 0;
else
set_x = i;
}
gtk_combo_box_set_active( GTK_COMBO_BOX( data->su_command ), set_x );
if ( custom_su )
g_free( custom_su );
// gsu
char* custom_gsu = NULL;
char* set_gsu;
data->gsu_command = (GtkWidget*)gtk_builder_get_object( builder,
"gsu_command" );
set_gsu = xset_get_s( "gsu_command" );
#ifdef PREFERABLE_SUDO_PROG
custom_gsu = g_find_program_in_path( PREFERABLE_SUDO_PROG );
#endif
if ( custom_gsu )
{
GtkListStore* gsu_list = GTK_LIST_STORE( gtk_combo_box_get_model(
GTK_COMBO_BOX( data->gsu_command ) ) );
gtk_list_store_prepend( gsu_list, &it );
gtk_list_store_set( GTK_LIST_STORE( gsu_list ), &it, 0, custom_gsu, -1 );
}
if ( !set_gsu )
set_x = 0;
else if ( custom_gsu && !strcmp( custom_gsu, set_gsu ) )
set_x = 0;
else
{
for ( i = 0; i < G_N_ELEMENTS( gsu_commands ); i++ )
{
if ( !strcmp( gsu_commands[i], set_gsu ) )
break;
}
if ( i == G_N_ELEMENTS( gsu_commands ) )
set_x = 0;
else if ( custom_gsu )
set_x = i + 1;
else
set_x = i;
}
gtk_combo_box_set_active( GTK_COMBO_BOX( data->gsu_command ), set_x );
if ( custom_gsu )
g_free( custom_gsu );
// date format
data->date_format = (GtkWidget*)gtk_builder_get_object( builder,
"date_format" );
data->date_display = (GtkWidget*)gtk_builder_get_object( builder,
"label_date_disp" );
model = GTK_TREE_MODEL( gtk_list_store_new( 1, G_TYPE_STRING ) );
gtk_combo_box_set_model( GTK_COMBO_BOX( data->date_format ), model );
gtk_combo_box_set_entry_text_column( GTK_COMBO_BOX( data->date_format ), 0 );
g_object_unref( model );
for ( i = 0; i < G_N_ELEMENTS( date_formats ); ++i )
{
gtk_combo_box_text_append_text ( GTK_COMBO_BOX_TEXT( data->date_format ), date_formats[ i ] );
}
char* date_s = xset_get_s( "date_format" );
if ( date_s )
{
for ( i = 0; i < G_N_ELEMENTS( date_formats ); ++i )
{
if ( 0 == strcmp( date_formats[ i ], date_s ) )
break;
}
if ( i >= G_N_ELEMENTS( date_formats ) )
{
gtk_combo_box_text_prepend_text ( GTK_COMBO_BOX_TEXT( data->date_format ), date_s );
i = 0;
}
gtk_combo_box_set_active( GTK_COMBO_BOX( data->date_format ), i );
}
on_date_format_changed( NULL, data );
g_signal_connect( data->date_format, "changed", G_CALLBACK( on_date_format_changed),
data );
// editors
data->editor = (GtkWidget*)gtk_builder_get_object( builder,
"editor" );
if ( xset_get_s( "editor" ) )
gtk_entry_set_text( GTK_ENTRY( data->editor ), xset_get_s( "editor" ) );
data->editor_terminal = (GtkWidget*)gtk_builder_get_object( builder,
"editor_terminal" );
gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON( data->editor_terminal ),
xset_get_b( "editor" ) );
data->root_editor = (GtkWidget*)gtk_builder_get_object( builder,
"root_editor" );
if ( xset_get_s( "root_editor" ) )
gtk_entry_set_text( GTK_ENTRY( data->root_editor ), xset_get_s( "root_editor" ) );
data->root_editor_terminal = (GtkWidget*)gtk_builder_get_object( builder,
"root_editor_terminal" );
gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON( data->root_editor_terminal ),
xset_get_b( "root_editor" ) );
g_signal_connect( dlg, "response", G_CALLBACK(on_response), data );
g_object_unref( builder );
}
gtk_notebook_set_current_page( (GtkNotebook*)data->notebook, page );
gtk_window_present( (GtkWindow*)data->dlg );
return TRUE;
}
|
150 | ./spacefm/src/find-files.c | /*
* find-files.c
*
* Copyright 2008 PCMan <pcman.tw@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
/* FIXME: Currently this only works with GNU find-utils.
* Compatibility with other systems like BSD, need to be improved.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <glib/gi18n.h>
#include <gtk/gtk.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/wait.h>
#include "pcmanfm.h"
#include "glib-mem.h"
#include "vfs-dir.h"
#include "vfs-file-info.h"
#include "vfs-async-task.h"
#include "exo-tree-view.h"
#include "vfs-volume.h"
#include "main-window.h"
#include "settings.h"
#include "ptk-file-misc.h"
#include "ptk-utils.h"
enum
{
COL_ICON,
COL_NAME,
COL_DIR,
COL_SIZE,
COL_TYPE,
COL_MTIME,
COL_INFO,
N_RES_COLS
};
typedef struct _FindFile
{
GtkWidget* win;
GtkWidget* search_criteria;
GtkWidget* fn_pattern;
GtkWidget* fn_pattern_entry;
GtkWidget* fn_case_sensitive;
/* file content */
GtkWidget* fc_pattern;
GtkWidget* fc_case_sensitive;
GtkWidget* fc_use_regexp;
/* advanced options */
GtkWidget* search_hidden;
/* size & date */
GtkWidget* use_size_lower;
GtkWidget* use_size_upper;
GtkWidget* size_lower;
GtkWidget* size_upper;
GtkWidget* size_lower_unit;
GtkWidget* size_upper_unit;
GtkWidget* date_limit;
GtkWidget* date1;
GtkWidget* date2;
/* file types */
GtkWidget* all_files;
GtkWidget* text_files;
GtkWidget* img_files;
GtkWidget* audio_files;
GtkWidget* video_files;
/* places */
GtkListStore* places_list;
GtkWidget* places_view;
GtkWidget* add_folder_btn;
GtkWidget* remove_folder_btn;
GtkWidget* include_sub;
/* search result pane */
GtkWidget* search_result;
GtkWidget* result_view;
GtkListStore* result_list;
/* buttons */
GtkWidget* start_btn;
GtkWidget* stop_btn;
GtkWidget* again_btn;
GPid pid;
int stdo;
VFSAsyncTask* task;
}FindFile;
typedef struct
{
VFSFileInfo* fi;
char* dir_path;
}FoundFile;
static const char menu_def[] =
"<ui>"
"<popup name=\"Popup\">"
"<menuitem name=\"Open\" action=\"OpenAction\" />"
"<menuitem name=\"OpenFolder\" action=\"OpenFolderAction\" />"
"</popup>"
"</ui>";
static gboolean open_file( char* dir, GList* files, PtkFileBrowser* file_browser )
{
if( files )
{
ptk_open_files_with_app( dir, files, NULL, NULL, FALSE, TRUE );
//sfm open selected dirs
if ( file_browser )
{
GList * l;
gchar* full_path;
VFSFileInfo* file;
for ( l = files; l; l = l->next )
{
file = ( VFSFileInfo* ) l->data;
if ( G_UNLIKELY( ! file ) )
continue;
full_path = g_build_filename( dir,
vfs_file_info_get_name( file ),
NULL );
if ( G_LIKELY( full_path ) )
{
if ( g_file_test( full_path, G_FILE_TEST_IS_DIR ) )
{
ptk_file_browser_emit_open( file_browser,
full_path, PTK_OPEN_NEW_TAB );
}
g_free( full_path );
}
}
}
vfs_file_info_list_free( files ); //sfm moved free list to here
return TRUE;
}
return FALSE;
}
static void open_dir( char* dir, GList* files, FMMainWindow* w )
{
fm_main_window_add_new_tab( w, dir );
}
static void on_open_files( GtkAction* action, FindFile* data )
{
GtkTreeModel* model;
GtkTreeSelection* sel;
GtkTreeIter it;
GList *row, *rows, *sel_files;
GHashTable* hash;
GtkWidget* w;
VFSFileInfo* fi;
gboolean open_files_has_dir = FALSE; //sfm
PtkFileBrowser* file_browser = NULL; //sfm
gboolean open_files = TRUE;
if ( action )
open_files = (0 == strcmp( gtk_action_get_name(action), "OpenAction") );
sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( data->result_view ) );
rows = gtk_tree_selection_get_selected_rows( sel, &model );
if( ! rows )
return;
//sfm this frees list when new value inserted - caused segfault
//hash = g_hash_table_new_full( g_str_hash, g_str_equal, (GDestroyNotify)g_free, open_files ? (GDestroyNotify)vfs_file_info_list_free : NULL );
hash = g_hash_table_new_full( g_str_hash, g_str_equal, (GDestroyNotify)g_free, NULL );
for( row = rows; row; row = row->next )
{
char* dir;
GtkTreePath* tp = (GtkTreePath*)row->data;
if( gtk_tree_model_get_iter( model, &it, tp ) )
{
if( open_files ) /* open files */
gtk_tree_model_get( model, &it, COL_INFO, &fi, COL_DIR, &dir, -1 );
else /* open containing folders */
gtk_tree_model_get( model, &it, COL_DIR, &dir, -1 );
if( open_files )
{
GList *l;
l = g_hash_table_lookup( hash, dir );
l = g_list_prepend( l, vfs_file_info_ref(fi) );
g_hash_table_insert( hash, dir, l ); //sfm caused segfault with destroy function
if ( vfs_file_info_is_dir( fi ) ) //sfm
open_files_has_dir = TRUE;
}
else
{
if( g_hash_table_lookup( hash, dir ) )
g_free( dir );
g_hash_table_insert( hash, dir, NULL );
}
}
gtk_tree_path_free( tp );
}
g_list_free( rows );
if( open_files )
{
if ( open_files_has_dir )
{
w = GTK_WIDGET( fm_main_window_get_on_current_desktop() );
if( ! w )
{
w = fm_main_window_new();
gtk_window_set_default_size( GTK_WINDOW( w ), app_settings.width, app_settings.height );
}
gtk_window_present( (GtkWindow*)w );
file_browser = (PtkFileBrowser*)fm_main_window_get_current_file_browser(
(FMMainWindow*)w );
}
g_hash_table_foreach_steal( hash, (GHRFunc)open_file, file_browser );
}
else
{
w = GTK_WIDGET( fm_main_window_get_on_current_desktop() );
if( ! w )
{
w = fm_main_window_new();
gtk_window_set_default_size( GTK_WINDOW( w ), app_settings.width, app_settings.height );
}
g_hash_table_foreach( hash, (GHFunc)open_dir, w );
gtk_window_present( (GtkWindow*)w );
}
g_hash_table_destroy( hash );
}
static GtkActionEntry menu_actions[] =
{
{ "OpenAction", GTK_STOCK_OPEN, N_("_Open"), NULL, NULL, G_CALLBACK(on_open_files) },
{ "OpenFolderAction", GTK_STOCK_OPEN, N_("Open Containing _Folder"), NULL, NULL, G_CALLBACK(on_open_files) }
};
static int get_date_offset( GtkCalendar* calendar )
{
/* FIXME: I think we need a better implementation for this */
GDate* date;
GDate* today;
int y, m, d, offset;
time_t timeval = time(NULL);
struct tm* lt = localtime( &timeval );
gtk_calendar_get_date( calendar, &y, &m, &d );
date = g_date_new_dmy( d, m, y );
today = g_date_new_dmy( lt->tm_mday, lt->tm_mon, lt->tm_year+1900 );
offset = g_date_days_between( date, today );
g_date_free(date);
g_date_free(today);
return ABS(offset);
}
static char** compose_command( FindFile* data )
{
GArray* argv = g_array_sized_new( TRUE, TRUE, sizeof(char*), 10 );
char *arg, *tmp;
GtkTreeIter it;
char size_units[] = {"ckMG"};
int idx;
gboolean print = FALSE;
arg = g_strdup( "find" );
g_array_append_val( argv, arg );
arg = g_strdup("-H");
g_array_append_val( argv, arg );
if( gtk_tree_model_get_iter_first( GTK_TREE_MODEL( data->places_list ), &it ) )
{
do {
gtk_tree_model_get( GTK_TREE_MODEL( data->places_list ), &it, 0, &arg, -1 );
if( arg )
{
if( *arg )
g_array_append_val( argv, arg );
else
g_free( arg );
}
}while( gtk_tree_model_iter_next( GTK_TREE_MODEL( data->places_list ), &it ) );
}
/* if include sub is excluded */ //MOD added
if( ! gtk_toggle_button_get_active((GtkToggleButton*)data->include_sub ) )
{
arg = g_strdup("-maxdepth");
g_array_append_val( argv, arg );
arg = g_strdup("1");
g_array_append_val( argv, arg );
}
/* if hidden files is excluded */
if( ! gtk_toggle_button_get_active((GtkToggleButton*)data->search_hidden ) )
{
arg = g_strdup("-name");
g_array_append_val( argv, arg );
arg = g_strdup(".*");
g_array_append_val( argv, arg );
arg = g_strdup("-prune");
g_array_append_val( argv, arg );
arg = g_strdup("-or");
g_array_append_val( argv, arg );
}
/* if lower limit of file size is set */
if( gtk_toggle_button_get_active((GtkToggleButton*)data->use_size_lower ) )
{
// arg = g_strdup("(");
// g_array_append_val( argv, arg );
arg = g_strdup("-size");
g_array_append_val( argv, arg );
tmp = g_strdup_printf( "+%u%c",
gtk_spin_button_get_value_as_int( (GtkSpinButton*)data->size_lower ),
size_units[ gtk_combo_box_get_active( (GtkComboBox*)data->size_lower_unit ) ] );
g_array_append_val( argv, tmp );
/* arg = g_strdup( tmp + 1 );
g_array_append_val( argv, arg );
arg = g_strdup("-o"); // -or
g_array_append_val( argv, arg );
arg = g_strdup("-size");
g_array_append_val( argv, arg );
g_array_append_val( argv, tmp );
arg = g_strdup(")");
g_array_append_val( argv, arg );
*/ }
/* if upper limit of file size is set */
if( gtk_toggle_button_get_active((GtkToggleButton*)data->use_size_upper ) )
{
// arg = g_strdup("(");
// g_array_append_val( argv, arg );
arg = g_strdup("-size");
g_array_append_val( argv, arg );
tmp = g_strdup_printf( "-%u%c",
gtk_spin_button_get_value_as_int( (GtkSpinButton*)data->size_upper ),
size_units[ gtk_combo_box_get_active( (GtkComboBox*)data->size_upper_unit ) ] );
arg = g_strdup( tmp + 1 );
g_array_append_val( argv, arg );
/*
arg = g_strdup("-o"); // -or
g_array_append_val( argv, arg );
arg = g_strdup("-size");
g_array_append_val( argv, arg );
g_array_append_val( argv, tmp );
arg = g_strdup(")");
g_array_append_val( argv, arg );
*/
}
/* If -name is used */
tmp = (char*)gtk_entry_get_text( (GtkEntry*)data->fn_pattern_entry );
if( tmp && strcmp(tmp, "*") )
{
if( gtk_toggle_button_get_active((GtkToggleButton*)data->fn_case_sensitive) )
arg = g_strdup("-name");
else
arg = g_strdup("-iname");
g_array_append_val( argv, arg );
arg = g_strdup( tmp );
g_array_append_val( argv, arg );
}
/* match by mtime */
idx = gtk_combo_box_get_active( (GtkComboBox*)data->date_limit );
if( idx > 0 )
{
if( idx == 5 ) /* range */
{
arg = g_strdup("(");
g_array_append_val( argv, arg );
arg = g_strdup( "-mtime" );
g_array_append_val( argv, arg );
/* date1 */
arg = g_strdup_printf( "-%d", get_date_offset( (GtkCalendar*)data->date1 ) );
g_array_append_val( argv, arg );
arg = g_strdup( "-mtime" );
g_array_append_val( argv, arg );
/* date2 */
arg = g_strdup_printf( "+%d", get_date_offset( (GtkCalendar*)data->date2 ) );
g_array_append_val( argv, arg );
arg = g_strdup(")");
g_array_append_val( argv, arg );
}
else
{
arg = g_strdup( "-mtime" );
g_array_append_val( argv, arg );
switch( idx )
{
case 1: /* within one day */
arg = g_strdup( "-1" );
break;
case 2: /* within one week */
arg = g_strdup( "-7" );
break;
case 3: /* within one month */
arg = g_strdup( "-30" );
break;
case 4: /* within one year */
arg = g_strdup( "-365" );
break;
}
g_array_append_val( argv, arg );
}
}
/* grep text inside files */
tmp = (char*)gtk_entry_get_text( (GtkEntry*)data->fc_pattern );
if( tmp && *tmp )
{
print = TRUE;
/* ensure we only call 'grep' on regular files */
arg = g_strdup("-type");
g_array_append_val( argv, arg );
arg = g_strdup("f");
g_array_append_val( argv, arg );
arg = g_strdup("-exec");
g_array_append_val( argv, arg );
arg = g_strdup("grep");
g_array_append_val( argv, arg );
if( !gtk_toggle_button_get_active((GtkToggleButton*)data->fc_case_sensitive) )
{
arg = g_strdup("-i");
g_array_append_val( argv, arg );
}
arg = g_strdup("--files-with-matches");
g_array_append_val( argv, arg );
if( gtk_toggle_button_get_active((GtkToggleButton*)data->fc_use_regexp) )
arg = g_strdup( "--regexp" );
else
arg = g_strdup( "--fixed-strings" );
g_array_append_val( argv, arg );
arg = g_strdup(tmp);
g_array_append_val( argv, arg );
arg = g_strdup("{}");
g_array_append_val( argv, arg );
arg = g_strdup(";");
g_array_append_val( argv, arg );
}
if( ! print )
{
arg = g_strdup("-print");
g_array_append_val( argv, arg );
}
return (char**)g_array_free( argv, FALSE );
}
static void finish_search( FindFile* data )
{
if( data->pid )
{
int status;
kill( data->pid, SIGTERM );
waitpid( data->pid, &status, 0 );
data->pid = 0;
/* g_debug( "find process is killed!" ); */
}
if( data->task )
{
g_object_unref( data->task );
data->task = NULL;
}
gdk_window_set_cursor( gtk_widget_get_window( data->search_result ), NULL );
gtk_widget_hide( data->stop_btn );
gtk_widget_show( data->again_btn );
}
static void process_found_files( FindFile* data, GQueue* queue, const char* path )
{
char *name;
gsize len, term;
GtkTreeIter it;
VFSFileInfo* fi;
GdkPixbuf* icon;
FoundFile* ff;
if( path )
{
name = g_filename_display_basename( path );
fi = vfs_file_info_new();
if( vfs_file_info_get( fi, path, name ) )
{
ff = g_slice_new0( FoundFile );
ff->fi = fi;
ff->dir_path = g_path_get_dirname( path );
g_queue_push_tail( queue, ff );
}
else
{
vfs_file_info_unref( fi );
}
g_free( name );
/* we queue the found files, and not add them to the tree view direclty.
* when we queued more than 10 files, we add them at once. I think
* this can prevent locking gtk+ too frequently and improve responsiveness.
* FIXME: This could blocked the last queued files and delay their display
* to the end of the whole search. A better method is needed.
*/
//MOD disabled this - causes last queued files to not display
// if( g_queue_get_length( queue ) < 10 )
// return;
}
while( ff = (FoundFile*)g_queue_pop_head(queue) )
{
GDK_THREADS_ENTER();
gtk_list_store_append( data->result_list, &it );
icon = vfs_file_info_get_small_icon( ff->fi );
gtk_list_store_set( data->result_list, &it,
COL_ICON, icon,
COL_NAME, vfs_file_info_get_disp_name(ff->fi),
COL_DIR, ff->dir_path, /* FIXME: non-UTF8? */
COL_TYPE, vfs_file_info_get_mime_type_desc( ff->fi ),
COL_SIZE, vfs_file_info_get_disp_size( ff->fi ),
COL_MTIME, vfs_file_info_get_disp_mtime( ff->fi ),
COL_INFO, ff->fi, -1 );
g_object_unref( icon );
GDK_THREADS_LEAVE();
g_slice_free( FoundFile, ff );
}
}
static gpointer search_thread( VFSAsyncTask* task, FindFile* data )
{
ssize_t rlen;
char buf[4096 ];
GString* path = g_string_new_len( NULL, 256 );
GQueue* queue = g_queue_new();
while( ! data->task->cancel && ( rlen = read( data->stdo, buf, sizeof(buf) - 1 ) ) > 0 )
{
char*pbuf, *eol;
buf[ rlen ] = '\0';
pbuf = buf;
while( ! data->task->cancel )
{
if( eol = strchr( pbuf, '\n' ) ) /* end of line is reached */
{
*eol = '\0';
g_string_append( path, pbuf );
/* we get a complete file path */
if( ! data->task->cancel )
{
process_found_files( data, queue, path->str );
}
pbuf = eol + 1; /* start reading the next line */
g_string_assign( path, "" ); /* empty the line buffer */
}
else /* end of line is not reached */
{
g_string_append( path, pbuf ); /* store the partial path in the buffer */
break;
}
}
}
/* end of stream (EOF) is reached */
if( path->len > 0 ) /* this is the last line without eol character '\n' */
{
if( ! data->task->cancel )
{
process_found_files( data, queue, path->str );
process_found_files( data, queue, NULL );
}
}
g_queue_free( queue );
g_string_free( path, TRUE );
return NULL;
}
static void on_search_finish( VFSAsyncTask* task, gboolean cancelled, FindFile* data )
{
finish_search( data );
}
static void on_start_search( GtkWidget* btn, FindFile* data )
{
char** argv;
GError* err = NULL;
int stdo, stde;
char* cmd_line;
GtkAllocation allocation;
gtk_widget_get_allocation ( GTK_WIDGET( data->win ), &allocation );
int width = allocation.width;
int height = allocation.height;
if ( width && height )
{
char* str = g_strdup_printf( "%d", width );
xset_set( "main_search", "x", str );
g_free( str );
str = g_strdup_printf( "%d", height );
xset_set( "main_search", "y", str );
g_free( str );
}
gtk_widget_hide( data->search_criteria );
gtk_widget_show( data->search_result );
gtk_widget_hide( btn );
gtk_widget_show( data->stop_btn );
argv = compose_command( data );
cmd_line = g_strjoinv( " ", argv );
g_debug( "find command: %s", cmd_line );
g_free( cmd_line );
if( g_spawn_async_with_pipes( g_get_home_dir(), argv, NULL,
G_SPAWN_SEARCH_PATH | G_SPAWN_STDERR_TO_DEV_NULL,
NULL, NULL, &data->pid,
NULL, &data->stdo, NULL, &err ) )
{
GdkCursor* busy_cursor;
data->task = vfs_async_task_new( (VFSAsyncFunc)search_thread, data );
g_signal_connect( data->task, "finish", G_CALLBACK( on_search_finish ), data );
vfs_async_task_execute( data->task );
busy_cursor = gdk_cursor_new( GDK_WATCH );
gdk_window_set_cursor( gtk_widget_get_window (data->search_result), busy_cursor );
gdk_cursor_unref( busy_cursor );
}
else
{
g_error_free( err );
}
g_strfreev( argv );
}
static void on_stop_search( GtkWidget* btn, FindFile* data )
{
if( data->task && ! vfs_async_task_is_finished( data->task ) )
{
// see note in vfs-async-task.c: vfs_async_task_real_cancel()
GDK_THREADS_LEAVE();
vfs_async_task_cancel( data->task );
GDK_THREADS_ENTER();
}
}
static void on_search_again( GtkWidget* btn, FindFile* data )
{
GtkAllocation allocation;
gtk_widget_get_allocation ( GTK_WIDGET( data->win ), &allocation );
int width = allocation.width;
int height = allocation.height;
if ( width && height )
{
char* str = g_strdup_printf( "%d", width );
xset_set( "main_search", "x", str );
g_free( str );
str = g_strdup_printf( "%d", height );
xset_set( "main_search", "y", str );
g_free( str );
}
gtk_widget_show( data->search_criteria );
gtk_widget_hide( data->search_result );
gtk_widget_hide( btn );
gtk_widget_show( data->start_btn );
g_object_ref( data->result_list );
gtk_tree_view_set_model( (GtkTreeView*)data->result_view, NULL );
gtk_list_store_clear( data->result_list );
gtk_tree_view_set_model( (GtkTreeView*)data->result_view, GTK_TREE_MODEL( data->result_list ) );
g_object_unref( data->result_list );
}
static void menu_pos( GtkMenu* menu, int* x, int* y, gboolean *push_in, GtkWidget* btn )
{
GtkAllocation allocation;
/* FIXME: I'm not sure if this work well in different WMs */
gdk_window_get_position( gtk_widget_get_window( btn ), x, y);
/* gdk_window_get_root_origin( btn->window, x, y); */
gtk_widget_get_allocation ( GTK_WIDGET( btn ), &allocation );
*x += allocation.x;
*y += allocation.y + allocation.height;
*push_in = FALSE;
}
static void add_search_dir( FindFile* data, const char* path )
{
GtkTreeIter it;
gtk_list_store_append( data->places_list, &it );
gtk_list_store_set( data->places_list, &it, 0, path, -1 );
}
static void on_add_search_browse(GtkWidget* menu, FindFile* data)
{
GtkWidget* dlg = gtk_file_chooser_dialog_new(
_("Select a folder"), GTK_WINDOW( data->win ),
GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
GTK_STOCK_OPEN, GTK_RESPONSE_OK,
NULL );
gtk_dialog_set_alternative_button_order( GTK_DIALOG( dlg ), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL );
if( gtk_dialog_run( GTK_DIALOG( dlg ) ) == GTK_RESPONSE_OK )
{
char* path = gtk_file_chooser_get_filename( GTK_FILE_CHOOSER( dlg ) );
add_search_dir( data, path );
g_free( path );
}
gtk_widget_destroy( dlg );
}
static void on_add_search_home(GtkWidget* menu, FindFile* data)
{
add_search_dir( data, g_get_home_dir() );
}
static void on_add_search_desktop(GtkWidget* menu, FindFile* data)
{
add_search_dir( data, vfs_get_desktop_dir() );
}
static void on_add_search_volumes(GtkWidget* menu, FindFile* data)
{
const char* path;
const GList* vols = vfs_volume_get_all_volumes(), *l;
for( l = vols; l; l = l->next )
{
VFSVolume* vol = (VFSVolume*)l->data;
if ( vfs_volume_is_mounted( vol ) )
{
path = vfs_volume_get_mount_point( vol );
if ( path && path[0] != '\0' )
add_search_dir( data, path );
}
}
}
static void on_add_search_folder( GtkWidget* btn, FindFile* data )
{
GtkWidget* menu = gtk_menu_new();
GtkWidget* item;
GtkWidget* img;
const char* dir;
item = gtk_image_menu_item_new_with_label( _("Browse...") );
gtk_menu_shell_append( GTK_MENU_SHELL( menu ), item );
g_signal_connect( item, "activate", G_CALLBACK(on_add_search_browse), data );
item = gtk_separator_menu_item_new();
gtk_menu_shell_append( GTK_MENU_SHELL( menu ), item );
item = gtk_image_menu_item_new_with_label( g_get_home_dir() );
//img = gtk_image_new_from_icon_name( "gnome-fs-directory", GTK_ICON_SIZE_MENU );
img = xset_get_image( "gtk-directory", GTK_ICON_SIZE_MENU );
gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM( item ), img );
gtk_menu_shell_append( GTK_MENU_SHELL( menu ), item );
g_signal_connect( item, "activate", G_CALLBACK(on_add_search_home), data );
if( dir = vfs_get_desktop_dir() )
{
item = gtk_image_menu_item_new_with_label( dir );
//img = gtk_image_new_from_icon_name( "gnome-fs-desktop", GTK_ICON_SIZE_MENU );
img = xset_get_image( "gtk-directory", GTK_ICON_SIZE_MENU );
gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM( item ), img );
gtk_menu_shell_append( GTK_MENU_SHELL( menu ), item );
g_signal_connect( item, "activate", G_CALLBACK(on_add_search_desktop), data );
}
item = gtk_image_menu_item_new_with_label( _("Local Volumes") );
//img = gtk_image_new_from_icon_name( "gnome-dev-harddisk", GTK_ICON_SIZE_MENU );
img = xset_get_image( "gtk-harddisk", GTK_ICON_SIZE_MENU );
gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM( item ), img );
gtk_menu_shell_append( GTK_MENU_SHELL( menu ), item );
g_signal_connect( item, "activate", G_CALLBACK(on_add_search_volumes), data );
/* FIXME: Add all volumes */
/* FIXME: Add all bookmarks */
gtk_widget_show_all( menu );
gtk_menu_popup( GTK_MENU( menu ), NULL, NULL, (GtkMenuPositionFunc)menu_pos,
btn, 0, gtk_get_current_event_time() );
}
static void on_remove_search_folder( GtkWidget* btn, FindFile* data )
{
GtkTreeIter it;
GtkTreeSelection* sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( data->places_view ) );
if( gtk_tree_selection_get_selected(sel, NULL, &it) )
gtk_list_store_remove( data->places_list, &it );
}
static void on_date_limit_changed( GtkWidget* date_limit, FindFile* data )
{
int sel = gtk_combo_box_get_active( (GtkComboBox*)date_limit );
gboolean sensitive = ( sel == 5 ); /* date range */
gtk_widget_set_sensitive( data->date1, sensitive );
gtk_widget_set_sensitive( data->date2, sensitive );
}
static void free_data( FindFile* data )
{
g_slice_free( FindFile, data );
}
static void init_search_result( FindFile* data )
{
GtkTreeIter it;
GtkTreeViewColumn* col;
GtkCellRenderer* render;
gtk_tree_selection_set_mode( gtk_tree_view_get_selection((GtkTreeView*)data->result_view),
GTK_SELECTION_MULTIPLE );
data->result_list = gtk_list_store_new( N_RES_COLS,
GDK_TYPE_PIXBUF, /* icon */
G_TYPE_STRING, /* name */
G_TYPE_STRING, /* dir */
G_TYPE_STRING, /* type */
G_TYPE_STRING, /* size */
G_TYPE_STRING, /* mtime */
G_TYPE_POINTER /* VFSFileInfo */ );
gtk_tree_view_set_model( (GtkTreeView*)data->result_view, (GtkTreeModel*)data->result_list );
g_object_unref( data->result_list );
col = gtk_tree_view_column_new();
gtk_tree_view_column_set_title( col, _("Name") );
render = gtk_cell_renderer_pixbuf_new();
gtk_tree_view_column_pack_start( col, render, FALSE );
gtk_tree_view_column_set_attributes( col, render, "pixbuf", COL_ICON, NULL );
render = gtk_cell_renderer_text_new();
g_object_set( render, "ellipsize", PANGO_ELLIPSIZE_END, NULL );
gtk_tree_view_column_pack_start( col, render, TRUE );
gtk_tree_view_column_set_attributes( col, render, "text", COL_NAME, NULL );
gtk_tree_view_column_set_expand ( col, TRUE );
gtk_tree_view_column_set_min_width( col, 200 );
gtk_tree_view_column_set_resizable ( col, TRUE );
gtk_tree_view_append_column( (GtkTreeView*)data->result_view, col );
render = gtk_cell_renderer_text_new();
g_object_set( render, "ellipsize", PANGO_ELLIPSIZE_END, NULL );
col = gtk_tree_view_column_new_with_attributes( _("Folder"), render, "text", COL_DIR, NULL );
gtk_tree_view_column_set_expand ( col, TRUE );
gtk_tree_view_column_set_resizable ( col, TRUE );
gtk_tree_view_column_set_min_width( col, 200 );
gtk_tree_view_append_column( (GtkTreeView*)data->result_view, col );
col = gtk_tree_view_column_new_with_attributes( _("Size"), gtk_cell_renderer_text_new(), "text", COL_SIZE, NULL );
gtk_tree_view_column_set_resizable ( col, TRUE );
gtk_tree_view_append_column( (GtkTreeView*)data->result_view, col );
col = gtk_tree_view_column_new_with_attributes( _("Type"), gtk_cell_renderer_text_new(), "text", COL_TYPE, NULL );
gtk_tree_view_column_set_sizing( col, GTK_TREE_VIEW_COLUMN_FIXED );
gtk_tree_view_column_set_fixed_width ( col, 120 );
gtk_tree_view_column_set_resizable ( col, TRUE );
gtk_tree_view_append_column( (GtkTreeView*)data->result_view, col );
col = gtk_tree_view_column_new_with_attributes( _("Last Modified"), gtk_cell_renderer_text_new(), "text", COL_MTIME, NULL );
gtk_tree_view_column_set_resizable ( col, TRUE );
gtk_tree_view_append_column( (GtkTreeView*)data->result_view, col );
}
static gboolean on_view_button_press( GtkTreeView* view, GdkEventButton* evt, FindFile* data )
{
if( evt->type == GDK_BUTTON_PRESS )
{
if( evt->button == 3 ) /* right single click */
{
//sfm if current item not selected, unselect all and select it
GtkTreePath *tree_path;
GtkTreeSelection* tree_sel;
gtk_tree_view_get_path_at_pos( GTK_TREE_VIEW( view ),
evt->x, evt->y, &tree_path, NULL, NULL, NULL );
tree_sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( view ) );
if ( tree_path && tree_sel &&
!gtk_tree_selection_path_is_selected( tree_sel, tree_path ) )
{
gtk_tree_selection_unselect_all( tree_sel );
gtk_tree_selection_select_path( tree_sel, tree_path );
}
gtk_tree_path_free( tree_path );
GtkWidget* popup;
GtkUIManager* menu_mgr;
GtkActionGroup* action_group = gtk_action_group_new ("PopupActions");
gtk_action_group_set_translation_domain( action_group, GETTEXT_PACKAGE );
menu_mgr = gtk_ui_manager_new ();
gtk_action_group_add_actions( action_group, menu_actions, G_N_ELEMENTS(menu_actions), data );
gtk_ui_manager_insert_action_group( menu_mgr, action_group, 0 );
gtk_ui_manager_add_ui_from_string( menu_mgr, menu_def, -1, NULL );
popup = gtk_ui_manager_get_widget( menu_mgr, "/Popup" );
g_object_unref( action_group );
gtk_menu_popup( GTK_MENU( popup ), NULL, NULL, NULL, NULL, evt->button, evt->time );
/* clean up */
g_signal_connect( popup, "selection-done", G_CALLBACK(gtk_widget_destroy), NULL );
g_object_weak_ref( G_OBJECT( popup ), (GWeakNotify)g_object_unref, menu_mgr );
return TRUE;
}
}
else if( evt->type == GDK_2BUTTON_PRESS )
{
if( evt->button == 1 ) /* left double click */
{
on_open_files( NULL, data );
return TRUE;
}
}
return FALSE;
}
void on_use_size_lower_toggled( GtkWidget* widget, FindFile* data )
{
gtk_widget_set_sensitive( data->size_lower,
gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( data->use_size_lower ) ) );
gtk_widget_set_sensitive( data->size_lower_unit,
gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( data->use_size_lower ) ) );
}
void on_use_size_upper_toggled( GtkWidget* widget, FindFile* data )
{
gtk_widget_set_sensitive( data->size_upper,
gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( data->use_size_upper ) ) );
gtk_widget_set_sensitive( data->size_upper_unit,
gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( data->use_size_upper ) ) );
}
void fm_find_files( const char** search_dirs )
{
FindFile* data = g_slice_new0(FindFile);
GtkTreeIter it;
GtkTreeViewColumn* col;
GtkWidget *add_folder_btn, *remove_folder_btn, *img;
#if GTK_CHECK_VERSION (3, 0, 0)
GtkBuilder* builder = _gtk_builder_new_from_file( PACKAGE_UI_DIR "/find-files2.ui", NULL );
#else
GtkBuilder* builder = _gtk_builder_new_from_file( PACKAGE_UI_DIR "/find-files.ui", NULL );
#endif
data->win = (GtkWidget*)gtk_builder_get_object( builder, "win" );
g_object_set_data_full( G_OBJECT( data->win ), "find-files", data, (GDestroyNotify)free_data );
GdkPixbuf* icon = NULL;
GtkIconTheme* theme = gtk_icon_theme_get_default();
if ( theme )
icon = gtk_icon_theme_load_icon( theme, "spacefm-find", 48, 0, NULL );
if ( icon )
{
gtk_window_set_icon( GTK_WINDOW( data->win ), icon );
g_object_unref( icon );
}
else
gtk_window_set_icon_name( GTK_WINDOW( data->win ), GTK_STOCK_FIND );
/* search criteria pane */
data->search_criteria = (GtkWidget*)gtk_builder_get_object( builder, "search_criteria" );
data->fn_pattern = (GtkWidget*)gtk_builder_get_object( builder, "fn_pattern" );
data->fn_pattern_entry = gtk_bin_get_child( GTK_BIN( data->fn_pattern ) );
data->fn_case_sensitive = (GtkWidget*)gtk_builder_get_object( builder, "fn_case_sensitive" );
gtk_entry_set_activates_default( (GtkEntry*)data->fn_pattern_entry, TRUE );
/* file content */
data->fc_pattern = (GtkWidget*)gtk_builder_get_object( builder, "fc_pattern" );
data->fc_case_sensitive = (GtkWidget*)gtk_builder_get_object( builder, "fc_case_sensitive" );
data->fc_use_regexp = (GtkWidget*)gtk_builder_get_object( builder, "fc_use_regexp" );
/* advanced options */
data->search_hidden = (GtkWidget*)gtk_builder_get_object( builder, "search_hidden" );
/* size & date */
data->use_size_lower = (GtkWidget*)gtk_builder_get_object( builder, "use_size_lower" );
data->use_size_upper = (GtkWidget*)gtk_builder_get_object( builder, "use_size_upper" );
data->size_lower = (GtkWidget*)gtk_builder_get_object( builder, "size_lower" );
data->size_upper = (GtkWidget*)gtk_builder_get_object( builder, "size_upper" );
data->size_lower_unit = (GtkWidget*)gtk_builder_get_object( builder, "size_lower_unit" );
data->size_upper_unit = (GtkWidget*)gtk_builder_get_object( builder, "size_upper_unit" );
g_signal_connect( data->use_size_lower, "toggled",
G_CALLBACK( on_use_size_lower_toggled ), data );
g_signal_connect( data->use_size_upper, "toggled",
G_CALLBACK( on_use_size_upper_toggled ), data );
on_use_size_lower_toggled( data->use_size_lower, data );
on_use_size_upper_toggled( data->use_size_upper, data );
data->date_limit = (GtkWidget*)gtk_builder_get_object( builder, "date_limit" );
data->date1 = (GtkWidget*)gtk_builder_get_object( builder, "date1" );
data->date2 = (GtkWidget*)gtk_builder_get_object( builder, "date2" );
g_signal_connect( data->date_limit, "changed", G_CALLBACK( on_date_limit_changed ), data );
/* file types */
data->all_files = (GtkWidget*)gtk_builder_get_object( builder, "all_files" );
data->text_files = (GtkWidget*)gtk_builder_get_object( builder, "text_files" );
data->img_files = (GtkWidget*)gtk_builder_get_object( builder, "img_files" );
data->audio_files = (GtkWidget*)gtk_builder_get_object( builder, "audio_files" );
data->video_files = (GtkWidget*)gtk_builder_get_object( builder, "video_files" );
/* places */
data->places_list = gtk_list_store_new( 1, G_TYPE_STRING );
data->places_view = (GtkWidget*)gtk_builder_get_object( builder, "places_view" );
add_folder_btn = (GtkWidget*)gtk_builder_get_object( builder, "add_folder_btn" );
remove_folder_btn = (GtkWidget*)gtk_builder_get_object( builder, "remove_folder_btn" );
data->include_sub = (GtkWidget*)gtk_builder_get_object( builder, "include_sub" );
if( search_dirs )
{
const char** dir;
for( dir = search_dirs; *dir; ++dir )
{
if( g_file_test( *dir, G_FILE_TEST_IS_DIR ) )
gtk_list_store_insert_with_values( data->places_list, &it, 0, 0, *dir, -1 );
}
}
gtk_tree_view_set_model( (GtkTreeView*)data->places_view, (GtkTreeModel*)data->places_list );
g_object_unref( data->places_list );
col = gtk_tree_view_column_new_with_attributes(NULL, gtk_cell_renderer_text_new(), "text", 0, NULL );
gtk_tree_view_append_column( (GtkTreeView*)data->places_view, col );
g_signal_connect(add_folder_btn, "clicked", G_CALLBACK( on_add_search_folder ), data );
g_signal_connect(remove_folder_btn, "clicked", G_CALLBACK( on_remove_search_folder ), data );
/* search result pane */
data->search_result = (GtkWidget*)gtk_builder_get_object( builder, "search_result" );
/* replace the problematic GtkTreeView with ExoTreeView */
data->result_view = exo_tree_view_new();
if( app_settings.single_click )
{
exo_tree_view_set_single_click( EXO_TREE_VIEW( data->result_view ), TRUE );
exo_tree_view_set_single_click_timeout( EXO_TREE_VIEW( data->result_view ),
SINGLE_CLICK_TIMEOUT );
}
gtk_widget_show( data->result_view );
gtk_container_add( (GtkContainer*)gtk_builder_get_object(builder, "result_scroll"), data->result_view );
init_search_result( data );
g_signal_connect(data->result_view, "button-press-event", G_CALLBACK( on_view_button_press ), data );
/* buttons */
data->start_btn = (GtkWidget*)gtk_builder_get_object( builder, "start_btn" );
data->stop_btn = (GtkWidget*)gtk_builder_get_object( builder, "stop_btn" );
data->again_btn = (GtkWidget*)gtk_builder_get_object( builder, "again_btn" );
img = gtk_image_new_from_icon_name( GTK_STOCK_REFRESH, GTK_ICON_SIZE_BUTTON );
gtk_button_set_image( (GtkButton*)data->again_btn, img );
g_signal_connect(data->start_btn, "clicked", G_CALLBACK( on_start_search ), data );
g_signal_connect(data->stop_btn, "clicked", G_CALLBACK( on_stop_search ), data );
g_signal_connect(data->again_btn, "clicked", G_CALLBACK( on_search_again ), data );
gtk_entry_set_text( (GtkEntry*)data->fn_pattern_entry, "*" );
gtk_editable_select_region( (GtkEditable*)data->fn_pattern_entry, 0, -1 );
gtk_combo_box_set_active( (GtkComboBox*)data->size_lower_unit, 1 );
gtk_spin_button_set_range( (GtkSpinButton*)data->size_lower, 0, G_MAXINT );
gtk_combo_box_set_active( (GtkComboBox*)data->size_upper_unit, 2 );
gtk_spin_button_set_range( (GtkSpinButton*)data->size_upper, 0, G_MAXINT );
gtk_combo_box_set_active( (GtkComboBox*)data->date_limit, 0 );
g_signal_connect( data->win, "delete-event", G_CALLBACK(gtk_widget_destroy), NULL );
pcmanfm_ref();
g_signal_connect( data->win, "destroy", G_CALLBACK(pcmanfm_unref), NULL );
int width = xset_get_int( "main_search", "x" );
int height = xset_get_int( "main_search", "y" );
if ( width && height )
gtk_window_set_default_size( GTK_WINDOW( data->win ), width, height );
gtk_widget_show( data->win );
}
|
151 | ./spacefm/src/compat/glib-utils.c | /*
* C++ Interface: glib-mem
*
* Description: Compatibility macros for older versions of glib
*
*
* Author: Hong Jen Yee (PCMan) <pcman.tw (AT) gmail.com>, (C) 2006
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#include "glib-utils.h"
/* older versions of glib don't provde these API */
#if ! GLIB_CHECK_VERSION(2, 8, 0)
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
int g_mkdir_with_parents(const gchar *pathname, int mode)
{
struct stat statbuf;
char *dir, *sep;
dir = g_strdup( pathname );
sep = dir[0] == '/' ? dir + 1 : dir;
do {
sep = strchr( sep, '/' );
if( G_LIKELY( sep ) )
*sep = '\0';
if( stat( dir, &statbuf) == 0 )
{
if( ! S_ISDIR(statbuf.st_mode) ) /* parent not dir */
goto err;
}
else /* stat failed */
{
if( errno == ENOENT ) /* not exists */
{
if( mkdir( dir, mode ) == -1 )
goto err;
}
else
goto err; /* unknown error */
}
if( G_LIKELY( sep ) )
{
*sep = '/';
++sep;
}
else
break;
}while( sep );
g_free( dir );
return 0;
err:
g_free( dir );
return -1;
}
#endif
#if ! GLIB_CHECK_VERSION(2, 16, 0)
#include <string.h>
int g_strcmp0(const char *str1, const char *str2)
{
if( G_UNLIKELY(str1 == str2) ) /* the same string or both NULL */
return 0;
if( G_UNLIKELY(str1 == NULL) ) /* str2 is non-NULL */
return -1;
else if( G_UNLIKELY(str2 == NULL) ) /* str1 is non-NULL */
return 1;
return strcmp( str1, str2 );
}
#endif
|
152 | ./spacefm/src/desktop/desktop.c | /*
* main.c - desktop manager of pcmanfm
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "desktop.h"
#ifdef DESKTOP_INTEGRATION
#include <gtk/gtk.h>
//#include "fm-desktop.h"
#include "vfs-file-info.h"
#include "vfs-mime-type.h"
//#include "vfs-app-desktop.h"
#include "vfs-file-monitor.h"
#include "vfs-volume.h"
#include "vfs-thumbnail-loader.h"
#include "vfs-dir.h"
#include "desktop-window.h"
#include "settings.h"
static GtkWindowGroup* group = NULL;
static GdkFilterReturn on_rootwin_event ( GdkXEvent *xevent, GdkEvent *event, gpointer data );
static GtkWidget **desktops = NULL;
static gint n_screens = 0;
static guint theme_change_notify = 0;
static void on_icon_theme_changed( GtkIconTheme* theme, gpointer data )
{
/* reload icons of desktop windows */
int i;
for ( i = 0; i < n_screens; i++ )
desktop_window_reload_icons( (DesktopWindow*)desktops[ i ] );
}
void fm_turn_on_desktop_icons()
{
GdkDisplay * gdpy;
gint i;
int big = 0;
if( ! group )
group = gtk_window_group_new();
theme_change_notify = g_signal_connect( gtk_icon_theme_get_default(), "changed",
G_CALLBACK(on_icon_theme_changed), NULL );
vfs_mime_type_get_icon_size( &big, NULL );
gdpy = gdk_display_get_default();
n_screens = gdk_display_get_n_screens( gdpy );
desktops = g_new( GtkWidget *, n_screens );
for ( i = 0; i < n_screens; i++ )
{
desktops[ i ] = desktop_window_new();
desktop_window_set_icon_size( (DesktopWindow*)desktops[ i ], big );
desktop_window_set_single_click( (DesktopWindow*)desktops[ i ], app_settings.single_click );
gtk_window_set_role( GTK_WINDOW( desktops[i] ), "desktop_manager" );
gtk_widget_realize( desktops[ i ] ); /* without this, setting wallpaper won't work */
gtk_widget_show_all( desktops[ i ] );
gdk_window_lower( gtk_widget_get_window(desktops[ i ]) );
gtk_window_group_add_window( GTK_WINDOW_GROUP(group), GTK_WINDOW( desktops[i] ) );
}
fm_desktop_update_colors();
fm_desktop_update_wallpaper();
}
void fm_turn_off_desktop_icons()
{
int i;
if( theme_change_notify )
{
g_signal_handler_disconnect( gtk_icon_theme_get_default(), theme_change_notify );
theme_change_notify = 0;
}
for ( i = 0; i < n_screens; i++ )
{
gtk_widget_destroy( desktops[ i ] );
/* gtk_window_group_remove_window() */
}
g_free( desktops );
// if ( busy_cursor > 0 )
// g_source_remove( busy_cursor );
g_object_unref( group );
group = NULL;
}
void fm_desktop_update_thumbnails()
{
/* FIXME: thumbnail on desktop cannot be turned off. */
}
void fm_desktop_update_wallpaper()
{
DWBgType type;
GdkPixbuf* pix;
int i;
if( app_settings.show_wallpaper && app_settings.wallpaper )
{
switch( app_settings.wallpaper_mode )
{
case WPM_FULL:
type = DW_BG_FULL;
break;
case WPM_ZOOM:
type = DW_BG_ZOOM;
break;
case WPM_CENTER:
type = DW_BG_CENTER;
break;
case WPM_TILE:
type = DW_BG_TILE;
break;
case WPM_STRETCH:
default:
type = DW_BG_STRETCH;
}
pix = gdk_pixbuf_new_from_file( app_settings.wallpaper, NULL );
}
else
{
type = DW_BG_COLOR;
pix = NULL;
}
for ( i = 0; i < n_screens; i++ )
desktop_window_set_background( DESKTOP_WINDOW(desktops[ i ]), pix, type );
if( pix )
g_object_unref( pix );
}
void fm_desktop_update_colors()
{
int i;
for ( i = 0; i < n_screens; i++ )
{
desktop_window_set_bg_color( DESKTOP_WINDOW(desktops[ i ]), &app_settings.desktop_bg1 );
desktop_window_set_text_color( DESKTOP_WINDOW(desktops[ i ]), &app_settings.desktop_text, &app_settings.desktop_shadow );
}
}
void fm_desktop_update_icons()
{
int i;
int big = 0;
vfs_mime_type_get_icon_size( &big, NULL );
for ( i = 0; i < n_screens; i++ )
desktop_window_set_icon_size( (DesktopWindow*)desktops[ i ], big );
}
void fm_desktop_set_single_click( gboolean single_click )
{
int i;
for ( i = 0; i < n_screens; i++ )
desktop_window_set_single_click( (DesktopWindow*)desktops[ i ], single_click );
}
#else /* ! DESKTOP_INTEGRATION */
/* dummy implementations */
void fm_turn_on_desktop_icons() { }
void fm_turn_off_desktop_icons() { }
void fm_desktop_update_thumbnails() { }
void fm_desktop_update_wallpaper() { }
void fm_desktop_update_colors() { }
void fm_desktop_update_icons() { }
void fm_desktop_set_single_click( gboolean single_click ) { }
#endif
|
153 | ./spacefm/src/desktop/working-area.c | /*
* Guifications - The end all, be all, toaster popup plugin
* Copyright (C) 2003-2004 Gary Kramlich
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/*
2005.07.22 Modified by Hong Jen Yee (PCMan)
This piece of code detecting working area is got from Guifications, a plug-in for Gaim.
*/
# include <gdk/gdk.h>
# include <gdk/gdkx.h>
# include <X11/Xlib.h>
# include <X11/Xutil.h>
# include <X11/Xatom.h>
gboolean
gf_display_get_workarea(GdkScreen* g_screen, GdkRectangle *rect) {
Atom xa_desktops, xa_current, xa_workarea, xa_type;
Display *x_display;
Window x_root;
guint32 desktops = 0, current = 0;
gulong *workareas, len, fill;
guchar *data;
gint format;
GdkDisplay *g_display;
Screen *x_screen;
/* get the gdk display */
g_display = gdk_display_get_default();
if(!g_display)
return FALSE;
/* get the x display from the gdk display */
x_display = gdk_x11_display_get_xdisplay(g_display);
if(!x_display)
return FALSE;
/* get the x screen from the gdk screen */
x_screen = gdk_x11_screen_get_xscreen(g_screen);
if(!x_screen)
return FALSE;
/* get the root window from the screen */
x_root = XRootWindowOfScreen(x_screen);
/* find the _NET_NUMBER_OF_DESKTOPS atom */
xa_desktops = XInternAtom(x_display, "_NET_NUMBER_OF_DESKTOPS", True);
if(xa_desktops == None)
return FALSE;
/* get the number of desktops */
if(XGetWindowProperty(x_display, x_root, xa_desktops, 0, 1, False,
XA_CARDINAL, &xa_type, &format, &len, &fill,
&data) != Success)
{
return FALSE;
}
if(!data)
return FALSE;
desktops = *(guint32 *)data;
XFree(data);
/* find the _NET_CURRENT_DESKTOP atom */
xa_current = XInternAtom(x_display, "_NET_CURRENT_DESKTOP", True);
if(xa_current == None)
return FALSE;
/* get the current desktop */
if(XGetWindowProperty(x_display, x_root, xa_current, 0, 1, False,
XA_CARDINAL, &xa_type, &format, &len, &fill,
&data) != Success)
{
return FALSE;
}
if(!data)
return FALSE;
current = *(guint32 *)data;
XFree(data);
/* find the _NET_WORKAREA atom */
xa_workarea = XInternAtom(x_display, "_NET_WORKAREA", True);
if(xa_workarea == None)
return FALSE;
if(XGetWindowProperty(x_display, x_root, xa_workarea, 0, (glong)(4 * 32),
False, AnyPropertyType, &xa_type, &format, &len,
&fill, &data) != Success)
{
return FALSE;
}
/* make sure the type and format are good */
if(xa_type == None || format == 0)
return FALSE;
/* make sure we don't have any leftovers */
if(fill)
return FALSE;
/* make sure len divides evenly by 4 */
if(len % 4)
return FALSE;
/* it's good, lets use it */
workareas = (gulong *)(guint32 *)data;
rect->x = (guint32)workareas[current * 4];
rect->y = (guint32)workareas[current * 4 + 1];
rect->width = (guint32)workareas[current * 4 + 2];
rect->height = (guint32)workareas[current * 4 + 3];
/* clean up our memory */
XFree(data);
return TRUE;
}
void get_working_area( GdkScreen* screen, GdkRectangle* area )
{
if( !gf_display_get_workarea(screen, area) )
{
area->x = 0;
area->y = 0;
area->width = gdk_screen_width();
area->height = gdk_screen_height();
}
}
|
154 | ./spacefm/src/desktop/desktop-window.c | /*
* desktop-window.c
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <glib/gi18n.h>
#include "desktop-window.h"
#include "vfs-file-info.h"
#include "vfs-mime-type.h"
#include "vfs-thumbnail-loader.h"
#include "vfs-app-desktop.h"
#include "glib-mem.h"
#include "working-area.h"
#include "ptk-file-misc.h"
#include "ptk-file-menu.h"
#include "ptk-file-task.h"
#include "ptk-utils.h"
#include "settings.h"
#include "main-window.h"
#include "pref-dialog.h"
#include "ptk-file-browser.h"
#include "ptk-clipboard.h"
#include "ptk-file-archiver.h"
#include "ptk-location-view.h"
#include "ptk-app-chooser.h"
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <gdk/gdkx.h>
#include <gdk/gdkkeysyms.h>
#include <fnmatch.h>
#include "gtk2-compat.h"
#if GTK_CHECK_VERSION (3, 0, 0)
#include <cairo-xlib.h>
#endif
#include <string.h>
/* for stat */
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "gtk2-compat.h"
struct _DesktopItem
{
VFSFileInfo* fi;
guint order;
GdkRectangle box; /* bounding rect */
GdkRectangle icon_rect;
GdkRectangle text_rect;
/* Since pango doesn't support using "wrap" and "ellipsize" at the same time,
let's do some dirty hack here. We draw these two lines separately, and
we can ellipsize the second line. */
int len1; /* length for the first line of label text */
int line_h1; /* height of the first line */
gboolean is_selected : 1;
gboolean is_prelight : 1;
};
static void desktop_window_class_init (DesktopWindowClass *klass);
static void desktop_window_init (DesktopWindow *self);
static void desktop_window_finalize (GObject *object);
#if GTK_CHECK_VERSION (3, 0, 0)
static gboolean on_draw( GtkWidget* w, cairo_t* cr );
static void desktop_window_get_preferred_width (GtkWidget *widget, gint *minimal_width, gint *natural_width);
static void desktop_window_get_preferred_height (GtkWidget *widget, gint *minimal_height, gint *natural_height);
#else
static gboolean on_expose( GtkWidget* w, GdkEventExpose* evt );
#endif
static void on_size_allocate( GtkWidget* w, GtkAllocation* alloc );
static void on_size_request( GtkWidget* w, GtkRequisition* req );
static gboolean on_button_press( GtkWidget* w, GdkEventButton* evt );
static gboolean on_button_release( GtkWidget* w, GdkEventButton* evt );
static gboolean on_mouse_move( GtkWidget* w, GdkEventMotion* evt );
static gboolean on_key_press( GtkWidget* w, GdkEventKey* evt );
static void on_style_set( GtkWidget* w, GtkStyle* prev );
static void on_realize( GtkWidget* w );
static gboolean on_focus_in( GtkWidget* w, GdkEventFocus* evt );
static gboolean on_focus_out( GtkWidget* w, GdkEventFocus* evt );
/* static gboolean on_scroll( GtkWidget *w, GdkEventScroll *evt, gpointer user_data ); */
static void on_drag_begin( GtkWidget* w, GdkDragContext* ctx );
static gboolean on_drag_motion( GtkWidget* w, GdkDragContext* ctx, gint x, gint y, guint time );
static gboolean on_drag_drop( GtkWidget* w, GdkDragContext* ctx, gint x, gint y, guint time );
static void on_drag_data_get( GtkWidget* w, GdkDragContext* ctx, GtkSelectionData* data, guint info, guint time );
static void on_drag_data_received( GtkWidget* w, GdkDragContext* ctx, gint x, gint y, GtkSelectionData* data, guint info, guint time );
static void on_drag_leave( GtkWidget* w, GdkDragContext* ctx, guint time );
static void on_drag_end( GtkWidget* w, GdkDragContext* ctx );
static void on_file_listed( VFSDir* dir, gboolean is_cancelled, DesktopWindow* self );
static void on_file_created( VFSDir* dir, VFSFileInfo* file, gpointer user_data );
static void on_file_deleted( VFSDir* dir, VFSFileInfo* file, gpointer user_data );
static void on_file_changed( VFSDir* dir, VFSFileInfo* file, gpointer user_data );
static void on_thumbnail_loaded( VFSDir* dir, VFSFileInfo* fi, DesktopWindow* self );
static void on_sort_by_name ( GtkMenuItem *menuitem, DesktopWindow* self );
static void on_sort_by_size ( GtkMenuItem *menuitem, DesktopWindow* self );
static void on_sort_by_mtime ( GtkMenuItem *menuitem, DesktopWindow* self );
static void on_sort_by_type ( GtkMenuItem *menuitem, DesktopWindow* self );
static void on_sort_custom( GtkMenuItem *menuitem, DesktopWindow* self );
static void on_sort_ascending( GtkMenuItem *menuitem, DesktopWindow* self );
static void on_sort_descending( GtkMenuItem *menuitem, DesktopWindow* self );
static void on_paste( GtkMenuItem *menuitem, DesktopWindow* self );
static void on_settings( GtkMenuItem *menuitem, DesktopWindow* self );
static GdkFilterReturn on_rootwin_event ( GdkXEvent *xevent, GdkEvent *event, gpointer data );
static void forward_event_to_rootwin( GdkScreen *gscreen, GdkEvent *event );
static void calc_item_size( DesktopWindow* self, DesktopItem* item );
static void layout_items( DesktopWindow* self );
static void paint_item( DesktopWindow* self, DesktopItem* item, GdkRectangle* expose_area );
static void move_item( DesktopWindow* self, DesktopItem* item, int x, int y, gboolean is_offset );
static void paint_rubber_banding_rect( DesktopWindow* self );
/* FIXME: this is too dirty and here is some redundant code.
* We really need better and cleaner APIs for this */
static void open_folders( GList* folders );
static GList* sort_items( GList* items, DesktopWindow* win );
static GCompareDataFunc get_sort_func( DesktopWindow* win );
static int comp_item_by_name( DesktopItem* item1, DesktopItem* item2, DesktopWindow* win );
static int comp_item_by_size( DesktopItem* item1, DesktopItem* item2, DesktopWindow* win );
static int comp_item_by_mtime( DesktopItem* item1, DesktopItem* item2, DesktopWindow* win );
static int comp_item_by_type( DesktopItem* item1, DesktopItem* item2, DesktopWindow* win );
static int comp_item_custom( DesktopItem* item1, DesktopItem* item2, DesktopWindow* win );
static void redraw_item( DesktopWindow* win, DesktopItem* item );
static void desktop_item_free( DesktopItem* item );
/*
static GdkPixmap* get_root_pixmap( GdkWindow* root );
static gboolean set_root_pixmap( GdkWindow* root , GdkPixmap* pix );
*/
static DesktopItem* hit_test( DesktopWindow* self, int x, int y );
/* static Atom ATOM_XROOTMAP_ID = 0; */
static Atom ATOM_NET_WORKAREA = 0;
/* Local data */
static GtkWindowClass *parent_class = NULL;
/*static GdkPixmap* pix = NULL;*/
enum {
DRAG_TARGET_URI_LIST,
DRAG_TARGET_DESKTOP_ICON
};
/* Drag & Drop/Clipboard targets */
static GtkTargetEntry drag_targets[] = {
{ "text/uri-list", 0 , DRAG_TARGET_URI_LIST },
{ "DESKTOP_ICON", GTK_TARGET_SAME_WIDGET, DRAG_TARGET_DESKTOP_ICON }
};
static GdkAtom text_uri_list_atom = 0;
static GdkAtom desktop_icon_atom = 0;
//sfm from ptk-file-icon-renderer.c
static GdkPixbuf* link_icon = NULL;
/* GdkPixbuf RGBA C-Source image dump */
#ifdef __SUNPRO_C
#pragma align 4 (link_icon_data)
#endif
#ifdef __GNUC__
static const guint8 link_icon_data[] __attribute__ ((__aligned__ (4))) =
#else
static const guint8 link_icon_data[] =
#endif
{ ""
/* Pixbuf magic (0x47646b50) */
"GdkP"
/* length: header (24) + pixel_data (400) */
"\0\0\1\250"
/* pixdata_type (0x1010002) */
"\1\1\0\2"
/* rowstride (40) */
"\0\0\0("
/* width (10) */
"\0\0\0\12"
/* height (10) */
"\0\0\0\12"
/* pixel_data: */
"\200\200\200\377\200\200\200\377\200\200\200\377\200\200\200\377\200"
"\200\200\377\200\200\200\377\200\200\200\377\200\200\200\377\200\200"
"\200\377\0\0\0\377\200\200\200\377\377\377\377\377\377\377\377\377\377"
"\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377"
"\377\377\377\377\377\377\0\0\0\377\200\200\200\377\377\377\377\377\0"
"\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\377\377\377\377\377"
"\377\377\377\0\0\0\377\200\200\200\377\377\377\377\377\0\0\0\377\0\0"
"\0\377\0\0\0\377\0\0\0\377\377\377\377\377\377\377\377\377\377\377\377"
"\377\0\0\0\377\200\200\200\377\377\377\377\377\0\0\0\377\0\0\0\377\0"
"\0\0\377\0\0\0\377\0\0\0\377\377\377\377\377\377\377\377\377\0\0\0\377"
"\200\200\200\377\377\377\377\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0"
"\377\0\0\0\377\0\0\0\377\377\377\377\377\0\0\0\377\200\200\200\377\377"
"\377\377\377\0\0\0\377\377\377\377\377\377\377\377\377\0\0\0\377\0\0"
"\0\377\0\0\0\377\377\377\377\377\0\0\0\377\200\200\200\377\377\377\377"
"\377\377\377\377\377\377\377\377\377\377\377\377\377\0\0\0\377\0\0\0"
"\377\0\0\0\377\377\377\377\377\0\0\0\377\200\200\200\377\377\377\377"
"\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377"
"\377\377\377\377\377\377\377\377\377\377\377\377\0\0\0\377\0\0\0\377"
"\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377"
"\0\0\0\377\0\0\0\377"
};
GType desktop_window_get_type(void)
{
static GType self_type = 0;
if (! self_type)
{
static const GTypeInfo self_info =
{
sizeof(DesktopWindowClass),
NULL, /* base_init */
NULL, /* base_finalize */
(GClassInitFunc)desktop_window_class_init,
NULL, /* class_finalize */
NULL, /* class_data */
sizeof(DesktopWindow),
0,
(GInstanceInitFunc)desktop_window_init,
NULL /* value_table */
};
self_type = g_type_register_static(GTK_TYPE_WINDOW, "DesktopWindow", &self_info, 0); }
return self_type;
}
static void desktop_window_class_init(DesktopWindowClass *klass)
{
GObjectClass *g_object_class;
GtkWidgetClass* wc;
typedef gboolean (*DeleteEvtHandler) (GtkWidget*, GdkEvent*);
g_object_class = G_OBJECT_CLASS(klass);
wc = GTK_WIDGET_CLASS(klass);
g_object_class->finalize = desktop_window_finalize;
#if GTK_CHECK_VERSION (3, 0, 0)
wc->draw = on_draw;
wc->get_preferred_width = desktop_window_get_preferred_width;
wc->get_preferred_height = desktop_window_get_preferred_height;
#else
wc->expose_event = on_expose;
wc->size_request = on_size_request;
#endif
wc->size_allocate = on_size_allocate;
wc->button_press_event = on_button_press;
wc->button_release_event = on_button_release;
wc->motion_notify_event = on_mouse_move;
wc->key_press_event = on_key_press;
wc->style_set = on_style_set;
wc->realize = on_realize;
wc->focus_in_event = on_focus_in;
wc->focus_out_event = on_focus_out;
/* wc->scroll_event = on_scroll; */
wc->delete_event = (gpointer)gtk_true;
wc->drag_begin = on_drag_begin;
wc->drag_motion = on_drag_motion;
wc->drag_drop = on_drag_drop;
wc->drag_data_get = on_drag_data_get;
wc->drag_data_received = on_drag_data_received;
wc->drag_leave = on_drag_leave;
wc->drag_end = on_drag_end;
parent_class = (GtkWindowClass*)g_type_class_peek(GTK_TYPE_WINDOW);
/* ATOM_XROOTMAP_ID = XInternAtom( GDK_DISPLAY(),"_XROOTMAP_ID", False ); */
ATOM_NET_WORKAREA = XInternAtom( gdk_x11_get_default_xdisplay(),"_NET_WORKAREA", False );
text_uri_list_atom = gdk_atom_intern_static_string( drag_targets[DRAG_TARGET_URI_LIST].target );
desktop_icon_atom = gdk_atom_intern_static_string( drag_targets[DRAG_TARGET_DESKTOP_ICON].target );
/* on emit, desktop window is not an object so this doesn't work
g_signal_new ( "task-notify",
G_TYPE_FROM_CLASS ( klass ),
G_SIGNAL_RUN_FIRST,
0,
NULL, NULL,
g_cclosure_marshal_VOID__POINTER,
G_TYPE_NONE, 1, G_TYPE_POINTER );
*/
}
static void desktop_window_init(DesktopWindow *self)
{
PangoContext* pc;
PangoFontMetrics *metrics;
int font_h;
GdkWindow* root;
/* sort by name by default */
// self->sort_by = DW_SORT_BY_NAME;
// self->sort_type = GTK_SORT_ASCENDING;
self->sort_by = app_settings.desktop_sort_by;
self->sort_type = app_settings.desktop_sort_type;
self->icon_render = gtk_cell_renderer_pixbuf_new();
g_object_set( self->icon_render, "follow-state", TRUE, NULL);
g_object_ref_sink(self->icon_render);
pc = gtk_widget_get_pango_context( (GtkWidget*)self );
self->pl = gtk_widget_create_pango_layout( (GtkWidget*)self, NULL );
pango_layout_set_alignment( self->pl, PANGO_ALIGN_CENTER );
pango_layout_set_wrap( self->pl, PANGO_WRAP_WORD_CHAR );
pango_layout_set_width( self->pl, 100 * PANGO_SCALE );
metrics = pango_context_get_metrics(
pc, gtk_widget_get_style( ((GtkWidget*)self) )->font_desc,
pango_context_get_language(pc));
font_h = pango_font_metrics_get_ascent(metrics) + pango_font_metrics_get_descent (metrics);
font_h /= PANGO_SCALE;
self->label_w = 100;
self->icon_size = 48;
self->spacing = 0;
self->x_pad = 6;
self->y_pad = 6;
self->y_margin = 6;
self->x_margin = 6;
if ( !link_icon )
{
link_icon = gdk_pixbuf_new_from_inline(
sizeof(link_icon_data),
link_icon_data,
FALSE, NULL );
g_object_add_weak_pointer( G_OBJECT(link_icon), (gpointer)&link_icon );
}
else
g_object_ref( (link_icon) );
const char* desk_dir = vfs_get_desktop_dir();
if ( desk_dir )
{
if ( !g_file_test( desk_dir, G_FILE_TEST_EXISTS ) )
{
g_mkdir_with_parents( desk_dir, 0700 );
desk_dir = vfs_get_desktop_dir();
}
if ( g_file_test( desk_dir, G_FILE_TEST_EXISTS ) )
self->dir = vfs_dir_get_by_path( vfs_get_desktop_dir() );
else
self->dir = NULL; // FIXME this is not handled well
}
if ( self->dir && vfs_dir_is_file_listed( self->dir ) )
on_file_listed( self->dir, FALSE, self );
if ( self->dir )
{
g_signal_connect( self->dir, "file-listed", G_CALLBACK( on_file_listed ), self );
g_signal_connect( self->dir, "file-created", G_CALLBACK( on_file_created ), self );
g_signal_connect( self->dir, "file-deleted", G_CALLBACK( on_file_deleted ), self );
g_signal_connect( self->dir, "file-changed", G_CALLBACK( on_file_changed ), self );
g_signal_connect( self->dir, "thumbnail-loaded", G_CALLBACK( on_thumbnail_loaded ), self );
}
gtk_widget_set_can_focus ( (GtkWidget*)self, TRUE );
gtk_widget_set_app_paintable( (GtkWidget*)self, TRUE );
/* gtk_widget_set_double_buffered( (GtkWidget*)self, FALSE ); */
gtk_widget_add_events( (GtkWidget*)self,
GDK_POINTER_MOTION_MASK |
GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK |
GDK_KEY_PRESS_MASK|
GDK_PROPERTY_CHANGE_MASK );
gtk_drag_dest_set( (GtkWidget*)self, 0, NULL, 0,
GDK_ACTION_COPY|GDK_ACTION_MOVE|GDK_ACTION_LINK );
root = gdk_screen_get_root_window( gtk_widget_get_screen( (GtkWidget*)self ) );
gdk_window_set_events( root, gdk_window_get_events( root )
| GDK_PROPERTY_CHANGE_MASK );
gdk_window_add_filter( root, on_rootwin_event, self );
//g_signal_connect( G_OBJECT( self ), "task-notify",
// G_CALLBACK( ptk_file_task_notify_handler ), NULL );
}
GtkWidget* desktop_window_new(void)
{
GtkWindow* w = (GtkWindow*)g_object_new(DESKTOP_WINDOW_TYPE, NULL);
return (GtkWidget*)w;
}
void desktop_item_free( DesktopItem* item )
{
vfs_file_info_unref( item->fi );
g_slice_free( DesktopItem, item );
}
void desktop_window_finalize(GObject *object)
{
DesktopWindow *self = (DesktopWindow*)object;
Display *xdisplay = GDK_DISPLAY_XDISPLAY( gtk_widget_get_display( (GtkWidget*)object) );
g_return_if_fail(object != NULL);
g_return_if_fail(IS_DESKTOP_WINDOW(object));
gdk_window_remove_filter(
gdk_screen_get_root_window( gtk_widget_get_screen( (GtkWidget*)object) ),
on_rootwin_event, self );
#if GTK_CHECK_VERSION (3, 0, 0)
if( self->background )
XFreePixmap ( xdisplay, self->background );
if( self->surface )
cairo_surface_destroy ( self->surface );
#else
if( self->background )
g_object_unref( self->background );
#endif
if( self->hand_cursor )
gdk_cursor_unref( self->hand_cursor );
if ( link_icon )
g_object_unref( link_icon );
self = DESKTOP_WINDOW(object);
if ( self->dir )
g_object_unref( self->dir );
g_list_foreach( self->items, (GFunc)desktop_item_free, NULL );
g_list_free( self->items );
if (G_OBJECT_CLASS(parent_class)->finalize)
(* G_OBJECT_CLASS(parent_class)->finalize)(object);
}
/*--------------- Signal handlers --------------*/
#if GTK_CHECK_VERSION (3, 0, 0)
gboolean on_draw( GtkWidget* w, cairo_t* cr)
#else
gboolean on_expose( GtkWidget* w, GdkEventExpose* evt )
#endif
{
DesktopWindow* self = (DesktopWindow*)w;
GList* l;
GdkRectangle intersect;
#if GTK_CHECK_VERSION (3, 0, 0)
GtkAllocation allocation;
gtk_widget_get_allocation (w, &allocation);
#endif
if( G_UNLIKELY( ! gtk_widget_get_visible (w) || ! gtk_widget_get_mapped (w) ) )
return TRUE;
/*
gdk_draw_drawable( w->window, self->gc,
self->background,
evt->area.x, evt->area.y,
evt->area.x, evt->area.y,
evt->area.width, evt->area.height );
*/
/*
gdk_gc_set_tile( self->gc, self->background );
gdk_gc_set_fill( self->gc, GDK_TILED );/*
gdk_draw_rectangle( w->window, self->gc, TRUE,
evt->area.x, evt->area.y,
evt->area.width, evt->area.height );
*/
if( self->rubber_bending )
paint_rubber_banding_rect( self );
for( l = self->items; l; l = l->next )
{
DesktopItem* item = (DesktopItem*)l->data;
#if GTK_CHECK_VERSION (3, 0, 0)
if( gdk_rectangle_intersect( &allocation, &item->box, &intersect ) )
paint_item( self, item, &intersect );
#else
if( gdk_rectangle_intersect( &evt->area, &item->box, &intersect ) )
paint_item( self, item, &intersect );
#endif
}
return TRUE;
}
void on_size_allocate( GtkWidget* w, GtkAllocation* alloc )
{
GdkPixbuf* pix;
DesktopWindow* self = (DesktopWindow*)w;
GdkRectangle wa;
get_working_area( gtk_widget_get_screen(w), &self->wa );
layout_items( DESKTOP_WINDOW(w) );
GTK_WIDGET_CLASS(parent_class)->size_allocate( w, alloc );
}
void desktop_window_set_bg_color( DesktopWindow* win, GdkColor* clr )
{
if( clr )
{
win->bg = *clr;
// Allocating colors is unnecessary with gtk3
#if !GTK_CHECK_VERSION (3, 0, 0)
gdk_colormap_alloc_color ( gtk_widget_get_colormap( (GtkWidget*)win ),
&win->bg, FALSE, TRUE );
#endif
if( gtk_widget_get_visible( (GtkWidget*)win ) )
gtk_widget_queue_draw( (GtkWidget*)win );
}
}
void desktop_window_set_text_color( DesktopWindow* win, GdkColor* clr, GdkColor* shadow )
{
if( clr || shadow )
{
if( clr )
{
win->fg = *clr;
// Allocating colors is unnecessary with gtk3
#if !GTK_CHECK_VERSION (3, 0, 0)
gdk_colormap_alloc_color ( gtk_widget_get_colormap( (GtkWidget*)win ),
&win->fg, FALSE, TRUE );
#endif
}
if( shadow )
{
win->shadow = *shadow;
// Allocating colors is unnecessary with gtk3
#if !GTK_CHECK_VERSION (3, 0, 0)
gdk_colormap_alloc_color ( gtk_widget_get_colormap( (GtkWidget*)win ),
&win->shadow, FALSE, TRUE );
#endif
}
if( gtk_widget_get_visible( (GtkWidget*)win ) )
gtk_widget_queue_draw( (GtkWidget*)win );
}
}
/*
* Set background of the desktop window.
* src_pix is the source pixbuf in original size (no scaling)
* This function will stretch or add border to this pixbuf accordiong to 'type'.
* If type = DW_BG_COLOR and src_pix = NULL, the background color is used to fill the window.
*/
void desktop_window_set_background( DesktopWindow* win, GdkPixbuf* src_pix, DWBgType type )
{
#if GTK_CHECK_VERSION (3, 0, 0)
Pixmap pixmap = 0;
cairo_surface_t *surface = NULL;
cairo_pattern_t *pattern = NULL;
#else
GdkPixmap* pixmap = NULL;
#endif
Display* xdisplay;
Pixmap xpixmap = 0;
Visual *xvisual;
Window xroot;
cairo_t *cr;
int dummy;
unsigned int udummy, depth;
/* set root map here */
xdisplay = GDK_DISPLAY_XDISPLAY( gtk_widget_get_display( (GtkWidget*)win) );
XGetGeometry (xdisplay, GDK_WINDOW_XID( gtk_widget_get_window( (GtkWidget*)win ) ),
&xroot, &dummy, &dummy, &dummy, &dummy, &udummy, &depth);
xvisual = GDK_VISUAL_XVISUAL (gdk_screen_get_system_visual ( gtk_widget_get_screen ( (GtkWidget*)win) ) );
win->bg_type = type;
if( src_pix )
{
int src_w = gdk_pixbuf_get_width(src_pix);
int src_h = gdk_pixbuf_get_height(src_pix);
int dest_w = gdk_screen_get_width( gtk_widget_get_screen((GtkWidget*)win) );
int dest_h = gdk_screen_get_height( gtk_widget_get_screen((GtkWidget*)win) );
GdkPixbuf* scaled = NULL;
if( type == DW_BG_TILE )
{
#if GTK_CHECK_VERSION (3, 0, 0)
pixmap = XCreatePixmap(xdisplay, xroot, src_w, src_h, depth);
surface = cairo_xlib_surface_create (xdisplay, pixmap, xvisual,
src_w, src_h);
cr = cairo_create ( surface );
#else
pixmap = gdk_pixmap_new( gtk_widget_get_window( ((GtkWidget*)win) ), src_w, src_h, -1 );
cr = gdk_cairo_create ( pixmap );
#endif
gdk_cairo_set_source_pixbuf ( cr, src_pix, 0, 0 );
cairo_paint ( cr );
}
else
{
int src_x = 0, src_y = 0;
int dest_x = 0, dest_y = 0;
int w = 0, h = 0;
#if GTK_CHECK_VERSION (3, 0, 0)
pixmap = XCreatePixmap(xdisplay, xroot, dest_w, dest_h, depth);
surface = cairo_xlib_surface_create (xdisplay, pixmap, xvisual,
dest_w, dest_h);
cr = cairo_create ( surface );
#else
pixmap = gdk_pixmap_new( gtk_widget_get_window( ((GtkWidget*)win) ), dest_w, dest_h, -1 );
cr = gdk_cairo_create ( pixmap );
#endif
switch( type )
{
case DW_BG_STRETCH:
if( src_w == dest_w && src_h == dest_h ) /* the same size, no scale is needed */
scaled = (GdkPixbuf*)g_object_ref( src_pix );
else
scaled = gdk_pixbuf_scale_simple( src_pix, dest_w, dest_h, GDK_INTERP_BILINEAR );
w = dest_w;
h = dest_h;
break;
case DW_BG_FULL:
case DW_BG_ZOOM:
if( src_w == dest_w && src_h == dest_h )
scaled = (GdkPixbuf*)g_object_ref( src_pix );
else
{
gdouble w_ratio = (float)dest_w / src_w;
gdouble h_ratio = (float)dest_h / src_h;
gdouble ratio;
if (type == DW_BG_FULL)
ratio = MIN( w_ratio, h_ratio );
else
ratio = MAX( w_ratio, h_ratio );
if( ratio == 1.0 )
scaled = (GdkPixbuf*)g_object_ref( src_pix );
else
scaled = gdk_pixbuf_scale_simple( src_pix, (src_w * ratio), (src_h * ratio), GDK_INTERP_BILINEAR );
}
w = gdk_pixbuf_get_width( scaled );
h = gdk_pixbuf_get_height( scaled );
dest_x = (dest_w - w) / 2;
dest_y = (dest_h - h) / 2;
break;
case DW_BG_CENTER: /* no scale is needed */
scaled = (GdkPixbuf*)g_object_ref( src_pix );
if( src_w > dest_w )
{
w = dest_w;
src_x = (src_w - dest_w) / 2;
}
else
{
w = src_w;
dest_x = (dest_w - src_w) / 2;
}
if( src_h > dest_h )
{
h = dest_h;
src_y = (src_h - dest_h) / 2;
}
else
{
h = src_h;
dest_y = (dest_h - src_h) / 2;
}
break;
}
if( scaled )
{
if( w != dest_w || h != dest_h )
{
gdk_cairo_set_source_color ( cr, &win->bg );
cairo_rectangle ( cr, 0, 0, dest_w, dest_h );
cairo_paint ( cr );
}
gdk_cairo_set_source_pixbuf ( cr, scaled, dest_x, dest_y );
cairo_move_to ( cr, src_x, src_y );
cairo_paint ( cr );
g_object_unref( scaled );
}
else
{
#if GTK_CHECK_VERSION (3, 0, 0)
XFreePixmap ( xdisplay, pixmap );
pixmap = 0;
#else
g_object_unref( pixmap );
pixmap = NULL;
#endif
}
}
cairo_destroy ( cr );
}
#if GTK_CHECK_VERSION (3, 0, 0)
if( win->background )
XFreePixmap ( xdisplay, win->background );
if( win->surface )
cairo_surface_destroy ( win->surface );
win->surface = surface;
#else
if( win->background )
g_object_unref( win->background );
#endif
win->background = pixmap;
if( pixmap )
{
#if GTK_CHECK_VERSION (3, 0, 0)
pattern = cairo_pattern_create_for_surface( surface );
cairo_pattern_set_extend( pattern, CAIRO_EXTEND_REPEAT );
gdk_window_set_background_pattern( gtk_widget_get_window( ((GtkWidget*)win) ), pattern );
cairo_pattern_destroy( pattern );
#else
gdk_window_set_back_pixmap( gtk_widget_get_window( ((GtkWidget*)win) ), pixmap, FALSE );
#endif
}
else
gdk_window_set_background( gtk_widget_get_window( ((GtkWidget*)win) ), &win->bg );
#if !GTK_CHECK_VERSION (3, 0, 0)
gdk_window_clear( gtk_widget_get_window( ((GtkWidget*)win) ) );
#else
/* cairo_t *cr2 = gdk_cairo_create( gtk_widget_get_window ((GtkWidget*)win) );
gdk_cairo_set_source_color( cr2, &win->bg );
cairo_paint( cr2 );
if ( surface )
{
cairo_set_source_surface( cr2, surface, 0, 0 );
cairo_paint( cr2 );
}
cairo_destroy(cr2);*/
#endif
gtk_widget_queue_draw( (GtkWidget*)win );
XGrabServer (xdisplay);
if( pixmap )
{
#if GTK_CHECK_VERSION (3, 0, 0)
xpixmap = pixmap;
#else
xpixmap = GDK_WINDOW_XID(pixmap);
#endif
XChangeProperty( xdisplay,
xroot,
gdk_x11_get_xatom_by_name("_XROOTPMAP_ID"), XA_PIXMAP,
32, PropModeReplace,
(guchar *) &xpixmap, 1);
XSetWindowBackgroundPixmap( xdisplay, xroot, xpixmap );
}
else
{
/* FIXME: Anyone knows how to handle this correctly??? */
}
XClearWindow( xdisplay, xroot );
XUngrabServer( xdisplay );
XFlush( xdisplay );
}
void desktop_window_set_icon_size( DesktopWindow* win, int size )
{
GList* l;
win->icon_size = size;
layout_items( win );
for( l = win->items; l; l = l->next )
{
VFSFileInfo* fi = ((DesktopItem*)l->data)->fi;
char* path;
/* reload the icons for special items if needed */
if( (fi->flags & VFS_FILE_INFO_DESKTOP_ENTRY) && ! fi->big_thumbnail)
{
path = g_build_filename( vfs_get_desktop_dir(), fi->name, NULL );
vfs_file_info_load_special_info( fi, path );
g_free( path );
}
else if(fi->flags & VFS_FILE_INFO_VIRTUAL)
{
/* Currently only "My Documents" is supported */
if( fi->big_thumbnail )
g_object_unref( fi->big_thumbnail );
fi->big_thumbnail = gtk_icon_theme_load_icon(gtk_icon_theme_get_default(), "gnome-fs-home", size, 0, NULL );
if( ! fi->big_thumbnail )
fi->big_thumbnail = gtk_icon_theme_load_icon(gtk_icon_theme_get_default(), "folder-home", size, 0, NULL );
}
else if( vfs_file_info_is_image( fi ) && ! fi->big_thumbnail )
{
vfs_thumbnail_loader_request( win->dir, fi, TRUE );
}
}
}
void desktop_window_reload_icons( DesktopWindow* win )
{
/*
GList* l;
for( l = win->items; l; l = l->next )
{
DesktopItem* item = (DesktopItem*)l->data;
if( item->icon )
g_object_unref( item->icon );
if( item->fi )
item->icon = vfs_file_info_get_big_icon( item->fi );
else
item->icon = NULL;
}
*/
layout_items( win );
}
void on_size_request( GtkWidget* w, GtkRequisition* req )
{
GdkScreen* scr = gtk_widget_get_screen( w );
req->width = gdk_screen_get_width( scr );
req->height = gdk_screen_get_height( scr );
}
#if GTK_CHECK_VERSION (3, 0, 0)
static void
desktop_window_get_preferred_width (GtkWidget *widget,
gint *minimal_width,
gint *natural_width)
{
GtkRequisition requisition;
on_size_request (widget, &requisition);
*minimal_width = *natural_width = requisition.width;
}
static void
desktop_window_get_preferred_height (GtkWidget *widget,
gint *minimal_height,
gint *natural_height)
{
GtkRequisition requisition;
on_size_request (widget, &requisition);
*minimal_height = *natural_height = requisition.height;
}
#endif
static void calc_rubber_banding_rect( DesktopWindow* self, int x, int y, GdkRectangle* rect )
{
int x1, x2, y1, y2, w, h;
if( self->drag_start_x < x )
{
x1 = self->drag_start_x;
x2 = x;
}
else
{
x1 = x;
x2 = self->drag_start_x;
}
if( self->drag_start_y < y )
{
y1 = self->drag_start_y;
y2 = y;
}
else
{
y1 = y;
y2 = self->drag_start_y;
}
rect->x = x1;
rect->y = y1;
rect->width = x2 - x1;
rect->height = y2 - y1;
}
/*
* Reference: xfdesktop source code
* http://svn.xfce.org/index.cgi/xfce/view/xfdesktop/trunk/src/xfdesktop-icon-view.c
* xfdesktop_multiply_pixbuf_rgba()
* Originally copied from Nautilus, Copyright (C) 2000 Eazel, Inc.
* Multiplies each pixel in a pixbuf by the specified color
*/
static void colorize_pixbuf( GdkPixbuf* pix, GdkColor* clr, guint alpha )
{
guchar *pixels, *p;
int x, y, width, height, rowstride;
gboolean has_alpha;
int r = clr->red * 255 / 65535;
int g = clr->green * 255 / 65535;
int b = clr->blue * 255 / 65535;
int a = alpha * 255 / 255;
pixels = gdk_pixbuf_get_pixels(pix);
width = gdk_pixbuf_get_width(pix);
height = gdk_pixbuf_get_height(pix);
has_alpha = gdk_pixbuf_get_has_alpha(pix);
rowstride = gdk_pixbuf_get_rowstride(pix);
for (y = 0; y < height; y++)
{
p = pixels;
for (x = 0; x < width; x++)
{
p[0] = p[0] * r / 255;
p[1] = p[1] * g / 255;
p[2] = p[2] * b / 255;
if( has_alpha )
{
p[3] = p[3] * a / 255;
p += 4;
}
else
p += 3;
}
pixels += rowstride;
}
}
void paint_rubber_banding_rect( DesktopWindow* self )
{
int x1, x2, y1, y2, w, h, pattern_w, pattern_h;
GdkRectangle rect;
GdkColor *clr;
guchar alpha;
GdkPixbuf* pix;
cairo_t *cr;
calc_rubber_banding_rect( self, self->rubber_bending_x, self->rubber_bending_y, &rect );
if( rect.width <= 0 || rect.height <= 0 )
return;
/*
gtk_widget_style_get( GTK_WIDGET(self),
"selection-box-color", &clr,
"selection-box-alpha", &alpha,
NULL);
*/
cr = gdk_cairo_create ( gtk_widget_get_window( ((GtkWidget*)self) ) );
clr = gdk_color_copy (>k_widget_get_style( GTK_WIDGET (self) )->base[GTK_STATE_SELECTED]);
alpha = 64; /* FIXME: should be themable in the future */
pix = NULL;
if( self->bg_type == DW_BG_TILE )
{
/* FIXME: disable background in tile mode because current implementation is too slow */
/*
gdk_drawable_get_size( self->background, &pattern_w, &pattern_h );
pix = gdk_pixbuf_get_from_drawable( NULL, self->background, gdk_drawable_get_colormap(self->background),
0, 0, 0, 0, pattern_w, pattern_h );
*/
}
else if( self->bg_type != DW_BG_COLOR )
{
if( self->background )
#if GTK_CHECK_VERSION (3, 0, 0)
pix = gdk_pixbuf_get_from_surface( self->surface,
rect.x, rect.y, rect.width, rect.height );
#else
pix = gdk_pixbuf_get_from_drawable( NULL, self->background, gdk_drawable_get_colormap(self->background),
rect.x, rect.y, 0, 0, rect.width, rect.height );
#endif
}
if( pix )
{
colorize_pixbuf( pix, clr, alpha );
if( self->bg_type == DW_BG_TILE ) /* this is currently unreachable */
{
/*GdkPixmap* pattern;*/
/* FIXME: This is damn slow!! */
/*pattern = gdk_pixmap_new( gtk_widget_get_window( ((GtkWidget*)self) ), pattern_w, pattern_h, -1 );
if( pattern )
{
gdk_draw_pixbuf( pattern, gc, pix, 0, 0,
0, 0, pattern_w, pattern_h, GDK_RGB_DITHER_NONE, 0, 0 );
gdk_gc_set_tile( gc, pattern );
gdk_gc_set_fill( gc, GDK_TILED );
gdk_draw_rectangle( gtk_widget_get_window( ((GtkWidget*)self) ), gc, TRUE,
rect.x, rect.y, rect.width-1, rect.height-1 );
g_object_unref( pattern );
gdk_gc_set_fill( gc, GDK_SOLID );
} */
}
else
{
gdk_cairo_set_source_pixbuf( cr, pix, rect.x, rect.y );
cairo_rectangle( cr, rect.x, rect.y, rect.width, rect.height );
cairo_fill( cr );
}
g_object_unref( pix );
}
else if( self->bg_type == DW_BG_COLOR ) /* draw background color */
{
GdkColor clr2 = self->bg;
clr2.pixel = 0;
clr2.red = clr2.red * clr->red / 65535;
clr2.green = clr2.green * clr->green / 65535;
clr2.blue = clr2.blue * clr->blue / 65535;
gdk_cairo_set_source_color( cr, &clr2 );
cairo_rectangle( cr, rect.x, rect.y, rect.width - 1, rect.height - 1 );
cairo_fill( cr );
}
/* draw the border */
gdk_cairo_set_source_color( cr, clr );
cairo_rectangle( cr, rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2 );
cairo_stroke( cr );
gdk_color_free (clr);
}
static void update_rubberbanding( DesktopWindow* self, int newx, int newy, gboolean add )
{
GList* l;
GdkRectangle old_rect, new_rect;
#if GTK_CHECK_VERSION (3, 0, 0)
cairo_region_t *region;
#else
GdkRegion *region;
#endif
calc_rubber_banding_rect(self, self->rubber_bending_x, self->rubber_bending_y, &old_rect );
calc_rubber_banding_rect(self, newx, newy, &new_rect );
gdk_window_invalidate_rect(gtk_widget_get_window( ((GtkWidget*)self) ), &old_rect, FALSE );
gdk_window_invalidate_rect(gtk_widget_get_window( ((GtkWidget*)self) ), &new_rect, FALSE );
// gdk_window_clear_area(((GtkWidget*)self)->window, new_rect.x, new_rect.y, new_rect.width, new_rect.height );
/*
region = gdk_region_rectangle( &old_rect );
gdk_region_union_with_rect( region, &new_rect );
// gdk_window_invalidate_region( ((GtkWidget*)self)->window, ®ion, TRUE );
gdk_region_destroy( region );
*/
self->rubber_bending_x = newx;
self->rubber_bending_y = newy;
/* update selection */
for( l = self->items; l; l = l->next )
{
DesktopItem* item = (DesktopItem*)l->data;
gboolean selected;
if( gdk_rectangle_intersect( &new_rect, &item->icon_rect, NULL ) ||
gdk_rectangle_intersect( &new_rect, &item->text_rect, NULL ) )
selected = TRUE;
else
selected = FALSE;
if( ( item->is_selected != selected ) && ( !add || !item->is_selected ) )
{
item->is_selected = selected;
redraw_item( self, item );
}
}
}
static void open_clicked_item( DesktopItem* clicked_item )
{
char* path = NULL;
if( vfs_file_info_is_dir( clicked_item->fi ) ) /* this is a folder */
{
GList* sel_files = NULL;
sel_files = g_list_prepend( sel_files, clicked_item->fi );
open_folders( sel_files );
g_list_free( sel_files );
}
else /* regular files */
{
GList* sel_files = NULL;
sel_files = g_list_prepend( sel_files, clicked_item->fi );
// archive?
if( sel_files && !xset_get_b( "arc_def_open" ) )
{
VFSFileInfo* file = vfs_file_info_ref( (VFSFileInfo*)sel_files->data );
VFSMimeType* mime_type = vfs_file_info_get_mime_type( file );
path = g_build_filename( vfs_get_desktop_dir(),
vfs_file_info_get_name( file ), NULL );
vfs_file_info_unref( file );
if ( ptk_file_archiver_is_format_supported( mime_type, TRUE ) )
{
int no_write_access = ptk_file_browser_no_access (
vfs_get_desktop_dir(), NULL );
// first file is archive - use default archive action
if ( xset_get_b( "arc_def_ex" ) && !no_write_access )
{
ptk_file_archiver_extract( NULL, sel_files,
vfs_get_desktop_dir(), vfs_get_desktop_dir() );
goto _done;
}
else if ( xset_get_b( "arc_def_exto" ) ||
( xset_get_b( "arc_def_ex" ) && no_write_access &&
!( g_str_has_suffix( path, ".gz" ) &&
!g_str_has_suffix( path, ".tar.gz" ) ) ) )
{
ptk_file_archiver_extract( NULL, sel_files,
vfs_get_desktop_dir(), NULL );
goto _done;
}
else if ( xset_get_b( "arc_def_list" ) &&
!( g_str_has_suffix( path, ".gz" ) &&
!g_str_has_suffix( path, ".tar.gz" ) ) )
{
ptk_file_archiver_extract( NULL, sel_files,
vfs_get_desktop_dir(), "////LIST" );
goto _done;
}
}
}
if ( sel_files && xset_get_b( "iso_auto" ) )
{
VFSFileInfo* file = vfs_file_info_ref( (VFSFileInfo*)sel_files->data );
VFSMimeType* mime_type = vfs_file_info_get_mime_type( file );
if ( mime_type && (
!strcmp( vfs_mime_type_get_type( mime_type ), "application/x-cd-image" ) ||
!strcmp( vfs_mime_type_get_type( mime_type ), "application/x-iso9660-image" ) ||
g_str_has_suffix( vfs_file_info_get_name( file ), ".iso" ) ||
g_str_has_suffix( vfs_file_info_get_name( file ), ".img" ) ) )
{
char* str = g_find_program_in_path( "udevil" );
if ( str )
{
g_free( str );
str = g_build_filename( vfs_get_desktop_dir(),
vfs_file_info_get_name( file ), NULL );
mount_iso( NULL, str );
g_free( str );
vfs_file_info_unref( file );
goto _done;
}
}
vfs_file_info_unref( file );
}
ptk_open_files_with_app( vfs_get_desktop_dir(), sel_files, NULL, NULL,
TRUE, FALSE ); //MOD
_done:
g_free( path );
g_list_free( sel_files );
}
}
void show_desktop_menu( DesktopWindow* self, guint event_button,
guint32 event_time )
{
GtkMenu* popup;
DesktopItem *item;
GList* l;
GList* sel = desktop_window_get_selected_items( self );
if ( sel )
{
item = (DesktopItem*)sel->data;
char* file_path = g_build_filename( vfs_get_desktop_dir(),
item->fi->name, NULL );
for ( l = sel; l; l = l->next )
l->data = vfs_file_info_ref( ((DesktopItem*)l->data)->fi );
popup = GTK_MENU( ptk_file_menu_new( self, NULL, file_path,
item->fi, vfs_get_desktop_dir(), sel ) );
g_free( file_path );
}
else
popup = GTK_MENU( ptk_file_menu_new( self, NULL, NULL, NULL,
vfs_get_desktop_dir(), NULL ) );
gtk_menu_popup( popup, NULL, NULL, NULL, NULL, event_button,
event_time );
}
gboolean on_button_press( GtkWidget* w, GdkEventButton* evt )
{
DesktopWindow* self = (DesktopWindow*)w;
DesktopItem *item, *clicked_item = NULL;
GList* l;
clicked_item = hit_test( DESKTOP_WINDOW(w), (int)evt->x, (int)evt->y );
if( evt->type == GDK_BUTTON_PRESS )
{
if( evt->button == 1 ) /* left button */
{
self->button_pressed = TRUE; /* store button state for drag & drop */
self->drag_start_x = evt->x;
self->drag_start_y = evt->y;
}
/* if ctrl / shift is not pressed, deselect all. */
if( ! (evt->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) )
{
/* don't cancel selection if clicking on selected items OR
* clicking on desktop with right button */
if( !( (evt->button == 1 || evt->button == 3 || evt->button == 0)
&& clicked_item && clicked_item->is_selected)
&& !( !clicked_item && evt->button == 3 ) )
desktop_window_select( self, DW_SELECT_NONE );
}
if( clicked_item )
{
if( evt->state & ( GDK_CONTROL_MASK) )
clicked_item->is_selected = ! clicked_item->is_selected;
else if ( evt->state & ( GDK_SHIFT_MASK ) )
{
// select range from last focus
if ( self->focus )
{
int i;
l = g_list_find( self->items, clicked_item );
int pos_clicked = g_list_position( self->items, l );
l = g_list_find( self->items, self->focus );
int pos_focus = g_list_position( self->items, l );
if ( pos_focus >= 0 && pos_clicked >= 0 )
{
if ( pos_clicked < pos_focus )
{
i = pos_focus;
pos_focus = pos_clicked;
pos_clicked = i;
}
for ( i = pos_focus; i <= pos_clicked; i++ )
{
l = g_list_nth( self->items, i );
if ( l )
{
item = (DesktopItem*) l->data;
item->is_selected = TRUE;
redraw_item( DESKTOP_WINDOW(w), item );
}
}
}
}
clicked_item->is_selected = TRUE;
}
else
clicked_item->is_selected = TRUE;
if( self->focus && self->focus != clicked_item )
{
DesktopItem* old_focus = self->focus;
if( old_focus )
redraw_item( DESKTOP_WINDOW(w), old_focus );
}
self->focus = clicked_item;
redraw_item( self, clicked_item );
if( evt->button == 3 ) /* right click */
{
GList* sel = desktop_window_get_selected_items( self );
if( sel )
{
item = (DesktopItem*)sel->data;
GtkMenu* popup;
GList* l;
char* file_path = g_build_filename( vfs_get_desktop_dir(),
item->fi->name, NULL );
for( l = sel; l; l = l->next )
l->data = vfs_file_info_ref( ((DesktopItem*)l->data)->fi );
popup = GTK_MENU(ptk_file_menu_new( self, NULL, file_path,
item->fi, vfs_get_desktop_dir(), sel ));
g_free( file_path );
gtk_menu_popup( popup, NULL, NULL, NULL, NULL, evt->button,
evt->time );
}
}
goto out;
}
else /* no item is clicked */
{
if( evt->button == 3 ) /* right click on the blank area */
{
if( ! app_settings.show_wm_menu ) /* if our desktop menu is used */
{
show_desktop_menu( self, evt->button, evt->time );
goto out; // don't forward the event to root win
}
}
else if( evt->button == 1 )
{
self->rubber_bending = TRUE;
/* FIXME: if you foward the event here, this will break rubber bending... */
/* forward the event to root window */
/* forward_event_to_rootwin( gtk_widget_get_screen(w), evt ); */
gtk_grab_add( w );
self->rubber_bending_x = evt->x;
self->rubber_bending_y = evt->y;
goto out;
}
}
}
else if( evt->type == GDK_2BUTTON_PRESS )
{
if( clicked_item && evt->button == 1) /* left double click */
{
open_clicked_item( clicked_item );
goto out;
}
}
/* forward the event to root window */
forward_event_to_rootwin( gtk_widget_get_screen(w), (GdkEvent*)evt );
out:
if( ! gtk_widget_has_focus(w) )
{
/* g_debug( "we don't have the focus, grab it!" ); */
gtk_widget_grab_focus( w );
}
return TRUE;
}
gboolean on_button_release( GtkWidget* w, GdkEventButton* evt )
{
DesktopWindow* self = (DesktopWindow*)w;
DesktopItem* clicked_item = hit_test( self, evt->x, evt->y );
self->button_pressed = FALSE;
if( self->rubber_bending )
{
update_rubberbanding( self, evt->x, evt->y, !!(evt->state & GDK_CONTROL_MASK) );
gtk_grab_remove( w );
self->rubber_bending = FALSE;
}
else if( self->dragging )
{
self->dragging = FALSE;
}
else if( self->single_click && evt->button == 1 && (GDK_BUTTON1_MASK == evt->state) )
{
if( clicked_item )
{
open_clicked_item( clicked_item );
return TRUE;
}
}
/* forward the event to root window */
if( ! clicked_item )
forward_event_to_rootwin( gtk_widget_get_screen(w), (GdkEvent*)evt );
return TRUE;
}
static gboolean on_single_click_timeout( DesktopWindow* self )
{
GtkWidget* w = (GtkWidget*)self;
GdkEventButton evt;
int x, y;
/* generate a fake button press */
/* FIXME: will this cause any problem? */
evt.type = GDK_BUTTON_PRESS;
evt.window = gtk_widget_get_window(w);
gdk_window_get_pointer( gtk_widget_get_window(w), &x, &y, &evt.state );
evt.x = x;
evt.y = y;
evt.state |= GDK_BUTTON_PRESS_MASK;
evt.state &= ~GDK_BUTTON_MOTION_MASK;
on_button_press( GTK_WIDGET(self), &evt );
return FALSE;
}
gboolean on_mouse_move( GtkWidget* w, GdkEventMotion* evt )
{
DesktopWindow* self = (DesktopWindow*)w;
if( ! self->button_pressed )
{
if( self->single_click )
{
DesktopItem* item = hit_test( self, evt->x, evt->y );
if( item != self->hover_item )
{
if( 0 != self->single_click_timeout_handler )
{
g_source_remove( self->single_click_timeout_handler );
self->single_click_timeout_handler = 0;
}
}
if( item )
{
gdk_window_set_cursor( gtk_widget_get_window(w), self->hand_cursor );
/* FIXME: timeout should be customizable */
if( 0 == self->single_click_timeout_handler )
self->single_click_timeout_handler =
g_timeout_add( SINGLE_CLICK_TIMEOUT,
(GSourceFunc)on_single_click_timeout, self );
}
else
{
gdk_window_set_cursor( gtk_widget_get_window(w), NULL );
}
self->hover_item = item;
}
return TRUE;
}
if( self->dragging )
{
}
else if( self->rubber_bending )
{
update_rubberbanding( self, evt->x, evt->y, !!(evt->state & GDK_CONTROL_MASK) );
}
else
{
if ( gtk_drag_check_threshold( w,
self->drag_start_x,
self->drag_start_y,
evt->x, evt->y))
{
GtkTargetList* target_list;
gboolean virtual_item = FALSE;
GList* sels = desktop_window_get_selected_items(self);
self->dragging = TRUE;
if( sels && sels->next == NULL ) /* only one item selected */
{
DesktopItem* item = (DesktopItem*)sels->data;
if( item->fi->flags & VFS_FILE_INFO_VIRTUAL )
virtual_item = TRUE;
}
g_list_free( sels );
if( virtual_item )
target_list = gtk_target_list_new( drag_targets + 1, G_N_ELEMENTS(drag_targets) - 1 );
else
target_list = gtk_target_list_new( drag_targets, G_N_ELEMENTS(drag_targets) );
gtk_drag_begin( w, target_list,
GDK_ACTION_COPY|GDK_ACTION_MOVE|GDK_ACTION_LINK,
1, (GdkEvent*)evt );
gtk_target_list_unref( target_list );
}
}
return TRUE;
}
void on_drag_begin( GtkWidget* w, GdkDragContext* ctx )
{
DesktopWindow* self = (DesktopWindow*)w;
}
static GdkAtom get_best_target_at_dest( DesktopWindow* self, GdkDragContext* ctx, gint x, gint y )
{
DesktopItem* item;
GdkAtom expected_target = 0;
if( G_LIKELY(gdk_drag_context_list_targets( ctx ) ) )
{
if( gdk_drag_context_get_selected_action( ctx ) != GDK_ACTION_MOVE )
expected_target = text_uri_list_atom;
else
{
item = hit_test( self, x, y );
if( item ) /* drag over a desktpo item */
{
GList* sels;
sels = desktop_window_get_selected_items( self );
/* drag over the selected items themselves */
if( g_list_find( sels, item ) )
expected_target = desktop_icon_atom;
else
expected_target = text_uri_list_atom;
g_list_free( sels );
}
else /* drag over blank area, check if it's a desktop icon first. */
{
if( g_list_find( gdk_drag_context_list_targets( ctx ), GUINT_TO_POINTER(desktop_icon_atom) ) )
return desktop_icon_atom;
expected_target = text_uri_list_atom;
}
}
if( g_list_find( gdk_drag_context_list_targets( ctx ), GUINT_TO_POINTER(expected_target) ) )
return expected_target;
}
return GDK_NONE;
}
#define GDK_ACTION_ALL (GDK_ACTION_MOVE|GDK_ACTION_COPY|GDK_ACTION_LINK)
gboolean on_drag_motion( GtkWidget* w, GdkDragContext* ctx, gint x, gint y, guint time )
{
DesktopWindow* self = (DesktopWindow*)w;
//DesktopItem* item;
//GdkAtom target;
if( ! self->drag_entered )
{
self->drag_entered = TRUE;
}
if( self->rubber_bending )
{
/* g_debug("rubber banding!"); */
return TRUE;
}
/* g_debug( "suggest: %d, action = %d", ctx->suggested_action, ctx->action ); */
if( g_list_find( gdk_drag_context_list_targets( ctx ), GUINT_TO_POINTER(text_uri_list_atom) ) )
{
GdkDragAction suggested_action = 0;
/* Only 'move' is available. The user force move action by pressing Shift key */
if( (gdk_drag_context_get_actions( ctx ) & GDK_ACTION_ALL) == GDK_ACTION_MOVE )
suggested_action = GDK_ACTION_MOVE;
/* Only 'copy' is available. The user force copy action by pressing Ctrl key */
else if( (gdk_drag_context_get_actions( ctx ) & GDK_ACTION_ALL) == GDK_ACTION_COPY )
suggested_action = GDK_ACTION_COPY;
/* Only 'link' is available. The user force link action by pressing Shift+Ctrl key */
else if( (gdk_drag_context_get_actions( ctx ) & GDK_ACTION_ALL) == GDK_ACTION_LINK )
suggested_action = GDK_ACTION_LINK;
/* Several different actions are available. We have to figure out a good default action. */
else
{
if( get_best_target_at_dest(self, ctx, x, y ) == text_uri_list_atom )
{
self->pending_drop_action = TRUE;
/* check the status of drop site */
gtk_drag_get_data( w, ctx, text_uri_list_atom, time );
return TRUE;
}
else /* move desktop icon */
{
suggested_action = GDK_ACTION_MOVE;
}
}
gdk_drag_status( ctx, suggested_action, time );
}
else if( g_list_find( gdk_drag_context_list_targets( ctx ), GUINT_TO_POINTER(desktop_icon_atom) ) ) /* moving desktop icon */
{
gdk_drag_status( ctx, GDK_ACTION_MOVE, time );
}
else
{
gdk_drag_status (ctx, 0, time);
}
return TRUE;
}
gboolean on_drag_drop( GtkWidget* w, GdkDragContext* ctx, gint x, gint y, guint time )
{
DesktopWindow* self = (DesktopWindow*)w;
GdkAtom target = get_best_target_at_dest( self, ctx, x, y );
/* g_debug("DROP: %s!", gdk_atom_name(target) ); */
if( target == GDK_NONE )
return FALSE;
if( target == text_uri_list_atom || target == desktop_icon_atom )
gtk_drag_get_data( w, ctx, target, time );
return TRUE;
}
void on_drag_data_get( GtkWidget* w, GdkDragContext* ctx, GtkSelectionData* data, guint info, guint time )
{
DesktopWindow* self = (DesktopWindow*)w;
GList *sels, *l;
char* uri_list;
gsize len;
if( info == DRAG_TARGET_URI_LIST )
{
GString *buf = g_string_sized_new( 4096 );
sels = desktop_window_get_selected_files( self );
for( l = sels; l; l = l->next )
{
VFSFileInfo* fi = (VFSFileInfo*)l->data;
char* path, *uri;
if( fi->flags & VFS_FILE_INFO_VIRTUAL )
continue;
path = g_build_filename( vfs_get_desktop_dir(), fi->name, NULL );
uri = g_filename_to_uri( path, NULL, NULL );
g_free( path );
g_string_append( buf, uri );
g_string_append( buf, "\r\n" );
g_free( uri );
}
g_list_foreach( sels, (GFunc)vfs_file_info_unref, NULL );
g_list_free( sels );
uri_list = g_convert( buf->str, buf->len, "ASCII", "UTF-8", NULL, &len, NULL);
g_string_free( buf, TRUE);
if( uri_list )
{
gtk_selection_data_set( data,
text_uri_list_atom,
8, (guchar *)uri_list, len );
g_free (uri_list);
}
}
else if( info == DRAG_TARGET_DESKTOP_ICON )
{
}
}
static char** get_files_from_selection_data(GtkSelectionData* data)
{
char** files = gtk_selection_data_get_uris(data), **pfile;
if( files )
{
/* convert uris to filenames */
for( pfile = files; *pfile; ++pfile )
{
char* file = g_filename_from_uri( *pfile, NULL, NULL );
g_free( *pfile );
if( file )
*pfile = file;
else
{
/* FIXME: This is very inefficient, but it's a rare case. */
int n = g_strv_length( pfile + 1 );
if( n > 0 )
{
memmove( pfile, file + sizeof(char*), sizeof(char*) * (n + 1) ); /* omit the path if conversion fails */
--pfile;
}
else
{
*pfile = NULL;
break;
}
}
}
}
if( files && ! *files )
{
g_strfreev( files );
files = NULL;
}
return files;
}
void on_drag_data_received( GtkWidget* w, GdkDragContext* ctx, gint x, gint y, GtkSelectionData* data, guint info, guint time )
{
DesktopWindow* self = (DesktopWindow*)w;
if( gtk_selection_data_get_target( data ) == text_uri_list_atom )
{
DesktopItem* item = hit_test( self, x, y );
char* dest_dir = NULL;
VFSFileTaskType file_action = VFS_FILE_TASK_MOVE;
PtkFileTask* task = NULL;
char** files;
int n, i;
GList* file_list;
if( (gtk_selection_data_get_length( data ) < 0) || (gtk_selection_data_get_format( data ) != 8) )
{
gtk_drag_finish( ctx, FALSE, FALSE, time );
return;
}
if ( item && vfs_file_info_is_dir( item->fi ) )
dest_dir = g_build_filename( vfs_get_desktop_dir(), item->fi->name, NULL );
/* We are just checking the suggested actions for the drop site, not really drop */
if( self->pending_drop_action )
{
GdkDragAction suggested_action = 0;
dev_t dest_dev;
struct stat statbuf; // skip stat64
if( stat( dest_dir ? dest_dir : vfs_get_desktop_dir(), &statbuf ) == 0 )
{
dest_dev = statbuf.st_dev;
if( 0 == self->drag_src_dev )
{
char** pfile;
files = get_files_from_selection_data(data);
self->drag_src_dev = dest_dev;
if( files )
{
for( pfile = files; *pfile; ++pfile )
{
if( stat( *pfile, &statbuf ) == 0 && statbuf.st_dev != dest_dev )
{
self->drag_src_dev = statbuf.st_dev;
break;
}
}
}
g_strfreev( files );
}
if( self->drag_src_dev != dest_dev ) /* src and dest are on different devices */
suggested_action = GDK_ACTION_COPY;
else
suggested_action = GDK_ACTION_MOVE;
}
g_free( dest_dir );
self->pending_drop_action = FALSE;
gdk_drag_status( ctx, suggested_action, time );
return;
}
switch ( gdk_drag_context_get_selected_action( ctx ) )
{
case GDK_ACTION_COPY:
file_action = VFS_FILE_TASK_COPY;
break;
case GDK_ACTION_LINK:
file_action = VFS_FILE_TASK_LINK;
break;
/* FIXME:
GDK_ACTION_DEFAULT, GDK_ACTION_PRIVATE, and GDK_ACTION_ASK are not handled */
default:
break;
}
files = get_files_from_selection_data( data );
if( files )
{
/* g_debug("file_atcion: %d", file_action); */
file_list = NULL;
n = g_strv_length( files );
for( i = 0; i < n; ++i )
file_list = g_list_prepend( file_list, files[i] );
g_free( files );
task = ptk_file_task_new( file_action,
file_list,
dest_dir ? dest_dir : vfs_get_desktop_dir(),
GTK_WINDOW( self ), NULL );
ptk_file_task_run( task );
}
g_free( dest_dir );
gtk_drag_finish( ctx, files != NULL, FALSE, time );
}
else if( gtk_selection_data_get_target( data ) == desktop_icon_atom ) /* moving desktop icon */
{
GList* sels = desktop_window_get_selected_items(self), *l;
int x_off = x - self->drag_start_x;
int y_off = y - self->drag_start_y;
for( l = sels; l; l = l->next )
{
DesktopItem* item = l->data;
#if 0 /* temporarily turn off */
move_item( self, item, x_off, y_off, TRUE );
#endif
/* g_debug( "move: %d, %d", x_off, y_off ); */
}
g_list_free( sels );
gtk_drag_finish( ctx, TRUE, FALSE, time );
}
}
void on_drag_leave( GtkWidget* w, GdkDragContext* ctx, guint time )
{
DesktopWindow* self = (DesktopWindow*)w;
self->drag_entered = FALSE;
self->drag_src_dev = 0;
}
void on_drag_end( GtkWidget* w, GdkDragContext* ctx )
{
DesktopWindow* self = (DesktopWindow*)w;
}
void desktop_window_rename_selected_files( DesktopWindow* win,
GList* files, const char* cwd )
{
GList* l;
VFSFileInfo* file;
for ( l = files; l; l = l->next )
{
file = (VFSFileInfo*)l->data;
if ( vfs_file_info_is_desktop_entry( file ) )
{
char* filename = g_filename_display_name( file->name );
if ( filename )
{
char* path = g_build_filename( cwd, filename, NULL );
const char* name = vfs_file_info_get_disp_name( file );
char* new_name = NULL;
char* target = g_file_read_link( path, NULL );
if ( !target )
target = g_strdup( path );
char* msg = g_strdup_printf( _("Enter new desktop item name:\n\nChanging the name of this desktop item requires modifying the contents of desktop file %s"), target );
g_free( target );
if ( !xset_text_dialog( GTK_WIDGET( win ), _("Change Desktop Item Name"), NULL, FALSE, msg,
NULL, name, &new_name, NULL, FALSE, NULL ) || !new_name )
{
g_free( msg );
g_free( path );
g_free( filename );
break;
}
g_free( msg );
if ( new_name[0] == '\0' )
{
g_free( path );
g_free( filename );
break;
}
if ( !vfs_app_desktop_rename( path, new_name ) )
{
if ( win->dir )
// in case file is a link
vfs_dir_emit_file_changed( win->dir, filename, file, FALSE );
g_free( path );
g_free( filename );
xset_msg_dialog( GTK_WIDGET( win ), GTK_MESSAGE_ERROR, _("Rename Error"), NULL, 0, _("An error occured renaming this desktop item."), NULL, NULL );
break;
}
if ( win->dir )
// in case file is a link
vfs_dir_emit_file_changed( win->dir, filename, file, FALSE );
g_free( path );
g_free( filename );
}
}
else
{
if ( !ptk_rename_file( win, NULL, cwd, file, NULL, FALSE, 0, NULL ) )
break;
}
}
}
DesktopItem* get_next_item( DesktopWindow* self, int direction )
{
DesktopItem *item, *current_item;
DesktopItem* next_item = NULL;
GList* l;
if ( self->focus )
current_item = self->focus;
else if ( self->items )
{
current_item = (DesktopItem*) self->items->data;
self->focus = current_item;
}
else
return NULL; //No items!
for ( l = self->items; l; l = l->next )
{
item = (DesktopItem*) l->data;
if ( item != current_item )
{
next_item = item;
break;
}
}
if ( next_item ) //If there are other items
{
int sign = ( direction==GDK_KEY_Down||direction==GDK_KEY_Right)? 1 : -1;
int keep_x = (direction==GDK_KEY_Down||direction==GDK_KEY_Up)? 1 : 0;
int test_x = 1 - keep_x;
int keep_y = (direction==GDK_KEY_Left||direction==GDK_KEY_Right)? 1 : 0;
int test_y = 1 - keep_y;
int diff = 32000;
int nearest_diff = diff;
int line_diff;
gboolean done = FALSE;
int myline_x = current_item->icon_rect.x;
int myline_y = current_item->icon_rect.y;
for ( l = self->items; l; l = l->next )
{
item = (DesktopItem*) l->data;
if ( item == current_item )
continue;
diff = item->icon_rect.x*test_x + item->icon_rect.y*test_y;
diff -= current_item->icon_rect.x*test_x + current_item->icon_rect.y*test_y;
diff = diff*sign; //positive diff for the valid items;
//so we have icons with variable height, let's get dirty...
line_diff = item->icon_rect.x*keep_x + item->icon_rect.y*keep_y;
line_diff -= current_item->icon_rect.x*keep_x + current_item->icon_rect.y*keep_y;
if ( line_diff < 0 )
line_diff = -line_diff; //positive line diff for adding;
diff += 2*line_diff*(diff>0?1:-1); //line_diff is more important than diff
if ( ( !line_diff || test_x ) && diff > 0 && diff < nearest_diff )
{
next_item = item;
nearest_diff = diff;
done = TRUE;
}
}
//Support for jumping through the borders to the next/prev row or column
/* self->items is sorted by columns by default, so for now let's just support up-down looping */
if ( !done && test_y )
{
GList* m;
for ( l = self->items; l; l = l->next )
{
item = (DesktopItem*) l->data;
if ( item == current_item )
{
m = sign == 1 ? l->next : l->prev;
if ( m )
{
next_item = (DesktopItem*) m->data;
done = TRUE;
}
break;
}
}
}
if ( !done )
return current_item;
else
return next_item;
}
return current_item;
}
void focus_item( DesktopWindow* self, DesktopItem* item )
{
if ( !item )
return;
DesktopItem* current = self->focus;
if ( current )
redraw_item( self, current );
self->focus = item;
redraw_item( self, item );
}
void desktop_window_select( DesktopWindow* self, DWSelectMode mode )
{
char* key;
char* name;
gboolean icase = FALSE;
if ( mode < DW_SELECT_ALL || mode > DW_SELECT_PATTERN )
return;
if ( mode == DW_SELECT_PATTERN )
{
// get pattern from user (store in ob1 so it's not saved)
XSet* set = xset_get( "select_patt" );
if ( !xset_text_dialog( GTK_WIDGET( self ), _("Select By Pattern"), NULL, FALSE, _("Enter pattern to select files and folders:\n\nIf your pattern contains any uppercase characters, the matching will be case sensitive.\n\nExample: *sp*e?m*\n\nTIP: You can also enter '%% PATTERN' in the path bar."),
NULL, set->ob1, &set->ob1,
NULL, FALSE, NULL ) || !set->ob1 )
return;
key = set->ob1;
// case insensitive search ?
char* lower_key = g_utf8_strdown( key, -1 );
if ( !strcmp( lower_key, key ) )
{
// key is all lowercase so do icase search
icase = TRUE;
}
g_free( lower_key );
}
else
key = NULL;
GList* l;
DesktopItem* item;
gboolean sel;
for( l = self->items; l; l = l->next )
{
item = (DesktopItem*) l->data;
if ( mode == DW_SELECT_ALL )
sel = TRUE;
else if ( mode == DW_SELECT_NONE )
sel = FALSE;
else if ( mode == DW_SELECT_INVERSE )
sel = !item->is_selected;
else
{
// DW_SELECT_PATTERN - test name
name = (char*)vfs_file_info_get_disp_name( item->fi );
if ( icase )
name = g_utf8_strdown( name, -1 );
sel = fnmatch( key, name, 0 ) == 0;
if ( icase )
g_free( name );
}
if ( sel != item->is_selected )
{
item->is_selected = sel;
redraw_item( self, item );
}
}
}
void select_item( DesktopWindow* self, DesktopItem* item, gboolean val )
{
if ( !item )
return;
item->is_selected = val;
redraw_item( self, item );
}
gboolean on_key_press( GtkWidget* w, GdkEventKey* event )
{
DesktopWindow* desktop = (DesktopWindow*)w;
int keymod = ( event->state & ( GDK_SHIFT_MASK | GDK_CONTROL_MASK |
GDK_MOD1_MASK | GDK_SUPER_MASK | GDK_HYPER_MASK | GDK_META_MASK ) );
if ( event->keyval == 0 )
return FALSE;
GList* l;
XSet* set;
char* xname;
for ( l = xsets; l; l = l->next )
{
if ( ((XSet*)l->data)->shared_key )
{
// set has shared key
set = xset_get( ((XSet*)l->data)->shared_key );
if ( set->key == event->keyval && set->keymod == keymod )
{
// shared key match
if ( g_str_has_prefix( set->name, "panel" ) )
return FALSE;
goto _key_found; // for speed
}
else
continue;
}
if ( ((XSet*)l->data)->key == event->keyval
&& ((XSet*)l->data)->keymod == keymod )
{
set = (XSet*)l->data;
_key_found:
// run menu_cb
if ( set->menu_style < XSET_MENU_SUBMENU )
{
set->browser = NULL;
set->desktop = desktop;
xset_menu_cb( NULL, set ); // also does custom activate
}
if ( !set->lock )
return TRUE;
// handlers
if ( !strcmp( set->name, "new_app" ) )
desktop_window_add_application( desktop );
else if ( g_str_has_prefix( set->name, "desk_" ) )
{
if ( g_str_has_prefix( set->name, "desk_sort_" ) )
{
int by;
char* xname = set->name + 10;
if ( !strcmp( xname, "name" ) )
by = DW_SORT_BY_NAME;
else if ( !strcmp( xname, "size" ) )
by = DW_SORT_BY_SIZE;
else if ( !strcmp( xname, "type" ) )
by = DW_SORT_BY_TYPE;
else if ( !strcmp( xname, "date" ) )
by = DW_SORT_BY_MTIME;
else
{
if ( !strcmp( xname, "ascend" ) )
by = GTK_SORT_ASCENDING;
else if ( !strcmp( xname, "descend" ) )
by = GTK_SORT_DESCENDING;
else
return TRUE;
desktop_window_sort_items( desktop, desktop->sort_by, by );
return TRUE;
}
desktop_window_sort_items( desktop, by, desktop->sort_type );
}
else if ( !strcmp( set->name, "desk_pref" ) )
fm_edit_preference( GTK_WINDOW( desktop ), PREF_DESKTOP );
}
else if ( g_str_has_prefix( set->name, "paste_" ) )
{
xname = set->name + 6;
if ( !strcmp( xname, "link" ) )
ptk_clipboard_paste_links(
GTK_WINDOW( gtk_widget_get_toplevel(
GTK_WIDGET( desktop ) ) ),
vfs_get_desktop_dir(), NULL );
else if ( !strcmp( xname, "target" ) )
ptk_clipboard_paste_targets( GTK_WINDOW(
gtk_widget_get_toplevel( GTK_WIDGET( desktop ) ) ),
vfs_get_desktop_dir(),
NULL );
else if ( !strcmp( xname, "as" ) )
ptk_file_misc_paste_as( desktop, NULL, vfs_get_desktop_dir() );
}
else if ( g_str_has_prefix( set->name, "select_" ) )
{
DWSelectMode mode;
xname = set->name + 7;
if ( !strcmp( xname, "all" ) )
mode = DW_SELECT_ALL;
else if ( !strcmp( xname, "un" ) )
mode = DW_SELECT_NONE;
else if ( !strcmp( xname, "invert" ) )
mode = DW_SELECT_INVERSE;
else if ( !strcmp( xname, "patt" ) )
mode = DW_SELECT_PATTERN;
else
return TRUE;
desktop_window_select( desktop, mode );
}
else
// all the rest require ptkfilemenu data
ptk_file_menu_action( desktop, NULL, set->name );
return TRUE;
}
}
if ( keymod == GDK_CONTROL_MASK )
{
switch ( event->keyval )
{
case GDK_KEY_Down:
case GDK_KEY_Up:
case GDK_KEY_Left:
case GDK_KEY_Right:
focus_item( desktop, get_next_item( desktop, event->keyval ) );
return TRUE;
case GDK_KEY_space:
if ( desktop->focus )
select_item( desktop, desktop->focus, !desktop->focus->is_selected );
return TRUE;
}
}
else if ( keymod == 0 )
{
switch ( event->keyval )
{
case GDK_KEY_Return:
case GDK_KEY_space:
if ( desktop->focus )
open_clicked_item( desktop->focus );
return TRUE;
case GDK_KEY_Down:
case GDK_KEY_Up:
case GDK_KEY_Left:
case GDK_KEY_Right:
desktop_window_select( desktop, DW_SELECT_NONE );
focus_item( desktop, get_next_item( desktop, event->keyval ) );
if ( desktop->focus )
select_item( desktop, desktop->focus, TRUE );
return TRUE;
case GDK_KEY_Menu:
show_desktop_menu( desktop, 0, event->time );
return TRUE;
}
}
return FALSE;
}
void on_style_set( GtkWidget* w, GtkStyle* prev )
{
DesktopWindow* self = (DesktopWindow*)w;
PangoContext* pc;
PangoFontMetrics *metrics;
int font_h;
pc = gtk_widget_get_pango_context( (GtkWidget*)self );
metrics = pango_context_get_metrics(
pc, gtk_widget_get_style((GtkWidget*)self)->font_desc,
pango_context_get_language(pc));
font_h = pango_font_metrics_get_ascent(metrics) + pango_font_metrics_get_descent (metrics);
font_h /= PANGO_SCALE;
}
void on_realize( GtkWidget* w )
{
guint32 val;
DesktopWindow* self = (DesktopWindow*)w;
GTK_WIDGET_CLASS(parent_class)->realize( w );
gdk_window_set_type_hint( gtk_widget_get_window(w),
GDK_WINDOW_TYPE_HINT_DESKTOP );
gtk_window_set_skip_pager_hint( GTK_WINDOW(w), TRUE );
gtk_window_set_skip_taskbar_hint( GTK_WINDOW(w), TRUE );
gtk_window_set_resizable( (GtkWindow*)w, FALSE );
/* This is borrowed from fbpanel */
#define WIN_HINTS_SKIP_FOCUS (1<<0) /* skip "alt-tab" */
val = WIN_HINTS_SKIP_FOCUS;
XChangeProperty(gdk_x11_get_default_xdisplay(), GDK_WINDOW_XID(gtk_widget_get_window(w)),
XInternAtom(gdk_x11_get_default_xdisplay(), "_WIN_HINTS", False), XA_CARDINAL, 32,
PropModeReplace, (unsigned char *) &val, 1);
// if( self->background )
// gdk_window_set_back_pixmap( w->window, self->background, FALSE );
}
gboolean on_focus_in( GtkWidget* w, GdkEventFocus* evt )
{
DesktopWindow* self = (DesktopWindow*) w;
//sfm gtk3 gtk_widget_grab_focus( w ) not equivalent
//gtk_widget_grab_focus( w );
#if GTK_CHECK_VERSION (3, 0, 0)
// TODO
#else
GTK_WIDGET_SET_FLAGS( w, GTK_HAS_FOCUS );
#endif
if( self->focus )
redraw_item( self, self->focus );
return FALSE;
}
gboolean on_focus_out( GtkWidget* w, GdkEventFocus* evt )
{
DesktopWindow* self = (DesktopWindow*) w;
if( self->focus )
{
//sfm gtk3 restored - can GTK_WIDGET_UNSET_FLAGS be removed without changes?
#if GTK_CHECK_VERSION (3, 0, 0)
// TODO
#else
GTK_WIDGET_UNSET_FLAGS( w, GTK_HAS_FOCUS );
#endif
redraw_item( self, self->focus );
}
return FALSE;
}
/*
gboolean on_scroll( GtkWidget *w, GdkEventScroll *evt, gpointer user_data )
{
forward_event_to_rootwin( gtk_widget_get_screen( w ), ( GdkEvent* ) evt );
return TRUE;
}
*/
void on_sort_by_name ( GtkMenuItem *menuitem, DesktopWindow* self )
{
desktop_window_sort_items( self, DW_SORT_BY_NAME, self->sort_type );
}
void on_sort_by_size ( GtkMenuItem *menuitem, DesktopWindow* self )
{
desktop_window_sort_items( self, DW_SORT_BY_SIZE, self->sort_type );
}
void on_sort_by_mtime ( GtkMenuItem *menuitem, DesktopWindow* self )
{
desktop_window_sort_items( self, DW_SORT_BY_MTIME, self->sort_type );
}
void on_sort_by_type ( GtkMenuItem *menuitem, DesktopWindow* self )
{
desktop_window_sort_items( self, DW_SORT_BY_TYPE, self->sort_type );
}
void on_sort_custom( GtkMenuItem *menuitem, DesktopWindow* self )
{
desktop_window_sort_items( self, DW_SORT_CUSTOM, self->sort_type );
}
void on_sort_ascending( GtkMenuItem *menuitem, DesktopWindow* self )
{
desktop_window_sort_items( self, self->sort_by, GTK_SORT_ASCENDING );
}
void on_sort_descending( GtkMenuItem *menuitem, DesktopWindow* self )
{
desktop_window_sort_items( self, self->sort_by, GTK_SORT_DESCENDING );
}
void on_paste( GtkMenuItem *menuitem, DesktopWindow* self )
{
const gchar* dest_dir = vfs_get_desktop_dir();
ptk_clipboard_paste_files( NULL, dest_dir, NULL );
}
void desktop_window_on_autoopen_cb( gpointer task, gpointer aop )
{
if ( !aop )
return;
AutoOpenCreate* ao = (AutoOpenCreate*)aop;
DesktopWindow* self = (DesktopWindow*)ao->file_browser;
if ( ao->path && g_file_test( ao->path, G_FILE_TEST_EXISTS ) )
{
char* cwd = g_path_get_dirname( ao->path );
VFSFileInfo* file;
// select item on desktop
if ( GTK_IS_WINDOW( self ) && self->dir &&
!g_strcmp0( cwd, vfs_get_desktop_dir() ) )
{
char* name = g_path_get_basename( ao->path );
// force file created notify
vfs_dir_emit_file_created( self->dir, name, TRUE );
vfs_dir_flush_notify_cache();
// find item on desktop
GList* l;
DesktopItem* item;
for ( l = self->items; l; l = l->next )
{
item = (DesktopItem*)l->data;
if ( !g_strcmp0( vfs_file_info_get_name( item->fi ), name ) )
break;
}
if ( l ) // found
{
desktop_window_select( self, DW_SELECT_NONE );
select_item( self, (DesktopItem*)l->data, TRUE );
focus_item( self, (DesktopItem*)l->data );
}
g_free( name );
}
// open file/folder
if ( ao->open_file )
{
file = vfs_file_info_new();
vfs_file_info_get( file, ao->path, NULL );
GList* sel_files = NULL;
sel_files = g_list_prepend( sel_files, file );
if ( g_file_test( ao->path, G_FILE_TEST_IS_DIR ) )
{
gdk_threads_enter();
open_folders( sel_files );
gdk_threads_leave();
}
else
ptk_open_files_with_app( cwd, sel_files,
NULL, NULL, FALSE, TRUE );
vfs_file_info_unref( file );
g_list_free( sel_files );
}
g_free( cwd );
}
g_free( ao->path );
g_slice_free( AutoOpenCreate, ao );
}
void on_settings( GtkMenuItem *menuitem, DesktopWindow* self )
{
fm_edit_preference( GTK_WINDOW( self ), PREF_DESKTOP );
}
/* private methods */
void calc_item_size( DesktopWindow* self, DesktopItem* item )
{
PangoLayoutLine* line;
int line_h;
item->box.width = self->item_w;
item->box.height = self->y_pad * 2;
item->box.height += self->icon_size;
item->box.height += self->spacing;
pango_layout_set_text( self->pl, item->fi->disp_name, -1 );
pango_layout_set_wrap( self->pl, PANGO_WRAP_WORD_CHAR ); /* wrap the text */
pango_layout_set_ellipsize( self->pl, PANGO_ELLIPSIZE_NONE );
if( pango_layout_get_line_count(self->pl) >= 2 ) /* there are more than 2 lines */
{
/* we only allow displaying two lines, so let's get the second line */
/* Pango only provide version check macros in the latest versions...
* So there is no point in making this check.
* FIXME: this check should be done ourselves in configure.
*/
#if defined (PANGO_VERSION_CHECK)
#if PANGO_VERSION_CHECK( 1, 16, 0 )
line = pango_layout_get_line_readonly( self->pl, 1 );
#else
line = pango_layout_get_line( self->pl, 1 );
#endif
#else
line = pango_layout_get_line( self->pl, 1 );
#endif
item->len1 = line->start_index; /* this the position where the first line wraps */
/* OK, now we layout these 2 lines separately */
pango_layout_set_text( self->pl, item->fi->disp_name, item->len1 );
pango_layout_get_pixel_size( self->pl, NULL, &line_h );
item->text_rect.height = line_h;
}
else
{
item->text_rect.height = 0;
}
pango_layout_set_wrap( self->pl, 0 ); /* wrap the text */
pango_layout_set_ellipsize( self->pl, PANGO_ELLIPSIZE_END );
pango_layout_set_text( self->pl, item->fi->disp_name + item->len1, -1 );
pango_layout_get_pixel_size( self->pl, NULL, &line_h );
item->text_rect.height += line_h;
item->text_rect.width = 100;
item->box.height += item->text_rect.height;
item->icon_rect.width = item->icon_rect.height = self->icon_size;
}
void layout_items( DesktopWindow* self )
{
GList* l;
DesktopItem* item;
GtkWidget* widget = (GtkWidget*)self;
int x, y, w, y2;
self->item_w = MAX( self->label_w, self->icon_size ) + self->x_pad * 2;
x = self->wa.x + self->x_margin;
y = self->wa.y + self->y_margin;
pango_layout_set_width( self->pl, 100 * PANGO_SCALE );
for( l = self->items; l; l = l->next )
{
item = (DesktopItem*)l->data;
item->box.x = x;
item->box.y = y;
item->box.width = self->item_w;
calc_item_size( self, item );
y2 = self->wa.y + self->wa.height - self->y_margin; /* bottom */
if( y + item->box.height > y2 ) /* bottom is reached */
{
y = self->wa.y + self->y_margin;
item->box.y = y;
y += item->box.height;
x += self->item_w; /* go to the next column */
item->box.x = x;
}
else /* bottom is not reached */
{
y += item->box.height; /* move to the next row */
}
item->icon_rect.x = item->box.x + (item->box.width - self->icon_size) / 2;
item->icon_rect.y = item->box.y + self->y_pad;
item->text_rect.x = item->box.x + self->x_pad;
item->text_rect.y = item->box.y + self->y_pad + self->icon_size + self->spacing;
}
gtk_widget_queue_draw( GTK_WIDGET(self) );
}
void on_file_listed( VFSDir* dir, gboolean is_cancelled, DesktopWindow* self )
{
GList* l, *items = NULL;
VFSFileInfo* fi;
DesktopItem* item;
g_mutex_lock( dir->mutex );
for( l = dir->file_list; l; l = l->next )
{
fi = (VFSFileInfo*)l->data;
if( fi->name[0] == '.' ) /* skip the hidden files */
continue;
item = g_slice_new0( DesktopItem );
item->fi = vfs_file_info_ref( fi );
items = g_list_prepend( items, item );
/* item->icon = vfs_file_info_get_big_icon( fi ); */
if( vfs_file_info_is_image( fi ) )
vfs_thumbnail_loader_request( dir, fi, TRUE );
}
g_mutex_unlock( dir->mutex );
self->items = NULL;
self->items = g_list_sort_with_data( items, get_sort_func(self), self );
/*
// Make an item for Home dir
fi = vfs_file_info_new();
fi->disp_name = g_strdup( _("My Documents") );
fi->mime_type = vfs_mime_type_get_from_type( XDG_MIME_TYPE_DIRECTORY );
fi->name = g_strdup( g_get_home_dir() );
fi->mode |= S_IFDIR;
fi->flags |= VFS_FILE_INFO_VIRTUAL; // this is a virtual file which doesn't exist on the file system
fi->big_thumbnail = gtk_icon_theme_load_icon(gtk_icon_theme_get_default(), "gnome-fs-home", self->icon_size, 0, NULL );
if( ! fi->big_thumbnail )
fi->big_thumbnail = gtk_icon_theme_load_icon(gtk_icon_theme_get_default(), "folder-home", self->icon_size, 0, NULL );
item = g_slice_new0( DesktopItem );
item->fi = fi;
// item->icon = vfs_file_info_get_big_thumbnail( fi );
self->items = g_list_prepend( self->items, item );
*/
layout_items( self );
}
void on_thumbnail_loaded( VFSDir* dir, VFSFileInfo* fi, DesktopWindow* self )
{
GList* l;
GtkWidget* w = (GtkWidget*)self;
for( l = self->items; l; l = l->next )
{
DesktopItem* item = (DesktopItem*) l->data;
if( item->fi == fi )
{
/*
if( item->icon )
g_object_unref( item->icon );
item->icon = vfs_file_info_get_big_thumbnail( fi );
*/
redraw_item( self, item );
return;
}
}
}
void on_file_created( VFSDir* dir, VFSFileInfo* file, gpointer user_data )
{
GList *l;
DesktopWindow* self = (DesktopWindow*)user_data;
DesktopItem* item;
/* don't show hidden files */
if( file->name[0] == '.' )
return;
/* prevent duplicated items */
for( l = self->items; l; l = l->next )
{
item = (DesktopItem*)l->data;
if( strcmp( file->name, item->fi->name ) == 0 )
return;
}
item = g_slice_new0( DesktopItem );
item->fi = vfs_file_info_ref( file );
/* item->icon = vfs_file_info_get_big_icon( file ); */
self->items = g_list_insert_sorted_with_data( self->items, item,
get_sort_func(self), self );
/* FIXME: we shouldn't update the whole screen */
/* FIXME: put this in idle handler with priority higher than redraw but lower than resize */
layout_items( self );
}
void on_file_deleted( VFSDir* dir, VFSFileInfo* file, gpointer user_data )
{
GList *l;
DesktopWindow* self = (DesktopWindow*)user_data;
DesktopItem* item;
/* FIXME: special handling is needed here */
if( ! file )
return;
/* don't deal with hidden files */
if( file->name[0] == '.' )
return;
/* find items */
for( l = self->items; l; l = l->next )
{
item = (DesktopItem*)l->data;
if( item->fi == file )
break;
}
if( l ) /* found */
{
item = (DesktopItem*)l->data;
self->items = g_list_delete_link( self->items, l );
desktop_item_free( item );
/* FIXME: we shouldn't update the whole screen */
/* FIXME: put this in idle handler with priority higher than redraw but lower than resize */
layout_items( self );
}
}
void on_file_changed( VFSDir* dir, VFSFileInfo* file, gpointer user_data )
{
GList *l;
DesktopWindow* self = (DesktopWindow*)user_data;
DesktopItem* item;
GtkWidget* w = (GtkWidget*)self;
/* don't touch hidden files */
if( file->name[0] == '.' )
return;
/* find items */
for( l = self->items; l; l = l->next )
{
item = (DesktopItem*)l->data;
if( item->fi == file )
break;
}
if( l ) /* found */
{
item = (DesktopItem*)l->data;
/*
if( item->icon )
g_object_unref( item->icon );
item->icon = vfs_file_info_get_big_icon( file );
*/
if( gtk_widget_get_visible( w ) )
{
/* redraw the item */
redraw_item( self, item );
}
}
}
void desktop_window_copycmd( DesktopWindow* desktop, GList* sel_files,
char* cwd, char* setname )
{
if ( !setname || !desktop || !sel_files )
return;
XSet* set2;
char* copy_dest = NULL;
char* move_dest = NULL;
char* path;
if ( !strcmp( setname, "copy_loc_last" ) )
{
set2 = xset_get( "copy_loc_last" );
copy_dest = g_strdup( set2->desc );
}
else if ( !strcmp( setname, "move_loc_last" ) )
{
set2 = xset_get( "copy_loc_last" );
move_dest = g_strdup( set2->desc );
}
else if ( strcmp( setname, "copy_loc" ) && strcmp( setname, "move_loc" ) )
return;
if ( !strcmp( setname, "copy_loc" ) || !strcmp( setname, "move_loc" ) ||
( !copy_dest && !move_dest ) )
{
char* folder;
set2 = xset_get( "copy_loc_last" );
if ( set2->desc )
folder = set2->desc;
else
folder = cwd;
path = xset_file_dialog( GTK_WIDGET( desktop ),
GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER,
_("Choose Location"), folder, NULL );
if ( path && g_file_test( path, G_FILE_TEST_IS_DIR ) )
{
if ( g_str_has_prefix( setname, "copy_loc" ) )
copy_dest = path;
else
move_dest = path;
set2 = xset_get( "copy_loc_last" );
xset_set_set( set2, "desc", path );
}
else
return;
}
if ( copy_dest || move_dest )
{
int file_action;
char* dest_dir;
if ( copy_dest )
{
file_action = VFS_FILE_TASK_COPY;
dest_dir = copy_dest;
}
else
{
file_action = VFS_FILE_TASK_MOVE;
dest_dir = move_dest;
}
if ( !strcmp( dest_dir, cwd ) )
{
xset_msg_dialog( GTK_WIDGET( desktop ), GTK_MESSAGE_ERROR,
_("Invalid Destination"), NULL, 0,
_("Destination same as source"), NULL, NULL );
g_free( dest_dir );
return;
}
// rebuild sel_files with full paths
GList* file_list = NULL;
GList* sel;
char* file_path;
VFSFileInfo* file;
for ( sel = sel_files; sel; sel = sel->next )
{
file = ( VFSFileInfo* ) sel->data;
file_path = g_build_filename( cwd,
vfs_file_info_get_name( file ), NULL );
file_list = g_list_prepend( file_list, file_path );
}
// task
PtkFileTask* task = ptk_file_task_new( file_action,
file_list,
dest_dir,
GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET(
desktop ) ) ),
NULL );
ptk_file_task_run( task );
g_free( dest_dir );
}
else
{
xset_msg_dialog( GTK_WIDGET( desktop ), GTK_MESSAGE_ERROR,
_("Invalid Destination"), NULL, 0,
_("Invalid destination"), NULL, NULL );
}
}
/*-------------- Private methods -------------------*/
void paint_item( DesktopWindow* self, DesktopItem* item, GdkRectangle* expose_area )
{
/* GdkPixbuf* icon = item->icon ? gdk_pixbuf_ref(item->icon) : NULL; */
GdkPixbuf* icon;
const char* text = item->fi->disp_name;
GtkWidget* widget = (GtkWidget*)self;
#if !GTK_CHECK_VERSION (3, 0, 0)
GdkDrawable* drawable = gtk_widget_get_window(widget);
#endif
GtkCellRendererState state = 0;
GdkRectangle text_rect;
int w, h;
cairo_t *cr;
cr = gdk_cairo_create( gtk_widget_get_window( widget ) );
if( item->fi->big_thumbnail )
icon = g_object_ref( item->fi->big_thumbnail );
else
icon = vfs_file_info_get_big_icon( item->fi );
if( item->is_selected )
state = GTK_CELL_RENDERER_SELECTED;
g_object_set( self->icon_render, "pixbuf", icon, NULL );
#if GTK_CHECK_VERSION (3, 0, 0)
gtk_cell_renderer_render( self->icon_render, cr, widget,
&item->icon_rect, &item->icon_rect, state );
#else
gtk_cell_renderer_render( self->icon_render, drawable, widget,
&item->icon_rect, &item->icon_rect, expose_area, state );
#endif
if( icon )
g_object_unref( icon );
// add link_icon arrow to links
if ( item->fi )
{
if ( vfs_file_info_is_symlink( item->fi ) && link_icon )
{
cairo_set_operator ( cr, CAIRO_OPERATOR_OVER );
gdk_cairo_set_source_pixbuf ( cr, link_icon,
item->icon_rect.x,
item->icon_rect.y );
gdk_cairo_rectangle ( cr, &item->icon_rect );
cairo_fill ( cr );
}
}
// text
text_rect = item->text_rect;
pango_layout_set_wrap( self->pl, 0 );
if( item->is_selected )
{
GdkRectangle intersect={0};
if( gdk_rectangle_intersect( expose_area, &item->text_rect, &intersect ) )
{
gdk_cairo_set_source_color( cr, >k_widget_get_style(widget)->bg[GTK_STATE_SELECTED] );
cairo_rectangle( cr, intersect.x, intersect.y, intersect.width, intersect.height );
cairo_fill( cr );
}
}
else
{
/* Do the drop shadow stuff... This is a little bit dirty... */
++text_rect.x;
++text_rect.y;
gdk_cairo_set_source_color( cr, &self->shadow );
if( item->len1 > 0 )
{
pango_layout_set_text( self->pl, text, item->len1 );
pango_layout_get_pixel_size( self->pl, &w, &h );
pango_cairo_update_layout( cr, self->pl );
cairo_move_to( cr, text_rect.x, text_rect.y );
pango_cairo_show_layout( cr, self->pl );
text_rect.y += h;
}
pango_layout_set_text( self->pl, text + item->len1, -1 );
pango_layout_set_ellipsize( self->pl, PANGO_ELLIPSIZE_END );
cairo_move_to( cr, text_rect.x, text_rect.y );
pango_cairo_show_layout( cr, self->pl );
--text_rect.x;
--text_rect.y;
}
if( self->focus == item && gtk_widget_has_focus(widget) )
{
#if GTK_CHECK_VERSION (3, 0, 0)
gtk_paint_focus( gtk_widget_get_style(widget), cr,
GTK_STATE_NORMAL,/*item->is_selected ? GTK_STATE_SELECTED : GTK_STATE_NORMAL,*/
widget, "icon_view",
item->text_rect.x, item->text_rect.y,
item->text_rect.width, item->text_rect.height);
#else
gtk_paint_focus( gtk_widget_get_style(widget), gtk_widget_get_window(widget),
GTK_STATE_NORMAL,/*item->is_selected ? GTK_STATE_SELECTED : GTK_STATE_NORMAL,*/
&item->text_rect, widget, "icon_view",
item->text_rect.x, item->text_rect.y,
item->text_rect.width, item->text_rect.height);
#endif
}
text_rect = item->text_rect;
gdk_cairo_set_source_color( cr, &self->fg );
if( item->len1 > 0 )
{
pango_layout_set_text( self->pl, text, item->len1 );
pango_layout_get_pixel_size( self->pl, &w, &h );
pango_cairo_update_layout( cr, self->pl );
cairo_move_to( cr, text_rect.x, text_rect.y );
pango_cairo_show_layout( cr, self->pl );
text_rect.y += h;
}
pango_layout_set_text( self->pl, text + item->len1, -1 );
pango_layout_set_ellipsize( self->pl, PANGO_ELLIPSIZE_END );
cairo_move_to( cr, text_rect.x, text_rect.y );
pango_cairo_show_layout( cr, self->pl );
cairo_destroy( cr );
}
void move_item( DesktopWindow* self, DesktopItem* item, int x, int y, gboolean is_offset )
{
GdkRectangle old = item->box;
if( ! is_offset )
{
x -= item->box.x;
y -= item->box.y;
}
item->box.x += x;
item->box.y += y;
item->icon_rect.x += x;
item->icon_rect.y += y;
item->text_rect.x += x;
item->text_rect.y += y;
gtk_widget_queue_draw_area( (GtkWidget*)self, old.x, old.y, old.width, old.height );
gtk_widget_queue_draw_area( (GtkWidget*)self, item->box.x, item->box.y, item->box.width, item->box.height );
}
static gboolean is_point_in_rect( GdkRectangle* rect, int x, int y )
{
return rect->x < x && x < (rect->x + rect->width) && y > rect->y && y < (rect->y + rect->height);
}
DesktopItem* hit_test( DesktopWindow* self, int x, int y )
{
DesktopItem* item;
GList* l;
for( l = self->items; l; l = l->next )
{
item = (DesktopItem*) l->data;
if( is_point_in_rect( &item->icon_rect, x, y )
|| is_point_in_rect( &item->text_rect, x, y ) )
return item;
}
return NULL;
}
/* FIXME: this is too dirty and here is some redundant code.
* We really need better and cleaner APIs for this */
void open_folders( GList* folders )
{
FMMainWindow* main_window;
gboolean new_window = FALSE;
main_window = fm_main_window_get_on_current_desktop();
if ( !main_window )
{
main_window = FM_MAIN_WINDOW(fm_main_window_new());
//FM_MAIN_WINDOW( main_window ) ->splitter_pos = app_settings.splitter_pos;
gtk_window_set_default_size( GTK_WINDOW( main_window ),
app_settings.width,
app_settings.height );
gtk_widget_show( GTK_WIDGET(main_window) );
new_window = !xset_get_b( "main_save_tabs" );
}
while( folders )
{
VFSFileInfo* fi = (VFSFileInfo*)folders->data;
char* path;
if( fi->flags & VFS_FILE_INFO_VIRTUAL )
{
/* if this is a special item, not a real file in desktop dir */
if( fi->name[0] == '/' ) /* it's a real path */
{
path = g_strdup( fi->name );
}
else
{
folders = folders->next;
continue;
}
/* FIXME/TODO: In the future we should handle mounting here. */
}
else
{
path = g_build_filename( vfs_get_desktop_dir(), fi->name, NULL );
}
if ( new_window )
{
main_window_open_path_in_current_tab( main_window, path );
new_window = FALSE;
}
else
fm_main_window_add_new_tab( FM_MAIN_WINDOW( main_window ), path );
g_free( path );
folders = folders->next;
}
gtk_window_present( GTK_WINDOW( main_window ) );
}
GCompareDataFunc get_sort_func( DesktopWindow* win )
{
GCompareDataFunc comp;
switch( win->sort_by )
{
case DW_SORT_BY_NAME:
comp = (GCompareDataFunc)comp_item_by_name;
break;
case DW_SORT_BY_SIZE:
comp = (GCompareDataFunc)comp_item_by_size;
break;
case DW_SORT_BY_TYPE:
comp = (GCompareDataFunc)comp_item_by_type;
break;
case DW_SORT_BY_MTIME:
comp = (GCompareDataFunc)comp_item_by_mtime;
break;
case DW_SORT_CUSTOM:
comp = (GCompareDataFunc)comp_item_custom;
break;
default:
comp = (GCompareDataFunc)comp_item_by_name;
}
return comp;
}
/* return -1 if item1 is virtual, and item2 is not, and vice versa. return 0 if both are, or both aren't. */
#define COMP_VIRTUAL( item1, item2 ) \
( ( ((item2->fi->flags & VFS_FILE_INFO_VIRTUAL) ? 1 : 0) - ((item1->fi->flags & VFS_FILE_INFO_VIRTUAL) ? 1 : 0) ) )
int comp_item_by_name( DesktopItem* item1, DesktopItem* item2, DesktopWindow* win )
{
int ret;
if( ret = COMP_VIRTUAL( item1, item2 ) )
return ret;
ret =g_utf8_collate( item1->fi->disp_name, item2->fi->disp_name );
if( win->sort_type == GTK_SORT_DESCENDING )
ret = -ret;
return ret;
}
int comp_item_by_size( DesktopItem* item1, DesktopItem* item2, DesktopWindow* win )
{
int ret;
if( ret = COMP_VIRTUAL( item1, item2 ) )
return ret;
ret =item1->fi->size - item2->fi->size;
if ( ret == 0 ) //sfm
ret = g_utf8_collate( item1->fi->disp_name, item2->fi->disp_name );
else if( win->sort_type == GTK_SORT_DESCENDING )
ret = -ret;
return ret;
}
int comp_item_by_mtime( DesktopItem* item1, DesktopItem* item2, DesktopWindow* win )
{
int ret;
if( ret = COMP_VIRTUAL( item1, item2 ) )
return ret;
ret =item1->fi->mtime - item2->fi->mtime;
if ( ret == 0 ) //sfm
ret = g_utf8_collate( item1->fi->disp_name, item2->fi->disp_name );
else if( win->sort_type == GTK_SORT_DESCENDING )
ret = -ret;
return ret;
}
int comp_item_by_type( DesktopItem* item1, DesktopItem* item2, DesktopWindow* win )
{
int ret;
if( ret = COMP_VIRTUAL( item1, item2 ) )
return ret;
ret = strcmp( item1->fi->mime_type->type, item2->fi->mime_type->type );
if ( ret == 0 ) //sfm
ret = g_utf8_collate( item1->fi->disp_name, item2->fi->disp_name );
else if( win->sort_type == GTK_SORT_DESCENDING )
ret = -ret;
return ret;
}
int comp_item_custom( DesktopItem* item1, DesktopItem* item2, DesktopWindow* win )
{
return (item1->order - item2->order);
}
void redraw_item( DesktopWindow* win, DesktopItem* item )
{
GdkRectangle rect = item->box;
--rect.x;
--rect.y;
rect.width += 2;
rect.height += 2;
gdk_window_invalidate_rect( gtk_widget_get_window((GtkWidget*)win), &rect, FALSE );
}
/* ----------------- public APIs ------------------*/
void desktop_window_sort_items( DesktopWindow* win, DWSortType sort_by,
GtkSortType sort_type )
{
GList* items = NULL;
GList* special_items;
if( win->sort_type == sort_type && win->sort_by == sort_by )
return;
app_settings.desktop_sort_by = win->sort_by = sort_by;
app_settings.desktop_sort_type = win->sort_type = sort_type;
xset_autosave( NULL );
/* skip the special items since they always appears first */
gboolean special = FALSE; //MOD added - otherwise caused infinite loop in layout items once My Documents was removed
special_items = win->items;
for( items = special_items; items; items = items->next )
{
DesktopItem* item = (DesktopItem*)items->data;
if( ! (item->fi->flags & VFS_FILE_INFO_VIRTUAL) )
break;
else
special = TRUE;
}
if( ! items )
return;
/* the previous item of the first non-special item is the last special item */
if( special && items->prev )
{
items->prev->next = NULL;
items->prev = NULL;
}
items = g_list_sort_with_data( items, get_sort_func(win), win );
if ( special )
win->items = g_list_concat( special_items, items );
else
win->items = items;
layout_items( win );
}
GList* desktop_window_get_selected_items( DesktopWindow* win )
{
GList* sel = NULL;
GList* l;
for( l = win->items; l; l = l->next )
{
DesktopItem* item = (DesktopItem*) l->data;
if( item->is_selected )
{
if( G_UNLIKELY( item == win->focus ) )
sel = g_list_prepend( sel, item );
else
sel = g_list_append( sel, item );
}
}
return sel;
}
GList* desktop_window_get_selected_files( DesktopWindow* win )
{
GList* sel = desktop_window_get_selected_items( win );
GList* l;
l = sel;
while( l )
{
DesktopItem* item = (DesktopItem*) l->data;
if( item->fi->flags & VFS_FILE_INFO_VIRTUAL )
{
/* don't include virtual items */
GList* tmp = l;
l = tmp->next;
sel = g_list_remove_link( sel, tmp );
g_list_free1( tmp );
}
else
{
l->data = vfs_file_info_ref( item->fi );
l = l->next;
}
}
return sel;
}
void desktop_window_add_application( DesktopWindow* desktop )
{
char* app = NULL;
VFSMimeType* mime_type;
GList* sel_files = desktop_window_get_selected_files( desktop );
if ( sel_files )
{
mime_type = vfs_file_info_get_mime_type( (VFSFileInfo*)sel_files->data );
if ( G_LIKELY( ! mime_type ) )
mime_type = vfs_mime_type_get_from_type( XDG_MIME_TYPE_UNKNOWN );
g_list_foreach( sel_files, (GFunc)vfs_file_info_unref, NULL );
g_list_free( sel_files );
}
else
mime_type = vfs_mime_type_get_from_type( XDG_MIME_TYPE_DIRECTORY );
app = (char *) ptk_choose_app_for_mime_type( GTK_WINDOW( desktop ),
mime_type, TRUE );
if ( app )
{
char* path = vfs_mime_type_locate_desktop_file( NULL, app );
if ( path && g_file_test( path, G_FILE_TEST_IS_REGULAR ) )
{
sel_files = g_list_prepend( NULL, path );
PtkFileTask* task = ptk_file_task_new( VFS_FILE_TASK_LINK,
sel_files,
vfs_get_desktop_dir(),
GTK_WINDOW( desktop ),
NULL );
ptk_file_task_run( task );
}
else
g_free( path );
g_free( app );
}
vfs_mime_type_unref( mime_type );
}
/*----------------- X11-related sutff ----------------*/
static
GdkFilterReturn on_rootwin_event ( GdkXEvent *xevent,
GdkEvent *event,
gpointer data )
{
XPropertyEvent * evt = ( XPropertyEvent* ) xevent;
DesktopWindow* self = (DesktopWindow*)data;
if ( evt->type == PropertyNotify )
{
if( evt->atom == ATOM_NET_WORKAREA )
{
/* working area is resized */
get_working_area( gtk_widget_get_screen((GtkWidget*)self), &self->wa );
layout_items( self );
}
#if 0
else if( evt->atom == ATOM_XROOTMAP_ID )
{
/* wallpaper was changed by other programs */
}
#endif
}
return GDK_FILTER_TRANSLATE;
}
/* This function is taken from xfdesktop */
void forward_event_to_rootwin( GdkScreen *gscreen, GdkEvent *event )
{
XButtonEvent xev, xev2;
Display *dpy = GDK_DISPLAY_XDISPLAY( gdk_screen_get_display( gscreen ) );
if ( event->type == GDK_BUTTON_PRESS || event->type == GDK_BUTTON_RELEASE )
{
if ( event->type == GDK_BUTTON_PRESS )
{
xev.type = ButtonPress;
/*
* rox has an option to disable the next
* instruction. it is called "blackbox_hack". Does
* anyone know why exactly it is needed?
*/
XUngrabPointer( dpy, event->button.time );
}
else
xev.type = ButtonRelease;
xev.button = event->button.button;
xev.x = event->button.x; /* Needed for icewm */
xev.y = event->button.y;
xev.x_root = event->button.x_root;
xev.y_root = event->button.y_root;
xev.state = event->button.state;
xev2.type = 0;
}
else if ( event->type == GDK_SCROLL )
{
xev.type = ButtonPress;
xev.button = event->scroll.direction + 4;
xev.x = event->scroll.x; /* Needed for icewm */
xev.y = event->scroll.y;
xev.x_root = event->scroll.x_root;
xev.y_root = event->scroll.y_root;
xev.state = event->scroll.state;
xev2.type = ButtonRelease;
xev2.button = xev.button;
}
else
return ;
xev.window = GDK_WINDOW_XID( gdk_screen_get_root_window( gscreen ) );
xev.root = xev.window;
xev.subwindow = None;
xev.time = event->button.time;
xev.same_screen = True;
XSendEvent( dpy, xev.window, False, ButtonPressMask | ButtonReleaseMask,
( XEvent * ) & xev );
if ( xev2.type == 0 )
return ;
/* send button release for scroll event */
xev2.window = xev.window;
xev2.root = xev.root;
xev2.subwindow = xev.subwindow;
xev2.time = xev.time;
xev2.x = xev.x;
xev2.y = xev.y;
xev2.x_root = xev.x_root;
xev2.y_root = xev.y_root;
xev2.state = xev.state;
xev2.same_screen = xev.same_screen;
XSendEvent( dpy, xev2.window, False, ButtonPressMask | ButtonReleaseMask,
( XEvent * ) & xev2 );
}
/* FIXME: set single click timeout */
void desktop_window_set_single_click( DesktopWindow* win, gboolean single_click )
{
if( single_click == win->single_click )
return;
win->single_click = single_click;
if( single_click )
{
win->hand_cursor = gdk_cursor_new_for_display( gtk_widget_get_display(GTK_WIDGET(win)), GDK_HAND2 );
}
else
{
gdk_cursor_unref( win->hand_cursor );
win->hand_cursor = NULL;
if( gtk_widget_get_realized( (GtkWidget*)win ) )
gdk_window_set_cursor( gtk_widget_get_window((GtkWidget*)win), NULL );
}
}
#if 0
GdkPixmap* get_root_pixmap( GdkWindow* root )
{
Pixmap root_pix = None;
Atom type;
int format;
long bytes_after;
Pixmap *data = NULL;
long n_items;
int result;
result = XGetWindowProperty(
GDK_WINDOW_XDISPLAY( root ),
GDK_WINDOW_XID( root ),
ATOM_XROOTMAP_ID,
0, 16L,
False, XA_PIXMAP,
&type, &format, &n_items,
&bytes_after, (unsigned char **)&data);
if (result == Success && n_items)
root_pix = *data;
if (data)
XFree(data);
return root_pix ? gdk_pixmap_foreign_new( root_pix ) : NULL;
}
gboolean set_root_pixmap( GdkWindow* root, GdkPixmap* pix )
{
return TRUE;
}
#endif
void desktop_context_fill( DesktopWindow* win, gpointer context )
{
GtkClipboard* clip = NULL;
if ( !win )
return;
XSetContext* c = (XSetContext*)context;
c->valid = FALSE;
// assume we don't need all selected files info
if ( !c->var[CONTEXT_IS_ROOT] )
c->var[CONTEXT_IS_ROOT] = geteuid() == 0 ?
g_strdup( "true" ) : g_strdup( "false" );
if ( !c->var[CONTEXT_CLIP_FILES] )
{
clip = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD );
if ( ! gtk_clipboard_wait_is_target_available ( clip,
gdk_atom_intern( "x-special/gnome-copied-files", FALSE ) ) &&
! gtk_clipboard_wait_is_target_available ( clip,
gdk_atom_intern( "text/uri-list", FALSE ) ) )
c->var[CONTEXT_CLIP_FILES] = g_strdup( "false" );
else
c->var[CONTEXT_CLIP_FILES] = g_strdup( "true" );
}
if ( !c->var[CONTEXT_CLIP_TEXT] )
{
if ( !clip )
clip = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD );
c->var[CONTEXT_CLIP_TEXT] = gtk_clipboard_wait_is_text_available( clip ) ?
g_strdup( "true" ) : g_strdup( "false" );
}
c->var[CONTEXT_BOOKMARK] = g_strdup( "" );
c->var[CONTEXT_DEVICE] = g_strdup( "" );
c->var[CONTEXT_DEVICE_LABEL] = g_strdup( "" );
c->var[CONTEXT_DEVICE_MOUNT_POINT] = g_strdup( "" );
c->var[CONTEXT_DEVICE_UDI] = g_strdup( "" );
c->var[CONTEXT_DEVICE_FSTYPE] = g_strdup( "" );
c->var[CONTEXT_DEVICE_PROP] = g_strdup( "" );
c->var[CONTEXT_PANEL_COUNT] = g_strdup( "" );
c->var[CONTEXT_PANEL] = g_strdup( "" );
c->var[CONTEXT_TAB] = g_strdup( "" );
c->var[CONTEXT_TAB_COUNT] = g_strdup( "" );
int p;
for ( p = 1; p < 5; p++ )
{
c->var[CONTEXT_PANEL1_DIR + p - 1] = g_strdup( "" );
c->var[CONTEXT_PANEL1_SEL + p - 1] = g_strdup( "false" );
c->var[CONTEXT_PANEL1_DEVICE + p - 1] = g_strdup( "" );
}
c->var[CONTEXT_TASK_TYPE] = g_strdup( "" );
c->var[CONTEXT_TASK_NAME] = g_strdup( "" );
c->var[CONTEXT_TASK_DIR] = g_strdup( "" );
c->var[CONTEXT_TASK_COUNT] = g_strdup( "0" );
c->valid = TRUE;
}
gboolean desktop_write_exports( VFSFileTask* vtask, const char* value, FILE* file )
{
int result;
const char* cwd = vfs_get_desktop_dir();
char* path;
char* esc_path;
GList* sel_files;
GList* l;
VFSFileInfo* fi;
if ( !vtask->exec_desktop )
return FALSE;
DesktopWindow* win = (DesktopWindow*)vtask->exec_desktop;
XSet* set = (XSet*)vtask->exec_set;
if ( !file )
return FALSE;
result = fputs( "# source\n\n", file );
if ( result < 0 ) return FALSE;
write_src_functions( file );
// selected files
sel_files = desktop_window_get_selected_files( win );
if ( sel_files )
{
fprintf( file, "fm_desktop_files=(\n" );
for ( l = sel_files; l; l = l->next )
{
fi = (VFSFileInfo*)l->data;
if ( fi->flags & VFS_FILE_INFO_VIRTUAL )
{
continue;
}
path = g_build_filename( cwd, fi->name, NULL );
esc_path = bash_quote( path );
fprintf( file, "%s\n", esc_path );
g_free( esc_path );
g_free( path );
}
fputs( ")\n", file );
fprintf( file, "fm_filenames=(\n" );
for ( l = sel_files; l; l = l->next )
{
fi = (VFSFileInfo*)l->data;
if ( fi->flags & VFS_FILE_INFO_VIRTUAL )
{
continue;
}
esc_path = bash_quote( fi->name );
fprintf( file, "%s\n", esc_path );
g_free( esc_path );
}
fputs( ")\n", file );
g_list_foreach( sel_files, (GFunc)vfs_file_info_unref, NULL );
g_list_free( sel_files );
}
// my selected files
esc_path = bash_quote( cwd );
fprintf( file, "fm_pwd=%s\n", esc_path );
fprintf( file, "fm_desktop_pwd=%s\n", esc_path );
g_free( esc_path );
fprintf( file, "\nfm_files=(\"${fm_desktop_files[@]}\")\n" );
fprintf( file, "fm_file=\"${fm_files[0]}\"\n" );
fprintf( file, "fm_filename=\"${fm_filenames[0]}\"\n" );
// command
if ( vtask->exec_command )
{
esc_path = bash_quote( vtask->exec_command );
fprintf( file, "fm_command=%s\n", esc_path );
g_free( esc_path );
}
// user
const char* this_user = g_get_user_name();
if ( this_user )
{
esc_path = bash_quote( this_user );
fprintf( file, "fm_user=%s\n", esc_path );
g_free( esc_path );
//g_free( this_user ); DON'T
}
// variable value
if ( value )
{
esc_path = bash_quote( value );
fprintf( file, "fm_value=%s\n", esc_path );
g_free( esc_path );
}
// utils
esc_path = bash_quote( xset_get_s( "editor" ) );
fprintf( file, "fm_editor=%s\n", esc_path );
g_free( esc_path );
fprintf( file, "fm_editor_terminal=%d\n", xset_get_b( "editor" ) ? 1 : 0 );
// set
if ( set )
{
// cmd_dir
if ( set->plugin )
{
path = g_build_filename( set->plug_dir, "files", NULL );
if ( !g_file_test( path, G_FILE_TEST_EXISTS ) )
{
g_free( path );
path = g_build_filename( set->plug_dir, set->plug_name, NULL );
}
}
else
{
path = g_build_filename( xset_get_config_dir(), "scripts",
set->name, NULL );
}
esc_path = bash_quote( path );
fprintf( file, "fm_cmd_dir=%s\n", esc_path );
g_free( esc_path );
g_free( path );
// cmd_data
if ( set->plugin )
{
XSet* mset = xset_get_plugin_mirror( set );
path = g_build_filename( xset_get_config_dir(), "plugin-data",
mset->name, NULL );
}
else
path = g_build_filename( xset_get_config_dir(), "plugin-data",
set->name, NULL );
esc_path = bash_quote( path );
fprintf( file, "fm_cmd_data=%s\n", esc_path );
g_free( esc_path );
g_free( path );
// plugin_dir
if ( set->plugin )
{
esc_path = bash_quote( set->plug_dir );
fprintf( file, "fm_plugin_dir=%s\n", esc_path );
g_free( esc_path );
}
// cmd_name
if ( set->menu_label )
{
esc_path = bash_quote( set->menu_label );
fprintf( file, "fm_cmd_name=%s\n", esc_path );
g_free( esc_path );
}
}
// tmp
if ( geteuid() != 0 && vtask->exec_as_user
&& !strcmp( vtask->exec_as_user, "root" ) )
fprintf( file, "fm_tmp_dir=%s\n", xset_get_shared_tmp_dir() );
else
fprintf( file, "fm_tmp_dir=%s\n", xset_get_user_tmp_dir() );
result = fputs( "\n", file );
return result >= 0;
}
|
155 | ./spacefm/src/libmd5-rfc/md5.c | /*
Copyright (C) 1999, 2000, 2002 Aladdin Enterprises. All rights reserved.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
L. Peter Deutsch
ghost@aladdin.com
*/
/* $Id: md5.c,v 1.6 2002/04/13 19:20:28 lpd Exp $ */
/*
Independent implementation of MD5 (RFC 1321).
This code implements the MD5 Algorithm defined in RFC 1321, whose
text is available at
http://www.ietf.org/rfc/rfc1321.txt
The code is derived from the text of the RFC, including the test suite
(section A.5) but excluding the rest of Appendix A. It does not include
any code or documentation that is identified in the RFC as being
copyrighted.
The original and principal author of md5.c is L. Peter Deutsch
<ghost@aladdin.com>. Other authors are noted in the change history
that follows (in reverse chronological order):
2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order
either statically or dynamically; added missing #include <string.h>
in library.
2002-03-11 lpd Corrected argument list for main(), and added int return
type, in test program and T value program.
2002-02-21 lpd Added missing #include <stdio.h> in test program.
2000-07-03 lpd Patched to eliminate warnings about "constant is
unsigned in ANSI C, signed in traditional"; made test program
self-checking.
1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5).
1999-05-03 lpd Original version.
*/
/* Add by Hong Jen Yee on 2008-12-17 */
#include <glib.h>
#if ! GLIB_CHECK_VERSION(2, 16, 0) /* since glib 2.16, md5 is provided */
#include "md5.h"
#include <string.h>
#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */
#ifdef ARCH_IS_BIG_ENDIAN
# define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1)
#else
# define BYTE_ORDER 0
#endif
#define T_MASK ((md5_word_t)~0)
#define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87)
#define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9)
#define T3 0x242070db
#define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111)
#define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050)
#define T6 0x4787c62a
#define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec)
#define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe)
#define T9 0x698098d8
#define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850)
#define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e)
#define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841)
#define T13 0x6b901122
#define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c)
#define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71)
#define T16 0x49b40821
#define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d)
#define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf)
#define T19 0x265e5a51
#define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855)
#define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2)
#define T22 0x02441453
#define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e)
#define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437)
#define T25 0x21e1cde6
#define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829)
#define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278)
#define T28 0x455a14ed
#define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa)
#define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07)
#define T31 0x676f02d9
#define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375)
#define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd)
#define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e)
#define T35 0x6d9d6122
#define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3)
#define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb)
#define T38 0x4bdecfa9
#define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f)
#define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f)
#define T41 0x289b7ec6
#define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805)
#define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a)
#define T44 0x04881d05
#define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6)
#define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a)
#define T47 0x1fa27cf8
#define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a)
#define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb)
#define T50 0x432aff97
#define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58)
#define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6)
#define T53 0x655b59c3
#define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d)
#define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82)
#define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e)
#define T57 0x6fa87e4f
#define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f)
#define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb)
#define T60 0x4e0811a1
#define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d)
#define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca)
#define T63 0x2ad7d2bb
#define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e)
static void
md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/)
{
md5_word_t
a = pms->abcd[0], b = pms->abcd[1],
c = pms->abcd[2], d = pms->abcd[3];
md5_word_t t;
#if BYTE_ORDER > 0
/* Define storage only for big-endian CPUs. */
md5_word_t X[16];
#else
/* Define storage for little-endian or both types of CPUs. */
md5_word_t xbuf[16];
const md5_word_t *X;
#endif
{
#if BYTE_ORDER == 0
/*
* Determine dynamically whether this is a big-endian or
* little-endian machine, since we can use a more efficient
* algorithm on the latter.
*/
static const int w = 1;
if (*((const md5_byte_t *)&w)) /* dynamic little-endian */
#endif
#if BYTE_ORDER <= 0 /* little-endian */
{
/*
* On little-endian machines, we can process properly aligned
* data without copying it.
*/
if (!((data - (const md5_byte_t *)0) & 3)) {
/* data are properly aligned */
X = (const md5_word_t *)data;
} else {
/* not aligned */
memcpy(xbuf, data, 64);
X = xbuf;
}
}
#endif
#if BYTE_ORDER == 0
else /* dynamic big-endian */
#endif
#if BYTE_ORDER >= 0 /* big-endian */
{
/*
* On big-endian machines, we must arrange the bytes in the
* right order.
*/
const md5_byte_t *xp = data;
int i;
# if BYTE_ORDER == 0
X = xbuf; /* (dynamic only) */
# else
# define xbuf X /* (static only) */
# endif
for (i = 0; i < 16; ++i, xp += 4)
xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24);
}
#endif
}
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
/* Round 1. */
/* Let [abcd k s i] denote the operation
a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
#define F(x, y, z) (((x) & (y)) | (~(x) & (z)))
#define SET(a, b, c, d, k, s, Ti)\
t = a + F(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 0, 7, T1);
SET(d, a, b, c, 1, 12, T2);
SET(c, d, a, b, 2, 17, T3);
SET(b, c, d, a, 3, 22, T4);
SET(a, b, c, d, 4, 7, T5);
SET(d, a, b, c, 5, 12, T6);
SET(c, d, a, b, 6, 17, T7);
SET(b, c, d, a, 7, 22, T8);
SET(a, b, c, d, 8, 7, T9);
SET(d, a, b, c, 9, 12, T10);
SET(c, d, a, b, 10, 17, T11);
SET(b, c, d, a, 11, 22, T12);
SET(a, b, c, d, 12, 7, T13);
SET(d, a, b, c, 13, 12, T14);
SET(c, d, a, b, 14, 17, T15);
SET(b, c, d, a, 15, 22, T16);
#undef SET
/* Round 2. */
/* Let [abcd k s i] denote the operation
a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
#define G(x, y, z) (((x) & (z)) | ((y) & ~(z)))
#define SET(a, b, c, d, k, s, Ti)\
t = a + G(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 1, 5, T17);
SET(d, a, b, c, 6, 9, T18);
SET(c, d, a, b, 11, 14, T19);
SET(b, c, d, a, 0, 20, T20);
SET(a, b, c, d, 5, 5, T21);
SET(d, a, b, c, 10, 9, T22);
SET(c, d, a, b, 15, 14, T23);
SET(b, c, d, a, 4, 20, T24);
SET(a, b, c, d, 9, 5, T25);
SET(d, a, b, c, 14, 9, T26);
SET(c, d, a, b, 3, 14, T27);
SET(b, c, d, a, 8, 20, T28);
SET(a, b, c, d, 13, 5, T29);
SET(d, a, b, c, 2, 9, T30);
SET(c, d, a, b, 7, 14, T31);
SET(b, c, d, a, 12, 20, T32);
#undef SET
/* Round 3. */
/* Let [abcd k s t] denote the operation
a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define SET(a, b, c, d, k, s, Ti)\
t = a + H(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 5, 4, T33);
SET(d, a, b, c, 8, 11, T34);
SET(c, d, a, b, 11, 16, T35);
SET(b, c, d, a, 14, 23, T36);
SET(a, b, c, d, 1, 4, T37);
SET(d, a, b, c, 4, 11, T38);
SET(c, d, a, b, 7, 16, T39);
SET(b, c, d, a, 10, 23, T40);
SET(a, b, c, d, 13, 4, T41);
SET(d, a, b, c, 0, 11, T42);
SET(c, d, a, b, 3, 16, T43);
SET(b, c, d, a, 6, 23, T44);
SET(a, b, c, d, 9, 4, T45);
SET(d, a, b, c, 12, 11, T46);
SET(c, d, a, b, 15, 16, T47);
SET(b, c, d, a, 2, 23, T48);
#undef SET
/* Round 4. */
/* Let [abcd k s t] denote the operation
a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
#define I(x, y, z) ((y) ^ ((x) | ~(z)))
#define SET(a, b, c, d, k, s, Ti)\
t = a + I(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 0, 6, T49);
SET(d, a, b, c, 7, 10, T50);
SET(c, d, a, b, 14, 15, T51);
SET(b, c, d, a, 5, 21, T52);
SET(a, b, c, d, 12, 6, T53);
SET(d, a, b, c, 3, 10, T54);
SET(c, d, a, b, 10, 15, T55);
SET(b, c, d, a, 1, 21, T56);
SET(a, b, c, d, 8, 6, T57);
SET(d, a, b, c, 15, 10, T58);
SET(c, d, a, b, 6, 15, T59);
SET(b, c, d, a, 13, 21, T60);
SET(a, b, c, d, 4, 6, T61);
SET(d, a, b, c, 11, 10, T62);
SET(c, d, a, b, 2, 15, T63);
SET(b, c, d, a, 9, 21, T64);
#undef SET
/* Then perform the following additions. (That is increment each
of the four registers by the value it had before this block
was started.) */
pms->abcd[0] += a;
pms->abcd[1] += b;
pms->abcd[2] += c;
pms->abcd[3] += d;
}
void
md5_init(md5_state_t *pms)
{
pms->count[0] = pms->count[1] = 0;
pms->abcd[0] = 0x67452301;
pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476;
pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301;
pms->abcd[3] = 0x10325476;
}
void
md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes)
{
const md5_byte_t *p = data;
int left = nbytes;
int offset = (pms->count[0] >> 3) & 63;
md5_word_t nbits = (md5_word_t)(nbytes << 3);
if (nbytes <= 0)
return;
/* Update the message length. */
pms->count[1] += nbytes >> 29;
pms->count[0] += nbits;
if (pms->count[0] < nbits)
pms->count[1]++;
/* Process an initial partial block. */
if (offset) {
int copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
memcpy(pms->buf + offset, p, copy);
if (offset + copy < 64)
return;
p += copy;
left -= copy;
md5_process(pms, pms->buf);
}
/* Process full blocks. */
for (; left >= 64; p += 64, left -= 64)
md5_process(pms, p);
/* Process a final partial block. */
if (left)
memcpy(pms->buf, p, left);
}
void
md5_finish(md5_state_t *pms, md5_byte_t digest[16])
{
static const md5_byte_t pad[64] = {
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
md5_byte_t data[8];
int i;
/* Save the length before padding. */
for (i = 0; i < 8; ++i)
data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
/* Pad to 56 bytes mod 64. */
md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
/* Append the length. */
md5_append(pms, data, 8);
for (i = 0; i < 16; ++i)
digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
}
#endif /* GLIB_CHECK_VERSION(2, 16, 0) */
|
156 | ./spacefm/src/vfs/vfs-mime-type.c | /*
* C Implementation: vfs-mime_type-type
*
* Description:
*
*
* Author: Hong Jen Yee (PCMan) <pcman.tw (AT) gmail.com>, (C) 2006
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#include "vfs-mime-type.h"
#include "mime-action.h"
#include "vfs-file-monitor.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <gtk/gtk.h>
#include "glib-mem.h"
#include "vfs-utils.h" /* for vfs_load_icon */
static GHashTable *mime_hash = NULL;
GStaticRWLock mime_hash_lock = G_STATIC_RW_LOCK_INIT; /* mutex lock is needed */
static guint reload_callback_id = 0;
static GList* reload_cb = NULL;
static int big_icon_size = 32, small_icon_size = 16;
static VFSFileMonitor** mime_caches_monitor = NULL;
static guint theme_change_notify = 0;
static void on_icon_theme_changed( GtkIconTheme *icon_theme,
gpointer user_data );
typedef struct {
GFreeFunc cb;
gpointer user_data;
}VFSMimeReloadCbEnt;
static gboolean vfs_mime_type_reload( gpointer user_data )
{
GList* l;
/* FIXME: process mime database reloading properly. */
/* Remove all items in the hash table */
GDK_THREADS_ENTER();
g_static_rw_lock_writer_lock( &mime_hash_lock );
g_hash_table_foreach_remove ( mime_hash, ( GHRFunc ) gtk_true, NULL );
g_static_rw_lock_writer_unlock( &mime_hash_lock );
g_source_remove( reload_callback_id );
reload_callback_id = 0;
/* g_debug( "reload mime-types" ); */
/* call all registered callbacks */
for( l = reload_cb; l; l = l->next )
{
VFSMimeReloadCbEnt* ent = (VFSMimeReloadCbEnt*)l->data;
ent->cb( ent->user_data );
}
GDK_THREADS_LEAVE();
return FALSE;
}
static void on_mime_cache_changed( VFSFileMonitor* fm,
VFSFileMonitorEvent event,
const char* file_name,
gpointer user_data )
{
MimeCache* cache = (MimeCache*)user_data;
switch( event )
{
case VFS_FILE_MONITOR_CREATE:
case VFS_FILE_MONITOR_DELETE:
/* NOTE: FAM sometimes generate incorrect "delete" notification for non-existent files.
* So if the cache is not loaded originally (the cache file is non-existent), we skip it. */
if( ! cache->buffer )
return;
case VFS_FILE_MONITOR_CHANGE:
mime_cache_reload( cache );
/* g_debug( "reload cache: %s", file_name ); */
if( 0 == reload_callback_id )
reload_callback_id = g_idle_add( vfs_mime_type_reload, NULL );
}
}
void vfs_mime_type_init()
{
GtkIconTheme * theme;
MimeCache** caches;
int i, n_caches;
VFSFileMonitor* fm;
mime_type_init();
/* install file alteration monitor for mime-cache */
caches = mime_type_get_caches( &n_caches );
mime_caches_monitor = g_new0( VFSFileMonitor*, n_caches );
for( i = 0; i < n_caches; ++i )
{
//MOD NOTE1 check to see if path exists - otherwise it later tries to
// remove NULL fm with inotify which caused segfault
if ( g_file_test( caches[i]->file_path, G_FILE_TEST_EXISTS ) )
fm = vfs_file_monitor_add_file( caches[i]->file_path,
on_mime_cache_changed, caches[i] );
else
fm = NULL;
mime_caches_monitor[i] = fm;
}
mime_hash = g_hash_table_new_full( g_str_hash, g_str_equal,
NULL, vfs_mime_type_unref );
theme = gtk_icon_theme_get_default();
theme_change_notify = g_signal_connect( theme, "changed",
G_CALLBACK( on_icon_theme_changed ),
NULL );
}
void vfs_mime_type_clean()
{
GtkIconTheme * theme;
MimeCache** caches;
int i, n_caches;
theme = gtk_icon_theme_get_default();
g_signal_handler_disconnect( theme, theme_change_notify );
/* remove file alteration monitor for mime-cache */
caches = mime_type_get_caches( &n_caches );
for( i = 0; i < n_caches; ++i )
{
if ( mime_caches_monitor[i] ) //MOD added if !NULL - see NOTE1 above
vfs_file_monitor_remove( mime_caches_monitor[i],
on_mime_cache_changed, caches[i] );
}
g_free( mime_caches_monitor );
mime_type_finalize();
g_hash_table_destroy( mime_hash );
}
VFSMimeType* vfs_mime_type_get_from_file_name( const char* ufile_name )
{
const char * type;
/* type = xdg_mime_get_mime_type_from_file_name( ufile_name ); */
type = mime_type_get_by_filename( ufile_name, NULL );
return vfs_mime_type_get_from_type( type );
}
VFSMimeType* vfs_mime_type_get_from_file( const char* file_path,
const char* base_name,
struct stat64* pstat )
{
const char * type;
type = mime_type_get_by_file( file_path, pstat, base_name );
return vfs_mime_type_get_from_type( type );
}
VFSMimeType* vfs_mime_type_get_from_type( const char* type )
{
VFSMimeType * mime_type;
g_static_rw_lock_reader_lock( &mime_hash_lock );
mime_type = g_hash_table_lookup( mime_hash, type );
g_static_rw_lock_reader_unlock( &mime_hash_lock );
if ( !mime_type )
{
mime_type = vfs_mime_type_new( type );
g_static_rw_lock_writer_lock( &mime_hash_lock );
g_hash_table_insert( mime_hash, mime_type->type, mime_type );
g_static_rw_lock_writer_unlock( &mime_hash_lock );
}
vfs_mime_type_ref( mime_type );
return mime_type;
}
VFSMimeType* vfs_mime_type_new( const char* type_name )
{
VFSMimeType * mime_type = g_slice_new0( VFSMimeType );
mime_type->type = g_strdup( type_name );
mime_type->n_ref = 1;
return mime_type;
}
void vfs_mime_type_ref( VFSMimeType* mime_type )
{
g_atomic_int_inc(&mime_type->n_ref);
}
void vfs_mime_type_unref( gpointer mime_type_ )
{
VFSMimeType* mime_type = (VFSMimeType*)mime_type_;
if ( g_atomic_int_dec_and_test(&mime_type->n_ref) )
{
g_free( mime_type->type );
if ( mime_type->big_icon )
g_object_unref( mime_type->big_icon );
if ( mime_type->small_icon )
g_object_unref( mime_type->small_icon );
/* g_strfreev( mime_type->actions ); */
g_slice_free( VFSMimeType, mime_type );
}
}
GdkPixbuf* vfs_mime_type_get_icon( VFSMimeType* mime_type, gboolean big )
{
GdkPixbuf * icon = NULL;
const char* sep;
char icon_name[ 100 ];
GtkIconTheme *icon_theme;
int size;
if ( big )
{
if ( G_LIKELY( mime_type->big_icon ) ) /* big icon */
return g_object_ref( mime_type->big_icon );
size = big_icon_size;
}
else /* small icon */
{
if ( G_LIKELY( mime_type->small_icon ) )
return g_object_ref( mime_type->small_icon );
size = small_icon_size;
}
icon_theme = gtk_icon_theme_get_default ();
if ( G_UNLIKELY( 0 == strcmp( mime_type->type, XDG_MIME_TYPE_DIRECTORY ) ) )
{
icon = vfs_load_icon ( icon_theme, "folder", size );
if( G_UNLIKELY( !icon) )
icon = vfs_load_icon ( icon_theme, "gnome-fs-directory", size );
if( G_UNLIKELY( !icon) )
icon = vfs_load_icon ( icon_theme, "gtk-directory", size );
if ( big )
mime_type->big_icon = icon;
else
mime_type->small_icon = icon;
return icon ? g_object_ref( icon ) : NULL;
}
sep = strchr( mime_type->type, '/' );
if ( sep )
{
/* convert mime-type foo/bar to foo-bar */
strcpy( icon_name, mime_type->type );
icon_name[ (sep - mime_type->type) ] = '-';
/* is there an icon named foo-bar? */
icon = vfs_load_icon ( icon_theme, icon_name, size );
if ( ! icon )
{
/* maybe we can find a legacy icon named gnome-mime-foo-bar */
strcpy( icon_name, "gnome-mime-" );
strncat( icon_name, mime_type->type, ( sep - mime_type->type ) );
strcat( icon_name, "-" );
strcat( icon_name, sep + 1 );
icon = vfs_load_icon ( icon_theme, icon_name, size );
}
// hack for x-xz-compressed-tar missing icon
if ( !icon && strstr( mime_type->type, "compressed" ) )
{
icon = vfs_load_icon ( icon_theme, "application-x-archive", size );
if ( !icon )
icon = vfs_load_icon ( icon_theme, "gnome-mime-application-x-archive",
size );
}
/* try gnome-mime-foo */
if ( G_UNLIKELY( ! icon ) )
{
icon_name[ 11 ] = '\0'; /* strlen("gnome-mime-") = 11 */
strncat( icon_name, mime_type->type, ( sep - mime_type->type ) );
icon = vfs_load_icon ( icon_theme, icon_name, size );
}
/* try foo-x-generic */
if ( G_UNLIKELY( ! icon ) )
{
strncpy( icon_name, mime_type->type, ( sep - mime_type->type ) );
icon_name[ (sep - mime_type->type) ] = '\0';
strcat( icon_name, "-x-generic" );
icon = vfs_load_icon ( icon_theme, icon_name, size );
}
}
if( G_UNLIKELY( !icon ) )
{
/* prevent endless recursion of XDG_MIME_TYPE_UNKNOWN */
if( G_LIKELY( strcmp(mime_type->type, XDG_MIME_TYPE_UNKNOWN) ) )
{
/* FIXME: fallback to icon of parent mime-type */
VFSMimeType* unknown;
unknown = vfs_mime_type_get_from_type( XDG_MIME_TYPE_UNKNOWN );
icon = vfs_mime_type_get_icon( unknown, big );
vfs_mime_type_unref( unknown );
}
else /* unknown */
{
icon = vfs_load_icon ( icon_theme, "unknown", size );
}
}
if ( big )
mime_type->big_icon = icon;
else
mime_type->small_icon = icon;
return icon ? g_object_ref( icon ) : NULL;
}
static void free_cached_icons ( gpointer key,
gpointer value,
gpointer user_data )
{
VFSMimeType * mime_type = ( VFSMimeType* ) value;
gboolean big = GPOINTER_TO_INT( user_data );
if ( big )
{
if ( mime_type->big_icon )
{
g_object_unref( mime_type->big_icon );
mime_type->big_icon = NULL;
}
}
else
{
if ( mime_type->small_icon )
{
g_object_unref( mime_type->small_icon );
mime_type->small_icon = NULL;
}
}
}
void vfs_mime_type_set_icon_size( int big, int small )
{
g_static_rw_lock_writer_lock( &mime_hash_lock );
if ( big != big_icon_size )
{
big_icon_size = big;
/* Unload old cached icons */
g_hash_table_foreach( mime_hash,
free_cached_icons,
GINT_TO_POINTER( 1 ) );
}
if ( small != small_icon_size )
{
small_icon_size = small;
/* Unload old cached icons */
g_hash_table_foreach( mime_hash,
free_cached_icons,
GINT_TO_POINTER( 0 ) );
}
g_static_rw_lock_writer_unlock( &mime_hash_lock );
}
void vfs_mime_type_get_icon_size( int* big, int* small )
{
if ( big )
* big = big_icon_size;
if ( small )
* small = small_icon_size;
}
const char* vfs_mime_type_get_type( VFSMimeType* mime_type )
{
return mime_type->type;
}
/* Get human-readable description of mime type */
const char* vfs_mime_type_get_description( VFSMimeType* mime_type )
{
if ( G_UNLIKELY( ! mime_type->description ) )
{
mime_type->description = mime_type_get_desc( mime_type->type, NULL );
/* FIXME: should handle this better */
if ( G_UNLIKELY( ! mime_type->description || ! *mime_type->description ) )
{
g_warning( "mime-type %s has no desc", mime_type->type );
mime_type->description = mime_type_get_desc( XDG_MIME_TYPE_UNKNOWN, NULL );
}
}
return mime_type->description;
}
/*
* Join two string vector containing app lists to generate a new one.
* Duplicated app will be removed.
*/
char** vfs_mime_type_join_actions( char** list1, gsize len1,
char** list2, gsize len2 )
{
gchar **ret = NULL;
int i, j, k;
if ( len1 > 0 || len2 > 0 )
ret = g_new0( char*, len1 + len2 + 1 );
for ( i = 0; i < len1; ++i )
{
ret[ i ] = g_strdup( list1[ i ] );
}
for ( j = 0, k = 0; j < len2; ++j )
{
for ( i = 0; i < len1; ++i )
{
if ( 0 == strcmp( ret[ i ], list2[ j ] ) )
break;
}
if ( i >= len1 )
{
ret[ len1 + k ] = g_strdup( list2[ j ] );
++k;
}
}
return ret;
}
char** vfs_mime_type_get_actions( VFSMimeType* mime_type )
{
return (char**)mime_type_get_actions( mime_type->type );
}
char* vfs_mime_type_get_default_action( VFSMimeType* mime_type )
{
char* def = (char*)mime_type_get_default_action( mime_type->type );
/* FIXME:
* If default app is not set, choose one from all availble actions.
* Is there any better way to do this?
* Should we put this fallback handling here, or at API of higher level?
*/
if( ! def )
{
char** actions = mime_type_get_actions( mime_type->type );
if( actions )
{
def = g_strdup( actions[0] );
g_strfreev( actions );
}
}
return def;
}
/*
* Set default app.desktop for specified file.
* app can be the name of the desktop file or a command line.
*/
void vfs_mime_type_set_default_action( VFSMimeType* mime_type,
const char* desktop_id )
{
char* cust_desktop = NULL;
/*
if( ! g_str_has_suffix( desktop_id, ".desktop" ) )
return;
*/
vfs_mime_type_add_action( mime_type, desktop_id, &cust_desktop );
if( cust_desktop )
desktop_id = cust_desktop;
mime_type_set_default_action( mime_type->type, desktop_id );
g_free( cust_desktop );
}
void vfs_mime_type_remove_action( VFSMimeType* mime_type,
const char* desktop_id )
{
mime_type_remove_action( mime_type->type, desktop_id );
}
/* If user-custom desktop file is created, it's returned in custom_desktop. */
void vfs_mime_type_add_action( VFSMimeType* mime_type,
const char* desktop_id,
char** custom_desktop )
{
//MOD don't create custom desktop file if desktop_id is not a command
if ( !g_str_has_suffix( desktop_id, ".desktop" ) )
mime_type_add_action( mime_type->type, desktop_id, custom_desktop );
else if ( custom_desktop ) //sfm
*custom_desktop = g_strdup( desktop_id );
}
/*
* char** vfs_mime_type_get_all_known_apps():
*
* Get all app.desktop files for all mime types.
* The returned string array contains a list of *.desktop file names,
* and should be freed when no longer needed.
*/
#if 0
static void hash_to_strv ( gpointer key, gpointer value, gpointer user_data )
{
char***all_apps = ( char*** ) user_data;
**all_apps = ( char* ) key;
++*all_apps;
}
#endif
void on_icon_theme_changed( GtkIconTheme *icon_theme,
gpointer user_data )
{
/* reload_mime_icons */
g_static_rw_lock_writer_lock( &mime_hash_lock );
g_hash_table_foreach( mime_hash,
free_cached_icons,
GINT_TO_POINTER( 1 ) );
g_hash_table_foreach( mime_hash,
free_cached_icons,
GINT_TO_POINTER( 0 ) );
g_static_rw_lock_writer_unlock( &mime_hash_lock );
}
GList* vfs_mime_type_add_reload_cb( GFreeFunc cb, gpointer user_data )
{
VFSMimeReloadCbEnt* ent = g_slice_new( VFSMimeReloadCbEnt );
ent->cb = cb;
ent->user_data = user_data;
reload_cb = g_list_append( reload_cb, ent );
return g_list_last( reload_cb );
}
void vfs_mime_type_remove_reload_cb( GList* cb )
{
g_slice_free( VFSMimeReloadCbEnt, cb->data );
reload_cb = g_list_delete_link( reload_cb, cb );
}
char* vfs_mime_type_locate_desktop_file( const char* dir, const char* desktop_id )
{
return mime_type_locate_desktop_file( dir, desktop_id );
}
void vfs_mime_type_append_action( const char* type, const char* desktop_id )
{
mime_type_append_action( type, desktop_id );
}
|
157 | ./spacefm/src/vfs/vfs-execute.c | /*
* C Implementation: vfs-execute
*
* Description:
*
*
* Author: Hong Jen Yee (PCMan) <pcman.tw (AT) gmail.com>, (C) 2006
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#include "vfs-execute.h"
#ifdef HAVE_SN
/* FIXME: Startup notification may cause problems */
#define SN_API_NOT_YET_FROZEN
#include <libsn/sn-launcher.h>
#include <X11/Xatom.h>
#include <gtk/gtk.h>
#include <gdk/gdkx.h>
#include <time.h>
#endif
#include <string.h>
#include <stdlib.h>
gboolean vfs_exec( const char* work_dir,
char** argv, char** envp,
const char* disp_name,
GSpawnFlags flags,
GError **err )
{
return vfs_exec_on_screen( gdk_screen_get_default(), work_dir,
argv, envp, disp_name, flags, err );
}
#ifdef HAVE_SN
static gboolean sn_timeout( gpointer user_data )
{
SnLauncherContext * ctx = ( SnLauncherContext* ) user_data;
gdk_threads_enter();
/* FIXME: startup notification, is this correct? */
sn_launcher_context_complete ( ctx );
sn_launcher_context_unref ( ctx );
gdk_threads_leave();
return FALSE;
}
/* This function is taken from the code of thunar, written by Benedikt Meurer <benny@xfce.org> */
static gint
tvsn_get_active_workspace_number ( GdkScreen *screen )
{
GdkWindow * root;
gulong bytes_after_ret = 0;
gulong nitems_ret = 0;
guint *prop_ret = NULL;
Atom _NET_CURRENT_DESKTOP;
Atom _WIN_WORKSPACE;
Atom type_ret = None;
gint format_ret;
gint ws_num = 0;
gdk_error_trap_push ();
root = gdk_screen_get_root_window ( screen );
/* determine the X atom values */
_NET_CURRENT_DESKTOP = XInternAtom ( GDK_WINDOW_XDISPLAY ( root ), "_NET_CURRENT_DESKTOP", False );
_WIN_WORKSPACE = XInternAtom ( GDK_WINDOW_XDISPLAY ( root ), "_WIN_WORKSPACE", False );
if ( XGetWindowProperty ( GDK_WINDOW_XDISPLAY ( root ), GDK_WINDOW_XID ( root ),
_NET_CURRENT_DESKTOP, 0, 32, False, XA_CARDINAL,
&type_ret, &format_ret, &nitems_ret, &bytes_after_ret,
( gpointer ) & prop_ret ) != Success )
{
if ( XGetWindowProperty ( GDK_WINDOW_XDISPLAY ( root ), GDK_WINDOW_XID ( root ),
_WIN_WORKSPACE, 0, 32, False, XA_CARDINAL,
&type_ret, &format_ret, &nitems_ret, &bytes_after_ret,
( gpointer ) & prop_ret ) != Success )
{
if ( G_UNLIKELY ( prop_ret != NULL ) )
{
XFree ( prop_ret );
prop_ret = NULL;
}
}
}
if ( G_LIKELY ( prop_ret != NULL ) )
{
if ( G_LIKELY ( type_ret != None && format_ret != 0 ) )
ws_num = *prop_ret;
XFree ( prop_ret );
}
gint err = gdk_error_trap_pop ();
return ws_num;
}
#endif
gboolean vfs_exec_on_screen( GdkScreen* screen,
const char* work_dir,
char** argv, char** envp,
const char* disp_name,
GSpawnFlags flags,
GError **err )
{
#ifdef HAVE_SN
SnLauncherContext * ctx = NULL;
SnDisplay* display;
#endif
gboolean ret;
GSpawnChildSetupFunc setup_func = NULL;
extern char **environ;
char** new_env = envp;
int i, n_env = 0;
char* display_name;
int display_index = -1, startup_id_index = -1;
if ( ! envp )
envp = environ;
n_env = g_strv_length(envp);
new_env = g_new0( char*, n_env + 4 );
for ( i = 0; i < n_env; ++i )
{
/* g_debug( "old envp[%d] = \"%s\"" , i, envp[i]); */
if ( 0 == strncmp( envp[ i ], "DISPLAY=", 8 ) )
display_index = i;
else
{
if ( 0 == strncmp( envp[ i ], "DESKTOP_STARTUP_ID=", 19 ) )
startup_id_index = i;
new_env[i] = g_strdup( envp[ i ] );
}
}
#ifdef HAVE_SN
display = sn_display_new ( GDK_SCREEN_XDISPLAY ( screen ),
( SnDisplayErrorTrapPush ) gdk_error_trap_push,
( SnDisplayErrorTrapPush ) gdk_error_trap_pop );
if ( G_LIKELY ( display ) )
{
if ( !disp_name )
disp_name = argv[ 0 ];
ctx = sn_launcher_context_new( display, gdk_screen_get_number( screen ) );
sn_launcher_context_set_description( ctx, disp_name );
sn_launcher_context_set_name( ctx, g_get_prgname() );
sn_launcher_context_set_binary_name( ctx, argv[ 0 ] );
sn_launcher_context_set_workspace ( ctx, tvsn_get_active_workspace_number( screen ) );
/* FIXME: I don't think this is correct, other people seem to use CurrentTime here.
However, using CurrentTime causes problems, so I so it like this.
Maybe this is incorrect, but it works, so, who cares?
*/
/* time( &cur_time ); */
sn_launcher_context_initiate( ctx, g_get_prgname(),
argv[ 0 ], gtk_get_current_event_time() /*cur_time*/ );
setup_func = (GSpawnChildSetupFunc) sn_launcher_context_setup_child_process;
if( startup_id_index >= 0 )
g_free( new_env[i] );
else
startup_id_index = i++;
new_env[ startup_id_index ] = g_strconcat( "DESKTOP_STARTUP_ID=",
sn_launcher_context_get_startup_id ( ctx ), NULL );
}
#endif
/* This is taken from gdk_spawn_on_screen */
display_name = gdk_screen_make_display_name ( screen );
if ( display_index >= 0 )
new_env[ display_index ] = g_strconcat( "DISPLAY=", display_name, NULL );
else
new_env[ i++ ] = g_strconcat( "DISPLAY=", display_name, NULL );
g_free( display_name );
new_env[ i ] = NULL;
ret = g_spawn_async( work_dir,
argv, new_env,
flags,
NULL, NULL,
NULL, err );
/* for debugging */
#if 0
g_debug( "debug vfs_execute_on_screen(): flags: %d, display_index=%d", flags, display_index );
for( i = 0; argv[i]; ++i ) {
g_debug( "argv[%d] = \"%s\"" , i, argv[i] );
}
for( i = 0; i < n_env /*new_env[i]*/; ++i ) {
g_debug( "new_env[%d] = \"%s\"" , i, new_env[i] );
}
if( ret )
g_debug( "the program was executed without error" );
else
g_debug( "launch failed: %s", (*err)->message );
#endif
g_strfreev( new_env );
#ifdef HAVE_SN
if ( G_LIKELY ( ctx ) )
{
if ( G_LIKELY ( ret ) )
g_timeout_add ( 20 * 1000, sn_timeout, ctx );
else
{
sn_launcher_context_complete ( ctx );
sn_launcher_context_unref ( ctx );
}
}
if ( G_LIKELY ( display ) )
sn_display_unref ( display );
#endif
return ret;
}
|
158 | ./spacefm/src/vfs/vfs-volume-hal.c | /*
* vfs-volume-hal.c - Support voulme management with HAL
*
* Copyright (C) 2004-2005 Red Hat, Inc, David Zeuthen <davidz@redhat.com>
* Copyright (c) 2005-2007 Benedikt Meurer <benny@xfce.org>
* Copyright 2008 PCMan <pcman.tw@gmail.com>
*
* This file contains source code from other projects:
*
* The icon-name and volume display name parts are taken from
* gnome-vfs-hal-mounts.c of libgnomevfs by David Zeuthen <davidz@redhat.com>.
*
* The HAL volume listing and updating-related parts are taken from
* thunar-vfs-volume-hal.c of Thunar by Benedikt Meurer <benny@xfce.org>.
*
* The mount/umount/eject-related source code is modified from exo-mount.c
* taken from libexo. It's originally written by Benedikt Meurer <benny@xfce.org>.
*
* The fstab-related mount/umount/eject code is modified from gnome-mount.c
* taken from gnome-mount. The original author is David Zeuthen, <david@fubar.dk>.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
/*
* NOTE:
* Originally, I want to use source code from gnome-vfs-hal-mounts.c of gnomevfs
* because its implementation is more complete and *might* be more correct.
* Unfortunately, it's poorly-written, and thanks to the complicated and
* poorly-documented HAL, the readability of most source code in
* gnome-vfs-hal-mounts.c is very poor. So I decided to use the implementation
* provided in Thunar and libexo, which are much cleaner IMHO.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef HAVE_HAL
/* uncomment to get helpful debug messages */
/* #define HAL_SHOW_DEBUG */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#ifdef HAVE_SYS_SYSMACROS_H
#include <sys/sysmacros.h>
#endif
#include <sys/types.h>
#include <unistd.h>
#include <limits.h>
#include <glib.h>
#include <libhal.h>
#include <libhal-storage.h>
#include <dbus/dbus-glib.h>
#include <dbus/dbus-glib-lowlevel.h>
#include "vfs-volume.h"
#include "glib-mem.h"
#include "vfs-file-info.h"
#include "vfs-volume-hal-options.h"
#include "vfs-utils.h" /* for vfs_sudo_cmd() */
#include "main-window.h" //sfm for main_window_event
#include <glib/gi18n.h>
#include <errno.h>
#include <locale.h>
#ifndef PATHNAME_MAX
# define PATHNAME_MAX 1024
#endif
/* For fstab related things */
#if !defined(sun) && !defined(__FreeBSD__)
#include <mntent.h>
#elif defined(__FreeBSD__)
#include <fstab.h>
#include <sys/param.h>
#include <sys/ucred.h>
#include <sys/mount.h>
#elif defined(sun)
#include <sys/mnttab.h>
#endif
typedef enum {
HAL_ICON_DRIVE_REMOVABLE_DISK = 0x10000,
HAL_ICON_DRIVE_REMOVABLE_DISK_IDE = 0x10001,
HAL_ICON_DRIVE_REMOVABLE_DISK_SCSI = 0x10002,
HAL_ICON_DRIVE_REMOVABLE_DISK_USB = 0x10003,
HAL_ICON_DRIVE_REMOVABLE_DISK_IEEE1394 = 0x10004,
HAL_ICON_DRIVE_REMOVABLE_DISK_CCW = 0x10005,
HAL_ICON_DRIVE_DISK = 0x10100,
HAL_ICON_DRIVE_DISK_IDE = 0x10101,
HAL_ICON_DRIVE_DISK_SCSI = 0x10102,
HAL_ICON_DRIVE_DISK_USB = 0x10103,
HAL_ICON_DRIVE_DISK_IEEE1394 = 0x10104,
HAL_ICON_DRIVE_DISK_CCW = 0x10105,
HAL_ICON_DRIVE_CDROM = 0x10200,
HAL_ICON_DRIVE_CDWRITER = 0x102ff,
HAL_ICON_DRIVE_FLOPPY = 0x10300,
HAL_ICON_DRIVE_TAPE = 0x10400,
HAL_ICON_DRIVE_COMPACT_FLASH = 0x10500,
HAL_ICON_DRIVE_MEMORY_STICK = 0x10600,
HAL_ICON_DRIVE_SMART_MEDIA = 0x10700,
HAL_ICON_DRIVE_SD_MMC = 0x10800,
HAL_ICON_DRIVE_CAMERA = 0x10900,
HAL_ICON_DRIVE_PORTABLE_AUDIO_PLAYER = 0x10a00,
HAL_ICON_DRIVE_ZIP = 0x10b00,
HAL_ICON_DRIVE_JAZ = 0x10c00,
HAL_ICON_DRIVE_FLASH_KEY = 0x10d00,
HAL_ICON_VOLUME_REMOVABLE_DISK = 0x20000,
HAL_ICON_VOLUME_REMOVABLE_DISK_IDE = 0x20001,
HAL_ICON_VOLUME_REMOVABLE_DISK_SCSI = 0x20002,
HAL_ICON_VOLUME_REMOVABLE_DISK_USB = 0x20003,
HAL_ICON_VOLUME_REMOVABLE_DISK_IEEE1394 = 0x20004,
HAL_ICON_VOLUME_REMOVABLE_DISK_CCW = 0x20005,
HAL_ICON_VOLUME_DISK = 0x20100,
HAL_ICON_VOLUME_DISK_IDE = 0x20101,
HAL_ICON_VOLUME_DISK_SCSI = 0x20102,
HAL_ICON_VOLUME_DISK_USB = 0x20103,
HAL_ICON_VOLUME_DISK_IEEE1394 = 0x20104,
HAL_ICON_VOLUME_DISK_CCW = 0x20105,
/* specifically left out as we use icons based on media type in the optical drive
HAL_ICON_VOLUME_CDROM = 0x20200 */
HAL_ICON_VOLUME_FLOPPY = 0x20300,
HAL_ICON_VOLUME_TAPE = 0x20400,
HAL_ICON_VOLUME_COMPACT_FLASH = 0x20500,
HAL_ICON_VOLUME_MEMORY_STICK = 0x20600,
HAL_ICON_VOLUME_SMART_MEDIA = 0x20700,
HAL_ICON_VOLUME_SD_MMC = 0x20800,
HAL_ICON_VOLUME_CAMERA = 0x20900,
HAL_ICON_VOLUME_PORTABLE_AUDIO_PLAYER = 0x20a00,
HAL_ICON_VOLUME_ZIP = 0x20b00,
HAL_ICON_VOLUME_JAZ = 0x20c00,
HAL_ICON_VOLUME_FLASH_KEY = 0x20d00,
HAL_ICON_DISC_CDROM = 0x30000,
HAL_ICON_DISC_CDR = 0x30001,
HAL_ICON_DISC_CDRW = 0x30002,
HAL_ICON_DISC_DVDROM = 0x30003,
HAL_ICON_DISC_DVDRAM = 0x30004,
HAL_ICON_DISC_DVDR = 0x30005,
HAL_ICON_DISC_DVDRW = 0x30006,
HAL_ICON_DISC_DVDPLUSR = 0x30007,
HAL_ICON_DISC_DVDPLUSRW = 0x30008,
HAL_ICON_DISC_DVDPLUSR_DL = 0x30009
} HalIcon;
typedef struct {
HalIcon icon;
const char *icon_path;
} HalIconPair;
static const char gnome_dev_removable[] = "gnome-dev-removable";
static const char gnome_dev_removable_usb[] = "gnome-dev-removable-usb";
static const char gnome_dev_removable_1394[] = "gnome-dev-removable-1394";
static const char gnome_dev_harddisk[] = "gnome-dev-harddisk";
static const char gnome_dev_harddisk_usb[] = "gnome-dev-harddisk-usb";
static const char gnome_dev_harddisk_1394[] = "gnome-dev-harddisk-1394";
/* by design, the enums are laid out so we can do easy computations */
static const HalIconPair hal_icon_mapping[] = {
{HAL_ICON_DRIVE_REMOVABLE_DISK, gnome_dev_removable},
{HAL_ICON_DRIVE_REMOVABLE_DISK_IDE, gnome_dev_removable},
{HAL_ICON_DRIVE_REMOVABLE_DISK_SCSI, gnome_dev_removable},
{HAL_ICON_DRIVE_REMOVABLE_DISK_USB, gnome_dev_removable_usb},
{HAL_ICON_DRIVE_REMOVABLE_DISK_IEEE1394, gnome_dev_removable_1394},
{HAL_ICON_DRIVE_REMOVABLE_DISK_CCW, gnome_dev_removable},
{HAL_ICON_DRIVE_DISK, gnome_dev_removable},
{HAL_ICON_DRIVE_DISK_IDE, gnome_dev_removable},
{HAL_ICON_DRIVE_DISK_SCSI, gnome_dev_removable}, /* TODO: gnome-dev-removable-scsi */
{HAL_ICON_DRIVE_DISK_USB, gnome_dev_removable_usb},
{HAL_ICON_DRIVE_DISK_IEEE1394, gnome_dev_removable_1394},
{HAL_ICON_DRIVE_DISK_CCW, gnome_dev_removable},
{HAL_ICON_DRIVE_CDROM, gnome_dev_removable}, /* TODO: gnome-dev-removable-cdrom */
{HAL_ICON_DRIVE_CDWRITER, gnome_dev_removable}, /* TODO: gnome-dev-removable-cdwriter */
{HAL_ICON_DRIVE_FLOPPY, gnome_dev_removable}, /* TODO: gnome-dev-removable-floppy */
{HAL_ICON_DRIVE_TAPE, gnome_dev_removable}, /* TODO: gnome-dev-removable-tape */
{HAL_ICON_DRIVE_COMPACT_FLASH, gnome_dev_removable}, /* TODO: gnome-dev-removable-cf */
{HAL_ICON_DRIVE_MEMORY_STICK, gnome_dev_removable}, /* TODO: gnome-dev-removable-ms */
{HAL_ICON_DRIVE_SMART_MEDIA, gnome_dev_removable}, /* TODO: gnome-dev-removable-sm */
{HAL_ICON_DRIVE_SD_MMC, gnome_dev_removable}, /* TODO: gnome-dev-removable-sdmmc */
{HAL_ICON_DRIVE_CAMERA, gnome_dev_removable}, /* TODO: gnome-dev-removable-camera */
{HAL_ICON_DRIVE_PORTABLE_AUDIO_PLAYER, gnome_dev_removable}, /* TODO: gnome-dev-removable-ipod */
{HAL_ICON_DRIVE_ZIP, gnome_dev_removable}, /* TODO: gnome-dev-removable-zip */
{HAL_ICON_DRIVE_JAZ, gnome_dev_removable}, /* TODO: gnome-dev-removable-jaz */
{HAL_ICON_DRIVE_FLASH_KEY, gnome_dev_removable}, /* TODO: gnome-dev-removable-pendrive */
{HAL_ICON_VOLUME_REMOVABLE_DISK, gnome_dev_harddisk},
{HAL_ICON_VOLUME_REMOVABLE_DISK_IDE, gnome_dev_harddisk},
{HAL_ICON_VOLUME_REMOVABLE_DISK_SCSI, gnome_dev_harddisk}, /* TODO: gnome-dev-harddisk-scsi */
{HAL_ICON_VOLUME_REMOVABLE_DISK_USB, gnome_dev_harddisk_usb},
{HAL_ICON_VOLUME_REMOVABLE_DISK_IEEE1394, gnome_dev_harddisk_1394},
{HAL_ICON_VOLUME_REMOVABLE_DISK_CCW, gnome_dev_harddisk},
{HAL_ICON_VOLUME_DISK, gnome_dev_harddisk},
{HAL_ICON_VOLUME_DISK_IDE, gnome_dev_harddisk},
{HAL_ICON_VOLUME_DISK_SCSI, gnome_dev_harddisk},
{HAL_ICON_VOLUME_DISK_USB, gnome_dev_harddisk_usb},
{HAL_ICON_VOLUME_DISK_IEEE1394, gnome_dev_harddisk_1394},
{HAL_ICON_VOLUME_DISK_CCW, gnome_dev_harddisk},
{HAL_ICON_VOLUME_FLOPPY, "gnome-dev-floppy"},
{HAL_ICON_VOLUME_TAPE, gnome_dev_harddisk},
{HAL_ICON_VOLUME_COMPACT_FLASH, "gnome-dev-media-cf"},
{HAL_ICON_VOLUME_MEMORY_STICK, "gnome-dev-media-ms"},
{HAL_ICON_VOLUME_SMART_MEDIA, "gnome-dev-media-sm"},
{HAL_ICON_VOLUME_SD_MMC, "gnome-dev-media-sdmmc"},
{HAL_ICON_VOLUME_CAMERA, "camera"},
{HAL_ICON_VOLUME_PORTABLE_AUDIO_PLAYER, "gnome-dev-ipod"},
{HAL_ICON_VOLUME_ZIP, "gnome-dev-zipdisk"},
{HAL_ICON_VOLUME_JAZ, "gnome-dev-jazdisk"},
{HAL_ICON_VOLUME_FLASH_KEY, gnome_dev_harddisk}, /* TODO: gnome-dev-pendrive */
{HAL_ICON_DISC_CDROM, "gnome-dev-cdrom"},
{HAL_ICON_DISC_CDR, "gnome-dev-disc-cdr"},
{HAL_ICON_DISC_CDRW, "gnome-dev-disc-cdrw"},
{HAL_ICON_DISC_DVDROM, "gnome-dev-disc-dvdrom"},
{HAL_ICON_DISC_DVDRAM, "gnome-dev-disc-dvdram"},
{HAL_ICON_DISC_DVDR, "gnome-dev-disc-dvdr"},
{HAL_ICON_DISC_DVDRW, "gnome-dev-disc-dvdrw"},
{HAL_ICON_DISC_DVDPLUSR, "gnome-dev-disc-dvdr-plus"},
{HAL_ICON_DISC_DVDPLUSRW, "gnome-dev-disc-dvdrw"}, /* TODO: gnome-dev-disc-dvdrw-plus */
{HAL_ICON_DISC_DVDPLUSR_DL, "gnome-dev-disc-dvdr-plus"}, /* TODO: gnome-dev-disc-dvdr-plus-dl */
{0x00, NULL}
};
const char ERR_BUSY[] = "org.freedesktop.Hal.Device.Volume.Busy";
const char ERR_PERM_DENIED[] = "org.freedesktop.Hal.Device.Volume.PermissionDenied";
const char ERR_UNKNOWN_FAILURE[] = "org.freedesktop.Hal.Device.Volume.UnknownFailure";
const char ERR_INVALID_MOUNT_OPT[] = "org.freedesktop.Hal.Device.Volume.InvalidMountOption";
const char ERR_UNKNOWN_FS[] = "org.freedesktop.Hal.Device.Volume.UnknownFilesystemType";
const char ERR_NOT_MOUNTED[] = "org.freedesktop.Hal.Device.Volume.NotMounted";
const char ERR_NOT_MOUNTED_BY_HAL[] = "org.freedesktop.Hal.Device.Volume.NotMountedByHal";
const char ERR_ALREADY_MOUNTED[] = "org.freedesktop.Hal.Device.Volume.AlreadyMounted";
const char ERR_INVALID_MOUNT_POINT[] = "org.freedesktop.Hal.Device.Volume.InvalidMountpoint";
const char ERR_MOUNT_POINT_NOT_AVAILABLE[] = "org.freedesktop.Hal.Device.Volume.MountPointNotAvailable";
struct _VFSVolume
{
char* udi;
char* disp_name;
const char* icon;
char* mount_point;
char* device_file;
gboolean is_mounted : 1;
/* gboolean is_hotpluggable : 1; */
gboolean is_removable : 1;
gboolean is_mountable : 1;
gboolean requires_eject : 1;
gboolean is_user_visible : 1;
};
typedef struct _VFSVolumeCallbackData
{
VFSVolumeCallback cb;
gpointer user_data;
}VFSVolumeCallbackData;
/*------------------------------------------------------------------------*/
/* BEGIN: Added by Hong Jen Yee on 2008-02-02 */
static LibHalContext* hal_context = NULL;
static DBusConnection * dbus_connection = NULL;
static GList* volumes = NULL;
static GArray* callbacks = NULL;
static VFSVolume *vfs_volume_get_volume_by_udi (const gchar *udi);
static void vfs_volume_update_volume_by_udi ( const gchar *udi);
static void vfs_volume_device_added (LibHalContext *context,
const gchar *udi);
static void vfs_volume_device_removed (LibHalContext *context,
const gchar *udi);
static void vfs_volume_device_new_capability (LibHalContext *context,
const gchar *udi,
const gchar *capability);
static void vfs_volume_device_lost_capability (LibHalContext *context,
const gchar *udi,
const gchar *capability);
static void vfs_volume_device_property_modified (LibHalContext *context,
const gchar *udi,
const gchar *key,
dbus_bool_t is_removed,
dbus_bool_t is_added);
static void vfs_volume_device_condition (LibHalContext *context,
const gchar *udi,
const gchar *name,
const gchar *details);
static gboolean vfs_volume_mount_by_udi_as_root( const char* udi );
static gboolean vfs_volume_umount_by_udi_as_root( const char* udi );
static gboolean vfs_volume_eject_by_udi_as_root( const char* udi );
static void call_callbacks( VFSVolume* vol, VFSVolumeState state )
{
int i;
VFSVolumeCallbackData* e;
if ( !callbacks )
return ;
e = ( VFSVolumeCallbackData* ) callbacks->data;
for ( i = 0; i < callbacks->len; ++i )
{
( *e[ i ].cb ) ( vol, state, e[ i ].user_data );
}
if ( evt_device->s || evt_device->ob2_data )
main_window_event( NULL, NULL, "evt_device", 0, 0, vol->device_file, 0,
0, state, FALSE );
}
/* END: Added by Hong Jen Yee on 2008-02-02 */
static const char *
_hal_lookup_icon (HalIcon icon)
{
int i;
const char *result;
result = NULL;
/* TODO: could make lookup better than O(n) */
for (i = 0; hal_icon_mapping[i].icon_path != NULL; i++) {
if (hal_icon_mapping[i].icon == icon) {
result = hal_icon_mapping[i].icon_path;
break;
}
}
return result;
}
/* hal_volume may be NULL */
static char *
_hal_drive_policy_get_icon (LibHalDrive *hal_drive, LibHalVolume *hal_volume)
{
const char *name;
LibHalDriveBus bus;
LibHalDriveType drive_type;
name = libhal_drive_get_dedicated_icon_drive (hal_drive);
if (name != NULL)
goto out;
bus = libhal_drive_get_bus (hal_drive);
drive_type = libhal_drive_get_type (hal_drive);
/* by design, the enums are laid out so we can do easy computations */
switch (drive_type) {
case LIBHAL_DRIVE_TYPE_REMOVABLE_DISK:
case LIBHAL_DRIVE_TYPE_DISK:
name = _hal_lookup_icon (0x10000 + drive_type*0x100 + bus);
break;
case LIBHAL_DRIVE_TYPE_CDROM:
{
LibHalDriveCdromCaps cdrom_caps;
gboolean cdrom_can_burn;
/* can burn if other flags than cdrom and dvdrom */
cdrom_caps = libhal_drive_get_cdrom_caps (hal_drive);
cdrom_can_burn = ((cdrom_caps & (LIBHAL_DRIVE_CDROM_CAPS_CDROM|
LIBHAL_DRIVE_CDROM_CAPS_DVDROM)) == cdrom_caps);
name = _hal_lookup_icon (0x10000 + drive_type*0x100 + (cdrom_can_burn ? 0xff : 0x00));
break;
}
default:
name = _hal_lookup_icon (0x10000 + drive_type*0x100);
}
out:
if (name != NULL)
return g_strdup (name);
else {
g_warning ("_hal_drive_policy_get_icon : error looking up icon; defaulting to gnome-dev-removable");
return g_strdup (gnome_dev_removable);
}
}
static char *
_hal_volume_policy_get_icon (LibHalDrive *hal_drive, LibHalVolume *hal_volume)
{
const char *name;
LibHalDriveBus bus;
LibHalDriveType drive_type;
LibHalVolumeDiscType disc_type;
name = libhal_drive_get_dedicated_icon_volume (hal_drive);
if (name != NULL)
goto out;
/* by design, the enums are laid out so we can do easy computations */
if (libhal_volume_is_disc (hal_volume)) {
disc_type = libhal_volume_get_disc_type (hal_volume);
name = _hal_lookup_icon (0x30000 + disc_type);
goto out;
}
if (hal_drive == NULL) {
name = _hal_lookup_icon (HAL_ICON_VOLUME_REMOVABLE_DISK);
goto out;
}
bus = libhal_drive_get_bus (hal_drive);
drive_type = libhal_drive_get_type (hal_drive);
switch (drive_type) {
case LIBHAL_DRIVE_TYPE_REMOVABLE_DISK:
case LIBHAL_DRIVE_TYPE_DISK:
name = _hal_lookup_icon (0x20000 + drive_type*0x100 + bus);
break;
default:
name = _hal_lookup_icon (0x20000 + drive_type*0x100);
}
out:
if (name != NULL)
return g_strdup (name);
else {
g_warning ("_hal_volume_policy_get_icon : error looking up icon; defaulting to gnome-dev-harddisk");
return g_strdup (gnome_dev_harddisk);
}
}
/*------------------------------------------------------------------------*/
/* hal_volume may be NULL */
static char *
_hal_drive_policy_get_display_name (LibHalDrive *hal_drive, LibHalVolume *hal_volume)
{
const char *model;
const char *vendor;
LibHalDriveType drive_type;
char *name;
char *vm_name;
gboolean may_prepend_external;
name = NULL;
may_prepend_external = FALSE;
drive_type = libhal_drive_get_type (hal_drive);
/* Handle disks without removable media */
if ((drive_type == LIBHAL_DRIVE_TYPE_DISK) &&
!libhal_drive_uses_removable_media (hal_drive) &&
hal_volume != NULL) {
const char *label;
char size_str[64];
/* use label if available */
label = libhal_volume_get_label (hal_volume);
if (label != NULL && strlen (label) > 0) {
name = g_strdup (label);
goto out;
}
/* Otherwise, just use volume size */
vfs_file_size_to_string (size_str, libhal_volume_get_size (hal_volume));
name = g_strdup_printf (_("%s Volume"), size_str);
goto out;
}
/* removable media and special drives */
/* drives we know the type of */
if (drive_type == LIBHAL_DRIVE_TYPE_CDROM) {
const char *first;
const char *second;
LibHalDriveCdromCaps drive_cdrom_caps;
drive_cdrom_caps = libhal_drive_get_cdrom_caps (hal_drive);
first = _("CD-ROM");
if (drive_cdrom_caps & LIBHAL_DRIVE_CDROM_CAPS_CDR)
first = _("CD-R");
if (drive_cdrom_caps & LIBHAL_DRIVE_CDROM_CAPS_CDRW)
first = _("CD-RW");
second = NULL;
if (drive_cdrom_caps & LIBHAL_DRIVE_CDROM_CAPS_DVDROM)
second = _("DVD-ROM");
if (drive_cdrom_caps & LIBHAL_DRIVE_CDROM_CAPS_DVDPLUSR)
second = _("DVD+R");
if (drive_cdrom_caps & LIBHAL_DRIVE_CDROM_CAPS_DVDPLUSRW)
second = _("DVD+RW");
if (drive_cdrom_caps & LIBHAL_DRIVE_CDROM_CAPS_DVDR)
second = _("DVD-R");
if (drive_cdrom_caps & LIBHAL_DRIVE_CDROM_CAPS_DVDRW)
second = _("DVD-RW");
if (drive_cdrom_caps & LIBHAL_DRIVE_CDROM_CAPS_DVDRAM)
second = _("DVD-RAM");
if ((drive_cdrom_caps & LIBHAL_DRIVE_CDROM_CAPS_DVDR) &&
(drive_cdrom_caps & LIBHAL_DRIVE_CDROM_CAPS_DVDPLUSR))
second = ("DVD┬▒R");
if ((drive_cdrom_caps & LIBHAL_DRIVE_CDROM_CAPS_DVDRW) &&
(drive_cdrom_caps & LIBHAL_DRIVE_CDROM_CAPS_DVDPLUSRW))
second = ("DVD┬▒RW");
if (second != NULL) {
name = g_strdup_printf (_("%s/%s Drive"), first, second);
} else {
name = g_strdup_printf (_("%s Drive"), first);
}
may_prepend_external = TRUE;
} else if (drive_type == LIBHAL_DRIVE_TYPE_FLOPPY) {
name = g_strdup (_("Floppy Drive"));
may_prepend_external = TRUE;
} else if (drive_type == LIBHAL_DRIVE_TYPE_COMPACT_FLASH) {
name = g_strdup (_("Compact Flash Drive"));
} else if (drive_type == LIBHAL_DRIVE_TYPE_MEMORY_STICK) {
name = g_strdup (_("Memory Stick Drive"));
} else if (drive_type == LIBHAL_DRIVE_TYPE_SMART_MEDIA) {
name = g_strdup (_("Smart Media Drive"));
} else if (drive_type == LIBHAL_DRIVE_TYPE_SD_MMC) {
name = g_strdup (_("SD/MMC Drive"));
} else if (drive_type == LIBHAL_DRIVE_TYPE_ZIP) {
name = g_strdup (_("Zip Drive"));
may_prepend_external = TRUE;
} else if (drive_type == LIBHAL_DRIVE_TYPE_JAZ) {
name = g_strdup (_("Jaz Drive"));
may_prepend_external = TRUE;
} else if (drive_type == LIBHAL_DRIVE_TYPE_FLASHKEY) {
name = g_strdup (_("Pen Drive"));
} else if (drive_type == LIBHAL_DRIVE_TYPE_PORTABLE_AUDIO_PLAYER) {
const char *vendor;
const char *model;
vendor = libhal_drive_get_vendor (hal_drive);
model = libhal_drive_get_model (hal_drive);
name = g_strdup_printf (_("%s %s Music Player"),
vendor != NULL ? vendor : "",
model != NULL ? model : "");
} else if (drive_type == LIBHAL_DRIVE_TYPE_CAMERA) {
const char *vendor;
const char *model;
vendor = libhal_drive_get_vendor (hal_drive);
model = libhal_drive_get_model (hal_drive);
name = g_strdup_printf (_("%s %s Digital Camera"),
vendor != NULL ? vendor : "",
model != NULL ? model : "");
}
if (name != NULL)
goto out;
/* model and vendor at last resort */
model = libhal_drive_get_model (hal_drive);
vendor = libhal_drive_get_vendor (hal_drive);
vm_name = NULL;
if (vendor == NULL || strlen (vendor) == 0) {
if (model != NULL && strlen (model) > 0)
vm_name = g_strdup (model);
} else {
if (model == NULL || strlen (model) == 0)
vm_name = g_strdup (vendor);
else {
vm_name = g_strdup_printf ("%s %s", vendor, model);
}
}
if (vm_name != NULL) {
name = vm_name;
}
out:
/* lame fallback */
if (name == NULL)
name = g_strdup (_("Drive"));
if (may_prepend_external) {
if (libhal_drive_is_hotpluggable (hal_drive)) {
char *tmp = name;
name = g_strdup_printf (_("External %s"), name);
g_free (tmp);
}
}
return name;
}
static char *
_hal_volume_policy_get_display_name (LibHalDrive *hal_drive, LibHalVolume *hal_volume)
{
LibHalDriveType drive_type;
const char *volume_label;
char *name;
char size_str[64];
name = NULL;
drive_type = libhal_drive_get_type (hal_drive);
volume_label = libhal_volume_get_label (hal_volume);
/* Use volume label if available */
if (volume_label != NULL) {
name = g_strdup (volume_label);
goto out;
}
/* Handle media in optical drives */
if (drive_type == LIBHAL_DRIVE_TYPE_CDROM) {
switch (libhal_volume_get_disc_type (hal_volume)) {
default:
/* explict fallthrough */
case LIBHAL_VOLUME_DISC_TYPE_CDROM:
name = g_strdup (_("CD-ROM Disc"));
break;
case LIBHAL_VOLUME_DISC_TYPE_CDR:
if (libhal_volume_disc_is_blank (hal_volume))
name = g_strdup (_("Blank CD-R Disc"));
else
name = g_strdup (_("CD-R Disc"));
break;
case LIBHAL_VOLUME_DISC_TYPE_CDRW:
if (libhal_volume_disc_is_blank (hal_volume))
name = g_strdup (_("Blank CD-RW Disc"));
else
name = g_strdup (_("CD-RW Disc"));
break;
case LIBHAL_VOLUME_DISC_TYPE_DVDROM:
name = g_strdup (_("DVD-ROM Disc"));
break;
case LIBHAL_VOLUME_DISC_TYPE_DVDRAM:
if (libhal_volume_disc_is_blank (hal_volume))
name = g_strdup (_("Blank DVD-RAM Disc"));
else
name = g_strdup (_("DVD-RAM Disc"));
break;
case LIBHAL_VOLUME_DISC_TYPE_DVDR:
if (libhal_volume_disc_is_blank (hal_volume))
name = g_strdup (_("Blank DVD-R Disc"));
else
name = g_strdup (_("DVD-R Disc"));
break;
case LIBHAL_VOLUME_DISC_TYPE_DVDRW:
if (libhal_volume_disc_is_blank (hal_volume))
name = g_strdup (_("Blank DVD-RW Disc"));
else
name = g_strdup (_("DVD-RW Disc"));
break;
case LIBHAL_VOLUME_DISC_TYPE_DVDPLUSR:
if (libhal_volume_disc_is_blank (hal_volume))
name = g_strdup (_("Blank DVD+R Disc"));
else
name = g_strdup (_("DVD+R Disc"));
break;
case LIBHAL_VOLUME_DISC_TYPE_DVDPLUSRW:
if (libhal_volume_disc_is_blank (hal_volume))
name = g_strdup (_("Blank DVD+RW Disc"));
else
name = g_strdup (_("DVD+RW Disc"));
break;
}
/* Special case for pure audio disc */
if (libhal_volume_disc_has_audio (hal_volume) && !libhal_volume_disc_has_data (hal_volume)) {
free (name);
name = g_strdup (_("Audio Disc"));
}
goto out;
}
/* Fallback: size of media */
vfs_file_size_to_string (size_str, libhal_volume_get_size (hal_volume));
if (libhal_drive_uses_removable_media (hal_drive)) {
name = g_strdup_printf (_("%s Removable Volume"), size_str);
} else {
name = g_strdup_printf (_("%s Volume"), size_str);
}
out:
/* lame fallback */
if (name == NULL)
name = g_strdup (_("Volume"));
return name;
}
/*------------------------------------------------------------------------*/
#if 0
static gboolean
_hal_volume_temp_udi (LibHalDrive *hal_drive, LibHalVolume *hal_volume)
{
const char *volume_udi;
gboolean ret;
ret = FALSE;
volume_udi = libhal_volume_get_udi (hal_volume);
if (strncmp (volume_udi, "/org/freedesktop/Hal/devices/temp",
strlen ("/org/freedesktop/Hal/devices/temp")) == 0)
ret = TRUE;
return ret;
}
static gboolean
_hal_volume_policy_show_on_desktop (LibHalDrive *hal_drive, LibHalVolume *hal_volume)
{
gboolean ret;
ret = TRUE;
/* Right now we show everything on the desktop as there is no setting
* for this.. potentially we could hide fixed drives..
*/
return ret;
}
#endif
/*------------------------------------------------------------------------*/
static VFSVolume* vfs_volume_new( const char* udi )
{
VFSVolume * volume;
volume = g_slice_new0( VFSVolume );
volume->udi = g_strdup( udi );
return volume;
}
void vfs_volume_free( VFSVolume* volume )
{
g_free( volume->udi );
g_free( volume->disp_name );
g_free( volume->mount_point );
g_free( volume->device_file );
g_slice_free( VFSVolume, volume );
}
static void
vfs_volume_update (VFSVolume *volume,
LibHalContext *context,
LibHalVolume *hv,
LibHalDrive *hd)
{
gchar *desired_mount_point;
gchar *mount_root;
gchar *basename;
gchar *filename;
/* reset the volume status */
// volume->status = 0;
/* determine the new device file */
g_free (volume->device_file);
volume->device_file = g_strdup ((hv != NULL) ? libhal_volume_get_device_file (hv) : libhal_drive_get_device_file (hd));
/* release the previous mount point (if any) */
if (G_LIKELY (volume->mount_point != NULL))
{
g_free(volume->mount_point);
volume->mount_point = NULL;
}
if (libhal_drive_uses_removable_media (hd)
|| libhal_drive_is_hotpluggable (hd))
{
volume->is_removable = TRUE;
}
else
volume->is_removable = FALSE;
#if 0
/* determine the type of the volume */
switch (libhal_drive_get_type (hd))
{
case LIBHAL_DRIVE_TYPE_CDROM:
/* check if we have a pure audio CD without any data track */
if (libhal_volume_disc_has_audio (hv) && !libhal_volume_disc_has_data (hv))
{
/* special treatment for pure audio CDs */
volume->kind = VFS_VOLUME_KIND_AUDIO_CD;
}
else
{
/* check which kind of CD-ROM/DVD we have */
switch (libhal_volume_get_disc_type (hv))
{
case LIBHAL_VOLUME_DISC_TYPE_CDROM:
volume->kind = VFS_VOLUME_KIND_CDROM;
break;
case LIBHAL_VOLUME_DISC_TYPE_CDR:
volume->kind = VFS_VOLUME_KIND_CDR;
break;
case LIBHAL_VOLUME_DISC_TYPE_CDRW:
volume->kind = VFS_VOLUME_KIND_CDRW;
break;
case LIBHAL_VOLUME_DISC_TYPE_DVDROM:
volume->kind = VFS_VOLUME_KIND_DVDROM;
break;
case LIBHAL_VOLUME_DISC_TYPE_DVDRAM:
volume->kind = VFS_VOLUME_KIND_DVDRAM;
break;
case LIBHAL_VOLUME_DISC_TYPE_DVDR:
volume->kind = VFS_VOLUME_KIND_DVDR;
break;
case LIBHAL_VOLUME_DISC_TYPE_DVDRW:
volume->kind = VFS_VOLUME_KIND_DVDRW;
break;
case LIBHAL_VOLUME_DISC_TYPE_DVDPLUSR:
volume->kind = VFS_VOLUME_KIND_DVDPLUSR;
break;
case LIBHAL_VOLUME_DISC_TYPE_DVDPLUSRW:
volume->kind = VFS_VOLUME_KIND_DVDPLUSRW;
break;
default:
/* unsupported disc type */
volume->kind = VFS_VOLUME_KIND_UNKNOWN;
break;
}
}
break;
case LIBHAL_DRIVE_TYPE_FLOPPY:
volume->kind = VFS_VOLUME_KIND_FLOPPY;
break;
case LIBHAL_DRIVE_TYPE_PORTABLE_AUDIO_PLAYER:
volume->kind = VFS_VOLUME_KIND_AUDIO_PLAYER;
break;
case LIBHAL_DRIVE_TYPE_SMART_MEDIA:
case LIBHAL_DRIVE_TYPE_SD_MMC:
volume->kind = VFS_VOLUME_KIND_MEMORY_CARD;
break;
default:
/* check if the drive is connected to the USB bus */
if (libhal_drive_get_bus (hd) == LIBHAL_DRIVE_BUS_USB)
{
/* we consider the drive to be an USB stick */
volume->kind = VFS_VOLUME_KIND_USBSTICK;
}
else if (libhal_drive_uses_removable_media (hd)
|| libhal_drive_is_hotpluggable (hd))
{
/* fallback to generic removable disk */
volume->kind = VFS_VOLUME_KIND_REMOVABLE_DISK;
}
else
{
/* fallback to harddisk drive */
volume->kind = VFS_VOLUME_KIND_HARDDISK;
}
break;
}
#endif
/* either we have a volume, which means we have media, or
* a drive, which means non-pollable then, so it's present
*/
// volume->status |= VFS_VOLUME_STATUS_PRESENT;
/* figure out if the volume is mountable */
if(hv != NULL && libhal_volume_get_fsusage (hv) == LIBHAL_VOLUME_USAGE_MOUNTABLE_FILESYSTEM)
volume->is_mountable = TRUE;
/* check if the drive requires eject */
volume->requires_eject = libhal_drive_requires_eject (hd);
/* check if the volume is currently mounted */
if (hv != NULL && libhal_volume_is_mounted (hv))
{
/* try to determine the new mount point */
volume->mount_point = g_strdup(libhal_volume_get_mount_point (hv));
/* we only mark the volume as mounted if we have a valid mount point */
if (G_LIKELY (volume->mount_point != NULL))
volume->is_mounted = TRUE;
}
else
{
/* we don't trust HAL, so let's see what the kernel says about the volume */
volume->mount_point = NULL;
// volume->mount_point = vfs_volume_find_active_mount_point (volume);
volume->is_mounted = FALSE;
/* we must have been mounted successfully if we have a mount point */
//if (G_LIKELY (volume->mount_point != NULL))
// volume->status |= VFS_VOLUME_STATUS_MOUNTED | VFS_VOLUME_STATUS_PRESENT;
}
/* check if we have to figure out the mount point ourself */
if (G_UNLIKELY (volume->mount_point == NULL))
{
/* ask HAL for the default mount root (falling back to /media otherwise) */
mount_root = libhal_device_get_property_string (context, "/org/freedesktop/Hal/devices/computer", "storage.policy.default.mount_root", NULL);
if (G_UNLIKELY (mount_root == NULL || !g_path_is_absolute (mount_root)))
{
/* fallback to /media (seems to be sane) */
g_free (mount_root);
mount_root = g_strdup ("/media");
}
/* lets see, maybe /etc/fstab knows where to mount */
//FIXME: volume->mount_point = vfs_volume_find_fstab_mount_point (volume);
volume->mount_point = NULL;
/* if we still don't have a mount point, ask HAL */
if (G_UNLIKELY (volume->mount_point == NULL))
{
/* determine the desired mount point and prepend the mount root */
desired_mount_point = libhal_device_get_property_string (context, volume->udi, "volume.policy.desired_mount_point", NULL);
if (G_LIKELY (desired_mount_point != NULL && *desired_mount_point != '\0'))
{
filename = g_build_filename (mount_root, desired_mount_point, NULL);
volume->mount_point = filename;
}
libhal_free_string (desired_mount_point);
}
/* ok, last fallback, just use <mount-root>/<device> */
if (G_UNLIKELY (volume->mount_point == NULL))
{
/* <mount-root>/<device> looks like a good idea */
basename = g_path_get_basename (volume->device_file);
filename = g_build_filename (mount_root, basename, NULL);
volume->mount_point = filename;
g_free (basename);
}
/* release the mount root */
g_free (mount_root);
}
/* if we get here, we must have a valid mount point */
g_assert (volume->mount_point != NULL);
/* compute a usable display name for the volume/drive */
g_free( volume->disp_name );
volume->disp_name = (volume->is_mounted && hv )
? _hal_volume_policy_get_display_name(hd, hv)
: _hal_drive_policy_get_display_name(hd, hv);
if (G_UNLIKELY (volume->disp_name == NULL))
{
/* use the basename of the device file as label */
volume->disp_name = g_path_get_basename (volume->device_file);
}
/* compute a usable list of icon names for the volume/drive */
volume->icon = (volume->is_mounted && hv )
? _hal_volume_policy_get_icon( hd, hv)
: _hal_drive_policy_get_icon( hd, hv );
/* emit the "changed" signal */
//vfs_volume_is_changed (THUNAR_VFS_VOLUME (volume));
call_callbacks( volume, VFS_VOLUME_CHANGED );
}
gboolean vfs_volume_init ()
{
LibHalDrive *hd;
DBusError error;
gchar **drive_udis;
gchar **udis;
gint n_drive_udis;
gint n_udis;
gint n, m;
/* initialize the D-BUS error */
dbus_error_init (&error);
/* allocate a HAL context */
hal_context = libhal_ctx_new ();
if (G_UNLIKELY (hal_context == NULL))
return FALSE;
/* try to connect to the system bus */
dbus_connection = dbus_bus_get (DBUS_BUS_SYSTEM, &error);
if (G_UNLIKELY (dbus_connection == NULL))
goto failed;
/* setup the D-BUS connection for the HAL context */
libhal_ctx_set_dbus_connection (hal_context, dbus_connection);
/* connect our manager object to the HAL context */
// libhal_ctx_set_user_data (hal_context, manager_hal);
/* setup callbacks */
libhal_ctx_set_device_added (hal_context, vfs_volume_device_added);
libhal_ctx_set_device_removed (hal_context, vfs_volume_device_removed);
libhal_ctx_set_device_new_capability (hal_context, vfs_volume_device_new_capability);
libhal_ctx_set_device_lost_capability (hal_context, vfs_volume_device_lost_capability);
libhal_ctx_set_device_property_modified (hal_context, vfs_volume_device_property_modified);
libhal_ctx_set_device_condition (hal_context, vfs_volume_device_condition);
/* try to initialize the HAL context */
if (!libhal_ctx_init (hal_context, &error))
goto failed;
/* setup the D-BUS connection with the GLib main loop */
dbus_connection_setup_with_g_main (dbus_connection, NULL);
/* lookup all drives currently known to HAL */
drive_udis = libhal_find_device_by_capability (hal_context, "storage", &n_drive_udis, &error);
if (G_LIKELY (drive_udis != NULL))
{
/* process all drives UDIs */
for (m = 0; m < n_drive_udis; ++m)
{
/* determine the LibHalDrive for the drive UDI */
hd = libhal_drive_from_udi (hal_context, drive_udis[m]);
if (G_UNLIKELY (hd == NULL))
continue;
/* check if we have a floppy disk here */
if (libhal_drive_get_type (hd) == LIBHAL_DRIVE_TYPE_FLOPPY)
{
/* add the drive based on the UDI */
vfs_volume_device_added (hal_context, drive_udis[m]);
}
else
{
/* determine all volumes for the given drive */
udis = libhal_drive_find_all_volumes (hal_context, hd, &n_udis);
if (G_LIKELY (udis != NULL))
{
/* add volumes for all given UDIs */
for (n = 0; n < n_udis; ++n)
{
/* add the volume based on the UDI */
vfs_volume_device_added (hal_context, udis[n]);
/* release the UDI (HAL bug #5279) */
free (udis[n]);
}
/* release the UDIs array (HAL bug #5279) */
free (udis);
}
}
/* release the hal drive */
libhal_drive_free (hd);
}
/* release the drive UDIs */
libhal_free_string_array (drive_udis);
}
/* watch all devices for changes */
if (!libhal_device_property_watch_all (hal_context, &error))
goto failed;
return TRUE;
failed:
/* release the HAL context */
if (G_LIKELY (hal_context != NULL))
{
libhal_ctx_free (hal_context);
hal_context = NULL;
}
/* print a warning message */
if (dbus_error_is_set (&error))
{
g_warning (_("Failed to connect to the HAL daemon: %s"), error.message);
dbus_error_free (&error);
}
return FALSE;
}
static VFSVolume*
vfs_volume_get_volume_by_udi ( const gchar *udi)
{
GList *l;
for (l = volumes; l != NULL; l = l->next)
if ( ! strcmp( ((VFSVolume*)l->data)->udi, udi) )
return (VFSVolume*)l->data;
return NULL;
}
static void
vfs_volume_update_volume_by_udi ( const gchar *udi)
{
VFSVolume *volume;
LibHalVolume *hv = NULL;
LibHalDrive *hd = NULL;
const gchar *drive_udi;
/* check if we have a volume for the UDI */
volume = vfs_volume_get_volume_by_udi (udi);
if (G_UNLIKELY (volume == NULL))
return;
/* check if we have a volume here */
hv = libhal_volume_from_udi (hal_context, udi);
if (G_UNLIKELY (hv == NULL))
{
/* check if we have a drive here */
hd = libhal_drive_from_udi (hal_context, udi);
if (G_UNLIKELY (hd == NULL))
{
/* the device is no longer a drive or volume, so drop it */
vfs_volume_device_removed (hal_context, udi);
return;
}
/* update the drive with the new HAL drive/volume */
vfs_volume_update (volume, hal_context, NULL, hd);
/* release the drive */
libhal_drive_free (hd);
}
else
{
/* determine the UDI of the drive to which this volume belongs */
drive_udi = libhal_volume_get_storage_device_udi (hv);
if (G_LIKELY (drive_udi != NULL))
{
/* determine the drive for the volume */
hd = libhal_drive_from_udi (hal_context, drive_udi);
}
/* check if we have the drive for the volume */
if (G_LIKELY (hd != NULL))
{
/* update the volume with the new HAL drive/volume */
vfs_volume_update (volume, hal_context, hv, hd);
/* release the drive */
libhal_drive_free (hd);
}
else
{
/* unable to determine the drive, volume gone? */
vfs_volume_device_removed (hal_context, udi);
}
/* release the volume */
libhal_volume_free (hv);
}
}
static void vfs_volume_add( VFSVolume* volume )
{
volumes = g_list_append( volumes, volume );
call_callbacks( volume, VFS_VOLUME_ADDED );
}
static void vfs_volume_remove( VFSVolume* volume )
{
volumes = g_list_remove( volumes, volume );
call_callbacks( volume, VFS_VOLUME_REMOVED );
vfs_volume_free( volume );
}
static void
vfs_volume_device_added (LibHalContext *context,
const gchar *udi)
{
VFSVolume *volume;
LibHalVolume *hv;
LibHalDrive *hd;
const gchar *drive_udi;
/* check if we have a volume here */
hv = libhal_volume_from_udi (context, udi);
/* HAL might want us to ignore this volume for some reason */
if (G_UNLIKELY (hv != NULL && libhal_volume_should_ignore (hv)))
{
libhal_volume_free (hv);
return;
}
/* emit the "device-added" signal (to support thunar-volman) */
// g_signal_emit_by_name (G_OBJECT (manager_hal), "device-added", udi);
if (G_LIKELY (hv != NULL))
{
/* check if we have a mountable file system here */
if (libhal_volume_get_fsusage (hv) == LIBHAL_VOLUME_USAGE_MOUNTABLE_FILESYSTEM)
{
/* determine the UDI of the drive to which this volume belongs */
drive_udi = libhal_volume_get_storage_device_udi (hv);
if (G_LIKELY (drive_udi != NULL))
{
/* determine the drive for the volume */
hd = libhal_drive_from_udi (context, drive_udi);
if (G_LIKELY (hd != NULL))
{
/* check if we already have a volume object for the UDI */
volume = vfs_volume_get_volume_by_udi (udi);
if (G_LIKELY (volume == NULL))
{
/* otherwise, we allocate a new volume object */
volume = vfs_volume_new( udi );
}
/* update the volume object with the new data from the HAL volume/drive */
vfs_volume_update (volume, context, hv, hd);
/* add the volume object to our list if we allocated a new one */
if (g_list_find (volumes, volume) == NULL)
{
/* add the volume to the volume manager */
vfs_volume_add (volume);
}
/* release the HAL drive */
libhal_drive_free (hd);
}
}
}
/* release the HAL volume */
libhal_volume_free (hv);
}
else
{
/* but maybe we have a floppy disk drive here */
hd = libhal_drive_from_udi (context, udi);
if (G_UNLIKELY (hd == NULL))
return;
/* check if we have a floppy disk drive */
if (G_LIKELY (libhal_drive_get_type (hd) == LIBHAL_DRIVE_TYPE_FLOPPY))
{
/* check if we already have a volume object for the UDI */
volume = vfs_volume_get_volume_by_udi (udi);
if (G_LIKELY (volume == NULL))
{
/* otherwise, we allocate a new volume object */
volume = vfs_volume_new( udi );
}
/* update the volume object with the new data from the HAL volume/drive */
vfs_volume_update (volume, context, NULL, hd);
/* add the volume object to our list if we allocated a new one */
if (g_list_find (volumes, volume) == NULL)
{
/* add the volume to the volume manager */
vfs_volume_add (volume);
}
}
/* release the HAL drive */
libhal_drive_free (hd);
}
}
static void
vfs_volume_device_removed (LibHalContext *context,
const gchar *udi)
{
VFSVolume *volume;
/* emit the "device-removed" signal (to support thunar-volman) */
//g_signal_emit_by_name (G_OBJECT (manager_hal), "device-removed", udi);
/* check if we already have a volume object for the UDI */
volume = vfs_volume_get_volume_by_udi (udi);
if (G_LIKELY (volume != NULL))
{
/* remove the volume from the volume manager */
vfs_volume_remove (volume);
}
}
static void
vfs_volume_device_new_capability (LibHalContext *context,
const gchar *udi,
const gchar *capability)
{
/* update the volume for the device (if any) */
vfs_volume_update_volume_by_udi (udi);
}
static void
vfs_volume_device_lost_capability (LibHalContext *context,
const gchar *udi,
const gchar *capability)
{
/* update the volume for the device (if any) */
vfs_volume_update_volume_by_udi (udi);
}
static void
vfs_volume_device_property_modified (LibHalContext *context,
const gchar *udi,
const gchar *key,
dbus_bool_t is_removed,
dbus_bool_t is_added)
{
/* update the volume for the device (if any) */
vfs_volume_update_volume_by_udi (udi);
}
static void
vfs_volume_device_condition (LibHalContext *context,
const gchar *udi,
const gchar *name,
const gchar *details)
{
#if 0
VFSVolume *volume;
DBusError derror;
GList *eject_volumes = NULL;
GList *lp;
gchar **volume_udis;
gint n_volume_udis;
gint n;
#endif
// FIXME: What's this?
#if 0
/* check if the device should be ejected */
if (G_LIKELY (strcmp (name, "EjectPressed") == 0))
{
/* check if we have a volume for the device */
volume = vfs_volume_get_volume_by_udi (udi);
if (G_LIKELY (volume == NULL))
{
/* initialize D-Bus error */
dbus_error_init (&derror);
/* the UDI most probably identifies the drive of the volume */
volume_udis = libhal_manager_find_device_string_match (context, "info.parent", udi, &n_volume_udis, &derror);
if (G_LIKELY (volume_udis != NULL))
{
/* determine the volumes for the UDIs */
for (n = 0; n < n_volume_udis; ++n)
{
/* check if we have a mounted volume for this UDI */
volume = vfs_volume_get_volume_by_udi (volume_udis[n]);
if (vfs_volume_is_mounted (volume))
eject_volumes = g_list_prepend (volumes, volume));
}
libhal_free_string_array (volume_udis);
}
/* free D-Bus error */
dbus_error_free (&derror);
}
else if (vfs_volume_is_mounted (volume))
{
eject_volumes = g_list_prepend (volumes, volume));
}
/* check there are any mounted volumes on the device */
if (G_LIKELY (volumes != NULL))
{
/* tell everybody, that we're about to unmount those volumes */
for (lp = volumes; lp != NULL; lp = lp->next)
{
vfs_volume_is_pre_unmount (lp->data);
}
g_list_free (volumes);
/* emit the "device-eject" signal and let Thunar eject the device */
// g_signal_emit_by_name (G_OBJECT (manager_hal), "device-eject", udi);
call_callbacks( vol, VFS_VOLUME_EJECT );
}
}
#endif
}
gboolean vfs_volume_finalize()
{
if ( callbacks )
g_array_free( callbacks, TRUE );
if ( G_LIKELY( volumes ) )
{
g_list_foreach( volumes, (GFunc)vfs_volume_free, NULL );
g_list_free( volumes );
volumes = NULL;
}
/* shutdown the HAL context */
if (G_LIKELY (hal_context != NULL))
{
libhal_ctx_shutdown (hal_context, NULL);
libhal_ctx_free (hal_context);
}
/* shutdown the D-BUS connection */
if (G_LIKELY (dbus_connection != NULL))
dbus_connection_unref (dbus_connection);
return TRUE;
}
const GList* vfs_volume_get_all_volumes()
{
return volumes;
}
void vfs_volume_add_callback( VFSVolumeCallback cb, gpointer user_data )
{
VFSVolumeCallbackData e;
if ( !cb )
return;
if ( !callbacks )
callbacks = g_array_sized_new( FALSE, FALSE, sizeof( VFSVolumeCallbackData ), 8 );
e.cb = cb;
e.user_data = user_data;
callbacks = g_array_append_val( callbacks, e );
}
void vfs_volume_remove_callback( VFSVolumeCallback cb, gpointer user_data )
{
int i;
VFSVolumeCallbackData* e;
if ( !callbacks )
return ;
e = ( VFSVolumeCallbackData* ) callbacks->data;
for ( i = 0; i < callbacks->len; ++i )
{
if ( e[ i ].cb == cb && e[ i ].user_data == user_data )
{
callbacks = g_array_remove_index_fast( callbacks, i );
if ( callbacks->len > 8 )
g_array_set_size( callbacks, 8 );
break;
}
}
}
const char* vfs_volume_get_disp_name( VFSVolume *vol )
{
if( G_UNLIKELY( NULL == vol) )
return NULL;
return vol->disp_name;
}
const char* vfs_volume_get_mount_point( VFSVolume *vol )
{
if( G_UNLIKELY( NULL == vol) )
return NULL;
return vol->mount_point;
}
const char* vfs_volume_get_device( VFSVolume *vol )
{
if( G_UNLIKELY( NULL == vol) )
return NULL;
return vol->device_file;
}
const char* vfs_volume_get_fstype( VFSVolume *vol )
{
return NULL;
}
const char* vfs_volume_get_icon( VFSVolume *vol )
{
if( G_UNLIKELY( NULL == vol) )
return NULL;
return vol->icon;
}
gboolean vfs_volume_is_removable( VFSVolume *vol )
{
if( G_UNLIKELY( NULL == vol) )
return FALSE;
return vol->is_removable;
}
gboolean vfs_volume_is_mounted( VFSVolume *vol )
{
if( G_UNLIKELY( NULL == vol) )
return FALSE;
return vol->is_mounted;
}
gboolean vfs_volume_requires_eject( VFSVolume *vol )
{
if( G_UNLIKELY( NULL == vol) )
return FALSE;
return vol->requires_eject;
}
/* Following fstab code is taken from gnome-mount and modified */
static gboolean
fstab_open (gpointer *handle)
{
#ifdef __FreeBSD__
return setfsent () == 1;
#else
*handle = fopen ("/etc/fstab", "r");
return *handle != NULL;
#endif
}
static char *
fstab_next (gpointer handle, char **mount_point)
{
#ifdef __FreeBSD__
struct fstab *fstab;
fstab = getfsent ();
/* TODO: fill out mount_point */
if (mount_point != NULL && fstab != NULL) {
*mount_point = fstab->fs_file;
}
return fstab ? fstab->fs_spec : NULL;
#else
struct mntent *mnt;
mnt = getmntent (handle);
if (mount_point != NULL && mnt != NULL) {
*mount_point = mnt->mnt_dir;
}
return mnt ? mnt->mnt_fsname : NULL;
#endif
}
static void
fstab_close (gpointer handle)
{
#ifdef __FreeBSD__
endfsent ();
#else
fclose (handle);
#endif
}
/* borrowed from gtk/gtkfilesystemunix.c in GTK+ on 02/23/2006 */
static void
canonicalize_filename (gchar *filename)
{
gchar *p, *q;
gboolean last_was_slash = FALSE;
p = filename;
q = filename;
while (*p)
{
if (*p == G_DIR_SEPARATOR)
{
if (!last_was_slash)
*q++ = G_DIR_SEPARATOR;
last_was_slash = TRUE;
}
else
{
if (last_was_slash && *p == '.')
{
if (*(p + 1) == G_DIR_SEPARATOR ||
*(p + 1) == '\0')
{
if (*(p + 1) == '\0')
break;
p += 1;
}
else if (*(p + 1) == '.' &&
(*(p + 2) == G_DIR_SEPARATOR ||
*(p + 2) == '\0'))
{
if (q > filename + 1)
{
q--;
while (q > filename + 1 &&
*(q - 1) != G_DIR_SEPARATOR)
q--;
}
if (*(p + 2) == '\0')
break;
p += 2;
}
else
{
*q++ = *p;
last_was_slash = FALSE;
}
}
else
{
*q++ = *p;
last_was_slash = FALSE;
}
}
p++;
}
if (q > filename + 1 && *(q - 1) == G_DIR_SEPARATOR)
q--;
*q = '\0';
}
static char *
resolve_symlink (const char *file)
{
GError *error;
char *dir;
char *link;
char *f;
char *f1;
f = g_strdup (file);
while (g_file_test (f, G_FILE_TEST_IS_SYMLINK)) {
link = g_file_read_link (f, &error);
if (link == NULL) {
g_warning ("Cannot resolve symlink %s: %s", f, error->message);
g_error_free (error);
g_free (f);
f = NULL;
goto out;
}
dir = g_path_get_dirname (f);
f1 = g_strdup_printf ("%s/%s", dir, link);
g_free (dir);
g_free (link);
g_free (f);
f = f1;
}
out:
if (f != NULL)
canonicalize_filename (f);
return f;
}
static LibHalVolume *
volume_findby (LibHalContext *hal_ctx, const char *property, const char *value)
{
int i;
char **hal_udis;
int num_hal_udis;
LibHalVolume *result = NULL;
char *found_udi = NULL;
DBusError error;
dbus_error_init (&error);
if ((hal_udis = libhal_manager_find_device_string_match (hal_ctx, property,
value, &num_hal_udis, &error)) == NULL)
goto out;
for (i = 0; i < num_hal_udis; i++) {
char *udi;
udi = hal_udis[i];
if (libhal_device_query_capability (hal_ctx, udi, "volume", &error)) {
found_udi = strdup (udi);
break;
}
}
libhal_free_string_array (hal_udis);
if (found_udi != NULL)
result = libhal_volume_from_udi (hal_ctx, found_udi);
free (found_udi);
out:
return result;
}
static gboolean
is_in_fstab (const char *device_file, const char *label, const char *uuid, char **mount_point)
{
gboolean ret;
gpointer handle;
char *entry;
char *_mount_point;
ret = FALSE;
/* check if /etc/fstab mentions this device... (with symlinks etc) */
if (!fstab_open (&handle)) {
handle = NULL;
goto out;
}
while ((entry = fstab_next (handle, &_mount_point)) != NULL) {
char *resolved;
if (label != NULL && g_str_has_prefix (entry, "LABEL=")) {
if (strcmp (entry + 6, label) == 0) {
gboolean skip_fstab_entry;
skip_fstab_entry = FALSE;
/* OK, so what's if someone attaches an external disk with the label '/' and
* /etc/fstab has
*
* LABEL=/ / ext3 defaults 1 1
*
* in /etc/fstab as most Red Hat systems do? Bugger, this is a very common use
* case; suppose that you take the disk from your Fedora server and attaches it
* to your laptop. Bingo, you now have two disks with the label '/'. One must
* seriously wonder if using things like LABEL=/ for / is a good idea; just
* what happens if you boot in this configuration? (answer: the initrd gets
* it wrong most of the time.. sigh)
*
* To work around this, check if the listed entry in /etc/fstab is already mounted,
* if it is, then check if it's the same device_file as the given one...
*/
/* see if a volume is mounted at this mount point */
if (_mount_point != NULL) {
LibHalVolume *mounted_vol;
mounted_vol = volume_findby (hal_context, "volume.mount_point", _mount_point);
if (mounted_vol != NULL) {
const char *mounted_vol_device_file;
mounted_vol_device_file = libhal_volume_get_device_file (mounted_vol);
/* no need to resolve symlinks, hal uses the canonical device file */
/* g_debug ("device_file = '%s'", device_file); */
/* g_debug ("mounted_vol_device_file = '%s'", mounted_vol_device_file); */
if (mounted_vol_device_file != NULL &&
strcmp (mounted_vol_device_file, device_file) !=0) {
/* g_debug ("Wanting to mount %s that has label %s, but /etc/fstab says LABEL=%s is to be mounted at mount point '%s'. However %s (that also has label %s), is already mounted at said mount point. So, skipping said /etc/fstab entry.\n",
device_file, label, label, _mount_point, mounted_vol_device_file, _mount_point); */
skip_fstab_entry = TRUE;
}
libhal_volume_free (mounted_vol);
}
}
if (!skip_fstab_entry) {
ret = TRUE;
if (mount_point != NULL)
*mount_point = g_strdup (_mount_point);
goto out;
}
}
}
if (uuid != NULL && g_str_has_prefix (entry, "UUID=")) {
if (strcmp (entry + 5, uuid) == 0) {
ret = TRUE;
if (mount_point != NULL)
*mount_point = g_strdup (_mount_point);
goto out;
}
}
resolved = resolve_symlink (entry);
if (strcmp (device_file, resolved) == 0) {
ret = TRUE;
g_free (resolved);
if (mount_point != NULL)
*mount_point = g_strdup (_mount_point);
goto out;
}
g_free (resolved);
}
out:
if (handle != NULL)
fstab_close (handle);
return ret;
}
#ifdef __FreeBSD__
#define MOUNT "/sbin/mount"
#define UMOUNT "/sbin/umount"
#else
#define MOUNT "/bin/mount"
#define UMOUNT "/bin/umount"
#endif
/* Following mount/umount/eject-related source code is modified from exo-mount.c
* included in libexo originally written by Benedikt Meurer <benny@xfce.org>.
*/
struct _ExoMountHalDevice
{
gchar *udi;
LibHalDrive *drive;
LibHalVolume *volume;
/* device internals */
gchar *file;
gchar *name;
/* file system options */
gchar **fsoptions;
const gchar *fstype;
LibHalVolumeUsage fsusage;
};
typedef struct _ExoMountHalDevice ExoMountHalDevice;
typedef enum{
VA_MOUNT,
VA_UMOUNT,
VA_EJECT
}VolumnAction;
static gboolean translate_hal_error( GError** error, ExoMountHalDevice *device, const char* hal_err, VolumnAction action );
void
vfs_volume_hal_free (ExoMountHalDevice *device)
{
/* check if we have a device */
if (G_LIKELY (device != NULL))
{
libhal_free_string_array (device->fsoptions);
libhal_volume_free (device->volume);
libhal_drive_free (device->drive);
g_free (device->file);
g_free (device->name);
g_free (device->udi);
g_slice_free ( ExoMountHalDevice, device );
}
}
static void
exo_mount_hal_propagate_error (GError **error,
DBusError *derror)
{
g_return_if_fail (error == NULL || *error == NULL);
/* check if we need to propragate an error */
if (G_LIKELY (derror != NULL && dbus_error_is_set (derror)))
{
/* propagate the error */
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, "%s", derror->message);
/* reset the D-Bus error */
dbus_error_free (derror);
}
}
ExoMountHalDevice*
vfs_volume_hal_from_udi (const gchar *udi,
GError **error)
{
ExoMountHalDevice *device = NULL;
DBusError derror;
gchar **interfaces;
gchar **volume_udis;
gchar *volume_udi = NULL;
gint n_volume_udis;
gint n;
g_return_val_if_fail (udi != NULL, NULL);
g_return_val_if_fail (error == NULL || *error == NULL, NULL);
/* initialize D-Bus error */
dbus_error_init (&derror);
again:
/* determine the info.interfaces property of the device */
interfaces = libhal_device_get_property_strlist (hal_context, udi, "info.interfaces", &derror);
if (G_UNLIKELY (interfaces == NULL))
{
/* reset D-Bus error */
dbus_error_free (&derror);
/* release any previous volume UDI */
g_free (volume_udi);
volume_udi = NULL;
/* ok, but maybe we have a volume whose parent is identified by the udi */
volume_udis = libhal_manager_find_device_string_match (hal_context, "info.parent", udi, &n_volume_udis, &derror);
if (G_UNLIKELY (volume_udis == NULL))
{
err0: exo_mount_hal_propagate_error (error, &derror);
goto out;
}
else if (G_UNLIKELY (n_volume_udis < 1))
{
/* no match, we cannot handle that device */
libhal_free_string_array (volume_udis);
goto err1;
}
/* use the first volume UDI... */
volume_udi = g_strdup (volume_udis[0]);
libhal_free_string_array (volume_udis);
/* ..and try again using that UDI */
udi = (const gchar *) volume_udi;
goto again;
}
/* verify that we have a mountable device here */
for (n = 0; interfaces[n] != NULL; ++n)
if (strcmp (interfaces[n], "org.freedesktop.Hal.Device.Volume") == 0)
break;
if (G_UNLIKELY (interfaces[n] == NULL))
{
/* definitely not a device that we're able to mount, eject or unmount */
err1: g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("Given device \"%s\" is not a volume or drive"), udi);
goto out;
}
/* setup the device struct */
device = g_slice_new0 (ExoMountHalDevice);
device->udi = g_strdup (udi);
/* check if we have a volume here */
device->volume = libhal_volume_from_udi (hal_context, udi);
if (G_LIKELY (device->volume != NULL))
{
/* determine the storage drive for the volume */
device->drive = libhal_drive_from_udi (hal_context, libhal_volume_get_storage_device_udi (device->volume));
if (G_LIKELY (device->drive != NULL))
{
/* setup the device internals */
device->file = g_strdup (libhal_volume_get_device_file (device->volume));
device->name = _hal_volume_policy_get_display_name( device->drive, device->volume );
/* setup the file system internals */
device->fstype = libhal_volume_get_fstype (device->volume);
device->fsusage = libhal_volume_get_fsusage (device->volume);
}
}
else
{
/* check if we have a drive here (i.e. floppy) */
device->drive = libhal_drive_from_udi (hal_context, udi);
if (G_LIKELY (device->drive != NULL))
{
/* setup the device internals */
device->file = g_strdup (libhal_drive_get_device_file (device->drive));
device->name = _hal_drive_policy_get_display_name( device->drive, NULL );
/* setup the file system internals */
device->fstype = "";
device->fsusage = LIBHAL_VOLUME_USAGE_MOUNTABLE_FILESYSTEM;
}
}
/* determine the valid mount options from the UDI */
device->fsoptions = libhal_device_get_property_strlist (hal_context, udi, "volume.mount.valid_options", &derror);
/* sanity checking */
if (G_UNLIKELY (device->file == NULL || device->name == NULL))
{
vfs_volume_hal_free (device);
device = NULL;
goto err0;
}
/* check if we failed */
if (G_LIKELY (device->drive == NULL))
{
/* definitely not a device that we're able to mount, eject or unmount */
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("Given device \"%s\" is not a volume or drive"), udi);
vfs_volume_hal_free (device);
device = NULL;
}
out:
/* cleanup */
libhal_free_string_array (interfaces);
g_free (volume_udi);
return device;
}
ExoMountHalDevice*
vfs_volume_hal_from_file (const gchar *file,
GError **error)
{
ExoMountHalDevice *device = NULL;
DBusError derror;
gchar **interfaces;
gchar **udis;
gint n_udis;
gint n, m;
g_return_val_if_fail (g_path_is_absolute (file), NULL);
g_return_val_if_fail (error == NULL || *error == NULL, NULL);
/* initialize D-Bus error */
dbus_error_init (&derror);
/* query matching UDIs from HAL */
udis = libhal_manager_find_device_string_match (hal_context, "block.device", file, &n_udis, &derror);
if (G_UNLIKELY (udis == NULL))
{
/* propagate the error */
exo_mount_hal_propagate_error (error, &derror);
return NULL;
}
/* look for an UDI that specifies the Volume interface */
for (n = 0; n < n_udis; ++n)
{
/* check if we should ignore this device */
if (libhal_device_get_property_bool (hal_context, udis[n], "info.ignore", NULL))
continue;
/* determine the info.interfaces property of the device */
interfaces = libhal_device_get_property_strlist (hal_context, udis[n], "info.interfaces", NULL);
if (G_UNLIKELY (interfaces == NULL))
continue;
/* check if we have a mountable device here */
for (m = 0; interfaces[m] != NULL; ++m)
if (strcmp (interfaces[m], "org.freedesktop.Hal.Device.Volume") == 0)
break;
/* check if it's a usable device */
if (interfaces[m] != NULL)
{
libhal_free_string_array (interfaces);
break;
}
/* next one, please */
libhal_free_string_array (interfaces);
}
/* check if we have an UDI */
if (G_LIKELY (n < n_udis))
{
/* try to query the device from the HAL daemon */
device = vfs_volume_hal_from_udi (udis[n], error);
}
else
{
/* tell the caller that no matching device was found */
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_INVAL, _("Device \"%s\" not found in file system device table"), file);
}
/* cleanup */
libhal_free_string_array (udis);
return device;
}
gboolean
vfs_volume_hal_is_readonly (VFSVolume* volume)
{
LibHalDrive* drive;
g_return_val_if_fail (volume != NULL, FALSE);
/* the "volume.is_mounted_read_only" property might be a good start */
if (libhal_device_get_property_bool (hal_context, volume->udi, "volume.is_mounted_read_only", NULL))
return TRUE;
drive = libhal_drive_from_udi( hal_context, volume->udi );
if( drive )
{
/* otherwise guess based on the drive type */
switch (libhal_drive_get_type (drive))
{
/* CD-ROMs and floppies are read-only... */
case LIBHAL_DRIVE_TYPE_CDROM:
case LIBHAL_DRIVE_TYPE_FLOPPY:
return TRUE;
/* ...everything else is writable */
default:
return FALSE;
}
libhal_drive_free( drive );
}
return FALSE;
}
gboolean
vfs_volume_hal_eject (VFSVolume* volume,
GError **error)
{
const gchar **options = { NULL };
const guint n_options = 0;
DBusMessage *message;
DBusMessage *result;
DBusError derror;
const gchar *uuid = NULL, *label = NULL;
ExoMountHalDevice* device;
g_return_val_if_fail (volume != NULL, FALSE);
g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
device = vfs_volume_hal_from_file ( volume->device_file, error );
if( ! device )
return FALSE;
/* check if it's in /etc/fstab */
if( device->volume != NULL) {
label = libhal_volume_get_label (device->volume);
uuid = libhal_volume_get_uuid (device->volume);
}
if( device->file != NULL) {
char *mount_point = NULL;
if (is_in_fstab (device->file, label, uuid, &mount_point)) {
gboolean ret = FALSE;
GError *err = NULL;
char *sout = NULL;
char *serr = NULL;
int exit_status;
char *args[3] = {"eject", NULL, NULL};
char **envp = {NULL};
//g_print (_("Device %s is in /etc/fstab with mount point \"%s\"\n"),
// device_file, mount_point);
args[1] = mount_point;
if (!g_spawn_sync ("/",
args,
envp,
G_SPAWN_SEARCH_PATH,
NULL,
NULL,
&sout,
&serr,
&exit_status,
&err)) {
/* g_warning ("Cannot execute %s\n", "eject"); */
g_free (mount_point);
goto out;
}
if (exit_status != 0) {
/* g_warning ("%s said error %d, stdout='%s', stderr='%s'\n",
"eject", exit_status, sout, serr); */
if (strstr (serr, "is busy") != NULL) {
translate_hal_error( error, device, ERR_BUSY, VA_EJECT);
} else if (strstr (serr, "only root") != NULL|| strstr (serr, "unable to open") != NULL ) {
/* Let's try to do it as root */
if( vfs_volume_eject_by_udi_as_root( volume->udi ) )
ret = TRUE;
else
translate_hal_error( error, device, ERR_PERM_DENIED, VA_EJECT);
} else {
translate_hal_error( error, device, ERR_UNKNOWN_FAILURE, VA_EJECT);
}
goto out;
}
/* g_print (_("Ejected %s (using /etc/fstab).\n"), device->file); */
ret = TRUE;
out:
g_free (mount_point);
vfs_volume_hal_free( device );
return ret;
}
g_free (mount_point);
}
/* allocate the D-Bus message for the "Eject" method */
message = dbus_message_new_method_call ("org.freedesktop.Hal", volume->udi, "org.freedesktop.Hal.Device.Volume", "Eject");
if (G_UNLIKELY (message == NULL))
{
/* out of memory */
oom: g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_NOMEM, g_strerror (ENOMEM));
vfs_volume_hal_free( device );
return FALSE;
}
/* append the (empty) eject options array */
if (!dbus_message_append_args (message, DBUS_TYPE_ARRAY, DBUS_TYPE_STRING, &options, n_options, DBUS_TYPE_INVALID))
{
dbus_message_unref (message);
goto oom;
}
/* initialize D-Bus error */
dbus_error_init (&derror);
/* send the message to the HAL daemon and block for the reply */
result = dbus_connection_send_with_reply_and_block (dbus_connection, message, -1, &derror);
if (G_LIKELY (result != NULL))
{
/* check if an error was returned */
if (dbus_message_get_type (result) == DBUS_MESSAGE_TYPE_ERROR)
dbus_set_error_from_message (&derror, result);
/* release the result */
dbus_message_unref (result);
}
/* release the message */
dbus_message_unref (message);
/* check if we failed */
if (G_UNLIKELY (dbus_error_is_set (&derror)))
{
if( 0 == strcmp( derror.name, ERR_PERM_DENIED ) ) /* permission denied */
{
if( vfs_volume_eject_by_udi_as_root( volume->udi ) ) /* try to eject as root */
{
dbus_error_free (&derror);
vfs_volume_hal_free( device );
return TRUE;
}
}
/* try to translate the error appropriately */
if( ! translate_hal_error( error, device, derror.name, VA_EJECT ) )
{
/* no precise error message, use the HAL one */
exo_mount_hal_propagate_error (error, &derror);
}
/* release the DBus error */
dbus_error_free (&derror);
vfs_volume_hal_free( device );
return FALSE;
}
vfs_volume_hal_free( device );
return TRUE;
}
static const char* not_privileged[]={
N_("You are not privileged to mount the volume \"%s\""),
N_("You are not privileged to unmount the volume \"%s\""),
N_("You are not privileged to eject the volume \"%s\"")
};
gboolean translate_hal_error( GError** error, ExoMountHalDevice *device, const char* hal_err, VolumnAction action )
{
/* try to translate the error appropriately */
if (strcmp (hal_err, ERR_PERM_DENIED) == 0)
{
/* TRANSLATORS: User tried to mount a volume, but is not privileged to do so. */
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _(not_privileged[action]), device->name);
} else if (strcmp (hal_err, ERR_INVALID_MOUNT_OPT) == 0) {
/* TODO: slim down mount options to what is allowed, cf. volume.mount.valid_options */
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("Invalid mount option when attempting to mount the volume \"%s\""), device->name);
} else if (strcmp (hal_err, ERR_UNKNOWN_FS) == 0) {
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("The volume \"%s\" uses the <i>%s</i> file system which is not supported by your system"), device->name, device->fstype);
} else if( strcmp(hal_err, ERR_BUSY) == 0 ) {
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("An application is preventing the volume \"%s\" from being unmounted"), device->name);
} else if( strcmp( hal_err, ERR_NOT_MOUNTED ) == 0 ) {
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("The volume \"%s\" is not mounted"), device->name);
} else if( strcmp (hal_err, ERR_UNKNOWN_FAILURE ) == 0 ) {
g_set_error( error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("Error <i>%s</i>"), hal_err );
} else if(strcmp ( hal_err, ERR_NOT_MOUNTED_BY_HAL ) == 0 ) {
/* TRANSLATORS: HAL can only unmount volumes that were mounted via HAL. */
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("The volume \"%s\" was probably mounted manually on the command line"), device->name);
} else {
/* try to come up with a useful error message */
if( action == VA_MOUNT ) {
if (device->volume != NULL && libhal_volume_is_disc (device->volume) && libhal_volume_disc_is_blank (device->volume))
{
/* TRANSLATORS: User tried to mount blank disc, which is not going to work. */
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("Blank discs cannot be mounted, use a CD "
"recording application to "
"record audio or data on the disc"));
}
else if (device->volume != NULL
&& libhal_volume_is_disc (device->volume)
&& !libhal_volume_disc_has_data (device->volume)
&& libhal_volume_disc_has_audio (device->volume))
{
/* TRANSLATORS: User tried to mount an Audio CD that doesn't contain a data track. */
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("Audio CDs cannot be mounted, use "
"music players to play the audio tracks"));
}
else
return FALSE;
}
else
return FALSE;
}
return TRUE;
}
gboolean
vfs_volume_hal_mount (ExoMountHalDevice *device,
GError **error)
{
DBusMessage *message;
DBusMessage *result;
DBusError derror;
gchar *mount_point = NULL;
gchar **options = NULL;
gchar *fstype = NULL;
gchar *s;
const gchar *uuid = NULL, *label = NULL;
gint m, n = 0;
VFSVolumeOptions opts;
g_return_val_if_fail (device != NULL, FALSE);
g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
if( device->volume != NULL) {
label = libhal_volume_get_label (device->volume);
uuid = libhal_volume_get_uuid (device->volume);
// device_file = libhal_volume_get_device_file (volume);
} else if ( device->drive != NULL) {
// device_file = libhal_drive_get_device_file (drive);
}
if (is_in_fstab( device->file, label, uuid, &mount_point) ) {
GError *err = NULL;
char *sout = NULL;
char *serr = NULL;
int exit_status;
char *args[3] = {MOUNT, NULL, NULL};
char **envp = {NULL};
/* g_print (_("Device %s is in /etc/fstab with mount point \"%s\"\n"),
device->file, mount_point); */
args[1] = mount_point;
if (!g_spawn_sync ("/",
args,
envp,
0,
NULL,
NULL,
&sout,
&serr,
&exit_status,
&err)) {
g_warning ("Cannot execute %s\n", MOUNT);
g_free (mount_point);
mount_point = NULL;
return FALSE;
}
if (exit_status != 0) {
// char errstr[] = "mount: unknown filesystem type";
/*
g_warning ("%s said error %d, stdout='%s', stderr='%s'\n",
MOUNT, exit_status, sout, serr);
*/
if (strstr (serr, "unknown filesystem type") != NULL) {
translate_hal_error( error, device, ERR_UNKNOWN_FS, VA_MOUNT );
} else if (strstr (serr, "already mounted") != NULL) {
g_free( mount_point );
return TRUE;
} else if (strstr (serr, "only root") != NULL) {
/* Let's try to do it as root */
if( vfs_volume_mount_by_udi_as_root( device->udi ) )
{
g_free( mount_point );
return TRUE;
}
else
translate_hal_error( error, device, ERR_PERM_DENIED, VA_MOUNT );
} else if (strstr (serr, "bad option") != NULL) {
translate_hal_error( error, device, ERR_INVALID_MOUNT_OPT, VA_MOUNT);
} else {
translate_hal_error( error, device, ERR_UNKNOWN_FAILURE, VA_MOUNT);
}
g_free (mount_point);
return FALSE;
}
return TRUE;
}
/* determine the required mount options */
/* get mount options set by pcmanfm first */
if( vfs_volume_hal_get_options( device->fstype, &opts ) )
{
char** popts = opts.mount_options;
n = g_strv_length( popts );
if( n > 0)
{
int i;
/* We have to allocate a new larger array bacause we might need to
* append new options to the array later */
options = g_new0 (gchar *, n + 4);
for( i = 0; i < n; ++i )
{
options[i] = popts[i];
popts[i] = NULL;
/* steal the string */
}
/* the strings in the array are already stolen, so strfreev is not needed. */
}
g_free( opts.mount_options );
fstype = opts.fstype_override;
}
if( G_UNLIKELY( ! options ) )
{
options = g_new0 (gchar *, 20);
/* check if we know any valid mount options */
if (G_LIKELY (device->fsoptions != NULL))
{
/* process all valid mount options */
for (m = 0; device->fsoptions[m] != NULL; ++m)
{
/* this is currently mostly Linux specific noise */
if (
#ifndef __FreeBSD__
strcmp (device->fsoptions[m], "uid=") == 0
#else
strcmp (ret->mount_options[i], "-u=") == 0
#endif
&& (strcmp (device->fstype, "vfat") == 0
|| strcmp (device->fstype, "iso9660") == 0
|| strcmp (device->fstype, "udf") == 0
|| device->volume == NULL))
{
#ifndef __FreeBSD__
options[n++] = g_strdup_printf ("uid=%u", (guint) getuid ());
#else
options[n++] = g_strdup_printf ("-u=%u", (guint) getuid ());
#endif
}
else if (strcmp (device->fsoptions[m], "shortname=") == 0
&& strcmp (device->fstype, "vfat") == 0)
{
options[n++] = g_strdup_printf ("shortname=winnt");
}
else if (strcmp (device->fsoptions[m], "sync") == 0
&& device->volume == NULL)
{
/* non-pollable drive... */
options[n++] = g_strdup ("sync");
}
else if (strcmp (device->fsoptions[m], "longnames") == 0
&& strcmp (device->fstype, "vfat") == 0)
{
/* however this one is FreeBSD specific */
options[n++] = g_strdup ("longnames");
}
else if (strcmp (device->fsoptions[m], "locale=") == 0
&& strcmp (device->fstype, "ntfs-3g") == 0)
{
options[n++] = g_strdup_printf ("locale=%s", setlocale (LC_ALL, ""));
}
}
}
}
/* try to determine a usable mount point */
if (G_LIKELY (device->volume != NULL))
{
/* maybe we can use the volume's label... */
mount_point = g_strdup( libhal_volume_get_label (device->volume) );
}
else
{
/* maybe we can use the the textual type... */
mount_point = g_strdup( libhal_drive_get_type_textual (device->drive) );
}
/* However, the label may contain G_DIR_SEPARATOR so just replace these
* with underscores. Pretty typical use-case, suppose you hotplug a disk
* from a server, then you get e.g. two ext3 fs'es with labels '/' and
* '/home' - typically seen on Red Hat systems...
*/
/* make sure that the mount point is usable (i.e. does not contain G_DIR_SEPARATOR's) */
/*
mount_point = (mount_point != NULL && *mount_point != '\0')
? exo_str_replace (mount_point, G_DIR_SEPARATOR_S, "_")
: g_strdup ("");
*/
if( mount_point )
{
char* pmp = mount_point;
for ( ;*pmp; ++pmp) {
if (*pmp == G_DIR_SEPARATOR) {
*pmp = '_';
}
}
}
else
mount_point = g_strdup ("");
if( ! fstype )
{
/* let HAL guess the fstype */
fstype = g_strdup ("");
}
/* setup the D-Bus error */
dbus_error_init (&derror);
/* now several times... */
for (;;)
{
/* prepare the D-Bus message for the "Mount" method */
message = dbus_message_new_method_call ("org.freedesktop.Hal", device->udi, "org.freedesktop.Hal.Device.Volume", "Mount");
if (G_UNLIKELY (message == NULL))
{
oom: g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_NOMEM, g_strerror (ENOMEM));
g_strfreev (options);
g_free (mount_point);
g_free (fstype);
return FALSE;
}
/* append the message parameters */
if (!dbus_message_append_args (message,
DBUS_TYPE_STRING, &mount_point,
DBUS_TYPE_STRING, &fstype,
DBUS_TYPE_ARRAY, DBUS_TYPE_STRING, &options, n,
DBUS_TYPE_INVALID))
{
dbus_message_unref (message);
goto oom;
}
/* send the message to the HAL daemon */
result = dbus_connection_send_with_reply_and_block (dbus_connection, message, -1, &derror);
if (G_LIKELY (result != NULL))
{
/* check if an error was returned */
if (dbus_message_get_type (result) == DBUS_MESSAGE_TYPE_ERROR)
dbus_set_error_from_message (&derror, result);
/* release the result */
dbus_message_unref (result);
}
/* release the messages */
dbus_message_unref (message);
/* check if we succeed */
if (!dbus_error_is_set (&derror))
break;
/* check if the device was already mounted */
if (strcmp (derror.name, ERR_ALREADY_MOUNTED) == 0)
{
dbus_error_free (&derror);
break;
}
/* check if the specified mount point was invalid */
if (strcmp (derror.name, ERR_INVALID_MOUNT_POINT) == 0 && *mount_point != '\0')
{
/* try again without a mount point */
g_free (mount_point);
mount_point = g_strdup ("");
/* reset the error */
dbus_error_free (&derror);
continue;
}
/* check if the specified mount point is not available */
if (strcmp (derror.name, ERR_MOUNT_POINT_NOT_AVAILABLE) == 0 && *mount_point != '\0')
{
/* try again with a new mount point */
s = g_strconcat (mount_point, "_", NULL);
g_free (mount_point);
mount_point = s;
/* reset the error */
dbus_error_free (&derror);
continue;
}
#if defined(__FreeBSD__)
/* check if an unknown error occurred while trying to mount a floppy */
if (strcmp (derror.name, "org.freedesktop.Hal.Device.UnknownError") == 0
&& libhal_drive_get_type (device->drive) == LIBHAL_DRIVE_TYPE_FLOPPY)
{
/* check if no file system type was specified */
if (G_LIKELY (*fstype == '\0'))
{
/* try again with msdosfs */
g_free (fstype);
fstype = g_strdup ("msdosfs");
/* reset the error */
dbus_error_free (&derror);
continue;
}
}
#endif
/* it's also possible that we need to include "ro" in the options */
for (n = 0; options[n] != NULL; ++n)
if (strcmp (options[n], "ro") == 0)
break;
if (G_UNLIKELY (options[n] != NULL))
{
/* we already included "ro" in the options, no way
* to mount that device then... we simply give up.
*/
break;
}
/* add "ro" to the options and try again */
options[n++] = g_strdup ("ro");
/* reset the error */
dbus_error_free (&derror);
}
/* cleanup */
g_strfreev (options);
g_free (mount_point);
g_free (fstype);
/* check if we failed */
if (dbus_error_is_set (&derror))
{
if (strcmp (derror.name, ERR_ALREADY_MOUNTED) == 0)
{
/* Ups, already mounted, we succeed! */
dbus_error_free (&derror);
return TRUE;
}
if( 0 == strcmp( derror.name, ERR_PERM_DENIED ) ) /* permission denied */
{
if( vfs_volume_mount_by_udi_as_root( device->udi ) ) /* try to eject as root */
{
dbus_error_free (&derror);
return TRUE;
}
}
if( ! translate_hal_error( error, device, derror.name, VA_MOUNT ) )
{
/* unknown error, use HAL's message */
exo_mount_hal_propagate_error (error, &derror);
}
/* release D-Bus error */
dbus_error_free (&derror);
return FALSE;
}
return TRUE;
}
gboolean
vfs_volume_hal_unmount (VFSVolume* volume,
GError **error)
{
const gchar **options = { NULL };
const guint n_options = 0;
DBusMessage *message;
DBusMessage *result;
DBusError derror;
const char *label = NULL, *uuid=NULL;
ExoMountHalDevice* device = NULL;
g_return_val_if_fail (volume != NULL, FALSE);
g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
/* FIXME: volume->udi might be a udi to hal_drive, not hal_volume. */
/* check if it's in /etc/fstab */
device = vfs_volume_hal_from_file ( volume->device_file, NULL );
if( ! device )
return FALSE;
/* check if it's in /etc/fstab */
if( device->volume != NULL) {
label = libhal_volume_get_label (device->volume);
uuid = libhal_volume_get_uuid (device->volume);
}
if (device->file != NULL) {
char *mount_point = NULL;
if (is_in_fstab (device->file, label, uuid, &mount_point)) {
gboolean ret = FALSE;
GError *err = NULL;
char *sout = NULL;
char *serr = NULL;
int exit_status;
char *args[3] = {UMOUNT, NULL, NULL};
char **envp = {NULL};
/* g_print (_("Device %s is in /etc/fstab with mount point \"%s\"\n"),
device->file, mount_point); */
args[1] = mount_point;
if (!g_spawn_sync ("/",
args,
envp,
0,
NULL,
NULL,
&sout,
&serr,
&exit_status,
&err)) {
/* g_warning ("Cannot execute %s\n", UMOUNT); */
g_free (mount_point);
goto out;
}
if (exit_status != 0) {
/* g_warning ("%s said error %d, stdout='%s', stderr='%s'\n",
UMOUNT, exit_status, sout, serr); */
if (strstr (serr, "is busy") != NULL) {
translate_hal_error( error, device, ERR_BUSY, VA_UMOUNT);
} else if (strstr (serr, "not mounted") != NULL) {
translate_hal_error( error, device, ERR_NOT_MOUNTED, VA_UMOUNT);
} else if (strstr (serr, "only root") != NULL) {
/* Let's try to do it as root */
if( vfs_volume_umount_by_udi_as_root( volume->udi ) )
ret = TRUE;
else
translate_hal_error( error, device, ERR_PERM_DENIED, VA_UMOUNT);
} else {
translate_hal_error( error, device, ERR_UNKNOWN_FAILURE, VA_UMOUNT);
}
goto out;
}
/* g_print (_("Unmounted %s (using /etc/fstab)\n"), device_file); */
ret = TRUE;
out:
g_free (mount_point);
vfs_volume_hal_free( device );
return ret;
}
g_free (mount_point);
}
/* allocate the D-Bus message for the "Unmount" method */
message = dbus_message_new_method_call ("org.freedesktop.Hal", volume->udi, "org.freedesktop.Hal.Device.Volume", "Unmount");
if (G_UNLIKELY (message == NULL))
{
/* out of memory */
oom: g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_NOMEM, g_strerror (ENOMEM));
vfs_volume_hal_free( device );
return FALSE;
}
/* append the (empty) eject options array */
if (!dbus_message_append_args (message, DBUS_TYPE_ARRAY, DBUS_TYPE_STRING, &options, n_options, DBUS_TYPE_INVALID))
{
dbus_message_unref (message);
goto oom;
}
/* initialize D-Bus error */
dbus_error_init (&derror);
/* send the message to the HAL daemon and block for the reply */
result = dbus_connection_send_with_reply_and_block (dbus_connection, message, -1, &derror);
if (G_LIKELY (result != NULL))
{
/* check if an error was returned */
if (dbus_message_get_type (result) == DBUS_MESSAGE_TYPE_ERROR)
dbus_set_error_from_message (&derror, result);
/* release the result */
dbus_message_unref (result);
}
/* release the message */
dbus_message_unref (message);
/* check if we failed */
if (G_UNLIKELY (dbus_error_is_set (&derror)))
{
/* try to translate the error appropriately */
if (strcmp (derror.name, ERR_NOT_MOUNTED) == 0)
{
/* Ups, volume not mounted, we succeed! */
dbus_error_free (&derror);
vfs_volume_hal_free( device );
return TRUE;
}
if( 0 == strcmp( derror.name, ERR_PERM_DENIED ) ) /* permission denied */
{
if( vfs_volume_umount_by_udi_as_root( device->udi ) ) /* try to eject as root */
{
dbus_error_free (&derror);
vfs_volume_hal_free( device );
return TRUE;
}
}
if( ! translate_hal_error( error, device, derror.name, VA_UMOUNT ) )
{
/* unknown error, use the HAL one */
exo_mount_hal_propagate_error (error, &derror);
}
/* release the DBus error */
dbus_error_free (&derror);
vfs_volume_hal_free( device );
return FALSE;
}
vfs_volume_hal_free( device );
return TRUE;
}
gboolean vfs_volume_mount( VFSVolume* vol, GError** err )
{
ExoMountHalDevice* device;
gboolean ret = FALSE;
device = vfs_volume_hal_from_udi( vol->udi, err );
if( device )
{
ret = vfs_volume_hal_mount( device, err );
vfs_volume_hal_free( device );
}
return ret;
}
gboolean vfs_volume_umount( VFSVolume *vol, GError** err )
{
return vfs_volume_hal_unmount( vol, err );
}
gboolean vfs_volume_eject( VFSVolume *vol, GError** err )
{
return vfs_volume_hal_eject( vol, err );
}
gboolean vfs_volume_mount_by_udi( const char* udi, GError** err )
{
ExoMountHalDevice* device;
gboolean ret = FALSE;
device = vfs_volume_hal_from_udi( udi, err );
if( device )
{
ret = vfs_volume_hal_mount( device, err );
vfs_volume_hal_free( device );
}
return ret;
}
gboolean vfs_volume_umount_by_udi( const char* udi, GError** err )
{
VFSVolume* volume = vfs_volume_get_volume_by_udi( udi );
return volume ? vfs_volume_hal_unmount( volume, err ) : FALSE;
}
gboolean vfs_volume_eject_by_udi( const char* udi, GError** err )
{
VFSVolume* volume = vfs_volume_get_volume_by_udi( udi );
return volume ? vfs_volume_hal_eject( volume, err ) : FALSE;
}
/* helper functions to mount/umount/eject devices as root */
gboolean vfs_volume_mount_by_udi_as_root( const char* udi )
{
int ret;
char* argv[5]; //MOD
if ( G_UNLIKELY( geteuid() == 0 ) ) /* we are already root */
return FALSE;
//MOD separate arguments for ktsuss compatibility
//cmd = g_strdup_printf( "%s --mount '%s'", g_get_prgname(), udi );
argv[1] = g_get_prgname();
argv[2] = g_strdup_printf ( "--mount" );
argv[3] = g_strdup( udi );
argv[4] = NULL;
vfs_sudo_cmd_sync( NULL, argv, &ret, NULL,NULL, NULL ); //MOD
return (ret == 0);
}
gboolean vfs_volume_umount_by_udi_as_root( const char* udi )
{
int ret;
char* argv[5]; //MOD
if ( G_UNLIKELY( geteuid() == 0 ) ) /* we are already root */
return FALSE;
//MOD separate arguments for ktsuss compatibility
//cmd = g_strdup_printf( "%s --umount '%s'", g_get_prgname(), udi );
argv[1] = g_get_prgname();
argv[2] = g_strdup_printf ( "--umount" );
argv[3] = g_strdup( udi );
argv[4] = NULL;
vfs_sudo_cmd_sync( NULL, argv, &ret, NULL,NULL, NULL );
return (ret == 0);
}
gboolean vfs_volume_eject_by_udi_as_root( const char* udi )
{
int ret;
char* argv[5]; //MOD
if ( G_UNLIKELY( geteuid() == 0 ) ) /* we are already root */
return FALSE;
//MOD separate arguments for ktsuss compatibility
//cmd = g_strdup_printf( "%s --eject '%s'", g_get_prgname(), udi );
argv[1] = g_get_prgname();
argv[2] = g_strdup_printf ( "--eject" );
argv[3] = g_strdup( udi );
argv[4] = NULL;
vfs_sudo_cmd_sync( NULL, argv, &ret, NULL,NULL, NULL );
return (ret == 0);
}
#endif /* HAVE_HAL */
|
159 | ./spacefm/src/vfs/vfs-app-desktop.c | /*
* C Implementation: vfs-app-desktop
*
* Description:
*
*
* Author: Hong Jen Yee (PCMan) <pcman.tw (AT) gmail.com>, (C) 2006
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#include "vfs-app-desktop.h"
#include <glib/gi18n.h>
#include "glib-mem.h"
#include <string.h>
#include "vfs-execute.h"
#include "vfs-utils.h" /* for vfs_load_icon */
const char desktop_entry_name[] = "Desktop Entry";
/*
* If file_name is not a full path, this function searches default paths
* for the desktop file.
*/
VFSAppDesktop* vfs_app_desktop_new( const char* file_name )
{
GKeyFile* file;
gboolean load;
char* relative_path;
VFSAppDesktop* app = g_slice_new0( VFSAppDesktop );
app->n_ref = 1;
file = g_key_file_new();
if( !file_name )
{
g_key_file_free( file );
return app;
}
if( g_path_is_absolute( file_name ) )
{
app->file_name = g_path_get_basename( file_name );
load = g_key_file_load_from_file( file, file_name,
G_KEY_FILE_NONE, NULL );
}
else
{
app->file_name = g_strdup( file_name );
relative_path = g_build_filename( "applications",
app->file_name, NULL );
load = g_key_file_load_from_data_dirs( file, relative_path, NULL,
G_KEY_FILE_NONE, NULL );
g_free( relative_path );
}
if( load )
{
app->disp_name = g_key_file_get_locale_string ( file,
desktop_entry_name,
"Name", NULL, NULL);
app->comment = g_key_file_get_locale_string ( file, desktop_entry_name,
"Comment", NULL, NULL);
app->exec = g_key_file_get_string ( file, desktop_entry_name,
"Exec", NULL);
app->icon_name = g_key_file_get_string ( file, desktop_entry_name,
"Icon", NULL);
app->terminal = g_key_file_get_boolean( file, desktop_entry_name,
"Terminal", NULL );
app->hidden = g_key_file_get_boolean( file, desktop_entry_name,
"NoDisplay", NULL );
}
g_key_file_free( file );
return app;
}
static void vfs_app_desktop_free( VFSAppDesktop* app )
{
g_free( app->disp_name );
g_free( app->comment );
g_free( app->exec );
g_free( app->icon_name );
g_slice_free( VFSAppDesktop, app );
}
void vfs_app_desktop_ref( VFSAppDesktop* app )
{
g_atomic_int_inc( &app->n_ref );
}
void vfs_app_desktop_unref( gpointer data )
{
VFSAppDesktop* app = (VFSAppDesktop*)data;
if( g_atomic_int_dec_and_test(&app->n_ref) )
vfs_app_desktop_free( app );
}
gboolean vfs_app_desktop_rename( char* desktop_file_path, char* new_name ) //sfm
{
if ( !desktop_file_path || !new_name )
return FALSE;
GKeyFile* kfile = g_key_file_new();
// load
if ( !g_key_file_load_from_file( kfile, desktop_file_path,
G_KEY_FILE_KEEP_COMMENTS
| G_KEY_FILE_KEEP_TRANSLATIONS, NULL ) )
{
g_key_file_free( kfile );
return FALSE;
}
// get user's locale
const char* locale = NULL;
const char* const * langs = g_get_language_names();
char* dot = strchr( langs[0], '.' );
if( dot )
locale = g_strndup( langs[0], (size_t)(dot - langs[0]) );
else
locale = langs[0];
if ( !locale || locale[0] == '\0' )
locale = "en";
char* l = g_strdup( locale );
char* ll = strchr( l, '_' );
if ( ll )
ll[0] = '\0';
// update keyfile
g_key_file_set_locale_string( kfile, desktop_entry_name, "Name", l, new_name );
if ( strcmp( l, locale ) )
g_key_file_set_locale_string( kfile, desktop_entry_name, "Name", locale, new_name );
g_free( l );
// get keyfile as string
char* data = g_key_file_to_data( kfile, NULL, NULL );
g_key_file_free( kfile );
// overwrite desktop file
if ( data )
{
FILE* file = fopen( desktop_file_path, "w" );
if ( file )
{
int result = fputs( data, file );
g_free( data );
fclose( file );
if ( result < 0 )
return FALSE;
}
else
{
g_free( data );
return FALSE;
}
}
else
return FALSE;
return TRUE;
}
const char* vfs_app_desktop_get_name( VFSAppDesktop* app )
{
return app->file_name;
}
const char* vfs_app_desktop_get_disp_name( VFSAppDesktop* app )
{
if( G_LIKELY(app->disp_name) )
return app->disp_name;
return app->file_name;
}
const char* vfs_app_desktop_get_exec( VFSAppDesktop* app )
{
return app->exec;
}
const char* vfs_app_desktop_get_icon_name( VFSAppDesktop* app )
{
return app->icon_name;
}
static GdkPixbuf* load_icon_file( const char* file_name, int size )
{
GdkPixbuf* icon = NULL;
char* file_path;
const gchar** dirs = (const gchar**) g_get_system_data_dirs();
const gchar** dir;
for( dir = dirs; *dir; ++dir )
{
file_path = g_build_filename( *dir, "pixmaps", file_name, NULL );
icon = gdk_pixbuf_new_from_file_at_scale( file_path, size, size, TRUE, NULL );
g_free( file_path );
if( icon )
break;
}
return icon;
}
GdkPixbuf* vfs_app_desktop_get_icon( VFSAppDesktop* app, int size, gboolean use_fallback )
{
GtkIconTheme* theme;
char *icon_name = NULL, *suffix;
GdkPixbuf* icon = NULL;
if( app->icon_name )
{
if( g_path_is_absolute( app->icon_name) )
{
icon = gdk_pixbuf_new_from_file_at_scale( app->icon_name,
size, size, TRUE, NULL );
}
else
{
theme = gtk_icon_theme_get_default();
suffix = strchr( app->icon_name, '.' );
if( suffix ) /* has file extension, it's a basename of icon file */
{
/* try to find it in pixmaps dirs */
icon = load_icon_file( app->icon_name, size );
if( G_UNLIKELY( ! icon ) ) /* unfortunately, not found */
{
/* Let's remove the suffix, and see if this name can match an icon
in current icon theme */
icon_name = g_strndup( app->icon_name,
(suffix - app->icon_name) );
icon = vfs_load_icon( theme, icon_name, size );
g_free( icon_name );
}
}
else /* no file extension, it could be an icon name in the icon theme */
{
icon = vfs_load_icon( theme, app->icon_name, size );
}
}
}
if( G_UNLIKELY( ! icon ) && use_fallback ) /* fallback to generic icon */
{
theme = gtk_icon_theme_get_default();
icon = vfs_load_icon( theme, "application-x-executable", size );
if( G_UNLIKELY( ! icon ) ) /* fallback to generic icon */
{
icon = vfs_load_icon( theme, "gnome-mime-application-x-executable", size );
}
}
return icon;
}
gboolean vfs_app_desktop_open_multiple_files( VFSAppDesktop* app )
{
char* p;
if( app->exec )
{
for( p = app->exec; *p; ++p )
{
if( *p == '%' )
{
++p;
switch( *p )
{
case 'U':
case 'F':
case 'N':
case 'D':
return TRUE;
case '\0':
return FALSE;
}
}
return TRUE;
}
}
return FALSE;
}
gboolean vfs_app_desktop_open_in_terminal( VFSAppDesktop* app )
{
return app->terminal;
}
gboolean vfs_app_desktop_is_hidden( VFSAppDesktop* app )
{
return app->hidden;
}
/*
* Parse Exec command line of app desktop file, and translate
* it into a real command which can be passed to g_spawn_command_line_async().
* file_list is a null-terminated file list containing full
* paths of the files passed to app.
* returned char* should be freed when no longer needed.
*/
static char* translate_app_exec_to_command_line( VFSAppDesktop* app,
GList* file_list )
{
const char* pexec = vfs_app_desktop_get_exec( app );
char* file;
GList* l;
gchar *tmp;
GString* cmd = g_string_new("");
gboolean add_files = FALSE;
for( ; *pexec; ++pexec )
{
if( *pexec == '%' )
{
++pexec;
switch( *pexec )
{
case 'U':
for( l = file_list; l; l = l->next )
{
tmp = g_filename_to_uri( (char*)l->data, NULL, NULL );
file = g_shell_quote( tmp );
g_free( tmp );
g_string_append( cmd, file );
g_string_append_c( cmd, ' ' );
g_free( file );
}
add_files = TRUE;
break;
case 'u':
if( file_list && file_list->data )
{
file = (char*)file_list->data;
tmp = g_filename_to_uri( file, NULL, NULL );
file = g_shell_quote( tmp );
g_free( tmp );
g_string_append( cmd, file );
g_free( file );
add_files = TRUE;
}
break;
case 'F':
case 'N':
for( l = file_list; l; l = l->next )
{
file = (char*)l->data;
tmp = g_shell_quote( file );
g_string_append( cmd, tmp );
g_string_append_c( cmd, ' ' );
g_free( tmp );
}
add_files = TRUE;
break;
case 'f':
case 'n':
if( file_list && file_list->data )
{
file = (char*)file_list->data;
tmp = g_shell_quote( file );
g_string_append( cmd, tmp );
g_free( tmp );
add_files = TRUE;
}
break;
case 'D':
for( l = file_list; l; l = l->next )
{
tmp = g_path_get_dirname( (char*)l->data );
file = g_shell_quote( tmp );
g_free( tmp );
g_string_append( cmd, file );
g_string_append_c( cmd, ' ' );
g_free( file );
}
add_files = TRUE;
break;
case 'd':
if( file_list && file_list->data )
{
tmp = g_path_get_dirname( (char*)file_list->data );
file = g_shell_quote( tmp );
g_free( tmp );
g_string_append( cmd, file );
g_free( tmp );
add_files = TRUE;
}
break;
case 'c':
g_string_append( cmd, vfs_app_desktop_get_disp_name( app ) );
break;
case 'i':
/* Add icon name */
if( vfs_app_desktop_get_icon_name( app ) )
{
g_string_append( cmd, "--icon " );
g_string_append( cmd, vfs_app_desktop_get_icon_name( app ) );
}
break;
case 'k':
/* Location of the desktop file */
break;
case 'v':
/* Device name */
break;
case '%':
g_string_append_c ( cmd, '%' );
break;
case '\0':
goto _finish;
break;
}
}
else /* not % escaped part */
{
g_string_append_c ( cmd, *pexec );
}
}
_finish:
if( ! add_files )
{
g_string_append_c ( cmd, ' ' );
for( l = file_list; l; l = l->next )
{
file = (char*)l->data;
tmp = g_shell_quote( file );
g_string_append( cmd, tmp );
g_string_append_c( cmd, ' ' );
g_free( tmp );
}
}
return g_string_free( cmd, FALSE );
}
gboolean vfs_app_desktop_open_files( GdkScreen* screen,
const char* working_dir,
VFSAppDesktop* app,
GList* file_paths,
GError** err )
{
char* exec = NULL;
char* cmd;
GList* l;
gchar** argv = NULL;
gint argc = 0;
const char* sn_desc;
if( vfs_app_desktop_get_exec( app ) )
{
if ( ! strchr( vfs_app_desktop_get_exec( app ), '%' ) )
{ /* No filename parameters */
exec = g_strconcat( vfs_app_desktop_get_exec( app ), " %f", NULL );
}
else
{
exec = g_strdup( vfs_app_desktop_get_exec( app ) );
}
}
if ( exec )
{
if( !screen )
screen = gdk_screen_get_default();
sn_desc = vfs_app_desktop_get_disp_name( app );
if( !sn_desc )
sn_desc = exec;
if( vfs_app_desktop_open_multiple_files( app ) )
{
cmd = translate_app_exec_to_command_line( app, file_paths );
if ( cmd )
{
/* g_debug( "Execute %s\n", cmd ); */
if( g_shell_parse_argv( cmd, &argc, &argv, NULL ) )
{
vfs_exec_on_screen( screen, NULL, argv, NULL,
sn_desc, VFS_EXEC_DEFAULT_FLAGS, err );
g_strfreev( argv );
}
g_free( cmd );
}
else
{
for( l = file_paths; l; l = l->next )
{
cmd = translate_app_exec_to_command_line( app, l );
if ( cmd )
{
/* g_debug( "Execute %s\n", cmd ); */
if( g_shell_parse_argv( cmd, &argc, &argv, NULL ) )
{
vfs_exec_on_screen( screen, NULL,argv, NULL, sn_desc,
G_SPAWN_SEARCH_PATH|
G_SPAWN_STDOUT_TO_DEV_NULL|
G_SPAWN_STDERR_TO_DEV_NULL,
err );
g_strfreev( argv );
}
g_free( cmd );
}
}
}
g_free( exec );
}
return TRUE;
}
g_set_error( err, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED, _("Command not found") );
return FALSE;
}
|
160 | ./spacefm/src/vfs/vfs-dir.c | /*
* C Implementation: vfs-dir
*
* Description: Object used to present a directory
*
*
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE // euidaccess
#endif
#include "vfs-dir.h"
#include "vfs-thumbnail-loader.h"
#include "glib-mem.h"
#include <glib/gi18n.h>
#include <string.h>
#include <fcntl.h> /* for open() */
#include <unistd.h> /* for read */
#include "vfs-volume.h"
static void vfs_dir_class_init( VFSDirClass* klass );
static void vfs_dir_init( VFSDir* dir );
static void vfs_dir_finalize( GObject *obj );
static void vfs_dir_set_property ( GObject *obj,
guint prop_id,
const GValue *value,
GParamSpec *pspec );
static void vfs_dir_get_property ( GObject *obj,
guint prop_id,
GValue *value,
GParamSpec *pspec );
char* gethidden( const char* path ); //MOD added
gboolean ishidden( const char* hidden, const char* file_name ); //MOD added
/* constructor is private */
static VFSDir* vfs_dir_new( const char* path );
static void vfs_dir_load( VFSDir* dir );
static gpointer vfs_dir_load_thread( VFSAsyncTask* task, VFSDir* dir );
static void vfs_dir_monitor_callback( VFSFileMonitor* fm,
VFSFileMonitorEvent event,
const char* file_name,
gpointer user_data );
#if 0
static gpointer load_thumbnail_thread( gpointer user_data );
#endif
static void on_mime_type_reload( gpointer user_data );
static void update_changed_files( gpointer key, gpointer data,
gpointer user_data );
static gboolean notify_file_change( gpointer user_data );
static gboolean update_file_info( VFSDir* dir, VFSFileInfo* file );
#if 0
static gboolean is_dir_desktop( const char* path );
#endif
static void on_list_task_finished( VFSAsyncTask* task, gboolean is_cancelled, VFSDir* dir );
enum {
FILE_CREATED_SIGNAL = 0,
FILE_DELETED_SIGNAL,
FILE_CHANGED_SIGNAL,
THUMBNAIL_LOADED_SIGNAL,
FILE_LISTED_SIGNAL,
N_SIGNALS
};
static guint signals[ N_SIGNALS ] = { 0 };
static GObjectClass *parent_class = NULL;
static GHashTable* dir_hash = NULL;
static GList* mime_cb = NULL;
static guint change_notify_timeout = 0;
static guint theme_change_notify = 0;
static char* desktop_dir = NULL;
static char* home_trash_dir = NULL;
static size_t home_trash_dir_len = 0;
static gboolean is_desktop_set = FALSE;
GType vfs_dir_get_type()
{
static GType type = G_TYPE_INVALID;
if ( G_UNLIKELY ( type == G_TYPE_INVALID ) )
{
static const GTypeInfo info =
{
sizeof ( VFSDirClass ),
NULL,
NULL,
( GClassInitFunc ) vfs_dir_class_init,
NULL,
NULL,
sizeof ( VFSDir ),
0,
( GInstanceInitFunc ) vfs_dir_init,
NULL,
};
type = g_type_register_static ( G_TYPE_OBJECT, "VFSDir", &info, 0 );
}
return type;
}
void vfs_dir_class_init( VFSDirClass* klass )
{
GObjectClass * object_class;
object_class = ( GObjectClass * ) klass;
parent_class = g_type_class_peek_parent ( klass );
object_class->set_property = vfs_dir_set_property;
object_class->get_property = vfs_dir_get_property;
object_class->finalize = vfs_dir_finalize;
/* signals */
// klass->file_created = on_vfs_dir_file_created;
// klass->file_deleted = on_vfs_dir_file_deleted;
// klass->file_changed = on_vfs_dir_file_changed;
/*
* file-created is emitted when there is a new file created in the dir.
* The param is VFSFileInfo of the newly created file.
*/
signals[ FILE_CREATED_SIGNAL ] =
g_signal_new ( "file-created",
G_TYPE_FROM_CLASS ( klass ),
G_SIGNAL_RUN_FIRST,
G_STRUCT_OFFSET ( VFSDirClass, file_created ),
NULL, NULL,
g_cclosure_marshal_VOID__POINTER,
G_TYPE_NONE, 1, G_TYPE_POINTER );
/*
* file-deleted is emitted when there is a file deleted in the dir.
* The param is VFSFileInfo of the newly created file.
*/
signals[ FILE_DELETED_SIGNAL ] =
g_signal_new ( "file-deleted",
G_TYPE_FROM_CLASS ( klass ),
G_SIGNAL_RUN_FIRST,
G_STRUCT_OFFSET ( VFSDirClass, file_deleted ),
NULL, NULL,
g_cclosure_marshal_VOID__POINTER,
G_TYPE_NONE, 1, G_TYPE_POINTER );
/*
* file-changed is emitted when there is a file changed in the dir.
* The param is VFSFileInfo of the newly created file.
*/
signals[ FILE_CHANGED_SIGNAL ] =
g_signal_new ( "file-changed",
G_TYPE_FROM_CLASS ( klass ),
G_SIGNAL_RUN_FIRST,
G_STRUCT_OFFSET ( VFSDirClass, file_changed ),
NULL, NULL,
g_cclosure_marshal_VOID__POINTER,
G_TYPE_NONE, 1, G_TYPE_POINTER );
signals[ THUMBNAIL_LOADED_SIGNAL ] =
g_signal_new ( "thumbnail-loaded",
G_TYPE_FROM_CLASS ( klass ),
G_SIGNAL_RUN_FIRST,
G_STRUCT_OFFSET ( VFSDirClass, thumbnail_loaded ),
NULL, NULL,
g_cclosure_marshal_VOID__POINTER,
G_TYPE_NONE, 1, G_TYPE_POINTER );
signals[ FILE_LISTED_SIGNAL ] =
g_signal_new ( "file-listed",
G_TYPE_FROM_CLASS ( klass ),
G_SIGNAL_RUN_FIRST,
G_STRUCT_OFFSET ( VFSDirClass, file_listed ),
NULL, NULL,
g_cclosure_marshal_VOID__BOOLEAN,
G_TYPE_NONE, 1, G_TYPE_BOOLEAN );
/* FIXME: Is there better way to do this? */
if( G_UNLIKELY( ! is_desktop_set ) )
vfs_get_desktop_dir();
if( ! home_trash_dir )
vfs_get_trash_dir();
}
/* constructor */
void vfs_dir_init( VFSDir* dir )
{
dir->mutex = g_mutex_new();
}
/* destructor */
void vfs_dir_finalize( GObject *obj )
{
VFSDir * dir = VFS_DIR( obj );
//printf("vfs_dir_finalize %s\n", dir->path );
do{}
while( g_source_remove_by_user_data( dir ) );
if( G_UNLIKELY( dir->task ) )
{
g_signal_handlers_disconnect_by_func( dir->task, on_list_task_finished, dir );
/* FIXME: should we generate a "file-list" signal to indicate the dir loading was cancelled? */
//printf("spacefm: vfs_dir_finalize -> vfs_async_task_cancel\n");
vfs_async_task_cancel( dir->task );
g_object_unref( dir->task );
dir->task = NULL;
}
if ( dir->monitor )
{
vfs_file_monitor_remove( dir->monitor,
vfs_dir_monitor_callback,
dir );
}
if ( dir->path )
{
if( G_LIKELY( dir_hash ) )
{
g_hash_table_remove( dir_hash, dir->path );
/* There is no VFSDir instance */
if ( 0 == g_hash_table_size( dir_hash ) )
{
g_hash_table_destroy( dir_hash );
dir_hash = NULL;
vfs_mime_type_remove_reload_cb( mime_cb );
mime_cb = NULL;
if( change_notify_timeout )
{
g_source_remove( change_notify_timeout );
change_notify_timeout = 0;
}
g_signal_handler_disconnect( gtk_icon_theme_get_default(),
theme_change_notify );
theme_change_notify = 0;
}
}
g_free( dir->path );
g_free( dir->disp_path );
dir->path = dir->disp_path = NULL;
}
/* g_debug( "dir->thumbnail_loader: %p", dir->thumbnail_loader ); */
if( G_UNLIKELY( dir->thumbnail_loader ) )
{
/* g_debug( "FREE THUMBNAIL LOADER IN VFSDIR" ); */
vfs_thumbnail_loader_free( dir->thumbnail_loader );
dir->thumbnail_loader = NULL;
}
if ( dir->file_list )
{
g_list_foreach( dir->file_list, ( GFunc ) vfs_file_info_unref, NULL );
g_list_free( dir->file_list );
dir->file_list = NULL;
dir->n_files = 0;
}
if( dir->changed_files )
{
g_slist_foreach( dir->changed_files, (GFunc)vfs_file_info_unref, NULL );
g_slist_free( dir->changed_files );
dir->changed_files = NULL;
}
if( dir->created_files )
{
g_slist_foreach( dir->created_files, (GFunc)g_free, NULL );
g_slist_free( dir->created_files );
dir->created_files = NULL;
}
g_mutex_free( dir->mutex );
G_OBJECT_CLASS( parent_class ) ->finalize( obj );
}
void vfs_dir_get_property ( GObject *obj,
guint prop_id,
GValue *value,
GParamSpec *pspec )
{}
void vfs_dir_set_property ( GObject *obj,
guint prop_id,
const GValue *value,
GParamSpec *pspec )
{}
static GList* vfs_dir_find_file( VFSDir* dir, const char* file_name, VFSFileInfo* file )
{
GList * l;
VFSFileInfo* file2;
for ( l = dir->file_list; l; l = l->next )
{
file2 = ( VFSFileInfo* ) l->data;
if( G_UNLIKELY( file == file2 ) )
return l;
if ( file2->name && 0 == strcmp( file2->name, file_name ) )
{
return l;
}
}
return NULL;
}
/* signal handlers */
void vfs_dir_emit_file_created( VFSDir* dir, const char* file_name, gboolean force )
{
GList* l;
if ( !force && dir->avoid_changes )
return;
if ( G_UNLIKELY( 0 == strcmp(file_name, dir->path) ) )
{
// Special Case: The directory itself was created?
return;
}
dir->created_files = g_slist_append( dir->created_files, g_strdup( file_name ) );
if ( 0 == change_notify_timeout )
{
change_notify_timeout = g_timeout_add_full( G_PRIORITY_LOW,
200,
notify_file_change,
NULL, NULL );
}
}
void vfs_dir_emit_file_deleted( VFSDir* dir, const char* file_name, VFSFileInfo* file )
{
GList* l;
VFSFileInfo* file_found;
if( G_UNLIKELY( 0 == strcmp(file_name, dir->path) ) )
{
/* Special Case: The directory itself was deleted... */
file = NULL;
/* clear the whole list */
g_mutex_lock( dir->mutex );
g_list_foreach( dir->file_list, (GFunc)vfs_file_info_unref, NULL );
g_list_free( dir->file_list );
dir->file_list = NULL;
g_mutex_unlock( dir->mutex );
g_signal_emit( dir, signals[ FILE_DELETED_SIGNAL ], 0, file );
return;
}
l = vfs_dir_find_file( dir, file_name, file );
if ( G_LIKELY( l ) )
{
file_found = vfs_file_info_ref( ( VFSFileInfo* ) l->data );
if( !g_slist_find( dir->changed_files, file_found ) )
{
dir->changed_files = g_slist_prepend( dir->changed_files, file_found );
if ( 0 == change_notify_timeout )
{
change_notify_timeout = g_timeout_add_full( G_PRIORITY_LOW,
200,
notify_file_change,
NULL, NULL );
}
}
else
vfs_file_info_unref( file_found );
}
}
void vfs_dir_emit_file_changed( VFSDir* dir, const char* file_name,
VFSFileInfo* file, gboolean force )
{
GList* l;
//printf("vfs_dir_emit_file_changed dir=%s file_name=%s avoid=%s\n", dir->path, file_name, dir->avoid_changes ? "TRUE" : "FALSE" );
if ( !force && dir->avoid_changes )
return;
/* Test not needed because file won't be found in list?
if ( G_UNLIKELY( 0 == strcmp(file_name, dir->path) ) )
{
// Special Case: The directory itself was changed
return;
}
*/
g_mutex_lock( dir->mutex );
l = vfs_dir_find_file( dir, file_name, file );
if ( G_LIKELY( l ) )
{
file = vfs_file_info_ref( ( VFSFileInfo* ) l->data );
if( !g_slist_find( dir->changed_files, file ) )
{
if ( force )
{
dir->changed_files = g_slist_prepend( dir->changed_files, file );
if ( 0 == change_notify_timeout )
{
change_notify_timeout = g_timeout_add_full( G_PRIORITY_LOW,
100,
notify_file_change,
NULL, NULL );
}
}
else if( G_LIKELY( update_file_info( dir, file ) ) ) // update file info the first time
{
dir->changed_files = g_slist_prepend( dir->changed_files, file );
if ( 0 == change_notify_timeout )
{
change_notify_timeout = g_timeout_add_full( G_PRIORITY_LOW,
500,
notify_file_change,
NULL, NULL );
}
g_signal_emit( dir, signals[ FILE_CHANGED_SIGNAL ], 0, file );
}
}
else
vfs_file_info_unref( file );
}
g_mutex_unlock( dir->mutex );
}
void vfs_dir_emit_thumbnail_loaded( VFSDir* dir, VFSFileInfo* file )
{
GList* l;
g_mutex_lock( dir->mutex );
l = vfs_dir_find_file( dir, file->name, file );
if( l )
{
g_assert( file == (VFSFileInfo*)l->data );
file = vfs_file_info_ref( (VFSFileInfo*)l->data );
}
else
file = NULL;
g_mutex_unlock( dir->mutex );
if ( G_LIKELY( file ) )
{
g_signal_emit( dir, signals[ THUMBNAIL_LOADED_SIGNAL ], 0, file );
vfs_file_info_unref( file );
}
}
/* methods */
VFSDir* vfs_dir_new( const char* path )
{
VFSDir * dir;
dir = ( VFSDir* ) g_object_new( VFS_TYPE_DIR, NULL );
dir->path = g_strdup( path );
#ifdef HAVE_HAL
dir->avoid_changes = FALSE;
#else
dir->avoid_changes = vfs_volume_dir_avoid_changes( path );
#endif
//printf("vfs_dir_new %s avoid_changes=%s\n", dir->path, dir->avoid_changes ? "TRUE" : "FALSE" );
return dir;
}
void on_list_task_finished( VFSAsyncTask* task, gboolean is_cancelled, VFSDir* dir )
{
g_object_unref( dir->task );
dir->task = NULL;
g_signal_emit( dir, signals[FILE_LISTED_SIGNAL], 0, is_cancelled );
dir->file_listed = 1;
dir->load_complete = 1;
}
static gboolean is_dir_trash( const char* path )
{
/* FIXME: Temporarily disable trash support since it's not finished */
#if 0
/* FIXME: Only support home trash now */
if( strncmp( path, home_trash_dir, home_trash_dir_len ) == 0 )
{
if( strcmp( path + home_trash_dir_len, "/files" ) == 0 )
{
return TRUE;
}
}
#endif
return FALSE;
}
static gboolean is_dir_mount_point( const char* path )
{
return FALSE; /* FIXME: not implemented */
}
static gboolean is_dir_remote( const char* path )
{
return FALSE; /* FIXME: not implemented */
}
static gboolean is_dir_virtual( const char* path )
{
return FALSE; /* FIXME: not implemented */
}
char* gethidden( const char* path ) //MOD added
{
// Read .hidden into string
char* hidden_path = g_build_filename( path, ".hidden", NULL );
// test access first because open() on missing file may cause
// long delay on nfs
int acc;
#if defined(HAVE_EUIDACCESS)
acc = euidaccess( hidden_path, R_OK );
#elif defined(HAVE_EACCESS)
acc = eaccess( hidden_path, R_OK );
#else
acc = 0;
#endif
if ( acc != 0 )
{
g_free( hidden_path );
return NULL;
}
int fd = open( hidden_path, O_RDONLY );
g_free( hidden_path );
if ( fd != -1 )
{
struct stat s; // skip stat64
if ( G_LIKELY( fstat( fd, &s ) != -1 ) )
{
char* buf = g_malloc( s.st_size + 1 );
if( (s.st_size = read( fd, buf, s.st_size )) != -1 )
{
buf[ s.st_size ] = 0;
close( fd );
return buf;
}
else
g_free( buf );
}
close( fd );
}
return NULL;
}
gboolean ishidden( const char* hidden, const char* file_name ) //MOD added
{ // assumes hidden,file_name != NULL
char* str;
char c;
str = strstr( hidden, file_name );
while ( str )
{
if ( str == hidden )
{
// file_name is at start of buffer
c = hidden[ strlen( file_name ) ];
if ( c == '\n' || c == '\0' )
return TRUE;
}
else
{
c = str[ strlen( file_name ) ];
if ( str[-1] == '\n' && ( c == '\n' || c == '\0' ) )
return TRUE;
}
str = strstr( ++str, file_name );
}
return FALSE;
}
gboolean vfs_dir_add_hidden( const char* path, const char* file_name )
{
gboolean ret = TRUE;
char* hidden = gethidden( path );
if ( !( hidden && ishidden( hidden, file_name ) ) )
{
char* buf = g_strdup_printf( "%s\n", file_name );
char* file_path = g_build_filename( path, ".hidden", NULL );
int fd = open( file_path, O_WRONLY | O_CREAT | O_APPEND, 0644 );
g_free( file_path );
if ( fd != -1 )
{
if ( write( fd, buf, strlen( buf ) ) == -1 )
ret = FALSE;
close( fd );
}
else
ret = FALSE;
g_free( buf );
}
if ( hidden )
g_free( hidden );
return ret;
}
void vfs_dir_load( VFSDir* dir )
{
if ( G_LIKELY(dir->path) )
{
dir->disp_path = g_filename_display_name( dir->path );
dir->flags = 0;
/* FIXME: We should check access here! */
if( G_UNLIKELY( strcmp( dir->path, vfs_get_desktop_dir() ) == 0 ) )
dir->is_desktop = TRUE;
else if( G_UNLIKELY( strcmp( dir->path, g_get_home_dir() ) == 0 ) )
dir->is_home = TRUE;
if( G_UNLIKELY(is_dir_trash(dir->path)) )
{
// g_free( dir->disp_path );
// dir->disp_path = g_strdup( _("Trash") );
dir->is_trash = TRUE;
}
if( G_UNLIKELY( is_dir_mount_point(dir->path)) )
dir->is_mount_point = TRUE;
if( G_UNLIKELY( is_dir_remote(dir->path)) )
dir->is_remote = TRUE;
if( G_UNLIKELY( is_dir_virtual(dir->path)) )
dir->is_virtual = TRUE;
dir->task = vfs_async_task_new( (VFSAsyncFunc)vfs_dir_load_thread, dir );
g_signal_connect( dir->task, "finish", G_CALLBACK(on_list_task_finished), dir );
vfs_async_task_execute( dir->task );
}
}
#if 0
gboolean is_dir_desktop( const char* path )
{
return (desktop_dir && 0 == strcmp(path, desktop_dir));
}
#endif
gpointer vfs_dir_load_thread( VFSAsyncTask* task, VFSDir* dir )
{
const gchar * file_name;
char* full_path;
GDir* dir_content;
VFSFileInfo* file;
char* hidden = NULL; //MOD added
dir->file_listed = 0;
dir->load_complete = 0;
dir->xhidden_count = 0; //MOD
if ( dir->path )
{
/* Install file alteration monitor */
dir->monitor = vfs_file_monitor_add_dir( dir->path,
vfs_dir_monitor_callback,
dir );
dir_content = g_dir_open( dir->path, 0, NULL );
if ( dir_content )
{
GKeyFile* kf;
if( G_UNLIKELY(dir->is_trash) )
kf = g_key_file_new();
// MOD dir contains .hidden file?
hidden = gethidden( dir->path );
while ( ! vfs_async_task_is_cancelled( dir->task )
&& ( file_name = g_dir_read_name( dir_content ) ) )
{
full_path = g_build_filename( dir->path, file_name, NULL );
if ( !full_path )
continue;
//MOD ignore if in .hidden
if ( hidden && ishidden( hidden, file_name ) )
{
dir->xhidden_count++;
continue;
}
/* FIXME: Is locking GDK needed here? */
/* GDK_THREADS_ENTER(); */
file = vfs_file_info_new();
if ( G_LIKELY( vfs_file_info_get( file, full_path, file_name ) ) )
{
g_mutex_lock( dir->mutex );
/* Special processing for desktop folder */
vfs_file_info_load_special_info( file, full_path );
/* FIXME: load info, too when new file is added to trash dir */
if( G_UNLIKELY( dir->is_trash ) ) /* load info of trashed files */
{
gboolean info_loaded;
char* info = g_strconcat( home_trash_dir, "/info/", file_name, ".trashinfo", NULL );
info_loaded = g_key_file_load_from_file( kf, info, 0, NULL );
g_free( info );
if( info_loaded )
{
char* ori_path = g_key_file_get_string( kf, "Trash Info", "Path", NULL );
if( ori_path )
{
/* Thanks to the stupid freedesktop.org spec, the filename is encoded
* like a URL, which is insane. This add nothing more than overhead. */
char* fake_uri = g_strconcat( "file://", ori_path, NULL );
g_free( ori_path );
ori_path = g_filename_from_uri( fake_uri, NULL, NULL );
/* g_debug( ori_path ); */
if( file->disp_name && file->disp_name != file->name )
g_free( file->disp_name );
file->disp_name = g_filename_display_basename( ori_path );
g_free( ori_path );
}
}
}
dir->file_list = g_list_prepend( dir->file_list, file );
g_mutex_unlock( dir->mutex );
++dir->n_files;
}
else
{
vfs_file_info_unref( file );
}
/* GDK_THREADS_LEAVE(); */
g_free( full_path );
}
g_dir_close( dir_content );
if ( hidden )
g_free( hidden );
if( G_UNLIKELY(dir->is_trash) )
g_key_file_free( kf );
}
}
return NULL;
}
gboolean vfs_dir_is_loading( VFSDir* dir )
{
return dir->task ? TRUE : FALSE;
}
gboolean vfs_dir_is_file_listed( VFSDir* dir )
{
return dir->file_listed;
}
void vfs_cancel_load( VFSDir* dir )
{
dir->cancel = TRUE;
if ( dir->task )
{
printf("spacefm: vfs_cancel_load -> vfs_async_task_cancel\n");
vfs_async_task_cancel( dir->task );
/* don't do g_object_unref on task here since this is done in the handler of "finish" signal. */
dir->task = NULL;
}
}
gboolean update_file_info( VFSDir* dir, VFSFileInfo* file )
{
char* full_path;
char* file_name;
gboolean ret = FALSE;
/* gboolean is_desktop = is_dir_desktop(dir->path); */
/* FIXME: Dirty hack: steal the string to prevent memory allocation */
file_name = file->name;
if( file->name == file->disp_name )
file->disp_name = NULL;
file->name = NULL;
full_path = g_build_filename( dir->path, file_name, NULL );
if ( G_LIKELY( full_path ) )
{
if( G_LIKELY( vfs_file_info_get( file, full_path, file_name ) ) )
{
ret = TRUE;
/* if( G_UNLIKELY(is_desktop) ) */
vfs_file_info_load_special_info( file, full_path );
}
else /* The file doesn't exist */
{
GList* l;
l = g_list_find( dir->file_list, file );
if( G_UNLIKELY(l) )
{
dir->file_list = g_list_delete_link( dir->file_list, l );
--dir->n_files;
if ( file )
{
g_signal_emit( dir, signals[ FILE_DELETED_SIGNAL ], 0, file );
vfs_file_info_unref( file );
}
}
ret = FALSE;
}
g_free( full_path );
}
g_free( file_name );
return ret;
}
void update_changed_files( gpointer key, gpointer data, gpointer user_data )
{
VFSDir* dir = (VFSDir*)data;
GSList* l;
VFSFileInfo* file;
if ( dir->changed_files )
{
g_mutex_lock( dir->mutex );
for ( l = dir->changed_files; l; l = l->next )
{
file = vfs_file_info_ref( ( VFSFileInfo* ) l->data ); ///
if ( update_file_info( dir, file ) )
{
g_signal_emit( dir, signals[ FILE_CHANGED_SIGNAL ], 0, file );
vfs_file_info_unref( file );
}
// else was deleted, signaled, and unrefed in update_file_info
}
g_slist_free( dir->changed_files );
dir->changed_files = NULL;
g_mutex_unlock( dir->mutex );
}
}
void update_created_files( gpointer key, gpointer data, gpointer user_data )
{
VFSDir* dir = (VFSDir*)data;
GSList* l;
char* full_path;
VFSFileInfo* file;
GList* ll;
if ( dir->created_files )
{
g_mutex_lock( dir->mutex );
for ( l = dir->created_files; l; l = l->next )
{
if ( !( ll = vfs_dir_find_file( dir, (char*)l->data, NULL ) ) )
{
// file is not in dir file_list
full_path = g_build_filename( dir->path, (char*)l->data, NULL );
file = vfs_file_info_new();
if ( vfs_file_info_get( file, full_path, NULL ) )
{
// add new file to dir file_list
vfs_file_info_load_special_info( file, full_path );
dir->file_list = g_list_prepend( dir->file_list,
vfs_file_info_ref( file ) );
++dir->n_files;
g_signal_emit( dir, signals[ FILE_CREATED_SIGNAL ], 0, file );
}
// else file doesn't exist in filesystem
vfs_file_info_unref( file );
g_free( full_path );
}
else
{
// file already exists in dir file_list
file = vfs_file_info_ref( (VFSFileInfo*)ll->data );
if ( update_file_info( dir, file ) )
{
g_signal_emit( dir, signals[ FILE_CHANGED_SIGNAL ], 0, file );
vfs_file_info_unref( file );
}
// else was deleted, signaled, and unrefed in update_file_info
}
g_free( (char*)l->data ); // free file_name string
}
g_slist_free( dir->created_files );
dir->created_files = NULL;
g_mutex_unlock( dir->mutex );
}
}
gboolean notify_file_change( gpointer user_data )
{
//GDK_THREADS_ENTER(); //sfm not needed because in main thread?
g_hash_table_foreach( dir_hash, update_changed_files, NULL );
g_hash_table_foreach( dir_hash, update_created_files, NULL );
/* remove the timeout */
change_notify_timeout = 0;
//GDK_THREADS_LEAVE();
return FALSE;
}
void vfs_dir_flush_notify_cache()
{
if ( change_notify_timeout )
g_source_remove( change_notify_timeout );
change_notify_timeout = 0;
g_hash_table_foreach( dir_hash, update_changed_files, NULL );
g_hash_table_foreach( dir_hash, update_created_files, NULL );
}
/* Callback function which will be called when monitored events happen */
void vfs_dir_monitor_callback( VFSFileMonitor* fm,
VFSFileMonitorEvent event,
const char* file_name,
gpointer user_data )
{
VFSDir* dir = ( VFSDir* ) user_data;
GDK_THREADS_ENTER();
switch ( event )
{
case VFS_FILE_MONITOR_CREATE:
vfs_dir_emit_file_created( dir, file_name, FALSE );
break;
case VFS_FILE_MONITOR_DELETE:
vfs_dir_emit_file_deleted( dir, file_name, NULL );
break;
case VFS_FILE_MONITOR_CHANGE:
vfs_dir_emit_file_changed( dir, file_name, NULL, FALSE );
break;
default:
g_warning("Error: unrecognized file monitor signal!");
}
GDK_THREADS_LEAVE();
}
/* called on every VFSDir when icon theme got changed */
static void reload_icons( const char* path, VFSDir* dir, gpointer user_data )
{
GList* l;
for( l = dir->file_list; l; l = l->next )
{
VFSFileInfo* fi = (VFSFileInfo*)l->data;
/* It's a desktop entry file */
if( fi->flags & VFS_FILE_INFO_DESKTOP_ENTRY )
{
char* file_path = g_build_filename( path, fi->name,NULL );
if( fi->big_thumbnail )
{
g_object_unref( fi->big_thumbnail );
fi->big_thumbnail = NULL;
}
if( fi->small_thumbnail )
{
g_object_unref( fi->small_thumbnail );
fi->small_thumbnail = NULL;
}
vfs_file_info_load_special_info( fi, file_path );
g_free( file_path );
}
}
}
static void on_theme_changed( GtkIconTheme *icon_theme, gpointer user_data )
{
g_hash_table_foreach( dir_hash, (GHFunc)reload_icons, NULL );
}
VFSDir* vfs_dir_get_by_path_soft( const char* path )
{
if ( G_UNLIKELY( !dir_hash || !path ) )
return NULL;
VFSDir * dir = g_hash_table_lookup( dir_hash, path );
if ( dir )
g_object_ref( dir );
return dir;
}
VFSDir* vfs_dir_get_by_path( const char* path )
{
VFSDir * dir = NULL;
g_return_val_if_fail( G_UNLIKELY(path), NULL );
if ( G_UNLIKELY( ! dir_hash ) )
{
dir_hash = g_hash_table_new_full( g_str_hash, g_str_equal, NULL, NULL );
if( 0 == theme_change_notify )
theme_change_notify = g_signal_connect( gtk_icon_theme_get_default(), "changed",
G_CALLBACK( on_theme_changed ), NULL );
}
else
{
dir = g_hash_table_lookup( dir_hash, path );
}
if( G_UNLIKELY( !mime_cb ) )
mime_cb = vfs_mime_type_add_reload_cb( on_mime_type_reload, NULL );
if ( dir )
{
g_object_ref( dir );
}
else
{
dir = vfs_dir_new( path );
vfs_dir_load( dir ); /* asynchronous operation */
g_hash_table_insert( dir_hash, (gpointer)dir->path, (gpointer)dir );
}
return dir;
}
static void reload_mime_type( char* key, VFSDir* dir, gpointer user_data )
{
GList* l;
VFSFileInfo* file;
char* full_path;
if( G_UNLIKELY( ! dir || ! dir->file_list ) )
return;
g_mutex_lock( dir->mutex );
for( l = dir->file_list; l; l = l->next )
{
file = (VFSFileInfo*)l->data;
full_path = g_build_filename( dir->path,
vfs_file_info_get_name( file ), NULL );
vfs_file_info_reload_mime_type( file, full_path );
/* g_debug( "reload %s", full_path ); */
g_free( full_path );
}
for( l = dir->file_list; l; l = l->next )
{
file = (VFSFileInfo*)l->data;
g_signal_emit( dir, signals[FILE_CHANGED_SIGNAL], 0, file );
}
g_mutex_unlock( dir->mutex );
}
static void on_mime_type_reload( gpointer user_data )
{
if( ! dir_hash )
return;
/* g_debug( "reload mime-type" ); */
g_hash_table_foreach( dir_hash, (GHFunc)reload_mime_type, NULL );
}
/* Thanks to the freedesktop.org, things are much more complicated now... */
const char* vfs_get_desktop_dir()
{
char* def;
if( G_LIKELY(is_desktop_set) )
return desktop_dir;
/* glib provides API for this since ver. 2.14, but I think my implementation is better. */
#if GLIB_CHECK_VERSION( 2, 14, 0 ) && 0 /* Delete && 0 to use the one provided by glib */
desktop_dir = g_get_user_special_dir( G_USER_DIRECTORY_DESKTOP );
#else
def = g_build_filename( g_get_user_config_dir(), "user-dirs.dirs", NULL );
if( def )
{
int fd = open( def, O_RDONLY );
g_free( def );
if( G_LIKELY( fd != -1 ) )
{
struct stat s; // skip stat64
if( G_LIKELY( fstat( fd, &s ) != -1 ) )
{
char* buf = g_malloc( s.st_size + 1 );
if( (s.st_size = read( fd, buf, s.st_size )) != -1 )
{
char* line;
buf[ s.st_size ] = 0;
line = strstr( buf, "XDG_DESKTOP_DIR=" );
if( G_LIKELY( line ) )
{
char* eol;
line += 16;
if( G_LIKELY( ( eol = strchr( line, '\n' ) ) ) )
*eol = '\0';
line = g_shell_unquote( line, NULL );
if( g_str_has_prefix(line, "$HOME") )
{
desktop_dir = g_build_filename( g_get_home_dir(), line + 5, NULL );
g_free( line );
}
else
desktop_dir = line;
}
}
g_free( buf );
}
close( fd );
}
}
if( ! desktop_dir )
desktop_dir = g_build_filename( g_get_home_dir(), "Desktop", NULL );
#endif
#if 0
/* FIXME: what should we do if the user has no desktop dir? */
if( ! g_file_test( desktop_dir, G_FILE_TEST_IS_DIR ) )
{
g_free( desktop_dir );
desktop_dir = NULL;
}
#endif
is_desktop_set = TRUE;
return desktop_dir;
}
const char* vfs_get_trash_dir()
{
if( G_UNLIKELY( ! home_trash_dir ) )
{
home_trash_dir = g_build_filename( g_get_user_data_dir(), "Trash", NULL );
home_trash_dir_len = strlen( home_trash_dir );
}
return home_trash_dir;
}
void vfs_dir_foreach( GHFunc func, gpointer user_data )
{
if( ! dir_hash )
return;
/* g_debug( "reload mime-type" ); */
g_hash_table_foreach( dir_hash, (GHFunc)func, user_data );
}
void vfs_dir_unload_thumbnails( VFSDir* dir, gboolean is_big )
{
GList* l;
VFSFileInfo* file;
char* file_path;
g_mutex_lock( dir->mutex );
if( is_big )
{
for( l = dir->file_list; l; l = l->next )
{
file = (VFSFileInfo*)l->data;
if( file->big_thumbnail )
{
g_object_unref( file->big_thumbnail );
file->big_thumbnail = NULL;
}
/* This is a desktop entry file, so the icon needs reload
FIXME: This is not a good way to do things, but there is no better way now. */
if( file->flags & VFS_FILE_INFO_DESKTOP_ENTRY )
{
file_path = g_build_filename( dir->path, file->name, NULL );
vfs_file_info_load_special_info( file, file_path );
g_free( file_path );
}
}
}
else
{
for( l = dir->file_list; l; l = l->next )
{
file = (VFSFileInfo*)l->data;
if( file->small_thumbnail )
{
g_object_unref( file->small_thumbnail );
file->small_thumbnail = NULL;
}
/* This is a desktop entry file, so the icon needs reload
FIXME: This is not a good way to do things, but there is no better way now. */
if( file->flags & VFS_FILE_INFO_DESKTOP_ENTRY )
{
file_path = g_build_filename( dir->path, file->name, NULL );
vfs_file_info_load_special_info( file, file_path );
g_free( file_path );
}
}
}
g_mutex_unlock( dir->mutex );
}
//sfm added mime change timer
guint mime_change_timer = 0;
VFSDir* mime_dir = NULL;
gboolean on_mime_change_timer( gpointer user_data )
{
//printf("MIME-UPDATE on_timer\n" );
char* cmd = g_strdup_printf( "update-mime-database %s/mime",
g_get_user_data_dir() );
g_spawn_command_line_async( cmd, NULL );
g_free( cmd );
cmd = g_strdup_printf( "update-desktop-database %s/applications",
g_get_user_data_dir() );
g_spawn_command_line_async( cmd, NULL );
g_free( cmd );
g_source_remove( mime_change_timer );
mime_change_timer = 0;
return FALSE;
}
void mime_change( gpointer user_data )
{
if ( mime_change_timer )
{
// timer is already running, so ignore request
//printf("MIME-UPDATE already set\n" );
return;
}
if ( mime_dir )
{
// update mime database in 2 seconds
mime_change_timer = g_timeout_add_seconds( 2,
( GSourceFunc ) on_mime_change_timer, NULL );
//printf("MIME-UPDATE timer started\n" );
}
}
void vfs_dir_monitor_mime()
{
// start watching for changes
if ( mime_dir )
return;
char* path = g_build_filename( g_get_user_data_dir(), "mime/packages", NULL );
if ( g_file_test( path, G_FILE_TEST_IS_DIR ) )
{
mime_dir = vfs_dir_get_by_path( path );
if ( mime_dir )
{
g_signal_connect( mime_dir, "file-listed", G_CALLBACK( mime_change ), NULL );
g_signal_connect( mime_dir, "file-created", G_CALLBACK( mime_change ), NULL );
g_signal_connect( mime_dir, "file-deleted", G_CALLBACK( mime_change ), NULL );
g_signal_connect( mime_dir, "file-changed", G_CALLBACK( mime_change ), NULL );
}
//printf("MIME-UPDATE watch started\n" );
}
g_free( path );
}
|
161 | ./spacefm/src/vfs/vfs-volume-hal-options.c | #ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "vfs-volume-hal-options.h"
#include <string.h>
#include <unistd.h> /* for getuid() */
#include <sys/types.h>
#include <locale.h> /* for setlocale() */
#define CONFIG_FILE PACKAGE_DATA_DIR "/mount.rules"
gboolean vfs_volume_hal_get_options( const char* fs, VFSVolumeOptions* ret )
{
GKeyFile* f;
if( fs == NULL || ! *fs)
return FALSE;
g_return_val_if_fail( ret != NULL, FALSE );
f = g_key_file_new();
if( g_key_file_load_from_file( f, CONFIG_FILE, 0, NULL) )
{
gsize n = 0;
int i;
ret->mount_options = g_key_file_get_string_list( f, fs, "mount_options", &n, NULL );
ret->fstype_override = g_key_file_get_string(f, fs, "fstype_override", NULL );
for( i = 0; i < n; ++i )
{
/* replace "uid=" with "uid=<actual uid>" */
#ifndef __FreeBSD__
if (strcmp (ret->mount_options[i], "uid=") == 0) {
g_free (ret->mount_options[i]);
ret->mount_options[i] = g_strdup_printf ("uid=%u", getuid ());
}
#else
if (strcmp (ret->mount_options[i], "-u=") == 0) {
g_free (ret->mount_options[i]);
ret->mount_options[i] = g_strdup_printf ("-u=%u", getuid ());
}
#endif
/* for ntfs-3g */
if (strcmp (ret->mount_options[i], "locale=") == 0) {
g_free (ret->mount_options[i]);
ret->mount_options[i] = g_strdup_printf ("locale=%s", setlocale (LC_ALL, ""));
}
}
}
else
{
ret->mount_options = NULL;
ret->fstype_override = NULL;
}
g_key_file_free(f);
return (ret->mount_options || ret->fstype_override);
}
|
162 | ./spacefm/src/vfs/vfs-file-info.c | /*
* C Implementation: vfs-file-info
*
* Description: File information
*
*
* Author: Hong Jen Yee (PCMan) <pcman.tw (AT) gmail.com>, (C) 2006
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#include "vfs-file-info.h"
#include <glib.h>
#include "glib-mem.h"
#include <glib/gi18n.h>
#include <grp.h> /* Query group name */
#include <pwd.h> /* Query user name */
#include <string.h>
#include "settings.h"
#include "vfs-app-desktop.h"
#include "vfs-thumbnail-loader.h"
#include "vfs-utils.h" /* for vfs_load_icon */
static int big_thumb_size = 48, small_thumb_size = 20;
static gboolean utf8_file_name = FALSE;
static const char* desktop_dir = NULL; //MOD added
void vfs_file_info_set_utf8_filename( gboolean is_utf8 )
{
utf8_file_name = is_utf8;
}
VFSFileInfo* vfs_file_info_new ()
{
VFSFileInfo * fi = g_slice_new0( VFSFileInfo );
fi->n_ref = 1;
return fi;
}
static void vfs_file_info_clear( VFSFileInfo* fi )
{
if ( fi->disp_name && fi->disp_name != fi->name )
{
g_free( fi->disp_name );
fi->disp_name = NULL;
}
if ( fi->name )
{
g_free( fi->name );
fi->name = NULL;
}
if ( fi->collate_key ) //sfm
{
g_free( fi->collate_key );
fi->collate_key = NULL;
}
if ( fi->collate_icase_key ) //sfm
{
g_free( fi->collate_icase_key );
fi->collate_icase_key = NULL;
}
if ( fi->disp_size )
{
g_free( fi->disp_size );
fi->disp_size = NULL;
}
if ( fi->disp_owner )
{
g_free( fi->disp_owner );
fi->disp_owner = NULL;
}
if ( fi->disp_mtime )
{
g_free( fi->disp_mtime );
fi->disp_mtime = NULL;
}
if ( fi->big_thumbnail )
{
g_object_unref( fi->big_thumbnail );
fi->big_thumbnail = NULL;
}
if ( fi->small_thumbnail )
{
g_object_unref( fi->small_thumbnail );
fi->small_thumbnail = NULL;
}
fi->disp_perm[ 0 ] = '\0';
if ( fi->mime_type )
{
vfs_mime_type_unref( fi->mime_type );
fi->mime_type = NULL;
}
fi->flags = VFS_FILE_INFO_NONE;
}
VFSFileInfo* vfs_file_info_ref( VFSFileInfo* fi )
{
g_atomic_int_inc( &fi->n_ref );
return fi;
}
void vfs_file_info_unref( VFSFileInfo* fi )
{
if ( g_atomic_int_dec_and_test( &fi->n_ref) )
{
vfs_file_info_clear( fi );
g_slice_free( VFSFileInfo, fi );
}
}
gboolean vfs_file_info_get( VFSFileInfo* fi,
const char* file_path,
const char* base_name )
{
struct stat64 file_stat;
vfs_file_info_clear( fi );
if ( base_name )
fi->name = g_strdup( base_name );
else
fi->name = g_path_get_basename( file_path );
if ( lstat64( file_path, &file_stat ) == 0 )
{
/* This is time-consuming but can save much memory */
fi->mode = file_stat.st_mode;
fi->dev = file_stat.st_dev;
fi->uid = file_stat.st_uid;
fi->gid = file_stat.st_gid;
fi->size = file_stat.st_size;
//printf("size %s %llu\n", fi->name, fi->size );
fi->mtime = file_stat.st_mtime;
fi->atime = file_stat.st_atime;
fi->blksize = file_stat.st_blksize;
fi->blocks = file_stat.st_blocks;
if ( G_LIKELY( utf8_file_name && g_utf8_validate ( fi->name, -1, NULL ) ) )
{
fi->disp_name = fi->name; /* Don't duplicate the name and save memory */
}
else
{
fi->disp_name = g_filename_display_name( fi->name );
}
fi->mime_type = vfs_mime_type_get_from_file( file_path,
fi->disp_name,
&file_stat );
//sfm get collate keys
fi->collate_key = g_utf8_collate_key_for_filename( fi->disp_name, -1 );
char* str = g_utf8_casefold( fi->disp_name, -1 );
fi->collate_icase_key = g_utf8_collate_key_for_filename( str, -1 );
g_free( str );
return TRUE;
}
else
fi->mime_type = vfs_mime_type_get_from_type( XDG_MIME_TYPE_UNKNOWN );
return FALSE;
}
const char* vfs_file_info_get_name( VFSFileInfo* fi )
{
return fi->name;
}
/* Get displayed name encoded in UTF-8 */
const char* vfs_file_info_get_disp_name( VFSFileInfo* fi )
{
return fi->disp_name;
}
void vfs_file_info_set_disp_name( VFSFileInfo* fi, const char* name )
{
if ( fi->disp_name && fi->disp_name != fi->name )
g_free( fi->disp_name );
fi->disp_name = g_strdup( name );
//sfm get new collate keys
g_free( fi->collate_key );
g_free( fi->collate_icase_key );
fi->collate_key = g_utf8_collate_key_for_filename( fi->disp_name, -1 );
char* str = g_utf8_casefold( fi->disp_name, -1 );
fi->collate_icase_key = g_utf8_collate_key_for_filename( str, -1 );
g_free( str );
}
void vfs_file_info_set_name( VFSFileInfo* fi, const char* name )
{
g_free( fi->name );
fi->name = g_strdup( name );
}
off_t vfs_file_info_get_size( VFSFileInfo* fi )
{
return fi->size;
}
const char* vfs_file_info_get_disp_size( VFSFileInfo* fi )
{
if ( G_UNLIKELY( !fi->disp_size ) )
{
char buf[ 64 ];
vfs_file_size_to_string( buf, fi->size );
fi->disp_size = g_strdup( buf );
}
return fi->disp_size;
}
off_t vfs_file_info_get_blocks( VFSFileInfo* fi )
{
return fi->blocks;
}
VFSMimeType* vfs_file_info_get_mime_type( VFSFileInfo* fi )
{
vfs_mime_type_ref( fi->mime_type );
return fi->mime_type;
}
void vfs_file_info_reload_mime_type( VFSFileInfo* fi,
const char* full_path )
{
VFSMimeType * old_mime_type;
struct stat64 file_stat;
/* convert VFSFileInfo to struct stat */
/* In current implementation, only st_mode is used in
mime-type detection, so let's save some CPU cycles
and don't copy unused fields.
*/
file_stat.st_mode = fi->mode;
/*
file_stat.st_dev = fi->dev;
file_stat.st_uid = fi->uid;
file_stat.st_gid = fi->gid;
file_stat.st_size = fi->size;
file_stat.st_mtime = fi->mtime;
file_stat.st_atime = fi->atime;
file_stat.st_blksize = fi->blksize;
file_stat.st_blocks = fi->blocks;
*/
old_mime_type = fi->mime_type;
fi->mime_type = vfs_mime_type_get_from_file( full_path,
fi->name, &file_stat );
vfs_file_info_load_special_info( fi, full_path );
vfs_mime_type_unref( old_mime_type ); /* FIXME: is vfs_mime_type_unref needed ?*/
}
const char* vfs_file_info_get_mime_type_desc( VFSFileInfo* fi )
{
return vfs_mime_type_get_description( fi->mime_type );
}
GdkPixbuf* vfs_file_info_get_big_icon( VFSFileInfo* fi )
{
/* get special icons for special files, especially for
some desktop icons */
if ( G_UNLIKELY( fi->flags != VFS_FILE_INFO_NONE ) )
{
int w, h;
int icon_size;
vfs_mime_type_get_icon_size( &icon_size, NULL );
if ( fi->big_thumbnail )
{
w = gdk_pixbuf_get_width( fi->big_thumbnail );
h = gdk_pixbuf_get_height( fi->big_thumbnail );
}
else
w = h = 0;
if ( ABS( MAX( w, h ) - icon_size ) > 2 )
{
char * icon_name = NULL;
if ( fi->big_thumbnail )
{
icon_name = ( char* ) g_object_steal_data(
G_OBJECT(fi->big_thumbnail), "name" );
g_object_unref( fi->big_thumbnail );
fi->big_thumbnail = NULL;
}
if ( G_LIKELY( icon_name ) )
{
if ( G_UNLIKELY( icon_name[ 0 ] == '/' ) )
fi->big_thumbnail = gdk_pixbuf_new_from_file( icon_name, NULL );
else
fi->big_thumbnail = vfs_load_icon(
gtk_icon_theme_get_default(),
icon_name, icon_size );
}
if ( fi->big_thumbnail )
g_object_set_data_full( G_OBJECT(fi->big_thumbnail), "name", icon_name, g_free );
else
g_free( icon_name );
}
return fi->big_thumbnail ? g_object_ref( fi->big_thumbnail ) : NULL;
}
if( G_UNLIKELY(!fi->mime_type) )
return NULL;
return vfs_mime_type_get_icon( fi->mime_type, TRUE );
}
GdkPixbuf* vfs_file_info_get_small_icon( VFSFileInfo* fi )
{
if ( fi->flags & VFS_FILE_INFO_DESKTOP_ENTRY && fi->small_thumbnail ) //sfm
return g_object_ref( fi->small_thumbnail );
if( G_UNLIKELY(!fi->mime_type) )
return NULL;
return vfs_mime_type_get_icon( fi->mime_type, FALSE );
}
GdkPixbuf* vfs_file_info_get_big_thumbnail( VFSFileInfo* fi )
{
return fi->big_thumbnail ? g_object_ref( fi->big_thumbnail ) : NULL;
}
GdkPixbuf* vfs_file_info_get_small_thumbnail( VFSFileInfo* fi )
{
return fi->small_thumbnail ? g_object_ref( fi->small_thumbnail ) : NULL;
}
const char* vfs_file_info_get_disp_owner( VFSFileInfo* fi )
{
struct passwd * puser;
struct group* pgroup;
char uid_str_buf[ 32 ];
char* user_name;
char gid_str_buf[ 32 ];
char* group_name;
/* FIXME: user names should be cached */
if ( ! fi->disp_owner )
{
puser = getpwuid( fi->uid );
if ( puser && puser->pw_name && *puser->pw_name )
user_name = puser->pw_name;
else
{
sprintf( uid_str_buf, "%d", fi->uid );
user_name = uid_str_buf;
}
pgroup = getgrgid( fi->gid );
if ( pgroup && pgroup->gr_name && *pgroup->gr_name )
group_name = pgroup->gr_name;
else
{
sprintf( gid_str_buf, "%d", fi->gid );
group_name = gid_str_buf;
}
fi->disp_owner = g_strdup_printf ( "%s:%s", user_name, group_name );
}
return fi->disp_owner;
}
const char* vfs_file_info_get_disp_mtime( VFSFileInfo* fi )
{
if ( ! fi->disp_mtime )
{
char buf[ 64 ];
strftime( buf, sizeof( buf ),
app_settings.date_format, //"%Y-%m-%d %H:%M",
localtime( &fi->mtime ) );
fi->disp_mtime = g_strdup( buf );
}
return fi->disp_mtime;
}
time_t* vfs_file_info_get_mtime( VFSFileInfo* fi )
{
return & fi->mtime;
}
time_t* vfs_file_info_get_atime( VFSFileInfo* fi )
{
return & fi->atime;
}
static void get_file_perm_string( char* perm, mode_t mode )
{
if ( S_ISREG( mode ) ) //sfm
perm[0] = '-';
else if ( S_ISDIR( mode ) )
perm[0] = 'd';
else if ( S_ISLNK( mode ) )
perm[0] = 'l';
else if ( G_UNLIKELY( S_ISCHR( mode ) ) )
perm[0] = 'c';
else if ( G_UNLIKELY( S_ISBLK( mode ) ) )
perm[0] = 'b';
else if ( G_UNLIKELY( S_ISFIFO( mode ) ) )
perm[0] = 'p';
else if ( G_UNLIKELY( S_ISSOCK( mode ) ) )
perm[0] = 's';
else
perm[0] = '-';
perm[ 1 ] = ( mode & S_IRUSR ) ? 'r' : '-';
perm[ 2 ] = ( mode & S_IWUSR ) ? 'w' : '-';
if ( G_UNLIKELY( mode & S_ISUID ) ) //sfm
{
if ( G_LIKELY( mode & S_IXUSR ) )
perm[ 3 ] = 's';
else
perm[ 3 ] = 'S';
}
else
perm[ 3 ] = ( mode & S_IXUSR ) ? 'x' : '-';
perm[ 4 ] = ( mode & S_IRGRP ) ? 'r' : '-';
perm[ 5 ] = ( mode & S_IWGRP ) ? 'w' : '-';
if ( G_UNLIKELY( mode & S_ISGID ) ) //sfm
{
if ( G_LIKELY( mode & S_IXGRP ) )
perm[ 6 ] = 's';
else
perm[ 6 ] = 'S';
}
else
perm[ 6 ] = ( mode & S_IXGRP ) ? 'x' : '-';
perm[ 7 ] = ( mode & S_IROTH ) ? 'r' : '-';
perm[ 8 ] = ( mode & S_IWOTH ) ? 'w' : '-';
if ( G_UNLIKELY( mode & S_ISVTX ) ) //MOD
{
if ( G_LIKELY( mode & S_IXOTH ) )
perm[ 9 ] = 't';
else
perm[ 9 ] = 'T';
}
else
perm[ 9 ] = ( mode & S_IXOTH ) ? 'x' : '-';
perm[ 10 ] = '\0';
}
const char* vfs_file_info_get_disp_perm( VFSFileInfo* fi )
{
if ( ! fi->disp_perm[ 0 ] )
get_file_perm_string( fi->disp_perm,
fi->mode );
return fi->disp_perm;
}
void vfs_file_size_to_string_format( char* buf, guint64 size, char* format ) //MOD added
{ // if format == NULL uses automatic format based on size
char * unit;
gfloat val;
/*
FIXME: Is floating point calculation slower than integer division?
Some profiling is needed here.
*/
if ( size > ( ( guint64 ) 1 ) << 30 )
{
if ( size > ( ( guint64 ) 1 ) << 40 )
{
/*
size /= ( ( ( guint64 ) 1 << 40 ) / 10 );
point = ( guint ) ( size % 10 );
size /= 10;
*/
if (app_settings.use_si_prefix==TRUE)
{
val = ((gfloat)size) / (( guint64 ) 1000000000000 );
unit = _("T");
}
else
{
val = ((gfloat)size) / ( ( guint64 ) 1 << 40 );
unit = _("T"); //MOD was TiB
}
}
else
{
/*
size /= ( ( 1 << 30 ) / 10 );
point = ( guint ) ( size % 10 );
size /= 10;
*/
if (app_settings.use_si_prefix==TRUE)
{
val = ((gfloat)size) / (( guint64 ) 1000000000 );
unit = _("G");
}
else
{
val = ((gfloat)size) / ( ( guint64 ) 1 << 30 );
unit = _("G"); //MOD was GiB
}
}
}
else if ( size > ( 1 << 20 ) )
{
/*
size /= ( ( 1 << 20 ) / 10 );
point = ( guint ) ( size % 10 );
size /= 10;
*/
if (app_settings.use_si_prefix==TRUE)
{
val = ((gfloat)size) / (( guint64 ) 1000000 );
unit = _("M");
}
else
{
val = ((gfloat)size) / ( ( guint64 ) 1 << 20 );
unit = _("M"); //MOD was MiB
}
}
else if ( size > ( 1 << 10 ) )
{
/*
size /= ( ( 1 << 10 ) / 10 );
point = size % 10;
size /= 10;
*/
if (app_settings.use_si_prefix==TRUE)
{
val = ((gfloat)size) / (( guint64 ) 1000 );
unit = _("K"); //MOD was KB
}
else
{
val = ((gfloat)size) / ( ( guint64 ) 1 << 10 );
unit = _("K"); //MOD was KiB
}
}
else
{
unit = _("B"); //size > 1 ? _("B") : _("B");
sprintf( buf, "%u %s", ( guint ) size, unit );
return ;
}
if ( format )
sprintf( buf, format, val, unit ); // "%.0f%s"
else if ( val < 10 )
sprintf( buf, "%.1f %s", val, unit );
else
sprintf( buf, "%.0f %s", val, unit );
}
void vfs_file_size_to_string( char* buf, guint64 size )
{
char * unit;
/* guint point; */
gfloat val;
/*
FIXME: Is floating point calculation slower than integer division?
Some profiling is needed here.
*/
if ( size > ( ( guint64 ) 1 ) << 30 )
{
if ( size > ( ( guint64 ) 1 ) << 40 )
{
/*
size /= ( ( ( guint64 ) 1 << 40 ) / 10 );
point = ( guint ) ( size % 10 );
size /= 10;
*/
if (app_settings.use_si_prefix==TRUE)
{
val = ((gfloat)size) / (( guint64 ) 1000000000000 );
unit = _("T");
}
else
{
val = ((gfloat)size) / ( ( guint64 ) 1 << 40 );
unit = _("T"); //MOD was TiB
}
}
else
{
/*
size /= ( ( 1 << 30 ) / 10 );
point = ( guint ) ( size % 10 );
size /= 10;
*/
if (app_settings.use_si_prefix==TRUE)
{
val = ((gfloat)size) / (( guint64 ) 1000000000 );
unit = _("G");
}
else
{
val = ((gfloat)size) / ( ( guint64 ) 1 << 30 );
unit = _("G"); //MOD was GiB
}
}
}
else if ( size > ( 1 << 20 ) )
{
/*
size /= ( ( 1 << 20 ) / 10 );
point = ( guint ) ( size % 10 );
size /= 10;
*/
if (app_settings.use_si_prefix==TRUE)
{
val = ((gfloat)size) / (( guint64 ) 1000000 );
unit = _("M");
}
else
{
val = ((gfloat)size) / ( ( guint64 ) 1 << 20 );
unit = _("M"); //MOD was MiB
}
}
else if ( size > ( 1 << 10 ) )
{
/*
size /= ( ( 1 << 10 ) / 10 );
point = size % 10;
size /= 10;
*/
if (app_settings.use_si_prefix==TRUE)
{
val = ((gfloat)size) / (( guint64 ) 1000 );
unit = _("K"); //MOD was KB
}
else
{
val = ((gfloat)size) / ( ( guint64 ) 1 << 10 );
unit = _("K"); //MOD was KiB
}
}
else
{
//unit = size > 1 ? "Bytes" : "Byte";
unit = _("B");
sprintf( buf, "%u %s", ( guint ) size, unit );
return ;
}
/* sprintf( buf, "%llu.%u %s", size, point, unit ); */
sprintf( buf, "%.1f %s", val, unit );
}
gboolean vfs_file_info_is_dir( VFSFileInfo* fi )
{
if ( S_ISDIR( fi->mode ) )
return TRUE;
if ( S_ISLNK( fi->mode ) &&
0 == strcmp( vfs_mime_type_get_type( fi->mime_type ), XDG_MIME_TYPE_DIRECTORY ) )
{
return TRUE;
}
return FALSE;
}
gboolean vfs_file_info_is_symlink( VFSFileInfo* fi )
{
return S_ISLNK( fi->mode ) ? TRUE : FALSE;
}
gboolean vfs_file_info_is_image( VFSFileInfo* fi )
{
/* FIXME: We had better use functions of xdg_mime to check this */
if ( ! strncmp( "image/", vfs_mime_type_get_type( fi->mime_type ), 6 ) )
return TRUE;
return FALSE;
}
gboolean vfs_file_info_is_desktop_entry( VFSFileInfo* fi )
{
return 0 != (fi->flags & VFS_FILE_INFO_DESKTOP_ENTRY);
}
gboolean vfs_file_info_is_unknown_type( VFSFileInfo* fi )
{
if ( ! strcmp( XDG_MIME_TYPE_UNKNOWN,
vfs_mime_type_get_type( fi->mime_type ) ) )
return TRUE;
return FALSE;
}
/* full path of the file is required by this function */
gboolean vfs_file_info_is_executable( VFSFileInfo* fi, const char* file_path )
{
return mime_type_is_executable_file( file_path, fi->mime_type->type );
}
/* full path of the file is required by this function */
gboolean vfs_file_info_is_text( VFSFileInfo* fi, const char* file_path )
{
return mime_type_is_text_file( file_path, fi->mime_type->type );
}
/*
* Run default action of specified file.
* Full path of the file is required by this function.
*/
gboolean vfs_file_info_open_file( VFSFileInfo* fi,
const char* file_path,
GError** err )
{
VFSMimeType * mime_type;
char* app_name;
VFSAppDesktop* app;
GList* files = NULL;
gboolean ret = FALSE;
char* argv[ 2 ];
if ( vfs_file_info_is_executable( fi, file_path ) )
{
argv[ 0 ] = (char *) file_path;
argv[ 1 ] = '\0';
ret = g_spawn_async( NULL, argv, NULL, G_SPAWN_STDOUT_TO_DEV_NULL|
G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, err );
}
else
{
mime_type = vfs_file_info_get_mime_type( fi );
app_name = vfs_mime_type_get_default_action( mime_type );
if ( app_name )
{
app = vfs_app_desktop_new( app_name );
if ( ! vfs_app_desktop_get_exec( app ) )
app->exec = g_strdup( app_name ); /* FIXME: app->exec */
files = g_list_prepend( files, (gpointer) file_path );
/* FIXME: working dir is needed */
ret = vfs_app_desktop_open_files( gdk_screen_get_default(),
NULL, app, files, err );
g_list_free( files );
vfs_app_desktop_unref( app );
g_free( app_name );
}
vfs_mime_type_unref( mime_type );
}
return ret;
}
mode_t vfs_file_info_get_mode( VFSFileInfo* fi )
{
return fi->mode;
}
gboolean vfs_file_info_is_thumbnail_loaded( VFSFileInfo* fi, gboolean big )
{
if ( big )
return ( fi->big_thumbnail != NULL );
return ( fi->small_thumbnail != NULL );
}
gboolean vfs_file_info_load_thumbnail( VFSFileInfo* fi,
const char* full_path,
gboolean big )
{
GdkPixbuf* thumbnail;
if ( big )
{
if ( fi->big_thumbnail )
return TRUE;
}
else
{
if ( fi->small_thumbnail )
return TRUE;
}
thumbnail = vfs_thumbnail_load_for_file( full_path,
big ? big_thumb_size : small_thumb_size , fi->mtime );
if( G_LIKELY( thumbnail ) )
{
if ( big )
fi->big_thumbnail = thumbnail;
else
fi->small_thumbnail = thumbnail;
}
else /* fallback to mime_type icon */
{
if ( big )
fi->big_thumbnail = vfs_file_info_get_big_icon( fi );
else
fi->small_thumbnail = vfs_file_info_get_small_icon( fi );
}
return ( thumbnail != NULL );
}
void vfs_file_info_set_thumbnail_size( int big, int small )
{
big_thumb_size = big;
small_thumb_size = small;
}
void vfs_file_info_load_special_info( VFSFileInfo* fi,
const char* file_path )
{
/*if ( G_LIKELY(fi->type) && G_UNLIKELY(fi->type->name, "application/x-desktop") ) */
if ( G_UNLIKELY( g_str_has_suffix( fi->name, ".desktop") ) )
{
VFSAppDesktop * desktop;
const char* icon_name;
if ( !desktop_dir )
desktop_dir = vfs_get_desktop_dir();
char* file_dir = g_path_get_dirname( file_path );
fi->flags |= VFS_FILE_INFO_DESKTOP_ENTRY;
desktop = vfs_app_desktop_new( file_path );
//MOD display real filenames of .desktop files not in desktop folder
if ( desktop_dir && !strcmp( file_dir, desktop_dir ) )
{
if ( vfs_app_desktop_get_disp_name( desktop ) )
{
vfs_file_info_set_disp_name(
fi, vfs_app_desktop_get_disp_name( desktop ) );
}
}
if ( (icon_name = vfs_app_desktop_get_icon_name( desktop )) )
{
GdkPixbuf* icon;
int big_size, small_size;
vfs_mime_type_get_icon_size( &big_size, &small_size );
if( ! fi->big_thumbnail )
{
icon = vfs_app_desktop_get_icon( desktop, big_size, FALSE );
if( G_LIKELY(icon) )
fi->big_thumbnail =icon;
}
if( ! fi->small_thumbnail )
{
icon = vfs_app_desktop_get_icon( desktop, small_size, FALSE );
if( G_LIKELY(icon) )
fi->small_thumbnail =icon;
}
}
vfs_app_desktop_unref( desktop );
g_free( file_dir );
}
}
void vfs_file_info_list_free( GList* list )
{
g_list_foreach( list, (GFunc)vfs_file_info_unref, NULL );
g_list_free( list );
}
char* vfs_file_resolve_path( const char* cwd, const char* relative_path )
{
GString* ret = g_string_sized_new( 4096 );
int len;
gboolean strip_tail;
g_return_val_if_fail( G_LIKELY(relative_path), NULL );
len = strlen( relative_path );
strip_tail = (0 == len || relative_path[len-1] != '/');
if( G_UNLIKELY(*relative_path != '/') ) /* relative path */
{
if( G_UNLIKELY(relative_path[0] == '~') ) /* home dir */
{
g_string_append( ret, g_get_home_dir());
++relative_path;
}
else
{
if( ! cwd )
{
char *cwd_new;
cwd_new = g_get_current_dir();
g_string_append( ret, cwd_new );
g_free( cwd_new );
}
else
g_string_append( ret, cwd );
}
}
if( relative_path[0] != '/' && (0 == ret->len || ret->str[ ret->len - 1 ] != '/' ) )
g_string_append_c( ret, '/' );
while( G_LIKELY( *relative_path ) )
{
if( G_UNLIKELY(*relative_path == '.') )
{
if( relative_path[1] == '/' || relative_path[1] == '\0' ) /* current dir */
{
relative_path += relative_path[1] ? 2 : 1;
continue;
}
if( relative_path[1] == '.' &&
( relative_path[2] == '/' || relative_path[2] == '\0') ) /* parent dir */
{
gsize len = ret->len - 2;
while( ret->str[ len ] != '/' )
--len;
g_string_truncate( ret, len + 1 );
relative_path += relative_path[2] ? 3 : 2;
continue;
}
}
do
{
g_string_append_c( ret, *relative_path );
}while( G_LIKELY( *(relative_path++) != '/' && *relative_path ) );
}
/* if original path contains tailing '/', preserve it; otherwise, remove it. */
if( strip_tail && G_LIKELY( ret->len > 1 ) && G_UNLIKELY( ret->str[ ret->len - 1 ] == '/' ) )
g_string_truncate( ret, ret->len - 1 );
return g_string_free( ret, FALSE );
}
|
163 | ./spacefm/src/vfs/vfs-file-task.c | /*
* C Implementation: vfs-file-task
*
* Description: modified and redesigned for SpaceFM
*
*
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "vfs-file-task.h"
#include <unistd.h>
#include <fcntl.h>
#include <utime.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <glib.h>
#include "glib-mem.h"
#include "glib-utils.h"
#include <glib/gi18n.h>
#include <stdio.h>
#include <stdlib.h> /* for mkstemp */
#include <string.h>
#include <errno.h>
#include "vfs-dir.h"
#include "settings.h"
#include <sys/wait.h> //MOD for exec
#include "main-window.h"
#include "desktop-window.h"
#include "vfs-volume.h"
const mode_t chmod_flags[] =
{
S_IRUSR, S_IWUSR, S_IXUSR,
S_IRGRP, S_IWGRP, S_IXGRP,
S_IROTH, S_IWOTH, S_IXOTH,
S_ISUID, S_ISGID, S_ISVTX
};
/*
* void get_total_size_of_dir( const char* path, off_t* size )
* Recursively count total size of all files in the specified directory.
* If the path specified is a file, the size of the file is directly returned.
* cancel is used to cancel the operation. This function will check the value
* pointed by cancel in every iteration. If cancel is set to TRUE, the
* calculation is cancelled.
* NOTE: *size should be set to zero before calling this function.
*/
static void get_total_size_of_dir( VFSFileTask* task,
const char* path,
off_t* size,
struct stat64* have_stat );
void vfs_file_task_error( VFSFileTask* task, int errnox, const char* action,
const char* target );
void vfs_file_task_exec_error( VFSFileTask* task, int errnox, char* action );
void add_task_dev( VFSFileTask* task, dev_t dev );
static gboolean should_abort( VFSFileTask* task );
void gx_free( gpointer x ) {} // dummy free - test only
void append_add_log( VFSFileTask* task, const char* msg, gint msg_len )
{
g_mutex_lock( task->mutex );
GtkTextIter iter;
gtk_text_buffer_get_iter_at_mark( task->add_log_buf, &iter, task->add_log_end );
gtk_text_buffer_insert( task->add_log_buf, &iter, msg, msg_len );
g_mutex_unlock( task->mutex );
}
static void call_state_callback( VFSFileTask* task,
VFSFileTaskState state )
{
task->state = state;
if ( task->state_cb )
{
if ( !task->state_cb( task, state, NULL, task->state_cb_data ) )
{
task->abort = TRUE;
if ( task->type == VFS_FILE_TASK_EXEC && task->exec_cond )
{
// this is used only if exec task run in non-main loop thread
g_mutex_lock( task->mutex );
g_cond_broadcast( task->exec_cond );
g_mutex_unlock( task->mutex );
}
}
else
task->state = VFS_FILE_TASK_RUNNING;
}
}
static gboolean should_abort( VFSFileTask* task )
{
if ( task->state_pause != VFS_FILE_TASK_RUNNING )
{
// paused or queued - suspend thread
g_mutex_lock( task->mutex );
g_timer_stop( task->timer );
task->pause_cond = g_cond_new();
g_cond_wait( task->pause_cond, task->mutex );
// resume
g_cond_free( task->pause_cond );
task->pause_cond = NULL;
task->last_elapsed = g_timer_elapsed( task->timer, NULL );
task->last_progress = task->progress;
task->last_speed = 0;
g_timer_continue( task->timer );
task->state_pause = VFS_FILE_TASK_RUNNING;
g_mutex_unlock( task->mutex );
}
return task->abort;
}
char* vfs_file_task_get_unique_name( const char* dest_dir, const char* base_name,
const char* ext )
{ // returns NULL if all names used; otherwise newly allocated string
struct stat64 dest_stat;
char* new_name = g_strdup_printf( "%s%s%s", base_name,
ext && ext[0] ? "." : "",
ext ? ext : "" );
char* new_dest_file = g_build_filename( dest_dir, new_name, NULL );
g_free( new_name );
uint n = 1;
while ( n && lstat64( new_dest_file, &dest_stat ) == 0 )
{
g_free( new_dest_file );
new_name = g_strdup_printf( "%s-%s%d%s%s", base_name,
_("copy"),
++n,
ext && ext[0] ? "." : "",
ext ? ext : "" );
new_dest_file = g_build_filename( dest_dir, new_name, NULL );
g_free( new_name );
}
if ( n == 0 )
{
g_free( new_dest_file );
return NULL;
}
return new_dest_file;
}
/*
* Check if the destination file exists.
* If the dest_file exists, let the user choose a new destination,
* skip/overwrite/auto-rename/all, pause, or cancel.
* The returned string is the new destination file chosen by the user
*/
static
gboolean check_overwrite( VFSFileTask* task,
const gchar* dest_file,
gboolean* dest_exists,
char** new_dest_file )
{
struct stat64 dest_stat;
const char* use_dest_file;
char* new_dest;
while ( 1 )
{
*new_dest_file = NULL;
if ( task->overwrite_mode == VFS_FILE_TASK_OVERWRITE_ALL )
{
*dest_exists = !lstat64( dest_file, &dest_stat );
if ( !g_strcmp0( task->current_file, task->current_dest ) )
{
// src and dest are same file - don't overwrite (truncates)
// occurs if user pauses task and changes overwrite mode
return FALSE;
}
return TRUE;
}
if ( task->overwrite_mode == VFS_FILE_TASK_SKIP_ALL )
{
*dest_exists = !lstat64( dest_file, &dest_stat );
return !*dest_exists;
}
if ( task->overwrite_mode == VFS_FILE_TASK_AUTO_RENAME )
{
*dest_exists = !lstat64( dest_file, &dest_stat );
if ( !*dest_exists )
return !task->abort;
// auto-rename
char* ext;
char* old_name = g_path_get_basename( dest_file );
char* dest_dir = g_path_get_dirname( dest_file );
char* base_name = get_name_extension( old_name,
S_ISDIR( dest_stat.st_mode ),
&ext );
g_free( old_name );
*new_dest_file = vfs_file_task_get_unique_name( dest_dir, base_name, ext );
*dest_exists = FALSE;
g_free( dest_dir );
g_free( base_name );
g_free( ext );
if ( *new_dest_file )
return !task->abort;
// else ran out of names - fall through to query user
}
*dest_exists = !lstat64( dest_file, &dest_stat );
if ( !*dest_exists )
return !task->abort;
// dest exists - query user
if ( !task->state_cb ) // failsafe
return FALSE;
use_dest_file = dest_file;
do
{
// destination file exists
*dest_exists = TRUE;
task->state = VFS_FILE_TASK_QUERY_OVERWRITE;
new_dest = NULL;
// query user
if ( !task->state_cb( task, VFS_FILE_TASK_QUERY_OVERWRITE,
&new_dest, task->state_cb_data ) )
// task->abort is actually set in query_overwrite_response
// VFS_FILE_TASK_QUERY_OVERWRITE never returns FALSE
task->abort = TRUE;
task->state = VFS_FILE_TASK_RUNNING;
// may pause here - user may change overwrite mode
if ( should_abort( task ) )
{
g_free( new_dest );
return FALSE;
}
if ( task->overwrite_mode != VFS_FILE_TASK_RENAME )
{
g_free( new_dest );
new_dest = NULL;
if( task->overwrite_mode == VFS_FILE_TASK_OVERWRITE ||
task->overwrite_mode == VFS_FILE_TASK_OVERWRITE_ALL )
{
*dest_exists = !lstat64( dest_file, &dest_stat );
if ( !g_strcmp0( task->current_file, task->current_dest ) )
{
// src and dest are same file - don't overwrite (truncates)
// occurs if user pauses task and changes overwrite mode
return FALSE;
}
return TRUE;
}
else if ( task->overwrite_mode == VFS_FILE_TASK_AUTO_RENAME )
break;
else
return FALSE;
}
// user renamed file or pressed Pause btn
if ( new_dest )
// user renamed file - test if new name exists
use_dest_file = new_dest;
} while ( lstat64( use_dest_file, &dest_stat ) != -1 );
if ( new_dest )
{
// user renamed file to unique name
*dest_exists = FALSE;
*new_dest_file = new_dest;
return !task->abort;
}
}
}
gboolean check_dest_in_src( VFSFileTask* task, const char* src_dir )
{
char real_src_path[PATH_MAX];
char real_dest_path[PATH_MAX];
int len;
if ( !( task->dest_dir && realpath( task->dest_dir, real_dest_path ) ) )
return FALSE;
if ( realpath( src_dir, real_src_path ) &&
g_str_has_prefix( real_dest_path, real_src_path ) &&
( len = strlen( real_src_path ) ) &&
( real_dest_path[len] == '/' ||
real_dest_path[len] == '\0' ) )
{
// source is contained in destination dir
char* disp_src = g_filename_display_name( src_dir );
char* disp_dest = g_filename_display_name( task->dest_dir );
char* err = g_strdup_printf( _("Destination directory \"%1$s\" is contained in source \"%2$s\""), disp_dest, disp_src );
append_add_log( task, err, -1 );
g_free( err );
g_free( disp_src );
g_free( disp_dest );
if ( task->state_cb )
task->state_cb( task, VFS_FILE_TASK_ERROR,
NULL, task->state_cb_data );
task->state = VFS_FILE_TASK_RUNNING;
return TRUE;
}
return FALSE;
}
void update_file_display( const char* path )
{
// for devices like nfs, emit created and flush to avoid a
// blocking stat call in GUI thread during writes
GDK_THREADS_ENTER();
char* dir_path = g_path_get_dirname( path );
VFSDir* vdir = vfs_dir_get_by_path_soft( dir_path );
g_free( dir_path );
if ( vdir && vdir->avoid_changes )
{
VFSFileInfo* file = vfs_file_info_new();
vfs_file_info_get( file, path, NULL );
vfs_dir_emit_file_created( vdir,
vfs_file_info_get_name( file ), TRUE );
vfs_file_info_unref( file );
vfs_dir_flush_notify_cache();
}
if ( vdir )
g_object_unref( vdir );
GDK_THREADS_LEAVE();
}
/*
void update_file_display( const char* path )
{
// for devices like nfs, emit instant changed
GDK_THREADS_ENTER();
char* dir_path = g_path_get_dirname( path );
VFSDir* vdir = vfs_dir_get_by_path_soft( dir_path );
g_free( dir_path );
if ( vdir && vdir->avoid_changes )
{
char* filename = g_path_get_basename( path );
vfs_dir_emit_file_changed( vdir, filename, NULL, TRUE );
g_free( filename );
}
if ( vdir )
g_object_unref( vdir );
GDK_THREADS_LEAVE();
}
*/
static gboolean
vfs_file_task_do_copy( VFSFileTask* task,
const char* src_file,
const char* dest_file )
{
GDir * dir;
const gchar* file_name;
gchar* sub_src_file;
gchar* sub_dest_file;
struct stat64 file_stat;
char buffer[ 4096 ];
int rfd;
int wfd;
ssize_t rsize;
char* new_dest_file = NULL;
gboolean dest_exists;
gboolean copy_fail = FALSE;
int result;
GError *error;
if ( should_abort( task ) )
return FALSE;
//printf("vfs_file_task_do_copy( %s, %s )\n", src_file, dest_file );
g_mutex_lock( task->mutex );
string_copy_free( &task->current_file, src_file );
string_copy_free( &task->current_dest, dest_file );
task->current_item++;
g_mutex_unlock( task->mutex );
if ( lstat64( src_file, &file_stat ) == -1 )
{
vfs_file_task_error( task, errno, _("Accessing"), src_file );
return FALSE;
}
result = 0;
if ( S_ISDIR( file_stat.st_mode ) )
{
if ( check_dest_in_src( task, src_file ) )
goto _return_;
if ( ! check_overwrite( task, dest_file,
&dest_exists, &new_dest_file ) )
goto _return_;
if ( new_dest_file )
{
dest_file = new_dest_file;
g_mutex_lock( task->mutex );
string_copy_free( &task->current_dest, dest_file );
g_mutex_unlock( task->mutex );
}
if ( ! dest_exists )
result = mkdir( dest_file, file_stat.st_mode | 0700 );
if ( result == 0 )
{
struct utimbuf times;
g_mutex_lock( task->mutex );
task->progress += file_stat.st_size;
g_mutex_unlock( task->mutex );
error = NULL;
dir = g_dir_open( src_file, 0, &error );
if ( dir )
{
while ( (file_name = g_dir_read_name( dir )) )
{
if ( should_abort( task ) )
break;
sub_src_file = g_build_filename( src_file, file_name, NULL );
sub_dest_file = g_build_filename( dest_file, file_name, NULL );
if ( !vfs_file_task_do_copy( task, sub_src_file, sub_dest_file )
&& !copy_fail )
copy_fail = TRUE;
g_free(sub_dest_file );
g_free(sub_src_file );
}
g_dir_close( dir );
}
else if ( error )
{
char* msg = g_strdup_printf( "\n%s\n", error->message );
g_error_free( error );
vfs_file_task_exec_error( task, 0, msg );
g_free( msg );
copy_fail = TRUE;
if ( should_abort( task ) )
goto _return_;
}
chmod( dest_file, file_stat.st_mode );
times.actime = file_stat.st_atime;
times.modtime = file_stat.st_mtime;
utime( dest_file, × );
if ( task->avoid_changes )
update_file_display( dest_file );
/* Move files to different device: Need to delete source dir */
if ( ( task->type == VFS_FILE_TASK_MOVE
|| task->type == VFS_FILE_TASK_TRASH )
&& !should_abort( task ) && !copy_fail )
{
if ( (result = rmdir( src_file )) )
{
vfs_file_task_error( task, errno, _("Removing"), src_file );
copy_fail = TRUE;
if ( should_abort( task ) )
goto _return_;
}
}
}
else
{
vfs_file_task_error( task, errno, _("Creating Dir"), dest_file );
copy_fail = TRUE;
}
}
else if ( S_ISLNK( file_stat.st_mode ) )
{
if ( ( rfd = readlink( src_file, buffer, sizeof( buffer ) - 1 ) ) > 0 )
{
buffer[rfd] = '\0'; //MOD terminate buffer string
if ( ! check_overwrite( task, dest_file,
&dest_exists, &new_dest_file ) )
goto _return_;
if ( new_dest_file )
{
dest_file = new_dest_file;
g_mutex_lock( task->mutex );
string_copy_free( &task->current_dest, dest_file );
g_mutex_unlock( task->mutex );
}
//MOD delete it first to prevent exists error
if ( dest_exists )
{
result = unlink( dest_file );
if ( result && errno != 2 /* no such file */ )
{
vfs_file_task_error( task, errno, _("Removing"), dest_file );
goto _return_;
}
}
if ( ( wfd = symlink( buffer, dest_file ) ) == 0 )
{
//MOD don't chmod link because it changes target
//chmod( dest_file, file_stat.st_mode );
/* Move files to different device: Need to delete source files */
if ( ( task->type == VFS_FILE_TASK_MOVE
|| task->type == VFS_FILE_TASK_TRASH )
&& !copy_fail )
{
result = unlink( src_file );
if ( result )
{
vfs_file_task_error( task, errno, _("Removing"), src_file );
copy_fail = TRUE;
}
}
g_mutex_lock( task->mutex );
task->progress += file_stat.st_size;
g_mutex_unlock( task->mutex );
}
else
{
vfs_file_task_error( task, errno, _("Creating Link"), dest_file );
copy_fail = TRUE;
}
}
else
{
vfs_file_task_error( task, errno, _("Accessing"), src_file );
copy_fail = TRUE;
}
}
else
{
if ( ( rfd = open( src_file, O_RDONLY ) ) >= 0 )
{
if ( ! check_overwrite( task, dest_file,
&dest_exists, &new_dest_file ) )
{
close( rfd );
goto _return_;
}
if ( new_dest_file )
{
dest_file = new_dest_file;
g_mutex_lock( task->mutex );
string_copy_free( &task->current_dest, dest_file );
g_mutex_unlock( task->mutex );
}
//MOD if dest is a symlink, delete it first to prevent overwriting target!
if ( g_file_test( dest_file, G_FILE_TEST_IS_SYMLINK ) )
{
result = unlink( dest_file );
if ( result )
{
vfs_file_task_error( task, errno, _("Removing"), dest_file );
close( rfd );
goto _return_;
}
}
if ( ( wfd = creat( dest_file,
file_stat.st_mode | S_IWUSR ) ) >= 0 )
{
// sshfs becomes unresponsive with this, nfs is okay with it
//if ( task->avoid_changes )
// emit_created( dest_file );
struct utimbuf times;
while ( ( rsize = read( rfd, buffer, sizeof( buffer ) ) ) > 0 )
{
if ( should_abort( task ) )
{
copy_fail = TRUE;
break;
}
if ( write( wfd, buffer, rsize ) > 0 )
{
g_mutex_lock( task->mutex );
task->progress += rsize;
g_mutex_unlock( task->mutex );
}
else
{
vfs_file_task_error( task, errno, _("Writing"), dest_file );
copy_fail = TRUE;
break;
}
}
close( wfd );
if ( copy_fail )
{
result = unlink( dest_file );
if ( result && errno != 2 /* no such file */ )
{
vfs_file_task_error( task, errno, _("Removing"), dest_file );
copy_fail = TRUE;
}
}
else
{
//MOD don't chmod link
if ( ! g_file_test( dest_file, G_FILE_TEST_IS_SYMLINK ) )
{
chmod( dest_file, file_stat.st_mode );
times.actime = file_stat.st_atime;
times.modtime = file_stat.st_mtime;
utime( dest_file, × );
}
if ( task->avoid_changes )
update_file_display( dest_file );
/* Move files to different device: Need to delete source files */
if ( (task->type == VFS_FILE_TASK_MOVE || task->type == VFS_FILE_TASK_TRASH)
&& !should_abort( task ) )
{
result = unlink( src_file );
if ( result )
{
vfs_file_task_error( task, errno, _("Removing"), src_file );
copy_fail = TRUE;
}
}
}
}
else
{
vfs_file_task_error( task, errno, _("Creating"), dest_file );
copy_fail = TRUE;
}
close( rfd );
}
else
{
vfs_file_task_error( task, errno, _("Accessing"), src_file );
copy_fail = TRUE;
}
}
if ( new_dest_file )
g_free( new_dest_file );
if ( !copy_fail && task->error_first )
task->error_first = FALSE;
return !copy_fail;
_return_:
if ( new_dest_file )
g_free( new_dest_file );
return FALSE;
}
static void
vfs_file_task_copy( char* src_file, VFSFileTask* task )
{
gchar * file_name;
gchar* dest_file;
file_name = g_path_get_basename( src_file );
dest_file = g_build_filename( task->dest_dir, file_name, NULL );
g_free(file_name );
vfs_file_task_do_copy( task, src_file, dest_file );
g_free(dest_file );
}
static int
vfs_file_task_do_move ( VFSFileTask* task,
const char* src_file,
const char* dest_file ) //MOD void to int
{
gchar* new_dest_file = NULL;
gboolean dest_exists;
struct stat64 file_stat;
int result;
if ( should_abort( task ) )
return 0;
g_mutex_lock( task->mutex );
string_copy_free( &task->current_file, src_file );
string_copy_free( &task->current_dest, dest_file );
task->current_item++;
g_mutex_unlock( task->mutex );
/* g_debug( "move \"%s\" to \"%s\"\n", src_file, dest_file ); */
if ( lstat64( src_file, &file_stat ) == -1 )
{
vfs_file_task_error( task, errno, _("Accessing"), src_file );
return 0;
}
if ( should_abort( task ) )
return 0;
if ( S_ISDIR( file_stat.st_mode ) && check_dest_in_src( task, src_file ) )
return 0;
if ( ! check_overwrite( task, dest_file,
&dest_exists, &new_dest_file ) )
return 0;
if ( new_dest_file )
{
dest_file = new_dest_file;
g_mutex_lock( task->mutex );
string_copy_free( &task->current_dest, dest_file );
g_mutex_unlock( task->mutex );
}
result = rename( src_file, dest_file );
if ( result != 0 )
{
if ( result == -1 && errno == 18 ) //MOD Invalid cross-link device
return 18;
vfs_file_task_error( task, errno, _("Renaming"), src_file );
if ( should_abort( task ) )
{
g_free( new_dest_file );
return 0;
}
}
//MOD don't chmod link
else if ( ! g_file_test( dest_file, G_FILE_TEST_IS_SYMLINK ) )
chmod( dest_file, file_stat.st_mode );
g_mutex_lock( task->mutex );
task->progress += file_stat.st_size;
if ( task->error_first )
task->error_first = FALSE;
g_mutex_unlock( task->mutex );
if ( new_dest_file )
g_free( new_dest_file );
return 0;
}
static void
vfs_file_task_move( char* src_file, VFSFileTask* task )
{
struct stat64 src_stat;
struct stat64 dest_stat;
gchar* file_name;
gchar* dest_file;
GKeyFile* kf; /* for trash info */
int tmpfd = -1;
if ( should_abort( task ) )
return ;
g_mutex_lock( task->mutex );
string_copy_free( &task->current_file, src_file );
g_mutex_unlock( task->mutex );
file_name = g_path_get_basename( src_file );
if( task->type == VFS_FILE_TASK_TRASH )
{
dest_file = g_strconcat( task->dest_dir, "/", file_name, "XXXXXX", NULL );
tmpfd = mkstemp( dest_file );
if( tmpfd < 0 )
{
goto on_error;
}
g_debug( dest_file, NULL );
}
else
dest_file = g_build_filename( task->dest_dir, file_name, NULL );
g_free(file_name );
if ( lstat64( src_file, &src_stat ) == 0
&& stat64( task->dest_dir, &dest_stat ) == 0 )
{
/* Not on the same device */
if ( src_stat.st_dev != dest_stat.st_dev )
{
/* g_print("not on the same dev: %s\n", src_file); */
vfs_file_task_do_copy( task, src_file, dest_file );
}
else if ( S_ISDIR( src_stat.st_mode ) &&
g_file_test( dest_file, G_FILE_TEST_IS_DIR) )
{
// moving a directory onto a directory that exists - overwrite
vfs_file_task_do_copy( task, src_file, dest_file );
}
else
{
/* g_print("on the same dev: %s\n", src_file); */
if ( vfs_file_task_do_move( task, src_file, dest_file ) == 18 ) //MOD
{
//MOD Invalid cross-device link (st_dev not always accurate test)
// so now redo move as copy
vfs_file_task_do_copy( task, src_file, dest_file );
}
}
}
else
vfs_file_task_error( task, errno, _("Accessing"), src_file );
on_error:
if( tmpfd >= 0 )
{
close( tmpfd );
unlink( dest_file );
}
g_free(dest_file );
}
static void
vfs_file_task_delete( char* src_file, VFSFileTask* task )
{
GDir * dir;
const gchar* file_name;
gchar* sub_src_file;
struct stat64 file_stat;
int result;
GError *error;
if ( should_abort( task ) )
return ;
g_mutex_lock( task->mutex );
string_copy_free( &task->current_file, src_file );
task->current_item++;
g_mutex_unlock( task->mutex );
if ( lstat64( src_file, &file_stat ) == -1 )
{
vfs_file_task_error( task, errno, _("Accessing"), src_file );
return;
}
if ( S_ISDIR( file_stat.st_mode ) )
{
error = NULL;
dir = g_dir_open( src_file, 0, &error );
if ( dir )
{
while ( (file_name = g_dir_read_name( dir )) )
{
if ( should_abort( task ) )
break;
sub_src_file = g_build_filename( src_file, file_name, NULL );
vfs_file_task_delete( sub_src_file, task );
g_free(sub_src_file );
}
g_dir_close( dir );
}
else if ( error )
{
char* msg = g_strdup_printf( "\n%s\n", error->message );
g_error_free( error );
vfs_file_task_exec_error( task, 0, msg );
g_free( msg );
}
if ( should_abort( task ) )
return ;
result = rmdir( src_file );
if ( result != 0 )
{
vfs_file_task_error( task, errno, _("Removing"), src_file );
return ;
}
}
else
{
result = unlink( src_file );
if ( result != 0 )
{
vfs_file_task_error( task, errno, _("Removing"), src_file );
return ;
}
}
g_mutex_lock( task->mutex );
task->progress += file_stat.st_size;
if ( task->error_first )
task->error_first = FALSE;
g_mutex_unlock( task->mutex );
}
static void
vfs_file_task_link( char* src_file, VFSFileTask* task )
{
struct stat64 src_stat;
int result;
gchar* old_dest_file;
gchar* dest_file;
gchar* file_name;
gboolean dest_exists; //MOD
char* new_dest_file = NULL; //MOD
if ( should_abort( task ) )
return ;
file_name = g_path_get_basename( src_file );
old_dest_file = g_build_filename( task->dest_dir, file_name, NULL );
g_free(file_name );
dest_file = old_dest_file;
//MOD setup task for check overwrite
if ( should_abort( task ) )
return ;
g_mutex_lock( task->mutex );
string_copy_free( &task->current_file, src_file );
string_copy_free( &task->current_dest, old_dest_file );
task->current_item++;
g_mutex_unlock( task->mutex );
if ( stat64( src_file, &src_stat ) == -1 )
{
//MOD allow link to broken symlink
if ( errno != 2 || ! g_file_test( src_file, G_FILE_TEST_IS_SYMLINK ) ) //MOD
{
vfs_file_task_error( task, errno, _("Accessing"), src_file );
if ( should_abort( task ) )
return ;
}
}
/* FIXME: Check overwrite!! */ //MOD added check overwrite
if ( ! check_overwrite( task, dest_file,
&dest_exists, &new_dest_file ) )
return;
if ( new_dest_file )
{
dest_file = new_dest_file;
g_mutex_lock( task->mutex );
string_copy_free( &task->current_dest, dest_file );
g_mutex_unlock( task->mutex );
}
//MOD if dest exists, delete it first to prevent exists error
if ( dest_exists )
{
result = unlink( dest_file );
if ( result )
{
vfs_file_task_error( task, errno, _("Removing"), dest_file );
return;
}
}
result = symlink( src_file, dest_file );
if ( result )
{
vfs_file_task_error( task, errno, _("Creating Link"), dest_file );
if ( should_abort( task ) )
return ;
}
g_mutex_lock( task->mutex );
task->progress += src_stat.st_size;
if ( task->error_first )
task->error_first = FALSE;
g_mutex_unlock( task->mutex );
if ( new_dest_file )
g_free( new_dest_file );
g_free( old_dest_file );
}
static void
vfs_file_task_chown_chmod( char* src_file, VFSFileTask* task )
{
struct stat64 src_stat;
int i;
GDir* dir;
gchar* sub_src_file;
const gchar* file_name;
mode_t new_mode;
int result;
GError* error;
if( should_abort( task ) )
return ;
g_mutex_lock( task->mutex );
string_copy_free( &task->current_file, src_file );
task->current_item++;
g_mutex_unlock( task->mutex );
/* g_debug("chmod_chown: %s\n", src_file); */
if ( lstat64( src_file, &src_stat ) == 0 )
{
/* chown */
if ( task->uid != -1 || task->gid != -1 )
{
result = chown( src_file, task->uid, task->gid );
if ( result != 0 )
{
vfs_file_task_error( task, errno, "chown", src_file );
if ( should_abort( task ) )
return ;
}
}
/* chmod */
if ( task->chmod_actions )
{
new_mode = src_stat.st_mode;
for ( i = 0; i < N_CHMOD_ACTIONS; ++i )
{
if ( task->chmod_actions[ i ] == 2 ) /* Don't change */
continue;
if ( task->chmod_actions[ i ] == 0 ) /* Remove this bit */
new_mode &= ~chmod_flags[ i ];
else /* Add this bit */
new_mode |= chmod_flags[ i ];
}
if ( new_mode != src_stat.st_mode )
{
result = chmod( src_file, new_mode );
if ( result != 0 )
{
vfs_file_task_error( task, errno, "chmod", src_file );
if ( should_abort( task ) )
return ;
}
}
}
g_mutex_lock( task->mutex );
task->progress += src_stat.st_size;
g_mutex_unlock( task->mutex );
if ( task->avoid_changes )
update_file_display( src_file );
if ( S_ISDIR( src_stat.st_mode ) && task->recursive )
{
error = NULL;
dir = g_dir_open( src_file, 0, &error );
if ( dir )
{
while ( (file_name = g_dir_read_name( dir )) )
{
if ( should_abort( task ) )
break;
sub_src_file = g_build_filename( src_file, file_name, NULL );
vfs_file_task_chown_chmod( sub_src_file, task );
g_free(sub_src_file );
}
g_dir_close( dir );
}
else if ( error )
{
char* msg = g_strdup_printf( "\n%s\n", error->message );
g_error_free( error );
vfs_file_task_exec_error( task, 0, msg );
g_free( msg );
if ( should_abort( task ) )
return ;
}
else
{
vfs_file_task_error( task, errno, _("Accessing"), src_file );
if ( should_abort( task ) )
return ;
}
}
}
if ( task->error_first )
task->error_first = FALSE;
}
char* vfs_file_task_get_cpids( GPid pid )
{ // get child pids recursively as multi-line string
char* nl;
char* pids;
char* pida;
GPid pidi;
char* stdout = NULL;
char* cpids;
char* gcpids;
char* old_cpids;
if ( !pid )
return NULL;
char* command = g_strdup_printf( "/bin/ps h --ppid %d -o pid", pid );
gboolean ret = g_spawn_command_line_sync( command, &stdout, NULL, NULL, NULL );
g_free(command );
if ( ret && stdout && stdout[0] != '\0' && strchr( stdout, '\n' ) )
{
cpids = g_strdup( stdout );
// get grand cpids recursively
pids = stdout;
while ( nl = strchr( pids, '\n' ) )
{
nl[0] = '\0';
pida = g_strdup( pids );
nl[0] = '\n';
pids = nl + 1;
pidi = atoi( pida );
g_free(pida );
if ( pidi )
{
if ( gcpids = vfs_file_task_get_cpids( pidi ) )
{
old_cpids = cpids;
cpids = g_strdup_printf( "%s%s", old_cpids, gcpids );
g_free(old_cpids );
g_free(gcpids );
}
}
}
g_free(stdout );
//printf("vfs_file_task_get_cpids %d\n[\n%s]\n", pid, cpids );
return cpids;
}
if ( stdout )
g_free(stdout );
return NULL;
}
void vfs_file_task_kill_cpids( char* cpids, int signal )
{
char* nl;
char* pids;
char* pida;
GPid pidi;
if ( !signal || !cpids || cpids[0] == '\0' )
return;
pids = cpids;
while ( nl = strchr( pids, '\n' ) )
{
nl[0] = '\0';
pida = g_strdup( pids );
nl[0] = '\n';
pids = nl + 1;
pidi = atoi( pida );
g_free(pida );
if ( pidi )
{
//printf("KILL_CPID %d %d\n", pidi, signal );
kill( pidi, signal );
}
}
}
static void cb_exec_child_cleanup( GPid pid, gint status, char* tmp_file )
{ // delete tmp files after async task terminates
//printf("cb_exec_child_cleanup pid=%d status=%d file=%s\n", pid, status, tmp_file );
g_spawn_close_pid( pid );
if ( tmp_file )
{
unlink( tmp_file );
g_free( tmp_file );
}
//printf("cb_exec_child_cleanup DONE\n", pid, status);
}
static void cb_exec_child_watch( GPid pid, gint status, VFSFileTask* task )
{
gboolean bad_status = FALSE;
g_spawn_close_pid( pid );
task->exec_pid = 0;
if ( status )
{
if ( WIFEXITED( status ) )
task->exec_exit_status = WEXITSTATUS( status );
else
{
bad_status = TRUE;
task->exec_exit_status = -1;
}
}
else
task->exec_exit_status = 0;
if ( !task->exec_keep_tmp )
{
if ( task->exec_script )
unlink( task->exec_script );
}
printf("child finished pid=%d exit_status=%d\n", pid,
bad_status ? -1 : task->exec_exit_status );
if ( !task->exec_exit_status && !bad_status )
{
if ( !task->custom_percent )
task->percent = 100;
}
else
call_state_callback( task, VFS_FILE_TASK_ERROR );
if ( bad_status || ( !task->exec_channel_out && !task->exec_channel_err ) )
call_state_callback( task, VFS_FILE_TASK_FINISH );
}
static gboolean cb_exec_out_watch( GIOChannel *channel, GIOCondition cond,
VFSFileTask* task )
{
/*
printf("cb_exec_out_watch %d\n", channel);
if ( cond & G_IO_IN )
printf(" G_IO_IN\n");
if ( cond & G_IO_OUT )
printf(" G_IO_OUT\n");
if ( cond & G_IO_PRI )
printf(" G_IO_PRI\n");
if ( cond & G_IO_ERR )
printf(" G_IO_ERR\n");
if ( cond & G_IO_HUP )
printf(" G_IO_HUP\n");
if ( cond & G_IO_NVAL )
printf(" G_IO_NVAL\n");
if ( !( cond & G_IO_NVAL ) )
{
gint fd = g_io_channel_unix_get_fd( channel );
printf(" fd=%d\n", fd);
if ( fcntl(fd, F_GETFL) != -1 || errno != EBADF )
{
int flags = g_io_channel_get_flags( channel );
if ( flags & G_IO_FLAG_IS_READABLE )
printf( " G_IO_FLAG_IS_READABLE\n");
}
else
printf(" Invalid FD\n");
}
*/
gchar *line;
gsize size;
GtkTextIter iter;
if ( ( cond & G_IO_NVAL ) )
{
g_io_channel_unref( channel );
return FALSE;
}
else if ( !( cond & G_IO_IN ) )
{
if ( ( cond & G_IO_HUP ) )
goto _unref_channel;
else
return TRUE;
}
else if ( !( fcntl( g_io_channel_unix_get_fd( channel ), F_GETFL ) != -1
|| errno != EBADF ) )
{
// bad file descriptor - occurs with stop on fast output
goto _unref_channel;
}
//GError *error = NULL;
gchar buf[2048];
if ( g_io_channel_read_chars( channel, buf, sizeof( buf ), &size, NULL ) ==
G_IO_STATUS_NORMAL && size > 0 )
{
//gtk_text_buffer_get_iter_at_mark( task->exec_err_buf, &iter,
// task->exec_mark_end );
if ( task->exec_type == VFS_EXEC_UDISKS
&& task->exec_show_error //prevent progress_cb opening taskmanager
&& g_strstr_len( buf, size, "ount failed:" ) )
{
// bug in udisks - exit status not set
if ( size > 81 && !strncmp( buf, "Mount failed: Error mounting: mount exited with exit code 1: helper failed with:\n", 81 ) ) //cleanup output - useless line
//gtk_text_buffer_insert( task->exec_err_buf, &iter, buf + 81, size - 81 );
append_add_log( task, buf + 81, size - 81 );
else
//gtk_text_buffer_insert( task->exec_err_buf, &iter, buf, size );
append_add_log( task, buf, size );
call_state_callback( task, VFS_FILE_TASK_ERROR );
}
else // no error
//gtk_text_buffer_insert( task->exec_err_buf, &iter, buf, size );
append_add_log( task, buf, size );
//task->err_count++; //notify of new output - does not indicate error for exec
}
else
printf("cb_exec_out_watch: g_io_channel_read_chars != G_IO_STATUS_NORMAL\n");
/*
// this hangs ????
GError *error = NULL;
gchar* buf;
printf("g_io_channel_read_to_end\n");
if ( g_io_channel_read_to_end( channel, &buf, &size, &error ) ==
G_IO_STATUS_NORMAL )
{
gtk_text_buffer_get_iter_at_mark( task->exec_err_buf, &iter,
task->exec_mark_end );
gtk_text_buffer_insert( task->exec_err_buf, &iter, buf, size );
g_free(buf );
task->err_count++;
task->ticks = 10000;
}
else
printf("cb_exec_out_watch: g_io_channel_read_to_end != G_IO_STATUS_NORMAL\n");
printf("g_io_channel_read_to_end DONE\n");
*/
/*
// this works except that it blocks when a linefeed is not in buffer
// eg echo -n aaaa unless NONBLOCK set
if ( g_io_channel_read_line( channel, &line, &size, NULL, NULL ) ==
G_IO_STATUS_NORMAL )
{
//printf(" line=%s", line );
gtk_text_buffer_get_iter_at_mark( task->exec_err_buf, &iter,
task->exec_mark_end );
if ( task->exec_type == VFS_EXEC_UDISKS && strstr( line, "ount failed:" ) )
{
// bug in udisks - exit status not set
call_state_callback( task, VFS_FILE_TASK_ERROR );
if ( !strstr( line, "helper failed with:" ) ) //cleanup udisks output
gtk_text_buffer_insert( task->exec_err_buf, &iter, line, -1 );
}
else
gtk_text_buffer_insert( task->exec_err_buf, &iter, line, -1 );
g_free(line );
task->err_count++; //signal new output
task->ticks = 10000;
}
else
printf("cb_exec_out_watch: g_io_channel_read_line != G_IO_STATUS_NORMAL\n");
*/
// don't enable this or last lines are lost
//if ( ( cond & G_IO_HUP ) ) // put here in case both G_IO_IN and G_IO_HUP
// goto _unref_channel;
return TRUE;
_unref_channel:
g_io_channel_unref( channel );
if ( channel == task->exec_channel_out )
task->exec_channel_out = 0;
else if ( channel == task->exec_channel_err )
task->exec_channel_err = 0;
if ( !task->exec_channel_out && !task->exec_channel_err && !task->exec_pid )
call_state_callback( task, VFS_FILE_TASK_FINISH );
return FALSE;
}
char* get_sha256sum( char* path )
{
char* sha256sum = g_find_program_in_path( "/usr/bin/sha256sum" );
if ( !sha256sum )
{
g_warning( _("Please install /usr/bin/sha256sum so I can improve your security while running root commands\n") );
return NULL;
}
char* stdout;
char* sum;
char* cmd = g_strdup_printf( "%s %s", sha256sum, path );
if ( g_spawn_command_line_sync( cmd, &stdout, NULL, NULL, NULL ) )
{
sum = g_strndup( stdout, 64 );
g_free( stdout );
if ( strlen( sum ) != 64 )
{
g_free( sum );
sum = NULL;
}
}
g_free( cmd );
return sum;
}
void vfs_file_task_exec_error( VFSFileTask* task, int errnox, char* action )
{
char* msg;
if ( errnox )
msg = g_strdup_printf( "%s\n%s\n", action, g_strerror( errnox ) );
else
msg = g_strdup_printf( "%s\n", action );
append_add_log( task, msg, -1 );
g_free( msg );
call_state_callback( task, VFS_FILE_TASK_ERROR );
}
static void vfs_file_task_exec( char* src_file, VFSFileTask* task )
{
// this function is now thread safe but is not currently run in
// another thread because gio adds watches to main loop thread anyway
char* su = NULL;
char* gsu = NULL;
char* str;
const char* tmp;
char* hex8;
char* hexname;
int result;
FILE* file;
char* terminal = NULL;
char** terminalv = NULL;
const char* value;
char* sum_script = NULL;
GtkWidget* parent = NULL;
gboolean success;
int i;
//printf("vfs_file_task_exec\n");
//task->exec_keep_tmp = TRUE;
g_mutex_lock( task->mutex );
value = task->current_dest; // variable value temp storage
task->current_dest = NULL;
if ( task->exec_browser )
parent = gtk_widget_get_toplevel( task->exec_browser );
else if ( task->exec_desktop )
parent = gtk_widget_get_toplevel( task->exec_desktop );
task->state = VFS_FILE_TASK_RUNNING;
string_copy_free( &task->current_file, src_file );
task->total_size = 0;
task->percent = 0;
g_mutex_unlock( task->mutex );
if ( should_abort( task ) )
return;
// need su?
if ( task->exec_as_user )
{
if ( geteuid() == 0 && !strcmp( task->exec_as_user, "root" ) )
{
// already root so no su
g_free( task->exec_as_user );
task->exec_as_user = NULL;
}
else
{
// get su programs
su = get_valid_su();
if ( !su )
{
str = _("Please configure a valid Terminal SU command in View|Preferences|Advanced");
g_warning ( str, NULL );
// do not use xset_msg_dialog if non-main thread
//vfs_file_task_exec_error( task, 0, str );
xset_msg_dialog( parent, GTK_MESSAGE_ERROR,
_("Terminal SU Not Available"), NULL, 0, str, NULL, NULL );
goto _exit_with_error_lean;
}
gsu = get_valid_gsu();
if ( !gsu )
{
str = _("Please configure a valid Graphical SU command in View|Preferences|Advanced");
g_warning ( str, NULL );
// do not use xset_msg_dialog if non-main thread
//vfs_file_task_exec_error( task, 0, str );
xset_msg_dialog( parent, GTK_MESSAGE_ERROR,
_("Graphical SU Not Available"), NULL, 0, str, NULL, NULL );
goto _exit_with_error_lean;
}
}
}
// make tmpdir
if ( geteuid() != 0 && task->exec_as_user && !strcmp( task->exec_as_user, "root" ) )
tmp = xset_get_shared_tmp_dir();
else
tmp = xset_get_user_tmp_dir();
if ( !tmp || ( tmp && !g_file_test( tmp, G_FILE_TEST_IS_DIR ) ) )
{
str = _("Cannot create temporary directory");
g_warning ( str, NULL );
// do not use xset_msg_dialog if non-main thread
//vfs_file_task_exec_error( task, 0, str );
xset_msg_dialog( parent, GTK_MESSAGE_ERROR,
_("Error"), NULL, 0, str, NULL, NULL );
goto _exit_with_error_lean;
}
// get terminal if needed
if ( !task->exec_terminal && task->exec_as_user )
{
if ( !strcmp( gsu, "/bin/su" ) || !strcmp( gsu, "/usr/bin/sudo" ) )
{
// using a non-GUI gsu so run in terminal
if ( su )
g_free( su );
su = strdup( gsu );
task->exec_terminal = TRUE;
}
}
if ( task->exec_terminal )
{
// get terminal
str = g_strdup( xset_get_s( "main_terminal" ) );
g_strstrip( str );
terminalv = g_strsplit( str, " ", 0 );
g_free( str );
if ( terminalv && terminalv[0] && terminalv[0][0] != '\0' )
terminal = g_find_program_in_path( terminalv[0] );
if ( !( terminal && terminal[0] == '/' ) )
{
str = _("Please set a valid terminal program in View|Preferences|Advanced");
g_warning ( str, NULL );
// do not use xset_msg_dialog if non-main thread
//vfs_file_task_exec_error( task, 0, str );
xset_msg_dialog( parent, GTK_MESSAGE_ERROR,
_("Terminal Not Available"), NULL, 0, str, NULL, NULL );
goto _exit_with_error_lean;
}
}
// Build exec script
if ( !task->exec_direct )
{
// get script name
do
{
if ( task->exec_script )
g_free( task->exec_script );
hex8 = randhex8();
hexname = g_strdup_printf( "%s-tmp.sh", hex8 );
task->exec_script = g_build_filename( tmp, hexname, NULL );
g_free( hexname );
g_free( hex8 );
}
while ( g_file_test( task->exec_script, G_FILE_TEST_EXISTS ) );
// open file
file = fopen( task->exec_script, "w" );
if ( !file ) goto _exit_with_error;
// build - header
result = fputs( "#!/bin/bash\n#\n# Temporary SpaceFM exec script - it is safe to delete this file\n\n", file );
if ( result < 0 ) goto _exit_with_error;
// build - exports
if ( task->exec_export && ( task->exec_browser || task->exec_desktop ) )
{
if ( task->exec_browser )
success = main_write_exports( task, value, file );
else
#ifdef DESKTOP_INTEGRATION
success = desktop_write_exports( task, value, file );
#else
success = FALSE;
#endif
if ( !success ) goto _exit_with_error;
}
else
{
if ( task->exec_export && !task->exec_browser && !task->exec_desktop )
{
task->exec_export = FALSE;
g_warning( "exec_export set without exec_browser/exec_desktop" );
}
}
// build - run
result = fprintf( file, "# run\n\nif [ \"$1\" == \"run\" ]; then\n\n" );
if ( result < 0 ) goto _exit_with_error;
// build - write root settings
if ( task->exec_write_root && geteuid() != 0 )
{
const char* this_user = g_get_user_name();
if ( this_user && this_user[0] != '\0' )
{
char* root_set_path= g_strdup_printf(
"/etc/spacefm/%s-as-root", this_user );
write_root_settings( file, root_set_path );
g_free( root_set_path );
//g_free( this_user ); DON'T
}
else
{
char* root_set_path= g_strdup_printf(
"/etc/spacefm/%d-as-root", geteuid() );
write_root_settings( file, root_set_path );
g_free( root_set_path );
}
}
// build - export vars
if ( task->exec_export )
result = fprintf( file, "export fm_import='source %s'\n", task->exec_script );
else
result = fprintf( file, "export fm_import=''\n" );
if ( result < 0 ) goto _exit_with_error;
result = fprintf( file, "export fm_source='%s'\n\n", task->exec_script );
if ( result < 0 ) goto _exit_with_error;
// build - trap rm
if ( !task->exec_keep_tmp && terminal &&
( strstr( terminal, "lxterminal" ) ||
strstr( terminal, "urxvtc" ) || // sure no option avail?
strstr( terminal, "konsole" ) ) )
{
// these terminals provide no option to start a new instance, child
// exit occurs immediately so can't delete tmp files
// so keep files and let trap delete on exit
// *these terminals will not work properly with Run As Task
// note for konsole: if you create a link to it and execute the
// link, it will start a new instance (might also work for lxterminal?)
// http://www.linuxjournal.com/content/start-and-control-konsole-dbus
result = fprintf( file, "trap \"rm -f %s; exit\" EXIT SIGINT SIGTERM SIGQUIT SIGHUP\n\n",
task->exec_script );
if ( result < 0 ) goto _exit_with_error;
task->exec_keep_tmp = TRUE;
}
else if ( !task->exec_keep_tmp && geteuid() != 0 && task->exec_as_user
&& !strcmp( task->exec_as_user, "root" ) )
{
// run as root command, clean up
result = fprintf( file, "trap \"rm -f %s; exit\" EXIT SIGINT SIGTERM SIGQUIT SIGHUP\n\n",
task->exec_script );
if ( result < 0 ) goto _exit_with_error;
}
// build - command
printf("\nTASK_COMMAND=%s\n", task->exec_command );
result = fprintf( file, "%s\nfm_err=$?\n", task->exec_command );
if ( result < 0 ) goto _exit_with_error;
// build - press enter to close
if ( terminal && task->exec_keep_terminal )
{
if ( geteuid() == 0 ||
( task->exec_as_user && !strcmp( task->exec_as_user, "root" ) ) )
result = fprintf( file, "\necho\necho -n '%s: '\nread s",
"[ Finished ] Press Enter to close" );
else
{
result = fprintf( file, "\necho\necho -n '%s: '\nread s\nif [ \"$s\" = 's' ]; then\n if [ \"$(whoami)\" = \"root\" ]; then\n echo\n echo '[ %s ]'\n fi\n echo\n /bin/bash\nfi\n\n", "[ Finished ] Press Enter to close or s + Enter for a shell", "You are ROOT" );
}
if ( result < 0 ) goto _exit_with_error;
}
result = fprintf( file, "\nexit $fm_err\nfi\n" );
if ( result < 0 ) goto _exit_with_error;
// close file
result = fclose( file );
file = NULL;
if ( result ) goto _exit_with_error;
// set permissions
if ( task->exec_as_user && strcmp( task->exec_as_user, "root" ) )
// run as a non-root user
chmod( task->exec_script,
S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH );
else
// run as self or as root
chmod( task->exec_script, S_IRWXU );
if ( task->exec_as_user && geteuid() != 0 )
sum_script = get_sha256sum( task->exec_script );
}
task->percent = 50;
// Spawn
GPid pid;
gchar *argv[35];
gint out, err;
int a = 0;
char* use_su;
gboolean single_arg = FALSE;
char* auth = NULL;
if ( terminal )
{
// terminal
argv[a++] = terminal;
// terminal options - add <=9 options
for ( i = 0; terminalv[i]; i++ )
{
if ( i == 0 || a > 9 || terminalv[i][0] == '\0' )
g_free( terminalv[i] );
else
argv[a++] = terminalv[i]; // steal
}
g_free( terminalv ); // all strings freed or stolen
terminalv = NULL;
// automatic terminal options
if ( strstr( terminal, "roxterm" ) )
{
argv[a++] = g_strdup_printf( "--disable-sm" );
argv[a++] = g_strdup_printf( "--separate" );
}
else if ( strstr( terminal, "xfce4-terminal" )
|| g_str_has_suffix( terminal, "/terminal" ) )
argv[a++] = g_strdup_printf( "--disable-server" );
else if ( strstr( terminal, "gnome-terminal" ) )
argv[a++] = g_strdup_printf( "--disable-factory" );
if ( strstr( terminal, "xfce4-terminal" )
|| strstr( terminal, "gnome-terminal" )
|| strstr( terminal, "terminator" )
|| g_str_has_suffix( terminal, "/terminal" ) ) // xfce
argv[a++] = g_strdup( "-x" );
else
argv[a++] = g_strdup( "-e" );
use_su = su;
}
else
use_su = gsu;
if ( task->exec_as_user )
{
// su
argv[a++] = g_strdup( use_su );
if ( strcmp( task->exec_as_user, "root" ) )
{
if ( strcmp( use_su, "/bin/su" ) )
argv[a++] = g_strdup( "-u" );
argv[a++] = g_strdup( task->exec_as_user );
}
if ( !strcmp( use_su, "/usr/bin/gksu" ) || !strcmp( use_su, "/usr/bin/gksudo" ) )
{
// gksu*
argv[a++] = g_strdup( "-g" );
argv[a++] = g_strdup( "-D" );
argv[a++] = g_strdup( "SpaceFM Command" );
single_arg = TRUE;
}
else if ( strstr( use_su, "kdesu" ) )
{
// kdesu kdesudo
argv[a++] = g_strdup( "-d" );
argv[a++] = g_strdup( "-c" );
single_arg = TRUE;
}
else if ( !strcmp( use_su, "/bin/su" ) )
{
// /bin/su
argv[a++] = g_strdup( "-s" );
argv[a++] = g_strdup( "/bin/bash" ); //shell spec
argv[a++] = g_strdup( "-c" );
single_arg = TRUE;
}
else if ( !strcmp( use_su, "/usr/bin/gnomesu" )
|| !strcmp( use_su, "/usr/bin/xdg-su" ) )
{
argv[a++] = g_strdup( "-c" );
single_arg = TRUE;
}
}
if ( sum_script )
{
// spacefm-auth exists?
auth = g_find_program_in_path( "spacefm-auth" );
if ( !auth )
{
g_free( sum_script );
sum_script = NULL;
g_warning( _("spacefm-auth not found in path - this reduces your security") );
}
}
if ( sum_script && auth )
{
// spacefm-auth
if ( single_arg )
{
argv[a++] = g_strdup_printf( "/bin/bash %s%s %s %s",
auth,
!strcmp( task->exec_as_user, "root" ) ? " root" : "",
task->exec_script,
sum_script );
g_free( auth );
}
else
{
argv[a++] = g_strdup( "/bin/bash" );
argv[a++] = auth;
if ( !strcmp( task->exec_as_user, "root" ) )
argv[a++] = g_strdup( "root" );
argv[a++] = g_strdup( task->exec_script );
argv[a++] = g_strdup( sum_script );
}
g_free( sum_script );
}
else if ( task->exec_direct )
{
// add direct args - not currently used
if ( single_arg )
{
argv[a++] = g_strjoinv( " ", &task->exec_argv[0] );
for ( i = 0; i < 7; i++ )
{
if ( !task->exec_argv[i] )
break;
g_free( task->exec_argv[i] );
}
}
else
{
for ( i = 0; i < 7; i++ )
{
if ( !task->exec_argv[i] )
break;
argv[a++] = task->exec_argv[i];
}
}
}
else
{
if ( single_arg )
{
argv[a++] = g_strdup_printf( "/bin/bash %s run", task->exec_script );
}
else
{
argv[a++] = g_strdup( "/bin/bash" );
argv[a++] = g_strdup( task->exec_script );
argv[a++] = g_strdup( "run" );
}
}
argv[a++] = NULL;
if ( su )
g_free( su );
if ( gsu )
g_free( gsu );
printf( "SPAWN=" );
i = 0;
while ( argv[i] )
{
printf( "%s%s", i == 0 ? "" : " ", argv[i] );
i++;
}
printf( "\n" );
char* first_arg = g_strdup( argv[0] );
if ( task->exec_sync )
{
result = g_spawn_async_with_pipes( task->dest_dir, argv, NULL,
G_SPAWN_DO_NOT_REAP_CHILD, NULL,
NULL, &pid, NULL, &out, &err, NULL );
}
else
{
result = g_spawn_async_with_pipes( task->dest_dir, argv, NULL,
G_SPAWN_DO_NOT_REAP_CHILD, NULL,
NULL, &pid, NULL, NULL, NULL, NULL );
}
if( !result )
{
printf(" result=%d ( %s )\n", errno, g_strerror( errno ));
if ( !task->exec_keep_tmp && task->exec_sync )
{
if ( task->exec_script )
unlink( task->exec_script );
}
str = g_strdup_printf( _("Error executing '%s'\nSee stdout (run spacefm in a terminal) for debug info"), first_arg );
g_free( first_arg );
vfs_file_task_exec_error( task, errno, str );
g_free( str );
call_state_callback( task, VFS_FILE_TASK_FINISH );
return;
}
else
printf( " pid = %d\n", pid );
g_free( first_arg );
if ( !task->exec_sync )
{
// catch termination to delete tmp
if ( !task->exec_keep_tmp && !task->exec_direct && task->exec_script )
{
// task can be destroyed while this watch is still active
g_child_watch_add( pid, (GChildWatchFunc)cb_exec_child_cleanup,
g_strdup( task->exec_script ) );
}
call_state_callback( task, VFS_FILE_TASK_FINISH );
return;
}
task->exec_pid = pid;
// catch termination (always is run in the main loop thread)
guint child_watch = g_child_watch_add( pid,
(GChildWatchFunc)cb_exec_child_watch, task );
// create channels for output
fcntl( out, F_SETFL,O_NONBLOCK );
fcntl( err, F_SETFL,O_NONBLOCK );
task->exec_channel_out = g_io_channel_unix_new( out );
task->exec_channel_err = g_io_channel_unix_new( err );
g_io_channel_set_close_on_unref( task->exec_channel_out, TRUE );
g_io_channel_set_close_on_unref( task->exec_channel_err, TRUE );
// Add watches to channels
// These are run in the main loop thread so use G_PRIORITY_LOW to not
// interfere with g_idle_add in vfs-dir/vfs-async-task etc
// "Use this for very low priority background tasks. It is not used within
// GLib or GTK+."
g_io_add_watch_full( task->exec_channel_out, G_PRIORITY_LOW,
G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR, //want ERR?
(GIOFunc)cb_exec_out_watch, task, NULL );
g_io_add_watch_full( task->exec_channel_err, G_PRIORITY_LOW,
G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR, //want ERR?
(GIOFunc)cb_exec_out_watch, task, NULL );
// running
task->state = VFS_FILE_TASK_RUNNING;
/* enable if this function is not in main loop thread
// wait
task->exec_cond = g_cond_new();
g_mutex_lock( task->mutex );
g_cond_wait( task->exec_cond, task->mutex );
g_cond_free( task->exec_cond );
task->exec_cond = NULL;
g_source_remove( child_watch );
g_mutex_unlock( task->mutex );
*/
//printf("vfs_file_task_exec DONE\n");
return; // exit thread
// out and err can/should be closed too?
_exit_with_error:
vfs_file_task_exec_error( task, errno, _("Error writing temporary file") );
if ( file )
fclose( file );
if ( !task->exec_keep_tmp )
{
if ( task->exec_script )
unlink( task->exec_script );
}
_exit_with_error_lean:
g_strfreev( terminalv );
g_free( terminal );
g_free( su );
g_free( gsu );
call_state_callback( task, VFS_FILE_TASK_FINISH );
//printf("vfs_file_task_exec DONE ERROR\n");
}
gboolean on_size_timeout( VFSFileTask* task )
{
if ( !task->abort )
task->state = VFS_FILE_TASK_SIZE_TIMEOUT;
return FALSE;
}
static gpointer vfs_file_task_thread ( VFSFileTask* task )
//void * vfs_file_task_thread ( void * ptr )
{
GList * l;
struct stat64 file_stat;
dev_t dest_dev = 0;
off64_t size;
GFunc funcs[] = {( GFunc ) vfs_file_task_move,
( GFunc ) vfs_file_task_copy,
( GFunc ) vfs_file_task_move, /* trash */
( GFunc ) vfs_file_task_delete,
( GFunc ) vfs_file_task_link,
( GFunc ) vfs_file_task_chown_chmod,
( GFunc ) vfs_file_task_exec};
//VFSFileTask* task = (VFSFileTask*)ptr;
if ( task->type < VFS_FILE_TASK_MOVE
|| task->type >= VFS_FILE_TASK_LAST )
goto _exit_thread;
g_mutex_lock( task->mutex );
task->state = VFS_FILE_TASK_RUNNING;
string_copy_free( &task->current_file,
task->src_paths ? (char*)task->src_paths->data : NULL );
task->total_size = 0;
if( task->type == VFS_FILE_TASK_TRASH )
{
task->dest_dir = g_build_filename( vfs_get_trash_dir(), "files", NULL );
/* Create the trash dir if it doesn't exist */
if( ! g_file_test( task->dest_dir, G_FILE_TEST_EXISTS ) )
g_mkdir_with_parents( task->dest_dir, 0700 );
}
g_mutex_unlock( task->mutex );
if ( task->abort )
goto _exit_thread;
/* Calculate total size of all files */
guint size_timeout = 0;
if ( task->recursive )
{
// start timer to limit the amount of time to spend on this - can be
// VERY slow for network filesystems
size_timeout = g_timeout_add_seconds( 5,
( GSourceFunc ) on_size_timeout, task );
for ( l = task->src_paths; l; l = l->next )
{
if ( lstat64( (char*)l->data, &file_stat ) == -1 )
{
// don't report error here since its reported later
//vfs_file_task_error( task, errno, _("Accessing"), (char*)l->data );
}
else
{
size = 0;
get_total_size_of_dir( task, ( char* ) l->data, &size, &file_stat );
g_mutex_lock( task->mutex );
task->total_size += size;
g_mutex_unlock( task->mutex );
}
if ( task->abort )
goto _exit_thread;
if ( task->state == VFS_FILE_TASK_SIZE_TIMEOUT )
break;
}
}
else if ( task->type != VFS_FILE_TASK_EXEC )
{
// start timer to limit the amount of time to spend on this - can be
// VERY slow for network filesystems
size_timeout = g_timeout_add_seconds( 5,
( GSourceFunc ) on_size_timeout, task );
if ( task->type != VFS_FILE_TASK_CHMOD_CHOWN )
{
if ( !( task->dest_dir && stat64( task->dest_dir, &file_stat ) == 0 ) )
{
vfs_file_task_error( task, errno, _("Accessing"), task->dest_dir );
task->abort = TRUE;
goto _exit_thread;
}
dest_dev = file_stat.st_dev;
}
for ( l = task->src_paths; l; l = l->next )
{
if ( lstat64( ( char* ) l->data, &file_stat ) == -1 )
{
// don't report error here since it's reported later
//vfs_file_task_error( task, errno, _("Accessing"), ( char* ) l->data );
}
else
{
/*
// sfm why does this code change task->recursive back and forth?
if ( S_ISLNK( file_stat.st_mode ) ) // Don't do deep copy for symlinks
task->recursive = FALSE;
else if ( task->type == VFS_FILE_TASK_MOVE || task->type == VFS_FILE_TASK_TRASH )
task->recursive = ( file_stat.st_dev != dest_dev );
else
task->recursive = FALSE;
if ( task->recursive )
*/
if ( ( task->type == VFS_FILE_TASK_MOVE ||
task->type == VFS_FILE_TASK_TRASH )
&& file_stat.st_dev != dest_dev )
{
// recursive size
size = 0;
get_total_size_of_dir( task, ( char* ) l->data, &size, &file_stat );
g_mutex_lock( task->mutex );
task->total_size += size;
g_mutex_unlock( task->mutex );
}
else
{
g_mutex_lock( task->mutex );
task->total_size += file_stat.st_size;
g_mutex_unlock( task->mutex );
}
}
if ( task->abort )
goto _exit_thread;
if ( task->state == VFS_FILE_TASK_SIZE_TIMEOUT )
break;
}
}
if ( task->dest_dir && stat64( task->dest_dir, &file_stat ) != -1 )
add_task_dev( task, file_stat.st_dev );
if ( task->abort )
goto _exit_thread;
// cancel the timer
if ( size_timeout )
g_source_remove_by_user_data( task );
if ( task->state_pause == VFS_FILE_TASK_QUEUE )
{
if ( task->state != VFS_FILE_TASK_SIZE_TIMEOUT && xset_get_b( "task_q_smart" ) )
{
// make queue exception for smaller tasks
off64_t exlimit;
if ( task->type == VFS_FILE_TASK_MOVE ||
task->type == VFS_FILE_TASK_COPY )
exlimit = 10485760; // 10M
else if ( task->type == VFS_FILE_TASK_DELETE ||
task->type == VFS_FILE_TASK_TRASH )
exlimit = 5368709120; // 5G
else
exlimit = 0; // always exception for other types
if ( !exlimit || task->total_size < exlimit )
task->state_pause = VFS_FILE_TASK_RUNNING;
}
// device list is populated so signal queue start
task->queue_start = TRUE;
}
if ( task->state == VFS_FILE_TASK_SIZE_TIMEOUT )
{
append_add_log( task, _("Timed out calculating total size\n"), -1 );
task->total_size = 0;
}
task->state = VFS_FILE_TASK_RUNNING;
if ( should_abort( task ) )
goto _exit_thread;
g_list_foreach( task->src_paths,
funcs[ task->type ],
task );
_exit_thread:
task->state = VFS_FILE_TASK_RUNNING;
if ( size_timeout )
g_source_remove_by_user_data( task );
if ( task->state_cb )
{
call_state_callback( task, VFS_FILE_TASK_FINISH );
}
/* else
{
// FIXME: Will this cause any problem?
task->thread = NULL;
vfs_file_task_free( task );
}
*/
return NULL;
}
/*
* source_files sould be a newly allocated list, and it will be
* freed after file operation has been completed
*/
VFSFileTask* vfs_task_new ( VFSFileTaskType type,
GList* src_files,
const char* dest_dir )
{
VFSFileTask * task;
task = g_slice_new0( VFSFileTask );
task->type = type;
task->src_paths = src_files;
task->dest_dir = g_strdup( dest_dir );
task->current_file = NULL;
task->current_dest = NULL;
task->recursive = ( task->type == VFS_FILE_TASK_COPY ||
task->type == VFS_FILE_TASK_DELETE );
task->err_count = 0;
task->abort = FALSE;
task->error_first = TRUE;
task->custom_percent = FALSE;
task->exec_type = VFS_EXEC_NORMAL;
task->exec_action = NULL;
task->exec_command = NULL;
task->exec_sync = TRUE;
task->exec_popup = FALSE;
task->exec_show_output = FALSE;
task->exec_show_error = FALSE;
task->exec_terminal = FALSE;
task->exec_keep_terminal = FALSE;
task->exec_export = FALSE;
task->exec_direct = FALSE;
task->exec_as_user = NULL;
task->exec_icon = NULL;
task->exec_script = NULL;
task->exec_keep_tmp = FALSE;
task->exec_browser = NULL;
task->exec_desktop = NULL;
task->exec_pid = 0;
task->exec_is_error = FALSE;
task->exec_scroll_lock = FALSE;
task->exec_write_root = FALSE;
task->exec_set = NULL;
task->exec_cond = NULL;
task->exec_ptask = NULL;
task->pause_cond = NULL;
task->state_pause = VFS_FILE_TASK_RUNNING;
task->queue_start = FALSE;
task->devs = NULL;
task->mutex = g_mutex_new();
GtkTextIter iter;
task->add_log_buf = gtk_text_buffer_new( NULL );
task->add_log_end = gtk_text_mark_new( NULL, FALSE );
gtk_text_buffer_get_end_iter( task->add_log_buf, &iter);
gtk_text_buffer_add_mark( task->add_log_buf, task->add_log_end, &iter );
task->start_time = time( NULL );
task->last_speed = 0;
task->last_progress = 0;
task->current_item = 0;
task->timer = g_timer_new();
task->last_elapsed = 0;
return task;
}
/* Set some actions for chmod, this array will be copied
* and stored in VFSFileTask */
void vfs_file_task_set_chmod( VFSFileTask* task,
guchar* chmod_actions )
{
task->chmod_actions = g_slice_alloc( sizeof( guchar ) * N_CHMOD_ACTIONS );
memcpy( ( void* ) task->chmod_actions, ( void* ) chmod_actions,
sizeof( guchar ) * N_CHMOD_ACTIONS );
}
void vfs_file_task_set_chown( VFSFileTask* task,
uid_t uid, gid_t gid )
{
task->uid = uid;
task->gid = gid;
}
void vfs_file_task_run ( VFSFileTask* task )
{
if ( task->type != VFS_FILE_TASK_EXEC )
{
#ifdef HAVE_HAL
task->avoid_changes = FALSE;
#else
if ( task->type == VFS_FILE_TASK_CHMOD_CHOWN && task->src_paths->data )
{
char* dir = g_path_get_dirname( (char*)task->src_paths->data );
task->avoid_changes = vfs_volume_dir_avoid_changes( dir );
g_free( dir );
}
else
task->avoid_changes = vfs_volume_dir_avoid_changes( task->dest_dir );
#endif
task->thread = g_thread_create( ( GThreadFunc ) vfs_file_task_thread,
task, TRUE, NULL );
//task->thread = g_thread_create_full( ( GThreadFunc ) vfs_file_task_thread,
// task, 0, TRUE, TRUE, G_THREAD_PRIORITY_NORMAL, NULL );
//pthread_t tid;
//task->thread = pthread_create( &tid, NULL, vfs_file_task_thread, task );
}
else
{
// don't use another thread for exec since gio adds watches to main
// loop thread anyway
task->thread = NULL;
vfs_file_task_exec( (char*)task->src_paths->data, task );
}
}
void vfs_file_task_try_abort ( VFSFileTask* task )
{
task->abort = TRUE;
if ( task->pause_cond )
{
g_mutex_lock( task->mutex );
g_cond_broadcast( task->pause_cond );
task->last_elapsed = g_timer_elapsed( task->timer, NULL );
task->last_progress = task->progress;
task->last_speed = 0;
g_mutex_unlock( task->mutex );
}
else
{
g_mutex_lock( task->mutex );
task->last_elapsed = g_timer_elapsed( task->timer, NULL );
task->last_progress = task->progress;
task->last_speed = 0;
g_mutex_unlock( task->mutex );
}
task->state_pause = VFS_FILE_TASK_RUNNING;
}
void vfs_file_task_abort ( VFSFileTask* task )
{
task->abort = TRUE;
/* Called from another thread */
if ( task->thread && g_thread_self() != task->thread
&& task->type != VFS_FILE_TASK_EXEC )
{
g_thread_join( task->thread );
task->thread = NULL;
}
}
void vfs_file_task_free ( VFSFileTask* task )
{
if ( task->src_paths )
{
g_list_foreach( task->src_paths, ( GFunc ) g_free, NULL );
g_list_free( task->src_paths );
}
g_free( task->dest_dir );
g_free( task->current_file );
g_free( task->current_dest );
g_slist_free( task->devs );
if ( task->chmod_actions )
g_slice_free1( sizeof( guchar ) * N_CHMOD_ACTIONS,
task->chmod_actions );
if ( task->exec_action )
g_free(task->exec_action );
if ( task->exec_as_user )
g_free(task->exec_as_user );
if ( task->exec_command )
g_free(task->exec_command );
if ( task->exec_script )
g_free(task->exec_script );
g_mutex_free( task->mutex );
gtk_text_buffer_set_text( task->add_log_buf, "", -1 );
g_object_unref( task->add_log_buf );
g_timer_destroy( task->timer );
g_slice_free( VFSFileTask, task );
}
void add_task_dev( VFSFileTask* task, dev_t dev )
{
dev_t parent = 0;
if ( !g_slist_find( task->devs, GUINT_TO_POINTER( dev ) ) )
{
#ifndef HAVE_HAL
parent = get_device_parent( dev );
#endif
//printf("add_task_dev %d:%d\n", major(dev), minor(dev) );
g_mutex_lock( task->mutex );
task->devs = g_slist_append( task->devs, GUINT_TO_POINTER( dev ) );
if ( parent && !g_slist_find( task->devs, GUINT_TO_POINTER( parent ) ) )
{
//printf("add_task_dev PARENT %d:%d\n", major(parent), minor(parent) );
task->devs = g_slist_append( task->devs, GUINT_TO_POINTER( parent ) );
}
g_mutex_unlock( task->mutex );
}
}
/*
* void get_total_size_of_dir( const char* path, off_t* size )
* Recursively count total size of all files in the specified directory.
* If the path specified is a file, the size of the file is directly returned.
* cancel is used to cancel the operation. This function will check the value
* pointed by cancel in every iteration. If cancel is set to TRUE, the
* calculation is cancelled.
* NOTE: *size should be set to zero before calling this function.
*/
void get_total_size_of_dir( VFSFileTask* task,
const char* path,
off64_t* size,
struct stat64* have_stat )
{
GDir * dir;
const char* name;
char* full_path;
struct stat64 file_stat;
if ( task->abort )
return;
if ( have_stat )
file_stat = *have_stat;
else if ( lstat64( path, &file_stat ) == -1 )
return;
*size += file_stat.st_size;
// remember device for smart queue
if ( !task->devs )
add_task_dev( task, file_stat.st_dev );
else if ( (uint)file_stat.st_dev != GPOINTER_TO_UINT( task->devs->data ) )
add_task_dev( task, file_stat.st_dev );
// Don't follow symlinks
if ( S_ISLNK( file_stat.st_mode ) || !S_ISDIR( file_stat.st_mode ) )
return;
dir = g_dir_open( path, 0, NULL );
if ( dir )
{
while ( (name = g_dir_read_name( dir )) )
{
if ( task->state == VFS_FILE_TASK_SIZE_TIMEOUT || task->abort )
break;
full_path = g_build_filename( path, name, NULL );
if ( lstat64( full_path, &file_stat ) != -1 )
{
if ( S_ISDIR( file_stat.st_mode ) )
get_total_size_of_dir( task, full_path, size, &file_stat );
else
*size += file_stat.st_size;
}
g_free(full_path );
}
g_dir_close( dir );
}
}
void vfs_file_task_set_recursive( VFSFileTask* task, gboolean recursive )
{
task->recursive = recursive;
}
void vfs_file_task_set_overwrite_mode( VFSFileTask* task,
VFSFileTaskOverwriteMode mode )
{
task->overwrite_mode = mode;
}
void vfs_file_task_set_progress_callback( VFSFileTask* task,
VFSFileTaskProgressCallback cb,
gpointer user_data )
{
task->progress_cb = cb;
task->progress_cb_data = user_data;
}
void vfs_file_task_set_state_callback( VFSFileTask* task,
VFSFileTaskStateCallback cb,
gpointer user_data )
{
task->state_cb = cb;
task->state_cb_data = user_data;
}
void vfs_file_task_error( VFSFileTask* task, int errnox, const char* action,
const char* target )
{
task->error = errnox;
char* msg = g_strdup_printf( _("\n%s %s\nError: %s\n"), action, target,
g_strerror( errnox ) );
append_add_log( task, msg, -1 );
g_free( msg );
call_state_callback( task, VFS_FILE_TASK_ERROR );
}
|
164 | ./spacefm/src/vfs/vfs-async-task.c | /*
* vfs-async-task.c
*
* Copyright 2008 PCMan <pcman.tw@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "vfs-async-task.h"
#include <gtk/gtk.h>
static void vfs_async_task_class_init (VFSAsyncTaskClass *klass);
static void vfs_async_task_init (VFSAsyncTask *task);
static void vfs_async_task_finalize (GObject *object);
static void vfs_async_task_finish( VFSAsyncTask* task, gboolean is_cancelled );
static void vfs_async_thread_cleanup( VFSAsyncTask* task, gboolean finalize );
void vfs_async_task_real_cancel( VFSAsyncTask* task, gboolean finalize );
/* Local data */
static GObjectClass *parent_class = NULL;
enum {
FINISH_SIGNAL,
N_SIGNALS
};
static guint signals[ N_SIGNALS ] = { 0 };
GType vfs_async_task_get_type(void)
{
static GType self_type = 0;
if (! self_type)
{
static const GTypeInfo self_info =
{
sizeof(VFSAsyncTaskClass),
NULL, /* base_init */
NULL, /* base_finalize */
(GClassInitFunc)vfs_async_task_class_init,
NULL, /* class_finalize */
NULL, /* class_data */
sizeof(VFSAsyncTask),
0,
(GInstanceInitFunc)vfs_async_task_init,
NULL /* value_table */
};
self_type = g_type_register_static(G_TYPE_OBJECT, "VFSAsyncTask", &self_info, 0); }
return self_type;
}
static void vfs_async_task_class_init(VFSAsyncTaskClass *klass)
{
GObjectClass *g_object_class;
g_object_class = G_OBJECT_CLASS(klass);
g_object_class->finalize = vfs_async_task_finalize;
parent_class = (GObjectClass*)g_type_class_peek(G_TYPE_OBJECT);
klass->finish = vfs_async_task_finish;
signals[ FINISH_SIGNAL ] =
g_signal_new ( "finish",
G_TYPE_FROM_CLASS ( klass ),
G_SIGNAL_RUN_FIRST,
G_STRUCT_OFFSET ( VFSAsyncTaskClass, finish ),
NULL, NULL,
g_cclosure_marshal_VOID__BOOLEAN,
G_TYPE_NONE, 1, G_TYPE_BOOLEAN );
}
static void vfs_async_task_init(VFSAsyncTask *task)
{
task->lock = g_mutex_new();
}
VFSAsyncTask* vfs_async_task_new( VFSAsyncFunc task_func, gpointer user_data )
{
VFSAsyncTask* task = (VFSAsyncTask*)g_object_new(VFS_ASYNC_TASK_TYPE, NULL);
task->func = task_func;
task->user_data = user_data;
return (VFSAsyncTask*)task;
}
gpointer vfs_async_task_get_data( VFSAsyncTask* task )
{
return task->user_data;
}
void vfs_async_task_set_data( VFSAsyncTask* task, gpointer user_data )
{
task->user_data = user_data;
}
gpointer vfs_async_task_get_return_value( VFSAsyncTask* task )
{
return task->ret_val;
}
void vfs_async_task_finalize(GObject *object)
{
VFSAsyncTask *task;
/* FIXME: destroying the object without calling vfs_async_task_cancel
currently induces unknown errors. */
task = (VFSAsyncTask*)object;
/* finalize = TRUE, inhibit the emission of signals */
vfs_async_task_real_cancel( task, TRUE );
vfs_async_thread_cleanup( task, TRUE );
g_mutex_free( task->lock );
task->lock = NULL;
if (G_OBJECT_CLASS(parent_class)->finalize)
(* G_OBJECT_CLASS(parent_class)->finalize)(object);
}
gboolean on_idle( gpointer _task )
{
VFSAsyncTask *task = VFS_ASYNC_TASK(_task);
//GDK_THREADS_ENTER(); // not needed because this runs in main thread
vfs_async_thread_cleanup( task, FALSE );
//GDK_THREADS_LEAVE();
return TRUE; /* the idle handler is removed in vfs_async_thread_cleanup. */
}
gpointer vfs_async_task_thread( gpointer _task )
{
VFSAsyncTask *task = VFS_ASYNC_TASK(_task);
gpointer ret = NULL;
ret = task->func( task, task->user_data );
vfs_async_task_lock( task );
task->idle_id = g_idle_add( on_idle, task ); // runs in main loop thread
task->ret_val = ret;
task->finished = TRUE;
vfs_async_task_unlock( task );
return ret;
}
void vfs_async_task_execute( VFSAsyncTask* task )
{
task->thread = g_thread_create( vfs_async_task_thread, task, TRUE, NULL );
}
void vfs_async_thread_cleanup( VFSAsyncTask* task, gboolean finalize )
{
if( task->idle_id )
{
g_source_remove( task->idle_id );
task->idle_id = 0;
}
if( G_LIKELY( task->thread ) )
{
g_thread_join( task->thread );
task->thread = NULL;
task->finished = TRUE;
/* Only emit the signal when we are not finalizing.
Emitting signal on an object during destruction is not allowed. */
if( G_LIKELY( ! finalize ) )
g_signal_emit( task, signals[ FINISH_SIGNAL ], 0, task->cancelled );
}
}
void vfs_async_task_real_cancel( VFSAsyncTask* task, gboolean finalize )
{
if( ! task->thread )
return;
/*
* NOTE: Well, this dirty hack is needed. Since the function is always
* called from main thread, the GTK+ main loop may have this gdk lock locked
* when this function gets called. However, our task running in another thread
* might need to use GTK+, too. If we don't release the gdk lock in main thread
* temporarily, the task in another thread will be blocked due to waiting for
* the gdk lock locked by our main thread, and hence cannot be finished.
* Then we'll end up in endless waiting for that thread to finish, the so-called deadlock.
*
* The doc of GTK+ really sucks. GTK+ use this GTK_THREADS_ENTER everywhere internally,
* but the behavior of the lock is not well-documented. So it's very difficult for use
* to get things right.
*/
//sfm this deadlocks on quick dir change
//GDK_THREADS_LEAVE();
vfs_async_task_lock( task );
task->cancel = TRUE;
vfs_async_task_unlock( task );
vfs_async_thread_cleanup( task, finalize );
task->cancelled = TRUE;
//GDK_THREADS_ENTER();
}
void vfs_async_task_cancel( VFSAsyncTask* task )
{
vfs_async_task_real_cancel( task, FALSE );
}
void vfs_async_task_lock( VFSAsyncTask* task )
{
g_mutex_lock( task->lock );
}
void vfs_async_task_unlock( VFSAsyncTask* task )
{
g_mutex_unlock( task->lock );
}
void vfs_async_task_finish( VFSAsyncTask* task, gboolean is_cancelled )
{
/* default handler of "finish" signal. */
}
gboolean vfs_async_task_is_finished( VFSAsyncTask* task )
{
return task->finished;
}
gboolean vfs_async_task_is_cancelled( VFSAsyncTask* task )
{
return task->cancel;
}
|
165 | ./spacefm/src/vfs/vfs-utils.c | /*
* vfs-utils.c
*
* Copyright 2008 PCMan <pcman.tw@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <glib/gi18n.h>
#include <string.h>
#include "vfs-utils.h"
#include "settings.h" //MOD
GdkPixbuf* vfs_load_icon( GtkIconTheme* theme, const char* icon_name, int size )
{
GdkPixbuf* icon = NULL;
const char* file;
GtkIconInfo* inf = gtk_icon_theme_lookup_icon( theme, icon_name, size,
GTK_ICON_LOOKUP_USE_BUILTIN );
if( G_UNLIKELY( ! inf ) )
return NULL;
file = gtk_icon_info_get_filename( inf );
if( G_LIKELY( file ) )
icon = gdk_pixbuf_new_from_file( file, NULL );
else
{
icon = gtk_icon_info_get_builtin_pixbuf( inf );
g_object_ref( icon );
}
gtk_icon_info_free( inf );
if( G_LIKELY( icon ) ) /* scale down the icon if it's too big */
{
int width, height;
height = gdk_pixbuf_get_height(icon);
width = gdk_pixbuf_get_width(icon);
if( G_UNLIKELY( height > size || width > size ) )
{
GdkPixbuf* scaled;
if( height > width )
{
width = size * height / width;
height = size;
}
else if( height < width )
{
height = size * width / height;
width = size;
}
else
height = width = size;
scaled = gdk_pixbuf_scale_simple( icon, width, height, GDK_INTERP_BILINEAR );
g_object_unref( icon );
icon = scaled;
}
}
return icon;
}
#ifdef HAVE_HAL
static char* find_su_program( GError** err )
{
char* su = NULL;
#ifdef PREFERABLE_SUDO_PROG
su = g_find_program_in_path( PREFERABLE_SUDO_PROG );
#endif
// Use default search rules
if ( ! su )
su = get_valid_gsu();
if ( ! su )
su = g_find_program_in_path( "ktsuss" );
if ( ! su )
su = g_find_program_in_path( "gksudo" );
if ( ! su )
su = g_find_program_in_path( "gksu" );
if ( ! su )
su = g_find_program_in_path( "kdesu" );
if ( ! su )
g_set_error( err, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED, _( "su command not found" ) ); //MOD
return su;
}
gboolean vfs_sudo_cmd_sync( const char* cwd, char* argv[],
int* exit_status,
char** pstdout, char** pstderr, GError** err ) //MOD
{
char *su; //MOD
gboolean ret;
if ( ! ( su = find_su_program( err ) ) )
return FALSE;
argv[0] = su;
if ( ! strstr( su, "ktsuss" ) ) //MOD
{
// Combine arguments for gksu, kdesu, etc but not for ktsuss
argv[1] = g_strdup_printf( "%s %s '%s'", argv[1], argv[2], argv[3] );
argv[2] = NULL;
}
ret = g_spawn_sync( cwd, argv, NULL,
G_SPAWN_STDOUT_TO_DEV_NULL | G_SPAWN_STDERR_TO_DEV_NULL,
NULL, NULL,
pstdout, pstderr, exit_status, err );
return ret;
}
#endif
/*
gboolean vfs_sudo_cmd_async( const char* cwd, const char* cmd, GError** err )
{
char *su, *argv[3];
gboolean ret;
if ( ! ( su = find_su_program( err ) ) )
return FALSE;
argv[0] = su;
argv[1] = g_strdup( cmd );
argv[2] = NULL;
ret = g_spawn_async( cwd, argv, NULL,
G_SPAWN_STDOUT_TO_DEV_NULL | G_SPAWN_STDERR_TO_DEV_NULL,
NULL, NULL, NULL, err );
return ret;
}
static char* argv_to_cmdline( char** argv )
{
GString* cmd;
char* quoted;
cmd = g_string_new(NULL);
while( *argv )
{
quoted = g_shell_quote( *argv );
g_string_append( cmd, quoted );
g_free( quoted );
}
return g_string_free( cmd, FALSE );
}
*/
|
166 | ./spacefm/src/vfs/vfs-thumbnail-loader.c | /*
* vfs-thumbnail-loader.c
*
* Copyright 2008 PCMan <pcman.tw@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "vfs-thumbnail-loader.h"
#include "glib-mem.h" /* for g_slice API */
#include "glib-utils.h" /* for g_mkdir_with_parents() */
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#if GLIB_CHECK_VERSION(2, 16, 0)
#include "md5.h" /* for thumbnails */
#endif
struct _VFSThumbnailLoader
{
VFSDir* dir;
GQueue* queue;
VFSAsyncTask* task;
guint idle_handler;
GQueue* update_queue;
};
enum
{
LOAD_BIG_THUMBNAIL,
LOAD_SMALL_THUMBNAIL,
N_LOAD_TYPES
};
typedef struct _ThumbnailRequest
{
int n_requests[ N_LOAD_TYPES ];
VFSFileInfo* file;
}
ThumbnailRequest;
static gpointer thumbnail_loader_thread( VFSAsyncTask* task, VFSThumbnailLoader* loader );
/* static void on_load_finish( VFSAsyncTask* task, gboolean is_cancelled, VFSThumbnailLoader* loader ); */
static void thumbnail_request_free( ThumbnailRequest* req );
static gboolean on_thumbnail_idle( VFSThumbnailLoader* loader );
VFSThumbnailLoader* vfs_thumbnail_loader_new( VFSDir* dir )
{
VFSThumbnailLoader* loader = g_slice_new0( VFSThumbnailLoader );
loader->dir = g_object_ref( dir );
loader->queue = g_queue_new();
loader->update_queue = g_queue_new();
loader->task = vfs_async_task_new( (VFSAsyncFunc)thumbnail_loader_thread, loader );
/* g_signal_connect( loader->task, "finish", G_CALLBACK(on_load_finish), loader ); */
return loader;
}
void vfs_thumbnail_loader_free( VFSThumbnailLoader* loader )
{
if( loader->idle_handler )
g_source_remove( loader->idle_handler );
/* g_signal_handlers_disconnect_by_func( loader->task, on_load_finish, loader ); */
/* stop the running thread, if any. */
vfs_async_task_cancel( loader->task );
if( loader->idle_handler )
g_source_remove( loader->idle_handler );
g_object_unref( loader->task );
if( loader->queue )
{
g_queue_foreach( loader->queue, (GFunc) thumbnail_request_free, NULL );
g_queue_free( loader->queue );
}
if( loader->update_queue )
{
g_queue_foreach( loader->update_queue, (GFunc) vfs_file_info_unref, NULL );
g_queue_free( loader->update_queue );
}
/* g_debug( "FREE THUMBNAIL LOADER" ); */
/* prevent recursive unref called from vfs_dir_finalize */
loader->dir->thumbnail_loader = NULL;
g_object_unref( loader->dir );
}
#if 0 /* This is not used in the program. For debug only */
void on_load_finish( VFSAsyncTask* task, gboolean is_cancelled, VFSThumbnailLoader* loader )
{
g_debug( "TASK FINISHED" );
}
#endif
void thumbnail_request_free( ThumbnailRequest* req )
{
vfs_file_info_unref( req->file );
g_slice_free( ThumbnailRequest, req );
/* g_debug( "FREE REQUEST!" ); */
}
gboolean on_thumbnail_idle( VFSThumbnailLoader* loader )
{
VFSFileInfo* file;
/* g_debug( "ENTER ON_THUMBNAIL_IDLE" ); */
vfs_async_task_lock( loader->task );
while( ( file = (VFSFileInfo*)g_queue_pop_head(loader->update_queue) ) )
{
GDK_THREADS_ENTER();
vfs_dir_emit_thumbnail_loaded( loader->dir, file );
vfs_file_info_unref( file );
GDK_THREADS_LEAVE();
}
loader->idle_handler = 0;
vfs_async_task_unlock( loader->task );
if( vfs_async_task_is_finished( loader->task ) )
{
/* g_debug( "FREE LOADER IN IDLE HANDLER" ); */
loader->dir->thumbnail_loader = NULL;
vfs_thumbnail_loader_free(loader);
}
/* g_debug( "LEAVE ON_THUMBNAIL_IDLE" ); */
return FALSE;
}
gpointer thumbnail_loader_thread( VFSAsyncTask* task, VFSThumbnailLoader* loader )
{
ThumbnailRequest* req;
int i;
gboolean load_big, need_update;
while( G_LIKELY( ! vfs_async_task_is_cancelled(task) ))
{
vfs_async_task_lock( task );
req = (ThumbnailRequest*)g_queue_pop_head( loader->queue );
vfs_async_task_unlock( task );
if( G_UNLIKELY( ! req ) )
break;
/* g_debug("pop: %s", req->file->name); */
/* Only we have the reference. That means, no body is using the file */
if( req->file->n_ref == 1 )
{
thumbnail_request_free( req );
continue;
}
need_update = FALSE;
for ( i = 0; i < 2; ++i )
{
if ( 0 == req->n_requests[ i ] )
continue;
load_big = ( i == LOAD_BIG_THUMBNAIL );
if ( ! vfs_file_info_is_thumbnail_loaded( req->file, load_big ) )
{
char* full_path;
full_path = g_build_filename( loader->dir->path,
vfs_file_info_get_name( req->file ),
NULL );
vfs_file_info_load_thumbnail( req->file, full_path, load_big );
g_free( full_path );
/* Slow donwn for debugging.
g_debug( "DELAY!!" );
g_usleep(G_USEC_PER_SEC/2);
*/
/* g_debug( "thumbnail loaded: %s", req->file ); */
}
need_update = TRUE;
}
if( ! vfs_async_task_is_cancelled(task) && need_update )
{
vfs_async_task_lock( task );
g_queue_push_tail( loader->update_queue, vfs_file_info_ref(req->file) );
if( 0 == loader->idle_handler)
loader->idle_handler = g_idle_add_full( G_PRIORITY_LOW, (GSourceFunc) on_thumbnail_idle, loader, NULL );
vfs_async_task_unlock( task );
}
/* g_debug( "NEED_UPDATE: %d", need_update ); */
thumbnail_request_free( req );
}
if( vfs_async_task_is_cancelled(task) )
{
/* g_debug( "THREAD CANCELLED!!!" ); */
vfs_async_task_lock( task );
if( loader->idle_handler)
{
g_source_remove( loader->idle_handler );
loader->idle_handler = 0;
}
vfs_async_task_unlock( task );
}
else
{
if( 0 == loader->idle_handler)
{
/* g_debug( "ADD IDLE HANDLER BEFORE THREAD ENDING" ); */
loader->idle_handler = g_idle_add_full( G_PRIORITY_LOW, (GSourceFunc) on_thumbnail_idle, loader, NULL );
}
}
/* g_debug("THREAD ENDED!"); */
return NULL;
}
void vfs_thumbnail_loader_request( VFSDir* dir, VFSFileInfo* file, gboolean is_big )
{
VFSThumbnailLoader* loader;
ThumbnailRequest* req;
gboolean new_task = FALSE;
GList* l;
/* g_debug( "request thumbnail: %s, is_big: %d", file->name, is_big ); */
if( G_UNLIKELY( ! dir->thumbnail_loader ) )
{
dir->thumbnail_loader = vfs_thumbnail_loader_new( dir );
new_task = TRUE;
}
loader = dir->thumbnail_loader;
if( G_UNLIKELY( ! loader->task ) )
{
loader->task = vfs_async_task_new( (VFSAsyncFunc)thumbnail_loader_thread, loader );
new_task = TRUE;
}
vfs_async_task_lock( loader->task );
/* Check if the request is already scheduled */
for( l = loader->queue->head; l; l = l->next )
{
req = (ThumbnailRequest*)l->data;
/* If file with the same name is already in our queue */
if( req->file == file || 0 == strcmp( req->file->name, file->name ) )
break;
}
if( l )
{
req = (ThumbnailRequest*)l->data;
}
else
{
req = g_slice_new0( ThumbnailRequest );
req->file = vfs_file_info_ref(file);
g_queue_push_tail( dir->thumbnail_loader->queue, req );
}
++req->n_requests[ is_big ? LOAD_BIG_THUMBNAIL : LOAD_SMALL_THUMBNAIL ];
vfs_async_task_unlock( loader->task );
if( new_task )
vfs_async_task_execute( loader->task );
}
void vfs_thumbnail_loader_cancel_all_requests( VFSDir* dir, gboolean is_big )
{
GList* l;
VFSThumbnailLoader* loader;
ThumbnailRequest* req;
if( G_UNLIKELY( (loader=dir->thumbnail_loader) ) )
{
vfs_async_task_lock( loader->task );
/* g_debug( "TRY TO CANCEL REQUESTS!!" ); */
for( l = loader->queue->head; l; )
{
req = (ThumbnailRequest*)l->data;
--req->n_requests[ is_big ? LOAD_BIG_THUMBNAIL : LOAD_SMALL_THUMBNAIL ];
if( req->n_requests[0] <= 0 && req->n_requests[1] <= 0 ) /* nobody needs this */
{
GList* next = l->next;
g_queue_delete_link( loader->queue, l );
l = next;
}
else
l = l->next;
}
if( g_queue_get_length( loader->queue ) == 0 )
{
/* g_debug( "FREE LOADER IN vfs_thumbnail_loader_cancel_all_requests!" ); */
vfs_async_task_unlock( loader->task );
loader->dir->thumbnail_loader = NULL;
vfs_thumbnail_loader_free( loader );
return;
}
vfs_async_task_unlock( loader->task );
}
}
static GdkPixbuf* _vfs_thumbnail_load( const char* file_path, const char* uri,
int size, time_t mtime )
{
#if GLIB_CHECK_VERSION(2, 16, 0)
GChecksum *cs;
#else
md5_state_t md5_state;
md5_byte_t md5[ 16 ];
#endif
char file_name[ 40 ];
char* thumbnail_file;
char mtime_str[ 32 ];
const char* thumb_mtime;
int i, w, h;
struct stat statbuf;
GdkPixbuf* thumbnail, *result = NULL;
if ( !gdk_pixbuf_get_file_info( file_path, &w, &h ) )
return NULL; /* image format cannot be recognized */
/* If the image itself is very small, we should load it directly */
if ( w <= 128 && h <= 128 )
{
if( w <= size && h <= size )
return gdk_pixbuf_new_from_file( file_path, NULL );
return gdk_pixbuf_new_from_file_at_size( file_path, size, size, NULL );
}
#if GLIB_CHECK_VERSION(2, 16, 0)
cs = g_checksum_new(G_CHECKSUM_MD5);
g_checksum_update(cs, uri, strlen(uri));
memcpy( file_name, g_checksum_get_string(cs), 32 );
g_checksum_free(cs);
#else
md5_init( &md5_state );
md5_append( &md5_state, ( md5_byte_t * ) uri, strlen( uri ) );
md5_finish( &md5_state, md5 );
for ( i = 0; i < 16; ++i )
sprintf( ( file_name + i * 2 ), "%02x", md5[ i ] );
#endif
strcpy( ( file_name + 32 ), ".png" );
thumbnail_file = g_build_filename( g_get_home_dir(),
".thumbnails/normal",
file_name, NULL );
if( G_UNLIKELY( 0 == mtime ) )
{
if( stat( file_path, &statbuf ) != -1 )
mtime = statbuf.st_mtime;
}
/* load existing thumbnail */
thumbnail = gdk_pixbuf_new_from_file( thumbnail_file, NULL );
if ( !thumbnail ||
!( thumb_mtime = gdk_pixbuf_get_option( thumbnail, "tEXt::Thumb::MTime" ) ) ||
atol( thumb_mtime ) != mtime )
{
if( thumbnail )
g_object_unref( thumbnail );
/* create new thumbnail */
thumbnail = gdk_pixbuf_new_from_file_at_size( file_path, 128, 128, NULL );
if ( thumbnail )
{
thumbnail = gdk_pixbuf_apply_embedded_orientation( thumbnail );
sprintf( mtime_str, "%lu", mtime );
gdk_pixbuf_save( thumbnail, thumbnail_file, "png", NULL,
"tEXt::Thumb::URI", uri, "tEXt::Thumb::MTime", mtime_str, NULL );
chmod( thumbnail_file, 0600 ); /* only the owner can read it. */
}
}
if ( thumbnail )
{
w = gdk_pixbuf_get_width( thumbnail );
h = gdk_pixbuf_get_height( thumbnail );
if ( w > h )
{
h = h * size / w;
w = size;
}
else if ( h > w )
{
w = w * size / h;
h = size;
}
else
{
w = h = size;
}
if ( w > 0 && h > 0 )
result = gdk_pixbuf_scale_simple(
thumbnail,
w, h, GDK_INTERP_BILINEAR );
g_object_unref( thumbnail );
}
g_free( thumbnail_file );
return result;
}
GdkPixbuf* vfs_thumbnail_load_for_uri( const char* uri, int size, time_t mtime )
{
GdkPixbuf* ret;
char* file = g_filename_from_uri( uri, NULL, NULL );
ret = _vfs_thumbnail_load( file, uri, size, mtime );
g_free( file );
return ret;
}
GdkPixbuf* vfs_thumbnail_load_for_file( const char* file, int size, time_t mtime )
{
GdkPixbuf* ret;
char* uri = g_filename_to_uri( file, NULL, NULL );
ret = _vfs_thumbnail_load( file, uri, size, mtime );
g_free( uri );
return ret;
}
/* Ensure the thumbnail dirs exist and have proper file permission. */
void vfs_thumbnail_init()
{
char* dir;
dir = g_build_filename( g_get_home_dir(), ".thumbnails/normal", NULL );
if( G_LIKELY( g_file_test( dir, G_FILE_TEST_IS_DIR ) ) )
chmod( dir, 0700 );
else
g_mkdir_with_parents( dir, 0700 );
g_free( dir );
}
|
167 | ./spacefm/src/vfs/vfs-file-monitor.c | /*
* C Implementation: vfs-monitor
*
* Description: File alteration monitor
*
*
* Author: Hong Jen Yee (PCMan) <pcman.tw (AT) gmail.com>, (C) 2006
*
* Copyright: See COPYING file that comes with this distribution
*
* Most of the inotify parts are taken from "menu-monitor-inotify.c" of
* gnome-menus, which is licensed under GNU Lesser General Public License.
*
* Copyright (C) 2005 Red Hat, Inc.
* Copyright (C) 2006 Mark McLoughlin
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "vfs-file-monitor.h"
#include "vfs-file-info.h"
#include <sys/types.h> /* for stat */
#include <sys/stat.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include "glib-mem.h"
typedef struct
{
VFSFileMonitorCallback callback;
gpointer user_data;
}
VFSFileMonitorCallbackEntry;
static GHashTable* monitor_hash = NULL;
static GIOChannel* fam_io_channel = NULL;
static guint fam_io_watch = 0;
#ifdef USE_INOTIFY
static int inotify_fd = -1;
#else
static FAMConnection fam;
#endif
/* event handler of all FAM events */
static gboolean on_fam_event( GIOChannel *channel,
GIOCondition cond,
gpointer user_data );
static gboolean connect_to_fam()
{
#ifdef USE_INOTIFY
inotify_fd = inotify_init ();
if ( inotify_fd < 0 )
{
fam_io_channel = NULL;
g_warning( "failed to initialize inotify." );
return FALSE;
}
fam_io_channel = g_io_channel_unix_new( inotify_fd );
#else /* use FAM|gamin */
if ( FAMOpen( &fam ) )
{
fam_io_channel = NULL;
fam.fd = -1;
g_warning( "There is no FAM/gamin server\n" );
return FALSE;
}
#if HAVE_FAMNOEXISTS
/*
* Disable the initital directory content loading.
* This can greatly speed up directory loading, but
* unfortunately, it's not compatible with original FAM.
*/
FAMNoExists( &fam ); /* This is an extension of gamin */
#endif
fam_io_channel = g_io_channel_unix_new( FAMCONNECTION_GETFD( &fam ) );
#endif
/* set fam socket to non-blocking */
/* fcntl( FAMCONNECTION_GETFD( &fam ),F_SETFL,O_NONBLOCK); */
g_io_channel_set_encoding( fam_io_channel, NULL, NULL );
g_io_channel_set_buffered( fam_io_channel, FALSE );
g_io_channel_set_flags( fam_io_channel, G_IO_FLAG_NONBLOCK, NULL );
fam_io_watch = g_io_add_watch( fam_io_channel,
G_IO_IN | G_IO_PRI | G_IO_HUP|G_IO_ERR,
on_fam_event,
NULL );
return TRUE;
}
static void disconnect_from_fam()
{
if ( fam_io_channel )
{
g_io_channel_unref( fam_io_channel );
fam_io_channel = NULL;
g_source_remove( fam_io_watch );
#ifdef USE_INOTIFY
close( inotify_fd );
inotify_fd = -1;
#else
FAMClose( &fam );
#endif
}
}
/* final cleanup */
void vfs_file_monitor_clean()
{
disconnect_from_fam();
if ( monitor_hash )
{
g_hash_table_destroy( monitor_hash );
monitor_hash = NULL;
}
}
/*
* Init monitor:
* Establish connection with gamin/fam.
*/
gboolean vfs_file_monitor_init()
{
monitor_hash = g_hash_table_new( g_str_hash, g_str_equal );
if ( ! connect_to_fam() )
return FALSE;
return TRUE;
}
VFSFileMonitor* vfs_file_monitor_add( char* path,
gboolean is_dir,
VFSFileMonitorCallback cb,
gpointer user_data )
{
VFSFileMonitor * monitor;
VFSFileMonitorCallbackEntry cb_ent;
struct stat file_stat; // skip stat64
char resolved_path[PATH_MAX];
char* real_path;
//printf( "vfs_file_monitor_add %s\n", path );
if ( ! monitor_hash )
return NULL;
// Since gamin, FAM and inotify don't follow symlinks, need to get real path
if ( strlen( path ) > PATH_MAX - 1 )
{
g_warning ( "PATH_MAX exceeded on %s", path );
real_path = path; //fallback
}
else if ( realpath( path, resolved_path ) == NULL )
{
g_warning ( "realpath failed on %s", path );
real_path = path; //fallback
}
else
real_path = resolved_path;
monitor = ( VFSFileMonitor* ) g_hash_table_lookup ( monitor_hash, real_path );
if ( ! monitor )
{
monitor = g_slice_new0( VFSFileMonitor );
monitor->path = g_strdup( real_path );
monitor->callbacks = g_array_new ( FALSE, FALSE, sizeof( VFSFileMonitorCallbackEntry ) );
g_hash_table_insert ( monitor_hash,
monitor->path,
monitor );
/* OLD METHOD - removes wrong dir due to symlinks
// NOTE: Since gamin, FAM and inotify don't follow symlinks,
we need to do some special processing here.
if ( lstat( path, &file_stat ) == 0 )
{
const char* link_file = path;
while( G_UNLIKELY( S_ISLNK(file_stat.st_mode) ) )
{
char* link = g_file_read_link( link_file, NULL );
char* dirname = g_path_get_dirname( link_file );
real_path = vfs_file_resolve_path( dirname, link );
g_free( link );
g_free( dirname );
if( lstat( real_path, &file_stat ) == -1 )
break;
link_file = real_path;
}
}
*/
#ifdef USE_INOTIFY /* Linux inotify */
monitor->wd = inotify_add_watch ( inotify_fd, real_path,
IN_MODIFY | IN_CREATE | IN_DELETE |
IN_DELETE_SELF | IN_MOVE |
IN_MOVE_SELF | IN_UNMOUNT | IN_ATTRIB );
if ( monitor->wd < 0 )
{
g_warning ( "Failed to add monitor on '%s' ('%s'): %s",
real_path, path,
g_strerror ( errno ) );
return NULL;
}
//printf("vfs_file_monitor_add %s (%s) %d\n", real_path, path, monitor->wd );
#else /* Use FAM|gamin */
//MOD see NOTE1 in vfs-mime-type.c - what happens here if path doesn't exist?
// inotify returns NULL - does fam?
if ( fam_io_channel )
{
if ( is_dir )
{
FAMMonitorDirectory( &fam,
real_path,
&monitor->request,
monitor );
}
else
{
FAMMonitorFile( &fam,
real_path,
&monitor->request,
monitor );
}
}
else
{
g_warning( "FAM/gamin server is not running ?" );
return NULL;
}
#endif
}
if( G_LIKELY(monitor) )
{
/* g_debug( "monitor installed: %s, %p", path, monitor ); */
if ( cb )
{ /* Install a callback */
cb_ent.callback = cb;
cb_ent.user_data = user_data;
monitor->callbacks = g_array_append_val( monitor->callbacks, cb_ent );
}
g_atomic_int_inc( &monitor->n_ref );
}
return monitor;
}
void vfs_file_monitor_remove( VFSFileMonitor * fm,
VFSFileMonitorCallback cb,
gpointer user_data )
{
int i;
VFSFileMonitorCallbackEntry* callbacks;
//printf( "vfs_file_monitor_remove\n" );
if ( cb && fm && fm->callbacks )
{
callbacks = ( VFSFileMonitorCallbackEntry* ) fm->callbacks->data;
for ( i = 0; i < fm->callbacks->len; ++i )
{
if ( callbacks[ i ].callback == cb && callbacks[ i ].user_data == user_data )
{
fm->callbacks = g_array_remove_index_fast ( fm->callbacks, i );
break;
}
}
}
if ( fm && g_atomic_int_dec_and_test( &fm->n_ref ) ) //MOD added "fm &&"
{
#ifdef USE_INOTIFY /* Linux inotify */
//printf( "vfs_file_monitor_remove %d\n", fm->wd );
inotify_rm_watch ( inotify_fd, fm->wd );
#else /* Use FAM|gamin */
if ( fam_io_channel )
FAMCancelMonitor( &fam, &fm->request );
else
g_warning( "FAM/gamin server is not running ?" );
#endif
g_hash_table_remove( monitor_hash, fm->path );
g_free( fm->path );
g_array_free( fm->callbacks, TRUE );
g_slice_free( VFSFileMonitor, fm );
}
//printf( "vfs_file_monitor_remove DONE\n" );
}
static void reconnect_fam( gpointer key,
gpointer value,
gpointer user_data )
{
struct stat file_stat; // skip stat64
VFSFileMonitor* monitor = ( VFSFileMonitor* ) value;
const char* path = ( const char* ) key;
if ( lstat( path, &file_stat ) != -1 )
{
#ifdef USE_INOTIFY /* Linux inotify */
monitor->wd = inotify_add_watch ( inotify_fd, path,
IN_MODIFY | IN_CREATE | IN_DELETE | IN_MOVE );
if ( monitor->wd < 0 )
{
/*
* FIXME: add monitor to an ancestor which does actually exist,
* or do the equivalent of inotify-missing.c by maintaining
* a list of monitors on non-existent files/directories
* which you retry in a timeout.
*/
g_warning ( "Failed to add monitor on '%s': %s",
path,
g_strerror ( errno ) );
return ;
}
#else
if ( S_ISDIR( file_stat.st_mode ) )
{
FAMMonitorDirectory( &fam,
path,
&monitor->request,
monitor );
}
else
{
FAMMonitorFile( &fam,
path,
&monitor->request,
monitor );
}
#endif
}
}
#ifdef USE_INOTIFY
static gboolean find_monitor( gpointer key,
gpointer value,
gpointer user_data )
{
int wd = GPOINTER_TO_INT( user_data );
VFSFileMonitor* monitor = ( VFSFileMonitor* ) value;
return ( monitor->wd == wd );
}
static VFSFileMonitorEvent translate_inotify_event( int inotify_mask )
{
if ( inotify_mask & ( IN_CREATE | IN_MOVED_TO ) )
return VFS_FILE_MONITOR_CREATE;
else if ( inotify_mask & ( IN_DELETE | IN_MOVED_FROM | IN_DELETE_SELF | IN_UNMOUNT ) )
return VFS_FILE_MONITOR_DELETE;
else if ( inotify_mask & ( IN_MODIFY | IN_ATTRIB ) )
return VFS_FILE_MONITOR_CHANGE;
else
{
//IN_IGNORED not handled
//g_warning( "translate_inotify_event mask not handled %d", inotify_mask );
return VFS_FILE_MONITOR_CHANGE;
}
}
#endif
static void dispatch_event( VFSFileMonitor * monitor,
VFSFileMonitorEvent evt,
const char * file_name )
{
VFSFileMonitorCallbackEntry * cb;
VFSFileMonitorCallback func;
int i;
/* Call the callback functions */
if ( monitor->callbacks && monitor->callbacks->len )
{
cb = ( VFSFileMonitorCallbackEntry* ) monitor->callbacks->data;
for ( i = 0; i < monitor->callbacks->len; ++i )
{
func = cb[ i ].callback;
func( monitor, evt, file_name, cb[ i ].user_data );
}
}
}
/* event handler of all FAM events */
static gboolean on_fam_event( GIOChannel * channel,
GIOCondition cond,
gpointer user_data )
{
#ifdef USE_INOTIFY /* Linux inootify */
#define BUF_LEN (1024 * (sizeof (struct inotify_event) + 16))
char buf[ BUF_LEN ];
int i, len;
#else /* FAM|gamin */
FAMEvent evt;
#endif
VFSFileMonitor* monitor = NULL;
if ( cond & (G_IO_HUP | G_IO_ERR) )
{
disconnect_from_fam();
if ( g_hash_table_size ( monitor_hash ) > 0 )
{
/*
Disconnected from FAM server, but there are still monitors.
This may be caused by crash of FAM server.
So we have to reconnect to FAM server.
*/
if ( connect_to_fam() )
g_hash_table_foreach( monitor_hash, ( GHFunc ) reconnect_fam,
NULL );
}
return TRUE; /* don't need to remove the event source since
it has been removed by disconnect_from_fam(). */
}
#ifdef USE_INOTIFY /* Linux inotify */
while ( ( len = read ( inotify_fd, buf, BUF_LEN ) ) < 0
&& errno == EINTR );
if ( len < 0 )
{
g_warning ( "Error reading inotify event: %s",
g_strerror ( errno ) );
/* goto error_cancel; */
return FALSE;
}
if ( len == 0 )
{
/*
* FIXME: handle this better?
*/
g_warning ( "Error reading inotify event: supplied buffer was too small" );
/* goto error_cancel; */
return FALSE;
}
i = 0;
while ( i < len )
{
struct inotify_event * ievent = ( struct inotify_event * ) & buf [ i ];
/* FIXME: 2 different paths can have the same wd because of link
* This was fixed in spacefm 0.8.7 ?? */
monitor = ( VFSFileMonitor* ) g_hash_table_find(
monitor_hash,
find_monitor,
GINT_TO_POINTER( ievent->wd ) );
if( G_LIKELY(monitor) )
{
const char* file_name;
file_name = ievent->len > 0 ? ievent->name : monitor->path;
/*
//MOD for debug output only
char* desc;
if ( ievent->mask & ( IN_CREATE | IN_MOVED_TO ) )
desc = "CREATE";
else if ( ievent->mask & ( IN_DELETE | IN_MOVED_FROM | IN_DELETE_SELF | IN_UNMOUNT ) )
desc = "DELETE";
else if ( ievent->mask & ( IN_MODIFY | IN_ATTRIB ) )
desc = "CHANGE";
if ( !strcmp( monitor->path, "/tmp" ) && g_str_has_prefix( file_name, "vte" ) )
{ } // due to current vte scroll problems creating and deleting massive numbers of
// /tmp/vte8CBO7V types of files, ignore these (creates feedback loop when
// spacefm is run in terminal because each printf triggers a scroll,
// which triggers another printf below, which triggers another file change)
// https://bugs.launchpad.net/ubuntu/+source/vte/+bug/778872
else
printf("inotify-event %s: %s///%s\n", desc, monitor->path, file_name);
//g_debug("inotify (%d) :%s", ievent->mask, file_name);
*/
dispatch_event( monitor,
translate_inotify_event( ievent->mask ),
file_name );
}
i += sizeof ( struct inotify_event ) + ievent->len;
}
#else /* FAM|gamin */
while ( FAMPending( &fam ) )
{
if ( FAMNextEvent( &fam, &evt ) > 0 )
{
monitor = ( VFSFileMonitor* ) evt.userdata;
switch ( evt.code )
{
case FAMCreated:
case FAMDeleted:
case FAMChanged:
/* FIXME: There exists a possibility that a file can accidentally become
a directory, and a directory can become a file when using chmod.
Should we delete original request, and create a new one when this happens?
*/
/* g_debug("FAM event(%d): %s", evt.code, evt.filename); */
/* Call the callback functions */
dispatch_event( monitor, evt.code, evt.filename );
break;
/* Other events are not supported */
default:
break;
}
}
}
#endif
return TRUE;
}
|
168 | ./spacefm/src/vfs/vfs-volume-nohal.c | /*
* C Implementation: vfs-volume
*
* udev & mount monitor code by IgnorantGuru
* device info code uses code excerpts from freedesktop's udisks v1.0.4
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "vfs-volume.h"
#include "glib-mem.h"
#include <glib/gi18n.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
// udev
#include <libudev.h>
#include <fcntl.h>
#include <errno.h>
// waitpid
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h> // kill
#ifdef HAVE_STATVFS
#include <sys/statvfs.h>
#endif
#include <vfs-file-info.h>
#include "ptk-file-task.h"
#include "main-window.h"
void vfs_volume_monitor_start();
VFSVolume* vfs_volume_read_by_device( struct udev_device *udevice );
VFSVolume* vfs_volume_read_by_mount( const char* mount_points );
static void vfs_volume_device_added ( VFSVolume* volume, gboolean automount );
static void vfs_volume_device_removed ( char* device_file );
static gboolean vfs_volume_nonblock_removed( const char* mount_points );
static void call_callbacks( VFSVolume* vol, VFSVolumeState state );
void vfs_volume_special_unmounted( const char* device_file );
void unmount_if_mounted( const char* device_file );
static void vfs_volume_clean();
typedef struct _VFSVolumeCallbackData
{
VFSVolumeCallback cb;
gpointer user_data;
}VFSVolumeCallbackData;
static GList* volumes = NULL;
static GList* special_mounts = NULL;
static GArray* callbacks = NULL;
GPid monpid = 0;
gboolean global_inhibit_auto = FALSE;
typedef struct devmount_t {
guint major;
guint minor;
char* mount_points;
char* fstype;
GList* mounts;
} devmount_t;
GList* devmounts = NULL;
struct udev *udev = NULL;
struct udev_monitor *umonitor = NULL;
GIOChannel* uchannel = NULL;
GIOChannel* mchannel = NULL;
/* *************************************************************************
* device info
************************************************************************** */
typedef struct device_t {
struct udev_device *udevice;
char *devnode;
char *native_path;
char *major;
char *minor;
char *mount_points;
gboolean device_is_system_internal;
gboolean device_is_partition;
gboolean device_is_partition_table;
gboolean device_is_removable;
gboolean device_is_media_available;
gboolean device_is_read_only;
gboolean device_is_drive;
gboolean device_is_optical_disc;
gboolean device_is_mounted;
char *device_presentation_hide;
char *device_presentation_nopolicy;
char *device_presentation_name;
char *device_presentation_icon_name;
char *device_automount_hint;
char *device_by_id;
guint64 device_size;
guint64 device_block_size;
char *id_usage;
char *id_type;
char *id_version;
char *id_uuid;
char *id_label;
char *drive_vendor;
char *drive_model;
char *drive_revision;
char *drive_serial;
char *drive_wwn;
char *drive_connection_interface;
guint64 drive_connection_speed;
char *drive_media_compatibility;
char *drive_media;
gboolean drive_is_media_ejectable;
gboolean drive_can_detach;
char *partition_scheme;
char *partition_number;
char *partition_type;
char *partition_label;
char *partition_uuid;
char *partition_flags;
char *partition_offset;
char *partition_size;
char *partition_alignment_offset;
char *partition_table_scheme;
char *partition_table_count;
gboolean optical_disc_is_blank;
gboolean optical_disc_is_appendable;
gboolean optical_disc_is_closed;
char *optical_disc_num_tracks;
char *optical_disc_num_audio_tracks;
char *optical_disc_num_sessions;
} device_t;
static char *
_dupv8 (const char *s)
{
const char *end_valid;
if (!g_utf8_validate (s, -1, &end_valid))
{
g_print ("**** NOTE: The string '%s' is not valid UTF-8. Invalid characters begins at '%s'\n", s, end_valid);
return g_strndup (s, end_valid - s);
}
else
{
return g_strdup (s);
}
}
/* unescapes things like \x20 to " " and ensures the returned string is valid UTF-8.
*
* see volume_id_encode_string() in extras/volume_id/lib/volume_id.c in the
* udev tree for the encoder
*/
static gchar *
decode_udev_encoded_string (const gchar *str)
{
GString *s;
gchar *ret;
const gchar *end_valid;
guint n;
s = g_string_new (NULL);
for (n = 0; str[n] != '\0'; n++)
{
if (str[n] == '\\')
{
gint val;
if (str[n + 1] != 'x' || str[n + 2] == '\0' || str[n + 3] == '\0')
{
g_print ("**** NOTE: malformed encoded string '%s'\n", str);
break;
}
val = (g_ascii_xdigit_value (str[n + 2]) << 4) | g_ascii_xdigit_value (str[n + 3]);
g_string_append_c (s, val);
n += 3;
}
else
{
g_string_append_c (s, str[n]);
}
}
if (!g_utf8_validate (s->str, -1, &end_valid))
{
g_print ("**** NOTE: The string '%s' is not valid UTF-8. Invalid characters begins at '%s'\n", s->str, end_valid);
ret = g_strndup (s->str, end_valid - s->str);
g_string_free (s, TRUE);
}
else
{
ret = g_string_free (s, FALSE);
}
return ret;
}
static gint
ptr_str_array_compare (const gchar **a,
const gchar **b)
{
return g_strcmp0 (*a, *b);
}
static double
sysfs_get_double (const char *dir,
const char *attribute)
{
double result;
char *contents;
char *filename;
result = 0.0;
filename = g_build_filename (dir, attribute, NULL);
if (g_file_get_contents (filename, &contents, NULL, NULL))
{
result = atof (contents);
g_free (contents);
}
g_free (filename);
return result;
}
static char *
sysfs_get_string (const char *dir,
const char *attribute)
{
char *result;
char *filename;
result = NULL;
filename = g_build_filename (dir, attribute, NULL);
if (!g_file_get_contents (filename, &result, NULL, NULL))
{
result = g_strdup ("");
}
g_free (filename);
return result;
}
static int
sysfs_get_int (const char *dir,
const char *attribute)
{
int result;
char *contents;
char *filename;
result = 0;
filename = g_build_filename (dir, attribute, NULL);
if (g_file_get_contents (filename, &contents, NULL, NULL))
{
result = strtol (contents, NULL, 0);
g_free (contents);
}
g_free (filename);
return result;
}
static guint64
sysfs_get_uint64 (const char *dir,
const char *attribute)
{
guint64 result;
char *contents;
char *filename;
result = 0;
filename = g_build_filename (dir, attribute, NULL);
if (g_file_get_contents (filename, &contents, NULL, NULL))
{
result = strtoll (contents, NULL, 0);
g_free (contents);
}
g_free (filename);
return result;
}
static gboolean
sysfs_file_exists (const char *dir,
const char *attribute)
{
gboolean result;
char *filename;
result = FALSE;
filename = g_build_filename (dir, attribute, NULL);
if (g_file_test (filename, G_FILE_TEST_EXISTS))
{
result = TRUE;
}
g_free (filename);
return result;
}
static char *
sysfs_resolve_link (const char *sysfs_path,
const char *name)
{
char *full_path;
char link_path[PATH_MAX];
char resolved_path[PATH_MAX];
ssize_t num;
gboolean found_it;
found_it = FALSE;
full_path = g_build_filename (sysfs_path, name, NULL);
//g_debug ("name='%s'", name);
//g_debug ("full_path='%s'", full_path);
num = readlink (full_path, link_path, sizeof(link_path) - 1);
if (num != -1)
{
char *absolute_path;
link_path[num] = '\0';
//g_debug ("link_path='%s'", link_path);
absolute_path = g_build_filename (sysfs_path, link_path, NULL);
//g_debug ("absolute_path='%s'", absolute_path);
if (realpath (absolute_path, resolved_path) != NULL)
{
//g_debug ("resolved_path='%s'", resolved_path);
found_it = TRUE;
}
g_free (absolute_path);
}
g_free (full_path);
if (found_it)
return g_strdup (resolved_path);
else
return NULL;
}
gboolean info_is_system_internal( device_t *device )
{
const char *value;
if ( value = udev_device_get_property_value( device->udevice, "UDISKS_SYSTEM_INTERNAL" ) )
return atoi( value ) != 0;
/* A Linux MD device is system internal if, and only if
*
* - a single component is system internal
* - there are no components
* SKIP THIS TEST
*/
/* a partition is system internal only if the drive it belongs to is system internal */
//TODO
/* a LUKS cleartext device is system internal only if the underlying crypto-text
* device is system internal
* SKIP THIS TEST
*/
// devices with removable media are never system internal
if ( device->device_is_removable )
return FALSE;
/* devices on certain buses are never system internal */
if ( device->drive_connection_interface != NULL )
{
if (strcmp (device->drive_connection_interface, "ata_serial_esata") == 0
|| strcmp (device->drive_connection_interface, "sdio") == 0
|| strcmp (device->drive_connection_interface, "usb") == 0
|| strcmp (device->drive_connection_interface, "firewire") == 0)
return FALSE;
}
return TRUE;
}
void info_drive_connection( device_t *device )
{
char *s;
char *p;
char *q;
char *model;
char *vendor;
char *subsystem;
char *serial;
char *revision;
const char *connection_interface;
guint64 connection_speed;
connection_interface = NULL;
connection_speed = 0;
/* walk up the device tree to figure out the subsystem */
s = g_strdup (device->native_path);
do
{
p = sysfs_resolve_link (s, "subsystem");
if ( !device->device_is_removable && sysfs_get_int( s, "removable") != 0 )
device->device_is_removable = TRUE;
if (p != NULL)
{
subsystem = g_path_get_basename (p);
g_free (p);
if (strcmp (subsystem, "scsi") == 0)
{
connection_interface = "scsi";
connection_speed = 0;
/* continue walking up the chain; we just use scsi as a fallback */
/* grab the names from SCSI since the names from udev currently
* - replaces whitespace with _
* - is missing for e.g. Firewire
*/
vendor = sysfs_get_string (s, "vendor");
if (vendor != NULL)
{
g_strstrip (vendor);
/* Don't overwrite what we set earlier from ID_VENDOR */
if (device->drive_vendor == NULL)
{
device->drive_vendor = _dupv8 (vendor);
}
g_free (vendor);
}
model = sysfs_get_string (s, "model");
if (model != NULL)
{
g_strstrip (model);
/* Don't overwrite what we set earlier from ID_MODEL */
if (device->drive_model == NULL)
{
device->drive_model = _dupv8 (model);
}
g_free (model);
}
/* TODO: need to improve this code; we probably need the kernel to export more
* information before we can properly get the type and speed.
*/
if (device->drive_vendor != NULL && strcmp (device->drive_vendor, "ATA") == 0)
{
connection_interface = "ata";
break;
}
}
else if (strcmp (subsystem, "usb") == 0)
{
double usb_speed;
/* both the interface and the device will be 'usb'. However only
* the device will have the 'speed' property.
*/
usb_speed = sysfs_get_double (s, "speed");
if (usb_speed > 0)
{
connection_interface = "usb";
connection_speed = usb_speed * (1000 * 1000);
break;
}
}
else if (strcmp (subsystem, "firewire") == 0 || strcmp (subsystem, "ieee1394") == 0)
{
/* TODO: krh has promised a speed file in sysfs; theoretically, the speed can
* be anything from 100, 200, 400, 800 and 3200. Till then we just hardcode
* a resonable default of 400 Mbit/s.
*/
connection_interface = "firewire";
connection_speed = 400 * (1000 * 1000);
break;
}
else if (strcmp (subsystem, "mmc") == 0)
{
/* TODO: what about non-SD, e.g. MMC? Is that another bus? */
connection_interface = "sdio";
/* Set vendor name. According to this MMC document
*
* http://www.mmca.org/membership/IAA_Agreement_10_12_06.pdf
*
* - manfid: the manufacturer id
* - oemid: the customer of the manufacturer
*
* Apparently these numbers are kept secret. It would be nice
* to map these into names for setting the manufacturer of the drive,
* e.g. Panasonic, Sandisk etc.
*/
model = sysfs_get_string (s, "name");
if (model != NULL)
{
g_strstrip (model);
/* Don't overwrite what we set earlier from ID_MODEL */
if (device->drive_model == NULL)
{
device->drive_model = _dupv8 (model);
}
g_free (model);
}
serial = sysfs_get_string (s, "serial");
if (serial != NULL)
{
g_strstrip (serial);
/* Don't overwrite what we set earlier from ID_SERIAL */
if (device->drive_serial == NULL)
{
/* this is formatted as a hexnumber; drop the leading 0x */
device->drive_serial = _dupv8 (serial + 2);
}
g_free (serial);
}
/* TODO: use hwrev and fwrev files? */
revision = sysfs_get_string (s, "date");
if (revision != NULL)
{
g_strstrip (revision);
/* Don't overwrite what we set earlier from ID_REVISION */
if (device->drive_revision == NULL)
{
device->drive_revision = _dupv8 (revision);
}
g_free (revision);
}
/* TODO: interface speed; the kernel driver knows; would be nice
* if it could export it */
}
else if (strcmp (subsystem, "platform") == 0)
{
const gchar *sysfs_name;
sysfs_name = g_strrstr (s, "/");
if (g_str_has_prefix (sysfs_name + 1, "floppy.")
&& device->drive_vendor == NULL )
{
device->drive_vendor = g_strdup( "Floppy Drive" );
connection_interface = "platform";
}
}
g_free (subsystem);
}
/* advance up the chain */
p = g_strrstr (s, "/");
if (p == NULL)
break;
*p = '\0';
/* but stop at the root */
if (strcmp (s, "/sys/devices") == 0)
break;
}
while (TRUE);
if (connection_interface != NULL)
{
device->drive_connection_interface = g_strdup( connection_interface );
device->drive_connection_speed = connection_speed;
}
g_free (s);
}
static const struct
{
const char *udev_property;
const char *media_name;
} drive_media_mapping[] =
{
{ "ID_DRIVE_FLASH", "flash" },
{ "ID_DRIVE_FLASH_CF", "flash_cf" },
{ "ID_DRIVE_FLASH_MS", "flash_ms" },
{ "ID_DRIVE_FLASH_SM", "flash_sm" },
{ "ID_DRIVE_FLASH_SD", "flash_sd" },
{ "ID_DRIVE_FLASH_SDHC", "flash_sdhc" },
{ "ID_DRIVE_FLASH_MMC", "flash_mmc" },
{ "ID_DRIVE_FLOPPY", "floppy" },
{ "ID_DRIVE_FLOPPY_ZIP", "floppy_zip" },
{ "ID_DRIVE_FLOPPY_JAZ", "floppy_jaz" },
{ "ID_CDROM", "optical_cd" },
{ "ID_CDROM_CD_R", "optical_cd_r" },
{ "ID_CDROM_CD_RW", "optical_cd_rw" },
{ "ID_CDROM_DVD", "optical_dvd" },
{ "ID_CDROM_DVD_R", "optical_dvd_r" },
{ "ID_CDROM_DVD_RW", "optical_dvd_rw" },
{ "ID_CDROM_DVD_RAM", "optical_dvd_ram" },
{ "ID_CDROM_DVD_PLUS_R", "optical_dvd_plus_r" },
{ "ID_CDROM_DVD_PLUS_RW", "optical_dvd_plus_rw" },
{ "ID_CDROM_DVD_PLUS_R_DL", "optical_dvd_plus_r_dl" },
{ "ID_CDROM_DVD_PLUS_RW_DL", "optical_dvd_plus_rw_dl" },
{ "ID_CDROM_BD", "optical_bd" },
{ "ID_CDROM_BD_R", "optical_bd_r" },
{ "ID_CDROM_BD_RE", "optical_bd_re" },
{ "ID_CDROM_HDDVD", "optical_hddvd" },
{ "ID_CDROM_HDDVD_R", "optical_hddvd_r" },
{ "ID_CDROM_HDDVD_RW", "optical_hddvd_rw" },
{ "ID_CDROM_MO", "optical_mo" },
{ "ID_CDROM_MRW", "optical_mrw" },
{ "ID_CDROM_MRW_W", "optical_mrw_w" },
{ NULL, NULL }, };
static const struct
{
const char *udev_property;
const char *media_name;
} media_mapping[] =
{
{ "ID_DRIVE_MEDIA_FLASH", "flash" },
{ "ID_DRIVE_MEDIA_FLASH_CF", "flash_cf" },
{ "ID_DRIVE_MEDIA_FLASH_MS", "flash_ms" },
{ "ID_DRIVE_MEDIA_FLASH_SM", "flash_sm" },
{ "ID_DRIVE_MEDIA_FLASH_SD", "flash_sd" },
{ "ID_DRIVE_MEDIA_FLASH_SDHC", "flash_sdhc" },
{ "ID_DRIVE_MEDIA_FLASH_MMC", "flash_mmc" },
{ "ID_DRIVE_MEDIA_FLOPPY", "floppy" },
{ "ID_DRIVE_MEDIA_FLOPPY_ZIP", "floppy_zip" },
{ "ID_DRIVE_MEDIA_FLOPPY_JAZ", "floppy_jaz" },
{ "ID_CDROM_MEDIA_CD", "optical_cd" },
{ "ID_CDROM_MEDIA_CD_R", "optical_cd_r" },
{ "ID_CDROM_MEDIA_CD_RW", "optical_cd_rw" },
{ "ID_CDROM_MEDIA_DVD", "optical_dvd" },
{ "ID_CDROM_MEDIA_DVD_R", "optical_dvd_r" },
{ "ID_CDROM_MEDIA_DVD_RW", "optical_dvd_rw" },
{ "ID_CDROM_MEDIA_DVD_RAM", "optical_dvd_ram" },
{ "ID_CDROM_MEDIA_DVD_PLUS_R", "optical_dvd_plus_r" },
{ "ID_CDROM_MEDIA_DVD_PLUS_RW", "optical_dvd_plus_rw" },
{ "ID_CDROM_MEDIA_DVD_PLUS_R_DL", "optical_dvd_plus_r_dl" },
{ "ID_CDROM_MEDIA_DVD_PLUS_RW_DL", "optical_dvd_plus_rw_dl" },
{ "ID_CDROM_MEDIA_BD", "optical_bd" },
{ "ID_CDROM_MEDIA_BD_R", "optical_bd_r" },
{ "ID_CDROM_MEDIA_BD_RE", "optical_bd_re" },
{ "ID_CDROM_MEDIA_HDDVD", "optical_hddvd" },
{ "ID_CDROM_MEDIA_HDDVD_R", "optical_hddvd_r" },
{ "ID_CDROM_MEDIA_HDDVD_RW", "optical_hddvd_rw" },
{ "ID_CDROM_MEDIA_MO", "optical_mo" },
{ "ID_CDROM_MEDIA_MRW", "optical_mrw" },
{ "ID_CDROM_MEDIA_MRW_W", "optical_mrw_w" },
{ NULL, NULL }, };
void info_drive_properties ( device_t *device )
{
GPtrArray *media_compat_array;
const char *media_in_drive;
gboolean drive_is_ejectable;
gboolean drive_can_detach;
char *decoded_string;
guint n;
const char *value;
// drive identification
device->device_is_drive = sysfs_file_exists( device->native_path, "range" );
// vendor
if ( value = udev_device_get_property_value( device->udevice, "ID_VENDOR_ENC" ) )
{
decoded_string = decode_udev_encoded_string ( value );
g_strstrip (decoded_string);
device->drive_vendor = decoded_string;
}
else if ( value = udev_device_get_property_value( device->udevice, "ID_VENDOR" ) )
{
device->drive_vendor = g_strdup( value );
}
// model
if ( value = udev_device_get_property_value( device->udevice, "ID_MODEL_ENC" ) )
{
decoded_string = decode_udev_encoded_string ( value );
g_strstrip (decoded_string);
device->drive_model = decoded_string;
}
else if ( value = udev_device_get_property_value( device->udevice, "ID_MODEL" ) )
{
device->drive_model = g_strdup( value );
}
// revision
device->drive_revision = g_strdup( udev_device_get_property_value(
device->udevice, "ID_REVISION" ) );
// serial
if ( value = udev_device_get_property_value( device->udevice, "ID_SCSI_SERIAL" ) )
{
/* scsi_id sometimes use the WWN as the serial - annoying - see
* http://git.kernel.org/?p=linux/hotplug/udev.git;a=commit;h=4e9fdfccbdd16f0cfdb5c8fa8484a8ba0f2e69d3
* for details
*/
device->drive_serial = g_strdup( value );
}
else if ( value = udev_device_get_property_value( device->udevice, "ID_SERIAL_SHORT" ) )
{
device->drive_serial = g_strdup( value );
}
// wwn
if ( value = udev_device_get_property_value( device->udevice, "ID_WWN_WITH_EXTENSION" ) )
{
device->drive_wwn = g_strdup( value + 2 );
}
else if ( value = udev_device_get_property_value( device->udevice, "ID_WWN" ) )
{
device->drive_wwn = g_strdup( value + 2 );
}
/* pick up some things (vendor, model, connection_interface, connection_speed)
* not (yet) exported by udev helpers
*/
//update_drive_properties_from_sysfs (device);
info_drive_connection( device );
// is_ejectable
if ( value = udev_device_get_property_value( device->udevice, "ID_DRIVE_EJECTABLE" ) )
{
drive_is_ejectable = atoi( value ) != 0;
}
else
{
drive_is_ejectable = FALSE;
drive_is_ejectable |= ( udev_device_get_property_value(
device->udevice, "ID_CDROM" ) != NULL );
drive_is_ejectable |= ( udev_device_get_property_value(
device->udevice, "ID_DRIVE_FLOPPY_ZIP" ) != NULL );
drive_is_ejectable |= ( udev_device_get_property_value(
device->udevice, "ID_DRIVE_FLOPPY_JAZ" ) != NULL );
}
device->drive_is_media_ejectable = drive_is_ejectable;
// drive_media_compatibility
media_compat_array = g_ptr_array_new ();
for (n = 0; drive_media_mapping[n].udev_property != NULL; n++)
{
if ( udev_device_get_property_value( device->udevice,
drive_media_mapping[n].udev_property ) == NULL )
continue;
g_ptr_array_add (media_compat_array, (gpointer) drive_media_mapping[n].media_name);
}
/* special handling for SDIO since we don't yet have a sdio_id helper in udev to set properties */
if (g_strcmp0 (device->drive_connection_interface, "sdio") == 0)
{
gchar *type;
type = sysfs_get_string (device->native_path, "../../type");
g_strstrip (type);
if (g_strcmp0 (type, "MMC") == 0)
{
g_ptr_array_add (media_compat_array, "flash_mmc");
}
else if (g_strcmp0 (type, "SD") == 0)
{
g_ptr_array_add (media_compat_array, "flash_sd");
}
else if (g_strcmp0 (type, "SDHC") == 0)
{
g_ptr_array_add (media_compat_array, "flash_sdhc");
}
g_free (type);
}
g_ptr_array_sort (media_compat_array, (GCompareFunc) ptr_str_array_compare);
g_ptr_array_add (media_compat_array, NULL);
device->drive_media_compatibility = g_strjoinv( " ", (gchar**)media_compat_array->pdata );
// drive_media
media_in_drive = NULL;
if (device->device_is_media_available)
{
for (n = 0; media_mapping[n].udev_property != NULL; n++)
{
if ( udev_device_get_property_value( device->udevice,
media_mapping[n].udev_property ) == NULL )
continue;
// should this be media_mapping[n] ? doesn't matter, same?
media_in_drive = drive_media_mapping[n].media_name;
break;
}
/* If the media isn't set (from e.g. udev rules), just pick the first one in media_compat - note
* that this may be NULL (if we don't know what media is compatible with the drive) which is OK.
*/
if (media_in_drive == NULL)
media_in_drive = ((const gchar **) media_compat_array->pdata)[0];
}
device->drive_media = g_strdup( media_in_drive );
g_ptr_array_free (media_compat_array, TRUE);
// drive_can_detach
// right now, we only offer to detach USB devices
drive_can_detach = FALSE;
if (g_strcmp0 (device->drive_connection_interface, "usb") == 0)
{
drive_can_detach = TRUE;
}
if ( value = udev_device_get_property_value( device->udevice, "ID_DRIVE_DETACHABLE" ) )
{
drive_can_detach = atoi( value ) != 0;
}
device->drive_can_detach = drive_can_detach;
}
void info_device_properties( device_t *device )
{
const char* value;
device->native_path = g_strdup( udev_device_get_syspath( device->udevice ) );
device->devnode = g_strdup( udev_device_get_devnode( device->udevice ) );
device->major = g_strdup( udev_device_get_property_value( device->udevice, "MAJOR") );
device->minor = g_strdup( udev_device_get_property_value( device->udevice, "MINOR") );
if ( !device->native_path || !device->devnode || !device->major || !device->minor )
{
if ( device->native_path )
g_free( device->native_path );
device->native_path = NULL;
return;
}
//by id - would need to read symlinks in /dev/disk/by-id
// is_removable may also be set in info_drive_connection walking up sys tree
device->device_is_removable = sysfs_get_int( device->native_path, "removable");
device->device_presentation_hide = g_strdup( udev_device_get_property_value(
device->udevice, "UDISKS_PRESENTATION_HIDE") );
device->device_presentation_nopolicy = g_strdup( udev_device_get_property_value(
device->udevice, "UDISKS_PRESENTATION_NOPOLICY") );
device->device_presentation_name = g_strdup( udev_device_get_property_value(
device->udevice, "UDISKS_PRESENTATION_NAME") );
device->device_presentation_icon_name = g_strdup( udev_device_get_property_value(
device->udevice, "UDISKS_PRESENTATION_ICON_NAME") );
device->device_automount_hint = g_strdup( udev_device_get_property_value(
device->udevice, "UDISKS_AUTOMOUNT_HINT") );
// filesystem properties
gchar *decoded_string;
const gchar *partition_scheme;
gint partition_type = 0;
partition_scheme = udev_device_get_property_value( device->udevice, "UDISKS_PARTITION_SCHEME");
if ( value = udev_device_get_property_value( device->udevice, "UDISKS_PARTITION_TYPE") )
partition_type = atoi( value );
if (g_strcmp0 (partition_scheme, "mbr") == 0 && (partition_type == 0x05 ||
partition_type == 0x0f ||
partition_type == 0x85))
{
}
else
{
device->id_usage = g_strdup( udev_device_get_property_value( device->udevice,
"ID_FS_USAGE" ) );
device->id_type = g_strdup( udev_device_get_property_value( device->udevice,
"ID_FS_TYPE" ) );
device->id_version = g_strdup( udev_device_get_property_value( device->udevice,
"ID_FS_VERSION" ) );
device->id_uuid = g_strdup( udev_device_get_property_value( device->udevice,
"ID_FS_UUID" ) );
if ( value = udev_device_get_property_value( device->udevice, "ID_FS_LABEL_ENC" ) )
{
decoded_string = decode_udev_encoded_string ( value );
g_strstrip (decoded_string);
device->id_label = decoded_string;
}
else if ( value = udev_device_get_property_value( device->udevice, "ID_FS_LABEL" ) )
{
device->id_label = g_strdup( value );
}
}
// device_is_media_available
gboolean media_available = FALSE;
if ( ( device->id_usage && device->id_usage[0] != '\0' ) ||
( device->id_type && device->id_type[0] != '\0' ) ||
( device->id_uuid && device->id_uuid[0] != '\0' ) ||
( device->id_label && device->id_label[0] != '\0' ) )
{
media_available = TRUE;
}
else if ( g_str_has_prefix( device->devnode, "/dev/loop" ) )
media_available = FALSE;
else if ( device->device_is_removable )
{
gboolean is_cd, is_floppy;
if ( value = udev_device_get_property_value( device->udevice, "ID_CDROM" ) )
is_cd = atoi( value ) != 0;
else
is_cd = FALSE;
if ( value = udev_device_get_property_value( device->udevice, "ID_DRIVE_FLOPPY" ) )
is_floppy = atoi( value ) != 0;
else
is_floppy = FALSE;
if ( !is_cd && !is_floppy )
{
// this test is limited for non-root - user may not have read
// access to device file even if media is present
int fd;
fd = open( device->devnode, O_RDONLY );
if ( fd >= 0 )
{
media_available = TRUE;
close( fd );
}
}
else if ( value = udev_device_get_property_value( device->udevice, "ID_CDROM_MEDIA" ) )
media_available = ( atoi( value ) == 1 );
}
else if ( value = udev_device_get_property_value( device->udevice, "ID_CDROM_MEDIA" ) )
media_available = ( atoi( value ) == 1 );
else
media_available = TRUE;
device->device_is_media_available = media_available;
/* device_size, device_block_size and device_is_read_only properties */
if (device->device_is_media_available)
{
guint64 block_size;
device->device_size = sysfs_get_uint64( device->native_path, "size")
* ((guint64) 512);
device->device_is_read_only = (sysfs_get_int (device->native_path,
"ro") != 0);
/* This is not available on all devices so fall back to 512 if unavailable.
*
* Another way to get this information is the BLKSSZGET ioctl but we don't want
* to open the device. Ideally vol_id would export it.
*/
block_size = sysfs_get_uint64 (device->native_path, "queue/hw_sector_size");
if (block_size == 0)
block_size = 512;
device->device_block_size = block_size;
}
else
{
device->device_size = device->device_block_size = 0;
device->device_is_read_only = FALSE;
}
// links
struct udev_list_entry *entry = udev_device_get_devlinks_list_entry(
device->udevice );
while ( entry )
{
const char *entry_name = udev_list_entry_get_name( entry );
if ( entry_name && ( g_str_has_prefix( entry_name, "/dev/disk/by-id/" )
|| g_str_has_prefix( entry_name, "/dev/disk/by-uuid/" ) ) )
{
device->device_by_id = g_strdup( entry_name );
break;
}
entry = udev_list_entry_get_next( entry );
}
}
gchar* info_mount_points( device_t *device )
{
gchar *contents;
gchar **lines;
GError *error;
guint n;
GList* mounts = NULL;
if ( !device->major || !device->minor )
return NULL;
guint dmajor = atoi( device->major );
guint dminor = atoi( device->minor );
// if we have the mount point list, use this instead of reading mountinfo
if ( devmounts )
{
GList* l;
for ( l = devmounts; l; l = l->next )
{
if ( ((devmount_t*)l->data)->major == dmajor &&
((devmount_t*)l->data)->minor == dminor )
{
return g_strdup( ((devmount_t*)l->data)->mount_points );
}
}
return NULL;
}
contents = NULL;
lines = NULL;
error = NULL;
if (!g_file_get_contents ("/proc/self/mountinfo", &contents, NULL, &error))
{
g_warning ("Error reading /proc/self/mountinfo: %s", error->message);
g_error_free (error);
return NULL;
}
/* See Documentation/filesystems/proc.txt for the format of /proc/self/mountinfo
*
* Note that things like space are encoded as \020.
*/
lines = g_strsplit (contents, "\n", 0);
for (n = 0; lines[n] != NULL; n++)
{
guint mount_id;
guint parent_id;
guint major, minor;
gchar encoded_root[PATH_MAX];
gchar encoded_mount_point[PATH_MAX];
gchar *mount_point;
//dev_t dev;
if (strlen (lines[n]) == 0)
continue;
if (sscanf (lines[n],
"%d %d %d:%d %s %s",
&mount_id,
&parent_id,
&major,
&minor,
encoded_root,
encoded_mount_point) != 6)
{
g_warning ("Error reading /proc/self/mountinfo: Error parsing line '%s'", lines[n]);
continue;
}
/* ignore mounts where only a subtree of a filesystem is mounted */
if (g_strcmp0 (encoded_root, "/") != 0)
continue;
/* Temporary work-around for btrfs, see
*
* https://github.com/IgnorantGuru/spacefm/issues/165
* http://article.gmane.org/gmane.comp.file-systems.btrfs/2851
* https://bugzilla.redhat.com/show_bug.cgi?id=495152#c31
*/
if ( major == 0 )
{
const gchar *sep;
sep = strstr( lines[n], " - " );
if ( sep != NULL )
{
gchar typebuf[PATH_MAX];
gchar mount_source[PATH_MAX];
struct stat statbuf;
if ( sscanf( sep + 3, "%s %s", typebuf, mount_source ) == 2 &&
!g_strcmp0( typebuf, "btrfs" ) &&
g_str_has_prefix( mount_source, "/dev/" ) &&
stat( mount_source, &statbuf ) == 0 &&
S_ISBLK( statbuf.st_mode ) )
{
major = major( statbuf.st_rdev );
minor = minor( statbuf.st_rdev );
}
}
}
if ( major != dmajor || minor != dminor )
continue;
mount_point = g_strcompress (encoded_mount_point);
if ( mount_point && mount_point[0] != '\0' )
{
if ( !g_list_find( mounts, mount_point ) )
{
mounts = g_list_prepend( mounts, mount_point );
}
else
g_free (mount_point);
}
}
g_free (contents);
g_strfreev (lines);
if ( mounts )
{
gchar *points, *old_points;
GList* l;
// Sort the list to ensure that shortest mount paths appear first
mounts = g_list_sort( mounts, (GCompareFunc) g_strcmp0 );
points = g_strdup( (gchar*)mounts->data );
l = mounts;
while ( l = l->next )
{
old_points = points;
points = g_strdup_printf( "%s, %s", old_points, (gchar*)l->data );
g_free( old_points );
}
g_list_foreach( mounts, (GFunc)g_free, NULL );
g_list_free( mounts );
return points;
}
else
return NULL;
}
void info_partition_table( device_t *device )
{
gboolean is_partition_table = FALSE;
const char* value;
/* Check if udisks-part-id identified the device as a partition table.. this includes
* identifying partition tables set up by kpartx for multipath etc.
*/
if ( ( value = udev_device_get_property_value( device->udevice, "UDISKS_PARTITION_TABLE" ) )
&& atoi( value ) == 1 )
{
device->partition_table_scheme = g_strdup( udev_device_get_property_value(
device->udevice,
"UDISKS_PARTITION_TABLE_SCHEME" ) );
device->partition_table_count = g_strdup( udev_device_get_property_value(
device->udevice,
"UDISKS_PARTITION_TABLE_COUNT" ) );
is_partition_table = TRUE;
}
/* Note that udisks-part-id might not detect all partition table
* formats.. so in the negative case, also double check with
* information in sysfs.
*
* The kernel guarantees that all childs are created before the
* uevent for the parent is created. So if we have childs, we must
* be a partition table.
*
* To detect a child we check for the existance of a subdir that has
* the parents name as a prefix (e.g. for parent sda then sda1,
* sda2, sda3 ditto md0, md0p1 etc. etc. will work).
*/
if (!is_partition_table)
{
gchar *s;
GDir *dir;
s = g_path_get_basename (device->native_path);
if ((dir = g_dir_open (device->native_path, 0, NULL)) != NULL)
{
guint partition_count;
const gchar *name;
partition_count = 0;
while ((name = g_dir_read_name (dir)) != NULL)
{
if (g_str_has_prefix (name, s))
{
partition_count++;
}
}
g_dir_close (dir);
if (partition_count > 0)
{
device->partition_table_scheme = g_strdup( "" );
device->partition_table_count = g_strdup_printf( "%d", partition_count );
is_partition_table = TRUE;
}
}
g_free (s);
}
device->device_is_partition_table = is_partition_table;
if (!is_partition_table)
{
if ( device->partition_table_scheme )
g_free( device->partition_table_scheme );
device->partition_table_scheme = NULL;
if ( device->partition_table_count )
g_free( device->partition_table_count );
device->partition_table_count = NULL;
}
}
void info_partition( device_t *device )
{
gboolean is_partition = FALSE;
/* Check if udisks-part-id identified the device as a partition.. this includes
* identifying partitions set up by kpartx for multipath
*/
if ( udev_device_get_property_value( device->udevice,"UDISKS_PARTITION" ) )
{
const gchar *size;
const gchar *scheme;
const gchar *type;
const gchar *label;
const gchar *uuid;
const gchar *flags;
const gchar *offset;
const gchar *alignment_offset;
const gchar *slave_sysfs_path;
const gchar *number;
scheme = udev_device_get_property_value( device->udevice, "UDISKS_PARTITION_SCHEME");
size = udev_device_get_property_value( device->udevice, "UDISKS_PARTITION_SIZE");
type = udev_device_get_property_value( device->udevice, "UDISKS_PARTITION_TYPE");
label = udev_device_get_property_value( device->udevice, "UDISKS_PARTITION_LABEL");
uuid = udev_device_get_property_value( device->udevice, "UDISKS_PARTITION_UUID");
flags = udev_device_get_property_value( device->udevice, "UDISKS_PARTITION_FLAGS");
offset = udev_device_get_property_value( device->udevice, "UDISKS_PARTITION_OFFSET");
alignment_offset = udev_device_get_property_value( device->udevice,
"UDISKS_PARTITION_ALIGNMENT_OFFSET");
number = udev_device_get_property_value( device->udevice, "UDISKS_PARTITION_NUMBER");
slave_sysfs_path = udev_device_get_property_value( device->udevice, "UDISKS_PARTITION_SLAVE");
if (slave_sysfs_path != NULL && scheme != NULL && number != NULL && atoi( number ) > 0)
{
device->partition_scheme = g_strdup( scheme );
device->partition_size = g_strdup( size );
device->partition_type = g_strdup( type );
device->partition_label = g_strdup( label );
device->partition_uuid = g_strdup( uuid );
device->partition_flags = g_strdup( flags );
device->partition_offset = g_strdup( offset );
device->partition_alignment_offset = g_strdup( alignment_offset );
device->partition_number = g_strdup( number );
is_partition = TRUE;
}
}
/* Also handle the case where we are partitioned by the kernel and don't have
* any UDISKS_PARTITION_* properties.
*
* This works without any udev UDISKS_PARTITION_* properties and is
* there for maximum compatibility since udisks-part-id only knows a
* limited set of partition table formats.
*/
if (!is_partition && sysfs_file_exists (device->native_path, "start"))
{
guint64 size;
guint64 offset;
guint64 alignment_offset;
gchar *s;
guint n;
size = sysfs_get_uint64 (device->native_path, "size");
alignment_offset = sysfs_get_uint64 (device->native_path, "alignment_offset");
device->partition_size = g_strdup_printf( "%lu", size * 512 );
device->partition_alignment_offset = g_strdup_printf( "%lu", alignment_offset );
offset = sysfs_get_uint64 (device->native_path, "start") * device->device_block_size;
device->partition_offset = g_strdup_printf( "%lu", offset );
s = device->native_path;
for (n = strlen (s) - 1; n >= 0 && g_ascii_isdigit (s[n]); n--)
;
device->partition_number = g_strdup_printf( "%ld", strtol (s + n + 1, NULL, 0) );
/*
s = g_strdup (device->priv->native_path);
for (n = strlen (s) - 1; n >= 0 && s[n] != '/'; n--)
s[n] = '\0';
s[n] = '\0';
device_set_partition_slave (device, compute_object_path (s));
g_free (s);
*/
is_partition = TRUE;
}
device->device_is_partition = is_partition;
if (!is_partition)
{
device->partition_scheme = NULL;
device->partition_size = NULL;
device->partition_type = NULL;
device->partition_label = NULL;
device->partition_uuid = NULL;
device->partition_flags = NULL;
device->partition_offset = NULL;
device->partition_alignment_offset = NULL;
device->partition_number = NULL;
}
else
{
device->device_is_drive = FALSE;
}
}
void info_optical_disc( device_t *device )
{
const char *cdrom_disc_state;
if ( udev_device_get_property_value( device->udevice, "ID_CDROM_MEDIA") )
{
device->device_is_optical_disc = TRUE;
device->optical_disc_num_tracks = g_strdup( udev_device_get_property_value(
device->udevice, "ID_CDROM_MEDIA_TRACK_COUNT") );
device->optical_disc_num_audio_tracks = g_strdup( udev_device_get_property_value(
device->udevice, "ID_CDROM_MEDIA_TRACK_COUNT_AUDIO") );
device->optical_disc_num_sessions = g_strdup( udev_device_get_property_value(
device->udevice, "ID_CDROM_MEDIA_SESSION_COUNT") );
cdrom_disc_state = udev_device_get_property_value( device->udevice, "ID_CDROM_MEDIA_STATE");
device->optical_disc_is_blank = ( g_strcmp0( cdrom_disc_state,
"blank" ) == 0);
device->optical_disc_is_appendable = ( g_strcmp0( cdrom_disc_state,
"appendable" ) == 0);
device->optical_disc_is_closed = ( g_strcmp0( cdrom_disc_state,
"complete" ) == 0);
}
else
device->device_is_optical_disc = FALSE;
}
static void device_free( device_t *device )
{
if ( !device )
return;
g_free( device->native_path );
g_free( device->major );
g_free( device->minor );
g_free( device->mount_points );
g_free( device->devnode );
g_free( device->device_presentation_hide );
g_free( device->device_presentation_nopolicy );
g_free( device->device_presentation_name );
g_free( device->device_presentation_icon_name );
g_free( device->device_automount_hint );
g_free( device->device_by_id );
g_free( device->id_usage );
g_free( device->id_type );
g_free( device->id_version );
g_free( device->id_uuid );
g_free( device->id_label );
g_free( device->drive_vendor );
g_free( device->drive_model );
g_free( device->drive_revision );
g_free( device->drive_serial );
g_free( device->drive_wwn );
g_free( device->drive_connection_interface );
g_free( device->drive_media_compatibility );
g_free( device->drive_media );
g_free( device->partition_scheme );
g_free( device->partition_number );
g_free( device->partition_type );
g_free( device->partition_label );
g_free( device->partition_uuid );
g_free( device->partition_flags );
g_free( device->partition_offset );
g_free( device->partition_size );
g_free( device->partition_alignment_offset );
g_free( device->partition_table_scheme );
g_free( device->partition_table_count );
g_free( device->optical_disc_num_tracks );
g_free( device->optical_disc_num_audio_tracks );
g_free( device->optical_disc_num_sessions );
g_slice_free( device_t, device );
}
device_t *device_alloc( struct udev_device *udevice )
{
device_t *device = g_slice_new0( device_t );
device->udevice = udevice;
device->native_path = NULL;
device->major = NULL;
device->minor = NULL;
device->mount_points = NULL;
device->devnode = NULL;
device->device_is_system_internal = TRUE;
device->device_is_partition = FALSE;
device->device_is_partition_table = FALSE;
device->device_is_removable = FALSE;
device->device_is_media_available = FALSE;
device->device_is_read_only = FALSE;
device->device_is_drive = FALSE;
device->device_is_optical_disc = FALSE;
device->device_is_mounted = FALSE;
device->device_presentation_hide = NULL;
device->device_presentation_nopolicy = NULL;
device->device_presentation_name = NULL;
device->device_presentation_icon_name = NULL;
device->device_automount_hint = NULL;
device->device_by_id = NULL;
device->device_size = 0;
device->device_block_size = 0;
device->id_usage = NULL;
device->id_type = NULL;
device->id_version = NULL;
device->id_uuid = NULL;
device->id_label = NULL;
device->drive_vendor = NULL;
device->drive_model = NULL;
device->drive_revision = NULL;
device->drive_serial = NULL;
device->drive_wwn = NULL;
device->drive_connection_interface = NULL;
device->drive_connection_speed = 0;
device->drive_media_compatibility = NULL;
device->drive_media = NULL;
device->drive_is_media_ejectable = FALSE;
device->drive_can_detach = FALSE;
device->partition_scheme = NULL;
device->partition_number = NULL;
device->partition_type = NULL;
device->partition_label = NULL;
device->partition_uuid = NULL;
device->partition_flags = NULL;
device->partition_offset = NULL;
device->partition_size = NULL;
device->partition_alignment_offset = NULL;
device->partition_table_scheme = NULL;
device->partition_table_count = NULL;
device->optical_disc_is_blank = FALSE;
device->optical_disc_is_appendable = FALSE;
device->optical_disc_is_closed = FALSE;
device->optical_disc_num_tracks = NULL;
device->optical_disc_num_audio_tracks = NULL;
device->optical_disc_num_sessions = NULL;
return device;
}
gboolean device_get_info( device_t *device )
{
info_device_properties( device );
if ( !device->native_path )
return FALSE;
info_drive_properties( device );
device->device_is_system_internal = info_is_system_internal( device );
device->mount_points = info_mount_points( device );
device->device_is_mounted = ( device->mount_points != NULL );
info_partition_table( device );
info_partition( device );
info_optical_disc( device );
return TRUE;
}
char* device_show_info( device_t *device )
{
gchar* line[140];
int i = 0;
line[i++] = g_strdup_printf("Showing information for %s\n", device->devnode );
line[i++] = g_strdup_printf(" native-path: %s\n", device->native_path );
line[i++] = g_strdup_printf(" device: %s:%s\n", device->major, device->minor );
line[i++] = g_strdup_printf(" device-file: %s\n", device->devnode );
line[i++] = g_strdup_printf(" presentation: %s\n", device->devnode );
if ( device->device_by_id )
line[i++] = g_strdup_printf(" by-id: %s\n", device->device_by_id );
line[i++] = g_strdup_printf(" system internal: %d\n", device->device_is_system_internal );
line[i++] = g_strdup_printf(" removable: %d\n", device->device_is_removable);
line[i++] = g_strdup_printf(" has media: %d\n", device->device_is_media_available);
line[i++] = g_strdup_printf(" is read only: %d\n", device->device_is_read_only );
line[i++] = g_strdup_printf(" is mounted: %d\n", device->device_is_mounted );
line[i++] = g_strdup_printf(" mount paths: %s\n", device->mount_points ? device->mount_points : "" );
line[i++] = g_strdup_printf(" presentation hide: %s\n", device->device_presentation_hide ?
device->device_presentation_hide : "0" );
line[i++] = g_strdup_printf(" presentation nopolicy: %s\n", device->device_presentation_nopolicy ?
device->device_presentation_nopolicy : "0" );
line[i++] = g_strdup_printf(" presentation name: %s\n", device->device_presentation_name ?
device->device_presentation_name : "" );
line[i++] = g_strdup_printf(" presentation icon: %s\n", device->device_presentation_icon_name ?
device->device_presentation_icon_name : "" );
line[i++] = g_strdup_printf(" automount hint: %s\n", device->device_automount_hint ?
device->device_automount_hint : "" );
line[i++] = g_strdup_printf(" size: %" G_GUINT64_FORMAT "\n", device->device_size);
line[i++] = g_strdup_printf(" block size: %" G_GUINT64_FORMAT "\n", device->device_block_size);
line[i++] = g_strdup_printf(" usage: %s\n", device->id_usage ? device->id_usage : "" );
line[i++] = g_strdup_printf(" type: %s\n", device->id_type ? device->id_type : "" );
line[i++] = g_strdup_printf(" version: %s\n", device->id_version ? device->id_version : "" );
line[i++] = g_strdup_printf(" uuid: %s\n", device->id_uuid ? device->id_uuid : "" );
line[i++] = g_strdup_printf(" label: %s\n", device->id_label ? device->id_label : "" );
if (device->device_is_partition_table)
{
line[i++] = g_strdup_printf(" partition table:\n");
line[i++] = g_strdup_printf(" scheme: %s\n", device->partition_table_scheme ?
device->partition_table_scheme : "" );
line[i++] = g_strdup_printf(" count: %s\n", device->partition_table_count ?
device->partition_table_count : "0" );
}
if (device->device_is_partition)
{
line[i++] = g_strdup_printf(" partition:\n");
line[i++] = g_strdup_printf(" scheme: %s\n", device->partition_scheme ?
device->partition_scheme : "" );
line[i++] = g_strdup_printf(" number: %s\n", device->partition_number ?
device->partition_number : "" );
line[i++] = g_strdup_printf(" type: %s\n", device->partition_type ?
device->partition_type : "" );
line[i++] = g_strdup_printf(" flags: %s\n", device->partition_flags ?
device->partition_flags : "" );
line[i++] = g_strdup_printf(" offset: %s\n", device->partition_offset ?
device->partition_offset : "" );
line[i++] = g_strdup_printf(" alignment offset: %s\n", device->partition_alignment_offset ?
device->partition_alignment_offset : "" );
line[i++] = g_strdup_printf(" size: %s\n", device->partition_size ?
device->partition_size : "" );
line[i++] = g_strdup_printf(" label: %s\n", device->partition_label ?
device->partition_label : "" );
line[i++] = g_strdup_printf(" uuid: %s\n", device->partition_uuid ?
device->partition_uuid : "" );
}
if (device->device_is_optical_disc)
{
line[i++] = g_strdup_printf(" optical disc:\n");
line[i++] = g_strdup_printf(" blank: %d\n", device->optical_disc_is_blank);
line[i++] = g_strdup_printf(" appendable: %d\n", device->optical_disc_is_appendable);
line[i++] = g_strdup_printf(" closed: %d\n", device->optical_disc_is_closed);
line[i++] = g_strdup_printf(" num tracks: %s\n", device->optical_disc_num_tracks ?
device->optical_disc_num_tracks : "0" );
line[i++] = g_strdup_printf(" num audio tracks: %s\n", device->optical_disc_num_audio_tracks ?
device->optical_disc_num_audio_tracks : "0" );
line[i++] = g_strdup_printf(" num sessions: %s\n", device->optical_disc_num_sessions ?
device->optical_disc_num_sessions : "0" );
}
if (device->device_is_drive)
{
line[i++] = g_strdup_printf(" drive:\n");
line[i++] = g_strdup_printf(" vendor: %s\n", device->drive_vendor ?
device->drive_vendor : "" );
line[i++] = g_strdup_printf(" model: %s\n", device->drive_model ?
device->drive_model : "" );
line[i++] = g_strdup_printf(" revision: %s\n", device->drive_revision ?
device->drive_revision : "" );
line[i++] = g_strdup_printf(" serial: %s\n", device->drive_serial ?
device->drive_serial : "" );
line[i++] = g_strdup_printf(" WWN: %s\n", device->drive_wwn ?
device->drive_wwn : "" );
line[i++] = g_strdup_printf(" detachable: %d\n", device->drive_can_detach);
line[i++] = g_strdup_printf(" ejectable: %d\n", device->drive_is_media_ejectable);
line[i++] = g_strdup_printf(" media: %s\n", device->drive_media ?
device->drive_media : "" );
line[i++] = g_strdup_printf(" compat: %s\n", device->drive_media_compatibility ?
device->drive_media_compatibility : "" );
if ( device->drive_connection_interface == NULL ||
strlen (device->drive_connection_interface) == 0 )
line[i++] = g_strdup_printf(" interface: (unknown)\n");
else
line[i++] = g_strdup_printf(" interface: %s\n", device->drive_connection_interface);
if (device->drive_connection_speed == 0)
line[i++] = g_strdup_printf(" if speed: (unknown)\n");
else
line[i++] = g_strdup_printf(" if speed: %" G_GINT64_FORMAT " bits/s\n",
device->drive_connection_speed);
}
line[i] = NULL;
gchar* output = g_strjoinv( NULL, line );
i = 0;
while ( line[i] )
g_free( line[i++] );
return output;
}
/* ************************************************************************
* udev & mount monitors
* ************************************************************************ */
gint cmp_devmounts( devmount_t *a, devmount_t *b )
{
if ( !a && !b )
return 0;
if ( !a || !b )
return 1;
if ( a->major == b->major && a->minor == b->minor )
return 0;
return 1;
}
void parse_mounts( gboolean report )
{
gchar *contents;
gchar **lines;
GError *error;
guint n;
//printf("\n@@@@@@@@@@@@@ parse_mounts %s\n\n", report ? "TRUE" : "FALSE" );
contents = NULL;
lines = NULL;
struct udev_device *udevice;
dev_t dev;
char* str;
error = NULL;
if (!g_file_get_contents ("/proc/self/mountinfo", &contents, NULL, &error))
{
g_warning ("Error reading /proc/self/mountinfo: %s", error->message);
g_error_free (error);
return;
}
// get all mount points for all devices
GList* newmounts = NULL;
GList* l;
GList* changed = NULL;
devmount_t *devmount;
/* See Documentation/filesystems/proc.txt for the format of /proc/self/mountinfo
*
* Note that things like space are encoded as \020.
*
* This file contains lines of the form:
* 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue
* (1)(2)(3) (4) (5) (6) (7) (8) (9) (10) (11)
* (1) mount ID: unique identifier of the mount (may be reused after umount)
* (2) parent ID: ID of parent (or of self for the top of the mount tree)
* (3) major:minor: value of st_dev for files on filesystem
* (4) root: root of the mount within the filesystem
* (5) mount point: mount point relative to the process's root
* (6) mount options: per mount options
* (7) optional fields: zero or more fields of the form "tag[:value]"
* (8) separator: marks the end of the optional fields
* (9) filesystem type: name of filesystem of the form "type[.subtype]"
* (10) mount source: filesystem specific information or "none"
* (11) super options: per super block options
* Parsers should ignore all unrecognised optional fields.
*/
lines = g_strsplit (contents, "\n", 0);
for ( n = 0; lines[n] != NULL; n++ )
{
guint mount_id;
guint parent_id;
guint major, minor;
gchar encoded_root[PATH_MAX];
gchar encoded_mount_point[PATH_MAX];
gchar* mount_point;
gchar* fstype;
if ( strlen( lines[n] ) == 0 )
continue;
if ( sscanf( lines[n],
"%d %d %d:%d %s %s",
&mount_id,
&parent_id,
&major,
&minor,
encoded_root,
encoded_mount_point ) != 6 )
{
g_warning ("Error reading /proc/self/mountinfo: Error parsing line '%s'", lines[n]);
continue;
}
/* ignore mounts where only a subtree of a filesystem is mounted */
if ( g_strcmp0( encoded_root, "/" ) != 0 )
continue;
/* Temporary work-around for btrfs, see
*
* https://github.com/IgnorantGuru/spacefm/issues/165
* http://article.gmane.org/gmane.comp.file-systems.btrfs/2851
* https://bugzilla.redhat.com/show_bug.cgi?id=495152#c31
*/
if ( major == 0 )
{
const gchar *sep;
sep = strstr( lines[n], " - " );
if ( sep != NULL )
{
gchar typebuf[PATH_MAX];
gchar mount_source[PATH_MAX];
struct stat statbuf;
if ( sscanf( sep + 3, "%s %s", typebuf, mount_source ) == 2 &&
!g_strcmp0( typebuf, "btrfs" ) &&
g_str_has_prefix( mount_source, "/dev/" ) &&
stat( mount_source, &statbuf ) == 0 &&
S_ISBLK( statbuf.st_mode ) )
{
major = major( statbuf.st_rdev );
minor = minor( statbuf.st_rdev );
}
}
}
mount_point = g_strcompress( encoded_mount_point );
if ( !mount_point || ( mount_point && mount_point[0] == '\0' ) )
{
g_free( mount_point );
continue;
}
// fstype
fstype = strstr( lines[n], " - " );
if ( fstype )
{
fstype += 3;
// modifies lines[n]
if ( str = strchr( fstype, ' ' ) )
str[0] = '\0';
}
//printf("mount_point(%d:%d)=%s\n", major, minor, mount_point );
devmount = NULL;
for ( l = newmounts; l; l = l->next )
{
if ( ((devmount_t*)l->data)->major == major &&
((devmount_t*)l->data)->minor == minor )
{
devmount = (devmount_t*)l->data;
break;
}
}
if ( !devmount )
{
//printf(" new devmount %s\n", mount_point);
if ( report )
{
devmount = g_slice_new0( devmount_t );
devmount->major = major;
devmount->minor = minor;
devmount->mount_points = NULL;
devmount->fstype = g_strdup( fstype );
devmount->mounts = NULL;
newmounts = g_list_prepend( newmounts, devmount );
}
else
{
// initial load !report don't add non-block devices
dev = makedev( major, minor );
udevice = udev_device_new_from_devnum( udev, 'b', dev );
if ( udevice )
{
udev_device_unref( udevice );
devmount = g_slice_new0( devmount_t );
devmount->major = major;
devmount->minor = minor;
devmount->mount_points = NULL;
devmount->fstype = g_strdup( fstype );
devmount->mounts = NULL;
newmounts = g_list_prepend( newmounts, devmount );
}
}
}
if ( devmount && !g_list_find( devmount->mounts, mount_point ) )
{
//printf(" prepended\n");
devmount->mounts = g_list_prepend( devmount->mounts, mount_point );
}
else
g_free (mount_point);
}
g_free( contents );
g_strfreev( lines );
//printf("\nLINES DONE\n\n");
// translate each mount points list to string
gchar *points, *old_points;
GList* m;
for ( l = newmounts; l; l = l->next )
{
devmount = (devmount_t*)l->data;
// Sort the list to ensure that shortest mount paths appear first
devmount->mounts = g_list_sort( devmount->mounts, (GCompareFunc) g_strcmp0 );
m = devmount->mounts;
points = g_strdup( (gchar*)m->data );
while ( m = m->next )
{
old_points = points;
points = g_strdup_printf( "%s, %s", old_points, (gchar*)m->data );
g_free( old_points );
}
g_list_foreach( devmount->mounts, (GFunc)g_free, NULL );
g_list_free( devmount->mounts );
devmount->mounts = NULL;
devmount->mount_points = points;
//printf( "translate %d:%d %s\n", devmount->major, devmount->minor, points );
}
// compare old and new lists
GList* found;
if ( report )
{
for ( l = newmounts; l; l = l->next )
{
devmount = (devmount_t*)l->data;
//printf("finding %d:%d\n", devmount->major, devmount->minor );
found = g_list_find_custom( devmounts, (gconstpointer)devmount,
(GCompareFunc)cmp_devmounts );
if ( found )
{
//printf(" found\n");
if ( !g_strcmp0( ((devmount_t*)found->data)->mount_points,
devmount->mount_points ) )
{
//printf(" freed\n");
// no change to mount points, so remove from old list
devmount = (devmount_t*)found->data;
g_free( devmount->mount_points );
g_free( devmount->fstype );
devmounts = g_list_remove( devmounts, devmount );
g_slice_free( devmount_t, devmount );
}
}
else
{
// new mount
//printf(" new mount %d:%d %s\n", devmount->major, devmount->minor, devmount->mount_points );
devmount_t* devcopy = g_slice_new0( devmount_t );
devcopy->major = devmount->major;
devcopy->minor = devmount->minor;
devcopy->mount_points = g_strdup( devmount->mount_points );
devcopy->fstype = g_strdup( devmount->fstype );
devcopy->mounts = NULL;
changed = g_list_prepend( changed, devcopy );
}
}
}
//printf( "\nREMAINING\n\n");
// any remaining devices in old list have changed mount status
for ( l = devmounts; l; l = l->next )
{
devmount = (devmount_t*)l->data;
//printf("remain %d:%d\n", devmount->major, devmount->minor );
if ( report )
{
changed = g_list_prepend( changed, devmount );
}
else
{
g_free( devmount->mount_points );
g_free( devmount->fstype );
g_slice_free( devmount_t, devmount );
}
}
g_list_free( devmounts );
devmounts = newmounts;
// report
if ( report && changed )
{
VFSVolume* volume;
char* devnode;
for ( l = changed; l; l = l->next )
{
devnode = NULL;
devmount = (devmount_t*)l->data;
dev = makedev( devmount->major, devmount->minor );
udevice = udev_device_new_from_devnum( udev, 'b', dev );
if ( udevice )
devnode = g_strdup( udev_device_get_devnode( udevice ) );
if ( devnode )
{
printf( "mount changed: %s\n", devnode );
if ( volume = vfs_volume_read_by_device( udevice ) )
vfs_volume_device_added( volume, TRUE ); //frees volume if needed
g_free( devnode );
}
else
{
// not a block device
if ( volume = vfs_volume_read_by_mount( devmount->mount_points ) )
{
printf( "network mount changed: %s\n", devmount->mount_points );
vfs_volume_device_added( volume, FALSE ); //frees volume if needed
}
else
vfs_volume_nonblock_removed( devmount->mount_points );
}
udev_device_unref( udevice );
g_free( devmount->mount_points );
g_free( devmount->fstype );
g_slice_free( devmount_t, devmount );
}
g_list_free( changed );
}
//printf ( "END PARSE\n");
}
static void free_devmounts()
{
GList* l;
devmount_t *devmount;
if ( !devmounts )
return;
for ( l = devmounts; l; l = l->next )
{
devmount = (devmount_t*)l->data;
g_free( devmount->mount_points );
g_free( devmount->fstype );
g_slice_free( devmount_t, devmount );
}
g_list_free( devmounts );
devmounts = NULL;
}
const char* get_devmount_fstype( int major, int minor )
{
GList* l;
for ( l = devmounts; l; l = l->next )
{
if ( ((devmount_t*)l->data)->major == major &&
((devmount_t*)l->data)->minor == minor )
return ((devmount_t*)l->data)->fstype;
}
return NULL;
}
static gboolean cb_mount_monitor_watch( GIOChannel *channel, GIOCondition cond,
gpointer user_data )
{
if ( cond & ~G_IO_ERR )
return TRUE;
//printf ("@@@ /proc/self/mountinfo changed\n");
parse_mounts( TRUE );
return TRUE;
}
static gboolean cb_udev_monitor_watch( GIOChannel *channel, GIOCondition cond,
gpointer user_data )
{
/*
printf("cb_monitor_watch %d\n", channel);
if ( cond & G_IO_IN )
printf(" G_IO_IN\n");
if ( cond & G_IO_OUT )
printf(" G_IO_OUT\n");
if ( cond & G_IO_PRI )
printf(" G_IO_PRI\n");
if ( cond & G_IO_ERR )
printf(" G_IO_ERR\n");
if ( cond & G_IO_HUP )
printf(" G_IO_HUP\n");
if ( cond & G_IO_NVAL )
printf(" G_IO_NVAL\n");
if ( !( cond & G_IO_NVAL ) )
{
gint fd = g_io_channel_unix_get_fd( channel );
printf(" fd=%d\n", fd);
if ( fcntl(fd, F_GETFL) != -1 || errno != EBADF )
{
int flags = g_io_channel_get_flags( channel );
if ( flags & G_IO_FLAG_IS_READABLE )
printf( " G_IO_FLAG_IS_READABLE\n");
}
else
printf(" Invalid FD\n");
}
*/
if ( ( cond & G_IO_NVAL ) )
{
g_warning( "udev g_io_channel_unref G_IO_NVAL" );
g_io_channel_unref( channel );
return FALSE;
}
else if ( !( cond & G_IO_IN ) )
{
if ( ( cond & G_IO_HUP ) )
{
g_warning( "udev g_io_channel_unref !G_IO_IN && G_IO_HUP" );
g_io_channel_unref( channel );
return FALSE;
}
else
return TRUE;
}
else if ( !( fcntl( g_io_channel_unix_get_fd( channel ), F_GETFL ) != -1
|| errno != EBADF ) )
{
// bad file descriptor
g_warning( "udev g_io_channel_unref BAD_FD" );
g_io_channel_unref( channel );
return FALSE;
}
struct udev_device *udevice;
const char *action;
const char *acted = NULL;
char* devnode;
VFSVolume* volume;
if ( udevice = udev_monitor_receive_device( umonitor ) )
{
action = udev_device_get_action( udevice );
devnode = g_strdup( udev_device_get_devnode( udevice ) );
if ( action )
{
// print action
if ( !strcmp( action, "add" ) )
acted = "added: ";
else if ( !strcmp( action, "remove" ) )
acted = "removed: ";
else if ( !strcmp( action, "change" ) )
acted = "changed: ";
else if ( !strcmp( action, "move" ) )
acted = "moved: ";
if ( acted )
printf( "udev %s%s\n", acted, devnode );
// add/remove volume
if ( !strcmp( action, "add" ) || !strcmp( action, "change" ) )
{
if ( volume = vfs_volume_read_by_device( udevice ) )
vfs_volume_device_added( volume, TRUE ); //frees volume if needed
}
else if ( !strcmp( action, "remove" ) )
{
char* devnode = g_strdup( udev_device_get_devnode( udevice ) );
if ( devnode )
{
vfs_volume_device_removed( devnode );
g_free( devnode );
}
}
// what to do for move action?
}
g_free( devnode );
udev_device_unref( udevice );
}
return TRUE;
}
/* ************************************************************************ */
#if 0
static void cb_child_watch( GPid pid, gint status, char *data )
{
g_spawn_close_pid( pid );
if ( monpid == pid )
monpid = NULL;
}
static gboolean cb_out_watch( GIOChannel *channel, GIOCondition cond,
char *data )
{
gchar *line;
gsize size;
char* parameter;
char* value;
char* valuec;
char* linec;
size_t colonx;
VFSVolume* volume = NULL;
if ( ( cond & G_IO_HUP ) || ( cond & G_IO_NVAL ) )
{
g_io_channel_unref( channel );
return FALSE;
}
else if ( !( cond & G_IO_IN ) )
return TRUE;
if ( g_io_channel_read_line( channel, &line, &size, NULL, NULL )
!= G_IO_STATUS_NORMAL )
{
//printf(" !G_IO_STATUS_NORMAL\n");
return TRUE;
}
//printf("umon: %s\n", line );
// parse line to get parameter and value
//added: /org/freedesktop/UDisks/devices/sdd1
//changed: /org/freedesktop/UDisks/devices/sdd1
//removed: /org/freedesktop/UDisks/devices/sdd1
colonx = strcspn( line, ":" );
if ( colonx < strlen( line ) )
{
parameter = g_strndup(line, colonx );
valuec = g_strdup( line + colonx + 1 );
value = valuec;
while ( value[0] == ' ' ) value++;
while ( value[ strlen( value ) - 1 ] == '\n' )
value[ strlen( value ) - 1 ] = '\0';
if ( parameter && value )
{
if ( !strncmp( value, "/org/freedesktop/UDisks/devices/", 32) )
{
value += 27;
value[0] = '/';
value[1] = 'd';
value[2] = 'e';
value[3] = 'v';
value[4] = '/';
if ( !strcmp( parameter, "added" ) || !strcmp( parameter, "changed" ) )
{
//printf( "umon add/change %s\n", value );
volume = vfs_volume_read_by_device( value );
vfs_volume_device_added( volume, TRUE ); //frees volume if needed
}
else if ( !strcmp( parameter, "removed" ) )
{
//printf( "umon remove %s\n", value );
vfs_volume_device_removed( value );
}
}
g_free( parameter );
g_free( valuec );
}
}
g_free( line );
return TRUE;
}
void vfs_volume_monitor_start()
{
GPid pid;
gchar *argv[] = { "/usr/bin/udisks", "--monitor", NULL };
gint out,
err;
GIOChannel *out_ch,
*err_ch;
gboolean ret;
//printf("vfs_volume_monitor_start\n");
if ( monpid )
{
//printf("monpid non-null - skipping start\n");
return;
}
// start polling on /dev/sr0 - this also starts the udisks daemon
char* stdout = NULL;
char* stderr = NULL;
g_spawn_command_line_sync( "/usr/bin/udisks --poll-for-media /dev/sr0",
&stdout, &stderr, NULL, NULL );
if ( stdout )
g_free( stdout );
if ( stderr )
g_free( stderr );
// start udisks monitor
ret = g_spawn_async_with_pipes( NULL, argv, NULL,
G_SPAWN_DO_NOT_REAP_CHILD // | G_SPAWN_SEARCH_PATH
| G_SPAWN_STDERR_TO_DEV_NULL,
NULL, NULL, &pid, NULL, &out, NULL, NULL );
if( ! ret )
{
//g_warning( "udisks monitor not available - is /usr/bin/udisks installed?" );
return;
}
monpid = pid;
// catch termination
g_child_watch_add( pid, (GChildWatchFunc)cb_child_watch, NULL );
// create channels for output
out_ch = g_io_channel_unix_new( out );
g_io_channel_set_close_on_unref( out_ch, TRUE );
// if enable err channel, need to add &err to g_spawn_async_with_pipes
// and remove G_SPAWN_STDERR_TO_DEV_NULL flag
//err_ch = g_io_channel_unix_new( err );
//g_io_channel_set_close_on_unref( err_ch, TRUE );
// Add watches to channels
g_io_add_watch( out_ch, G_IO_IN | G_IO_HUP | G_IO_NVAL, (GIOFunc)cb_out_watch, NULL );
//g_io_add_watch( err_ch, G_IO_IN | G_IO_HUP | G_IO_NVAL, (GIOFunc)cb_out_watch, NULL );
//printf("started pid %d\n", pid);
}
#endif
void vfs_free_volume_members( VFSVolume* volume )
{
g_free ( volume->device_file );
g_free ( volume->udi );
g_free ( volume->label );
g_free ( volume->mount_point );
g_free ( volume->disp_name );
g_free ( volume->icon );
}
char* free_slash_total( const char* dir )
{
guint64 total_size;
char size_str[ 64 ];
#ifdef HAVE_STATVFS
struct statvfs fs_stat = {0};
#endif
#ifdef HAVE_STATVFS
if( statvfs( dir, &fs_stat ) == 0 )
{
char total_size_str[ 64 ];
vfs_file_size_to_string_format( size_str, fs_stat.f_bsize * fs_stat.f_bavail,
"%.0f%s" );
vfs_file_size_to_string_format( total_size_str,
fs_stat.f_frsize * fs_stat.f_blocks, "%.0f%s" );
return g_strdup_printf( "%s/%s", size_str, total_size_str );
}
#endif
return g_strdup( "" );
}
void vfs_volume_set_info( VFSVolume* volume )
{
char* parameter;
char* value;
char* valuec;
char* lastcomma;
char* disp_device;
char* disp_label;
char* disp_size;
char* disp_mount;
char* disp_fstype;
char* disp_id = NULL;
char size_str[ 64 ];
if ( !volume )
return;
// set device icon
if ( volume->device_type == DEVICE_TYPE_BLOCK )
{
if ( volume->is_audiocd )
volume->icon = g_strdup_printf( "dev_icon_audiocd" );
else if ( volume->is_optical )
{
if ( volume->is_mounted )
volume->icon = g_strdup_printf( "dev_icon_optical_mounted" );
else if ( volume->is_mountable )
volume->icon = g_strdup_printf( "dev_icon_optical_media" );
else
volume->icon = g_strdup_printf( "dev_icon_optical_nomedia" );
}
else if ( volume->is_floppy )
{
if ( volume->is_mounted )
volume->icon = g_strdup_printf( "dev_icon_floppy_mounted" );
else
volume->icon = g_strdup_printf( "dev_icon_floppy_unmounted" );
volume->is_mountable = TRUE;
}
else if ( volume->is_removable )
{
if ( volume->is_mounted )
volume->icon = g_strdup_printf( "dev_icon_remove_mounted" );
else
volume->icon = g_strdup_printf( "dev_icon_remove_unmounted" );
}
else
{
if ( volume->is_mounted )
{
if ( g_str_has_prefix( volume->device_file, "/dev/loop" ) )
volume->icon = g_strdup_printf( "dev_icon_file" );
else
volume->icon = g_strdup_printf( "dev_icon_internal_mounted" );
}
else
volume->icon = g_strdup_printf( "dev_icon_internal_unmounted" );
}
}
else if ( volume->device_type == DEVICE_TYPE_NETWORK )
volume->icon = g_strdup_printf( "dev_icon_network" );
// set disp_id using by-id
if ( volume->device_type == DEVICE_TYPE_BLOCK )
{
if ( volume->is_floppy && !volume->udi )
disp_id = g_strdup_printf( _(":floppy") );
else if ( volume->udi )
{
if ( lastcomma = strrchr( volume->udi, '/' ) )
{
lastcomma++;
if ( !strncmp( lastcomma, "usb-", 4 ) )
lastcomma += 4;
else if ( !strncmp( lastcomma, "ata-", 4 ) )
lastcomma += 4;
else if ( !strncmp( lastcomma, "scsi-", 5 ) )
lastcomma += 5;
}
else
lastcomma = volume->udi;
if ( lastcomma[0] != '\0' )
{
disp_id = g_strdup_printf( ":%.16s", lastcomma );
}
}
else if ( volume->is_optical )
disp_id = g_strdup_printf( _(":optical") );
if ( !disp_id )
disp_id = g_strdup( "" );
// table type
if ( volume->is_table )
{
if ( volume->fs_type && volume->fs_type[0] == '\0' )
{
g_free( volume->fs_type );
volume->fs_type = NULL;
}
if ( !volume->fs_type )
volume->fs_type = g_strdup( "table" );
}
}
else
disp_id = g_strdup( volume->udi );
// set display name
if ( volume->is_mounted )
{
if ( volume->label && volume->label[0] != '\0' )
disp_label = g_strdup_printf( "%s", volume->label );
else
disp_label = g_strdup( "" );
/* if ( volume->mount_point && volume->mount_point[0] != '\0' )
{
// causes GUI hang during mount due to fs access
disp_size = free_slash_total( volume->mount_point );
}
else */ if ( volume->size > 0 )
{
vfs_file_size_to_string_format( size_str, volume->size, "%.0f%s" );
disp_size = g_strdup_printf( "%s", size_str );
}
else
disp_size = g_strdup( "" );
if ( volume->mount_point && volume->mount_point[0] != '\0' )
disp_mount = g_strdup_printf( "%s", volume->mount_point );
else
disp_mount = g_strdup_printf( "???" );
}
else if ( volume->is_mountable ) //has_media
{
if ( volume->is_blank )
disp_label = g_strdup_printf( _("[blank]") );
else if ( volume->label && volume->label[0] != '\0' )
disp_label = g_strdup_printf( "%s", volume->label );
else if ( volume->is_audiocd )
disp_label = g_strdup_printf( _("[audio]") );
else
disp_label = g_strdup( "" );
if ( volume->size > 0 )
{
vfs_file_size_to_string_format( size_str, volume->size, "%.0f%s" );
disp_size = g_strdup_printf( "%s", size_str );
}
else
disp_size = g_strdup( "" );
disp_mount = g_strdup_printf( "---" );
}
else
{
disp_label = g_strdup_printf( _("[no media]") );
disp_size = g_strdup( "" );
disp_mount = g_strdup( "" );
}
if ( !strncmp( volume->device_file, "/dev/", 5 ) )
disp_device = g_strdup( volume->device_file + 5 );
else if ( g_str_has_prefix( volume->device_file, "curlftpfs#" ) )
disp_device = g_strdup( volume->device_file + 10 );
else
disp_device = g_strdup( volume->device_file );
if ( volume->fs_type && volume->fs_type[0] != '\0' )
disp_fstype = g_strdup( volume->fs_type );// g_strdup_printf( "-%s", volume->fs_type );
else
disp_fstype = g_strdup( "" );
char* fmt = xset_get_s( "dev_dispname" );
if ( !fmt )
parameter = g_strdup_printf( "%s %s %s %s %s %s",
disp_device, disp_size, disp_fstype, disp_label,
disp_mount, disp_id );
else
{
value = replace_string( fmt, "%v", disp_device, FALSE );
valuec = replace_string( value, "%s", disp_size, FALSE );
g_free( value );
value = replace_string( valuec, "%t", disp_fstype, FALSE );
g_free( valuec );
valuec = replace_string( value, "%l", disp_label, FALSE );
g_free( value );
value = replace_string( valuec, "%m", disp_mount, FALSE );
g_free( valuec );
parameter = replace_string( value, "%i", disp_id, FALSE );
g_free( value );
}
//volume->disp_name = g_filename_to_utf8( parameter, -1, NULL, NULL, NULL );
while ( strstr( parameter, " " ) )
{
value = parameter;
parameter = replace_string( value, " ", " ", FALSE );
g_free( value );
}
while ( parameter[0] == ' ' )
{
value = parameter;
parameter = g_strdup( parameter + 1 );
g_free( value );
}
volume->disp_name = g_filename_display_name( parameter );
g_free( parameter );
g_free( disp_label );
g_free( disp_size );
g_free( disp_mount );
g_free( disp_device );
g_free( disp_fstype );
g_free( disp_id );
if ( !volume->udi )
volume->udi = g_strdup( volume->device_file );
}
VFSVolume* vfs_volume_read_by_device( struct udev_device *udevice )
{ // uses udev to read device parameters into returned volume
VFSVolume* volume = NULL;
if ( !udevice )
return NULL;
device_t* device = device_alloc( udevice );
if ( !device_get_info( device ) || !device->devnode
|| !g_str_has_prefix( device->devnode, "/dev/" ) )
{
device_free( device );
return NULL;
}
// translate device info to VFSVolume
volume = g_slice_new0( VFSVolume );
volume->device_type = DEVICE_TYPE_BLOCK;
volume->device_file = g_strdup( device->devnode );
volume->udi = g_strdup( device->device_by_id );
volume->is_optical = device->device_is_optical_disc;
volume->is_table = device->device_is_partition_table;
volume->is_floppy = ( device->drive_media_compatibility
&& !strcmp( device->drive_media_compatibility, "floppy" ) );
volume->is_removable = !device->device_is_system_internal;
volume->requires_eject = device->drive_is_media_ejectable;
volume->is_mountable = device->device_is_media_available;
volume->is_audiocd = ( device->device_is_optical_disc
&& device->optical_disc_num_audio_tracks
&& atoi( device->optical_disc_num_audio_tracks ) > 0 );
volume->is_dvd = ( device->drive_media
&& strstr( device->drive_media, "optical_dvd" ) );
volume->is_blank = ( device->device_is_optical_disc
&& device->optical_disc_is_blank );
volume->is_mounted = device->device_is_mounted;
volume->is_user_visible = device->device_presentation_hide ?
!atoi( device->device_presentation_hide ) : TRUE;
volume->ever_mounted = FALSE;
volume->open_main_window = NULL;
volume->nopolicy = device->device_presentation_nopolicy ?
atoi( device->device_presentation_nopolicy ) : FALSE;
volume->mount_point = NULL;
if ( device->mount_points && device->mount_points[0] != '\0' )
{
char* comma;
if ( comma = strchr( device->mount_points, ',' ) )
{
comma[0] = '\0';
volume->mount_point = g_strdup( device->mount_points );
comma[0] = ',';
}
else
volume->mount_point = g_strdup( device->mount_points );
}
volume->size = device->device_size;
volume->label = g_strdup( device->id_label );
volume->fs_type = g_strdup( device->id_type );
volume->disp_name = NULL;
volume->icon = NULL;
volume->automount_time = 0;
volume->inhibit_auto = FALSE;
device_free( device );
// adjustments
volume->ever_mounted = volume->is_mounted;
//if ( volume->is_blank )
// volume->is_mountable = FALSE; //has_media is now used for showing
if ( volume->is_dvd )
volume->is_audiocd = FALSE;
vfs_volume_set_info( volume );
/*
printf( "====device_file=%s\n", volume->device_file );
printf( " udi=%s\n", volume->udi );
printf( " label=%s\n", volume->label );
printf( " icon=%s\n", volume->icon );
printf( " is_mounted=%d\n", volume->is_mounted );
printf( " is_mountable=%d\n", volume->is_mountable );
printf( " is_optical=%d\n", volume->is_optical );
printf( " is_audiocd=%d\n", volume->is_audiocd );
printf( " is_blank=%d\n", volume->is_blank );
printf( " is_floppy=%d\n", volume->is_floppy );
printf( " is_table=%d\n", volume->is_table );
printf( " is_removable=%d\n", volume->is_removable );
printf( " requires_eject=%d\n", volume->requires_eject );
printf( " is_user_visible=%d\n", volume->is_user_visible );
printf( " mount_point=%s\n", volume->mount_point );
printf( " size=%u\n", volume->size );
printf( " disp_name=%s\n", volume->disp_name );
*/
return volume;
}
static gboolean path_is_mounted_mtab( const char* path, char** device_file )
{
gchar *contents;
gchar **lines;
GError *error;
guint n;
gboolean ret = FALSE;
char* str;
char* file;
char* point;
gchar encoded_file[PATH_MAX];
gchar encoded_point[PATH_MAX];
if ( !path )
return FALSE;
contents = NULL;
lines = NULL;
error = NULL;
if ( !g_file_get_contents( "/proc/mounts", &contents, NULL, NULL ) )
{
if ( !g_file_get_contents( "/etc/mtab", &contents, NULL, &error ) )
{
g_warning ("Error reading mtab: %s", error->message);
g_error_free (error);
return FALSE;
}
}
lines = g_strsplit( contents, "\n", 0 );
for ( n = 0; lines[n] != NULL; n++ )
{
if ( lines[n][0] == '\0' )
continue;
if ( sscanf( lines[n],
"%s %s ",
encoded_file,
encoded_point ) != 2 )
{
g_warning ("Error parsing mtab line '%s'", lines[n]);
continue;
}
point = g_strcompress( encoded_point );
if ( !g_strcmp0( point, path ) )
{
if ( device_file )
*device_file = g_strcompress( encoded_file );
ret = TRUE;
break;
}
g_free( point );
}
g_free( contents );
g_strfreev( lines );
return ret;
}
int parse_network_url( const char* url, const char* fstype,
netmount_t** netmount )
{ // returns 0=not a network url 1=valid network url 2=invalid network url
if ( !url || !netmount )
return 0;
int ret = 0;
char* str;
char* str2;
netmount_t* nm = g_slice_new0( netmount_t );
nm->fstype = NULL;
nm->host = NULL;
nm->ip = NULL;
nm->port = NULL;
nm->user = NULL;
nm->pass = NULL;
nm->path = NULL;
char* orig_url = strdup( url );
char* xurl = orig_url;
gboolean is_colon = FALSE;
// determine url type
if ( g_str_has_prefix( xurl, "smb:" ) || g_str_has_prefix( xurl, "smbfs:" )
|| g_str_has_prefix( xurl, "cifs:" )
|| g_str_has_prefix( xurl, "//" ) )
{
ret = 2;
// mount [-t smbfs] //host[:<port>]/<path>
if ( !g_str_has_prefix( xurl, "//" ) )
is_colon = TRUE;
if ( fstype && strcmp( fstype, "smbfs" ) && strcmp( fstype, "cifs" ) )
{
// wlog( _("udevil: error 26: invalid type '%s' for SMB share - must be cifs or smbfs\n"),
// fstype, 2 );
goto _net_free;
}
if ( !g_strcmp0( fstype, "smbfs" ) || g_str_has_prefix( xurl, "smbfs:" ) )
nm->fstype = g_strdup( "smbfs" );
else
nm->fstype = g_strdup( "cifs" );
}
else if ( g_str_has_prefix( xurl, "nfs:" ) )
{
ret = 2;
is_colon = TRUE;
if ( fstype && strcmp( fstype, "nfs" ) && strcmp( fstype, "nfs4" ) )
{
// wlog( _("udevil: error 27: invalid type '%s' for NFS share - must be nfs or nfs4\n"),
// fstype, 2 );
goto _net_free;
}
nm->fstype = g_strdup( "nfs" );
}
else if ( g_str_has_prefix( xurl, "curlftpfs#" ) )
{
ret = 2;
if ( g_str_has_prefix( xurl, "curlftpfs#ftp:" ) )
is_colon = TRUE;
if ( fstype && strcmp( fstype, "curlftpfs" ) )
{
// wlog( _("udevil: error 28: invalid type '%s' for curlftpfs share - must be curlftpfs\n"),
// fstype, 2 );
goto _net_free;
}
nm->fstype = g_strdup( "curlftpfs" );
}
else if ( g_str_has_prefix( xurl, "ftp:" ) )
{
ret = 2;
is_colon = TRUE;
if ( fstype && strcmp( fstype, "ftpfs" ) && strcmp( fstype, "curlftpfs" ) )
{
// wlog( _("udevil: error 29: invalid type '%s' for FTP share - must be curlftpfs or ftpfs\n"),
// fstype, 2 );
goto _net_free;
}
if ( fstype )
nm->fstype = g_strdup( fstype );
else
{
// detect curlftpfs or ftpfs
if ( str = g_find_program_in_path( "curlftpfs" ) )
nm->fstype = g_strdup( "curlftpfs" );
else
nm->fstype = g_strdup( "ftpfs" );
g_free( str );
}
}
else if ( g_str_has_prefix( xurl, "sshfs#" ) )
{
ret = 2;
if ( g_str_has_prefix( xurl, "sshfs#ssh:" )
|| g_str_has_prefix( xurl, "sshfs#sshfs:" )
|| g_str_has_prefix( xurl, "sshfs#sftp:" ) )
is_colon = TRUE;
if ( fstype && strcmp( fstype, "sshfs" ) )
{
// wlog( _("udevil: error 30: invalid type '%s' for sshfs share - must be sshfs\n"),
// fstype, 2 );
goto _net_free;
}
nm->fstype = g_strdup( "sshfs" );
}
else if ( g_str_has_prefix( xurl, "ssh:" ) || g_str_has_prefix( xurl, "sshfs:" )
|| g_str_has_prefix( xurl, "sftp:" ) )
{
ret = 2;
is_colon = TRUE;
if ( fstype && strcmp( fstype, "sshfs" ) )
{
// wlog( _("udevil: error 31: invalid type '%s' for sshfs share - must be sshfs\n"),
// fstype, 2 );
goto _net_free;
}
nm->fstype = g_strdup( "sshfs" );
}
else if ( g_str_has_prefix( xurl, "http:" ) || g_str_has_prefix( xurl, "https:" ) )
{
ret = 2;
is_colon = TRUE;
if ( fstype && strcmp( fstype, "davfs" ) )
{
// wlog( _("udevil: error 151: invalid type '%s' for WebDAV share - must be davfs\n"),
// fstype, 2 );
goto _net_free;
}
nm->fstype = g_strdup( "davfs" );
}
else if ( ( str = strstr( xurl, ":/" ) ) && xurl[0] != ':' && xurl[0] != '/' )
{
ret = 2;
str[0] = '\0';
if ( strchr( xurl, '@' ) || !g_strcmp0( fstype, "sshfs" ) )
{
nm->fstype = g_strdup( "sshfs" );
if ( fstype && strcmp( fstype, "sshfs" ) )
{
// wlog( _("udevil: error 32: invalid type '%s' for sshfs share - must be sshfs\n"),
// fstype, 2 );
goto _net_free;
}
}
else
{
// mount [-t nfs] host:/path
nm->fstype = g_strdup( "nfs" );
if ( fstype && strcmp( fstype, "nfs" ) && strcmp( fstype, "nfs4" ) )
{
// wlog( _("udevil: error 33: invalid type '%s' for NFS share - must be nfs or nfs4\n"),
// fstype, 2 );
goto _net_free;
}
}
str[0] = ':';
}
else if ( fstype && ( !strcmp( fstype, "nfs" ) ||
!strcmp( fstype, "nfs4" ) ||
!strcmp( fstype, "smbfs" ) ||
!strcmp( fstype, "cifs" ) ||
!strcmp( fstype, "sshfs" ) ||
!strcmp( fstype, "davfs" ) ||
!strcmp( fstype, "curlftpfs" ) ||
!strcmp( fstype, "ftpfs" ) ) )
{
// no protocol but user specified a valid network fstype
ret = 2;
nm->fstype = g_strdup( fstype );
}
if ( ret != 2 )
goto _net_free;
// parse
if ( is_colon && ( str = strchr( xurl, ':' ) ) )
{
xurl = str + 1;
}
while ( xurl[0] == '/' )
xurl++;
char* trim_url = g_strdup( xurl );
// user:pass
if ( str = strchr( xurl, '@' ) )
{
if ( str2 = strchr( str + 1, '@' ) )
{
// there is a second @ - assume username contains email address
str = str2;
}
str[0] = '\0';
if ( str2 = strchr( xurl, ':' ) )
{
str2[0] = '\0';
if ( str2[1] != '\0' )
nm->pass = g_strdup( str2 + 1 );
}
if ( xurl[0] != '\0' )
nm->user = g_strdup( xurl );
xurl = str + 1;
}
// path
if ( str = strchr( xurl, '/' ) )
{
nm->path = g_strdup( str );
str[0] = '\0';
}
// host:port
if ( xurl[0] == '[' )
{
// ipv6 literal
if ( str = strchr( xurl, ']' ) )
{
str[0] = '\0';
if ( xurl[1] != '\0' )
nm->host = g_strdup( xurl + 1 );
if ( str[1] == ':' && str[2] != '\0' )
nm->port = g_strdup( str + 1 );
}
}
else if ( xurl[0] != '\0' )
{
if ( str = strchr( xurl, ':' ) )
{
str[0] = '\0';
if ( str[1] != '\0' )
nm->port = g_strdup( str + 1 );
}
nm->host = g_strdup( xurl );
}
// url
if ( nm->host )
{
if ( !g_strcmp0( nm->fstype, "cifs" ) || !g_strcmp0( nm->fstype, "smbfs" ) )
nm->url = g_strdup_printf( "//%s%s", nm->host, nm->path ? nm->path : "/" );
else if ( !g_strcmp0( nm->fstype, "nfs" ) )
nm->url = g_strdup_printf( "%s:%s", nm->host, nm->path ? nm->path : "/" );
else if ( !g_strcmp0( nm->fstype, "curlftpfs" ) )
nm->url = g_strdup_printf( "curlftpfs#ftp://%s%s%s%s",
nm->host,
nm->port ? ":" : "",
nm->port ? nm->port : "",
nm->path ? nm->path : "/" );
else if ( !g_strcmp0( nm->fstype, "ftpfs" ) )
nm->url = g_strdup( "none" );
else if ( !g_strcmp0( nm->fstype, "sshfs" ) )
nm->url = g_strdup_printf( "sshfs#%s%s%s%s%s:%s",
nm->user ? nm->user : g_get_user_name(),
nm->pass ? ":" : "",
nm->pass ? nm->pass : "",
"@", //nm->user || nm->pass ? "@" : "",
nm->host,
nm->path ? nm->path : "/" );
else if ( !g_strcmp0( nm->fstype, "davfs" ) )
nm->url = g_strdup( url );
else
nm->url = g_strdup( trim_url );
}
g_free( trim_url );
g_free( orig_url );
if ( !nm->host )
{
// wlog( _("udevil: error 34: '%s' is not a recognized network url\n"), url, 2 );
goto _net_free;
}
// check user pass port
if ( ( nm->user && strchr( nm->user, ' ' ) )
|| ( nm->pass && strchr( nm->pass, ' ' ) )
|| ( nm->port && strchr( nm->port, ' ' ) ) )
{
// wlog( _("udevil: error 35: invalid network url\n"), fstype, 2 );
goto _net_free;
}
/* for udevil only
// lookup ip
if ( !( nm->ip = get_ip( nm->host ) ) || ( nm->ip && nm->ip[0] == '\0' ) )
{
// wlog( _("udevil: error 36: lookup host '%s' failed\n"), nm->host, 2 );
goto _net_free;
}
*/
// valid
*netmount = nm;
return 1;
_net_free:
g_free( nm->url );
g_free( nm->fstype );
g_free( nm->host );
g_free( nm->ip );
g_free( nm->port );
g_free( nm->user );
g_free( nm->pass );
g_free( nm->path );
g_slice_free( netmount_t, nm );
return ret;
}
VFSVolume* vfs_volume_read_by_mount( const char* mount_points )
{ // read a non-block device
VFSVolume* volume;
char* str;
int i;
struct stat64 statbuf;
netmount_t *netmount = NULL;
if ( !mount_points )
return NULL;
// get single mount point
char* point = g_strdup( mount_points );
if ( str = strchr( point, ',' ) )
str[0] = '\0';
g_strstrip( point );
if ( !( point && point[0] == '/' ) )
return NULL;
// get device name
char* name = NULL;
if ( !( path_is_mounted_mtab( point, &name ) && name && name[0] != '\0' ) )
return NULL;
i = parse_network_url( name, NULL, &netmount );
if ( i != 1 )
return NULL;
// network URL
volume = g_slice_new0( VFSVolume );
volume->device_type = DEVICE_TYPE_NETWORK;
volume->udi = netmount->url;
volume->label = netmount->host;
volume->fs_type = netmount->fstype;
volume->size = 0;
volume->device_file = name;
volume->is_mounted = TRUE;
volume->ever_mounted = TRUE;
volume->open_main_window = NULL;
volume->mount_point = point;
volume->disp_name = NULL;
volume->icon = NULL;
volume->automount_time = 0;
volume->inhibit_auto = FALSE;
// free unused netmount
g_free( netmount->ip );
g_free( netmount->port );
g_free( netmount->user );
g_free( netmount->pass );
g_free( netmount->path );
g_slice_free( netmount_t, netmount );
vfs_volume_set_info( volume );
return volume;
}
#if 0
VFSVolume* vfs_volume_read_by_device( char* device_file )
{
// uses udisks to read device parameters into returned volume
FILE *fp;
char line[1024];
char* value;
char* valuec;
char* linec;
char* lastcomma;
char* parameter;
VFSVolume* volume = NULL;
size_t colonx;
char* device_file_delayed;
//printf( ">>> udisks --show-info %s\n", device_file );
fp = popen(g_strdup_printf( "/usr/bin/udisks --show-info %s", device_file ), "r");
if (fp)
{
volume = g_slice_new0( VFSVolume );
volume->device_file = NULL;
volume->udi = NULL;
volume->is_optical = FALSE;
volume->is_table = FALSE;
volume->is_floppy = FALSE;
volume->is_removable = FALSE;
volume->requires_eject = FALSE;
volume->is_mountable = FALSE;
volume->is_audiocd = FALSE;
volume->is_dvd = FALSE;
volume->is_blank = FALSE;
volume->is_mounted = FALSE;
volume->is_user_visible = TRUE;
volume->ever_mounted = FALSE;
volume->open_main_window = NULL;
volume->nopolicy = FALSE;
volume->mount_point = NULL;
volume->size = 0;
volume->label = NULL;
volume->fs_type = NULL;
volume->disp_name = NULL;
volume->icon = NULL;
volume->automount_time = 0;
volume->inhibit_auto = FALSE;
while (fgets(line, sizeof(line)-1, fp) != NULL)
{
// parse line to get parameter and value
colonx = strcspn( line, ":" );
if ( colonx < strlen( line ) )
{
parameter = g_strndup(line, colonx );
valuec = g_strdup( line + colonx + 1 );
value = valuec;
while ( value[0] == ' ' ) value++;
while ( value[ strlen( value ) - 1 ] == '\n' )
value[ strlen( value ) - 1 ] = '\0';
if ( parameter && value )
{
// set volume from parameters
//printf( " (%s)=%s\n", parameter, value );
if ( !strcmp( parameter, " device-file" ) )
volume->device_file = g_strdup( value );
else if ( !strcmp( parameter, " system internal" ) )
volume->is_removable = !atoi( value );
else if ( !strcmp( parameter, " ejectable" ) )
volume->requires_eject = atoi( value );
else if ( !strcmp( parameter, " is mounted" ) )
volume->is_mounted = atoi( value );
else if ( !strcmp( parameter, " has media" ) )
volume->is_mountable = atoi( value );
else if ( !strcmp( parameter, " blank" ) && atoi( value ) )
volume->is_blank = TRUE;
else if ( !strcmp( parameter, " num audio tracks" ) )
volume->is_audiocd = atoi( value ) > 0;
else if ( !strcmp( parameter, " media" )
&& strstr( value, "optical_dvd" ) )
volume->is_dvd = TRUE;
else if ( !strcmp( parameter, " presentation hide" ) )
volume->is_user_visible = !atoi( value );
else if ( !strcmp( parameter, " presentation nopolicy" ) )
volume->nopolicy = atoi( value );
// use last mount path as mount point
else if ( !strcmp( parameter, " mount paths" ) )
{
lastcomma = strrchr( value, ',' );
if ( lastcomma )
{
lastcomma++;
while ( lastcomma[0] == ' ' ) lastcomma++;
volume->mount_point = g_strdup( lastcomma );
}
else
volume->mount_point = g_strdup( value );
}
else if ( !strcmp( parameter, " by-id" ) && !volume->udi )
volume->udi = g_strdup( value );
else if ( !strcmp( parameter, " size" ) )
volume->size = atoll( value );
else if ( !strcmp( parameter, " label" ) )
volume->label = g_strdup( value );
else if ( !strcmp( parameter, " compat" ) )
{
if ( strstr( value, "optical" ) != NULL )
volume->is_optical = TRUE;
if ( !strcmp( value, "floppy" ) )
volume->is_floppy = TRUE;
}
else if ( !strcmp( parameter, " type" ) )
volume->fs_type = g_strdup( value );
else if ( !strcmp( parameter, " partition table" ) )
volume->is_table = TRUE;
else if ( !strcmp( parameter, " type" ) && !strcmp( value, "0x05" ) )
volume->is_table = TRUE; //extended partition
g_free( parameter );
g_free( valuec );
}
}
}
pclose(fp);
volume->ever_mounted = volume->is_mounted;
//if ( volume->is_blank )
// volume->is_mountable = FALSE; //has_media is now used for showing
if ( volume->is_dvd )
volume->is_audiocd = FALSE;
if ( volume->device_file && !strcmp( volume->device_file, device_file ) )
{
vfs_volume_set_info( volume );
/*
printf( "====device_file=%s\n", volume->device_file );
printf( " udi=%s\n", volume->udi );
printf( " label=%s\n", volume->label );
printf( " icon=%s\n", volume->icon );
printf( " is_mounted=%d\n", volume->is_mounted );
printf( " is_mountable=%d\n", volume->is_mountable );
printf( " is_optical=%d\n", volume->is_optical );
printf( " is_audiocd=%d\n", volume->is_audiocd );
printf( " is_blank=%d\n", volume->is_blank );
printf( " is_floppy=%d\n", volume->is_floppy );
printf( " is_table=%d\n", volume->is_table );
printf( " is_removable=%d\n", volume->is_removable );
printf( " requires_eject=%d\n", volume->requires_eject );
printf( " is_user_visible=%d\n", volume->is_user_visible );
printf( " mount_point=%s\n", volume->mount_point );
printf( " size=%u\n", volume->size );
printf( " disp_name=%s\n", volume->disp_name );
*/
}
else
{
vfs_free_volume_members( volume );
g_slice_free( VFSVolume, volume );
volume = NULL;
}
}
//printf( ">>> udisks --show-info %s DONE\n", device_file );
return volume;
}
#endif
gboolean vfs_volume_is_automount( VFSVolume* vol )
{ // determine if volume should be automounted or auto-unmounted
int i, j;
char* test;
char* value;
if ( !vol->is_mountable || vol->is_blank || vol->device_type != DEVICE_TYPE_BLOCK )
return FALSE;
char* showhidelist = g_strdup_printf( " %s ", xset_get_s( "dev_automount_volumes" ) );
for ( i = 0; i < 3; i++ )
{
for ( j = 0; j < 2; j++ )
{
if ( i == 0 )
value = vol->device_file;
else if ( i == 1 )
value = vol->label;
else
{
value = vol->udi;
value = strrchr( value, '/' );
if ( value )
value++;
}
if ( j == 0 )
test = g_strdup_printf( " +%s ", value );
else
test = g_strdup_printf( " -%s ", value );
if ( strstr( showhidelist, test ) )
{
g_free( test );
g_free( showhidelist );
return ( j == 0 );
}
g_free( test );
}
}
g_free( showhidelist );
// udisks no?
if ( vol->nopolicy && !xset_get_b( "dev_ignore_udisks_nopolicy" ) )
return FALSE;
// table?
if ( vol->is_table )
return FALSE;
// optical
if ( vol->is_optical )
return xset_get_b( "dev_automount_optical" );
// internal?
if ( vol->is_removable && xset_get_b( "dev_automount_removable" ) )
return TRUE;
return FALSE;
}
char* vfs_volume_device_info( const char* device_file )
{
struct stat statbuf; // skip stat64
struct udev_device *udevice;
if ( !udev )
return g_strdup_printf( _("( udev was unavailable at startup )") );
if ( stat( device_file, &statbuf ) != 0 )
{
g_printerr ( "Cannot stat device file %s: %m\n", device_file );
return g_strdup_printf( _("( cannot stat device file )") );
}
if (statbuf.st_rdev == 0)
{
printf( "Device file %s is not a block device\n", device_file );
return g_strdup_printf( _("( not a block device )") );
}
udevice = udev_device_new_from_devnum( udev, 'b', statbuf.st_rdev );
if ( udevice == NULL )
{
printf( "No udev device for device %s (devnum 0x%08x)\n",
device_file, (gint)statbuf.st_rdev );
return g_strdup_printf( _("( no udev device )") );
}
device_t *device = device_alloc( udevice );
if ( !device_get_info( device ) )
return g_strdup( "" );
char* info = device_show_info( device );
device_free( device );
udev_device_unref( udevice );
return info;
}
char* vfs_volume_device_mount_cmd( const char* device_file, const char* options )
{
char* command = NULL;
char* s1;
const char* cmd = xset_get_s( "dev_mount_cmd" );
if ( !cmd || ( cmd && cmd[0] == '\0' ) )
{
// discovery
if ( s1 = g_find_program_in_path( "udevil" ) )
{
// udevil
if ( options && options[0] != '\0' )
command = g_strdup_printf( "%s mount %s -o '%s'",
s1, device_file, options );
else
command = g_strdup_printf( "%s mount %s",
s1, device_file );
}
else if ( s1 = g_find_program_in_path( "pmount" ) )
{
// pmount
command = g_strdup_printf( "%s %s", s1, device_file );
}
else if ( s1 = g_find_program_in_path( "udisksctl" ) )
{
// udisks2
if ( options && options[0] != '\0' )
command = g_strdup_printf( "%s mount -b %s -o '%s'",
s1, device_file, options );
else
command = g_strdup_printf( "%s mount -b %s",
s1, device_file );
}
else if ( s1 = g_find_program_in_path( "udisks" ) )
{
// udisks1
if ( options && options[0] != '\0' )
command = g_strdup_printf( "%s --mount %s --mount-options '%s'",
s1, device_file, options );
else
command = g_strdup_printf( "%s --mount %s",
s1, device_file );
}
g_free( s1 );
}
else
{
// user specified
s1 = replace_string( cmd, "%v", device_file, FALSE );
command = replace_string( s1, "%o", options, TRUE );
g_free( s1 );
}
return command;
}
char* vfs_volume_device_unmount_cmd( const char* device_file )
{
char* command = NULL;
char* s1;
const char* cmd = xset_get_s( "dev_unmount_cmd" );
if ( !cmd || ( cmd && cmd[0] == '\0' ) )
{
// discovery
if ( s1 = g_find_program_in_path( "udevil" ) )
{
// udevil
command = g_strdup_printf( "%s umount '%s'", s1, device_file );
}
else if ( s1 = g_find_program_in_path( "pumount" ) )
{
// pmount
command = g_strdup_printf( "%s %s", s1, device_file );
}
else if ( s1 = g_find_program_in_path( "udisksctl" ) )
{
// udisks2
command = g_strdup_printf( "%s unmount -b %s", s1, device_file );
}
else if ( s1 = g_find_program_in_path( "udisks" ) )
{
// udisks1
command = g_strdup_printf( "%s --unmount %s", s1, device_file );
}
g_free( s1 );
}
else
{
// user specified
command = replace_string( cmd, "%v", device_file, FALSE );
}
return command;
}
char* vfs_volume_get_mount_options( VFSVolume* vol, char* options )
{
if ( !options )
return NULL;
// change spaces to commas
gboolean leading = TRUE;
gboolean trailing = FALSE;
int j = -1;
int i;
char news[ strlen( options ) + 1 ];
for ( i = 0; i < strlen ( options ); i++ )
{
if ( leading && ( options[ i ] == ' ' || options[ i ] == ',' ) )
continue;
if ( options[ i ] != ' ' && options[ i ] != ',' )
{
j++;
news[ j ] = options[ i ];
trailing = TRUE;
leading = FALSE;
}
else if ( trailing )
{
j++;
news[ j ] = ',';
trailing = FALSE;
}
}
if ( news[ j ] == ',' )
news[ j ] = '\0';
else
{
j++;
news[ j ] = '\0';
}
// no options
if ( news[0] == '\0' )
return NULL;
// parse options with fs type
// nosuid,sync+vfat,utf+vfat,nosuid-ext4
char* opts = g_strdup_printf( ",%s,", news );
const char* fstype = vfs_volume_get_fstype( vol );
char newo[ strlen( opts ) + 1 ];
newo[0] = ',';
newo[1] = '\0';
char* newoptr = newo + 1;
char* ptr = opts + 1;
char* comma;
char* single;
char* singlefs;
char* plus;
char* test;
while ( ptr[0] != '\0' )
{
comma = strchr( ptr, ',' );
single = g_strndup( ptr, comma - ptr );
if ( !strchr( single, '+' ) && !strchr( single, '-' ) )
{
// pure option, check for -fs option
test = g_strdup_printf( ",%s-%s,", single, fstype );
if ( !strstr( opts, test ) )
{
// add option
strcpy( newoptr, single );
newoptr = newo + strlen( newo );
newoptr[0] = ',';
newoptr[1] = '\0';
newoptr++;
}
g_free( test );
}
else if ( plus = strchr( single, '+' ) )
{
//opt+fs
plus[0] = '\0'; //set single to just option
singlefs = g_strdup_printf( "%s+%s", single, fstype );
plus[0] = '+'; //restore single to option+fs
if ( !strcmp( singlefs, single ) )
{
// correct fstype, check if already in options
plus[0] = '\0'; //set single to just option
test = g_strdup_printf( ",%s,", single );
if ( !strstr( newo, test ) )
{
// add +fs option
strcpy( newoptr, single );
newoptr = newo + strlen( newo );
newoptr[0] = ',';
newoptr[1] = '\0';
newoptr++;
}
g_free( test );
}
g_free( singlefs );
}
g_free( single );
ptr = comma + 1;
}
newoptr--;
newoptr[0] = '\0';
g_free( opts );
if ( newo[1] == '\0' )
return NULL;
else
return g_strdup( newo + 1 );
}
char* vfs_volume_get_mount_command( VFSVolume* vol, char* default_options )
{
char* command;
char* options = vfs_volume_get_mount_options( vol, default_options );
command = vfs_volume_device_mount_cmd( vol->device_file, options );
g_free( options );
return command;
}
void vfs_volume_exec( VFSVolume* vol, char* command )
{
//printf( "vfs_volume_exec %s %s\n", vol->device_file, command );
if ( !command || command[0] == '\0' || vol->device_type != DEVICE_TYPE_BLOCK )
return;
char *s1;
char *s2;
s1 = replace_string( command, "%m", vol->mount_point, TRUE );
s2 = replace_string( s1, "%l", vol->label, TRUE );
g_free( s1 );
s1 = replace_string( s2, "%v", vol->device_file, FALSE );
g_free( s2 );
GList* files = NULL;
files = g_list_prepend( files, g_strdup_printf( "autoexec" ) );
printf( _("\nAutoexec: %s\n"), s1 );
PtkFileTask* task = ptk_file_task_new( VFS_FILE_TASK_EXEC, files, "/", NULL,
NULL );
task->task->exec_action = g_strdup_printf( "autoexec" );
task->task->exec_command = s1;
task->task->exec_sync = FALSE;
task->task->exec_export = FALSE;
task->task->exec_keep_tmp = FALSE;
ptk_file_task_run( task );
}
void vfs_volume_autoexec( VFSVolume* vol )
{
char* command = NULL;
char* path;
// Note: audiocd is is_mountable
if ( !vol->is_mountable || global_inhibit_auto ||
!vfs_volume_is_automount( vol ) ||
vol->device_type != DEVICE_TYPE_BLOCK )
return;
if ( vol->is_audiocd )
{
command = xset_get_s( "dev_exec_audio" );
}
else if ( vol->is_mounted && vol->mount_point && vol->mount_point[0] !='\0' )
{
if ( vol->inhibit_auto )
{
// user manually mounted this vol, so no autoexec this time
vol->inhibit_auto = FALSE;
return;
}
else
{
path = g_build_filename( vol->mount_point, "VIDEO_TS", NULL );
if ( vol->is_dvd && g_file_test( path, G_FILE_TEST_IS_DIR ) )
command = xset_get_s( "dev_exec_video" );
else
{
if ( xset_get_b( "dev_auto_open" ) )
{
FMMainWindow* main_window = fm_main_window_get_last_active();
if ( main_window )
{
printf( _("\nAuto Open Tab for %s in %s\n"), vol->device_file,
vol->mount_point );
//PtkFileBrowser* file_browser =
// (PtkFileBrowser*)fm_main_window_get_current_file_browser(
// main_window );
//if ( file_browser )
// ptk_file_browser_emit_open( file_browser, vol->mount_point,
// PTK_OPEN_DIR ); //PTK_OPEN_NEW_TAB
//fm_main_window_add_new_tab causes hang without GDK_THREADS_ENTER
GDK_THREADS_ENTER();
fm_main_window_add_new_tab( main_window, vol->mount_point );
GDK_THREADS_LEAVE();
//printf("DONE Auto Open Tab for %s in %s\n", vol->device_file,
// vol->mount_point );
}
else
{
char* prog = g_find_program_in_path( g_get_prgname() );
if ( !prog )
prog = g_strdup( g_get_prgname() );
if ( !prog )
prog = g_strdup( "spacefm" );
char* quote_path = bash_quote( vol->mount_point );
char* line = g_strdup_printf( "%s -t %s", prog, quote_path );
g_spawn_command_line_async( line, NULL );
g_free( prog );
g_free( quote_path );
g_free( line );
}
}
command = xset_get_s( "dev_exec_fs" );
}
g_free( path );
}
}
vfs_volume_exec( vol, command );
}
void vfs_volume_autounmount( VFSVolume* vol )
{
if ( !vol->is_mounted || !vfs_volume_is_automount( vol ) )
return;
char* line = vfs_volume_device_unmount_cmd( vol->device_file );
if ( line )
{
printf( _("\nAuto-Unmount: %s\n"), line );
g_spawn_command_line_async( line, NULL );
g_free( line );
}
else
printf( _("\nAuto-Unmount: error: no unmount program available\n") );
}
void vfs_volume_automount( VFSVolume* vol )
{
if ( vol->is_mounted || vol->ever_mounted || vol->is_audiocd
|| !vfs_volume_is_automount( vol ) )
return;
if ( vol->automount_time && time( NULL ) - vol->automount_time < 5 )
return;
vol->automount_time = time( NULL );
char* line = vfs_volume_get_mount_command( vol,
xset_get_s( "dev_mount_options" ) );
if ( line )
{
printf( _("\nAutomount: %s\n"), line );
g_spawn_command_line_async( line, NULL );
g_free( line );
}
else
printf( _("\nAutomount: error: no mount program available\n") );
}
static void vfs_volume_device_added( VFSVolume* volume, gboolean automount )
{ //frees volume if needed
GList* l;
gboolean was_mounted, was_audiocd, was_mountable;
if ( !volume || !volume->udi || !volume->device_file )
return;
// check if we already have this volume device file
for ( l = volumes; l; l = l->next )
{
if ( !strcmp( ((VFSVolume*)l->data)->device_file, volume->device_file ) )
{
// update existing volume
was_mounted = ((VFSVolume*)l->data)->is_mounted;
was_audiocd = ((VFSVolume*)l->data)->is_audiocd;
was_mountable = ((VFSVolume*)l->data)->is_mountable;
vfs_free_volume_members( (VFSVolume*)l->data );
((VFSVolume*)l->data)->udi = g_strdup( volume->udi );
((VFSVolume*)l->data)->device_file = g_strdup( volume->device_file );
((VFSVolume*)l->data)->label = g_strdup( volume->label );
((VFSVolume*)l->data)->mount_point = g_strdup( volume->mount_point );
((VFSVolume*)l->data)->icon = g_strdup( volume->icon );
((VFSVolume*)l->data)->disp_name = g_strdup( volume->disp_name );
((VFSVolume*)l->data)->is_mounted = volume->is_mounted;
((VFSVolume*)l->data)->is_mountable = volume->is_mountable;
((VFSVolume*)l->data)->is_optical = volume->is_optical;
((VFSVolume*)l->data)->requires_eject = volume->requires_eject;
((VFSVolume*)l->data)->is_removable = volume->is_removable;
((VFSVolume*)l->data)->is_user_visible = volume->is_user_visible;
((VFSVolume*)l->data)->size = volume->size;
((VFSVolume*)l->data)->is_table = volume->is_table;
((VFSVolume*)l->data)->is_floppy = volume->is_floppy;
((VFSVolume*)l->data)->nopolicy = volume->nopolicy;
((VFSVolume*)l->data)->fs_type = volume->fs_type;
((VFSVolume*)l->data)->is_blank = volume->is_blank;
((VFSVolume*)l->data)->is_audiocd = volume->is_audiocd;
((VFSVolume*)l->data)->is_dvd = volume->is_dvd;
// Mount and ejection detect for automount
if ( volume->is_mounted )
{
((VFSVolume*)l->data)->ever_mounted = TRUE;
((VFSVolume*)l->data)->automount_time = 0;
}
else
{
if ( volume->is_removable && !volume->is_mountable ) // ejected
{
((VFSVolume*)l->data)->ever_mounted = FALSE;
((VFSVolume*)l->data)->automount_time = 0;
((VFSVolume*)l->data)->inhibit_auto = FALSE;
}
}
call_callbacks( (VFSVolume*)l->data, VFS_VOLUME_CHANGED );
vfs_free_volume_members( volume );
g_slice_free( VFSVolume, volume );
volume = (VFSVolume*)l->data;
if ( automount )
{
vfs_volume_automount( volume );
if ( !was_mounted && volume->is_mounted )
vfs_volume_autoexec( volume );
else if ( was_mounted && !volume->is_mounted )
{
vfs_volume_exec( volume, xset_get_s( "dev_exec_unmount" ) );
vfs_volume_special_unmounted( volume->device_file );
//remove udevil mount points in case other unmounted
vfs_volume_clean();
}
else if ( !was_audiocd && volume->is_audiocd )
vfs_volume_autoexec( volume );
//media inserted ?
if ( !was_mountable && volume->is_mountable )
vfs_volume_exec( volume, xset_get_s( "dev_exec_insert" ) );
// media ejected ?
if ( was_mountable && !volume->is_mountable && volume->is_mounted &&
( volume->is_optical || volume->is_removable ) )
unmount_if_mounted( volume->device_file );
}
return;
}
}
// add as new volume
volumes = g_list_append( volumes, volume );
call_callbacks( volume, VFS_VOLUME_ADDED );
if ( automount )
{
vfs_volume_automount( volume );
vfs_volume_exec( volume, xset_get_s( "dev_exec_insert" ) );
if ( volume->is_audiocd )
vfs_volume_autoexec( volume );
}
}
static void vfs_volume_clean()
{ // clean udevil mount points
char* udevil;
const char* mount_cmd = xset_get_s( "dev_mount_cmd" );
const char* umount_cmd = xset_get_s( "dev_unmount_cmd" );
// is udevil current u/mount solution?
if ( !mount_cmd || !umount_cmd )
udevil = g_find_program_in_path( "udevil" );
else if ( strstr( mount_cmd, "udevil" ) || strstr( umount_cmd, "udevil" ) )
udevil = g_find_program_in_path( "udevil" );
else
udevil = NULL;
if ( !udevil )
return;
char* line = g_strdup_printf( "bash -c \"sleep 1 ; %s clean\"", udevil );
//printf("Clean: %s\n", line );
g_free( udevil );
g_spawn_command_line_async( line, NULL );
g_free( line );
}
static gboolean vfs_volume_nonblock_removed( const char* mount_points )
{
GList* l;
VFSVolume* volume;
char* str;
if ( !mount_points )
return FALSE;
char* point = g_strdup( mount_points );
if ( str = strchr( point, ',' ) )
str[0] = '\0';
g_strstrip( point );
if ( !( point && point[0] == '/' ) )
return FALSE;
for ( l = volumes; l; l = l->next )
{
if ( ((VFSVolume*)l->data)->device_type != DEVICE_TYPE_BLOCK &&
!g_strcmp0( ((VFSVolume*)l->data)->mount_point, point ) )
{
// remove volume
printf( "network mount removed: %s\n", point );
volume = (VFSVolume*)l->data;
vfs_volume_special_unmounted( volume->device_file );
volumes = g_list_remove( volumes, volume );
call_callbacks( volume, VFS_VOLUME_REMOVED );
vfs_free_volume_members( volume );
g_slice_free( VFSVolume, volume );
vfs_volume_clean();
return TRUE;
}
}
return FALSE;
}
static void vfs_volume_device_removed( char* device_file )
{
GList* l;
VFSVolume* volume;
if ( !device_file )
return;
for ( l = volumes; l; l = l->next )
{
if ( ((VFSVolume*)l->data)->device_type == DEVICE_TYPE_BLOCK &&
!g_strcmp0( ((VFSVolume*)l->data)->device_file, device_file ) )
{
// remove volume
//printf("remove volume %s\n", device_file );
volume = (VFSVolume*)l->data;
vfs_volume_exec( volume, xset_get_s( "dev_exec_remove" ) );
if ( volume->is_mounted && volume->is_removable )
unmount_if_mounted( volume->device_file );
volumes = g_list_remove( volumes, volume );
call_callbacks( volume, VFS_VOLUME_REMOVED );
vfs_free_volume_members( volume );
g_slice_free( VFSVolume, volume );
break;
}
}
vfs_volume_clean();
}
void unmount_if_mounted( const char* device_file )
{
if ( !device_file )
return;
char* str = vfs_volume_device_unmount_cmd( device_file );
if ( !str )
return;
char* mtab = "/etc/mtab";
if ( !g_file_test( mtab, G_FILE_TEST_EXISTS ) )
mtab = "/proc/mounts";
char* line = g_strdup_printf( "bash -c \"grep -qs '^%s ' %s 2>/dev/null && %s 2>/dev/null\"",
device_file, mtab, str );
g_free( str );
printf( _("Unmount-If-Mounted: %s\n"), line );
g_spawn_command_line_async( line, NULL );
g_free( line );
}
void vfs_volume_special_unmount_all()
{
GList* l;
char* line;
for ( l = special_mounts; l; l = l->next )
{
if ( l->data )
{
line = g_strdup_printf( "udevil umount '%s'", (char*)l->data );
printf( _("\nAuto-Unmount: %s\n"), line );
g_spawn_command_line_async( line, NULL );
g_free( line );
g_free( l->data );
}
}
g_list_free( special_mounts );
special_mounts = NULL;
}
void vfs_volume_special_unmounted( const char* device_file )
{
GList* l;
if ( !device_file )
return;
for ( l = special_mounts; l; l = l->next )
{
if ( !g_strcmp0( (char*)l->data, device_file ) )
{
//printf("special_mounts --- %s\n", (char*)l->data );
g_free( l->data );
special_mounts = g_list_remove( special_mounts, l->data );
return;
}
}
}
void vfs_volume_special_mounted( const char* device_file )
{
GList* l;
const char* mfile = NULL;
if ( !device_file )
return;
//printf("vfs_volume_special_mounted %s\n", device_file );
// is device_file an ISO mount point? get device file
if ( !g_str_has_prefix( device_file, "/dev/" ) )
{
for ( l = volumes; l; l = l->next )
{
if ( ((VFSVolume*)l->data)->device_type == DEVICE_TYPE_BLOCK &&
((VFSVolume*)l->data)->is_mounted &&
g_str_has_prefix( ((VFSVolume*)l->data)->device_file, "/dev/loop" ) &&
!g_strcmp0( ((VFSVolume*)l->data)->mount_point, device_file ) )
{
mfile = ((VFSVolume*)l->data)->device_file;
break;
}
}
}
if ( !mfile )
mfile = device_file;
for ( l = special_mounts; l; l = l->next )
{
if ( !g_strcmp0( (char*)l->data, mfile ) )
return;
}
//printf("special_mounts +++ %s\n", mfile );
special_mounts = g_list_prepend( special_mounts, g_strdup( mfile ) );
}
gboolean on_cancel_inhibit_timer( gpointer user_data )
{
global_inhibit_auto = FALSE;
return FALSE;
}
gboolean vfs_volume_init()
{
struct udev_device *udevice;
struct udev_enumerate *enumerate;
struct udev_list_entry *devices, *dev_list_entry;
VFSVolume* volume;
// create udev
udev = udev_new();
if ( !udev )
{
printf( "spacefm: unable to initialize udev\n" );
return TRUE;
}
// read all block mount points
parse_mounts( FALSE );
// enumerate devices
enumerate = udev_enumerate_new( udev );
if ( enumerate )
{
udev_enumerate_add_match_subsystem( enumerate, "block" );
udev_enumerate_scan_devices( enumerate );
devices = udev_enumerate_get_list_entry( enumerate );
udev_list_entry_foreach( dev_list_entry, devices )
{
const char *syspath = udev_list_entry_get_name( dev_list_entry );
udevice = udev_device_new_from_syspath( udev, syspath );
if ( udevice )
{
if ( volume = vfs_volume_read_by_device( udevice ) )
vfs_volume_device_added( volume, FALSE ); // frees volume if needed
udev_device_unref( udevice );
}
}
udev_enumerate_unref(enumerate);
}
// enumerate non-block
parse_mounts( TRUE );
// start udev monitor
umonitor = udev_monitor_new_from_netlink( udev, "udev" );
if ( !umonitor )
{
printf( "spacefm: cannot create udev monitor\n" );
goto finish_;
}
if ( udev_monitor_enable_receiving( umonitor ) )
{
printf( "spacefm: cannot enable udev monitor receiving\n");
goto finish_;
}
if ( udev_monitor_filter_add_match_subsystem_devtype( umonitor, "block", NULL ) )
{
printf( "spacefm: cannot set udev filter\n");
goto finish_;
}
gint ufd = udev_monitor_get_fd( umonitor );
if ( ufd == 0 )
{
printf( "spacefm: cannot get udev monitor socket file descriptor\n");
goto finish_;
}
global_inhibit_auto = TRUE; // don't autoexec during startup
uchannel = g_io_channel_unix_new( ufd );
g_io_channel_set_flags( uchannel, G_IO_FLAG_NONBLOCK, NULL );
g_io_channel_set_close_on_unref( uchannel, TRUE );
g_io_add_watch( uchannel, G_IO_IN | G_IO_HUP, // | G_IO_NVAL | G_IO_ERR,
(GIOFunc)cb_udev_monitor_watch, NULL );
// start mount monitor
GError *error = NULL;
mchannel = g_io_channel_new_file ( "/proc/self/mountinfo", "r", &error );
if ( mchannel != NULL )
{
g_io_channel_set_close_on_unref( mchannel, TRUE );
g_io_add_watch ( mchannel, G_IO_ERR, (GIOFunc)cb_mount_monitor_watch, NULL );
}
else
{
free_devmounts();
printf( "spacefm: error monitoring /proc/self/mountinfo: %s\n", error->message );
g_error_free (error);
}
// do startup automounts
GList* l;
for ( l = volumes; l; l = l->next )
vfs_volume_automount( (VFSVolume*)l->data );
// start resume autoexec timer
g_timeout_add_seconds( 3, ( GSourceFunc ) on_cancel_inhibit_timer, NULL );
return TRUE;
finish_:
if ( umonitor )
{
udev_monitor_unref( umonitor );
umonitor = NULL;
}
if ( udev )
{
udev_unref( udev );
udev = NULL;
}
return TRUE;
}
gboolean vfs_volume_finalize()
{
// stop mount monitor
if ( mchannel )
{
g_io_channel_unref( mchannel );
mchannel = NULL;
}
free_devmounts();
// stop udev monitor
if ( uchannel )
{
g_io_channel_unref( uchannel );
uchannel = NULL;
}
if ( umonitor )
{
udev_monitor_unref( umonitor );
umonitor = NULL;
}
if ( udev )
{
udev_unref( udev );
udev = NULL;
}
// free callbacks
if ( callbacks )
g_array_free( callbacks, TRUE );
// free volumes / unmount all ?
GList* l;
gboolean unmount_all = xset_get_b( "dev_unmount_quit" );
if ( G_LIKELY( volumes ) )
{
for ( l = volumes; l; l = l->next )
{
if ( unmount_all )
vfs_volume_autounmount( (VFSVolume*)l->data );
vfs_free_volume_members( (VFSVolume*)l->data );
g_slice_free( VFSVolume, l->data );
}
}
volumes = NULL;
// unmount networks and files mounted during this session
vfs_volume_special_unmount_all();
// remove unused udevil mount points
vfs_volume_clean();
return TRUE;
}
/*
gboolean vfs_volume_init ()
{
FILE *fp;
char line[1024];
VFSVolume* volume;
GList* l;
if ( !g_file_test( "/usr/bin/udisks", G_FILE_TEST_EXISTS ) )
return TRUE;
// lookup all devices currently known to udisks
fp = popen("/usr/bin/udisks --enumerate-device-files", "r");
if ( fp )
{
while (fgets( line, sizeof( line )-1, fp ) != NULL)
{
if ( strncmp( line, "/dev/disk/", 10 ) && !strncmp( line, "/dev/", 5 ) )
{
line[ strlen( line ) - 1 ] = '\0'; // removes trailing \n
if ( volume = vfs_volume_read_by_device( line ) )
vfs_volume_device_added( volume, FALSE ); // frees volume if needed
}
}
pclose( fp );
}
global_inhibit_auto = TRUE; // don't autoexec during startup
vfs_volume_monitor_start();
for ( l = volumes; l; l = l->next )
vfs_volume_automount( (VFSVolume*)l->data );
g_timeout_add_seconds( 3, ( GSourceFunc ) on_cancel_inhibit_timer, NULL );
return TRUE;
}
gboolean vfs_volume_finalize()
{
GList* l;
// stop udisks monitor
if ( monpid )
{
if ( !waitpid( monpid, NULL, WNOHANG ) )
{
kill( monpid, SIGUSR1 );
monpid = NULL;
}
}
if ( callbacks )
g_array_free( callbacks, TRUE );
gboolean unmount_all = xset_get_b( "dev_unmount_quit" );
if ( G_LIKELY( volumes ) )
{
for ( l = volumes; l; l = l->next )
{
if ( unmount_all )
vfs_volume_autounmount( (VFSVolume*)l->data );
vfs_free_volume_members( (VFSVolume*)l->data );
g_slice_free( VFSVolume, l->data );
}
}
volumes = NULL;
return TRUE;
}
*/
const GList* vfs_volume_get_all_volumes()
{
return volumes;
}
static void call_callbacks( VFSVolume* vol, VFSVolumeState state )
{
int i;
VFSVolumeCallbackData* e;
if ( !callbacks )
return ;
e = ( VFSVolumeCallbackData* ) callbacks->data;
for ( i = 0; i < callbacks->len; ++i )
{
( *e[ i ].cb ) ( vol, state, e[ i ].user_data );
}
if ( evt_device->s || evt_device->ob2_data )
{
main_window_event( NULL, NULL, "evt_device", 0, 0, vol->device_file, 0,
0, state, FALSE );
}
}
void vfs_volume_add_callback( VFSVolumeCallback cb, gpointer user_data )
{
VFSVolumeCallbackData e;
if ( !cb )
return;
if ( !callbacks )
callbacks = g_array_sized_new( FALSE, FALSE, sizeof( VFSVolumeCallbackData ), 8 );
e.cb = cb;
e.user_data = user_data;
callbacks = g_array_append_val( callbacks, e );
}
void vfs_volume_remove_callback( VFSVolumeCallback cb, gpointer user_data )
{
int i;
VFSVolumeCallbackData* e;
if ( !callbacks )
return ;
e = ( VFSVolumeCallbackData* ) callbacks->data;
for ( i = 0; i < callbacks->len; ++i )
{
if ( e[ i ].cb == cb && e[ i ].user_data == user_data )
{
callbacks = g_array_remove_index_fast( callbacks, i );
if ( callbacks->len > 8 )
g_array_set_size( callbacks, 8 );
break;
}
}
}
gboolean vfs_volume_mount( VFSVolume* vol, GError** err )
{
return TRUE;
}
gboolean vfs_volume_umount( VFSVolume *vol, GError** err )
{
return TRUE;
}
gboolean vfs_volume_eject( VFSVolume *vol, GError** err )
{
return TRUE;
}
const char* vfs_volume_get_disp_name( VFSVolume *vol )
{
return vol->disp_name;
}
const char* vfs_volume_get_mount_point( VFSVolume *vol )
{
return vol->mount_point;
}
const char* vfs_volume_get_device( VFSVolume *vol )
{
return vol->device_file;
}
const char* vfs_volume_get_fstype( VFSVolume *vol )
{
return vol->fs_type;
}
const char* vfs_volume_get_icon( VFSVolume *vol )
{
if ( !vol->icon )
return NULL;
XSet* set = xset_get( vol->icon );
return set->icon;
}
gboolean vfs_volume_is_removable( VFSVolume *vol )
{
return vol->is_removable;
}
gboolean vfs_volume_is_mounted( VFSVolume *vol )
{
return vol->is_mounted;
}
gboolean vfs_volume_requires_eject( VFSVolume *vol )
{
return vol->requires_eject;
}
gboolean vfs_volume_dir_avoid_changes( const char* dir )
{
// determines if file change detection should be disabled for this
// dir (eg nfs stat calls block when a write is in progress so file
// change detection is unwanted)
// return FALSE to detect changes in this dir, TRUE to avoid change detection
const char* devnode;
gboolean ret;
//printf("vfs_volume_dir_avoid_changes( %s )\n", dir );
if ( !udev || !dir )
return FALSE;
// canonicalize path
char buf[ PATH_MAX + 1 ];
char* canon = realpath( dir, buf );
if ( !canon )
return FALSE;
// get devnum
struct stat stat_buf; // skip stat64
if ( stat( canon, &stat_buf ) == -1 )
return FALSE;
//printf(" stat_buf.st_dev = %d:%d\n", major(stat_buf.st_dev), minor( stat_buf.st_dev) );
struct udev_device* udevice = udev_device_new_from_devnum( udev, 'b',
stat_buf.st_dev );
if ( udevice )
devnode = udev_device_get_devnode( udevice );
else
devnode = NULL;
if ( devnode == NULL )
{
// not a block device
const char* fstype = get_devmount_fstype( major( stat_buf.st_dev ),
minor( stat_buf.st_dev ) );
//printf(" !udevice || !devnode fstype=%s\n", fstype );
if ( !fstype )
ret = FALSE;
else
// blacklist these types for no change detection (if not block device)
ret = ( g_str_has_prefix( fstype, "nfs" ) // nfs nfs4 etc
|| ( g_str_has_prefix( fstype, "fuse" ) &&
strcmp( fstype, "fuseblk" ) ) // fuse fuse.sshfs curlftpfs(fuse) etc
|| strstr( fstype, "cifs" )
|| !strcmp( fstype, "smbfs" )
|| !strcmp( fstype, "ftpfs" ) );
/* whitelist
!g_strcmp0( fstype, "tmpfs" ) || !g_strcmp0( fstype, "ramfs" )
|| !g_strcmp0( fstype, "aufs" ) || !g_strcmp0( fstype, "devtmpfs" )
|| !g_strcmp0( fstype, "overlayfs" ) );
*/
}
else
// block device
ret = FALSE;
if ( udevice )
udev_device_unref( udevice );
//printf( " avoid_changes = %s\n", ret ? "TRUE" : "FALSE" );
return ret;
}
dev_t get_device_parent( dev_t dev )
{
if ( !udev )
return 0;
struct udev_device* udevice = udev_device_new_from_devnum( udev, 'b', dev );
if ( !udevice )
return 0;
char* native_path = g_strdup( udev_device_get_syspath( udevice ) );
udev_device_unref( udevice );
if ( !native_path || ( native_path && !sysfs_file_exists( native_path, "start" ) ) )
{
// not a partition if no "start"
g_free( native_path );
return 0;
}
char* parent = g_path_get_dirname( native_path );
g_free( native_path );
udevice = udev_device_new_from_syspath( udev, parent );
g_free( parent );
if ( !udevice )
return 0;
dev_t retdev = udev_device_get_devnum( udevice );
udev_device_unref( udevice );
return retdev;
}
|
169 | ./spacefm/src/exo/exo-tree-view.c | /* $Id: exo-tree-view.c 22991 2006-09-02 11:41:18Z benny $ */
/*-
* Copyright (c) 2004-2006 Benedikt Meurer <benny@xfce.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/* Modified by Hong Jen Yee (PCMan) <pcman.tw@gmail.com>
* on 2008.05.11 for use in PCManFM */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include<glib/gi18n.h>
#include "exo-tree-view.h"
#include "exo-string.h"
#include "exo-marshal.h"
#include "exo-private.h"
#include "gtk2-compat.h"
#define I_(string) g_intern_static_string(string)
#if defined(G_PARAM_STATIC_NAME) && defined(G_PARAM_STATIC_NICK) && defined(G_PARAM_STATIC_BLURB)
#define EXO_PARAM_READABLE (G_PARAM_READABLE \
| G_PARAM_STATIC_NAME \
| G_PARAM_STATIC_NICK \
| G_PARAM_STATIC_BLURB)
#define EXO_PARAM_WRITABLE (G_PARAM_WRITABLE \
| G_PARAM_STATIC_NAME \
| G_PARAM_STATIC_NICK \
| G_PARAM_STATIC_BLURB)
#define EXO_PARAM_READWRITE (G_PARAM_READWRITE \
| G_PARAM_STATIC_NAME \
| G_PARAM_STATIC_NICK \
| G_PARAM_STATIC_BLURB)
#else
#define EXO_PARAM_READABLE (G_PARAM_READABLE)
#define EXO_PARAM_WRITABLE (G_PARAM_WRITABLE)
#define EXO_PARAM_READWRITE (G_PARAM_READWRITE)
#endif
#define exo_noop_false gtk_false
/*
#include <exo/exo-config.h>
#include <exo/exo-private.h>
#include <exo/exo-string.h>
#include <exo/exo-tree-view.h>
#include <exo/exo-utils.h>
#include <exo/exo-alias.h>
*/
#define EXO_TREE_VIEW_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), EXO_TYPE_TREE_VIEW, ExoTreeViewPrivate))
/* Property identifiers */
enum
{
PROP_0,
PROP_SINGLE_CLICK,
PROP_SINGLE_CLICK_TIMEOUT,
};
static void exo_tree_view_class_init (ExoTreeViewClass *klass);
static void exo_tree_view_init (ExoTreeView *tree_view);
static void exo_tree_view_finalize (GObject *object);
static void exo_tree_view_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec);
static void exo_tree_view_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec);
static gboolean exo_tree_view_button_press_event (GtkWidget *widget,
GdkEventButton *event);
static gboolean exo_tree_view_button_release_event (GtkWidget *widget,
GdkEventButton *event);
static gboolean exo_tree_view_motion_notify_event (GtkWidget *widget,
GdkEventMotion *event);
static gboolean exo_tree_view_leave_notify_event (GtkWidget *widget,
GdkEventCrossing *event);
static void exo_tree_view_drag_begin (GtkWidget *widget,
GdkDragContext *context);
static gboolean exo_tree_view_move_cursor (GtkTreeView *view,
GtkMovementStep step,
gint count);
static gboolean exo_tree_view_single_click_timeout (gpointer user_data);
static void exo_tree_view_single_click_timeout_destroy (gpointer user_data);
struct _ExoTreeViewPrivate
{
/* whether the next button-release-event should emit "row-activate" */
guint button_release_activates : 1;
/* whether drag and drop must be re-enabled on button-release-event (rubberbanding active) */
guint button_release_unblocks_dnd : 1;
/* whether rubberbanding must be re-enabled on button-release-event (drag and drop active) */
guint button_release_enables_rubber_banding : 1;
/* single click mode */
guint single_click : 1;
guint single_click_timeout;
gint single_click_timeout_id;
guint single_click_timeout_state;
/* the path below the pointer or NULL */
GtkTreePath *hover_path;
/* the column which is the only activable */
GtkTreeViewColumn* activable_column;
};
static GObjectClass *exo_tree_view_parent_class;
GType
exo_tree_view_get_type (void)
{
static GType type = G_TYPE_INVALID;
if (G_UNLIKELY (type == G_TYPE_INVALID))
{
type = _exo_g_type_register_simple (GTK_TYPE_TREE_VIEW,
"ExoTreeView",
sizeof (ExoTreeViewClass),
exo_tree_view_class_init,
sizeof (ExoTreeView),
exo_tree_view_init);
}
return type;
}
static void
exo_tree_view_class_init (ExoTreeViewClass *klass)
{
GtkTreeViewClass *gtktree_view_class;
GtkWidgetClass *gtkwidget_class;
GObjectClass *gobject_class;
/* add our private data to the class */
g_type_class_add_private (klass, sizeof (ExoTreeViewPrivate));
/* determine our parent type class */
exo_tree_view_parent_class = g_type_class_peek_parent (klass);
gobject_class = G_OBJECT_CLASS (klass);
gobject_class->finalize = exo_tree_view_finalize;
gobject_class->get_property = exo_tree_view_get_property;
gobject_class->set_property = exo_tree_view_set_property;
gtkwidget_class = GTK_WIDGET_CLASS (klass);
gtkwidget_class->button_press_event = exo_tree_view_button_press_event;
gtkwidget_class->button_release_event = exo_tree_view_button_release_event;
gtkwidget_class->motion_notify_event = exo_tree_view_motion_notify_event;
gtkwidget_class->leave_notify_event = exo_tree_view_leave_notify_event;
gtkwidget_class->drag_begin = exo_tree_view_drag_begin;
gtktree_view_class = GTK_TREE_VIEW_CLASS (klass);
gtktree_view_class->move_cursor = exo_tree_view_move_cursor;
/* initialize the library's i18n support */
/* _exo_i18n_init (); */
/**
* ExoTreeView:single-click:
*
* %TRUE to activate items using a single click instead of a
* double click.
*
* Since: 0.3.1.3
**/
g_object_class_install_property (gobject_class,
PROP_SINGLE_CLICK,
g_param_spec_boolean ("single-click",
_("Single Click"),
_("Whether the items in the view can be activated with single clicks"),
FALSE,
EXO_PARAM_READWRITE));
/**
* ExoTreeView:single-click-timeout:
*
* The amount of time in milliseconds after which the hover row (the row
* which is hovered by the mouse cursor) will be selected automatically
* in single-click mode. A value of %0 disables the automatic selection.
*
* Since: 0.3.1.5
**/
g_object_class_install_property (gobject_class,
PROP_SINGLE_CLICK_TIMEOUT,
g_param_spec_uint ("single-click-timeout",
_("Single Click Timeout"),
_("The amount of time after which the item under the mouse cursor will be selected automatically in single click mode"),
0, G_MAXUINT, 0,
EXO_PARAM_READWRITE));
}
static void
exo_tree_view_init (ExoTreeView *tree_view)
{
/* grab a pointer on the private data */
tree_view->priv = EXO_TREE_VIEW_GET_PRIVATE (tree_view);
tree_view->priv->single_click_timeout_id = -1;
}
static void
exo_tree_view_finalize (GObject *object)
{
ExoTreeView *tree_view = EXO_TREE_VIEW (object);
/* be sure to cancel any single-click timeout */
if (G_UNLIKELY (tree_view->priv->single_click_timeout_id >= 0))
g_source_remove (tree_view->priv->single_click_timeout_id);
/* be sure to release the hover path */
if (G_UNLIKELY (tree_view->priv->hover_path == NULL))
gtk_tree_path_free (tree_view->priv->hover_path);
(*G_OBJECT_CLASS (exo_tree_view_parent_class)->finalize) (object);
}
static void
exo_tree_view_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
ExoTreeView *tree_view = EXO_TREE_VIEW (object);
switch (prop_id)
{
case PROP_SINGLE_CLICK:
g_value_set_boolean (value, exo_tree_view_get_single_click (tree_view));
break;
case PROP_SINGLE_CLICK_TIMEOUT:
g_value_set_uint (value, exo_tree_view_get_single_click_timeout (tree_view));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
exo_tree_view_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
ExoTreeView *tree_view = EXO_TREE_VIEW (object);
switch (prop_id)
{
case PROP_SINGLE_CLICK:
exo_tree_view_set_single_click (tree_view, g_value_get_boolean (value));
break;
case PROP_SINGLE_CLICK_TIMEOUT:
exo_tree_view_set_single_click_timeout (tree_view, g_value_get_uint (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static gboolean
exo_tree_view_button_press_event (GtkWidget *widget,
GdkEventButton *event)
{
GtkTreeSelection *selection;
ExoTreeView *tree_view = EXO_TREE_VIEW (widget);
GtkTreePath *path = NULL;
gboolean result;
GList *selected_paths = NULL;
GList *lp;
GtkTreeViewColumn* col;
gboolean treat_as_blank = FALSE;
/* by default we won't emit "row-activated" on button-release-events */
tree_view->priv->button_release_activates = FALSE;
/* grab the tree selection */
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (tree_view));
/* be sure to cancel any pending single-click timeout */
if (G_UNLIKELY (tree_view->priv->single_click_timeout_id >= 0))
g_source_remove (tree_view->priv->single_click_timeout_id);
/* check if the button press was on the internal tree view window */
if (G_LIKELY (event->window == gtk_tree_view_get_bin_window (GTK_TREE_VIEW (tree_view))))
{
/* determine the path at the event coordinates */
if (!gtk_tree_view_get_path_at_pos (GTK_TREE_VIEW (tree_view), event->x, event->y, &path, &col, NULL, NULL))
path = NULL;
if( tree_view->priv->activable_column && col != tree_view->priv->activable_column )
{
treat_as_blank = TRUE;
if( path )
{
gtk_tree_path_free( path );
path = NULL;
}
gtk_tree_selection_unselect_all (selection);
}
/* we unselect all selected items if the user clicks on an empty
* area of the tree view and no modifier key is active.
*/
if (path == NULL && (event->state & gtk_accelerator_get_default_mod_mask ()) == 0)
gtk_tree_selection_unselect_all (selection);
/* completely ignore double-clicks in single-click mode */
if (tree_view->priv->single_click && event->type == GDK_2BUTTON_PRESS)
{
/* make sure we ignore the GDK_BUTTON_RELEASE
* event for this GDK_2BUTTON_PRESS event.
*/
gtk_tree_path_free (path);
return TRUE;
}
/* check if the next button-release-event should activate the selected row (single click support) */
tree_view->priv->button_release_activates = (tree_view->priv->single_click && event->type == GDK_BUTTON_PRESS && event->button == 1
&& (event->state & gtk_accelerator_get_default_mod_mask ()) == 0);
}
/* unfortunately GtkTreeView will unselect rows except the clicked one,
* which makes dragging from a GtkTreeView problematic. That's why we
* remember the selected paths here and restore them later.
*/
if (event->type == GDK_BUTTON_PRESS && (event->state & gtk_accelerator_get_default_mod_mask ()) == 0
&& path != NULL && gtk_tree_selection_path_is_selected (selection, path))
{
/* if no custom select function is set, we simply use exo_noop_false here,
* to tell the tree view that it may not alter the selection.
*/
//MOD disabled exo_noop_false due to GTK 2.20 bug https://bugzilla.gnome.org/show_bug.cgi?id=612802
/* if (G_LIKELY (selection->user_func == NULL))
gtk_tree_selection_set_select_function (selection, (GtkTreeSelectionFunc) exo_noop_false, NULL, NULL);
else
*/
selected_paths = gtk_tree_selection_get_selected_rows (selection, NULL);
}
/* Rubberbanding in GtkTreeView 2.9.0 and above is rather buggy, unfortunately, and
* doesn't interact properly with GTKs own DnD mechanism. So we need to block all
* dragging here when pressing the mouse button on a not yet selected row if
* rubberbanding is active, or disable rubberbanding when starting a drag.
*/
if (gtk_tree_selection_get_mode (selection) == GTK_SELECTION_MULTIPLE
&& gtk_tree_view_get_rubber_banding (GTK_TREE_VIEW (tree_view))
&& event->button == 1 && event->type == GDK_BUTTON_PRESS)
{
/* check if clicked on empty area or on a not yet selected row */
if (G_LIKELY (path == NULL || !gtk_tree_selection_path_is_selected (selection, path)))
{
/* need to disable drag and drop because we're rubberbanding now */
gpointer drag_data = g_object_get_data (G_OBJECT (tree_view), I_("gtk-site-data"));
if (G_LIKELY (drag_data != NULL))
{
g_signal_handlers_block_matched (G_OBJECT (tree_view),
G_SIGNAL_MATCH_DATA,
0, 0, NULL, NULL,
drag_data);
}
/* remember to re-enable drag and drop later */
tree_view->priv->button_release_unblocks_dnd = TRUE;
}
else
{
/* need to disable rubberbanding because we're dragging now */
gtk_tree_view_set_rubber_banding (GTK_TREE_VIEW (tree_view), FALSE);
/* remember to re-enable rubberbanding later */
tree_view->priv->button_release_enables_rubber_banding = TRUE;
}
}
/* call the parent's button press handler */
result = (*GTK_WIDGET_CLASS (exo_tree_view_parent_class)->button_press_event) (widget, event);
if( treat_as_blank )
gtk_tree_selection_unselect_all( selection );
/* restore previous selection if the path is still selected */
if (event->type == GDK_BUTTON_PRESS && (event->state & gtk_accelerator_get_default_mod_mask ()) == 0
&& path != NULL && gtk_tree_selection_path_is_selected (selection, path))
{
/* check if we have to restore paths */
if (G_LIKELY (gtk_tree_selection_get_select_function (selection) == (GtkTreeSelectionFunc) exo_noop_false))
{
/* just reset the select function (previously set to exo_noop_false),
* there's no clean way to do this, so what the heck.
*/
gtk_tree_selection_set_select_function (selection, NULL, NULL, NULL);
}
else
{
/* select all previously selected paths */
for (lp = selected_paths; lp != NULL; lp = lp->next)
gtk_tree_selection_select_path (selection, lp->data);
}
}
/* release the path (if any) */
if (G_LIKELY (path != NULL))
gtk_tree_path_free (path);
/* release the selected paths list */
g_list_foreach (selected_paths, (GFunc) gtk_tree_path_free, NULL);
g_list_free (selected_paths);
return result;
}
static gboolean
exo_tree_view_button_release_event (GtkWidget *widget,
GdkEventButton *event)
{
GtkTreeViewColumn *column;
GtkTreeSelection *selection;
GtkTreePath *path;
ExoTreeView *tree_view = EXO_TREE_VIEW (widget);
/* verify that the release event is for the internal tree view window */
if (G_LIKELY (event->window == gtk_tree_view_get_bin_window (GTK_TREE_VIEW (tree_view))))
{
/* check if we're in single-click mode and the button-release-event should emit a "row-activate" */
if (G_UNLIKELY (tree_view->priv->single_click && tree_view->priv->button_release_activates))
{
/* reset the "release-activates" flag */
tree_view->priv->button_release_activates = FALSE;
/* determine the path to the row that should be activated */
if (gtk_tree_view_get_path_at_pos (GTK_TREE_VIEW (tree_view), event->x, event->y, &path, &column, NULL, NULL))
{
/* emit row-activated for the determined row */
if( ! tree_view->priv->activable_column || tree_view->priv->activable_column == column )
gtk_tree_view_row_activated (GTK_TREE_VIEW (tree_view), path, column);
/* cleanup */
gtk_tree_path_free (path);
}
}
else if ((event->state & gtk_accelerator_get_default_mod_mask ()) == 0 && !tree_view->priv->button_release_unblocks_dnd)
{
/* determine the path on which the button was released and select only this row, this way
* the user is still able to alter the selection easily if all rows are selected.
*/
if (gtk_tree_view_get_path_at_pos (GTK_TREE_VIEW (tree_view), event->x, event->y, &path, &column, NULL, NULL))
{
/* check if the path is selected */
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (tree_view));
if (gtk_tree_selection_path_is_selected (selection, path))
{
/* unselect all rows */
gtk_tree_selection_unselect_all (selection);
/* select the row and place the cursor on it */
gtk_tree_view_set_cursor (GTK_TREE_VIEW (tree_view), path, column, FALSE);
}
/* cleanup */
gtk_tree_path_free (path);
}
}
}
/* check if we need to re-enable drag and drop */
if (G_LIKELY (tree_view->priv->button_release_unblocks_dnd))
{
gpointer drag_data = g_object_get_data (G_OBJECT (tree_view), I_("gtk-site-data"));
if (G_LIKELY (drag_data != NULL))
{
g_signal_handlers_unblock_matched (G_OBJECT (tree_view),
G_SIGNAL_MATCH_DATA,
0, 0, NULL, NULL,
drag_data);
}
tree_view->priv->button_release_unblocks_dnd = FALSE;
}
/* check if we need to re-enable rubberbanding */
if (G_UNLIKELY (tree_view->priv->button_release_enables_rubber_banding))
{
gtk_tree_view_set_rubber_banding (GTK_TREE_VIEW (tree_view), TRUE);
tree_view->priv->button_release_enables_rubber_banding = FALSE;
}
/* call the parent's button release handler */
return (*GTK_WIDGET_CLASS (exo_tree_view_parent_class)->button_release_event) (widget, event);
}
static gboolean
exo_tree_view_motion_notify_event (GtkWidget *widget,
GdkEventMotion *event)
{
ExoTreeView *tree_view = EXO_TREE_VIEW (widget);
GtkTreePath *path;
GdkCursor *cursor;
GtkTreeViewColumn *column;
/* check if the event occurred on the tree view internal window and we are in single-click mode */
if (event->window == gtk_tree_view_get_bin_window (GTK_TREE_VIEW (tree_view)) && tree_view->priv->single_click)
{
/* check if we're doing a rubberband selection right now (which means DnD is blocked) */
if (G_UNLIKELY (tree_view->priv->button_release_unblocks_dnd))
{
/* we're doing a rubberband selection, so don't activate anything */
tree_view->priv->button_release_activates = FALSE;
/* also be sure to reset the cursor */
gdk_window_set_cursor (event->window, NULL);
}
else
{
/* determine the path at the event coordinates */
if (!gtk_tree_view_get_path_at_pos (GTK_TREE_VIEW (tree_view), event->x, event->y, &path, &column, NULL, NULL))
path = NULL;
/* determine if the column is activable */
if( tree_view->priv->activable_column && column != tree_view->priv->activable_column )
{
if(path)
{
gtk_tree_path_free(path);
path = NULL;
}
}
/* check if we have a new path */
if ((path == NULL && tree_view->priv->hover_path != NULL) || (path != NULL && tree_view->priv->hover_path == NULL)
|| (path != NULL && tree_view->priv->hover_path != NULL && gtk_tree_path_compare (path, tree_view->priv->hover_path) != 0))
{
/* release the previous hover path */
if (tree_view->priv->hover_path != NULL)
gtk_tree_path_free (tree_view->priv->hover_path);
/* setup the new path */
tree_view->priv->hover_path = path;
/* check if we're over a row right now */
if (G_LIKELY (path != NULL))
{
/* setup the hand cursor to indicate that the row at the pointer can be activated with a single click */
cursor = gdk_cursor_new (GDK_HAND2);
gdk_window_set_cursor (event->window, cursor);
gdk_cursor_unref (cursor);
}
else
{
/* reset the cursor to its default */
gdk_window_set_cursor (event->window, NULL);
}
/* check if autoselection is enabled and the pointer is over a row */
if (G_LIKELY (tree_view->priv->single_click_timeout > 0 && tree_view->priv->hover_path != NULL))
{
/* cancel any previous single-click timeout */
if (G_LIKELY (tree_view->priv->single_click_timeout_id >= 0))
g_source_remove (tree_view->priv->single_click_timeout_id);
/* remember the current event state */
tree_view->priv->single_click_timeout_state = event->state;
/* schedule a new single-click timeout */
tree_view->priv->single_click_timeout_id = g_timeout_add_full (G_PRIORITY_LOW, tree_view->priv->single_click_timeout,
exo_tree_view_single_click_timeout, tree_view,
exo_tree_view_single_click_timeout_destroy);
}
}
else
{
/* release the path resources */
if (path != NULL)
gtk_tree_path_free (path);
}
}
}
/* call the parent's motion notify handler */
return (*GTK_WIDGET_CLASS (exo_tree_view_parent_class)->motion_notify_event) (widget, event);
}
static gboolean
exo_tree_view_leave_notify_event (GtkWidget *widget,
GdkEventCrossing *event)
{
ExoTreeView *tree_view = EXO_TREE_VIEW (widget);
/* be sure to cancel any pending single-click timeout */
if (G_UNLIKELY (tree_view->priv->single_click_timeout_id >= 0))
g_source_remove (tree_view->priv->single_click_timeout_id);
/* release and reset the hover path (if any) */
if (tree_view->priv->hover_path != NULL)
{
gtk_tree_path_free (tree_view->priv->hover_path);
tree_view->priv->hover_path = NULL;
}
/* reset the cursor for the tree view internal window */
if (gtk_widget_get_realized (GTK_WIDGET (tree_view)))
gdk_window_set_cursor (gtk_tree_view_get_bin_window (GTK_TREE_VIEW (tree_view)), NULL);
/* the next button-release-event should not activate */
tree_view->priv->button_release_activates = FALSE;
/* call the parent's leave notify handler */
return (*GTK_WIDGET_CLASS (exo_tree_view_parent_class)->leave_notify_event) (widget, event);
}
static void
exo_tree_view_drag_begin (GtkWidget *widget,
GdkDragContext *context)
{
ExoTreeView *tree_view = EXO_TREE_VIEW (widget);
/* the next button-release-event should not activate */
tree_view->priv->button_release_activates = FALSE;
/* call the parent's drag begin handler */
(*GTK_WIDGET_CLASS (exo_tree_view_parent_class)->drag_begin) (widget, context);
}
static gboolean
exo_tree_view_move_cursor (GtkTreeView *view,
GtkMovementStep step,
gint count)
{
ExoTreeView *tree_view = EXO_TREE_VIEW (view);
/* be sure to cancel any pending single-click timeout */
if (G_UNLIKELY (tree_view->priv->single_click_timeout_id >= 0))
g_source_remove (tree_view->priv->single_click_timeout_id);
/* release and reset the hover path (if any) */
if (tree_view->priv->hover_path != NULL)
{
gtk_tree_path_free (tree_view->priv->hover_path);
tree_view->priv->hover_path = NULL;
}
/* reset the cursor for the tree view internal window */
if (gtk_widget_get_realized (GTK_WIDGET (tree_view)))
gdk_window_set_cursor (gtk_tree_view_get_bin_window (GTK_TREE_VIEW (tree_view)), NULL);
/* call the parent's handler */
return (*GTK_TREE_VIEW_CLASS (exo_tree_view_parent_class)->move_cursor) (view, step, count);
}
static gboolean
exo_tree_view_single_click_timeout (gpointer user_data)
{
GtkTreeViewColumn *cursor_column;
GtkTreeSelection *selection;
GtkTreeModel *model;
GtkTreePath *cursor_path;
GtkTreeIter iter;
ExoTreeView *tree_view = EXO_TREE_VIEW (user_data);
gboolean hover_path_selected;
GList *rows;
GList *lp;
//GDK_THREADS_ENTER (); //sfm not needed because called from g_idle?
/* verify that we are in single-click mode, have focus and a hover path */
if (gtk_widget_has_focus (GTK_WIDGET (tree_view)) && tree_view->priv->single_click && tree_view->priv->hover_path != NULL)
{
/* transform the hover_path to a tree iterator */
model = gtk_tree_view_get_model (GTK_TREE_VIEW (tree_view));
if (model != NULL && gtk_tree_model_get_iter (model, &iter, tree_view->priv->hover_path))
{
/* determine the current cursor path/column */
gtk_tree_view_get_cursor (GTK_TREE_VIEW (tree_view), &cursor_path, &cursor_column);
/* be sure the row is fully visible */
gtk_tree_view_scroll_to_cell (GTK_TREE_VIEW (tree_view),
tree_view->priv->hover_path,
0, //sfm was cursor_column - caused horizontal scroll
FALSE, 0.0f, 0.0f);
/* determine the selection and change it appropriately */
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (tree_view));
if (gtk_tree_selection_get_mode (selection) == GTK_SELECTION_NONE)
{
/* just place the cursor on the row */
gtk_tree_view_set_cursor (GTK_TREE_VIEW (tree_view), tree_view->priv->hover_path, cursor_column, FALSE);
}
else if ((tree_view->priv->single_click_timeout_state & GDK_SHIFT_MASK) != 0
&& gtk_tree_selection_get_mode (selection) == GTK_SELECTION_MULTIPLE)
{
/* check if the item is not already selected (otherwise do nothing) */
if (!gtk_tree_selection_path_is_selected (selection, tree_view->priv->hover_path))
{
/* unselect all previously selected items */
gtk_tree_selection_unselect_all (selection);
/* since we cannot access the anchor of a GtkTreeView, we
* use the cursor instead which is usually the same row.
*/
if (G_UNLIKELY (cursor_path == NULL))
{
/* place the cursor on the new row */
gtk_tree_view_set_cursor (GTK_TREE_VIEW (tree_view), tree_view->priv->hover_path, cursor_column, FALSE);
}
else
{
/* select all between the cursor and the current row */
gtk_tree_selection_select_range (selection, tree_view->priv->hover_path, cursor_path);
}
}
}
else
{
/* remember the previously selected rows as set_cursor() clears the selection */
rows = gtk_tree_selection_get_selected_rows (selection, NULL);
/* check if the hover path is selected (as it will be selected after the set_cursor() call) */
hover_path_selected = gtk_tree_selection_path_is_selected (selection, tree_view->priv->hover_path);
/* place the cursor on the hover row */
gtk_tree_view_set_cursor (GTK_TREE_VIEW (tree_view), tree_view->priv->hover_path, cursor_column, FALSE);
/* restore the previous selection */
for (lp = rows; lp != NULL; lp = lp->next)
{
gtk_tree_selection_select_path (selection, lp->data);
gtk_tree_path_free (lp->data);
}
g_list_free (rows);
/* check what to do */
if ((gtk_tree_selection_get_mode (selection) == GTK_SELECTION_MULTIPLE ||
(gtk_tree_selection_get_mode (selection) == GTK_SELECTION_SINGLE && hover_path_selected))
&& (tree_view->priv->single_click_timeout_state & GDK_CONTROL_MASK) != 0)
{
/* toggle the selection state of the row */
if (G_UNLIKELY (hover_path_selected))
gtk_tree_selection_unselect_path (selection, tree_view->priv->hover_path);
else
gtk_tree_selection_select_path (selection, tree_view->priv->hover_path);
}
else if (G_UNLIKELY (!hover_path_selected))
{
/* unselect all other rows */
gtk_tree_selection_unselect_all (selection);
/* select only the hover row */
gtk_tree_selection_select_path (selection, tree_view->priv->hover_path);
}
}
/* cleanup */
if (G_LIKELY (cursor_path != NULL))
gtk_tree_path_free (cursor_path);
}
}
//GDK_THREADS_LEAVE ();
return FALSE;
}
static void
exo_tree_view_single_click_timeout_destroy (gpointer user_data)
{
EXO_TREE_VIEW (user_data)->priv->single_click_timeout_id = -1;
}
/**
* exo_tree_view_new:
*
* Allocates a new #ExoTreeView instance.
*
* Return value: the newly allocated #ExoTreeView.
*
* Since: 0.3.1.3
**/
GtkWidget*
exo_tree_view_new (void)
{
return g_object_new (EXO_TYPE_TREE_VIEW, NULL);
}
/**
* exo_tree_view_get_single_click:
* @tree_view : an #ExoTreeView.
*
* Returns %TRUE if @tree_view is in single-click mode, else %FALSE.
*
* Return value: whether @tree_view is in single-click mode.
*
* Since: 0.3.1.3
**/
gboolean
exo_tree_view_get_single_click (const ExoTreeView *tree_view)
{
g_return_val_if_fail (EXO_IS_TREE_VIEW (tree_view), FALSE);
return tree_view->priv->single_click;
}
/**
* exo_tree_view_set_single_click:
* @tree_view : an #ExoTreeView.
* @single_click : %TRUE to use single-click for @tree_view, %FALSE otherwise.
*
* If @single_click is %TRUE, @tree_view will use single-click mode, else
* the default double-click mode will be used.
*
* Since: 0.3.1.3
**/
void
exo_tree_view_set_single_click (ExoTreeView *tree_view,
gboolean single_click)
{
g_return_if_fail (EXO_IS_TREE_VIEW (tree_view));
if (tree_view->priv->single_click != !!single_click)
{
tree_view->priv->single_click = !!single_click;
g_object_notify (G_OBJECT (tree_view), "single-click");
}
}
/**
* exo_tree_view_get_single_click_timeout:
* @tree_view : a #ExoTreeView.
*
* Returns the amount of time in milliseconds after which the
* item under the mouse cursor will be selected automatically
* in single click mode. A value of %0 means that the behavior
* is disabled and the user must alter the selection manually.
*
* Return value: the single click autoselect timeout or %0 if
* the behavior is disabled.
*
* Since: 0.3.1.5
**/
guint
exo_tree_view_get_single_click_timeout (const ExoTreeView *tree_view)
{
g_return_val_if_fail (EXO_IS_TREE_VIEW (tree_view), 0u);
return tree_view->priv->single_click_timeout;
}
/**
* exo_tree_view_set_single_click_timeout:
* @tree_view : a #ExoTreeView.
* @single_click_timeout : the new timeout or %0 to disable.
*
* If @single_click_timeout is a value greater than zero, it specifies
* the amount of time in milliseconds after which the item under the
* mouse cursor will be selected automatically in single click mode.
* A value of %0 for @single_click_timeout disables the autoselection
* for @tree_view.
*
* This setting does not have any effect unless the @tree_view is in
* single-click mode, see exo_tree_view_set_single_click().
*
* Since: 0.3.1.5
**/
void
exo_tree_view_set_single_click_timeout (ExoTreeView *tree_view,
guint single_click_timeout)
{
g_return_if_fail (EXO_IS_TREE_VIEW (tree_view));
/* check if we have a new setting */
if (tree_view->priv->single_click_timeout != single_click_timeout)
{
/* apply the new setting */
tree_view->priv->single_click_timeout = single_click_timeout;
/* be sure to cancel any pending single click timeout */
if (G_UNLIKELY (tree_view->priv->single_click_timeout_id >= 0))
g_source_remove (tree_view->priv->single_click_timeout_id);
/* notify listeners */
g_object_notify (G_OBJECT (tree_view), "single-click-timeout");
}
}
/* 2008.07.16 added by Hong Jen Yee for PCManFM.
* If activable column is set, only the specified column can be activated.
* Other columns are viewed as blank area and won't receive mouse clicks.
*/
GtkTreeViewColumn* exo_tree_view_get_activable_column( ExoTreeView *tree_view )
{
return tree_view->priv->activable_column;
}
void exo_tree_view_set_activable_column( ExoTreeView *tree_view,
GtkTreeViewColumn* column )
{
tree_view->priv->activable_column = column;
}
/*
#define __EXO_TREE_VIEW_C__
#include <exo/exo-aliasdef.c>
*/
|
170 | ./spacefm/src/exo/exo-string.c | /* $Id: exo-string.c 47 2006-01-30 02:32:10Z pcmanx $ */
/*-
* Copyright (c) 2004 os-cillation e.K.
*
* Written by Benedikt Meurer <benny@xfce.org>.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef HAVE_MEMORY_H
#include <memory.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#include "exo-string.h"
/**
* exo_str_elide_underscores:
* @text : A zero terminated string.
*
* Returns a copy of @text with all mnemonic underscores
* stripped off.
*
* Return value: A copy of @text without underscores. The
* returned string must be freed when no
* longer required.
**/
gchar*
exo_str_elide_underscores (const gchar *text)
{
const gchar *s;
gboolean last_underscore = FALSE;
gchar *result;
gchar *t;
g_return_val_if_fail (text != NULL, NULL);
result = g_malloc (strlen (text) + 1);
for (s = text, t = result; *s != '\0'; ++s)
if (!last_underscore && *s == '_')
{
last_underscore = TRUE;
}
else
{
last_underscore = FALSE;
*t++ = *s;
}
*t = '\0';
return result;
}
/**
* exo_str_is_equal:
* @a : A pointer to first string or %NULL.
* @b : A pointer to second string or %NULL.
*
* %NULL-safe string comparison. Returns %TRUE if both @a and @b are
* %NULL or if @a and @b refer to valid strings which are equal.
*
* You should always prefer this function over strcmp().
*
* Return value: %TRUE if @a equals @b, else %FALSE.
**/
gboolean
exo_str_is_equal (const gchar *a,
const gchar *b)
{
if (a == NULL && b == NULL)
return TRUE;
else if (a == NULL || b == NULL)
return FALSE;
while (*a == *b++)
if (*a++ == '\0')
return TRUE;
return FALSE;
}
/**
* exo_strndupv:
* @strv : String vector to duplicate.
* @num : Number of strings in @strv to
* duplicate.
*
* Creates a new string vector containing the
* first @n elements of @strv.
*
* Return value: The new string vector. Should be
* freed using g_strfreev() when no
* longer needed.
**/
gchar**
exo_strndupv (gchar **strv,
gint num)
{
gchar **result;
g_return_val_if_fail (strv != NULL, NULL);
g_return_val_if_fail (num >= 0, NULL);
result = g_new (gchar *, num + 1);
result[num--] = NULL;
for (; num >= 0; --num)
result[num] = g_strdup (strv[num]);
return result;
}
|
171 | ./spacefm/src/exo/exo-private.c | /* $Id: exo-private.c 22884 2006-08-26 12:40:43Z benny $ */
/*-
* Copyright (c) 2004-2006 os-cillation e.K.
*
* Written by Benedikt Meurer <benny@xfce.org>.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef HAVE_LIBINTL_H
#include <libintl.h>
#endif
#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif
#include "exo-private.h"
#include "exo-string.h"
#define I_(string) g_intern_static_string(string)
/*
void
_exo_i18n_init (void)
{
static gboolean inited = FALSE;
if (G_UNLIKELY (!inited))
{
inited = TRUE;
bindtextdomain (GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
#ifdef HAVE_BIND_TEXTDOMAIN_CODESET
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
#endif
}
}
*/
void
_exo_gtk_widget_send_focus_change (GtkWidget *widget,
gboolean in)
{
#if !GTK_CHECK_VERSION (2, 22, 0)
if (in)
GTK_WIDGET_SET_FLAGS (widget, GTK_HAS_FOCUS);
else
GTK_WIDGET_UNSET_FLAGS (widget, GTK_HAS_FOCUS);
#endif
GdkEvent *fevent;
g_object_ref (G_OBJECT (widget));
fevent = gdk_event_new (GDK_FOCUS_CHANGE);
fevent->focus_change.type = GDK_FOCUS_CHANGE;
fevent->focus_change.window = g_object_ref (gtk_widget_get_window (widget));
fevent->focus_change.in = in;
#if GTK_CHECK_VERSION (2, 22, 0)
gtk_widget_send_focus_change (widget, fevent);
#else
gtk_widget_event (widget, fevent);
g_object_notify (G_OBJECT (widget), "has-focus");
#endif
g_object_unref (G_OBJECT (widget));
gdk_event_free (fevent);
}
/**
* _exo_g_type_register_simple:
* @type_parent : the parent #GType.
* @type_name_static : the name of the new #GType, must reside in static
* storage and remain unchanged during the lifetime
* of the process.
* @class_size : the size of the class structure in bytes.
* @class_init : the class init function or %NULL.
* @instance_size : the size of the instance structure in bytes.
* @instance_init : the constructor function or %NULL.
*
* Simple wrapper for g_type_register_static(), which takes the most
* important aspects of the type as parameters to avoid relocations
* when using static constant #GTypeInfo<!---->s.
*
* Return value: the newly registered #GType.
**/
GType
_exo_g_type_register_simple (GType type_parent,
const gchar *type_name_static,
guint class_size,
gpointer class_init,
guint instance_size,
gpointer instance_init)
{
/* generate the type info (on the stack) */
GTypeInfo info =
{
class_size,
NULL,
NULL,
class_init,
NULL,
NULL,
instance_size,
0,
instance_init,
NULL,
};
/* register the static type */
return g_type_register_static (type_parent, I_(type_name_static), &info, 0);
}
/**
* _exo_g_type_add_interface_simple:
* @instance_type : the #GType which should implement the @interface_type.
* @interface_type : the #GType of the interface.
* @interface_init_func : initialization function for the interface.
*
* Simple wrapper for g_type_add_interface_static(), which helps to avoid unnecessary
* relocations for the #GInterfaceInfo<!---->s.
**/
void
_exo_g_type_add_interface_simple (GType instance_type,
GType interface_type,
GInterfaceInitFunc interface_init_func)
{
GInterfaceInfo info =
{
interface_init_func,
NULL,
NULL,
};
g_type_add_interface_static (instance_type, interface_type, &info);
}
|
172 | ./spacefm/src/exo/exo-icon-view.c | /* $Id: exo-icon-view.c 24207 2006-12-28 19:16:50Z benny $ */
/*-
* Copyright (c) 2004-2006 os-cillation e.K.
* Copyright (c) 2002,2004 Anders Carlsson <andersca@gnu.org>
*
* Written by Benedikt Meurer <benny@xfce.org>.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/* Modified by Hong Jen Yee (PCMan) <pcman.tw@gmail.com>
* on 2008.05.11 for use in PCManFM */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
/* #ifdef HAVE_MATH_H */
#include <math.h>
/* #endif */
#ifdef HAVE_MEMORY_H
#include <memory.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#include <gdk/gdkkeysyms.h>
#include "exo-icon-view.h"
#include "exo-string.h"
#include "exo-marshal.h"
#include "exo-private.h"
#include "gtk2-compat.h"
#if defined(G_PARAM_STATIC_NAME) && defined(G_PARAM_STATIC_NICK) && defined(G_PARAM_STATIC_BLURB)
#define EXO_PARAM_READABLE (G_PARAM_READABLE \
| G_PARAM_STATIC_NAME \
| G_PARAM_STATIC_NICK \
| G_PARAM_STATIC_BLURB)
#define EXO_PARAM_WRITABLE (G_PARAM_WRITABLE \
| G_PARAM_STATIC_NAME \
| G_PARAM_STATIC_NICK \
| G_PARAM_STATIC_BLURB)
#define EXO_PARAM_READWRITE (G_PARAM_READWRITE \
| G_PARAM_STATIC_NAME \
| G_PARAM_STATIC_NICK \
| G_PARAM_STATIC_BLURB)
#else
#define EXO_PARAM_READABLE (G_PARAM_READABLE)
#define EXO_PARAM_WRITABLE (G_PARAM_WRITABLE)
#define EXO_PARAM_READWRITE (G_PARAM_READWRITE)
#endif
#define I_(string) g_intern_static_string(string)
GType
exo_icon_view_layout_mode_get_type (void)
{
static GType type = 0;
if (type == 0) {
static const GEnumValue values[] = {
{ EXO_ICON_VIEW_LAYOUT_ROWS, "EXO_ICON_VIEW_LAYOUT_ROWS", "rows" },
{ EXO_ICON_VIEW_LAYOUT_COLS, "EXO_ICON_VIEW_LAYOUT_COLS", "cols" },
{ 0, NULL, NULL }
};
type = g_enum_register_static ("ExoIconViewLayoutMode", values);
}
return type;
}
#define EXO_TYPE_ICON_VIEW_LAYOUT_MODE (exo_icon_view_layout_mode_get_type())
/* enumerations from "exo-mount-point.h" */
/*
#include <exo/exo-config.h>
#include <exo/exo-enum-types.h>
#include <exo/exo-icon-view.h>
#include <exo/exo-private.h>
#include <exo/exo-alias.h>
*/
/* the search dialog timeout (in ms) */
#define EXO_ICON_VIEW_SEARCH_DIALOG_TIMEOUT (5000)
#define SCROLL_EDGE_SIZE 15
/* Property identifiers */
enum
{
PROP_0,
PROP_PIXBUF_COLUMN,
PROP_TEXT_COLUMN,
PROP_MARKUP_COLUMN,
PROP_SELECTION_MODE,
PROP_LAYOUT_MODE,
PROP_ORIENTATION,
PROP_MODEL,
PROP_COLUMNS,
PROP_ITEM_WIDTH,
PROP_SPACING,
PROP_ROW_SPACING,
PROP_COLUMN_SPACING,
PROP_MARGIN,
PROP_REORDERABLE,
PROP_SINGLE_CLICK,
PROP_SINGLE_CLICK_TIMEOUT,
PROP_ENABLE_SEARCH,
PROP_SEARCH_COLUMN,
#if GTK_CHECK_VERSION (3, 0, 0)
PROP_HADJUSTMENT,
PROP_VADJUSTMENT,
PROP_HSCROLL_POLICY,
PROP_VSCROLL_POLICY,
#endif
};
/* Signal identifiers */
enum
{
ITEM_ACTIVATED,
SELECTION_CHANGED,
SELECT_ALL,
UNSELECT_ALL,
SELECT_CURSOR_ITEM,
TOGGLE_CURSOR_ITEM,
MOVE_CURSOR,
ACTIVATE_CURSOR_ITEM,
START_INTERACTIVE_SEARCH,
LAST_SIGNAL
};
/* Icon view flags */
typedef enum
{
EXO_ICON_VIEW_DRAW_KEYFOCUS = (1l << 0), /* whether to draw keyboard focus */
EXO_ICON_VIEW_ITERS_PERSIST = (1l << 1), /* whether current model provides persistent iterators */
} ExoIconViewFlags;
#define EXO_ICON_VIEW_SET_FLAG(icon_view, flag) G_STMT_START{ (EXO_ICON_VIEW (icon_view)->priv->flags |= flag); }G_STMT_END
#define EXO_ICON_VIEW_UNSET_FLAG(icon_view, flag) G_STMT_START{ (EXO_ICON_VIEW (icon_view)->priv->flags &= ~(flag));}G_STMT_END
#define EXO_ICON_VIEW_FLAG_SET(icon_view, flag) ((EXO_ICON_VIEW (icon_view)->priv->flags & (flag)) == (flag))
typedef struct _ExoIconViewCellInfo ExoIconViewCellInfo;
typedef struct _ExoIconViewChild ExoIconViewChild;
typedef struct _ExoIconViewItem ExoIconViewItem;
#define EXO_ICON_VIEW_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), EXO_TYPE_ICON_VIEW, ExoIconViewPrivate))
#define EXO_ICON_VIEW_CELL_INFO(obj) ((ExoIconViewCellInfo *) (obj))
#define EXO_ICON_VIEW_CHILD(obj) ((ExoIconViewChild *) (obj))
#define EXO_ICON_VIEW_ITEM(obj) ((ExoIconViewItem *) (obj))
static void exo_icon_view_class_init (ExoIconViewClass *klass);
static void exo_icon_view_cell_layout_init (GtkCellLayoutIface *iface);
static void exo_icon_view_init (ExoIconView *icon_view);
static void exo_icon_view_dispose (GObject *object);
static void exo_icon_view_finalize (GObject *object);
static void exo_icon_view_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec);
static void exo_icon_view_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec);
static void exo_icon_view_realize (GtkWidget *widget);
static void exo_icon_view_unrealize (GtkWidget *widget);
static void exo_icon_view_size_allocate (GtkWidget *widget,
GtkAllocation *allocation);
static void exo_icon_view_style_set (GtkWidget *widget,
GtkStyle *previous_style);
#if GTK_CHECK_VERSION (3, 0, 0)
static gboolean exo_icon_view_draw (GtkWidget *widget,
cairo_t *cr);
static void exo_icon_view_set_hadjustment (ExoIconView *icon_view,
GtkAdjustment *hadj);
static void exo_icon_view_set_vadjustment (ExoIconView *icon_view,
GtkAdjustment *vadj);
#else
static gboolean exo_icon_view_expose_event (GtkWidget *widget,
GdkEventExpose *event);
static void exo_icon_view_set_adjustments (ExoIconView *icon_view,
GtkAdjustment *hadj,
GtkAdjustment *vadj);
#endif
static void exo_icon_view_size_request (GtkWidget *widget,
GtkRequisition *requisition);
static gboolean exo_icon_view_motion_notify_event (GtkWidget *widget,
GdkEventMotion *event);
static gboolean exo_icon_view_button_press_event (GtkWidget *widget,
GdkEventButton *event);
static gboolean exo_icon_view_button_release_event (GtkWidget *widget,
GdkEventButton *event);
static gboolean exo_icon_view_scroll_event (GtkWidget *widget,
GdkEventScroll *event);
static gboolean exo_icon_view_key_press_event (GtkWidget *widget,
GdkEventKey *event);
static gboolean exo_icon_view_focus_out_event (GtkWidget *widget,
GdkEventFocus *event);
static gboolean exo_icon_view_leave_notify_event (GtkWidget *widget,
GdkEventCrossing *event);
static void exo_icon_view_remove (GtkContainer *container,
GtkWidget *widget);
static void exo_icon_view_forall (GtkContainer *container,
gboolean include_internals,
GtkCallback callback,
gpointer callback_data);
static void exo_icon_view_real_select_all (ExoIconView *icon_view);
static void exo_icon_view_real_unselect_all (ExoIconView *icon_view);
static void exo_icon_view_real_select_cursor_item (ExoIconView *icon_view);
static void exo_icon_view_real_toggle_cursor_item (ExoIconView *icon_view);
static gboolean exo_icon_view_real_activate_cursor_item (ExoIconView *icon_view);
static gboolean exo_icon_view_real_start_interactive_search (ExoIconView *icon_view);
static void exo_icon_view_adjustment_changed (GtkAdjustment *adjustment,
ExoIconView *icon_view);
static gint exo_icon_view_layout_cols (ExoIconView *icon_view,
gint item_height,
gint *x,
gint *maximum_height,
gint max_rows);
static gint exo_icon_view_layout_rows (ExoIconView *icon_view,
gint item_width,
gint *y,
gint *maximum_width,
gint max_cols);
static void exo_icon_view_layout (ExoIconView *icon_view);
static void exo_icon_view_paint_item (ExoIconView *icon_view,
ExoIconViewItem *item,
GdkRectangle *area,
#if GTK_CHECK_VERSION (3, 0, 0)
cairo_t *cr,
#else
GdkDrawable *drawable,
#endif
gint x,
gint y,
gboolean draw_focus);
static void exo_icon_view_queue_draw_item (ExoIconView *icon_view,
ExoIconViewItem *item);
static void exo_icon_view_queue_layout (ExoIconView *icon_view);
static void exo_icon_view_set_cursor_item (ExoIconView *icon_view,
ExoIconViewItem *item,
gint cursor_cell);
static void exo_icon_view_start_rubberbanding (ExoIconView *icon_view,
gint x,
gint y);
static void exo_icon_view_stop_rubberbanding (ExoIconView *icon_view);
static void exo_icon_view_update_rubberband_selection (ExoIconView *icon_view);
static gboolean exo_icon_view_item_hit_test (ExoIconView *icon_view,
ExoIconViewItem *item,
gint x,
gint y,
gint width,
gint height);
static gboolean exo_icon_view_unselect_all_internal (ExoIconView *icon_view);
static void exo_icon_view_calculate_item_size (ExoIconView *icon_view,
ExoIconViewItem *item);
static void exo_icon_view_calculate_item_size2 (ExoIconView *icon_view,
ExoIconViewItem *item,
gint *max_width,
gint *max_height);
static void exo_icon_view_update_rubberband (gpointer data);
static void exo_icon_view_invalidate_sizes (ExoIconView *icon_view);
static void exo_icon_view_add_move_binding (GtkBindingSet *binding_set,
guint keyval,
guint modmask,
GtkMovementStep step,
gint count);
static gboolean exo_icon_view_real_move_cursor (ExoIconView *icon_view,
GtkMovementStep step,
gint count);
static void exo_icon_view_move_cursor_up_down (ExoIconView *icon_view,
gint count);
static void exo_icon_view_move_cursor_page_up_down (ExoIconView *icon_view,
gint count);
static void exo_icon_view_move_cursor_left_right (ExoIconView *icon_view,
gint count);
static void exo_icon_view_move_cursor_start_end (ExoIconView *icon_view,
gint count);
static void exo_icon_view_scroll_to_item (ExoIconView *icon_view,
ExoIconViewItem *item);
static void exo_icon_view_select_item (ExoIconView *icon_view,
ExoIconViewItem *item);
static void exo_icon_view_unselect_item (ExoIconView *icon_view,
ExoIconViewItem *item);
static gboolean exo_icon_view_select_all_between (ExoIconView *icon_view,
ExoIconViewItem *anchor,
ExoIconViewItem *cursor);
static ExoIconViewItem * exo_icon_view_get_item_at_coords (const ExoIconView *icon_view,
gint x,
gint y,
gboolean only_in_cell,
ExoIconViewCellInfo **cell_at_pos);
static void exo_icon_view_get_cell_area (ExoIconView *icon_view,
ExoIconViewItem *item,
ExoIconViewCellInfo *cell_info,
GdkRectangle *cell_area);
static ExoIconViewCellInfo *exo_icon_view_get_cell_info (ExoIconView *icon_view,
GtkCellRenderer *renderer);
static void exo_icon_view_set_cell_data (const ExoIconView *icon_view,
ExoIconViewItem *item);
static void exo_icon_view_cell_layout_pack_start (GtkCellLayout *layout,
GtkCellRenderer *renderer,
gboolean expand);
static void exo_icon_view_cell_layout_pack_end (GtkCellLayout *layout,
GtkCellRenderer *renderer,
gboolean expand);
static void exo_icon_view_cell_layout_add_attribute (GtkCellLayout *layout,
GtkCellRenderer *renderer,
const gchar *attribute,
gint column);
static void exo_icon_view_cell_layout_clear (GtkCellLayout *layout);
static void exo_icon_view_cell_layout_clear_attributes (GtkCellLayout *layout,
GtkCellRenderer *renderer);
static void exo_icon_view_cell_layout_set_cell_data_func (GtkCellLayout *layout,
GtkCellRenderer *cell,
GtkCellLayoutDataFunc func,
gpointer func_data,
GDestroyNotify destroy);
static void exo_icon_view_cell_layout_reorder (GtkCellLayout *layout,
GtkCellRenderer *cell,
gint position);
static void exo_icon_view_item_activate_cell (ExoIconView *icon_view,
ExoIconViewItem *item,
ExoIconViewCellInfo *cell_info,
GdkEvent *event);
static void exo_icon_view_put (ExoIconView *icon_view,
GtkWidget *widget,
ExoIconViewItem *item,
gint cell);
static void exo_icon_view_remove_widget (GtkCellEditable *editable,
ExoIconView *icon_view);
static void exo_icon_view_start_editing (ExoIconView *icon_view,
ExoIconViewItem *item,
ExoIconViewCellInfo *cell_info,
GdkEvent *event);
static void exo_icon_view_stop_editing (ExoIconView *icon_view,
gboolean cancel_editing);
/* Source side drag signals */
static void exo_icon_view_drag_begin (GtkWidget *widget,
GdkDragContext *context);
static void exo_icon_view_drag_end (GtkWidget *widget,
GdkDragContext *context);
static void exo_icon_view_drag_data_get (GtkWidget *widget,
GdkDragContext *context,
GtkSelectionData *selection_data,
guint info,
guint time);
static void exo_icon_view_drag_data_delete (GtkWidget *widget,
GdkDragContext *context);
/* Target side drag signals */
static void exo_icon_view_drag_leave (GtkWidget *widget,
GdkDragContext *context,
guint time);
static gboolean exo_icon_view_drag_motion (GtkWidget *widget,
GdkDragContext *context,
gint x,
gint y,
guint time);
static gboolean exo_icon_view_drag_drop (GtkWidget *widget,
GdkDragContext *context,
gint x,
gint y,
guint time);
static void exo_icon_view_drag_data_received (GtkWidget *widget,
GdkDragContext *context,
gint x,
gint y,
GtkSelectionData *selection_data,
guint info,
guint time);
static gboolean exo_icon_view_maybe_begin_drag (ExoIconView *icon_view,
GdkEventMotion *event);
static void remove_scroll_timeout (ExoIconView *icon_view);
/* single-click autoselection support */
static gboolean exo_icon_view_single_click_timeout (gpointer user_data);
static void exo_icon_view_single_click_timeout_destroy (gpointer user_data);
/* Interactive search support */
static void exo_icon_view_search_activate (GtkEntry *entry,
ExoIconView *icon_view);
static void exo_icon_view_search_dialog_hide (GtkWidget *search_dialog,
ExoIconView *icon_view);
static void exo_icon_view_search_ensure_directory (ExoIconView *icon_view);
static void exo_icon_view_search_init (GtkWidget *search_entry,
ExoIconView *icon_view);
static gboolean exo_icon_view_search_iter (ExoIconView *icon_view,
GtkTreeModel *model,
GtkTreeIter *iter,
const gchar *text,
gint *count,
gint n);
static void exo_icon_view_search_move (GtkWidget *widget,
ExoIconView *icon_view,
gboolean move_up);
#if GTK_CHECK_VERSION (3, 0, 0)
static void exo_icon_view_search_preedit_changed (GtkEntry *entry,
gchar *preedit,
#else
static void exo_icon_view_search_preedit_changed (GtkIMContext *im_context,
#endif
ExoIconView *icon_view);
static gboolean exo_icon_view_search_start (ExoIconView *icon_view,
gboolean keybinding);
static gboolean exo_icon_view_search_equal_func (GtkTreeModel *model,
gint column,
const gchar *key,
GtkTreeIter *iter,
gpointer user_data);
static void exo_icon_view_search_position_func (ExoIconView *icon_view,
GtkWidget *search_dialog,
gpointer user_data);
static gboolean exo_icon_view_search_button_press_event (GtkWidget *widget,
GdkEventButton *event,
ExoIconView *icon_view);
static gboolean exo_icon_view_search_delete_event (GtkWidget *widget,
GdkEventAny *event,
ExoIconView *icon_view);
static gboolean exo_icon_view_search_key_press_event (GtkWidget *widget,
GdkEventKey *event,
ExoIconView *icon_view);
static gboolean exo_icon_view_search_scroll_event (GtkWidget *widget,
GdkEventScroll *event,
ExoIconView *icon_view);
static gboolean exo_icon_view_search_timeout (gpointer user_data);
static void exo_icon_view_search_timeout_destroy (gpointer user_data);
struct _ExoIconViewCellInfo
{
GtkCellRenderer *cell;
guint expand : 1;
guint pack : 1;
guint editing : 1;
gint position;
GSList *attributes;
GtkCellLayoutDataFunc func;
gpointer func_data;
GDestroyNotify destroy;
};
struct _ExoIconViewChild
{
ExoIconViewItem *item;
GtkWidget *widget;
gint cell;
};
struct _ExoIconViewItem
{
GtkTreeIter iter;
/* Bounding box (a value of -1 for width indicates
* that the item needs to be layouted first)
*/
GdkRectangle area;
/* Individual cells.
* box[i] is the actual area occupied by cell i,
* before, after are used to calculate the cell
* area relative to the box.
* See exo_icon_view_get_cell_area().
*/
gint n_cells;
GdkRectangle *box;
gint *before;
gint *after;
guint row : ((sizeof (guint) / 2) * 8) - 1;
guint col : ((sizeof (guint) / 2) * 8) - 1;
guint selected : 1;
guint selected_before_rubberbanding : 1;
};
struct _ExoIconViewPrivate
{
gint width, height;
gint rows, cols;
GtkSelectionMode selection_mode;
ExoIconViewLayoutMode layout_mode;
GdkWindow *bin_window;
GList *children;
GtkTreeModel *model;
GList *items;
GtkAdjustment *hadjustment;
GtkAdjustment *vadjustment;
#if GTK_CHECK_VERSION (3, 0, 0)
guint hscroll_policy : 1;
guint vscroll_policy : 1;
#endif
gint layout_idle_id;
gboolean doing_rubberband;
gint rubberband_x1, rubberband_y1;
gint rubberband_x2, rubberband_y2;
#if GTK_CHECK_VERSION (3, 0, 0)
GdkRGBA rubberband_border_color;
GdkRGBA rubberband_fill_color;
#else
GdkColor *rubberband_border_color;
GdkColor *rubberband_fill_color;
#endif
gint scroll_timeout_id;
gint scroll_value_diff;
gint event_last_x, event_last_y;
ExoIconViewItem *anchor_item;
ExoIconViewItem *cursor_item;
ExoIconViewItem *edited_item;
GtkCellEditable *editable;
ExoIconViewItem *prelit_item;
ExoIconViewItem *last_single_clicked;
GList *cell_list;
guint n_cells;
gint cursor_cell;
GtkOrientation orientation;
gint columns;
gint item_width;
gint spacing;
gint row_spacing;
gint column_spacing;
gint margin;
gint text_column;
gint markup_column;
gint pixbuf_column;
gint pixbuf_cell;
gint text_cell;
/* Drag-and-drop. */
GdkModifierType start_button_mask;
gint pressed_button;
gint press_start_x;
gint press_start_y;
GtkTargetList *source_targets;
GdkDragAction source_actions;
GtkTargetList *dest_targets;
GdkDragAction dest_actions;
GtkTreeRowReference *dest_item;
ExoIconViewDropPosition dest_pos;
/* delayed scrolling */
GtkTreeRowReference *scroll_to_path;
gfloat scroll_to_row_align;
gfloat scroll_to_col_align;
guint scroll_to_use_align : 1;
/* misc flags */
guint source_set : 1;
guint dest_set : 1;
guint reorderable : 1;
guint empty_view_drop :1;
guint ctrl_pressed : 1;
guint shift_pressed : 1;
/* Single-click support
* The single_click_timeout is the timeout after which the
* prelited item will be automatically selected in single
* click mode (0 to disable).
*/
guint single_click : 1;
guint single_click_timeout;
guint single_click_timeout_id;
guint single_click_timeout_state;
/* Interactive search support */
guint enable_search : 1;
guint search_imcontext_changed : 1;
gint search_column;
gint search_selected_iter;
gint search_timeout_id;
gboolean search_disable_popdown;
ExoIconViewSearchEqualFunc search_equal_func;
gpointer search_equal_data;
GDestroyNotify search_equal_destroy;
ExoIconViewSearchPositionFunc search_position_func;
gpointer search_position_data;
GDestroyNotify search_position_destroy;
gint search_entry_changed_id;
GtkWidget *search_entry;
GtkWidget *search_window;
/* ExoIconViewFlags */
guint flags;
};
static GObjectClass *exo_icon_view_parent_class;
static guint icon_view_signals[LAST_SIGNAL];
GType
exo_icon_view_get_type (void)
{
static GType type = G_TYPE_INVALID;
if (G_UNLIKELY (type == G_TYPE_INVALID))
{
type = _exo_g_type_register_simple (GTK_TYPE_CONTAINER,
"ExoIconView",
sizeof (ExoIconViewClass),
exo_icon_view_class_init,
sizeof (ExoIconView),
exo_icon_view_init);
_exo_g_type_add_interface_simple (type, GTK_TYPE_CELL_LAYOUT, (GInterfaceInitFunc) exo_icon_view_cell_layout_init);
#if GTK_CHECK_VERSION (3, 0, 0)
_exo_g_type_add_interface_simple (type, GTK_TYPE_SCROLLABLE, NULL);
#endif
}
return type;
}
#if GTK_CHECK_VERSION (3, 0, 0)
static void
exo_icon_view_get_preferred_width (GtkWidget *widget,
gint *minimal_width,
gint *natural_width)
{
GtkRequisition requisition;
exo_icon_view_size_request (widget, &requisition);
*minimal_width = *natural_width = requisition.width;
}
static void
exo_icon_view_get_preferred_height (GtkWidget *widget,
gint *minimal_height,
gint *natural_height)
{
GtkRequisition requisition;
exo_icon_view_size_request (widget, &requisition);
*minimal_height = *natural_height = requisition.height;
}
#endif
static void
exo_icon_view_class_init (ExoIconViewClass *klass)
{
GtkContainerClass *gtkcontainer_class;
GtkWidgetClass *gtkwidget_class;
GtkBindingSet *gtkbinding_set;
GObjectClass *gobject_class;
/* determine the parent type class */
exo_icon_view_parent_class = g_type_class_peek_parent (klass);
/* add our private data to the type's instances */
g_type_class_add_private (klass, sizeof (ExoIconViewPrivate));
gobject_class = G_OBJECT_CLASS (klass);
gobject_class->dispose = exo_icon_view_dispose;
gobject_class->finalize = exo_icon_view_finalize;
gobject_class->set_property = exo_icon_view_set_property;
gobject_class->get_property = exo_icon_view_get_property;
gtkwidget_class = GTK_WIDGET_CLASS (klass);
gtkwidget_class->realize = exo_icon_view_realize;
gtkwidget_class->unrealize = exo_icon_view_unrealize;
gtkwidget_class->size_allocate = exo_icon_view_size_allocate;
gtkwidget_class->style_set = exo_icon_view_style_set;
#if GTK_CHECK_VERSION (3, 0, 0)
gtkwidget_class->draw = exo_icon_view_draw;
gtkwidget_class->get_preferred_width = exo_icon_view_get_preferred_width;
gtkwidget_class->get_preferred_height = exo_icon_view_get_preferred_height;
#else
gtkwidget_class->size_request = exo_icon_view_size_request;
gtkwidget_class->expose_event = exo_icon_view_expose_event;
#endif
gtkwidget_class->motion_notify_event = exo_icon_view_motion_notify_event;
gtkwidget_class->button_press_event = exo_icon_view_button_press_event;
gtkwidget_class->button_release_event = exo_icon_view_button_release_event;
gtkwidget_class->scroll_event = exo_icon_view_scroll_event;
gtkwidget_class->key_press_event = exo_icon_view_key_press_event;
gtkwidget_class->focus_out_event = exo_icon_view_focus_out_event;
gtkwidget_class->leave_notify_event = exo_icon_view_leave_notify_event;
gtkwidget_class->drag_begin = exo_icon_view_drag_begin;
gtkwidget_class->drag_end = exo_icon_view_drag_end;
gtkwidget_class->drag_data_get = exo_icon_view_drag_data_get;
gtkwidget_class->drag_data_delete = exo_icon_view_drag_data_delete;
gtkwidget_class->drag_leave = exo_icon_view_drag_leave;
gtkwidget_class->drag_motion = exo_icon_view_drag_motion;
gtkwidget_class->drag_drop = exo_icon_view_drag_drop;
gtkwidget_class->drag_data_received = exo_icon_view_drag_data_received;
gtkcontainer_class = GTK_CONTAINER_CLASS (klass);
gtkcontainer_class->remove = exo_icon_view_remove;
gtkcontainer_class->forall = exo_icon_view_forall;
#if !GTK_CHECK_VERSION (3, 0, 0)
klass->set_scroll_adjustments = exo_icon_view_set_adjustments;
#endif
klass->select_all = exo_icon_view_real_select_all;
klass->unselect_all = exo_icon_view_real_unselect_all;
klass->select_cursor_item = exo_icon_view_real_select_cursor_item;
klass->toggle_cursor_item = exo_icon_view_real_toggle_cursor_item;
klass->move_cursor = exo_icon_view_real_move_cursor;
klass->activate_cursor_item = exo_icon_view_real_activate_cursor_item;
klass->start_interactive_search = exo_icon_view_real_start_interactive_search;
/**
* ExoIconView:column-spacing:
*
* The column-spacing property specifies the space which is inserted between
* the columns of the icon view.
*
* Since: 0.3.1
**/
g_object_class_install_property (gobject_class,
PROP_COLUMN_SPACING,
g_param_spec_int ("column-spacing",
_("Column Spacing"),
_("Space which is inserted between grid column"),
0, G_MAXINT, 6,
EXO_PARAM_READWRITE));
/**
* ExoIconView:columns:
*
* The columns property contains the number of the columns in which the
* items should be displayed. If it is -1, the number of columns will
* be chosen automatically to fill the available area.
*
* Since: 0.3.1
**/
g_object_class_install_property (gobject_class,
PROP_COLUMNS,
g_param_spec_int ("columns",
_("Number of columns"),
_("Number of columns to display"),
-1, G_MAXINT, -1,
EXO_PARAM_READWRITE));
/**
* ExoIconView:enable-search:
*
* View allows user to search through columns interactively.
*
* Since: 0.3.1.3
**/
g_object_class_install_property (gobject_class,
PROP_ENABLE_SEARCH,
g_param_spec_boolean ("enable-search",
_("Enable Search"),
_("View allows user to search through columns interactively"),
TRUE,
EXO_PARAM_READWRITE));
/**
* ExoIconView:item-width:
*
* The item-width property specifies the width to use for each item.
* If it is set to -1, the icon view will automatically determine a
* suitable item size.
*
* Since: 0.3.1
**/
g_object_class_install_property (gobject_class,
PROP_ITEM_WIDTH,
g_param_spec_int ("item-width",
_("Width for each item"),
_("The width used for each item"),
-1, G_MAXINT, -1,
EXO_PARAM_READWRITE));
/**
* ExoIconView:layout-mode:
*
* The layout-mode property specifies the way items are layed out in
* the #ExoIconView. This can be either %EXO_ICON_VIEW_LAYOUT_ROWS,
* which is the default, where items are layed out horizontally in
* rows from top to bottom, or %EXO_ICON_VIEW_LAYOUT_COLS, where items
* are layed out vertically in columns from left to right.
*
* Since: 0.3.1.5
**/
g_object_class_install_property (gobject_class,
PROP_LAYOUT_MODE,
g_param_spec_enum ("layout-mode",
_("Layout mode"),
_("The layout mode"),
EXO_TYPE_ICON_VIEW_LAYOUT_MODE,
EXO_ICON_VIEW_LAYOUT_ROWS,
EXO_PARAM_READWRITE));
/**
* ExoIconView:margin:
*
* The margin property specifies the space which is inserted
* at the edges of the icon view.
*
* Since: 0.3.1
**/
g_object_class_install_property (gobject_class,
PROP_MARGIN,
g_param_spec_int ("margin",
_("Margin"),
_("Space which is inserted at the edges of the icon view"),
0, G_MAXINT, 6,
EXO_PARAM_READWRITE));
/**
* ExoIconView:markup-column:
*
* The markup-column property contains the number of the model column
* containing markup information to be displayed. The markup column must be
* of type #G_TYPE_STRING. If this property and the text-column property
* are both set to column numbers, it overrides the text column.
* If both are set to -1, no texts are displayed.
**/
g_object_class_install_property (gobject_class,
PROP_MARKUP_COLUMN,
g_param_spec_int ("markup-column",
_("Markup column"),
_("Model column used to retrieve the text if using Pango markup"),
-1, G_MAXINT, -1,
EXO_PARAM_READWRITE));
/**
* ExoIconView:model:
*
* The model property contains the #GtkTreeModel, which should be
* display by this icon view. Setting this property to %NULL turns
* off the display of anything.
**/
g_object_class_install_property (gobject_class,
PROP_MODEL,
g_param_spec_object ("model",
_("Icon View Model"),
_("The model for the icon view"),
GTK_TYPE_TREE_MODEL,
EXO_PARAM_READWRITE));
/**
* ExoIconView:orientation:
*
* The orientation property specifies how the cells (i.e. the icon and
* the text) of the item are positioned relative to each other.
**/
g_object_class_install_property (gobject_class,
PROP_ORIENTATION,
g_param_spec_enum ("orientation",
_("Orientation"),
_("How the text and icon of each item are positioned relative to each other"),
GTK_TYPE_ORIENTATION,
GTK_ORIENTATION_VERTICAL,
EXO_PARAM_READWRITE));
/**
* ExoIconView:pixbuf-column:
*
* The ::pixbuf-column property contains the number of the model column
* containing the pixbufs which are displayed. The pixbuf column must be
* of type #GDK_TYPE_PIXBUF. Setting this property to -1 turns off the
* display of pixbufs.
**/
g_object_class_install_property (gobject_class,
PROP_PIXBUF_COLUMN,
g_param_spec_int ("pixbuf-column",
_("Pixbuf column"),
_("Model column used to retrieve the icon pixbuf from"),
-1, G_MAXINT, -1,
EXO_PARAM_READWRITE));
/**
* ExoIconView:reorderable:
*
* The reorderable property specifies if the items can be reordered
* by Drag and Drop.
*
* Since: 0.3.1
**/
g_object_class_install_property (gobject_class,
PROP_REORDERABLE,
g_param_spec_boolean ("reorderable",
_("Reorderable"),
_("View is reorderable"),
FALSE,
EXO_PARAM_READWRITE));
/**
* ExoIconView:row-spacing:
*
* The row-spacing property specifies the space which is inserted between
* the rows of the icon view.
*
* Since: 0.3.1
**/
g_object_class_install_property (gobject_class,
PROP_ROW_SPACING,
g_param_spec_int ("row-spacing",
_("Row Spacing"),
_("Space which is inserted between grid rows"),
0, G_MAXINT, 6,
EXO_PARAM_READWRITE));
/**
* ExoIconView:search-column:
*
* Model column to search through when searching through code.
*
* Since: 0.3.1.3
**/
g_object_class_install_property (gobject_class,
PROP_SEARCH_COLUMN,
g_param_spec_int ("search-column",
_("Search Column"),
_("Model column to search through when searching through item"),
-1, G_MAXINT, -1,
EXO_PARAM_READWRITE));
/**
* ExoIconView:selection-mode:
*
* The selection-mode property specifies the selection mode of
* icon view. If the mode is #GTK_SELECTION_MULTIPLE, rubberband selection
* is enabled, for the other modes, only keyboard selection is possible.
**/
g_object_class_install_property (gobject_class,
PROP_SELECTION_MODE,
g_param_spec_enum ("selection-mode",
_("Selection mode"),
_("The selection mode"),
GTK_TYPE_SELECTION_MODE,
GTK_SELECTION_SINGLE,
EXO_PARAM_READWRITE));
/**
* ExoIconView:single-click:
*
* Determines whether items can be activated by single or double clicks.
*
* Since: 0.3.1.3
**/
g_object_class_install_property (gobject_class,
PROP_SINGLE_CLICK,
g_param_spec_boolean ("single-click",
_("Single Click"),
_("Whether the items in the view can be activated with single clicks"),
FALSE,
EXO_PARAM_READWRITE));
/**
* ExoIconView:single-click-timeout:
*
* The amount of time in milliseconds after which a prelited item (an item
* which is hovered by the mouse cursor) will be selected automatically in
* single click mode. A value of %0 disables the automatic selection.
*
* Since: 0.3.1.5
**/
g_object_class_install_property (gobject_class,
PROP_SINGLE_CLICK_TIMEOUT,
g_param_spec_uint ("single-click-timeout",
_("Single Click Timeout"),
_("The amount of time after which the item under the mouse cursor will be selected automatically in single click mode"),
0, G_MAXUINT, 0,
EXO_PARAM_READWRITE));
/**
* ExoIconView:spacing:
*
* The spacing property specifies the space which is inserted between
* the cells (i.e. the icon and the text) of an item.
*
* Since: 0.3.1
**/
g_object_class_install_property (gobject_class,
PROP_SPACING,
g_param_spec_int ("spacing",
_("Spacing"),
_("Space which is inserted between cells of an item"),
0, G_MAXINT, 0,
EXO_PARAM_READWRITE));
/**
* ExoIconView:text-column:
*
* The text-column property contains the number of the model column
* containing the texts which are displayed. The text column must be
* of type #G_TYPE_STRING. If this property and the markup-column
* property are both set to -1, no texts are displayed.
**/
g_object_class_install_property (gobject_class,
PROP_TEXT_COLUMN,
g_param_spec_int ("text-column",
_("Text column"),
_("Model column used to retrieve the text from"),
-1, G_MAXINT, -1,
EXO_PARAM_READWRITE));
gtk_widget_class_install_style_property (gtkwidget_class,
g_param_spec_boxed ("selection-box-color",
_("Selection Box Color"),
_("Color of the selection box"),
GDK_TYPE_COLOR,
EXO_PARAM_READABLE));
gtk_widget_class_install_style_property (gtkwidget_class,
g_param_spec_uchar ("selection-box-alpha",
_("Selection Box Alpha"),
_("Opacity of the selection box"),
0, 0xff,
0x40,
EXO_PARAM_READABLE));
#if GTK_CHECK_VERSION (3, 0, 0)
g_object_class_override_property (gobject_class, PROP_HADJUSTMENT, "hadjustment");
g_object_class_override_property (gobject_class, PROP_VADJUSTMENT, "vadjustment");
g_object_class_override_property (gobject_class, PROP_HSCROLL_POLICY, "hscroll-policy");
g_object_class_override_property (gobject_class, PROP_VSCROLL_POLICY, "vscroll-policy");
#endif
/**
* ExoIconView::item-activated:
* @icon_view : a #ExoIconView.
* @path :
**/
icon_view_signals[ITEM_ACTIVATED] =
g_signal_new (I_("item-activated"),
G_TYPE_FROM_CLASS (gobject_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (ExoIconViewClass, item_activated),
NULL, NULL,
g_cclosure_marshal_VOID__BOXED,
G_TYPE_NONE, 1,
GTK_TYPE_TREE_PATH);
/**
* ExoIconView::selection-changed:
* @icon_view : a #ExoIconView.
**/
icon_view_signals[SELECTION_CHANGED] =
g_signal_new (I_("selection-changed"),
G_TYPE_FROM_CLASS (gobject_class),
G_SIGNAL_RUN_FIRST,
G_STRUCT_OFFSET (ExoIconViewClass, selection_changed),
NULL, NULL,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
#if !GTK_CHECK_VERSION (3, 0, 0)
/**
* ExoIconView::set-scroll-adjustments:
* @icon_view : a #ExoIconView.
* @hadjustment :
* @vadjustment :
**/
gtkwidget_class->set_scroll_adjustments_signal =
g_signal_new (I_("set-scroll-adjustments"),
G_TYPE_FROM_CLASS (gobject_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (ExoIconViewClass, set_scroll_adjustments),
NULL, NULL,
_exo_marshal_VOID__OBJECT_OBJECT,
G_TYPE_NONE, 2,
GTK_TYPE_ADJUSTMENT, GTK_TYPE_ADJUSTMENT);
#endif
/**
* ExoIconView::select-all:
* @icon_view : a #ExoIconView.
**/
icon_view_signals[SELECT_ALL] =
g_signal_new (I_("select-all"),
G_TYPE_FROM_CLASS (gobject_class),
G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
G_STRUCT_OFFSET (ExoIconViewClass, select_all),
NULL, NULL,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
/**
* ExoIconView::unselect-all:
* @icon_view : a #ExoIconView.
**/
icon_view_signals[UNSELECT_ALL] =
g_signal_new (I_("unselect-all"),
G_TYPE_FROM_CLASS (gobject_class),
G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
G_STRUCT_OFFSET (ExoIconViewClass, unselect_all),
NULL, NULL,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
/**
* ExoIconView::select-cursor-item:
* @icon_view : a #ExoIconView.
**/
icon_view_signals[SELECT_CURSOR_ITEM] =
g_signal_new (I_("select-cursor-item"),
G_TYPE_FROM_CLASS (gobject_class),
G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
G_STRUCT_OFFSET (ExoIconViewClass, select_cursor_item),
NULL, NULL,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
/**
* ExoIconView::toggle-cursor-item:
* @icon_view : a #ExoIconView.
**/
icon_view_signals[TOGGLE_CURSOR_ITEM] =
g_signal_new (I_("toggle-cursor-item"),
G_TYPE_FROM_CLASS (gobject_class),
G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
G_STRUCT_OFFSET (ExoIconViewClass, toggle_cursor_item),
NULL, NULL,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
/**
* ExoIconView::activate-cursor-item:
* @icon_view : a #ExoIconView.
*
* Return value:
**/
icon_view_signals[ACTIVATE_CURSOR_ITEM] =
g_signal_new (I_("activate-cursor-item"),
G_TYPE_FROM_CLASS (gobject_class),
G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
G_STRUCT_OFFSET (ExoIconViewClass, activate_cursor_item),
NULL, NULL,
_exo_marshal_BOOLEAN__VOID,
G_TYPE_BOOLEAN, 0);
/**
* ExoIconView::start-interactive-search:
* @iconb_view : a #ExoIconView.
*
* Return value:
**/
icon_view_signals[START_INTERACTIVE_SEARCH] =
g_signal_new (I_("start-interactive-search"),
G_TYPE_FROM_CLASS (gobject_class),
G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
G_STRUCT_OFFSET (ExoIconViewClass, start_interactive_search),
NULL, NULL,
_exo_marshal_BOOLEAN__VOID,
G_TYPE_BOOLEAN, 0);
/**
* ExoIconView::move-cursor:
* @icon_view : a #ExoIconView.
* @step :
* @count :
*
* Return value:
**/
icon_view_signals[MOVE_CURSOR] =
g_signal_new (I_("move-cursor"),
G_TYPE_FROM_CLASS (gobject_class),
G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
G_STRUCT_OFFSET (ExoIconViewClass, move_cursor),
NULL, NULL,
_exo_marshal_BOOLEAN__ENUM_INT,
G_TYPE_BOOLEAN, 2,
GTK_TYPE_MOVEMENT_STEP,
G_TYPE_INT);
/* Key bindings */
gtkbinding_set = gtk_binding_set_by_class (klass);
gtk_binding_entry_add_signal (gtkbinding_set, GDK_KEY_a, GDK_CONTROL_MASK, "select-all", 0);
gtk_binding_entry_add_signal (gtkbinding_set, GDK_KEY_a, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "unselect-all", 0);
gtk_binding_entry_add_signal (gtkbinding_set, GDK_KEY_space, GDK_CONTROL_MASK, "toggle-cursor-item", 0);
gtk_binding_entry_add_signal (gtkbinding_set, GDK_KEY_space, 0, "activate-cursor-item", 0);
gtk_binding_entry_add_signal (gtkbinding_set, GDK_KEY_Return, 0, "activate-cursor-item", 0);
gtk_binding_entry_add_signal (gtkbinding_set, GDK_KEY_ISO_Enter, 0, "activate-cursor-item", 0);
gtk_binding_entry_add_signal (gtkbinding_set, GDK_KEY_KP_Enter, 0, "activate-cursor-item", 0);
// gtk_binding_entry_add_signal (gtkbinding_set, GDK_f, GDK_CONTROL_MASK, "start-interactive-search", 0); //MOD stole ctrl-f for create new folder
gtk_binding_entry_add_signal (gtkbinding_set, GDK_KEY_F, GDK_CONTROL_MASK, "start-interactive-search", 0);
exo_icon_view_add_move_binding (gtkbinding_set, GDK_KEY_Up, 0, GTK_MOVEMENT_DISPLAY_LINES, -1);
exo_icon_view_add_move_binding (gtkbinding_set, GDK_KEY_KP_Up, 0, GTK_MOVEMENT_DISPLAY_LINES, -1);
exo_icon_view_add_move_binding (gtkbinding_set, GDK_KEY_Down, 0, GTK_MOVEMENT_DISPLAY_LINES, 1);
exo_icon_view_add_move_binding (gtkbinding_set, GDK_KEY_KP_Down, 0, GTK_MOVEMENT_DISPLAY_LINES, 1);
exo_icon_view_add_move_binding (gtkbinding_set, GDK_KEY_p, GDK_CONTROL_MASK, GTK_MOVEMENT_DISPLAY_LINES, -1);
exo_icon_view_add_move_binding (gtkbinding_set, GDK_KEY_n, GDK_CONTROL_MASK, GTK_MOVEMENT_DISPLAY_LINES, 1);
exo_icon_view_add_move_binding (gtkbinding_set, GDK_KEY_Home, 0, GTK_MOVEMENT_BUFFER_ENDS, -1);
exo_icon_view_add_move_binding (gtkbinding_set, GDK_KEY_KP_Home, 0, GTK_MOVEMENT_BUFFER_ENDS, -1);
exo_icon_view_add_move_binding (gtkbinding_set, GDK_KEY_End, 0, GTK_MOVEMENT_BUFFER_ENDS, 1);
exo_icon_view_add_move_binding (gtkbinding_set, GDK_KEY_KP_End, 0, GTK_MOVEMENT_BUFFER_ENDS, 1);
exo_icon_view_add_move_binding (gtkbinding_set, GDK_KEY_Page_Up, 0, GTK_MOVEMENT_PAGES, -1);
exo_icon_view_add_move_binding (gtkbinding_set, GDK_KEY_KP_Page_Up, 0, GTK_MOVEMENT_PAGES, -1);
exo_icon_view_add_move_binding (gtkbinding_set, GDK_KEY_Page_Down, 0, GTK_MOVEMENT_PAGES, 1);
exo_icon_view_add_move_binding (gtkbinding_set, GDK_KEY_KP_Page_Down, 0, GTK_MOVEMENT_PAGES, 1);
exo_icon_view_add_move_binding (gtkbinding_set, GDK_KEY_Right, 0, GTK_MOVEMENT_VISUAL_POSITIONS, 1);
exo_icon_view_add_move_binding (gtkbinding_set, GDK_KEY_Left, 0, GTK_MOVEMENT_VISUAL_POSITIONS, -1);
exo_icon_view_add_move_binding (gtkbinding_set, GDK_KEY_KP_Right, 0, GTK_MOVEMENT_VISUAL_POSITIONS, 1);
exo_icon_view_add_move_binding (gtkbinding_set, GDK_KEY_KP_Left, 0, GTK_MOVEMENT_VISUAL_POSITIONS, -1);
}
static void
exo_icon_view_cell_layout_init (GtkCellLayoutIface *iface)
{
iface->pack_start = exo_icon_view_cell_layout_pack_start;
iface->pack_end = exo_icon_view_cell_layout_pack_end;
iface->clear = exo_icon_view_cell_layout_clear;
iface->add_attribute = exo_icon_view_cell_layout_add_attribute;
iface->set_cell_data_func = exo_icon_view_cell_layout_set_cell_data_func;
iface->clear_attributes = exo_icon_view_cell_layout_clear_attributes;
iface->reorder = exo_icon_view_cell_layout_reorder;
}
static void
exo_icon_view_init (ExoIconView *icon_view)
{
icon_view->priv = EXO_ICON_VIEW_GET_PRIVATE (icon_view);
icon_view->priv->selection_mode = GTK_SELECTION_SINGLE;
icon_view->priv->pressed_button = -1;
icon_view->priv->press_start_x = -1;
icon_view->priv->press_start_y = -1;
icon_view->priv->text_column = -1;
icon_view->priv->markup_column = -1;
icon_view->priv->pixbuf_column = -1;
icon_view->priv->text_cell = -1;
icon_view->priv->pixbuf_cell = -1;
gtk_widget_set_can_focus (GTK_WIDGET(icon_view), TRUE);
#if !GTK_CHECK_VERSION (3, 0, 0)
exo_icon_view_set_adjustments (icon_view, NULL, NULL);
#endif
icon_view->priv->cursor_cell = -1;
icon_view->priv->orientation = GTK_ORIENTATION_VERTICAL;
icon_view->priv->columns = -1;
icon_view->priv->item_width = -1;
icon_view->priv->row_spacing = 3;
icon_view->priv->column_spacing = 3;
icon_view->priv->margin = 3;
icon_view->priv->enable_search = TRUE;
icon_view->priv->search_column = -1;
icon_view->priv->search_equal_func = exo_icon_view_search_equal_func;
icon_view->priv->search_position_func = exo_icon_view_search_position_func;
icon_view->priv->flags = EXO_ICON_VIEW_DRAW_KEYFOCUS;
}
static void
exo_icon_view_dispose (GObject *object)
{
ExoIconView *icon_view = EXO_ICON_VIEW (object);
/* cancel any pending search timeout */
if (G_UNLIKELY (icon_view->priv->search_timeout_id != 0))
g_source_remove (icon_view->priv->search_timeout_id);
/* destroy the interactive search dialog */
if (G_UNLIKELY (icon_view->priv->search_window != NULL))
{
gtk_widget_destroy (icon_view->priv->search_window);
icon_view->priv->search_entry = NULL;
icon_view->priv->search_window = NULL;
}
/* drop search equal and position functions (if any) */
exo_icon_view_set_search_equal_func (icon_view, NULL, NULL, NULL);
exo_icon_view_set_search_position_func (icon_view, NULL, NULL, NULL);
/* reset the drag dest item */
exo_icon_view_set_drag_dest_item (icon_view, NULL, EXO_ICON_VIEW_NO_DROP);
/* drop the scroll to path (if any) */
if (G_UNLIKELY (icon_view->priv->scroll_to_path != NULL))
{
gtk_tree_row_reference_free (icon_view->priv->scroll_to_path);
icon_view->priv->scroll_to_path = NULL;
}
/* reset the model (also stops any active editing) */
exo_icon_view_set_model (icon_view, NULL);
/* drop the scroll timer */
remove_scroll_timeout (icon_view);
(*G_OBJECT_CLASS (exo_icon_view_parent_class)->dispose) (object);
}
static void
exo_icon_view_finalize (GObject *object)
{
ExoIconView *icon_view = EXO_ICON_VIEW (object);
/* drop the scroll adjustments */
g_object_unref (G_OBJECT (icon_view->priv->hadjustment));
g_object_unref (G_OBJECT (icon_view->priv->vadjustment));
/* drop the cell renderers */
exo_icon_view_cell_layout_clear (GTK_CELL_LAYOUT (icon_view));
/* be sure to cancel the single click timeout */
if (G_UNLIKELY (icon_view->priv->single_click_timeout_id != 0))
g_source_remove (icon_view->priv->single_click_timeout_id);
/* kill the layout idle source (it's important to have this last!) */
if (G_UNLIKELY (icon_view->priv->layout_idle_id != 0))
g_source_remove (icon_view->priv->layout_idle_id);
(*G_OBJECT_CLASS (exo_icon_view_parent_class)->finalize) (object);
}
static void
exo_icon_view_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
const ExoIconViewPrivate *priv = EXO_ICON_VIEW (object)->priv;
switch (prop_id)
{
case PROP_COLUMN_SPACING:
g_value_set_int (value, priv->column_spacing);
break;
case PROP_COLUMNS:
g_value_set_int (value, priv->columns);
break;
case PROP_ENABLE_SEARCH:
g_value_set_boolean (value, priv->enable_search);
break;
case PROP_ITEM_WIDTH:
g_value_set_int (value, priv->item_width);
break;
case PROP_MARGIN:
g_value_set_int (value, priv->margin);
break;
case PROP_MARKUP_COLUMN:
g_value_set_int (value, priv->markup_column);
break;
case PROP_MODEL:
g_value_set_object (value, priv->model);
break;
case PROP_ORIENTATION:
g_value_set_enum (value, priv->orientation);
break;
case PROP_PIXBUF_COLUMN:
g_value_set_int (value, priv->pixbuf_column);
break;
case PROP_REORDERABLE:
g_value_set_boolean (value, priv->reorderable);
break;
case PROP_ROW_SPACING:
g_value_set_int (value, priv->row_spacing);
break;
case PROP_SEARCH_COLUMN:
g_value_set_int (value, priv->search_column);
break;
case PROP_SELECTION_MODE:
g_value_set_enum (value, priv->selection_mode);
break;
case PROP_SINGLE_CLICK:
g_value_set_boolean (value, priv->single_click);
break;
case PROP_SINGLE_CLICK_TIMEOUT:
g_value_set_uint (value, priv->single_click_timeout);
break;
case PROP_SPACING:
g_value_set_int (value, priv->spacing);
break;
case PROP_TEXT_COLUMN:
g_value_set_int (value, priv->text_column);
break;
case PROP_LAYOUT_MODE:
g_value_set_enum (value, priv->layout_mode);
break;
#if GTK_CHECK_VERSION (3, 0, 0)
case PROP_HADJUSTMENT:
g_value_set_object (value, priv->hadjustment);
break;
case PROP_VADJUSTMENT:
g_value_set_object (value, priv->vadjustment);
break;
case PROP_HSCROLL_POLICY:
g_value_set_enum (value, priv->hscroll_policy);
break;
case PROP_VSCROLL_POLICY:
g_value_set_enum (value, priv->vscroll_policy);
break;
#endif
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
exo_icon_view_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
ExoIconView *icon_view = EXO_ICON_VIEW (object);
switch (prop_id)
{
case PROP_COLUMN_SPACING:
exo_icon_view_set_column_spacing (icon_view, g_value_get_int (value));
break;
case PROP_COLUMNS:
exo_icon_view_set_columns (icon_view, g_value_get_int (value));
break;
case PROP_ENABLE_SEARCH:
exo_icon_view_set_enable_search (icon_view, g_value_get_boolean (value));
break;
case PROP_ITEM_WIDTH:
exo_icon_view_set_item_width (icon_view, g_value_get_int (value));
break;
case PROP_MARGIN:
exo_icon_view_set_margin (icon_view, g_value_get_int (value));
break;
case PROP_MARKUP_COLUMN:
exo_icon_view_set_markup_column (icon_view, g_value_get_int (value));
break;
case PROP_MODEL:
exo_icon_view_set_model (icon_view, g_value_get_object (value));
break;
case PROP_ORIENTATION:
exo_icon_view_set_orientation (icon_view, g_value_get_enum (value));
break;
case PROP_PIXBUF_COLUMN:
exo_icon_view_set_pixbuf_column (icon_view, g_value_get_int (value));
break;
case PROP_REORDERABLE:
exo_icon_view_set_reorderable (icon_view, g_value_get_boolean (value));
break;
case PROP_ROW_SPACING:
exo_icon_view_set_row_spacing (icon_view, g_value_get_int (value));
break;
case PROP_SEARCH_COLUMN:
exo_icon_view_set_search_column (icon_view, g_value_get_int (value));
break;
case PROP_SELECTION_MODE:
exo_icon_view_set_selection_mode (icon_view, g_value_get_enum (value));
break;
case PROP_SINGLE_CLICK:
exo_icon_view_set_single_click (icon_view, g_value_get_boolean (value));
break;
case PROP_SINGLE_CLICK_TIMEOUT:
exo_icon_view_set_single_click_timeout (icon_view, g_value_get_uint (value));
break;
case PROP_SPACING:
exo_icon_view_set_spacing (icon_view, g_value_get_int (value));
break;
case PROP_TEXT_COLUMN:
exo_icon_view_set_text_column (icon_view, g_value_get_int (value));
break;
case PROP_LAYOUT_MODE:
exo_icon_view_set_layout_mode (icon_view, g_value_get_enum (value));
break;
#if GTK_CHECK_VERSION (3, 0, 0)
case PROP_HADJUSTMENT:
exo_icon_view_set_hadjustment (icon_view, g_value_get_object (value));
break;
case PROP_VADJUSTMENT:
exo_icon_view_set_vadjustment (icon_view, g_value_get_object (value));
break;
case PROP_HSCROLL_POLICY:
icon_view->priv->hscroll_policy = g_value_get_enum (value);
gtk_widget_queue_resize (GTK_WIDGET (icon_view));
break;
case PROP_VSCROLL_POLICY:
icon_view->priv->vscroll_policy = g_value_get_enum (value);
gtk_widget_queue_resize (GTK_WIDGET (icon_view));
break;
#endif
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
exo_icon_view_realize (GtkWidget *widget)
{
ExoIconViewPrivate *priv = EXO_ICON_VIEW (widget)->priv;
GdkWindowAttr attributes;
GtkAllocation allocation;
gint attributes_mask;
gtk_widget_set_realized (widget, TRUE);
/* Allocate the clipping window */
attributes.window_type = GDK_WINDOW_CHILD;
gtk_widget_get_allocation (widget, &allocation);
attributes.x = allocation.x;
attributes.y = allocation.y;
attributes.width = allocation.width;
attributes.height = allocation.height;
attributes.wclass = GDK_INPUT_OUTPUT;
attributes.visual = gtk_widget_get_visual (widget);
attributes.event_mask = GDK_VISIBILITY_NOTIFY_MASK;
attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL;
#if !GTK_CHECK_VERSION (3, 0, 0)
attributes_mask |= GDK_WA_COLORMAP;
attributes.colormap = gtk_widget_get_colormap (widget);
#endif
gtk_widget_set_window (widget, gdk_window_new (gtk_widget_get_parent_window (widget), &attributes, attributes_mask));
gdk_window_set_user_data (gtk_widget_get_window(widget), widget);
/* Allocate the icons window */
attributes.x = 0;
attributes.y = 0;
attributes.width = MAX (priv->width, allocation.width);
attributes.height = MAX (priv->height, allocation.height);
attributes.event_mask = GDK_EXPOSURE_MASK
| GDK_SCROLL_MASK
| GDK_POINTER_MOTION_MASK
| GDK_BUTTON_PRESS_MASK
| GDK_BUTTON_RELEASE_MASK
| GDK_KEY_PRESS_MASK
| GDK_KEY_RELEASE_MASK
| gtk_widget_get_events (widget);
priv->bin_window = gdk_window_new (gtk_widget_get_window(widget), &attributes, attributes_mask);
gdk_window_set_user_data (priv->bin_window, widget);
/* Attach style/background */
gtk_widget_set_style (widget, gtk_style_attach (gtk_widget_get_style (widget), gtk_widget_get_window(widget)));
gdk_window_set_background (priv->bin_window, >k_widget_get_style (widget)->base[gtk_widget_get_state (widget)]);
gdk_window_set_background (gtk_widget_get_window (widget), >k_widget_get_style (widget)->base[gtk_widget_get_state (widget)]);
/* map the icons window */
gdk_window_show (priv->bin_window);
}
static void
exo_icon_view_unrealize (GtkWidget *widget)
{
ExoIconViewPrivate *priv = EXO_ICON_VIEW (widget)->priv;
/* drop the icons window */
gdk_window_set_user_data (priv->bin_window, NULL);
gdk_window_destroy (priv->bin_window);
priv->bin_window = NULL;
/* let GtkWidget destroy children and widget->window */
if (GTK_WIDGET_CLASS (exo_icon_view_parent_class)->unrealize)
(*GTK_WIDGET_CLASS (exo_icon_view_parent_class)->unrealize) (widget);
}
static void
exo_icon_view_size_request (GtkWidget *widget,
GtkRequisition *requisition)
{
const ExoIconViewPrivate *priv = EXO_ICON_VIEW (widget)->priv;
ExoIconViewChild *child;
GtkRequisition child_requisition;
GList *lp;
/* well, this is easy */
requisition->width = priv->width;
requisition->height = priv->height;
/* handle the child widgets */
for (lp = priv->children; lp != NULL; lp = lp->next)
{
child = lp->data;
if (gtk_widget_get_visible (child->widget))
gtk_widget_size_request (child->widget, &child_requisition);
}
}
static void
exo_icon_view_allocate_children (ExoIconView *icon_view)
{
const ExoIconViewPrivate *priv = icon_view->priv;
const ExoIconViewChild *child;
GtkAllocation allocation;
const GList *lp;
gint focus_line_width;
gint focus_padding;
for (lp = priv->children; lp != NULL; lp = lp->next)
{
child = EXO_ICON_VIEW_CHILD (lp->data);
/* totally ignore our child's requisition */
if (child->cell < 0)
allocation = child->item->area;
else
allocation = child->item->box[child->cell];
/* increase the item area by focus width/padding */
gtk_widget_style_get (GTK_WIDGET (icon_view), "focus-line-width", &focus_line_width, "focus-padding", &focus_padding, NULL);
allocation.x = MAX (0, allocation.x - (focus_line_width + focus_padding));
allocation.y = MAX (0, allocation.y - (focus_line_width + focus_padding));
allocation.width = MIN (priv->width - allocation.x, allocation.width + 2 * (focus_line_width + focus_padding));
allocation.height = MIN (priv->height - allocation.y, allocation.height + 2 * (focus_line_width + focus_padding));
/* allocate the area to the child */
gtk_widget_size_allocate (child->widget, &allocation);
}
}
static void
exo_icon_view_size_allocate (GtkWidget *widget,
GtkAllocation *allocation)
{
GtkAdjustment *hadjustment;
GtkAdjustment *vadjustment;
ExoIconView *icon_view = EXO_ICON_VIEW (widget);
/* apply the new size allocation */
gtk_widget_set_allocation (widget, allocation);
/* move/resize the clipping window, the icons window
* will be handled by exo_icon_view_layout().
*/
if (gtk_widget_get_realized (widget))
gdk_window_move_resize (gtk_widget_get_window (widget), MAX(0, allocation->x), MAX(0, allocation->y), allocation->width, allocation->height);
/* layout the items */
exo_icon_view_layout (icon_view);
/* allocate space to the widgets (editing) */
exo_icon_view_allocate_children (icon_view);
/* update the horizontal scroll adjustment accordingly */
hadjustment = icon_view->priv->hadjustment;
gtk_adjustment_set_page_size (hadjustment, allocation->width);
gtk_adjustment_set_page_increment (hadjustment, allocation->width * 0.9);
gtk_adjustment_set_step_increment (hadjustment, allocation->width * 0.1);
gtk_adjustment_set_lower (hadjustment, 0);
gtk_adjustment_set_upper (hadjustment, MAX (allocation->width, icon_view->priv->width));
if (gtk_adjustment_get_value (hadjustment) > gtk_adjustment_get_upper(hadjustment) - gtk_adjustment_get_page_size(hadjustment))
gtk_adjustment_set_value (hadjustment, MAX (0, gtk_adjustment_get_upper(hadjustment) - gtk_adjustment_get_page_size(hadjustment)));
/* update the vertical scroll adjustment accordingly */
vadjustment = icon_view->priv->vadjustment;
gtk_adjustment_set_page_size (vadjustment, allocation->height);
gtk_adjustment_set_page_increment (vadjustment, allocation->height * 0.9);
gtk_adjustment_set_step_increment (vadjustment, allocation->height * 0.1);
gtk_adjustment_set_lower (vadjustment, 0);
gtk_adjustment_set_upper (vadjustment, MAX (allocation->height, icon_view->priv->height));
if (gtk_adjustment_get_value (vadjustment) > gtk_adjustment_get_upper(vadjustment) - gtk_adjustment_get_page_size(vadjustment))
gtk_adjustment_set_value (vadjustment, MAX (0, gtk_adjustment_get_upper(vadjustment) - gtk_adjustment_get_page_size(vadjustment)));
/* we need to emit "changed" ourselves */
gtk_adjustment_changed (hadjustment);
gtk_adjustment_changed (vadjustment);
}
static void
exo_icon_view_style_set (GtkWidget *widget,
GtkStyle *previous_style)
{
ExoIconView *icon_view = EXO_ICON_VIEW (widget);
/* let GtkWidget do its work */
(*GTK_WIDGET_CLASS (exo_icon_view_parent_class)->style_set) (widget, previous_style);
/* apply the new style for the bin_window if we're realized */
if (gtk_widget_get_realized (widget))
gdk_window_set_background (icon_view->priv->bin_window, >k_widget_get_style(widget)->base[gtk_widget_get_state(widget)]);
}
#if GTK_CHECK_VERSION (3, 0, 0)
static gboolean
exo_icon_view_draw (GtkWidget *widget,
cairo_t *cr)
#else
static gboolean
exo_icon_view_expose_event (GtkWidget *widget,
GdkEventExpose *event)
#endif
{
ExoIconViewDropPosition dest_pos;
ExoIconViewPrivate *priv = EXO_ICON_VIEW (widget)->priv;
ExoIconViewItem *dest_item = NULL;
ExoIconViewItem *item;
#if GTK_CHECK_VERSION (3, 0, 0)
GtkAllocation event_area;
#else
GdkRectangle event_area = event->area;
#endif
ExoIconView *icon_view = EXO_ICON_VIEW (widget);
GtkTreePath *path;
GdkRectangle rubber_rect;
const GList *lp;
gint event_area_last;
gint dest_index = -1;
/* verify that the expose happened on the icon window */
#if GTK_CHECK_VERSION (3, 0, 0)
if (!G_UNLIKELY (gtk_cairo_should_draw_window (cr, priv->bin_window)))
return FALSE;
#else
if (G_UNLIKELY (event->window != priv->bin_window))
return FALSE;
#endif
/* don't handle expose if the layout isn't done yet; the layout
* method will schedule a redraw when done.
*/
if (G_UNLIKELY (priv->layout_idle_id != 0))
return FALSE;
#if !GTK_CHECK_VERSION (3, 0, 0)
cairo_t *cr;
cr = gdk_cairo_create (priv->bin_window);
cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
#else
gtk_cairo_transform_to_window (cr, widget, priv->bin_window);
#endif
cairo_set_line_width (cr, 1);
/* scroll to the previously remembered path (if any) */
if (G_UNLIKELY (priv->scroll_to_path != NULL))
{
/* grab the path from the reference and invalidate the reference */
path = gtk_tree_row_reference_get_path (priv->scroll_to_path);
gtk_tree_row_reference_free (priv->scroll_to_path);
priv->scroll_to_path = NULL;
/* check if the reference was still valid */
if (G_LIKELY (path != NULL))
{
/* try to scroll again */
exo_icon_view_scroll_to_path (icon_view, path,
priv->scroll_to_use_align,
priv->scroll_to_row_align,
priv->scroll_to_col_align);
/* release the path */
gtk_tree_path_free (path);
}
}
/* check if we need to draw a drag indicator */
exo_icon_view_get_drag_dest_item (icon_view, &path, &dest_pos);
if (G_UNLIKELY (path != NULL))
{
dest_index = gtk_tree_path_get_indices (path)[0];
gtk_tree_path_free (path);
}
/* paint the rubberband background */
if (G_UNLIKELY (priv->doing_rubberband))
{
/* calculate the rubberband area */
rubber_rect.x = MIN (priv->rubberband_x1, priv->rubberband_x2);
rubber_rect.y = MIN (priv->rubberband_y1, priv->rubberband_y2);
rubber_rect.width = ABS (priv->rubberband_x1 - priv->rubberband_x2) + 1;
rubber_rect.height = ABS (priv->rubberband_y1 - priv->rubberband_y2) + 1;
/* we take advantage of double-buffering here and use only a single
* draw_rectangle() operation w/o having to take care of clipping.
*/
#if GTK_CHECK_VERSION (3, 0, 0)
gdk_cairo_set_source_rgba (cr, &priv->rubberband_fill_color);
#else
gdk_cairo_set_source_color (cr, priv->rubberband_fill_color);
#endif
cairo_rectangle (cr, rubber_rect.x + 0.5, rubber_rect.y + 0.5, rubber_rect.width - 1, rubber_rect.height - 1);
cairo_fill (cr);
}
cairo_set_operator (cr, CAIRO_OPERATOR_OVER);
/* determine the last interesting coordinate (depending on the layout mode) */
#if GTK_CHECK_VERSION (3, 0, 0)
gtk_widget_get_allocation (widget, &event_area);
gdk_window_get_position (priv->bin_window, &event_area.x, &event_area.y);
event_area.x = -event_area.x;
event_area.y = -event_area.y;
#endif
event_area_last = (priv->layout_mode == EXO_ICON_VIEW_LAYOUT_ROWS)
? event_area.y + event_area.height
: event_area.x + event_area.width;
/* paint all items that are affected by the expose event */
for (lp = priv->items; lp != NULL; lp = lp->next)
{
/* check if this item is in the visible area */
item = EXO_ICON_VIEW_ITEM (lp->data);
if (G_LIKELY (priv->layout_mode == EXO_ICON_VIEW_LAYOUT_ROWS))
{
if (item->area.y > event_area_last)
break;
else if (item->area.y + item->area.height < event_area.y)
continue;
}
else
{
if (item->area.x > event_area_last)
break;
else if (item->area.x + item->area.width < event_area.x)
continue;
}
/* check if this item needs an update */
#if GTK_CHECK_VERSION (3, 0, 0)
if (G_LIKELY (gdk_rectangle_intersect(&event_area, &item->area, NULL)))
{
exo_icon_view_paint_item (icon_view, item, &event_area, cr, item->area.x, item->area.y, TRUE);
#else
if (G_LIKELY (gdk_region_rect_in (event->region, &item->area) != GDK_OVERLAP_RECTANGLE_OUT))
{
exo_icon_view_paint_item (icon_view, item, &event_area, event->window, item->area.x, item->area.y, TRUE);
#endif
if (G_UNLIKELY (dest_index >= 0 && dest_item == NULL && dest_index == g_list_index (priv->items, item)))
dest_item = item;
}
}
/* draw the drag indicator */
if (G_UNLIKELY (dest_item != NULL))
{
switch (dest_pos)
{
case EXO_ICON_VIEW_DROP_INTO:
#if GTK_CHECK_VERSION (3, 0, 0)
gtk_paint_focus (gtk_widget_get_style(widget), cr,
gtk_widget_get_state (widget), widget,
#else
gtk_paint_focus (gtk_widget_get_style(widget), priv->bin_window,
gtk_widget_get_state (widget), NULL, widget,
#endif
"iconview-drop-indicator",
dest_item->area.x, dest_item->area.y,
dest_item->area.width, dest_item->area.height);
break;
case EXO_ICON_VIEW_DROP_ABOVE:
#if GTK_CHECK_VERSION (3, 0, 0)
gtk_paint_focus (gtk_widget_get_style(widget), cr,
gtk_widget_get_state (widget), widget,
#else
gtk_paint_focus (gtk_widget_get_style(widget), priv->bin_window,
gtk_widget_get_state (widget), NULL, widget,
#endif
"iconview-drop-indicator",
dest_item->area.x, dest_item->area.y - 1,
dest_item->area.width, 2);
break;
case EXO_ICON_VIEW_DROP_LEFT:
#if GTK_CHECK_VERSION (3, 0, 0)
gtk_paint_focus (gtk_widget_get_style(widget), cr,
gtk_widget_get_state (widget), widget,
#else
gtk_paint_focus (gtk_widget_get_style(widget), priv->bin_window,
gtk_widget_get_state (widget), NULL, widget,
#endif
"iconview-drop-indicator",
dest_item->area.x - 1, dest_item->area.y,
2, dest_item->area.height);
break;
case EXO_ICON_VIEW_DROP_BELOW:
#if GTK_CHECK_VERSION (3, 0, 0)
gtk_paint_focus (gtk_widget_get_style(widget), cr,
gtk_widget_get_state (widget), widget,
#else
gtk_paint_focus (gtk_widget_get_style(widget), priv->bin_window,
gtk_widget_get_state (widget), NULL, widget,
#endif
"iconview-drop-indicator",
dest_item->area.x, dest_item->area.y + dest_item->area.height - 1,
dest_item->area.width, 2);
break;
case EXO_ICON_VIEW_DROP_RIGHT:
#if GTK_CHECK_VERSION (3, 0, 0)
gtk_paint_focus (gtk_widget_get_style(widget), cr,
gtk_widget_get_state (widget), widget,
#else
gtk_paint_focus (gtk_widget_get_style(widget), priv->bin_window,
gtk_widget_get_state (widget), NULL, widget,
#endif
"iconview-drop-indicator",
dest_item->area.x + dest_item->area.width - 1, dest_item->area.y,
2, dest_item->area.height);
case EXO_ICON_VIEW_NO_DROP:
break;
default:
g_assert_not_reached ();
}
}
/* draw the rubberband border */
if (G_UNLIKELY (priv->doing_rubberband))
{
/* draw the border */
#if GTK_CHECK_VERSION (3, 0, 0)
gdk_cairo_set_source_rgba (cr, &priv->rubberband_border_color);
#else
gdk_cairo_set_source_color (cr, priv->rubberband_border_color);
#endif
cairo_set_line_width (cr, 1);
cairo_rectangle (cr, rubber_rect.x + 0.5, rubber_rect.y + 0.5, rubber_rect.width - 1, rubber_rect.height - 1);
cairo_stroke (cr);
}
#if !GTK_CHECK_VERSION (3, 0, 0)
cairo_destroy (cr);
/* let the GtkContainer forward the expose event to all children */
(*GTK_WIDGET_CLASS (exo_icon_view_parent_class)->expose_event) (widget, event);
#endif
return FALSE;
}
static gboolean
rubberband_scroll_timeout (gpointer user_data)
{
GtkAdjustment *adjustment;
ExoIconView *icon_view = EXO_ICON_VIEW (user_data);
gdouble value;
GDK_THREADS_ENTER ();
/* determine the adjustment for the scroll direction */
adjustment = (icon_view->priv->layout_mode == EXO_ICON_VIEW_LAYOUT_ROWS)
? icon_view->priv->vadjustment
: icon_view->priv->hadjustment;
/* determine the new scroll value */
value = MIN (gtk_adjustment_get_value (adjustment) + icon_view->priv->scroll_value_diff, gtk_adjustment_get_upper (adjustment) - gtk_adjustment_get_page_size (adjustment) );
/* apply the new value */
gtk_adjustment_set_value (adjustment, value);
/* update the rubberband */
exo_icon_view_update_rubberband (icon_view);
GDK_THREADS_LEAVE ();
return TRUE;
}
static gboolean
exo_icon_view_motion_notify_event (GtkWidget *widget,
GdkEventMotion *event)
{
ExoIconViewItem *item;
GtkAllocation allocation;
ExoIconView *icon_view = EXO_ICON_VIEW (widget);
GdkCursor *cursor;
gint size;
gint abs;
exo_icon_view_maybe_begin_drag (icon_view, event);
gtk_widget_get_allocation (widget, &allocation);
if (icon_view->priv->doing_rubberband)
{
exo_icon_view_update_rubberband (widget);
if (icon_view->priv->layout_mode == EXO_ICON_VIEW_LAYOUT_ROWS)
{
abs = event->y - icon_view->priv->height *
(gtk_adjustment_get_value (icon_view->priv->vadjustment) /
(gtk_adjustment_get_upper (icon_view->priv->vadjustment) -
gtk_adjustment_get_lower (icon_view->priv->vadjustment)));
size = allocation.height;
}
else
{
abs = event->x - icon_view->priv->width *
(gtk_adjustment_get_value (icon_view->priv->hadjustment) /
(gtk_adjustment_get_upper (icon_view->priv->hadjustment) -
gtk_adjustment_get_lower (icon_view->priv->hadjustment)));
size = allocation.width;
}
if (abs < 0 || abs > size)
{
if (abs < 0)
icon_view->priv->scroll_value_diff = abs;
else
icon_view->priv->scroll_value_diff = abs - size;
icon_view->priv->event_last_x = event->x;
icon_view->priv->event_last_y = event->y;
if (icon_view->priv->scroll_timeout_id == 0)
icon_view->priv->scroll_timeout_id = g_timeout_add (30, rubberband_scroll_timeout,
icon_view);
}
else
{
remove_scroll_timeout (icon_view);
}
}
else
{
item = exo_icon_view_get_item_at_coords (icon_view, event->x, event->y, TRUE, NULL);
if (item != icon_view->priv->prelit_item)
{
if (G_LIKELY (icon_view->priv->prelit_item != NULL))
exo_icon_view_queue_draw_item (icon_view, icon_view->priv->prelit_item);
icon_view->priv->prelit_item = item;
if (G_LIKELY (item != NULL))
exo_icon_view_queue_draw_item (icon_view, item);
/* check if we are in single click mode right now */
if (G_UNLIKELY (icon_view->priv->single_click))
{
/* display a hand cursor when pointer is above an item */
if (G_LIKELY (item != NULL))
{
/* hand2 seems to be what we should use */
cursor = gdk_cursor_new (GDK_HAND2);
gdk_window_set_cursor (event->window, cursor);
gdk_cursor_unref (cursor);
}
else
{
/* reset the cursor */
gdk_window_set_cursor (event->window, NULL);
}
/* check if autoselection is enabled */
if (G_LIKELY (icon_view->priv->single_click_timeout > 0))
{
/* drop any running timeout */
if (G_LIKELY (icon_view->priv->single_click_timeout_id != 0))
g_source_remove (icon_view->priv->single_click_timeout_id);
/* remember the current event state */
icon_view->priv->single_click_timeout_state = event->state;
/* schedule a new timeout */
icon_view->priv->single_click_timeout_id = g_timeout_add_full (G_PRIORITY_LOW, icon_view->priv->single_click_timeout,
exo_icon_view_single_click_timeout, icon_view,
exo_icon_view_single_click_timeout_destroy);
}
}
}
}
return TRUE;
}
static void
exo_icon_view_remove (GtkContainer *container,
GtkWidget *widget)
{
ExoIconViewChild *child;
ExoIconView *icon_view = EXO_ICON_VIEW (container);
GList *lp;
for (lp = icon_view->priv->children; lp != NULL; lp = lp->next)
{
child = lp->data;
if (G_LIKELY (child->widget == widget))
{
icon_view->priv->children = g_list_delete_link (icon_view->priv->children, lp);
gtk_widget_unparent (widget);
_exo_slice_free (ExoIconViewChild, child);
return;
}
}
}
static void
exo_icon_view_forall (GtkContainer *container,
gboolean include_internals,
GtkCallback callback,
gpointer callback_data)
{
ExoIconView *icon_view = EXO_ICON_VIEW (container);
GList *lp;
for (lp = icon_view->priv->children; lp != NULL; lp = lp->next)
(*callback) (((ExoIconViewChild *) lp->data)->widget, callback_data);
}
static void
exo_icon_view_item_activate_cell (ExoIconView *icon_view,
ExoIconViewItem *item,
ExoIconViewCellInfo *info,
GdkEvent *event)
{
GtkCellRendererMode mode;
GdkRectangle cell_area;
GtkTreePath *path;
gboolean visible;
gchar *path_string;
exo_icon_view_set_cell_data (icon_view, item);
g_object_get (G_OBJECT (info->cell), "visible", &visible, "mode", &mode, NULL);
if (G_UNLIKELY (visible && mode == GTK_CELL_RENDERER_MODE_ACTIVATABLE))
{
exo_icon_view_get_cell_area (icon_view, item, info, &cell_area);
path = gtk_tree_path_new_from_indices (g_list_index (icon_view->priv->items, item), -1);
path_string = gtk_tree_path_to_string (path);
gtk_tree_path_free (path);
gtk_cell_renderer_activate (info->cell, event, GTK_WIDGET (icon_view), path_string, &cell_area, &cell_area, 0);
g_free (path_string);
}
}
static void
exo_icon_view_put (ExoIconView *icon_view,
GtkWidget *widget,
ExoIconViewItem *item,
gint cell)
{
ExoIconViewChild *child;
/* allocate the new child */
child = _exo_slice_new (ExoIconViewChild);
child->widget = widget;
child->item = item;
child->cell = cell;
/* hook up the child */
icon_view->priv->children = g_list_append (icon_view->priv->children, child);
/* setup the parent for the child */
if (gtk_widget_get_realized (GTK_WIDGET (icon_view)))
gtk_widget_set_parent_window (child->widget, icon_view->priv->bin_window);
gtk_widget_set_parent (widget, GTK_WIDGET (icon_view));
}
static void
exo_icon_view_remove_widget (GtkCellEditable *editable,
ExoIconView *icon_view)
{
ExoIconViewItem *item;
GList *lp;
if (G_LIKELY (icon_view->priv->edited_item != NULL))
{
item = icon_view->priv->edited_item;
icon_view->priv->edited_item = NULL;
icon_view->priv->editable = NULL;
for (lp = icon_view->priv->cell_list; lp != NULL; lp = lp->next)
((ExoIconViewCellInfo *) lp->data)->editing = FALSE;
if (gtk_widget_has_focus (GTK_WIDGET (editable)))
gtk_widget_grab_focus (GTK_WIDGET (icon_view));
g_signal_handlers_disconnect_by_func (editable, exo_icon_view_remove_widget, icon_view);
gtk_container_remove (GTK_CONTAINER (icon_view), GTK_WIDGET (editable));
exo_icon_view_queue_draw_item (icon_view, item);
}
}
static void
exo_icon_view_start_editing (ExoIconView *icon_view,
ExoIconViewItem *item,
ExoIconViewCellInfo *info,
GdkEvent *event)
{
GtkCellRendererMode mode;
GtkCellEditable *editable;
GdkRectangle cell_area;
GtkTreePath *path;
gboolean visible;
gchar *path_string;
/* setup cell data for the given item */
exo_icon_view_set_cell_data (icon_view, item);
/* check if the cell is visible and editable (given the updated cell data) */
g_object_get (info->cell, "visible", &visible, "mode", &mode, NULL);
if (G_LIKELY (visible && mode == GTK_CELL_RENDERER_MODE_EDITABLE))
{
/* draw keyboard focus while editing */
EXO_ICON_VIEW_SET_FLAG (icon_view, EXO_ICON_VIEW_DRAW_KEYFOCUS);
/* determine the cell area */
exo_icon_view_get_cell_area (icon_view, item, info, &cell_area);
/* determine the tree path */
path = gtk_tree_path_new_from_indices (g_list_index (icon_view->priv->items, item), -1);
path_string = gtk_tree_path_to_string (path);
gtk_tree_path_free (path);
/* allocate the editable from the cell renderer */
editable = gtk_cell_renderer_start_editing (info->cell, event, GTK_WIDGET (icon_view), path_string, &cell_area, &cell_area, 0);
/* ugly hack, but works */
if (g_object_class_find_property (G_OBJECT_GET_CLASS (editable), "has-frame") != NULL)
g_object_set (editable, "has-frame", TRUE, NULL);
/* setup the editing widget */
icon_view->priv->edited_item = item;
icon_view->priv->editable = editable;
info->editing = TRUE;
exo_icon_view_put (icon_view, GTK_WIDGET (editable), item, info->position);
gtk_cell_editable_start_editing (GTK_CELL_EDITABLE (editable), (GdkEvent *)event);
gtk_widget_grab_focus (GTK_WIDGET (editable));
g_signal_connect (G_OBJECT (editable), "remove-widget", G_CALLBACK (exo_icon_view_remove_widget), icon_view);
/* cleanup */
g_free (path_string);
}
}
static void
exo_icon_view_stop_editing (ExoIconView *icon_view,
gboolean cancel_editing)
{
ExoIconViewItem *item;
GtkCellRenderer *cell = NULL;
GList *lp;
if (icon_view->priv->edited_item == NULL)
return;
/*
* This is very evil. We need to do this, because
* gtk_cell_editable_editing_done may trigger exo_icon_view_row_changed
* later on. If exo_icon_view_row_changed notices
* icon_view->priv->edited_item != NULL, it'll call
* exo_icon_view_stop_editing again. Bad things will happen then.
*
* Please read that again if you intend to modify anything here.
*/
item = icon_view->priv->edited_item;
icon_view->priv->edited_item = NULL;
for (lp = icon_view->priv->cell_list; lp != NULL; lp = lp->next)
{
ExoIconViewCellInfo *info = lp->data;
if (info->editing)
{
cell = info->cell;
break;
}
}
if (G_UNLIKELY (cell == NULL))
return;
gtk_cell_renderer_stop_editing (cell, cancel_editing);
if (G_LIKELY (!cancel_editing))
gtk_cell_editable_editing_done (icon_view->priv->editable);
icon_view->priv->edited_item = item;
gtk_cell_editable_remove_widget (icon_view->priv->editable);
}
static gboolean
exo_icon_view_button_press_event (GtkWidget *widget,
GdkEventButton *event)
{
ExoIconViewCellInfo *info = NULL;
GtkCellRendererMode mode;
ExoIconViewItem *item;
ExoIconView *icon_view;
GtkTreePath *path;
gboolean dirty = FALSE;
gint cursor_cell;
icon_view = EXO_ICON_VIEW (widget);
if (event->window != icon_view->priv->bin_window)
return FALSE;
/* stop any pending "single-click-timeout" */
if (G_UNLIKELY (icon_view->priv->single_click_timeout_id != 0))
g_source_remove (icon_view->priv->single_click_timeout_id);
if (G_UNLIKELY (!gtk_widget_has_focus (widget)))
gtk_widget_grab_focus (widget);
if (event->button == 1 && event->type == GDK_BUTTON_PRESS)
{
item = exo_icon_view_get_item_at_coords (icon_view,
event->x, event->y,
TRUE,
&info);
if (item != NULL)
{
g_object_get (info->cell, "mode", &mode, NULL);
if (mode == GTK_CELL_RENDERER_MODE_ACTIVATABLE ||
mode == GTK_CELL_RENDERER_MODE_EDITABLE)
cursor_cell = g_list_index (icon_view->priv->cell_list, info);
else
cursor_cell = -1;
exo_icon_view_scroll_to_item (icon_view, item);
if (icon_view->priv->selection_mode == GTK_SELECTION_NONE)
{
exo_icon_view_set_cursor_item (icon_view, item, cursor_cell);
}
else if (icon_view->priv->selection_mode == GTK_SELECTION_MULTIPLE &&
(event->state & GDK_SHIFT_MASK))
{
if (!(event->state & GDK_CONTROL_MASK))
exo_icon_view_unselect_all_internal (icon_view);
exo_icon_view_set_cursor_item (icon_view, item, cursor_cell);
if (!icon_view->priv->anchor_item)
icon_view->priv->anchor_item = item;
else
exo_icon_view_select_all_between (icon_view,
icon_view->priv->anchor_item,
item);
dirty = TRUE;
}
else
{
if ((icon_view->priv->selection_mode == GTK_SELECTION_MULTIPLE ||
((icon_view->priv->selection_mode == GTK_SELECTION_SINGLE) && item->selected)) &&
(event->state & GDK_CONTROL_MASK))
{
item->selected = !item->selected;
exo_icon_view_queue_draw_item (icon_view, item);
dirty = TRUE;
}
else
{
if (!item->selected)
{
exo_icon_view_unselect_all_internal (icon_view);
item->selected = TRUE;
exo_icon_view_queue_draw_item (icon_view, item);
dirty = TRUE;
}
}
exo_icon_view_set_cursor_item (icon_view, item, cursor_cell);
icon_view->priv->anchor_item = item;
}
/* Save press to possibly begin a drag */
if (icon_view->priv->pressed_button < 0)
{
icon_view->priv->pressed_button = event->button;
icon_view->priv->press_start_x = event->x;
icon_view->priv->press_start_y = event->y;
}
//if (G_LIKELY (icon_view->priv->last_single_clicked == NULL)) //sfm disabled
icon_view->priv->last_single_clicked = item;
/* cancel the current editing, if it exists */
exo_icon_view_stop_editing (icon_view, TRUE);
if (mode == GTK_CELL_RENDERER_MODE_ACTIVATABLE)
exo_icon_view_item_activate_cell (icon_view, item, info,
(GdkEvent *)event);
else if (mode == GTK_CELL_RENDERER_MODE_EDITABLE)
exo_icon_view_start_editing (icon_view, item, info,
(GdkEvent *)event);
}
else
{
/* cancel the current editing, if it exists */
exo_icon_view_stop_editing (icon_view, TRUE);
if (icon_view->priv->selection_mode != GTK_SELECTION_BROWSE &&
!(event->state & GDK_CONTROL_MASK))
{
dirty = exo_icon_view_unselect_all_internal (icon_view);
}
if (icon_view->priv->selection_mode == GTK_SELECTION_MULTIPLE)
exo_icon_view_start_rubberbanding (icon_view, event->x, event->y);
}
}
else if (event->button == 1 && event->type == GDK_2BUTTON_PRESS)
{
/* ignore double-click events in single-click mode */
if (G_LIKELY (!icon_view->priv->single_click))
{
item = exo_icon_view_get_item_at_coords (icon_view,
event->x, event->y,
TRUE,
NULL);
if (G_LIKELY (item != NULL))
{
path = gtk_tree_path_new_from_indices (g_list_index (icon_view->priv->items, item), -1);
exo_icon_view_item_activated (icon_view, path);
gtk_tree_path_free (path);
}
}
icon_view->priv->last_single_clicked = NULL;
icon_view->priv->pressed_button = -1;
}
/* grab focus and stop drawing the keyboard focus indicator on single clicks */
if (G_LIKELY (event->type != GDK_2BUTTON_PRESS && event->type != GDK_3BUTTON_PRESS))
{
if (!gtk_widget_has_focus (GTK_WIDGET (icon_view)))
gtk_widget_grab_focus (GTK_WIDGET (icon_view));
EXO_ICON_VIEW_UNSET_FLAG (icon_view, EXO_ICON_VIEW_DRAW_KEYFOCUS);
}
if (dirty)
g_signal_emit (icon_view, icon_view_signals[SELECTION_CHANGED], 0);
return event->button == 1;
}
static gboolean
exo_icon_view_button_release_event (GtkWidget *widget,
GdkEventButton *event)
{
ExoIconViewItem *item;
ExoIconView *icon_view = EXO_ICON_VIEW (widget);
GtkTreePath *path;
if (icon_view->priv->pressed_button == event->button)
{
/* check if we're in single click mode */
if (G_UNLIKELY (icon_view->priv->single_click && (event->state & (GDK_CONTROL_MASK | GDK_SHIFT_MASK)) == 0))
{
/* determine the item at the mouse coords and check if this is the last single clicked one */
item = exo_icon_view_get_item_at_coords (icon_view, event->x, event->y, TRUE, NULL);
if (G_LIKELY (item != NULL && item == icon_view->priv->last_single_clicked))
{
/* emit an "item-activated" signal for this item */
path = gtk_tree_path_new_from_indices (g_list_index (icon_view->priv->items, item), -1);
exo_icon_view_item_activated (icon_view, path);
gtk_tree_path_free (path);
}
/* reset the last single clicked item */
icon_view->priv->last_single_clicked = NULL;
}
/* reset the pressed_button state */
icon_view->priv->pressed_button = -1;
}
exo_icon_view_stop_rubberbanding (icon_view);
remove_scroll_timeout (icon_view);
return TRUE;
}
static gboolean
exo_icon_view_scroll_event (GtkWidget *widget,
GdkEventScroll *event)
{
GtkAdjustment *adjustment;
ExoIconView *icon_view = EXO_ICON_VIEW (widget);
gdouble delta;
gdouble value;
/* we don't care for scroll events in "rows" layout mode, as
* that's completely handled by GtkScrolledWindow.
*/
if (icon_view->priv->layout_mode != EXO_ICON_VIEW_LAYOUT_COLS)
return FALSE;
/* also, we don't care for anything but Up/Down, as
* everything else will be handled by GtkScrolledWindow.
*/
if (event->direction != GDK_SCROLL_UP && event->direction != GDK_SCROLL_DOWN)
return FALSE;
/* determine the horizontal adjustment */
adjustment = icon_view->priv->hadjustment;
/* determine the scroll delta */
delta = pow (gtk_adjustment_get_page_size (adjustment), 2.0 / 3.0);
delta = (event->direction == GDK_SCROLL_UP) ? -delta : delta;
/* apply the new adjustment value */
value = CLAMP (gtk_adjustment_get_value (adjustment) + delta, gtk_adjustment_get_lower (adjustment), gtk_adjustment_get_upper (adjustment) - gtk_adjustment_get_page_size (adjustment));
gtk_adjustment_set_value (adjustment, value);
return TRUE;
}
static gboolean
exo_icon_view_key_press_event (GtkWidget *widget,
GdkEventKey *event)
{
ExoIconView *icon_view = EXO_ICON_VIEW (widget);
GdkScreen *screen;
GdkEvent *new_event;
gboolean retval;
gulong popup_menu_id;
gchar *new_text;
gchar *old_text;
/* let the parent class handle the key bindings and stuff */
if ((*GTK_WIDGET_CLASS (exo_icon_view_parent_class)->key_press_event) (widget, event))
return TRUE;
/* check if typeahead search is enabled */
if (G_UNLIKELY (!icon_view->priv->enable_search))
return FALSE;
exo_icon_view_search_ensure_directory (icon_view);
/* make sure the search window is realized */
gtk_widget_realize (icon_view->priv->search_window);
/* make a copy of the current text */
old_text = gtk_editable_get_chars (GTK_EDITABLE (icon_view->priv->search_entry), 0, -1);
/* make sure we don't accidently popup the context menu */
popup_menu_id = g_signal_connect (G_OBJECT (icon_view->priv->search_entry), "popup-menu", G_CALLBACK (gtk_true), NULL);
/* move the search window offscreen */
screen = gtk_widget_get_screen (GTK_WIDGET (icon_view));
gtk_window_move (GTK_WINDOW (icon_view->priv->search_window),
gdk_screen_get_width (screen) + 1,
gdk_screen_get_height (screen) + 1);
gtk_widget_show (icon_view->priv->search_window);
/* allocate a new event to forward */
new_event = gdk_event_copy ((GdkEvent *) event);
g_object_unref (G_OBJECT (new_event->key.window));
new_event->key.window = g_object_ref (G_OBJECT (gtk_widget_get_window (GTK_WIDGET(icon_view->priv->search_entry))));
/* send the event to the search entry. If the "preedit-changed" signal is
* emitted during this event, priv->search_imcontext_changed will be set.
*/
icon_view->priv->search_imcontext_changed = FALSE;
retval = gtk_widget_event (icon_view->priv->search_entry, new_event);
gtk_widget_hide (icon_view->priv->search_window);
/* release the temporary event */
gdk_event_free (new_event);
/* disconnect the popup menu prevention */
g_signal_handler_disconnect (G_OBJECT (icon_view->priv->search_entry), popup_menu_id);
/* we check to make sure that the entry tried to handle the,
* and that the text has actually changed.
*/
new_text = gtk_editable_get_chars (GTK_EDITABLE (icon_view->priv->search_entry), 0, -1);
retval = retval && (strcmp (new_text, old_text) != 0);
g_free (old_text);
g_free (new_text);
/* if we're in a preedit or the text was modified */
if (icon_view->priv->search_imcontext_changed || retval)
{
if (exo_icon_view_search_start (icon_view, FALSE))
{
gtk_widget_grab_focus (GTK_WIDGET (icon_view));
return TRUE;
}
else
{
gtk_entry_set_text (GTK_ENTRY (icon_view->priv->search_entry), "");
return FALSE;
}
}
return FALSE;
}
static gboolean
exo_icon_view_focus_out_event (GtkWidget *widget,
GdkEventFocus *event)
{
ExoIconView *icon_view = EXO_ICON_VIEW (widget);
/* be sure to cancel any single-click timeout */
if (G_UNLIKELY (icon_view->priv->single_click_timeout_id != 0))
g_source_remove (icon_view->priv->single_click_timeout_id);
/* reset the cursor if we're still realized */
if (G_LIKELY (icon_view->priv->bin_window != NULL))
gdk_window_set_cursor (icon_view->priv->bin_window, NULL);
/* destroy the interactive search dialog */
if (G_UNLIKELY (icon_view->priv->search_window != NULL))
exo_icon_view_search_dialog_hide (icon_view->priv->search_window, icon_view);
/* schedule a redraw with the new focus state */
gtk_widget_queue_draw (widget);
return FALSE;
}
static gboolean
exo_icon_view_leave_notify_event (GtkWidget *widget,
GdkEventCrossing *event)
{
/* reset cursor to default */
if (gtk_widget_get_realized (widget))
gdk_window_set_cursor (gtk_widget_get_window (widget), NULL);
/* call the parent's leave_notify_event (if any) */
if (GTK_WIDGET_CLASS (exo_icon_view_parent_class)->leave_notify_event != NULL)
return (*GTK_WIDGET_CLASS (exo_icon_view_parent_class)->leave_notify_event) (widget, event);
/* other signal handlers may be invoked */
return FALSE;
}
static void
exo_icon_view_update_rubberband (gpointer data)
{
ExoIconView *icon_view;
gint x, y;
GdkRectangle old_area;
GdkRectangle new_area;
GdkRectangle common;
#if GTK_CHECK_VERSION (3, 0, 0)
cairo_region_t *invalid_region;
#else
GdkRegion *invalid_region;
#endif
icon_view = EXO_ICON_VIEW (data);
gdk_window_get_pointer (icon_view->priv->bin_window, &x, &y, NULL);
x = MAX (x, 0);
y = MAX (y, 0);
old_area.x = MIN (icon_view->priv->rubberband_x1,
icon_view->priv->rubberband_x2);
old_area.y = MIN (icon_view->priv->rubberband_y1,
icon_view->priv->rubberband_y2);
old_area.width = ABS (icon_view->priv->rubberband_x2 -
icon_view->priv->rubberband_x1) + 1;
old_area.height = ABS (icon_view->priv->rubberband_y2 -
icon_view->priv->rubberband_y1) + 1;
new_area.x = MIN (icon_view->priv->rubberband_x1, x);
new_area.y = MIN (icon_view->priv->rubberband_y1, y);
new_area.width = ABS (x - icon_view->priv->rubberband_x1) + 1;
new_area.height = ABS (y - icon_view->priv->rubberband_y1) + 1;
#if GTK_CHECK_VERSION (3, 0, 0)
invalid_region = cairo_region_create_rectangle ((cairo_rectangle_int_t *)&old_area);
cairo_region_union_rectangle (invalid_region, (cairo_rectangle_int_t *)&new_area);
#else
invalid_region = gdk_region_rectangle (&old_area);
gdk_region_union_with_rect (invalid_region, &new_area);
#endif
gdk_rectangle_intersect (&old_area, &new_area, &common);
if (common.width > 2 && common.height > 2)
{
#if GTK_CHECK_VERSION (3, 0, 0)
cairo_region_t *common_region;
#else
GdkRegion *common_region;
#endif
/* make sure the border is invalidated */
common.x += 1;
common.y += 1;
common.width -= 2;
common.height -= 2;
#if GTK_CHECK_VERSION (3, 0, 0)
common_region = cairo_region_create_rectangle ((cairo_rectangle_int_t *)&common);
cairo_region_subtract (invalid_region, common_region);
cairo_region_destroy (common_region);
#else
common_region = gdk_region_rectangle (&common);
gdk_region_subtract (invalid_region, common_region);
gdk_region_destroy (common_region);
#endif
}
gdk_window_invalidate_region (icon_view->priv->bin_window, invalid_region, TRUE);
#if GTK_CHECK_VERSION (3, 0, 0)
cairo_region_destroy (invalid_region);
#else
gdk_region_destroy (invalid_region);
#endif
icon_view->priv->rubberband_x2 = x;
icon_view->priv->rubberband_y2 = y;
exo_icon_view_update_rubberband_selection (icon_view);
}
static void
exo_icon_view_start_rubberbanding (ExoIconView *icon_view,
gint x,
gint y)
{
const GdkColor *background_color;
GdkColor *color;
guchar alpha;
gpointer drag_data;
GList *items;
/* be sure to disable any previously active rubberband */
exo_icon_view_stop_rubberbanding (icon_view);
for (items = icon_view->priv->items; items; items = items->next)
{
ExoIconViewItem *item = items->data;
item->selected_before_rubberbanding = item->selected;
}
icon_view->priv->rubberband_x1 = x;
icon_view->priv->rubberband_y1 = y;
icon_view->priv->rubberband_x2 = x;
icon_view->priv->rubberband_y2 = y;
icon_view->priv->doing_rubberband = TRUE;
#if GTK_CHECK_VERSION (3, 0, 0)
GtkStyleContext *style_ctx = gtk_widget_get_style_context (GTK_WIDGET (icon_view));
gtk_style_context_save (style_ctx);
gtk_style_context_add_class (style_ctx, GTK_STYLE_CLASS_RUBBERBAND);
/* set the rubberband border color */
gtk_style_context_get_border_color (style_ctx, GTK_STATE_FLAG_NORMAL, &icon_view->priv->rubberband_border_color);
/* set the rubberband fill color */
gtk_style_context_get_background_color (style_ctx, GTK_STATE_FLAG_NORMAL, &icon_view->priv->rubberband_fill_color);
gtk_style_context_restore (style_ctx);
#else
/* determine the border color */
gtk_widget_style_get (GTK_WIDGET (icon_view), "selection-box-color", &color, NULL);
if (G_LIKELY (color == NULL))
color = gdk_color_copy (>k_widget_get_style(GTK_WIDGET (icon_view))->base[GTK_STATE_SELECTED]);
/* set the rubberband border color */
icon_view->priv->rubberband_border_color = color;
/* determine the fill color and alpha setting */
gtk_widget_style_get (GTK_WIDGET (icon_view), "selection-box-color", &color, "selection-box-alpha", &alpha, NULL);
if (G_LIKELY (color == NULL))
color = gdk_color_copy (>k_widget_get_style(GTK_WIDGET (icon_view))->base[GTK_STATE_SELECTED]);
/* calculate the fill color (based on the fill color, the alpha setting and the background color) */
background_color = >k_widget_get_style(GTK_WIDGET (icon_view))->base[GTK_STATE_NORMAL];
color->red = ((color->red * (alpha / 255.0)) + (background_color->red * (255.0 - alpha / 255.0)));
color->green = ((color->green * (alpha / 255.0)) + (background_color->green * (255.0 - alpha / 255.0)));
color->blue = ((color->blue * (alpha / 255.0)) + (background_color->blue * (255.0 - alpha / 255.0)));
/* set the rubberband background color */
icon_view->priv->rubberband_fill_color = color;
#endif
gtk_grab_add (GTK_WIDGET (icon_view));
/* be sure to disable Gtk+ DnD callbacks, because else rubberbanding will be interrupted */
drag_data = g_object_get_data (G_OBJECT (icon_view), I_("gtk-site-data"));
if (G_LIKELY (drag_data != NULL))
{
g_signal_handlers_block_matched (G_OBJECT (icon_view),
G_SIGNAL_MATCH_DATA,
0, 0, NULL, NULL,
drag_data);
}
}
static void
exo_icon_view_stop_rubberbanding (ExoIconView *icon_view)
{
gpointer drag_data;
if (G_LIKELY (icon_view->priv->doing_rubberband))
{
icon_view->priv->doing_rubberband = FALSE;
gtk_grab_remove (GTK_WIDGET (icon_view));
gtk_widget_queue_draw (GTK_WIDGET (icon_view));
#if !GTK_CHECK_VERSION (3, 0, 0)
/* Free the colors for drawing the rubberband */
gdk_color_free (icon_view->priv->rubberband_border_color);
gdk_color_free (icon_view->priv->rubberband_fill_color);
icon_view->priv->rubberband_border_color = NULL;
icon_view->priv->rubberband_fill_color = NULL;
#endif
/* re-enable Gtk+ DnD callbacks again */
drag_data = g_object_get_data (G_OBJECT (icon_view), I_("gtk-site-data"));
if (G_LIKELY (drag_data != NULL))
{
g_signal_handlers_unblock_matched (G_OBJECT (icon_view),
G_SIGNAL_MATCH_DATA,
0, 0, NULL, NULL,
drag_data);
}
}
}
static void
exo_icon_view_update_rubberband_selection (ExoIconView *icon_view)
{
ExoIconViewItem *item;
gboolean selected;
gboolean changed = FALSE;
gboolean is_in;
GList *lp;
gint x, y;
gint width;
gint height;
/* determine the new rubberband area */
x = MIN (icon_view->priv->rubberband_x1, icon_view->priv->rubberband_x2);
y = MIN (icon_view->priv->rubberband_y1, icon_view->priv->rubberband_y2);
width = ABS (icon_view->priv->rubberband_x1 - icon_view->priv->rubberband_x2);
height = ABS (icon_view->priv->rubberband_y1 - icon_view->priv->rubberband_y2);
/* check all items */
for (lp = icon_view->priv->items; lp != NULL; lp = lp->next)
{
item = EXO_ICON_VIEW_ITEM (lp->data);
is_in = exo_icon_view_item_hit_test (icon_view, item, x, y, width, height);
selected = is_in ^ item->selected_before_rubberbanding;
if (G_UNLIKELY (item->selected != selected))
{
changed = TRUE;
item->selected = selected;
exo_icon_view_queue_draw_item (icon_view, item);
}
}
if (G_LIKELY (changed))
g_signal_emit (G_OBJECT (icon_view), icon_view_signals[SELECTION_CHANGED], 0);
}
static gboolean
exo_icon_view_item_hit_test (ExoIconView *icon_view,
ExoIconViewItem *item,
gint x,
gint y,
gint width,
gint height)
{
GList *l;
GdkRectangle box;
for (l = icon_view->priv->cell_list; l; l = l->next)
{
ExoIconViewCellInfo *info = (ExoIconViewCellInfo *)l->data;
if (!gtk_cell_renderer_get_visible (info->cell))
continue;
box = item->box[info->position];
if (MIN (x + width, box.x + box.width) - MAX (x, box.x) > 0 &&
MIN (y + height, box.y + box.height) - MAX (y, box.y) > 0)
return TRUE;
}
return FALSE;
}
static gboolean
exo_icon_view_unselect_all_internal (ExoIconView *icon_view)
{
ExoIconViewItem *item;
gboolean dirty = FALSE;
GList *lp;
if (G_LIKELY (icon_view->priv->selection_mode != GTK_SELECTION_NONE))
{
for (lp = icon_view->priv->items; lp != NULL; lp = lp->next)
{
item = EXO_ICON_VIEW_ITEM (lp->data);
if (item->selected)
{
dirty = TRUE;
item->selected = FALSE;
exo_icon_view_queue_draw_item (icon_view, item);
}
}
}
return dirty;
}
#if GTK_CHECK_VERSION (3, 0, 0)
static void
exo_icon_view_set_hadjustment (ExoIconView *icon_view,
GtkAdjustment *hadj)
{
if (hadj && icon_view->priv->hadjustment == hadj)
return;
if (icon_view->priv->hadjustment)
{
g_signal_handlers_disconnect_matched (icon_view->priv->hadjustment, G_SIGNAL_MATCH_DATA,
0, 0, NULL, NULL, icon_view);
g_object_unref (icon_view->priv->hadjustment);
}
if (!hadj)
hadj = gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
icon_view->priv->hadjustment = g_object_ref_sink (G_OBJECT (hadj));
g_signal_connect (icon_view->priv->hadjustment, "value-changed",
G_CALLBACK (exo_icon_view_adjustment_changed),
icon_view);
if (icon_view->priv->vadjustment)
exo_icon_view_adjustment_changed (NULL, icon_view);
}
static void
exo_icon_view_set_vadjustment (ExoIconView *icon_view,
GtkAdjustment *vadj)
{
if (vadj && icon_view->priv->vadjustment == vadj)
return;
if (icon_view->priv->vadjustment)
{
g_signal_handlers_disconnect_matched (icon_view->priv->vadjustment, G_SIGNAL_MATCH_DATA,
0, 0, NULL, NULL, icon_view);
g_object_unref (icon_view->priv->vadjustment);
}
if (!vadj)
vadj = gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
icon_view->priv->vadjustment = g_object_ref_sink (G_OBJECT (vadj));
g_signal_connect (icon_view->priv->vadjustment, "value-changed",
G_CALLBACK (exo_icon_view_adjustment_changed),
icon_view);
if (icon_view->priv->hadjustment)
exo_icon_view_adjustment_changed (NULL, icon_view);
}
#else
static void
exo_icon_view_set_adjustments (ExoIconView *icon_view,
GtkAdjustment *hadj,
GtkAdjustment *vadj)
{
gboolean need_adjust = FALSE;
if (hadj)
_exo_return_if_fail (GTK_IS_ADJUSTMENT (hadj));
else
hadj = GTK_ADJUSTMENT (gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
if (vadj)
_exo_return_if_fail (GTK_IS_ADJUSTMENT (vadj));
else
vadj = GTK_ADJUSTMENT (gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
if (icon_view->priv->hadjustment && (icon_view->priv->hadjustment != hadj))
{
g_signal_handlers_disconnect_matched (icon_view->priv->hadjustment, G_SIGNAL_MATCH_DATA,
0, 0, NULL, NULL, icon_view);
g_object_unref (icon_view->priv->hadjustment);
}
if (icon_view->priv->vadjustment && (icon_view->priv->vadjustment != vadj))
{
g_signal_handlers_disconnect_matched (icon_view->priv->vadjustment, G_SIGNAL_MATCH_DATA,
0, 0, NULL, NULL, icon_view);
g_object_unref (icon_view->priv->vadjustment);
}
if (icon_view->priv->hadjustment != hadj)
{
icon_view->priv->hadjustment = hadj;
g_object_ref (icon_view->priv->hadjustment);
g_object_ref_sink (G_OBJECT (icon_view->priv->hadjustment));
g_signal_connect (icon_view->priv->hadjustment, "value-changed",
G_CALLBACK (exo_icon_view_adjustment_changed),
icon_view);
need_adjust = TRUE;
}
if (icon_view->priv->vadjustment != vadj)
{
icon_view->priv->vadjustment = vadj;
g_object_ref (icon_view->priv->vadjustment);
g_object_ref_sink (G_OBJECT (icon_view->priv->vadjustment));
g_signal_connect (icon_view->priv->vadjustment, "value-changed",
G_CALLBACK (exo_icon_view_adjustment_changed),
icon_view);
need_adjust = TRUE;
}
if (need_adjust)
exo_icon_view_adjustment_changed (NULL, icon_view);
}
#endif
static void
exo_icon_view_real_select_all (ExoIconView *icon_view)
{
exo_icon_view_select_all (icon_view);
}
static void
exo_icon_view_real_unselect_all (ExoIconView *icon_view)
{
exo_icon_view_unselect_all (icon_view);
}
static void
exo_icon_view_real_select_cursor_item (ExoIconView *icon_view)
{
exo_icon_view_unselect_all (icon_view);
if (icon_view->priv->cursor_item != NULL)
exo_icon_view_select_item (icon_view, icon_view->priv->cursor_item);
}
static gboolean
exo_icon_view_real_activate_cursor_item (ExoIconView *icon_view)
{
GtkTreePath *path;
GtkCellRendererMode mode;
ExoIconViewCellInfo *info = NULL;
if (!icon_view->priv->cursor_item)
return FALSE;
info = g_list_nth_data (icon_view->priv->cell_list,
icon_view->priv->cursor_cell);
if (info)
{
g_object_get (info->cell, "mode", &mode, NULL);
if (mode == GTK_CELL_RENDERER_MODE_ACTIVATABLE)
{
exo_icon_view_item_activate_cell (icon_view,
icon_view->priv->cursor_item,
info, NULL);
return TRUE;
}
else if (mode == GTK_CELL_RENDERER_MODE_EDITABLE)
{
exo_icon_view_start_editing (icon_view,
icon_view->priv->cursor_item,
info, NULL);
return TRUE;
}
}
path = gtk_tree_path_new_from_indices (g_list_index (icon_view->priv->items, icon_view->priv->cursor_item), -1);
exo_icon_view_item_activated (icon_view, path);
gtk_tree_path_free (path);
return TRUE;
}
static gboolean
exo_icon_view_real_start_interactive_search (ExoIconView *icon_view)
{
return exo_icon_view_search_start (icon_view, TRUE);
}
static void
exo_icon_view_real_toggle_cursor_item (ExoIconView *icon_view)
{
if (G_LIKELY (icon_view->priv->cursor_item != NULL))
{
switch (icon_view->priv->selection_mode)
{
case GTK_SELECTION_NONE:
break;
case GTK_SELECTION_BROWSE:
exo_icon_view_select_item (icon_view, icon_view->priv->cursor_item);
break;
case GTK_SELECTION_SINGLE:
if (icon_view->priv->cursor_item->selected)
exo_icon_view_unselect_item (icon_view, icon_view->priv->cursor_item);
else
exo_icon_view_select_item (icon_view, icon_view->priv->cursor_item);
break;
case GTK_SELECTION_MULTIPLE:
icon_view->priv->cursor_item->selected = !icon_view->priv->cursor_item->selected;
g_signal_emit (icon_view, icon_view_signals[SELECTION_CHANGED], 0);
exo_icon_view_queue_draw_item (icon_view, icon_view->priv->cursor_item);
break;
default:
g_assert_not_reached ();
}
}
}
static void
exo_icon_view_adjustment_changed (GtkAdjustment *adjustment,
ExoIconView *icon_view)
{
if (gtk_widget_get_realized (GTK_WIDGET (icon_view)))
{
gdk_window_move (icon_view->priv->bin_window, -gtk_adjustment_get_value (icon_view->priv->hadjustment), -gtk_adjustment_get_value (icon_view->priv->vadjustment));
if (G_UNLIKELY (icon_view->priv->doing_rubberband))
exo_icon_view_update_rubberband (GTK_WIDGET (icon_view));
gdk_window_process_updates (icon_view->priv->bin_window, TRUE);
}
}
static GList*
exo_icon_view_layout_single_row (ExoIconView *icon_view,
GList *first_item,
gint item_width,
gint row,
gint *y,
gint *maximum_width,
gint max_cols)
{
ExoIconViewPrivate *priv = icon_view->priv;
ExoIconViewItem *item;
GtkAllocation allocation;
gboolean rtl;
GList *last_item;
GList *items = first_item;
gint *max_width;
gint *max_height;
gint focus_width;
gint current_width;
gint colspan;
gint col = 0;
gint x;
gint i;
rtl = (gtk_widget_get_direction (GTK_WIDGET (icon_view)) == GTK_TEXT_DIR_RTL);
max_width = g_newa (gint, priv->n_cells);
max_height = g_newa (gint, priv->n_cells);
for (i = priv->n_cells; --i >= 0; )
{
max_width[i] = 0;
max_height[i] = 0;
}
gtk_widget_style_get (GTK_WIDGET (icon_view),
"focus-line-width", &focus_width,
NULL);
x = priv->margin + focus_width;
current_width = 2 * (priv->margin + focus_width);
gtk_widget_get_allocation (GTK_WIDGET (icon_view), &allocation);
for (items = first_item; items != NULL; items = items->next)
{
item = EXO_ICON_VIEW_ITEM (items->data);
exo_icon_view_calculate_item_size (icon_view, item);
colspan = 1 + (item->area.width - 1) / (item_width + priv->column_spacing);
item->area.width = colspan * item_width + (colspan - 1) * priv->column_spacing;
current_width += item->area.width + priv->column_spacing + 2 * focus_width;
if (G_LIKELY (items != first_item))
{
if ((priv->columns <= 0 && current_width > allocation.width) ||
(priv->columns > 0 && col >= priv->columns) ||
(max_cols > 0 && col >= max_cols))
break;
}
item->area.y = *y + focus_width;
item->area.x = rtl ? allocation.width - item->area.width - x : x;
x = current_width - (priv->margin + focus_width);
for (i = 0; i < priv->n_cells; i++)
{
max_width[i] = MAX (max_width[i], item->box[i].width);
max_height[i] = MAX (max_height[i], item->box[i].height);
}
if (current_width > *maximum_width)
*maximum_width = current_width;
item->row = row;
item->col = col;
col += colspan;
}
last_item = items;
/* Now go through the row again and align the icons */
for (items = first_item; items != last_item; items = items->next)
{
item = EXO_ICON_VIEW_ITEM (items->data);
exo_icon_view_calculate_item_size2 (icon_view, item, max_width, max_height);
/* We may want to readjust the new y coordinate. */
if (item->area.y + item->area.height + focus_width + priv->row_spacing > *y)
*y = item->area.y + item->area.height + focus_width + priv->row_spacing;
if (G_UNLIKELY (rtl))
item->col = col - 1 - item->col;
}
return last_item;
}
static GList*
exo_icon_view_layout_single_col (ExoIconView *icon_view,
GList *first_item,
gint item_height,
gint col,
gint *x,
gint *maximum_height,
gint max_rows)
{
ExoIconViewPrivate *priv = icon_view->priv;
ExoIconViewItem *item;
GtkAllocation allocation;
GList *items = first_item;
GList *last_item;
gint *max_width;
gint *max_height;
gint focus_width;
gint current_height;
gint rowspan;
gint row = 0;
gint y;
gint i;
max_width = g_newa (gint, priv->n_cells);
max_height = g_newa (gint, priv->n_cells);
for (i = priv->n_cells; --i >= 0; )
{
max_width[i] = 0;
max_height[i] = 0;
}
gtk_widget_style_get (GTK_WIDGET (icon_view),
"focus-line-width", &focus_width,
NULL);
y = priv->margin + focus_width;
current_height = 2 * (priv->margin + focus_width);
gtk_widget_get_allocation (GTK_WIDGET (icon_view), &allocation);
for (items = first_item; items != NULL; items = items->next)
{
item = EXO_ICON_VIEW_ITEM (items->data);
exo_icon_view_calculate_item_size (icon_view, item);
rowspan = 1 + (item->area.height - 1) / (item_height + priv->row_spacing);
item->area.height = rowspan * item_height + (rowspan - 1) * priv->row_spacing;
current_height += item->area.height + priv->row_spacing + 2 * focus_width;
if (G_LIKELY (items != first_item))
{
if (current_height >= allocation.height ||
(max_rows > 0 && row >= max_rows))
break;
}
item->area.y = y + focus_width;
item->area.x = *x;
y = current_height - (priv->margin + focus_width);
for (i = 0; i < priv->n_cells; i++)
{
max_width[i] = MAX (max_width[i], item->box[i].width);
max_height[i] = MAX (max_height[i], item->box[i].height);
}
if (current_height > *maximum_height)
*maximum_height = current_height;
item->row = row;
item->col = col;
row += rowspan;
}
last_item = items;
/* Now go through the column again and align the icons */
for (items = first_item; items != last_item; items = items->next)
{
item = EXO_ICON_VIEW_ITEM (items->data);
exo_icon_view_calculate_item_size2 (icon_view, item, max_width, max_height);
/* We may want to readjust the new x coordinate. */
if (item->area.x + item->area.width + focus_width + priv->column_spacing > *x)
*x = item->area.x + item->area.width + focus_width + priv->column_spacing;
}
return last_item;
}
static void
exo_icon_view_set_adjustment_upper (GtkAdjustment *adj,
gdouble upper)
{
if (upper != gtk_adjustment_get_upper (adj))
{
gdouble min = MAX (0.0, upper - gtk_adjustment_get_page_size (adj));
gboolean value_changed = FALSE;
gtk_adjustment_set_upper (adj, upper);
if (gtk_adjustment_get_value (adj) > min)
{
gtk_adjustment_set_value (adj, min);
value_changed = TRUE;
}
gtk_adjustment_changed (adj);
if (value_changed)
gtk_adjustment_value_changed (adj);
}
}
static gint
exo_icon_view_layout_cols (ExoIconView *icon_view,
gint item_height,
gint *x,
gint *maximum_height,
gint max_rows)
{
GList *icons = icon_view->priv->items;
GList *items;
gint col = 0;
gint rows;
*x = icon_view->priv->margin;
do
{
icons = exo_icon_view_layout_single_col (icon_view, icons,
item_height, col,
x, maximum_height, max_rows);
/* count the number of rows in the first column */
if (G_UNLIKELY (col == 0))
{
for (items = icon_view->priv->items, rows = 0; items != icons; items = items->next, ++rows)
;
}
col++;
}
while (icons != NULL);
*x += icon_view->priv->margin;
icon_view->priv->cols = col;
return rows;
}
static gint
exo_icon_view_layout_rows (ExoIconView *icon_view,
gint item_width,
gint *y,
gint *maximum_width,
gint max_cols)
{
GList *icons = icon_view->priv->items;
GList *items;
gint row = 0;
gint cols;
*y = icon_view->priv->margin;
do
{
icons = exo_icon_view_layout_single_row (icon_view, icons,
item_width, row,
y, maximum_width, max_cols);
/* count the number of columns in the first row */
if (G_UNLIKELY (row == 0))
{
for (items = icon_view->priv->items, cols = 0; items != icons; items = items->next, ++cols)
;
}
row++;
}
while (icons != NULL);
*y += icon_view->priv->margin;
icon_view->priv->rows = row;
return cols;
}
static void
exo_icon_view_layout (ExoIconView *icon_view)
{
ExoIconViewPrivate *priv = icon_view->priv;
ExoIconViewItem *item;
GtkAllocation allocation;
GList *icons;
gint maximum_height = 0;
gint maximum_width = 0;
gint item_height;
gint item_width;
gint rows, cols;
gint x, y;
/* verify that we still have a valid model */
if (G_UNLIKELY (priv->model == NULL))
return;
gtk_widget_get_allocation (GTK_WIDGET (icon_view), &allocation);
/* determine the layout mode */
if (G_LIKELY (priv->layout_mode == EXO_ICON_VIEW_LAYOUT_ROWS))
{
/* calculate item sizes on-demand */
item_width = priv->item_width;
if (item_width < 0)
{
for (icons = priv->items; icons != NULL; icons = icons->next)
{
item = icons->data;
exo_icon_view_calculate_item_size (icon_view, item);
item_width = MAX (item_width, item->area.width);
}
}
cols = exo_icon_view_layout_rows (icon_view, item_width, &y, &maximum_width, 0);
/* If, by adding another column, we increase the height of the icon view, thus forcing a
* vertical scrollbar to appear that would prevent the last column from being able to fit,
* we need to relayout the icons with one less column.
*/
if (cols == priv->cols + 1 && y > allocation.height &&
priv->height <= allocation.height)
{
cols = exo_icon_view_layout_rows (icon_view, item_width, &y, &maximum_width, priv->cols);
}
priv->width = maximum_width;
priv->height = y;
priv->cols = cols;
}
else
{
/* calculate item sizes on-demand */
for (icons = priv->items, item_height = 0; icons != NULL; icons = icons->next)
{
item = icons->data;
exo_icon_view_calculate_item_size (icon_view, item);
item_height = MAX (item_height, item->area.height);
}
rows = exo_icon_view_layout_cols (icon_view, item_height, &x, &maximum_height, 0);
/* If, by adding another row, we increase the width of the icon view, thus forcing a
* horizontal scrollbar to appear that would prevent the last row from being able to fit,
* we need to relayout the icons with one less row.
*/
if (rows == priv->rows + 1 && x > allocation.width &&
priv->width <= allocation.width)
{
rows = exo_icon_view_layout_cols (icon_view, item_height, &x, &maximum_height, priv->rows);
}
priv->height = maximum_height;
priv->width = x;
priv->rows = rows;
}
exo_icon_view_set_adjustment_upper (priv->hadjustment, priv->width);
exo_icon_view_set_adjustment_upper (priv->vadjustment, priv->height);
if (gtk_widget_get_realized (GTK_WIDGET (icon_view)))
{
gdk_window_resize (priv->bin_window,
MAX (priv->width, allocation.width),
MAX (priv->height, allocation.height));
}
/* drop any pending layout idle source */
if (priv->layout_idle_id != 0)
g_source_remove (priv->layout_idle_id);
gtk_widget_queue_draw (GTK_WIDGET (icon_view));
}
static void
exo_icon_view_get_cell_area (ExoIconView *icon_view,
ExoIconViewItem *item,
ExoIconViewCellInfo *info,
GdkRectangle *cell_area)
{
if (icon_view->priv->orientation == GTK_ORIENTATION_HORIZONTAL)
{
cell_area->x = item->box[info->position].x - item->before[info->position];
cell_area->y = item->area.y;
cell_area->width = item->box[info->position].width + item->before[info->position] + item->after[info->position];
cell_area->height = item->area.height;
}
else
{
cell_area->x = item->area.x;
cell_area->y = item->box[info->position].y - item->before[info->position];
cell_area->width = item->area.width;
cell_area->height = item->box[info->position].height + item->before[info->position] + item->after[info->position];
}
}
static void
exo_icon_view_calculate_item_size (ExoIconView *icon_view,
ExoIconViewItem *item)
{
ExoIconViewCellInfo *info;
GList *lp;
gchar *buffer;
if (G_LIKELY (item->area.width != -1))
return;
if (G_UNLIKELY (item->n_cells != icon_view->priv->n_cells))
{
/* apply the new cell size */
item->n_cells = icon_view->priv->n_cells;
/* release the memory chunk (if any) */
g_free (item->box);
/* allocate a single memory chunk for box, after and before */
buffer = g_malloc0 (item->n_cells * (sizeof (GdkRectangle) + 2 * sizeof (gint)));
/* assign the memory */
item->box = (GdkRectangle *) buffer;
item->after = (gint *) (buffer + item->n_cells * sizeof (GdkRectangle));
item->before = item->after + item->n_cells;
}
exo_icon_view_set_cell_data (icon_view, item);
item->area.width = 0;
item->area.height = 0;
for (lp = icon_view->priv->cell_list; lp != NULL; lp = lp->next)
{
info = EXO_ICON_VIEW_CELL_INFO (lp->data);
if (G_UNLIKELY (!gtk_cell_renderer_get_visible (info->cell)))
continue;
gtk_cell_renderer_get_size (info->cell, GTK_WIDGET (icon_view),
NULL, NULL, NULL,
&item->box[info->position].width,
&item->box[info->position].height);
if (icon_view->priv->orientation == GTK_ORIENTATION_HORIZONTAL)
{
item->area.width += item->box[info->position].width + (info->position > 0 ? icon_view->priv->spacing : 0);
item->area.height = MAX (item->area.height, item->box[info->position].height);
}
else
{
item->area.width = MAX (item->area.width, item->box[info->position].width);
item->area.height += item->box[info->position].height + (info->position > 0 ? icon_view->priv->spacing : 0);
}
}
}
static void
exo_icon_view_calculate_item_size2 (ExoIconView *icon_view,
ExoIconViewItem *item,
gint *max_width,
gint *max_height)
{
ExoIconViewCellInfo *info;
GdkRectangle *box;
GdkRectangle cell_area;
gboolean rtl;
gfloat xalign, yalign;
GList *lp;
gint spacing;
gint i, k;
gint xpad, ypad;
rtl = (gtk_widget_get_direction (GTK_WIDGET (icon_view)) == GTK_TEXT_DIR_RTL);
spacing = icon_view->priv->spacing;
if (G_LIKELY (icon_view->priv->layout_mode == EXO_ICON_VIEW_LAYOUT_ROWS))
{
item->area.height = 0;
for (i = 0; i < icon_view->priv->n_cells; ++i)
{
if (icon_view->priv->orientation == GTK_ORIENTATION_HORIZONTAL)
item->area.height = MAX (item->area.height, max_height[i]);
else
item->area.height += max_height[i] + (i > 0 ? spacing : 0);
}
}
else
{
item->area.width = 0;
for (i = 0; i < icon_view->priv->n_cells; ++i)
{
if (icon_view->priv->orientation == GTK_ORIENTATION_HORIZONTAL)
item->area.width += max_width[i] + (i > 0 ? spacing : 0);
else
item->area.width = MAX (item->area.width, max_width[i]);
}
}
cell_area.x = item->area.x;
cell_area.y = item->area.y;
for (k = 0; k < 2; ++k)
{
for (lp = icon_view->priv->cell_list, i = 0; lp != NULL; lp = lp->next, ++i)
{
info = EXO_ICON_VIEW_CELL_INFO (lp->data);
if (G_UNLIKELY (!gtk_cell_renderer_get_visible (info->cell) || info->pack == (k ? GTK_PACK_START : GTK_PACK_END)))
continue;
if (icon_view->priv->orientation == GTK_ORIENTATION_HORIZONTAL)
{
cell_area.width = item->box[info->position].width;
cell_area.height = item->area.height;
}
else
{
cell_area.width = item->area.width;
cell_area.height = max_height[i];
}
gtk_cell_renderer_get_alignment (info->cell, &xalign, &yalign);
gtk_cell_renderer_get_padding (info->cell, &xpad, &ypad);
box = item->box + info->position;
box->x = cell_area.x + (rtl ? (1.0 - xalign) : xalign) * (cell_area.width - box->width - (2 * xpad));
box->x = MAX (box->x, 0);
box->y = cell_area.y + yalign * (cell_area.height - box->height - (2 * ypad));
box->y = MAX (box->y, 0);
if (icon_view->priv->orientation == GTK_ORIENTATION_HORIZONTAL)
{
item->before[info->position] = item->box[info->position].x - cell_area.x;
item->after[info->position] = cell_area.width - item->box[info->position].width - item->before[info->position];
cell_area.x += cell_area.width + spacing;
}
else
{
if (item->box[info->position].width > item->area.width)
{
item->area.width = item->box[info->position].width;
cell_area.width = item->area.width;
}
item->before[info->position] = item->box[info->position].y - cell_area.y;
item->after[info->position] = cell_area.height - item->box[info->position].height - item->before[info->position];
cell_area.y += cell_area.height + spacing;
}
}
}
if (G_UNLIKELY (rtl && icon_view->priv->orientation == GTK_ORIENTATION_HORIZONTAL))
{
for (i = 0; i < icon_view->priv->n_cells; i++)
item->box[i].x = item->area.x + item->area.width - (item->box[i].x + item->box[i].width - item->area.x);
}
}
static void
exo_icon_view_invalidate_sizes (ExoIconView *icon_view)
{
GList *lp;
for (lp = icon_view->priv->items; lp != NULL; lp = lp->next)
EXO_ICON_VIEW_ITEM (lp->data)->area.width = -1;
exo_icon_view_queue_layout (icon_view);
}
static void
exo_icon_view_paint_item (ExoIconView *icon_view,
ExoIconViewItem *item,
GdkRectangle *area,
#if GTK_CHECK_VERSION (3, 0, 0)
cairo_t *cr,
#else
GdkDrawable *drawable,
#endif
gint x,
gint y,
gboolean draw_focus)
{
GtkCellRendererState flags;
ExoIconViewCellInfo *info;
GtkStateType state;
GdkRectangle cell_area;
gboolean rtl;
GList *lp;
if (G_UNLIKELY (icon_view->priv->model == NULL))
return;
exo_icon_view_set_cell_data (icon_view, item);
rtl = gtk_widget_get_direction (GTK_WIDGET (icon_view)) == GTK_TEXT_DIR_RTL;
if (item->selected)
{
flags = GTK_CELL_RENDERER_SELECTED;
state = gtk_widget_has_focus (GTK_WIDGET (icon_view)) ? GTK_STATE_SELECTED : GTK_STATE_ACTIVE;
}
else
{
flags = 0;
state = GTK_STATE_NORMAL;
}
if (G_UNLIKELY (icon_view->priv->prelit_item == item))
flags |= GTK_CELL_RENDERER_PRELIT;
/* NOTE by Hong Jen Yee: We always want to focus rectangle. */
if (G_UNLIKELY (/*EXO_ICON_VIEW_FLAG_SET (icon_view, EXO_ICON_VIEW_DRAW_KEYFOCUS) &&*/ icon_view->priv->cursor_item == item))
flags |= GTK_CELL_RENDERER_FOCUSED;
#ifdef DEBUG_ICON_VIEW
gdk_draw_rectangle (drawable,
GTK_WIDGET (icon_view)->style->black_gc,
FALSE,
x, y,
item->area.width, item->area.height);
#endif
for (lp = icon_view->priv->cell_list; lp != NULL; lp = lp->next)
{
info = EXO_ICON_VIEW_CELL_INFO (lp->data);
if (G_UNLIKELY (!gtk_cell_renderer_get_visible (info->cell)))
continue;
exo_icon_view_get_cell_area (icon_view, item, info, &cell_area);
#ifdef DEBUG_ICON_VIEW
gdk_draw_rectangle (drawable,
GTK_WIDGET (icon_view)->style->black_gc,
FALSE,
x - item->area.x + cell_area.x,
y - item->area.y + cell_area.y,
cell_area.width, cell_area.height);
gdk_draw_rectangle (drawable,
GTK_WIDGET (icon_view)->style->black_gc,
FALSE,
x - item->area.x + item->box[info->position].x,
y - item->area.y + item->box[info->position].y,
item->box[info->position].width, item->box[info->position].height);
#endif
cell_area.x = x - item->area.x + cell_area.x;
cell_area.y = y - item->area.y + cell_area.y;
#if GTK_CHECK_VERSION (3, 0, 0)
gtk_cell_renderer_render (info->cell,
cr,
GTK_WIDGET (icon_view),
&cell_area, &cell_area, flags);
#else
gtk_cell_renderer_render (info->cell,
drawable,
GTK_WIDGET (icon_view),
&cell_area, &cell_area, area, flags);
#endif
}
}
static void
exo_icon_view_queue_draw_item (ExoIconView *icon_view,
ExoIconViewItem *item)
{
GdkRectangle rect;
gint focus_width;
gtk_widget_style_get (GTK_WIDGET (icon_view),
"focus-line-width", &focus_width,
NULL);
rect.x = item->area.x - focus_width;
rect.y = item->area.y - focus_width;
rect.width = item->area.width + 2 * focus_width;
rect.height = item->area.height + 2 * focus_width;
if (icon_view->priv->bin_window)
gdk_window_invalidate_rect (icon_view->priv->bin_window, &rect, TRUE);
}
static gboolean
layout_callback (gpointer user_data)
{
ExoIconView *icon_view = EXO_ICON_VIEW (user_data);
GDK_THREADS_ENTER ();
exo_icon_view_layout (icon_view);
GDK_THREADS_LEAVE();
return FALSE;
}
static void
layout_destroy (gpointer user_data)
{
EXO_ICON_VIEW (user_data)->priv->layout_idle_id = 0;
}
static void
exo_icon_view_queue_layout (ExoIconView *icon_view)
{
if (G_UNLIKELY (icon_view->priv->layout_idle_id == 0))
icon_view->priv->layout_idle_id = g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, layout_callback, icon_view, layout_destroy);
}
static void
exo_icon_view_set_cursor_item (ExoIconView *icon_view,
ExoIconViewItem *item,
gint cursor_cell)
{
if (icon_view->priv->cursor_item == item &&
(cursor_cell < 0 || cursor_cell == icon_view->priv->cursor_cell))
return;
if (icon_view->priv->cursor_item != NULL)
exo_icon_view_queue_draw_item (icon_view, icon_view->priv->cursor_item);
icon_view->priv->cursor_item = item;
if (cursor_cell >= 0)
icon_view->priv->cursor_cell = cursor_cell;
exo_icon_view_queue_draw_item (icon_view, item);
}
static ExoIconViewItem*
exo_icon_view_get_item_at_coords (const ExoIconView *icon_view,
gint x,
gint y,
gboolean only_in_cell,
ExoIconViewCellInfo **cell_at_pos)
{
const ExoIconViewPrivate *priv = icon_view->priv;
ExoIconViewCellInfo *info;
ExoIconViewItem *item;
GdkRectangle box;
const GList *items;
const GList *lp;
for (items = priv->items; items != NULL; items = items->next)
{
item = items->data;
if (x >= item->area.x - priv->row_spacing / 2 && x <= item->area.x + item->area.width + priv->row_spacing / 2 &&
y >= item->area.y - priv->column_spacing / 2 && y <= item->area.y + item->area.height + priv->column_spacing / 2)
{
if (only_in_cell || cell_at_pos)
{
exo_icon_view_set_cell_data (icon_view, item);
for (lp = priv->cell_list; lp != NULL; lp = lp->next)
{
/* check if the cell is visible */
info = (ExoIconViewCellInfo *) lp->data;
if (!gtk_cell_renderer_get_visible (info->cell))
continue;
box = item->box[info->position];
if ((x >= box.x && x <= box.x + box.width &&
y >= box.y && y <= box.y + box.height) ||
(x >= box.x &&
x <= box.x + box.width &&
y >= box.y &&
y <= box.y + box.height))
{
if (cell_at_pos != NULL)
*cell_at_pos = info;
return item;
}
}
if (only_in_cell)
return NULL;
if (cell_at_pos != NULL)
*cell_at_pos = NULL;
}
return item;
}
}
return NULL;
}
static void
exo_icon_view_select_item (ExoIconView *icon_view,
ExoIconViewItem *item)
{
if (item->selected || icon_view->priv->selection_mode == GTK_SELECTION_NONE)
return;
else if (icon_view->priv->selection_mode != GTK_SELECTION_MULTIPLE)
exo_icon_view_unselect_all_internal (icon_view);
item->selected = TRUE;
exo_icon_view_queue_draw_item (icon_view, item);
g_signal_emit (icon_view, icon_view_signals[SELECTION_CHANGED], 0);
}
static void
exo_icon_view_unselect_item (ExoIconView *icon_view,
ExoIconViewItem *item)
{
if (!item->selected)
return;
if (icon_view->priv->selection_mode == GTK_SELECTION_NONE ||
icon_view->priv->selection_mode == GTK_SELECTION_BROWSE)
return;
item->selected = FALSE;
g_signal_emit (G_OBJECT (icon_view), icon_view_signals[SELECTION_CHANGED], 0);
exo_icon_view_queue_draw_item (icon_view, item);
}
static void
exo_icon_view_row_changed (GtkTreeModel *model,
GtkTreePath *path,
GtkTreeIter *iter,
ExoIconView *icon_view)
{
ExoIconViewItem *item;
item = g_list_nth_data (icon_view->priv->items, gtk_tree_path_get_indices(path)[0]);
/* stop editing this item */
if (G_UNLIKELY (item == icon_view->priv->edited_item))
exo_icon_view_stop_editing (icon_view, TRUE);
/* emit "selection-changed" if the item is selected */
if (G_UNLIKELY (item->selected))
g_signal_emit (icon_view, icon_view_signals[SELECTION_CHANGED], 0);
/* recalculate layout (a value of -1 for width
* indicates that the item needs to be layouted).
*/
item->area.width = -1;
exo_icon_view_queue_layout (icon_view);
}
static void
exo_icon_view_row_inserted (GtkTreeModel *model,
GtkTreePath *path,
GtkTreeIter *iter,
ExoIconView *icon_view)
{
ExoIconViewItem *item;
gint index;
index = gtk_tree_path_get_indices (path)[0];
/* allocate the new item */
item = _exo_slice_new0 (ExoIconViewItem);
item->iter = *iter;
item->area.width = -1;
icon_view->priv->items = g_list_insert (icon_view->priv->items, item, index);
/* recalculate the layout */
exo_icon_view_queue_layout (icon_view);
}
static void
exo_icon_view_row_deleted (GtkTreeModel *model,
GtkTreePath *path,
ExoIconView *icon_view)
{
ExoIconViewItem *item;
gboolean changed = FALSE;
GList *list;
/* determine the position and the item for the path */
list = g_list_nth (icon_view->priv->items, gtk_tree_path_get_indices (path)[0]);
item = list->data;
if (G_UNLIKELY (item == icon_view->priv->edited_item))
exo_icon_view_stop_editing (icon_view, TRUE);
/* use the next item (if any) as anchor, else use prev, otherwise reset anchor */
if (G_UNLIKELY (item == icon_view->priv->anchor_item))
icon_view->priv->anchor_item = (list->next != NULL) ? list->next->data : ((list->prev != NULL) ? list->prev->data : NULL);
/* use the next item (if any) as cursor, else use prev, otherwise reset cursor */
if (G_UNLIKELY (item == icon_view->priv->cursor_item))
icon_view->priv->cursor_item = (list->next != NULL) ? list->next->data : ((list->prev != NULL) ? list->prev->data : NULL);
if (G_UNLIKELY (item == icon_view->priv->prelit_item))
{
/* reset the prelit item */
icon_view->priv->prelit_item = NULL;
/* cancel any pending single click timer */
if (G_UNLIKELY (icon_view->priv->single_click_timeout_id != 0))
g_source_remove (icon_view->priv->single_click_timeout_id);
/* in single click mode, we also reset the cursor when realized */
if (G_UNLIKELY (icon_view->priv->single_click && gtk_widget_get_realized (GTK_WIDGET (icon_view))))
gdk_window_set_cursor (icon_view->priv->bin_window, NULL);
}
/* check if the selection changed */
if (G_UNLIKELY (item->selected))
changed = TRUE;
/* release the item resources */
g_free (item->box);
/* drop the item from the list */
icon_view->priv->items = g_list_delete_link (icon_view->priv->items, list);
/* release the item */
_exo_slice_free (ExoIconViewItem, item);
/* recalculate the layout */
exo_icon_view_queue_layout (icon_view);
/* if we removed a previous selected item, we need
* to tell others that we have a new selection.
*/
if (G_UNLIKELY (changed))
g_signal_emit (G_OBJECT (icon_view), icon_view_signals[SELECTION_CHANGED], 0);
}
static void
exo_icon_view_rows_reordered (GtkTreeModel *model,
GtkTreePath *parent,
GtkTreeIter *iter,
gint *new_order,
ExoIconView *icon_view)
{
GList **list_array;
GList *list;
gint *order;
gint length;
gint i;
/* cancel any editing attempt */
exo_icon_view_stop_editing (icon_view, TRUE);
/* determine the number of items to reorder */
length = gtk_tree_model_iter_n_children (model, NULL);
if (G_UNLIKELY (length == 0))
return;
list_array = g_newa (GList *, length);
order = g_newa (gint, length);
for (i = 0; i < length; i++)
order[new_order[i]] = i;
for (i = 0, list = icon_view->priv->items; list != NULL; list = list->next, i++)
list_array[order[i]] = list;
/* hook up the first item */
icon_view->priv->items = list_array[0];
list_array[0]->prev = NULL;
/* hook up the remaining items */
for (i = 1; i < length; ++i)
{
list_array[i - 1]->next = list_array[i];
list_array[i]->prev = list_array[i - 1];
}
/* hook up the last item */
list_array[length - 1]->next = NULL;
exo_icon_view_queue_layout (icon_view);
}
static void
exo_icon_view_add_move_binding (GtkBindingSet *binding_set,
guint keyval,
guint modmask,
GtkMovementStep step,
gint count)
{
gtk_binding_entry_add_signal (binding_set, keyval, modmask, "move-cursor", 2, G_TYPE_ENUM, step, G_TYPE_INT, count);
gtk_binding_entry_add_signal (binding_set, keyval, GDK_SHIFT_MASK, "move-cursor", 2, G_TYPE_ENUM, step, G_TYPE_INT, count);
if ((modmask & GDK_CONTROL_MASK) != GDK_CONTROL_MASK)
{
gtk_binding_entry_add_signal (binding_set, keyval, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "move-cursor", 2, G_TYPE_ENUM, step, G_TYPE_INT, count);
gtk_binding_entry_add_signal (binding_set, keyval, GDK_CONTROL_MASK, "move-cursor", 2, G_TYPE_ENUM, step, G_TYPE_INT, count);
}
}
static gboolean
exo_icon_view_real_move_cursor (ExoIconView *icon_view,
GtkMovementStep step,
gint count)
{
GdkModifierType state;
_exo_return_val_if_fail (EXO_ICON_VIEW (icon_view), FALSE);
_exo_return_val_if_fail (step == GTK_MOVEMENT_LOGICAL_POSITIONS ||
step == GTK_MOVEMENT_VISUAL_POSITIONS ||
step == GTK_MOVEMENT_DISPLAY_LINES ||
step == GTK_MOVEMENT_PAGES ||
step == GTK_MOVEMENT_BUFFER_ENDS, FALSE);
if (!gtk_widget_has_focus (GTK_WIDGET (icon_view)))
return FALSE;
exo_icon_view_stop_editing (icon_view, FALSE);
EXO_ICON_VIEW_SET_FLAG (icon_view, EXO_ICON_VIEW_DRAW_KEYFOCUS);
gtk_widget_grab_focus (GTK_WIDGET (icon_view));
if (gtk_get_current_event_state (&state))
{
if ((state & GDK_CONTROL_MASK) == GDK_CONTROL_MASK)
icon_view->priv->ctrl_pressed = TRUE;
if ((state & GDK_SHIFT_MASK) == GDK_SHIFT_MASK)
icon_view->priv->shift_pressed = TRUE;
}
/* else we assume not pressed */
switch (step)
{
case GTK_MOVEMENT_LOGICAL_POSITIONS:
case GTK_MOVEMENT_VISUAL_POSITIONS:
exo_icon_view_move_cursor_left_right (icon_view, count);
break;
case GTK_MOVEMENT_DISPLAY_LINES:
exo_icon_view_move_cursor_up_down (icon_view, count);
break;
case GTK_MOVEMENT_PAGES:
exo_icon_view_move_cursor_page_up_down (icon_view, count);
break;
case GTK_MOVEMENT_BUFFER_ENDS:
exo_icon_view_move_cursor_start_end (icon_view, count);
break;
default:
g_assert_not_reached ();
}
icon_view->priv->ctrl_pressed = FALSE;
icon_view->priv->shift_pressed = FALSE;
return TRUE;
}
static gint
find_cell (ExoIconView *icon_view,
ExoIconViewItem *item,
gint cell,
GtkOrientation orientation,
gint step,
gint *count)
{
GtkCellRendererMode mode;
gint n_focusable;
gint *focusable;
gint first_text;
gint current;
gint i, k;
GList *l;
if (icon_view->priv->orientation != orientation)
return cell;
exo_icon_view_set_cell_data (icon_view, item);
focusable = g_new0 (gint, icon_view->priv->n_cells);
n_focusable = 0;
first_text = 0;
current = 0;
for (k = 0; k < 2; k++)
for (l = icon_view->priv->cell_list, i = 0; l; l = l->next, i++)
{
ExoIconViewCellInfo *info = (ExoIconViewCellInfo *)l->data;
if (info->pack == (k ? GTK_PACK_START : GTK_PACK_END))
continue;
if (!gtk_cell_renderer_get_visible (info->cell))
continue;
if (GTK_IS_CELL_RENDERER_TEXT (info->cell))
first_text = i;
g_object_get (G_OBJECT (info->cell), "mode", &mode, NULL);
if (mode != GTK_CELL_RENDERER_MODE_INERT)
{
if (cell == i)
current = n_focusable;
focusable[n_focusable] = i;
n_focusable++;
}
}
if (n_focusable == 0)
focusable[n_focusable++] = first_text;
if (cell < 0)
{
current = step > 0 ? 0 : n_focusable - 1;
cell = focusable[current];
}
if (current + *count < 0)
{
cell = -1;
*count = current + *count;
}
else if (current + *count > n_focusable - 1)
{
cell = -1;
*count = current + *count - (n_focusable - 1);
}
else
{
cell = focusable[current + *count];
*count = 0;
}
g_free (focusable);
return cell;
}
static ExoIconViewItem *
find_item_page_up_down (ExoIconView *icon_view,
ExoIconViewItem *current,
gint count)
{
GList *item = g_list_find (icon_view->priv->items, current);
GList *next;
gint col = current->col;
gint y = current->area.y + count * gtk_adjustment_get_page_size (icon_view->priv->vadjustment);
if (count > 0)
{
for (; item != NULL; item = item->next)
{
for (next = item->next; next; next = next->next)
if (EXO_ICON_VIEW_ITEM (next->data)->col == col)
break;
if (next == NULL || EXO_ICON_VIEW_ITEM (next->data)->area.y > y)
break;
}
}
else
{
for (; item != NULL; item = item->prev)
{
for (next = item->prev; next; next = next->prev)
if (EXO_ICON_VIEW_ITEM (next->data)->col == col)
break;
if (next == NULL || EXO_ICON_VIEW_ITEM (next->data)->area.y < y)
break;
}
}
return (item != NULL) ? item->data : NULL;
}
static gboolean
exo_icon_view_select_all_between (ExoIconView *icon_view,
ExoIconViewItem *anchor,
ExoIconViewItem *cursor)
{
GList *items;
ExoIconViewItem *item, *last;
gboolean dirty = FALSE;
for (items = icon_view->priv->items; items; items = items->next)
{
item = items->data;
if (item == anchor)
{
last = cursor;
break;
}
else if (item == cursor)
{
last = anchor;
break;
}
}
for (; items; items = items->next)
{
item = items->data;
if (!item->selected)
dirty = TRUE;
item->selected = TRUE;
exo_icon_view_queue_draw_item (icon_view, item);
if (item == last)
break;
}
return dirty;
}
static void
exo_icon_view_move_cursor_up_down (ExoIconView *icon_view,
gint count)
{
ExoIconViewItem *item;
gboolean dirty = FALSE;
GList *list;
gint cell = -1;
gint step;
if (!gtk_widget_has_focus (GTK_WIDGET (icon_view)))
return;
if (!icon_view->priv->cursor_item)
{
if (count > 0)
list = icon_view->priv->items;
else
list = g_list_last (icon_view->priv->items);
item = list ? list->data : NULL;
}
else
{
item = icon_view->priv->cursor_item;
cell = icon_view->priv->cursor_cell;
step = count > 0 ? 1 : -1;
while (item)
{
cell = find_cell (icon_view, item, cell,
GTK_ORIENTATION_VERTICAL,
step, &count);
if (count == 0)
break;
/* determine the list position for the item */
list = g_list_find (icon_view->priv->items, item);
if (G_LIKELY (icon_view->priv->layout_mode == EXO_ICON_VIEW_LAYOUT_ROWS))
{
/* determine the item in the next/prev row */
if (step > 0)
{
for (list = list->next; list != NULL; list = list->next)
if (EXO_ICON_VIEW_ITEM (list->data)->row == item->row + step
&& EXO_ICON_VIEW_ITEM (list->data)->col == item->col)
break;
}
else
{
for (list = list->prev; list != NULL; list = list->prev)
if (EXO_ICON_VIEW_ITEM (list->data)->row == item->row + step
&& EXO_ICON_VIEW_ITEM (list->data)->col == item->col)
break;
}
}
else
{
list = (step > 0) ? list->next : list->prev;
}
/* check if we found a matching item */
item = (list != NULL) ? list->data : NULL;
count = count - step;
}
}
if (!item)
return;
if (icon_view->priv->ctrl_pressed ||
!icon_view->priv->shift_pressed ||
!icon_view->priv->anchor_item ||
icon_view->priv->selection_mode != GTK_SELECTION_MULTIPLE)
icon_view->priv->anchor_item = item;
exo_icon_view_set_cursor_item (icon_view, item, cell);
if (!icon_view->priv->ctrl_pressed &&
icon_view->priv->selection_mode != GTK_SELECTION_NONE)
{
dirty = exo_icon_view_unselect_all_internal (icon_view);
dirty = exo_icon_view_select_all_between (icon_view,
icon_view->priv->anchor_item,
item) || dirty;
}
exo_icon_view_scroll_to_item (icon_view, item);
if (dirty)
g_signal_emit (icon_view, icon_view_signals[SELECTION_CHANGED], 0);
}
static void
exo_icon_view_move_cursor_page_up_down (ExoIconView *icon_view,
gint count)
{
ExoIconViewItem *item;
gboolean dirty = FALSE;
if (!gtk_widget_has_focus (GTK_WIDGET (icon_view)))
return;
if (!icon_view->priv->cursor_item)
{
GList *list;
if (count > 0)
list = icon_view->priv->items;
else
list = g_list_last (icon_view->priv->items);
item = list ? list->data : NULL;
}
else
item = find_item_page_up_down (icon_view,
icon_view->priv->cursor_item,
count);
if (!item)
return;
if (icon_view->priv->ctrl_pressed ||
!icon_view->priv->shift_pressed ||
!icon_view->priv->anchor_item ||
icon_view->priv->selection_mode != GTK_SELECTION_MULTIPLE)
icon_view->priv->anchor_item = item;
exo_icon_view_set_cursor_item (icon_view, item, -1);
if (!icon_view->priv->ctrl_pressed &&
icon_view->priv->selection_mode != GTK_SELECTION_NONE)
{
dirty = exo_icon_view_unselect_all_internal (icon_view);
dirty = exo_icon_view_select_all_between (icon_view,
icon_view->priv->anchor_item,
item) || dirty;
}
exo_icon_view_scroll_to_item (icon_view, item);
if (dirty)
g_signal_emit (icon_view, icon_view_signals[SELECTION_CHANGED], 0);
}
static void
exo_icon_view_move_cursor_left_right (ExoIconView *icon_view,
gint count)
{
ExoIconViewItem *item;
gboolean dirty = FALSE;
GList *list;
gint cell = -1;
gint step;
if (!gtk_widget_has_focus (GTK_WIDGET (icon_view)))
return;
if (!icon_view->priv->cursor_item)
{
if (count > 0)
list = icon_view->priv->items;
else
list = g_list_last (icon_view->priv->items);
item = list ? list->data : NULL;
}
else
{
item = icon_view->priv->cursor_item;
cell = icon_view->priv->cursor_cell;
step = count > 0 ? 1 : -1;
while (item)
{
cell = find_cell (icon_view, item, cell,
GTK_ORIENTATION_HORIZONTAL,
step, &count);
if (count == 0)
break;
/* lookup the item in the list */
list = g_list_find (icon_view->priv->items, item);
if (G_LIKELY (icon_view->priv->layout_mode == EXO_ICON_VIEW_LAYOUT_ROWS))
{
/* determine the next/prev list item depending on step,
* support wrapping around on the edges, as requested
* in http://bugzilla.xfce.org/show_bug.cgi?id=1623.
*/
list = (step > 0) ? list->next : list->prev;
}
else
{
/* determine the item in the next/prev row */
if (step > 0)
{
for (list = list->next; list != NULL; list = list->next)
if (EXO_ICON_VIEW_ITEM (list->data)->col == item->col + step
&& EXO_ICON_VIEW_ITEM (list->data)->row == item->row)
break;
}
else
{
for (list = list->prev; list != NULL; list = list->prev)
if (EXO_ICON_VIEW_ITEM (list->data)->col == item->col + step
&& EXO_ICON_VIEW_ITEM (list->data)->row == item->row)
break;
}
}
/* determine the item for the list position (if any) */
item = (list != NULL) ? list->data : NULL;
count = count - step;
}
}
if (!item)
return;
if (icon_view->priv->ctrl_pressed ||
!icon_view->priv->shift_pressed ||
!icon_view->priv->anchor_item ||
icon_view->priv->selection_mode != GTK_SELECTION_MULTIPLE)
icon_view->priv->anchor_item = item;
exo_icon_view_set_cursor_item (icon_view, item, cell);
if (!icon_view->priv->ctrl_pressed &&
icon_view->priv->selection_mode != GTK_SELECTION_NONE)
{
dirty = exo_icon_view_unselect_all_internal (icon_view);
dirty = exo_icon_view_select_all_between (icon_view,
icon_view->priv->anchor_item,
item) || dirty;
}
exo_icon_view_scroll_to_item (icon_view, item);
if (dirty)
g_signal_emit (icon_view, icon_view_signals[SELECTION_CHANGED], 0);
}
static void
exo_icon_view_move_cursor_start_end (ExoIconView *icon_view,
gint count)
{
ExoIconViewItem *item;
gboolean dirty = FALSE;
GList *lp;
if (!gtk_widget_has_focus (GTK_WIDGET (icon_view)))
return;
lp = (count < 0) ? icon_view->priv->items : g_list_last (icon_view->priv->items);
if (G_UNLIKELY (lp == NULL))
return;
item = EXO_ICON_VIEW_ITEM (lp->data);
if (icon_view->priv->ctrl_pressed ||
!icon_view->priv->shift_pressed ||
!icon_view->priv->anchor_item ||
icon_view->priv->selection_mode != GTK_SELECTION_MULTIPLE)
icon_view->priv->anchor_item = item;
exo_icon_view_set_cursor_item (icon_view, item, -1);
if (!icon_view->priv->ctrl_pressed &&
icon_view->priv->selection_mode != GTK_SELECTION_NONE)
{
dirty = exo_icon_view_unselect_all_internal (icon_view);
dirty = exo_icon_view_select_all_between (icon_view,
icon_view->priv->anchor_item,
item) || dirty;
}
exo_icon_view_scroll_to_item (icon_view, item);
if (G_UNLIKELY (dirty))
g_signal_emit (icon_view, icon_view_signals[SELECTION_CHANGED], 0);
}
static void
exo_icon_view_scroll_to_item (ExoIconView *icon_view,
ExoIconViewItem *item)
{
GtkAllocation allocation;
gint x, y, width, height;
gint focus_width;
gtk_widget_style_get (GTK_WIDGET (icon_view),
"focus-line-width", &focus_width,
NULL);
gtk_widget_get_allocation (GTK_WIDGET (icon_view), &allocation);
width = gdk_window_get_width(icon_view->priv->bin_window);
height = gdk_window_get_height(icon_view->priv->bin_window);
gdk_window_get_position (icon_view->priv->bin_window, &x, &y);
if (y + item->area.y - focus_width < 0)
gtk_adjustment_set_value (icon_view->priv->vadjustment,
gtk_adjustment_get_value (icon_view->priv->vadjustment) + y + item->area.y - focus_width);
else if (y + item->area.y + item->area.height + focus_width > allocation.height)
gtk_adjustment_set_value (icon_view->priv->vadjustment,
gtk_adjustment_get_value (icon_view->priv->vadjustment) + y + item->area.y + item->area.height
+ focus_width - allocation.height);
if (x + item->area.x - focus_width < 0)
{
gtk_adjustment_set_value (icon_view->priv->hadjustment,
gtk_adjustment_get_value (icon_view->priv->hadjustment) + x + item->area.x - focus_width);
}
else if (x + item->area.x + item->area.width + focus_width > allocation.width
&& item->area.width < allocation.width)
{
/* the second condition above is to make sure that we don't scroll horizontally if the item
* width is larger than the allocation width. Fixes a weird scrolling bug in the compact view.
* See http://bugzilla.xfce.org/show_bug.cgi?id=1683 for details.
*/
gtk_adjustment_set_value (icon_view->priv->hadjustment,
gtk_adjustment_get_value (icon_view->priv->hadjustment) + x + item->area.x + item->area.width
+ focus_width - allocation.width);
}
gtk_adjustment_changed (icon_view->priv->hadjustment);
gtk_adjustment_changed (icon_view->priv->vadjustment);
}
static ExoIconViewCellInfo *
exo_icon_view_get_cell_info (ExoIconView *icon_view,
GtkCellRenderer *renderer)
{
GList *lp;
for (lp = icon_view->priv->cell_list; lp != NULL; lp = lp->next)
if (EXO_ICON_VIEW_CELL_INFO (lp->data)->cell == renderer)
return lp->data;
return NULL;
}
static void
exo_icon_view_set_cell_data (const ExoIconView *icon_view,
ExoIconViewItem *item)
{
ExoIconViewCellInfo *info;
GtkTreePath *path;
GtkTreeIter iter;
GValue value = {0, };
GSList *slp;
GList *lp;
if (G_UNLIKELY (!EXO_ICON_VIEW_FLAG_SET (icon_view, EXO_ICON_VIEW_ITERS_PERSIST)))
{
path = gtk_tree_path_new_from_indices (g_list_index (icon_view->priv->items, item), -1);
gtk_tree_model_get_iter (icon_view->priv->model, &iter, path);
gtk_tree_path_free (path);
}
else
{
iter = item->iter;
}
for (lp = icon_view->priv->cell_list; lp != NULL; lp = lp->next)
{
info = EXO_ICON_VIEW_CELL_INFO (lp->data);
for (slp = info->attributes; slp != NULL && slp->next != NULL; slp = slp->next->next)
{
gtk_tree_model_get_value (icon_view->priv->model, &iter, GPOINTER_TO_INT (slp->next->data), &value);
g_object_set_property (G_OBJECT (info->cell), slp->data, &value);
g_value_unset (&value);
}
if (G_UNLIKELY (info->func != NULL))
(*info->func) (GTK_CELL_LAYOUT (icon_view), info->cell, icon_view->priv->model, &iter, info->func_data);
}
}
static void
free_cell_attributes (ExoIconViewCellInfo *info)
{
GSList *lp;
for (lp = info->attributes; lp != NULL && lp->next != NULL; lp = lp->next->next)
g_free (lp->data);
g_slist_free (info->attributes);
info->attributes = NULL;
}
static void
free_cell_info (ExoIconViewCellInfo *info)
{
if (G_UNLIKELY (info->destroy != NULL))
(*info->destroy) (info->func_data);
free_cell_attributes (info);
g_object_unref (G_OBJECT (info->cell));
_exo_slice_free (ExoIconViewCellInfo, info);
}
static void
exo_icon_view_cell_layout_pack_start (GtkCellLayout *layout,
GtkCellRenderer *renderer,
gboolean expand)
{
ExoIconViewCellInfo *info;
ExoIconView *icon_view = EXO_ICON_VIEW (layout);
_exo_return_if_fail (GTK_IS_CELL_RENDERER (renderer));
_exo_return_if_fail (exo_icon_view_get_cell_info (icon_view, renderer) == NULL);
g_object_ref (renderer);
g_object_ref_sink (G_OBJECT (renderer));
info = _exo_slice_new0 (ExoIconViewCellInfo);
info->cell = renderer;
info->expand = expand ? TRUE : FALSE;
info->pack = GTK_PACK_START;
info->position = icon_view->priv->n_cells;
icon_view->priv->cell_list = g_list_append (icon_view->priv->cell_list, info);
icon_view->priv->n_cells++;
exo_icon_view_invalidate_sizes (icon_view);
}
static void
exo_icon_view_cell_layout_pack_end (GtkCellLayout *layout,
GtkCellRenderer *renderer,
gboolean expand)
{
ExoIconViewCellInfo *info;
ExoIconView *icon_view = EXO_ICON_VIEW (layout);
_exo_return_if_fail (GTK_IS_CELL_RENDERER (renderer));
_exo_return_if_fail (exo_icon_view_get_cell_info (icon_view, renderer) == NULL);
g_object_ref (renderer);
g_object_ref_sink (G_OBJECT (renderer));
info = _exo_slice_new0 (ExoIconViewCellInfo);
info->cell = renderer;
info->expand = expand ? TRUE : FALSE;
info->pack = GTK_PACK_END;
info->position = icon_view->priv->n_cells;
icon_view->priv->cell_list = g_list_append (icon_view->priv->cell_list, info);
icon_view->priv->n_cells++;
exo_icon_view_invalidate_sizes (icon_view);
}
static void
exo_icon_view_cell_layout_add_attribute (GtkCellLayout *layout,
GtkCellRenderer *renderer,
const gchar *attribute,
gint column)
{
ExoIconViewCellInfo *info;
info = exo_icon_view_get_cell_info (EXO_ICON_VIEW (layout), renderer);
if (G_LIKELY (info != NULL))
{
info->attributes = g_slist_prepend (info->attributes, GINT_TO_POINTER (column));
info->attributes = g_slist_prepend (info->attributes, g_strdup (attribute));
exo_icon_view_invalidate_sizes (EXO_ICON_VIEW (layout));
}
}
static void
exo_icon_view_cell_layout_clear (GtkCellLayout *layout)
{
ExoIconView *icon_view = EXO_ICON_VIEW (layout);
g_list_foreach (icon_view->priv->cell_list, (GFunc) free_cell_info, NULL);
g_list_free (icon_view->priv->cell_list);
icon_view->priv->cell_list = NULL;
icon_view->priv->n_cells = 0;
exo_icon_view_invalidate_sizes (icon_view);
}
static void
exo_icon_view_cell_layout_set_cell_data_func (GtkCellLayout *layout,
GtkCellRenderer *cell,
GtkCellLayoutDataFunc func,
gpointer func_data,
GDestroyNotify destroy)
{
ExoIconViewCellInfo *info;
GDestroyNotify notify;
info = exo_icon_view_get_cell_info (EXO_ICON_VIEW (layout), cell);
if (G_LIKELY (info != NULL))
{
if (G_UNLIKELY (info->destroy != NULL))
{
notify = info->destroy;
info->destroy = NULL;
(*notify) (info->func_data);
}
info->func = func;
info->func_data = func_data;
info->destroy = destroy;
exo_icon_view_invalidate_sizes (EXO_ICON_VIEW (layout));
}
}
static void
exo_icon_view_cell_layout_clear_attributes (GtkCellLayout *layout,
GtkCellRenderer *renderer)
{
ExoIconViewCellInfo *info;
info = exo_icon_view_get_cell_info (EXO_ICON_VIEW (layout), renderer);
if (G_LIKELY (info != NULL))
{
free_cell_attributes (info);
exo_icon_view_invalidate_sizes (EXO_ICON_VIEW (layout));
}
}
static void
exo_icon_view_cell_layout_reorder (GtkCellLayout *layout,
GtkCellRenderer *cell,
gint position)
{
ExoIconViewCellInfo *info;
ExoIconView *icon_view = EXO_ICON_VIEW (layout);
GList *lp;
gint n;
icon_view = EXO_ICON_VIEW (layout);
info = exo_icon_view_get_cell_info (icon_view, cell);
if (G_LIKELY (info != NULL))
{
lp = g_list_find (icon_view->priv->cell_list, info);
icon_view->priv->cell_list = g_list_remove_link (icon_view->priv->cell_list, lp);
icon_view->priv->cell_list = g_list_insert (icon_view->priv->cell_list, info, position);
for (lp = icon_view->priv->cell_list, n = 0; lp != NULL; lp = lp->next, ++n)
EXO_ICON_VIEW_CELL_INFO (lp->data)->position = n;
exo_icon_view_invalidate_sizes (icon_view);
}
}
/**
* exo_icon_view_new:
*
* Creates a new #ExoIconView widget
*
* Return value: A newly created #ExoIconView widget
**/
GtkWidget*
exo_icon_view_new (void)
{
return g_object_new (EXO_TYPE_ICON_VIEW, NULL);
}
/**
* exo_icon_view_new_with_model:
* @model: The model.
*
* Creates a new #ExoIconView widget with the model @model.
*
* Return value: A newly created #ExoIconView widget.
**/
GtkWidget*
exo_icon_view_new_with_model (GtkTreeModel *model)
{
g_return_val_if_fail (model == NULL || GTK_IS_TREE_MODEL (model), NULL);
return g_object_new (EXO_TYPE_ICON_VIEW,
"model", model,
NULL);
}
/**
* exo_icon_view_widget_to_icon_coords:
* @icon_view : a #ExoIconView.
* @wx : widget x coordinate.
* @wy : widget y coordinate.
* @ix : return location for icon x coordinate or %NULL.
* @iy : return location for icon y coordinate or %NULL.
*
* Converts widget coordinates to coordinates for the icon window
* (the full scrollable area of the icon view).
**/
void
exo_icon_view_widget_to_icon_coords (const ExoIconView *icon_view,
gint wx,
gint wy,
gint *ix,
gint *iy)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
if (G_LIKELY (ix != NULL))
*ix = wx + gtk_adjustment_get_value (icon_view->priv->hadjustment);
if (G_LIKELY (iy != NULL))
*iy = wy + gtk_adjustment_get_value (icon_view->priv->vadjustment);
}
/**
* exo_icon_view_icon_to_widget_coords:
* @icon_view : a #ExoIconView.
* @ix : icon x coordinate.
* @iy : icon y coordinate.
* @wx : return location for widget x coordinate or %NULL.
* @wy : return location for widget y coordinate or %NULL.
*
* Converts icon view coordinates (coordinates in full scrollable
* area of the icon view) to widget coordinates.
**/
void
exo_icon_view_icon_to_widget_coords (const ExoIconView *icon_view,
gint ix,
gint iy,
gint *wx,
gint *wy)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
if (G_LIKELY (wx != NULL))
*wx = ix - gtk_adjustment_get_value (icon_view->priv->hadjustment);
if (G_LIKELY (wy != NULL))
*wy = iy - gtk_adjustment_get_value (icon_view->priv->vadjustment);
}
/**
* exo_icon_view_get_path_at_pos:
* @icon_view : A #ExoIconView.
* @x : The x position to be identified
* @y : The y position to be identified
*
* Finds the path at the point (@x, @y), relative to widget coordinates.
* See exo_icon_view_get_item_at_pos(), if you are also interested in
* the cell at the specified position.
*
* Return value: The #GtkTreePath corresponding to the icon or %NULL
* if no icon exists at that position.
**/
GtkTreePath*
exo_icon_view_get_path_at_pos (const ExoIconView *icon_view,
gint x,
gint y)
{
ExoIconViewItem *item;
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), NULL);
/* translate the widget coordinates to icon window coordinates */
/*
NOTE by Hong Jen Yee: This should be disabled for pcmanfm to work. So weird.
x += icon_view->priv->hadjustment->value;
y += icon_view->priv->vadjustment->value;
*/
item = exo_icon_view_get_item_at_coords (icon_view, x, y, TRUE, NULL);
return (item != NULL) ? gtk_tree_path_new_from_indices (g_list_index (icon_view->priv->items, item), -1) : NULL;
}
/**
* exo_icon_view_get_item_at_pos:
* @icon_view: A #ExoIconView.
* @x: The x position to be identified
* @y: The y position to be identified
* @path: Return location for the path, or %NULL
* @cell: Return location for the renderer responsible for the cell
* at (@x, @y), or %NULL
*
* Finds the path at the point (@x, @y), relative to widget coordinates.
* In contrast to exo_icon_view_get_path_at_pos(), this function also
* obtains the cell at the specified position. The returned path should
* be freed with gtk_tree_path_free().
*
* Return value: %TRUE if an item exists at the specified position
*
* Since: 0.3.1
**/
gboolean
exo_icon_view_get_item_at_pos (const ExoIconView *icon_view,
gint x,
gint y,
GtkTreePath **path,
GtkCellRenderer **cell)
{
ExoIconViewCellInfo *info;
ExoIconViewItem *item;
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), FALSE);
item = exo_icon_view_get_item_at_coords (icon_view, x, y, TRUE, &info);
if (G_LIKELY (path != NULL))
*path = (item != NULL) ? gtk_tree_path_new_from_indices (g_list_index (icon_view->priv->items, item), -1) : NULL;
if (G_LIKELY (cell != NULL))
*cell = (info != NULL) ? info->cell : NULL;
return (item != NULL);
}
/**
* exo_icon_view_get_visible_range:
* @icon_view : A #ExoIconView
* @start_path : Return location for start of region, or %NULL
* @end_path : Return location for end of region, or %NULL
*
* Sets @start_path and @end_path to be the first and last visible path.
* Note that there may be invisible paths in between.
*
* Both paths should be freed with gtk_tree_path_free() after use.
*
* Return value: %TRUE, if valid paths were placed in @start_path and @end_path
*
* Since: 0.3.1
**/
gboolean
exo_icon_view_get_visible_range (const ExoIconView *icon_view,
GtkTreePath **start_path,
GtkTreePath **end_path)
{
const ExoIconViewPrivate *priv = icon_view->priv;
const ExoIconViewItem *item;
const GList *lp;
gint start_index = -1;
gint end_index = -1;
gint i;
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), FALSE);
if (priv->hadjustment == NULL || priv->vadjustment == NULL)
return FALSE;
if (start_path == NULL && end_path == NULL)
return FALSE;
for (i = 0, lp = priv->items; lp != NULL; ++i, lp = lp->next)
{
item = (const ExoIconViewItem *) lp->data;
if ((item->area.x + item->area.width >= (gint) gtk_adjustment_get_value (priv->hadjustment)) &&
(item->area.y + item->area.height >= (gint) gtk_adjustment_get_value (priv->vadjustment)) &&
(item->area.x <= (gint) (gtk_adjustment_get_value (priv->hadjustment) + gtk_adjustment_get_page_size (priv->hadjustment))) &&
(item->area.y <= (gint) (gtk_adjustment_get_value (priv->vadjustment) + gtk_adjustment_get_page_size (priv->vadjustment))))
{
if (start_index == -1)
start_index = i;
end_index = i;
}
}
if (start_path != NULL && start_index != -1)
*start_path = gtk_tree_path_new_from_indices (start_index, -1);
if (end_path != NULL && end_index != -1)
*end_path = gtk_tree_path_new_from_indices (end_index, -1);
return (start_index != -1);
}
/**
* exo_icon_view_selected_foreach:
* @icon_view : A #ExoIconView.
* @func : The funcion to call for each selected icon.
* @data : User data to pass to the function.
*
* Calls a function for each selected icon. Note that the model or
* selection cannot be modified from within this function.
**/
void
exo_icon_view_selected_foreach (ExoIconView *icon_view,
ExoIconViewForeachFunc func,
gpointer data)
{
GtkTreePath *path;
GList *lp;
path = gtk_tree_path_new_first ();
for (lp = icon_view->priv->items; lp != NULL; lp = lp->next)
{
if (EXO_ICON_VIEW_ITEM (lp->data)->selected)
(*func) (icon_view, path, data);
gtk_tree_path_next (path);
}
gtk_tree_path_free (path);
}
/**
* exo_icon_view_get_selection_mode:
* @icon_view : A #ExoIconView.
*
* Gets the selection mode of the @icon_view.
*
* Return value: the current selection mode
**/
GtkSelectionMode
exo_icon_view_get_selection_mode (const ExoIconView *icon_view)
{
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), GTK_SELECTION_SINGLE);
return icon_view->priv->selection_mode;
}
/**
* exo_icon_view_set_selection_mode:
* @icon_view : A #ExoIconView.
* @mode : The selection mode
*
* Sets the selection mode of the @icon_view.
**/
void
exo_icon_view_set_selection_mode (ExoIconView *icon_view,
GtkSelectionMode mode)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
if (G_LIKELY (mode != icon_view->priv->selection_mode))
{
if (mode == GTK_SELECTION_NONE || icon_view->priv->selection_mode == GTK_SELECTION_MULTIPLE)
exo_icon_view_unselect_all (icon_view);
icon_view->priv->selection_mode = mode;
g_object_notify (G_OBJECT (icon_view), "selection-mode");
}
}
/**
* exo_icon_view_get_layout_mode:
* @icon_view : A #ExoIconView.
*
* Returns the #ExoIconViewLayoutMode used to layout the
* items in the @icon_view.
*
* Return value: the layout mode of @icon_view.
*
* Since: 0.3.1.5
**/
ExoIconViewLayoutMode
exo_icon_view_get_layout_mode (const ExoIconView *icon_view)
{
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), EXO_ICON_VIEW_LAYOUT_ROWS);
return icon_view->priv->layout_mode;
}
/**
* exo_icon_view_set_layout_mode:
* @icon_view : a #ExoIconView.
* @layout_mode : the new #ExoIconViewLayoutMode for @icon_view.
*
* Sets the layout mode of @icon_view to @layout_mode.
*
* Since: 0.3.1.5
**/
void
exo_icon_view_set_layout_mode (ExoIconView *icon_view,
ExoIconViewLayoutMode layout_mode)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
/* check if we have a new setting */
if (G_LIKELY (icon_view->priv->layout_mode != layout_mode))
{
/* apply the new setting */
icon_view->priv->layout_mode = layout_mode;
/* cancel any active cell editor */
exo_icon_view_stop_editing (icon_view, TRUE);
/* invalidate the current item sizes */
exo_icon_view_invalidate_sizes (icon_view);
exo_icon_view_queue_layout (icon_view);
/* notify listeners */
g_object_notify (G_OBJECT (icon_view), "layout-mode");
}
}
/**
* exo_icon_view_get_model:
* @icon_view : a #ExoIconView
*
* Returns the model the #ExoIconView is based on. Returns %NULL if the
* model is unset.
*
* Return value: A #GtkTreeModel, or %NULL if none is currently being used.
**/
GtkTreeModel*
exo_icon_view_get_model (const ExoIconView *icon_view)
{
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), NULL);
return icon_view->priv->model;
}
/**
* exo_icon_view_set_model:
* @icon_view : A #ExoIconView.
* @model : The model.
*
* Sets the model for a #ExoIconView.
* If the @icon_view already has a model set, it will remove
* it before setting the new model. If @model is %NULL, then
* it will unset the old model.
**/
void
exo_icon_view_set_model (ExoIconView *icon_view,
GtkTreeModel *model)
{
ExoIconViewItem *item;
GtkTreeIter iter;
GList *items = NULL;
GList *lp;
gint n;
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
g_return_if_fail (model == NULL || GTK_IS_TREE_MODEL (model));
/* verify that we don't already use that model */
if (G_UNLIKELY (icon_view->priv->model == model))
return;
/* verify the new model */
if (G_LIKELY (model != NULL))
{
g_return_if_fail (gtk_tree_model_get_flags (model) & GTK_TREE_MODEL_LIST_ONLY);
if (G_UNLIKELY (icon_view->priv->pixbuf_column != -1))
g_return_if_fail (gtk_tree_model_get_column_type (model, icon_view->priv->pixbuf_column) == GDK_TYPE_PIXBUF);
if (G_UNLIKELY (icon_view->priv->text_column != -1))
g_return_if_fail (gtk_tree_model_get_column_type (model, icon_view->priv->text_column) == G_TYPE_STRING);
if (G_UNLIKELY (icon_view->priv->markup_column != -1))
g_return_if_fail (gtk_tree_model_get_column_type (model, icon_view->priv->markup_column) == G_TYPE_STRING);
}
/* be sure to cancel any pending editor */
exo_icon_view_stop_editing (icon_view, TRUE);
/* disconnect from the previous model */
if (G_LIKELY (icon_view->priv->model != NULL))
{
/* disconnect signals handlers from the previous model */
g_signal_handlers_disconnect_by_func (G_OBJECT (icon_view->priv->model), exo_icon_view_row_changed, icon_view);
g_signal_handlers_disconnect_by_func (G_OBJECT (icon_view->priv->model), exo_icon_view_row_inserted, icon_view);
g_signal_handlers_disconnect_by_func (G_OBJECT (icon_view->priv->model), exo_icon_view_row_deleted, icon_view);
g_signal_handlers_disconnect_by_func (G_OBJECT (icon_view->priv->model), exo_icon_view_rows_reordered, icon_view);
/* release our reference on the model */
g_object_unref (G_OBJECT (icon_view->priv->model));
/* drop all items belonging to the previous model */
for (lp = icon_view->priv->items; lp != NULL; lp = lp->next)
{
g_free (EXO_ICON_VIEW_ITEM (lp->data)->box);
_exo_slice_free (ExoIconViewItem, lp->data);
}
g_list_free (icon_view->priv->items);
icon_view->priv->items = NULL;
/* reset statistics */
icon_view->priv->search_column = -1;
icon_view->priv->anchor_item = NULL;
icon_view->priv->cursor_item = NULL;
icon_view->priv->prelit_item = NULL;
icon_view->priv->last_single_clicked = NULL;
icon_view->priv->width = 0;
icon_view->priv->height = 0;
/* cancel any pending single click timer */
if (G_UNLIKELY (icon_view->priv->single_click_timeout_id != 0))
g_source_remove (icon_view->priv->single_click_timeout_id);
/* reset cursor when in single click mode and realized */
if (G_UNLIKELY (icon_view->priv->single_click && gtk_widget_get_realized ( GTK_WIDGET (icon_view))))
gdk_window_set_cursor (icon_view->priv->bin_window, NULL);
}
/* be sure to drop any previous scroll_to_path reference,
* as it points to the old (no longer valid) model.
*/
if (G_UNLIKELY (icon_view->priv->scroll_to_path != NULL))
{
gtk_tree_row_reference_free (icon_view->priv->scroll_to_path);
icon_view->priv->scroll_to_path = NULL;
}
/* activate the new model */
icon_view->priv->model = model;
/* connect to the new model */
if (G_LIKELY (model != NULL))
{
/* take a reference on the model */
g_object_ref (G_OBJECT (model));
/* connect signals */
g_signal_connect (G_OBJECT (model), "row-changed", G_CALLBACK (exo_icon_view_row_changed), icon_view);
g_signal_connect (G_OBJECT (model), "row-inserted", G_CALLBACK (exo_icon_view_row_inserted), icon_view);
g_signal_connect (G_OBJECT (model), "row-deleted", G_CALLBACK (exo_icon_view_row_deleted), icon_view);
g_signal_connect (G_OBJECT (model), "rows-reordered", G_CALLBACK (exo_icon_view_rows_reordered), icon_view);
/* check if the new model supports persistent iterators */
if (gtk_tree_model_get_flags (model) & GTK_TREE_MODEL_ITERS_PERSIST)
EXO_ICON_VIEW_SET_FLAG (icon_view, EXO_ICON_VIEW_ITERS_PERSIST);
else
EXO_ICON_VIEW_UNSET_FLAG (icon_view, EXO_ICON_VIEW_ITERS_PERSIST);
/* determine an appropriate search column */
if (icon_view->priv->search_column <= 0)
{
/* we simply use the first string column */
for (n = 0; n < gtk_tree_model_get_n_columns (model); ++n)
if (g_value_type_transformable (gtk_tree_model_get_column_type (model, n), G_TYPE_STRING))
{
icon_view->priv->search_column = n;
break;
}
}
/* build up the initial items list */
if (gtk_tree_model_get_iter_first (model, &iter))
{
do
{
item = _exo_slice_new0 (ExoIconViewItem);
item->iter = iter;
item->area.width = -1;
items = g_list_prepend (items, item);
}
while (gtk_tree_model_iter_next (model, &iter));
}
icon_view->priv->items = g_list_reverse (items);
/* layout the new items */
exo_icon_view_queue_layout (icon_view);
}
/* hide the interactive search dialog (if any) */
if (G_LIKELY (icon_view->priv->search_window != NULL))
exo_icon_view_search_dialog_hide (icon_view->priv->search_window, icon_view);
/* notify listeners */
g_object_notify (G_OBJECT (icon_view), "model");
if (gtk_widget_get_realized (GTK_WIDGET (icon_view)))
gtk_widget_queue_resize (GTK_WIDGET (icon_view));
}
static void
update_text_cell (ExoIconView *icon_view)
{
ExoIconViewCellInfo *info;
GList *l;
gint i;
if (icon_view->priv->text_column == -1 &&
icon_view->priv->markup_column == -1)
{
if (icon_view->priv->text_cell != -1)
{
info = g_list_nth_data (icon_view->priv->cell_list,
icon_view->priv->text_cell);
icon_view->priv->cell_list = g_list_remove (icon_view->priv->cell_list, info);
free_cell_info (info);
icon_view->priv->n_cells--;
icon_view->priv->text_cell = -1;
}
}
else
{
if (icon_view->priv->text_cell == -1)
{
GtkCellRenderer *cell = gtk_cell_renderer_text_new ();
gtk_cell_layout_pack_end (GTK_CELL_LAYOUT (icon_view), cell, FALSE);
for (l = icon_view->priv->cell_list, i = 0; l; l = l->next, i++)
{
info = l->data;
if (info->cell == cell)
{
icon_view->priv->text_cell = i;
break;
}
}
}
info = g_list_nth_data (icon_view->priv->cell_list,
icon_view->priv->text_cell);
if (icon_view->priv->markup_column != -1)
gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (icon_view),
info->cell,
"markup", icon_view->priv->markup_column,
NULL);
else
gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (icon_view),
info->cell,
"text", icon_view->priv->text_column,
NULL);
}
}
static void
update_pixbuf_cell (ExoIconView *icon_view)
{
ExoIconViewCellInfo *info;
GList *l;
gint i;
if (icon_view->priv->pixbuf_column == -1)
{
if (icon_view->priv->pixbuf_cell != -1)
{
info = g_list_nth_data (icon_view->priv->cell_list,
icon_view->priv->pixbuf_cell);
icon_view->priv->cell_list = g_list_remove (icon_view->priv->cell_list, info);
free_cell_info (info);
icon_view->priv->n_cells--;
icon_view->priv->pixbuf_cell = -1;
}
}
else
{
if (icon_view->priv->pixbuf_cell == -1)
{
GtkCellRenderer *cell = gtk_cell_renderer_pixbuf_new ();
gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (icon_view), cell, FALSE);
for (l = icon_view->priv->cell_list, i = 0; l; l = l->next, i++)
{
info = l->data;
if (info->cell == cell)
{
icon_view->priv->pixbuf_cell = i;
break;
}
}
}
info = g_list_nth_data (icon_view->priv->cell_list,
icon_view->priv->pixbuf_cell);
gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (icon_view),
info->cell,
"pixbuf", icon_view->priv->pixbuf_column,
NULL);
}
}
/**
* exo_icon_view_get_text_column:
* @icon_view: A #ExoIconView.
*
* Returns the column with text for @icon_view.
*
* Returns: the text column, or -1 if it's unset.
*
* Deprecated: Use the more powerful #GtkCellRenderer<!---->s instead, as #ExoIconView
* now implements #GtkCellLayout.
*/
gint
exo_icon_view_get_text_column (const ExoIconView *icon_view)
{
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), -1);
return icon_view->priv->text_column;
}
/**
* exo_icon_view_set_text_column:
* @icon_view: A #ExoIconView.
* @column: A column in the currently used model.
*
* Sets the column with text for @icon_view to be @column. The text
* column must be of type #G_TYPE_STRING.
*
* Deprecated: Use the more powerful #GtkCellRenderer<!---->s instead, as #ExoIconView
* now implements #GtkCellLayout.
**/
void
exo_icon_view_set_text_column (ExoIconView *icon_view,
gint column)
{
GType column_type;
if (G_UNLIKELY (column == icon_view->priv->text_column))
return;
if (column == -1)
{
icon_view->priv->text_column = -1;
}
else
{
if (icon_view->priv->model != NULL)
{
column_type = gtk_tree_model_get_column_type (icon_view->priv->model, column);
g_return_if_fail (column_type == G_TYPE_STRING);
}
icon_view->priv->text_column = column;
}
exo_icon_view_stop_editing (icon_view, TRUE);
update_text_cell (icon_view);
exo_icon_view_invalidate_sizes (icon_view);
g_object_notify (G_OBJECT (icon_view), "text-column");
}
/**
* exo_icon_view_get_markup_column:
* @icon_view: A #ExoIconView.
*
* Returns the column with markup text for @icon_view.
*
* Returns: the markup column, or -1 if it's unset.
*
* Deprecated: Use the more powerful #GtkCellRenderer<!---->s instead, as #ExoIconView
* now implements #GtkCellLayout.
*/
gint
exo_icon_view_get_markup_column (const ExoIconView *icon_view)
{
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), -1);
return icon_view->priv->markup_column;
}
/**
* exo_icon_view_set_markup_column:
* @icon_view : A #ExoIconView.
* @column : A column in the currently used model.
*
* Sets the column with markup information for @icon_view to be
* @column. The markup column must be of type #G_TYPE_STRING.
* If the markup column is set to something, it overrides
* the text column set by exo_icon_view_set_text_column().
*
* Deprecated: Use the more powerful #GtkCellRenderer<!---->s instead, as #ExoIconView
* now implements #GtkCellLayout.
**/
void
exo_icon_view_set_markup_column (ExoIconView *icon_view,
gint column)
{
if (G_UNLIKELY (column == icon_view->priv->markup_column))
return;
if (column == -1)
icon_view->priv->markup_column = -1;
else
{
if (icon_view->priv->model != NULL)
{
GType column_type;
column_type = gtk_tree_model_get_column_type (icon_view->priv->model, column);
g_return_if_fail (column_type == G_TYPE_STRING);
}
icon_view->priv->markup_column = column;
}
exo_icon_view_stop_editing (icon_view, TRUE);
update_text_cell (icon_view);
exo_icon_view_invalidate_sizes (icon_view);
g_object_notify (G_OBJECT (icon_view), "markup-column");
}
/**
* exo_icon_view_get_pixbuf_column:
* @icon_view : A #ExoIconView.
*
* Returns the column with pixbufs for @icon_view.
*
* Returns: the pixbuf column, or -1 if it's unset.
*
* Deprecated: Use the more powerful #GtkCellRenderer<!---->s instead, as #ExoIconView
* now implements #GtkCellLayout.
*/
gint
exo_icon_view_get_pixbuf_column (const ExoIconView *icon_view)
{
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), -1);
return icon_view->priv->pixbuf_column;
}
/**
* exo_icon_view_set_pixbuf_column:
* @icon_view : A #ExoIconView.
* @column : A column in the currently used model.
*
* Sets the column with pixbufs for @icon_view to be @column. The pixbuf
* column must be of type #GDK_TYPE_PIXBUF
*
* Deprecated: Use the more powerful #GtkCellRenderer<!---->s instead, as #ExoIconView
* now implements #GtkCellLayout.
**/
void
exo_icon_view_set_pixbuf_column (ExoIconView *icon_view,
gint column)
{
GType column_type;
if (G_UNLIKELY (column == icon_view->priv->pixbuf_column))
return;
if (column == -1)
{
icon_view->priv->pixbuf_column = -1;
}
else
{
if (icon_view->priv->model != NULL)
{
column_type = gtk_tree_model_get_column_type (icon_view->priv->model, column);
g_return_if_fail (column_type == GDK_TYPE_PIXBUF);
}
icon_view->priv->pixbuf_column = column;
}
exo_icon_view_stop_editing (icon_view, TRUE);
update_pixbuf_cell (icon_view);
exo_icon_view_invalidate_sizes (icon_view);
g_object_notify (G_OBJECT (icon_view), "pixbuf-column");
}
/**
* exo_icon_view_select_path:
* @icon_view : A #ExoIconView.
* @path : The #GtkTreePath to be selected.
*
* Selects the row at @path.
**/
void
exo_icon_view_select_path (ExoIconView *icon_view,
GtkTreePath *path)
{
ExoIconViewItem *item;
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
g_return_if_fail (icon_view->priv->model != NULL);
g_return_if_fail (gtk_tree_path_get_depth (path) > 0);
item = g_list_nth_data (icon_view->priv->items, gtk_tree_path_get_indices(path)[0]);
if (G_LIKELY (item != NULL))
exo_icon_view_select_item (icon_view, item);
}
/**
* exo_icon_view_unselect_path:
* @icon_view : A #ExoIconView.
* @path : The #GtkTreePath to be unselected.
*
* Unselects the row at @path.
**/
void
exo_icon_view_unselect_path (ExoIconView *icon_view,
GtkTreePath *path)
{
ExoIconViewItem *item;
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
g_return_if_fail (icon_view->priv->model != NULL);
g_return_if_fail (gtk_tree_path_get_depth (path) > 0);
item = g_list_nth_data (icon_view->priv->items, gtk_tree_path_get_indices(path)[0]);
if (G_LIKELY (item != NULL))
exo_icon_view_unselect_item (icon_view, item);
}
/**
* exo_icon_view_get_selected_items:
* @icon_view: A #ExoIconView.
*
* Creates a list of paths of all selected items. Additionally, if you are
* planning on modifying the model after calling this function, you may
* want to convert the returned list into a list of #GtkTreeRowReference<!-- -->s.
* To do this, you can use gtk_tree_row_reference_new().
*
* To free the return value, use:
* <informalexample><programlisting>
* g_list_foreach (list, gtk_tree_path_free, NULL);
* g_list_free (list);
* </programlisting></informalexample>
*
* Return value: A #GList containing a #GtkTreePath for each selected row.
**/
GList*
exo_icon_view_get_selected_items (const ExoIconView *icon_view)
{
GList *selected = NULL;
GList *lp;
gint i;
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), NULL);
for (i = 0, lp = icon_view->priv->items; lp != NULL; ++i, lp = lp->next)
{
if (EXO_ICON_VIEW_ITEM (lp->data)->selected)
selected = g_list_append (selected, gtk_tree_path_new_from_indices (i, -1));
}
return selected;
}
/**
* exo_icon_view_select_all:
* @icon_view : A #ExoIconView.
*
* Selects all the icons. @icon_view must has its selection mode set
* to #GTK_SELECTION_MULTIPLE.
**/
void
exo_icon_view_select_all (ExoIconView *icon_view)
{
GList *items;
gboolean dirty = FALSE;
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
if (icon_view->priv->selection_mode != GTK_SELECTION_MULTIPLE)
return;
for (items = icon_view->priv->items; items; items = items->next)
{
ExoIconViewItem *item = items->data;
if (!item->selected)
{
dirty = TRUE;
item->selected = TRUE;
exo_icon_view_queue_draw_item (icon_view, item);
}
}
if (dirty)
g_signal_emit (icon_view, icon_view_signals[SELECTION_CHANGED], 0);
}
/**
* exo_icon_view_unselect_all:
* @icon_view : A #ExoIconView.
*
* Unselects all the icons.
**/
void
exo_icon_view_unselect_all (ExoIconView *icon_view)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
if (G_UNLIKELY (icon_view->priv->selection_mode == GTK_SELECTION_BROWSE))
return;
if (exo_icon_view_unselect_all_internal (icon_view))
g_signal_emit (icon_view, icon_view_signals[SELECTION_CHANGED], 0);
}
/**
* exo_icon_view_path_is_selected:
* @icon_view: A #ExoIconView.
* @path: A #GtkTreePath to check selection on.
*
* Returns %TRUE if the icon pointed to by @path is currently
* selected. If @icon does not point to a valid location, %FALSE is returned.
*
* Return value: %TRUE if @path is selected.
**/
gboolean
exo_icon_view_path_is_selected (const ExoIconView *icon_view,
GtkTreePath *path)
{
ExoIconViewItem *item;
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), FALSE);
g_return_val_if_fail (icon_view->priv->model != NULL, FALSE);
g_return_val_if_fail (gtk_tree_path_get_depth (path) > 0, FALSE);
item = g_list_nth_data (icon_view->priv->items, gtk_tree_path_get_indices(path)[0]);
return (item != NULL && item->selected);
}
/**
* exo_icon_view_item_activated:
* @icon_view : a #ExoIconView
* @path : the #GtkTreePath to be activated
*
* Activates the item determined by @path.
**/
void
exo_icon_view_item_activated (ExoIconView *icon_view,
GtkTreePath *path)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
g_return_if_fail (gtk_tree_path_get_depth (path) > 0);
g_signal_emit (icon_view, icon_view_signals[ITEM_ACTIVATED], 0, path);
}
/**
* exo_icon_view_get_cursor:
* @icon_view : A #ExoIconView
* @path : Return location for the current cursor path, or %NULL
* @cell : Return location the current focus cell, or %NULL
*
* Fills in @path and @cell with the current cursor path and cell.
* If the cursor isn't currently set, then *@path will be %NULL.
* If no cell currently has focus, then *@cell will be %NULL.
*
* The returned #GtkTreePath must be freed with gtk_tree_path_free().
*
* Return value: %TRUE if the cursor is set.
*
* Since: 0.3.1
**/
gboolean
exo_icon_view_get_cursor (const ExoIconView *icon_view,
GtkTreePath **path,
GtkCellRenderer **cell)
{
ExoIconViewCellInfo *info;
ExoIconViewItem *item;
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), FALSE);
item = icon_view->priv->cursor_item;
info = (icon_view->priv->cursor_cell < 0) ? NULL : g_list_nth_data (icon_view->priv->cell_list, icon_view->priv->cursor_cell);
if (G_LIKELY (path != NULL))
*path = (item != NULL) ? gtk_tree_path_new_from_indices (g_list_index (icon_view->priv->items, item), -1) : NULL;
if (G_LIKELY (cell != NULL))
*cell = (info != NULL) ? info->cell : NULL;
return (item != NULL);
}
/**
* exo_icon_view_set_cursor:
* @icon_view : a #ExoIconView
* @path : a #GtkTreePath
* @cell : a #GtkCellRenderer or %NULL
* @start_editing : %TRUE if the specified cell should start being edited.
*
* Sets the current keyboard focus to be at @path, and selects it. This is
* useful when you want to focus the user's attention on a particular item.
* If @cell is not %NULL, then focus is given to the cell specified by
* it. Additionally, if @start_editing is %TRUE, then editing should be
* started in the specified cell.
*
* This function is often followed by <literal>gtk_widget_grab_focus
* (icon_view)</literal> in order to give keyboard focus to the widget.
* Please note that editing can only happen when the widget is realized.
*
* Since: 0.3.1
**/
void
exo_icon_view_set_cursor (ExoIconView *icon_view,
GtkTreePath *path,
GtkCellRenderer *cell,
gboolean start_editing)
{
ExoIconViewItem *item;
ExoIconViewCellInfo *info = NULL;
GList *l;
gint i, cell_pos;
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
g_return_if_fail (path != NULL);
g_return_if_fail (cell == NULL || GTK_IS_CELL_RENDERER (cell));
exo_icon_view_stop_editing (icon_view, TRUE);
item = g_list_nth_data (icon_view->priv->items, gtk_tree_path_get_indices(path)[0]);
if (G_UNLIKELY (item == NULL))
return;
cell_pos = -1;
for (l = icon_view->priv->cell_list, i = 0; l; l = l->next, i++)
{
info = l->data;
if (info->cell == cell)
{
cell_pos = i;
break;
}
info = NULL;
}
/* place the cursor on the item */
exo_icon_view_set_cursor_item (icon_view, item, cell_pos);
/* scroll to the item (maybe delayed) */
exo_icon_view_scroll_to_path (icon_view, path, FALSE, 0.0f, 0.0f);
if (start_editing)
exo_icon_view_start_editing (icon_view, item, info, NULL);
}
/**
* exo_icon_view_scroll_to_path:
* @icon_view: A #ExoIconView.
* @path: The path of the item to move to.
* @use_align: whether to use alignment arguments, or %FALSE.
* @row_align: The vertical alignment of the item specified by @path.
* @col_align: The horizontal alignment of the item specified by @column.
*
* Moves the alignments of @icon_view to the position specified by @path.
* @row_align determines where the row is placed, and @col_align determines where
* @column is placed. Both are expected to be between 0.0 and 1.0.
* 0.0 means left/top alignment, 1.0 means right/bottom alignment, 0.5 means center.
*
* If @use_align is %FALSE, then the alignment arguments are ignored, and the
* tree does the minimum amount of work to scroll the item onto the screen.
* This means that the item will be scrolled to the edge closest to its current
* position. If the item is currently visible on the screen, nothing is done.
*
* This function only works if the model is set, and @path is a valid row on the
* model. If the model changes before the @tree_view is realized, the centered
* path will be modified to reflect this change.
*
* Since: 0.3.1
**/
void
exo_icon_view_scroll_to_path (ExoIconView *icon_view,
GtkTreePath *path,
gboolean use_align,
gfloat row_align,
gfloat col_align)
{
ExoIconViewItem *item;
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
g_return_if_fail (gtk_tree_path_get_depth (path) > 0);
g_return_if_fail (row_align >= 0.0 && row_align <= 1.0);
g_return_if_fail (col_align >= 0.0 && col_align <= 1.0);
/* Delay scrolling if either not realized or pending layout() */
if (!gtk_widget_get_realized (GTK_WIDGET (icon_view)) || icon_view->priv->layout_idle_id != 0)
{
/* release the previous scroll_to_path reference */
if (G_UNLIKELY (icon_view->priv->scroll_to_path != NULL))
gtk_tree_row_reference_free (icon_view->priv->scroll_to_path);
/* remember a reference for the new path and settings */
icon_view->priv->scroll_to_path = gtk_tree_row_reference_new_proxy (G_OBJECT (icon_view), icon_view->priv->model, path);
icon_view->priv->scroll_to_use_align = use_align;
icon_view->priv->scroll_to_row_align = row_align;
icon_view->priv->scroll_to_col_align = col_align;
}
else
{
item = g_list_nth_data (icon_view->priv->items, gtk_tree_path_get_indices(path)[0]);
if (G_UNLIKELY (item == NULL))
return;
if (use_align)
{
gint x, y;
gint focus_width;
gfloat offset, value;
GtkAllocation allocation;
gtk_widget_style_get (GTK_WIDGET (icon_view),
"focus-line-width", &focus_width,
NULL);
gtk_widget_get_allocation (GTK_WIDGET (icon_view), &allocation);
gdk_window_get_position (icon_view->priv->bin_window, &x, &y);
offset = y + item->area.y - focus_width -
row_align * (allocation.height - item->area.height);
value = CLAMP (gtk_adjustment_get_value (icon_view->priv->vadjustment) + offset,
gtk_adjustment_get_lower (icon_view->priv->vadjustment),
gtk_adjustment_get_upper (icon_view->priv->vadjustment) - gtk_adjustment_get_page_size (icon_view->priv->vadjustment));
gtk_adjustment_set_value (icon_view->priv->vadjustment, value);
offset = x + item->area.x - focus_width -
col_align * (allocation.width - item->area.width);
value = CLAMP (gtk_adjustment_get_value (icon_view->priv->hadjustment) + offset,
gtk_adjustment_get_lower (icon_view->priv->hadjustment),
gtk_adjustment_get_upper (icon_view->priv->hadjustment) - gtk_adjustment_get_page_size (icon_view->priv->hadjustment));
gtk_adjustment_set_value (icon_view->priv->hadjustment, value);
gtk_adjustment_changed (icon_view->priv->hadjustment);
gtk_adjustment_changed (icon_view->priv->vadjustment);
}
else
{
exo_icon_view_scroll_to_item (icon_view, item);
}
}
}
/**
* exo_icon_view_get_orientation:
* @icon_view : a #ExoIconView
*
* Returns the value of the ::orientation property which determines
* whether the labels are drawn beside the icons instead of below.
*
* Return value: the relative position of texts and icons
*
* Since: 0.3.1
**/
GtkOrientation
exo_icon_view_get_orientation (const ExoIconView *icon_view)
{
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), GTK_ORIENTATION_VERTICAL);
return icon_view->priv->orientation;
}
/**
* exo_icon_view_set_orientation:
* @icon_view : a #ExoIconView
* @orientation : the relative position of texts and icons
*
* Sets the ::orientation property which determines whether the labels
* are drawn beside the icons instead of below.
*
* Since: 0.3.1
**/
void
exo_icon_view_set_orientation (ExoIconView *icon_view,
GtkOrientation orientation)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
if (G_LIKELY (icon_view->priv->orientation != orientation))
{
icon_view->priv->orientation = orientation;
exo_icon_view_stop_editing (icon_view, TRUE);
exo_icon_view_invalidate_sizes (icon_view);
update_text_cell (icon_view);
update_pixbuf_cell (icon_view);
g_object_notify (G_OBJECT (icon_view), "orientation");
}
}
/**
* exo_icon_view_get_columns:
* @icon_view: a #ExoIconView
*
* Returns the value of the ::columns property.
*
* Return value: the number of columns, or -1
*/
gint
exo_icon_view_get_columns (const ExoIconView *icon_view)
{
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), -1);
return icon_view->priv->columns;
}
/**
* exo_icon_view_set_columns:
* @icon_view : a #ExoIconView
* @columns : the number of columns
*
* Sets the ::columns property which determines in how
* many columns the icons are arranged. If @columns is
* -1, the number of columns will be chosen automatically
* to fill the available area.
*
* Since: 0.3.1
*/
void
exo_icon_view_set_columns (ExoIconView *icon_view,
gint columns)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
if (G_LIKELY (icon_view->priv->columns != columns))
{
icon_view->priv->columns = columns;
exo_icon_view_stop_editing (icon_view, TRUE);
exo_icon_view_queue_layout (icon_view);
g_object_notify (G_OBJECT (icon_view), "columns");
}
}
/**
* exo_icon_view_get_item_width:
* @icon_view: a #ExoIconView
*
* Returns the value of the ::item-width property.
*
* Return value: the width of a single item, or -1
*
* Since: 0.3.1
*/
gint
exo_icon_view_get_item_width (const ExoIconView *icon_view)
{
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), -1);
return icon_view->priv->item_width;
}
/**
* exo_icon_view_set_item_width:
* @icon_view : a #ExoIconView
* @item_width : the width for each item
*
* Sets the ::item-width property which specifies the width
* to use for each item. If it is set to -1, the icon view will
* automatically determine a suitable item size.
*
* Since: 0.3.1
*/
void
exo_icon_view_set_item_width (ExoIconView *icon_view,
gint item_width)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
if (icon_view->priv->item_width != item_width)
{
icon_view->priv->item_width = item_width;
exo_icon_view_stop_editing (icon_view, TRUE);
exo_icon_view_invalidate_sizes (icon_view);
update_text_cell (icon_view);
g_object_notify (G_OBJECT (icon_view), "item-width");
}
}
/**
* exo_icon_view_get_spacing:
* @icon_view: a #ExoIconView
*
* Returns the value of the ::spacing property.
*
* Return value: the space between cells
*
* Since: 0.3.1
*/
gint
exo_icon_view_get_spacing (const ExoIconView *icon_view)
{
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), -1);
return icon_view->priv->spacing;
}
/**
* exo_icon_view_set_spacing:
* @icon_view : a #ExoIconView
* @spacing : the spacing
*
* Sets the ::spacing property which specifies the space
* which is inserted between the cells (i.e. the icon and
* the text) of an item.
*
* Since: 0.3.1
*/
void
exo_icon_view_set_spacing (ExoIconView *icon_view,
gint spacing)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
if (G_LIKELY (icon_view->priv->spacing != spacing))
{
icon_view->priv->spacing = spacing;
exo_icon_view_stop_editing (icon_view, TRUE);
exo_icon_view_invalidate_sizes (icon_view);
g_object_notify (G_OBJECT (icon_view), "spacing");
}
}
/**
* exo_icon_view_get_row_spacing:
* @icon_view: a #ExoIconView
*
* Returns the value of the ::row-spacing property.
*
* Return value: the space between rows
*
* Since: 0.3.1
*/
gint
exo_icon_view_get_row_spacing (const ExoIconView *icon_view)
{
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), -1);
return icon_view->priv->row_spacing;
}
/**
* exo_icon_view_set_row_spacing:
* @icon_view : a #ExoIconView
* @row_spacing : the row spacing
*
* Sets the ::row-spacing property which specifies the space
* which is inserted between the rows of the icon view.
*
* Since: 0.3.1
*/
void
exo_icon_view_set_row_spacing (ExoIconView *icon_view,
gint row_spacing)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
if (G_LIKELY (icon_view->priv->row_spacing != row_spacing))
{
icon_view->priv->row_spacing = row_spacing;
exo_icon_view_stop_editing (icon_view, TRUE);
exo_icon_view_invalidate_sizes (icon_view);
g_object_notify (G_OBJECT (icon_view), "row-spacing");
}
}
/**
* exo_icon_view_get_column_spacing:
* @icon_view: a #ExoIconView
*
* Returns the value of the ::column-spacing property.
*
* Return value: the space between columns
*
* Since: 0.3.1
**/
gint
exo_icon_view_get_column_spacing (const ExoIconView *icon_view)
{
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), -1);
return icon_view->priv->column_spacing;
}
/**
* exo_icon_view_set_column_spacing:
* @icon_view : a #ExoIconView
* @column_spacing : the column spacing
*
* Sets the ::column-spacing property which specifies the space
* which is inserted between the columns of the icon view.
*
* Since: 0.3.1
**/
void
exo_icon_view_set_column_spacing (ExoIconView *icon_view,
gint column_spacing)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
if (G_LIKELY (icon_view->priv->column_spacing != column_spacing))
{
icon_view->priv->column_spacing = column_spacing;
exo_icon_view_stop_editing (icon_view, TRUE);
exo_icon_view_invalidate_sizes (icon_view);
g_object_notify (G_OBJECT (icon_view), "column-spacing");
}
}
/**
* exo_icon_view_get_margin:
* @icon_view : a #ExoIconView
*
* Returns the value of the ::margin property.
*
* Return value: the space at the borders
*
* Since: 0.3.1
**/
gint
exo_icon_view_get_margin (const ExoIconView *icon_view)
{
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), -1);
return icon_view->priv->margin;
}
/**
* exo_icon_view_set_margin:
* @icon_view : a #ExoIconView
* @margin : the margin
*
* Sets the ::margin property which specifies the space
* which is inserted at the top, bottom, left and right
* of the icon view.
*
* Since: 0.3.1
**/
void
exo_icon_view_set_margin (ExoIconView *icon_view,
gint margin)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
if (G_LIKELY (icon_view->priv->margin != margin))
{
icon_view->priv->margin = margin;
exo_icon_view_stop_editing (icon_view, TRUE);
exo_icon_view_invalidate_sizes (icon_view);
g_object_notify (G_OBJECT (icon_view), "margin");
}
}
/* Get/set whether drag_motion requested the drag data and
* drag_data_received should thus not actually insert the data,
* since the data doesn't result from a drop.
*/
static void
set_status_pending (GdkDragContext *context,
GdkDragAction suggested_action)
{
g_object_set_data (G_OBJECT (context),
I_("exo-icon-view-status-pending"),
GINT_TO_POINTER (suggested_action));
}
static GdkDragAction
get_status_pending (GdkDragContext *context)
{
return GPOINTER_TO_INT (g_object_get_data (G_OBJECT (context), I_("exo-icon-view-status-pending")));
}
static void
unset_reorderable (ExoIconView *icon_view)
{
if (icon_view->priv->reorderable)
{
icon_view->priv->reorderable = FALSE;
g_object_notify (G_OBJECT (icon_view), "reorderable");
}
}
static void
clear_source_info (ExoIconView *icon_view)
{
if (icon_view->priv->source_targets)
gtk_target_list_unref (icon_view->priv->source_targets);
icon_view->priv->source_targets = NULL;
icon_view->priv->source_set = FALSE;
}
static void
clear_dest_info (ExoIconView *icon_view)
{
if (icon_view->priv->dest_targets)
gtk_target_list_unref (icon_view->priv->dest_targets);
icon_view->priv->dest_targets = NULL;
icon_view->priv->dest_set = FALSE;
}
static void
set_source_row (GdkDragContext *context,
GtkTreeModel *model,
GtkTreePath *source_row)
{
if (source_row)
g_object_set_data_full (G_OBJECT (context),
I_("exo-icon-view-source-row"),
gtk_tree_row_reference_new (model, source_row),
(GDestroyNotify) gtk_tree_row_reference_free);
else
g_object_set_data_full (G_OBJECT (context),
I_("exo-icon-view-source-row"),
NULL, NULL);
}
static GtkTreePath*
get_source_row (GdkDragContext *context)
{
GtkTreeRowReference *ref;
ref = g_object_get_data (G_OBJECT (context), I_("exo-icon-view-source-row"));
if (ref)
return gtk_tree_row_reference_get_path (ref);
else
return NULL;
}
typedef struct
{
GtkTreeRowReference *dest_row;
gboolean empty_view_drop;
gboolean drop_append_mode;
} DestRow;
static void
dest_row_free (gpointer data)
{
DestRow *dr = (DestRow *)data;
gtk_tree_row_reference_free (dr->dest_row);
_exo_slice_free (DestRow, dr);
}
static void
set_dest_row (GdkDragContext *context,
GtkTreeModel *model,
GtkTreePath *dest_row,
gboolean empty_view_drop,
gboolean drop_append_mode)
{
DestRow *dr;
if (!dest_row)
{
g_object_set_data_full (G_OBJECT (context),
I_("exo-icon-view-dest-row"),
NULL, NULL);
return;
}
dr = _exo_slice_new0 (DestRow);
dr->dest_row = gtk_tree_row_reference_new (model, dest_row);
dr->empty_view_drop = empty_view_drop;
dr->drop_append_mode = drop_append_mode;
g_object_set_data_full (G_OBJECT (context),
I_("exo-icon-view-dest-row"),
dr, (GDestroyNotify) dest_row_free);
}
static GtkTreePath*
get_dest_row (GdkDragContext *context)
{
DestRow *dr;
dr = g_object_get_data (G_OBJECT (context), I_("exo-icon-view-dest-row"));
if (dr)
{
GtkTreePath *path = NULL;
if (dr->dest_row)
path = gtk_tree_row_reference_get_path (dr->dest_row);
else if (dr->empty_view_drop)
path = gtk_tree_path_new_from_indices (0, -1);
else
path = NULL;
if (path && dr->drop_append_mode)
gtk_tree_path_next (path);
return path;
}
else
return NULL;
}
static gboolean
check_model_dnd (GtkTreeModel *model,
GType required_iface,
const gchar *signal)
{
if (model == NULL || !G_TYPE_CHECK_INSTANCE_TYPE ((model), required_iface))
{
g_warning ("You must override the default '%s' handler "
"on ExoIconView when using models that don't support "
"the %s interface and enabling drag-and-drop. The simplest way to do this "
"is to connect to '%s' and call "
"g_signal_stop_emission_by_name() in your signal handler to prevent "
"the default handler from running. Look at the source code "
"for the default handler in gtkiconview.c to get an idea what "
"your handler should do. (gtkiconview.c is in the GTK+ source "
"code.) If you're using GTK+ from a language other than C, "
"there may be a more natural way to override default handlers, e.g. via derivation.",
signal, g_type_name (required_iface), signal);
return FALSE;
}
else
return TRUE;
}
static void
remove_scroll_timeout (ExoIconView *icon_view)
{
if (icon_view->priv->scroll_timeout_id != 0)
{
g_source_remove (icon_view->priv->scroll_timeout_id);
icon_view->priv->scroll_timeout_id = 0;
}
}
static void
exo_icon_view_autoscroll (ExoIconView *icon_view)
{
gint px, py, x, y, width, height;
gint hoffset, voffset;
gfloat value;
gdk_window_get_pointer (gtk_widget_get_window (GTK_WIDGET (icon_view)), &px, &py, NULL);
#if GTK_CHECK_VERSION (3, 0, 0)
gdk_window_get_geometry (gtk_widget_get_window (GTK_WIDGET (icon_view)), &x, &y, &width, &height);
#else
gdk_window_get_geometry (gtk_widget_get_window (GTK_WIDGET (icon_view)), &x, &y, &width, &height, NULL);
#endif
/* see if we are near the edge. */
voffset = py - (y + 2 * SCROLL_EDGE_SIZE);
if (voffset > 0)
voffset = MAX (py - (y + height - 2 * SCROLL_EDGE_SIZE), 0);
hoffset = px - (x + 2 * SCROLL_EDGE_SIZE);
if (hoffset > 0)
hoffset = MAX (px - (x + width - 2 * SCROLL_EDGE_SIZE), 0);
if (voffset != 0)
{
value = CLAMP (gtk_adjustment_get_value (icon_view->priv->vadjustment) + voffset,
gtk_adjustment_get_lower (icon_view->priv->vadjustment),
gtk_adjustment_get_upper (icon_view->priv->vadjustment) - gtk_adjustment_get_page_size (icon_view->priv->vadjustment));
gtk_adjustment_set_value (icon_view->priv->vadjustment, value);
}
if (hoffset != 0)
{
value = CLAMP (gtk_adjustment_get_value (icon_view->priv->hadjustment) + hoffset,
gtk_adjustment_get_lower (icon_view->priv->hadjustment),
gtk_adjustment_get_upper (icon_view->priv->hadjustment) - gtk_adjustment_get_page_size (icon_view->priv->hadjustment));
gtk_adjustment_set_value (icon_view->priv->hadjustment, value);
}
}
static gboolean
drag_scroll_timeout (gpointer data)
{
ExoIconView *icon_view = EXO_ICON_VIEW (data);
GDK_THREADS_ENTER ();
exo_icon_view_autoscroll (icon_view);
GDK_THREADS_LEAVE ();
return TRUE;
}
static gboolean
set_destination (ExoIconView *icon_view,
GdkDragContext *context,
gint x,
gint y,
GdkDragAction *suggested_action,
GdkAtom *target)
{
GtkWidget *widget;
GtkTreePath *path = NULL;
ExoIconViewDropPosition pos;
ExoIconViewDropPosition old_pos;
GtkTreePath *old_dest_path = NULL;
gboolean can_drop = FALSE;
widget = GTK_WIDGET (icon_view);
*suggested_action = 0;
*target = GDK_NONE;
if (!icon_view->priv->dest_set)
{
/* someone unset us as a drag dest, note that if
* we return FALSE drag_leave isn't called
*/
exo_icon_view_set_drag_dest_item (icon_view,
NULL,
EXO_ICON_VIEW_DROP_LEFT);
remove_scroll_timeout (EXO_ICON_VIEW (widget));
return FALSE; /* no longer a drop site */
}
*target = gtk_drag_dest_find_target (widget, context, icon_view->priv->dest_targets);
if (*target == GDK_NONE)
return FALSE;
if (!exo_icon_view_get_dest_item_at_pos (icon_view, x, y, &path, &pos))
{
gint n_children;
GtkTreeModel *model;
/* the row got dropped on empty space, let's setup a special case
*/
if (path)
gtk_tree_path_free (path);
model = exo_icon_view_get_model (icon_view);
n_children = gtk_tree_model_iter_n_children (model, NULL);
if (n_children)
{
pos = EXO_ICON_VIEW_DROP_BELOW;
path = gtk_tree_path_new_from_indices (n_children - 1, -1);
}
else
{
pos = EXO_ICON_VIEW_DROP_ABOVE;
path = gtk_tree_path_new_from_indices (0, -1);
}
can_drop = TRUE;
goto out;
}
g_assert (path);
exo_icon_view_get_drag_dest_item (icon_view,
&old_dest_path,
&old_pos);
if (old_dest_path)
gtk_tree_path_free (old_dest_path);
if (TRUE /* FIXME if the location droppable predicate */)
{
can_drop = TRUE;
}
out:
if (can_drop)
{
GtkWidget *source_widget;
*suggested_action = gdk_drag_context_get_suggested_action (context);
source_widget = gtk_drag_get_source_widget (context);
if (source_widget == widget)
{
/* Default to MOVE, unless the user has
* pressed ctrl or shift to affect available actions
*/
if ((gdk_drag_context_get_actions (context) & GDK_ACTION_MOVE) != 0)
*suggested_action = GDK_ACTION_MOVE;
}
exo_icon_view_set_drag_dest_item (EXO_ICON_VIEW (widget),
path, pos);
}
else
{
/* can't drop here */
exo_icon_view_set_drag_dest_item (EXO_ICON_VIEW (widget),
NULL,
EXO_ICON_VIEW_DROP_LEFT);
}
if (path)
gtk_tree_path_free (path);
return TRUE;
}
static GtkTreePath*
get_logical_destination (ExoIconView *icon_view,
gboolean *drop_append_mode)
{
/* adjust path to point to the row the drop goes in front of */
GtkTreePath *path = NULL;
ExoIconViewDropPosition pos;
*drop_append_mode = FALSE;
exo_icon_view_get_drag_dest_item (icon_view, &path, &pos);
if (path == NULL)
return NULL;
if (pos == EXO_ICON_VIEW_DROP_RIGHT ||
pos == EXO_ICON_VIEW_DROP_BELOW)
{
GtkTreeIter iter;
GtkTreeModel *model = icon_view->priv->model;
if (!gtk_tree_model_get_iter (model, &iter, path) ||
!gtk_tree_model_iter_next (model, &iter))
*drop_append_mode = TRUE;
else
{
*drop_append_mode = FALSE;
gtk_tree_path_next (path);
}
}
return path;
}
static gboolean
exo_icon_view_maybe_begin_drag (ExoIconView *icon_view,
GdkEventMotion *event)
{
GdkDragContext *context;
GtkTreePath *path = NULL;
gint button;
GtkTreeModel *model;
gboolean retval = FALSE;
if (!icon_view->priv->source_set)
goto out;
if (icon_view->priv->pressed_button < 0)
goto out;
if (!gtk_drag_check_threshold (GTK_WIDGET (icon_view),
icon_view->priv->press_start_x,
icon_view->priv->press_start_y,
event->x, event->y))
goto out;
model = exo_icon_view_get_model (icon_view);
if (model == NULL)
goto out;
button = icon_view->priv->pressed_button;
icon_view->priv->pressed_button = -1;
path = exo_icon_view_get_path_at_pos (icon_view,
icon_view->priv->press_start_x,
icon_view->priv->press_start_y);
if (path == NULL)
goto out;
if (!GTK_IS_TREE_DRAG_SOURCE (model) ||
!gtk_tree_drag_source_row_draggable (GTK_TREE_DRAG_SOURCE (model),
path))
goto out;
/* FIXME Check whether we're a start button, if not return FALSE and
* free path
*/
/* Now we can begin the drag */
retval = TRUE;
context = gtk_drag_begin (GTK_WIDGET (icon_view),
icon_view->priv->source_targets,
icon_view->priv->source_actions,
button,
(GdkEvent*)event);
set_source_row (context, model, path);
out:
if (path)
gtk_tree_path_free (path);
return retval;
}
/* Source side drag signals */
static void
exo_icon_view_drag_begin (GtkWidget *widget,
GdkDragContext *context)
{
ExoIconView *icon_view;
ExoIconViewItem *item;
#if GTK_CHECK_VERSION (3, 0, 0)
cairo_surface_t *icon;
#else
GdkPixmap *icon;
#endif
gint x, y;
GtkTreePath *path;
icon_view = EXO_ICON_VIEW (widget);
/* if the user uses a custom DnD impl, we don't set the icon here */
if (!icon_view->priv->dest_set && !icon_view->priv->source_set)
return;
item = exo_icon_view_get_item_at_coords (icon_view,
icon_view->priv->press_start_x,
icon_view->priv->press_start_y,
TRUE,
NULL);
_exo_return_if_fail (item != NULL);
x = icon_view->priv->press_start_x - item->area.x + 1;
y = icon_view->priv->press_start_y - item->area.y + 1;
path = gtk_tree_path_new_from_indices (g_list_index (icon_view->priv->items, item), -1);
icon = exo_icon_view_create_drag_icon (icon_view, path);
gtk_tree_path_free (path);
#if GTK_CHECK_VERSION (3, 0, 0)
gtk_drag_set_icon_surface (context,
icon);
cairo_surface_destroy (icon);
#else
gtk_drag_set_icon_pixmap (context,
gdk_drawable_get_colormap (icon),
icon,
NULL,
x, y);
g_object_unref (icon);
#endif
}
static void
exo_icon_view_drag_end (GtkWidget *widget,
GdkDragContext *context)
{
/* do nothing */
}
static void
exo_icon_view_drag_data_get (GtkWidget *widget,
GdkDragContext *context,
GtkSelectionData *selection_data,
guint info,
guint time)
{
ExoIconView *icon_view;
GtkTreeModel *model;
GtkTreePath *source_row;
icon_view = EXO_ICON_VIEW (widget);
model = exo_icon_view_get_model (icon_view);
if (model == NULL)
return;
if (!icon_view->priv->dest_set)
return;
source_row = get_source_row (context);
if (source_row == NULL)
return;
/* We can implement the GTK_TREE_MODEL_ROW target generically for
* any model; for DragSource models there are some other targets
* we also support.
*/
if (GTK_IS_TREE_DRAG_SOURCE (model) &&
gtk_tree_drag_source_drag_data_get (GTK_TREE_DRAG_SOURCE (model),
source_row,
selection_data))
goto done;
/* If drag_data_get does nothing, try providing row data. */
if (gtk_selection_data_get_target (selection_data) == gdk_atom_intern ("GTK_TREE_MODEL_ROW", FALSE))
gtk_tree_set_row_drag_data (selection_data,
model,
source_row);
done:
gtk_tree_path_free (source_row);
}
static void
exo_icon_view_drag_data_delete (GtkWidget *widget,
GdkDragContext *context)
{
GtkTreeModel *model;
ExoIconView *icon_view;
GtkTreePath *source_row;
icon_view = EXO_ICON_VIEW (widget);
model = exo_icon_view_get_model (icon_view);
if (!check_model_dnd (model, GTK_TYPE_TREE_DRAG_SOURCE, "drag_data_delete"))
return;
if (!icon_view->priv->dest_set)
return;
source_row = get_source_row (context);
if (source_row == NULL)
return;
gtk_tree_drag_source_drag_data_delete (GTK_TREE_DRAG_SOURCE (model),
source_row);
gtk_tree_path_free (source_row);
set_source_row (context, NULL, NULL);
}
/* Target side drag signals */
static void
exo_icon_view_drag_leave (GtkWidget *widget,
GdkDragContext *context,
guint time)
{
ExoIconView *icon_view;
icon_view = EXO_ICON_VIEW (widget);
/* unset any highlight row */
exo_icon_view_set_drag_dest_item (icon_view,
NULL,
EXO_ICON_VIEW_DROP_LEFT);
remove_scroll_timeout (icon_view);
}
static gboolean
exo_icon_view_drag_motion (GtkWidget *widget,
GdkDragContext *context,
gint x,
gint y,
guint time)
{
ExoIconViewDropPosition pos;
GdkDragAction suggested_action = 0;
GtkTreePath *path = NULL;
ExoIconView *icon_view = EXO_ICON_VIEW (widget);
gboolean empty;
GdkAtom target;
if (!set_destination (icon_view, context, x, y, &suggested_action, &target))
return FALSE;
exo_icon_view_get_drag_dest_item (icon_view, &path, &pos);
/* we only know this *after* set_desination_row */
empty = icon_view->priv->empty_view_drop;
if (path == NULL && !empty)
{
/* Can't drop here. */
gdk_drag_status (context, 0, time);
}
else
{
if (icon_view->priv->scroll_timeout_id == 0)
icon_view->priv->scroll_timeout_id = g_timeout_add (50, drag_scroll_timeout, icon_view);
if (target == gdk_atom_intern ("GTK_TREE_MODEL_ROW", FALSE))
{
/* Request data so we can use the source row when
* determining whether to accept the drop
*/
set_status_pending (context, suggested_action);
gtk_drag_get_data (widget, context, target, time);
}
else
{
set_status_pending (context, 0);
gdk_drag_status (context, suggested_action, time);
}
}
if (path != NULL)
gtk_tree_path_free (path);
return TRUE;
}
static gboolean
exo_icon_view_drag_drop (GtkWidget *widget,
GdkDragContext *context,
gint x,
gint y,
guint time)
{
ExoIconView *icon_view;
GtkTreePath *path;
GdkDragAction suggested_action = 0;
GdkAtom target = GDK_NONE;
GtkTreeModel *model;
gboolean drop_append_mode;
icon_view = EXO_ICON_VIEW (widget);
model = exo_icon_view_get_model (icon_view);
remove_scroll_timeout (EXO_ICON_VIEW (widget));
if (!icon_view->priv->dest_set)
return FALSE;
if (!check_model_dnd (model, GTK_TYPE_TREE_DRAG_DEST, "drag_drop"))
return FALSE;
if (!set_destination (icon_view, context, x, y, &suggested_action, &target))
return FALSE;
path = get_logical_destination (icon_view, &drop_append_mode);
if (target != GDK_NONE && path != NULL)
{
/* in case a motion had requested drag data, change things so we
* treat drag data receives as a drop.
*/
set_status_pending (context, 0);
set_dest_row (context, model, path,
icon_view->priv->empty_view_drop, drop_append_mode);
}
if (path)
gtk_tree_path_free (path);
/* Unset this thing */
exo_icon_view_set_drag_dest_item (icon_view, NULL, EXO_ICON_VIEW_DROP_LEFT);
if (target != GDK_NONE)
{
gtk_drag_get_data (widget, context, target, time);
return TRUE;
}
else
return FALSE;
}
static void
exo_icon_view_drag_data_received (GtkWidget *widget,
GdkDragContext *context,
gint x,
gint y,
GtkSelectionData *selection_data,
guint info,
guint time)
{
GtkTreePath *path;
gboolean accepted = FALSE;
GtkTreeModel *model;
ExoIconView *icon_view;
GtkTreePath *dest_row;
GdkDragAction suggested_action;
gboolean drop_append_mode;
icon_view = EXO_ICON_VIEW (widget);
model = exo_icon_view_get_model (icon_view);
if (!check_model_dnd (model, GTK_TYPE_TREE_DRAG_DEST, "drag_data_received"))
return;
if (!icon_view->priv->dest_set)
return;
suggested_action = get_status_pending (context);
if (suggested_action)
{
/* We are getting this data due to a request in drag_motion,
* rather than due to a request in drag_drop, so we are just
* supposed to call drag_status, not actually paste in the
* data.
*/
path = get_logical_destination (icon_view, &drop_append_mode);
if (path == NULL)
suggested_action = 0;
if (suggested_action)
{
if (!gtk_tree_drag_dest_row_drop_possible (GTK_TREE_DRAG_DEST (model),
path,
selection_data))
suggested_action = 0;
}
gdk_drag_status (context, suggested_action, time);
if (path)
gtk_tree_path_free (path);
/* If you can't drop, remove user drop indicator until the next motion */
if (suggested_action == 0)
exo_icon_view_set_drag_dest_item (icon_view,
NULL,
EXO_ICON_VIEW_DROP_LEFT);
return;
}
dest_row = get_dest_row (context);
if (dest_row == NULL)
return;
if (gtk_selection_data_get_length (selection_data) >= 0)
{
if (gtk_tree_drag_dest_drag_data_received (GTK_TREE_DRAG_DEST (model),
dest_row,
selection_data))
accepted = TRUE;
}
gtk_drag_finish (context,
accepted,
(gdk_drag_context_get_selected_action (context) == GDK_ACTION_MOVE),
time);
gtk_tree_path_free (dest_row);
/* drop dest_row */
set_dest_row (context, NULL, NULL, FALSE, FALSE);
}
/**
* exo_icon_view_enable_model_drag_source:
* @icon_view : a #GtkIconTreeView
* @start_button_mask : Mask of allowed buttons to start drag
* @targets : the table of targets that the drag will support
* @n_targets : the number of items in @targets
* @actions : the bitmask of possible actions for a drag from this widget
*
* Turns @icon_view into a drag source for automatic DND.
*
* Since: 0.3.1
**/
void
exo_icon_view_enable_model_drag_source (ExoIconView *icon_view,
GdkModifierType start_button_mask,
const GtkTargetEntry *targets,
gint n_targets,
GdkDragAction actions)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
gtk_drag_source_set (GTK_WIDGET (icon_view), 0, NULL, 0, actions);
clear_source_info (icon_view);
icon_view->priv->start_button_mask = start_button_mask;
icon_view->priv->source_targets = gtk_target_list_new (targets, n_targets);
icon_view->priv->source_actions = actions;
icon_view->priv->source_set = TRUE;
unset_reorderable (icon_view);
}
/**
* exo_icon_view_enable_model_drag_dest:
* @icon_view : a #ExoIconView
* @targets : the table of targets that the drag will support
* @n_targets : the number of items in @targets
* @actions : the bitmask of possible actions for a drag from this widget
*
* Turns @icon_view into a drop destination for automatic DND.
*
* Since: 0.3.1
**/
void
exo_icon_view_enable_model_drag_dest (ExoIconView *icon_view,
const GtkTargetEntry *targets,
gint n_targets,
GdkDragAction actions)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
gtk_drag_dest_set (GTK_WIDGET (icon_view), 0, NULL, 0, actions);
clear_dest_info (icon_view);
icon_view->priv->dest_targets = gtk_target_list_new (targets, n_targets);
icon_view->priv->dest_actions = actions;
icon_view->priv->dest_set = TRUE;
unset_reorderable (icon_view);
}
/**
* exo_icon_view_unset_model_drag_source:
* @icon_view : a #ExoIconView
*
* Undoes the effect of #exo_icon_view_enable_model_drag_source().
*
* Since: 0.3.1
**/
void
exo_icon_view_unset_model_drag_source (ExoIconView *icon_view)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
if (icon_view->priv->source_set)
{
gtk_drag_source_unset (GTK_WIDGET (icon_view));
clear_source_info (icon_view);
}
unset_reorderable (icon_view);
}
/**
* exo_icon_view_unset_model_drag_dest:
* @icon_view : a #ExoIconView
*
* Undoes the effect of #exo_icon_view_enable_model_drag_dest().
*
* Since: 0.3.1
**/
void
exo_icon_view_unset_model_drag_dest (ExoIconView *icon_view)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
if (icon_view->priv->dest_set)
{
gtk_drag_dest_unset (GTK_WIDGET (icon_view));
clear_dest_info (icon_view);
}
unset_reorderable (icon_view);
}
/**
* exo_icon_view_set_drag_dest_item:
* @icon_view : a #ExoIconView
* @path : The path of the item to highlight, or %NULL.
* @pos : Specifies whether to drop, relative to the item
*
* Sets the item that is highlighted for feedback.
*
* Since: 0.3.1
*/
void
exo_icon_view_set_drag_dest_item (ExoIconView *icon_view,
GtkTreePath *path,
ExoIconViewDropPosition pos)
{
ExoIconViewItem *item;
GtkTreePath *previous_path;
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
/* Note; this function is exported to allow a custom DND
* implementation, so it can't touch TreeViewDragInfo
*/
if (icon_view->priv->dest_item != NULL)
{
/* determine and reset the previous path */
previous_path = gtk_tree_row_reference_get_path (icon_view->priv->dest_item);
gtk_tree_row_reference_free (icon_view->priv->dest_item);
icon_view->priv->dest_item = NULL;
/* check if the path is still valid */
if (G_LIKELY (previous_path != NULL))
{
/* schedule a redraw for the previous path */
item = g_list_nth_data (icon_view->priv->items, gtk_tree_path_get_indices (previous_path)[0]);
if (G_LIKELY (item != NULL))
exo_icon_view_queue_draw_item (icon_view, item);
gtk_tree_path_free (previous_path);
}
}
/* special case a drop on an empty model */
icon_view->priv->empty_view_drop = FALSE;
if (pos == GTK_TREE_VIEW_DROP_BEFORE && path
&& gtk_tree_path_get_depth (path) == 1
&& gtk_tree_path_get_indices (path)[0] == 0)
{
gint n_children;
n_children = gtk_tree_model_iter_n_children (icon_view->priv->model,
NULL);
if (n_children == 0)
icon_view->priv->empty_view_drop = TRUE;
}
icon_view->priv->dest_pos = pos;
if (G_LIKELY (path != NULL))
{
/* take a row reference for the new item path */
icon_view->priv->dest_item = gtk_tree_row_reference_new_proxy (G_OBJECT (icon_view), icon_view->priv->model, path);
/* schedule a redraw on the new path */
item = g_list_nth_data (icon_view->priv->items, gtk_tree_path_get_indices (path)[0]);
if (G_LIKELY (item != NULL))
exo_icon_view_queue_draw_item (icon_view, item);
}
}
/**
* exo_icon_view_get_drag_dest_item:
* @icon_view : a #ExoIconView
* @path : Return location for the path of the highlighted item, or %NULL.
* @pos : Return location for the drop position, or %NULL
*
* Gets information about the item that is highlighted for feedback.
*
* Since: 0.3.1
**/
void
exo_icon_view_get_drag_dest_item (ExoIconView *icon_view,
GtkTreePath **path,
ExoIconViewDropPosition *pos)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
if (path)
{
if (icon_view->priv->dest_item)
*path = gtk_tree_row_reference_get_path (icon_view->priv->dest_item);
else
*path = NULL;
}
if (pos)
*pos = icon_view->priv->dest_pos;
}
/**
* exo_icon_view_get_dest_item_at_pos:
* @icon_view : a #ExoIconView
* @drag_x : the position to determine the destination item for
* @drag_y : the position to determine the destination item for
* @path : Return location for the path of the highlighted item, or %NULL.
* @pos : Return location for the drop position, or %NULL
*
* Determines the destination item for a given position.
*
* Both @drag_x and @drag_y are given in icon window coordinates. Use
* #exo_icon_view_widget_to_icon_coords() if you need to translate
* widget coordinates first.
*
* Return value: whether there is an item at the given position.
*
* Since: 0.3.1
**/
gboolean
exo_icon_view_get_dest_item_at_pos (ExoIconView *icon_view,
gint drag_x,
gint drag_y,
GtkTreePath **path,
ExoIconViewDropPosition *pos)
{
ExoIconViewItem *item;
/* Note; this function is exported to allow a custom DND
* implementation, so it can't touch TreeViewDragInfo
*/
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), FALSE);
g_return_val_if_fail (drag_x >= 0, FALSE);
g_return_val_if_fail (drag_y >= 0, FALSE);
g_return_val_if_fail (icon_view->priv->bin_window != NULL, FALSE);
if (G_LIKELY (path != NULL))
*path = NULL;
item = exo_icon_view_get_item_at_coords (icon_view, drag_x, drag_y, FALSE, NULL);
if (G_UNLIKELY (item == NULL))
return FALSE;
if (G_LIKELY (path != NULL))
*path = gtk_tree_path_new_from_indices (g_list_index (icon_view->priv->items, item), -1);
if (G_LIKELY (pos != NULL))
{
if (drag_x < item->area.x + item->area.width / 4)
*pos = EXO_ICON_VIEW_DROP_LEFT;
else if (drag_x > item->area.x + item->area.width * 3 / 4)
*pos = EXO_ICON_VIEW_DROP_RIGHT;
else if (drag_y < item->area.y + item->area.height / 4)
*pos = EXO_ICON_VIEW_DROP_ABOVE;
else if (drag_y > item->area.y + item->area.height * 3 / 4)
*pos = EXO_ICON_VIEW_DROP_BELOW;
else
*pos = EXO_ICON_VIEW_DROP_INTO;
}
return TRUE;
}
/**
* exo_icon_view_create_drag_icon:
* @icon_view : a #ExoIconView
* @path : a #GtkTreePath in @icon_view
*
* Creates a #GdkPixmap or #cairo_surface_t representation of the item at @path.
* This image is used for a drag icon.
*
* Return value: a newly-allocated pixmap (gtk2) or cairo surface (gtk3) of the drag icon.
*
* Since: 0.3.1
**/
#if GTK_CHECK_VERSION (3, 0, 0)
cairo_surface_t*
#else
GdkPixmap*
#endif
exo_icon_view_create_drag_icon (ExoIconView *icon_view,
GtkTreePath *path)
{
GdkRectangle area;
GtkWidget *widget = GTK_WIDGET (icon_view);
#if GTK_CHECK_VERSION (3, 0, 0)
cairo_surface_t *drawable;
#else
GdkDrawable *drawable;
#endif
GList *lp;
gint index;
cairo_t *cr;
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), NULL);
g_return_val_if_fail (gtk_tree_path_get_depth (path) > 0, NULL);
/* verify that the widget is realized */
if (G_UNLIKELY (!gtk_widget_get_realized (GTK_WIDGET (icon_view))))
return NULL;
index = gtk_tree_path_get_indices (path)[0];
for (lp = icon_view->priv->items; lp != NULL; lp = lp->next)
{
ExoIconViewItem *item = lp->data;
if (G_UNLIKELY (index == g_list_index (icon_view->priv->items, item)))
{
#if GTK_CHECK_VERSION (3, 0, 0)
drawable = cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
item->area.width + 2,
item->area.height + 2);
cr = cairo_create (drawable);
#else
drawable = gdk_pixmap_new (icon_view->priv->bin_window,
item->area.width + 2,
item->area.height + 2,
-1);
cr = gdk_cairo_create (drawable);
#endif
cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
gdk_cairo_set_source_color (cr, >k_widget_get_style(widget)->base[gtk_widget_get_state (widget)]);
cairo_rectangle (cr, 0, 0, item->area.width + 2, item->area.height + 2);
cairo_fill (cr);
area.x = 0;
area.y = 0;
area.width = item->area.width;
area.height = item->area.height;
#if GTK_CHECK_VERSION (3, 0, 0)
exo_icon_view_paint_item (icon_view, item, &area, cr, 1, 1, FALSE);
#else
exo_icon_view_paint_item (icon_view, item, &area, drawable, 1, 1, FALSE);
#endif
gdk_cairo_set_source_color (cr, >k_widget_get_style(widget)->black);
cairo_rectangle (cr, 1, 1, item->area.width + 1, item->area.height + 1);
cairo_stroke (cr);
cairo_destroy (cr);
return drawable;
}
}
return NULL;
}
/**
* exo_icon_view_get_reorderable:
* @icon_view : a #ExoIconView
*
* Retrieves whether the user can reorder the list via drag-and-drop.
* See exo_icon_view_set_reorderable().
*
* Return value: %TRUE if the list can be reordered.
*
* Since: 0.3.1
**/
gboolean
exo_icon_view_get_reorderable (ExoIconView *icon_view)
{
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), FALSE);
return icon_view->priv->reorderable;
}
/**
* exo_icon_view_set_reorderable:
* @icon_view : A #ExoIconView.
* @reorderable : %TRUE, if the list of items can be reordered.
*
* This function is a convenience function to allow you to reorder models that
* support the #GtkTreeDragSourceIface and the #GtkTreeDragDestIface. Both
* #GtkTreeStore and #GtkListStore support these. If @reorderable is %TRUE, then
* the user can reorder the model by dragging and dropping rows. The
* developer can listen to these changes by connecting to the model's
* ::row-inserted and ::row-deleted signals.
*
* This function does not give you any degree of control over the order -- any
* reordering is allowed. If more control is needed, you should probably
* handle drag and drop manually.
*
* Since: 0.3.1
**/
void
exo_icon_view_set_reorderable (ExoIconView *icon_view,
gboolean reorderable)
{
static const GtkTargetEntry item_targets[] =
{
{ "GTK_TREE_MODEL_ROW", GTK_TARGET_SAME_WIDGET, 0, },
};
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
reorderable = (reorderable != FALSE);
if (G_UNLIKELY (icon_view->priv->reorderable == reorderable))
return;
if (G_LIKELY (reorderable))
{
exo_icon_view_enable_model_drag_source (icon_view, GDK_BUTTON1_MASK, item_targets, G_N_ELEMENTS (item_targets), GDK_ACTION_MOVE);
exo_icon_view_enable_model_drag_dest (icon_view, item_targets, G_N_ELEMENTS (item_targets), GDK_ACTION_MOVE);
}
else
{
exo_icon_view_unset_model_drag_source (icon_view);
exo_icon_view_unset_model_drag_dest (icon_view);
}
icon_view->priv->reorderable = reorderable;
g_object_notify (G_OBJECT (icon_view), "reorderable");
}
/*----------------------*
* Single-click support *
*----------------------*/
/**
* exo_icon_view_get_single_click:
* @icon_view : a #ExoIconView.
*
* Returns %TRUE if @icon_view is currently in single click mode,
* else %FALSE will be returned.
*
* Return value: whether @icon_view is currently in single click mode.
*
* Since: 0.3.1.3
**/
gboolean
exo_icon_view_get_single_click (const ExoIconView *icon_view)
{
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), FALSE);
return icon_view->priv->single_click;
}
/**
* exo_icon_view_set_single_click:
* @icon_view : a #ExoIconView.
* @single_click : %TRUE for single click, %FALSE for double click mode.
*
* If @single_click is %TRUE, @icon_view will be in single click mode
* afterwards, else @icon_view will be in double click mode.
*
* Since: 0.3.1.3
**/
void
exo_icon_view_set_single_click (ExoIconView *icon_view,
gboolean single_click)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
/* normalize the value */
single_click = !!single_click;
/* check if we have a new setting here */
if (icon_view->priv->single_click != single_click)
{
icon_view->priv->single_click = single_click;
g_object_notify (G_OBJECT (icon_view), "single-click");
}
}
/**
* exo_icon_view_get_single_click_timeout:
* @icon_view : a #ExoIconView.
*
* Returns the amount of time in milliseconds after which the
* item under the mouse cursor will be selected automatically
* in single click mode. A value of %0 means that the behavior
* is disabled and the user must alter the selection manually.
*
* Return value: the single click autoselect timeout or %0 if
* the behavior is disabled.
*
* Since: 0.3.1.5
**/
guint
exo_icon_view_get_single_click_timeout (const ExoIconView *icon_view)
{
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), 0u);
return icon_view->priv->single_click_timeout;
}
/**
* exo_icon_view_set_single_click_timeout:
* @icon_view : a #ExoIconView.
* @single_click_timeout : the new timeout or %0 to disable.
*
* If @single_click_timeout is a value greater than zero, it specifies
* the amount of time in milliseconds after which the item under the
* mouse cursor will be selected automatically in single click mode.
* A value of %0 for @single_click_timeout disables the autoselection
* for @icon_view.
*
* This setting does not have any effect unless the @icon_view is in
* single-click mode, see exo_icon_view_set_single_click().
*
* Since: 0.3.1.5
**/
void
exo_icon_view_set_single_click_timeout (ExoIconView *icon_view,
guint single_click_timeout)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
/* check if we have a new setting */
if (icon_view->priv->single_click_timeout != single_click_timeout)
{
/* apply the new setting */
icon_view->priv->single_click_timeout = single_click_timeout;
/* be sure to cancel any pending single click timeout */
if (G_UNLIKELY (icon_view->priv->single_click_timeout_id != 0))
g_source_remove (icon_view->priv->single_click_timeout_id);
/* notify listeners */
g_object_notify (G_OBJECT (icon_view), "single-click-timeout");
}
}
static gboolean
exo_icon_view_single_click_timeout (gpointer user_data)
{
ExoIconViewItem *item;
gboolean dirty = FALSE;
ExoIconView *icon_view = EXO_ICON_VIEW (user_data);
GDK_THREADS_ENTER ();
/* verify that we are in single-click mode, have focus and a prelit item */
if (gtk_widget_has_focus (GTK_WIDGET (icon_view)) && icon_view->priv->single_click && icon_view->priv->prelit_item != NULL)
{
/* work on the prelit item */
item = icon_view->priv->prelit_item;
/* be sure the item is fully visible */
exo_icon_view_scroll_to_item (icon_view, item);
/* change the selection appropriately */
if (G_UNLIKELY (icon_view->priv->selection_mode == GTK_SELECTION_NONE))
{
exo_icon_view_set_cursor_item (icon_view, item, -1);
}
else if ((icon_view->priv->single_click_timeout_state & GDK_SHIFT_MASK) != 0
&& icon_view->priv->selection_mode == GTK_SELECTION_MULTIPLE)
{
if (!(icon_view->priv->single_click_timeout_state & GDK_CONTROL_MASK))
/* unselect all previously selected items */
exo_icon_view_unselect_all_internal (icon_view);
/* select all items between the anchor and the prelit item */
exo_icon_view_set_cursor_item (icon_view, item, -1);
if (icon_view->priv->anchor_item == NULL)
icon_view->priv->anchor_item = item;
else
exo_icon_view_select_all_between (icon_view, icon_view->priv->anchor_item, item);
/* selection was changed */
dirty = TRUE;
}
else
{
if ((icon_view->priv->selection_mode == GTK_SELECTION_MULTIPLE ||
((icon_view->priv->selection_mode == GTK_SELECTION_SINGLE) && item->selected)) &&
(icon_view->priv->single_click_timeout_state & GDK_CONTROL_MASK) != 0)
{
item->selected = !item->selected;
exo_icon_view_queue_draw_item (icon_view, item);
dirty = TRUE;
}
else if (!item->selected)
{
exo_icon_view_unselect_all_internal (icon_view);
exo_icon_view_queue_draw_item (icon_view, item);
item->selected = TRUE;
dirty = TRUE;
}
exo_icon_view_set_cursor_item (icon_view, item, -1);
icon_view->priv->anchor_item = item;
}
}
/* emit "selection-changed" and stop drawing keyboard
* focus indicator if the selection was altered
*/
if (G_LIKELY (dirty))
{
/* reset "draw keyfocus" flag */
EXO_ICON_VIEW_UNSET_FLAG (icon_view, EXO_ICON_VIEW_DRAW_KEYFOCUS);
/* emit "selection-changed" */
g_signal_emit (G_OBJECT (icon_view), icon_view_signals[SELECTION_CHANGED], 0);
}
GDK_THREADS_LEAVE ();
return FALSE;
}
static void
exo_icon_view_single_click_timeout_destroy (gpointer user_data)
{
EXO_ICON_VIEW (user_data)->priv->single_click_timeout_id = 0;
}
/*----------------------------*
* Interactive search support *
*----------------------------*/
/**
* exo_icon_view_get_enable_search:
* @icon_view : an #ExoIconView.
*
* Returns whether or not the @icon_view allows to start
* interactive searching by typing in text.
*
* Return value: whether or not to let the user search
* interactively.
*
* Since: 0.3.1.3
**/
gboolean
exo_icon_view_get_enable_search (const ExoIconView *icon_view)
{
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), FALSE);
return icon_view->priv->enable_search;
}
/**
* exo_icon_view_set_enable_search:
* @icon_view : an #ExoIconView.
* @enable_search : %TRUE if the user can search interactively.
*
* If @enable_search is set, then the user can type in text to search through
* the @icon_view interactively (this is sometimes called "typeahead find").
*
* Note that even if this is %FALSE, the user can still initiate a search
* using the "start-interactive-search" key binding.
*
* Since: 0.3.1.3
**/
void
exo_icon_view_set_enable_search (ExoIconView *icon_view,
gboolean enable_search)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
enable_search = !!enable_search;
if (G_LIKELY (icon_view->priv->enable_search != enable_search))
{
icon_view->priv->enable_search = enable_search;
g_object_notify (G_OBJECT (icon_view), "enable-search");
}
}
/**
* exo_icon_view_get_search_column:
* @icon_view : an #ExoIconView.
*
* Returns the column searched on by the interactive search code.
*
* Return value: the column the interactive search code searches in.
*
* Since: 0.3.1.3
**/
gint
exo_icon_view_get_search_column (const ExoIconView *icon_view)
{
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), -1);
return icon_view->priv->search_column;
}
/**
* exo_icon_view_set_search_column:
* @icon_view : an #ExoIconView.
* @search_column : the column of the model to search in, or -1 to disable searching.
*
* Sets @search_column as the column where the interactive search code should search in.
*
* If the search column is set, user can use the "start-interactive-search" key
* binding to bring up search popup. The "enable-search" property controls
* whether simply typing text will also start an interactive search.
*
* Note that @search_column refers to a column of the model.
*
* Since: 0.3.1.3
**/
void
exo_icon_view_set_search_column (ExoIconView *icon_view,
gint search_column)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
g_return_if_fail (search_column >= -1);
if (G_LIKELY (icon_view->priv->search_column != search_column))
{
icon_view->priv->search_column = search_column;
g_object_notify (G_OBJECT (icon_view), "search-column");
}
}
/**
* exo_icon_view_get_search_equal_func:
* @icon_view : an #ExoIconView.
*
* Returns the compare function currently in use.
*
* Return value: the currently used compare function for the search code.
*
* Since: 0.3.1.3
**/
ExoIconViewSearchEqualFunc
exo_icon_view_get_search_equal_func (const ExoIconView *icon_view)
{
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), NULL);
return icon_view->priv->search_equal_func;
}
/**
* exo_icon_view_set_search_equal_func:
* @icon_view : an #ExoIconView.
* @search_equal_func : the compare function to use during the search, or %NULL.
* @search_equal_data : user data to pass to @search_equal_func, or %NULL.
* @search_equal_destroy : destroy notifier for @search_equal_data, or %NULL.
*
* Sets the compare function for the interactive search capabilities;
* note that some like strcmp() returning 0 for equality
* #ExoIconViewSearchEqualFunc returns %FALSE on matches.
*
* Specifying %NULL for @search_equal_func will reset @icon_view to use the default
* search equal function.
*
* Since: 0.3.1.3
**/
void
exo_icon_view_set_search_equal_func (ExoIconView *icon_view,
ExoIconViewSearchEqualFunc search_equal_func,
gpointer search_equal_data,
GDestroyNotify search_equal_destroy)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
g_return_if_fail (search_equal_func != NULL ||
(search_equal_data == NULL && search_equal_destroy == NULL));
/* destroy the previous data (if any) */
if (G_UNLIKELY (icon_view->priv->search_equal_destroy != NULL
&& icon_view->priv->search_equal_data != NULL)) //sfm
(*icon_view->priv->search_equal_destroy) (icon_view->priv->search_equal_data);
icon_view->priv->search_equal_func = (search_equal_func != NULL) ?
search_equal_func :
exo_icon_view_search_equal_func;
icon_view->priv->search_equal_data = search_equal_data;
icon_view->priv->search_equal_destroy = search_equal_destroy;
}
/**
* exo_icon_view_get_search_position_func:
* @icon_view : an #ExoIconView.
*
* Returns the search dialog positioning function currently in use.
*
* Return value: the currently used function for positioning the search dialog.
*
* Since: 0.3.1.3
**/
ExoIconViewSearchPositionFunc
exo_icon_view_get_search_position_func (const ExoIconView *icon_view)
{
g_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), NULL);
return icon_view->priv->search_position_func;
}
/**
* exo_icon_view_set_search_position_func:
* @icon_view : an #ExoIconView.
* @search_position_func : the function to use to position the search dialog, or %NULL.
* @search_position_data : user data to pass to @search_position_func, or %NULL.
* @search_position_destroy : destroy notifier for @search_position_data, or %NULL.
*
* Sets the function to use when positioning the seach dialog.
*
* Specifying %NULL for @search_position_func will reset @icon_view to use the default
* search position function.
*
* Since: 0.3.1.3
**/
void
exo_icon_view_set_search_position_func (ExoIconView *icon_view,
ExoIconViewSearchPositionFunc search_position_func,
gpointer search_position_data,
GDestroyNotify search_position_destroy)
{
g_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
g_return_if_fail (search_position_func != NULL || (search_position_data == NULL && search_position_destroy == NULL));
/* destroy the previous data (if any) */
if (icon_view->priv->search_position_destroy != NULL)
(*icon_view->priv->search_position_destroy) (icon_view->priv->search_position_data);
icon_view->priv->search_position_func = (search_position_func != NULL) ? search_position_func : exo_icon_view_search_position_func;
icon_view->priv->search_position_data = search_position_data;
icon_view->priv->search_position_destroy = search_position_destroy;
}
static void
exo_icon_view_search_activate (GtkEntry *entry,
ExoIconView *icon_view)
{
GtkTreePath *path;
/* hide the interactive search dialog */
exo_icon_view_search_dialog_hide (icon_view->priv->search_window, icon_view);
/* check if we have a cursor item, and if so, activate it */
if (exo_icon_view_get_cursor (icon_view, &path, NULL))
{
/* only activate the cursor item if it's selected */
if (exo_icon_view_path_is_selected (icon_view, path))
exo_icon_view_item_activated (icon_view, path);
gtk_tree_path_free (path);
}
}
static void
exo_icon_view_search_dialog_hide (GtkWidget *search_dialog,
ExoIconView *icon_view)
{
_exo_return_if_fail (GTK_IS_WIDGET (search_dialog));
_exo_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
if (icon_view->priv->search_disable_popdown)
return;
/* disconnect the "changed" signal handler */
if (icon_view->priv->search_entry_changed_id != 0)
{
g_signal_handler_disconnect (G_OBJECT (icon_view->priv->search_entry), icon_view->priv->search_entry_changed_id);
icon_view->priv->search_entry_changed_id = 0;
}
/* disable the flush timeout */
if (icon_view->priv->search_timeout_id != 0)
g_source_remove (icon_view->priv->search_timeout_id);
/* send focus-out event */
_exo_gtk_widget_send_focus_change (icon_view->priv->search_entry, FALSE);
gtk_widget_hide (search_dialog);
gtk_entry_set_text (GTK_ENTRY (icon_view->priv->search_entry), "");
}
static void
exo_icon_view_search_ensure_directory (ExoIconView *icon_view)
{
GtkWidget *toplevel;
GtkWidget *frame;
GtkWidget *vbox;
/* determine the toplevel window */
toplevel = gtk_widget_get_toplevel (GTK_WIDGET (icon_view));
/* check if we already have a search window */
if (G_LIKELY (icon_view->priv->search_window != NULL))
{
if (gtk_window_has_group (GTK_WINDOW (toplevel)))
gtk_window_group_add_window (gtk_window_get_group (GTK_WINDOW (toplevel)), GTK_WINDOW (icon_view->priv->search_window));
else if (gtk_window_has_group (GTK_WINDOW (icon_view->priv->search_window)))
gtk_window_group_remove_window (gtk_window_get_group (GTK_WINDOW (icon_view->priv->search_window)), GTK_WINDOW (icon_view->priv->search_window));
return;
}
/* allocate a new search window */
icon_view->priv->search_window = gtk_window_new (GTK_WINDOW_POPUP);
if (gtk_window_has_group (GTK_WINDOW (toplevel)))
gtk_window_group_add_window (gtk_window_get_group (GTK_WINDOW (toplevel)), GTK_WINDOW (icon_view->priv->search_window));
gtk_window_set_modal (GTK_WINDOW (icon_view->priv->search_window), TRUE);
gtk_window_set_screen (GTK_WINDOW (icon_view->priv->search_window), gtk_widget_get_screen (GTK_WIDGET (icon_view)));
/* connect signal handlers */
g_signal_connect (G_OBJECT (icon_view->priv->search_window), "delete-event", G_CALLBACK (exo_icon_view_search_delete_event), icon_view);
g_signal_connect (G_OBJECT (icon_view->priv->search_window), "scroll-event", G_CALLBACK (exo_icon_view_search_scroll_event), icon_view);
g_signal_connect (G_OBJECT (icon_view->priv->search_window), "key-press-event", G_CALLBACK (exo_icon_view_search_key_press_event), icon_view);
g_signal_connect (G_OBJECT (icon_view->priv->search_window), "button-press-event", G_CALLBACK (exo_icon_view_search_button_press_event), icon_view);
/* allocate the frame widget */
frame = g_object_new (GTK_TYPE_FRAME, "shadow-type", GTK_SHADOW_ETCHED_IN, NULL);
gtk_container_add (GTK_CONTAINER (icon_view->priv->search_window), frame);
gtk_widget_show (frame);
/* allocate the vertical box */
vbox = g_object_new (GTK_TYPE_VBOX, "border-width", 3, NULL);
gtk_container_add (GTK_CONTAINER (frame), vbox);
gtk_widget_show (vbox);
/* allocate the search entry widget */
icon_view->priv->search_entry = gtk_entry_new ();
g_signal_connect (G_OBJECT (icon_view->priv->search_entry), "activate", G_CALLBACK (exo_icon_view_search_activate), icon_view);
#if GTK_CHECK_VERSION (3, 0, 0)
g_signal_connect (G_OBJECT (GTK_ENTRY (icon_view->priv->search_entry)), "preedit-changed",
G_CALLBACK (exo_icon_view_search_preedit_changed), icon_view);
#else
g_signal_connect (G_OBJECT (GTK_ENTRY (icon_view->priv->search_entry)->im_context), "preedit-changed",
G_CALLBACK (exo_icon_view_search_preedit_changed), icon_view);
#endif
gtk_box_pack_start (GTK_BOX (vbox), icon_view->priv->search_entry, TRUE, TRUE, 0);
gtk_widget_realize (icon_view->priv->search_entry);
gtk_widget_show (icon_view->priv->search_entry);
}
static void
exo_icon_view_search_init (GtkWidget *search_entry,
ExoIconView *icon_view)
{
GtkTreeModel *model;
GtkTreeIter iter;
const gchar *text;
gint length;
gint count = 0;
_exo_return_if_fail (GTK_IS_ENTRY (search_entry));
_exo_return_if_fail (EXO_IS_ICON_VIEW (icon_view));
/* determine the current text for the search entry */
text = gtk_entry_get_text (GTK_ENTRY (search_entry));
if (G_UNLIKELY (text == NULL))
return;
/* unselect all items */
exo_icon_view_unselect_all (icon_view);
/* renew the flush timeout */
if ((icon_view->priv->search_timeout_id != 0))
{
/* drop the previous timeout */
g_source_remove (icon_view->priv->search_timeout_id);
/* schedule a new timeout */
icon_view->priv->search_timeout_id = g_timeout_add_full (G_PRIORITY_LOW, EXO_ICON_VIEW_SEARCH_DIALOG_TIMEOUT,
exo_icon_view_search_timeout, icon_view,
exo_icon_view_search_timeout_destroy);
}
/* verify that we have a search text */
length = strlen (text);
if (length < 1)
return;
/* verify that we have a valid model */
model = exo_icon_view_get_model (icon_view);
if (G_UNLIKELY (model == NULL))
return;
/* start the interactive search */
if (gtk_tree_model_get_iter_first (model, &iter))
{
/* let's see if we have a match */
if (exo_icon_view_search_iter (icon_view, model, &iter, text, &count, 1))
icon_view->priv->search_selected_iter = 1;
}
}
static gboolean
exo_icon_view_search_iter (ExoIconView *icon_view,
GtkTreeModel *model,
GtkTreeIter *iter,
const gchar *text,
gint *count,
gint n)
{
GtkTreePath *path;
_exo_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), FALSE);
_exo_return_val_if_fail (GTK_IS_TREE_MODEL (model), FALSE);
_exo_return_val_if_fail (count != NULL, FALSE);
/* search for a matching item */
do
{
if (!(*icon_view->priv->search_equal_func) (model, icon_view->priv->search_column, text, iter, icon_view->priv->search_equal_data))
{
(*count) += 1;
if (*count == n)
{
/* place cursor on the item and select it */
path = gtk_tree_model_get_path (model, iter);
exo_icon_view_select_path (icon_view, path);
exo_icon_view_set_cursor (icon_view, path, NULL, FALSE);
gtk_tree_path_free (path);
return TRUE;
}
}
}
while (gtk_tree_model_iter_next (model, iter));
/* no match */
return FALSE;
}
static void
exo_icon_view_search_move (GtkWidget *widget,
ExoIconView *icon_view,
gboolean move_up)
{
GtkTreeModel *model;
const gchar *text;
GtkTreeIter iter;
gboolean retval;
gint length;
gint count = 0;
/* determine the current text for the search entry */
text = gtk_entry_get_text (GTK_ENTRY (icon_view->priv->search_entry));
if (G_UNLIKELY (text == NULL))
return;
/* if we already selected the first item, we cannot go up */
if (move_up && icon_view->priv->search_selected_iter == 1)
return;
/* determine the length of the search text */
length = strlen (text);
if (G_UNLIKELY (length < 1))
return;
/* unselect all items */
exo_icon_view_unselect_all (icon_view);
/* verify that we have a valid model */
model = exo_icon_view_get_model (icon_view);
if (G_UNLIKELY (model == NULL))
return;
/* determine the iterator to the first item */
if (!gtk_tree_model_get_iter_first (model, &iter))
return;
/* first attempt to search */
retval = exo_icon_view_search_iter (icon_view, model, &iter, text, &count, move_up
? (icon_view->priv->search_selected_iter - 1)
: (icon_view->priv->search_selected_iter + 1));
/* check if we found something */
if (G_LIKELY (retval))
{
/* match found */
icon_view->priv->search_selected_iter += move_up ? -1 : 1;
}
else
{
/* return to old iter */
if (gtk_tree_model_get_iter_first (model, &iter))
{
count = 0;
exo_icon_view_search_iter (icon_view, model, &iter, text, &count,
icon_view->priv->search_selected_iter);
}
}
}
#if GTK_CHECK_VERSION (3, 0, 0)
static void
exo_icon_view_search_preedit_changed (GtkEntry *entry,
gchar *preedit,
#else
static void
exo_icon_view_search_preedit_changed (GtkIMContext *im_context,
#endif
ExoIconView *icon_view)
{
icon_view->priv->search_imcontext_changed = TRUE;
/* re-register the search timeout */
if (G_LIKELY (icon_view->priv->search_timeout_id != 0))
{
g_source_remove (icon_view->priv->search_timeout_id);
icon_view->priv->search_timeout_id = g_timeout_add_full (G_PRIORITY_LOW, EXO_ICON_VIEW_SEARCH_DIALOG_TIMEOUT,
exo_icon_view_search_timeout, icon_view,
exo_icon_view_search_timeout_destroy);
}
}
static gboolean
exo_icon_view_search_start (ExoIconView *icon_view,
gboolean keybinding)
{
GTypeClass *klass;
/* check if typeahead is enabled */
if (G_UNLIKELY (!icon_view->priv->enable_search && !keybinding))
return FALSE;
/* check if we already display the search window */
if (icon_view->priv->search_window != NULL && gtk_widget_get_visible (icon_view->priv->search_window))
return TRUE;
/* we only start interactive search if we have focus,
* we don't want to start interactive search if one of
* our children has the focus.
*/
if (!gtk_widget_has_focus (GTK_WIDGET (icon_view)))
return FALSE;
/* verify that we have a search column */
if (G_UNLIKELY (icon_view->priv->search_column < 0))
return FALSE;
exo_icon_view_search_ensure_directory (icon_view);
/* clear search entry if we were started by a keybinding */
if (G_UNLIKELY (keybinding))
gtk_entry_set_text (GTK_ENTRY (icon_view->priv->search_entry), "");
/* determine the position for the search dialog */
(*icon_view->priv->search_position_func) (icon_view, icon_view->priv->search_window, icon_view->priv->search_position_data);
/* display the search dialog */
gtk_widget_show (icon_view->priv->search_window);
/* connect "changed" signal for the entry */
if (G_UNLIKELY (icon_view->priv->search_entry_changed_id == 0))
{
icon_view->priv->search_entry_changed_id = g_signal_connect (G_OBJECT (icon_view->priv->search_entry), "changed",
G_CALLBACK (exo_icon_view_search_init), icon_view);
}
/* start the search timeout */
icon_view->priv->search_timeout_id = g_timeout_add_full (G_PRIORITY_LOW, EXO_ICON_VIEW_SEARCH_DIALOG_TIMEOUT,
exo_icon_view_search_timeout, icon_view,
exo_icon_view_search_timeout_destroy);
/* grab focus will select all the text, we don't want that to happen, so we
* call the parent instance and bypass the selection change. This is probably
* really hackish, but GtkTreeView does it as well *hrhr*
*/
klass = g_type_class_peek_parent (GTK_ENTRY_GET_CLASS (icon_view->priv->search_entry));
(*GTK_WIDGET_CLASS (klass)->grab_focus) (icon_view->priv->search_entry);
/* send focus-in event */
_exo_gtk_widget_send_focus_change (icon_view->priv->search_entry, TRUE);
/* search first matching iter */
exo_icon_view_search_init (icon_view->priv->search_entry, icon_view);
return TRUE;
}
static gboolean
exo_icon_view_search_equal_func (GtkTreeModel *model,
gint column,
const gchar *key,
GtkTreeIter *iter,
gpointer user_data)
{
const gchar *str;
gboolean retval = TRUE;
GValue transformed = { 0, };
GValue value = { 0, };
gchar *case_normalized_string = NULL;
gchar *case_normalized_key = NULL;
gchar *normalized_string;
gchar *normalized_key;
/* determine the value for the column/iter */
gtk_tree_model_get_value (model, iter, column, &value);
/* try to transform the value to a string */
g_value_init (&transformed, G_TYPE_STRING);
if (!g_value_transform (&value, &transformed))
{
g_value_unset (&value);
return TRUE;
}
g_value_unset (&value);
/* check if we have a string value */
str = g_value_get_string (&transformed);
if (G_UNLIKELY (str == NULL))
{
g_value_unset (&transformed);
return TRUE;
}
/* normalize the string and the key */
normalized_string = g_utf8_normalize (str, -1, G_NORMALIZE_ALL);
normalized_key = g_utf8_normalize (key, -1, G_NORMALIZE_ALL);
/* check if we have normalized both string */
if (G_LIKELY (normalized_string != NULL && normalized_key != NULL))
{
case_normalized_string = g_utf8_casefold (normalized_string, -1);
case_normalized_key = g_utf8_casefold (normalized_key, -1);
/* compare the casefolded strings */
if (strncmp (case_normalized_key, case_normalized_string, strlen (case_normalized_key)) == 0)
retval = FALSE;
}
/* cleanup */
g_free (case_normalized_string);
g_free (case_normalized_key);
g_value_unset (&transformed);
g_free (normalized_string);
g_free (normalized_key);
return retval;
}
static void
exo_icon_view_search_position_func (ExoIconView *icon_view,
GtkWidget *search_dialog,
gpointer user_data)
{
GtkRequisition requisition;
GdkRectangle monitor;
GdkWindow *view_window = gtk_widget_get_window (GTK_WIDGET (icon_view));
GdkScreen *screen = gtk_widget_get_screen(GTK_WIDGET(icon_view));
gint view_width, view_height;
gint view_x, view_y;
gint monitor_num;
gint x, y;
/* determine the monitor geometry */
monitor_num = gdk_screen_get_monitor_at_window (screen, view_window);
gdk_screen_get_monitor_geometry (screen, monitor_num, &monitor);
/* make sure the search dialog is realized */
gtk_widget_realize (search_dialog);
gdk_window_get_origin (view_window, &view_x, &view_y);
view_width = gdk_window_get_width (view_window);
view_height = gdk_window_get_height (view_window);
gtk_widget_size_request (search_dialog, &requisition);
if (view_x + view_width - requisition.width > gdk_screen_get_width (screen))
x = gdk_screen_get_width (screen) - requisition.width;
else if (view_x + view_width - requisition.width < 0)
x = 0;
else
x = view_x + view_width - requisition.width;
if (view_y + view_height > gdk_screen_get_height (screen))
y = gdk_screen_get_height (screen) - requisition.height;
else if (view_y + view_height < 0) /* isn't really possible ... */
y = 0;
else
y = view_y + view_height;
gtk_window_move (GTK_WINDOW (search_dialog), x, y);
}
static gboolean
exo_icon_view_search_button_press_event (GtkWidget *widget,
GdkEventButton *event,
ExoIconView *icon_view)
{
_exo_return_val_if_fail (GTK_IS_WIDGET (widget), FALSE);
_exo_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), FALSE);
/* hide the search dialog */
exo_icon_view_search_dialog_hide (widget, icon_view);
if (event->window == icon_view->priv->bin_window)
exo_icon_view_button_press_event (GTK_WIDGET (icon_view), event);
return TRUE;
}
static gboolean
exo_icon_view_search_delete_event (GtkWidget *widget,
GdkEventAny *event,
ExoIconView *icon_view)
{
_exo_return_val_if_fail (GTK_IS_WIDGET (widget), FALSE);
_exo_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), FALSE);
/* hide the search dialog */
exo_icon_view_search_dialog_hide (widget, icon_view);
return TRUE;
}
static gboolean
exo_icon_view_search_key_press_event (GtkWidget *widget,
GdkEventKey *event,
ExoIconView *icon_view)
{
gboolean retval = FALSE;
_exo_return_val_if_fail (GTK_IS_WIDGET (widget), FALSE);
_exo_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), FALSE);
/* close window and cancel the search */
if (event->keyval == GDK_KEY_Escape || event->keyval == GDK_KEY_Tab)
{
exo_icon_view_search_dialog_hide (widget, icon_view);
return TRUE;
}
/* select previous matching iter */
if (event->keyval == GDK_KEY_Up || event->keyval == GDK_KEY_KP_Up)
{
exo_icon_view_search_move (widget, icon_view, TRUE);
retval = TRUE;
}
if (((event->state & (GDK_CONTROL_MASK | GDK_SHIFT_MASK)) == (GDK_CONTROL_MASK | GDK_SHIFT_MASK))
&& (event->keyval == GDK_KEY_g || event->keyval == GDK_KEY_G))
{
exo_icon_view_search_move (widget, icon_view, TRUE);
retval = TRUE;
}
/* select next matching iter */
if (event->keyval == GDK_KEY_Down || event->keyval == GDK_KEY_KP_Down)
{
exo_icon_view_search_move (widget, icon_view, FALSE);
retval = TRUE;
}
if (((event->state & (GDK_CONTROL_MASK | GDK_SHIFT_MASK)) == GDK_CONTROL_MASK)
&& (event->keyval == GDK_KEY_g || event->keyval == GDK_KEY_G))
{
exo_icon_view_search_move (widget, icon_view, FALSE);
retval = TRUE;
}
/* renew the flush timeout */
if (retval && (icon_view->priv->search_timeout_id != 0))
{
/* drop the previous timeout */
g_source_remove (icon_view->priv->search_timeout_id);
/* schedule a new timeout */
icon_view->priv->search_timeout_id = g_timeout_add_full (G_PRIORITY_LOW, EXO_ICON_VIEW_SEARCH_DIALOG_TIMEOUT,
exo_icon_view_search_timeout, icon_view,
exo_icon_view_search_timeout_destroy);
}
return retval;
}
static gboolean
exo_icon_view_search_scroll_event (GtkWidget *widget,
GdkEventScroll *event,
ExoIconView *icon_view)
{
gboolean retval = TRUE;
_exo_return_val_if_fail (GTK_IS_WIDGET (widget), FALSE);
_exo_return_val_if_fail (EXO_IS_ICON_VIEW (icon_view), FALSE);
if (event->direction == GDK_SCROLL_UP)
exo_icon_view_search_move (widget, icon_view, TRUE);
else if (event->direction == GDK_SCROLL_DOWN)
exo_icon_view_search_move (widget, icon_view, FALSE);
else
retval = FALSE;
return retval;
}
static gboolean
exo_icon_view_search_timeout (gpointer user_data)
{
ExoIconView *icon_view = EXO_ICON_VIEW (user_data);
GDK_THREADS_ENTER ();
exo_icon_view_search_dialog_hide (icon_view->priv->search_window, icon_view);
GDK_THREADS_LEAVE ();
return FALSE;
}
static void
exo_icon_view_search_timeout_destroy (gpointer user_data)
{
EXO_ICON_VIEW (user_data)->priv->search_timeout_id = 0;
}
gboolean exo_icon_view_is_rubber_banding_active( ExoIconView* icon_view ) //sfm
{
return icon_view->priv->doing_rubberband;
}
|
173 | ./spacefm/src/exo/exo-marshal.c |
#include <glib-object.h>
#ifdef G_ENABLE_DEBUG
#define g_marshal_value_peek_boolean(v) g_value_get_boolean (v)
#define g_marshal_value_peek_char(v) g_value_get_char (v)
#define g_marshal_value_peek_uchar(v) g_value_get_uchar (v)
#define g_marshal_value_peek_int(v) g_value_get_int (v)
#define g_marshal_value_peek_uint(v) g_value_get_uint (v)
#define g_marshal_value_peek_long(v) g_value_get_long (v)
#define g_marshal_value_peek_ulong(v) g_value_get_ulong (v)
#define g_marshal_value_peek_int64(v) g_value_get_int64 (v)
#define g_marshal_value_peek_uint64(v) g_value_get_uint64 (v)
#define g_marshal_value_peek_enum(v) g_value_get_enum (v)
#define g_marshal_value_peek_flags(v) g_value_get_flags (v)
#define g_marshal_value_peek_float(v) g_value_get_float (v)
#define g_marshal_value_peek_double(v) g_value_get_double (v)
#define g_marshal_value_peek_string(v) (char*) g_value_get_string (v)
#define g_marshal_value_peek_param(v) g_value_get_param (v)
#define g_marshal_value_peek_boxed(v) g_value_get_boxed (v)
#define g_marshal_value_peek_pointer(v) g_value_get_pointer (v)
#define g_marshal_value_peek_object(v) g_value_get_object (v)
#else /* !G_ENABLE_DEBUG */
/* WARNING: This code accesses GValues directly, which is UNSUPPORTED API.
* Do not access GValues directly in your code. Instead, use the
* g_value_get_*() functions
*/
#define g_marshal_value_peek_boolean(v) (v)->data[0].v_int
#define g_marshal_value_peek_char(v) (v)->data[0].v_int
#define g_marshal_value_peek_uchar(v) (v)->data[0].v_uint
#define g_marshal_value_peek_int(v) (v)->data[0].v_int
#define g_marshal_value_peek_uint(v) (v)->data[0].v_uint
#define g_marshal_value_peek_long(v) (v)->data[0].v_long
#define g_marshal_value_peek_ulong(v) (v)->data[0].v_ulong
#define g_marshal_value_peek_int64(v) (v)->data[0].v_int64
#define g_marshal_value_peek_uint64(v) (v)->data[0].v_uint64
#define g_marshal_value_peek_enum(v) (v)->data[0].v_long
#define g_marshal_value_peek_flags(v) (v)->data[0].v_ulong
#define g_marshal_value_peek_float(v) (v)->data[0].v_float
#define g_marshal_value_peek_double(v) (v)->data[0].v_double
#define g_marshal_value_peek_string(v) (v)->data[0].v_pointer
#define g_marshal_value_peek_param(v) (v)->data[0].v_pointer
#define g_marshal_value_peek_boxed(v) (v)->data[0].v_pointer
#define g_marshal_value_peek_pointer(v) (v)->data[0].v_pointer
#define g_marshal_value_peek_object(v) (v)->data[0].v_pointer
#endif /* !G_ENABLE_DEBUG */
/* VOID:INT,INT (exo-marshal.list:1) */
void
_exo_marshal_VOID__INT_INT (GClosure *closure,
GValue *return_value,
guint n_param_values,
const GValue *param_values,
gpointer invocation_hint,
gpointer marshal_data)
{
typedef void (*GMarshalFunc_VOID__INT_INT) (gpointer data1,
gint arg_1,
gint arg_2,
gpointer data2);
register GMarshalFunc_VOID__INT_INT callback;
register GCClosure *cc = (GCClosure*) closure;
register gpointer data1, data2;
g_return_if_fail (n_param_values == 3);
if (G_CCLOSURE_SWAP_DATA (closure))
{
data1 = closure->data;
data2 = g_value_peek_pointer (param_values + 0);
}
else
{
data1 = g_value_peek_pointer (param_values + 0);
data2 = closure->data;
}
callback = (GMarshalFunc_VOID__INT_INT) (marshal_data ? marshal_data : cc->callback);
callback (data1,
g_marshal_value_peek_int (param_values + 1),
g_marshal_value_peek_int (param_values + 2),
data2);
}
/* VOID:OBJECT,OBJECT (exo-marshal.list:2) */
void
_exo_marshal_VOID__OBJECT_OBJECT (GClosure *closure,
GValue *return_value,
guint n_param_values,
const GValue *param_values,
gpointer invocation_hint,
gpointer marshal_data)
{
typedef void (*GMarshalFunc_VOID__OBJECT_OBJECT) (gpointer data1,
gpointer arg_1,
gpointer arg_2,
gpointer data2);
register GMarshalFunc_VOID__OBJECT_OBJECT callback;
register GCClosure *cc = (GCClosure*) closure;
register gpointer data1, data2;
g_return_if_fail (n_param_values == 3);
if (G_CCLOSURE_SWAP_DATA (closure))
{
data1 = closure->data;
data2 = g_value_peek_pointer (param_values + 0);
}
else
{
data1 = g_value_peek_pointer (param_values + 0);
data2 = closure->data;
}
callback = (GMarshalFunc_VOID__OBJECT_OBJECT) (marshal_data ? marshal_data : cc->callback);
callback (data1,
g_marshal_value_peek_object (param_values + 1),
g_marshal_value_peek_object (param_values + 2),
data2);
}
/* STRING:POINTER (exo-marshal.list:3) */
void
_exo_marshal_STRING__POINTER (GClosure *closure,
GValue *return_value,
guint n_param_values,
const GValue *param_values,
gpointer invocation_hint,
gpointer marshal_data)
{
typedef gchar* (*GMarshalFunc_STRING__POINTER) (gpointer data1,
gpointer arg_1,
gpointer data2);
register GMarshalFunc_STRING__POINTER callback;
register GCClosure *cc = (GCClosure*) closure;
register gpointer data1, data2;
gchar* v_return;
g_return_if_fail (return_value != NULL);
g_return_if_fail (n_param_values == 2);
if (G_CCLOSURE_SWAP_DATA (closure))
{
data1 = closure->data;
data2 = g_value_peek_pointer (param_values + 0);
}
else
{
data1 = g_value_peek_pointer (param_values + 0);
data2 = closure->data;
}
callback = (GMarshalFunc_STRING__POINTER) (marshal_data ? marshal_data : cc->callback);
v_return = callback (data1,
g_marshal_value_peek_pointer (param_values + 1),
data2);
g_value_take_string (return_value, v_return);
}
/* STRING:STRING,STRING (exo-marshal.list:4) */
void
_exo_marshal_STRING__STRING_STRING (GClosure *closure,
GValue *return_value,
guint n_param_values,
const GValue *param_values,
gpointer invocation_hint,
gpointer marshal_data)
{
typedef gchar* (*GMarshalFunc_STRING__STRING_STRING) (gpointer data1,
gpointer arg_1,
gpointer arg_2,
gpointer data2);
register GMarshalFunc_STRING__STRING_STRING callback;
register GCClosure *cc = (GCClosure*) closure;
register gpointer data1, data2;
gchar* v_return;
g_return_if_fail (return_value != NULL);
g_return_if_fail (n_param_values == 3);
if (G_CCLOSURE_SWAP_DATA (closure))
{
data1 = closure->data;
data2 = g_value_peek_pointer (param_values + 0);
}
else
{
data1 = g_value_peek_pointer (param_values + 0);
data2 = closure->data;
}
callback = (GMarshalFunc_STRING__STRING_STRING) (marshal_data ? marshal_data : cc->callback);
v_return = callback (data1,
g_marshal_value_peek_string (param_values + 1),
g_marshal_value_peek_string (param_values + 2),
data2);
g_value_take_string (return_value, v_return);
}
/* BOOLEAN:VOID (exo-marshal.list:5) */
void
_exo_marshal_BOOLEAN__VOID (GClosure *closure,
GValue *return_value,
guint n_param_values,
const GValue *param_values,
gpointer invocation_hint,
gpointer marshal_data)
{
typedef gboolean (*GMarshalFunc_BOOLEAN__VOID) (gpointer data1,
gpointer data2);
register GMarshalFunc_BOOLEAN__VOID callback;
register GCClosure *cc = (GCClosure*) closure;
register gpointer data1, data2;
gboolean v_return;
g_return_if_fail (return_value != NULL);
g_return_if_fail (n_param_values == 1);
if (G_CCLOSURE_SWAP_DATA (closure))
{
data1 = closure->data;
data2 = g_value_peek_pointer (param_values + 0);
}
else
{
data1 = g_value_peek_pointer (param_values + 0);
data2 = closure->data;
}
callback = (GMarshalFunc_BOOLEAN__VOID) (marshal_data ? marshal_data : cc->callback);
v_return = callback (data1,
data2);
g_value_set_boolean (return_value, v_return);
}
/* BOOLEAN:ENUM,INT (exo-marshal.list:6) */
void
_exo_marshal_BOOLEAN__ENUM_INT (GClosure *closure,
GValue *return_value,
guint n_param_values,
const GValue *param_values,
gpointer invocation_hint,
gpointer marshal_data)
{
typedef gboolean (*GMarshalFunc_BOOLEAN__ENUM_INT) (gpointer data1,
gint arg_1,
gint arg_2,
gpointer data2);
register GMarshalFunc_BOOLEAN__ENUM_INT callback;
register GCClosure *cc = (GCClosure*) closure;
register gpointer data1, data2;
gboolean v_return;
g_return_if_fail (return_value != NULL);
g_return_if_fail (n_param_values == 3);
if (G_CCLOSURE_SWAP_DATA (closure))
{
data1 = closure->data;
data2 = g_value_peek_pointer (param_values + 0);
}
else
{
data1 = g_value_peek_pointer (param_values + 0);
data2 = closure->data;
}
callback = (GMarshalFunc_BOOLEAN__ENUM_INT) (marshal_data ? marshal_data : cc->callback);
v_return = callback (data1,
g_marshal_value_peek_enum (param_values + 1),
g_marshal_value_peek_int (param_values + 2),
data2);
g_value_set_boolean (return_value, v_return);
}
/* BOOLEAN:INT,ENUM,BOOLEAN,ENUM,BOOLEAN (exo-marshal.list:7) */
void
_exo_marshal_BOOLEAN__INT_ENUM_BOOLEAN_ENUM_BOOLEAN (GClosure *closure,
GValue *return_value,
guint n_param_values,
const GValue *param_values,
gpointer invocation_hint,
gpointer marshal_data)
{
typedef gboolean (*GMarshalFunc_BOOLEAN__INT_ENUM_BOOLEAN_ENUM_BOOLEAN) (gpointer data1,
gint arg_1,
gint arg_2,
gboolean arg_3,
gint arg_4,
gboolean arg_5,
gpointer data2);
register GMarshalFunc_BOOLEAN__INT_ENUM_BOOLEAN_ENUM_BOOLEAN callback;
register GCClosure *cc = (GCClosure*) closure;
register gpointer data1, data2;
gboolean v_return;
g_return_if_fail (return_value != NULL);
g_return_if_fail (n_param_values == 6);
if (G_CCLOSURE_SWAP_DATA (closure))
{
data1 = closure->data;
data2 = g_value_peek_pointer (param_values + 0);
}
else
{
data1 = g_value_peek_pointer (param_values + 0);
data2 = closure->data;
}
callback = (GMarshalFunc_BOOLEAN__INT_ENUM_BOOLEAN_ENUM_BOOLEAN) (marshal_data ? marshal_data : cc->callback);
v_return = callback (data1,
g_marshal_value_peek_int (param_values + 1),
g_marshal_value_peek_enum (param_values + 2),
g_marshal_value_peek_boolean (param_values + 3),
g_marshal_value_peek_enum (param_values + 4),
g_marshal_value_peek_boolean (param_values + 5),
data2);
g_value_set_boolean (return_value, v_return);
}
|
174 | ./spacefm/src/ptk/ptk-utils.c | /*
* C Implementation: ptkutils
*
* Description:
*
*
* Author: Hong Jen Yee (PCMan) <pcman.tw (AT) gmail.com>, (C) 2006
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#include "ptk-utils.h"
#include <glib.h>
#include <glib/gi18n.h>
#include "working-area.h"
#include "gtk2-compat.h"
GtkWidget* ptk_menu_new_from_data( PtkMenuItemEntry* entries,
gpointer cb_data,
GtkAccelGroup* accel_group )
{
GtkWidget* menu;
menu = gtk_menu_new();
ptk_menu_add_items_from_data( menu, entries, cb_data, accel_group );
return menu;
}
void ptk_menu_add_items_from_data( GtkWidget* menu,
PtkMenuItemEntry* entries,
gpointer cb_data,
GtkAccelGroup* accel_group )
{
PtkMenuItemEntry* ent;
GtkWidget* menu_item = NULL;
GtkWidget* sub_menu;
GtkWidget* image;
GSList* radio_group = NULL;
const char* signal;
for( ent = entries; ; ++ent )
{
if( G_LIKELY( ent->label ) )
{
/* Stock item */
signal = "activate";
if( G_UNLIKELY( PTK_IS_STOCK_ITEM(ent) ) ) {
menu_item = gtk_image_menu_item_new_from_stock( ent->label, accel_group );
}
else if( G_LIKELY(ent->stock_icon) ) {
if( G_LIKELY( ent->stock_icon > (char *)2 ) ) {
menu_item = gtk_image_menu_item_new_with_mnemonic(_(ent->label));
image = gtk_image_new_from_stock( ent->stock_icon, GTK_ICON_SIZE_MENU );
gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM(menu_item), image );
}
else if( G_UNLIKELY( PTK_IS_CHECK_MENU_ITEM(ent) ) ) {
menu_item = gtk_check_menu_item_new_with_mnemonic(_(ent->label));
signal = "toggled";
}
else if( G_UNLIKELY( PTK_IS_RADIO_MENU_ITEM(ent) ) ) {
menu_item = gtk_radio_menu_item_new_with_mnemonic( radio_group, _(ent->label) );
if( G_LIKELY( PTK_IS_RADIO_MENU_ITEM( (ent + 1) ) ) )
radio_group = gtk_radio_menu_item_get_group( GTK_RADIO_MENU_ITEM(menu_item) );
else
radio_group = NULL;
signal = "toggled";
}
}
else {
menu_item = gtk_menu_item_new_with_mnemonic(_(ent->label));
}
if( G_LIKELY(accel_group) && ent->key ) {
gtk_widget_add_accelerator (menu_item, "activate", accel_group,
ent->key, ent->mod, GTK_ACCEL_VISIBLE);
}
if( G_LIKELY(ent->callback) ) { /* Callback */
g_signal_connect( menu_item, signal, ent->callback, cb_data);
}
if( G_UNLIKELY( ent->sub_menu ) ) { /* Sub menu */
sub_menu = ptk_menu_new_from_data( ent->sub_menu, cb_data, accel_group );
gtk_menu_item_set_submenu( GTK_MENU_ITEM(menu_item), sub_menu );
ent->menu = sub_menu; //MOD
}
}
else
{
if( ! ent->stock_icon ) /* End of menu */
break;
menu_item = gtk_separator_menu_item_new();
}
gtk_menu_shell_append ( GTK_MENU_SHELL(menu), menu_item );
if( G_UNLIKELY(ent->ret) ) {// Return
*ent->ret = menu_item;
ent->ret = NULL;
}
}
}
#if 0
GtkWidget* ptk_toolbar_add_items_from_data( GtkWidget* toolbar,
PtkToolItemEntry* entries,
gpointer cb_data,
GtkTooltips* tooltips )
{
GtkWidget* btn;
PtkToolItemEntry* ent;
GtkWidget* image;
GtkWidget* menu;
GtkIconSize icon_size = gtk_toolbar_get_icon_size (GTK_TOOLBAR (toolbar));
GSList* radio_group = NULL;
for( ent = entries; ; ++ent )
{
/* Normal tool item */
if( G_LIKELY( ent->stock_icon || ent->tooltip || ent->label ) )
{
/* Stock item */
if( G_LIKELY(ent->stock_icon) )
image = gtk_image_new_from_stock( ent->stock_icon, icon_size );
else
image = NULL;
if( G_LIKELY( ! ent->menu ) ) { /* Normal button */
if( G_UNLIKELY( PTK_IS_STOCK_ITEM(ent) ) )
btn = GTK_WIDGET(gtk_tool_button_new_from_stock ( ent->label ));
else
btn = GTK_WIDGET(gtk_tool_button_new ( image, _(ent->label) ));
}
else if( G_UNLIKELY( PTK_IS_CHECK_TOOL_ITEM(ent) ) ) {
if( G_UNLIKELY( PTK_IS_STOCK_ITEM(ent) ) )
btn = GTK_WIDGET(gtk_toggle_tool_button_new_from_stock(ent->label));
else {
btn = GTK_WIDGET(gtk_toggle_tool_button_new ());
gtk_tool_button_set_icon_widget( GTK_TOOL_BUTTON(btn), image );
gtk_tool_button_set_label(GTK_TOOL_BUTTON(btn), _(ent->label));
}
}
else if( G_UNLIKELY( PTK_IS_RADIO_TOOL_ITEM(ent) ) ) {
if( G_UNLIKELY( PTK_IS_STOCK_ITEM(ent) ) )
btn = GTK_WIDGET(gtk_radio_tool_button_new_from_stock( radio_group, ent->label ));
else {
btn = GTK_WIDGET(gtk_radio_tool_button_new( radio_group ));
if( G_LIKELY( PTK_IS_RADIO_TOOL_ITEM( (ent + 1) ) ) )
radio_group = gtk_radio_tool_button_get_group( GTK_RADIO_TOOL_BUTTON(btn) );
else
radio_group = NULL;
gtk_tool_button_set_icon_widget( GTK_TOOL_BUTTON(btn), image );
gtk_tool_button_set_label(GTK_TOOL_BUTTON(btn), _(ent->label));
}
}
else if( ent->menu ) {
if( G_UNLIKELY( PTK_IS_STOCK_ITEM(ent) ) )
btn = GTK_WIDGET(gtk_menu_tool_button_new_from_stock ( ent->label ));
else {
btn = GTK_WIDGET(gtk_menu_tool_button_new ( image, _(ent->label) ));
if( G_LIKELY( 3 < (int)ent->menu ) ) { /* Sub menu */
menu = ptk_menu_new_from_data( ent->menu, cb_data, NULL );
gtk_menu_tool_button_set_menu( GTK_MENU_TOOL_BUTTON(btn), menu );
}
}
}
if( G_LIKELY(ent->callback) ) { /* Callback */
if( G_LIKELY( ent->menu == NULL || ent->menu == PTK_EMPTY_MENU) )
g_signal_connect( btn, "clicked", ent->callback, cb_data);
else
g_signal_connect( btn, "toggled", ent->callback, cb_data);
}
if( G_LIKELY(ent->tooltip) )
gtk_tool_item_set_tooltip (GTK_TOOL_ITEM (btn), tooltips, _(ent->tooltip), NULL);
}
else
{
if( ! PTK_IS_SEPARATOR_TOOL_ITEM(ent) ) /* End of menu */
break;
btn = (GtkWidget*)gtk_separator_tool_item_new ();
}
gtk_toolbar_insert ( GTK_TOOLBAR(toolbar), GTK_TOOL_ITEM(btn), -1 );
if( G_UNLIKELY(ent->ret) ) {/* Return */
*ent->ret = btn;
ent->ret = NULL;
}
}
return NULL;
}
#endif
void ptk_show_error(GtkWindow* parent, const char* title, const char* message )
{
GtkWidget* dlg = gtk_message_dialog_new_with_markup(parent, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, message, NULL);
if( title )
gtk_window_set_title( (GtkWindow*)dlg, title );
gtk_dialog_run( GTK_DIALOG(dlg) );
gtk_widget_destroy( dlg );
}
/* Make the size of dialogs smaller by breaking GNOME HIG
* http://library.gnome.org/devel/hig-book/stable/design-window.html.en
* According to GNOME HIG, spacings are increased by the multiples of 6.
* Change them to the multiples of 1 can greatly reduce the required size
* while still keeping some degree of spacing.
*/
static void break_gnome_hig( GtkWidget* w, gpointer _factor )
{
int factor = GPOINTER_TO_INT(_factor);
/* g_debug( G_OBJECT_TYPE_NAME(w) ); */
if( GTK_IS_CONTAINER(w) )
{
int val;
val = gtk_container_get_border_width( (GtkContainer*)w );
/* border of dialog defaults to 12 under gnome */
if( GTK_IS_DIALOG(w) )
{
if( val > 0 )
gtk_container_set_border_width( (GtkContainer*)w, val / factor );
}
else
{
if( GTK_IS_BOX(w) ) /* boxes, spacing defaults to 6, 12, 18 under gnome */
{
int spacing = gtk_box_get_spacing( (GtkBox*)w );
gtk_box_set_spacing( (GtkBox*)w, spacing / factor );
}
else if( GTK_IS_TABLE(w) ) /* tables, spacing defaults to 6, 12, 18 under gnome */
{
int spacing;
int col, row;
g_object_get( w, "n-columns", &col, "n-rows", &row, NULL );
if( col > 1 )
{
--col;
while( --col >= 0 )
{
spacing = gtk_table_get_col_spacing( (GtkTable*)w, col );
if( spacing > 0 )
gtk_table_set_col_spacing( (GtkTable*)w, col, spacing / factor );
}
}
if( row > 1 )
{
--row;
while( --row >= 0 )
{
spacing = gtk_table_get_row_spacing( (GtkTable*)w, row );
if( spacing > 0 )
gtk_table_set_row_spacing( (GtkTable*)w, row, spacing / factor );
}
}
/* FIXME: handle default spacings */
}
else if( GTK_IS_ALIGNMENT(w) ) /* groups, has 12 px indent by default */
{
int t, b, l, r;
gtk_alignment_get_padding( (GtkAlignment*)w, &t, &b, &l, &r );
if( l > 0 )
{
l /= (factor / 2); /* groups still need proper indent not to hurt usability */
gtk_alignment_set_padding( (GtkAlignment*)w, t, b, l, r );
}
}
if( val > 0 )
gtk_container_set_border_width( (GtkContainer*)w, val * 2 / factor );
}
gtk_container_foreach( (GtkContainer*)w, break_gnome_hig, GINT_TO_POINTER(factor) );
}
}
/* Because GNOME HIG causes some usability problems under limited screen size,
* this API is provided to adjust the dialogs, and try to fit them into
* small screens via totally breaking GNOME HIG and compress spacings.
*/
void ptk_dialog_fit_small_screen( GtkDialog* dlg )
{
GtkRequisition req;
GdkRectangle wa;
GtkAllocation allocation;
int dw, dh, i;
get_working_area( gtk_widget_get_screen((GtkWidget*)dlg), &wa );
gtk_widget_size_request( GTK_WIDGET(dlg), &req );
/* Try two times, so we won't be too aggrassive if mild shinkage can do the job.
* First time shrink all spacings to their 1/3.
* If this is not enough, shrink them again by dividing all spacings by 2. (1/6 size now)
*/
for( i =0; (req.width > wa.width || req.height > wa.height) && i < 2; ++i )
{
break_gnome_hig( GTK_WIDGET(dlg), GINT_TO_POINTER((i == 0 ? 3 : 2)) );
gtk_widget_size_request( GTK_WIDGET(dlg), &req );
/* g_debug("%d, %d", req.width, req.height ); */
}
if( gtk_widget_get_realized( GTK_WIDGET(dlg) ) )
{
gtk_widget_get_allocation ( (GtkWidget*)dlg, &allocation);
gboolean changed = FALSE;
if( allocation.width > wa.width )
{
dw = wa.width;
changed = TRUE;
}
if( allocation.height > wa.width )
{
dh = wa.height;
changed = TRUE;
}
if( changed )
gtk_window_resize( (GtkWindow*)dlg, dw, dh );
/* gtk_window_move( dlg, 0, 0 ); */
}
else
{
gtk_window_get_default_size( (GtkWindow*)dlg, &dw, &dh );
if( dw > wa.width )
dw = wa.width;
if( dh > wa.height )
dh = wa.height;
gtk_window_set_default_size( GTK_WINDOW(dlg), dw, dh );
}
}
typedef struct
{
GMainLoop* lp;
int response;
}DlgRunData;
static gboolean on_dlg_delete_event( GtkWidget* dlg, GdkEvent* evt, DlgRunData* data )
{
return TRUE;
}
static void on_dlg_response( GtkDialog* dlg, int response, DlgRunData* data )
{
data->response = response;
if( g_main_loop_is_running( data->lp ) )
g_main_loop_quit( data->lp );
}
int ptk_dialog_run_modaless( GtkDialog* dlg )
{
DlgRunData data = {0};
data.lp = g_main_loop_new( NULL, FALSE );
guint deh = g_signal_connect( dlg, "delete_event", G_CALLBACK(on_dlg_delete_event), &data );
guint rh = g_signal_connect( dlg, "response", G_CALLBACK(on_dlg_response), &data );
gtk_window_present( (GtkWindow*)dlg );
GDK_THREADS_LEAVE();
g_main_loop_run(data.lp);
GDK_THREADS_ENTER();
g_main_loop_unref(data.lp);
g_signal_handler_disconnect( dlg, deh );
g_signal_handler_disconnect( dlg, rh );
return data.response;
}
GtkBuilder* _gtk_builder_new_from_file( const char* file, GError** err )
{
GtkBuilder* builder = gtk_builder_new();
if( G_UNLIKELY( ! gtk_builder_add_from_file( builder, file, err ) ) )
{
g_object_unref( builder );
return NULL;
}
return builder;
}
|
175 | ./spacefm/src/ptk/ptk-file-misc.c | /*
* C Implementation: ptk-file-misc
*
* Description: Miscellaneous GUI-realated functions for files
*
*
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#include "ptk-file-misc.h"
#include <glib.h>
#include "glib-mem.h"
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <glib/gi18n.h>
#include "ptk-utils.h"
#include "ptk-file-task.h"
#include "vfs-file-task.h"
#include "ptk-file-properties.h"
#include "ptk-input-dialog.h"
#include "ptk-file-browser.h"
#include "vfs-app-desktop.h"
#include "vfs-execute.h"
#include "ptk-app-chooser.h"
#include "ptk-clipboard.h"
#include <gdk/gdkkeysyms.h>
#include "settings.h"
#include "gtk2-compat.h"
typedef struct
{
char* full_path;
const char* old_path;
char* new_path;
char* desc;
gboolean is_dir;
gboolean is_link;
gboolean clip_copy;
int create_new;
GtkWidget* dlg;
GtkWidget* parent;
PtkFileBrowser* browser;
DesktopWindow* desktop;
GtkLabel* label_type;
GtkLabel* label_mime;
GtkWidget* hbox_type;
char* mime_type;
GtkLabel* label_target;
GtkEntry* entry_target;
GtkWidget* hbox_target;
GtkWidget* browse_target;
GtkLabel* label_template;
GtkComboBox* combo_template;
GtkComboBox* combo_template_dir;
GtkWidget* hbox_template;
GtkWidget* browse_template;
GtkLabel* label_name;
GtkWidget* scroll_name;
GtkWidget* input_name;
GtkTextBuffer* buf_name;
GtkLabel* blank_name;
GtkWidget* hbox_ext;
GtkLabel* label_ext;
GtkEntry* entry_ext;
GtkLabel* label_full_name;
GtkWidget* scroll_full_name;
GtkWidget* input_full_name;
GtkTextBuffer* buf_full_name;
GtkLabel* blank_full_name;
GtkLabel* label_path;
GtkWidget* scroll_path;
GtkWidget* input_path;
GtkTextBuffer* buf_path;
GtkLabel* blank_path;
GtkLabel* label_full_path;
GtkWidget* scroll_full_path;
GtkWidget* input_full_path;
GtkTextBuffer* buf_full_path;
GtkWidget* opt_move;
GtkWidget* opt_copy;
GtkWidget* opt_link;
GtkWidget* opt_copy_target;
GtkWidget* opt_link_target;
GtkWidget* opt_as_root;
GtkWidget* opt_new_file;
GtkWidget* opt_new_folder;
GtkWidget* opt_new_link;
GtkWidget* options;
GtkWidget* browse;
GtkWidget* revert;
GtkWidget* cancel;
GtkWidget* next;
GtkWidget* open;
GtkWidget* last_widget;
gboolean full_path_exists;
gboolean full_path_exists_dir;
gboolean full_path_same;
gboolean path_missing;
gboolean path_exists_file;
gboolean mode_change;
gboolean is_move;
} MoveSet;
void on_toggled( GtkMenuItem* item, MoveSet* mset );
char* get_template_dir();
void ptk_delete_files( GtkWindow* parent_win,
const char* cwd,
GList* sel_files, GtkTreeView* task_view )
{
GtkWidget * dlg;
gchar* file_path;
gint ret;
GList* sel;
VFSFileInfo* file;
PtkFileTask* task = NULL;
GList* file_list;
if ( ! sel_files )
return ;
if( ! app_settings.use_trash_can && ! app_settings.no_confirm ) //MOD
{
// count
int count = g_list_length( sel_files );
char* msg = g_strdup_printf( ngettext( "Delete %d selected item ?",
"Delete %d selected items ?",
count ), count );
dlg = gtk_message_dialog_new( parent_win,
GTK_DIALOG_MODAL,
GTK_MESSAGE_WARNING,
GTK_BUTTONS_YES_NO,
msg, NULL );
gtk_dialog_set_default_response (GTK_DIALOG (dlg), GTK_RESPONSE_YES); //MOD
gtk_window_set_title( GTK_WINDOW( dlg ), _("Confirm Delete") );
xset_set_window_icon( GTK_WINDOW( dlg ) );
ret = gtk_dialog_run( GTK_DIALOG( dlg ) );
gtk_widget_destroy( dlg );
g_free( msg );
if ( ret != GTK_RESPONSE_YES )
return ;
}
file_list = NULL;
for ( sel = sel_files; sel; sel = g_list_next( sel ) )
{
file = ( VFSFileInfo* ) sel->data;
file_path = g_build_filename( cwd,
vfs_file_info_get_name( file ), NULL );
file_list = g_list_prepend( file_list, file_path );
}
/* file_list = g_list_reverse( file_list ); */
task = ptk_file_task_new( app_settings.use_trash_can ? VFS_FILE_TASK_TRASH : VFS_FILE_TASK_DELETE,
file_list,
NULL,
GTK_WINDOW( parent_win ),
GTK_WIDGET( task_view ) );
ptk_file_task_run( task );
}
static void select_file_name_part( GtkEntry* entry )
{
GtkEditable * editable = GTK_EDITABLE( entry );
const char* file_name = gtk_entry_get_text( entry );
const char* dot;
int pos;
if ( !file_name[ 0 ] || file_name[ 0 ] == '.' )
return ;
/* FIXME: Simply finding '.' usually gets wrong filename suffix. */
dot = g_utf8_strrchr( file_name, -1, '.' );
if ( dot )
{
pos = g_utf8_pointer_to_offset( file_name, dot );
gtk_editable_select_region( editable, 0, pos );
}
}
static gboolean on_move_keypress ( GtkWidget *widget, GdkEventKey *event, MoveSet* mset )
{
if ( event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_KP_Enter )
{
if ( gtk_widget_get_sensitive( GTK_WIDGET( mset->next ) ) )
gtk_dialog_response( GTK_DIALOG( mset->dlg ), GTK_RESPONSE_OK );
return TRUE;
}
return FALSE;
}
static gboolean on_move_entry_keypress ( GtkWidget *widget, GdkEventKey *event, MoveSet* mset )
{
if ( event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_KP_Enter )
{
if ( gtk_widget_get_sensitive( GTK_WIDGET( mset->next ) ) )
gtk_dialog_response( GTK_DIALOG( mset->dlg ), GTK_RESPONSE_OK );
return TRUE;
}
return FALSE;
}
void on_move_change( GtkWidget* widget, MoveSet* mset )
{
char* name;
char* full_name;
char* ext;
char* full_path;
char* path;
char* cwd;
char* str;
GtkTextIter iter, siter;
g_signal_handlers_block_matched( mset->entry_ext, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_move_change, NULL );
g_signal_handlers_block_matched( mset->buf_name, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_move_change, NULL );
g_signal_handlers_block_matched( mset->buf_full_name, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_move_change, NULL );
g_signal_handlers_block_matched( mset->buf_path, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_move_change, NULL );
g_signal_handlers_block_matched( mset->buf_full_path, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_move_change, NULL );
if ( widget == GTK_WIDGET( mset->buf_name ) || widget == GTK_WIDGET( mset->entry_ext ) )
{
if ( widget == GTK_WIDGET( mset->buf_name ) )
mset->last_widget = GTK_WIDGET( mset->input_name );
else
mset->last_widget = GTK_WIDGET( mset->entry_ext );
gtk_text_buffer_get_start_iter( mset->buf_name, &siter );
gtk_text_buffer_get_end_iter( mset->buf_name, &iter );
name = gtk_text_buffer_get_text( mset->buf_name, &siter, &iter, FALSE );
if ( name[0] == '\0' )
{
g_free( name );
name = NULL;
}
ext = (char*)gtk_entry_get_text( mset->entry_ext );
if ( ext[0] == '\0' )
{
ext = NULL;
}
else if ( ext[0] == '.' )
ext++; // ignore leading dot in extension field
// update full_name
if ( name && ext )
full_name = g_strdup_printf( "%s.%s", name, ext );
else if ( name && !ext )
full_name = g_strdup( name );
else if ( !name && ext )
full_name = g_strdup( ext );
else
full_name = g_strdup( "" );
if ( name )
g_free( name );
gtk_text_buffer_set_text( mset->buf_full_name, full_name, -1 );
// update full_path
gtk_text_buffer_get_start_iter( mset->buf_path, &siter );
gtk_text_buffer_get_end_iter( mset->buf_path, &iter );
path = gtk_text_buffer_get_text( mset->buf_path, &siter, &iter, FALSE );
if ( !strcmp( path, "." ) )
{
g_free( path );
path = g_path_get_dirname( mset->full_path );
}
else if ( !strcmp( path, ".." ) )
{
g_free( path );
cwd = g_path_get_dirname( mset->full_path );
path = g_path_get_dirname( cwd );
g_free( cwd );
}
if ( path[0] == '/' )
full_path = g_build_filename( path, full_name, NULL );
else
{
cwd = g_path_get_dirname( mset->full_path );
full_path = g_build_filename( cwd, path, full_name, NULL );
g_free( cwd );
}
gtk_text_buffer_set_text( mset->buf_full_path, full_path, -1 );
g_free( full_name );
}
else if ( widget == GTK_WIDGET( mset->buf_full_name ) )
{
mset->last_widget = GTK_WIDGET( mset->input_full_name );
// update name & ext
gtk_text_buffer_get_start_iter( mset->buf_full_name, &siter );
gtk_text_buffer_get_end_iter( mset->buf_full_name, &iter );
full_name = gtk_text_buffer_get_text( mset->buf_full_name, &siter, &iter, FALSE );
name = get_name_extension( full_name, mset->is_dir, &ext );
gtk_text_buffer_set_text( mset->buf_name, name, -1 );
if ( ext )
gtk_entry_set_text( mset->entry_ext, ext );
else
gtk_entry_set_text( mset->entry_ext, "" );
g_free( name );
g_free( ext );
// update full_path
gtk_text_buffer_get_start_iter( mset->buf_path, &siter );
gtk_text_buffer_get_end_iter( mset->buf_path, &iter );
path = gtk_text_buffer_get_text( mset->buf_path, &siter, &iter, FALSE );
if ( !strcmp( path, "." ) )
{
g_free( path );
path = g_path_get_dirname( mset->full_path );
}
else if ( !strcmp( path, ".." ) )
{
g_free( path );
cwd = g_path_get_dirname( mset->full_path );
path = g_path_get_dirname( cwd );
g_free( cwd );
}
if ( path[0] == '/' )
full_path = g_build_filename( path, full_name, NULL );
else
{
cwd = g_path_get_dirname( mset->full_path );
full_path = g_build_filename( cwd, path, full_name, NULL );
g_free( cwd );
}
gtk_text_buffer_set_text( mset->buf_full_path, full_path, -1 );
g_free( full_name );
}
else if ( widget == GTK_WIDGET( mset->buf_path ) )
{
mset->last_widget = GTK_WIDGET( mset->input_path );
// update full_path
gtk_text_buffer_get_start_iter( mset->buf_full_name, &siter );
gtk_text_buffer_get_end_iter( mset->buf_full_name, &iter );
full_name = gtk_text_buffer_get_text( mset->buf_full_name, &siter, &iter, FALSE );
gtk_text_buffer_get_start_iter( mset->buf_path, &siter );
gtk_text_buffer_get_end_iter( mset->buf_path, &iter );
path = gtk_text_buffer_get_text( mset->buf_path, &siter, &iter, FALSE );
if ( !strcmp( path, "." ) )
{
g_free( path );
path = g_path_get_dirname( mset->full_path );
}
else if ( !strcmp( path, ".." ) )
{
g_free( path );
cwd = g_path_get_dirname( mset->full_path );
path = g_path_get_dirname( cwd );
g_free( cwd );
}
if ( path[0] == '/' )
full_path = g_build_filename( path, full_name, NULL );
else
{
cwd = g_path_get_dirname( mset->full_path );
full_path = g_build_filename( cwd, path, full_name, NULL );
g_free( cwd );
}
gtk_text_buffer_set_text( mset->buf_full_path, full_path, -1 );
g_free( full_name );
}
else //if ( widget == GTK_WIDGET( mset->buf_full_path ) )
{
mset->last_widget = GTK_WIDGET( mset->input_full_path );
gtk_text_buffer_get_start_iter( mset->buf_full_path, &siter );
gtk_text_buffer_get_end_iter( mset->buf_full_path, &iter );
full_path = gtk_text_buffer_get_text( mset->buf_full_path, &siter, &iter, FALSE );
// update name & ext
if ( full_path[0] == '\0' )
full_name = g_strdup( "" );
else
full_name = g_path_get_basename( full_path );
path = g_path_get_dirname( full_path );
if ( !strcmp( path, "." ) )
{
g_free( path );
path = g_path_get_dirname( mset->full_path );
}
else if ( !strcmp( path, ".." ) )
{
g_free( path );
cwd = g_path_get_dirname( mset->full_path );
path = g_path_get_dirname( cwd );
g_free( cwd );
}
else if ( path[0] != '/' )
{
cwd = g_path_get_dirname( mset->full_path );
str = path;
path = g_build_filename( cwd, str, NULL );
g_free( str );
g_free( cwd );
}
name = get_name_extension( full_name, mset->is_dir, &ext );
gtk_text_buffer_set_text( mset->buf_name, name, -1 );
if ( ext )
gtk_entry_set_text( mset->entry_ext, ext );
else
gtk_entry_set_text( mset->entry_ext, "" );
// update full_name
if ( name && ext )
full_name = g_strdup_printf( "%s.%s", name, ext );
else if ( name && !ext )
full_name = g_strdup( name );
else if ( !name && ext )
full_name = g_strdup( ext );
else
full_name = g_strdup( "" );
g_free( name );
g_free( ext );
gtk_text_buffer_set_text( mset->buf_full_name, full_name, -1 );
// update path
gtk_text_buffer_set_text( mset->buf_path, path, -1 );
if ( full_path[0] != '/' )
{
// update full_path for tests below
cwd = g_path_get_dirname( mset->full_path );
str = full_path;
full_path = g_build_filename( cwd, str, NULL );
g_free( str );
g_free( cwd );
}
g_free( full_name );
}
// change relative path to absolute
if ( path[0] != '/' )
{
g_free( path );
path = g_path_get_dirname( full_path );
}
//printf("path=%s full=%s\n", path, full_path );
// tests
struct stat64 statbuf;
gboolean full_path_exists = FALSE;
gboolean full_path_exists_dir = FALSE;
gboolean full_path_same = FALSE;
gboolean path_missing = FALSE;
gboolean path_exists_file = FALSE;
gboolean is_move = FALSE;
if ( !strcmp( full_path, mset->full_path ) )
{
full_path_same = TRUE;
if ( mset->create_new &&
gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(
mset->opt_new_link ) ) )
{
if ( lstat64( full_path, &statbuf ) == 0 )
{
full_path_exists = TRUE;
if ( g_file_test( full_path, G_FILE_TEST_IS_DIR ) )
full_path_exists_dir = TRUE;
}
}
}
else
{
if ( lstat64( full_path, &statbuf ) == 0 )
{
full_path_exists = TRUE;
if ( g_file_test( full_path, G_FILE_TEST_IS_DIR ) )
full_path_exists_dir = TRUE;
}
else if ( lstat64( path, &statbuf ) == 0 )
{
if ( !g_file_test( path, G_FILE_TEST_IS_DIR ) )
path_exists_file = TRUE;
}
else
path_missing = TRUE;
if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_move ) ) )
{
is_move = strcmp( path, mset->old_path );
}
}
g_free( path );
g_free( full_path );
/*
printf( "\nTEST\n full_path_same %d %d\n", full_path_same, mset->full_path_same );
printf( " full_path_exists %d %d\n", full_path_exists, mset->full_path_exists );
printf( " full_path_exists_dir %d %d\n", full_path_exists_dir, mset->full_path_exists_dir );
printf( " path_missing %d %d\n", path_missing, mset->path_missing );
printf( " path_exists_file %d %d\n", path_exists_file, mset->path_exists_file );
*/
// update display
if ( mset->full_path_same != full_path_same
|| mset->full_path_exists != full_path_exists
|| mset->full_path_exists_dir != full_path_exists_dir
|| mset->path_missing != path_missing
|| mset->path_exists_file != path_exists_file
|| mset->mode_change )
{
// state change
mset->full_path_exists = full_path_exists;
mset->full_path_exists_dir = full_path_exists_dir;
mset->path_missing = path_missing;
mset->path_exists_file = path_exists_file;
mset->full_path_same = full_path_same;
mset->mode_change = FALSE;
//gboolean opt_move = gtk_toggle_button_get_active( mset->opt_move );
//gboolean opt_copy = gtk_toggle_button_get_active( mset->opt_copy );
//gboolean opt_link = gtk_toggle_button_get_active( mset->opt_link );
//gboolean opt_copy_target = gtk_toggle_button_get_active( mset->opt_copy_target );
//gboolean opt_link_target = gtk_toggle_button_get_active( mset->opt_link_target );
if ( full_path_same && ( mset->create_new == 0 || mset->create_new == 3 ) )
{
gtk_widget_set_sensitive( mset->next, gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( mset->opt_move ) ) );
gtk_label_set_markup_with_mnemonic( mset->label_full_path,
_("<b>P_ath:</b> <i>original</i>") );
gtk_label_set_markup_with_mnemonic( mset->label_name,
_("<b>_Name:</b> <i>original</i>") );
gtk_label_set_markup_with_mnemonic( mset->label_full_name,
_("<b>_Filename:</b> <i>original</i>") );
gtk_label_set_markup_with_mnemonic( mset->label_path,
_("<b>_Parent:</b> <i>original</i>") );
}
else if ( full_path_exists_dir )
{
gtk_widget_set_sensitive( mset->next, FALSE );
gtk_label_set_markup_with_mnemonic( mset->label_full_path,
_("<b>P_ath:</b> <i>exists as folder</i>") );
gtk_label_set_markup_with_mnemonic( mset->label_name,
_("<b>_Name:</b> <i>exists as folder</i>") );
gtk_label_set_markup_with_mnemonic( mset->label_full_name,
_("<b>_Filename:</b> <i>exists as folder</i>") );
gtk_label_set_markup_with_mnemonic( mset->label_path, _("<b>_Parent:</b>") );
}
else if ( full_path_exists )
{
if ( mset->is_dir || gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( mset->opt_new_folder ) ) )
{
gtk_widget_set_sensitive( mset->next, FALSE );
gtk_label_set_markup_with_mnemonic( mset->label_full_path,
_("<b>P_ath:</b> <i>exists as file</i>") );
gtk_label_set_markup_with_mnemonic( mset->label_name,
_("<b>_Name:</b> <i>exists as file</i>") );
gtk_label_set_markup_with_mnemonic( mset->label_full_name,
_("<b>_Filename:</b> <i>exists as file</i>") );
gtk_label_set_markup_with_mnemonic( mset->label_path, _("<b>_Parent:</b>") );
}
else
{
gtk_widget_set_sensitive( mset->next, TRUE );
gtk_label_set_markup_with_mnemonic( mset->label_full_path,
_("<b>P_ath:</b> <i>* overwrite existing file</i>") );
gtk_label_set_markup_with_mnemonic( mset->label_name,
_("<b>_Name:</b> <i>* overwrite existing file</i>") );
gtk_label_set_markup_with_mnemonic( mset->label_full_name,
_("<b>_Filename:</b> <i>* overwrite existing file</i>") );
gtk_label_set_markup_with_mnemonic( mset->label_path, _("<b>_Parent:</b>") );
}
}
else if ( path_exists_file )
{
gtk_widget_set_sensitive( mset->next, FALSE );
gtk_label_set_markup_with_mnemonic( mset->label_full_path,
_("<b>P_ath:</b> <i>parent exists as file</i>") );
gtk_label_set_markup_with_mnemonic( mset->label_name,
_("<b>_Name:</b>") );
gtk_label_set_markup_with_mnemonic( mset->label_full_name,
_("<b>_Filename:</b>") );
gtk_label_set_markup_with_mnemonic( mset->label_path,
_("<b>_Parent:</b> <i>parent exists as file</i>") );
}
else if ( path_missing )
{
gtk_widget_set_sensitive( mset->next, TRUE );
gtk_label_set_markup_with_mnemonic( mset->label_full_path,
_("<b>P_ath:</b> <i>* create parent</i>") );
gtk_label_set_markup_with_mnemonic( mset->label_name,
_("<b>_Name:</b>") );
gtk_label_set_markup_with_mnemonic( mset->label_full_name,
_("<b>_Filename:</b>") );
gtk_label_set_markup_with_mnemonic( mset->label_path,
_("<b>_Parent:</b> <i>* create parent</i>") );
}
else
{
gtk_widget_set_sensitive( mset->next, TRUE );
gtk_label_set_markup_with_mnemonic( mset->label_full_path,
_("<b>P_ath:</b>") );
gtk_label_set_markup_with_mnemonic( mset->label_name,
_("<b>_Name:</b>") );
gtk_label_set_markup_with_mnemonic( mset->label_full_name,
_("<b>_Filename:</b>") );
gtk_label_set_markup_with_mnemonic( mset->label_path,
_("<b>_Parent:</b>") );
}
}
if ( is_move != mset->is_move && !mset->create_new )
{
mset->is_move = is_move;
if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_move ) ) )
gtk_button_set_label( GTK_BUTTON( mset->next ),
is_move != 0 ? _("_Move") : _("_Rename") );
}
if ( mset->create_new &&
gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_new_link ) ) )
{
path = g_strdup( gtk_entry_get_text( GTK_ENTRY( mset->entry_target ) ) );
g_strstrip( path );
gtk_widget_set_sensitive( mset->next, ( path && path[0] != '\0' &&
!( full_path_same && full_path_exists ) &&
!full_path_exists_dir ) );
g_free( path );
}
if ( mset->open )
gtk_widget_set_sensitive( mset->open, gtk_widget_get_sensitive( mset->next ) );
g_signal_handlers_unblock_matched( mset->entry_ext, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_move_change, NULL );
g_signal_handlers_unblock_matched( mset->buf_name, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_move_change, NULL );
g_signal_handlers_unblock_matched( mset->buf_full_name, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_move_change, NULL );
g_signal_handlers_unblock_matched( mset->buf_path, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_move_change, NULL );
g_signal_handlers_unblock_matched( mset->buf_full_path, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_move_change, NULL );
}
void select_input( GtkWidget* widget, MoveSet* mset )
{
if ( GTK_IS_EDITABLE( widget ) )
gtk_editable_select_region( GTK_EDITABLE( widget ), 0, -1 );
else if ( GTK_IS_COMBO_BOX( widget ) )
gtk_editable_select_region( GTK_EDITABLE( GTK_ENTRY( gtk_bin_get_child(
GTK_BIN( widget ) ) ) ), 0, -1 );
else
{
GtkTextIter iter, siter;
GtkTextBuffer* buf = gtk_text_view_get_buffer( GTK_TEXT_VIEW( widget ) );
if ( widget == GTK_WIDGET( mset->input_full_name )
&& !gtk_widget_get_visible( gtk_widget_get_parent( mset->input_name ) ) )
{
// name is not visible so select name in filename
gtk_text_buffer_get_start_iter( mset->buf_full_name, &siter );
gtk_text_buffer_get_end_iter( mset->buf_full_name, &iter );
char* full_name = gtk_text_buffer_get_text( mset->buf_full_name,
&siter, &iter, FALSE );
char* ext;
char* name = get_name_extension( full_name, mset->is_dir, &ext );
g_free( ext );
g_free( full_name );
gtk_text_buffer_get_iter_at_offset( buf, &iter,
g_utf8_strlen( name, -1 ) );
g_free( name );
}
else
gtk_text_buffer_get_end_iter( buf, &iter );
gtk_text_buffer_get_start_iter( buf, &siter );
gtk_text_buffer_select_range( buf, &iter, &siter );
}
}
static gboolean on_focus( GtkWidget* widget, GtkDirectionType direction, MoveSet* mset )
{
/*
if ( direction == GTK_DIR_TAB_FORWARD || direction == GTK_DIR_TAB_BACKWARD )
{
if ( widget == mset->label_mime )
return TRUE;
}
*/
select_input( widget, mset );
return FALSE;
}
static gboolean on_button_focus( GtkWidget* widget, GtkDirectionType direction,
MoveSet* mset )
{
if ( direction == GTK_DIR_TAB_FORWARD || direction == GTK_DIR_TAB_BACKWARD )
{
if ( widget == mset->options || widget == mset->opt_move ||
widget == mset->opt_new_file )
{
GtkWidget* input = NULL;
if ( gtk_widget_get_visible( gtk_widget_get_parent( mset->input_name ) ) )
input = mset->input_name;
else if ( gtk_widget_get_visible( gtk_widget_get_parent( mset->input_full_name ) ) )
input = mset->input_full_name;
else if ( gtk_widget_get_visible( gtk_widget_get_parent( mset->input_path ) ) )
input = mset->input_path;
else if ( gtk_widget_get_visible( gtk_widget_get_parent( mset->input_full_path ) ) )
input = mset->input_full_path;
else if ( gtk_widget_get_visible( gtk_widget_get_parent( GTK_WIDGET(
mset->entry_target ) ) ) )
input = GTK_WIDGET( mset->entry_target );
else if ( gtk_widget_get_visible( gtk_widget_get_parent( GTK_WIDGET(
mset->combo_template ) ) ) )
input = GTK_WIDGET( mset->combo_template );
else if ( gtk_widget_get_visible( gtk_widget_get_parent( GTK_WIDGET(
mset->combo_template_dir ) ) ) )
input = GTK_WIDGET( mset->combo_template_dir );
if ( input )
{
select_input( input, mset );
gtk_widget_grab_focus( input );
}
}
else
{
GtkWidget* input = NULL;
if ( gtk_widget_get_visible( gtk_widget_get_parent( mset->input_full_path ) ) )
input = mset->input_full_path;
else if ( gtk_widget_get_visible( gtk_widget_get_parent( mset->input_path ) ) )
input = mset->input_path;
else if ( gtk_widget_get_visible( gtk_widget_get_parent( mset->input_full_name ) ) )
input = mset->input_full_name;
else if ( gtk_widget_get_visible( gtk_widget_get_parent( mset->input_name ) ) )
input = mset->input_name;
if ( input )
{
select_input( input, mset );
gtk_widget_grab_focus( input );
}
}
return TRUE;
}
return FALSE;
}
void on_revert_button_press( GtkWidget* widget, MoveSet* mset )
{
GtkWidget* temp = mset->last_widget;
gtk_text_buffer_set_text( mset->buf_full_path, mset->new_path, -1 );
mset->last_widget = temp;
select_input( mset->last_widget, mset );
gtk_widget_grab_focus( mset->last_widget );
}
void on_create_browse_button_press( GtkWidget* widget, MoveSet* mset )
{
int action;
const char* title;
const char* text;
char* dir;
char* name;
char* new_path;
if ( widget == GTK_WIDGET( mset->browse_target ) )
{
title = _("Select Link Target");
action = GTK_FILE_CHOOSER_ACTION_OPEN;
text = gtk_entry_get_text( mset->entry_target );
if ( text[0] == '/' )
{
dir = g_path_get_dirname( text );
name = g_path_get_basename( text );
}
else
{
dir = g_path_get_dirname( mset->full_path );
name = text[0] != '\0' ? g_strdup( text ) : NULL;
}
}
else if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_new_file ) ) )
{
title = _("Select Template File");
action = GTK_FILE_CHOOSER_ACTION_OPEN;
text = gtk_entry_get_text( GTK_ENTRY( gtk_bin_get_child( GTK_BIN(
mset->combo_template ) ) ) );
if ( text && text[0] == '/' )
{
dir = g_path_get_dirname( text );
name = g_path_get_basename( text );
}
else
{
dir = get_template_dir();
if ( !dir )
dir = g_path_get_dirname( mset->full_path );
name = g_strdup( text );
}
}
else
{
title = _("Select Template Folder");
action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER;
text = gtk_entry_get_text( GTK_ENTRY( gtk_bin_get_child( GTK_BIN(
mset->combo_template ) ) ) );
if ( text && text[0] == '/' )
{
dir = g_path_get_dirname( text );
name = g_path_get_basename( text );
}
else
{
dir = get_template_dir();
if ( !dir )
dir = g_path_get_dirname( mset->full_path );
name = g_strdup( text );
}
}
GtkWidget* dlg = gtk_file_chooser_dialog_new( title,
GTK_WINDOW( mset->parent ),
action,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
GTK_STOCK_OK, GTK_RESPONSE_OK, NULL );
xset_set_window_icon( GTK_WINDOW( dlg ) );
if ( !name )
gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dlg), dir );
else
{
char* path = g_build_filename( dir, name, NULL );
gtk_file_chooser_set_filename( GTK_FILE_CHOOSER( dlg ), path );
g_free( path );
}
g_free( dir );
g_free( name );
int width = xset_get_int( "move_dlg_help", "x" );
int height = xset_get_int( "move_dlg_help", "y" );
if ( width && height )
{
// filechooser won't honor default size or size request ?
gtk_widget_show_all( dlg );
gtk_window_set_position( GTK_WINDOW( dlg ), GTK_WIN_POS_CENTER_ALWAYS );
gtk_window_resize( GTK_WINDOW( dlg ), width, height );
while( gtk_events_pending() )
gtk_main_iteration();
gtk_window_set_position( GTK_WINDOW( dlg ), GTK_WIN_POS_CENTER );
}
gint response = gtk_dialog_run(GTK_DIALOG(dlg));
if( response == GTK_RESPONSE_OK )
{
new_path = gtk_file_chooser_get_filename( GTK_FILE_CHOOSER ( dlg ) );
char* path = new_path;
GtkWidget* w;
if ( widget == GTK_WIDGET( mset->browse_target ) )
w = GTK_WIDGET( mset->entry_target );
else
{
if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_new_file ) ) )
w = gtk_bin_get_child( GTK_BIN( mset->combo_template ) );
else
w = gtk_bin_get_child( GTK_BIN( mset->combo_template_dir ) );
dir = get_template_dir();
if ( dir )
{
if ( g_str_has_prefix( new_path, dir ) && new_path[strlen( dir )] == '/' )
path = new_path + strlen( dir ) + 1;
g_free( dir );
}
}
gtk_entry_set_text( GTK_ENTRY( w ), path );
g_free( new_path );
}
GtkAllocation allocation;
gtk_widget_get_allocation ( GTK_WIDGET ( dlg ), &allocation );
width = allocation.width;
height = allocation.height;
if ( width && height )
{
char* str = g_strdup_printf( "%d", width );
xset_set( "move_dlg_help", "x", str );
g_free( str );
str = g_strdup_printf( "%d", height );
xset_set( "move_dlg_help", "y", str );
g_free( str );
}
gtk_widget_destroy( dlg );
}
void on_browse_button_press( GtkWidget* widget, MoveSet* mset )
{
GtkTextIter iter, siter;
// action create folder does not work properly so not used:
// it creates a folder by default with no way to stop it
// it gives 'folder already exists' error popup
GtkWidget* dlg = gtk_file_chooser_dialog_new( _("Select File Path"),
GTK_WINDOW( mset->parent ),
//mset->is_dir ? GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER :
GTK_FILE_CHOOSER_ACTION_SAVE,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
GTK_STOCK_OK, GTK_RESPONSE_OK, NULL );
gtk_text_buffer_get_start_iter( mset->buf_path, &siter );
gtk_text_buffer_get_end_iter( mset->buf_path, &iter );
char* path = gtk_text_buffer_get_text( mset->buf_path, &siter,
&iter, FALSE );
gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dlg), path );
g_free( path );
gtk_text_buffer_get_start_iter( mset->buf_full_name, &siter );
gtk_text_buffer_get_end_iter( mset->buf_full_name, &iter );
path = gtk_text_buffer_get_text( mset->buf_full_name, &siter,
&iter, FALSE );
gtk_file_chooser_set_current_name( GTK_FILE_CHOOSER(dlg), path );
g_free( path );
gtk_file_chooser_set_do_overwrite_confirmation( GTK_FILE_CHOOSER(dlg), FALSE );
int width = xset_get_int( "move_dlg_help", "x" );
int height = xset_get_int( "move_dlg_help", "y" );
if ( width && height )
{
// filechooser won't honor default size or size request ?
gtk_widget_show_all( dlg );
gtk_window_set_position( GTK_WINDOW( dlg ), GTK_WIN_POS_CENTER_ALWAYS );
gtk_window_resize( GTK_WINDOW( dlg ), width, height );
while( gtk_events_pending() )
gtk_main_iteration();
gtk_window_set_position( GTK_WINDOW( dlg ), GTK_WIN_POS_CENTER );
}
gint response = gtk_dialog_run(GTK_DIALOG(dlg));
// bogus GTK warning here: Unable to retrieve the file info for...
if( response == GTK_RESPONSE_OK )
{
path = gtk_file_chooser_get_filename( GTK_FILE_CHOOSER ( dlg ) );
gtk_text_buffer_set_text( mset->buf_full_path, path, -1 );
g_free( path );
}
GtkAllocation allocation;
gtk_widget_get_allocation( GTK_WIDGET(dlg), &allocation );
width = allocation.width;
height = allocation.height;
if ( width && height )
{
char* str = g_strdup_printf( "%d", width );
xset_set( "move_dlg_help", "x", str );
g_free( str );
str = g_strdup_printf( "%d", height );
xset_set( "move_dlg_help", "y", str );
g_free( str );
}
gtk_widget_destroy( dlg );
}
void on_help_activate( GtkMenuItem* item, MoveSet* mset )
{
xset_msg_dialog( mset->dlg, 0, _("Rename / Move Tips"), NULL, 0, _("* To select all the text in an entry, click the entry's label (eg 'Filename:'), press the Alt key shortcut, or use Tab.\n\n* To quickly copy an entry's text to the clipboard, double- or middle-click on the entry's label (eg 'Filename:').\n\n* Multiple files can be selected in the file browser to rename a batch of files."), NULL, NULL );
}
void on_font_change( GtkMenuItem* item, MoveSet* mset )
{
PangoFontDescription* font_desc = NULL;
if ( xset_get_s( "move_dlg_font" ) )
font_desc = pango_font_description_from_string(
xset_get_s( "move_dlg_font" ) );
gtk_widget_modify_font( GTK_WIDGET( mset->input_name ), font_desc );
gtk_widget_modify_font( GTK_WIDGET( mset->entry_ext ), font_desc );
gtk_widget_modify_font( GTK_WIDGET( mset->input_full_name ), font_desc );
gtk_widget_modify_font( GTK_WIDGET( mset->input_path ), font_desc );
gtk_widget_modify_font( GTK_WIDGET( mset->input_full_path ), font_desc );
gtk_widget_modify_font( GTK_WIDGET( mset->label_mime ), font_desc );
if ( mset->entry_target )
gtk_widget_modify_font( GTK_WIDGET( mset->entry_target ), font_desc );
if ( mset->create_new )
{
// doesn't change drop-down font
//gtk_widget_modify_font( GTK_WIDGET( mset->combo_template ), font_desc );
gtk_widget_modify_font( GTK_WIDGET( gtk_bin_get_child(
GTK_BIN( mset->combo_template ) ) ), font_desc );
//gtk_widget_modify_font( GTK_WIDGET( mset->combo_template_dir ), font_desc );
gtk_widget_modify_font( GTK_WIDGET( gtk_bin_get_child(
GTK_BIN( mset->combo_template_dir ) ) ), font_desc );
}
if ( font_desc )
pango_font_description_free( font_desc );
}
void on_opt_toggled( GtkMenuItem* item, MoveSet* mset )
{
const char* action;
char* btn_label = NULL;
char* root_msg;
char* title;
GtkTextIter iter, siter;
gboolean move = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_move ) );
gboolean copy = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_copy ) );
gboolean link = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_link ) );
gboolean copy_target = gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( mset->opt_copy_target ) );
gboolean link_target = gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( mset->opt_link_target ) );
gboolean as_root = gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( mset->opt_as_root ) );
gboolean new_file = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_new_file ) );
gboolean new_folder = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_new_folder ) );
gboolean new_link = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_new_link ) );
const char* desc = NULL;
if ( mset->create_new )
{
btn_label = _("C_reate");
action = C_("Title|", "Create New");
if ( new_file )
desc = C_("Title|CreateNew|", "File");
else if ( new_folder )
desc = C_("Title|CreateNew|", "Folder");
else
desc = C_("Title|CreateNew|", "Link");
}
else
{
gtk_text_buffer_get_start_iter( mset->buf_full_path, &siter );
gtk_text_buffer_get_end_iter( mset->buf_full_path, &iter );
char* full_path = gtk_text_buffer_get_text( mset->buf_full_path, &siter, &iter,
FALSE );
char* new_path = g_path_get_dirname( full_path );
gboolean rename = ( !strcmp( mset->old_path, new_path ) || !strcmp( new_path, "." ) );
g_free( new_path );
g_free( full_path );
if ( move )
{
btn_label = rename ? _("_Rename") : _("_Move");
action = _("Move");
}
else if ( copy )
{
btn_label = _("C_opy");
action = _("Copy");
}
else if ( link )
{
btn_label = _("_Link");
action = _("Create Link To");
}
else if ( copy_target )
{
btn_label = _("C_opy");
action = _("Copy");
desc = _("Link Target");
}
else if ( link_target )
{
btn_label = _("_Link");
action = _("Create Link To");
desc = _("Target");
}
}
if ( as_root )
root_msg = _(" As Root");
else
root_msg = "";
// Window Icon
const char* win_icon;
if ( as_root )
win_icon = "gtk-dialog-warning";
else if ( mset->create_new )
win_icon = "gtk-new";
else
win_icon = "gtk-edit";
GdkPixbuf* pixbuf = gtk_icon_theme_load_icon( gtk_icon_theme_get_default(),
win_icon, 16,
GTK_ICON_LOOKUP_USE_BUILTIN, NULL );
if ( pixbuf )
gtk_window_set_icon( GTK_WINDOW( mset->dlg ), pixbuf );
// title
if ( !desc )
desc = mset->desc;
title = g_strdup_printf( "%s %s%s", action, desc, root_msg );
gtk_window_set_title( GTK_WINDOW( mset->dlg ), title );
g_free( title );
if ( btn_label )
gtk_button_set_label( GTK_BUTTON( mset->next ), btn_label );
gtk_button_set_image( GTK_BUTTON( mset->next ), xset_get_image( as_root ?
"GTK_STOCK_DIALOG_WARNING" : "GTK_STOCK_YES",
GTK_ICON_SIZE_BUTTON ) );
mset->full_path_same = FALSE;
mset->mode_change = TRUE;
on_move_change( GTK_WIDGET( mset->buf_full_path ), mset );
if ( mset->create_new )
on_toggled( NULL, mset );
}
void on_toggled( GtkMenuItem* item, MoveSet* mset )
{
//int (*show) () = NULL;
void (*show) () = NULL;
gboolean someone_is_visible = FALSE;
gboolean opts_visible = FALSE;
// opts
if ( xset_get_b( "move_copy" ) || mset->clip_copy )
gtk_widget_show( mset->opt_copy );
else
{
if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_copy ) ) )
gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( mset->opt_move ), TRUE );
gtk_widget_hide( mset->opt_copy );
}
if ( xset_get_b( "move_link" ) )
{
gtk_widget_show( mset->opt_link );
}
else
{
if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_link ) ) )
gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( mset->opt_move ), TRUE );
gtk_widget_hide( mset->opt_link );
}
if ( xset_get_b( "move_copyt" ) && mset->is_link )
gtk_widget_show( mset->opt_copy_target );
else
{
if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_copy_target ) ) )
gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( mset->opt_move ), TRUE );
gtk_widget_hide( mset->opt_copy_target );
}
if ( xset_get_b( "move_linkt" ) && mset->is_link )
gtk_widget_show( mset->opt_link_target );
else
{
if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_link_target ) ) )
gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( mset->opt_move ), TRUE );
gtk_widget_hide( mset->opt_link_target );
}
if ( xset_get_b( "move_as_root" ) )
gtk_widget_show( mset->opt_as_root );
else
{
gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( mset->opt_as_root ), FALSE );
gtk_widget_hide( mset->opt_as_root );
}
if ( !gtk_widget_get_visible( mset->opt_copy )
&& !gtk_widget_get_visible( mset->opt_link )
&& !gtk_widget_get_visible( mset->opt_copy_target )
&& !gtk_widget_get_visible( mset->opt_link_target ) )
{
gtk_widget_hide( mset->opt_move );
opts_visible = gtk_widget_get_visible( mset->opt_as_root );
}
else
{
gtk_widget_show( mset->opt_move );
opts_visible = TRUE;
}
// entries
if ( xset_get_b( "move_name" ) )
{
show = (GFunc)gtk_widget_show;
someone_is_visible = TRUE;
}
else
show = (GFunc)gtk_widget_hide;
show( mset->label_name );
show( mset->scroll_name );
show( mset->hbox_ext );
show( mset->blank_name );
if ( xset_get_b( "move_filename" ) )
{
show = (GFunc)gtk_widget_show;
someone_is_visible = TRUE;
}
else
show = (GFunc)gtk_widget_hide;
show( mset->label_full_name );
show( mset->scroll_full_name );
show( mset->blank_full_name );
if ( xset_get_b( "move_parent" ) )
{
show = (GFunc)gtk_widget_show;
someone_is_visible = TRUE;
}
else
show = (GFunc)gtk_widget_hide;
show( mset->label_path );
show( mset->scroll_path );
show( mset->blank_path );
if ( xset_get_b( "move_path" ) )
{
show = (GFunc)gtk_widget_show;
someone_is_visible = TRUE;
}
else
show = (GFunc)gtk_widget_hide;
show( mset->label_full_path );
show( mset->scroll_full_path );
if ( !mset->is_link && !mset->create_new && xset_get_b( "move_type" ) )
{
show = (GFunc)gtk_widget_show;
}
else
show = (GFunc)gtk_widget_hide;
show( mset->hbox_type );
gboolean new_file = FALSE;
gboolean new_folder = FALSE;
gboolean new_link = FALSE;
if ( mset->create_new )
{
new_file = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_new_file ) );
new_folder = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_new_folder ) );
new_link = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_new_link ) );
}
if ( new_link || ( mset->is_link && xset_get_b( "move_target" ) ) )
{
show = (GFunc)gtk_widget_show;
}
else
show = (GFunc)gtk_widget_hide;
show( mset->hbox_target );
if ( ( new_file || new_folder ) && xset_get_b( "move_template" ) )
{
show = (GFunc)gtk_widget_show;
if ( new_file )
{
gtk_widget_show( GTK_WIDGET( mset->combo_template ) );
gtk_label_set_mnemonic_widget( mset->label_template,
GTK_WIDGET( mset->combo_template ) );
gtk_widget_hide( GTK_WIDGET( mset->combo_template_dir ) );
}
else
{
gtk_widget_show( GTK_WIDGET( mset->combo_template_dir ) );
gtk_label_set_mnemonic_widget( mset->label_template,
GTK_WIDGET( mset->combo_template_dir ) );
gtk_widget_hide( GTK_WIDGET( mset->combo_template ) );
}
}
else
show = (GFunc)gtk_widget_hide;
show( mset->hbox_template );
if ( !someone_is_visible )
{
xset_set_b( "move_filename", TRUE );
on_toggled( NULL, mset );
}
if ( opts_visible )
{
if ( gtk_widget_get_visible( mset->hbox_type ) )
{}
else if ( gtk_widget_get_visible( GTK_WIDGET( mset->label_full_path ) ) )
{}
else if ( gtk_widget_get_visible( GTK_WIDGET( mset->blank_path ) ) )
gtk_widget_hide( GTK_WIDGET( mset->blank_path ) );
else if ( gtk_widget_get_visible( GTK_WIDGET( mset->blank_full_name ) ) )
gtk_widget_hide( GTK_WIDGET( mset->blank_full_name ) );
else if ( gtk_widget_get_visible( GTK_WIDGET( mset->blank_name ) ) )
gtk_widget_hide( GTK_WIDGET( mset->blank_name ) );
}
}
gboolean on_mnemonic_activate(GtkWidget *widget, gboolean arg1, MoveSet* mset )
{
select_input( widget, mset );
return FALSE;
}
void on_options_button_press( GtkWidget* btn, MoveSet* mset )
{
GtkWidget* popup = gtk_menu_new();
GtkAccelGroup* accel_group = gtk_accel_group_new();
xset_context_new();
XSet* set = xset_set_cb( "move_name", on_toggled, mset );
xset_add_menuitem( mset->desktop, mset->browser, popup, accel_group, set );
set = xset_set_cb( "move_filename", on_toggled, mset );
xset_add_menuitem( mset->desktop, mset->browser, popup, accel_group, set );
set = xset_set_cb( "move_parent", on_toggled, mset );
xset_add_menuitem( mset->desktop, mset->browser, popup, accel_group, set );
set = xset_set_cb( "move_path", on_toggled, mset );
xset_add_menuitem( mset->desktop, mset->browser, popup, accel_group, set );
set = xset_set_cb( "move_type", on_toggled, mset );
set->disable = ( mset->create_new || mset->is_link );
xset_add_menuitem( mset->desktop, mset->browser, popup, accel_group, set );
set = xset_set_cb( "move_target", on_toggled, mset );
set->disable = mset->create_new || !mset->is_link;
xset_add_menuitem( mset->desktop, mset->browser, popup, accel_group, set );
set = xset_set_cb( "move_template", on_toggled, mset );
set->disable = !mset->create_new;
xset_add_menuitem( mset->desktop, mset->browser, popup, accel_group, set );
set = xset_set_cb( "move_copy", on_toggled, mset );
set->disable = mset->clip_copy || mset->create_new;
set = xset_set_cb( "move_link", on_toggled, mset );
set->disable = mset->create_new;
set = xset_set_cb( "move_copyt", on_toggled, mset );
set->disable = !mset->is_link;
set = xset_set_cb( "move_linkt", on_toggled, mset );
set->disable = !mset->is_link;
xset_set_cb( "move_as_root", on_toggled, mset );
set = xset_get( "move_option" );
xset_add_menuitem( mset->desktop, mset->browser, popup, accel_group, set );
set = xset_get( "sep_mopt1" );
xset_add_menuitem( mset->desktop, mset->browser, popup, accel_group, set );
set = xset_get( "move_dlg_confirm_create" );
xset_add_menuitem( mset->desktop, mset->browser, popup, accel_group, set );
set = xset_set_cb( "move_dlg_font", on_font_change, mset );
xset_add_menuitem( mset->desktop, mset->browser, popup, accel_group, set );
set = xset_get( "sep_mopt2" );
xset_add_menuitem( mset->desktop, mset->browser, popup, accel_group, set );
set = xset_set_cb( "move_dlg_help", on_help_activate, mset );
xset_add_menuitem( mset->desktop, mset->browser, popup, accel_group, set );
gtk_widget_show_all( GTK_WIDGET( popup ) );
g_signal_connect( popup, "selection-done",
G_CALLBACK( gtk_widget_destroy ), NULL );
gtk_menu_popup( GTK_MENU( popup ), NULL, NULL,
NULL, NULL, 0, gtk_get_current_event_time() );
}
static gboolean on_label_focus( GtkWidget* widget, GtkDirectionType direction, MoveSet* mset )
{
GtkWidget* input = NULL;
if ( direction == GTK_DIR_TAB_FORWARD )
{
if ( widget == GTK_WIDGET( mset->label_name ) )
input = mset->input_name;
else if ( widget == GTK_WIDGET( mset->label_ext ) )
input = GTK_WIDGET( mset->entry_ext );
else if ( widget == GTK_WIDGET( mset->label_full_name ) )
input = mset->input_full_name;
else if ( widget == GTK_WIDGET( mset->label_path ) )
input = mset->input_path;
else if ( widget == GTK_WIDGET( mset->label_full_path ) )
input = mset->input_full_path;
else if ( widget == GTK_WIDGET( mset->label_type ) )
{
on_button_focus( mset->options, GTK_DIR_TAB_FORWARD, mset );
return TRUE;
}
else if ( widget == GTK_WIDGET( mset->label_target ) )
input = GTK_WIDGET( mset->entry_target );
else if ( widget == GTK_WIDGET( mset->label_template ) )
{
if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_new_file ) ) )
input = GTK_WIDGET( mset->combo_template );
else
input = GTK_WIDGET( mset->combo_template_dir );
}
}
else if ( direction == GTK_DIR_TAB_BACKWARD )
{
GtkWidget* input2;
GtkWidget* first_input;
if ( widget == GTK_WIDGET( mset->label_name ) )
{
if ( mset->combo_template_dir )
input = GTK_WIDGET( mset->combo_template_dir );
else if ( mset->combo_template )
input = GTK_WIDGET( mset->combo_template );
else if ( mset->entry_target )
input = GTK_WIDGET( mset->entry_target );
else
input = mset->input_full_path;
}
else if ( widget == GTK_WIDGET( mset->label_ext ) )
input = mset->input_name;
else if ( widget == GTK_WIDGET( mset->label_full_name ) )
{
if ( gtk_widget_get_visible( gtk_widget_get_parent(
GTK_WIDGET( mset->entry_ext ) ) )
&& gtk_widget_get_sensitive(
GTK_WIDGET( mset->entry_ext ) ) )
input = GTK_WIDGET( mset->entry_ext );
else
input = mset->input_name;
}
else if ( widget == GTK_WIDGET( mset->label_path ) )
input = mset->input_full_name;
else if ( widget == GTK_WIDGET( mset->label_full_path ) )
input = mset->input_path;
else
input = mset->input_full_path;
first_input = input;
while ( input && !gtk_widget_get_visible( gtk_widget_get_parent( input ) ) )
{
input2 = NULL;
if ( input == GTK_WIDGET( mset->combo_template_dir ) )
{
if ( mset->combo_template )
input2 = GTK_WIDGET( mset->combo_template );
else if ( mset->entry_target )
input2 = GTK_WIDGET( mset->entry_target );
else
input2 = mset->input_full_path;
}
else if ( input == GTK_WIDGET( mset->combo_template ) )
{
if ( mset->entry_target )
input2 = GTK_WIDGET( mset->entry_target );
else
input2 = mset->input_full_path;
}
else if ( input == GTK_WIDGET( mset->entry_target ) )
input2 = mset->input_full_path;
else if ( input == mset->input_full_path )
input2 = mset->input_path;
else if ( input == mset->input_path )
input2 = mset->input_full_name;
else if ( input == mset->input_full_name )
{
if ( gtk_widget_get_visible( gtk_widget_get_parent(
GTK_WIDGET( mset->entry_ext ) ) )
&& gtk_widget_get_sensitive(
GTK_WIDGET( mset->entry_ext ) ) )
input2 = GTK_WIDGET( mset->entry_ext );
else
input2 = mset->input_name;
}
else if ( input == GTK_WIDGET( mset->entry_ext ) )
input2 = mset->input_name;
else if ( input == mset->input_name )
{
if ( mset->combo_template_dir )
input2 = GTK_WIDGET( mset->combo_template_dir );
else if ( mset->combo_template )
input2 = GTK_WIDGET( mset->combo_template );
else if ( mset->entry_target )
input2 = GTK_WIDGET( mset->entry_target );
else
input2 = mset->input_full_path;
}
if ( input2 == first_input )
input = NULL;
else
input = input2;
}
}
if ( input == GTK_WIDGET( mset->label_mime ) )
{
gtk_label_select_region( mset->label_mime, 0, -1 );
gtk_widget_grab_focus( GTK_WIDGET( mset->label_mime ) );
}
else if ( input )
{
select_input( input, mset );
gtk_widget_grab_focus( input );
}
return TRUE;
}
void copy_entry_to_clipboard( GtkWidget* widget, MoveSet* mset )
{
GtkClipboard* clip = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD );
GtkTextBuffer* buf = NULL;
GtkTextIter iter, siter;
if ( widget == GTK_WIDGET( mset->label_name ) )
buf = mset->buf_name;
else if ( widget == GTK_WIDGET( mset->label_ext ) )
{
gtk_clipboard_set_text( clip, gtk_entry_get_text( mset->entry_ext ), -1 );
return;
}
else if ( widget == GTK_WIDGET( mset->label_full_name ) )
buf = mset->buf_full_name;
else if ( widget == GTK_WIDGET( mset->label_path ) )
buf = mset->buf_path;
else if ( widget == GTK_WIDGET( mset->label_full_path ) )
buf = mset->buf_full_path;
else if ( widget == GTK_WIDGET( mset->label_type ) )
{
gtk_clipboard_set_text( clip, mset->mime_type, -1 );
return;
}
else if ( widget == GTK_WIDGET( mset->label_target ) )
{
gtk_clipboard_set_text( clip, gtk_entry_get_text( mset->entry_target ), -1 );
return;
}
else if ( widget == GTK_WIDGET( mset->label_template ) )
{
GtkWidget* w;
if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_new_file ) ) )
w = gtk_bin_get_child( GTK_BIN( mset->combo_template ) );
else
w = gtk_bin_get_child( GTK_BIN( mset->combo_template_dir ) );
gtk_clipboard_set_text( clip, gtk_entry_get_text( GTK_ENTRY( w ) ), -1 );
}
if ( !buf )
return;
gtk_text_buffer_get_start_iter( buf, &siter );
gtk_text_buffer_get_end_iter( buf, &iter );
char* text = gtk_text_buffer_get_text( buf, &siter, &iter, FALSE );
gtk_clipboard_set_text( clip, text, -1 );
g_free( text );
}
gboolean on_label_button_press( GtkWidget *widget,
GdkEventButton *event,
MoveSet* mset )
{
if ( event->type == GDK_BUTTON_PRESS )
{
if ( event->button == 1 || event->button == 2 )
{
GtkWidget* input = NULL;
if ( widget == GTK_WIDGET( mset->label_name ) )
input = mset->input_name;
else if ( widget == GTK_WIDGET( mset->label_ext ) )
input = GTK_WIDGET( mset->entry_ext );
else if ( widget == GTK_WIDGET( mset->label_full_name ) )
input = mset->input_full_name;
else if ( widget == GTK_WIDGET( mset->label_path ) )
input = mset->input_path;
else if ( widget == GTK_WIDGET( mset->label_full_path ) )
input = mset->input_full_path;
else if ( widget == GTK_WIDGET( mset->label_type ) )
{
gtk_label_select_region( mset->label_mime, 0, -1 );
gtk_widget_grab_focus( GTK_WIDGET( mset->label_mime ) );
if ( event->button == 2 )
copy_entry_to_clipboard( widget, mset );
return TRUE;
}
else if ( widget == GTK_WIDGET( mset->label_target ) )
input = GTK_WIDGET( mset->entry_target );
else if ( widget == GTK_WIDGET( mset->label_template ) )
{
if ( gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( mset->opt_new_file ) ) )
input = GTK_WIDGET( mset->combo_template );
else
input = GTK_WIDGET( mset->combo_template_dir );
}
if ( input )
{
select_input( input, mset );
gtk_widget_grab_focus( input );
if ( event->button == 2 )
copy_entry_to_clipboard( widget, mset );
}
}
}
else if ( event->type == GDK_2BUTTON_PRESS )
copy_entry_to_clipboard( widget, mset );
return TRUE;
}
char* get_unique_name( const char* dir, const char* ext )
{
char* name, *path;
char* base = _("new");
if ( ext && ext[0] != '\0' )
{
name = g_strdup_printf( "%s.%s", base, ext );
path = g_build_filename( dir, name, NULL );
g_free( name );
}
else
path = g_build_filename( dir, base, NULL );
int n = 2;
struct stat64 statbuf;
while ( lstat64( path, &statbuf ) == 0 ) // g_file_test doesn't see broken links
{
g_free( path );
if ( n == 1000 )
return g_strdup( base );
if ( ext && ext[0] != '\0' )
name = g_strdup_printf( "%s%d.%s", base, n++, ext );
else
name = g_strdup_printf( "%s%d", base, n++ );
path = g_build_filename( dir, name, NULL );
g_free( name );
}
return path;
}
char* get_template_dir()
{
char* templates_path = g_strdup( g_getenv( "XDG_TEMPLATES_DIR" ) );
if ( !dir_has_files( templates_path ) )
{
g_free( templates_path );
templates_path = g_build_filename( g_get_home_dir(), "Templates", NULL );
if ( !dir_has_files( templates_path ) )
{
g_free( templates_path );
templates_path = g_build_filename( g_get_home_dir(), ".templates", NULL );
if ( !dir_has_files( templates_path ) )
{
g_free( templates_path );
templates_path = NULL;
}
}
}
return templates_path;
}
GList* get_templates( const char* templates_dir, const char* subdir,
GList* templates, gboolean getdir )
{
const char* name;
char* path;
char* subsubdir;
char* templates_path;
if ( !templates_dir )
{
templates_path = get_template_dir();
if ( templates_path )
templates = get_templates( templates_path, NULL, templates, getdir );
g_free( templates_path );
return templates;
}
templates_path = g_build_filename( templates_dir, subdir, NULL );
GDir* dir = g_dir_open( templates_path, 0, NULL );
if ( dir )
{
while ( name = g_dir_read_name( dir ) )
{
path = g_build_filename( templates_path, name, NULL );
if ( getdir )
{
if ( g_file_test( path, G_FILE_TEST_IS_DIR ) )
{
if ( subdir )
subsubdir = g_build_filename( subdir, name, NULL );
else
subsubdir = g_strdup( name );
templates = g_list_prepend( templates,
g_strdup_printf( "%s/", subsubdir ) );
templates = get_templates( templates_dir, subsubdir, templates,
getdir );
g_free( subsubdir );
}
}
else
{
if ( g_file_test( path, G_FILE_TEST_IS_REGULAR ) )
{
if ( subdir )
templates = g_list_prepend( templates, g_build_filename(
subdir, name, NULL ) );
else
templates = g_list_prepend( templates, g_strdup( name ) );
}
else if ( g_file_test( path, G_FILE_TEST_IS_DIR ) )
{
if ( subdir )
{
subsubdir = g_build_filename( subdir, name, NULL );
templates = get_templates( templates_dir, subsubdir,
templates, getdir );
g_free( subsubdir );
}
else
templates = get_templates( templates_dir, name, templates,
getdir );
}
}
g_free( path );
}
g_dir_close( dir );
}
g_free( templates_path );
return templates;
}
void on_template_changed( GtkWidget* widget, MoveSet* mset )
{
char* str = NULL;
char* str2;
if ( !gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( mset->opt_new_file ) ) )
return;
char* text = g_strdup( gtk_entry_get_text( GTK_ENTRY( gtk_bin_get_child(
GTK_BIN( mset->combo_template ) ) ) ) );
if ( text )
{
g_strstrip( text );
str = text;
while ( str2 = strchr( str, '/' ) )
str = str2 + 1;
if ( str[0] == '.' )
str++;
if ( str2 = strchr( str, '.' ) )
str = str2 + 1;
else
str = NULL;
}
gtk_entry_set_text( mset->entry_ext, str ? str : "" );
// need new name due to extension added?
GtkTextIter iter, siter;
gtk_text_buffer_get_start_iter( mset->buf_full_path, &siter );
gtk_text_buffer_get_end_iter( mset->buf_full_path, &iter );
char* full_path = gtk_text_buffer_get_text( mset->buf_full_path, &siter, &iter, FALSE );
struct stat64 statbuf;
if ( lstat64( full_path, &statbuf ) == 0 ) // g_file_test doesn't see broken links
{
char* dir = g_path_get_dirname( full_path );
g_free( full_path );
full_path = get_unique_name( dir, str );
if ( full_path )
{
gtk_text_buffer_set_text( mset->buf_full_path, full_path, -1 );
}
g_free( dir );
}
g_free( full_path );
g_free( text );
}
gboolean update_new_display_delayed( char* path )
{
char* dir_path = g_path_get_dirname( path );
VFSDir* vdir = vfs_dir_get_by_path_soft( dir_path );
g_free( dir_path );
if ( vdir && vdir->avoid_changes )
{
VFSFileInfo* file = vfs_file_info_new();
vfs_file_info_get( file, path, NULL );
vfs_dir_emit_file_created( vdir, vfs_file_info_get_name( file ), TRUE );
vfs_file_info_unref( file );
vfs_dir_flush_notify_cache();
}
if ( vdir )
g_object_unref( vdir );
g_free( path );
return FALSE;
}
void update_new_display( const char* path )
{
// for devices like nfs, emit created so the new file is shown
// update now
update_new_display_delayed( g_strdup( path ) );
// update a little later for exec tasks
g_timeout_add( 1500, (GSourceFunc)update_new_display_delayed, g_strdup( path ) );
}
int ptk_rename_file( DesktopWindow* desktop, PtkFileBrowser* file_browser,
const char* file_dir, VFSFileInfo* file,
const char* dest_dir, gboolean clip_copy,
int create_new, AutoOpenCreate* auto_open )
{
char* full_name;
char* full_path;
char* path;
char* old_path;
char* root_mkdir = g_strdup( "" );
char* to_path;
char* from_path;
char* task_name;
char* str;
GtkTextIter iter, siter;
GtkWidget* task_view = NULL;
int ret = 1;
gboolean target_missing = FALSE;
GList* templates;
FILE* touchfile;
struct stat64 statbuf;
if ( !file_dir )
return 0;
MoveSet* mset = g_slice_new0( MoveSet );
full_name = NULL;
if ( !create_new )
{
if ( !file )
return 0;
// special processing for files with inconsistent real name and display name
if( G_UNLIKELY( vfs_file_info_is_desktop_entry(file) ) )
full_name = g_filename_display_name( file->name );
if ( !full_name )
full_name = g_strdup( vfs_file_info_get_disp_name( file ) );
if ( !full_name )
full_name = g_strdup( vfs_file_info_get_name( file ) );
mset->is_dir = vfs_file_info_is_dir( file );
mset->is_link = vfs_file_info_is_symlink( file );
mset->clip_copy = clip_copy;
mset->full_path = g_build_filename( file_dir, full_name, NULL );
if ( dest_dir )
mset->new_path = g_build_filename( dest_dir, full_name, NULL );
else
mset->new_path = g_strdup( mset->full_path );
g_free( full_name );
full_name = NULL;
}
else if ( create_new == 3 && file ) // new link
{
full_name = g_strdup( vfs_file_info_get_disp_name( file ) );
if ( !full_name )
full_name = g_strdup( vfs_file_info_get_name( file ) );
mset->full_path = g_build_filename( file_dir, full_name, NULL );
mset->new_path = g_strdup( mset->full_path );
mset->is_dir = vfs_file_info_is_dir( file );
mset->is_link = vfs_file_info_is_symlink( file );
mset->clip_copy = FALSE;
}
else
{
mset->full_path = get_unique_name( file_dir, NULL );
mset->new_path = g_strdup( mset->full_path );
mset->is_dir = FALSE;
mset->is_link = FALSE;
mset->clip_copy = FALSE;
}
mset->create_new = create_new;
mset->old_path = file_dir;
mset->full_path_exists = FALSE;
mset->full_path_exists_dir = FALSE;
mset->full_path_same = FALSE;
mset->path_missing = FALSE;
mset->path_exists_file = FALSE;
mset->is_move = FALSE;
// Dialog
char* root_msg;
if ( mset->is_link )
mset->desc = _("Link");
else if ( mset->is_dir )
mset->desc = _("Folder");
else
mset->desc = _("File");
/*
char* title;
char* action;
if ( job == JOB_COPY )
action = "Copy";
else if ( job == JOB_MOVE )
action = "Rename / Move";
else
action = "Create Link To";
title = g_strdup_printf( "%s %s%s", action, mset->desc, root_msg );
*/
mset->browser = file_browser;
mset->desktop = desktop;
if ( file_browser )
{
mset->parent = gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) );
task_view = file_browser->task_view;
}
else
mset->parent = GTK_WIDGET( desktop );
mset->dlg = gtk_dialog_new_with_buttons( _("Move"),
GTK_WINDOW( mset->parent ),
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
NULL, NULL );
//g_free( title );
gtk_window_set_role( GTK_WINDOW( mset->dlg ), "rename_dialog" );
// Buttons
mset->options = gtk_button_new_with_mnemonic( _("Opt_ions") );
gtk_dialog_add_action_widget( GTK_DIALOG( mset->dlg ), mset->options, GTK_RESPONSE_YES);
gtk_button_set_image( GTK_BUTTON( mset->options ), xset_get_image( "GTK_STOCK_PROPERTIES",
GTK_ICON_SIZE_BUTTON ) );
gtk_button_set_focus_on_click( GTK_BUTTON( mset->options ), FALSE );
g_signal_connect( G_OBJECT( mset->options ), "clicked",
G_CALLBACK( on_options_button_press ), mset );
mset->browse = gtk_button_new_with_mnemonic( _("_Browse") );
gtk_dialog_add_action_widget( GTK_DIALOG( mset->dlg ), mset->browse, GTK_RESPONSE_YES);
gtk_button_set_image( GTK_BUTTON( mset->browse ), xset_get_image( "GTK_STOCK_OPEN",
GTK_ICON_SIZE_BUTTON ) );
gtk_button_set_focus_on_click( GTK_BUTTON( mset->browse ), FALSE );
g_signal_connect( G_OBJECT( mset->browse ), "clicked",
G_CALLBACK( on_browse_button_press ), mset );
mset->revert = gtk_button_new_with_mnemonic( _("Re_vert") );
gtk_dialog_add_action_widget( GTK_DIALOG( mset->dlg ), mset->revert, GTK_RESPONSE_NO);
gtk_button_set_image( GTK_BUTTON( mset->revert ), xset_get_image( "GTK_STOCK_REVERT_TO_SAVED",
GTK_ICON_SIZE_BUTTON ) );
gtk_button_set_focus_on_click( GTK_BUTTON( mset->revert ), FALSE );
g_signal_connect( G_OBJECT( mset->revert ), "clicked",
G_CALLBACK( on_revert_button_press ), mset );
mset->cancel = gtk_button_new_from_stock( GTK_STOCK_CANCEL );
gtk_dialog_add_action_widget( GTK_DIALOG( mset->dlg ), mset->cancel, GTK_RESPONSE_CANCEL);
mset->next = gtk_button_new_from_stock( GTK_STOCK_OK );
gtk_dialog_add_action_widget( GTK_DIALOG( mset->dlg ), mset->next, GTK_RESPONSE_OK);
gtk_button_set_focus_on_click( GTK_BUTTON( mset->next ), FALSE );
gtk_button_set_image( GTK_BUTTON( mset->next ), xset_get_image( "GTK_STOCK_YES",
GTK_ICON_SIZE_BUTTON ) );
gtk_button_set_label( GTK_BUTTON( mset->next ), _("_Rename") );
if ( create_new && auto_open )
{
mset->open = gtk_button_new_with_mnemonic( _("& _Open") );
gtk_dialog_add_action_widget( GTK_DIALOG( mset->dlg ), mset->open, GTK_RESPONSE_APPLY);
gtk_button_set_focus_on_click( GTK_BUTTON( mset->open ), FALSE );
}
else
mset->open = NULL;
// Window
int width = xset_get_int( "move_dlg_font", "x" );
int height = xset_get_int( "move_dlg_font", "y" );
if ( width && height )
gtk_window_set_default_size( GTK_WINDOW( mset->dlg ), width, height );
else
gtk_widget_set_size_request( GTK_WIDGET( mset->dlg ), 600, -1 );
gtk_window_set_resizable( GTK_WINDOW( mset->dlg ), TRUE );
gtk_window_set_type_hint( GTK_WINDOW ( mset->dlg ),
GDK_WINDOW_TYPE_HINT_DIALOG );
gtk_widget_show_all( mset->dlg );
// Entries
// Type
char* type;
mset->label_type = GTK_LABEL( gtk_label_new( NULL ) );
gtk_label_set_markup_with_mnemonic( mset->label_type, _("<b>Type:</b>") );
if ( mset->is_link )
{
//mset->mime_type = g_strdup_printf( "inode/symlink" );
//type = g_strdup_printf( "symbolic link ( inode/symlink )" );
path = g_file_read_link( mset->full_path, NULL );
if ( path )
{
mset->mime_type = path;
if ( g_file_test( path, G_FILE_TEST_EXISTS ) )
type = g_strdup_printf( _("Link-> %s"), path );
else
{
type = g_strdup_printf( _("!Link-> %s (missing)"), path );
target_missing = TRUE;
}
}
else
{
mset->mime_type = g_strdup_printf( "inode/symlink" );
type = g_strdup_printf( "symbolic link ( inode/symlink )" );
}
}
else if ( file )
{
VFSMimeType* mime_type = vfs_file_info_get_mime_type( file );
if ( mime_type )
{
mset->mime_type = g_strdup( vfs_mime_type_get_type( mime_type ) );
type = g_strdup_printf( " %s ( %s )",
vfs_mime_type_get_description( mime_type ),
mset->mime_type );
vfs_mime_type_unref( mime_type );
}
else
{
mset->mime_type = g_strdup_printf( "?" );
type = g_strdup( mset->mime_type );
}
}
else //create
{
mset->mime_type = g_strdup_printf( "?" );
type = g_strdup( mset->mime_type );
}
mset->label_mime = GTK_LABEL( gtk_label_new( type ) );
gtk_label_set_ellipsize( mset->label_mime, PANGO_ELLIPSIZE_MIDDLE );
g_free( type );
gtk_label_set_selectable( mset->label_mime, TRUE );
gtk_misc_set_alignment( GTK_MISC( mset->label_mime ), 0, 0 );
gtk_label_set_selectable( mset->label_type, TRUE );
g_signal_connect( G_OBJECT( mset->label_type ), "button-press-event",
G_CALLBACK( on_label_button_press ), mset );
g_signal_connect( G_OBJECT( mset->label_type ), "focus",
G_CALLBACK( on_label_focus ), mset );
// Target
if ( mset->is_link || create_new )
{
mset->label_target = GTK_LABEL( gtk_label_new( NULL ) );
gtk_label_set_markup_with_mnemonic( mset->label_target, _("<b>_Target:</b>") );
gtk_misc_set_alignment( GTK_MISC( mset->label_target ), 0, 1 );
mset->entry_target = GTK_ENTRY( gtk_entry_new() );
gtk_label_set_mnemonic_widget( mset->label_target, GTK_WIDGET( mset->entry_target ) );
g_signal_connect( G_OBJECT( mset->entry_target ), "mnemonic-activate",
G_CALLBACK( on_mnemonic_activate ), mset );
gtk_label_set_selectable( mset->label_target, TRUE );
g_signal_connect( G_OBJECT( mset->label_target ), "button-press-event",
G_CALLBACK( on_label_button_press ), mset );
g_signal_connect( G_OBJECT( mset->label_target ), "focus",
G_CALLBACK( on_label_focus ), mset );
g_signal_connect( G_OBJECT( mset->entry_target ), "key-press-event",
G_CALLBACK( on_move_entry_keypress ), mset );
//g_signal_connect_after( G_OBJECT( mset->entry_target ), "focus",
// G_CALLBACK( on_focus ), mset );
//gtk_widget_set_sensitive( GTK_WIDGET( mset->entry_target ), !mset->is_dir );
//gtk_widget_set_sensitive( GTK_WIDGET( mset->label_target ), !mset->is_dir );
if ( create_new )
{
// Target Browse button
mset->browse_target = gtk_button_new();
gtk_button_set_image( GTK_BUTTON( mset->browse_target ),
xset_get_image( "GTK_STOCK_OPEN", GTK_ICON_SIZE_BUTTON ) );
gtk_button_set_focus_on_click( GTK_BUTTON( mset->browse_target ), FALSE );
if ( mset->new_path && file )
gtk_entry_set_text( GTK_ENTRY( mset->entry_target ), mset->new_path );
g_signal_connect( G_OBJECT( mset->browse_target ), "clicked",
G_CALLBACK( on_create_browse_button_press ), mset );
}
else
{
gtk_entry_set_text( GTK_ENTRY( mset->entry_target ), mset->mime_type );
gtk_editable_set_editable( GTK_EDITABLE( mset->entry_target ), FALSE );
mset->browse_target = NULL;
}
g_signal_connect( G_OBJECT( mset->entry_target ), "changed",
G_CALLBACK( on_move_change ), mset );
}
else
mset->label_target = NULL;
// Template
if ( create_new )
{
mset->label_template = GTK_LABEL( gtk_label_new( NULL ) );
gtk_label_set_markup_with_mnemonic( mset->label_template, _("<b>_Template:</b>") );
gtk_misc_set_alignment( GTK_MISC( mset->label_template ), 0, 1 );
g_signal_connect( G_OBJECT( mset->entry_target ), "mnemonic-activate",
G_CALLBACK( on_mnemonic_activate ), mset );
gtk_label_set_selectable( mset->label_template, TRUE );
g_signal_connect( G_OBJECT( mset->label_template ), "button-press-event",
G_CALLBACK( on_label_button_press ), mset );
g_signal_connect( G_OBJECT( mset->label_template ), "focus",
G_CALLBACK( on_label_focus ), mset );
// template combo
mset->combo_template = GTK_COMBO_BOX( gtk_combo_box_text_new_with_entry() );
gtk_combo_box_set_focus_on_click( mset->combo_template, FALSE );
// add entries
gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( mset->combo_template ),
_("Empty File") );
templates = NULL;
templates = get_templates( NULL, NULL, templates, FALSE );
if ( templates )
{
templates = g_list_sort( templates, (GCompareFunc) g_strcmp0 );
GList* l;
for ( l = templates; l; l = l->next )
{
gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( mset->combo_template ),
(char*)l->data );
g_free( l->data );
}
g_list_free( templates );
}
//gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( mset->combo_template ),
// _("Add...") );
gtk_combo_box_set_active( GTK_COMBO_BOX( mset->combo_template ), 0 );
g_signal_connect( G_OBJECT( mset->combo_template ), "changed",
G_CALLBACK( on_template_changed ), mset );
g_signal_connect( G_OBJECT( gtk_bin_get_child( GTK_BIN( mset->combo_template ) ) ),
"key-press-event", G_CALLBACK( on_move_entry_keypress ), mset );
//gtk_label_set_mnemonic_widget( mset->label_template, GTK_WIDGET( mset->combo_template ) );
// template_dir combo
mset->combo_template_dir = GTK_COMBO_BOX( gtk_combo_box_text_new_with_entry() );
gtk_combo_box_set_focus_on_click( mset->combo_template_dir, FALSE );
// add entries
gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( mset->combo_template_dir ),
_("Empty Folder") );
templates = NULL;
templates = get_templates( NULL, NULL, templates, TRUE );
if ( templates )
{
templates = g_list_sort( templates, (GCompareFunc) g_strcmp0 );
GList* l;
for ( l = templates; l; l = l->next )
{
gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT(
mset->combo_template_dir ),
(char*)l->data );
g_free( l->data );
}
g_list_free( templates );
}
//gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( mset->combo_template_dir ),
// _("Add...") );
gtk_combo_box_set_active( GTK_COMBO_BOX( mset->combo_template_dir ), 0 );
g_signal_connect( G_OBJECT( gtk_bin_get_child( GTK_BIN( mset->combo_template_dir ) ) ),
"key-press-event", G_CALLBACK( on_move_entry_keypress ), mset );
//g_signal_connect( G_OBJECT( mset->combo_template_dir ), "changed",
// G_CALLBACK( on_template_changed ), mset );
//gtk_label_set_mnemonic_widget( mset->label_template, GTK_WIDGET(
// mset->combo_template_dir ) );
// Template Browse button
mset->browse_template = gtk_button_new();
gtk_button_set_image( GTK_BUTTON( mset->browse_template ),
xset_get_image( "GTK_STOCK_OPEN", GTK_ICON_SIZE_BUTTON ) );
gtk_button_set_focus_on_click( GTK_BUTTON( mset->browse_template ), FALSE );
g_signal_connect( G_OBJECT( mset->browse_template ), "clicked",
G_CALLBACK( on_create_browse_button_press ), mset );
}
else
{
mset->label_template = NULL;
mset->combo_template = NULL;
mset->combo_template_dir = NULL;
}
// Name
mset->label_name = GTK_LABEL( gtk_label_new( NULL ) );
gtk_label_set_markup_with_mnemonic( mset->label_name, _("<b>_Name:</b>") );
gtk_misc_set_alignment( GTK_MISC( mset->label_name ), 0, 0 );
mset->scroll_name = gtk_scrolled_window_new( NULL, NULL );
mset->input_name = GTK_WIDGET( multi_input_new(
GTK_SCROLLED_WINDOW( mset->scroll_name ), NULL, FALSE ) );
gtk_label_set_mnemonic_widget( mset->label_name, mset->input_name );
g_signal_connect( G_OBJECT( mset->input_name ), "key-press-event",
G_CALLBACK( on_move_keypress ), mset );
g_signal_connect( G_OBJECT( mset->input_name ), "mnemonic-activate",
G_CALLBACK( on_mnemonic_activate ), mset );
gtk_label_set_selectable( mset->label_name, TRUE );
g_signal_connect( G_OBJECT( mset->label_name ), "button-press-event",
G_CALLBACK( on_label_button_press ), mset );
g_signal_connect( G_OBJECT( mset->label_name ), "focus",
G_CALLBACK( on_label_focus ), mset );
mset->buf_name = GTK_TEXT_BUFFER( gtk_text_view_get_buffer(
GTK_TEXT_VIEW( mset->input_name ) ) );
g_signal_connect( G_OBJECT( mset->buf_name ), "changed",
G_CALLBACK( on_move_change ), mset );
g_signal_connect( G_OBJECT( mset->input_name ), "focus",
G_CALLBACK( on_focus ), mset );
mset->blank_name = GTK_LABEL( gtk_label_new( NULL ) );
// Ext
mset->label_ext = GTK_LABEL( gtk_label_new( NULL ) );
gtk_label_set_markup_with_mnemonic( mset->label_ext, _("<b>E_xtension:</b>") );
gtk_misc_set_alignment( GTK_MISC( mset->label_ext ), 0, 1 );
mset->entry_ext = GTK_ENTRY( gtk_entry_new() );
gtk_label_set_mnemonic_widget( mset->label_ext, GTK_WIDGET( mset->entry_ext ) );
g_signal_connect( G_OBJECT( mset->entry_ext ), "mnemonic-activate",
G_CALLBACK( on_mnemonic_activate ), mset );
gtk_label_set_selectable( mset->label_ext, TRUE );
g_signal_connect( G_OBJECT( mset->label_ext ), "button-press-event",
G_CALLBACK( on_label_button_press ), mset );
g_signal_connect( G_OBJECT( mset->label_ext ), "focus",
G_CALLBACK( on_label_focus ), mset );
g_signal_connect( G_OBJECT( mset->entry_ext ), "key-press-event",
G_CALLBACK( on_move_entry_keypress ), mset );
g_signal_connect( G_OBJECT( mset->entry_ext ), "changed",
G_CALLBACK( on_move_change ), mset );
g_signal_connect_after( G_OBJECT( mset->entry_ext ), "focus",
G_CALLBACK( on_focus ), mset );
gtk_widget_set_sensitive( GTK_WIDGET( mset->entry_ext ), !mset->is_dir );
gtk_widget_set_sensitive( GTK_WIDGET( mset->label_ext ), !mset->is_dir );
// Filename
mset->label_full_name = GTK_LABEL( gtk_label_new( NULL ) );
gtk_label_set_markup_with_mnemonic( mset->label_full_name, _("<b>_Filename:</b>") ); gtk_misc_set_alignment( GTK_MISC( mset->label_full_name ), 0, 0 );
mset->scroll_full_name = gtk_scrolled_window_new( NULL, NULL );
mset->input_full_name = GTK_WIDGET( multi_input_new(
GTK_SCROLLED_WINDOW( mset->scroll_full_name ), NULL, FALSE ) );
gtk_label_set_mnemonic_widget( mset->label_full_name, mset->input_full_name );
g_signal_connect( G_OBJECT( mset->input_full_name ), "mnemonic-activate",
G_CALLBACK( on_mnemonic_activate ), mset );
gtk_label_set_selectable( mset->label_full_name, TRUE );
g_signal_connect( G_OBJECT( mset->label_full_name ), "button-press-event",
G_CALLBACK( on_label_button_press ), mset );
g_signal_connect( G_OBJECT( mset->label_full_name ), "focus",
G_CALLBACK( on_label_focus ), mset );
g_signal_connect( G_OBJECT( mset->input_full_name ), "key-press-event",
G_CALLBACK( on_move_keypress ), mset );
mset->buf_full_name = gtk_text_view_get_buffer(
GTK_TEXT_VIEW( mset->input_full_name ) );
g_signal_connect( G_OBJECT( mset->buf_full_name ), "changed",
G_CALLBACK( on_move_change ), mset );
g_signal_connect( G_OBJECT( mset->input_full_name ), "focus",
G_CALLBACK( on_focus ), mset );
mset->blank_full_name = GTK_LABEL( gtk_label_new( NULL ) );
// Parent
mset->label_path = GTK_LABEL( gtk_label_new( NULL ) );
gtk_label_set_markup_with_mnemonic( mset->label_path, _("<b>_Parent:</b>") );
gtk_misc_set_alignment( GTK_MISC( mset->label_path ), 0, 0 );
mset->scroll_path = gtk_scrolled_window_new( NULL, NULL );
mset->input_path = GTK_WIDGET( multi_input_new( GTK_SCROLLED_WINDOW( mset->scroll_path ),
NULL, FALSE ) );
gtk_label_set_mnemonic_widget( mset->label_path, mset->input_path );
g_signal_connect( G_OBJECT( mset->input_path ), "mnemonic-activate",
G_CALLBACK( on_mnemonic_activate ), mset );
gtk_label_set_selectable( mset->label_path, TRUE );
g_signal_connect( G_OBJECT( mset->label_path ), "button-press-event",
G_CALLBACK( on_label_button_press ), mset );
g_signal_connect( G_OBJECT( mset->label_path ), "focus",
G_CALLBACK( on_label_focus ), mset );
g_signal_connect( G_OBJECT( mset->input_path ), "key-press-event",
G_CALLBACK( on_move_keypress ), mset );
mset->buf_path = gtk_text_view_get_buffer( GTK_TEXT_VIEW( mset->input_path ) );
g_signal_connect( G_OBJECT( mset->buf_path ), "changed",
G_CALLBACK( on_move_change ), mset );
g_signal_connect( G_OBJECT( mset->input_path ), "focus",
G_CALLBACK( on_focus ), mset );
mset->blank_path = GTK_LABEL( gtk_label_new( NULL ) );
// Path
mset->label_full_path = GTK_LABEL( gtk_label_new( NULL ) );
gtk_label_set_markup_with_mnemonic( mset->label_full_path, _("<b>P_ath:</b>") );
gtk_misc_set_alignment( GTK_MISC( mset->label_full_path ), 0, 0 );
mset->scroll_full_path = gtk_scrolled_window_new( NULL, NULL );
// set initial path
mset->input_full_path = GTK_WIDGET( multi_input_new(
GTK_SCROLLED_WINDOW( mset->scroll_full_path ),
mset->new_path, FALSE ) );
gtk_label_set_mnemonic_widget( mset->label_full_path, mset->input_full_path );
g_signal_connect( G_OBJECT( mset->input_full_path ), "mnemonic-activate",
G_CALLBACK( on_mnemonic_activate ), mset );
gtk_label_set_selectable( mset->label_full_path, TRUE );
g_signal_connect( G_OBJECT( mset->label_full_path ), "button-press-event",
G_CALLBACK( on_label_button_press ), mset );
g_signal_connect( G_OBJECT( mset->label_full_path ), "focus",
G_CALLBACK( on_label_focus ), mset );
g_signal_connect( G_OBJECT( mset->input_full_path ), "key-press-event",
G_CALLBACK( on_move_keypress ), mset );
mset->buf_full_path = gtk_text_view_get_buffer(
GTK_TEXT_VIEW( mset->input_full_path ) );
g_signal_connect( G_OBJECT( mset->buf_full_path ), "changed",
G_CALLBACK( on_move_change ), mset );
g_signal_connect( G_OBJECT( mset->input_full_path ), "focus",
G_CALLBACK( on_focus ), mset );
// Options
mset->opt_move = gtk_radio_button_new_with_mnemonic( NULL, _("Mov_e") );
mset->opt_copy = gtk_radio_button_new_with_mnemonic_from_widget(
GTK_RADIO_BUTTON(mset->opt_move), _("Cop_y") );
mset->opt_link = gtk_radio_button_new_with_mnemonic_from_widget(
GTK_RADIO_BUTTON(mset->opt_move), _("Lin_k") );
mset->opt_copy_target = gtk_radio_button_new_with_mnemonic_from_widget(
GTK_RADIO_BUTTON(mset->opt_move), _("Copy _Target") );
mset->opt_link_target = gtk_radio_button_new_with_mnemonic_from_widget(
GTK_RADIO_BUTTON(mset->opt_move), _("Link Tar_get") );
mset->opt_as_root = gtk_check_button_new_with_mnemonic( _("A_s Root") );
mset->opt_new_file = gtk_radio_button_new_with_mnemonic( NULL, C_("New|Radio", "Fil_e") );
mset->opt_new_folder = gtk_radio_button_new_with_mnemonic_from_widget(
GTK_RADIO_BUTTON( mset->opt_new_file ), C_("New|Radio", "Fol_der") );
mset->opt_new_link = gtk_radio_button_new_with_mnemonic_from_widget(
GTK_RADIO_BUTTON( mset->opt_new_file ), C_("New|Radio", "_Link") );
gtk_button_set_focus_on_click( GTK_BUTTON( mset->opt_move ), FALSE );
g_signal_connect( G_OBJECT( mset->opt_move ), "focus",
G_CALLBACK( on_button_focus ), mset );
gtk_button_set_focus_on_click( GTK_BUTTON( mset->opt_copy ), FALSE );
gtk_button_set_focus_on_click( GTK_BUTTON( mset->opt_link ), FALSE );
gtk_button_set_focus_on_click( GTK_BUTTON( mset->opt_copy_target ), FALSE );
gtk_button_set_focus_on_click( GTK_BUTTON( mset->opt_link_target ), FALSE );
gtk_button_set_focus_on_click( GTK_BUTTON( mset->opt_as_root ), FALSE );
gtk_button_set_focus_on_click( GTK_BUTTON( mset->opt_new_file ), FALSE );
g_signal_connect( G_OBJECT( mset->opt_new_file ), "focus",
G_CALLBACK( on_button_focus ), mset );
gtk_button_set_focus_on_click( GTK_BUTTON( mset->opt_new_folder ), FALSE );
gtk_button_set_focus_on_click( GTK_BUTTON( mset->opt_new_link ), FALSE );
gtk_widget_set_sensitive( mset->opt_copy_target, mset->is_link && !target_missing );
gtk_widget_set_sensitive( mset->opt_link_target, mset->is_link );
// Pack
GtkWidget* dlg_vbox = gtk_dialog_get_content_area( GTK_DIALOG( mset->dlg ) );
gtk_container_set_border_width( GTK_CONTAINER ( mset->dlg ), 10 );
gtk_box_pack_start( GTK_BOX( dlg_vbox ),
GTK_WIDGET( mset->label_name ), FALSE, TRUE, 4 );
gtk_box_pack_start( GTK_BOX( dlg_vbox ),
GTK_WIDGET( mset->scroll_name ), TRUE, TRUE, 0 );
mset->hbox_ext = gtk_hbox_new( FALSE, 0 );
gtk_box_pack_start( GTK_BOX( mset->hbox_ext ),
GTK_WIDGET( mset->label_ext ), FALSE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX( mset->hbox_ext ),
GTK_WIDGET( gtk_label_new( " " ) ), FALSE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX( mset->hbox_ext ),
GTK_WIDGET( mset->entry_ext ), TRUE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX( dlg_vbox ),
GTK_WIDGET( mset->hbox_ext ), FALSE, TRUE, 5 );
gtk_box_pack_start( GTK_BOX( dlg_vbox ),
GTK_WIDGET( mset->blank_name ), FALSE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX( dlg_vbox ),
GTK_WIDGET( mset->label_full_name ), FALSE, TRUE, 4 );
gtk_box_pack_start( GTK_BOX( dlg_vbox ),
GTK_WIDGET( mset->scroll_full_name ), TRUE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX( dlg_vbox ),
GTK_WIDGET( mset->blank_full_name ), FALSE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX( dlg_vbox ),
GTK_WIDGET( mset->label_path ), FALSE, TRUE, 4 );
gtk_box_pack_start( GTK_BOX( dlg_vbox ),
GTK_WIDGET( mset->scroll_path ), TRUE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX( dlg_vbox ),
GTK_WIDGET( mset->blank_path ), FALSE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX( dlg_vbox ),
GTK_WIDGET( mset->label_full_path ), FALSE, TRUE, 4 );
gtk_box_pack_start( GTK_BOX( dlg_vbox ),
GTK_WIDGET( mset->scroll_full_path ), TRUE, TRUE, 0 );
mset->hbox_type = gtk_hbox_new( FALSE, 0 );
gtk_box_pack_start( GTK_BOX( mset->hbox_type ),
GTK_WIDGET( mset->label_type ), FALSE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX( mset->hbox_type ),
GTK_WIDGET( mset->label_mime ), TRUE, TRUE, 5 );
gtk_box_pack_start( GTK_BOX( dlg_vbox ),
GTK_WIDGET( mset->hbox_type ), FALSE, TRUE, 5 );
mset->hbox_target = gtk_hbox_new( FALSE, 0 );
if ( mset->label_target )
{
gtk_box_pack_start( GTK_BOX( mset->hbox_target ),
GTK_WIDGET( mset->label_target ), FALSE, TRUE, 0 );
if ( !create_new )
gtk_box_pack_start( GTK_BOX( mset->hbox_target ),
GTK_WIDGET( gtk_label_new( " " ) ), FALSE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX( mset->hbox_target ),
GTK_WIDGET( mset->entry_target ), TRUE, TRUE,
create_new ? 3 : 0 );
if ( mset->browse_target )
gtk_box_pack_start( GTK_BOX( mset->hbox_target ),
GTK_WIDGET( mset->browse_target ), FALSE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX( dlg_vbox ),
GTK_WIDGET( mset->hbox_target ), FALSE, TRUE, 5 );
}
mset->hbox_template = gtk_hbox_new( FALSE, 0 );
if ( mset->label_template )
{
gtk_box_pack_start( GTK_BOX( mset->hbox_template ),
GTK_WIDGET( mset->label_template ), FALSE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX( mset->hbox_template ),
GTK_WIDGET( mset->combo_template ), TRUE, TRUE, 3 );
gtk_box_pack_start( GTK_BOX( mset->hbox_template ),
GTK_WIDGET( mset->combo_template_dir ), TRUE, TRUE, 3 );
gtk_box_pack_start( GTK_BOX( mset->hbox_template ),
GTK_WIDGET( mset->browse_template ), FALSE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX( dlg_vbox ),
GTK_WIDGET( mset->hbox_template ), FALSE, TRUE, 5 );
}
GtkWidget* hbox = gtk_hbox_new( FALSE, 4 );
if ( create_new )
{
gtk_box_pack_start( GTK_BOX( hbox ),
GTK_WIDGET( gtk_label_new( _("New") ) ), FALSE, TRUE, 3 );
gtk_box_pack_start( GTK_BOX( hbox ),
GTK_WIDGET( mset->opt_new_file ), FALSE, TRUE, 3 );
gtk_box_pack_start( GTK_BOX( hbox ),
GTK_WIDGET( mset->opt_new_folder ), FALSE, TRUE, 3 );
gtk_box_pack_start( GTK_BOX( hbox ),
GTK_WIDGET( mset->opt_new_link ), FALSE, TRUE, 3 );
}
else
{
gtk_box_pack_start( GTK_BOX( hbox ),
GTK_WIDGET( mset->opt_move ), FALSE, TRUE, 3 );
gtk_box_pack_start( GTK_BOX( hbox ),
GTK_WIDGET( mset->opt_copy ), FALSE, TRUE, 3 );
gtk_box_pack_start( GTK_BOX( hbox ),
GTK_WIDGET( mset->opt_link ), FALSE, TRUE, 3 );
gtk_box_pack_start( GTK_BOX( hbox ),
GTK_WIDGET( mset->opt_copy_target ), FALSE, TRUE, 3 );
gtk_box_pack_start( GTK_BOX( hbox ),
GTK_WIDGET( mset->opt_link_target ), FALSE, TRUE, 3 );
}
gtk_box_pack_start( GTK_BOX( hbox ),
GTK_WIDGET( gtk_label_new( " " ) ), FALSE, TRUE, 3 );
gtk_box_pack_start( GTK_BOX( hbox ),
GTK_WIDGET( mset->opt_as_root ), FALSE, TRUE, 6 );
gtk_box_pack_start( GTK_BOX( dlg_vbox ),
GTK_WIDGET( hbox ), FALSE, TRUE, 10 );
// show
on_font_change( NULL, mset );
gtk_widget_show_all( mset->dlg );
on_toggled( NULL, mset );
if ( mset->clip_copy )
{
gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON( mset->opt_copy ), TRUE );
gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON( mset->opt_move ), FALSE );
}
else if ( create_new == 2 )
{
gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON( mset->opt_new_folder ), TRUE );
gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON( mset->opt_new_file ), FALSE );
}
else if ( create_new == 3 )
{
gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON( mset->opt_new_link ), TRUE );
gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON( mset->opt_new_file ), FALSE );
}
// signals
g_signal_connect( G_OBJECT( mset->opt_move ), "toggled",
G_CALLBACK( on_opt_toggled ), mset );
g_signal_connect( G_OBJECT( mset->opt_copy ), "toggled",
G_CALLBACK( on_opt_toggled ), mset );
g_signal_connect( G_OBJECT( mset->opt_link ), "toggled",
G_CALLBACK( on_opt_toggled ), mset );
g_signal_connect( G_OBJECT( mset->opt_copy_target ), "toggled",
G_CALLBACK( on_opt_toggled ), mset );
g_signal_connect( G_OBJECT( mset->opt_link_target ), "toggled",
G_CALLBACK( on_opt_toggled ), mset );
g_signal_connect( G_OBJECT( mset->opt_as_root ), "toggled",
G_CALLBACK( on_opt_toggled ), mset );
g_signal_connect( G_OBJECT( mset->opt_new_file ), "toggled",
G_CALLBACK( on_opt_toggled ), mset );
g_signal_connect( G_OBJECT( mset->opt_new_folder ), "toggled",
G_CALLBACK( on_opt_toggled ), mset );
g_signal_connect( G_OBJECT( mset->opt_new_link ), "toggled",
G_CALLBACK( on_opt_toggled ), mset );
// init
on_move_change( GTK_WIDGET( mset->buf_full_path ), mset );
on_opt_toggled( NULL, mset );
// last widget
int last = xset_get_int( "move_dlg_font", "z" );
if ( last == 1 )
mset->last_widget = mset->input_name;
else if ( last == 2 )
mset->last_widget = GTK_WIDGET( mset->entry_ext );
else if ( last == 3 )
mset->last_widget = mset->input_path;
else if ( last == 4 )
mset->last_widget = mset->input_full_path;
else
mset->last_widget = mset->input_full_name;
if ( !gtk_widget_get_visible( gtk_widget_get_parent( mset->last_widget ) ) )
{
if ( gtk_widget_get_visible( gtk_widget_get_parent( mset->input_name ) ) )
mset->last_widget = mset->input_name;
else if ( gtk_widget_get_visible( gtk_widget_get_parent( mset->input_full_name ) ) )
mset->last_widget = mset->input_full_name;
else if ( gtk_widget_get_visible( gtk_widget_get_parent( mset->input_path ) ) )
mset->last_widget = mset->input_path;
else if ( gtk_widget_get_visible( gtk_widget_get_parent( mset->input_full_path ) ) )
mset->last_widget = mset->input_full_path;
}
// select last widget
select_input( mset->last_widget, mset );
gtk_widget_grab_focus( mset->last_widget );
g_signal_connect( G_OBJECT( mset->options ), "focus",
G_CALLBACK( on_button_focus ), mset );
g_signal_connect( G_OBJECT( mset->next ), "focus",
G_CALLBACK( on_button_focus ), mset );
g_signal_connect( G_OBJECT( mset->cancel ), "focus",
G_CALLBACK( on_button_focus ), mset );
// run
int response;
while ( response = gtk_dialog_run( GTK_DIALOG( mset->dlg ) ) )
{
if ( response == GTK_RESPONSE_OK || response == GTK_RESPONSE_APPLY )
{
gtk_text_buffer_get_start_iter( mset->buf_full_path, &siter );
gtk_text_buffer_get_end_iter( mset->buf_full_path, &iter );
full_path = gtk_text_buffer_get_text( mset->buf_full_path, &siter, &iter, FALSE );
if ( full_path[0] != '/' )
{
// update full_path to absolute
char* cwd = g_path_get_dirname( mset->full_path );
char* old_path = full_path;
full_path = g_build_filename( cwd, old_path, NULL );
g_free( cwd );
g_free( old_path );
}
if ( strchr( full_path, '\n' ) )
{
ptk_show_error( GTK_WINDOW( mset->dlg ),
_("Error"), _("Path contains linefeeds") );
g_free( full_path );
continue;
}
full_name = g_path_get_basename( full_path );
path = g_path_get_dirname( full_path );
old_path = g_path_get_dirname( mset->full_path );
gboolean overwrite = FALSE;
char* msg;
if ( response == GTK_RESPONSE_APPLY )
ret = 2;
if ( !create_new && ( mset->full_path_same ||
!strcmp( full_path, mset->full_path ) ) )
{
// not changed, proceed to next file
g_free( full_path );
g_free( full_name );
g_free( path );
g_free( old_path );
break;
}
// determine job
gboolean move = gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( mset->opt_move ) );
gboolean copy = gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( mset->opt_copy ) );
gboolean link = gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( mset->opt_link ) );
gboolean copy_target = gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( mset->opt_copy_target ) );
gboolean link_target = gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( mset->opt_link_target ) );
gboolean as_root = gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( mset->opt_as_root ) );
gboolean new_file = gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( mset->opt_new_file ) );
gboolean new_folder = gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( mset->opt_new_folder ) );
gboolean new_link = gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( mset->opt_new_link ) );
if ( as_root )
root_msg = _(" As Root");
else
root_msg = "";
if ( !g_file_test( path, G_FILE_TEST_EXISTS ) )
{
// create parent folder
if ( xset_get_b( "move_dlg_confirm_create" ) )
{
if ( xset_msg_dialog( mset->parent, GTK_MESSAGE_QUESTION,
_("Create Parent Folder"), NULL,
GTK_BUTTONS_YES_NO,
_("The parent folder does not exist. Create it?"), NULL, NULL )
!= GTK_RESPONSE_YES )
goto _continue_free;
}
if ( as_root )
{
g_free( root_mkdir );
to_path = bash_quote( path );
root_mkdir = g_strdup_printf( "mkdir -p %s && ", to_path );
g_free( to_path );
}
else if ( g_mkdir_with_parents( path, 0755 ) != 0 )
{
msg = g_strdup_printf( _("Error creating parent folder\n\n%s"),
strerror( errno ) );
ptk_show_error( GTK_WINDOW( mset->dlg ),
_("Mkdir Error"), msg );
g_free( msg );
goto _continue_free;
}
else
update_new_display( path );
}
else if ( lstat64( full_path, &statbuf ) == 0 )
{
// overwrite
if ( g_file_test( full_path, G_FILE_TEST_IS_DIR ) )
goto _continue_free; // just in case
if ( xset_msg_dialog( mset->parent, GTK_MESSAGE_WARNING,
_("Overwrite Existing File"), NULL,
GTK_BUTTONS_YES_NO,
_("OVERWRITE WARNING"), _("The file path exists. Overwrite existing file?"), NULL )
!= GTK_RESPONSE_YES )
goto _continue_free;
overwrite = TRUE;
}
if ( create_new && new_link )
{
// new link task
task_name = g_strdup_printf( _("Create Link%s"), root_msg );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL, mset->parent,
task_view );
g_free( task_name );
str = g_strdup( gtk_entry_get_text( mset->entry_target ) );
g_strstrip( str );
while ( g_str_has_suffix( str, "/" ) && str[1] != '\0' )
str[g_utf8_strlen( str, -1 ) - 1] = '\0';
from_path = bash_quote( str );
g_free( str );
to_path = bash_quote( full_path );
if ( overwrite )
{
task->task->exec_command = g_strdup_printf( "%sln -sf %s %s",
root_mkdir, from_path, to_path );
}
else
{
task->task->exec_command = g_strdup_printf( "%sln -s %s %s",
root_mkdir, from_path, to_path );
}
g_free( from_path );
g_free( to_path );
task->task->exec_sync = TRUE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE;
task->task->exec_export = FALSE;
task->task->exec_as_user = as_root ? g_strdup( "root" ) : NULL;
if ( auto_open )
{
auto_open->path = g_strdup( full_path );
auto_open->open_file = ( response == GTK_RESPONSE_APPLY );
task->complete_notify = auto_open->callback;
task->user_data = auto_open;
}
ptk_file_task_run( task );
update_new_display( full_path );
}
else if ( create_new && new_file )
{
// new file task
if ( gtk_widget_get_visible( gtk_widget_get_parent(
GTK_WIDGET( mset->combo_template ) ) ) &&
( str = gtk_combo_box_text_get_active_text(
GTK_COMBO_BOX_TEXT( mset->combo_template ) ) ) )
{
g_strstrip( str );
if ( str[0] == '/' )
from_path = bash_quote( str );
else if ( !g_strcmp0( _("Empty File"), str ) || str[0] == '\0' )
from_path = NULL;
else
{
char* tdir = get_template_dir();
if ( tdir )
{
from_path = g_build_filename( tdir, str, NULL );
if ( !g_file_test( from_path, G_FILE_TEST_IS_REGULAR ) )
{
ptk_show_error( GTK_WINDOW( mset->dlg ), _("Template Missing"),
_("The specified template does not exist") );
g_free( from_path );
g_free( str );
g_free( tdir );
goto _continue_free;
}
g_free( str );
g_free( tdir );
str = from_path;
from_path = bash_quote( str );
}
else
from_path = NULL;
}
g_free( str );
}
else
from_path = NULL;
to_path = bash_quote( full_path );
char* over_cmd;
if ( overwrite )
over_cmd = g_strdup_printf( "rm -f %s && ", to_path );
else
over_cmd = g_strdup( "" );
task_name = g_strdup_printf( _("Create New File%s"), root_msg );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL, mset->parent,
task_view );
g_free( task_name );
if ( !from_path )
task->task->exec_command = g_strdup_printf( "%s%stouch %s",
root_mkdir, over_cmd, to_path );
else
task->task->exec_command = g_strdup_printf( "%s%scp -f %s %s",
root_mkdir, over_cmd, from_path, to_path );
g_free( from_path );
g_free( to_path );
g_free( over_cmd );
task->task->exec_sync = TRUE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE;
task->task->exec_export = FALSE;
task->task->exec_as_user = as_root ? g_strdup( "root" ) : NULL;
if ( auto_open )
{
auto_open->path = g_strdup( full_path );
auto_open->open_file = ( response == GTK_RESPONSE_APPLY );
task->complete_notify = auto_open->callback;
task->user_data = auto_open;
}
ptk_file_task_run( task );
update_new_display( full_path );
}
else if ( create_new )
{
// new folder task
if ( !new_folder )
goto _continue_free; // failsafe
if ( gtk_widget_get_visible( gtk_widget_get_parent(
GTK_WIDGET( mset->combo_template_dir ) ) ) &&
( str = gtk_combo_box_text_get_active_text(
GTK_COMBO_BOX_TEXT( mset->combo_template_dir ) ) ) )
{
g_strstrip( str );
if ( str[0] == '/' )
from_path = bash_quote( str );
else if ( !g_strcmp0( _("Empty Folder"), str ) || str[0] == '\0' )
from_path = NULL;
else
{
char* tdir = get_template_dir();
if ( tdir )
{
from_path = g_build_filename( tdir, str, NULL );
if ( !g_file_test( from_path, G_FILE_TEST_IS_DIR ) )
{
ptk_show_error( GTK_WINDOW( mset->dlg ), _("Template Missing"),
_("The specified template does not exist") );
g_free( from_path );
g_free( str );
g_free( tdir );
goto _continue_free;
}
g_free( str );
g_free( tdir );
str = from_path;
from_path = bash_quote( str );
}
else
from_path = NULL;
}
g_free( str );
}
else
from_path = NULL;
to_path = bash_quote( full_path );
task_name = g_strdup_printf( _("Create New Folder%s"), root_msg );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL, mset->parent,
task_view );
g_free( task_name );
if ( !from_path )
task->task->exec_command = g_strdup_printf( "%smkdir %s",
root_mkdir, to_path );
else
task->task->exec_command = g_strdup_printf( "%scp -rL %s %s",
root_mkdir, from_path, to_path );
g_free( from_path );
g_free( to_path );
task->task->exec_sync = TRUE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE;
task->task->exec_export = FALSE;
task->task->exec_as_user = as_root ? g_strdup( "root" ) : NULL;
if ( auto_open )
{
auto_open->path = g_strdup( full_path );
auto_open->open_file = ( response == GTK_RESPONSE_APPLY );
task->complete_notify = auto_open->callback;
task->user_data = auto_open;
}
ptk_file_task_run( task );
update_new_display( full_path );
}
else if ( copy || copy_target )
{
// copy task
task_name = g_strdup_printf( _("Copy%s"), root_msg );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL, mset->parent,
task_view );
g_free( task_name );
char* over_opt = NULL;
to_path = bash_quote( full_path );
if ( copy || !mset->is_link )
from_path = bash_quote( mset->full_path );
else
{
str = g_file_read_link( mset->full_path, NULL );
if ( !str )
{
ptk_show_error( GTK_WINDOW( mset->dlg ), _("Copy Target Error"),
_("Error determining link's target") );
goto _continue_free;
}
from_path = bash_quote( str );
g_free( str );
}
if ( overwrite )
over_opt = g_strdup( " --remove-destination" );
if ( !over_opt )
over_opt = g_strdup( "" );
if ( mset->is_dir )
{
task->task->exec_command = g_strdup_printf( "%scp -Pfr %s %s",
root_mkdir, from_path, to_path );
}
else
{
task->task->exec_command = g_strdup_printf( "%scp -Pf%s %s %s",
root_mkdir, over_opt, from_path, to_path );
}
g_free( from_path );
g_free( to_path );
g_free( over_opt );
task->task->exec_sync = TRUE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE;
task->task->exec_export = FALSE;
task->task->exec_as_user = as_root ? g_strdup( "root" ) : NULL;
ptk_file_task_run( task );
update_new_display( full_path );
}
else if ( link || link_target )
{
// link task
task_name = g_strdup_printf( _("Create Link%s"), root_msg );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL, mset->parent,
task_view );
g_free( task_name );
if ( link || !mset->is_link )
from_path = bash_quote( mset->full_path );
else
{
str = g_file_read_link( mset->full_path, NULL );
if ( !str )
{
ptk_show_error( GTK_WINDOW( mset->dlg ), _("Link Target Error"),
_("Error determining link's target") );
goto _continue_free;
}
from_path = bash_quote( str );
g_free( str );
}
to_path = bash_quote( full_path );
if ( overwrite )
{
task->task->exec_command = g_strdup_printf( "%sln -sf %s %s",
root_mkdir, from_path, to_path );
}
else
{
task->task->exec_command = g_strdup_printf( "%sln -s %s %s",
root_mkdir, from_path, to_path );
}
g_free( from_path );
g_free( to_path );
task->task->exec_sync = TRUE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE;
task->task->exec_export = FALSE;
task->task->exec_as_user = as_root ? g_strdup( "root" ) : NULL;
ptk_file_task_run( task );
update_new_display( full_path );
}
// need move? (do move as task in case it takes a long time)
else if ( as_root || strcmp( old_path, path ) )
{
// move task
task_name = g_strdup_printf( _("Move%s"), root_msg );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL, mset->parent,
task_view );
g_free( task_name );
from_path = bash_quote( mset->full_path );
to_path = bash_quote( full_path );
if ( overwrite )
{
task->task->exec_command = g_strdup_printf( "%smv -f %s %s",
root_mkdir, from_path, to_path );
}
else
{
task->task->exec_command = g_strdup_printf( "%smv %s %s",
root_mkdir, from_path, to_path );
}
g_free( from_path );
g_free( to_path );
task->task->exec_sync = TRUE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE;
task->task->exec_export = FALSE;
task->task->exec_as_user = as_root ? g_strdup( "root" ) : NULL;
ptk_file_task_run( task );
update_new_display( full_path );
}
else
{
// rename (does overwrite)
if ( rename( mset->full_path, full_path ) != 0 )
{
msg = g_strdup_printf( _("Error renaming file\n\n%s"),
strerror( errno ) );
ptk_show_error( GTK_WINDOW( mset->dlg ),
_("Rename Error"), msg );
g_free( msg );
goto _continue_free;
}
else
update_new_display( full_path );
}
g_free( full_path );
g_free( full_name );
g_free( path );
g_free( old_path );
break;
_continue_free:
g_free( full_path );
g_free( full_name );
g_free( path );
g_free( old_path );
}
else if ( response == GTK_RESPONSE_CANCEL
|| response == GTK_RESPONSE_DELETE_EVENT )
{
ret = 0;
break;
}
}
if ( response == 0 )
ret = 0;
// save size
GtkAllocation allocation;
gtk_widget_get_allocation ( GTK_WIDGET( mset->dlg ), &allocation );
width = allocation.width;
height = allocation.height;
if ( width && height )
{
str = g_strdup_printf( "%d", width );
xset_set( "move_dlg_font", "x", str );
g_free( str );
str = g_strdup_printf( "%d", height );
xset_set( "move_dlg_font", "y", str );
g_free( str );
}
// save last_widget
if ( mset->last_widget == mset->input_name )
last = 1;
else if ( mset->last_widget == GTK_WIDGET( mset->entry_ext ) )
last = 2;
else if ( mset->last_widget == mset->input_path )
last = 3;
else if ( mset->last_widget == mset->input_full_path )
last = 4;
else
last = 0;
str = g_strdup_printf( "%d", last );
xset_set( "move_dlg_font", "z", str );
g_free( str );
// destroy
gtk_widget_destroy( mset->dlg );
g_free( root_mkdir );
g_free( mset->full_path );
if ( mset->new_path )
g_free( mset->new_path );
if ( mset->mime_type )
g_free( mset->mime_type );
g_slice_free( MoveSet, mset );
return ret;
}
/*
gboolean ptk_rename_file( GtkWindow* parent_win,
const char* cwd,
VFSFileInfo* file )
{
GtkWidget * input_dlg;
GtkLabel* prompt;
char* ufile_name;
char* file_name;
char* from_path;
char* to_path;
gboolean ret = FALSE;
char* disp_name = NULL;
if ( !cwd || !file )
return FALSE;
// special processing for files with incosistent real name and display name
if( G_UNLIKELY( vfs_file_info_is_desktop_entry(file) ) )
disp_name = g_filename_display_name( file->name );
input_dlg = ptk_input_dialog_new( _( "Rename File" ),
_( "Please input new file name:" ),
disp_name ? disp_name : vfs_file_info_get_disp_name( file ), parent_win );
g_free( disp_name );
gtk_window_set_default_size( GTK_WINDOW( input_dlg ),
360, -1 );
// Without this line, selected region in entry cannot be set
gtk_widget_show( input_dlg );
if ( ! vfs_file_info_is_dir( file ) )
select_file_name_part( GTK_ENTRY( ptk_input_dialog_get_entry( GTK_WIDGET( input_dlg ) ) ) );
while ( gtk_dialog_run( GTK_DIALOG( input_dlg ) ) == GTK_RESPONSE_OK )
{
prompt = GTK_LABEL( ptk_input_dialog_get_label( input_dlg ) );
ufile_name = ptk_input_dialog_get_text( input_dlg );
file_name = g_filename_from_utf8( ufile_name, -1, NULL, NULL, NULL );
g_free( ufile_name );
if ( file_name )
{
from_path = g_build_filename( cwd,
vfs_file_info_get_name( file ), NULL );
to_path = g_build_filename( cwd,
file_name, NULL );
if ( g_file_test( to_path, G_FILE_TEST_EXISTS ) )
{
gtk_label_set_text( prompt,
_( "The file name you specified already exists.\n"
"Please input a new one:" ) );
}
else
{
if ( 0 == rename( from_path, to_path ) )
{
ret = TRUE;
break;
}
else
{
gtk_label_set_text( prompt, strerror( errno ) );
}
}
g_free( from_path );
g_free( to_path );
}
else
{
gtk_label_set_text( prompt,
_( "The file name you specified already exists.\n"
"Please input a new one:" ) );
}
}
gtk_widget_destroy( input_dlg );
return ret;
}
*/
gboolean ptk_create_new_file( GtkWindow* parent_win,
const char* cwd,
gboolean create_folder,
VFSFileInfo** file )
{
gchar * full_path;
gchar* ufile_name;
gchar* file_name;
GtkLabel* prompt;
int result;
GtkWidget* dlg;
gboolean ret = FALSE;
gboolean looponce = FALSE; //MOD
if ( create_folder )
{
dlg = ptk_input_dialog_new( _( "New Folder" ),
_( "New folder name:" ),
_( "New Folder" ),
parent_win );
}
else
{
dlg = ptk_input_dialog_new( _( "New File" ),
_( "New filename:" ),
_( "New File" ),
parent_win );
}
while ( gtk_dialog_run( GTK_DIALOG( dlg ) ) == GTK_RESPONSE_OK )
{
looponce = TRUE; //MOD
ufile_name = ptk_input_dialog_get_text( dlg );
if ( g_get_filename_charsets( NULL ) )
file_name = ufile_name;
else
{
file_name = g_filename_from_utf8( ufile_name, -1,
NULL, NULL, NULL );
g_free( ufile_name );
}
full_path = g_build_filename( cwd, file_name, NULL );
g_free( file_name );
if ( g_file_test( full_path, G_FILE_TEST_EXISTS ) )
{
prompt = GTK_LABEL( ptk_input_dialog_get_label( dlg ) );
gtk_label_set_text( prompt,
_( "Name already exists.\n\nPlease input a new one:" ) );
g_free( full_path );
continue;
}
if ( create_folder )
{
result = mkdir( full_path, 0755 );
ret = (result==0);
}
else
{
result = open( full_path, O_CREAT, 0644 );
if ( result != -1 )
{
close( result );
ret = TRUE;
}
}
if( ret && file )
{
*file = vfs_file_info_new();
vfs_file_info_get( *file, full_path, NULL );
}
g_free( full_path );
break;
}
gtk_widget_destroy( dlg );
if( ! ret && looponce ) //MOD
ptk_show_error( parent_win,
_("Error"),
_( "The new file cannot be created" ) );
return ret;
}
void ptk_show_file_properties( GtkWindow* parent_win,
const char* cwd,
GList* sel_files, int page )
{
GtkWidget * dlg;
if ( sel_files )
{
/* Make a copy of the list */
sel_files = g_list_copy( sel_files );
g_list_foreach( sel_files, (GFunc) vfs_file_info_ref, NULL );
dlg = file_properties_dlg_new( parent_win, cwd, sel_files, page );
}
else
{
// no files selected, use cwd as file
VFSFileInfo* file = vfs_file_info_new();
vfs_file_info_get( file, cwd, NULL );
sel_files = g_list_prepend( NULL, vfs_file_info_ref( file ) );
char* parent_dir = g_path_get_dirname( cwd );
dlg = file_properties_dlg_new( parent_win, parent_dir, sel_files, page );
}
g_signal_connect_swapped( dlg, "destroy",
G_CALLBACK( vfs_file_info_list_free ), sel_files );
gtk_widget_show( dlg );
}
static gboolean open_files_with_app( const char* cwd,
GList* files,
const char* app_desktop,
PtkFileBrowser* file_browser )
{
gchar * name;
GError* err = NULL;
VFSAppDesktop* app;
GdkScreen* screen;
/* Check whether this is an app desktop file or just a command line */
/* Not a desktop entry name */
if ( g_str_has_suffix ( app_desktop, ".desktop" ) )
{
app = vfs_app_desktop_new( app_desktop );
}
else
{
/*
* If we are lucky enough, there might be a desktop entry
* for this program
*/
name = g_strconcat ( app_desktop, ".desktop", NULL );
if ( g_file_test( name, G_FILE_TEST_EXISTS ) )
{
app = vfs_app_desktop_new( name );
}
else
{
/* dirty hack! */
app = vfs_app_desktop_new( NULL );
app->exec = g_strdup( app_desktop );
}
g_free( name );
}
if( file_browser )
screen = gtk_widget_get_screen( GTK_WIDGET(file_browser) );
else
screen = gdk_screen_get_default();
if ( ! vfs_app_desktop_open_files( screen, cwd, app, files, &err ) )
{
GtkWidget * toplevel = file_browser ? gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) ) : NULL;
char* msg = g_markup_escape_text(err->message, -1);
ptk_show_error( GTK_WINDOW( toplevel ),
_("Error"),
msg );
g_free(msg);
g_error_free( err );
}
vfs_app_desktop_unref( app );
return TRUE;
}
static void open_files_with_each_app( gpointer key, gpointer value, gpointer user_data )
{
const char * app_desktop = ( const char* ) key;
const char* cwd;
GList* files = ( GList* ) value;
PtkFileBrowser* file_browser = ( PtkFileBrowser* ) user_data;
/* FIXME: cwd should be passed into this function */
cwd = file_browser ? ptk_file_browser_get_cwd(file_browser) : NULL;
open_files_with_app( cwd, files, app_desktop, file_browser );
}
static void free_file_list_hash( gpointer key, gpointer value, gpointer user_data )
{
const char * app_desktop;
GList* files;
app_desktop = ( const char* ) key;
files = ( GList* ) value;
g_list_foreach( files, ( GFunc ) g_free, NULL );
g_list_free( files );
}
void ptk_open_files_with_app( const char* cwd,
GList* sel_files,
char* app_desktop,
PtkFileBrowser* file_browser,
gboolean xforce, gboolean xnever )
{
GList * l;
gchar* full_path = NULL;
VFSFileInfo* file;
VFSMimeType* mime_type;
GList* files_to_open = NULL;
GHashTable* file_list_hash = NULL;
GError* err;
char* new_dir = NULL;
char* choosen_app = NULL;
GtkWidget* toplevel;
PtkFileBrowser* fb;
for ( l = sel_files; l; l = l->next )
{
file = ( VFSFileInfo* ) l->data;
if ( G_UNLIKELY( ! file ) )
continue;
full_path = g_build_filename( cwd,
vfs_file_info_get_name( file ),
NULL );
if ( G_LIKELY( full_path ) )
{
if ( ! app_desktop ) /* Use default apps for each file */
{
if ( g_file_test( full_path, G_FILE_TEST_IS_DIR ) )
{
if ( ! new_dir )
new_dir = full_path;
else
{
if ( G_LIKELY( file_browser ) )
{
ptk_file_browser_emit_open( file_browser,
full_path, PTK_OPEN_NEW_TAB );
}
}
continue;
}
/* If this file is an executable file, run it. */
if ( !xnever && vfs_file_info_is_executable( file, full_path ) &&
( ! app_settings.no_execute || xforce ) ) //MOD
{
char * argv[ 2 ] = { full_path, NULL };
GdkScreen* screen = file_browser ? gtk_widget_get_screen( GTK_WIDGET(file_browser) ) : gdk_screen_get_default();
err = NULL;
if ( ! vfs_exec_on_screen ( screen, cwd, argv, NULL,
vfs_file_info_get_disp_name( file ),
VFS_EXEC_DEFAULT_FLAGS, &err ) )
{
char* msg = g_markup_escape_text(err->message, -1);
toplevel = file_browser ? gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) ) : NULL;
ptk_show_error( ( GtkWindow* ) toplevel,
_("Error"),
msg );
g_free(msg);
g_error_free( err );
}
else
{
if ( G_LIKELY( file_browser ) )
{
ptk_file_browser_emit_open( file_browser,
full_path, PTK_OPEN_FILE );
}
}
g_free( full_path );
continue;
}
mime_type = vfs_file_info_get_mime_type( file );
/* The file itself is a desktop entry file. */
/* if( g_str_has_suffix( vfs_file_info_get_name( file ), ".desktop" ) ) */
if ( file->flags & VFS_FILE_INFO_DESKTOP_ENTRY &&
( ! app_settings.no_execute || xforce ) ) //sfm
app_desktop = full_path;
else
app_desktop = vfs_mime_type_get_default_action( mime_type );
if ( !app_desktop && mime_type_is_text_file( full_path, mime_type->type ) )
{
/* FIXME: special handling for plain text file */
vfs_mime_type_unref( mime_type );
mime_type = vfs_mime_type_get_from_type( XDG_MIME_TYPE_PLAIN_TEXT );
app_desktop = vfs_mime_type_get_default_action( mime_type );
}
if ( !app_desktop && vfs_file_info_is_symlink( file ) )
{
// broken link?
char* target_path = g_file_read_link( full_path, NULL );
if ( target_path )
{
if ( !g_file_test( target_path, G_FILE_TEST_EXISTS ) )
{
char* msg = g_strdup_printf( _("This symlink's target is missing or you do not have permission to access it:\n%s\n\nTarget: %s"), full_path, target_path );
toplevel = file_browser ? gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) ) : NULL;
ptk_show_error( ( GtkWindow* ) toplevel,
_("Broken Link"), msg );
g_free(msg);
g_free( full_path );
g_free( target_path );
continue;
}
g_free( target_path );
}
}
if ( !app_desktop )
{
toplevel = file_browser ? gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) ) : NULL; /* Let the user choose an application */
choosen_app = (char *) ptk_choose_app_for_mime_type(
( GtkWindow* ) toplevel,
mime_type, FALSE );
app_desktop = choosen_app;
}
if ( ! app_desktop )
{
g_free( full_path );
continue;
}
files_to_open = NULL;
if ( ! file_list_hash )
file_list_hash = g_hash_table_new_full( g_str_hash, g_str_equal, g_free, NULL );
else
files_to_open = g_hash_table_lookup( file_list_hash, app_desktop );
if ( app_desktop != full_path )
files_to_open = g_list_append( files_to_open, full_path );
g_hash_table_replace( file_list_hash, app_desktop, files_to_open );
app_desktop = NULL;
vfs_mime_type_unref( mime_type );
}
else
{
files_to_open = g_list_append( files_to_open, full_path );
}
}
}
if ( file_list_hash )
{
g_hash_table_foreach( file_list_hash,
open_files_with_each_app, file_browser );
g_hash_table_foreach( file_list_hash,
free_file_list_hash, NULL );
g_hash_table_destroy( file_list_hash );
}
else if ( files_to_open && app_desktop )
{
open_files_with_app( cwd, files_to_open,
app_desktop, file_browser );
g_list_foreach( files_to_open, ( GFunc ) g_free, NULL );
g_list_free( files_to_open );
}
if ( new_dir )
{
/*
ptk_file_browser_chdir( file_browser, new_dir, PTK_FB_CHDIR_ADD_HISTORY );
*/
if ( G_LIKELY( file_browser ) )
{
ptk_file_browser_emit_open( file_browser,
full_path, PTK_OPEN_DIR );
}
g_free( new_dir );
}
}
void ptk_file_misc_paste_as( DesktopWindow* desktop, PtkFileBrowser* file_browser,
const char* cwd )
{
gchar* file_path;
char* str;
gboolean is_cut = FALSE;
gint missing_targets;
VFSFileInfo* file;
char* file_dir;
GList* files = ptk_clipboard_get_file_paths( cwd, &is_cut, &missing_targets );
GList* l;
for ( l = files; l; l = l->next )
{
file_path = (char*)l->data;
file = vfs_file_info_new();
vfs_file_info_get( file, file_path, NULL );
file_dir = g_path_get_dirname( file_path );
if ( !ptk_rename_file( desktop, file_browser, file_dir, file, cwd, !is_cut,
0, NULL ) )
{
vfs_file_info_unref( file );
g_free( file_dir );
missing_targets = 0;
break;
}
vfs_file_info_unref( file );
g_free( file_dir );
}
g_list_foreach( files, ( GFunc ) g_free, NULL );
g_list_free( files );
if ( missing_targets > 0 )
{
GtkWidget* parent = NULL;
if ( file_browser )
parent = gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) );
else if ( desktop )
parent = gtk_widget_get_toplevel( GTK_WIDGET( desktop ) );
ptk_show_error( GTK_WINDOW( parent ),
g_strdup_printf ( _("Error") ),
g_strdup_printf ( "%i target%s missing",
missing_targets,
missing_targets > 1 ? g_strdup_printf ( "s are" ) :
g_strdup_printf ( " is" ) ) );
}
}
void ptk_file_misc_rootcmd( DesktopWindow* desktop, PtkFileBrowser* file_browser,
GList* sel_files,
char* cwd, char* setname )
{
/*
* root_copy_loc copy to location
* root_move2 move to
* root_delete delete
*/
if ( !setname || ( !file_browser && !desktop ) || !sel_files )
return;
XSet* set;
char* path;
char* cmd;
char* task_name;
GtkWidget* parent = desktop ? GTK_WIDGET( desktop ) : GTK_WIDGET( file_browser );
char* file_paths = g_strdup( "" );
GList* sel;
char* file_path;
char* file_path_q;
char* str;
int item_count = 0;
for ( sel = sel_files; sel; sel = sel->next )
{
file_path = g_build_filename( cwd,
vfs_file_info_get_name( ( VFSFileInfo* ) sel->data ), NULL );
file_path_q = bash_quote( file_path );
str = file_paths;
file_paths = g_strdup_printf( "%s %s", file_paths, file_path_q );
g_free( str );
g_free( file_path );
g_free( file_path_q );
item_count++;
}
if ( !strcmp( setname, "root_delete" ) )
{
if ( !app_settings.no_confirm )
{
str = g_strdup_printf( ngettext( "Delete %d selected item as root ?",
"Delete %d selected items as root ?",
item_count ), item_count );
if ( xset_msg_dialog( GTK_WIDGET( parent ), GTK_MESSAGE_WARNING,
_("Confirm Delete As Root"), NULL, GTK_BUTTONS_YES_NO,
_("DELETE AS ROOT"), str, NULL ) != GTK_RESPONSE_YES )
{
g_free( str );
return;
}
g_free( str );
}
cmd = g_strdup_printf( "rm -r %s", file_paths );
task_name = g_strdup( _("Delete As Root") );
}
else
{
char* folder;
set = xset_get( setname );
if ( set->desc )
folder = set->desc;
else
folder = cwd;
path = xset_file_dialog( GTK_WIDGET( parent ), GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER,
_("Choose Location"), folder, NULL );
if ( path && g_file_test( path, G_FILE_TEST_IS_DIR ) )
{
xset_set_set( set, "desc", path );
char* quote_path = bash_quote( path );
if ( !strcmp( setname, "root_move2" ) )
{
task_name = g_strdup( _("Move As Root") );
// problem: no warning if already exists
cmd = g_strdup_printf( "mv -f %s %s", file_paths, quote_path );
}
else
{
task_name = g_strdup( _("Copy As Root") );
// problem: no warning if already exists
cmd = g_strdup_printf( "cp -r %s %s", file_paths, quote_path );
}
g_free( quote_path );
g_free( path );
}
else
return;
}
g_free( file_paths );
// root task
PtkFileTask* task = ptk_file_exec_new( task_name, cwd, GTK_WIDGET( parent ),
file_browser ? file_browser->task_view : NULL );
g_free( task_name );
task->task->exec_command = cmd;
task->task->exec_sync = TRUE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE;
task->task->exec_export = FALSE;
task->task->exec_as_user = g_strdup( "root" );
ptk_file_task_run( task );
}
|
176 | ./spacefm/src/ptk/ptk-text-renderer.c | /* ptk-text-renderer.c
* Copyright (C) 2000 Red Hat, Inc., Jonathan Blandford <jrb@redhat.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/*
This file is originally copied from gtkcellrenderertext.c of gtk+ library.
2006.07.16 modified by Hong Jen Yee to produce a simplified text renderer
which supports center alignment of text to be used in PCMan File Manager.
*/
#include <stdlib.h>
#include <gtk/gtk.h>
#include <glib/gi18n.h>
#include "ptk-text-renderer.h"
static void ptk_text_renderer_init ( PtkTextRenderer *celltext );
static void ptk_text_renderer_class_init ( PtkTextRendererClass *class );
static void ptk_text_renderer_finalize ( GObject *object );
static void ptk_text_renderer_get_property ( GObject *object,
guint param_id,
GValue *value,
GParamSpec *pspec );
static void ptk_text_renderer_set_property ( GObject *object,
guint param_id,
const GValue *value,
GParamSpec *pspec );
static void ptk_text_renderer_get_size ( GtkCellRenderer *cell,
GtkWidget *widget,
#if GTK_CHECK_VERSION (3, 0, 0)
const GdkRectangle *cell_area,
#else
GdkRectangle *cell_area,
#endif
gint *x_offset,
gint *y_offset,
gint *width,
gint *height );
#if GTK_CHECK_VERSION (3, 0, 0)
static void ptk_text_renderer_render ( GtkCellRenderer *cell,
cairo_t *cr,
GtkWidget *widget,
const GdkRectangle *background_area,
const GdkRectangle *cell_area,
GtkCellRendererState flags );
#else
static void ptk_text_renderer_render ( GtkCellRenderer *cell,
GdkWindow *window,
GtkWidget *widget,
GdkRectangle *background_area,
GdkRectangle *cell_area,
GdkRectangle *expose_area,
GtkCellRendererState flags );
#endif
enum {
PROP_0,
PROP_TEXT,
PROP_WRAP_WIDTH,
/* Style args */
PROP_BACKGROUND,
PROP_FOREGROUND,
PROP_BACKGROUND_GDK,
PROP_FOREGROUND_GDK,
PROP_FONT,
PROP_FONT_DESC,
PROP_UNDERLINE,
PROP_ELLIPSIZE,
PROP_WRAP_MODE,
/* Whether-a-style-arg-is-set args */
PROP_BACKGROUND_SET,
PROP_FOREGROUND_SET,
PROP_UNDERLINE_SET,
PROP_ELLIPSIZE_SET
};
static gpointer parent_class;
#define PTK_TEXT_RENDERER_PATH "ptk-cell-renderer-text-path"
GType
ptk_text_renderer_get_type ( void )
{
static GType cell_text_type = 0;
if ( !cell_text_type )
{
static const GTypeInfo cell_text_info =
{
sizeof ( PtkTextRendererClass ),
NULL, /* base_init */
NULL, /* base_finalize */
( GClassInitFunc ) ptk_text_renderer_class_init,
NULL, /* class_finalize */
NULL, /* class_data */
sizeof ( PtkTextRenderer ),
0, /* n_preallocs */
( GInstanceInitFunc ) ptk_text_renderer_init,
};
cell_text_type =
g_type_register_static ( GTK_TYPE_CELL_RENDERER, "PtkTextRenderer",
&cell_text_info, 0 );
}
return cell_text_type;
}
static void
ptk_text_renderer_init ( PtkTextRenderer *celltext )
{
gtk_cell_renderer_set_alignment ( GTK_CELL_RENDERER ( celltext ), 0.0, 0.5 );
gtk_cell_renderer_set_padding ( GTK_CELL_RENDERER ( celltext ), 2, 2 );
celltext->font = pango_font_description_new ();
celltext->wrap_width = -1;
}
static void
ptk_text_renderer_class_init ( PtkTextRendererClass *class )
{
GObjectClass *object_class = G_OBJECT_CLASS ( class );
GtkCellRendererClass *cell_class = GTK_CELL_RENDERER_CLASS ( class );
parent_class = g_type_class_peek_parent ( class );
object_class->finalize = ptk_text_renderer_finalize;
object_class->get_property = ptk_text_renderer_get_property;
object_class->set_property = ptk_text_renderer_set_property;
cell_class->get_size = ptk_text_renderer_get_size;
cell_class->render = ptk_text_renderer_render;
g_object_class_install_property ( object_class,
PROP_TEXT,
g_param_spec_string ( "text",
_( "Text" ),
_( "Text to render" ),
NULL,
G_PARAM_READABLE | G_PARAM_WRITABLE ) );
g_object_class_install_property ( object_class,
PROP_BACKGROUND,
g_param_spec_string ( "background",
_( "Background color name" ),
_( "Background color as a string" ),
NULL,
G_PARAM_WRITABLE ) );
g_object_class_install_property ( object_class,
PROP_BACKGROUND_GDK,
g_param_spec_boxed ( "background-gdk",
_( "Background color" ),
_( "Background color as a GdkColor" ),
GDK_TYPE_COLOR,
G_PARAM_READABLE | G_PARAM_WRITABLE ) );
g_object_class_install_property ( object_class,
PROP_FOREGROUND,
g_param_spec_string ( "foreground",
_( "Foreground color name" ),
_( "Foreground color as a string" ),
NULL,
G_PARAM_WRITABLE ) );
g_object_class_install_property ( object_class,
PROP_FOREGROUND_GDK,
g_param_spec_boxed ( "foreground-gdk",
_( "Foreground color" ),
_( "Foreground color as a GdkColor" ),
GDK_TYPE_COLOR,
G_PARAM_READABLE | G_PARAM_WRITABLE ) );
g_object_class_install_property ( object_class,
PROP_FONT,
g_param_spec_string ( "font",
_( "Font" ),
_( "Font description as a string" ),
NULL,
G_PARAM_READABLE | G_PARAM_WRITABLE ) );
g_object_class_install_property ( object_class,
PROP_FONT_DESC,
g_param_spec_boxed ( "font-desc",
_( "Font" ),
_( "Font description as a PangoFontDescription struct" ),
PANGO_TYPE_FONT_DESCRIPTION,
G_PARAM_READABLE | G_PARAM_WRITABLE ) );
g_object_class_install_property ( object_class,
PROP_UNDERLINE,
g_param_spec_enum ( "underline",
_( "Underline" ),
_( "Style of underline for this text" ),
PANGO_TYPE_UNDERLINE,
PANGO_UNDERLINE_NONE,
G_PARAM_READABLE | G_PARAM_WRITABLE ) );
/**
* PtkTextRenderer:ellipsize:
*
* Specifies the preferred place to ellipsize the string, if the cell renderer
* does not have enough room to display the entire string. Setting it to
* %PANGO_ELLIPSIZE_NONE turns off ellipsizing. See the wrap-width property
* for another way of making the text fit into a given width.
*
* Since: 2.6
*/
g_object_class_install_property ( object_class,
PROP_ELLIPSIZE,
g_param_spec_enum ( "ellipsize",
_( "Ellipsize" ),
_( "The preferred place to ellipsize the string, "
"if the cell renderer does not have enough room "
"to display the entire string, if at all" ),
PANGO_TYPE_ELLIPSIZE_MODE,
PANGO_ELLIPSIZE_NONE,
G_PARAM_READABLE | G_PARAM_WRITABLE ) );
/**
* PtkTextRenderer:wrap-mode:
*
* Specifies how to break the string into multiple lines, if the cell
* renderer does not have enough room to display the entire string.
* This property has no effect unless the wrap-width property is set.
*
* Since: 2.8
*/
g_object_class_install_property ( object_class,
PROP_WRAP_MODE,
g_param_spec_enum ( "wrap-mode",
_( "Wrap mode" ),
_( "How to break the string into multiple lines, "
"if the cell renderer does not have enough room "
"to display the entire string" ),
PANGO_TYPE_WRAP_MODE,
PANGO_WRAP_CHAR,
G_PARAM_READABLE | G_PARAM_WRITABLE ) );
/**
* PtkTextRenderer:wrap-width:
*
* Specifies the width at which the text is wrapped. The wrap-mode property can
* be used to influence at what character positions the line breaks can be placed.
* Setting wrap-width to -1 turns wrapping off.
*
* Since: 2.8
*/
g_object_class_install_property ( object_class,
PROP_WRAP_WIDTH,
g_param_spec_int ( "wrap-width",
_( "Wrap width" ),
_( "The width at which the text is wrapped" ),
-1,
G_MAXINT,
-1,
G_PARAM_READABLE | G_PARAM_WRITABLE ) );
/* Style props are set or not */
#define ADD_SET_PROP(propname, propval, nick, blurb) g_object_class_install_property (object_class, propval, g_param_spec_boolean (propname, nick, blurb, FALSE, G_PARAM_READABLE|G_PARAM_WRITABLE))
ADD_SET_PROP ( "background-set", PROP_BACKGROUND_SET,
_( "Background set" ),
_( "Whether this tag affects the background color" ) );
ADD_SET_PROP ( "foreground-set", PROP_FOREGROUND_SET,
_( "Foreground set" ),
_( "Whether this tag affects the foreground color" ) );
ADD_SET_PROP ( "underline-set", PROP_UNDERLINE_SET,
_( "Underline set" ),
_( "Whether this tag affects underlining" ) );
ADD_SET_PROP ( "ellipsize-set", PROP_ELLIPSIZE_SET,
_( "Ellipsize set" ),
_( "Whether this tag affects the ellipsize mode" ) );
}
static void
ptk_text_renderer_finalize ( GObject *object )
{
PtkTextRenderer * celltext = PTK_TEXT_RENDERER ( object );
pango_font_description_free ( celltext->font );
g_free ( celltext->text );
( * G_OBJECT_CLASS ( parent_class ) ->finalize ) ( object );
}
static void
ptk_text_renderer_get_property ( GObject *object,
guint param_id,
GValue *value,
GParamSpec *pspec )
{
PtkTextRenderer * celltext = PTK_TEXT_RENDERER ( object );
switch ( param_id )
{
case PROP_TEXT:
g_value_set_string ( value, celltext->text );
break;
case PROP_BACKGROUND_GDK:
{
GdkColor color;
color.red = celltext->background.red;
color.green = celltext->background.green;
color.blue = celltext->background.blue;
g_value_set_boxed ( value, &color );
}
break;
case PROP_FOREGROUND_GDK:
{
GdkColor color;
color.red = celltext->foreground.red;
color.green = celltext->foreground.green;
color.blue = celltext->foreground.blue;
g_value_set_boxed ( value, &color );
}
break;
case PROP_FONT:
{
/* FIXME GValue imposes a totally gratuitous string copy
* here, we could just hand off string ownership
*/
gchar *str = pango_font_description_to_string ( celltext->font );
g_value_set_string ( value, str );
g_free ( str );
}
break;
case PROP_FONT_DESC:
g_value_set_boxed ( value, celltext->font );
break;
case PROP_UNDERLINE:
g_value_set_enum ( value, celltext->underline_style );
break;
case PROP_ELLIPSIZE:
g_value_set_enum ( value, celltext->ellipsize );
break;
case PROP_WRAP_MODE:
g_value_set_enum ( value, celltext->wrap_mode );
break;
case PROP_WRAP_WIDTH:
g_value_set_int ( value, celltext->wrap_width );
break;
case PROP_BACKGROUND_SET:
g_value_set_boolean ( value, celltext->background_set );
break;
case PROP_FOREGROUND_SET:
g_value_set_boolean ( value, celltext->foreground_set );
break;
case PROP_UNDERLINE_SET:
g_value_set_boolean ( value, celltext->underline_set );
break;
case PROP_ELLIPSIZE_SET:
g_value_set_boolean ( value, celltext->ellipsize_set );
break;
case PROP_BACKGROUND:
case PROP_FOREGROUND:
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID ( object, param_id, pspec );
break;
}
}
static void
set_bg_color ( PtkTextRenderer *celltext,
GdkColor *color )
{
if ( color )
{
if ( !celltext->background_set )
{
celltext->background_set = TRUE;
g_object_notify ( G_OBJECT ( celltext ), "background-set" );
}
celltext->background.red = color->red;
celltext->background.green = color->green;
celltext->background.blue = color->blue;
}
else
{
if ( celltext->background_set )
{
celltext->background_set = FALSE;
g_object_notify ( G_OBJECT ( celltext ), "background-set" );
}
}
}
static void
set_fg_color ( PtkTextRenderer *celltext,
GdkColor *color )
{
if ( color )
{
if ( !celltext->foreground_set )
{
celltext->foreground_set = TRUE;
g_object_notify ( G_OBJECT ( celltext ), "foreground-set" );
}
celltext->foreground.red = color->red;
celltext->foreground.green = color->green;
celltext->foreground.blue = color->blue;
}
else
{
if ( celltext->foreground_set )
{
celltext->foreground_set = FALSE;
g_object_notify ( G_OBJECT ( celltext ), "foreground-set" );
}
}
}
#if 0
static PangoFontMask
set_font_desc_fields ( PangoFontDescription *desc,
PangoFontMask to_set )
{
PangoFontMask changed_mask = 0;
if ( to_set & PANGO_FONT_MASK_FAMILY )
{
const char * family = pango_font_description_get_family ( desc );
if ( !family )
{
family = "sans";
changed_mask |= PANGO_FONT_MASK_FAMILY;
}
pango_font_description_set_family ( desc, family );
}
if ( to_set & PANGO_FONT_MASK_STYLE )
pango_font_description_set_style ( desc, pango_font_description_get_style ( desc ) );
if ( to_set & PANGO_FONT_MASK_VARIANT )
pango_font_description_set_variant ( desc, pango_font_description_get_variant ( desc ) );
if ( to_set & PANGO_FONT_MASK_WEIGHT )
pango_font_description_set_weight ( desc, pango_font_description_get_weight ( desc ) );
if ( to_set & PANGO_FONT_MASK_STRETCH )
pango_font_description_set_stretch ( desc, pango_font_description_get_stretch ( desc ) );
if ( to_set & PANGO_FONT_MASK_SIZE )
{
gint size = pango_font_description_get_size ( desc );
if ( size <= 0 )
{
size = 10 * PANGO_SCALE;
changed_mask |= PANGO_FONT_MASK_SIZE;
}
pango_font_description_set_size ( desc, size );
}
return changed_mask;
}
#endif
static void
notify_set_changed ( GObject *object,
PangoFontMask changed_mask )
{
if ( changed_mask & PANGO_FONT_MASK_FAMILY )
g_object_notify ( object, "family-set" );
if ( changed_mask & PANGO_FONT_MASK_STYLE )
g_object_notify ( object, "style-set" );
if ( changed_mask & PANGO_FONT_MASK_VARIANT )
g_object_notify ( object, "variant-set" );
if ( changed_mask & PANGO_FONT_MASK_WEIGHT )
g_object_notify ( object, "weight-set" );
if ( changed_mask & PANGO_FONT_MASK_STRETCH )
g_object_notify ( object, "stretch-set" );
if ( changed_mask & PANGO_FONT_MASK_SIZE )
g_object_notify ( object, "size-set" );
}
#if 0
static void
notify_fields_changed ( GObject *object,
PangoFontMask changed_mask )
{
if ( changed_mask & PANGO_FONT_MASK_FAMILY )
g_object_notify ( object, "family" );
if ( changed_mask & PANGO_FONT_MASK_STYLE )
g_object_notify ( object, "style" );
if ( changed_mask & PANGO_FONT_MASK_VARIANT )
g_object_notify ( object, "variant" );
if ( changed_mask & PANGO_FONT_MASK_WEIGHT )
g_object_notify ( object, "weight" );
if ( changed_mask & PANGO_FONT_MASK_STRETCH )
g_object_notify ( object, "stretch" );
if ( changed_mask & PANGO_FONT_MASK_SIZE )
g_object_notify ( object, "size" );
}
#endif
static void
set_font_description ( PtkTextRenderer *celltext,
PangoFontDescription *font_desc )
{
GObject * object = G_OBJECT ( celltext );
PangoFontDescription *new_font_desc;
PangoFontMask old_mask, new_mask, changed_mask, set_changed_mask;
if ( font_desc )
new_font_desc = pango_font_description_copy ( font_desc );
else
new_font_desc = pango_font_description_new ();
old_mask = pango_font_description_get_set_fields ( celltext->font );
new_mask = pango_font_description_get_set_fields ( new_font_desc );
changed_mask = old_mask | new_mask;
set_changed_mask = old_mask ^ new_mask;
pango_font_description_free ( celltext->font );
celltext->font = new_font_desc;
g_object_freeze_notify ( object );
g_object_notify ( object, "font-desc" );
g_object_notify ( object, "font" );
if ( changed_mask & PANGO_FONT_MASK_FAMILY )
g_object_notify ( object, "family" );
if ( changed_mask & PANGO_FONT_MASK_STYLE )
g_object_notify ( object, "style" );
if ( changed_mask & PANGO_FONT_MASK_VARIANT )
g_object_notify ( object, "variant" );
if ( changed_mask & PANGO_FONT_MASK_WEIGHT )
g_object_notify ( object, "weight" );
if ( changed_mask & PANGO_FONT_MASK_STRETCH )
g_object_notify ( object, "stretch" );
if ( changed_mask & PANGO_FONT_MASK_SIZE )
{
g_object_notify ( object, "size" );
g_object_notify ( object, "size-points" );
}
notify_set_changed ( object, set_changed_mask );
g_object_thaw_notify ( object );
}
static void
ptk_text_renderer_set_property ( GObject *object,
guint param_id,
const GValue *value,
GParamSpec *pspec )
{
PtkTextRenderer * celltext = PTK_TEXT_RENDERER ( object );
switch ( param_id )
{
case PROP_TEXT:
g_free ( celltext->text );
celltext->text = g_strdup ( g_value_get_string ( value ) );
g_object_notify ( object, "text" );
break;
case PROP_BACKGROUND:
{
GdkColor color;
if ( !g_value_get_string ( value ) )
set_bg_color ( celltext, NULL ); /* reset to backgrounmd_set to FALSE */
else if ( gdk_color_parse ( g_value_get_string ( value ), &color ) )
set_bg_color ( celltext, &color );
else
g_warning ( "Don't know color `%s'", g_value_get_string ( value ) );
g_object_notify ( object, "background-gdk" );
}
break;
case PROP_FOREGROUND:
{
GdkColor color;
if ( !g_value_get_string ( value ) )
set_fg_color ( celltext, NULL ); /* reset to foreground_set to FALSE */
else if ( gdk_color_parse ( g_value_get_string ( value ), &color ) )
set_fg_color ( celltext, &color );
else
g_warning ( "Don't know color `%s'", g_value_get_string ( value ) );
g_object_notify ( object, "foreground-gdk" );
}
break;
case PROP_BACKGROUND_GDK:
/* This notifies the GObject itself. */
set_bg_color ( celltext, g_value_get_boxed ( value ) );
break;
case PROP_FOREGROUND_GDK:
/* This notifies the GObject itself. */
set_fg_color ( celltext, g_value_get_boxed ( value ) );
break;
case PROP_FONT:
{
PangoFontDescription *font_desc = NULL;
const gchar *name;
name = g_value_get_string ( value );
if ( name )
font_desc = pango_font_description_from_string ( name );
set_font_description ( celltext, font_desc );
pango_font_description_free ( font_desc );
}
break;
case PROP_FONT_DESC:
set_font_description ( celltext, g_value_get_boxed ( value ) );
break;
case PROP_UNDERLINE:
celltext->underline_style = g_value_get_enum ( value );
celltext->underline_set = TRUE;
g_object_notify ( object, "underline-set" );
break;
case PROP_ELLIPSIZE:
celltext->ellipsize = g_value_get_enum ( value );
celltext->ellipsize_set = TRUE;
g_object_notify ( object, "ellipsize-set" );
break;
case PROP_WRAP_MODE:
celltext->wrap_mode = g_value_get_enum ( value );
break;
case PROP_WRAP_WIDTH:
celltext->wrap_width = g_value_get_int ( value );
break;
case PROP_BACKGROUND_SET:
celltext->background_set = g_value_get_boolean ( value );
break;
case PROP_FOREGROUND_SET:
celltext->foreground_set = g_value_get_boolean ( value );
break;
case PROP_UNDERLINE_SET:
celltext->underline_set = g_value_get_boolean ( value );
break;
case PROP_ELLIPSIZE_SET:
celltext->ellipsize_set = g_value_get_boolean ( value );
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID ( object, param_id, pspec );
break;
}
}
/**
* ptk_text_renderer_new:
*
* Creates a new #PtkTextRenderer. Adjust how text is drawn using
* object properties. Object properties can be
* set globally (with g_object_set()). Also, with #GtkTreeViewColumn,
* you can bind a property to a value in a #GtkTreeModel. For example,
* you can bind the "text" property on the cell renderer to a string
* value in the model, thus rendering a different string in each row
* of the #GtkTreeView
*
* Return value: the new cell renderer
**/
GtkCellRenderer *
ptk_text_renderer_new ( void )
{
return g_object_new ( PTK_TYPE_TEXT_RENDERER, NULL );
}
static void
add_attr ( PangoAttrList *attr_list,
PangoAttribute *attr )
{
attr->start_index = 0;
attr->end_index = G_MAXINT;
pango_attr_list_insert ( attr_list, attr );
}
static PangoLayout*
get_layout ( PtkTextRenderer *celltext,
GtkWidget *widget,
gboolean will_render,
GtkCellRendererState flags )
{
PangoAttrList * attr_list;
PangoLayout *layout;
PangoUnderline uline;
layout = gtk_widget_create_pango_layout ( widget, celltext->text );
pango_layout_set_alignment( layout, PANGO_ALIGN_CENTER );
attr_list = pango_attr_list_new ();
if ( will_render )
{
/* Add options that affect appearance but not size */
/* note that background doesn't go here, since it affects
* background_area not the PangoLayout area
*/
if ( celltext->foreground_set
&& ( flags & GTK_CELL_RENDERER_SELECTED ) == 0 )
{
PangoColor color;
color = celltext->foreground;
add_attr ( attr_list,
pango_attr_foreground_new ( color.red, color.green, color.blue ) );
}
}
add_attr ( attr_list, pango_attr_font_desc_new ( celltext->font ) );
if ( celltext->underline_set )
uline = celltext->underline_style;
else
uline = PANGO_UNDERLINE_NONE;
if ( ( flags & GTK_CELL_RENDERER_PRELIT ) == GTK_CELL_RENDERER_PRELIT )
{
switch ( uline )
{
case PANGO_UNDERLINE_NONE:
uline = PANGO_UNDERLINE_SINGLE;
break;
case PANGO_UNDERLINE_SINGLE:
uline = PANGO_UNDERLINE_DOUBLE;
break;
default:
break;
}
}
if ( uline != PANGO_UNDERLINE_NONE )
add_attr ( attr_list, pango_attr_underline_new ( celltext->underline_style ) );
if ( celltext->ellipsize_set )
pango_layout_set_ellipsize ( layout, celltext->ellipsize );
else
pango_layout_set_ellipsize ( layout, PANGO_ELLIPSIZE_NONE );
if ( celltext->wrap_width != -1 )
{
pango_layout_set_width ( layout, celltext->wrap_width * PANGO_SCALE );
pango_layout_set_wrap ( layout, celltext->wrap_mode );
if ( pango_layout_get_line_count ( layout ) == 1 )
{
pango_layout_set_width ( layout, -1 );
pango_layout_set_wrap ( layout, PANGO_WRAP_CHAR );
}
}
else
{
pango_layout_set_width ( layout, -1 );
pango_layout_set_wrap ( layout, PANGO_WRAP_CHAR );
}
pango_layout_set_attributes ( layout, attr_list );
pango_attr_list_unref ( attr_list );
return layout;
}
static void
get_size ( GtkCellRenderer *cell,
GtkWidget *widget,
#if GTK_CHECK_VERSION (3, 0, 0)
const GdkRectangle *cell_area,
#else
GdkRectangle *cell_area,
#endif
PangoLayout *layout,
gint *x_offset,
gint *y_offset,
gint *width,
gint *height )
{
PtkTextRenderer * celltext = ( PtkTextRenderer * ) cell;
PangoRectangle rect;
gint xpad, ypad;
gfloat xalign, yalign;
gtk_cell_renderer_get_padding ( cell, &xpad, &ypad );
gtk_cell_renderer_get_alignment ( cell, &xalign, &yalign );
if ( layout )
{
g_object_ref ( layout );
pango_layout_set_alignment( layout, PANGO_ALIGN_CENTER );
}
else
layout = get_layout ( celltext, widget, FALSE, 0 );
pango_layout_get_pixel_extents ( layout, NULL, &rect );
if ( height )
* height = ypad * 2 + rect.height;
/* The minimum size for ellipsized labels is ~ 3 chars */
if ( width )
{
if ( celltext->ellipsize )
{
PangoContext * context;
PangoFontMetrics *metrics;
gint char_width;
context = pango_layout_get_context ( layout );
metrics = pango_context_get_metrics ( context, gtk_widget_get_style ( widget ) ->font_desc, pango_context_get_language ( context ) );
char_width = pango_font_metrics_get_approximate_char_width ( metrics );
pango_font_metrics_unref ( metrics );
*width = xpad * 2 + ( PANGO_PIXELS ( char_width ) * 3 );
}
else
{
*width = xpad * 2 + rect.x + rect.width;
}
}
if ( cell_area )
{
if ( x_offset )
{
if ( gtk_widget_get_direction ( widget ) == GTK_TEXT_DIR_RTL )
* x_offset = ( 1.0 - xalign ) * ( cell_area->width - ( rect.x + rect.width + ( 2 * xpad ) ) );
else
*x_offset = xalign * ( cell_area->width - ( rect.x + rect.width + ( 2 * xpad ) ) );
if ( celltext->ellipsize_set || celltext->wrap_width != -1 )
* x_offset = MAX( *x_offset, 0 );
}
if ( y_offset )
{
*y_offset = yalign * ( cell_area->height - ( rect.height + ( 2 * ypad ) ) );
*y_offset = MAX ( *y_offset, 0 );
}
}
g_object_unref ( layout );
}
static void
ptk_text_renderer_get_size ( GtkCellRenderer *cell,
GtkWidget *widget,
#if GTK_CHECK_VERSION (3, 0, 0)
const GdkRectangle *cell_area,
#else
GdkRectangle *cell_area,
#endif
gint *x_offset,
gint *y_offset,
gint *width,
gint *height )
{
get_size ( cell, widget, cell_area, NULL,
x_offset, y_offset, width, height );
}
#if GTK_CHECK_VERSION (3, 0, 0)
static void
ptk_text_renderer_render ( GtkCellRenderer *cell,
cairo_t *cr,
GtkWidget *widget,
const GdkRectangle *background_area,
const GdkRectangle *cell_area,
GtkCellRendererState flags )
#else
static void
ptk_text_renderer_render ( GtkCellRenderer *cell,
GdkDrawable *window,
GtkWidget *widget,
GdkRectangle *background_area,
GdkRectangle *cell_area,
GdkRectangle *expose_area,
GtkCellRendererState flags )
#endif
{
PtkTextRenderer * celltext = ( PtkTextRenderer * ) cell;
PangoLayout *layout;
GtkStateType state;
gint x_offset;
gint y_offset;
gint width, height;
gint focus_pad, focus_width;
gint x, y;
gint xpad, ypad;
#if GTK_CHECK_VERSION (3, 0, 0)
cairo_save ( cr );
#else
cairo_t *cr;
cr = gdk_cairo_create ( window );
#endif
gtk_cell_renderer_get_padding ( cell, &xpad, &ypad );
/* get focus width and padding */
gtk_widget_style_get ( widget,
"focus-line-width", &focus_width,
"focus-padding", &focus_pad,
NULL );
/* get text extent */
layout = get_layout ( celltext, widget, TRUE, flags );
get_size ( cell, widget, cell_area, layout, &x_offset, &y_offset, &width, &height );
if ( !gtk_cell_renderer_get_sensitive ( cell ) )
{
state = GTK_STATE_INSENSITIVE;
}
else if ( ( flags & GTK_CELL_RENDERER_SELECTED ) == GTK_CELL_RENDERER_SELECTED )
{
if ( gtk_widget_has_focus ( widget ) )
state = GTK_STATE_SELECTED;
else
#if GTK_CHECK_VERSION (3, 0, 0)
state = GTK_STATE_SELECTED;
#else
state = GTK_STATE_ACTIVE;
#endif
}
else if ( ( flags & GTK_CELL_RENDERER_PRELIT ) == GTK_CELL_RENDERER_PRELIT &&
gtk_widget_get_state ( widget ) == GTK_STATE_PRELIGHT )
{
state = GTK_STATE_PRELIGHT;
}
else
{
if ( gtk_widget_get_state ( widget ) == GTK_STATE_INSENSITIVE )
state = GTK_STATE_INSENSITIVE;
else
state = GTK_STATE_NORMAL;
}
if(flags & (GTK_CELL_RENDERER_FOCUSED|GTK_CELL_RENDERER_SELECTED))
{
/* draw background color for selected state if needed */
if( flags & GTK_CELL_RENDERER_SELECTED )
{
gdk_cairo_set_source_color ( cr, >k_widget_get_style ( widget )->base[ state ] );
cairo_rectangle ( cr, cell_area->x + x_offset, cell_area->y + y_offset, width, height );
cairo_fill ( cr );
}
/* draw the focus */
if(flags & GTK_CELL_RENDERER_FOCUSED)
{
gtk_paint_focus( gtk_widget_get_style ( widget ),
#if GTK_CHECK_VERSION (3, 0, 0)
cr,
gtk_widget_get_state (widget),
widget, "icon_view",
#else
window,
gtk_widget_get_state (widget),
NULL, widget, "icon_view",
#endif
cell_area->x + x_offset - focus_width,
cell_area->y + y_offset - focus_width,
width + focus_width * 2, height + focus_width * 2);
flags &= ~GTK_CELL_RENDERER_FOCUSED;
}
}
if ( celltext->ellipsize_set )
pango_layout_set_width ( layout,
( cell_area->width - x_offset - 2 * xpad ) * PANGO_SCALE );
else if ( celltext->wrap_width == -1 )
pango_layout_set_width ( layout, -1 );
if ( pango_layout_is_wrapped ( layout ) )
x_offset = -xpad / 2;
gtk_paint_layout ( gtk_widget_get_style ( widget ),
#if GTK_CHECK_VERSION (3, 0, 0)
cr,
state,
TRUE,
#else
window,
state,
TRUE,
expose_area,
#endif
widget,
"cellrenderertext",
cell_area->x + x_offset + xpad,
cell_area->y + y_offset + ypad,
layout );
g_object_unref ( layout );
#if GTK_CHECK_VERSION (3, 0, 0)
cairo_restore ( cr );
#else
cairo_destroy ( cr );
#endif
}
|
177 | ./spacefm/src/ptk/ptk-file-properties.c | /*
* C Implementation: file_properties
*
* Description:
*
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <libintl.h>
#include "private.h"
#include <gtk/gtk.h>
#include "glib-mem.h"
#include "ptk-file-properties.h"
#include "mime-type/mime-type.h"
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
#include <string.h>
#include "ptk-file-task.h"
#include "ptk-utils.h"
#include "vfs-file-info.h"
#include "vfs-app-desktop.h"
#include "ptk-app-chooser.h"
#include "main-window.h"
const char* chmod_names[] =
{
"owner_r", "owner_w", "owner_x",
"group_r", "group_w", "group_x",
"others_r", "others_w", "others_x",
"set_uid", "set_gid", "sticky"
};
typedef struct
{
char* dir_path;
GList* file_list;
GtkWidget* dlg;
GtkEntry* owner;
GtkEntry* group;
char* owner_name;
char* group_name;
GtkEntry* mtime;
char* orig_mtime;
GtkEntry* atime;
char* orig_atime;
GtkToggleButton* chmod_btns[ N_CHMOD_ACTIONS ];
guchar chmod_states[ N_CHMOD_ACTIONS ];
GtkLabel* total_size_label;
GtkLabel* size_on_disk_label;
GtkLabel* count_label;
off64_t total_size;
off64_t size_on_disk;
guint total_count;
guint total_count_dir;
gboolean cancel;
gboolean done;
GThread* calc_size_thread;
guint update_label_timer;
GtkWidget* recurse;
}
FilePropertiesDialogData;
static void
on_dlg_response ( GtkDialog *dialog,
gint response_id,
gpointer user_data );
/*
* void get_total_size_of_dir( const char* path, off_t* size )
* Recursively count total size of all files in the specified directory.
* If the path specified is a file, the size of the file is directly returned.
* cancel is used to cancel the operation. This function will check the value
* pointed by cancel in every iteration. If cancel is set to TRUE, the
* calculation is cancelled.
* NOTE: path is encoded in on-disk encoding and not necessarily UTF-8.
*/
static void calc_total_size_of_files( const char* path, FilePropertiesDialogData* data )
{
GDir * dir;
const char* name;
char* full_path;
struct stat64 file_stat;
if ( data->cancel )
return ;
if ( lstat64( path, &file_stat ) )
return ;
data->total_size += file_stat.st_size;
data->size_on_disk += ( file_stat.st_blocks << 9 ); /* block x 512 */
dir = g_dir_open( path, 0, NULL );
if ( dir )
{
++data->total_count_dir;
while ( !data->cancel && ( name = g_dir_read_name( dir ) ) )
{
full_path = g_build_filename( path, name, NULL );
lstat64( full_path, &file_stat );
if ( S_ISDIR( file_stat.st_mode ) )
{
calc_total_size_of_files( full_path, data );
}
else
{
data->total_size += file_stat.st_size;
data->size_on_disk += ( file_stat.st_blocks << 9 );
++data->total_count;
}
g_free( full_path );
}
g_dir_close( dir );
}
else
++data->total_count;
}
static gpointer calc_size( gpointer user_data )
{
FilePropertiesDialogData * data = ( FilePropertiesDialogData* ) user_data;
GList* l;
char* path;
VFSFileInfo* file;
for ( l = data->file_list; l; l = l->next )
{
if ( data->cancel )
break;
file = ( VFSFileInfo* ) l->data;
path = g_build_filename( data->dir_path,
vfs_file_info_get_name( file ), NULL );
if ( path )
{
calc_total_size_of_files( path, data );
g_free( path );
}
}
data->done = TRUE;
return NULL;
}
gboolean on_update_labels( FilePropertiesDialogData* data )
{
char buf[ 64 ];
char buf2[ 32 ];
gdk_threads_enter();
vfs_file_size_to_string( buf2, data->total_size );
sprintf( buf, _("%s ( %lu bytes )"), buf2, ( guint64 ) data->total_size );
gtk_label_set_text( data->total_size_label, buf );
vfs_file_size_to_string( buf2, data->size_on_disk );
sprintf( buf, _("%s ( %lu bytes )"), buf2, ( guint64 ) data->size_on_disk );
gtk_label_set_text( data->size_on_disk_label, buf );
char* count;
char* count_dir;
if ( data->total_count_dir )
{
count_dir = g_strdup_printf( ngettext( "%d folder",
"%d folders",
data->total_count_dir ),
data->total_count_dir );
count = g_strdup_printf( ngettext( "%d file, %s",
"%d files, %s",
data->total_count ),
data->total_count, count_dir );
g_free( count_dir );
}
else
count = g_strdup_printf( ngettext( "%d files", "%d files",
data->total_count), data->total_count );
gtk_label_set_text( data->count_label, count );
g_free( count );
gdk_threads_leave();
return !data->done;
}
static void on_chmod_btn_toggled( GtkToggleButton* btn,
FilePropertiesDialogData* data )
{
/* Bypass the default handler */
g_signal_stop_emission_by_name( btn, "toggled" );
/* Block this handler while we are changing the state of buttons,
or this handler will be called recursively. */
g_signal_handlers_block_matched( btn, G_SIGNAL_MATCH_FUNC, 0,
0, NULL, on_chmod_btn_toggled, NULL );
if ( gtk_toggle_button_get_inconsistent( btn ) )
{
gtk_toggle_button_set_inconsistent( btn, FALSE );
gtk_toggle_button_set_active( btn, FALSE );
}
else if ( ! gtk_toggle_button_get_active( btn ) )
{
gtk_toggle_button_set_inconsistent( btn, TRUE );
}
g_signal_handlers_unblock_matched( btn, G_SIGNAL_MATCH_FUNC, 0,
0, NULL, on_chmod_btn_toggled, NULL );
}
static gboolean combo_sep( GtkTreeModel *model,
GtkTreeIter* it,
gpointer user_data )
{
int i;
for( i = 2; i > 0; --i )
{
char* tmp;
gtk_tree_model_get( model, it, i, &tmp, -1 );
if( tmp )
{
g_free( tmp );
return FALSE;
}
}
return TRUE;
}
static void on_combo_change( GtkComboBox* combo, gpointer user_data )
{
GtkTreeIter it;
if( gtk_combo_box_get_active_iter(combo, &it) )
{
const char* action;
GtkTreeModel* model = gtk_combo_box_get_model( combo );
gtk_tree_model_get( model, &it, 2, &action, -1 );
if( ! action )
{
char* action;
GtkWidget* parent;
VFSMimeType* mime = (VFSMimeType*)user_data;
parent = gtk_widget_get_toplevel( GTK_WIDGET( combo ) );
action = (char *) ptk_choose_app_for_mime_type( GTK_WINDOW(parent),
mime, FALSE );
if( action )
{
gboolean exist = FALSE;
/* check if the action is already in the list */
if( gtk_tree_model_get_iter_first( model, &it ) )
{
do
{
char* tmp;
gtk_tree_model_get( model, &it, 2, &tmp, -1 );
if( !tmp )
continue;
if( 0 == strcmp( tmp, action ) )
{
exist = TRUE;
g_free( tmp );
break;
}
g_free( tmp );
} while( gtk_tree_model_iter_next( model, &it ) );
}
if( ! exist ) /* It didn't exist */
{
VFSAppDesktop* app = vfs_app_desktop_new( action );
if( app )
{
GdkPixbuf* icon;
icon = vfs_app_desktop_get_icon( app, 20, TRUE );
gtk_list_store_insert_with_values(
GTK_LIST_STORE( model ), &it, 0,
0, icon,
1, vfs_app_desktop_get_disp_name(app),
2, action, -1 );
if( icon )
g_object_unref( icon );
vfs_app_desktop_unref( app );
exist = TRUE;
}
}
if( exist )
gtk_combo_box_set_active_iter( combo, &it );
g_free( action );
}
else
{
int prev_sel;
prev_sel = GPOINTER_TO_INT( g_object_get_data( G_OBJECT(combo), "prev_sel") );
gtk_combo_box_set_active( combo, prev_sel );
}
}
else
{
int prev_sel = gtk_combo_box_get_active( combo );
g_object_set_data( G_OBJECT(combo), "prev_sel", GINT_TO_POINTER(prev_sel) );
}
}
else
{
g_object_set_data( G_OBJECT(combo), "prev_sel", GINT_TO_POINTER(-1) );
}
}
GtkWidget* file_properties_dlg_new( GtkWindow* parent,
const char* dir_path,
GList* sel_files, int page )
{
GtkBuilder* builder = _gtk_builder_new_from_file( PACKAGE_UI_DIR "/file_properties.ui", NULL );
GtkWidget * dlg = (GtkWidget*)gtk_builder_get_object( builder, "dlg" );
GtkNotebook* notebook = (GtkNotebook*)gtk_builder_get_object( builder, "notebook" );
xset_set_window_icon( GTK_WINDOW( dlg ) );
FilePropertiesDialogData* data;
gboolean need_calc_size = TRUE;
VFSFileInfo *file, *file2;
VFSMimeType* mime;
const char* multiple_files = _( "( multiple files )" );
const char* calculating;
GtkWidget* name = (GtkWidget*)gtk_builder_get_object( builder, "file_name" );
GtkWidget* label_name = (GtkWidget*)gtk_builder_get_object( builder, "label_filename" );
GtkWidget* location = (GtkWidget*)gtk_builder_get_object( builder, "location" );
gtk_editable_set_editable ( GTK_EDITABLE( location ), FALSE );
GtkWidget* target = (GtkWidget*)gtk_builder_get_object( builder, "target" );
GtkWidget* label_target = (GtkWidget*)gtk_builder_get_object( builder, "label_target" );
gtk_editable_set_editable ( GTK_EDITABLE( target ), FALSE );
GtkWidget* mime_type = (GtkWidget*)gtk_builder_get_object( builder, "mime_type" );
GtkWidget* open_with = (GtkWidget*)gtk_builder_get_object( builder, "open_with" );
char buf[ 64 ];
char buf2[ 32 ];
const char* time_format = "%Y-%m-%d %H:%M:%S";
gchar* disp_path;
gchar* file_type;
int i;
GList* l;
gboolean same_type = TRUE;
gboolean is_dirs = FALSE;
char *owner_group, *tmp;
gtk_dialog_set_alternative_button_order( GTK_DIALOG(dlg), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1 );
ptk_dialog_fit_small_screen( GTK_DIALOG(dlg) );
int width = xset_get_int( "app_dlg", "s" );
int height = xset_get_int( "app_dlg", "z" );
if ( width && height )
gtk_window_set_default_size( GTK_WINDOW( dlg ), width, -1 );
data = g_slice_new0( FilePropertiesDialogData );
/* FIXME: When will the data be freed??? */
g_object_set_data( G_OBJECT( dlg ), "DialogData", data );
data->file_list = sel_files;
data->dlg = dlg;
data->dir_path = g_strdup( dir_path );
disp_path = g_filename_display_name( dir_path );
//gtk_label_set_text( GTK_LABEL( location ), disp_path );
gtk_entry_set_text( GTK_ENTRY( location ), disp_path );
g_free( disp_path );
data->total_size_label = GTK_LABEL( (GtkWidget*)gtk_builder_get_object( builder, "total_size" ) );
data->size_on_disk_label = GTK_LABEL( (GtkWidget*)gtk_builder_get_object( builder, "size_on_disk" ) );
data->count_label = GTK_LABEL( (GtkWidget*)gtk_builder_get_object( builder, "count" ) );
data->owner = GTK_ENTRY( (GtkWidget*)gtk_builder_get_object( builder, "owner" ) );
data->group = GTK_ENTRY( (GtkWidget*)gtk_builder_get_object( builder, "group" ) );
data->mtime = GTK_ENTRY( (GtkWidget*)gtk_builder_get_object( builder, "mtime" ) );
data->atime = GTK_ENTRY( (GtkWidget*)gtk_builder_get_object( builder, "atime" ) );
for ( i = 0; i < N_CHMOD_ACTIONS; ++i )
{
data->chmod_btns[ i ] = GTK_TOGGLE_BUTTON( (GtkWidget*)gtk_builder_get_object( builder, chmod_names[ i ] ) );
}
//MOD
VFSMimeType* type;
VFSMimeType* type2 = NULL;
for ( l = sel_files; l ; l = l->next )
{
file = ( VFSFileInfo* ) l->data;
type = vfs_file_info_get_mime_type( file );
if ( !type2 )
type2 = vfs_file_info_get_mime_type( file );
if ( vfs_file_info_is_dir( file ) )
is_dirs = TRUE;
if ( type != type2 )
same_type = FALSE;
vfs_mime_type_unref( type );
if ( is_dirs && !same_type )
break;
}
if ( type2 )
vfs_mime_type_unref( type2 );
data->recurse = (GtkWidget*)gtk_builder_get_object( builder, "recursive" );
gtk_widget_set_sensitive( data->recurse, is_dirs );
/* //MOD
for ( l = sel_files; l && l->next; l = l->next )
{
VFSMimeType *type, *type2;
file = ( VFSFileInfo* ) l->data;
file2 = ( VFSFileInfo* ) l->next->data;
type = vfs_file_info_get_mime_type( file );
type2 = vfs_file_info_get_mime_type( file2 );
if ( type != type2 )
{
vfs_mime_type_unref( type );
vfs_mime_type_unref( type2 );
same_type = FALSE;
break;
}
vfs_mime_type_unref( type );
vfs_mime_type_unref( type2 );
}
*/
file = ( VFSFileInfo* ) sel_files->data;
if ( same_type )
{
mime = vfs_file_info_get_mime_type( file );
file_type = g_strdup_printf( "%s\n%s",
vfs_mime_type_get_description( mime ),
vfs_mime_type_get_type( mime ) );
gtk_label_set_text( GTK_LABEL( mime_type ), file_type );
g_free( file_type );
vfs_mime_type_unref( mime );
}
else
{
gtk_label_set_text( GTK_LABEL( mime_type ), _( "( multiple types )" ) );
}
/* Open with...
* Don't show this option menu if files of different types are selected,
* ,the selected file is a folder, or its type is unknown.
*/
if( ! same_type ||
vfs_file_info_is_dir( file ) ||
vfs_file_info_is_desktop_entry( file ) ||
vfs_file_info_is_unknown_type( file ) ||
vfs_file_info_is_executable( file, NULL ) )
{
/* if open with shouldn't show, destroy it. */
gtk_widget_destroy( open_with );
open_with = NULL;
gtk_widget_destroy( (GtkWidget*)gtk_builder_get_object( builder, "open_with_label" ) );
}
else /* Add available actions to the option menu */
{
GtkTreeIter it;
char **action, **actions;
mime = vfs_file_info_get_mime_type( file );
actions = vfs_mime_type_get_actions( mime );
GtkCellRenderer* renderer;
GtkListStore* model;
gtk_cell_layout_clear( GTK_CELL_LAYOUT(open_with) );
renderer = gtk_cell_renderer_pixbuf_new();
gtk_cell_layout_pack_start( GTK_CELL_LAYOUT(open_with), renderer, FALSE);
gtk_cell_layout_set_attributes( GTK_CELL_LAYOUT(open_with), renderer,
"pixbuf", 0, NULL );
renderer = gtk_cell_renderer_text_new();
gtk_cell_layout_pack_start( GTK_CELL_LAYOUT(open_with), renderer, TRUE);
gtk_cell_layout_set_attributes( GTK_CELL_LAYOUT(open_with),renderer,
"text", 1, NULL );
model = gtk_list_store_new( 3, GDK_TYPE_PIXBUF,
G_TYPE_STRING,
G_TYPE_STRING,
G_TYPE_STRING );
if( actions )
{
for( action = actions; *action; ++action )
{
VFSAppDesktop* desktop;
GdkPixbuf* icon;
desktop = vfs_app_desktop_new( *action );
gtk_list_store_append( model, &it );
icon = vfs_app_desktop_get_icon(desktop, 20, TRUE);
gtk_list_store_set( model, &it,
0, icon,
1, vfs_app_desktop_get_disp_name(desktop),
2, *action, -1 );
if( icon )
g_object_unref( icon );
vfs_app_desktop_unref( desktop );
}
}
else
{
g_object_set_data( G_OBJECT(open_with), "prev_sel", GINT_TO_POINTER(-1) );
}
/* separator */
gtk_list_store_append( model, &it );
gtk_list_store_append( model, &it );
gtk_list_store_set( model, &it,
0, NULL,
1, _("Choose..."), -1 );
gtk_combo_box_set_model( GTK_COMBO_BOX(open_with),
GTK_TREE_MODEL(model) );
gtk_combo_box_set_row_separator_func(
GTK_COMBO_BOX(open_with), combo_sep,
NULL, NULL );
gtk_combo_box_set_active(GTK_COMBO_BOX(open_with), 0);
g_signal_connect( open_with, "changed",
G_CALLBACK(on_combo_change), mime );
/* vfs_mime_type_unref( mime ); */
/* We can unref mime when combo box gets destroyed */
g_object_weak_ref( G_OBJECT(open_with),
(GWeakNotify)vfs_mime_type_unref, mime );
}
g_object_set_data( G_OBJECT(dlg), "open_with", open_with );
/* Multiple files are selected */
if ( sel_files && sel_files->next )
{
gtk_widget_set_sensitive( name, FALSE );
gtk_entry_set_text( GTK_ENTRY( name ), multiple_files );
data->orig_mtime = NULL;
data->orig_atime = NULL;
for ( i = 0; i < N_CHMOD_ACTIONS; ++i )
{
gtk_toggle_button_set_inconsistent ( data->chmod_btns[ i ], TRUE );
data->chmod_states[ i ] = 2; /* Don't touch this bit */
g_signal_connect( G_OBJECT( data->chmod_btns[ i ] ), "toggled",
G_CALLBACK( on_chmod_btn_toggled ), data );
}
}
else
{
/* special processing for files with special display names */
if( vfs_file_info_is_desktop_entry( file ) )
{
char* disp_name = g_filename_display_name( file->name );
gtk_entry_set_text( GTK_ENTRY( name ),
disp_name );
g_free( disp_name );
}
else
{
if ( vfs_file_info_is_dir( file ) &&
!vfs_file_info_is_symlink( file ) )
gtk_label_set_markup_with_mnemonic( GTK_LABEL( label_name ),
_("<b>Folder _Name:</b>") );
gtk_entry_set_text( GTK_ENTRY( name ),
vfs_file_info_get_disp_name( file ) );
}
gtk_editable_set_editable ( GTK_EDITABLE( name ), FALSE );
if ( ! vfs_file_info_is_dir( file ) )
{
/* Only single "file" is selected, so we don't need to
caculate total file size */
need_calc_size = FALSE;
sprintf( buf, _("%s ( %lu bytes )"),
vfs_file_info_get_disp_size( file ),
( guint64 ) vfs_file_info_get_size( file ) );
gtk_label_set_text( data->total_size_label, buf );
vfs_file_size_to_string( buf2,
vfs_file_info_get_blocks( file ) * 512 );
sprintf( buf, _("%s ( %lu bytes )"), buf2,
( guint64 ) vfs_file_info_get_blocks( file ) * 512 );
gtk_label_set_text( data->size_on_disk_label, buf );
gtk_label_set_text( data->count_label, _("1 file") );
}
// Modified / Accessed
//gtk_entry_set_text( GTK_ENTRY( mtime ),
// vfs_file_info_get_disp_mtime( file ) );
strftime( buf, sizeof( buf ),
time_format, localtime( vfs_file_info_get_mtime( file ) ) );
gtk_entry_set_text( GTK_ENTRY( data->mtime ), buf );
data->orig_mtime = g_strdup( buf );
strftime( buf, sizeof( buf ),
time_format, localtime( vfs_file_info_get_atime( file ) ) );
gtk_entry_set_text( GTK_ENTRY( data->atime ), buf );
data->orig_atime = g_strdup( buf );
// Permissions
owner_group = (char *) vfs_file_info_get_disp_owner( file );
tmp = strchr( owner_group, ':' );
data->owner_name = g_strndup( owner_group, tmp - owner_group );
gtk_entry_set_text( GTK_ENTRY( data->owner ), data->owner_name );
data->group_name = g_strdup( tmp + 1 );
gtk_entry_set_text( GTK_ENTRY( data->group ), data->group_name );
for ( i = 0; i < N_CHMOD_ACTIONS; ++i )
{
if ( data->chmod_states[ i ] != 2 ) /* allow to touch this bit */
{
data->chmod_states[ i ] = ( vfs_file_info_get_mode( file ) & chmod_flags[ i ] ? 1 : 0 );
gtk_toggle_button_set_active( data->chmod_btns[ i ], data->chmod_states[ i ] );
}
}
// target
if ( vfs_file_info_is_symlink( file ) )
{
gtk_label_set_markup_with_mnemonic( GTK_LABEL( label_name ),
_("<b>Link _Name:</b>") );
disp_path = g_build_filename( dir_path, file->name, NULL );
char* target_path = g_file_read_link( disp_path, NULL );
if ( target_path )
{
if ( !g_file_test( target_path, G_FILE_TEST_EXISTS ) )
gtk_label_set_text( GTK_LABEL( mime_type ),
_("( broken link )") );
gtk_entry_set_text( GTK_ENTRY( target ), target_path );
g_free( target_path );
}
else
gtk_entry_set_text( GTK_ENTRY( target ), _("( read link error )") );
g_free( disp_path );
gtk_widget_show( target );
gtk_widget_show( label_target );
}
}
if ( need_calc_size )
{
/* The total file size displayed in "File Properties" is not
completely calculated yet. So "Calculating..." is displayed. */
calculating = _( "Calculating..." );
gtk_label_set_text( data->total_size_label, calculating );
gtk_label_set_text( data->size_on_disk_label, calculating );
g_object_set_data( G_OBJECT( dlg ), "calc_size", data );
data->calc_size_thread = g_thread_create ( ( GThreadFunc ) calc_size,
data, TRUE, NULL );
data->update_label_timer = g_timeout_add( 250,
( GSourceFunc ) on_update_labels,
data );
}
g_signal_connect( dlg, "response",
G_CALLBACK(on_dlg_response), dlg );
g_signal_connect_swapped( gtk_builder_get_object(builder, "ok_button"),
"clicked",
G_CALLBACK(gtk_widget_destroy), dlg );
g_signal_connect_swapped( gtk_builder_get_object(builder, "cancel_button"),
"clicked",
G_CALLBACK(gtk_widget_destroy), dlg );
g_object_unref( builder );
gtk_notebook_set_current_page( notebook, page );
gtk_window_set_transient_for( GTK_WINDOW( dlg ), parent );
return dlg;
}
static uid_t uid_from_name( const char* user_name )
{
struct passwd * pw;
uid_t uid = -1;
const char* p;
pw = getpwnam( user_name );
if ( pw )
{
uid = pw->pw_uid;
}
else
{
uid = 0;
for ( p = user_name; *p; ++p )
{
if ( !g_ascii_isdigit( *p ) )
return -1;
uid *= 10;
uid += ( *p - '0' );
}
#if 0 /* This is not needed */
/* Check the existance */
pw = getpwuid( uid );
if ( !pw ) /* Invalid uid */
return -1;
#endif
}
return uid;
}
gid_t gid_from_name( const char* group_name )
{
struct group * grp;
gid_t gid = -1;
const char* p;
grp = getgrnam( group_name );
if ( grp )
{
gid = grp->gr_gid;
}
else
{
gid = 0;
for ( p = group_name; *p; ++p )
{
if ( !g_ascii_isdigit( *p ) )
return -1;
gid *= 10;
gid += ( *p - '0' );
}
#if 0 /* This is not needed */
/* Check the existance */
grp = getgrgid( gid );
if ( !grp ) /* Invalid gid */
return -1;
#endif
}
return gid;
}
void
on_dlg_response ( GtkDialog *dialog,
gint response_id,
gpointer user_data )
{
FilePropertiesDialogData * data;
PtkFileTask* task;
gboolean mod_change;
uid_t uid = -1;
gid_t gid = -1;
const char* owner_name;
const char* group_name;
int i;
GList* l;
GList* file_list;
char* file_path;
GtkWidget* ask_recursive;
VFSFileInfo* file;
GtkAllocation allocation;
gtk_widget_get_allocation ( GTK_WIDGET( dialog ), &allocation );
int width = allocation.width;
int height = allocation.height;
if ( width && height )
{
char* str = g_strdup_printf( "%d", width );
xset_set( "app_dlg", "s", str );
g_free( str );
str = g_strdup_printf( "%d", height );
xset_set( "app_dlg", "z", str );
g_free( str );
}
data = ( FilePropertiesDialogData* ) g_object_get_data( G_OBJECT( dialog ),
"DialogData" );
if ( data )
{
if ( data->update_label_timer )
g_source_remove( data->update_label_timer );
data->cancel = TRUE;
if ( data->calc_size_thread )
g_thread_join( data->calc_size_thread );
if ( response_id == GTK_RESPONSE_OK )
{
// change file dates
char* cmd = NULL;
char* quoted_time;
char* quoted_path;
const char* new_mtime = gtk_entry_get_text( data->mtime );
if ( !( new_mtime && new_mtime[0] ) ||
!g_strcmp0( data->orig_mtime, new_mtime ) )
new_mtime = NULL;
const char* new_atime = gtk_entry_get_text( data->atime );
if ( !( new_atime && new_atime[0] ) ||
!g_strcmp0( data->orig_atime, new_atime ) )
new_atime = NULL;
if ( ( new_mtime || new_atime ) && data->file_list )
{
GString* gstr = g_string_new( NULL );
for ( l = data->file_list; l; l = l->next )
{
file_path = g_build_filename( data->dir_path,
((VFSFileInfo*)l->data)->name,
NULL );
quoted_path = bash_quote( file_path );
g_string_append_printf( gstr, " %s", quoted_path );
g_free( file_path );
g_free( quoted_path );
}
if ( new_mtime )
{
quoted_time = bash_quote( new_mtime );
cmd = g_strdup_printf( "touch --no-dereference --no-create -m -d %s%s",
quoted_time,
gstr->str );
}
if ( new_atime )
{
quoted_time = bash_quote( new_atime );
quoted_path = cmd; // temp str
cmd = g_strdup_printf( "%s%stouch --no-dereference --no-create -a -d %s%s",
cmd ? cmd : "",
cmd ? "\n" : "",
quoted_time,
gstr->str );
g_free( quoted_path );
}
g_free( quoted_time );
g_string_free( gstr, TRUE );
if ( cmd )
{
task = ptk_file_exec_new( _("Change File Date"), "/",
GTK_WIDGET( dialog ), NULL );
task->task->exec_command = cmd;
task->task->exec_sync = TRUE;
task->task->exec_export = FALSE;
task->task->exec_show_output = TRUE;
task->task->exec_show_error = TRUE;
ptk_file_task_run( task );
}
}
/* Set default action for mimetype */
GtkWidget* open_with;
if( ( open_with = (GtkWidget*)g_object_get_data( G_OBJECT(dialog), "open_with" ) ) )
{
GtkTreeModel* model = gtk_combo_box_get_model( GTK_COMBO_BOX(open_with) );
GtkTreeIter it;
if( model && gtk_combo_box_get_active_iter( GTK_COMBO_BOX(open_with), &it ) )
{
char* action;
gtk_tree_model_get( model, &it, 2, &action, -1 );
if( action )
{
file = ( VFSFileInfo* ) data->file_list->data;
VFSMimeType* mime = vfs_file_info_get_mime_type( file );
vfs_mime_type_set_default_action( mime, action );
vfs_mime_type_unref( mime );
g_free( action );
}
}
}
/* Check if we need chown */
owner_name = gtk_entry_get_text( data->owner );
if ( owner_name && *owner_name &&
(!data->owner_name || strcmp( owner_name, data->owner_name ) ) )
{
uid = uid_from_name( owner_name );
if ( uid == -1 )
{
ptk_show_error( GTK_WINDOW( dialog ), _("Error"), _( "Invalid User" ) );
return ;
}
}
group_name = gtk_entry_get_text( data->group );
if ( group_name && *group_name &&
(!data->group_name || strcmp( group_name, data->group_name ) ) )
{
gid = gid_from_name( group_name );
if ( gid == -1 )
{
ptk_show_error( GTK_WINDOW( dialog ), _("Error"), _( "Invalid Group" ) );
return ;
}
}
for ( i = 0; i < N_CHMOD_ACTIONS; ++i )
{
if ( gtk_toggle_button_get_inconsistent( data->chmod_btns[ i ] ) )
{
data->chmod_states[ i ] = 2; /* Don't touch this bit */
}
else if ( data->chmod_states[ i ] != gtk_toggle_button_get_active( data->chmod_btns[ i ] ) )
{
mod_change = TRUE;
data->chmod_states[ i ] = gtk_toggle_button_get_active( data->chmod_btns[ i ] );
}
else /* Don't change this bit */
{
data->chmod_states[ i ] = 2;
}
}
if ( uid != -1 || gid != -1 || mod_change )
{
file_list = NULL;
for ( l = data->file_list; l; l = l->next )
{
file = ( VFSFileInfo* ) l->data;
file_path = g_build_filename( data->dir_path,
vfs_file_info_get_name( file ), NULL );
file_list = g_list_prepend( file_list, file_path );
}
task = ptk_file_task_new( VFS_FILE_TASK_CHMOD_CHOWN,
file_list,
NULL,
GTK_WINDOW(gtk_widget_get_parent( GTK_WIDGET( dialog ) )),
NULL );
//MOD
ptk_file_task_set_recursive( task,
gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON( data->recurse ) ) );
/*
for ( l = data->file_list; l; l = l->next )
{
file = ( VFSFileInfo* ) l->data;
if ( vfs_file_info_is_dir( file ) )
{
ask_recursive = gtk_message_dialog_new(
GTK_WINDOW( data->dlg ),
GTK_DIALOG_MODAL,
GTK_MESSAGE_QUESTION,
GTK_BUTTONS_YES_NO,
_( "Do you want to recursively apply these changes to all files and sub-folders?" ) );
ptk_file_task_set_recursive( task,
( GTK_RESPONSE_YES == gtk_dialog_run( GTK_DIALOG( ask_recursive ) ) ) );
gtk_widget_destroy( ask_recursive );
break;
}
}
*/
if ( mod_change )
{
/* If the permissions of file has been changed by the user */
ptk_file_task_set_chmod( task, data->chmod_states );
}
/* For chown */
ptk_file_task_set_chown( task, uid, gid );
ptk_file_task_run( task );
/*
* This file list will be freed by file operation, so we don't
* need to do this. Just set the pointer to NULL.
*/
data->file_list = NULL;
}
}
g_free( data->owner_name );
g_free( data->group_name );
g_free( data->orig_mtime );
g_free( data->orig_atime );
/*
*NOTE: File operation chmod/chown will free the list when it's done,
*and we only need to free it when there is no file operation applyed.
*/
g_slice_free( FilePropertiesDialogData, data );
}
gtk_widget_destroy( GTK_WIDGET( dialog ) );
}
|
178 | ./spacefm/src/ptk/ptk-file-task.c | /*
* C Implementation: ptk-file-task
*
* Description:
*
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#include <glib.h>
#include <glib/gi18n.h>
#include "glib-mem.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <gdk/gdkkeysyms.h>
#include "ptk-file-task.h"
#include "ptk-utils.h"
#include "vfs-file-info.h" //MOD
#include "main-window.h"
#include "gtk2-compat.h"
// waitpid
#include <unistd.h>
#include <sys/wait.h>
static gboolean on_vfs_file_task_state_cb( VFSFileTask* task,
VFSFileTaskState state,
gpointer state_data,
gpointer user_data );
static void query_overwrite( PtkFileTask* ptask );
static void enter_callback( GtkEntry* entry, GtkDialog* dlg ); //MOD
void ptk_file_task_update( PtkFileTask* ptask );
//void ptk_file_task_notify_handler( GObject* o, PtkFileTask* ptask );
gboolean ptk_file_task_add_main( PtkFileTask* ptask );
void on_progress_dlg_response( GtkDialog* dlg, int response, PtkFileTask* ptask );
PtkFileTask* ptk_file_exec_new( const char* item_name, const char* dir,
GtkWidget* parent, GtkWidget* task_view )
{
GList* files = NULL;
GtkWidget* parent_win = NULL;
if ( parent )
parent_win = gtk_widget_get_toplevel( GTK_WIDGET( parent ) );
char* file = g_strdup( item_name );
files = g_list_prepend( files, file );
return ptk_file_task_new( VFS_FILE_TASK_EXEC, files, dir,
GTK_WINDOW( parent_win ), task_view );
}
PtkFileTask* ptk_file_task_new( VFSFileTaskType type,
GList* src_files,
const char* dest_dir,
GtkWindow* parent_window,
GtkWidget* task_view )
{
//printf("ptk_file_task_new\n");
PtkFileTask* ptask = g_slice_new0( PtkFileTask );
ptask->task = vfs_task_new( type, src_files, dest_dir );
//vfs_file_task_set_progress_callback( ptask->task,
// on_vfs_file_task_progress_cb,
// ptask );
vfs_file_task_set_state_callback( ptask->task,
on_vfs_file_task_state_cb, ptask );
ptask->parent_window = parent_window;
ptask->task_view = task_view;
ptask->task->exec_ptask = (gpointer)ptask;
ptask->progress_dlg = NULL;
ptask->complete = FALSE;
ptask->aborted = FALSE;
ptask->pause_change = FALSE;
ptask->pause_change_view = TRUE;
ptask->keep_dlg = FALSE;
ptask->err_count = 0;
if ( xset_get_b( "task_err_any" ) )
ptask->err_mode = PTASK_ERROR_ANY;
else if ( xset_get_b( "task_err_first" ) )
ptask->err_mode = PTASK_ERROR_FIRST;
else
ptask->err_mode = PTASK_ERROR_CONT;
GtkTextIter iter;
ptask->log_buf = gtk_text_buffer_new( NULL );
ptask->log_end = gtk_text_mark_new( NULL, FALSE );
gtk_text_buffer_get_end_iter( ptask->log_buf, &iter);
gtk_text_buffer_add_mark( ptask->log_buf, ptask->log_end, &iter );
ptask->log_appended = FALSE;
ptask->restart_timeout = FALSE;
ptask->dsp_file_count = g_strdup( "" );
ptask->dsp_size_tally = g_strdup( "" );
ptask->dsp_elapsed = g_strdup( "" );
ptask->dsp_curspeed = g_strdup( "" );
ptask->dsp_curest = g_strdup( "" );
ptask->dsp_avgspeed = g_strdup( "" );
ptask->dsp_avgest = g_strdup( "" );
ptask->progress_count = 0;
ptask->pop_handler = NULL;
ptask->query_cond = NULL;
ptask->query_cond_last = NULL;
ptask->query_new_dest = NULL;
// queue task
if ( ptask->task->exec_sync && ptask->task->type != VFS_FILE_TASK_EXEC &&
ptask->task->type != VFS_FILE_TASK_LINK &&
ptask->task->type != VFS_FILE_TASK_CHMOD_CHOWN &&
xset_get_b( "task_q_new" ) )
ptk_file_task_pause( ptask, VFS_FILE_TASK_QUEUE );
/* this method doesn't work because sig handler runs in task thread
// setup signal
ptask->signal_widget = gtk_label_new( NULL ); // dummy object for signal
g_signal_new( "task-notify",
G_TYPE_OBJECT, G_SIGNAL_RUN_FIRST,
0, NULL, NULL,
g_cclosure_marshal_VOID__POINTER,
G_TYPE_NONE, 1, G_TYPE_POINTER);
g_signal_connect( G_OBJECT( ptask->signal_widget ), "task-notify",
G_CALLBACK( ptk_file_task_notify_handler ), NULL );
*/
//GThread *self = g_thread_self ();
//printf("GUI_THREAD = %#x\n", self );
//printf("ptk_file_task_new DONE ptask=%#x\n", ptask);
return ptask;
}
/*
void ptk_file_task_destroy_delayed( PtkFileTask* task )
{
// in case of channel output following process exit
//printf("ptk_file_task_destroy_delayed %d\n", task->keep_dlg);
if ( task->destroy_timer )
{
g_source_remove( task->destroy_timer );
task->destroy_timer = 0;
}
if ( !task->keep_dlg && gtk_text_buffer_get_char_count( task->task->exec_err_buf ) )
on_vfs_file_task_progress_cb( task->task,
task->task->percent,
task->task->current_file,
task->old_dest_file,
task );
if ( !task->keep_dlg )
ptk_file_task_destroy( task );
return FALSE;
}
*/
void ptk_file_task_destroy( PtkFileTask* ptask )
{
//printf("ptk_file_task_destroy ptask=%#x\n", ptask);
if ( ptask->timeout )
{
g_source_remove( ptask->timeout );
ptask->timeout = 0;
}
if ( ptask->progress_timer )
{
g_source_remove( ptask->progress_timer );
ptask->progress_timer = 0;
}
main_task_view_remove_task( ptask );
main_task_start_queued( ptask->task_view, NULL );
if ( ptask->progress_dlg )
{
if ( ptask->overwrite_combo )
gtk_combo_box_popdown( GTK_COMBO_BOX( ptask->overwrite_combo ) );
if ( ptask->error_combo )
gtk_combo_box_popdown( GTK_COMBO_BOX( ptask->error_combo ) );
gtk_widget_destroy( ptask->progress_dlg );
ptask->progress_dlg = NULL;
}
if ( ptask->task->type == VFS_FILE_TASK_EXEC )
{
//printf(" g_io_channel_shutdown\n");
// channel shutdowns are needed to stop channel reads after task ends.
// Can't be placed in cb_exec_child_watch because it causes single
// line output to be lost
if ( ptask->task->exec_channel_out )
g_io_channel_shutdown( ptask->task->exec_channel_out, TRUE, NULL );
if ( ptask->task->exec_channel_err )
g_io_channel_shutdown( ptask->task->exec_channel_err, TRUE, NULL );
ptask->task->exec_channel_out = ptask->task->exec_channel_err = 0;
//printf(" g_io_channel_shutdown DONE\n");
}
if ( ptask->task )
vfs_file_task_free( ptask->task );
/*
g_signal_handlers_disconnect_by_func(
G_OBJECT( ptask->signal_widget ),
G_CALLBACK( ptk_file_task_notify_handler ), NULL );
gtk_widget_destroy( ptask->signal_widget );
*/
gtk_text_buffer_set_text( ptask->log_buf, "", -1 );
g_object_unref( ptask->log_buf );
g_free( ptask->dsp_file_count );
g_free( ptask->dsp_size_tally );
g_free( ptask->dsp_elapsed );
g_free( ptask->dsp_curspeed );
g_free( ptask->dsp_curest );
g_free( ptask->dsp_avgspeed );
g_free( ptask->dsp_avgest );
g_free( ptask->pop_handler );
g_slice_free( PtkFileTask, ptask );
//printf("ptk_file_task_destroy DONE ptask=%#x\n", ptask);
}
void ptk_file_task_set_complete_notify( PtkFileTask* ptask,
GFunc callback,
gpointer user_data )
{
ptask->complete_notify = callback;
ptask->user_data = user_data;
}
gboolean on_progress_timer( PtkFileTask* ptask )
{
//GThread *self = g_thread_self ();
//printf("PROGRESS_TIMER_THREAD = %#x\n", self );
// query condition?
if ( ptask->query_cond && ptask->query_cond != ptask->query_cond_last )
{
//printf("QUERY = %#x mutex = %#x\n", ptask->query_cond, ptask->task->mutex );
ptask->restart_timeout = ( ptask->timeout != 0 );
if ( ptask->timeout )
{
g_source_remove( ptask->timeout );
ptask->timeout = 0;
}
if ( ptask->progress_timer )
{
g_source_remove( ptask->progress_timer );
ptask->progress_timer = 0;
}
g_mutex_lock( ptask->task->mutex );
query_overwrite( ptask );
g_mutex_unlock( ptask->task->mutex );
return FALSE;
}
// start new queued task
if ( ptask->task->queue_start )
{
ptask->task->queue_start = FALSE;
if ( ptask->task->state_pause == VFS_FILE_TASK_RUNNING )
ptk_file_task_pause( ptask, VFS_FILE_TASK_RUNNING );
else
main_task_start_queued( ptask->task_view, ptask );
if ( ptask->timeout && ptask->task->state_pause != VFS_FILE_TASK_RUNNING &&
ptask->task->state == VFS_FILE_TASK_RUNNING )
{
// task is waiting in queue so list it
g_source_remove( ptask->timeout );
ptask->timeout = 0;
}
}
// only update every 300ms (6 * 50ms)
if ( ++ptask->progress_count < 6 )
return TRUE;
ptask->progress_count = 0;
//printf("on_progress_timer ptask=%#x\n", ptask);
if ( ptask->complete )
{
if ( ptask->progress_timer )
{
g_source_remove( ptask->progress_timer );
ptask->progress_timer = 0;
}
if ( ptask->complete_notify )
{
ptask->complete_notify( ptask->task, ptask->user_data );
ptask->complete_notify = NULL;
}
main_task_view_remove_task( ptask );
main_task_start_queued( ptask->task_view, NULL );
}
else if ( ptask->task->state_pause != VFS_FILE_TASK_RUNNING
&& !ptask->pause_change
&& ptask->task->type != VFS_FILE_TASK_EXEC )
return TRUE;
ptk_file_task_update( ptask );
if ( ptask->complete )
{
if ( !ptask->progress_dlg || ( !ptask->err_count && !ptask->keep_dlg ) )
{
ptk_file_task_destroy( ptask );
//printf("on_progress_timer DONE FALSE-COMPLETE ptask=%#x\n", ptask);
return FALSE;
}
}
//printf("on_progress_timer DONE TRUE ptask=%#x\n", ptask);
return !ptask->complete;
}
gboolean ptk_file_task_add_main( PtkFileTask* ptask )
{
//printf("ptk_file_task_add_main ptask=%#x\n", ptask);
if ( ptask->timeout )
{
g_source_remove( ptask->timeout );
ptask->timeout = 0;
}
if ( ptask->task->exec_popup || xset_get_b( "task_pop_all" ) )
ptk_file_task_progress_open( ptask );
if ( ptask->task->state_pause != VFS_FILE_TASK_RUNNING && !ptask->pause_change )
ptask->pause_change = ptask->pause_change_view = TRUE;
on_progress_timer( ptask );
//printf("ptk_file_task_add_main DONE ptask=%#x\n", ptask);
return FALSE;
}
/*
void ptk_file_task_notify_handler( GObject* o, PtkFileTask* ptask )
{
printf("ptk_file_task_notify_handler ptask=%#x\n", ptask);
//gdk_threads_enter();
on_progress_timer( ptask );
//gdk_threads_leave();
}
*/
void ptk_file_task_run( PtkFileTask* ptask )
{
//printf("ptk_file_task_run ptask=%#x\n", ptask);
// wait this long to first show task in manager, popup
ptask->timeout = g_timeout_add( 500,
(GSourceFunc)ptk_file_task_add_main, ptask );
ptask->progress_timer = 0;
vfs_file_task_run( ptask->task );
if ( ptask->task->type == VFS_FILE_TASK_EXEC )
{
if ( ( ptask->complete || !ptask->task->exec_sync ) && ptask->timeout )
{
g_source_remove( ptask->timeout );
ptask->timeout = 0;
}
}
ptask->progress_timer = g_timeout_add( 50, ( GSourceFunc ) on_progress_timer,
ptask );
//printf("ptk_file_task_run DONE ptask=%#x\n", ptask);
}
gboolean ptk_file_task_kill( gpointer pid )
{
//printf("SIGKILL %d\n", GPOINTER_TO_INT( pid ) );
kill( GPOINTER_TO_INT( pid ), SIGKILL );
return FALSE;
}
gboolean ptk_file_task_kill_cpids( char* cpids )
{
vfs_file_task_kill_cpids( cpids, SIGKILL );
g_free( cpids );
return FALSE;
}
gboolean ptk_file_task_cancel( PtkFileTask* ptask )
{
//GThread *self = g_thread_self ();
//printf("CANCEL_THREAD = %#x\n", self );
if ( ptask->timeout )
{
g_source_remove( ptask->timeout );
ptask->timeout = 0;
}
ptask->aborted = TRUE;
if ( ptask->task->type == VFS_FILE_TASK_EXEC )
{
ptask->keep_dlg = TRUE;
// resume task for task list responsiveness
if ( ptask->task->state_pause != VFS_FILE_TASK_RUNNING )
ptk_file_task_pause( ptask, VFS_FILE_TASK_RUNNING );
vfs_file_task_abort( ptask->task );
if ( ptask->task->exec_pid )
{
//printf("SIGTERM %d\n", ptask->task->exec_pid );
char* cpids = vfs_file_task_get_cpids( ptask->task->exec_pid );
kill( ptask->task->exec_pid, SIGTERM );
if ( cpids )
vfs_file_task_kill_cpids( cpids, SIGTERM );
// SIGKILL 2 seconds later in case SIGTERM fails
g_timeout_add( 2500, ( GSourceFunc ) ptk_file_task_kill,
GINT_TO_POINTER( ptask->task->exec_pid ) );
if ( cpids )
g_timeout_add( 2500, ( GSourceFunc ) ptk_file_task_kill_cpids,
cpids );
// other user run - need to kill as other
char* gsu;
if ( ptask->task->exec_as_user && geteuid() != 0 && ( gsu = get_valid_gsu() ) )
{
char* cmd;
// remove files
char* rm_cmd;
if ( ptask->task->exec_script )
rm_cmd = g_strdup_printf( " ; rm -f %s",
ptask->task->exec_script );
else
rm_cmd = g_strdup( "" );
// kill command
if ( cpids )
{
// convert linefeeds to spaces
char* scpids = g_strdup( cpids );
char* lf;
while ( lf = strchr( scpids, '\n' ) )
lf[0] = ' ';
cmd = g_strdup_printf( "/bin/kill %d %s ; sleep 3 ; /bin/kill -s KILL %d %s %s", ptask->task->exec_pid, scpids, ptask->task->exec_pid, scpids, rm_cmd );
g_free( scpids );
}
else
cmd = g_strdup_printf( "/bin/kill %d ; sleep 3 ; /bin/kill -s KILL %d %s", ptask->task->exec_pid, ptask->task->exec_pid, rm_cmd );
g_free( rm_cmd );
PtkFileTask* ptask2 = ptk_file_exec_new( _("Kill As Other"), NULL,
GTK_WIDGET( ptask->parent_window ), ptask->task_view );
ptask2->task->exec_command = cmd;
ptask2->task->exec_as_user = g_strdup( ptask->task->exec_as_user );
ptask2->task->exec_sync = FALSE;
ptask2->task->exec_browser = ptask->task->exec_browser;
ptk_file_task_run( ptask2 );
}
}
else
{
// no pid (exited)
// user pressed Stop on an exited process, remove task
// this may be needed because if process is killed, channels may not
// receive HUP and may remain open, leaving the task listed
ptask->complete = TRUE;
}
if ( ptask->task->exec_cond )
{
// this is used only if exec task run in non-main loop thread
g_mutex_lock( ptask->task->mutex );
if ( ptask->task->exec_cond )
g_cond_broadcast( ptask->task->exec_cond );
g_mutex_unlock( ptask->task->mutex );
}
}
else
vfs_file_task_try_abort( ptask->task );
return FALSE;
}
void set_button_states( PtkFileTask* ptask )
{
char* icon;
char* iconset;
char* label;
gboolean sens = !ptask->complete;
if ( !ptask->progress_dlg )
return;
if ( ptask->task->state_pause == VFS_FILE_TASK_PAUSE )
{
label = _("Q_ueue");
iconset = "task_que";
icon = GTK_STOCK_ADD;
}
else if ( ptask->task->state_pause == VFS_FILE_TASK_QUEUE )
{
label = _("Res_ume");
iconset = "task_resume";
icon = GTK_STOCK_MEDIA_PLAY;
}
else
{
label = _("Pa_use");
iconset = "task_pause";
icon = GTK_STOCK_MEDIA_PAUSE;
}
sens = sens && !( ptask->task->type == VFS_FILE_TASK_EXEC &&
!ptask->task->exec_pid );
XSet* set = xset_get( iconset );
if ( set->icon )
icon = set->icon;
gtk_widget_set_sensitive( ptask->progress_btn_pause, sens );
gtk_button_set_image( GTK_BUTTON( ptask->progress_btn_pause ),
xset_get_image( icon,
GTK_ICON_SIZE_BUTTON ) );
gtk_button_set_label( GTK_BUTTON( ptask->progress_btn_pause ), label );
gtk_widget_set_sensitive( ptask->progress_btn_close,
ptask->complete || !!ptask->task_view );
}
void ptk_file_task_pause( PtkFileTask* ptask, int state )
{
if ( ptask->task->type == VFS_FILE_TASK_EXEC )
{
// exec task
//ptask->keep_dlg = TRUE;
int sig;
if ( state == VFS_FILE_TASK_PAUSE ||
( ptask->task->state_pause == VFS_FILE_TASK_RUNNING &&
state == VFS_FILE_TASK_QUEUE ) )
{
sig = SIGSTOP;
ptask->task->state_pause = state;
g_timer_stop( ptask->task->timer );
}
else if ( state == VFS_FILE_TASK_QUEUE )
{
sig = 0;
ptask->task->state_pause = state;
}
else
{
sig = SIGCONT;
ptask->task->state_pause = VFS_FILE_TASK_RUNNING;
g_timer_continue( ptask->task->timer );
}
if ( sig && ptask->task->exec_pid )
{
// send signal
char* cpids = vfs_file_task_get_cpids( ptask->task->exec_pid );
char* gsu;
if ( ptask->task->exec_as_user && geteuid() != 0 &&
( gsu = get_valid_gsu() ) )
{
// other user run - need to signal as other
char* cmd;
if ( cpids )
{
// convert linefeeds to spaces
char* scpids = g_strdup( cpids );
char* lf;
while ( lf = strchr( scpids, '\n' ) )
lf[0] = ' ';
cmd = g_strdup_printf( "/bin/kill -s %d %d %s", sig,
ptask->task->exec_pid, scpids );
g_free( scpids );
}
else
cmd = g_strdup_printf( "/bin/kill -s %d %d", sig,
ptask->task->exec_pid );
PtkFileTask* ptask2 = ptk_file_exec_new( sig == SIGSTOP ?
_("Stop As Other") : _("Cont As Other"),
NULL,
GTK_WIDGET( ptask->parent_window ),
ptask->task_view );
ptask2->task->exec_command = cmd;
ptask2->task->exec_as_user = g_strdup( ptask->task->exec_as_user );
ptask2->task->exec_sync = FALSE;
ptask2->task->exec_browser = ptask->task->exec_browser;
ptk_file_task_run( ptask2 );
}
else
{
kill( ptask->task->exec_pid, sig );
if ( cpids )
vfs_file_task_kill_cpids( cpids, sig );
}
}
}
else if ( state == VFS_FILE_TASK_PAUSE )
ptask->task->state_pause = VFS_FILE_TASK_PAUSE;
else if ( state == VFS_FILE_TASK_QUEUE )
ptask->task->state_pause = VFS_FILE_TASK_QUEUE;
else
{
// Resume
if ( ptask->task->pause_cond )
{
g_mutex_lock( ptask->task->mutex );
g_cond_broadcast( ptask->task->pause_cond );
g_mutex_unlock( ptask->task->mutex );
}
ptask->task->state_pause = VFS_FILE_TASK_RUNNING;
}
set_button_states( ptask );
ptask->pause_change = ptask->pause_change_view = TRUE;
ptask->progress_count = 50; // trigger fast display
}
gboolean on_progress_dlg_delete_event( GtkWidget *widget, GdkEvent *event,
PtkFileTask* ptask )
{
return !( ptask->complete || ptask->task_view );
}
void on_progress_dlg_response( GtkDialog* dlg, int response, PtkFileTask* ptask )
{
if ( response != GTK_RESPONSE_HELP && ptask->complete && !ptask->complete_notify )
{
ptk_file_task_destroy( ptask );
return;
}
switch ( response )
{
case GTK_RESPONSE_CANCEL: // Stop btn
ptask->keep_dlg = FALSE;
if ( ptask->overwrite_combo )
gtk_combo_box_popdown( GTK_COMBO_BOX( ptask->overwrite_combo ) );
if ( ptask->error_combo )
gtk_combo_box_popdown( GTK_COMBO_BOX( ptask->error_combo ) );
gtk_widget_destroy( ptask->progress_dlg );
ptask->progress_dlg = NULL;
ptk_file_task_cancel( ptask );
break;
case GTK_RESPONSE_NO: // Pause btn
if ( ptask->task->state_pause == VFS_FILE_TASK_PAUSE )
{
ptk_file_task_pause( ptask, VFS_FILE_TASK_QUEUE );
}
else if ( ptask->task->state_pause == VFS_FILE_TASK_QUEUE )
{
ptk_file_task_pause( ptask, VFS_FILE_TASK_RUNNING );
}
else
{
ptk_file_task_pause( ptask, VFS_FILE_TASK_PAUSE );
}
main_task_start_queued( ptask->task_view, NULL );
break;
case GTK_RESPONSE_HELP:
xset_show_help( GTK_WIDGET( ptask->parent_window ), NULL, "#tasks-dlg" );
break;
case GTK_RESPONSE_OK:
case GTK_RESPONSE_NONE:
ptask->keep_dlg = FALSE;
if ( ptask->overwrite_combo )
gtk_combo_box_popdown( GTK_COMBO_BOX( ptask->overwrite_combo ) );
if ( ptask->error_combo )
gtk_combo_box_popdown( GTK_COMBO_BOX( ptask->error_combo ) );
gtk_widget_destroy( ptask->progress_dlg );
ptask->progress_dlg = NULL;
break;
}
}
void on_progress_dlg_destroy( GtkDialog* dlg, PtkFileTask* ptask )
{
char* s;
GtkAllocation allocation;
gtk_widget_get_allocation ( GTK_WIDGET(dlg), &allocation );
s = g_strdup_printf( "%d", allocation.width );
if ( ptask->task->type == VFS_FILE_TASK_EXEC )
xset_set( "task_pop_top", "s", s );
else
xset_set( "task_pop_top", "x", s );
g_free( s );
s = g_strdup_printf( "%d", allocation.height );
if ( ptask->task->type == VFS_FILE_TASK_EXEC )
xset_set( "task_pop_top", "z", s );
else
xset_set( "task_pop_top", "y", s );
g_free( s );
ptask->progress_dlg = NULL;
}
void on_view_popup( GtkTextView *entry, GtkMenu *menu, gpointer user_data )
{
GtkAccelGroup* accel_group = gtk_accel_group_new();
xset_context_new();
XSet* set = xset_get( "sep_v9" );
set->browser = NULL;
set->desktop = NULL;
xset_add_menuitem( NULL, NULL, GTK_WIDGET( menu ), accel_group, set );
set = xset_get( "task_pop_font" );
set->browser = NULL;
set->desktop = NULL;
xset_add_menuitem( NULL, NULL, GTK_WIDGET( menu ), accel_group, set );
gtk_widget_show_all( GTK_WIDGET( menu ) );
g_signal_connect( menu, "key-press-event",
G_CALLBACK( xset_menu_keypress ), NULL );
}
void set_progress_icon( PtkFileTask* ptask )
{
GdkPixbuf* pixbuf;
VFSFileTask* task = ptask->task;
if ( task->state_pause != VFS_FILE_TASK_RUNNING )
pixbuf = gtk_icon_theme_load_icon( gtk_icon_theme_get_default(),
GTK_STOCK_MEDIA_PAUSE, 16, GTK_ICON_LOOKUP_USE_BUILTIN, NULL );
else if ( task->err_count )
pixbuf = gtk_icon_theme_load_icon( gtk_icon_theme_get_default(),
"error", 16, GTK_ICON_LOOKUP_USE_BUILTIN, NULL );
else if ( task->type == VFS_FILE_TASK_MOVE || task->type == VFS_FILE_TASK_COPY ||
task->type == VFS_FILE_TASK_LINK )
pixbuf = gtk_icon_theme_load_icon( gtk_icon_theme_get_default(),
"stock_copy", 16, GTK_ICON_LOOKUP_USE_BUILTIN, NULL );
else if ( task->type == VFS_FILE_TASK_TRASH || task->type == VFS_FILE_TASK_DELETE )
pixbuf = gtk_icon_theme_load_icon( gtk_icon_theme_get_default(),
"stock_delete", 16, GTK_ICON_LOOKUP_USE_BUILTIN, NULL );
else if ( task->type == VFS_FILE_TASK_EXEC && task->exec_icon )
pixbuf = gtk_icon_theme_load_icon( gtk_icon_theme_get_default(),
task->exec_icon, 16, GTK_ICON_LOOKUP_USE_BUILTIN, NULL );
else
pixbuf = gtk_icon_theme_load_icon( gtk_icon_theme_get_default(),
"gtk-execute", 16, GTK_ICON_LOOKUP_USE_BUILTIN, NULL );
gtk_window_set_icon( GTK_WINDOW( ptask->progress_dlg ), pixbuf );
}
void on_overwrite_combo_changed( GtkComboBox* box, PtkFileTask* ptask )
{
int overwrite_mode = gtk_combo_box_get_active( box );
if ( overwrite_mode < 0 )
overwrite_mode = 0;
vfs_file_task_set_overwrite_mode( ptask->task, overwrite_mode );
}
void on_error_combo_changed( GtkComboBox* box, PtkFileTask* ptask )
{
int error_mode = gtk_combo_box_get_active( box );
if ( error_mode < 0 )
error_mode = 0;
ptask->err_mode = error_mode;
}
void ptk_file_task_progress_open( PtkFileTask* ptask )
{
GtkTable* table;
GtkLabel* label;
int i;
const char * actions[] =
{
N_( "Move: " ),
N_( "Copy: " ),
N_( "Trash: " ),
N_( "Delete: " ),
N_( "Link: " ),
N_( "Change: " ),
N_( "Run: " )
};
const char* titles[] =
{
N_( "Moving..." ),
N_( "Copying..." ),
N_( "Trashing..." ),
N_( "Deleting..." ),
N_( "Linking..." ),
N_( "Changing..." ),
N_( "Running..." )
};
if ( ptask->progress_dlg )
return;
//printf("ptk_file_task_progress_open\n");
VFSFileTask* task = ptask->task;
ptask->progress_dlg = gtk_dialog_new_with_buttons(
_( titles[ task->type ] ),
NULL /*was task->parent_window*/ , 0,
NULL, NULL );
// cache this value for speed
ptask->pop_detail = xset_get_b( "task_pop_detail" );
// Buttons
// Pause
XSet* set = xset_get( "task_pause" );
char* pause_icon = set->icon;
if ( !pause_icon )
pause_icon = GTK_STOCK_MEDIA_PAUSE;
ptask->progress_btn_pause = gtk_button_new_with_mnemonic( _("Pa_use") );
gtk_button_set_image( GTK_BUTTON( ptask->progress_btn_pause ),
xset_get_image( pause_icon,
GTK_ICON_SIZE_BUTTON ) );
gtk_dialog_add_action_widget( GTK_DIALOG( ptask->progress_dlg ),
ptask->progress_btn_pause,
GTK_RESPONSE_NO);
gtk_button_set_focus_on_click( GTK_BUTTON( ptask->progress_btn_pause ),
FALSE );
// Stop
ptask->progress_btn_stop = gtk_button_new_from_stock( GTK_STOCK_STOP );
gtk_dialog_add_action_widget( GTK_DIALOG( ptask->progress_dlg ),
ptask->progress_btn_stop,
GTK_RESPONSE_CANCEL);
gtk_button_set_focus_on_click( GTK_BUTTON( ptask->progress_btn_stop ),
FALSE );
// Close
ptask->progress_btn_close = gtk_button_new_from_stock( GTK_STOCK_CLOSE );
gtk_dialog_add_action_widget( GTK_DIALOG( ptask->progress_dlg ),
ptask->progress_btn_close,
GTK_RESPONSE_OK);
gtk_widget_set_sensitive( ptask->progress_btn_close, !!ptask->task_view );
// Help
GtkWidget* help_btn = gtk_button_new_from_stock( GTK_STOCK_HELP );
gtk_dialog_add_action_widget( GTK_DIALOG( ptask->progress_dlg ),
help_btn,
GTK_RESPONSE_HELP);
gtk_button_set_focus_on_click( GTK_BUTTON( help_btn ),
FALSE );
set_button_states( ptask );
// table
if ( task->type != VFS_FILE_TASK_EXEC )
table = GTK_TABLE(gtk_table_new( 5, 2, FALSE ));
else
table = GTK_TABLE(gtk_table_new( 3, 2, FALSE ));
gtk_container_set_border_width( GTK_CONTAINER ( table ), 5 );
gtk_table_set_row_spacings( table, 6 );
gtk_table_set_col_spacings( table, 4 );
int row = 0;
/* Copy/Move/Link: */
label = GTK_LABEL(gtk_label_new( _( actions[ task->type ] ) ));
gtk_misc_set_alignment( GTK_MISC ( label ), 0, 0.5 );
gtk_table_attach( table,
GTK_WIDGET(label),
0, 1, row, row+1, GTK_FILL, 0, 0, 0 );
ptask->from = GTK_LABEL(gtk_label_new(
ptask->complete ? "" : task->current_file ));
gtk_misc_set_alignment( GTK_MISC ( ptask->from ), 0, 0.5 );
gtk_label_set_ellipsize( ptask->from, PANGO_ELLIPSIZE_MIDDLE );
gtk_label_set_selectable( ptask->from, TRUE );
gtk_table_attach( table,
GTK_WIDGET( ptask->from ),
1, 2, row, row+1, GTK_FILL | GTK_EXPAND, 0, 0, 0 );
if ( task->type != VFS_FILE_TASK_EXEC )
{
// From: <src folder>
row++;
label = GTK_LABEL(gtk_label_new( _( "From:" ) ));
gtk_misc_set_alignment( GTK_MISC ( label ), 0, 0.5 );
gtk_table_attach( table,
GTK_WIDGET(label),
0, 1, row, row+1, GTK_FILL, 0, 0, 0 );
ptask->src_dir = GTK_LABEL( gtk_label_new( NULL ) );
gtk_misc_set_alignment( GTK_MISC ( ptask->src_dir ), 0, 0.5 );
gtk_label_set_ellipsize( ptask->src_dir, PANGO_ELLIPSIZE_MIDDLE );
gtk_label_set_selectable( ptask->src_dir, TRUE );
gtk_table_attach( table,
GTK_WIDGET( ptask->src_dir ),
1, 2, row, row+1, GTK_FILL, 0, 0, 0 );
if ( task->dest_dir )
{
/* To: <Destination folder>
ex. Copy file to..., Move file to...etc. */
row++;
label = GTK_LABEL(gtk_label_new( _( "To:" ) ));
gtk_misc_set_alignment( GTK_MISC ( label ), 0, 0.5 );
gtk_table_attach( table,
GTK_WIDGET(label),
0, 1, row, row+1, GTK_FILL, 0, 0, 0 );
ptask->to = GTK_LABEL( gtk_label_new( task->dest_dir ) );
gtk_misc_set_alignment( GTK_MISC ( ptask->to ), 0, 0.5 );
gtk_label_set_ellipsize( ptask->to, PANGO_ELLIPSIZE_MIDDLE );
gtk_label_set_selectable( ptask->to, TRUE );
gtk_table_attach( table,
GTK_WIDGET( ptask->to ),
1, 2, row, row+1, GTK_FILL, 0, 0, 0 );
}
else
ptask->to = NULL;
// Stats
row++;
label = GTK_LABEL(gtk_label_new( _( "Progress: " ) ));
gtk_misc_set_alignment( GTK_MISC ( label ), 0, 0.5 );
gtk_table_attach( table,
GTK_WIDGET(label),
0, 1, row, row+1, GTK_FILL, 0, 0, 0 );
ptask->current = GTK_LABEL(gtk_label_new( "" ));
gtk_misc_set_alignment( GTK_MISC ( ptask->current ), 0, 0.5 );
gtk_label_set_ellipsize( ptask->current, PANGO_ELLIPSIZE_MIDDLE );
gtk_label_set_selectable( ptask->current, TRUE );
gtk_table_attach( table,
GTK_WIDGET( ptask->current ),
1, 2, row, row+1, GTK_FILL, 0, 0, 0 );
}
else
{
ptask->src_dir = NULL;
ptask->to = NULL;
}
/* Processing: */
/* Processing: <Name of currently proccesed file> */
/* label = GTK_LABEL(gtk_label_new( _( "Processing:" ) ));
gtk_misc_set_alignment( GTK_MISC ( label ), 0, 0.5 );
gtk_table_attach( table,
GTK_WIDGET(label),
0, 1, 2, 3, GTK_FILL, 0, 0, 0 );
*/ //MOD
/* Preparing to do some file operation (Copy, Move, Delete...) */
/* ptask->current = GTK_LABEL(gtk_label_new( _( "Preparing..." ) ));
gtk_label_set_ellipsize( ptask->current, PANGO_ELLIPSIZE_MIDDLE );
gtk_misc_set_alignment( GTK_MISC ( ptask->current ), 0, 0.5 );
gtk_table_attach( table,
GTK_WIDGET( ptask->current ),
1, 2, 2, 3, GTK_FILL, 0, 0, 0 );
*/ //MOD
// Status
row++;
label = GTK_LABEL(gtk_label_new( _( "Status: " ) ));
gtk_misc_set_alignment( GTK_MISC ( label ), 0, 0.5 );
gtk_table_attach( table,
GTK_WIDGET(label),
0, 1, row, row+1, GTK_FILL, 0, 0, 0 );
char* status;
if ( task->state_pause == VFS_FILE_TASK_PAUSE )
status = _("Paused");
else if ( task->state_pause == VFS_FILE_TASK_QUEUE )
status = _("Queued");
else
status = _("Running...");
ptask->errors = GTK_LABEL( gtk_label_new( status ) );
gtk_misc_set_alignment( GTK_MISC ( ptask->errors ), 0, 0.5 );
gtk_label_set_ellipsize( ptask->errors, PANGO_ELLIPSIZE_MIDDLE );
gtk_label_set_selectable( ptask->errors, TRUE );
gtk_table_attach( table,
GTK_WIDGET( ptask->errors ),
1, 2, row, row+1, GTK_FILL | GTK_EXPAND, 0, 0, 0 );
/* Progress: */
row++;
//label = GTK_LABEL(gtk_label_new( _( "Progress:" ) ));
//gtk_misc_set_alignment( GTK_MISC ( label ), 0, 0.5 );
//gtk_table_attach( table,
// GTK_WIDGET(label),
// 0, 1, 3, 4, GTK_FILL, 0, 0, 0 );
ptask->progress_bar = GTK_PROGRESS_BAR(gtk_progress_bar_new());
#if GTK_CHECK_VERSION (3, 0, 0)
gtk_progress_bar_set_show_text( GTK_PROGRESS_BAR( ptask->progress_bar ), TRUE );
#endif
gtk_progress_bar_set_pulse_step( ptask->progress_bar, 0.08 );
gtk_table_attach( table,
GTK_WIDGET( ptask->progress_bar ),
0, 2, row, row+1, GTK_FILL | GTK_EXPAND, 0, 0, 0 );
// Error log
ptask->scroll = GTK_SCROLLED_WINDOW( gtk_scrolled_window_new( NULL, NULL ) );
ptask->error_view = gtk_text_view_new_with_buffer( ptask->log_buf );
// ubuntu shows input too small so use mininum height
gtk_widget_set_size_request( GTK_WIDGET( ptask->error_view ), -1, 70 );
gtk_widget_set_size_request( GTK_WIDGET( ptask->scroll ), -1, 70 );
gtk_container_add ( GTK_CONTAINER ( ptask->scroll ), ptask->error_view );
gtk_scrolled_window_set_policy ( GTK_SCROLLED_WINDOW ( ptask->scroll ),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC );
gtk_text_view_set_wrap_mode( GTK_TEXT_VIEW( ptask->error_view ), GTK_WRAP_WORD_CHAR );
gtk_text_view_set_editable( GTK_TEXT_VIEW( ptask->error_view ), FALSE );
if ( !task->exec_scroll_lock )
{
gtk_text_view_scroll_to_mark( GTK_TEXT_VIEW( ptask->error_view ), ptask->log_end,
0.0, FALSE, 0, 0 );
}
char* fontname = xset_get_s( "task_pop_font" );
if ( fontname )
{
PangoFontDescription* font_desc = pango_font_description_from_string( fontname );
gtk_widget_modify_font( ptask->error_view, font_desc );
pango_font_description_free( font_desc );
}
g_signal_connect( ptask->error_view, "populate-popup", G_CALLBACK(on_view_popup), NULL );
GtkWidget* align = gtk_alignment_new( 1, 1, 1 ,1 );
gtk_alignment_set_padding( GTK_ALIGNMENT( align ), 0, 0, 5, 5 );
gtk_container_add ( GTK_CONTAINER ( align ), GTK_WIDGET( ptask->scroll ) );
// Overwrite & Error
GtkWidget* overwrite_align;
if ( task->type != VFS_FILE_TASK_EXEC )
{
static const char* overwrite_options[] =
{
N_("Ask"),
N_("Overwrite All"),
N_("Skip All"),
N_("Auto Rename")
};
static const char* error_options[] =
{
N_("Stop If Error First"),
N_("Stop On Any Error"),
N_("Continue")
};
gboolean overtask = task->type == VFS_FILE_TASK_MOVE ||
task->type == VFS_FILE_TASK_COPY ||
task->type == VFS_FILE_TASK_LINK;
ptask->overwrite_combo = gtk_combo_box_text_new();
gtk_combo_box_set_focus_on_click( GTK_COMBO_BOX( ptask->overwrite_combo ),
FALSE );
gtk_widget_set_sensitive( ptask->overwrite_combo, overtask );
for ( i = 0; i < G_N_ELEMENTS( overwrite_options ); i++ )
gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( ptask->overwrite_combo ),
_(overwrite_options[i]) );
if ( overtask )
gtk_combo_box_set_active( GTK_COMBO_BOX( ptask->overwrite_combo ),
task->overwrite_mode < G_N_ELEMENTS( overwrite_options ) ?
task->overwrite_mode : 0 );
g_signal_connect( G_OBJECT( ptask->overwrite_combo ), "changed",
G_CALLBACK( on_overwrite_combo_changed ), ptask );
ptask->error_combo = gtk_combo_box_text_new();
gtk_combo_box_set_focus_on_click( GTK_COMBO_BOX( ptask->error_combo ),
FALSE );
for ( i = 0; i < G_N_ELEMENTS( error_options ); i++ )
gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( ptask->error_combo ),
_(error_options[i]) );
gtk_combo_box_set_active( GTK_COMBO_BOX( ptask->error_combo ),
ptask->err_mode < G_N_ELEMENTS( error_options ) ?
ptask->err_mode : 0 );
g_signal_connect( G_OBJECT( ptask->error_combo ), "changed",
G_CALLBACK( on_error_combo_changed ), ptask );
GtkWidget* overwrite_box = gtk_hbox_new( FALSE, 20 );
gtk_box_pack_start( GTK_BOX( overwrite_box ),
GTK_WIDGET( ptask->overwrite_combo ), FALSE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX( overwrite_box ),
GTK_WIDGET( ptask->error_combo ), FALSE, TRUE, 0 );
overwrite_align = gtk_alignment_new( 1, 0, 1 ,0 );
gtk_alignment_set_padding( GTK_ALIGNMENT( overwrite_align ), 0, 0, 5, 5 );
gtk_container_add ( GTK_CONTAINER ( overwrite_align ),
GTK_WIDGET( overwrite_box ) );
}
else
{
overwrite_align = NULL;
ptask->overwrite_combo = NULL;
ptask->error_combo = NULL;
}
// Pack
gtk_box_pack_start( GTK_BOX( gtk_dialog_get_content_area (
GTK_DIALOG( ptask->progress_dlg ) ) ),
GTK_WIDGET( table ), FALSE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX( gtk_dialog_get_content_area (
GTK_DIALOG( ptask->progress_dlg ) ) ),
GTK_WIDGET( align ), TRUE, TRUE, 0 );
if ( overwrite_align )
gtk_box_pack_start( GTK_BOX( gtk_dialog_get_content_area (
GTK_DIALOG( ptask->progress_dlg ) ) ),
GTK_WIDGET( overwrite_align ), FALSE, TRUE, 5 );
int win_width, win_height;
if ( task->type == VFS_FILE_TASK_EXEC )
{
win_width = xset_get_int( "task_pop_top", "s" );
win_height = xset_get_int( "task_pop_top", "z" );
}
else
{
win_width = xset_get_int( "task_pop_top", "x" );
win_height = xset_get_int( "task_pop_top", "y" );
}
if ( !win_width ) win_width = 750;
if ( !win_height ) win_height = -1;
gtk_window_set_default_size( GTK_WINDOW( ptask->progress_dlg ),
win_width, win_height );
gtk_button_box_set_layout ( GTK_BUTTON_BOX ( gtk_dialog_get_action_area ( GTK_DIALOG( ptask->progress_dlg ) ) ),
GTK_BUTTONBOX_END );
if ( xset_get_b( "task_pop_top" ) )
gtk_window_set_type_hint ( GTK_WINDOW ( ptask->progress_dlg ),
GDK_WINDOW_TYPE_HINT_DIALOG );
else
gtk_window_set_type_hint ( GTK_WINDOW ( ptask->progress_dlg ),
GDK_WINDOW_TYPE_HINT_NORMAL );
if ( xset_get_b( "task_pop_above" ) )
gtk_window_set_keep_above( GTK_WINDOW ( ptask->progress_dlg ), TRUE );
if ( xset_get_b( "task_pop_stick" ) )
gtk_window_stick( GTK_WINDOW ( ptask->progress_dlg ) );
gtk_window_set_gravity ( GTK_WINDOW ( ptask->progress_dlg ),
GDK_GRAVITY_NORTH_EAST );
gtk_window_set_position( GTK_WINDOW( ptask->progress_dlg ), GTK_WIN_POS_CENTER );
gtk_window_set_role( GTK_WINDOW( ptask->progress_dlg ), "task_dialog" );
// gtk_dialog_set_default_response( ptask->progress_dlg, GTK_RESPONSE_OK );
g_signal_connect( ptask->progress_dlg, "response",
G_CALLBACK( on_progress_dlg_response ), ptask );
g_signal_connect( ptask->progress_dlg, "destroy",
G_CALLBACK( on_progress_dlg_destroy ), ptask );
g_signal_connect( ptask->progress_dlg, "delete-event",
G_CALLBACK( on_progress_dlg_delete_event ), ptask );
gtk_widget_show_all( ptask->progress_dlg );
if ( ptask->overwrite_combo && !xset_get_b( "task_pop_over" ) )
gtk_widget_hide( ptask->overwrite_combo );
if ( ptask->error_combo && !xset_get_b( "task_pop_err" ) )
gtk_widget_hide( ptask->error_combo );
if ( overwrite_align && !gtk_widget_get_visible( ptask->overwrite_combo ) &&
!gtk_widget_get_visible( ptask->error_combo ) )
gtk_widget_hide( overwrite_align );
gtk_widget_grab_focus( ptask->progress_btn_close );
// icon
set_progress_icon( ptask );
ptask->progress_count = 50; // trigger fast display
//printf("ptk_file_task_progress_open DONE\n");
}
void ptk_file_task_progress_update( PtkFileTask* ptask )
{
char* ufile_path;
char* usrc_dir;
char* udest;
char* window_title;
char* str;
char* str2;
char percent_str[ 16 ];
char* stats;
char* errs;
GtkTextIter iter, siter;
GdkPixbuf* pixbuf;
if ( !ptask->progress_dlg )
{
if ( ptask->pause_change )
ptask->pause_change = FALSE; // stop elapsed timer
return;
}
//printf("ptk_file_task_progress_update ptask=%#x\n", ptask);
VFSFileTask* task = ptask->task;
// current file
usrc_dir = NULL;
udest = NULL;
if ( ptask->complete )
{
gtk_widget_set_sensitive( ptask->progress_btn_stop, FALSE );
gtk_widget_set_sensitive( ptask->progress_btn_pause, FALSE );
gtk_widget_set_sensitive( ptask->progress_btn_close, TRUE );
if ( ptask->overwrite_combo )
gtk_widget_set_sensitive( ptask->overwrite_combo, FALSE );
if ( ptask->error_combo )
gtk_widget_set_sensitive( ptask->error_combo, FALSE );
if ( task->type != VFS_FILE_TASK_EXEC )
ufile_path = NULL;
else
ufile_path = g_markup_printf_escaped ("<b>%s</b>", task->current_file );
if ( ptask->aborted )
window_title = _("Stopped");
else
{
if ( task->err_count )
window_title= _("Errors");
else
window_title= _("Done");
}
gtk_window_set_title( GTK_WINDOW( ptask->progress_dlg ), window_title );
if ( !ufile_path )
ufile_path = g_markup_printf_escaped ("<b>( %s )</b>", window_title );
}
else if ( task->current_file )
{
if ( task->type != VFS_FILE_TASK_EXEC )
{
// Copy: <src basename>
str = g_filename_display_basename( task->current_file );
ufile_path = g_markup_printf_escaped ("<b>%s</b>", str);
g_free( str );
// From: <src_dir>
str = g_path_get_dirname( task->current_file );
usrc_dir = g_filename_display_name( str );
g_free( str );
if ( !( usrc_dir[0] == '/' && usrc_dir[1] == '\0' ) )
{
str = usrc_dir;
usrc_dir = g_strdup_printf( "%s/", str );
g_free( str );
}
// To: <dest_dir> OR <dest_file>
if ( task->current_dest )
{
str = g_path_get_basename( task->current_file );
str2 = g_path_get_basename( task->current_dest );
if ( strcmp( str, str2 ) )
{
// source and dest filenames differ, user renamed - show all
g_free( str );
g_free( str2 );
udest = g_filename_display_name( task->current_dest );
}
else
{
// source and dest filenames same - show dest dir only
g_free( str );
g_free( str2 );
str = g_path_get_dirname( task->current_dest );
if ( str[0] == '/' && str[1] == '\0' )
udest = g_filename_display_name( str );
else
{
str2 = g_filename_display_name( str );
udest = g_strdup_printf( "%s/", str2 );
g_free( str2 );
}
g_free( str );
}
}
}
else
ufile_path = g_markup_printf_escaped ("<b>%s</b>", task->current_file );
}
else
ufile_path = NULL;
if ( !udest && !ptask->complete && task->dest_dir )
{
udest = g_filename_display_name( task->dest_dir );
if ( !( udest[0] == '/' && udest[1] == '\0' ) )
{
str = udest;
udest = g_strdup_printf( "%s/", str );
g_free( str );
}
}
gtk_label_set_markup( ptask->from, ufile_path );
if ( ptask->src_dir )
gtk_label_set_text( ptask->src_dir, usrc_dir );
if ( ptask->to )
gtk_label_set_text( ptask->to, udest );
g_free( ufile_path );
g_free( usrc_dir );
g_free( udest );
/*
// current dest
if ( ptask->old_dest_file )
{
ufile_path = g_filename_display_name( ptask->old_dest_file );
gtk_label_set_text( ptask->to, ufile_path );
g_free( ufile_path );
}
*/
// progress bar
if ( task->type != VFS_FILE_TASK_EXEC || ptask->task->custom_percent )
{
if ( task->percent >= 0 )
{
if ( task->percent > 100 )
task->percent = 100;
gtk_progress_bar_set_fraction( ptask->progress_bar,
( ( gdouble ) task->percent ) / 100 );
g_snprintf( percent_str, 16, "%d %%", task->percent );
gtk_progress_bar_set_text( ptask->progress_bar, percent_str );
}
else
gtk_progress_bar_set_fraction( ptask->progress_bar, 0 );
#if GTK_CHECK_VERSION (3, 0, 0)
gtk_progress_bar_set_show_text( GTK_PROGRESS_BAR( ptask->progress_bar ),
TRUE );
#endif
}
else if ( ptask->complete )
{
if ( !ptask->task->custom_percent )
{
if ( task->exec_is_error || ptask->aborted )
gtk_progress_bar_set_fraction( ptask->progress_bar, 0 );
else
gtk_progress_bar_set_fraction( ptask->progress_bar, 1 );
#if GTK_CHECK_VERSION (3, 0, 0)
gtk_progress_bar_set_show_text( GTK_PROGRESS_BAR( ptask->progress_bar ),
TRUE );
#endif
}
}
else if ( task->type == VFS_FILE_TASK_EXEC
&& task->state_pause == VFS_FILE_TASK_RUNNING )
{
#if GTK_CHECK_VERSION (3, 0, 0)
gtk_progress_bar_set_show_text( GTK_PROGRESS_BAR( ptask->progress_bar ),
FALSE );
#endif
gtk_progress_bar_pulse( ptask->progress_bar );
}
// progress
if ( task->type != VFS_FILE_TASK_EXEC )
{
if ( ptask->complete )
{
if ( ptask->pop_detail )
stats = g_strdup_printf( "#%s (%s) [%s] @avg %s",
ptask->dsp_file_count, ptask->dsp_size_tally,
ptask->dsp_elapsed, ptask->dsp_avgspeed );
else
stats = g_strdup_printf( "%s (%s)",
ptask->dsp_size_tally, ptask->dsp_avgspeed );
}
else
{
if ( ptask->pop_detail )
stats = g_strdup_printf( "#%s (%s) [%s] @cur %s (%s) @avg %s (%s)",
ptask->dsp_file_count, ptask->dsp_size_tally,
ptask->dsp_elapsed, ptask->dsp_curspeed,
ptask->dsp_curest, ptask->dsp_avgspeed,
ptask->dsp_avgest );
else
stats = g_strdup_printf( _("%s (%s) %s remaining"),
ptask->dsp_size_tally, ptask->dsp_avgspeed,
ptask->dsp_avgest );
}
gtk_label_set_text( ptask->current, stats );
//gtk_progress_bar_set_text( ptask->progress_bar, g_strdup_printf( "%d %% %s", task->percent, stats ) );
g_free( stats );
}
// error/output log
if ( ptask->log_appended )
{
// trim ?
if ( gtk_text_buffer_get_char_count( ptask->log_buf ) > 64000 ||
gtk_text_buffer_get_line_count( ptask->log_buf ) > 800 )
{
if ( gtk_text_buffer_get_char_count( ptask->log_buf ) > 64000 )
{
// trim to 50000 characters - handles single line flood
gtk_text_buffer_get_iter_at_offset( ptask->log_buf, &iter,
gtk_text_buffer_get_char_count( ptask->log_buf ) - 50000 );
}
else
// trim to 700 lines
gtk_text_buffer_get_iter_at_line( ptask->log_buf, &iter,
gtk_text_buffer_get_line_count( ptask->log_buf ) - 700 );
gtk_text_buffer_get_start_iter( ptask->log_buf, &siter );
gtk_text_buffer_delete( ptask->log_buf, &siter, &iter );
gtk_text_buffer_get_start_iter( ptask->log_buf, &siter );
if ( task->type == VFS_FILE_TASK_EXEC )
gtk_text_buffer_insert( ptask->log_buf, &siter, _("[ SNIP - additional output above has been trimmed from this log ]\n"), -1 );
else
gtk_text_buffer_insert( ptask->log_buf, &siter, _("[ SNIP - additional errors above have been trimmed from this log ]\n"), -1 );
}
if ( !task->exec_scroll_lock )
{
//scroll to end if scrollbar is mostly down
GtkAdjustment* adj = gtk_scrolled_window_get_vadjustment( ptask->scroll );
if ( gtk_adjustment_get_upper ( adj ) - gtk_adjustment_get_value ( adj ) < gtk_adjustment_get_page_size ( adj ) + 40 )
gtk_text_view_scroll_to_mark( GTK_TEXT_VIEW( ptask->error_view ),
ptask->log_end,
0.0, FALSE, 0, 0 );
}
}
// icon
if ( ptask->pause_change || ptask->err_count != task->err_count )
{
ptask->pause_change = FALSE;
ptask->err_count = task->err_count;
set_progress_icon( ptask );
}
// status
if ( ptask->complete )
{
if ( ptask->aborted )
{
if ( task->err_count && task->type != VFS_FILE_TASK_EXEC )
{
if ( ptask->err_mode == PTASK_ERROR_FIRST )
errs = g_strdup_printf( _("Error ( Stop If First )") );
else if ( ptask->err_mode == PTASK_ERROR_ANY )
errs = g_strdup_printf( _("Error ( Stop On Any )") );
else
errs = g_strdup_printf( ngettext( "Stopped with %d error",
"Stopped with %d errors",
task->err_count ),
task->err_count );
}
else
errs = g_strdup_printf( _("Stopped") );
}
else
{
if ( task->type != VFS_FILE_TASK_EXEC )
{
if ( task->err_count )
errs = g_strdup_printf( ngettext( "Finished with %d error",
"Finished with %d errors",
task->err_count ),
task->err_count );
else
errs = g_strdup_printf( _("Done") );
}
else
{
if ( task->exec_exit_status )
errs = g_strdup_printf( _("Finished with error ( exit status %d )"),
task->exec_exit_status );
else if ( task->exec_is_error )
errs = g_strdup_printf( _("Finished with error") );
else
errs = g_strdup_printf( _("Done") );
}
}
}
else if ( task->state_pause == VFS_FILE_TASK_PAUSE )
{
if ( task->type != VFS_FILE_TASK_EXEC )
errs = g_strdup_printf( _("Paused") );
else
{
if ( task->exec_pid )
errs = g_strdup_printf( _("Paused ( pid %d )"), task->exec_pid );
else
{
errs = g_strdup_printf( _("Paused ( exit status %d )"),
task->exec_exit_status );
set_button_states( ptask );
}
}
}
else if ( task->state_pause == VFS_FILE_TASK_QUEUE )
{
if ( task->type != VFS_FILE_TASK_EXEC )
errs = g_strdup_printf( _("Queued") );
else
{
if ( task->exec_pid )
errs = g_strdup_printf( _("Queued ( pid %d )"), task->exec_pid );
else
{
errs = g_strdup_printf( _("Queued ( exit status %d )"),
task->exec_exit_status );
set_button_states( ptask );
}
}
}
else
{
if ( task->type != VFS_FILE_TASK_EXEC )
{
if ( task->err_count )
errs = g_strdup_printf( ngettext( "Running with %d error",
"Running with %d errors",
task->err_count ),
task->err_count );
else
errs = g_strdup_printf( _("Running...") );
}
else
{
if ( task->exec_pid )
errs = g_strdup_printf( _("Running... ( pid %d )"), task->exec_pid );
else
{
errs = g_strdup_printf( _("Running... ( exit status %d )"),
task->exec_exit_status );
set_button_states( ptask );
}
}
}
gtk_label_set_text( ptask->errors, errs );
g_free( errs );
//printf("ptk_file_task_progress_update DONE ptask=%#x\n", ptask);
}
void ptk_file_task_set_chmod( PtkFileTask* ptask,
guchar* chmod_actions )
{
vfs_file_task_set_chmod( ptask->task, chmod_actions );
}
void ptk_file_task_set_chown( PtkFileTask* ptask,
uid_t uid, gid_t gid )
{
vfs_file_task_set_chown( ptask->task, uid, gid );
}
void ptk_file_task_set_recursive( PtkFileTask* ptask, gboolean recursive )
{
vfs_file_task_set_recursive( ptask->task, recursive );
}
void ptk_file_task_update( PtkFileTask* ptask )
{
//printf("ptk_file_task_update ptask=%#x\n", ptask);
// calculate updated display data
if ( !g_mutex_trylock( ptask->task->mutex ) )
{
//printf("UPDATE LOCKED @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n");
return;
}
VFSFileTask* task = ptask->task;
off64_t cur_speed;
gdouble timer_elapsed = g_timer_elapsed( task->timer, NULL );
if ( task->type != VFS_FILE_TASK_EXEC )
{
//cur speed
if ( task->state_pause == VFS_FILE_TASK_RUNNING )
{
gdouble since_last = timer_elapsed - task->last_elapsed;
if ( since_last >= 2.0 )
{
cur_speed = ( task->progress - task->last_progress ) / since_last;
//printf( "( %lld - %lld ) / %lf = %lld\n", task->progress,
// task->last_progress, since_last, cur_speed );
task->last_elapsed = timer_elapsed;
task->last_speed = cur_speed;
task->last_progress = task->progress;
}
else if ( since_last > 0.1 )
cur_speed = ( task->progress - task->last_progress ) / since_last;
else
cur_speed = 0;
}
// calc percent
int ipercent;
if ( task->total_size )
{
gdouble dpercent = ( ( gdouble ) task->progress ) / task->total_size;
ipercent = ( int ) ( dpercent * 100 );
}
else
ipercent = 50; // total_size calculation timed out
if ( ipercent != task->percent )
task->percent = ipercent;
}
//elapsed
guint hours = timer_elapsed / 3600.0;
char* elapsed;
char* elapsed2;
char* elapsed3;
if ( hours == 0 )
elapsed = g_strdup( "" );
else
elapsed = g_strdup_printf( "%d", hours );
guint mins = ( timer_elapsed - ( hours * 3600 ) ) / 60;
if ( hours > 0 )
elapsed2 = g_strdup_printf( "%s:%02d", elapsed, mins );
else if ( mins > 0 )
elapsed2 = g_strdup_printf( "%d", mins );
else
elapsed2 = g_strdup( elapsed );
guint secs = ( timer_elapsed - ( hours * 3600 ) - ( mins * 60 ) );
elapsed3 = g_strdup_printf( "%s:%02d", elapsed2, secs );
g_free( elapsed );
g_free( elapsed2 );
g_free( ptask->dsp_elapsed );
ptask->dsp_elapsed = elapsed3;
if ( task->type != VFS_FILE_TASK_EXEC )
{
char* file_count;
char* size_tally;
char* speed1;
char* speed2;
char* remain1;
char* remain2;
char buf1[ 64 ];
char buf2[ 64 ];
//count
file_count = g_strdup_printf( "%d", task->current_item );
//size
vfs_file_size_to_string_format( buf1, task->progress, NULL );
if ( task->total_size )
vfs_file_size_to_string_format( buf2, task->total_size, NULL );
else
sprintf( buf2, "??" ); // total_size calculation timed out
size_tally = g_strdup_printf( "%s / %s", buf1, buf2 );
// cur speed display
if ( task->last_speed != 0 )
// use speed of last 2 sec interval if available
cur_speed = task->last_speed;
if ( cur_speed == 0 || task->state_pause != VFS_FILE_TASK_RUNNING )
{
if ( task->state_pause == VFS_FILE_TASK_PAUSE )
speed1 = g_strdup_printf( _("paused") );
else if ( task->state_pause == VFS_FILE_TASK_QUEUE )
speed1 = g_strdup_printf( _("queued") );
else
speed1 = g_strdup_printf( _("stalled") );
}
else
{
vfs_file_size_to_string_format( buf1, cur_speed, NULL );
speed1 = g_strdup_printf( "%s/s", buf1 );
}
// avg speed
time_t avg_speed;
if ( timer_elapsed > 0 )
avg_speed = task->progress / timer_elapsed;
else
avg_speed = 0;
vfs_file_size_to_string_format( buf2, avg_speed, NULL );
speed2 = g_strdup_printf( "%s/s", buf2 );
//remain cur
off64_t remain;
if ( cur_speed > 0 && task->total_size != 0 )
remain = ( task->total_size - task->progress ) / cur_speed;
else
remain = 0;
if ( remain <= 0 )
remain1 = g_strdup( "" ); // n/a
else if ( remain > 3599 )
{
hours = remain / 3600;
if ( remain - ( hours * 3600 ) > 1799 )
hours++;
remain1 = g_strdup_printf( "%dh", hours );
}
else if ( remain > 59 )
remain1 = g_strdup_printf( "%lu:%02lu", remain / 60, remain -
( (guint)( remain / 60 ) * 60 ) );
else
remain1 = g_strdup_printf( ":%02lu", remain );
//remain avg
if ( avg_speed > 0 && task->total_size != 0 )
remain = ( task->total_size - task->progress ) / avg_speed;
else
remain = 0;
if ( remain <= 0 )
remain2 = g_strdup( "" ); // n/a
else if ( remain > 3599 )
{
hours = remain / 3600;
if ( remain - ( hours * 3600 ) > 1799 )
hours++;
remain2 = g_strdup_printf( "%dh", hours );
}
else if ( remain > 59 )
remain2 = g_strdup_printf( "%lu:%02lu", remain / 60, remain -
( (guint)( remain / 60 ) * 60 ) );
else
remain2 = g_strdup_printf( ":%02lu", remain );
g_free( ptask->dsp_file_count );
ptask->dsp_file_count = file_count;
g_free( ptask->dsp_size_tally );
ptask->dsp_size_tally = size_tally;
g_free( ptask->dsp_curspeed );
ptask->dsp_curspeed = speed1;
g_free( ptask->dsp_curest );
ptask->dsp_curest = remain1;
g_free( ptask->dsp_avgspeed );
ptask->dsp_avgspeed = speed2;
g_free( ptask->dsp_avgest );
ptask->dsp_avgest = remain2;
}
// move log lines from add_log_buf to log_buf
if ( gtk_text_buffer_get_char_count( task->add_log_buf ) )
{
GtkTextIter iter, siter;
char* text;
// get add_log text and delete
gtk_text_buffer_get_start_iter( task->add_log_buf, &siter );
gtk_text_buffer_get_iter_at_mark( task->add_log_buf, &iter, task->add_log_end );
text = gtk_text_buffer_get_text( task->add_log_buf, &siter, &iter, FALSE );
gtk_text_buffer_delete( task->add_log_buf, &siter, &iter );
// insert into log
gtk_text_buffer_get_iter_at_mark( ptask->log_buf, &iter, ptask->log_end );
gtk_text_buffer_insert( ptask->log_buf, &iter, text, -1 );
g_free( text );
ptask->log_appended = TRUE;
if ( !ptask->progress_dlg && task->type == VFS_FILE_TASK_EXEC
&& task->exec_show_output )
{
task->exec_show_output = FALSE; // disable to open every time output occurs
ptask->keep_dlg = TRUE;
ptk_file_task_progress_open( ptask );
}
}
if ( !ptask->progress_dlg )
{
if ( task->type != VFS_FILE_TASK_EXEC
&& ptask->err_count != task->err_count )
{
ptask->keep_dlg = TRUE;
ptk_file_task_progress_open( ptask );
}
else if ( task->type == VFS_FILE_TASK_EXEC
&& ptask->err_count != task->err_count )
{
if ( !ptask->aborted && task->exec_show_error )
{
ptask->keep_dlg = TRUE;
ptk_file_task_progress_open( ptask );
}
}
}
else
{
if ( task->type != VFS_FILE_TASK_EXEC
&& ptask->err_count != task->err_count )
{
ptask->keep_dlg = TRUE;
gtk_window_present( GTK_WINDOW( ptask->progress_dlg ) );
}
else if ( task->type == VFS_FILE_TASK_EXEC
&& ptask->err_count != task->err_count )
{
if ( !ptask->aborted && task->exec_show_error )
{
ptask->keep_dlg = TRUE;
gtk_window_present( GTK_WINDOW( ptask->progress_dlg ) );
}
}
}
ptk_file_task_progress_update( ptask );
if ( !ptask->timeout && !ptask->complete )
main_task_view_update_task( ptask );
g_mutex_unlock( task->mutex );
//printf("ptk_file_task_update DONE ptask=%#x\n", ptask);
}
gboolean on_vfs_file_task_state_cb( VFSFileTask* task,
VFSFileTaskState state,
gpointer state_data,
gpointer user_data )
{
PtkFileTask* ptask = ( PtkFileTask* ) user_data;
GtkWidget* dlg;
int response;
gboolean ret = TRUE;
char** new_dest;
switch ( state )
{
case VFS_FILE_TASK_FINISH:
//printf("VFS_FILE_TASK_FINISH\n");
ptask->complete = TRUE;
g_mutex_lock( task->mutex );
if ( task->type != VFS_FILE_TASK_EXEC )
string_copy_free( &task->current_file, NULL );
ptask->progress_count = 50; // trigger fast display
g_mutex_unlock( task->mutex );
//gtk_signal_emit_by_name( G_OBJECT( ptask->signal_widget ), "task-notify",
// ptask );
break;
case VFS_FILE_TASK_QUERY_OVERWRITE:
//0; GThread *self = g_thread_self ();
//printf("TASK_THREAD = %#x\n", self );
g_mutex_lock( task->mutex );
ptask->query_new_dest = ( char** ) state_data;
*ptask->query_new_dest = NULL;
ptask->query_cond = g_cond_new();
g_timer_stop( task->timer );
g_cond_wait( ptask->query_cond, task->mutex );
g_cond_free( ptask->query_cond );
ptask->query_cond = NULL;
ret = ptask->query_ret;
task->last_elapsed = g_timer_elapsed( task->timer, NULL );
task->last_progress = task->progress;
task->last_speed = 0;
g_timer_continue( task->timer );
g_mutex_unlock( task->mutex );
break;
case VFS_FILE_TASK_ERROR:
//printf("VFS_FILE_TASK_ERROR\n");
g_mutex_lock( task->mutex );
task->err_count++;
//printf(" ptask->item_count = %d\n", task->current_item );
if ( task->type == VFS_FILE_TASK_EXEC )
{
task->exec_is_error = TRUE;
ret = FALSE;
}
else if ( ptask->err_mode == PTASK_ERROR_ANY ||
( task->error_first && ptask->err_mode == PTASK_ERROR_FIRST ) )
{
ret = FALSE;
ptask->aborted = TRUE;
}
ptask->progress_count = 50; // trigger fast display
g_mutex_unlock( task->mutex );
if ( xset_get_b( "task_q_pause" ) )
{
// pause all queued
gdk_threads_enter();
main_task_pause_all_queued( ptask );
gdk_threads_leave();
}
break;
}
return ret; /* return TRUE to continue */
}
enum{
RESPONSE_OVERWRITE = 1 << 0,
RESPONSE_OVERWRITEALL = 1 << 1,
RESPONSE_RENAME = 1 << 2,
RESPONSE_SKIP = 1 << 3,
RESPONSE_SKIPALL = 1 << 4,
RESPONSE_AUTO_RENAME = 1 << 5,
RESPONSE_AUTO_RENAME_ALL = 1 << 6,
RESPONSE_PAUSE = 1 << 7
};
static gboolean on_query_input_keypress ( GtkWidget *widget, GdkEventKey *event,
PtkFileTask* ptask )
{
if ( event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_KP_Enter )
{
// User pressed enter in rename/overwrite dialog
gboolean can_rename;
char* new_name = multi_input_get_text( widget );
const char* old_name = ( const char* ) g_object_get_data( G_OBJECT( widget ),
"old_name" );
GtkWidget* dlg = gtk_widget_get_toplevel( widget );
if ( !GTK_IS_DIALOG( dlg ) )
return TRUE;
if ( new_name && new_name[0] != '\0' && strcmp( new_name, old_name ) )
gtk_dialog_response( GTK_DIALOG( dlg ), RESPONSE_RENAME );
else
gtk_dialog_response( GTK_DIALOG( dlg ), RESPONSE_AUTO_RENAME );
g_free( new_name );
return TRUE;
}
return FALSE;
}
static void on_multi_input_changed( GtkWidget* input_buf, GtkWidget* query_input )
{
char* new_name = multi_input_get_text( query_input );
const char* old_name = ( const char* ) g_object_get_data( G_OBJECT( query_input ),
"old_name" );
gboolean can_rename = new_name && ( 0 != strcmp( new_name, old_name ) );
g_free( new_name );
GtkWidget* dlg = gtk_widget_get_toplevel( query_input );
if ( !GTK_IS_DIALOG( dlg ) )
return;
GtkWidget* rename_button = (GtkWidget*)g_object_get_data( G_OBJECT( dlg ),
"rename_button" );
if ( GTK_IS_WIDGET( rename_button ) )
gtk_widget_set_sensitive( rename_button, can_rename );
gtk_dialog_set_response_sensitive ( GTK_DIALOG( dlg ), RESPONSE_OVERWRITE,
!can_rename );
gtk_dialog_set_response_sensitive ( GTK_DIALOG( dlg ), RESPONSE_OVERWRITEALL,
!can_rename );
}
void query_overwrite_response( GtkDialog *dlg, gint response, PtkFileTask* ptask )
{
char* file_name;
char* dir_name;
char* str;
switch ( response )
{
case RESPONSE_OVERWRITEALL:
vfs_file_task_set_overwrite_mode( ptask->task,
VFS_FILE_TASK_OVERWRITE_ALL );
if ( ptask->progress_dlg )
gtk_combo_box_set_active( GTK_COMBO_BOX( ptask->overwrite_combo ),
VFS_FILE_TASK_OVERWRITE_ALL );
break;
case RESPONSE_OVERWRITE:
vfs_file_task_set_overwrite_mode( ptask->task, VFS_FILE_TASK_OVERWRITE );
break;
case RESPONSE_SKIPALL:
vfs_file_task_set_overwrite_mode( ptask->task, VFS_FILE_TASK_SKIP_ALL );
if ( ptask->progress_dlg )
gtk_combo_box_set_active( GTK_COMBO_BOX( ptask->overwrite_combo ),
VFS_FILE_TASK_SKIP_ALL );
break;
case RESPONSE_SKIP:
vfs_file_task_set_overwrite_mode( ptask->task, VFS_FILE_TASK_SKIP );
break;
case RESPONSE_AUTO_RENAME_ALL:
vfs_file_task_set_overwrite_mode( ptask->task,
VFS_FILE_TASK_AUTO_RENAME );
if ( ptask->progress_dlg )
gtk_combo_box_set_active( GTK_COMBO_BOX( ptask->overwrite_combo ),
VFS_FILE_TASK_AUTO_RENAME );
break;
case RESPONSE_AUTO_RENAME:
case RESPONSE_RENAME:
vfs_file_task_set_overwrite_mode( ptask->task, VFS_FILE_TASK_RENAME );
if ( response == RESPONSE_AUTO_RENAME )
{
GtkWidget* auto_button = (GtkWidget*)g_object_get_data( G_OBJECT( dlg ),
"auto_button" );
str = gtk_widget_get_tooltip_text( auto_button );
}
else
{
GtkWidget* query_input = (GtkWidget*)g_object_get_data( G_OBJECT( dlg ),
"query_input" );
str = multi_input_get_text( query_input );
}
file_name = g_filename_from_utf8( str, -1, NULL, NULL, NULL );
if ( str && file_name && ptask->task->current_dest )
{
dir_name = g_path_get_dirname( ptask->task->current_dest );
*ptask->query_new_dest = g_build_filename( dir_name, file_name, NULL );
g_free( file_name );
g_free( dir_name );
}
g_free( str );
break;
case RESPONSE_PAUSE:
ptk_file_task_pause( ptask, VFS_FILE_TASK_PAUSE );
main_task_start_queued( ptask->task_view, ptask );
vfs_file_task_set_overwrite_mode( ptask->task, VFS_FILE_TASK_RENAME );
ptask->restart_timeout = FALSE;
break;
case GTK_RESPONSE_DELETE_EVENT: // escape was pressed or window closed
case GTK_RESPONSE_CANCEL:
ptask->task->abort = TRUE;
break;
}
// save size
GtkAllocation allocation;
gtk_widget_get_allocation ( GTK_WIDGET( dlg ), &allocation );
if ( allocation.width && allocation.height )
{
gint has_overwrite_btn = GPOINTER_TO_INT( (gpointer)g_object_get_data(
G_OBJECT( dlg ), "has_overwrite_btn" ) );
str = g_strdup_printf( "%d", allocation.width );
xset_set( "task_popups", has_overwrite_btn ? "x" : "s", str );
g_free( str );
str = g_strdup_printf( "%d", allocation.height );
xset_set( "task_popups", has_overwrite_btn ? "y" : "z", str );
g_free( str );
}
gtk_widget_destroy( GTK_WIDGET( dlg ) );
if ( ptask->query_cond )
{
g_mutex_lock( ptask->task->mutex );
ptask->query_ret = (response != GTK_RESPONSE_DELETE_EVENT)
&& (response != GTK_RESPONSE_CANCEL);
//g_cond_broadcast( ptask->query_cond );
g_cond_signal( ptask->query_cond );
g_mutex_unlock( ptask->task->mutex );
}
if ( ptask->restart_timeout )
{
ptask->timeout = g_timeout_add( 500,
( GSourceFunc ) ptk_file_task_add_main,
( gpointer ) ptask );
}
ptask->progress_count = 50;
ptask->progress_timer = g_timeout_add( 50,
( GSourceFunc ) on_progress_timer,
ptask );
}
void on_query_button_press( GtkWidget* widget, PtkFileTask* ptask )
{
GtkWidget* dlg = gtk_widget_get_toplevel( widget );
if ( !GTK_IS_DIALOG( dlg ) )
return;
GtkWidget* rename_button = (GtkWidget*)g_object_get_data( G_OBJECT( dlg ),
"rename_button" );
GtkWidget* auto_button = (GtkWidget*)g_object_get_data( G_OBJECT( dlg ),
"auto_button" );
if ( !rename_button || !auto_button )
return;
int response;
if ( widget == rename_button )
response = RESPONSE_RENAME;
else if ( widget == auto_button )
response = RESPONSE_AUTO_RENAME;
else
response = RESPONSE_AUTO_RENAME_ALL;
query_overwrite_response( GTK_DIALOG( dlg ), response, ptask );
}
static void query_overwrite( PtkFileTask* ptask )
{
//printf("query_overwrite ptask=%#x\n", ptask);
const char* title;
GtkWidget* dlg;
GtkWidget* parent_win;
GtkTextIter iter;
int response;
gboolean has_overwrite_btn = TRUE;
gboolean different_files, is_src_dir, is_dest_dir;
struct stat64 src_stat, dest_stat;
char* from_size_str = NULL;
char* to_size_str = NULL;
char* from_disp;
char* message;
if ( ptask->task->type == VFS_FILE_TASK_MOVE )
from_disp = _("Moving from folder:");
else if ( ptask->task->type == VFS_FILE_TASK_LINK )
from_disp = _("Linking from folder:");
else
from_disp = _("Copying from folder:");
different_files = ( 0 != g_strcmp0( ptask->task->current_file,
ptask->task->current_dest ) );
lstat64( ptask->task->current_file, &src_stat );
lstat64( ptask->task->current_dest, &dest_stat );
is_src_dir = !!S_ISDIR( dest_stat.st_mode );
is_dest_dir = !!S_ISDIR( src_stat.st_mode );
if ( different_files && is_dest_dir == is_src_dir )
{
if ( is_dest_dir )
{
/* Ask the user whether to overwrite dir content or not */
title = _("Folder Exists");
message = _("<b>Folder already exists.</b> Please rename or select an action.");
}
else
{
/* Ask the user whether to overwrite the file or not */
char buf[ 64 ];
char* dest_size;
char* dest_time;
char* src_size;
char* src_time;
char* src_rel;
const char* src_rel_size;
const char* src_rel_time;
const char* src_link;
const char* dest_link;
const char* link_warn;
if ( S_ISLNK( src_stat.st_mode ) )
src_link = _("\t<b>( link )</b>");
else
src_link = "";
if ( S_ISLNK( dest_stat.st_mode ) )
dest_link = _("\t<b>( link )</b>");
else
dest_link = "";
if ( S_ISLNK( src_stat.st_mode ) && !S_ISLNK( dest_stat.st_mode ) )
link_warn = _("\t<b>! overwrite file with link !</b>");
else
link_warn = "";
if ( src_stat.st_size == dest_stat.st_size )
{
src_size = g_strdup( _("<b>( same size )</b>") );
src_rel_size = NULL;
}
else
{
vfs_file_size_to_string( buf, src_stat.st_size );
src_size = g_strdup_printf( _("%s\t( %lu bytes )"), buf, src_stat.st_size );
if ( src_stat.st_size > dest_stat.st_size )
src_rel_size = _("larger");
else
src_rel_size = _("smaller");
}
if ( src_stat.st_mtime == dest_stat.st_mtime )
{
src_time = g_strdup( _("<b>( same time )</b>\t") );
src_rel_time = NULL;
}
else
{
strftime( buf, sizeof( buf ),
app_settings.date_format,
localtime( &src_stat.st_mtime ) );
src_time = g_strdup( buf );
if ( src_stat.st_mtime > dest_stat.st_mtime )
src_rel_time = _("newer");
else
src_rel_time = _("older");
}
vfs_file_size_to_string( buf, dest_stat.st_size );
dest_size = g_strdup_printf( _("%s\t( %lu bytes )"), buf, dest_stat.st_size );
strftime( buf, sizeof( buf ),
app_settings.date_format,
localtime( &dest_stat.st_mtime ) );
dest_time = g_strdup( buf );
src_rel = g_strdup_printf( "%s%s%s%s%s",
src_rel_time || src_rel_size ? "<b>( " : "",
src_rel_time ? src_rel_time : "",
src_rel_time && src_rel_size ? " & " : "",
src_rel_size ? src_rel_size : "",
src_rel_time || src_rel_size ? " )</b> " : "" );
from_size_str = g_strdup_printf( "\t%s\t%s%s%s%s", src_time, src_size,
src_rel ? "\t" : "", src_rel, src_link );
to_size_str = g_strdup_printf( "\t%s\t%s%s", dest_time, dest_size,
dest_link[0] ? dest_link : link_warn );
title = _("Filename Exists");
message = _("<b>Filename already exists.</b> Please rename or select an action.");
g_free( dest_size );
g_free( dest_time );
g_free( src_size );
g_free( src_time );
g_free( src_rel );
}
}
else
{ /* Rename is required */
has_overwrite_btn = FALSE;
title = _("Rename Required");
if ( !different_files )
from_disp = _("In folder:");
message = _("<b>Filename already exists.</b> Please rename or select an action.");
}
// filenames
char* ext;
char* base_name = g_path_get_basename( ptask->task->current_dest );
char* base_name_disp = g_filename_display_name( base_name ); // auto free
char* src_dir = g_path_get_dirname( ptask->task->current_file );
char* src_dir_disp = g_filename_display_name( src_dir );
char* dest_dir = g_path_get_dirname( ptask->task->current_dest );
char* dest_dir_disp = g_filename_display_name( dest_dir );
char* name = get_name_extension( base_name, S_ISDIR( dest_stat.st_mode ), &ext );
char* ext_disp = ext ? g_filename_display_name( ext ): NULL;
char* unique_name = vfs_file_task_get_unique_name( dest_dir, name, ext );
char* new_name_plain = unique_name ? g_path_get_basename( unique_name ) : NULL;
char* new_name = new_name_plain ? g_filename_display_name( new_name_plain ) : NULL;
int pos = ext_disp ?
g_utf8_strlen( base_name_disp, -1 ) - g_utf8_strlen( ext_disp, -1 ) - 1
: -1;
g_free( base_name );
g_free( name );
g_free( unique_name );
g_free( ext );
g_free( ext_disp );
g_free( src_dir );
g_free( dest_dir );
g_free( new_name_plain );
// create dialog
if ( ptask->progress_dlg )
parent_win = GTK_WIDGET( ptask->progress_dlg );
else
parent_win = GTK_WIDGET( ptask->parent_window );
dlg = gtk_dialog_new_with_buttons(
title,
GTK_WINDOW( parent_win ),
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
NULL, NULL );
g_signal_connect( G_OBJECT( dlg ), "response",
G_CALLBACK( query_overwrite_response ), ptask );
gtk_window_set_resizable( GTK_WINDOW( dlg ), TRUE );
gtk_window_set_title( GTK_WINDOW( dlg ), title );
gtk_window_set_type_hint ( GTK_WINDOW ( dlg ), GDK_WINDOW_TYPE_HINT_DIALOG );
gtk_window_set_gravity ( GTK_WINDOW ( dlg ),
GDK_GRAVITY_NORTH_EAST );
gtk_window_set_position( GTK_WINDOW( dlg ), GTK_WIN_POS_CENTER );
gtk_window_set_role( GTK_WINDOW( dlg ), "overwrite_dialog" );
int width, height;
if ( has_overwrite_btn )
{
width = xset_get_int( "task_popups", "x" );
height = xset_get_int( "task_popups", "y" );
}
else
{
width = xset_get_int( "task_popups", "s" );
height = xset_get_int( "task_popups", "z" );
}
if ( width && height )
gtk_window_set_default_size( GTK_WINDOW( dlg ), width, height );
else if ( !has_overwrite_btn )
gtk_widget_set_size_request( GTK_WIDGET( dlg ), 600, -1 );
GtkWidget* align = gtk_alignment_new( 1, 0, 1 ,1 );
gtk_alignment_set_padding( GTK_ALIGNMENT( align ), 0, 14, 7, 7 );
GtkWidget* vbox = gtk_vbox_new( FALSE, 0 );
gtk_container_add ( GTK_CONTAINER ( align ), vbox );
gtk_box_pack_start( GTK_BOX( gtk_dialog_get_content_area( GTK_DIALOG( dlg ) ) ),
align, TRUE, TRUE, 0 );
// buttons
if ( has_overwrite_btn )
{
gtk_dialog_add_buttons ( GTK_DIALOG( dlg ),
_( "_Overwrite" ), RESPONSE_OVERWRITE,
_( "Overwrite _All" ), RESPONSE_OVERWRITEALL,
NULL );
}
GtkWidget* btn_pause = gtk_dialog_add_button ( GTK_DIALOG( dlg ),
_( "_Pause" ), RESPONSE_PAUSE );
gtk_dialog_add_buttons( GTK_DIALOG( dlg ),
_( "_Skip" ), RESPONSE_SKIP,
_( "S_kip All" ), RESPONSE_SKIPALL,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
NULL );
XSet* set = xset_get( "task_pause" );
char* pause_icon = set->icon;
if ( !pause_icon )
pause_icon = GTK_STOCK_MEDIA_PAUSE;
gtk_button_set_image( GTK_BUTTON( btn_pause ),
xset_get_image( pause_icon, GTK_ICON_SIZE_BUTTON ) );
gtk_widget_set_sensitive( btn_pause, !!ptask->task_view );
// labels
gtk_box_pack_start( GTK_BOX( vbox ),
gtk_label_new( NULL ), FALSE, TRUE, 0 );
GtkWidget* msg = gtk_label_new( NULL );
gtk_label_set_markup( GTK_LABEL( msg ), message );
gtk_misc_set_alignment( GTK_MISC ( msg ), 0, 0 );
gtk_widget_set_can_focus( msg, FALSE );
gtk_box_pack_start( GTK_BOX( vbox ),
msg, FALSE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX( vbox ),
gtk_label_new( NULL ), FALSE, TRUE, 0 );
GtkWidget* from_label = gtk_label_new( NULL );
gtk_label_set_markup( GTK_LABEL( from_label ), from_disp );
gtk_misc_set_alignment( GTK_MISC ( from_label ), 0, 0 );
gtk_widget_set_can_focus( from_label, FALSE );
gtk_box_pack_start( GTK_BOX( vbox ),
from_label, FALSE, TRUE, 0 );
GtkWidget* from_dir = gtk_label_new( src_dir_disp );
gtk_misc_set_alignment( GTK_MISC ( from_dir ), 0, 0 );
gtk_label_set_ellipsize( GTK_LABEL( from_dir ), PANGO_ELLIPSIZE_MIDDLE );
gtk_label_set_selectable( GTK_LABEL( from_dir ), TRUE );
gtk_box_pack_start( GTK_BOX( vbox ),
from_dir, FALSE, TRUE, 0 );
if ( from_size_str )
{
GtkWidget* from_size = gtk_label_new( NULL );
gtk_label_set_markup( GTK_LABEL( from_size ), from_size_str );
gtk_misc_set_alignment( GTK_MISC ( from_size ), 0, 1.0 );
gtk_label_set_selectable( GTK_LABEL( from_size ), TRUE );
gtk_box_pack_start( GTK_BOX( vbox ),
from_size, FALSE, TRUE, 0 );
}
GtkWidget* to_dir = NULL;
if ( has_overwrite_btn || different_files )
{
gtk_box_pack_start( GTK_BOX( vbox ),
gtk_label_new( NULL ), FALSE, TRUE, 0 );
GtkWidget* to_label = gtk_label_new( NULL );
gtk_label_set_markup( GTK_LABEL( to_label ), _( "To folder:" ) );
gtk_misc_set_alignment( GTK_MISC ( to_label ), 0, 0 );
gtk_box_pack_start( GTK_BOX( vbox ),
to_label, FALSE, TRUE, 0 );
GtkWidget* to_dir = gtk_label_new( dest_dir_disp );
gtk_misc_set_alignment( GTK_MISC ( to_dir ), 0, 0 );
gtk_label_set_ellipsize( GTK_LABEL( to_dir ), PANGO_ELLIPSIZE_MIDDLE );
gtk_label_set_selectable( GTK_LABEL( to_dir ), TRUE );
gtk_box_pack_start( GTK_BOX( vbox ),
to_dir, FALSE, TRUE, 0 );
if ( to_size_str )
{
GtkWidget* to_size = gtk_label_new( NULL );
gtk_label_set_markup( GTK_LABEL( to_size ), to_size_str );
gtk_misc_set_alignment( GTK_MISC ( to_size ), 0, 1.0 );
gtk_label_set_selectable( GTK_LABEL( to_size ), TRUE );
gtk_box_pack_start( GTK_BOX( vbox ),
to_size, FALSE, TRUE, 0 );
}
}
gtk_box_pack_start( GTK_BOX( vbox ),
gtk_label_new( NULL ), FALSE, TRUE, 0 );
GtkWidget* name_label = gtk_label_new( NULL );
gtk_label_set_markup( GTK_LABEL( name_label ),
is_dest_dir ? _( "<b>Folder Name:</b>" ) : _( "<b>Filename:</b>" ) );
gtk_misc_set_alignment( GTK_MISC ( name_label ), 0, 0 );
gtk_box_pack_start( GTK_BOX( vbox ),
name_label, FALSE, TRUE, 0 );
// name input
GtkWidget* scroll = gtk_scrolled_window_new( NULL, NULL );
GtkWidget* query_input = GTK_WIDGET( multi_input_new(
GTK_SCROLLED_WINDOW( scroll ), base_name_disp, TRUE ) );
g_signal_connect( G_OBJECT( query_input ), "key-press-event",
G_CALLBACK( on_query_input_keypress ), ptask );
GtkWidget* input_buf = GTK_WIDGET( gtk_text_view_get_buffer(
GTK_TEXT_VIEW( query_input ) ) );
gtk_text_buffer_get_iter_at_offset( GTK_TEXT_BUFFER( input_buf ), &iter, pos );
gtk_text_buffer_place_cursor( GTK_TEXT_BUFFER( input_buf ), &iter );
g_signal_connect( G_OBJECT( input_buf ), "changed",
G_CALLBACK( on_multi_input_changed ), query_input );
g_object_set_data_full( G_OBJECT( query_input ), "old_name",
base_name_disp, g_free );
gtk_widget_set_size_request( GTK_WIDGET( query_input ), -1, 60 );
gtk_widget_set_size_request( GTK_WIDGET( scroll ), -1, 60 );
GtkTextBuffer* buf = gtk_text_view_get_buffer( GTK_TEXT_VIEW( query_input ) );
GtkTextMark* mark = gtk_text_buffer_get_insert( buf );
gtk_text_view_scroll_to_mark( GTK_TEXT_VIEW( query_input ), mark, 0, TRUE, 0, 0 );
gtk_box_pack_start( GTK_BOX( vbox ),
GTK_WIDGET( scroll ), TRUE, TRUE, 4 );
// extra buttons
GtkWidget* rename_button = gtk_button_new_with_mnemonic( _(" _Rename ") );
gtk_widget_set_sensitive( rename_button, FALSE );
g_signal_connect( G_OBJECT( rename_button ), "clicked",
G_CALLBACK( on_query_button_press ), ptask );
GtkWidget* auto_button = gtk_button_new_with_mnemonic( _(" A_uto Rename ") );
g_signal_connect( G_OBJECT( auto_button ), "clicked",
G_CALLBACK( on_query_button_press ), ptask );
gtk_widget_set_tooltip_text( auto_button, new_name );
GtkWidget* auto_all_button = gtk_button_new_with_mnemonic( _(" Auto Re_name All ") );
g_signal_connect( G_OBJECT( auto_all_button ), "clicked",
G_CALLBACK( on_query_button_press ), ptask );
GtkWidget* hbox = gtk_hbox_new( FALSE, 30 );
gtk_box_pack_start( GTK_BOX( hbox ),
GTK_WIDGET( rename_button ), FALSE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX( hbox ),
GTK_WIDGET( auto_button ), FALSE, TRUE, 0 );
gtk_box_pack_start( GTK_BOX( hbox ),
GTK_WIDGET( auto_all_button ), FALSE, TRUE, 0 );
align = gtk_alignment_new( 1, 0, 0 ,0 );
gtk_container_add ( GTK_CONTAINER ( align ), GTK_WIDGET( hbox ) );
gtk_box_pack_start( GTK_BOX( vbox ),
GTK_WIDGET( align ), FALSE, TRUE, 0 );
g_free( src_dir_disp );
g_free( dest_dir_disp );
g_free( new_name );
g_free( from_size_str );
g_free( to_size_str );
// update displays (mutex is already locked)
g_free( ptask->dsp_curspeed );
ptask->dsp_curspeed = g_strdup_printf( _("stalled") );
ptk_file_task_progress_update( ptask );
if ( ptask->task_view && gtk_widget_get_visible( gtk_widget_get_parent(
GTK_WIDGET( ptask->task_view ) ) ) )
main_task_view_update_task( ptask );
// show dialog
g_object_set_data( G_OBJECT( dlg ), "rename_button", rename_button );
g_object_set_data( G_OBJECT( dlg ), "auto_button", auto_button );
g_object_set_data( G_OBJECT( dlg ), "query_input", query_input );
g_object_set_data( G_OBJECT( dlg ), "has_overwrite_btn",
GINT_TO_POINTER( has_overwrite_btn ) );
gtk_widget_show_all( GTK_WIDGET( dlg ) );
gtk_widget_grab_focus( query_input );
// can't run gtk_dialog_run here because it doesn't unlock a low level
// mutex when run from inside the timer handler
return;
}
|
179 | ./spacefm/src/ptk/ptk-console-output.c | /*
*
* NOTE: This file is retained for reference purposes only - it is no longer
* included in the build system.
*
*/
#include <gtk/gtk.h>
#include <glib/gi18n.h>
#include "glib-mem.h"
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <string.h>
#include <signal.h> /* for kill(2) */
#include "ptk-utils.h"
typedef struct _PtkConsoleOutputData
{
GtkWidget* main_dlg;
GtkWidget* scroll;
GtkTextView* view;
GtkTextBuffer* buf;
GPid pid;
int stdo, stdi, stde;
GIOChannel *chstdo, *chstdi, *chstde;
}PtkConsoleOutputData;
static gboolean on_complete( gpointer user_data )
{
GtkAdjustment* adj = GTK_ADJUSTMENT( user_data );
gdk_threads_enter();
gtk_adjustment_set_value( adj, gtk_adjustment_get_upper( adj ) - gtk_adjustment_get_page_size( adj ) );
gdk_threads_leave();
return FALSE;
}
static gboolean delayed_destroy( gpointer dlg )
{
gdk_threads_enter();
gtk_widget_destroy( GTK_WIDGET( dlg ) );
gdk_threads_leave();
return FALSE;
}
static gboolean on_output( GIOChannel* ch, GIOCondition cond, gpointer user_data )
{
GtkTextIter it;
char buffer[4096];
gsize rlen = 0;
GtkAdjustment* adj;
int status;
PtkConsoleOutputData *data = (PtkConsoleOutputData*)user_data;
if( cond & G_IO_IN )
{
g_io_channel_read_chars( ch, buffer, sizeof(buffer), &rlen, NULL );
GDK_THREADS_ENTER();
/*gdk_window_freeze_updates( GTK_WIDGET(data->view)->window );*/
gtk_text_buffer_get_end_iter( data->buf, &it );
gtk_text_buffer_insert( data->buf, &it, buffer, rlen );
adj = gtk_scrolled_window_get_vadjustment( GTK_SCROLLED_WINDOW(data->scroll) );
gtk_adjustment_set_value( adj, gtk_adjustment_get_upper( adj ) - gtk_adjustment_get_page_size( adj ) );
/*gdk_window_thaw_updates( GTK_WIDGET(data->view)->window );*/
GDK_THREADS_LEAVE();
}
if( cond == G_IO_HUP )
{
if( data->chstdo == ch )
{
strcpy(buffer, _("\nComplete!"));
rlen = strlen(buffer);
GDK_THREADS_ENTER();
gtk_text_buffer_get_end_iter( data->buf, &it );
gtk_text_buffer_insert( data->buf, &it, buffer, rlen );
gtk_dialog_set_response_sensitive( GTK_DIALOG(data->main_dlg), GTK_RESPONSE_CANCEL, FALSE );
gtk_dialog_set_response_sensitive( GTK_DIALOG(data->main_dlg), GTK_RESPONSE_CLOSE, TRUE );
if( data->pid )
{
status = 0;
waitpid( data->pid, &status, 0 );
data->pid = 0;
if( WIFEXITED(status) && 0 == WEXITSTATUS(status) )
{
g_idle_add( delayed_destroy, data->main_dlg );
GDK_THREADS_LEAVE();
return FALSE;
}
adj = gtk_scrolled_window_get_vadjustment( GTK_SCROLLED_WINDOW(data->scroll) );
gtk_adjustment_set_value( adj, gtk_adjustment_get_upper( adj ) - gtk_adjustment_get_page_size( adj ) );
g_idle_add( on_complete, adj );
}
GDK_THREADS_LEAVE();
}
return FALSE;
}
return TRUE;
}
static void on_destroy( gpointer data, GObject* obj )
{
int status = 0;
PtkConsoleOutputData* ptk_data = (PtkConsoleOutputData *)data;
do{}
while( g_source_remove_by_user_data( ptk_data ) );
if( ptk_data->chstdo )
{
g_io_channel_unref(ptk_data->chstdo);
close( ptk_data->stdo );
}
if( ptk_data->chstde )
{
g_io_channel_unref(ptk_data->chstde);
close( ptk_data->stde );
}
if( ptk_data->pid )
{
kill( ptk_data->pid, 15 );
waitpid( ptk_data->pid, &status, 0 );
}
g_slice_free( PtkConsoleOutputData, ptk_data );
}
static void on_response( GtkDialog* dlg, int response,
PtkConsoleOutputData* data )
{
gtk_widget_destroy( data->main_dlg );
}
int ptk_console_output_run( GtkWindow* parent_win,
const char* title,
const char* desc,
const char* working_dir,
int argc, char* argv[] )
{
GtkWidget* main_dlg;
GtkWidget* desc_label;
PtkConsoleOutputData* data;
GtkWidget* hbox;
GtkWidget* entry;
GdkColor black={0}, white={0, 65535, 65535, 65535};
char* cmd;
GError* err;
data = g_slice_new0( PtkConsoleOutputData );
cmd = g_strjoinv( " ", &argv[0] );
main_dlg = gtk_dialog_new_with_buttons( title, NULL, 0,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE, NULL );
gtk_dialog_set_alternative_button_order( GTK_DIALOG(main_dlg), GTK_RESPONSE_CLOSE, GTK_RESPONSE_CANCEL, -1 );
g_object_weak_ref( G_OBJECT(main_dlg), on_destroy, data );
data->main_dlg = main_dlg;
gtk_dialog_set_response_sensitive( GTK_DIALOG(main_dlg), GTK_RESPONSE_CLOSE, FALSE );
gtk_window_set_type_hint( GTK_WINDOW(main_dlg),
GDK_WINDOW_TYPE_HINT_NORMAL );
desc_label = gtk_label_new( desc );
gtk_label_set_line_wrap( GTK_LABEL(desc_label), TRUE );
gtk_box_pack_start( GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(main_dlg))),
desc_label, FALSE, TRUE, 2 );
hbox = gtk_hbox_new( FALSE, 2 );
gtk_box_pack_start( GTK_BOX(hbox), gtk_label_new( _("Command:") ),
FALSE, FALSE, 2 );
entry = gtk_entry_new();
gtk_entry_set_text( GTK_ENTRY(entry), cmd );
gtk_editable_set_position( GTK_EDITABLE(entry), 0 );
gtk_editable_set_editable( GTK_EDITABLE(entry), FALSE );
gtk_editable_select_region( GTK_EDITABLE(entry), 0, 0 );
g_free( cmd );
gtk_box_pack_start( GTK_BOX(hbox), entry, TRUE, TRUE, 2 );
gtk_box_pack_start( GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(main_dlg))),
hbox, FALSE, TRUE, 2 );
data->buf = GTK_TEXT_BUFFER(gtk_text_buffer_new(NULL));
data->view = GTK_TEXT_VIEW(gtk_text_view_new_with_buffer( data->buf ));
gtk_widget_modify_base( GTK_WIDGET(data->view), GTK_STATE_NORMAL, &black );
gtk_widget_modify_text( GTK_WIDGET(data->view), GTK_STATE_NORMAL, &white );
data->scroll = gtk_scrolled_window_new(NULL, NULL);
gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW(data->scroll),
GTK_POLICY_AUTOMATIC,
GTK_POLICY_ALWAYS );
gtk_container_add( GTK_CONTAINER(data->scroll), GTK_WIDGET(data->view) );
gtk_box_pack_start( GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(main_dlg))), data->scroll, TRUE, TRUE, 2 );
gtk_widget_show_all( gtk_dialog_get_content_area(GTK_DIALOG(main_dlg)) );
gtk_window_set_default_size( GTK_WINDOW(main_dlg), 480, 240 );
gtk_widget_show( main_dlg );
if( g_spawn_async_with_pipes( working_dir, argv, NULL,
G_SPAWN_SEARCH_PATH, NULL, NULL,
&data->pid, NULL/*&stdi*/,
&data->stdo, &data->stde, &err ) )
{
/* fcntl(stdi,F_SETFL,O_NONBLOCK); */
fcntl(data->stdo,F_SETFL,O_NONBLOCK);
fcntl(data->stde,F_SETFL,O_NONBLOCK);
data->chstdo = g_io_channel_unix_new( data->stdo );
g_io_channel_set_encoding( data->chstdo, NULL, NULL );
g_io_channel_set_buffered( data->chstdo, FALSE );
g_io_add_watch( data->chstdo, G_IO_IN|G_IO_HUP, on_output, data );
fcntl(data->stde,F_SETFL,O_NONBLOCK);
data->chstde = g_io_channel_unix_new( data->stde );
g_io_channel_set_encoding( data->chstde, NULL, NULL );
g_io_channel_set_buffered( data->chstde, FALSE );
g_io_add_watch( data->chstde, G_IO_IN|G_IO_HUP, on_output, data );
g_signal_connect( main_dlg, "delete-event", G_CALLBACK(gtk_widget_destroy), NULL );
g_signal_connect( main_dlg, "response", G_CALLBACK(on_response), data );
}
else
{
gtk_widget_destroy( main_dlg );
ptk_show_error( parent_win, _("Error"), err->message );
g_error_free( err );
return 1;
}
return 0;
}
|
180 | ./spacefm/src/ptk/ptk-dir-tree.c | /*
* C Implementation: ptk-dir-tree
*
* Description:
*
*
* Author: Hong Jen Yee (PCMan) <pcman.tw (AT) gmail.com>, (C) 2006
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#include "ptk-dir-tree.h"
#include <gdk/gdk.h>
#include <glib/gi18n.h>
#include <string.h>
#include "vfs-file-info.h"
#include "vfs-file-monitor.h"
#include "glib-mem.h"
struct _PtkDirTreeNode
{
VFSFileInfo* file;
PtkDirTreeNode* children;
int n_children;
VFSFileMonitor* monitor;
int n_expand;
PtkDirTreeNode* parent;
PtkDirTreeNode* next;
PtkDirTreeNode* prev;
PtkDirTreeNode* last;
PtkDirTree* tree; /* FIXME: This is a waste of memory :-( */
};
static void ptk_dir_tree_init ( PtkDirTree *tree );
static void ptk_dir_tree_class_init ( PtkDirTreeClass *klass );
static void ptk_dir_tree_tree_model_init ( GtkTreeModelIface *iface );
static void ptk_dir_tree_drag_source_init ( GtkTreeDragSourceIface *iface );
static void ptk_dir_tree_drag_dest_init ( GtkTreeDragDestIface *iface );
static void ptk_dir_tree_finalize ( GObject *object );
static GtkTreeModelFlags ptk_dir_tree_get_flags ( GtkTreeModel *tree_model );
static gint ptk_dir_tree_get_n_columns ( GtkTreeModel *tree_model );
static GType ptk_dir_tree_get_column_type ( GtkTreeModel *tree_model,
gint index );
static gboolean ptk_dir_tree_get_iter ( GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreePath *path );
static GtkTreePath *ptk_dir_tree_get_path ( GtkTreeModel *tree_model,
GtkTreeIter *iter );
static void ptk_dir_tree_get_value ( GtkTreeModel *tree_model,
GtkTreeIter *iter,
gint column,
GValue *value );
static gboolean ptk_dir_tree_iter_next ( GtkTreeModel *tree_model,
GtkTreeIter *iter );
static gboolean ptk_dir_tree_iter_children ( GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreeIter *parent );
static gboolean ptk_dir_tree_iter_has_child ( GtkTreeModel *tree_model,
GtkTreeIter *iter );
static gint ptk_dir_tree_iter_n_children ( GtkTreeModel *tree_model,
GtkTreeIter *iter );
static gboolean ptk_dir_tree_iter_nth_child ( GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreeIter *parent,
gint n );
static gboolean ptk_dir_tree_iter_parent ( GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreeIter *child );
static gint ptk_dir_tree_node_compare( PtkDirTree* tree,
PtkDirTreeNode* a,
PtkDirTreeNode* b );
static void ptk_dir_tree_insert_child( PtkDirTree* tree,
PtkDirTreeNode* parent,
const char* file_path,
const char* name );
static void ptk_dir_tree_delete_child( PtkDirTree* tree,
PtkDirTreeNode* child );
/* signal handlers */
static void on_file_monitor_event ( VFSFileMonitor* fm,
VFSFileMonitorEvent event,
const char* file_name,
gpointer user_data );
static PtkDirTreeNode* ptk_dir_tree_node_new( PtkDirTree* tree,
PtkDirTreeNode* parent,
const char* path,
const char* base_name );
static void ptk_dir_tree_node_free( PtkDirTreeNode* node );
static GObjectClass* parent_class = NULL;
static GType column_types[ N_DIR_TREE_COLS ];
GType ptk_dir_tree_get_type ( void )
{
static GType type = 0;
if ( G_UNLIKELY( !type ) )
{
static const GTypeInfo type_info =
{
sizeof ( PtkDirTreeClass ),
NULL, /* base_init */
NULL, /* base_finalize */
( GClassInitFunc ) ptk_dir_tree_class_init,
NULL, /* class finalize */
NULL, /* class_data */
sizeof ( PtkDirTree ),
0, /* n_preallocs */
( GInstanceInitFunc ) ptk_dir_tree_init
};
static const GInterfaceInfo tree_model_info =
{
( GInterfaceInitFunc ) ptk_dir_tree_tree_model_init,
NULL,
NULL
};
static const GInterfaceInfo drag_src_info =
{
( GInterfaceInitFunc ) ptk_dir_tree_drag_source_init,
NULL,
NULL
};
static const GInterfaceInfo drag_dest_info =
{
( GInterfaceInitFunc ) ptk_dir_tree_drag_dest_init,
NULL,
NULL
};
type = g_type_register_static ( G_TYPE_OBJECT, "PtkDirTree",
&type_info, ( GTypeFlags ) 0 );
g_type_add_interface_static ( type, GTK_TYPE_TREE_MODEL, &tree_model_info );
g_type_add_interface_static ( type, GTK_TYPE_TREE_DRAG_SOURCE, &drag_src_info );
g_type_add_interface_static ( type, GTK_TYPE_TREE_DRAG_DEST, &drag_dest_info );
}
return type;
}
void ptk_dir_tree_init ( PtkDirTree *tree )
{
PtkDirTreeNode* child;
tree->root = g_slice_new0( PtkDirTreeNode );
tree->root->tree = tree;
tree->root->n_children = 1;
child = ptk_dir_tree_node_new( tree, tree->root, "/", "/" );
vfs_file_info_set_disp_name( child->file, _("File System") );
tree->root->children = child;
/*
child = ptk_dir_tree_node_new( tree, tree->root, g_get_home_dir(), NULL );
vfs_file_info_set_name( child->file, g_get_home_dir() );
tree->root->children->next = child;
*/
/* Random int to check whether an iter belongs to our model */
tree->stamp = g_random_int();
}
void ptk_dir_tree_class_init ( PtkDirTreeClass *klass )
{
GObjectClass * object_class;
parent_class = ( GObjectClass* ) g_type_class_peek_parent ( klass );
object_class = ( GObjectClass* ) klass;
object_class->finalize = ptk_dir_tree_finalize;
}
void ptk_dir_tree_tree_model_init ( GtkTreeModelIface *iface )
{
iface->get_flags = ptk_dir_tree_get_flags;
iface->get_n_columns = ptk_dir_tree_get_n_columns;
iface->get_column_type = ptk_dir_tree_get_column_type;
iface->get_iter = ptk_dir_tree_get_iter;
iface->get_path = ptk_dir_tree_get_path;
iface->get_value = ptk_dir_tree_get_value;
iface->iter_next = ptk_dir_tree_iter_next;
iface->iter_children = ptk_dir_tree_iter_children;
iface->iter_has_child = ptk_dir_tree_iter_has_child;
iface->iter_n_children = ptk_dir_tree_iter_n_children;
iface->iter_nth_child = ptk_dir_tree_iter_nth_child;
iface->iter_parent = ptk_dir_tree_iter_parent;
column_types [ COL_DIR_TREE_ICON ] = GDK_TYPE_PIXBUF;
column_types [ COL_DIR_TREE_DISP_NAME ] = G_TYPE_STRING;
column_types [ COL_DIR_TREE_INFO ] = G_TYPE_POINTER;
}
void ptk_dir_tree_drag_source_init ( GtkTreeDragSourceIface *iface )
{
/* FIXME: Unused. Will this cause any problem? */
}
void ptk_dir_tree_drag_dest_init ( GtkTreeDragDestIface *iface )
{
/* FIXME: Unused. Will this cause any problem? */
}
void ptk_dir_tree_finalize ( GObject *object )
{
PtkDirTree *tree = ( PtkDirTree* ) object;
if( tree->root )
ptk_dir_tree_node_free( tree->root );
/* must chain up - finalize parent */
( * parent_class->finalize ) ( object );
}
PtkDirTree *ptk_dir_tree_new ()
{
PtkDirTree * tree;
tree = ( PtkDirTree* ) g_object_new ( PTK_TYPE_DIR_TREE, NULL );
return tree;
}
GtkTreeModelFlags ptk_dir_tree_get_flags ( GtkTreeModel *tree_model )
{
g_return_val_if_fail ( PTK_IS_DIR_TREE( tree_model ), ( GtkTreeModelFlags ) 0 );
return GTK_TREE_MODEL_ITERS_PERSIST;
}
gint ptk_dir_tree_get_n_columns ( GtkTreeModel *tree_model )
{
return N_DIR_TREE_COLS;
}
GType ptk_dir_tree_get_column_type ( GtkTreeModel *tree_model,
gint index )
{
g_return_val_if_fail ( PTK_IS_DIR_TREE( tree_model ), G_TYPE_INVALID );
g_return_val_if_fail ( index < G_N_ELEMENTS( column_types ) && index >= 0, G_TYPE_INVALID );
return column_types[ index ];
}
static PtkDirTreeNode* get_nth_node( PtkDirTreeNode* parent, int n )
{
PtkDirTreeNode* node;
if ( n >= parent->n_children || n < 0 )
return NULL;
node = parent->children;
while( n > 0 && node )
{
node = node->next;
--n;
}
return node;
}
gboolean ptk_dir_tree_get_iter ( GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreePath *path )
{
PtkDirTree *tree;
gint *indices, i, depth;
PtkDirTreeNode* node;
g_assert(PTK_IS_DIR_TREE(tree_model));
g_assert(path!=NULL);
tree = PTK_DIR_TREE(tree_model);
if( !tree || !tree->root )
return FALSE;
indices = gtk_tree_path_get_indices(path);
depth = gtk_tree_path_get_depth(path);
node = tree->root;
for( i = 0; i < depth; ++i )
{
node = get_nth_node( node, indices[i] );
if( !node )
return FALSE;
}
/* We simply store a pointer in the iter */
iter->stamp = tree->stamp;
iter->user_data = node;
iter->user_data2 = NULL;
iter->user_data3 = NULL; /* unused */
return TRUE;
}
static int get_node_index( PtkDirTreeNode* parent, PtkDirTreeNode* child )
{
PtkDirTreeNode* node;
int i;
if( !parent || !child )
return -1;
for( i = 0, node = parent->children; node; node = node->next )
{
if( node == child )
{
return i;
}
++i;
}
return -1;
}
GtkTreePath *ptk_dir_tree_get_path ( GtkTreeModel *tree_model,
GtkTreeIter *iter )
{
PtkDirTreeNode* node;
GtkTreePath* path;
int i;
PtkDirTree* tree = PTK_DIR_TREE(tree_model);
g_return_val_if_fail (tree, NULL);
g_return_val_if_fail (iter->stamp == tree->stamp, NULL);
g_return_val_if_fail (iter != NULL, NULL);
g_return_val_if_fail (iter->user_data != NULL, NULL);
path = gtk_tree_path_new();
node = (PtkDirTreeNode*)iter->user_data;
g_return_val_if_fail( node->parent != NULL, (GtkTreePath *)(-1) );
while( node != tree->root )
{
i = get_node_index( node->parent, node );
if( i == -1 )
{
gtk_tree_path_free( path );
return NULL;
}
gtk_tree_path_prepend_index( path, i );
node = node->parent;
}
return path;
}
void ptk_dir_tree_get_value ( GtkTreeModel *tree_model,
GtkTreeIter *iter,
gint column,
GValue *value )
{
VFSFileInfo* info;
GdkPixbuf* icon;
PtkDirTreeNode* node;
g_return_if_fail (PTK_IS_DIR_TREE (tree_model));
g_return_if_fail (iter != NULL);
g_return_if_fail (column < G_N_ELEMENTS(column_types) );
g_value_init (value, column_types[column] );
node = (PtkDirTreeNode*) iter->user_data;
g_return_if_fail ( node != NULL );
info = node->file;
switch(column)
{
case COL_DIR_TREE_ICON:
if( G_UNLIKELY( !info ) )
return;
icon = vfs_file_info_get_small_icon( info );
if( icon )
{
g_value_set_object( value, icon );
g_object_unref( icon );
}
break;
case COL_DIR_TREE_DISP_NAME:
if( G_LIKELY( info ) )
g_value_set_string( value, vfs_file_info_get_disp_name(info) );
else
g_value_set_string( value, _("( no subfolder )") ); // no sub folder
break;
case COL_DIR_TREE_INFO:
if( G_UNLIKELY( !info ) )
return;
g_value_set_pointer( value, vfs_file_info_ref( info ) );
break;
}
}
gboolean ptk_dir_tree_iter_next ( GtkTreeModel *tree_model,
GtkTreeIter *iter )
{
PtkDirTreeNode* node;
PtkDirTree* tree;
g_return_val_if_fail (PTK_IS_DIR_TREE (tree_model), FALSE);
if (iter == NULL || iter->user_data == NULL)
return FALSE;
tree = PTK_DIR_TREE(tree_model);
node = (PtkDirTreeNode *) iter->user_data;
/* Is this the last child in the parent node? */
if ( ! node->next )
return FALSE;
iter->stamp = tree->stamp;
iter->user_data = node->next;
iter->user_data2 = NULL;
iter->user_data3 = NULL;
return TRUE;
}
gboolean ptk_dir_tree_iter_children ( GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreeIter *parent )
{
PtkDirTree* tree;
PtkDirTreeNode* parent_node;
g_return_val_if_fail ( parent == NULL || parent->user_data != NULL, FALSE );
g_return_val_if_fail ( PTK_IS_DIR_TREE ( tree_model ), FALSE );
tree = PTK_DIR_TREE( tree_model );
if ( parent )
parent_node = (PtkDirTreeNode*)parent->user_data;
else
{
/* parent == NULL is a special case; we need to return the first top-level row */
parent_node = tree->root;
}
/* No rows => no first row */
if ( parent_node->n_children == 0 )
return FALSE;
/* Set iter to first item in tree */
iter->stamp = tree->stamp;
iter->user_data = parent_node->children;
iter->user_data2 = iter->user_data3 = NULL;
return TRUE;
}
gboolean ptk_dir_tree_iter_has_child ( GtkTreeModel *tree_model,
GtkTreeIter *iter )
{
PtkDirTreeNode* node;
g_return_val_if_fail( iter != NULL, FALSE );
node = (PtkDirTreeNode*)iter->user_data;
return node->n_children != 0;
}
gint ptk_dir_tree_iter_n_children ( GtkTreeModel *tree_model,
GtkTreeIter *iter )
{
PtkDirTreeNode* node;
PtkDirTree* tree;
g_return_val_if_fail ( PTK_IS_DIR_TREE ( tree_model ), -1 );
tree = PTK_DIR_TREE( tree_model );
/* special case: if iter == NULL, return number of top-level rows */
if ( !iter )
node = tree->root;
else
node = (PtkDirTreeNode*)iter->user_data;
g_return_val_if_fail ( node != NULL, -1 );
return node->n_children;
}
gboolean ptk_dir_tree_iter_nth_child ( GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreeIter *parent,
gint n )
{
PtkDirTreeNode* parent_node;
PtkDirTreeNode* node;
PtkDirTree* tree;
g_return_val_if_fail (PTK_IS_DIR_TREE (tree_model), FALSE);
tree = PTK_DIR_TREE(tree_model);
if( G_LIKELY(parent) )
{
parent_node = ( PtkDirTreeNode* )parent->user_data;
g_return_val_if_fail( parent_node, FALSE );
}
else
{
/* special case: if parent == NULL, set iter to n-th top-level row */
parent_node = tree->root;
}
if( n >= parent_node->n_children || n < 0 )
return FALSE;
node = get_nth_node( parent_node, n );
iter->stamp = tree->stamp;
iter->user_data = node;
iter->user_data2 = iter->user_data3 = NULL;
return TRUE;
}
gboolean ptk_dir_tree_iter_parent ( GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreeIter *child )
{
PtkDirTreeNode* node;
PtkDirTree* tree;
g_return_val_if_fail( iter != NULL && child != NULL, FALSE );
tree = PTK_DIR_TREE( tree_model );
node = (PtkDirTreeNode*)child->user_data;
if( G_LIKELY( node->parent != tree->root ) )
{
iter->user_data = node->parent;
iter->user_data2 = iter->user_data3 = NULL;
return TRUE;
}
return FALSE;
}
gint ptk_dir_tree_node_compare( PtkDirTree* tree,
PtkDirTreeNode* a,
PtkDirTreeNode* b )
{
VFSFileInfo* file1 = a->file;
VFSFileInfo* file2 = b->file;
int ret;
if( ! file1 || !file2 )
return 0;
/* FIXME: UTF-8 strings should not be treated as ASCII when sorted */
ret = g_ascii_strcasecmp( vfs_file_info_get_disp_name(file2),
vfs_file_info_get_disp_name(file1) );
return ret;
}
PtkDirTreeNode* ptk_dir_tree_node_new( PtkDirTree* tree,
PtkDirTreeNode* parent,
const char* path,
const char* base_name )
{
PtkDirTreeNode* node;
node = g_slice_new0( PtkDirTreeNode );
node->tree = tree;
node->parent = parent;
if( path )
{
node->file = vfs_file_info_new();
vfs_file_info_get( node->file, path, base_name );
node->n_children = 1;
node->children = ptk_dir_tree_node_new( tree, node, NULL, NULL );
node->last = node->children;
}
return node;
}
void ptk_dir_tree_node_free( PtkDirTreeNode* node )
{
PtkDirTreeNode* child;
if( node->file )
vfs_file_info_unref( node->file );
for( child = node->children; child; child = child->next )
ptk_dir_tree_node_free( child );
if( node->monitor )
{
vfs_file_monitor_remove( node->monitor,
&on_file_monitor_event,
node );
}
g_slice_free( PtkDirTreeNode, node );
}
static char* dir_path_from_tree_node( PtkDirTree* tree, PtkDirTreeNode* node )
{
GSList* names = NULL, *l;
const char* name;
int len;
char* dir_path, *p;
if( !node )
return NULL;
while( node != tree->root )
{
if( !node->file || ! (name = vfs_file_info_get_name( node->file )) )
{
g_slist_free( names );
return NULL;
}
names = g_slist_prepend( names, (gpointer) name );
node = node->parent;
}
for( len = 1, l = names; l; l = l->next )
len += strlen((char*)l->data) + 1;
dir_path = g_malloc( len );
for( p = dir_path, l = names; l; l = l->next )
{
name = (char*)l->data;
len = strlen( name );
memcpy( p, name, len * sizeof(char) );
p += len;
if( l->next && strcmp( name, "/" ) )
{
*p = '/';
++p;
}
}
*p = '\0';
g_slist_free( names );
return dir_path;
}
void ptk_dir_tree_insert_child( PtkDirTree* tree,
PtkDirTreeNode* parent,
const char* file_path,
const char* name )
{
PtkDirTreeNode *child_node;
PtkDirTreeNode *node;
GtkTreeIter it;
GtkTreePath* tree_path;
child_node = ptk_dir_tree_node_new( tree, parent, file_path, name );
for( node = parent->children; node; node = node->next )
{
if( ptk_dir_tree_node_compare( tree, child_node, node ) >= 0 )
break;
}
if( node )
{
if( node->prev )
{
child_node->prev = node->prev;
node->prev->next = child_node;
}
child_node->next = node;
if( node == parent->children )
parent->children = child_node;
node->prev = child_node;
}
else
{
if( parent->children )
{
child_node->prev = parent->last;
parent->last->next = child_node;
parent->last = child_node;
}
else
{
parent->children = parent->last = child_node;
}
}
++parent->n_children;
it.stamp = tree->stamp;
it.user_data = child_node;
it.user_data2 = it.user_data3 = NULL;
tree_path = ptk_dir_tree_get_path( GTK_TREE_MODEL(tree), &it );
gtk_tree_model_row_inserted( GTK_TREE_MODEL(tree), tree_path, &it );
gtk_tree_model_row_has_child_toggled( GTK_TREE_MODEL(tree), tree_path, &it );
gtk_tree_path_free( tree_path );
}
void ptk_dir_tree_delete_child( PtkDirTree* tree,
PtkDirTreeNode* child )
{
GtkTreeIter child_it;
GtkTreePath* tree_path;
PtkDirTreeNode* parent;
if( !child )
return;
child_it.stamp = tree->stamp;
child_it.user_data = child;
child_it.user_data2 = child_it.user_data3 = NULL;
tree_path = ptk_dir_tree_get_path( GTK_TREE_MODEL(tree), &child_it );
gtk_tree_model_row_deleted( GTK_TREE_MODEL(tree), tree_path );
gtk_tree_path_free( tree_path );
parent = child->parent;
--parent->n_children;
if( child == parent->children )
parent->children = parent->last = child->next;
else if( child == parent->last )
parent->last = child->prev;
if( child->prev )
child->prev->next = child->next;
if( child->next )
child->next->prev = child->prev;
ptk_dir_tree_node_free( child );
if( parent->n_children == 0 )
{
/* add place holder */
ptk_dir_tree_insert_child( tree, parent, NULL,NULL );
}
}
void ptk_dir_tree_expand_row ( PtkDirTree* tree,
GtkTreeIter* iter,
GtkTreePath *tree_path )
{
PtkDirTreeNode *node, *place_holder;
GDir *dir;
char *path, *file_path;
const char *name=NULL;
node = (PtkDirTreeNode*)iter->user_data;
++node->n_expand;
if( node->n_expand > 1 || node->n_children > 1 )
return;
place_holder = node->children;
path = dir_path_from_tree_node( tree, node );
dir = g_dir_open( path, 0, NULL );
if( dir )
{
node->monitor = vfs_file_monitor_add_dir( path,
&on_file_monitor_event,
node );
while( (name = g_dir_read_name( dir )) )
{
file_path = g_build_filename( path, name, NULL );
if( g_file_test( file_path, G_FILE_TEST_IS_DIR ) )
{
ptk_dir_tree_insert_child( tree, node, file_path, name );
}
g_free( file_path );
}
g_dir_close( dir );
if( node->n_children > 1 )
{
ptk_dir_tree_delete_child( tree, place_holder );
}
}
g_free( path );
}
void ptk_dir_tree_collapse_row ( PtkDirTree* tree,
GtkTreeIter* iter,
GtkTreePath *path )
{
PtkDirTreeNode *node, *child, *next;
node = (PtkDirTreeNode*)iter->user_data;
--node->n_expand;
/* cache nodes containing more than 128 children */
/* FIXME: Is this useful? The nodes containing childrens
with 128+ children are still not cached. */
if( node->n_children > 128 || node->n_expand > 0 )
return;
if( node->n_children > 0 )
{
/* place holder */
if( node->n_children == 1 && ! node->children->file )
return;
if( G_LIKELY( node->monitor ) )
{
vfs_file_monitor_remove( node->monitor,
&on_file_monitor_event,
node );
node->monitor = NULL;
}
for( child = node->children; child; child = next )
{
next = child->next;
ptk_dir_tree_delete_child( tree, child );
}
}
}
char* ptk_dir_tree_get_dir_path( PtkDirTree* tree, GtkTreeIter* iter )
{
g_return_val_if_fail( iter->user_data != NULL, NULL );
return dir_path_from_tree_node( tree, (PtkDirTreeNode*)iter->user_data );
}
static PtkDirTreeNode* find_node( PtkDirTreeNode* parent, const char* name )
{
PtkDirTreeNode* child;
for( child = parent->children; child; child = child->next )
{
if( G_LIKELY(child->file )
&& 0 == strcmp( vfs_file_info_get_name(child->file), name ) )
{
return child;
}
}
return NULL;
}
void on_file_monitor_event ( VFSFileMonitor* fm,
VFSFileMonitorEvent event,
const char* file_name,
gpointer user_data )
{
PtkDirTreeNode* node = (PtkDirTreeNode*)user_data;
PtkDirTreeNode* child;
GtkTreeIter it;
GtkTreePath* tree_path;
char* file_path;
g_return_if_fail( node );
GDK_THREADS_ENTER();
child = find_node( node, file_name );
switch( event )
{
case VFS_FILE_MONITOR_CREATE:
if( G_LIKELY( !child ) )
{
/* remove place holder */
if( node->n_children == 1 && !node->children->file )
child = node->children;
else
child = NULL;
file_path = g_build_filename( fm->path, file_name, NULL );
if( g_file_test( file_path, G_FILE_TEST_IS_DIR ) )
{
ptk_dir_tree_insert_child( node->tree,
node, fm->path,
file_name );
if( child )
ptk_dir_tree_delete_child( node->tree, child );
}
g_free( file_path );
}
break;
case VFS_FILE_MONITOR_DELETE:
if( G_LIKELY( child ) )
{
ptk_dir_tree_delete_child( node->tree, child );
}
break;
/* //MOD Change isn't needed? Creates this warning and triggers subsequent
* errors and causes visible redrawing problems:
Gtk-CRITICAL **: /tmp/buildd/gtk+2.0-2.24.3/gtk/gtktreeview.c:6072 (validate_visible_area): assertion `has_next' failed.
There is a disparity between the internal view of the GtkTreeView,
and the GtkTreeModel. This generally means that the model has changed
without letting the view know. Any display from now on is likely to
be incorrect.
*/
case VFS_FILE_MONITOR_CHANGE:
/* if( G_LIKELY( child && child->file ) )
{
file_path = g_build_filename( fm->path, file_name, NULL );
if( ! g_file_test( file_path, G_FILE_TEST_IS_DIR ) )
{
g_free( file_path );
break;
}
vfs_file_info_get( child->file, file_path, file_name );
g_free( file_path );
it.stamp = node->tree->stamp;
it.user_data = child;
it.user_data2 = it.user_data3 = NULL;
tree_path = ptk_dir_tree_get_path(GTK_TREE_MODEL(node->tree), &it);
gtk_tree_model_row_changed( GTK_TREE_MODEL( node->tree ),
tree_path, &it );
gtk_tree_model_row_has_child_toggled( GTK_TREE_MODEL( node->tree ),
tree_path, &it );
gtk_tree_path_free( tree_path );
}
*/
break;
}
GDK_THREADS_LEAVE();
}
|
181 | ./spacefm/src/ptk/ptk-bookmarks.c | /*
* C Implementation: ptkbookmarks
*
* Description:
*
*
* Author: Hong Jen Yee (PCMan) <pcman.tw (AT) gmail.com>, (C) 2006
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#include "ptk-bookmarks.h"
#include "vfs-file-monitor.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <gtk/gtk.h>
#include "settings.h"
const char bookmarks_file_name[] = "bookmarks";
static PtkBookmarks bookmarks = {0};
static VFSFileMonitor* monitor = NULL;
typedef struct
{
GFunc callback;
gpointer user_data;
}
BookmarksCallback;
typedef struct unparsedLineO
{
int lineNum;
char *line;
} unparsedLine;
/**
* malloc a unparsedLine structure
*
* @ret return the pointer of newly allocate structure
*/
static unparsedLine* unparsedLine_new() {
unparsedLine* ret;
ret = (unparsedLine*) malloc(sizeof(unparsedLine));
if (ret!=NULL) {
memset(ret,0,sizeof(unparsedLine));
}
return ret;
}
/**
* free a unparsedLine structure
*
* @param data the pointer of the structure to be free
* @param user_data the pointer of a boolean value. If it's true, this
* function will also free the data->line. If it's NULL or
* false this function will only free the strcture.
*/
static void unparsedLine_delete( gpointer *data, gpointer *user_data) {
unparsedLine *d;
int *flag;
d = (unparsedLine*)(data);
flag = (int*)(user_data);
if (d!=NULL) {
if (flag && (*flag) && (d->line)) {
free(d->line);
d->line=NULL;
}
free(d);
}
}
/* Notify all callbacks that the bookmarks are changed. */
static void ptk_bookmarks_notify()
{
BookmarksCallback* cb;
int i;
/* Call the callback functions set by the user */
if( bookmarks.callbacks && bookmarks.callbacks->len )
{
cb = (BookmarksCallback*)bookmarks.callbacks->data;
for( i = 0; i < bookmarks.callbacks->len; ++i )
{
cb[i].callback( &bookmarks, cb[i].user_data );
}
}
}
static void load( const char* path )
{
FILE* file;
gchar* upath;
gchar* uri;
gchar* item;
gchar* name;
gchar* basename;
char line_buf[1024];
char *line=NULL;
int lineNum=0;
unparsedLine *unusedLine=NULL;
gsize name_len, upath_len;
file = fopen( path, "r" );
if( file )
{
for(lineNum=0; fgets( line_buf, sizeof(line_buf), file ); lineNum++)
{
/* Every line is an URI containing no space charactetrs
with its name appended (optional) */
line = strdup(line_buf);
uri = strtok( line, " \r\n" );
if( ! uri || !*uri )
{
unusedLine = unparsedLine_new();
unusedLine->lineNum = lineNum;
unusedLine->line = strdup(line_buf);
bookmarks.unparsedLines = g_list_append(
bookmarks.unparsedLines, unusedLine);
free(line);
line=NULL;
continue;
}
path = g_filename_from_uri(uri, NULL, NULL);
if( path )
{
upath = g_filename_to_utf8(path, -1, NULL, &upath_len, NULL);
g_free( (gpointer) path );
if( upath )
{
name = strtok( NULL, "\r\n" );
if( name )
{
name_len = strlen( name );
basename = NULL;
}
else
{
name = basename = g_path_get_basename( upath );
name_len = strlen( basename );
}
item = ptk_bookmarks_item_new( name, name_len,
upath, upath_len );
bookmarks.list = g_list_append( bookmarks.list,
item );
g_free(upath);
g_free( basename );
}
}
else if ( g_str_has_prefix( uri, "//" ) || strstr( uri, ":/" ) )
{
name = strtok( NULL, "\r\n" );
if( name )
{
name_len = strlen( name );
basename = NULL;
}
else
{
name = basename = g_strdup( uri );
name_len = strlen( basename );
}
item = ptk_bookmarks_item_new( name, name_len,
uri, strlen( uri ) );
bookmarks.list = g_list_append( bookmarks.list,
item );
g_free( basename );
}
else
{
unusedLine = unparsedLine_new();
unusedLine->lineNum = lineNum;
unusedLine->line = strdup(line_buf);
bookmarks.unparsedLines = g_list_append(
bookmarks.unparsedLines, unusedLine);
}
free(line);
line=NULL;
}
fclose( file );
}
}
static void on_bookmark_file_changed( VFSFileMonitor* fm,
VFSFileMonitorEvent event,
const char* file_name,
gpointer user_data )
{
/* This callback is called from IO channel handler insode VFSFileMonotor. */
GDK_THREADS_ENTER();
g_list_foreach( bookmarks.list, (GFunc)g_free, NULL );
g_list_free( bookmarks.list );
bookmarks.list = 0;
if (bookmarks.unparsedLines != NULL) {
int flag=1;
g_list_foreach( bookmarks.unparsedLines, (GFunc)unparsedLine_delete, &flag );
g_list_free(bookmarks.unparsedLines);
bookmarks.unparsedLines=NULL;
}
load( file_name );
ptk_bookmarks_notify();
GDK_THREADS_LEAVE();
}
/*
Get a self-maintained list of bookmarks
This is read from "~/.gtk-bookmarks".
*/
PtkBookmarks* ptk_bookmarks_get ()
{
gchar* path;
if( 0 == bookmarks.n_ref )
{
path = g_build_filename( xset_get_config_dir(), bookmarks_file_name, NULL );
//path = g_build_filename( g_get_home_dir(), bookmarks_file_name, NULL );
//monitor = vfs_file_monitor_add_file( path, on_bookmark_file_changed, NULL );
load( path );
g_free( path );
}
g_atomic_int_inc( &bookmarks.n_ref );
return &bookmarks;
}
/*
Replace the content of the bookmarks with new_list.
PtkBookmarks will then owns new_list, and hence
new_list shouldn't be freed after this function is called.
*/
void ptk_bookmarks_set ( GList* new_list )
{
g_list_foreach( bookmarks.list, (GFunc)g_free, NULL );
g_list_free( bookmarks.list );
bookmarks.list = new_list;
ptk_bookmarks_notify();
ptk_bookmarks_save();
}
/* Insert an item into bookmarks */
void ptk_bookmarks_insert ( const char* name, const char* path, gint pos )
{
char* item;
item = ptk_bookmarks_item_new(name, strlen(name), path, strlen(path));
bookmarks.list = g_list_insert( bookmarks.list,
item, pos );
ptk_bookmarks_notify();
ptk_bookmarks_save();
}
/* Append an item into bookmarks */
void ptk_bookmarks_append ( const char* name, const char* path )
{
char* item;
item = ptk_bookmarks_item_new(name, strlen(name), path, strlen(path));
bookmarks.list = g_list_append( bookmarks.list,
item );
ptk_bookmarks_notify();
ptk_bookmarks_save();
}
/* find an item from bookmarks */
static GList* find_item( const char* path )
{
GList* l;
char* item;
char* item_path;
int len;
for( l = bookmarks.list; l; l = l->next )
{
item = (char*)l->data;
len = strlen( item );
item_path = item + len + 1;
if( 0 == strcmp( path, item_path ) )
break;
}
return l;
}
void ptk_bookmarks_change( const char* path, const char* new_path )
{
GList* l;
char* item;
char* item_path;
int len;
int pos = 0;
for( l = bookmarks.list; l; l = l->next )
{
item = (char*)l->data;
len = strlen( item );
item_path = item + len + 1;
if( 0 == strcmp( path, item_path ) )
break;
pos++;
}
if ( l )
{
char* name = g_strdup( item );
ptk_bookmarks_remove( path );
ptk_bookmarks_insert( name, new_path, pos );
ptk_bookmarks_notify();
ptk_bookmarks_save();
g_free( name );
}
}
void ptk_bookmarks_remove ( const char* path )
{
GList* l;
if( (l = find_item( path )) )
{
g_free( l->data );
bookmarks.list = g_list_delete_link( bookmarks.list, l );
ptk_bookmarks_notify();
ptk_bookmarks_save();
}
}
void ptk_bookmarks_rename ( const char* path, const char* new_name )
{
GList* l;
char* item;
if( path && new_name && (l = find_item( path )) )
{
item = ptk_bookmarks_item_new(new_name, strlen(new_name),
path, strlen(path));
g_free( l->data );
l->data = item;
ptk_bookmarks_notify();
ptk_bookmarks_save();
}
}
static void ptk_bookmarks_save_item( GList* l, FILE* file )
{
gchar* item;
const gchar* upath;
char* uri;
char* path;
item = (char*)l->data;
upath = ptk_bookmarks_item_get_path( item );
path = g_filename_from_utf8( upath, -1, NULL, NULL, NULL );
if( path )
{
uri = g_filename_to_uri( path, NULL, NULL );
if( uri )
{
fprintf( file, "%s %s\n", uri, item );
g_free( uri );
}
else if ( g_str_has_prefix( path, "//" ) || strstr( path, ":/" ) )
fprintf( file, "%s %s\n", path, item );
g_free( path );
}
}
void ptk_bookmarks_save ()
{
FILE* file;
gchar* path;
GList* l;
GList* ul;
int lineNum=0;
path = g_build_filename( xset_get_config_dir(), bookmarks_file_name, NULL );
//path = g_build_filename( g_get_home_dir(), bookmarks_file_name, NULL );
file = fopen( path, "w" );
g_free( path );
if( file )
{
lineNum=0;
ul = bookmarks.unparsedLines;
for( l = bookmarks.list; l; l = l->next )
{
while (ul != NULL && ul->data != NULL
&& ((unparsedLine*)ul->data)->lineNum==lineNum) {
fputs(((unparsedLine*)ul->data)->line,file);
lineNum++;
ul = g_list_next(ul);
}
ptk_bookmarks_save_item( l, file );
lineNum++;
}
while (ul != NULL && ul->data != NULL) {
fputs(((unparsedLine*)ul->data)->line,file);
lineNum++;
ul = g_list_next(ul);
}
fclose( file );
}
}
/* Add a callback which gets called when the content of bookmarks changed */
void ptk_bookmarks_add_callback ( GFunc callback, gpointer user_data )
{
BookmarksCallback cb;
cb.callback = callback;
cb.user_data = user_data;
if( !bookmarks.callbacks )
{
bookmarks.callbacks = g_array_new (FALSE, FALSE, sizeof(BookmarksCallback));
}
bookmarks.callbacks = g_array_append_val( bookmarks.callbacks, cb );
}
/* Remove a callback added by ptk_bookmarks_add_callback */
void ptk_bookmarks_remove_callback ( GFunc callback, gpointer user_data )
{
BookmarksCallback* cb = (BookmarksCallback*)bookmarks.callbacks->data;
int i;
if( bookmarks.callbacks )
{
for(i = 0; i < bookmarks.callbacks->len; ++i )
{
if( cb[i].callback == callback && cb[i].user_data == user_data )
{
bookmarks.callbacks = g_array_remove_index_fast ( bookmarks.callbacks, i );
break;
}
}
}
}
void ptk_bookmarks_unref ()
{
if( g_atomic_int_dec_and_test(&bookmarks.n_ref) )
{
//vfs_file_monitor_remove( monitor, on_bookmark_file_changed, NULL );
monitor = NULL;
bookmarks.n_ref = 0;
if( bookmarks.list )
{
g_list_foreach( bookmarks.list, (GFunc)g_free, NULL );
g_list_free( bookmarks.list );
bookmarks.list = NULL;
}
if( bookmarks.callbacks )
{
g_array_free(bookmarks.callbacks, TRUE);
bookmarks.callbacks = NULL;
}
}
}
/*
* Create a new bookmark item.
* name: displayed name of the bookmark item.
* name_len: length of name;
* upath: dir path of the bookmark item encoded in UTF-8.
* upath_len: length of upath;
* Returned value is a newly allocated string.
*/
gchar* ptk_bookmarks_item_new( const gchar* name, gsize name_len,
const gchar* upath, gsize upath_len )
{
char* buf;
++name_len; /* include terminating null */
++upath_len; /* include terminating null */
buf = g_new( char, name_len + upath_len );
memcpy( buf, name, name_len );
memcpy( buf + name_len, upath, upath_len );
return buf;
}
/*
* item: bookmark item
* Returned value: dir path of the bookmark item. (int utf-8)
*/
const gchar* ptk_bookmarks_item_get_path( const gchar* item )
{
int name_len = strlen(item);
return (item + name_len + 1);
}
|
182 | ./spacefm/src/ptk/ptk-path-entry.c | /*
* C Implementation: ptk-path-entry
*
* Description: A custom entry widget with auto-completion
*
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#include "ptk-path-entry.h"
#include <gdk/gdkkeysyms.h>
#include "vfs-file-info.h" /* for vfs_file_resolve_path */
#include <string.h>
#include "settings.h"
#include "main-window.h"
#include <glib/gi18n.h>
#include "gtk2-compat.h"
static void on_changed( GtkEntry* entry, gpointer user_data );
enum
{
COL_NAME,
COL_PATH,
N_COLS
};
/*
static GQuark use_hand_cursor = (GQuark)"hand_cursor";
#define is_hand_cursor_used( entry ) (g_object_get_qdata(entry, use_hand_cursor))
*/
static char*
get_cwd( GtkEntry* entry )
{
const char* path = gtk_entry_get_text( entry );
if ( path[0] == '/' )
return g_path_get_dirname( path );
else if ( path[0] != '$' && path[0] != '+' && path[0] != '&'
&& path[0] != '!' && path[0] != '\0' && path[0] != ' ' )
{
EntryData* edata = (EntryData*)g_object_get_data(
G_OBJECT( entry ), "edata" );
if ( edata && edata->browser )
{
char* real_path = vfs_file_resolve_path( ptk_file_browser_get_cwd(
edata->browser ), path );
char* ret = g_path_get_dirname( real_path );
g_free( real_path );
return ret;
}
}
return NULL;
}
gboolean seek_path( GtkEntry* entry )
{
if ( !GTK_IS_ENTRY( entry ) )
return FALSE;
EntryData* edata = (EntryData*)g_object_get_data(
G_OBJECT( entry ), "edata" );
if ( !( edata && edata->browser ) )
return FALSE;
if ( edata->seek_timer )
{
g_source_remove( edata->seek_timer );
edata->seek_timer = 0;
}
if ( !xset_get_b( "path_seek" ) )
return FALSE;
char* str;
char* seek_dir;
char* seek_name = NULL;
char* full_path;
const char* path = gtk_entry_get_text( entry );
if ( !path || path[0] == '$' || path[0] == '+' || path[0] == '&'
|| path[0] == '!' || path[0] == '\0' || path[0] == ' '
|| path[0] == '%' )
return FALSE;
// get dir and name prefix
seek_dir = get_cwd( entry );
if ( !( seek_dir && g_file_test( seek_dir, G_FILE_TEST_IS_DIR ) ) )
{
// entry does not contain a valid dir
g_free( seek_dir );
return FALSE;
}
if ( !g_str_has_suffix( path, "/" ) )
{
// get name prefix
seek_name = g_path_get_basename( path );
char* test_path = g_build_filename( seek_dir, seek_name, NULL );
if ( g_file_test( test_path, G_FILE_TEST_IS_DIR ) )
{
// complete dir path is in entry - is it unique?
GDir* dir;
const char* name;
int count = 0;
if ( ( dir = g_dir_open( seek_dir, 0, NULL ) ) )
{
while ( count < 2 && ( name = g_dir_read_name( dir ) ) )
{
if ( g_str_has_prefix( name, seek_name ) )
{
full_path = g_build_filename( seek_dir, name, NULL );
if ( g_file_test( full_path, G_FILE_TEST_IS_DIR ) )
count++;
g_free( full_path );
}
}
g_dir_close( dir );
}
if ( count == 1 )
{
// is unique - use as seek dir
g_free( seek_dir );
seek_dir = test_path;
g_free( seek_name );
seek_name = NULL;
}
}
else
g_free( test_path );
}
/* this interferes with entering URLs in path bar
char* actual_path = g_build_filename( seek_dir, seek_name, NULL );
if ( strcmp( actual_path, "/" ) && g_str_has_suffix( path, "/" ) )
{
str = actual_path;
actual_path = g_strdup_printf( "%s/", str );
g_free( str );
}
if ( strcmp( path, actual_path ) )
{
// actual dir differs from entry - update
g_signal_handlers_block_matched( G_OBJECT( entry ),
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_changed, NULL );
gtk_entry_set_text( GTK_ENTRY( entry ), actual_path );
gtk_editable_set_position( (GtkEditable*)entry, -1 );
g_signal_handlers_unblock_matched( G_OBJECT( entry ),
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_changed, NULL );
}
g_free( actual_path );
*/
if ( strcmp( seek_dir, "/" ) && g_str_has_suffix( seek_dir, "/" ) )
{
// strip trialing slash
seek_dir[strlen( seek_dir ) - 1] = '\0';
}
ptk_file_browser_seek_path( edata->browser, seek_dir, seek_name );
g_free( seek_dir );
g_free( seek_name );
return FALSE;
}
void seek_path_delayed( GtkEntry* entry, guint delay )
{
EntryData* edata = (EntryData*)g_object_get_data(
G_OBJECT( entry ), "edata" );
if ( !( edata && edata->browser ) )
return;
// user is still typing - restart timer
if ( edata->seek_timer )
g_source_remove( edata->seek_timer );
edata->seek_timer = g_timeout_add( delay ? delay : 250,
( GSourceFunc )seek_path, entry );
}
static gboolean match_func_cmd( GtkEntryCompletion *completion,
const gchar *key,
GtkTreeIter *it,
gpointer user_data)
{
char* name = NULL;
GtkTreeModel* model = gtk_entry_completion_get_model(completion);
gtk_tree_model_get( model, it, COL_NAME, &name, -1 );
if ( name && key && g_str_has_prefix( name, key ) )
{
g_free( name );
return TRUE;
}
g_free( name );
return FALSE;
}
static gboolean match_func( GtkEntryCompletion *completion,
const gchar *key,
GtkTreeIter *it,
gpointer user_data)
{
char* name = NULL;
GtkTreeModel* model = gtk_entry_completion_get_model(completion);
key = (const char*)g_object_get_data( G_OBJECT(completion), "fn" );
gtk_tree_model_get( model, it, COL_NAME, &name, -1 );
if( G_LIKELY(name) )
{
if( *key == 0 || 0 == g_ascii_strncasecmp( name, key, strlen(key) ) )
{
g_free( name );
return TRUE;
}
g_free( name );
}
return FALSE;
}
static void update_completion( GtkEntry* entry,
GtkEntryCompletion* completion )
{
GtkListStore* list;
GtkTreeIter it;
const char* text = gtk_entry_get_text( entry );
if ( text && ( text[0] == '$' || text[0] == '+' || text[0] == '&'
|| text[0] == '!' || text[0] == '%' ||
( text[0] != '/' && strstr( text, ":/" ) ) ||
g_str_has_prefix( text, "//" ) ) )
{
// command history
GList* l;
list = (GtkListStore*)gtk_entry_completion_get_model( completion );
gtk_list_store_clear( list );
for ( l = xset_cmd_history; l; l = l->next )
{
gtk_list_store_append( list, &it );
gtk_list_store_set( list, &it, COL_NAME, (char*)l->data,
COL_PATH, (char*)l->data, -1 );
}
gtk_entry_completion_set_match_func( completion, match_func_cmd, NULL, NULL );
}
else
{
// dir completion
char* new_dir, *fn;
const char* old_dir;
const char *sep;
sep = strrchr( text, '/' );
if( sep )
fn = (char*)sep + 1;
else
fn = (char*)text;
g_object_set_data_full( G_OBJECT(completion), "fn", g_strdup(fn), (GDestroyNotify)g_free );
new_dir = get_cwd( entry );
old_dir = (const char*)g_object_get_data( (GObject*)completion, "cwd" );
if ( old_dir && new_dir && 0 == g_ascii_strcasecmp( old_dir, new_dir ) )
{
g_free( new_dir );
return;
}
g_object_set_data_full( (GObject*)completion, "cwd",
new_dir, g_free );
list = (GtkListStore*)gtk_entry_completion_get_model( completion );
gtk_list_store_clear( list );
if ( new_dir )
{
GDir* dir;
if( (dir = g_dir_open( new_dir, 0, NULL )) )
{
// build list of dir names
const char* name;
GSList* name_list = NULL;
while( (name = g_dir_read_name( dir )) )
{
char* full_path = g_build_filename( new_dir, name, NULL );
if( g_file_test( full_path, G_FILE_TEST_IS_DIR ) )
name_list = g_slist_prepend( name_list, full_path );
}
g_dir_close( dir );
// add sorted list to liststore
GSList* l;
char* disp_name;
name_list = g_slist_sort( name_list, (GCompareFunc)g_strcmp0 );
for ( l = name_list; l; l = l->next )
{
disp_name = g_filename_display_basename( (char*)l->data );
gtk_list_store_append( list, &it );
gtk_list_store_set( list, &it, COL_NAME, disp_name,
COL_PATH, (char*)l->data, -1 );
g_free( disp_name );
g_free( (char*)l->data );
}
g_slist_free( name_list );
gtk_entry_completion_set_match_func( completion, match_func, NULL, NULL );
}
else
gtk_entry_completion_set_match_func( completion, NULL, NULL, NULL );
}
}
}
static void
on_changed( GtkEntry* entry, gpointer user_data )
{
GtkEntryCompletion* completion;
completion = gtk_entry_get_completion( entry );
update_completion( entry, completion );
gtk_entry_completion_complete( gtk_entry_get_completion(GTK_ENTRY(entry)) );
seek_path_delayed( GTK_ENTRY( entry ), 0 );
}
void insert_complete( GtkEntry* entry )
{
// find a real completion
const char* prefix = gtk_entry_get_text( GTK_ENTRY( entry ) );
if ( !prefix )
return;
char* dir_path = get_cwd( entry );
if ( !( dir_path && g_file_test( dir_path, G_FILE_TEST_IS_DIR ) ) )
{
g_free( dir_path );
return;
}
// find longest common prefix
GDir* dir;
if ( !( dir = g_dir_open( dir_path, 0, NULL ) ) )
{
g_free( dir_path );
return;
}
int count = 0;
int len;
int long_len = 0;
int i;
const char* name;
char* last_path = NULL;
char* prefix_name;
char* full_path;
char* str;
char* long_prefix = NULL;
if ( g_str_has_suffix( prefix, "/" ) )
prefix_name = NULL;
else
prefix_name = g_path_get_basename( prefix );
while ( name = g_dir_read_name( dir ) )
{
full_path = g_build_filename( dir_path, name, NULL );
if ( g_file_test( full_path, G_FILE_TEST_IS_DIR ) )
{
if ( !prefix_name )
{
// full match
g_free( last_path );
last_path = full_path;
full_path = NULL;
if ( ++count > 1 )
break;
}
else if ( g_str_has_prefix( name, prefix_name ) )
{
// prefix matches
count++;
if ( !long_prefix )
long_prefix = g_strdup( name );
else
{
i = 0;
while ( name[i] && name[i] == long_prefix[i] )
i++;
if ( i && long_prefix[i] )
{
// shorter prefix found
g_free( long_prefix );
long_prefix = g_strndup( name, i );
}
}
}
}
g_free( full_path );
}
char* new_prefix = NULL;
if ( !prefix_name && count == 1 )
new_prefix = g_strdup_printf( "%s/", last_path );
else if ( long_prefix )
{
full_path = g_build_filename( dir_path, long_prefix, NULL );
if ( count == 1 && g_file_test( full_path, G_FILE_TEST_IS_DIR ) )
{
new_prefix = g_strdup_printf( "%s/", full_path );
g_free( full_path );
}
else
new_prefix = full_path;
g_free( long_prefix );
}
if ( new_prefix )
{
g_signal_handlers_block_matched( G_OBJECT( entry ),
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_changed, NULL );
gtk_entry_set_text( GTK_ENTRY( entry ), new_prefix );
gtk_editable_set_position( (GtkEditable*)entry, -1 );
g_signal_handlers_unblock_matched( G_OBJECT( entry ),
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_changed, NULL );
g_free( new_prefix );
}
g_dir_close( dir );
g_free( last_path );
g_free( prefix_name );
g_free( dir_path );
}
static gboolean
on_key_press( GtkWidget *entry, GdkEventKey* evt, EntryData* edata )
{
int keymod = ( evt->state & ( GDK_SHIFT_MASK | GDK_CONTROL_MASK |
GDK_MOD1_MASK | GDK_SUPER_MASK | GDK_HYPER_MASK | GDK_META_MASK ) );
if( evt->keyval == GDK_KEY_Tab && !keymod )
{
//gtk_entry_completion_insert_prefix( gtk_entry_get_completion(GTK_ENTRY(entry)) );
//gtk_editable_set_position( (GtkEditable*)entry, -1 );
/*
g_signal_handlers_block_matched( G_OBJECT( entry ),
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_changed, NULL );
gtk_entry_completion_insert_prefix( gtk_entry_get_completion(GTK_ENTRY(entry)) );
const char* path = gtk_entry_get_text( GTK_ENTRY( entry ) );
if ( path && path[0] && !g_str_has_suffix( path, "/" ) &&
g_file_test( path, G_FILE_TEST_IS_DIR ) )
{
char* new_path = g_strdup_printf( "%s/", path );
gtk_entry_set_text( GTK_ENTRY( entry ), new_path );
g_free( new_path );
}
gtk_editable_set_position( (GtkEditable*)entry, -1 );
g_signal_handlers_unblock_matched( G_OBJECT( entry ),
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_changed, NULL );
on_changed( GTK_ENTRY( entry ), NULL );
*/
insert_complete( GTK_ENTRY( entry ) );
on_changed( GTK_ENTRY( entry ), NULL );
seek_path_delayed( GTK_ENTRY( entry ), 10 );
return TRUE;
}
else if ( evt->keyval == GDK_KEY_BackSpace && keymod == 1 ) // shift
{
gtk_entry_set_text( GTK_ENTRY( entry ), "" );
return TRUE;
}
return FALSE;
}
gboolean on_insert_prefix( GtkEntryCompletion *completion,
gchar *prefix,
GtkWidget *entry )
{
// don't use the default handler because it inserts partial names
return TRUE;
}
gboolean on_match_selected( GtkEntryCompletion *completion,
GtkTreeModel *model,
GtkTreeIter *iter,
GtkWidget *entry )
{
char* path = NULL;
gtk_tree_model_get( model, iter, COL_PATH, &path, -1 );
if ( path && path[0] )
{
g_signal_handlers_block_matched( G_OBJECT( entry ),
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_changed, NULL );
gtk_entry_set_text( GTK_ENTRY( entry ), path );
g_free( path );
gtk_editable_set_position( (GtkEditable*)entry, -1 );
g_signal_handlers_unblock_matched( G_OBJECT( entry ),
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_changed, NULL );
on_changed( GTK_ENTRY( entry ), NULL );
seek_path_delayed( GTK_ENTRY( entry ), 10 );
}
return TRUE;
}
#if 0
gboolean on_match_selected( GtkEntryCompletion *completion,
GtkTreeModel *model,
GtkTreeIter *iter,
GtkWidget *entry )
{
char* path = NULL;
gtk_tree_model_get( model, iter, COL_PATH, &path, -1 );
if ( path && path[0] && !g_str_has_suffix( path, "/" ) )
{
g_signal_handlers_block_matched( G_OBJECT( entry ),
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_changed, NULL );
char* new_path = g_strdup_printf( "%s/", path );
gtk_entry_set_text( GTK_ENTRY( entry ), new_path );
g_free( new_path );
g_free( path );
gtk_editable_set_position( (GtkEditable*)entry, -1 );
g_signal_handlers_unblock_matched( G_OBJECT( entry ),
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_changed, NULL );
on_changed( GTK_ENTRY( entry ), NULL );
return TRUE;
}
return FALSE;
}
#endif
static gboolean
on_focus_in( GtkWidget *entry, GdkEventFocus* evt, gpointer user_data )
{
GtkEntryCompletion* completion = gtk_entry_completion_new();
GtkListStore* list = gtk_list_store_new( N_COLS, G_TYPE_STRING, G_TYPE_STRING );
GtkCellRenderer* render;
gtk_entry_completion_set_minimum_key_length( completion, 1 );
gtk_entry_completion_set_model( completion, GTK_TREE_MODEL(list) );
g_object_unref( list );
/* gtk_entry_completion_set_text_column( completion, COL_PATH ); */
// Following line causes GTK3 to show both columns, so skip this and use
// custom match-selected handler to insert COL_PATH
//g_object_set( completion, "text-column", COL_PATH, NULL );
render = gtk_cell_renderer_text_new();
gtk_cell_layout_pack_start( (GtkCellLayout*)completion, render, TRUE );
gtk_cell_layout_add_attribute( (GtkCellLayout*)completion, render, "text", COL_NAME );
//gtk_entry_completion_set_inline_completion( completion, TRUE );
gtk_entry_completion_set_popup_set_width( completion, TRUE );
gtk_entry_set_completion( GTK_ENTRY(entry), completion );
g_signal_connect( G_OBJECT(entry), "changed", G_CALLBACK(on_changed), NULL );
g_signal_connect( G_OBJECT( completion ), "match-selected",
G_CALLBACK( on_match_selected ), entry );
g_signal_connect( G_OBJECT( completion ), "insert-prefix",
G_CALLBACK( on_insert_prefix ), entry );
g_object_unref( completion );
return FALSE;
}
static gboolean
on_focus_out( GtkWidget *entry, GdkEventFocus* evt, gpointer user_data )
{
g_signal_handlers_disconnect_by_func( entry, on_changed, NULL );
gtk_entry_set_completion( GTK_ENTRY(entry), NULL );
return FALSE;
}
#if 0
/* Weird! We cannot change the cursor of GtkEntry... */
static gboolean on_mouse_move(GtkWidget *entry,
GdkEventMotion *evt,
gpointer user_data)
{
if( evt->state == GDK_CONTROL_MASK )
{
if( ! is_hand_cursor_used( entry ) )
{
GdkCursor* hand = gdk_cursor_new_for_display( gtk_widget_get_display(entry), GDK_HAND2 );
gdk_window_set_cursor( entry->window, hand );
gdk_cursor_unref( hand );
g_object_set_qdata( entry, use_hand_cursor, (gpointer)TRUE );
g_debug( "SET" );
}
return TRUE;
}
else
{
if( is_hand_cursor_used( entry ) )
{
gdk_window_set_cursor( entry->window, NULL );
g_object_set_qdata( entry, use_hand_cursor, (gpointer)FALSE );
g_debug( "UNSET" );
}
}
return FALSE;
}
#endif
void ptk_path_entry_man( GtkWidget* widget, GtkWidget* parent )
{
xset_show_help( parent, NULL, "#gui-pathbar" );
}
void ptk_path_entry_help( GtkWidget* widget, GtkWidget* parent )
{
GtkWidget* parent_win = gtk_widget_get_toplevel( GTK_WIDGET( parent ) );
GtkWidget* dlg = gtk_message_dialog_new( GTK_WINDOW( parent_win ),
GTK_DIALOG_MODAL,
GTK_MESSAGE_INFO,
GTK_BUTTONS_OK,
_("In addition to a folder or file path, commands can be entered in the Path Bar. Prefixes:\n\t$\trun as task\n\t&\trun and forget\n\t+\trun in terminal\n\t!\trun as root\nUse:\n\t%%F\tselected files or %%f first selected file\n\t%%N\tselected filenames or %%n first selected filename\n\t%%d\tcurrent directory\n\t%%v\tselected device (eg /dev/sda1)\n\t%%m\tdevice mount point (eg /media/dvd); %%l device label\n\t%%b\tselected bookmark\n\t%%t\tselected task directory; %%p task pid\n\t%%a\tmenu item value\n\t$fm_panel, $fm_tab, $fm_command, etc\n\nExample: $ echo \"Current Directory: %%d\"\nExample: +! umount %%v") );
gtk_window_set_title( GTK_WINDOW( dlg ), "Path Bar Help" );
gtk_dialog_run( GTK_DIALOG( dlg ) );
gtk_widget_destroy( dlg );
}
static gboolean on_button_press( GtkWidget* entry, GdkEventButton *evt,
gpointer user_data )
{
if ( ( evt_win_click->s || evt_win_click->ob2_data ) &&
main_window_event( NULL, evt_win_click, "evt_win_click", 0, 0, "pathbar", 0,
evt->button, evt->state, TRUE ) )
return TRUE;
return FALSE;
}
static gboolean on_button_release( GtkEntry *entry,
GdkEventButton *evt,
gpointer user_data )
{
if ( GDK_BUTTON_RELEASE != evt->type )
return FALSE;
if ( 1 == evt->button && ( evt->state & GDK_CONTROL_MASK ) )
{
int pos;
const char *text, *sep;
char *path;
text = gtk_entry_get_text( entry );
if ( !( text[0] == '$' || text[0] == '+' || text[0] == '&'
|| text[0] == '!' || text[0] == '%' || text[0] == '\0' ) )
{
pos = gtk_editable_get_position( GTK_EDITABLE( entry ) );
if( G_LIKELY( text && *text ) )
{
sep = g_utf8_offset_to_pointer( text, pos );
if( G_LIKELY( sep ) )
{
while( *sep && *sep != '/' )
sep = g_utf8_next_char(sep);
if( G_UNLIKELY( sep == text ) )
{
if( '/' == *sep )
++sep;
else
return FALSE;
}
path = g_strndup( text, (sep - text) );
gtk_entry_set_text( entry, path );
gtk_editable_set_position( (GtkEditable*)entry, -1 );
g_free( path );
gtk_widget_activate( (GtkWidget*)entry );
}
}
}
}
return FALSE;
}
void on_populate_popup( GtkEntry *entry, GtkMenu *menu, PtkFileBrowser* file_browser )
{
if ( !file_browser )
return;
XSetContext* context = xset_context_new();
main_context_fill( file_browser, context );
GtkAccelGroup* accel_group = gtk_accel_group_new();
XSet* set = xset_get( "sep_entry" );
xset_add_menuitem( NULL, file_browser, GTK_WIDGET( menu ), accel_group, set );
set = xset_get( "path_seek" );
xset_add_menuitem( NULL, file_browser, GTK_WIDGET( menu ), accel_group, set );
set = xset_get( "path_hand" );
xset_add_menuitem( NULL, file_browser, GTK_WIDGET( menu ), accel_group, set );
set = xset_set_cb_panel( file_browser->mypanel, "font_path", main_update_fonts, file_browser );
xset_add_menuitem( NULL, file_browser, GTK_WIDGET( menu ), accel_group, set );
set = xset_set_cb( "path_help", ptk_path_entry_man, file_browser );
xset_add_menuitem( NULL, file_browser, GTK_WIDGET( menu ), accel_group, set );
gtk_widget_show_all( GTK_WIDGET( menu ) );
g_signal_connect( menu, "key-press-event",
G_CALLBACK( xset_menu_keypress ), NULL );
}
void on_entry_insert( GtkEntryBuffer *buf, guint position, gchar *chars,
guint n_chars, gpointer user_data )
{
char* new_text = NULL;
const char* text = gtk_entry_buffer_get_text( buf );
if ( !text )
return;
if ( strchr( text, '\n' ) )
{
// remove linefeeds from pasted text
text = new_text = replace_string( text, "\n", "", FALSE );
}
// remove leading spaces for test
while ( text[0] == ' ' )
text++;
if ( text[0] == '\'' && g_str_has_suffix( text, "'" ) && text[1] != '\0' )
{
// path is quoted - assume bash quote
char* unquote = g_strdup( text + 1 );
unquote[strlen( unquote ) - 1] = '\0';
g_free( new_text );
new_text = replace_string( unquote, "'\\''", "'", FALSE );
g_free( unquote );
}
if ( new_text )
{
gtk_entry_buffer_set_text( buf, new_text, -1 );
g_free( new_text );
}
}
void entry_data_free( EntryData* edata )
{
g_slice_free( EntryData, edata );
}
GtkWidget* ptk_path_entry_new( PtkFileBrowser* file_browser )
{
GtkWidget* entry = gtk_entry_new();
gtk_entry_set_has_frame( GTK_ENTRY( entry ), TRUE );
// set font
if ( file_browser->mypanel > 0 && file_browser->mypanel < 5 &&
xset_get_s_panel( file_browser->mypanel, "font_path" ) )
{
PangoFontDescription* font_desc = pango_font_description_from_string(
xset_get_s_panel( file_browser->mypanel, "font_path" ) );
gtk_widget_modify_font( entry, font_desc );
pango_font_description_free( font_desc );
}
EntryData* edata = g_slice_new0( EntryData );
edata->browser = file_browser;
edata->seek_timer = 0;
g_signal_connect( entry, "focus-in-event", G_CALLBACK(on_focus_in), NULL );
g_signal_connect( entry, "focus-out-event", G_CALLBACK(on_focus_out), NULL );
/* used to eat the tab key */
g_signal_connect( entry, "key-press-event", G_CALLBACK(on_key_press), edata );
/*
g_signal_connect( entry, "motion-notify-event", G_CALLBACK(on_mouse_move), NULL );
*/
g_signal_connect( entry, "button-press-event", G_CALLBACK(on_button_press),
NULL );
g_signal_connect( entry, "button-release-event", G_CALLBACK(on_button_release), NULL );
g_signal_connect( entry, "populate-popup", G_CALLBACK(on_populate_popup), file_browser );
g_signal_connect_after( G_OBJECT( gtk_entry_get_buffer( GTK_ENTRY( entry ) ) ),
"inserted-text",
G_CALLBACK( on_entry_insert ), NULL );
g_object_weak_ref( G_OBJECT( entry ), (GWeakNotify) entry_data_free, edata );
g_object_set_data( G_OBJECT( entry ), "edata", edata );
return entry;
}
|
183 | ./spacefm/src/ptk/ptk-file-archiver.c | /*
* C Implementation: ptk-file-archiver
*
* Description:
*
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#include <glib/gi18n.h>
#include <string.h>
#include "ptk-file-archiver.h"
#include "ptk-console-output.h"
#include "ptk-file-task.h"
#include "vfs-file-info.h"
#include "vfs-mime-type.h"
#include "settings.h"
#include "gtk2-compat.h"
typedef struct _ArchiveHandler
{
const char* mime_type;
const char* compress_cmd;
const char* extract_cmd;
const char* list_cmd;
const char* file_ext;
const char* name;
gboolean multiple_files;
}
ArchiveHandler;
const ArchiveHandler handlers[]=
{
{
"application/x-bzip-compressed-tar",
"tar %o -cvjf",
"tar -xvjf",
"tar -tvf",
".tar.bz2", "arc_tar_bz2", TRUE
},
{
"application/x-compressed-tar",
"tar %o -cvzf",
"tar -xvzf",
"tar -tvf",
".tar.gz", "arc_tar_gz", TRUE
},
{
"application/x-xz-compressed-tar", //MOD added
"tar %o -cvJf",
"tar -xvJf",
"tar -tvf",
".tar.xz", "arc_tar_xz", TRUE
},
{
"application/zip",
"zip %o -r",
"unzip",
"unzip -l",
".zip", "arc_zip", TRUE
},
{
"application/x-7z-compressed",
"7za %o a", // hack - also uses 7zr if available
"7za x",
"7za l",
".7z", "arc_7z", TRUE
},
{
"application/x-tar",
"tar %o -cvf",
"tar -xvf",
"tar -tvf",
".tar", "arc_tar", TRUE
},
{
"application/x-rar",
"rar a -r %o",
"unrar -o- x",
"unrar lt",
".rar", "arc_rar", TRUE
},
{
"application/x-gzip",
NULL,
"gunzip",
NULL,
".gz", NULL, TRUE
}
};
static void on_format_changed( GtkComboBox* combo, gpointer user_data )
{
GtkFileChooser* dlg = GTK_FILE_CHOOSER(user_data);
int i, n, len;
char* ext = NULL;
char *path, *name, *new_name;
path = gtk_file_chooser_get_filename( dlg );
if( !path )
return;
ext = gtk_combo_box_text_get_active_text( GTK_COMBO_BOX_TEXT( combo ) );
name = g_path_get_basename( path );
g_free( path );
n = gtk_tree_model_iter_n_children( gtk_combo_box_get_model(combo),
NULL );
for( i = 0; i < n; ++i )
{
if( g_str_has_suffix( name, handlers[i].file_ext ) )
break;
}
if( i < n )
{
len = strlen( name ) - strlen( handlers[i].file_ext );
name[len] = '\0';
}
new_name = g_strjoin( NULL, name, ext, NULL );
g_free( name );
g_free( ext );
gtk_file_chooser_set_current_name( dlg, new_name );
g_free( new_name );
// set options
i = gtk_combo_box_get_active(combo);
GtkEntry* entry = (GtkEntry*)g_object_get_data( G_OBJECT(dlg), "entry" );
if ( xset_get_s( handlers[i].name ) )
gtk_entry_set_text( entry, xset_get_s( handlers[i].name ) );
else
gtk_entry_buffer_delete_text( gtk_entry_get_buffer( entry ), 0, -1 );
}
void ptk_file_archiver_create( PtkFileBrowser* file_browser, GList* files,
const char* cwd )
{
GList* l;
GtkWidget* dlg;
GtkFileFilter* filter;
char* dest_file;
char* ext;
char* str;
char* cmd;
int res;
//char **argv, **cmdv;
int argc, cmdc, i, n;
int format;
GtkWidget* combo;
GtkWidget* hbox;
char* udest_file;
char* desc;
dlg = gtk_file_chooser_dialog_new( _("Save Archive"),
GTK_WINDOW( gtk_widget_get_toplevel(
GTK_WIDGET( file_browser ) ) ),
GTK_FILE_CHOOSER_ACTION_SAVE,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
GTK_STOCK_SAVE, GTK_RESPONSE_OK, NULL );
filter = gtk_file_filter_new();
hbox = gtk_hbox_new( FALSE, 4 );
gtk_box_pack_start( GTK_BOX(hbox),
gtk_label_new( _("Archive Format:") ),
FALSE, TRUE, 2 );
combo = gtk_combo_box_text_new();
for( i = 0; i < G_N_ELEMENTS(handlers); ++i )
{
if( handlers[i].compress_cmd )
{
gtk_file_filter_add_mime_type( filter, handlers[i].mime_type );
gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT(combo), handlers[i].file_ext );
}
}
gtk_file_chooser_set_filter( GTK_FILE_CHOOSER(dlg), filter );
n = gtk_tree_model_iter_n_children( gtk_combo_box_get_model(
GTK_COMBO_BOX( combo ) ), NULL );
i = xset_get_int( "arc_dlg", "z" );
if ( i < 0 || i > n - 1 )
i = 0;
gtk_combo_box_set_active( GTK_COMBO_BOX(combo), i );
g_signal_connect( combo, "changed", G_CALLBACK(on_format_changed), dlg );
gtk_box_pack_start( GTK_BOX(hbox),
combo,
FALSE, FALSE, 2 );
gtk_box_pack_start( GTK_BOX(hbox),
gtk_label_new( _("Options:") ),
FALSE, FALSE, 2 );
GtkEntry* entry = ( GtkEntry* ) gtk_entry_new();
if ( xset_get_s( handlers[i].name ) )
gtk_entry_set_text( entry, xset_get_s( handlers[i].name ) );
//GtkWidget* align = gtk_alignment_new( 0, 0, 1, 1 );
//gtk_alignment_set_padding( GTK_ALIGNMENT( align ), 0, 0, 0, 0 );
//gtk_container_add ( GTK_CONTAINER ( align ), GTK_WIDGET( entry ) );
gtk_box_pack_start( GTK_BOX(hbox), GTK_WIDGET( entry ), TRUE, TRUE, 4 );
g_object_set_data( G_OBJECT( dlg ), "entry", entry );
gtk_widget_show_all( hbox );
gtk_box_pack_start( GTK_BOX( gtk_dialog_get_content_area (
GTK_DIALOG( dlg ) ) ),
hbox, FALSE, TRUE, 0 );
gtk_file_chooser_set_action( GTK_FILE_CHOOSER(dlg), GTK_FILE_CHOOSER_ACTION_SAVE );
gtk_file_chooser_set_do_overwrite_confirmation( GTK_FILE_CHOOSER(dlg), TRUE );
if( files )
{
// gtk_file_chooser_set_current_name( GTK_FILE_CHOOSER(dlg),
// vfs_file_info_get_disp_name( (VFSFileInfo*)files->data ) );
ext = gtk_combo_box_text_get_active_text( GTK_COMBO_BOX_TEXT(combo) );
dest_file = g_strjoin( NULL,
vfs_file_info_get_disp_name( (VFSFileInfo*)files->data ),
ext, NULL );
gtk_file_chooser_set_current_name( GTK_FILE_CHOOSER(dlg), dest_file );
g_free( dest_file );
/*
if ( !files->next )
{
dest_file = g_build_filename( cwd,
vfs_file_info_get_disp_name( (VFSFileInfo*)files->data ), NULL );
if ( g_file_test( dest_file, G_FILE_TEST_IS_DIR ) )
{
g_free( dest_file );
dest_file = g_strjoin( NULL,
vfs_file_info_get_disp_name( (VFSFileInfo*)files->data ),
ext, NULL );
}
else
{
g_free( dest_file );
dest_file = g_strdup( vfs_file_info_get_disp_name(
(VFSFileInfo*)files->data ) );
}
gtk_file_chooser_set_current_name( GTK_FILE_CHOOSER(dlg), dest_file );
g_free( dest_file );
}
else
gtk_file_chooser_set_current_name( GTK_FILE_CHOOSER(dlg), "new archive" );
*/
g_free( ext );
}
gtk_file_chooser_set_current_folder( GTK_FILE_CHOOSER (dlg), cwd );
int width = xset_get_int( "arc_dlg", "x" );
int height = xset_get_int( "arc_dlg", "y" );
if ( width && height )
{
// filechooser won't honor default size or size request ?
gtk_widget_show_all( dlg );
gtk_window_set_position( GTK_WINDOW( dlg ), GTK_WIN_POS_CENTER_ALWAYS );
gtk_window_resize( GTK_WINDOW( dlg ), width, height );
while( gtk_events_pending() )
gtk_main_iteration();
gtk_window_set_position( GTK_WINDOW( dlg ), GTK_WIN_POS_CENTER );
}
res = gtk_dialog_run(GTK_DIALOG(dlg));
dest_file = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dlg));
format = gtk_combo_box_get_active( GTK_COMBO_BOX(combo) );
char* options = g_strdup( gtk_entry_get_text( entry ) );
if ( res == GTK_RESPONSE_OK )
{
char* str;
GtkAllocation allocation;
gtk_widget_get_allocation ( GTK_WIDGET ( dlg ), &allocation );
width = allocation.width;
height = allocation.height;
if ( width && height )
{
str = g_strdup_printf( "%d", width );
xset_set( "arc_dlg", "x", str );
g_free( str );
str = g_strdup_printf( "%d", height );
xset_set( "arc_dlg", "y", str );
g_free( str );
}
str = g_strdup_printf( "%d", format );
xset_set( "arc_dlg", "z", str );
g_free( str );
xset_set( handlers[format].name, "s", gtk_entry_get_text( entry ) );
}
gtk_widget_destroy( dlg );
if ( res != GTK_RESPONSE_OK )
{
g_free( dest_file );
return;
}
char* s1;
if ( options )
{
s1 = replace_string( handlers[format].compress_cmd, "%o", options, FALSE );
g_free( options );
}
else
s1 = g_strdup( handlers[format].compress_cmd );
if ( format == 4 )
{
// for 7z use 7za OR 7zr
str = g_find_program_in_path( "7za" );
if ( !str )
str = g_find_program_in_path( "7zr" );
if ( str )
{
cmd = s1;
s1 = replace_string( cmd, "7za", str, FALSE );
g_free( cmd );
g_free( str );
}
}
udest_file = g_filename_display_name( dest_file );
/*
if ( !g_str_has_suffix( udest_file, handlers[format].file_ext ) )
{
g_free( dest_file );
dest_file = udest_file;
udest_file = g_strdup_printf( "%s%s", dest_file, handlers[format].file_ext );
}
*/
g_free( dest_file );
// overwrite?
/*
if ( g_file_test( udest_file, G_FILE_TEST_EXISTS ) )
{
char* afile = g_path_get_basename( udest_file );
char* msg = g_strdup_printf( _("Archive '%s' exists.\n\nOverwrite?"), afile );
g_free( afile );
if ( xset_msg_dialog( GTK_WIDGET( file_browser ), GTK_MESSAGE_QUESTION,
_("Overwrite?"), NULL, GTK_BUTTONS_OK_CANCEL,
msg, NULL, NULL ) != GTK_RESPONSE_OK )
{
g_free( udest_file );
g_free( s1 );
g_free( msg );
return;
}
g_free( msg );
}
*/
char* udest_quote = bash_quote( udest_file );
//char* cmd = g_strdup_printf( "%s %s \"${fm_filenames[@]}\"", s1, udest_quote );
cmd = g_strdup_printf( "%s %s", s1, udest_quote );
g_free( udest_file );
g_free( udest_quote );
g_free( s1 );
// add selected files
for( l = files; l; l = l->next )
{
// FIXME: Maybe we should consider filename encoding here.
s1 = cmd;
desc = bash_quote( (char *) vfs_file_info_get_name( (VFSFileInfo*) l->data ) );
cmd = g_strdup_printf( "%s %s", s1, desc );
g_free( desc );
g_free( s1 );
}
// task
char* task_name = g_strdup_printf( _("Archive") );
PtkFileTask* task = ptk_file_exec_new( task_name, cwd, GTK_WIDGET( file_browser ),
file_browser->task_view );
g_free( task_name );
task->task->exec_browser = file_browser;
if ( format == 3 || format == 4 || format == 6 )
{
// use terminal for noisy rar, 7z, zip creation
task->task->exec_terminal = TRUE;
task->task->exec_sync = FALSE;
s1 = cmd;
cmd = g_strdup_printf( "%s ; fm_err=$?; if [ $fm_err -ne 0 ]; then echo; echo -n '%s: '; read s; exit $fm_err; fi", s1, "[ Finished With Errors ] Press Enter to close" );
g_free( s1 );
}
else
{
task->task->exec_sync = TRUE;
}
task->task->exec_command = cmd;
task->task->exec_show_error = TRUE;
task->task->exec_export = TRUE;
//task->task->exec_keep_tmp = TRUE;
XSet* set = xset_get( "new_archive" );
if ( set->icon )
task->task->exec_icon = g_strdup( set->icon );
ptk_file_task_run( task );
/*
g_shell_parse_argv( handlers[format].compress_cmd,
&cmdc, &cmdv, NULL );
n = g_list_length( files );
argc = cmdc + n + 1;
argv = g_new0( char*, argc + 1 );
for( i = 0; i < cmdc; ++i )
argv[i] = cmdv[i];
argv[i] = dest_file;
++i;
for( l = files; l; l = l->next )
{
// FIXME: Maybe we should consider filename encoding here.
argv[i] = (char *) vfs_file_info_get_name( (VFSFileInfo*) l->data );
++i;
}
argv[i] = NULL;
udest_file = g_filename_display_name( dest_file );
desc = g_strdup_printf( _("Creating Compressed File: %s"), udest_file );
g_free( udest_file );
ptk_console_output_run( parent_win, _("Compress Files"),
desc,
working_dir,
argc, argv );
g_free( dest_file );
g_strfreev( cmdv );
g_free( argv );
*/
}
void ptk_file_archiver_extract( PtkFileBrowser* file_browser, GList* files,
const char* cwd, const char* dest_dir )
{
GtkWidget* dlg;
GtkWidget* dlgparent = NULL;
char* choose_dir = NULL;
gboolean create_parent;
gboolean write_access;
gboolean list_contents = FALSE;
VFSFileInfo* file;
VFSMimeType* mime;
const char* type;
GList* l;
char* mkparent;
char* perm;
char* prompt;
char* full_path;
char* full_quote;
char* dest_quote;
const char* dest;
char* cmd;
char* str;
int i, n, j;
struct stat64 statbuf;
gboolean keep_term;
gboolean in_term;
const char* suffix[] = { ".tar", ".tar.gz", ".tgz", ".tar.bz2", ".tar.xz",
".txz", ".zip", ".rar", ".7z" };
if( !files )
return;
if ( file_browser )
dlgparent = gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) );
//else if ( desktop )
// dlgparent = gtk_widget_get_toplevel( desktop ); // causes drag action???
if( !dest_dir )
{
dlg = gtk_file_chooser_dialog_new( _("Extract To"),
GTK_WINDOW( dlgparent ),
GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
GTK_STOCK_OK, GTK_RESPONSE_OK, NULL );
GtkWidget* hbox = gtk_hbox_new( FALSE, 10 );
GtkWidget* chk_parent = gtk_check_button_new_with_mnemonic(
_("Cre_ate subfolder(s)") );
gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( chk_parent ),
xset_get_b( "arc_dlg" ) );
GtkWidget* chk_write = gtk_check_button_new_with_mnemonic(
_("Make contents user-_writable") );
gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( chk_write ),
xset_get_int( "arc_dlg", "s" ) == 1 && geteuid() != 0 );
gtk_widget_set_sensitive( chk_write, geteuid() != 0 );
gtk_box_pack_start( GTK_BOX(hbox), chk_parent, FALSE, FALSE, 6 );
gtk_box_pack_start( GTK_BOX(hbox), chk_write, FALSE, FALSE, 6 );
gtk_widget_show_all( hbox );
gtk_file_chooser_set_extra_widget( GTK_FILE_CHOOSER(dlg), hbox );
gtk_file_chooser_set_current_folder( GTK_FILE_CHOOSER (dlg), cwd );
int width = xset_get_int( "arc_dlg", "x" );
int height = xset_get_int( "arc_dlg", "y" );
if ( width && height )
{
// filechooser won't honor default size or size request ?
gtk_widget_show_all( dlg );
gtk_window_set_position( GTK_WINDOW( dlg ), GTK_WIN_POS_CENTER_ALWAYS );
gtk_window_resize( GTK_WINDOW( dlg ), width, height );
while( gtk_events_pending() )
gtk_main_iteration();
gtk_window_set_position( GTK_WINDOW( dlg ), GTK_WIN_POS_CENTER );
}
if( gtk_dialog_run( GTK_DIALOG(dlg) ) == GTK_RESPONSE_OK )
{
GtkAllocation allocation;
gtk_widget_get_allocation ( GTK_WIDGET ( dlg ), &allocation );
width = allocation.width;
height = allocation.height;
if ( width && height )
{
str = g_strdup_printf( "%d", width );
xset_set( "arc_dlg", "x", str );
g_free( str );
str = g_strdup_printf( "%d", height );
xset_set( "arc_dlg", "y", str );
g_free( str );
}
choose_dir = gtk_file_chooser_get_filename( GTK_FILE_CHOOSER(dlg) );
create_parent = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( chk_parent ) );
write_access = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( chk_write ) );
xset_set_b( "arc_dlg", create_parent );
str = g_strdup_printf( "%d", write_access ? 1 : 0 );
xset_set( "arc_dlg", "s", str );
g_free( str );
}
gtk_widget_destroy( dlg );
if( !choose_dir )
return;
dest = choose_dir;
}
else
{
create_parent = xset_get_b( "arc_def_parent" );
write_access = xset_get_b( "arc_def_write" );
list_contents = !strcmp( dest_dir, "////LIST" );
dest = dest_dir;
}
for ( l = files; l; l = l->next )
{
file = (VFSFileInfo*)l->data;
mime = vfs_file_info_get_mime_type( file );
type = vfs_mime_type_get_type( mime );
for ( i = 0; i < G_N_ELEMENTS(handlers); ++i )
{
if( 0 == strcmp( type, handlers[i].mime_type ) )
break;
}
if ( i == G_N_ELEMENTS(handlers) )
continue;
if ( ( list_contents && !handlers[i].list_cmd )
|| ( !list_contents && !handlers[i].extract_cmd ) )
continue;
// handler found
keep_term = TRUE;
in_term = FALSE;
full_path = g_build_filename( cwd, vfs_file_info_get_name( file ), NULL );
full_quote = bash_quote( full_path );
dest_quote = bash_quote( dest );
if ( list_contents )
{
// list contents
cmd = g_strdup_printf( "%s %s | more -d", handlers[i].list_cmd, full_quote );
in_term = TRUE;
}
else if ( !strcmp( type, "application/x-gzip" ) )
{
// extract .gz
char* base = g_build_filename( dest, vfs_file_info_get_name( file ),
NULL );
if ( g_str_has_suffix( base, ".gz" ) )
base[strlen(base)-3] = '\0';
char* test_path = g_strdup( base );
n = 1;
while ( lstat64( test_path, &statbuf ) == 0 )
{
g_free( test_path );
test_path = g_strdup_printf( "%s-%s%d", base, _("copy"), ++n );
}
g_free( dest_quote );
dest_quote = bash_quote( test_path );
g_free( test_path );
g_free( base );
cmd = g_strdup_printf( "%s -c %s > %s", handlers[i].extract_cmd,
full_quote, dest_quote );
}
else
{
// extract
if ( create_parent && strcmp( type, "application/x-gzip" ) )
{
// create parent
char* full_name = g_path_get_basename( full_path );
char* parent_name = NULL;
for ( j = 0; j < G_N_ELEMENTS(suffix); ++j )
{
if ( g_str_has_suffix( full_name, suffix[j] ) )
{
n = strlen( full_name ) - strlen( suffix[j] );
full_name[n] = '\0';
parent_name = g_strdup( full_name );
full_name[n] = '.';
break;
}
}
if ( !parent_name )
parent_name = g_strdup( full_name );
g_free( full_name );
char* parent_path = g_build_filename( dest, parent_name, NULL );
char* parent_orig = g_strdup( parent_path );
n = 1;
while ( lstat64( parent_path, &statbuf ) == 0 )
{
g_free( parent_path );
parent_path = g_strdup_printf( "%s-%s%d", parent_orig,
_("copy"), ++n );
}
g_free( parent_orig );
char* parent_quote = bash_quote( parent_path );
mkparent = g_strdup_printf( "mkdir -p %s && cd %s && ", parent_quote,
parent_quote );
if ( write_access && geteuid() != 0 )
perm = g_strdup_printf( " && chmod -R u+rwX %s", parent_quote );
else
perm = g_strdup( "" );
g_free( parent_path );
g_free( parent_quote );
}
else
{
// no create parent
mkparent = g_strdup( "" );
if ( write_access && geteuid() != 0 && strcmp( type, "application/x-gzip" ) )
perm = g_strdup_printf( " && chmod -R u+rwX %s/*", dest_quote );
else
perm = g_strdup( "" );
}
if ( i == 3 || i == 4 || i == 6 )
{
// zip 7z rar in terminal for password & output
in_term = TRUE; // run in terminal
keep_term = FALSE;
prompt = g_strdup_printf( " ; fm_err=$?; if [ $fm_err -ne 0 ]; then echo; echo -n '%s: '; read s; exit $fm_err; fi", /* no translate for security*/
"[ Finished With Errors ] Press Enter to close" );
}
else
prompt = g_strdup( "" );
char* handler = NULL;
if ( i == 4 )
{
// for 7z use 7za OR 7zr
str = g_find_program_in_path( "7za" );
if ( !str )
str = g_find_program_in_path( "7zr" );
if ( str )
{
handler = replace_string( handlers[i].extract_cmd, "7za", str, FALSE );
g_free( str );
}
}
cmd = g_strdup_printf( "cd %s && %s%s %s%s%s", dest_quote, mkparent,
handler ? handler : handlers[i].extract_cmd,
full_quote, prompt, perm );
g_free( mkparent );
g_free( perm );
g_free( prompt );
g_free( handler );
}
g_free( dest_quote );
g_free( full_quote );
g_free( full_path );
// task
char* task_name = g_strdup_printf( _("Extract %s"),
vfs_file_info_get_name( file ) );
PtkFileTask* task = ptk_file_exec_new( task_name, cwd, dlgparent,
file_browser ? file_browser->task_view : NULL );
g_free( task_name );
task->task->exec_command = cmd;
task->task->exec_browser = file_browser;
task->task->exec_sync = !in_term;
task->task->exec_show_error = TRUE;
task->task->exec_show_output = in_term;
task->task->exec_terminal = in_term;
task->task->exec_keep_terminal = keep_term;
task->task->exec_export = FALSE;
//task->task->exec_keep_tmp = TRUE;
XSet* set = xset_get( "arc_extract" );
if ( set->icon )
task->task->exec_icon = g_strdup( set->icon );
ptk_file_task_run( task );
}
if ( choose_dir )
g_free( choose_dir );
/*
file = (VFSFileInfo*)files->data;
mime = vfs_file_info_get_mime_type( file );
type = vfs_mime_type_get_type( mime );
for( i = 0; i < G_N_ELEMENTS(handlers); ++i )
{
if( 0 == strcmp( type, handlers[i].mime_type ) )
break;
}
if( i < G_N_ELEMENTS(handlers) ) // handler found
{
g_shell_parse_argv( handlers[i].extract_cmd,
&cmdc, &cmdv, NULL );
n = g_list_length( files );
argc = cmdc + n;
argv = g_new0( char*, argc + 1 );
for( i = 0; i < cmdc; ++i )
argv[i] = cmdv[i];
for( l = files; l; l = l->next )
{
file = (VFSFileInfo*)l->data;
full_path = g_build_filename( working_dir,
vfs_file_info_get_name( file ),
NULL );
// FIXME: Maybe we should consider filename encoding here.
argv[i] = full_path;
++i;
}
argv[i] = NULL;
argc = i;
udest_dir = g_filename_display_name( dest_dir );
desc = g_strdup_printf( _("Extracting Files to: %s"), udest_dir );
g_free( udest_dir );
ptk_console_output_run( parent_win, _("Extract Files"),
desc,
dest_dir,
argc, argv );
g_strfreev( cmdv );
for( i = cmdc; i < argc; ++i )
g_free( argv[i] );
g_free( argv );
}
g_free( _dest_dir );
*/
}
gboolean ptk_file_archiver_is_format_supported( VFSMimeType* mime,
gboolean extract )
{
int i;
const char* type;
if( !mime ) return FALSE;
type = vfs_mime_type_get_type( mime );
if(! type ) return FALSE;
/* alias = mime_type_get_alias( type ); */
for( i = 0; i < G_N_ELEMENTS(handlers); ++i )
{
if( 0 == strcmp( type, handlers[i].mime_type ) )
{
if( extract )
{
if( handlers[i].extract_cmd )
return TRUE;
}
else if( handlers[i].compress_cmd )
{
return TRUE;
}
break;
}
}
return FALSE;
}
|
184 | ./spacefm/src/ptk/ptk-clipboard.c | /*
* C Implementation: ptk-clipboard
*
* Description:
*
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#include "ptk-clipboard.h"
#include <string.h>
#include "vfs-file-info.h"
#include "ptk-file-task.h"
#include "vfs-file-task.h"
#include "ptk-utils.h" //MOD
static GdkDragAction clipboard_action = GDK_ACTION_DEFAULT;
static GList* clipboard_file_list = NULL;
static void clipboard_get_data ( GtkClipboard *clipboard,
GtkSelectionData *selection_data,
guint info,
gpointer user_data )
{
GdkAtom uri_list_target = gdk_atom_intern( "text/uri-list", FALSE );
GdkAtom gnome_target = gdk_atom_intern( "x-special/gnome-copied-files", FALSE );
GList* l;
gchar* file_name;
gchar* action;
gboolean use_uri = FALSE;
GString* list;
if ( ! clipboard_file_list )
return ;
list = g_string_sized_new( 8192 );
if ( gtk_selection_data_get_target ( selection_data ) == gnome_target )
{
action = clipboard_action == GDK_ACTION_MOVE ? "cut\n" : "copy\n";
g_string_append( list, action );
use_uri = TRUE;
}
else if ( gtk_selection_data_get_target ( selection_data ) == uri_list_target )
use_uri = TRUE;
for ( l = clipboard_file_list; l; l = l->next )
{
if ( use_uri )
{
file_name = g_filename_to_uri( ( char* ) l->data, NULL, NULL );
}
else
{
file_name = g_filename_display_name( ( char* ) l->data );
}
g_string_append( list, file_name );
g_free( file_name );
if ( gtk_selection_data_get_target ( selection_data ) != uri_list_target )
g_string_append_c( list, '\n' );
else
g_string_append( list, "\r\n" );
}
gtk_selection_data_set ( selection_data,
gtk_selection_data_get_target ( selection_data ),
8,
( guchar* ) list->str, list->len + 1 );
/* g_debug( "clipboard data:\n%s\n\n", list->str ); */
g_string_free( list, TRUE );
}
static void clipboard_clean_data ( GtkClipboard *clipboard,
gpointer user_data )
{
/* g_debug( "clean clipboard!\n" ); */
if ( clipboard_file_list )
{
g_list_foreach( clipboard_file_list, ( GFunc ) g_free, NULL );
g_list_free( clipboard_file_list );
clipboard_file_list = NULL;
}
clipboard_action = GDK_ACTION_DEFAULT;
}
void ptk_clipboard_copy_as_text( const char* working_dir,
GList* files ) //MOD added
{ // aka copy path
GtkClipboard* clip = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD );
GtkClipboard* clip_primary = gtk_clipboard_get( GDK_SELECTION_PRIMARY );
GList *l;
VFSFileInfo* file;
char* file_path;
char* file_text;
char* str;
char* quoted;
file_text = g_strdup( "" );
for ( l = files; l; l = l->next )
{
file = ( VFSFileInfo* ) l->data;
file_path = g_build_filename( working_dir,
vfs_file_info_get_name( file ), NULL );
quoted = bash_quote( file_path );
str = file_text;
file_text = g_strdup_printf( "%s %s", str, quoted );
g_free( str );
g_free( quoted );
g_free( file_path );
}
gtk_clipboard_set_text ( clip, file_text , -1 );
gtk_clipboard_set_text ( clip_primary, file_text , -1 );
g_free( file_text );
}
void ptk_clipboard_copy_name( const char* working_dir,
GList* files ) //MOD added
{
GtkClipboard* clip = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD );
GtkClipboard* clip_primary = gtk_clipboard_get( GDK_SELECTION_PRIMARY );
GList *l;
VFSFileInfo* file;
char* file_text;
gint fcount = 0;
char* str;
file_text = g_strdup( "" );
for ( l = files; l; l = l->next )
{
file = ( VFSFileInfo* ) l->data;
str = file_text;
if ( fcount == 0 )
file_text = g_strdup_printf( "%s", vfs_file_info_get_name( file ) );
else if ( fcount == 1 )
file_text = g_strdup_printf( "%s\n%s\n", file_text,
vfs_file_info_get_name( file ) );
else
file_text = g_strdup_printf( "%s%s\n", file_text,
vfs_file_info_get_name( file ) );
fcount++;
g_free( str );
}
gtk_clipboard_set_text( clip, file_text , -1 );
gtk_clipboard_set_text( clip_primary, file_text , -1 );
g_free( file_text );
}
void ptk_clipboard_copy_text( const char* text ) //MOD added
{
GtkClipboard * clip = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD );
GtkClipboard* clip_primary = gtk_clipboard_get( GDK_SELECTION_PRIMARY );
gtk_clipboard_set_text( clip, text, -1 );
gtk_clipboard_set_text( clip_primary, text, -1 );
}
void ptk_clipboard_cut_or_copy_files( const char* working_dir,
GList* files,
gboolean copy )
{
GtkClipboard * clip = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD );
GtkTargetList* target_list = gtk_target_list_new( NULL, 0 );
GList* target;
gint n_targets;
GtkTargetEntry* new_target;
GtkTargetEntry* targets;
GList *l;
VFSFileInfo* file;
char* file_path;
GList* file_list = NULL;
gtk_target_list_add_text_targets( target_list, 0 );
targets = gtk_target_table_new_from_list( target_list, &n_targets );
n_targets += 2;
targets = g_renew( GtkTargetEntry, targets, n_targets );
#if 0
new_target = gtk_target_entry_new( "x-special/gnome-copied-files", 0, 0 );
#else
new_target = g_new0( GtkTargetEntry, 1 );
new_target->target = "x-special/gnome-copied-files";
#endif
g_memmove( &(targets[ n_targets - 2 ]), new_target, sizeof (GtkTargetEntry));
#if 0
new_target = gtk_target_entry_new( "text/uri-list", 0, 0 );
#else
new_target = g_new0( GtkTargetEntry, 1 );
new_target->target = "text/uri-list";
#endif
g_memmove( &(targets[ n_targets - 1 ]), new_target, sizeof (GtkTargetEntry));
gtk_target_list_unref ( target_list );
for ( l = g_list_last( files ); l; l = l->prev ) //sfm was reverse order
{
file = ( VFSFileInfo* ) l->data;
file_path = g_build_filename( working_dir,
vfs_file_info_get_name( file ), NULL );
file_list = g_list_prepend( file_list, file_path );
}
gtk_clipboard_set_with_data ( clip, targets, n_targets,
clipboard_get_data,
clipboard_clean_data,
NULL );
g_free( targets );
clipboard_file_list = file_list;
clipboard_action = copy ? GDK_ACTION_COPY : GDK_ACTION_MOVE;
}
void ptk_clipboard_copy_file_list( char** path, gboolean copy )
{
GtkClipboard * clip = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD );
GtkTargetList* target_list = gtk_target_list_new( NULL, 0 );
GList* target;
gint n_targets;
GtkTargetEntry* new_target;
GtkTargetEntry* targets;
GList *l;
VFSFileInfo* file;
char** file_path;
GList* file_list = NULL;
gtk_target_list_add_text_targets( target_list, 0 );
targets = gtk_target_table_new_from_list( target_list, &n_targets );
n_targets += 2;
targets = g_renew( GtkTargetEntry, targets, n_targets );
#if 0
new_target = gtk_target_entry_new( "x-special/gnome-copied-files", 0, 0 );
#else
new_target = g_new0( GtkTargetEntry, 1 );
new_target->target = "x-special/gnome-copied-files";
#endif
g_memmove( &(targets[ n_targets - 2 ]), new_target, sizeof (GtkTargetEntry));
#if 0
new_target = gtk_target_entry_new( "text/uri-list", 0, 0 );
#else
new_target = g_new0( GtkTargetEntry, 1 );
new_target->target = "text/uri-list";
#endif
g_memmove( &(targets[ n_targets - 1 ]), new_target, sizeof (GtkTargetEntry));
gtk_target_list_unref ( target_list );
file_path = path;
while ( *file_path )
{
if ( *file_path[0] == '/' )
file_list = g_list_append( file_list, g_strdup( *file_path ) );
file_path++;
}
gtk_clipboard_set_with_data ( clip, targets, n_targets,
clipboard_get_data,
clipboard_clean_data,
NULL );
g_free( targets );
clipboard_file_list = file_list;
clipboard_action = copy ? GDK_ACTION_COPY : GDK_ACTION_MOVE;
}
void ptk_clipboard_paste_files( GtkWindow* parent_win,
const char* dest_dir, GtkTreeView* task_view )
{
GtkClipboard * clip = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD );
GdkAtom gnome_target;
GdkAtom uri_list_target;
gchar **uri_list, **puri;
GtkSelectionData* sel_data = NULL;
GList* files = NULL;
gchar* file_path;
PtkFileTask* task;
VFSFileTaskType action;
char* uri_list_str;
gnome_target = gdk_atom_intern( "x-special/gnome-copied-files", FALSE );
sel_data = gtk_clipboard_wait_for_contents( clip, gnome_target );
if ( sel_data )
{
if ( gtk_selection_data_get_length( sel_data ) <= 0 ||
gtk_selection_data_get_format( sel_data ) != 8 )
{
gtk_selection_data_free( sel_data );
return;
}
uri_list_str = ( char* ) gtk_selection_data_get_data( sel_data );
if ( 0 == strncmp( ( char* ) gtk_selection_data_get_data( sel_data ), "cut", 3 ) )
action = VFS_FILE_TASK_MOVE;
else
action = VFS_FILE_TASK_COPY;
if ( uri_list_str )
{
while ( *uri_list_str && *uri_list_str != '\n' )
++uri_list_str;
}
}
else
{
uri_list_target = gdk_atom_intern( "text/uri-list", FALSE );
sel_data = gtk_clipboard_wait_for_contents( clip, uri_list_target );
if ( !sel_data )
return;
if ( gtk_selection_data_get_length( sel_data ) <= 0 ||
gtk_selection_data_get_format( sel_data ) != 8 )
{
gtk_selection_data_free( sel_data );
return;
}
uri_list_str = ( char* ) gtk_selection_data_get_data( sel_data );
if ( clipboard_action == GDK_ACTION_MOVE )
action = VFS_FILE_TASK_MOVE;
else
action = VFS_FILE_TASK_COPY;
}
if ( uri_list_str )
{
puri = uri_list = g_uri_list_extract_uris( uri_list_str );
while ( *puri )
{
file_path = g_filename_from_uri( *puri, NULL, NULL );
if ( file_path )
{
files = g_list_prepend( files, file_path );
}
++puri;
}
g_strfreev( uri_list );
//sfm
if ( files )
files = g_list_reverse( files );
/*
* If only one item is selected and the item is a
* directory, paste the files in that directory;
* otherwise, paste the file in current directory.
*/
task = ptk_file_task_new( action,
files,
dest_dir,
GTK_WINDOW( parent_win ),
GTK_WIDGET( task_view ) );
ptk_file_task_run( task );
}
gtk_selection_data_free( sel_data );
}
void ptk_clipboard_paste_links( GtkWindow* parent_win,
const char* dest_dir,
GtkTreeView* task_view ) //MOD added
{
GtkClipboard * clip = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD );
GdkAtom gnome_target;
GdkAtom uri_list_target;
gchar **uri_list, **puri;
GtkSelectionData* sel_data = NULL;
GList* files = NULL;
gchar* file_path;
PtkFileTask* task;
VFSFileTaskType action;
char* uri_list_str;
gnome_target = gdk_atom_intern( "x-special/gnome-copied-files", FALSE );
sel_data = gtk_clipboard_wait_for_contents( clip, gnome_target );
if ( sel_data )
{
if ( gtk_selection_data_get_length( sel_data ) <= 0 ||
gtk_selection_data_get_format( sel_data ) != 8 )
{
gtk_selection_data_free( sel_data );
return;
}
uri_list_str = ( char* ) gtk_selection_data_get_data( sel_data );
action = VFS_FILE_TASK_LINK;
if ( uri_list_str )
{
while ( *uri_list_str && *uri_list_str != '\n' )
++uri_list_str;
}
}
else
{
uri_list_target = gdk_atom_intern( "text/uri-list", FALSE );
sel_data = gtk_clipboard_wait_for_contents( clip, uri_list_target );
if ( !sel_data )
return;
if ( gtk_selection_data_get_length( sel_data ) <= 0 ||
gtk_selection_data_get_format( sel_data ) != 8 )
{
gtk_selection_data_free( sel_data );
return;
}
uri_list_str = ( char* ) gtk_selection_data_get_data( sel_data );
action = VFS_FILE_TASK_LINK;
}
if ( uri_list_str )
{
puri = uri_list = g_uri_list_extract_uris( uri_list_str );
while ( *puri )
{
if ( file_path = g_filename_from_uri( *puri, NULL, NULL ) )
files = g_list_prepend( files, file_path );
++puri;
}
g_strfreev( uri_list );
//sfm
if ( files )
files = g_list_reverse( files );
task = ptk_file_task_new( action,
files,
dest_dir,
GTK_WINDOW( parent_win ),
task_view ? GTK_WIDGET( task_view ) : NULL );
ptk_file_task_run( task );
}
gtk_selection_data_free( sel_data );
}
void ptk_clipboard_paste_targets( GtkWindow* parent_win,
const char* dest_dir,
GtkTreeView* task_view ) //MOD added
{
GtkClipboard * clip = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD );
GdkAtom gnome_target;
GdkAtom uri_list_target;
gchar **uri_list, **puri;
GtkSelectionData* sel_data = NULL;
GList* files = NULL;
gchar* file_path;
gint missing_targets = 0;
char* str;
PtkFileTask* task;
VFSFileTaskType action;
char* uri_list_str;
gnome_target = gdk_atom_intern( "x-special/gnome-copied-files", FALSE );
sel_data = gtk_clipboard_wait_for_contents( clip, gnome_target );
if ( sel_data )
{
if ( gtk_selection_data_get_length( sel_data ) <= 0 ||
gtk_selection_data_get_format( sel_data ) != 8 )
{
gtk_selection_data_free( sel_data );
return;
}
uri_list_str = ( char* ) gtk_selection_data_get_data( sel_data );
action = VFS_FILE_TASK_COPY;
if ( uri_list_str )
{
while ( *uri_list_str && *uri_list_str != '\n' )
++uri_list_str;
}
}
else
{
uri_list_target = gdk_atom_intern( "text/uri-list", FALSE );
sel_data = gtk_clipboard_wait_for_contents( clip, uri_list_target );
if ( !sel_data )
return;
if ( gtk_selection_data_get_length( sel_data ) <= 0 ||
gtk_selection_data_get_format( sel_data ) != 8 )
{
gtk_selection_data_free( sel_data );
return;
}
uri_list_str = ( char* ) gtk_selection_data_get_data( sel_data );
action = VFS_FILE_TASK_COPY;
}
if ( uri_list_str )
{
puri = uri_list = g_uri_list_extract_uris( uri_list_str );
while ( *puri )
{
file_path = g_filename_from_uri( *puri, NULL, NULL );
if ( file_path )
{
if ( g_file_test( file_path, G_FILE_TEST_IS_SYMLINK ) )
{
str = file_path;
file_path = g_file_read_link ( file_path, NULL );
g_free( str );
}
if ( file_path )
{
if ( g_file_test( file_path, G_FILE_TEST_EXISTS ) )
files = g_list_prepend( files, file_path );
else
missing_targets++;
}
}
++puri;
}
g_strfreev( uri_list );
//sfm
if ( files )
files = g_list_reverse( files );
task = ptk_file_task_new( action,
files,
dest_dir,
GTK_WINDOW( parent_win ),
GTK_WIDGET( task_view ) );
ptk_file_task_run( task );
if ( missing_targets > 0 )
ptk_show_error( GTK_WINDOW( parent_win ),
g_strdup_printf ( "Error" ),
g_strdup_printf ( "%i target%s missing",
missing_targets,
missing_targets > 1 ? g_strdup_printf ( "s are" ) :
g_strdup_printf ( " is" ) ) );
}
gtk_selection_data_free( sel_data );
}
GList* ptk_clipboard_get_file_paths( const char* cwd, gboolean* is_cut,
gint* missing_targets )
{
GtkClipboard * clip = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD );
GdkAtom gnome_target;
GdkAtom uri_list_target;
gchar **uri_list, **puri;
GtkSelectionData* sel_data = NULL;
GList* files = NULL;
gchar* file_path;
char* uri_list_str;
*is_cut = FALSE;
*missing_targets = 0;
// get files from clip
gnome_target = gdk_atom_intern( "x-special/gnome-copied-files", FALSE );
sel_data = gtk_clipboard_wait_for_contents( clip, gnome_target );
if ( sel_data )
{
if ( gtk_selection_data_get_length( sel_data ) <= 0 ||
gtk_selection_data_get_format( sel_data ) != 8 )
{
gtk_selection_data_free( sel_data );
return NULL;
}
uri_list_str = ( char* ) gtk_selection_data_get_data( sel_data );
*is_cut = ( 0 == strncmp( ( char* ) gtk_selection_data_get_data( sel_data ),
"cut", 3 ) );
if ( uri_list_str )
{
while ( *uri_list_str && *uri_list_str != '\n' )
++uri_list_str;
}
}
else
{
uri_list_target = gdk_atom_intern( "text/uri-list", FALSE );
sel_data = gtk_clipboard_wait_for_contents( clip, uri_list_target );
if ( ! sel_data )
return NULL;
if ( gtk_selection_data_get_length( sel_data ) <= 0 ||
gtk_selection_data_get_format( sel_data ) != 8 )
{
gtk_selection_data_free( sel_data );
return NULL;
}
uri_list_str = ( char* ) gtk_selection_data_get_data( sel_data );
}
if ( !uri_list_str )
{
gtk_selection_data_free( sel_data );
return NULL;
}
// create file list
puri = uri_list = g_uri_list_extract_uris( uri_list_str );
while ( *puri )
{
file_path = g_filename_from_uri( *puri, NULL, NULL );
if ( file_path )
{
if ( g_file_test( file_path, G_FILE_TEST_EXISTS ) )
{
files = g_list_prepend( files, file_path );
}
else
*missing_targets++;
}
++puri;
}
g_strfreev( uri_list );
gtk_selection_data_free( sel_data );
return files;
}
|
185 | ./spacefm/src/ptk/ptk-location-view.c | /*
* C Implementation: PtkLocationView
*
* Description:
*
*
* Copyright: See COPYING file that comes with this distribution
*
*/
//MOD this file extensively changed separating bookmarks list and adding
// udisks support and device manager features
#include <glib.h>
#include <glib/gi18n.h>
#include "ptk-location-view.h"
#include <stdio.h>
#include <string.h>
#include "ptk-bookmarks.h"
#include "ptk-utils.h"
#include "ptk-file-browser.h" //MOD
#include "settings.h" //MOD
#include "vfs-volume.h"
#include <gdk/gdkkeysyms.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include "vfs-dir.h"
#include "vfs-utils.h" /* for vfs_load_icon */
#include "glib-utils.h" /* for g_mkdir_with_parents */
#include "ptk-file-task.h"
#include "main-window.h"
#include "gtk2-compat.h"
static GtkTreeModel* model = NULL;
static GtkTreeModel* bookmodel = NULL;
static int n_vols = 0;
static guint theme_changed = 0; /* GtkIconTheme::"changed" handler */
static guint theme_bookmark_changed = 0; /* GtkIconTheme::"changed" handler */
static gboolean has_desktop_dir = TRUE;
static gboolean show_trash_can = FALSE;
static void ptk_location_view_init_model( GtkListStore* list );
static void ptk_bookmark_view_init_model( GtkListStore* list );
static void on_volume_event ( VFSVolume* vol, VFSVolumeState state, gpointer user_data );
static void add_volume( VFSVolume* vol, gboolean set_icon );
static void remove_volume( VFSVolume* vol );
static void update_volume( VFSVolume* vol );
static gboolean on_button_press_event( GtkTreeView* view, GdkEventButton* evt,
gpointer user_data );
static void on_bookmark_model_destroy( gpointer data, GObject* object );
void on_bookmark_row_deleted( GtkTreeView* view, GtkTreePath* tree_path,
GtkTreeViewColumn *col, gpointer user_data );
void on_bookmark_row_inserted( GtkTreeView* view, GtkTreePath* tree_path,
GtkTreeViewColumn *col, gpointer user_data );
void full_update_bookmark_icons();
void on_bookmark_device( GtkMenuItem* item, VFSVolume* vol );
static gboolean update_drag_dest_row( GtkWidget *widget, GdkDragContext *drag_context,
gint x, gint y, guint time, gpointer user_data );
static gboolean on_drag_motion( GtkWidget *widget, GdkDragContext *drag_context,
gint x, gint y, guint time, gpointer user_data );
static gboolean on_drag_drop( GtkWidget *widget, GdkDragContext *drag_context,
gint x, gint y, guint time, gpointer user_data );
static void on_drag_data_received( GtkWidget *widget, GdkDragContext *drag_context,
gint x, gint y, GtkSelectionData *data, guint info,
guint time, gpointer user_data);
static gboolean try_mount( GtkTreeView* view, VFSVolume* vol );
enum {
COL_ICON = 0,
COL_NAME,
COL_PATH,
COL_DATA,
N_COLS
};
typedef struct _AutoOpen
{
PtkFileBrowser* file_browser;
char* device_file;
int job;
}AutoOpen;
gboolean volume_is_visible( VFSVolume* vol );
gboolean run_command( char* command, char** output );
void update_all();
// do not translate - bash security
const char* data_loss_overwrite = "DATA LOSS WARNING - overwriting";
const char* type_yes_to_proceed = "Type yes and press Enter to proceed, or no to cancel";
const char* press_enter_to_close = "[ Finished ] Press Enter to close";
/* Drag & Drop/Clipboard targets */
static GtkTargetEntry drag_targets[] = { {"text/uri-list", 0 , 0 } };
static void show_busy( GtkWidget* view )
{
GtkWidget* toplevel;
GdkCursor* cursor;
toplevel = gtk_widget_get_toplevel( GTK_WIDGET(view) );
cursor = gdk_cursor_new_for_display( gtk_widget_get_display(GTK_WIDGET( view )), GDK_WATCH );
gdk_window_set_cursor( gtk_widget_get_window ( toplevel ), cursor );
gdk_cursor_unref( cursor );
/* update the GUI */
while (gtk_events_pending ())
gtk_main_iteration ();
}
static void show_ready( GtkWidget* view )
{
GtkWidget* toplevel;
toplevel = gtk_widget_get_toplevel( GTK_WIDGET(view) );
gdk_window_set_cursor( gtk_widget_get_window ( toplevel ), NULL );
}
static void on_bookmark_changed( gpointer bookmarks_, gpointer data )
{
g_signal_handlers_block_matched( bookmodel, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_bookmark_row_deleted, NULL );
gtk_list_store_clear( GTK_LIST_STORE( bookmodel ) );
ptk_bookmark_view_init_model( GTK_LIST_STORE( bookmodel ) );
g_signal_handlers_unblock_matched( bookmodel, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_bookmark_row_deleted, NULL );
}
static void on_model_destroy( gpointer data, GObject* object )
{
GtkIconTheme* icon_theme;
vfs_volume_remove_callback( on_volume_event, (gpointer)object );
model = NULL;
n_vols = 0;
icon_theme = gtk_icon_theme_get_default();
g_signal_handler_disconnect( icon_theme, theme_changed );
}
void update_volume_icons()
{
GtkIconTheme* icon_theme;
GtkTreeIter it;
GdkPixbuf* icon;
VFSVolume* vol;
int i;
//GtkListStore* list = GTK_LIST_STORE( model );
icon_theme = gtk_icon_theme_get_default();
if ( gtk_tree_model_get_iter_first( model, &it ) )
{
do
{
gtk_tree_model_get( model, &it, COL_DATA, &vol, -1 );
if ( vol )
{
if ( vfs_volume_get_icon( vol ) )
icon = vfs_load_icon ( icon_theme, vfs_volume_get_icon( vol ),
app_settings.small_icon_size );
else
icon = NULL;
gtk_list_store_set( GTK_LIST_STORE( model ), &it, COL_ICON, icon, -1 );
if ( icon )
g_object_unref( icon );
}
}
while ( gtk_tree_model_iter_next( model, &it ) );
}
}
#ifndef HAVE_HAL
void update_all()
{
const GList* l;
VFSVolume* vol;
GtkTreeIter it;
VFSVolume* v = NULL;
gboolean havevol;
if ( !model )
return;
const GList* volumes = vfs_volume_get_all_volumes();
for ( l = volumes; l; l = l->next )
{
vol = (VFSVolume*)l->data;
if ( vol )
{
// search model for volume vol
if ( gtk_tree_model_get_iter_first( model, &it ) )
{
do
{
gtk_tree_model_get( model, &it, COL_DATA, &v, -1 );
}
while ( v != vol && gtk_tree_model_iter_next( model, &it ) );
havevol = ( v == vol );
}
else
havevol = FALSE;
if ( volume_is_visible( vol ) )
{
if ( havevol )
{
update_volume( vol );
// attempt automount in case settings changed
vol->automount_time = 0;
vol->ever_mounted = FALSE;
vfs_volume_automount( vol );
}
else
add_volume( vol, TRUE );
}
else if ( havevol )
remove_volume( vol );
}
}
}
static void update_names()
{
GtkTreeIter it;
VFSVolume* v;
VFSVolume* vol;
const GList* l;
const GList* volumes = vfs_volume_get_all_volumes();
for ( l = volumes; l; l = l->next )
{
if ( l->data )
{
vol = l->data;
vfs_volume_set_info( vol );
// search model for volume vol
if ( gtk_tree_model_get_iter_first( model, &it ) )
{
do
{
gtk_tree_model_get( model, &it, COL_DATA, &v, -1 );
}
while ( v != vol && gtk_tree_model_iter_next( model, &it ) );
if ( v == vol )
update_volume( vol );
}
}
}
}
#endif
gboolean ptk_location_view_chdir( GtkTreeView* location_view, const char* cur_dir )
{
GtkTreeIter it;
GtkTreeSelection* tree_sel;
VFSVolume* vol;
const char* mount_point;
if ( !cur_dir || !GTK_IS_TREE_VIEW( location_view ) )
return FALSE;
tree_sel = gtk_tree_view_get_selection( location_view );
if ( gtk_tree_model_get_iter_first( model, &it ) )
{
do
{
gtk_tree_model_get( model, &it, COL_DATA, &vol, -1 );
mount_point = vfs_volume_get_mount_point( vol );
if ( mount_point && !strcmp( cur_dir, mount_point ) )
{
gtk_tree_selection_select_iter( tree_sel, &it );
GtkTreePath* path = gtk_tree_model_get_path( model, &it );
if ( path )
{
gtk_tree_view_scroll_to_cell( location_view,
path, NULL, TRUE, .25, 0 );
gtk_tree_path_free( path );
}
return TRUE;
}
}
while ( gtk_tree_model_iter_next ( model, &it ) );
}
gtk_tree_selection_unselect_all ( tree_sel );
return FALSE;
}
VFSVolume* ptk_location_view_get_selected_vol( GtkTreeView* location_view )
{
//printf("ptk_location_view_get_selected_vol view = %d\n", location_view );
GtkTreeIter it;
GtkTreeSelection* tree_sel;
GtkTreePath* tree_path;
char* real_path = NULL;
VFSVolume* vol;
tree_sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( location_view ) );
if ( gtk_tree_selection_get_selected( tree_sel, NULL, &it ) )
{
gtk_tree_model_get( model, &it, COL_DATA, &vol, -1 );
return vol;
}
return NULL;
}
char* ptk_location_view_get_selected_dir( GtkTreeView* location_view )
{
GtkTreeIter it;
GtkTreeSelection* tree_sel;
char* real_path = NULL;
VFSVolume* vol;
tree_sel = gtk_tree_view_get_selection( location_view );
if ( gtk_tree_selection_get_selected( tree_sel, NULL, &it ) )
{
gtk_tree_model_get( model, &it, COL_PATH, &real_path, -1 );
if( ! real_path || real_path[0] == '\0' ||
! g_file_test( real_path, G_FILE_TEST_EXISTS ) )
{
gtk_tree_model_get( model, &it, COL_DATA, &vol, -1 );
//if( ! vfs_volume_is_mounted( vol ) )
// try_mount( location_view, vol );
if ( !vfs_volume_is_mounted( vol ) )
return NULL;
real_path = (char*)vfs_volume_get_mount_point( vol );
if( real_path )
{
gtk_list_store_set( GTK_LIST_STORE(model), &it, COL_PATH, real_path, -1 );
return g_strdup(real_path);
}
else
return NULL;
}
}
return real_path;
}
void on_row_activated( GtkTreeView* view, GtkTreePath* tree_path,
GtkTreeViewColumn *col, PtkFileBrowser* file_browser )
{
VFSVolume* vol;
GtkTreeIter it;
const char* mount_point;
//printf("on_row_activated view = %d\n", view );
if ( !file_browser )
return;
if ( !gtk_tree_model_get_iter( model, &it, tree_path ) )
return;
gtk_tree_model_get( model, &it, COL_DATA, &vol, -1 );
if ( !vol )
return;
#ifndef HAVE_HAL
if ( !vfs_volume_is_mounted( vol ) && vol->device_type == DEVICE_TYPE_BLOCK )
#else
if ( !vfs_volume_is_mounted( vol ) )
#endif
{
try_mount( view, vol );
if ( vfs_volume_is_mounted( vol ) )
{
mount_point = vfs_volume_get_mount_point( vol );
if ( mount_point && mount_point[0] != '\0' )
{
gtk_list_store_set( GTK_LIST_STORE( model ), &it,
COL_PATH, mount_point, -1 );
}
}
}
#ifndef HAVE_HAL
if ( vfs_volume_is_mounted( vol ) && vol->mount_point )
{
if ( xset_get_b( "dev_newtab" ) )
{
ptk_file_browser_emit_open( file_browser, vol->mount_point,
PTK_OPEN_NEW_TAB );
ptk_location_view_chdir( view, ptk_file_browser_get_cwd( file_browser ) );
}
else
{
if ( strcmp( vol->mount_point, ptk_file_browser_get_cwd( file_browser ) ) )
ptk_file_browser_chdir( file_browser, vol->mount_point,
PTK_FB_CHDIR_ADD_HISTORY );
}
}
#else
if ( vfs_volume_is_mounted( vol ) && vfs_volume_get_mount_point( vol ) )
{
ptk_file_browser_emit_open( file_browser, vfs_volume_get_mount_point( vol ),
PTK_OPEN_NEW_TAB );
}
#endif
}
void ptk_location_view_init_model( GtkListStore* list )
{
GtkTreeIter it;
gchar* name;
gchar* real_path;
PtkBookmarks* bookmarks;
const GList* l;
n_vols = 0;
l = vfs_volume_get_all_volumes();
vfs_volume_add_callback( on_volume_event, model );
for ( ; l; l = l->next )
{
add_volume( (VFSVolume*)l->data, FALSE );
}
update_volume_icons();
}
GtkWidget* ptk_location_view_new( PtkFileBrowser* file_browser )
{
GtkWidget* view;
GtkTreeViewColumn* col;
GtkCellRenderer* renderer;
GtkListStore* list;
GtkIconTheme* icon_theme;
if ( ! model )
{
list = gtk_list_store_new( N_COLS,
GDK_TYPE_PIXBUF,
G_TYPE_STRING,
G_TYPE_STRING,
G_TYPE_POINTER );
g_object_weak_ref( G_OBJECT( list ), on_model_destroy, NULL );
model = ( GtkTreeModel* ) list;
ptk_location_view_init_model( list );
icon_theme = gtk_icon_theme_get_default();
theme_changed = g_signal_connect( icon_theme, "changed",
G_CALLBACK( update_volume_icons ), NULL );
}
else
{
g_object_ref( G_OBJECT( model ) );
}
view = gtk_tree_view_new_with_model( model );
g_object_unref( G_OBJECT( model ) );
//printf("ptk_location_view_new view = %d\n", view );
GtkTreeSelection* tree_sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( view ) );
gtk_tree_selection_set_mode( tree_sel, GTK_SELECTION_SINGLE );
/*gtk_tree_view_enable_model_drag_dest (
GTK_TREE_VIEW( view ),
drag_targets, G_N_ELEMENTS( drag_targets ), GDK_ACTION_LINK ); */ //MOD
gtk_tree_view_set_headers_visible( GTK_TREE_VIEW( view ), FALSE );
//g_signal_connect( view, "drag-motion", G_CALLBACK( on_drag_motion ), NULL ); //MOD
//g_signal_connect( view, "drag-drop", G_CALLBACK( on_drag_drop ), NULL ); //MOD
//g_signal_connect( view, "drag-data-received", G_CALLBACK( on_drag_data_received ), NULL ); //MOD
col = gtk_tree_view_column_new();
renderer = gtk_cell_renderer_pixbuf_new();
gtk_tree_view_column_pack_start( col, renderer, FALSE );
gtk_tree_view_column_set_attributes( col, renderer,
"pixbuf", COL_ICON, NULL );
renderer = gtk_cell_renderer_text_new();
//g_signal_connect( renderer, "edited", G_CALLBACK(on_bookmark_edited), view ); //MOD
gtk_tree_view_column_pack_start( col, renderer, TRUE );
gtk_tree_view_column_set_attributes( col, renderer,
"text", COL_NAME, NULL );
gtk_tree_view_column_set_min_width( col, 10 );
if ( GTK_IS_TREE_SORTABLE( model ) ) // why is this needed to stop error on new tab?
gtk_tree_sortable_set_sort_column_id( GTK_TREE_SORTABLE( model ), COL_NAME,
GTK_SORT_ASCENDING ); //MOD
//gtk_tree_view_column_set_sort_indicator( col, TRUE ); //MOD
//gtk_tree_view_column_set_sort_column_id( col, COL_NAME ); //MOD
//gtk_tree_view_column_set_sort_order( col, GTK_SORT_ASCENDING ); //MOD
gtk_tree_view_append_column ( GTK_TREE_VIEW( view ), col );
gtk_tree_view_column_set_sizing( col, GTK_TREE_VIEW_COLUMN_AUTOSIZE );
g_object_set_data( G_OBJECT( view ), "file_browser", file_browser );
g_signal_connect( view, "row-activated", G_CALLBACK( on_row_activated ), file_browser );
g_signal_connect( view, "button-press-event", G_CALLBACK( on_button_press_event ), NULL );
// set font
if ( xset_get_s_panel( file_browser->mypanel, "font_dev" ) )
{
PangoFontDescription* font_desc = pango_font_description_from_string(
xset_get_s_panel( file_browser->mypanel, "font_dev" ) );
gtk_widget_modify_font( view, font_desc );
pango_font_description_free( font_desc );
}
return view;
}
void on_volume_event ( VFSVolume* vol, VFSVolumeState state, gpointer user_data )
{
switch ( state )
{
case VFS_VOLUME_ADDED:
add_volume( vol, TRUE );
break;
case VFS_VOLUME_REMOVED:
remove_volume( vol );
break;
case VFS_VOLUME_CHANGED:
if ( !volume_is_visible( vol ) )
remove_volume( vol );
else
update_volume( vol );
break;
default:
break;
}
}
void add_volume( VFSVolume* vol, gboolean set_icon )
{
GtkIconTheme * icon_theme;
GdkPixbuf* icon;
GtkTreeIter it;
const char* mnt;
if ( !volume_is_visible( vol ) )
return;
mnt = vfs_volume_get_mount_point( vol );
if( mnt && !*mnt )
mnt = NULL;
gtk_list_store_insert_with_values( GTK_LIST_STORE( model ), &it, 0,
COL_NAME,
vfs_volume_get_disp_name( vol ),
COL_PATH,
mnt,
COL_DATA, vol, -1 );
if( set_icon )
{
icon_theme = gtk_icon_theme_get_default();
icon = vfs_load_icon ( icon_theme,
vfs_volume_get_icon( vol ),
app_settings.small_icon_size );
gtk_list_store_set( GTK_LIST_STORE( model ), &it, COL_ICON, icon, -1 );
if ( icon )
g_object_unref( icon );
}
++n_vols;
}
void remove_volume( VFSVolume* vol )
{
GtkTreeIter it;
VFSVolume* v = NULL;
if ( !vol )
return;
if ( gtk_tree_model_get_iter_first( model, &it ) )
{
do
{
gtk_tree_model_get( model, &it, COL_DATA, &v, -1 );
}
while ( v != vol && gtk_tree_model_iter_next( model, &it ) );
}
if ( v != vol )
return ;
gtk_list_store_remove( GTK_LIST_STORE( model ), &it );
--n_vols;
}
void update_volume( VFSVolume* vol )
{
GtkIconTheme * icon_theme;
GdkPixbuf* icon;
GtkTreeIter it;
VFSVolume* v = NULL;
if ( !vol )
return;
if ( gtk_tree_model_get_iter_first( model, &it ) )
{
do
{
gtk_tree_model_get( model, &it, COL_DATA, &v, -1 );
}
while ( v != vol && gtk_tree_model_iter_next( model, &it ) );
}
if ( v != vol )
{
add_volume( vol, TRUE );
return;
}
icon_theme = gtk_icon_theme_get_default();
icon = vfs_load_icon ( icon_theme,
vfs_volume_get_icon( vol ),
app_settings.small_icon_size );
gtk_list_store_set( GTK_LIST_STORE( model ), &it,
COL_ICON,
icon,
COL_NAME,
vfs_volume_get_disp_name( vol ),
COL_PATH,
vfs_volume_get_mount_point( vol ), -1 );
if ( icon )
g_object_unref( icon );
}
#ifdef HAVE_HAL
static void on_mount( GtkMenuItem* item, VFSVolume* vol )
{
GError* err = NULL;
GtkWidget* view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
if ( view )
show_busy( view );
if( ! vfs_volume_mount( vol, &err ) )
{
char* msg = g_markup_escape_text(err->message, -1);
if ( view )
show_ready( view );
ptk_show_error( NULL, _("Unable to mount device"), msg );
g_free(msg);
g_error_free( err );
}
else if ( view )
show_ready( view );
}
static void on_umount( GtkMenuItem* item, VFSVolume* vol )
{
GError* err = NULL;
GtkWidget* view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
if ( view )
show_busy( view );
if( ! vfs_volume_umount( vol, &err ) )
{
char* msg = g_markup_escape_text(err->message, -1);
if ( view )
show_ready( view );
ptk_show_error( NULL, _("Unable to unmount device"), msg );
g_free(msg);
g_error_free( err );
}
else if ( view )
show_ready( view );
}
static void on_eject( GtkMenuItem* item, VFSVolume* vol )
{
GError* err = NULL;
GtkWidget* view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
if( vfs_volume_is_mounted( vol ) )
{
if ( view )
show_busy( view );
if( ! vfs_volume_umount( vol, &err ) || ! vfs_volume_eject( vol, &err ) )
{
char* msg = g_markup_escape_text(err->message, -1);
if ( view )
show_ready( view );
ptk_show_error( NULL, _("Unable to eject device"), msg );
g_free(msg);
g_error_free( err );
}
else if ( view )
show_ready( view );
}
}
static gboolean try_mount( GtkTreeView* view, VFSVolume* vol )
{
GError* err = NULL;
GtkWidget* toplevel = gtk_widget_get_toplevel( GTK_WIDGET(view) );
gboolean ret = TRUE;
show_busy( (GtkWidget*)view );
if ( ! vfs_volume_mount( vol, &err ) )
{
char* msg = g_markup_escape_text(err->message, -1);
ptk_show_error( GTK_WINDOW( toplevel ),
_( "Unable to mount device" ),
msg);
g_free(msg);
g_error_free( err );
ret = FALSE;
}
/* Run main loop to process HAL events or volume info won't get updated correctly. */
while(gtk_events_pending () )
gtk_main_iteration ();
show_ready( GTK_WIDGET(view) );
return ret;
}
void mount_network( PtkFileBrowser* file_browser, const char* url, gboolean new_tab )
{
xset_msg_dialog( GTK_WIDGET( file_browser ), GTK_MESSAGE_ERROR,
_("udev Not Configured"), NULL, 0,
_("Mounting a network share requires a udev (--disable-hal) build of SpaceFM."),
NULL, NULL );
}
#else
void on_autoopen_net_cb( VFSFileTask* task, AutoOpen* ao )
{
const GList* l;
VFSVolume* vol;
const GList* volumes = vfs_volume_get_all_volumes();
for ( l = volumes; l; l = l->next )
{
vol = (VFSVolume*)l->data;
if ( strstr( vol->device_file, ao->device_file ) )
{
if ( vol->is_mounted )
{
vfs_volume_special_mounted( ao->device_file );
if ( GTK_IS_WIDGET( ao->file_browser ) )
{
GDK_THREADS_ENTER();
ptk_file_browser_emit_open( ao->file_browser, vol->mount_point,
ao->job );
GDK_THREADS_LEAVE();
}
}
break;
}
}
if ( ao->job == PTK_OPEN_NEW_TAB && GTK_IS_WIDGET( ao->file_browser ) )
{
if ( ao->file_browser->side_dev )
ptk_location_view_chdir(
GTK_TREE_VIEW( ao->file_browser->side_dev ),
ptk_file_browser_get_cwd( ao->file_browser ) );
if ( ao->file_browser->side_book )
ptk_bookmark_view_chdir(
GTK_TREE_VIEW( ao->file_browser->side_book ),
ptk_file_browser_get_cwd( ao->file_browser ) );
}
g_free( ao->device_file );
g_slice_free( AutoOpen, ao );
}
void mount_network( PtkFileBrowser* file_browser, const char* url, gboolean new_tab )
{
char* str;
char* line;
netmount_t *netmount = NULL;
char* handler = xset_get_s( "path_hand" );
if ( !handler )
{
str = g_find_program_in_path( "udevil" );
if ( !str )
{
g_free( str );
xset_msg_dialog( GTK_WIDGET( file_browser ), GTK_MESSAGE_ERROR,
_("udevil Not Installed"), NULL, 0,
_("Mounting a network share requires udevil to be installed, or you can set a custom protocol handler by right-clicking on the Path Bar."),
NULL, NULL );
return;
}
g_free( str );
}
// parse
char* neturl = NULL;
char* fstype = NULL;
int i = parse_network_url( url, NULL, &netmount );
if ( i != 1 )
{
// unrecognized url - clean it up in case udevil can mount it
if ( str = strstr( url, "://" ) )
neturl = g_strdup( str + 3 );
else
neturl = g_strdup( url );
if ( str = strchr( neturl, ':' ) )
str[0] = '\0';
}
else
{
neturl = netmount->url;
if ( g_str_has_prefix( neturl, "sshfs#" ) )
{
// sshfs doesn't include sshfs# prefix in mtab
str = neturl;
neturl = g_strdup( str + 6 );
g_free( str );
}
fstype = netmount->fstype;
g_free( netmount->host );
g_free( netmount->ip );
g_free( netmount->port );
g_free( netmount->user );
g_free( netmount->pass );
g_free( netmount->path );
g_slice_free( netmount_t, netmount );
}
// already mounted?
const GList* l;
VFSVolume* vol;
const GList* volumes = vfs_volume_get_all_volumes();
for ( l = volumes; l; l = l->next )
{
vol = (VFSVolume*)l->data;
if ( strstr( vol->device_file, neturl ) )
{
if ( vol->is_mounted )
{
if ( new_tab )
{
ptk_file_browser_emit_open( file_browser, vol->mount_point,
PTK_OPEN_NEW_TAB );
}
else
{
if ( strcmp( vol->mount_point, ptk_file_browser_get_cwd( file_browser ) ) )
ptk_file_browser_chdir( file_browser, vol->mount_point,
PTK_FB_CHDIR_ADD_HISTORY );
}
g_free( neturl );
return;
}
break;
}
}
// task
char* keepterm;
gboolean in_term = FALSE;
gboolean is_sync = TRUE;
if ( !handler && !g_strcmp0( fstype, "sshfs" ) )
{
in_term = TRUE;
is_sync = FALSE;
keepterm = g_strdup_printf( " ; if [ $? -ne 0 ]; then echo \"%s\"; read; else echo \"Press Enter to close (closing this window may unmount sshfs)\"; read; fi", press_enter_to_close );
}
else if ( !handler && ( !g_strcmp0( fstype, "smbfs" ) ||
!g_strcmp0( fstype, "cifs" ) ||
!g_strcmp0( fstype, "curlftpfs" ) ||
!g_strcmp0( fstype, "davfs" ) ) )
{
in_term = TRUE;
keepterm = g_strdup_printf( " || ( echo \"%s\"; read )", press_enter_to_close );
}
else
keepterm = g_strdup( "" );
AutoOpen* ao = NULL;
if ( is_sync )
{
ao = g_slice_new0( AutoOpen );
ao->device_file = neturl;
ao->file_browser = file_browser;
if ( new_tab )
ao->job = PTK_OPEN_NEW_TAB;
else
ao->job = PTK_OPEN_DIR;
}
str = "echo Connecting...;"; // do not translate
if ( handler )
line = g_strdup_printf( "%s %s '%s'", str, handler, url );
else
line = g_strdup_printf( "%s udevil mount '%s'%s", str, url, keepterm );
g_free( keepterm );
g_free( fstype );
char* task_name = g_strdup_printf( _("Netmount %s"), url );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL, GTK_WIDGET( file_browser ),
file_browser->task_view );
g_free( task_name );
task->task->exec_command = line;
task->task->exec_sync = is_sync;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE;
task->task->exec_terminal = in_term;
task->task->exec_keep_terminal = FALSE;
XSet* set = xset_get( "dev_icon_network" );
task->task->exec_icon = g_strdup( set->icon );
task->complete_notify = is_sync ? (GFunc)on_autoopen_net_cb : NULL;
task->user_data = ao;
ptk_file_task_run( task );
return;
}
static void popup_missing_mount( GtkWidget* view, int job )
{
const char *cmd, *cmdcap;
if ( job == 0 )
{
cmd = "mount";
cmdcap = "Mount";
}
else
{
cmd = "unmount";
cmdcap = "Unmount";
}
char* msg = g_strdup_printf( "No %s program was found. Please install udisks or set a custom %s command in Settings|%s Command.", cmd, cmd, cmdcap );
xset_msg_dialog( view, GTK_MESSAGE_ERROR, "Program Not Installed", NULL, 0,
msg, NULL, NULL );
g_free( msg );
}
static void on_mount( GtkMenuItem* item, VFSVolume* vol, GtkWidget* view2 )
{
GtkWidget* view;
if ( !item )
view = view2;
else
view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
if ( !view || !vol )
return;
if ( !vol->device_file )
return;
PtkFileBrowser* file_browser = (PtkFileBrowser*)g_object_get_data( G_OBJECT(view),
"file_browser" );
if ( !file_browser )
return;
// task
char* line = vfs_volume_get_mount_command( vol, xset_get_s( "dev_mount_options" ) );
if ( !line )
{
popup_missing_mount( view, 0 );
return;
}
char* task_name = g_strdup_printf( _("Mount %s"), vol->device_file );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL, view, file_browser->task_view );
g_free( task_name );
if ( strstr( line, "udisks " ) ) // udisks v1
task->task->exec_type = VFS_EXEC_UDISKS;
task->task->exec_command = line;
task->task->exec_sync = TRUE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE;
task->task->exec_icon = g_strdup( vfs_volume_get_icon( vol ) );
vol->inhibit_auto = TRUE;
ptk_file_task_run( task );
}
static void on_check_root( GtkMenuItem* item, VFSVolume* vol, GtkWidget* view2 )
{
GtkWidget* view;
char* msg;
if ( !item )
view = view2;
else
view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
if ( vol->is_mounted )
{
msg = g_strdup_printf( _("%s is currently mounted. You must unmount it before you can check it."), vol->device_file );
xset_msg_dialog( view, 0, _("Device Is Mounted"), NULL, 0, msg, NULL, "#devices-root-check" );
g_free( msg );
return;
}
XSet* set = xset_get( "dev_root_check" );
msg = g_strdup_printf( _("Enter filesystem check command:\n\nUse:\n\t%%%%v\tdevice file ( %s )\n\nEDIT WITH CARE This command is run as root"), vol->device_file );
if ( !set->s )
set->s = g_strdup( set->desc );
char* old_set_s = g_strdup( set->s );
if ( xset_text_dialog( view, _("Check As Root"),
xset_get_image( "GTK_STOCK_DIALOG_WARNING",
GTK_ICON_SIZE_DIALOG ),
TRUE, _("CHECK AS ROOT"), msg, set->s,
&set->s, set->desc, TRUE, set->line )
&& set->s )
{
gboolean change_root = ( !old_set_s || strcmp( old_set_s, set->s ) );
char* cmd = replace_string( set->s, "%v", vol->device_file, FALSE );
// task
PtkFileBrowser* file_browser = (PtkFileBrowser*)g_object_get_data( G_OBJECT(view),
"file_browser" );
char* task_name = g_strdup_printf( _("Check As Root %s"), vol->device_file );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL, view, file_browser->task_view );
g_free( task_name );
char* scmd = g_strdup_printf( "echo \">>> %s\"; echo; %s; echo; echo -n \"%s: \"; read s", cmd, cmd, press_enter_to_close );
g_free( cmd );
task->task->exec_command = scmd;
task->task->exec_write_root = change_root;
task->task->exec_as_user = g_strdup_printf( "root" );
task->task->exec_sync = FALSE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = FALSE;
task->task->exec_export = FALSE;
task->task->exec_terminal = TRUE;
task->task->exec_browser = file_browser;
task->task->exec_icon = g_strdup( vfs_volume_get_icon( vol ) );
ptk_file_task_run( task );
}
g_free( msg );
}
static void on_mount_root( GtkMenuItem* item, VFSVolume* vol, GtkWidget* view2 )
{
GtkWidget* view;
if ( !item )
view = view2;
else
view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
XSet* set = xset_get( "dev_root_mount" );
char* options = vfs_volume_get_mount_options( vol, xset_get_s( "dev_mount_options" ) );
if ( !options )
options = g_strdup( "" );
char* msg = g_strdup_printf( _("Enter mount command:\n\nUse:\n\t%%%%v\tdevice file ( %s )\n\t%%%%o\tvolume-specific mount options\n\t\t( %s )\n\nNote: fstab overrides some options\n\nEDIT WITH CARE This command is run as root"), vol->device_file, options );
if ( !set->s )
set->s = g_strdup( set->z );
char* old_set_s = g_strdup( set->s );
if ( xset_text_dialog( view, _("Mount As Root"),
xset_get_image( "GTK_STOCK_DIALOG_WARNING",
GTK_ICON_SIZE_DIALOG ),
TRUE, _("MOUNT AS ROOT"), msg, set->s,
&set->s, set->z, TRUE, set->line )
&& set->s )
{
gboolean change_root = ( !old_set_s || strcmp( old_set_s, set->s ) );
char* s1 = replace_string( set->s, "%v", vol->device_file, FALSE );
char* cmd = replace_string( s1, "%o", options, FALSE );
g_free( s1 );
s1 = cmd;
cmd = g_strdup_printf( "echo %s; echo; %s", s1, s1 );
g_free( s1 );
// task
PtkFileBrowser* file_browser = (PtkFileBrowser*)g_object_get_data( G_OBJECT(view),
"file_browser" );
char* task_name = g_strdup_printf( _("Mount As Root %s"), vol->device_file );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL, view, file_browser->task_view );
g_free( task_name );
task->task->exec_command = cmd;
task->task->exec_write_root = change_root;
if ( strstr( cmd, "udisks " ) ) // udisks v1
task->task->exec_type = VFS_EXEC_UDISKS;
task->task->exec_as_user = g_strdup_printf( "root" );
task->task->exec_sync = TRUE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE;
task->task->exec_export = FALSE;
task->task->exec_browser = file_browser;
task->task->exec_icon = g_strdup( vfs_volume_get_icon( vol ) );
ptk_file_task_run( task );
}
g_free( msg );
g_free( options );
}
static void on_umount_root( GtkMenuItem* item, VFSVolume* vol, GtkWidget* view2 )
{
GtkWidget* view;
if ( !item )
view = view2;
else
view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
XSet* set = xset_get( "dev_root_unmount" );
char* msg = g_strdup_printf( _("Enter unmount command:\n\nUse:\n\t%%%%v\tdevice file ( %s )\n\nEDIT WITH CARE This command is run as root"), vol->device_file );
if ( !set->s )
set->s = g_strdup( set->z );
char* old_set_s = g_strdup( set->s );
if ( xset_text_dialog( view, _("Unmount As Root"),
xset_get_image( "GTK_STOCK_DIALOG_WARNING",
GTK_ICON_SIZE_DIALOG ),
TRUE, _("UNMOUNT AS ROOT"), msg, set->s,
&set->s, set->z, TRUE, set->line )
&& set->s )
{
gboolean change_root = ( !old_set_s || strcmp( old_set_s, set->s ) );
// task
char* s1 = replace_string( set->s, "%v", vol->device_file, FALSE );
char* cmd = g_strdup_printf( "echo %s; echo; %s", s1, s1 );
g_free( s1 );
PtkFileBrowser* file_browser = (PtkFileBrowser*)g_object_get_data( G_OBJECT(view),
"file_browser" );
char* task_name = g_strdup_printf( _("Unmount As Root %s"), vol->device_file );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL, view, file_browser->task_view );
g_free( task_name );
if ( strstr( cmd, "udisks " ) ) // udisks v1
task->task->exec_type = VFS_EXEC_UDISKS;
task->task->exec_command = cmd;
task->task->exec_write_root = change_root;
task->task->exec_as_user = g_strdup_printf( "root" );
task->task->exec_sync = TRUE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE;
task->task->exec_export = FALSE;
task->task->exec_browser = file_browser;
task->task->exec_icon = g_strdup( vfs_volume_get_icon( vol ) );
ptk_file_task_run( task );
}
g_free( msg );
}
static void on_change_label( GtkMenuItem* item, VFSVolume* vol, GtkWidget* view2 )
{
GtkWidget* view;
if ( !item )
view = view2;
else
view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
char* fstype;
if ( vol->fs_type && g_ascii_isalnum( vol->fs_type[0] ) )
{
if ( !strcmp( vol->fs_type, "ext2" )
|| !strcmp( vol->fs_type, "ext3" )
|| !strcmp( vol->fs_type, "ext4" ) )
fstype = g_strdup_printf( "label_cmd_ext" );
else
fstype = g_strdup_printf( "label_cmd_%s", vol->fs_type );
}
else
fstype = g_strdup_printf( "label_cmd_unknown" );
XSet* set = xset_get( fstype );
g_free( fstype );
// set->y contains current remove label command
// set->z contains current set label command
// set->desc contains default remove label command
// set->title contains default set label command
if ( !set->y && set->desc )
set->y = g_strdup( set->desc );
if ( !set->x && set->title )
set->x = g_strdup( set->title );
char* mount_warn;
if ( vol->is_mounted )
{
mount_warn = g_strdup_printf( _("\n\nWARNING: %s is mounted. You may want or need to unmount it before changing the label."), vol->device_file );
}
else
mount_warn = g_strdup( "" );
char* msg = g_strdup_printf( _("Enter volume label for %s:%s"), vol->device_file, mount_warn );
char* new_label = NULL;
if ( !xset_text_dialog( view, _("Change Volume Label"),
NULL,
FALSE, msg, NULL, vol->label, &new_label,
NULL, FALSE, set->line ) )
{
g_free( msg );
return;
}
g_free( msg );
char* label_cmd;
char* def_cmd;
char* new_label_cmd = NULL;
if ( !vol->is_mounted )
{
g_free( mount_warn );
mount_warn = g_strdup( "" );
}
if ( !new_label )
{
new_label = g_strdup( "" );
label_cmd = set->y;
def_cmd = set->desc;
msg = g_strdup_printf( _("Enter remove label command for fstype '%s':\n\nUse:\n\t%%%%v\tdevice file ( %s )\n\t%%%%l\tnew label ( \"%s\" )\n\nEDIT WITH CARE This command is run as root%s"), vol->fs_type, vol->device_file, new_label, mount_warn );
}
else
{
label_cmd = set->x;
def_cmd = set->title;
msg = g_strdup_printf( _("Enter change label command for fstype '%s':\n\nUse:\n\t%%%%v\tdevice file ( %s )\n\t%%%%l\tnew label ( \"%s\" )\n\nEDIT WITH CARE This command is run as root%s"), vol->fs_type ? vol->fs_type : "none", vol->device_file, new_label, mount_warn );
}
g_free( mount_warn );
if ( xset_text_dialog( view, _("Change Label As Root"),
xset_get_image( "GTK_STOCK_DIALOG_WARNING",
GTK_ICON_SIZE_DIALOG ),
TRUE, _("LABEL AS ROOT"), msg, label_cmd,
&new_label_cmd, def_cmd, TRUE, set->line )
&& new_label_cmd )
{
gboolean change_root = ( !label_cmd || !new_label_cmd
|| strcmp( label_cmd, new_label_cmd ) );
if ( new_label[0] == '\0' )
xset_set_set( set, "y", new_label_cmd );
else
xset_set_set( set, "x", new_label_cmd );
// task
PtkFileBrowser* file_browser = (PtkFileBrowser*)g_object_get_data( G_OBJECT(view),
"file_browser" );
char* task_name = g_strdup_printf( _("Label As Root %s"), vol->device_file );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL, view, file_browser->task_view );
g_free( task_name );
task->task->exec_write_root = change_root;
char* s1 = new_label;
new_label = g_strdup_printf( "\"%s\"", s1 );
g_free( s1 );
s1 = replace_string( new_label_cmd, "%v", vol->device_file, FALSE );
task->task->exec_command = replace_string( s1, "%l", new_label, FALSE );
g_free( s1 );
g_free( new_label_cmd );
task->task->exec_as_user = g_strdup_printf( "root" );
task->task->exec_sync = TRUE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE;
task->task->exec_keep_tmp = FALSE;
task->task->exec_export = FALSE;
task->task->exec_browser = file_browser;
task->task->exec_icon = g_strdup( vfs_volume_get_icon( vol ) );
ptk_file_task_run( task );
}
g_free( msg );
g_free( new_label );
}
static void on_umount( GtkMenuItem* item, VFSVolume* vol, GtkWidget* view2 )
{
GtkWidget* view;
if ( !item )
view = view2;
else
view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
PtkFileBrowser* file_browser = (PtkFileBrowser*)g_object_get_data( G_OBJECT(view),
"file_browser" );
/*
if ( vol->device_type != DEVICE_TYPE_BLOCK )
{
char* str = g_find_program_in_path( "udevil" );
if ( !str )
{
g_free( str );
xset_msg_dialog( GTK_WIDGET( file_browser ), GTK_MESSAGE_ERROR,
_("udevil Not Installed"), NULL, 0,
_("Unmounting a network share requires udevil to be installed."),
NULL, NULL );
return;
}
g_free( str );
}
*/
// task
char* line = vfs_volume_device_unmount_cmd( vol->device_file );
if ( !line )
{
popup_missing_mount( view, 1 );
return;
}
char* task_name = g_strdup_printf( _("Unmount %s"), vol->device_file );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL, view,
file_browser->task_view );
g_free( task_name );
if ( strstr( line, "udisks " ) ) // udisks v1
task->task->exec_type = VFS_EXEC_UDISKS;
task->task->exec_command = line;
task->task->exec_sync = TRUE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE;
task->task->exec_icon = g_strdup( vfs_volume_get_icon( vol ) );
ptk_file_task_run( task );
}
static void on_eject( GtkMenuItem* item, VFSVolume* vol, GtkWidget* view2 )
{
PtkFileTask* task;
char* line;
GtkWidget* view;
if ( !item )
view = view2;
else
view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
PtkFileBrowser* file_browser = (PtkFileBrowser*)g_object_get_data( G_OBJECT(view),
"file_browser" );
// Note: file_browser may be NULL
/*
if ( vol->device_type != DEVICE_TYPE_BLOCK )
{
char* str = g_find_program_in_path( "udevil" );
if ( !str )
{
g_free( str );
xset_msg_dialog( GTK_WIDGET( file_browser ), GTK_MESSAGE_ERROR,
_("udevil Not Installed"), NULL, 0,
_("Unmounting a network share requires udevil to be installed."),
NULL, NULL );
return;
}
g_free( str );
}
*/
if ( vfs_volume_is_mounted( vol ) )
{
// task
char* eject;
char* unmount = vfs_volume_device_unmount_cmd( vol->device_file );
if ( !unmount )
{
popup_missing_mount( view, 1 );
return;
}
if ( vol->device_type == DEVICE_TYPE_BLOCK &&
( vol->is_optical || vol->requires_eject ) )
eject = g_strdup_printf( "\nelse\n eject %s", vol->device_file );
else
eject = g_strdup( "" );
if ( strstr( unmount, "udisks " ) ) // udisks v1
line = g_strdup_printf( "sync\nfm_udisks=`%s 2>&1`\necho \"$fm_udisks\"\nif [ \"$fm_udisks\" != \"${fm_udisks/ount failed:/}\" ]; then\n exit 1%s\nfi", unmount, eject );
else
line = g_strdup_printf( "sync\n%s\nif [ $? -ne 0 ]; then\n exit 1%s\nfi", unmount, eject );
g_free( eject );
char* task_name = g_strdup_printf( "Remove %s", vol->device_file );
task = ptk_file_exec_new( task_name, NULL, view,
file_browser ? file_browser->task_view : NULL );
g_free( task_name );
if ( strstr( line, "udisks " ) ) // udisks v1
task->task->exec_type = VFS_EXEC_UDISKS;
task->task->exec_command = line;
task->task->exec_sync = TRUE;
task->task->exec_show_error = TRUE;
task->task->exec_icon = g_strdup( vfs_volume_get_icon( vol ) );
}
else if ( vol->is_optical || vol->requires_eject )
{
// task
line = g_strdup_printf( "eject %s", vol->device_file );
char* task_name = g_strdup_printf( _("Remove %s"), vol->device_file );
task = ptk_file_exec_new( task_name, NULL, view,
file_browser ? file_browser->task_view : NULL );
g_free( task_name );
task->task->exec_command = line;
task->task->exec_sync = FALSE;
task->task->exec_show_error = FALSE;
task->task->exec_icon = g_strdup( vfs_volume_get_icon( vol ) );
}
else
{
// task
line = g_strdup_printf( "sync" );
char* task_name = g_strdup_printf( _("Remove %s"), vol->device_file );
task = ptk_file_exec_new( task_name, NULL, view,
file_browser ? file_browser->task_view : NULL );
g_free( task_name );
task->task->exec_command = line;
task->task->exec_sync = FALSE;
task->task->exec_show_error = FALSE;
task->task->exec_icon = g_strdup( vfs_volume_get_icon( vol ) );
}
ptk_file_task_run( task );
}
gboolean on_autoopen_cb( VFSFileTask* task, AutoOpen* ao )
{
const GList* l;
VFSVolume* vol;
//printf("on_autoopen_cb\n");
const GList* volumes = vfs_volume_get_all_volumes();
for ( l = volumes; l; l = l->next )
{
vol = (VFSVolume*)l->data;
if ( !strcmp( vol->device_file, ao->device_file ) )
{
vol->inhibit_auto = FALSE;
if ( vol->is_mounted )
{
if ( GTK_IS_WIDGET( ao->file_browser ) )
{
GDK_THREADS_ENTER(); // hangs on dvd mount without this - why?
ptk_file_browser_emit_open( ao->file_browser, vol->mount_point,
ao->job );
GDK_THREADS_LEAVE();
}
else
open_in_prog( vol->mount_point );
}
break;
}
}
if ( GTK_IS_WIDGET( ao->file_browser ) && ao->job == PTK_OPEN_NEW_TAB &&
ao->file_browser->side_dev )
ptk_location_view_chdir(
GTK_TREE_VIEW( ao->file_browser->side_dev ),
ptk_file_browser_get_cwd( ao->file_browser ) );
g_free( ao->device_file );
g_slice_free( AutoOpen, ao );
return FALSE;
}
static gboolean try_mount( GtkTreeView* view, VFSVolume* vol )
{
if ( !view || !vol )
return FALSE;
PtkFileBrowser* file_browser = (PtkFileBrowser*)g_object_get_data( G_OBJECT(view),
"file_browser" );
if ( !file_browser )
return FALSE;
// task
AutoOpen* ao = g_slice_new0( AutoOpen );
ao->device_file = g_strdup( vol->device_file );
ao->file_browser = file_browser;
if ( xset_get_b( "dev_newtab" ) )
ao->job = PTK_OPEN_NEW_TAB;
else
ao->job = PTK_OPEN_DIR;
char* line = vfs_volume_get_mount_command( vol, xset_get_s( "dev_mount_options" ) );
if ( !line )
{
popup_missing_mount( GTK_WIDGET( view ), 0 );
return FALSE;
}
char* task_name = g_strdup_printf( _("Mount %s"), vol->device_file );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL, GTK_WIDGET( view ),
file_browser->task_view );
g_free( task_name );
if ( strstr( line, "udisks " ) ) // udisks v1
task->task->exec_type = VFS_EXEC_UDISKS;
task->task->exec_command = line;
task->task->exec_sync = TRUE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE; // set to true for error on click
task->task->exec_icon = g_strdup( vfs_volume_get_icon( vol ) );
task->complete_notify = (GFunc)on_autoopen_cb;
task->user_data = ao;
vol->inhibit_auto = TRUE;
ptk_file_task_run( task );
return vfs_volume_is_mounted( vol );
}
static void on_open_tab( GtkMenuItem* item, VFSVolume* vol, GtkWidget* view2 )
{
GtkWidget* view;
if ( !item )
view = view2;
else
view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
if ( !view )
return;
PtkFileBrowser* file_browser = (PtkFileBrowser*)g_object_get_data( G_OBJECT(view),
"file_browser" );
if ( !file_browser || !vol )
return;
if ( !vol->is_mounted )
{
// task
AutoOpen* ao = g_slice_new0( AutoOpen );
ao->device_file = g_strdup( vol->device_file );
ao->file_browser = file_browser;
ao->job = PTK_OPEN_NEW_TAB;
char* line = vfs_volume_get_mount_command( vol, xset_get_s( "dev_mount_options" ) );
if ( !line )
{
popup_missing_mount( view, 0 );
return;
}
char* task_name = g_strdup_printf( _("Mount %s"), vol->device_file );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL, view,
file_browser->task_view );
g_free( task_name );
if ( strstr( line, "udisks " ) ) // udisks v1
task->task->exec_type = VFS_EXEC_UDISKS;
task->task->exec_command = line;
task->task->exec_sync = TRUE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE;
task->task->exec_icon = g_strdup( vfs_volume_get_icon( vol ) );
task->complete_notify = (GFunc)on_autoopen_cb;
task->user_data = ao;
vol->inhibit_auto = TRUE;
ptk_file_task_run( task );
}
else
ptk_file_browser_emit_open( file_browser, vol->mount_point,
PTK_OPEN_NEW_TAB );
}
static void on_open( GtkMenuItem* item, VFSVolume* vol, GtkWidget* view2 )
{
GtkWidget* view;
if ( !item )
view = view2;
else
view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
if ( !view )
return;
PtkFileBrowser* file_browser = (PtkFileBrowser*)g_object_get_data( G_OBJECT(view),
"file_browser" );
// Note: file_browser may be NULL
if ( !vol )
return;
if ( !vol->is_mounted )
{
// task
AutoOpen* ao = g_slice_new0( AutoOpen );
ao->device_file = g_strdup( vol->device_file );
ao->file_browser = file_browser;
ao->job = PTK_OPEN_DIR;
char* line = vfs_volume_get_mount_command( vol, xset_get_s( "dev_mount_options" ) );
if ( !line )
{
popup_missing_mount( view, 0 );
return;
}
char* task_name = g_strdup_printf( _("Mount %s"), vol->device_file );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL, view,
file_browser ? file_browser->task_view : NULL );
g_free( task_name );
if ( strstr( line, "udisks " ) ) // udisks v1
task->task->exec_type = VFS_EXEC_UDISKS;
task->task->exec_command = line;
task->task->exec_sync = TRUE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE;
task->task->exec_icon = g_strdup( vfs_volume_get_icon( vol ) );
task->complete_notify = (GFunc)on_autoopen_cb;
task->user_data = ao;
vol->inhibit_auto = TRUE;
ptk_file_task_run( task );
}
else if ( file_browser )
ptk_file_browser_emit_open( file_browser, vol->mount_point,
PTK_OPEN_DIR );
else
open_in_prog( vol->mount_point );
}
static void on_remount( GtkMenuItem* item, VFSVolume* vol, GtkWidget* view2 )
{
char* line;
GtkWidget* view;
if ( !item )
view = view2;
else
view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
PtkFileBrowser* file_browser = (PtkFileBrowser*)g_object_get_data( G_OBJECT(view),
"file_browser" );
// get user options
XSet* set = xset_get( "dev_remount_options" );
if ( !xset_text_dialog( view, set->title, NULL, TRUE, set->desc, NULL, set->s,
&set->s, set->z, FALSE, set->line ) )
return;
char* mount_command = vfs_volume_get_mount_command( vol, set->s );
if ( !mount_command )
{
popup_missing_mount( view, 0 );
return;
}
// task
char* task_name = g_strdup_printf( _("Remount %s"), vol->device_file );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL, view,
file_browser->task_view );
g_free( task_name );
if ( vfs_volume_is_mounted( vol ) )
{
// udisks can't remount, so unmount and mount
char* unmount_command = vfs_volume_device_unmount_cmd( vol->device_file );
if ( !unmount_command )
{
g_free( mount_command );
popup_missing_mount( view, 1 );
return;
}
if ( strstr( unmount_command, "udisks " ) ) // udisks v1
line = g_strdup_printf( "fm_udisks=`%s 2>&1`\necho \"$fm_udisks\"\nif [ \"$fm_udisks\" != \"${fm_udisks/ount failed:/}\" ]; then\n exit 1\nelse\n %s\nfi",
unmount_command, mount_command );
else
line = g_strdup_printf( "%s\nif [ $? -ne 0 ]; then\n exit 1\nelse\n %s\nfi",
unmount_command, mount_command );
g_free( mount_command );
g_free( unmount_command );
}
else
line = mount_command;
if ( strstr( line, "udisks " ) ) // udisks v1
task->task->exec_type = VFS_EXEC_UDISKS;
task->task->exec_command = line;
task->task->exec_sync = TRUE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE;
task->task->exec_icon = g_strdup( vfs_volume_get_icon( vol ) );
vol->inhibit_auto = TRUE;
ptk_file_task_run( task );
}
static void on_reload( GtkMenuItem* item, VFSVolume* vol, GtkWidget* view2 )
{
char* line;
PtkFileTask* task;
GtkWidget* view;
if ( !item )
view = view2;
else
view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
PtkFileBrowser* file_browser = (PtkFileBrowser*)g_object_get_data( G_OBJECT(view),
"file_browser" );
if ( vfs_volume_is_mounted( vol ) )
{
// task
char* eject;
char* unmount = vfs_volume_device_unmount_cmd( vol->device_file );
if ( !unmount )
{
popup_missing_mount( view, 1 );
return;
}
if ( vol->is_optical || vol->requires_eject )
eject = g_strdup_printf( "\nelse\n eject %s\n sleep 0.3\n eject -t %s", vol->device_file, vol->device_file );
else
eject = g_strdup( "" );
if ( strstr( unmount, "udisks " ) ) // udisks v1
line = g_strdup_printf( "sync\nfm_udisks=`%s 2>&1`\necho \"$fm_udisks\"\nif [ \"$fm_udisks\" != \"${fm_udisks/ount failed:/}\" ]; then\n exit 1%s\nfi", unmount, eject );
else
line = g_strdup_printf( "sync\n%s\nif [ $? -ne 0 ]; then\n exit 1%s\nfi", unmount, eject );
g_free( eject );
char* task_name = g_strdup_printf( "Reload %s", vol->device_file );
task = ptk_file_exec_new( task_name, NULL, view, file_browser->task_view );
g_free( task_name );
if ( strstr( line, "udisks " ) ) // udisks v1
task->task->exec_type = VFS_EXEC_UDISKS;
task->task->exec_command = line;
task->task->exec_sync = TRUE;
task->task->exec_show_error = TRUE;
task->task->exec_icon = g_strdup( vfs_volume_get_icon( vol ) );
}
else if ( vol->is_optical || vol->requires_eject )
{
// task
line = g_strdup_printf( "eject %s; sleep 0.3; eject -t %s",
vol->device_file, vol->device_file );
char* task_name = g_strdup_printf( _("Reload %s"), vol->device_file );
task = ptk_file_exec_new( task_name, NULL, view, file_browser->task_view );
g_free( task_name );
task->task->exec_command = line;
task->task->exec_sync = FALSE;
task->task->exec_show_error = FALSE;
task->task->exec_icon = g_strdup( vfs_volume_get_icon( vol ) );
}
else
return;
ptk_file_task_run( task );
// vol->ever_mounted = FALSE;
}
static void on_sync( GtkMenuItem* item, VFSVolume* vol, GtkWidget* view2 )
{
GtkWidget* view;
if ( !item )
view = view2;
else
{
g_signal_stop_emission_by_name( item, "activate" );
view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
}
PtkFileBrowser* file_browser = (PtkFileBrowser*)g_object_get_data( G_OBJECT(view),
"file_browser" );
PtkFileTask* task = ptk_file_exec_new( _("Sync"), NULL, view, file_browser->task_view );
task->task->exec_browser = NULL;
task->task->exec_action = g_strdup_printf( "sync" );
task->task->exec_command = g_strdup_printf( "sync" );
task->task->exec_as_user = NULL;
task->task->exec_sync = TRUE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = TRUE;
task->task->exec_terminal = FALSE;
task->task->exec_export = FALSE;
//task->task->exec_icon = g_strdup_printf( "start-here" );
ptk_file_task_run( task );
}
static void on_format( GtkMenuItem* item, VFSVolume* vol, GtkWidget* view2,
XSet* set2 )
{
GtkWidget* view;
XSet* set;
char* msg;
if ( !item )
{
view = view2;
set = set2;
}
else
{
view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
set = (XSet*)g_object_get_data( G_OBJECT(item), "set" );
}
if ( vol->is_mounted )
{
msg = g_strdup_printf( _("%s is currently mounted. You must unmount it before you can format it."), vol->device_file );
xset_msg_dialog( view, 0, _("Device Is Mounted"), NULL, 0, msg, NULL, "#devices-root-format" );
g_free( msg );
return;
}
if ( !set->s )
set->s = g_strdup( set->title );
char* old_set_s = g_strdup( set->s );
char* entire;
if ( strlen( vol->device_file ) < 9 )
entire = g_strdup_printf( _(" ( AN ENTIRE DEVICE ) ") );
else
entire = g_strdup( "" );
if ( !strcmp( set->desc, "zero" ) || !strcmp( set->desc, "urandom" ) )
{
msg = g_strdup_printf( _("You are about to erase %s %s- ALL DATA WILL BE LOST. Be patient - this can take awhile and dd gives no feedback.\n\nEnter command to overwrite entire volume with /dev/%s:\n\nUse:\n\t%%%%v\tdevice file ( %s )\n\nEDIT WITH CARE This command is run as root"), vol->device_file, entire, set->desc, vol->device_file );
}
else
msg = g_strdup_printf( _("You are about to format %s %s- ALL DATA WILL BE LOST.\n\nEnter %s format command:\n\nUse:\n\t%%%%v\tdevice file ( %s )\n\nEDIT WITH CARE This command is run as root"), vol->device_file, entire, set->desc, vol->device_file );
if ( xset_text_dialog( view, _("Format"),
xset_get_image( "GTK_STOCK_DIALOG_WARNING",
GTK_ICON_SIZE_DIALOG ),
TRUE, _("DATA LOSS WARNING"), msg, set->s,
&set->s, set->title, TRUE, set->line )
&& set->s )
{
gboolean change_root = ( !old_set_s || strcmp( old_set_s, set->s ) );
// task
char* cmd = replace_string( set->s, "%v", vol->device_file, FALSE );
PtkFileBrowser* file_browser = (PtkFileBrowser*)g_object_get_data( G_OBJECT(view),
"file_browser" );
char* task_name = g_strdup_printf( _("Format %s"), vol->device_file );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL, view, file_browser->task_view );
g_free( task_name );
char* scmd = g_strdup_printf( "echo \">>> %s\"; echo; echo \"%s %s\"; echo; echo -n \"%s: \"; read s; if [ \"$s\" != \"yes\" ]; then exit; fi; %s; echo; echo -n \"%s: \"; read s", cmd, data_loss_overwrite, vol->device_file, type_yes_to_proceed, cmd, press_enter_to_close );
g_free( cmd );
task->task->exec_command = scmd;
task->task->exec_write_root = change_root;
task->task->exec_as_user = g_strdup_printf( "root" );
task->task->exec_sync = FALSE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = FALSE;
task->task->exec_export = FALSE;
task->task->exec_terminal = TRUE;
task->task->exec_browser = file_browser;
task->task->exec_icon = g_strdup( vfs_volume_get_icon( vol ) );
ptk_file_task_run( task );
}
g_free( msg );
if ( old_set_s )
g_free( old_set_s );
g_free( entire );
}
static void on_restore( GtkMenuItem* item, VFSVolume* vol, GtkWidget* view2,
XSet* set2 )
{
GtkWidget* view;
XSet* set;
char* msg;
gboolean change_root = FALSE;
if ( !item )
{
view = view2;
set = set2;
}
else
{
view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
set = (XSet*)g_object_get_data( G_OBJECT(item), "set" );
}
if ( vol->is_mounted )
{
msg = g_strdup_printf( _("%s is currently mounted. You must unmount it before you can restore it."), vol->device_file );
xset_msg_dialog( view, GTK_MESSAGE_ERROR, _("Device Is Mounted"), NULL, 0,
msg, NULL,
"#devices-root-resfile" );
g_free( msg );
return;
}
char* bfile = xset_file_dialog( view, GTK_FILE_CHOOSER_ACTION_OPEN, _("Choose Backup For Restore"),
set->z, set->s );
if ( !bfile )
return;
char* bname = g_path_get_basename( bfile );
if ( set->z )
g_free( set->z );
set->z = g_path_get_dirname( bfile );
if ( set->s )
g_free( set->s );
set->s = g_path_get_basename( bfile );
int job;
char* type;
char* vfile;
if ( g_str_has_suffix( bfile, ".fsa" ) || strstr( bfile, "fsarchiver" ) )
{
job = 0;
type = "FSArchiver";
}
else if ( g_str_has_suffix( bfile, ".000" ) || strstr( bfile, "partimage" ) )
{
job = 1;
type = "Partimage";
}
else if ( g_str_has_suffix( bfile, ".mbr.bin" )
|| g_str_has_suffix( bfile, ".mbr" )
|| g_str_has_suffix( bfile, "-MBR-back" ) )
{
job = 2;
type = "MBR";
vfile = g_strndup( vol->device_file, 8 );
msg = g_strdup_printf( _("You are about to overwrite the MBR boot code of %s using %s.\n\nThis change may prevent your computer from booting properly. All important data on the entire device should be backed up first.\n\nProceed? (If you press Yes, you still have one more opportunity to abort before the disk is modified.)"), vfile, bname );
if ( xset_msg_dialog( view, GTK_MESSAGE_WARNING, _("Restore MBR"), NULL, GTK_BUTTONS_YES_NO, _("DATA LOSS WARNING"), msg, "#devices-root-resfile" ) != GTK_RESPONSE_YES )
{
g_free( vfile );
g_free( bfile );
g_free( bname );
g_free( msg );
return;
}
g_free( msg );
}
else
{
xset_msg_dialog( view, GTK_MESSAGE_ERROR, _("Unknown Type"), NULL, 0, _("The selected file is not a recognized backup file.\n\nFSArchiver filenames contain 'fsarchiver' or end in '.fsa'. Partimage filenames contain 'partimage' or end in '.000'. MBR filenames end in '.mbr', '.mbr.bin', or '-MBR-back' and are 512 bytes in size. If you are SURE this file is a valid backup, you can rename it to avoid this error."), NULL, "#devices-root-resinfo" );
g_free( bfile );
g_free( bname );
return;
}
// get command
char* sfile = bash_quote( bfile );
char* cmd;
if ( job == 2 )
{
// restore only first 448 bytes of MBR to leave partition table untouched
cmd = g_strdup_printf( "dd if=%s of=%s bs=448 count=1", sfile, vfile );
}
else
{
char* set_cmd;
char* def_cmd;
char* new_cmd = NULL;
vfile = g_strdup( vol->device_file );
if ( job == 0 )
{
//fsa
if ( !set->x )
set->x = g_strdup( set->desc );
set_cmd = set->x;
def_cmd = set->desc;
}
else
{
//partimage
if ( !set->y )
set->y = g_strdup( set->title );
set_cmd = set->y;
def_cmd = set->title;
}
char* entire;
if ( strlen( vol->device_file ) < 9 )
entire = _(" ( AN ENTIRE DEVICE ) ");
else
entire = "";
msg = g_strdup_printf( _("You are about to restore %s %susing %s - ALL DATA WILL BE LOST.\n\nEnter %s restore command:\n\nUse:\n\t%%%%v\tdevice file ( %s )\n\t%%%%s\tbackup file ( %s )\n\nEDIT WITH CARE This command is run as root"), vol->device_file, entire, bname, type, vol->device_file, bname );
if ( xset_text_dialog( view, _("Restore"),
xset_get_image( "GTK_STOCK_DIALOG_WARNING",
GTK_ICON_SIZE_DIALOG ),
TRUE, _("DATA LOSS WARNING"), msg, set_cmd, &new_cmd, def_cmd,
TRUE, set->line ) && new_cmd )
{
change_root = ( !set_cmd || !new_cmd || strcmp( set_cmd, new_cmd ) );
if ( job == 0 )
{
//fsa
if ( set->x )
g_free( set->x );
set->x = new_cmd;
}
else
{
//partimage
if ( set->y )
g_free( set->y );
set->y = new_cmd;
}
char* s1 = replace_string( new_cmd, "%v", vol->device_file, FALSE );
cmd = replace_string( s1, "%s", sfile, FALSE );
g_free( s1 );
g_free( msg );
}
else
{
g_free( msg );
g_free( bfile );
return;
}
}
g_free( bfile );
g_free( bname );
// task
PtkFileBrowser* file_browser = (PtkFileBrowser*)g_object_get_data( G_OBJECT(view),
"file_browser" );
char* task_name = g_strdup_printf( _("%s Restore %s"), type, vfile );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL, view, file_browser->task_view );
g_free( task_name );
char* scmd;
if ( job == 2 )
scmd = g_strdup_printf( "echo \">>> %s\"; echo; echo \"%s %s\"; echo; echo -n \"%s: \"; read s; if [ \"$s\" != \"yes\" ]; then exit; fi; %s; echo; echo -n \"%s \"; read s", cmd, "DATA LOSS WARNING - overwriting MBR boot code of", vfile, type_yes_to_proceed, cmd, press_enter_to_close );
else if ( job == 1 )
scmd = g_strdup_printf( "echo \">>> %s\"; echo; echo \"%s %s\"; echo; echo -n \"%s: \"; read s; if [ \"$s\" != \"yes\" ]; then exit; fi; %s; echo; echo -n \"%s: \"; read s", cmd, data_loss_overwrite, vfile, type_yes_to_proceed, cmd, press_enter_to_close );
else
{
// sudo has trouble finding fsarchiver because it's not in user path
char* fsarc_bin = g_strdup( "/usr/sbin/fsarchiver" );
if ( !g_file_test( fsarc_bin, G_FILE_TEST_EXISTS ) )
{
g_free( fsarc_bin );
fsarc_bin = g_strdup( "/sbin/fsarchiver" );
if ( !g_file_test( fsarc_bin, G_FILE_TEST_EXISTS ) )
{
g_free( fsarc_bin );
fsarc_bin = g_strdup( "fsarchiver" );
}
}
scmd = g_strdup_printf( "echo \">>> %s archinfo %s\"; echo; %s archinfo %s; echo; echo \">>> %s\"; echo; echo \"%s %s\"; echo; echo -n \"%s: \"; read s; if [ \"$s\" != \"yes\" ]; then exit; fi; %s; echo; echo -n \"%s: \"; read s", fsarc_bin, sfile, fsarc_bin, sfile, cmd, data_loss_overwrite, vfile, type_yes_to_proceed, cmd, press_enter_to_close );
g_free( fsarc_bin );
}
g_free( cmd );
g_free( vfile );
g_free( sfile );
task->task->exec_command = scmd;
task->task->exec_write_root = change_root;
task->task->exec_as_user = g_strdup_printf( "root" );
task->task->exec_sync = FALSE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = FALSE;
task->task->exec_export = FALSE;
task->task->exec_terminal = TRUE;
task->task->exec_browser = file_browser;
task->task->exec_icon = g_strdup( vfs_volume_get_icon( vol ) );
ptk_file_task_run( task );
}
static void on_root_fstab( GtkMenuItem* item, GtkWidget* view )
{
xset_edit( view, "/etc/fstab", TRUE, FALSE );
}
static void on_root_udevil( GtkMenuItem* item, GtkWidget* view )
{
if ( g_file_test( "/etc/udevil", G_FILE_TEST_IS_DIR ) )
xset_edit( view, "/etc/udevil/udevil.conf", TRUE, FALSE );
else
xset_msg_dialog( view, GTK_MESSAGE_ERROR, _("Directory Missing"), NULL, 0,
_("The /etc/udevil directory was not found. Is udevil installed?"),
NULL, NULL );
}
static void on_restore_info( GtkMenuItem* item, GtkWidget* view, XSet* set2 )
{
XSet* set;
if ( !item )
set = set2;
else
set = (XSet*)g_object_get_data( G_OBJECT(item), "set" );
char* bfile = xset_file_dialog( view, GTK_FILE_CHOOSER_ACTION_OPEN, _("Choose Backup For Info"),
set->z, set->s );
if ( !bfile )
return;
if ( set->z )
g_free( set->z );
set->z = g_path_get_dirname( bfile );
if ( set->s )
g_free( set->s );
set->s = g_path_get_basename( bfile );
char* sfile = bash_quote( bfile );
char* cmd;
if ( g_str_has_suffix( bfile, ".fsa" ) || strstr( bfile, "fsarchiver" ) )
{
// sudo has trouble finding fsarchiver because it's not in user path
char* fsarc_bin = g_strdup( "/usr/sbin/fsarchiver" );
if ( !g_file_test( fsarc_bin, G_FILE_TEST_EXISTS ) )
{
g_free( fsarc_bin );
fsarc_bin = g_strdup( "/sbin/fsarchiver" );
if ( !g_file_test( fsarc_bin, G_FILE_TEST_EXISTS ) )
{
g_free( fsarc_bin );
fsarc_bin = g_strdup( "fsarchiver" );
}
}
cmd = g_strdup_printf( "%s archinfo %s", fsarc_bin, sfile );
g_free( fsarc_bin );
}
else if ( g_str_has_suffix( bfile, ".000" ) || strstr( bfile, "partimage" ) )
{
// sudo has trouble finding partimage because it's not in user path
char* pi_bin = g_strdup( "/usr/sbin/partimage" );
if ( !g_file_test( pi_bin, G_FILE_TEST_EXISTS ) )
{
g_free( pi_bin );
pi_bin = g_strdup( "/sbin/partimage" );
if ( !g_file_test( pi_bin, G_FILE_TEST_EXISTS ) )
{
g_free( pi_bin );
pi_bin = g_strdup( "partimage" );
}
}
cmd = g_strdup_printf( "%s imginfo %s", pi_bin, sfile );
g_free( pi_bin );
}
else if ( g_str_has_suffix( bfile, ".mbr.bin" )
|| g_str_has_suffix( bfile, ".mbr" )
|| g_str_has_suffix( bfile, "-MBR-back" ) )
{
xset_msg_dialog( view, 0, _("MBR File"), NULL, 0, _("Based on its name, the selected file appears to be an MBR backup file. No other information is available for this type of backup."), NULL, "#devices-root-resinfo" );
g_free( bfile );
return;
}
else
{
xset_msg_dialog( view, GTK_MESSAGE_ERROR, _("Unknown Type"), NULL, 0, _("The selected file is not a recognized backup file.\n\nFSArchiver filenames contain 'fsarchiver' or end in '.fsa'. Partimage filenames contain 'partimage' or end in '.000'. MBR filenames end in '.mbr', '.mbr.bin', or '-MBR-back' and are 512 bytes in size. If you are SURE this file is a valid backup, you can rename it to avoid this error."), NULL, "#devices-root-resinfo" );
g_free( bfile );
return;
}
g_free( bfile );
g_free( sfile );
// task
PtkFileBrowser* file_browser = (PtkFileBrowser*)g_object_get_data( G_OBJECT(view),
"file_browser" );
PtkFileTask* task = ptk_file_exec_new( _("Restore Info"), NULL, view, file_browser->task_view );
task->task->exec_command = g_strdup_printf( "echo \">>> %s\"; echo; %s; echo; echo -n \"%s: \"; read s", cmd, cmd, press_enter_to_close );
g_free( cmd );
task->task->exec_as_user = g_strdup_printf( "root" );
task->task->exec_sync = FALSE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = FALSE;
task->task->exec_export = FALSE;
task->task->exec_terminal = TRUE;
task->task->exec_browser = file_browser;
ptk_file_task_run( task );
}
static void on_backup( GtkMenuItem* item, VFSVolume* vol, GtkWidget* view2,
XSet* set2 )
{
GtkWidget* view;
XSet* set;
char* msg;
char* msg2;
if ( !item )
{
view = view2;
set = set2;
}
else
{
view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
set = (XSet*)g_object_get_data( G_OBJECT(item), "set" );
}
char* vfile;
char* bfile;
char* vshort;
char* cmd;
char* hostname;
char buf[256];
gboolean change_root = FALSE;
if ( gethostname( buf, 256 ) == 0 )
{
hostname = g_strdup_printf( "%s-", buf );
}
else
hostname = g_strdup( "" );
if ( !strcmp( set->name, "dev_back_mbr" ) )
{
vfile = g_strndup( vol->device_file, 8 );
vshort = g_path_get_basename( vfile );
bfile = g_strdup_printf( "backup-%s%s.mbr.bin", hostname, vshort );
}
else if ( !strcmp( set->name, "dev_back_fsarc" ) )
{
vfile = g_strdup( vol->device_file );
vshort = g_path_get_basename( vfile );
bfile = g_strdup_printf( "backup-%s%s.fsarchiver.fsa", hostname, vshort );
if ( vol->is_mounted )
msg2 = g_strdup_printf( _("\n\nWARNING: %s is mounted. By default, FSArchiver will only backup volumes mounted read-only. To backup a read-write volume, you need to add --allow-rw-mounted to the command. See 'man fsarchiver' for details."), vol->device_file );
else
msg2 = g_strdup( "" );
}
else if ( !strcmp( set->name, "dev_back_part" ) )
{
if ( vol->is_mounted )
{
msg = g_strdup_printf( _("%s is currently mounted. You must unmount it before you can create a backup using Partimage."), vol->device_file );
xset_msg_dialog( view, GTK_MESSAGE_ERROR, _("Device Is Mounted"),
NULL, 0, msg, NULL, "#devices-root-parti" );
g_free( msg );
g_free( hostname );
return;
}
vfile = g_strdup( vol->device_file );
vshort = g_path_get_basename( vfile );
bfile = g_strdup_printf( "backup-%s%s.partimage", hostname, vshort );
msg2 = g_strdup( "" );
}
else
return; // failsafe
g_free( vshort );
g_free( hostname );
char* title = g_strdup_printf( _("Save %s Backup"), set->desc );
char* sfile = xset_file_dialog( view, GTK_FILE_CHOOSER_ACTION_SAVE, title,
set->z, bfile );
g_free( title );
if ( !sfile )
{
g_free( vfile );
g_free( bfile );
return;
}
// test if partimage sfile already exists
if ( !strcmp( set->name, "dev_back_part" ) )
{
char* volb = g_strdup_printf( "%s.000", sfile );
if ( g_file_test( volb, G_FILE_TEST_EXISTS ) )
{
if ( xset_msg_dialog( view, GTK_MESSAGE_QUESTION, _("Overwrite?"), NULL, GTK_BUTTONS_YES_NO, _("The selected backup already exists. Overwrite?"), NULL, "#devices-root-parti" ) != GTK_RESPONSE_YES )
{
g_free( vfile );
g_free( bfile );
g_free( volb );
return;
}
}
g_free( volb );
}
if ( set->z )
g_free( set->z );
set->z = g_path_get_dirname( sfile );
g_free( bfile );
bfile = bash_quote( sfile );
char* bshort = g_path_get_basename( sfile );
g_free( sfile );
if ( !strcmp( set->name, "dev_back_mbr" ) )
{
cmd = g_strdup_printf( "dd if=%s of=%s bs=512 count=1", vfile, bfile );
}
else
{
if ( !set->s )
set->s = g_strdup( set->title );
char* old_set_s = g_strdup( set->s );
msg = g_strdup_printf( _("Enter %s backup command:\n\nUse:\n\t%%%%v\tdevice file ( %s )\n\t%%%%s\tbackup file ( %s )%s\n\nEDIT WITH CARE This command is run as root"),
set->desc, vol->device_file, bshort, msg2 );
g_free( msg2 );
if ( xset_text_dialog( view, _("Backup"), NULL, TRUE, msg, NULL, set->s,
&set->s, set->title, TRUE, set->line )
&& set->s )
{
change_root = ( !old_set_s || strcmp( old_set_s, set->s ) );
char* s1 = replace_string( set->s, "%v", vol->device_file, FALSE );
cmd = replace_string( s1, "%s", bfile, FALSE );
g_free( s1 );
g_free( old_set_s );
g_free( msg );
}
else
{
g_free( bshort );
g_free( msg );
g_free( vfile );
g_free( bfile );
g_free( old_set_s );
return;
}
}
g_free( bfile );
g_free( bshort );
// task
PtkFileBrowser* file_browser = (PtkFileBrowser*)g_object_get_data( G_OBJECT(view),
"file_browser" );
char* task_name = g_strdup_printf( _("%s Backup %s"), set->desc, vfile );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL, view, file_browser->task_view );
g_free( task_name );
g_free( vfile );
char* scmd = g_strdup_printf( "echo \">>> %s\"; echo; %s; echo; echo -n \"%s: \"; read s", cmd, cmd, press_enter_to_close );
g_free( cmd );
task->task->exec_command = scmd;
task->task->exec_write_root = change_root;
task->task->exec_as_user = g_strdup_printf( "root" );
task->task->exec_sync = FALSE;
task->task->exec_popup = FALSE;
task->task->exec_show_output = FALSE;
task->task->exec_show_error = FALSE;
task->task->exec_export = FALSE;
task->task->exec_terminal = TRUE;
task->task->exec_browser = file_browser;
task->task->exec_icon = g_strdup( vfs_volume_get_icon( vol ) );
ptk_file_task_run( task );
}
static void on_prop( GtkMenuItem* item, VFSVolume* vol, GtkWidget* view2 )
{
GtkWidget* view;
char size_str[ 64 ];
char* df;
char* udisks;
char* lsof;
char* infobash;
char* path;
char* flags;
char* old_flags;
char* uuid = NULL;
char* fstab = NULL;
char* cmd;
char* info;
char* esc_path;
if ( !item )
view = view2;
else
view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
if ( !vol || !view )
return;
if ( !vol->device_file )
return;
char* base = g_path_get_basename( vol->device_file );
if ( base )
{
// /bin/ls -l /dev/disk/by-uuid | grep ../sdc2 | sed 's/.* \([a-fA-F0-9\-]*\) -> .*/\1/'
cmd = g_strdup_printf( "bash -c \"/bin/ls -l /dev/disk/by-uuid | grep '\\.\\./%s$' | sed 's/.* \\([a-fA-F0-9-]*\\) -> .*/\\1/'\"", base );
g_spawn_command_line_sync( cmd, &uuid, NULL, NULL, NULL );
g_free( cmd );
if ( uuid && strlen( uuid ) < 9 )
{
g_free( uuid );
uuid = NULL;
}
if ( uuid )
{
if ( old_flags = strchr( uuid, '\n' ) )
old_flags[0] = '\0';
}
if ( uuid )
{
cmd = g_strdup_printf( "bash -c \"cat /etc/fstab | grep -e '%s' -e '%s'\"", uuid, vol->device_file );
//cmd = g_strdup_printf( "bash -c \"cat /etc/fstab | grep -e ^[#\\ ]*UUID=$(/bin/ls -l /dev/disk/by-uuid | grep \\.\\./%s | sed 's/.* \\([a-fA-F0-9\-]*\\) -> \.*/\\1/')\\ */ -e '^[# ]*%s '\"", base, vol->device_file );
g_spawn_command_line_sync( cmd, &fstab, NULL, NULL, NULL );
g_free( cmd );
}
if ( !fstab )
{
cmd = g_strdup_printf( "bash -c \"cat /etc/fstab | grep '%s'\"", vol->device_file );
//cmd = g_strdup_printf( "bash -c \"cat /etc/fstab | grep '^[# ]*%s '\"", vol->device_file );
g_spawn_command_line_sync( cmd, &fstab, NULL, NULL, NULL );
g_free( cmd );
}
if ( fstab && strlen( fstab ) < 9 )
{
g_free( fstab );
fstab = NULL;
}
if ( fstab )
{
///if ( old_flags = strchr( fstab, '\n' ) )
/// old_flags[0] = '\0';
while ( strstr( fstab, " " ) )
{
old_flags = fstab;
fstab = replace_string( fstab, " ", " ", FALSE );
g_free( old_flags );
}
}
}
//printf("dev=%s\nuuid=%s\nfstab=%s\n", vol->device_file, uuid, fstab );
if ( uuid && fstab )
{
info = g_strdup_printf( "echo FSTAB ; echo '%s'; echo INFO ; echo 'UUID=%s' ; ",
fstab, uuid );
g_free( uuid );
g_free( fstab );
}
else if ( uuid && !fstab )
{
info = g_strdup_printf( "echo FSTAB ; echo '( not found )' ; echo ; echo INFO ; echo 'UUID=%s' ; ", uuid );
g_free( uuid );
}
else if ( !uuid && fstab )
{
info = g_strdup_printf( "echo FSTAB ; echo '%s' ; echo INFO ; ", fstab );
g_free( fstab );
}
else
info = g_strdup_printf( "echo FSTAB ; echo '( not found )' ; echo ; echo INFO ; " );
flags = g_strdup_printf( "echo %s ; echo %s ", "DEVICE", vol->device_file );
if ( vol->is_removable )
{ old_flags = flags; flags = g_strdup_printf( "%s removable", flags ); g_free( old_flags ); }
else
{ old_flags = flags; flags = g_strdup_printf( "%s internal", flags ); g_free( old_flags ); }
if ( vol->requires_eject )
{ old_flags = flags; flags = g_strdup_printf( "%s ejectable", flags ); g_free( old_flags ); }
if ( vol->is_optical )
{ old_flags = flags; flags = g_strdup_printf( "%s optical", flags ); g_free( old_flags ); }
if ( vol->is_table )
{ old_flags = flags; flags = g_strdup_printf( "%s table", flags ); g_free( old_flags ); }
if ( vol->is_floppy )
{ old_flags = flags; flags = g_strdup_printf( "%s floppy", flags ); g_free( old_flags ); }
if ( !vol->is_user_visible )
{ old_flags = flags; flags = g_strdup_printf( "%s policy_hide", flags ); g_free( old_flags ); }
if ( vol->nopolicy )
{ old_flags = flags; flags = g_strdup_printf( "%s policy_noauto", flags ); g_free( old_flags ); }
if ( vol->is_mounted )
{ old_flags = flags; flags = g_strdup_printf( "%s mounted", flags ); g_free( old_flags ); }
else if ( vol->is_mountable && !vol->is_table )
{ old_flags = flags; flags = g_strdup_printf( "%s mountable", flags ); g_free( old_flags ); }
else
{ old_flags = flags; flags = g_strdup_printf( "%s no_media", flags ); g_free( old_flags ); }
if ( vol->is_blank )
{ old_flags = flags; flags = g_strdup_printf( "%s blank", flags ); g_free( old_flags ); }
if ( vol->is_audiocd )
{ old_flags = flags; flags = g_strdup_printf( "%s audiocd", flags ); g_free( old_flags ); }
if ( vol->is_dvd )
{ old_flags = flags; flags = g_strdup_printf( "%s dvd", flags ); g_free( old_flags ); }
if ( vol->is_mounted )
{
old_flags = flags;
flags = g_strdup_printf( "%s ; mount | grep \"%s \" | sed 's/\\/dev.*\\( on .*\\)/\\1/' ; echo ; ", flags, vol->device_file );
g_free( old_flags );
}
else
{ old_flags = flags; flags = g_strdup_printf( "%s ; echo ; ", flags ); g_free( old_flags ); }
if ( vol->is_mounted )
{
path = g_find_program_in_path( "df" );
if ( !path )
df = g_strdup_printf( "echo %s ; echo \"( please install df )\" ; echo ; ", "USAGE" );
else
{
esc_path = bash_quote( vol->mount_point );
df = g_strdup_printf( "echo %s ; %s -hT %s ; echo ; ", "USAGE", path, esc_path );
g_free( path );
g_free( esc_path );
}
}
else
{
if ( vol->is_mountable )
{
vfs_file_size_to_string_format( size_str, vol->size, "%.1f %s" );
df = g_strdup_printf( "echo %s ; echo \"%s %s %s ( not mounted )\" ; echo ; ", "USAGE", vol->device_file, vol->fs_type ? vol->fs_type : "", size_str );
}
else
df = g_strdup_printf( "echo %s ; echo \"%s ( no media )\" ; echo ; ", "USAGE", vol->device_file );
}
char* udisks_info = vfs_volume_device_info( vol->device_file );
udisks = g_strdup_printf( "%s\ncat << EOF\n%sEOF\necho ; ", info, udisks_info );
g_free( udisks_info );
if ( vol->is_mounted )
{
path = g_find_program_in_path( "lsof" );
if ( !path )
lsof = g_strdup_printf( "echo %s ; echo \"( %s lsof )\" ; echo ; ", "PROCESSES", "please install" );
else
{
if ( !strcmp( vol->mount_point, "/" ) )
lsof = g_strdup_printf( "echo %s ; %s -w | grep /$ | head -n 500 ; echo ; ", "PROCESSES", path );
else
{
esc_path = bash_quote( vol->mount_point );
lsof = g_strdup_printf( "echo %s ; %s -w %s | head -n 500 ; echo ; ", "PROCESSES", path, esc_path );
g_free( esc_path );
}
g_free( path );
}
}
else
lsof = g_strdup( "" );
/* not desirable ?
if ( path = g_find_program_in_path( "infobash" ) )
{
infobash = g_strdup_printf( "echo SYSTEM ; %s -v3 0 ; echo ; ", path );
g_free( path );
}
else
*/ infobash = g_strdup( "" );
// task
PtkFileBrowser* file_browser = (PtkFileBrowser*)g_object_get_data( G_OBJECT(view),
"file_browser" );
// Note: file_browser may be NULL
char* task_name = g_strdup_printf( _("Properties %s"), vol->device_file );
PtkFileTask* task = ptk_file_exec_new( task_name, NULL,
file_browser ? GTK_WIDGET( file_browser ) : view,
file_browser ? file_browser->task_view : NULL );
g_free( task_name );
// don't free cwd!
task->task->exec_browser = file_browser;
task->task->exec_command = g_strdup_printf( "%s%s%s%s%s", flags, df, udisks, lsof, infobash );
task->task->exec_sync = TRUE;
task->task->exec_popup = TRUE;
task->task->exec_show_output = TRUE;
task->task->exec_export = FALSE;
task->task->exec_scroll_lock = TRUE;
task->task->exec_icon = g_strdup( vfs_volume_get_icon( vol ) );
//task->task->exec_keep_tmp = TRUE;
ptk_file_task_run( task );
g_free( df );
g_free( udisks );
g_free( lsof );
g_free( infobash );
}
static void on_showhide( GtkMenuItem* item, VFSVolume* vol, GtkWidget* view2 )
{
char* msg;
GtkWidget* view;
if ( !item )
view = view2;
else
view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
XSet* set = xset_get( "dev_show_hide_volumes" );
if ( vol )
{
char* devid = vol->udi;
devid = strrchr( devid, '/' );
if ( devid )
devid++;
msg = g_strdup_printf( _("%sCurrently Selected Device: %s\nVolume Label: %s\nDevice ID: %s"),
set->desc, vol->device_file, vol->label, devid );
}
else
msg = g_strdup( set->desc );
if ( xset_text_dialog( view, set->title, NULL, TRUE, msg, NULL, set->s, &set->s,
NULL, FALSE, set->line ) )
update_all();
g_free( msg );
}
static void on_automountlist( GtkMenuItem* item, VFSVolume* vol, GtkWidget* view2 )
{
char* msg;
GtkWidget* view;
if ( !item )
view = view2;
else
view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
XSet* set = xset_get( "dev_automount_volumes" );
if ( vol )
{
char* devid = vol->udi;
devid = strrchr( devid, '/' );
if ( devid )
devid++;
msg = g_strdup_printf( _("%sCurrently Selected Device: %s\nVolume Label: %s\nDevice ID: %s"),
set->desc, vol->device_file, vol->label, devid );
}
else
msg = g_strdup( set->desc );
if ( xset_text_dialog( view, set->title, NULL, TRUE, msg, NULL, set->s, &set->s,
NULL, FALSE, set->line ) )
{
// update view / automount all?
}
g_free( msg );
}
#endif
void open_external_tab( const char* path )
{
char* prog = g_find_program_in_path( g_get_prgname() );
if ( !prog )
prog = g_strdup( g_get_prgname() );
if ( !prog )
prog = g_strdup( "spacefm" );
char* quote_path = bash_quote( path );
char* line = g_strdup_printf( "%s -t %s", prog, quote_path );
g_spawn_command_line_async( line, NULL );
g_free( prog );
g_free( quote_path );
g_free( line );
}
void mount_iso( PtkFileBrowser* file_browser, const char* path )
{
char* udevil = g_find_program_in_path( "udevil" );
if ( !udevil )
{
g_free( udevil );
xset_msg_dialog( file_browser ? GTK_WIDGET( file_browser ) : NULL,
GTK_MESSAGE_ERROR,
_("udevil Not Installed"), NULL, 0,
_("Mounting a disc image file requires udevil to be installed."),
NULL, NULL );
return;
}
char* stdout = NULL;
char* stderr = NULL;
char* command;
gboolean ret;
gint exit_status;
char* str = bash_quote( path );
command = g_strdup_printf( "%s mount %s", udevil, str );
g_free( str );
g_free( udevil );
ret = g_spawn_command_line_sync( command, &stdout, &stderr, &exit_status, NULL );
g_free( command );
if ( !ret || ( exit_status && WIFEXITED( exit_status ) ) )
{
if ( stderr && ( str = strstr( stderr, " is already mounted at " ) ) )
{
char* str2;
if ( str2 = strstr( str, " (or specify mount point" ) )
{
str2[0] = '\0';
if ( file_browser )
ptk_file_browser_emit_open( file_browser, g_strdup( str + 23 ),
PTK_OPEN_NEW_TAB );
else
open_external_tab( str + 23 );
goto _exit_mount_iso;
}
}
xset_msg_dialog( file_browser ? GTK_WIDGET( file_browser ) : NULL,
GTK_MESSAGE_ERROR, _("Mount Disc Image Failed"), NULL,
0, stderr, NULL, NULL );
}
else
{
if ( stdout && g_str_has_prefix( stdout, "Mounted " ) &&
( str = strstr( stdout, " at " ) ) )
{
while ( g_str_has_suffix( stdout, "\n" ) )
stdout[ strlen( stdout ) - 1 ] = '\0';
if ( file_browser )
ptk_file_browser_emit_open( file_browser, g_strdup( str + 4 ),
PTK_OPEN_NEW_TAB );
else
open_external_tab( str + 4 );
// let mount be detected
while (gtk_events_pending ())
gtk_main_iteration ();
#ifndef HAVE_HAL
vfs_volume_special_mounted( str + 4 );
#endif
}
}
_exit_mount_iso:
g_free( stderr );
g_free( stdout );
return;
}
gboolean volume_is_visible( VFSVolume* vol )
{
#ifndef HAVE_HAL
// check show/hide
int i, j;
char* test;
char* value;
char* showhidelist = g_strdup_printf( " %s ", xset_get_s( "dev_show_hide_volumes" ) );
for ( i = 0; i < 3; i++ )
{
for ( j = 0; j < 2; j++ )
{
if ( i == 0 )
value = vol->device_file;
else if ( i == 1 )
value = vol->label;
else
{
if ( value = vol->udi )
{
value = strrchr( value, '/' );
if ( value )
value++;
}
}
if ( value && value[0] != '\0' )
{
if ( j == 0 )
test = g_strdup_printf( " +%s ", value );
else
test = g_strdup_printf( " -%s ", value );
if ( strstr( showhidelist, test ) )
{
g_free( test );
g_free( showhidelist );
return ( j == 0 );
}
g_free( test );
}
}
}
g_free( showhidelist );
// network
if ( vol->device_type == DEVICE_TYPE_NETWORK )
return xset_get_b( "dev_show_net" );
// loop
if ( g_str_has_prefix( vol->device_file, "/dev/loop" ) )
{
if ( vol->is_mounted && xset_get_b( "dev_show_file" ) )
return TRUE;
if ( !vol->is_mountable && !vol->is_mounted )
return FALSE;
// fall through
}
// ramfs CONFIG_BLK_DEV_RAM causes multiple entries of /dev/ram*
if ( !vol->is_mounted && g_str_has_prefix( vol->device_file, "/dev/ram" ) &&
vol->device_file[8] &&
g_ascii_isdigit( vol->device_file[8] ) )
return FALSE;
// internal?
if ( !vol->is_removable && !xset_get_b( "dev_show_internal_drives" ) )
return FALSE;
// table?
if ( vol->is_table && !xset_get_b( "dev_show_partition_tables" ) )
return FALSE;
// udisks hide?
if ( !vol->is_user_visible && !xset_get_b( "dev_ignore_udisks_hide" ) )
return FALSE;
// has media?
if ( !vol->is_mountable && !vol->is_mounted && !xset_get_b( "dev_show_empty" ) )
return FALSE;
#endif
return TRUE;
}
#ifndef HAVE_HAL
void ptk_location_view_on_action( GtkWidget* view, XSet* set )
{
char* xname;
//printf("ptk_location_view_on_action\n");
if ( !view )
return;
VFSVolume* vol = ptk_location_view_get_selected_vol( GTK_TREE_VIEW( view ) );
if ( !strcmp( set->name, "dev_show_internal_drives" )
|| !strcmp( set->name, "dev_show_empty" )
|| !strcmp( set->name, "dev_show_partition_tables" )
|| !strcmp( set->name, "dev_show_net" )
|| !strcmp( set->name, "dev_show_file" )
|| !strcmp( set->name, "dev_ignore_udisks_hide" )
|| !strcmp( set->name, "dev_show_hide_volumes" )
|| !strcmp( set->name, "dev_automount_optical" )
|| !strcmp( set->name, "dev_automount_removable" )
|| !strcmp( set->name, "dev_ignore_udisks_nopolicy" ) )
update_all();
else if ( !strcmp( set->name, "dev_automount_volumes" ) )
on_automountlist( NULL, vol, view );
else if ( !strcmp( set->name, "dev_root_fstab" ) )
on_root_fstab( NULL, view );
else if ( !strcmp( set->name, "dev_root_udevil" ) )
on_root_udevil( NULL, view );
else if ( !strcmp( set->name, "dev_rest_info" ) )
on_restore_info( NULL, view, set );
else if ( g_str_has_prefix( set->name, "dev_icon_" ) )
update_volume_icons();
else if ( !strcmp( set->name, "dev_dispname" ) )
update_names();
else if ( !strcmp( set->name, "dev_menu_sync" ) )
on_sync( NULL, vol, view );
else if ( !vol )
return;
else
{
// require vol != NULL
if ( g_str_has_prefix( set->name, "dev_menu_" ) )
{
xname = set->name + 9;
if ( !strcmp( xname, "remove" ) )
on_eject( NULL, vol, view );
else if ( !strcmp( xname, "unmount" ) )
on_umount( NULL, vol, view );
else if ( !strcmp( xname, "reload" ) )
on_reload( NULL, vol, view );
else if ( !strcmp( xname, "open" ) )
on_open( NULL, vol, view );
else if ( !strcmp( xname, "tab" ) )
on_open_tab( NULL, vol, view );
else if ( !strcmp( xname, "mount" ) )
on_mount( NULL, vol, view );
else if ( !strcmp( xname, "remount" ) )
on_remount( NULL, vol, view );
}
else if ( g_str_has_prefix( set->name, "dev_root_" ) )
{
xname = set->name + 9;
if ( !strcmp( xname, "mount" ) )
on_mount_root( NULL, vol, view );
else if ( !strcmp( xname, "unmount" ) )
on_umount_root( NULL, vol, view );
else if ( !strcmp( xname, "label" ) )
on_change_label( NULL, vol, view );
else if ( !strcmp( xname, "check" ) )
on_check_root( NULL, vol, view );
}
else if ( g_str_has_prefix( set->name, "dev_fmt_" ) )
on_format( NULL, vol, view, set );
else if ( g_str_has_prefix( set->name, "dev_back_" ) )
on_backup( NULL, vol, view, set );
else if ( !strcmp( set->name, "dev_rest_info" ) )
on_restore( NULL, vol, view, set );
else if ( !strcmp( set->name, "dev_prop" ) )
on_prop( NULL, vol, view );
}
}
#endif
gboolean on_button_press_event( GtkTreeView* view, GdkEventButton* evt,
gpointer user_data )
{
GtkTreeIter it;
GtkTreeSelection* tree_sel = NULL;
GtkTreePath* tree_path = NULL;
int pos;
GtkWidget* popup;
GtkWidget* item;
VFSVolume* vol = NULL;
XSet* set;
char* str;
gboolean ret = FALSE;
if( evt->type != GDK_BUTTON_PRESS )
return FALSE;
//printf("on_button_press_event view = %d\n", view );
PtkFileBrowser* file_browser = (PtkFileBrowser*)g_object_get_data( G_OBJECT(view),
"file_browser" );
ptk_file_browser_focus_me( file_browser );
if ( ( evt_win_click->s || evt_win_click->ob2_data ) &&
main_window_event( file_browser->main_window, evt_win_click, "evt_win_click",
0, 0, "devices", 0, evt->button, evt->state, TRUE ) )
return FALSE;
// get selected vol
if ( gtk_tree_view_get_path_at_pos( view, evt->x, evt->y, &tree_path, NULL, NULL, NULL ) )
{
tree_sel = gtk_tree_view_get_selection( view );
if ( gtk_tree_model_get_iter( model, &it, tree_path ) )
{
gtk_tree_selection_select_iter( tree_sel, &it );
gtk_tree_model_get( model, &it, COL_DATA, &vol, -1 );
}
}
if ( evt->button == 1 ) /* left button */
{
if ( vol )
{
if ( xset_get_b( "dev_single" ) )
{
gtk_tree_view_row_activated( view, tree_path, NULL );
ret = TRUE;
}
}
else
{
gtk_tree_selection_unselect_all( gtk_tree_view_get_selection( view ) );
ret = TRUE;
}
}
#ifndef HAVE_HAL
else if ( vol && evt->button == 2 ) /* middle button */
{
on_eject( NULL, vol, GTK_WIDGET( view ) );
ret = TRUE;
}
#endif
else if ( evt->button == 3 ) /* right button */
{
popup = gtk_menu_new();
GtkAccelGroup* accel_group = gtk_accel_group_new ();
XSetContext* context = xset_context_new();
main_context_fill( file_browser, context );
#ifndef HAVE_HAL
set = xset_set_cb( "dev_menu_remove", on_eject, vol );
xset_set_ob1( set, "view", view );
set->disable = !vol;
set = xset_set_cb( "dev_menu_unmount", on_umount, vol );
xset_set_ob1( set, "view", view );
set->disable = !vol;
set = xset_set_cb( "dev_menu_reload", on_reload, vol );
xset_set_ob1( set, "view", view );
set->disable = !( vol && vol->device_type == DEVICE_TYPE_BLOCK );
set = xset_set_cb( "dev_menu_sync", on_sync, vol );
xset_set_ob1( set, "view", view );
set = xset_set_cb( "dev_menu_open", on_open, vol );
xset_set_ob1( set, "view", view );
set->disable = !vol;
set = xset_set_cb( "dev_menu_tab", on_open_tab, vol );
xset_set_ob1( set, "view", view );
set->disable = !vol;
set = xset_set_cb( "dev_menu_mount", on_mount, vol );
xset_set_ob1( set, "view", view );
set->disable = !vol;
set = xset_set_cb( "dev_menu_remount", on_remount, vol );
xset_set_ob1( set, "view", view );
set->disable = !vol;
set = xset_set_cb( "dev_root_mount", on_mount_root, vol );
xset_set_ob1( set, "view", view );
set->disable = !vol;
set = xset_set_cb( "dev_root_unmount", on_umount_root, vol );
xset_set_ob1( set, "view", view );
set->disable = !vol;
set = xset_set_cb( "dev_root_label", on_change_label, vol );
xset_set_ob1( set, "view", view );
set->disable = !( vol && vol->device_type == DEVICE_TYPE_BLOCK );
xset_set_cb( "dev_root_fstab", on_root_fstab, view );
xset_set_cb( "dev_root_udevil", on_root_udevil, view );
set = xset_set_cb( "dev_menu_mark", on_bookmark_device, vol );
xset_set_ob1( set, "view", view );
xset_set_cb( "dev_show_internal_drives", update_all, NULL );
xset_set_cb( "dev_show_empty", update_all, NULL );
xset_set_cb( "dev_show_partition_tables", update_all, NULL );
xset_set_cb( "dev_show_net", update_all, NULL );
set = xset_set_cb( "dev_show_file", update_all, NULL );
set->disable = xset_get_b( "dev_show_internal_drives" );
xset_set_cb( "dev_ignore_udisks_hide", update_all, NULL );
xset_set_cb( "dev_show_hide_volumes", on_showhide, vol );
set = xset_set_cb( "dev_automount_optical", update_all, NULL );
gboolean auto_optical = set->b == XSET_B_TRUE;
set = xset_set_cb( "dev_automount_removable", update_all, NULL );
gboolean auto_removable = set->b == XSET_B_TRUE;
xset_set_cb( "dev_ignore_udisks_nopolicy", update_all, NULL );
set = xset_set_cb( "dev_automount_volumes", on_automountlist, vol );
xset_set_ob1( set, "view", view );
if ( vol && ( g_str_has_prefix( vol->device_file, "//" )
|| strstr( vol->device_file, ":/" ) ) )
str = " dev_menu_mark";
else
str = "";
char* menu_elements = g_strdup_printf( "dev_menu_remove dev_menu_reload dev_menu_unmount dev_menu_sync sep_dm1 dev_menu_open dev_menu_tab dev_menu_mount dev_menu_remount%s", str );
xset_add_menu( NULL, file_browser, popup, accel_group, menu_elements );
g_free( menu_elements );
#else
item = gtk_menu_item_new_with_mnemonic( _( "_Mount" ) );
g_object_set_data( G_OBJECT(item), "view", view );
g_signal_connect( item, "activate", G_CALLBACK(on_mount), vol );
if( vfs_volume_is_mounted( vol ) )
gtk_widget_set_sensitive( item, FALSE );
gtk_menu_shell_append( GTK_MENU_SHELL( popup ), item );
if( vfs_volume_requires_eject( vol ) )
{
item = gtk_menu_item_new_with_mnemonic( _( "_Eject" ) );
g_object_set_data( G_OBJECT(item), "view", view );
g_signal_connect( item, "activate", G_CALLBACK(on_eject), vol );
}
else
{
item = gtk_menu_item_new_with_mnemonic( _( "_Unmount" ) );
g_object_set_data( G_OBJECT(item), "view", view );
g_signal_connect( item, "activate", G_CALLBACK(on_umount), vol );
}
if( ! vfs_volume_is_mounted( vol ) )
gtk_widget_set_sensitive( item, FALSE );
gtk_menu_shell_append( GTK_MENU_SHELL( popup ), item );
#endif
#ifndef HAVE_HAL
if ( vol )
{
set = xset_set_cb( "dev_fmt_vfat", on_format, vol );
xset_set_ob1( set, "view", view );
xset_set_ob2( set, "set", set );
set = xset_set_cb( "dev_fmt_ntfs", on_format, vol );
xset_set_ob1( set, "view", view );
xset_set_ob2( set, "set", set );
set = xset_set_cb( "dev_fmt_ext2", on_format, vol );
xset_set_ob1( set, "view", view );
xset_set_ob2( set, "set", set );
set = xset_set_cb( "dev_fmt_ext3", on_format, vol );
xset_set_ob1( set, "view", view );
xset_set_ob2( set, "set", set );
set = xset_set_cb( "dev_fmt_ext4", on_format, vol );
xset_set_ob1( set, "view", view );
xset_set_ob2( set, "set", set );
set = xset_set_cb( "dev_fmt_btrfs", on_format, vol );
xset_set_ob1( set, "view", view );
xset_set_ob2( set, "set", set );
set = xset_set_cb( "dev_fmt_reis", on_format, vol );
xset_set_ob1( set, "view", view );
xset_set_ob2( set, "set", set );
set = xset_set_cb( "dev_fmt_reis4", on_format, vol );
xset_set_ob1( set, "view", view );
xset_set_ob2( set, "set", set );
set = xset_set_cb( "dev_fmt_swap", on_format, vol );
xset_set_ob1( set, "view", view );
xset_set_ob2( set, "set", set );
set = xset_set_cb( "dev_fmt_zero", on_format, vol );
xset_set_ob1( set, "view", view );
xset_set_ob2( set, "set", set );
set = xset_set_cb( "dev_fmt_urand", on_format, vol );
xset_set_ob1( set, "view", view );
xset_set_ob2( set, "set", set );
set = xset_set_cb( "dev_back_fsarc", on_backup, vol );
xset_set_ob1( set, "view", view );
xset_set_ob2( set, "set", set );
set->disable = !vol;
set = xset_set_cb( "dev_back_part", on_backup, vol );
xset_set_ob1( set, "view", view );
xset_set_ob2( set, "set", set );
set->disable = ( !vol || ( vol && vol->is_mounted ) );
set = xset_set_cb( "dev_back_mbr", on_backup, vol );
xset_set_ob1( set, "view", view );
xset_set_ob2( set, "set", set );
set->disable = ( !vol || ( vol && vol->is_optical ) );
set = xset_set_cb( "dev_rest_file", on_restore, vol );
xset_set_ob1( set, "view", view );
xset_set_ob2( set, "set", set );
set = xset_set_cb( "dev_rest_info", on_restore_info, view );
xset_set_ob1( set, "set", set );
}
set = xset_set_cb( "dev_prop", on_prop, vol );
xset_set_ob1( set, "view", view );
set->disable = !( vol && vol->device_type == DEVICE_TYPE_BLOCK );
set = xset_get( "dev_menu_root" );
//set->disable = !vol;
set = xset_get( "dev_menu_format" );
set->disable = !( vol && !vol->is_mounted &&
vol->device_type == DEVICE_TYPE_BLOCK );
set = xset_set_cb( "dev_root_check", on_check_root, vol );
set->disable = !( vol && !vol->is_mounted &&
vol->device_type == DEVICE_TYPE_BLOCK );
xset_set_ob1( set, "view", view );
set = xset_get( "dev_menu_restore" );
set->disable = !( vol && !vol->is_mounted &&
vol->device_type == DEVICE_TYPE_BLOCK );
set = xset_get( "dev_menu_backup" );
set->disable = !( vol && vol->device_type == DEVICE_TYPE_BLOCK );
xset_set_cb_panel( file_browser->mypanel, "font_dev", main_update_fonts,
file_browser );
xset_set_cb( "dev_icon_audiocd", update_volume_icons, NULL );
xset_set_cb( "dev_icon_optical_mounted", update_volume_icons, NULL );
xset_set_cb( "dev_icon_optical_media", update_volume_icons, NULL );
xset_set_cb( "dev_icon_optical_nomedia", update_volume_icons, NULL );
xset_set_cb( "dev_icon_floppy_mounted", update_volume_icons, NULL );
xset_set_cb( "dev_icon_floppy_unmounted", update_volume_icons, NULL );
xset_set_cb( "dev_icon_remove_mounted", update_volume_icons, NULL );
xset_set_cb( "dev_icon_remove_unmounted", update_volume_icons, NULL );
xset_set_cb( "dev_icon_internal_mounted", update_volume_icons, NULL );
xset_set_cb( "dev_icon_internal_unmounted", update_volume_icons, NULL );
xset_set_cb( "dev_dispname", update_names, NULL );
set = xset_get( "dev_exec_fs" );
set->disable = !auto_optical && !auto_removable;
set = xset_get( "dev_exec_audio" );
set->disable = !auto_optical;
set = xset_get( "dev_exec_video" );
set->disable = !auto_optical;
set = xset_get( "dev_menu_settings" );
menu_elements = g_strdup_printf( "dev_show sep_dm4 dev_menu_auto dev_exec dev_mount_options dev_mount_cmd dev_unmount_cmd sep_dm5 dev_single dev_newtab dev_icon panel%d_font_dev", file_browser->mypanel );
xset_set_set( set, "desc", menu_elements );
g_free( menu_elements );
menu_elements = g_strdup_printf( "sep_dm2 dev_menu_root sep_dm3 dev_menu_settings dev_prop" );
xset_add_menu( NULL, file_browser, popup, accel_group, menu_elements );
g_free( menu_elements );
//xset_add_menu( NULL, file_browser, popup, accel_group, set->name );
#endif
gtk_widget_show_all( GTK_WIDGET(popup) );
g_signal_connect( popup, "selection-done",
G_CALLBACK( gtk_widget_destroy ), NULL );
g_signal_connect( popup, "key-press-event",
G_CALLBACK( xset_menu_keypress ), NULL );
gtk_menu_popup( GTK_MENU( popup ), NULL, NULL, NULL, NULL,
evt->button, evt->time );
ret = TRUE;
}
if ( tree_path )
gtk_tree_path_free( tree_path );
return ret;
}
void on_dev_menu_hide( GtkWidget *widget, GtkWidget* dev_menu )
{
gtk_widget_set_sensitive( widget, TRUE );
gtk_menu_shell_deactivate( GTK_MENU_SHELL( dev_menu ) );
}
static void show_dev_design_menu( GtkWidget* menu, GtkWidget* dev_item,
VFSVolume* vol,
guint button, guint32 time )
{
// validate vol
const GList* l;
const GList* volumes = vfs_volume_get_all_volumes();
for ( l = volumes; l; l = l->next )
{
if ( (VFSVolume*)l->data == vol )
break;
}
if ( !l )
/////// destroy menu?
return;
// create menu
XSet* set;
GtkWidget* item;
GtkWidget* view = (GtkWidget*)g_object_get_data( G_OBJECT(menu), "parent" );
GtkWidget* popup = gtk_menu_new();
//////////XSetContext* context = xset_context_new();
//main_context_fill( file_browser, context );
#ifndef HAVE_HAL
GtkWidget* image;
set = xset_get( "dev_menu_remove" );
item = gtk_image_menu_item_new_with_mnemonic( set->menu_label );
if ( set->icon )
{
image = xset_get_image( set->icon, GTK_ICON_SIZE_MENU );
if ( image )
gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM ( item ),
image );
}
g_object_set_data( G_OBJECT( item ), "view", view );
g_signal_connect( item, "activate", G_CALLBACK( on_eject ), vol );
gtk_menu_shell_append( GTK_MENU_SHELL( popup ), item );
set = xset_get( "dev_menu_open" );
item = gtk_image_menu_item_new_with_mnemonic( set->menu_label );
if ( set->icon )
{
image = xset_get_image( set->icon, GTK_ICON_SIZE_MENU );
if ( image )
gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM ( item ),
image );
}
g_object_set_data( G_OBJECT( item ), "view", view );
g_signal_connect( item, "activate", G_CALLBACK( on_open ), vol );
gtk_menu_shell_append( GTK_MENU_SHELL( popup ), item );
set = xset_get( "dev_prop" );
item = gtk_image_menu_item_new_with_mnemonic( set->menu_label );
if ( set->icon )
{
image = xset_get_image( set->icon, GTK_ICON_SIZE_MENU );
if ( image )
gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM ( item ),
image );
}
g_object_set_data( G_OBJECT( item ), "view", view );
g_signal_connect( item, "activate", G_CALLBACK( on_prop ), vol );
gtk_menu_shell_append( GTK_MENU_SHELL( popup ), item );
if ( !( vol && vol->device_type == DEVICE_TYPE_BLOCK ) )
gtk_widget_set_sensitive( item, FALSE );
#else
item = gtk_menu_item_new_with_mnemonic( _( "_Mount" ) );
g_signal_connect( item, "activate", G_CALLBACK(on_mount), vol );
if( vfs_volume_is_mounted( vol ) )
gtk_widget_set_sensitive( item, FALSE );
gtk_menu_shell_append( GTK_MENU_SHELL( popup ), item );
if( vfs_volume_requires_eject( vol ) )
{
item = gtk_menu_item_new_with_mnemonic( _( "_Eject" ) );
g_signal_connect( item, "activate", G_CALLBACK(on_eject), vol );
}
else
{
item = gtk_menu_item_new_with_mnemonic( _( "_Unmount" ) );
g_signal_connect( item, "activate", G_CALLBACK(on_umount), vol );
}
if( ! vfs_volume_is_mounted( vol ) )
gtk_widget_set_sensitive( item, FALSE );
gtk_menu_shell_append( GTK_MENU_SHELL( popup ), item );
#endif
// show menu
gtk_widget_show_all( GTK_WIDGET( popup ) );
gtk_menu_popup( GTK_MENU( popup ), GTK_WIDGET( menu ), dev_item, NULL, NULL,
button, time );
gtk_widget_set_sensitive( GTK_WIDGET( menu ), FALSE );
g_signal_connect( menu, "hide", G_CALLBACK( on_dev_menu_hide ), popup );
g_signal_connect( popup, "selection-done",
G_CALLBACK( gtk_widget_destroy ), NULL );
}
gboolean on_dev_menu_keypress( GtkWidget* menu, GdkEventKey* event,
gpointer user_data )
{
GtkWidget* item = gtk_menu_shell_get_selected_item( GTK_MENU_SHELL( menu ) );
if ( item )
{
if ( event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_KP_Enter ||
event->keyval == GDK_KEY_space )
{
VFSVolume* vol = (VFSVolume*)g_object_get_data( G_OBJECT(item), "vol" );
show_dev_design_menu( menu, item, vol, 1, event->time );
return TRUE;
}
}
return FALSE;
}
gboolean on_dev_menu_button_press( GtkWidget* item, GdkEventButton* event,
VFSVolume* vol )
{
GtkWidget* menu = (GtkWidget*)g_object_get_data( G_OBJECT(item), "menu" );
int keymod = ( event->state & ( GDK_SHIFT_MASK | GDK_CONTROL_MASK |
GDK_MOD1_MASK | GDK_SUPER_MASK | GDK_HYPER_MASK | GDK_META_MASK ) );
if ( event->type == GDK_BUTTON_RELEASE )
{
if ( event->button == 1 && keymod == 0 )
{
// user released left button - due to an apparent gtk bug, activate
// doesn't always fire on this event so handle it ourselves
// see also settings.c xset_design_cb()
// test: gtk2 Crux theme with touchpad on Edit|Copy To|Location
// https://github.com/IgnorantGuru/spacefm/issues/31
// https://github.com/IgnorantGuru/spacefm/issues/228
if ( menu )
gtk_menu_shell_deactivate( GTK_MENU_SHELL( menu ) );
gtk_menu_item_activate( GTK_MENU_ITEM( item ) );
return TRUE;
}
return FALSE;
}
else if ( event->type != GDK_BUTTON_PRESS )
return FALSE;
show_dev_design_menu( menu, item, vol, event->button, event->time );
return TRUE;
}
gint cmp_dev_name( VFSVolume* a, VFSVolume* b )
{
return g_strcmp0( vfs_volume_get_disp_name( a ),
vfs_volume_get_disp_name( b ) );
}
void ptk_location_view_dev_menu( GtkWidget* parent, GtkWidget* menu )
{ // add currently visible devices to menu with dev design mode callback
const GList* v;
VFSVolume* vol;
GtkTreeIter it;
GtkWidget* item;
XSet* set;
GList* names = NULL;
GList* l;
g_object_set_data( G_OBJECT( menu ), "parent", parent );
const GList* volumes = vfs_volume_get_all_volumes();
for ( v = volumes; v; v = v->next )
{
vol = (VFSVolume*)v->data;
if ( vol && volume_is_visible( vol ) )
names = g_list_prepend( names, vol );
}
names = g_list_sort( names, (GCompareFunc)cmp_dev_name );
for ( l = names; l; l = l->next )
{
vol = (VFSVolume*)l->data;
item = gtk_image_menu_item_new_with_label(
vfs_volume_get_disp_name( vol ) );
if ( vfs_volume_get_icon( vol ) )
{
GtkWidget* image = xset_get_image( vfs_volume_get_icon( vol ),
GTK_ICON_SIZE_MENU );
if ( image )
gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM( item ),
image );
}
g_object_set_data( G_OBJECT( item ), "menu", menu );
g_object_set_data( G_OBJECT( item ), "vol", vol );
g_signal_connect( item, "button-press-event",
G_CALLBACK( on_dev_menu_button_press ), vol );
g_signal_connect( item, "button-release-event",
G_CALLBACK( on_dev_menu_button_press ), vol );
gtk_menu_shell_append( GTK_MENU_SHELL( menu ), item );
}
g_list_free( names );
g_signal_connect( menu, "key_press_event",
G_CALLBACK( on_dev_menu_keypress ), NULL );
#ifndef HAVE_HAL
xset_set_cb( "dev_show_internal_drives", update_all, NULL );
xset_set_cb( "dev_show_empty", update_all, NULL );
xset_set_cb( "dev_show_partition_tables", update_all, NULL );
xset_set_cb( "dev_show_net", update_all, NULL );
set = xset_set_cb( "dev_show_file", update_all, NULL );
set->disable = xset_get_b( "dev_show_internal_drives" );
xset_set_cb( "dev_ignore_udisks_hide", update_all, NULL );
xset_set_cb( "dev_show_hide_volumes", on_showhide, vol );
set = xset_set_cb( "dev_automount_optical", update_all, NULL );
gboolean auto_optical = set->b == XSET_B_TRUE;
set = xset_set_cb( "dev_automount_removable", update_all, NULL );
gboolean auto_removable = set->b == XSET_B_TRUE;
xset_set_cb( "dev_ignore_udisks_nopolicy", update_all, NULL );
xset_set_cb( "dev_automount_volumes", on_automountlist, vol );
set = xset_get( "dev_menu_settings" );
char* desc = g_strdup_printf( "dev_show sep_dm4 dev_menu_auto dev_exec dev_mount_options dev_mount_cmd dev_unmount_cmd" );
xset_set_set( set, "desc", desc );
g_free( desc );
#endif
}
/*
void ptk_location_view_rename_selected_bookmark( GtkTreeView* location_view )
{
GtkTreeIter it;
GtkTreePath* tree_path;
GtkTreeSelection* tree_sel;
int pos;
GtkTreeViewColumn* col;
GList *l, *renderers;
tree_sel = gtk_tree_view_get_selection( location_view );
if( gtk_tree_selection_get_selected( tree_sel, NULL, &it ) )
{
tree_path = gtk_tree_model_get_path( bookmodel, &it );
pos = gtk_tree_path_get_indices( tree_path ) [ 0 ];
if( pos > sep_idx )
{
col = gtk_tree_view_get_column( location_view, 0 );
renderers = gtk_tree_view_column_get_cell_renderers( col );
for( l = renderers; l; l = l->next )
{
if( GTK_IS_CELL_RENDERER_TEXT(l->data) )
{
g_object_set( G_OBJECT(l->data), "editable", TRUE, NULL );
gtk_tree_view_set_cursor_on_cell( location_view, tree_path,
col,
GTK_CELL_RENDERER( l->data ),
TRUE );
g_object_set( G_OBJECT(l->data), "editable", FALSE, NULL );
break;
}
}
g_list_free( renderers );
}
gtk_tree_path_free( tree_path );
}
}
*/
VFSVolume* ptk_location_view_get_volume( GtkTreeView* location_view, GtkTreeIter* it )
{
VFSVolume* vol = NULL;
gtk_tree_model_get( model, it, COL_DATA, &vol, -1 );
return vol;
}
/*
gboolean update_drag_dest_row( GtkWidget *widget, GdkDragContext *drag_context,
gint x, gint y, guint time, gpointer user_data )
{
GtkTreeView* view = (GtkTreeView*)widget;
GtkTreePath* tree_path;
GtkTreeViewDropPosition pos;
gboolean ret = TRUE;
if( gtk_tree_view_get_dest_row_at_pos(view, x, y, &tree_path, &pos ) )
{
int row = gtk_tree_path_get_indices(tree_path)[0];
if( row <= sep_idx )
{
gtk_tree_path_get_indices(tree_path)[0] = sep_idx;
gtk_tree_view_set_drag_dest_row( view, tree_path, GTK_TREE_VIEW_DROP_AFTER );
}
else
{
if( pos == GTK_TREE_VIEW_DROP_BEFORE || pos == GTK_TREE_VIEW_DROP_AFTER )
gtk_tree_view_set_drag_dest_row( view, tree_path, pos );
else
ret = FALSE;
}
}
else
{
int n = gtk_tree_model_iter_n_children( model, NULL );
tree_path = gtk_tree_path_new_from_indices( n - 1, -1 );
gtk_tree_view_set_drag_dest_row( view, tree_path, GTK_TREE_VIEW_DROP_AFTER );
}
gtk_tree_path_free( tree_path );
if( ret )
gdk_drag_status( drag_context, GDK_ACTION_LINK, time );
return ret;
}
*/
/*
gboolean on_drag_motion( GtkWidget *widget, GdkDragContext *drag_context,
gint x, gint y, guint time, gpointer user_data )
{
// stop the default handler of GtkTreeView
g_signal_stop_emission_by_name( widget, "drag-motion" );
return update_drag_dest_row( widget, drag_context, x, y, time, user_data );
}
gboolean on_drag_drop( GtkWidget *widget, GdkDragContext *drag_context,
gint x, gint y, guint time, gpointer user_data )
{
GdkAtom target = gdk_atom_intern( "text/uri-list", FALSE );
update_drag_dest_row( widget, drag_context, x, y, time, user_data );
gtk_drag_get_data( widget, drag_context, target, time );
gtk_tree_view_set_drag_dest_row( (GtkTreeView*)widget, NULL, 0 );
return TRUE;
}
void on_drag_data_received( GtkWidget *widget, GdkDragContext *drag_context,
gint x, gint y, GtkSelectionData *data, guint info,
guint time, gpointer user_data)
{
char** uris, **uri, *file, *name;
GtkTreeView* view;
GtkTreePath* tree_path;
GtkTreeViewDropPosition pos;
int idx;
if ((data->length >= 0) && (data->format == 8))
{
if( uris = gtk_selection_data_get_uris(data) )
{
view = (GtkTreeView*)widget;
gtk_tree_view_get_drag_dest_row( view, &tree_path, &pos );
if( tree_path )
{
idx = gtk_tree_path_get_indices(tree_path)[0];
idx -= sep_idx;
if( pos == GTK_TREE_VIEW_DROP_BEFORE )
--idx;
for( uri = uris; *uri; ++uri, ++idx )
{
file = g_filename_from_uri( *uri, NULL, NULL );
if( g_file_test( file, G_FILE_TEST_IS_DIR ) )
{
name = g_filename_display_basename( file );
ptk_bookmarks_insert( name, file, idx );
g_free( name );
}
g_free( file );
}
}
g_strfreev( uris );
}
}
gtk_drag_finish (drag_context, FALSE, FALSE, time);
}
*/
//===============================================================================
//MOD NEW BOOKMARK LIST
void ptk_bookmark_view_init_model( GtkListStore* list )
{
int pos = 0;
GtkTreeIter it;
gchar* name;
gchar* real_path;
PtkBookmarks* bookmarks;
const GList* l;
bookmarks = ptk_bookmarks_get();
for ( l = bookmarks->list; l; l = l->next )
{
name = ( char* ) l->data;
gtk_list_store_insert_with_values( list, &it, ++pos,
COL_NAME,
name,
COL_PATH,
ptk_bookmarks_item_get_path( name ), -1 );
}
update_bookmark_icons();
}
int book_item_comp( const char* item, const char* path )
{
return strcmp( ptk_bookmarks_item_get_path( item ), path );
}
void on_bookmark_device( GtkMenuItem* item, VFSVolume* vol )
{
const char* url;
GtkWidget* view = (GtkWidget*)g_object_get_data( G_OBJECT(item), "view" );
PtkFileBrowser* file_browser = (PtkFileBrowser*)g_object_get_data( G_OBJECT(view),
"file_browser" );
if ( !view || !file_browser )
return;
#ifndef HAVE_HAL
if ( g_str_has_prefix( vol->device_file, "curlftpfs#" ) )
url = vol->device_file + 10;
else
url = vol->device_file;
#else
url = vfs_volume_get_device( vol );
#endif
if ( ! g_list_find_custom( app_settings.bookmarks->list,
url,
( GCompareFunc ) book_item_comp ) )
{
ptk_bookmarks_append( url, url );
}
else
{
xset_msg_dialog( GTK_WIDGET( file_browser ), GTK_MESSAGE_INFO,
_("Bookmark Exists"), NULL, 0,
_("Bookmark already exists"), NULL, NULL );
}
}
void on_bookmark_remove( GtkMenuItem* item, PtkFileBrowser* file_browser )
{
char * dir_path;
dir_path = ptk_bookmark_view_get_selected_dir( GTK_TREE_VIEW(
file_browser->side_book ) );
if ( dir_path )
{
ptk_bookmarks_remove( dir_path );
g_free( dir_path );
}
}
void on_bookmark_rename( GtkMenuItem* item, PtkFileBrowser* file_browser )
{
char * dir_path;
char* name;
dir_path = ptk_bookmark_view_get_selected_dir(
GTK_TREE_VIEW( file_browser->side_book ) );
if ( dir_path )
{
name = g_strdup( ptk_bookmark_view_get_selected_name(
GTK_TREE_VIEW( file_browser->side_book ) ) );
if ( xset_text_dialog( GTK_WIDGET( file_browser ), _("Rename Bookmark"),
NULL, FALSE,
_("Enter new bookmark name:"), NULL, name, &name,
NULL, FALSE, NULL )
&& name )
ptk_bookmarks_rename( dir_path, name );
g_free( name );
g_free( dir_path );
}
}
void on_bookmark_edit( GtkMenuItem* item, PtkFileBrowser* file_browser )
{
char * dir_path;
char* name;
dir_path = ptk_bookmark_view_get_selected_dir(
GTK_TREE_VIEW( file_browser->side_book ) );
if ( dir_path )
{
name = ptk_bookmark_view_get_selected_name(
GTK_TREE_VIEW( file_browser->side_book ) );
char* path = g_strdup( dir_path );
char* msg = g_strdup_printf( _("Enter new folder for bookmark '%s':"), name );
if ( xset_text_dialog( GTK_WIDGET( file_browser ), _("Edit Bookmark Location"), NULL, FALSE,
msg, NULL, path, &path, NULL, FALSE, NULL )
&& path )
ptk_bookmarks_change( dir_path, path );
g_free( msg );
g_free( dir_path );
g_free( path );
}
}
void on_bookmark_open( GtkMenuItem* item, PtkFileBrowser* file_browser )
{
char * dir_path;
dir_path = ptk_bookmark_view_get_selected_dir(
GTK_TREE_VIEW( file_browser->side_book ) );
if ( g_str_has_prefix( dir_path, "//" ) || strstr( dir_path, ":/" ) )
{
mount_network( file_browser, dir_path, xset_get_b( "book_newtab" ) );
g_free( dir_path );
}
else if ( dir_path )
{
if ( strcmp( dir_path, ptk_file_browser_get_cwd( file_browser ) ) )
ptk_file_browser_chdir( file_browser, dir_path, PTK_FB_CHDIR_ADD_HISTORY );
g_free( dir_path );
}
}
void on_bookmark_open_tab( GtkMenuItem* item, PtkFileBrowser* file_browser )
{
char * dir_path;
if ( !file_browser )
return;
dir_path = ptk_bookmark_view_get_selected_dir(
GTK_TREE_VIEW( file_browser->side_book ) );
if ( !dir_path )
return;
if ( g_str_has_prefix( dir_path, "//" ) || strstr( dir_path, ":/" ) )
{
mount_network( file_browser, dir_path, TRUE );
g_free( dir_path );
}
else if ( dir_path )
{
ptk_file_browser_emit_open( file_browser, dir_path, PTK_OPEN_NEW_TAB );
}
}
void on_bookmark_row_activated ( GtkTreeView *tree_view,
GtkTreePath *path,
GtkTreeViewColumn *column,
PtkFileBrowser* file_browser )
{
char * dir_path = NULL;
//ptk_file_browser_focus_me( file_browser );
dir_path = ptk_bookmark_view_get_selected_dir(
GTK_TREE_VIEW( file_browser->side_book ) );
if ( !dir_path )
return;
if ( g_str_has_prefix( dir_path, "//" ) || strstr( dir_path, ":/" ) )
mount_network( file_browser, dir_path, xset_get_b( "book_newtab" ) );
else
{
if ( !xset_get_b( "book_newtab" ) )
{
if ( strcmp( dir_path, ptk_file_browser_get_cwd( file_browser ) ) )
ptk_file_browser_chdir( file_browser, dir_path, PTK_FB_CHDIR_ADD_HISTORY );
}
else
{
ptk_file_browser_emit_open( file_browser, dir_path, PTK_OPEN_NEW_TAB );
//dir_path = NULL;
ptk_bookmark_view_chdir( tree_view,
ptk_file_browser_get_cwd( file_browser ) );
}
}
g_free( dir_path );
}
static gboolean on_bookmark_button_press_event( GtkTreeView* view,
GdkEventButton* evt, PtkFileBrowser* file_browser )
{
if ( evt->type != GDK_BUTTON_PRESS )
return FALSE;
ptk_file_browser_focus_me( file_browser );
if ( ( evt_win_click->s || evt_win_click->ob2_data ) &&
main_window_event( file_browser->main_window, evt_win_click, "evt_win_click", 0, 0,
"bookmarks", 0, evt->button, evt->state, TRUE ) )
return FALSE;
if ( evt->button == 1 ) // left
{
file_browser->bookmark_button_press = TRUE;
return FALSE;
}
GtkTreeSelection* tree_sel;
GtkTreePath* tree_path;
GtkWidget* popup;
XSet* set;
tree_sel = gtk_tree_view_get_selection( view );
gtk_tree_view_get_path_at_pos( view, evt->x, evt->y, &tree_path, NULL, NULL, NULL );
if ( tree_path )
{
if ( !gtk_tree_selection_path_is_selected( tree_sel, tree_path ) )
gtk_tree_selection_select_path( tree_sel, tree_path );
gtk_tree_path_free( tree_path );
}
else
gtk_tree_selection_unselect_all( tree_sel );
if ( evt->button == 2 ) //middle
{
on_bookmark_open_tab( NULL, file_browser );
return TRUE;
}
else if ( evt->button == 3 ) //right
{
gboolean sel = gtk_tree_selection_get_selected( tree_sel, NULL, NULL );
popup = gtk_menu_new();
GtkAccelGroup* accel_group = gtk_accel_group_new();
XSetContext* context = xset_context_new();
main_context_fill( file_browser, context );
xset_set_cb_panel( file_browser->mypanel, "font_book", main_update_fonts,
file_browser );
xset_set_cb( "book_icon", full_update_bookmark_icons, NULL );
xset_set_cb( "book_new", ptk_file_browser_add_bookmark, file_browser );
set = xset_set_cb( "book_open", on_bookmark_open, file_browser );
set->disable = !sel;
set = xset_set_cb( "book_tab", on_bookmark_open_tab, file_browser );
set->disable = !sel;
set = xset_set_cb( "book_remove", on_bookmark_remove, file_browser );
set->disable = !sel;
set = xset_set_cb( "book_rename", on_bookmark_rename, file_browser );
set->disable = !sel;
set = xset_set_cb( "book_edit", on_bookmark_edit, file_browser );
set->disable = !sel;
set = xset_get( "book_settings" );
if ( set->desc )
g_free( set->desc );
set->desc = g_strdup_printf( "book_single book_newtab book_icon panel%d_font_book",
file_browser->mypanel );
char* menu_elements = g_strdup_printf( "book_new book_rename book_edit book_remove sep_bk1 book_open book_tab sep_bk2 book_settings" );
xset_add_menu( NULL, file_browser, popup, accel_group, menu_elements );
g_free( menu_elements );
gtk_widget_show_all( GTK_WIDGET( popup ) );
g_signal_connect( GTK_MENU( popup ), "selection-done",
G_CALLBACK( gtk_widget_destroy ), NULL );
g_signal_connect( GTK_MENU( popup ), "key-press-event",
G_CALLBACK( xset_menu_keypress ), NULL );
gtk_menu_popup( GTK_MENU( popup ), NULL, NULL, NULL, NULL, evt->button, evt->time );
return TRUE;
}
return FALSE;
}
static gboolean on_bookmark_button_release_event( GtkTreeView* view,
GdkEventButton* evt, PtkFileBrowser* file_browser )
{
GtkTreeIter it;
GtkTreeSelection* tree_sel;
GtkTreePath* tree_path;
int pos;
GtkMenu* popup;
GtkWidget* item;
VFSVolume* vol;
// don't activate row if drag was begun
if( evt->type != GDK_BUTTON_RELEASE || !file_browser->bookmark_button_press )
return FALSE;
file_browser->bookmark_button_press = FALSE;
if ( evt->button == 1 ) //left
{
gtk_tree_view_get_path_at_pos( view, evt->x, evt->y, &tree_path, NULL, NULL, NULL );
if ( !tree_path )
{
gtk_tree_selection_unselect_all( gtk_tree_view_get_selection( view ) );
return TRUE;
}
if ( !xset_get_b( "book_single" ) )
return FALSE;
tree_sel = gtk_tree_view_get_selection( view );
gtk_tree_model_get_iter( bookmodel, &it, tree_path );
pos = gtk_tree_path_get_indices( tree_path ) [ 0 ];
gtk_tree_selection_select_iter( tree_sel, &it );
gtk_tree_view_row_activated( view, tree_path, NULL );
gtk_tree_path_free( tree_path );
}
return FALSE;
}
void on_bookmark_drag_begin ( GtkWidget *widget,
GdkDragContext *drag_context,
PtkFileBrowser* file_browser )
{
// don't activate row if drag was begun
file_browser->bookmark_button_press = FALSE;
}
GtkWidget* ptk_bookmark_view_new( PtkFileBrowser* file_browser )
{
GtkWidget* view;
GtkTreeViewColumn* col;
GtkCellRenderer* renderer;
GtkListStore* list;
GtkIconTheme* icon_theme;
if ( ! bookmodel )
{
list = gtk_list_store_new( N_COLS,
GDK_TYPE_PIXBUF,
G_TYPE_STRING,
G_TYPE_STRING,
G_TYPE_POINTER );
g_object_weak_ref( G_OBJECT( list ), on_bookmark_model_destroy, NULL );
bookmodel = ( GtkTreeModel* ) list;
ptk_bookmark_view_init_model( list );
ptk_bookmarks_add_callback( on_bookmark_changed, NULL );
icon_theme = gtk_icon_theme_get_default();
theme_bookmark_changed = g_signal_connect( icon_theme, "changed",
G_CALLBACK( update_bookmark_icons ), NULL );
}
else
{
g_object_ref( G_OBJECT( bookmodel ) );
}
view = gtk_tree_view_new_with_model( bookmodel );
g_object_unref( G_OBJECT( bookmodel ) );
// no dnd if using auto-reorderable unless you code reorder dnd manually
// gtk_tree_view_enable_model_drag_dest (
// GTK_TREE_VIEW( view ),
// drag_targets, G_N_ELEMENTS( drag_targets ), GDK_ACTION_LINK );
// g_signal_connect( view, "drag-motion", G_CALLBACK( on_bookmark_drag_motion ), NULL );
// g_signal_connect( view, "drag-drop", G_CALLBACK( on_bookmark_drag_drop ), NULL );
// g_signal_connect( view, "drag-data-received", G_CALLBACK( on_bookmark_drag_data_received ), NULL );
gtk_tree_view_set_headers_visible( GTK_TREE_VIEW( view ), FALSE );
col = gtk_tree_view_column_new();
renderer = gtk_cell_renderer_pixbuf_new();
gtk_tree_view_column_pack_start( col, renderer, FALSE );
gtk_tree_view_column_set_attributes( col, renderer,
"pixbuf", COL_ICON, NULL );
gtk_tree_view_append_column ( GTK_TREE_VIEW( view ), col );
col = gtk_tree_view_column_new();
renderer = gtk_cell_renderer_text_new();
//g_signal_connect( renderer, "edited", G_CALLBACK(on_bookmark_edited), view );
gtk_tree_view_column_pack_start( col, renderer, TRUE );
gtk_tree_view_column_set_attributes( col, renderer,
"text", COL_NAME, NULL );
gtk_tree_view_append_column ( GTK_TREE_VIEW( view ), col );
gtk_tree_view_set_reorderable ( GTK_TREE_VIEW( view ), TRUE );
g_object_set_data( G_OBJECT( view ), "file_browser", file_browser );
//g_signal_connect( view, "row-activated", G_CALLBACK( on_bookmark_row_activated ), NULL );
//g_signal_connect_after( bookmodel, "row_inserted", G_CALLBACK( on_bookmark_row_inserted ),
// NULL );
g_signal_connect( bookmodel, "row_deleted", G_CALLBACK( on_bookmark_row_deleted ),
NULL );
// handle single-clicks in addition to auto-reorderable dnd
g_signal_connect( view, "drag-begin", G_CALLBACK( on_bookmark_drag_begin ),
file_browser );
g_signal_connect( view, "button-press-event",
G_CALLBACK( on_bookmark_button_press_event ), file_browser );
g_signal_connect( view, "button-release-event",
G_CALLBACK( on_bookmark_button_release_event ), file_browser );
g_signal_connect ( view, "row-activated",
G_CALLBACK ( on_bookmark_row_activated ), file_browser );
file_browser->bookmark_button_press = FALSE;
// set font
if ( xset_get_s_panel( file_browser->mypanel, "font_book" ) )
{
PangoFontDescription* font_desc = pango_font_description_from_string(
xset_get_s_panel( file_browser->mypanel, "font_book" ) );
gtk_widget_modify_font( view, font_desc );
pango_font_description_free( font_desc );
}
return view;
}
static void on_bookmark_model_destroy( gpointer data, GObject* object )
{
GtkIconTheme* icon_theme;
ptk_bookmarks_remove_callback( on_bookmark_changed, NULL );
//cleanup
bookmodel = NULL;
icon_theme = gtk_icon_theme_get_default();
g_signal_handler_disconnect( icon_theme, theme_bookmark_changed );
}
void update_bookmark_icons()
{
GtkIconTheme* icon_theme;
GtkTreeIter it;
GdkPixbuf* icon = NULL;
GtkListStore* list = GTK_LIST_STORE( bookmodel );
icon_theme = gtk_icon_theme_get_default();
XSet* set = xset_get( "book_icon" );
char* book_icon = set->icon;
if ( book_icon && book_icon[0] != '\0' )
icon = vfs_load_icon ( icon_theme, book_icon, app_settings.small_icon_size );
if ( !icon )
icon = vfs_load_icon ( icon_theme, "user-bookmarks",
app_settings.small_icon_size );
if ( !icon )
icon = vfs_load_icon ( icon_theme, "gnome-fs-directory",
app_settings.small_icon_size );
if ( !icon )
icon = vfs_load_icon ( icon_theme, "gtk-directory",
app_settings.small_icon_size );
if ( gtk_tree_model_get_iter_first( bookmodel, &it ) )
{
gtk_list_store_set( list, &it, COL_ICON, icon, -1 );
while( gtk_tree_model_iter_next( bookmodel, &it ) )
gtk_list_store_set( list, &it, COL_ICON, icon, -1 );
}
if ( icon )
g_object_unref( icon );
}
void full_update_bookmark_icons()
{
update_bookmark_icons();
main_window_update_bookmarks();
}
char* ptk_bookmark_view_get_selected_dir( GtkTreeView* bookmark_view )
{
GtkTreeIter it;
GtkTreeSelection* tree_sel;
GtkTreePath* tree_path;
char* real_path = NULL;
int i;
tree_sel = gtk_tree_view_get_selection( bookmark_view );
if ( gtk_tree_selection_get_selected( tree_sel, NULL, &it ) )
{
gtk_tree_model_get( bookmodel, &it, COL_PATH, &real_path, -1 );
}
return real_path;
}
gboolean ptk_bookmark_view_chdir( GtkTreeView* bookmark_view, const char* cur_dir )
{
GtkTreeIter it;
GtkTreeSelection* tree_sel;
char* real_path;
if ( !cur_dir || !GTK_IS_TREE_VIEW( bookmark_view ) )
return FALSE;
tree_sel = gtk_tree_view_get_selection( bookmark_view );
if ( gtk_tree_model_get_iter_first( bookmodel, &it ) )
{
do
{
gtk_tree_model_get( bookmodel, &it, COL_PATH, &real_path, -1 );
if ( real_path && !strcmp( cur_dir, real_path ) )
{
gtk_tree_selection_select_iter( tree_sel, &it );
GtkTreePath* path = gtk_tree_model_get_path( bookmodel, &it );
if ( path )
{
gtk_tree_view_scroll_to_cell( bookmark_view,
path, NULL, TRUE, .25, 0 );
gtk_tree_path_free( path );
}
g_free( real_path );
return TRUE;
}
g_free( real_path );
}
while ( gtk_tree_model_iter_next ( bookmodel, &it ) );
}
gtk_tree_selection_unselect_all( tree_sel );
return FALSE;
}
char* ptk_bookmark_view_get_selected_name( GtkTreeView* bookmark_view )
{
GtkTreeIter it;
GtkTreeSelection* tree_sel;
GtkTreePath* tree_path;
char* name = NULL;
int i;
tree_sel = gtk_tree_view_get_selection( bookmark_view );
if ( gtk_tree_selection_get_selected( tree_sel, NULL, &it ) )
{
gtk_tree_model_get( bookmodel, &it, COL_NAME, &name, -1 );
}
return name;
}
void on_bookmark_row_deleted( GtkTreeView* view, GtkTreePath* tree_path,
GtkTreeViewColumn *col, gpointer user_data )
{
GList* l;
GtkTreeIter it;
gchar *name, *path, *item;
// printf("row-deleted\n");
/*
if ( ! gtk_tree_model_get_iter( bookmodel, &it, tree_path ) )
return ;
gtk_tree_model_get( bookmodel, &it, COL_PATH, &path, -1 );
if ( path )
ptk_bookmarks_remove( path );
*/
//printf("row_deleted\n");
// update bookmarks from model
ptk_bookmarks_remove_callback( on_bookmark_changed, NULL );
l = NULL;
if( gtk_tree_model_get_iter_first( GTK_TREE_MODEL( bookmodel ), &it ) )
{
do
{
gtk_tree_model_get( GTK_TREE_MODEL( bookmodel ), &it,
COL_NAME, &name,
COL_PATH, &path,
-1 );
if( ! name )
name = g_path_get_basename( path );
item = ptk_bookmarks_item_new( name, strlen(name),
path ? path : "", path ? strlen(path) : 0 );
l = g_list_append( l, item );
g_free(name);
g_free(path);
}
while( gtk_tree_model_iter_next( GTK_TREE_MODEL( bookmodel ), &it) );
}
ptk_bookmarks_set( l );
ptk_bookmarks_add_callback( on_bookmark_changed, NULL );
}
/*
void on_bookmark_row_inserted( GtkTreeView* view, GtkTreePath* tree_path,
GtkTreeViewColumn *col, gpointer user_data )
{
GtkTreeIter it;
gchar *name, *path;
printf("row-inserted\n");
return;
int i = gtk_tree_path_get_indices( tree_path ) [ 0 ];
if ( ! gtk_tree_model_get_iter( bookmodel, &it, tree_path ) )
return ;
gtk_tree_model_get( bookmodel, &it,
COL_NAME, &name,
COL_PATH, &path,
-1 );
//printf(" insert %d %s %s...\n", i, name, path);
if ( name && path )
ptk_bookmarks_insert( name, path, i );
}
*/
|
186 | ./spacefm/src/ptk/ptk-app-chooser.c | /*
* C Implementation: appchooserdlg
*
* Description:
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "ptk-app-chooser.h"
#include "ptk-utils.h"
#include <gtk/gtk.h>
#include <glib.h>
#include <string.h>
#include "private.h"
#include "vfs-mime-type.h"
#include "vfs-app-desktop.h"
#include "vfs-async-task.h"
#include "settings.h"
enum{
COL_APP_ICON = 0,
COL_APP_NAME,
COL_DESKTOP_FILE,
N_COLS
};
extern gboolean is_my_lock;
static void load_all_apps_in_dir( const char* dir_path, GtkListStore* list, VFSAsyncTask* task );
static gpointer load_all_known_apps_thread( VFSAsyncTask* task );
static void init_list_view( GtkTreeView* view )
{
GtkTreeViewColumn * col = gtk_tree_view_column_new();
GtkCellRenderer* renderer;
renderer = gtk_cell_renderer_pixbuf_new();
gtk_tree_view_column_pack_start( col, renderer, FALSE );
gtk_tree_view_column_set_attributes( col, renderer, "pixbuf",
COL_APP_ICON, NULL );
renderer = gtk_cell_renderer_text_new();
gtk_tree_view_column_pack_start( col, renderer, TRUE );
gtk_tree_view_column_set_attributes( col, renderer, "text",
COL_APP_NAME, NULL );
gtk_tree_view_append_column ( view, col );
}
static gint sort_by_name( GtkTreeModel *model,
GtkTreeIter *a,
GtkTreeIter *b,
gpointer user_data )
{
char * name_a, *name_b;
gint ret = 0;
gtk_tree_model_get( model, a, COL_APP_NAME, &name_a, -1 );
if ( name_a )
{
gtk_tree_model_get( model, b, COL_APP_NAME, &name_b, -1 );
if ( name_b )
{
ret = strcmp( name_a, name_b );
g_free( name_b );
}
g_free( name_a );
}
return ret;
}
static void add_list_item( GtkListStore* list, VFSAppDesktop* desktop )
{
GtkTreeIter it;
GdkPixbuf* icon = NULL;
icon = vfs_app_desktop_get_icon( desktop, 20, TRUE );
gtk_list_store_append( list, &it );
gtk_list_store_set( list, &it, COL_APP_ICON, icon,
COL_APP_NAME, vfs_app_desktop_get_disp_name( desktop ),
COL_DESKTOP_FILE, vfs_app_desktop_get_name( desktop ), -1 );
if ( icon )
g_object_unref( icon );
}
static GtkTreeModel* create_model_from_mime_type( VFSMimeType* mime_type )
{
char** apps, **app;
const char *type;
GtkListStore* list = gtk_list_store_new( N_COLS, GDK_TYPE_PIXBUF,
G_TYPE_STRING, G_TYPE_STRING );
if ( mime_type )
{
apps = vfs_mime_type_get_actions( mime_type );
type = vfs_mime_type_get_type( mime_type );
if ( !apps && mime_type_is_text_file( NULL, type ) )
{
mime_type = vfs_mime_type_get_from_type( XDG_MIME_TYPE_PLAIN_TEXT );
apps = vfs_mime_type_get_actions( mime_type );
vfs_mime_type_unref( mime_type );
}
if( apps )
{
for( app = apps; *app; ++app )
{
VFSAppDesktop* desktop = vfs_app_desktop_new( *app );
add_list_item( list, desktop );
vfs_app_desktop_unref( desktop );
}
g_strfreev( apps );
}
}
return (GtkTreeModel*) list;
}
gboolean on_cmdline_keypress( GtkWidget *widget,
GdkEventKey *event,
GtkNotebook* notebook )
{
gtk_widget_set_sensitive( GTK_WIDGET( notebook ), gtk_entry_get_text_length(
(GtkEntry*)widget ) == 0 );
return FALSE;
}
void on_view_row_activated ( GtkTreeView *tree_view,
GtkTreePath *path,
GtkTreeViewColumn* col,
GtkWidget* dlg )
{
GtkBuilder* builder = (GtkBuilder*)g_object_get_data(G_OBJECT(dlg), "builder");
GtkWidget* ok = (GtkWidget*)gtk_builder_get_object( builder, "okbutton");
gtk_button_clicked( GTK_BUTTON( ok ) );
}
GtkWidget* app_chooser_dialog_new( GtkWindow* parent, VFSMimeType* mime_type,
gboolean no_default )
{
GtkBuilder* builder = _gtk_builder_new_from_file( PACKAGE_UI_DIR "/appchooserdlg.ui", NULL );
GtkWidget * dlg = (GtkWidget*)gtk_builder_get_object( builder, "dlg" );
GtkWidget* file_type = (GtkWidget*)gtk_builder_get_object( builder, "file_type" );
char* mime_desc;
GtkTreeView* view;
GtkTreeModel* model;
GtkEntry* entry;
GtkNotebook* notebook;
g_object_set_data_full( G_OBJECT(dlg), "builder", builder, (GDestroyNotify)g_object_unref );
xset_set_window_icon( GTK_WINDOW( dlg ) );
gtk_dialog_set_alternative_button_order( GTK_DIALOG(dlg), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1 );
ptk_dialog_fit_small_screen( GTK_DIALOG(dlg) );
int width = xset_get_int( "app_dlg", "x" );
int height = xset_get_int( "app_dlg", "y" );
if ( width && height )
gtk_window_set_default_size( GTK_WINDOW( dlg ), width, height );
mime_desc = g_strdup_printf( " %s\n ( %s )",
vfs_mime_type_get_description( mime_type ),
mime_type->type );
if ( mime_desc )
{
gtk_label_set_text( GTK_LABEL( file_type ), mime_desc );
g_free( mime_desc );
}
/* Don't set default handler for directories and files with unknown type */
if ( no_default ||
0 == strcmp( vfs_mime_type_get_type( mime_type ), XDG_MIME_TYPE_UNKNOWN ) ||
0 == strcmp( vfs_mime_type_get_type( mime_type ), XDG_MIME_TYPE_DIRECTORY ) )
{
gtk_widget_hide( (GtkWidget*)gtk_builder_get_object( builder, "set_default" ) );
}
view = GTK_TREE_VIEW( (GtkWidget*)gtk_builder_get_object( builder, "recommended_apps" ) );
entry = GTK_ENTRY( (GtkWidget*)gtk_builder_get_object( builder, "cmdline" ) );
notebook = GTK_NOTEBOOK( (GtkWidget*)gtk_builder_get_object( builder, "notebook" ) );
model = create_model_from_mime_type( mime_type );
gtk_tree_view_set_model( view, model );
g_object_unref( G_OBJECT( model ) );
init_list_view( view );
gtk_widget_grab_focus( GTK_WIDGET( view ) );
g_signal_connect( entry, "key_release_event",
G_CALLBACK(on_cmdline_keypress), notebook );
g_signal_connect( (GtkWidget*)gtk_builder_get_object( builder, "notebook"),
"switch_page",
G_CALLBACK(on_notebook_switch_page), dlg );
g_signal_connect( (GtkWidget*)gtk_builder_get_object( builder, "browse_btn"),
"clicked",
G_CALLBACK(on_browse_btn_clicked), dlg );
g_signal_connect ( G_OBJECT( view ), "row_activated",
G_CALLBACK ( on_view_row_activated ),
dlg );
gtk_window_set_transient_for( GTK_WINDOW( dlg ), parent );
if ( no_default )
{
// select All Apps tab
gtk_widget_show( dlg );
gtk_notebook_next_page( notebook );
}
return dlg;
}
static void on_load_all_apps_finish( VFSAsyncTask* task, gboolean is_cancelled, GtkWidget* dlg )
{
GtkTreeModel* model;
GtkTreeView* view;
model = (GtkTreeModel*)vfs_async_task_get_data( task );
if( is_cancelled )
{
g_object_unref( model );
return;
}
view = (GtkTreeView*)g_object_get_data( G_OBJECT(task), "view" );
gtk_tree_sortable_set_sort_func ( GTK_TREE_SORTABLE( model ),
COL_APP_NAME, sort_by_name, NULL, NULL );
gtk_tree_sortable_set_sort_column_id ( GTK_TREE_SORTABLE( model ),
COL_APP_NAME, GTK_SORT_ASCENDING );
gtk_tree_view_set_model( view, model );
g_object_unref( model );
gdk_window_set_cursor( gtk_widget_get_window ( dlg ), NULL );
}
void
on_notebook_switch_page ( GtkNotebook *notebook,
GtkWidget *page,
guint page_num,
gpointer user_data )
{
GtkWidget * dlg = ( GtkWidget* ) user_data;
GtkTreeView* view;
GtkBuilder* builder = (GtkBuilder*)g_object_get_data(G_OBJECT(dlg), "builder");
/* Load all known apps installed on the system */
if ( page_num == 1 )
{
view = GTK_TREE_VIEW( (GtkWidget*)gtk_builder_get_object( builder, "all_apps" ) );
if ( ! gtk_tree_view_get_model( view ) )
{
GdkCursor* busy;
VFSAsyncTask* task;
GtkListStore* list;
init_list_view( view );
gtk_widget_grab_focus( GTK_WIDGET( view ) );
busy = gdk_cursor_new_for_display( gtk_widget_get_display(GTK_WIDGET( view )), GDK_WATCH );
gdk_window_set_cursor( gtk_widget_get_window( GTK_WIDGET( gtk_widget_get_toplevel(GTK_WIDGET(view)) ) ), busy );
gdk_cursor_unref( busy );
list = gtk_list_store_new( N_COLS, GDK_TYPE_PIXBUF,
G_TYPE_STRING, G_TYPE_STRING );
task = vfs_async_task_new( (VFSAsyncFunc) load_all_known_apps_thread, list );
g_object_set_data( G_OBJECT(task), "view", view );
g_object_set_data( G_OBJECT(dlg), "task", task );
g_signal_connect( task, "finish", G_CALLBACK(on_load_all_apps_finish), dlg );
vfs_async_task_execute( task );
g_signal_connect ( G_OBJECT( view ), "row_activated",
G_CALLBACK ( on_view_row_activated ),
dlg );
}
}
}
/*
* Return selected application in a ``newly allocated'' string.
* Returned string is the file name of the *.desktop file or a command line.
* These two can be separated by check if the returned string is ended
* with ".desktop" postfix.
*/
gchar* app_chooser_dialog_get_selected_app( GtkWidget* dlg )
{
gchar * app = NULL;
GtkBuilder* builder = (GtkBuilder*)g_object_get_data(G_OBJECT(dlg), "builder");
GtkEntry* entry = GTK_ENTRY( (GtkWidget*)gtk_builder_get_object( builder, "cmdline" ) );
GtkNotebook* notebook;
int idx;
GtkBin* scroll;
GtkTreeView* view;
GtkTreeSelection* tree_sel;
GtkTreeModel* model;
GtkTreeIter it;
app = (char*)gtk_entry_get_text( entry );
if ( app && *app )
{
return g_strdup( app );
}
notebook = GTK_NOTEBOOK( (GtkWidget*)gtk_builder_get_object( builder, "notebook" ) );
idx = gtk_notebook_get_current_page ( notebook );
scroll = GTK_BIN( gtk_notebook_get_nth_page( notebook, idx ) );
view = GTK_TREE_VIEW(gtk_bin_get_child( scroll ));
tree_sel = gtk_tree_view_get_selection( view );
if ( gtk_tree_selection_get_selected ( tree_sel, &model, &it ) )
{
gtk_tree_model_get( model, &it, COL_DESKTOP_FILE, &app, -1 );
}
else
app = NULL;
return app;
}
/*
* Check if the user set the selected app default handler.
*/
gboolean app_chooser_dialog_get_set_default( GtkWidget* dlg )
{
GtkBuilder* builder = (GtkBuilder*)g_object_get_data(G_OBJECT(dlg), "builder");
GtkWidget * check = (GtkWidget*)gtk_builder_get_object( builder, "set_default" );
return gtk_toggle_button_get_active ( GTK_TOGGLE_BUTTON( check ) );
}
void
on_browse_btn_clicked ( GtkButton *button,
gpointer user_data )
{
char * filename;
char* app_name;
GtkEntry* entry;
GtkNotebook* notebook;
const char* app_path = "/usr/share/applications";
GtkWidget* parent = GTK_WIDGET(user_data );
GtkWidget* dlg = gtk_file_chooser_dialog_new( NULL, GTK_WINDOW( parent ),
GTK_FILE_CHOOSER_ACTION_OPEN,
GTK_STOCK_CANCEL,
GTK_RESPONSE_CANCEL,
GTK_STOCK_OPEN,
GTK_RESPONSE_OK,
NULL );
GtkBuilder* builder = (GtkBuilder*)g_object_get_data(G_OBJECT(parent), "builder");
xset_set_window_icon( GTK_WINDOW( dlg ) );
gtk_file_chooser_set_current_folder ( GTK_FILE_CHOOSER ( dlg ),
"/usr/bin" );
if ( gtk_dialog_run( GTK_DIALOG( dlg ) ) == GTK_RESPONSE_OK )
{
filename = gtk_file_chooser_get_filename ( GTK_FILE_CHOOSER ( dlg ) );
if( filename )
{
entry = GTK_ENTRY( (GtkWidget*)gtk_builder_get_object( builder, "cmdline" ) );
notebook = GTK_NOTEBOOK( (GtkWidget*)gtk_builder_get_object( builder, "notebook" ) );
/* FIXME: path shouldn't be hard-coded */
if( g_str_has_prefix( filename, app_path )
&& g_str_has_suffix( filename, ".desktop" ) )
{
app_name = g_path_get_basename( filename );
gtk_entry_set_text( entry, app_name );
g_free( app_name );
}
else
{
gtk_entry_set_text( entry, filename );
}
g_free ( filename );
gtk_widget_set_sensitive( GTK_WIDGET( notebook ),
gtk_entry_get_text_length( entry ) == 0 );
gtk_widget_grab_focus( GTK_WIDGET( entry ) );
gtk_editable_set_position( GTK_EDITABLE( entry ), -1 );
}
}
gtk_widget_destroy( dlg );
}
static void on_dlg_response( GtkDialog* dlg, int id, gpointer user_data )
{
VFSAsyncTask* task;
GtkAllocation allocation;
gtk_widget_get_allocation ( GTK_WIDGET( dlg ), &allocation );
int width = allocation.width;
int height = allocation.height;
if ( width && height )
{
char* str = g_strdup_printf( "%d", width );
xset_set( "app_dlg", "x", str );
g_free( str );
str = g_strdup_printf( "%d", height );
xset_set( "app_dlg", "y", str );
g_free( str );
}
switch( id )
{
/* The dialog is going to be closed */
case GTK_RESPONSE_OK:
case GTK_RESPONSE_CANCEL:
case GTK_RESPONSE_NONE:
case GTK_RESPONSE_DELETE_EVENT:
/* cancel app loading on dialog closing... */
task = (VFSAsyncTask*)g_object_get_data( G_OBJECT(dlg), "task" );
if( task )
{
printf("spacefm: app-chooser.c -> vfs_async_task_cancel\n");
// see note in vfs-async-task.c: vfs_async_task_real_cancel()
GDK_THREADS_LEAVE();
vfs_async_task_cancel( task );
GDK_THREADS_ENTER();
/* The GtkListStore will be freed in "finish" handler of task - on_load_all_app_finish(). */
g_object_unref( task );
}
break;
}
}
gchar* ptk_choose_app_for_mime_type( GtkWindow* parent,
VFSMimeType* mime_type,
gboolean no_default )
{
GtkWidget * dlg;
gchar* app = NULL;
gchar* custom = NULL;
dlg = app_chooser_dialog_new( parent, mime_type, no_default );
g_signal_connect( dlg, "response", G_CALLBACK(on_dlg_response), NULL );
if ( gtk_dialog_run( GTK_DIALOG( dlg ) ) == GTK_RESPONSE_OK )
{
app = app_chooser_dialog_get_selected_app( dlg );
if ( app )
{
/* The selected app is set to default action */
/* TODO: full-featured mime editor??? */
if ( app_chooser_dialog_get_set_default( dlg ) )
{
vfs_mime_type_set_default_action( mime_type, app );
}
else if ( strcmp( vfs_mime_type_get_type( mime_type ), XDG_MIME_TYPE_UNKNOWN )
&& strcmp( vfs_mime_type_get_type( mime_type ), XDG_MIME_TYPE_DIRECTORY ))
{
vfs_mime_type_add_action( mime_type, app, &custom );
g_free( app );
app = custom;
}
}
}
gtk_widget_destroy( dlg );
return app;
}
void load_all_apps_in_dir( const char* dir_path, GtkListStore* list, VFSAsyncTask* task )
{
GDir* dir = g_dir_open( dir_path, 0, NULL );
if( dir )
{
const char* name;
char* path;
VFSAppDesktop* app;
while( (name = g_dir_read_name( dir )) )
{
vfs_async_task_lock( task );
if( task->cancel )
{
vfs_async_task_unlock( task );
break;
}
vfs_async_task_unlock( task );
path = g_build_filename( dir_path, name, NULL );
if( G_UNLIKELY( g_file_test( path, G_FILE_TEST_IS_DIR ) ) )
{
/* recursively load sub dirs */
load_all_apps_in_dir( path, list, task );
g_free( path );
continue;
}
if( ! g_str_has_suffix(name, ".desktop") )
continue;
vfs_async_task_lock( task );
if( task->cancel )
{
vfs_async_task_unlock( task );
break;
}
vfs_async_task_unlock( task );
app = vfs_app_desktop_new( path );
GDK_THREADS_ENTER();
add_list_item( list, app ); /* There are some operations using GTK+, so lock may be needed. */
GDK_THREADS_LEAVE();
vfs_app_desktop_unref( app );
g_free( path );
}
g_dir_close( dir );
}
}
gpointer load_all_known_apps_thread( VFSAsyncTask* task )
{
gchar* dir, **dirs;
GtkListStore* list;
gboolean cancel = FALSE;
GDK_THREADS_ENTER();
list = GTK_LIST_STORE( vfs_async_task_get_data(task) );
GDK_THREADS_LEAVE();
dir = g_build_filename( g_get_user_data_dir(), "applications", NULL );
load_all_apps_in_dir( dir, list, task );
g_free( dir );
for( dirs = (gchar **) g_get_system_data_dirs(); ! task->cancel && *dirs; ++dirs )
{
dir = g_build_filename( *dirs, "applications", NULL );
load_all_apps_in_dir( dir, list, task );
g_free( dir );
}
vfs_async_task_lock( task );
cancel = task->cancel;
vfs_async_task_unlock( task );
return NULL;
}
|
187 | ./spacefm/src/ptk/ptk-input-dialog.c | /*
* C Implementation: ptk-input-dialog
*
* Description:
*
*
* Author: Hong Jen Yee (PCMan) <pcman.tw (AT) gmail.com>, (C) 2005
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#include "ptk-input-dialog.h"
#include <gtk/gtk.h>
/*
* Create a dialog used to prompt the user to input a string.
* title: the title of dialog.
* prompt: prompt showed to the user
*/
GtkWidget* ptk_input_dialog_new( const char* title,
const char* prompt,
const char* default_text,
GtkWindow* parent )
{
GtkWidget * dlg;
GtkWidget* box;
GtkWidget* label;
GtkWidget* entry;
dlg = gtk_dialog_new_with_buttons( title,
parent,
0,
GTK_STOCK_CANCEL,
GTK_RESPONSE_CANCEL,
GTK_STOCK_OK,
GTK_RESPONSE_OK,
NULL );
gtk_dialog_set_alternative_button_order( GTK_DIALOG(dlg), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1 );
box = gtk_dialog_get_content_area ( GTK_DIALOG(dlg) );
label = gtk_label_new( prompt );
gtk_box_pack_start( GTK_BOX( box ), label, FALSE, FALSE, 4 );
entry = gtk_entry_new();
gtk_entry_set_text( GTK_ENTRY( entry ),
default_text ? default_text : "" );
gtk_box_pack_start( GTK_BOX( box ), entry, FALSE, FALSE, 4 );
g_object_set_data( G_OBJECT( dlg ), "prompt", label );
g_object_set_data( G_OBJECT( dlg ), "entry", entry );
gtk_dialog_set_default_response( ( GtkDialog* ) dlg,
GTK_RESPONSE_OK );
gtk_entry_set_activates_default ( GTK_ENTRY( entry ), TRUE );
gtk_widget_show_all( box );
return dlg;
}
/*
* Get user input from the text entry of the input dialog.
* The returned string should be freed when no longer needed.
* input_dialog: the input dialog
*/
gchar* ptk_input_dialog_get_text( GtkWidget* input_dialog )
{
GtkWidget * entry = ptk_input_dialog_get_entry( input_dialog );
return g_strdup( gtk_entry_get_text( GTK_ENTRY( entry ) ) );
}
/*
* Get the prompt label of the input dialog.
* input_dialog: the input dialog
*/
GtkWidget* ptk_input_dialog_get_label( GtkWidget* input_dialog )
{
return GTK_WIDGET( g_object_get_data(
G_OBJECT( input_dialog ), "prompt" ) );
}
/*
* Get the text entry widget of the input dialog.
* input_dialog: the input dialog
*/
GtkWidget* ptk_input_dialog_get_entry( GtkWidget* input_dialog )
{
return GTK_WIDGET( g_object_get_data(
G_OBJECT( input_dialog ), "entry" ) );
}
|
188 | ./spacefm/src/ptk/ptk-file-menu.c | /*
* C Implementation: ptk-file-menu
*
* Description:
*
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <unistd.h> /* for access */
#include "ptk-file-menu.h"
#include <glib.h>
#include "glib-mem.h"
#include <string.h>
#include <stdlib.h>
#include <glib/gi18n.h>
#include <gdk/gdkkeysyms.h>
#include "vfs-app-desktop.h"
#include "ptk-utils.h"
#include "ptk-file-misc.h"
#include "ptk-file-archiver.h"
#include "ptk-clipboard.h"
#include "ptk-app-chooser.h"
#include "settings.h" //MOD
#include "main-window.h"
#include "ptk-location-view.h"
#include "ptk-file-list.h" //sfm for sort extra
#include "pref-dialog.h"
//#include "ptk-bookmarks.h"
#include "gtk2-compat.h"
//#define get_toplevel_win(data) ( (GtkWindow*) (data->browser ? ( gtk_widget_get_toplevel((GtkWidget*) data->browser) ) : NULL) )
gboolean on_app_button_press( GtkWidget* item, GdkEventButton* event,
PtkFileMenu* data );
gboolean app_menu_keypress( GtkWidget* widget, GdkEventKey* event,
PtkFileMenu* data );
static void show_app_menu( GtkWidget* menu, GtkWidget* app_item, PtkFileMenu* data,
guint button, guint32 time );
/* Signal handlers for popup menu */
static void
on_popup_open_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data );
static void
on_popup_open_with_another_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data );
#if 0
static void
on_file_properties_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data );
#endif
static void
on_popup_run_app ( GtkMenuItem *menuitem,
PtkFileMenu* data );
static void
on_popup_open_in_new_tab_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data );
static void
on_popup_open_in_new_win_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data );
static void on_popup_open_in_terminal_activate( GtkMenuItem *menuitem,
PtkFileMenu* data );
static void
on_popup_cut_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data );
static void
on_popup_copy_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data );
static void
on_popup_paste_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data );
static void
on_popup_paste_link_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data ); //MOD added
static void
on_popup_paste_target_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data ); //MOD added
static void
on_popup_copy_text_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data ); //MOD added
static void
on_popup_copy_name_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data ); //MOD added
void
on_popup_copy_parent_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data ); //MOD added
void
on_popup_paste_as_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data ); //sfm added
static void
on_popup_delete_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data );
static void
on_popup_rename_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data );
static void
on_popup_compress_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data );
static void
on_popup_extract_here_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data );
static void
on_popup_extract_to_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data );
void on_popup_extract_list_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data );
static void
on_popup_new_folder_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data );
static void
on_popup_new_text_file_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data );
static void
on_popup_new_link_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data );
static void
on_popup_file_properties_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data );
void on_popup_file_permissions_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data );
static void on_popup_open_files_activate( GtkMenuItem *menuitem,
PtkFileMenu* data ); //MOD
static void on_popup_open_all( GtkMenuItem *menuitem, PtkFileMenu* data );
void
on_popup_canon ( GtkMenuItem *menuitem, PtkFileMenu* data );
/*
static void on_popup_run_command( GtkMenuItem *menuitem,
PtkFileMenu* data ); //MOD
static void on_popup_user_6 ( GtkMenuItem *menuitem,
PtkFileMenu* data ); //MOD
static void on_popup_user_7 ( GtkMenuItem *menuitem,
PtkFileMenu* data ); //MOD
static void on_popup_user_8 ( GtkMenuItem *menuitem,
PtkFileMenu* data ); //MOD
static void on_popup_user_9 ( GtkMenuItem *menuitem,
PtkFileMenu* data ); //MOD
*/
/*
static PtkMenuItemEntry create_new_menu[] =
{
PTK_IMG_MENU_ITEM( N_( "_Folder" ), "gtk-directory", on_popup_new_folder_activate, GDK_f, GDK_CONTROL_MASK ), //MOD stole ctrl-f
PTK_IMG_MENU_ITEM( N_( "_Text File" ), "gtk-edit", on_popup_new_text_file_activate, GDK_f, GDK_CONTROL_MASK | GDK_SHIFT_MASK ), //MOD added ctrl-shift-f
PTK_MENU_END
};
static PtkMenuItemEntry extract_menu[] =
{
PTK_MENU_ITEM( N_( "E_xtract Here" ), on_popup_extract_here_activate, 0, 0 ),
PTK_IMG_MENU_ITEM( N_( "Extract _To" ), "gtk-directory", on_popup_extract_to_activate, 0, 0 ),
PTK_MENU_END
};
static PtkMenuItemEntry basic_popup_menu[] =
{
PTK_MENU_ITEM( N_( "Open _with..." ), NULL, 0, 0 ),
PTK_SEPARATOR_MENU_ITEM,
PTK_STOCK_MENU_ITEM( "gtk-cut", on_popup_cut_activate ),
PTK_STOCK_MENU_ITEM( "gtk-copy", on_popup_copy_activate ),
PTK_IMG_MENU_ITEM( N_( "Copy as Te_xt" ), GTK_STOCK_COPY, on_popup_copy_text_activate, GDK_C, GDK_CONTROL_MASK | GDK_SHIFT_MASK ), //MOD added
PTK_IMG_MENU_ITEM( N_( "Copy _Name" ), GTK_STOCK_COPY, on_popup_copy_name_activate, GDK_C, GDK_MOD1_MASK | GDK_SHIFT_MASK ), //MOD added
PTK_STOCK_MENU_ITEM( "gtk-paste", on_popup_paste_activate ),
PTK_IMG_MENU_ITEM( N_( "Paste as _Link" ), GTK_STOCK_PASTE, on_popup_paste_link_activate, GDK_V, GDK_CONTROL_MASK | GDK_SHIFT_MASK ), //MOD added
PTK_IMG_MENU_ITEM( N_( "Paste as Tar_get" ), GTK_STOCK_PASTE, on_popup_paste_target_activate, GDK_V, GDK_MOD1_MASK | GDK_SHIFT_MASK ), //MOD added
PTK_IMG_MENU_ITEM( N_( "_Delete" ), "gtk-delete", on_popup_delete_activate, GDK_Delete, 0 ),
PTK_IMG_MENU_ITEM( N_( "_Rename" ), "gtk-edit", on_popup_rename_activate, GDK_F2, 0 ),
PTK_SEPARATOR_MENU_ITEM,
PTK_MENU_ITEM( N_( "Compress" ), on_popup_compress_activate, 0, 0 ),
PTK_POPUP_MENU( N_( "E_xtract" ), extract_menu ),
PTK_POPUP_IMG_MENU( N_( "_Create New" ), "gtk-new", create_new_menu ),
PTK_IMG_MENU_ITEM( N_( "R_un Command..." ), GTK_STOCK_EXECUTE, on_popup_run_command, GDK_r, GDK_CONTROL_MASK ), //MOD
PTK_SEPARATOR_MENU_ITEM,
PTK_IMG_MENU_ITEM( N_( "_Properties" ), "gtk-info", on_popup_file_properties_activate, GDK_Return, GDK_MOD1_MASK ),
PTK_MENU_END
};
static PtkMenuItemEntry dir_popup_menu_items[] =
{
PTK_SEPARATOR_MENU_ITEM,
PTK_MENU_ITEM( N_( "Open in New _Tab" ), on_popup_open_in_new_tab_activate, 0, 0 ),
PTK_MENU_ITEM( N_( "Open in New _Window" ), on_popup_open_in_new_win_activate, 0, 0 ),
PTK_IMG_MENU_ITEM( N_( "Open in Terminal" ), GTK_STOCK_EXECUTE, on_popup_open_in_terminal_activate, 0, 0 ),
PTK_MENU_END
};
#if 0
static gboolean same_file_type( GList* files )
{
GList * l;
VFSMimeType* mime_type;
if ( ! files || ! files->next )
return TRUE;
mime_type = vfs_file_info_get_mime_type( ( VFSFileInfo* ) l->data );
for ( l = files->next; l ; l = l->next )
{
VFSMimeType * mime_type2;
mime_type2 = vfs_file_info_get_mime_type( ( VFSFileInfo* ) l->data );
vfs_mime_type_unref( mime_type2 );
if ( mime_type != mime_type2 )
{
vfs_mime_type_unref( mime_type );
return FALSE;
}
}
vfs_mime_type_unref( mime_type );
return TRUE;
}
#endif
*/
void on_popup_list_detailed( GtkMenuItem *menuitem, PtkFileBrowser* browser )
{
int p = browser->mypanel;
if ( xset_get_b_panel( p, "list_detailed" ) )
{
xset_set_b_panel( p, "list_icons", FALSE );
xset_set_b_panel( p, "list_compact", FALSE );
}
else
{
if ( !xset_get_b_panel( p, "list_icons" )
&& !xset_get_b_panel( p, "list_compact" ) )
xset_set_b_panel( p, "list_icons", TRUE );
}
update_views_all_windows( NULL, browser );
}
void on_popup_list_icons( GtkMenuItem *menuitem, PtkFileBrowser* browser )
{
int p = browser->mypanel;
if ( xset_get_b_panel( p, "list_icons" ) )
{
xset_set_b_panel( p, "list_detailed", FALSE );
xset_set_b_panel( p, "list_compact", FALSE );
}
else
{
if ( !xset_get_b_panel( p, "list_detailed" )
&& !xset_get_b_panel( p, "list_compact" ) )
xset_set_b_panel( p, "list_detailed", TRUE );
}
update_views_all_windows( NULL, browser );
}
void on_popup_list_compact( GtkMenuItem *menuitem, PtkFileBrowser* browser )
{
int p = browser->mypanel;
if ( xset_get_b_panel( p, "list_compact" ) )
{
xset_set_b_panel( p, "list_detailed", FALSE );
xset_set_b_panel( p, "list_icons", FALSE );
}
else
{
if ( !xset_get_b_panel( p, "list_icons" )
&& !xset_get_b_panel( p, "list_detailed" ) )
xset_set_b_panel( p, "list_detailed", TRUE );
}
update_views_all_windows( NULL, browser );
}
void on_popup_show_hidden( GtkMenuItem *menuitem, PtkFileMenu* data )
{
if ( data->browser )
ptk_file_browser_show_hidden_files( data->browser,
xset_get_b_panel( data->browser->mypanel, "show_hidden" ) );
}
void on_copycmd( GtkMenuItem *menuitem, PtkFileMenu* data, XSet* set2 )
{
XSet* set;
if ( menuitem )
set = (XSet*)g_object_get_data( G_OBJECT( menuitem ), "set" );
else
set = set2;
if ( !set )
return;
if ( data->browser )
ptk_file_browser_copycmd( data->browser, data->sel_files, data->cwd,
set->name );
#ifdef DESKTOP_INTEGRATION
else if ( data->desktop )
desktop_window_copycmd( data->desktop, data->sel_files, data->cwd,
set->name );
#endif
}
void on_popup_rootcmd_activate( GtkMenuItem *menuitem, PtkFileMenu* data, XSet* set2 )
{
XSet* set;
if ( menuitem )
set = (XSet*)g_object_get_data( G_OBJECT( menuitem ), "set" );
else
set = set2;
if ( set )
ptk_file_misc_rootcmd( data->desktop, data->browser, data->sel_files,
data->cwd, set->name );
}
void on_popup_select_pattern( GtkMenuItem *menuitem, PtkFileMenu* data )
{
if ( data->browser )
ptk_file_browser_select_pattern( NULL, data->browser, NULL );
}
void on_open_in_tab( GtkMenuItem *menuitem, PtkFileMenu* data )
{
int tab_num = GPOINTER_TO_INT( g_object_get_data( G_OBJECT( menuitem ),
"tab_num" ) );
if ( data->browser )
ptk_file_browser_open_in_tab( data->browser, tab_num, data->file_path );
}
void on_open_in_panel( GtkMenuItem *menuitem, PtkFileMenu* data )
{
int panel_num = GPOINTER_TO_INT( g_object_get_data( G_OBJECT( menuitem ),
"panel_num" ) );
if ( data->browser )
main_window_open_in_panel( data->browser, panel_num, data->file_path );
}
void on_file_edit( GtkMenuItem *menuitem, PtkFileMenu* data )
{
xset_edit( data->browser ? GTK_WIDGET( data->browser ) :
GTK_WIDGET( data->desktop ),
data->file_path, FALSE, TRUE );
}
void on_file_root_edit( GtkMenuItem *menuitem, PtkFileMenu* data )
{
xset_edit( data->browser ? GTK_WIDGET( data->browser ) :
GTK_WIDGET( data->desktop ),
data->file_path, TRUE, FALSE );
}
void on_popup_sort_extra( GtkMenuItem *menuitem, PtkFileBrowser* file_browser,
XSet* set2 )
{
XSet* set;
if ( menuitem )
set = (XSet*)g_object_get_data( G_OBJECT( menuitem ), "set" );
else
set = set2;
ptk_file_browser_set_sort_extra( file_browser, set->name );
}
void on_popup_sortby( GtkMenuItem *menuitem, PtkFileBrowser* file_browser, int order )
{
char* val;
int v;
int sort_order;
if ( menuitem )
sort_order = GPOINTER_TO_INT( g_object_get_data( G_OBJECT(menuitem),
"sortorder" ) );
else
sort_order = order;
if ( sort_order < 0 )
{
if ( sort_order == -1 )
v = GTK_SORT_ASCENDING;
else
v = GTK_SORT_DESCENDING;
val = g_strdup_printf( "%d", v );
xset_set_panel( file_browser->mypanel, "list_detailed", "y", val );
g_free( val );
ptk_file_browser_set_sort_type( file_browser, v );
}
else
{
val = g_strdup_printf( "%d", sort_order );
xset_set_panel( file_browser->mypanel, "list_detailed", "x", val );
g_free( val );
ptk_file_browser_set_sort_order( file_browser, sort_order );
}
}
void on_popup_detailed_column( GtkMenuItem *menuitem, PtkFileBrowser* file_browser )
{
if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
on_folder_view_columns_changed( GTK_TREE_VIEW( file_browser->folder_view ),
file_browser );
}
void on_archive_default( GtkMenuItem *menuitem, XSet* set )
{
const char* arcname[] =
{
"arc_def_open",
"arc_def_ex",
"arc_def_exto",
"arc_def_list"
};
int i;
for ( i = 0; i < G_N_ELEMENTS( arcname ); i++ )
{
if ( !strcmp( set->name, arcname[i] ) )
set->b = XSET_B_TRUE;
else
xset_set_b( arcname[i], FALSE );
}
}
void on_hide_file( GtkMenuItem *menuitem, PtkFileMenu* data )
{
if ( data->browser )
ptk_file_browser_hide_selected( data->browser, data->sel_files, data->cwd );
}
void on_permission( GtkMenuItem *menuitem, PtkFileMenu* data )
{
if ( data->browser )
ptk_file_browser_on_permission( menuitem, data->browser, data->sel_files,
data->cwd );
}
int bookmark_item_comp2( const char* item, const char* path )
{
return strcmp( ptk_bookmarks_item_get_path( item ), path );
}
void on_add_bookmark( GtkMenuItem *menuitem, PtkFileMenu* data )
{
char* name;
char* path;
if ( !data->cwd )
return;
if ( data->file_path && g_file_test( data->file_path, G_FILE_TEST_IS_DIR ) )
path = data->file_path;
else
path = data->cwd;
if ( ! g_list_find_custom( app_settings.bookmarks->list,
path,
( GCompareFunc ) bookmark_item_comp2 ) )
{
name = g_path_get_basename( path );
ptk_bookmarks_append( name, path );
g_free( name );
}
else
xset_msg_dialog( data->browser ? GTK_WIDGET( data->browser ) :
GTK_WIDGET( data->desktop ),
GTK_MESSAGE_INFO,
_("Bookmark Exists"), NULL, 0,
_("Bookmark already exists"), NULL, NULL );
}
void on_popup_mount_iso( GtkMenuItem *menuitem, PtkFileMenu* data )
{
mount_iso( data->browser, data->file_path );
}
void on_popup_desktop_sort_activate( GtkMenuItem *menuitem,
DesktopWindow* desktop, XSet* set2 )
{
XSet* set;
if ( menuitem )
set = (XSet*)g_object_get_data( G_OBJECT( menuitem ), "set" );
else
set = set2;
if ( !( set && desktop && g_str_has_prefix( set->name, "desk_sort_" ) ) )
return;
#ifdef DESKTOP_INTEGRATION
int by;
char* xname = set->name + 10;
if ( !strcmp( xname, "name" ) )
by = DW_SORT_BY_NAME;
else if ( !strcmp( xname, "size" ) )
by = DW_SORT_BY_SIZE;
else if ( !strcmp( xname, "type" ) )
by = DW_SORT_BY_TYPE;
else if ( !strcmp( xname, "date" ) )
by = DW_SORT_BY_MTIME;
else
{
if ( !strcmp( xname, "ascend" ) )
by = GTK_SORT_ASCENDING;
else if ( !strcmp( xname, "descend" ) )
by = GTK_SORT_DESCENDING;
else
return;
desktop_window_sort_items( desktop, desktop->sort_by, by );
return;
}
desktop_window_sort_items( desktop, by, desktop->sort_type );
#endif
}
void on_popup_desktop_pref_activate( GtkMenuItem *menuitem, DesktopWindow* desktop )
{
if ( desktop )
fm_edit_preference( GTK_WINDOW( desktop ), PREF_DESKTOP );
}
void on_popup_desktop_new_app_activate( GtkMenuItem *menuitem, DesktopWindow* desktop )
{
#ifdef DESKTOP_INTEGRATION
if ( desktop )
desktop_window_add_application( desktop );
#endif
}
void on_popup_desktop_select( GtkMenuItem *menuitem,
DesktopWindow* desktop, XSet* set2 )
{
XSet* set;
if ( menuitem )
set = (XSet*)g_object_get_data( G_OBJECT( menuitem ), "set" );
else
set = set2;
if ( !( set && set->name && desktop ) )
return;
#ifdef DESKTOP_INTEGRATION
DWSelectMode mode;
if ( !strcmp( set->name, "select_all" ) )
mode = DW_SELECT_ALL;
else if ( !strcmp( set->name, "select_un" ) )
mode = DW_SELECT_NONE;
else if ( !strcmp( set->name, "select_invert" ) )
mode = DW_SELECT_INVERSE;
else if ( !strcmp( set->name, "select_patt" ) )
mode = DW_SELECT_PATTERN;
else
return;
desktop_window_select( desktop, mode );
#endif
}
void on_bookmark_activate( GtkWidget* item, const char* name )
{
if ( name )
open_in_prog( ptk_bookmarks_item_get_path( name ) );
}
static void ptk_file_menu_free( PtkFileMenu *data )
{
if ( data->file_path )
g_free( data->file_path );
if ( data->info )
vfs_file_info_unref( data->info );
g_free( data->cwd );
if ( data->sel_files )
vfs_file_info_list_free( data->sel_files );
if ( data->accel_group )
g_object_unref( data->accel_group );
g_slice_free( PtkFileMenu, data );
}
/* Retrive popup menu for selected file(s) */
GtkWidget* ptk_file_menu_new( DesktopWindow* desktop, PtkFileBrowser* browser,
const char* file_path, VFSFileInfo* info,
const char* cwd, GList* sel_files )
{ // either desktop or browser must be non-NULL
GtkWidget * popup = NULL;
VFSMimeType* mime_type;
GtkWidget *app_menu_item;
GtkWidget* submenu;
gboolean is_dir;
gboolean is_text;
gboolean is_clip;
char **apps, **app;
const char* app_name = NULL;
VFSAppDesktop* desktop_file;
char* name;
char* desc;
char* str;
XSet* set_radio;
GdkPixbuf* app_icon;
int icon_w, icon_h;
GtkWidget* app_img;
int i;
PtkFileMenu* data;
int no_write_access = 0, no_read_access = 0;
XSet* set, *set2;
GtkMenuItem* item;
if ( !desktop && !browser )
return NULL;
data = g_slice_new0( PtkFileMenu );
data->cwd = g_strdup( cwd );
data->browser = browser;
data->desktop = desktop;
data->file_path = g_strdup( file_path );
if ( info )
data->info = vfs_file_info_ref( info );
else
data->info = NULL;
data->sel_files = sel_files;
data->accel_group = gtk_accel_group_new ();
popup = gtk_menu_new();
GtkAccelGroup* accel_group = gtk_accel_group_new();
g_object_weak_ref( G_OBJECT( popup ), (GWeakNotify) ptk_file_menu_free, data );
g_signal_connect_after( ( gpointer ) popup, "selection-done",
G_CALLBACK ( gtk_widget_destroy ), NULL );
//is_dir = file_path && g_file_test( file_path, G_FILE_TEST_IS_DIR );
is_dir = ( info && vfs_file_info_is_dir( info ) );
// Note: network filesystems may become unresponsive here
is_text = info && file_path && vfs_file_info_is_text( info, file_path );
// test R/W access to cwd instead of selected file
// Note: network filesystems may become unresponsive here
#if defined(HAVE_EUIDACCESS)
no_read_access = euidaccess( cwd, R_OK );
no_write_access = euidaccess( cwd, W_OK );
#elif defined(HAVE_EACCESS)
no_read_access = eaccess( cwd, R_OK );
no_write_access = eaccess( cwd, W_OK );
#endif
GtkClipboard* clip = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD );
if ( ! gtk_clipboard_wait_is_target_available ( clip,
gdk_atom_intern( "x-special/gnome-copied-files", FALSE ) ) &&
! gtk_clipboard_wait_is_target_available ( clip,
gdk_atom_intern( "text/uri-list", FALSE ) ) )
is_clip = FALSE;
else
is_clip = TRUE;
int p = 0;
int tab_count = 0;
int tab_num = 0;
int panel_count = 0;
if ( browser )
{
p = browser->mypanel;
main_window_get_counts( browser, &panel_count, &tab_count, &tab_num );
}
XSetContext* context = xset_context_new();
// Get mime type and apps
if ( info )
{
mime_type = vfs_file_info_get_mime_type( info );
apps = vfs_mime_type_get_actions( mime_type );
context->var[CONTEXT_MIME] = g_strdup( vfs_mime_type_get_type( mime_type ) );
}
else
{
mime_type = NULL;
apps = NULL;
context->var[CONTEXT_MIME] = g_strdup( "" );
}
// context
if ( file_path )
context->var[CONTEXT_NAME] = g_path_get_basename( file_path );
else
context->var[CONTEXT_NAME] = g_strdup( "" );
context->var[CONTEXT_DIR] = g_strdup( cwd );
context->var[CONTEXT_WRITE_ACCESS] = no_write_access ? g_strdup( "false" ) :
g_strdup( "true" );
context->var[CONTEXT_IS_TEXT] = is_text ? g_strdup( "true" ) :
g_strdup( "false" );
context->var[CONTEXT_IS_DIR] = is_dir ? g_strdup( "true" ) :
g_strdup( "false" );
context->var[CONTEXT_MUL_SEL] = sel_files && sel_files->next ?
g_strdup( "true" ) : g_strdup( "false" );
context->var[CONTEXT_CLIP_FILES] = is_clip ? g_strdup( "true" ) :
g_strdup( "false" );
if ( info )
context->var[CONTEXT_IS_LINK] = vfs_file_info_is_symlink( info ) ?
g_strdup( "true" ) : g_strdup( "false" );
else
context->var[CONTEXT_IS_LINK] = g_strdup( "false" );
if ( browser )
main_context_fill( browser, context );
#ifdef DESKTOP_INTEGRATION
else
desktop_context_fill( desktop, context );
#endif
if ( !context->valid )
{
// rare exception due to context_fill hacks - fb was probably destroyed
g_warning( "context_fill rare exception" );
context = xset_context_new();
g_slice_free( XSetContext, context );
context = NULL;
return NULL;
}
// Open >
set = xset_get( "con_open" );
set->disable = !sel_files;
item = GTK_MENU_ITEM( xset_add_menuitem( desktop, browser, popup,
accel_group, set ) );
if ( sel_files )
{
submenu = gtk_menu_item_get_submenu( item );
// Execute
if ( !is_dir && info && file_path &&
( info->flags & VFS_FILE_INFO_DESKTOP_ENTRY ||
// Note: network filesystems may become unresponsive here
vfs_file_info_is_executable( info, file_path ) ) )
{
set = xset_set_cb( "open_execute", on_popup_open_activate, data );
xset_add_menuitem( desktop, browser, submenu, accel_group, set );
}
// add apps
if ( is_text )
{
char **tmp, **txt_apps;
VFSMimeType* txt_type;
int len1, len2;
txt_type = vfs_mime_type_get_from_type( XDG_MIME_TYPE_PLAIN_TEXT );
txt_apps = vfs_mime_type_get_actions( txt_type );
if ( txt_apps )
{
len1 = apps ? g_strv_length( apps ) : 0;
len2 = g_strv_length( txt_apps );
tmp = apps;
apps = vfs_mime_type_join_actions( apps, len1, txt_apps, len2 );
g_strfreev( txt_apps );
g_strfreev( tmp );
}
vfs_mime_type_unref( txt_type );
}
if ( apps )
{
for ( app = apps; *app; ++app )
{
if ( ( app - apps ) == 1 ) // Add a separator after default app
{
item = GTK_MENU_ITEM( gtk_separator_menu_item_new() );
gtk_widget_show ( GTK_WIDGET( item ) );
gtk_container_add ( GTK_CONTAINER ( submenu ),
GTK_WIDGET( item ) );
}
desktop_file = vfs_app_desktop_new( *app );
app_name = vfs_app_desktop_get_disp_name( desktop_file );
if ( app_name )
app_menu_item = gtk_image_menu_item_new_with_label ( app_name );
else
app_menu_item = gtk_image_menu_item_new_with_label ( *app );
gtk_container_add ( GTK_CONTAINER ( submenu ), app_menu_item );
g_signal_connect( G_OBJECT( app_menu_item ), "activate",
G_CALLBACK( on_popup_run_app ), ( gpointer ) data );
g_object_set_data( G_OBJECT( app_menu_item ), "menu", submenu );
g_signal_connect( G_OBJECT( app_menu_item ), "button-press-event",
G_CALLBACK( on_app_button_press ),
( gpointer ) data );
g_signal_connect( G_OBJECT( app_menu_item ), "button-release-event",
G_CALLBACK( on_app_button_press ),
( gpointer ) data );
g_object_set_data_full( G_OBJECT( app_menu_item ), "desktop_file",
desktop_file, vfs_app_desktop_unref );
gtk_icon_size_lookup_for_settings( gtk_settings_get_default(),
GTK_ICON_SIZE_MENU,
&icon_w, &icon_h );
app_icon = vfs_app_desktop_get_icon( desktop_file,
icon_w > icon_h ? icon_w : icon_h, TRUE );
if ( app_icon )
{
app_img = gtk_image_new_from_pixbuf( app_icon );
if ( app_img )
gtk_image_menu_item_set_image ( GTK_IMAGE_MENU_ITEM(
app_menu_item ), app_img );
g_object_unref( app_icon );
}
}
g_strfreev( apps );
}
// open with other
item = GTK_MENU_ITEM( gtk_separator_menu_item_new() );
gtk_menu_shell_append( GTK_MENU_SHELL( submenu ), GTK_WIDGET( item ) );
set = xset_set_cb( "open_other", on_popup_open_with_another_activate, data );
xset_add_menuitem( desktop, browser, submenu, accel_group, set );
// Default
char* plain_type = NULL;
if ( mime_type )
plain_type = g_strdup( vfs_mime_type_get_type( mime_type ) );
if ( !plain_type )
plain_type = g_strdup( "" );
str = plain_type;
plain_type = replace_string( str, "-", "_", FALSE );
g_free( str );
str = replace_string( plain_type, " ", "", FALSE );
g_free( plain_type );
plain_type = g_strdup_printf( "open_all_type_%s", str );
g_free( str );
set = xset_set_cb( plain_type, on_popup_open_all, data );
g_free( plain_type );
set->lock = TRUE;
set->menu_style = XSET_MENU_NORMAL;
if ( set->shared_key )
g_free( set->shared_key );
set->shared_key = g_strdup( "open_all" );
set2 = xset_get( "open_all" );
if ( set->menu_label )
g_free( set->menu_label );
set->menu_label = g_strdup( set2->menu_label );
if ( set->context )
{
g_free( set->context );
set->context = NULL;
}
item = GTK_MENU_ITEM( xset_add_menuitem( desktop, browser, submenu,
accel_group, set ) );
app_icon = mime_type ? vfs_mime_type_get_icon( mime_type, FALSE ) : NULL;
if ( app_icon )
{
app_img = gtk_image_new_from_pixbuf( app_icon );
if ( app_img )
gtk_image_menu_item_set_image ( GTK_IMAGE_MENU_ITEM( item ),
app_img );
g_object_unref( app_icon );
}
if ( set->menu_label )
g_free( set->menu_label );
set->menu_label = NULL; // don't bother to save this
// Edit / Dir
if ( ( is_dir && browser ) || ( is_text && sel_files && !sel_files->next ) )
{
item = GTK_MENU_ITEM( gtk_separator_menu_item_new() );
gtk_menu_shell_append( GTK_MENU_SHELL( submenu ), GTK_WIDGET( item ) );
if ( is_text )
{
// Edit
set = xset_set_cb( "open_edit", on_file_edit, data );
set->disable = ( geteuid() == 0 );
xset_add_menuitem( desktop, browser, submenu, accel_group, set );
set = xset_set_cb( "open_edit_root", on_file_root_edit, data );
xset_add_menuitem( desktop, browser, submenu, accel_group, set );
}
else if ( browser && is_dir )
{
// Open Dir
set = xset_set_cb( "opentab_prev", on_open_in_tab, data );
xset_set_ob1_int( set, "tab_num", -1 );
set->disable = ( tab_num == 1 );
set = xset_set_cb( "opentab_next", on_open_in_tab, data );
xset_set_ob1_int( set, "tab_num", -2 );
set->disable = ( tab_num == tab_count );
set = xset_set_cb( "opentab_new", on_popup_open_in_new_tab_activate,
data );
for ( i = 1; i < 11; i++ )
{
name = g_strdup_printf( "opentab_%d", i );
set = xset_set_cb( name, on_open_in_tab, data );
xset_set_ob1_int( set, "tab_num", i );
set->disable = ( i > tab_count ) || ( i == tab_num );
g_free( name );
}
set = xset_set_cb( "open_in_panelprev", on_open_in_panel, data );
xset_set_ob1_int( set, "panel_num", -1 );
set->disable = ( panel_count == 1 );
set = xset_set_cb( "open_in_panelnext", on_open_in_panel, data );
xset_set_ob1_int( set, "panel_num", -2 );
set->disable = ( panel_count == 1 );
for ( i = 1; i < 5; i++ )
{
name = g_strdup_printf( "open_in_panel%d", i );
set = xset_set_cb( name, on_open_in_panel, data );
xset_set_ob1_int( set, "panel_num", i );
//set->disable = ( p == i );
g_free( name );
}
set = xset_get( "open_in_tab" );
xset_add_menuitem( desktop, browser, submenu, accel_group, set );
set = xset_get( "open_in_panel" );
xset_add_menuitem( desktop, browser, submenu, accel_group, set );
}
}
if ( mime_type && ptk_file_archiver_is_format_supported( mime_type, TRUE ) )
{
item = GTK_MENU_ITEM( gtk_separator_menu_item_new() );
gtk_menu_shell_append( GTK_MENU_SHELL( submenu ), GTK_WIDGET( item ) );
set = xset_set_cb( "arc_extract", on_popup_extract_here_activate, data );
xset_set_ob1( set, "set", set );
set->disable = no_write_access;
xset_add_menuitem( desktop, browser, submenu, accel_group, set );
set = xset_set_cb( "arc_extractto", on_popup_extract_to_activate, data );
xset_set_ob1( set, "set", set );
xset_add_menuitem( desktop, browser, submenu, accel_group, set );
set = xset_set_cb( "arc_list", on_popup_extract_list_activate, data );
xset_set_ob1( set, "set", set );
xset_add_menuitem( desktop, browser, submenu, accel_group, set );
set = xset_get( "arc_def_open" );
xset_set_cb( "arc_def_open", on_archive_default, set );
xset_set_ob2( set, NULL, NULL );
set_radio = set;
set = xset_get( "arc_def_ex" );
xset_set_cb( "arc_def_ex", on_archive_default, set );
xset_set_ob2( set, NULL, set_radio );
set = xset_get( "arc_def_exto" );
xset_set_cb( "arc_def_exto", on_archive_default, set );
xset_set_ob2( set, NULL, set_radio );
set = xset_get( "arc_def_list" );
xset_set_cb( "arc_def_list", on_archive_default, set );
xset_set_ob2( set, NULL, set_radio );
set = xset_get( "arc_def_write" );
if ( geteuid() == 0 )
{
set->b = XSET_B_FALSE;
set->disable = TRUE;
}
xset_add_menuitem( desktop, browser, submenu, accel_group,
xset_get( "arc_default" ) );
}
else if ( file_path && mime_type && (
!strcmp( vfs_mime_type_get_type( mime_type ),
"application/x-cd-image" ) ||
!strcmp( vfs_mime_type_get_type( mime_type ),
"application/x-iso9660-image" ) ||
g_str_has_suffix( file_path, ".iso" ) ||
g_str_has_suffix( file_path, ".img" ) ) )
{
item = GTK_MENU_ITEM( gtk_separator_menu_item_new() );
gtk_menu_shell_append( GTK_MENU_SHELL( submenu ), GTK_WIDGET( item ) );
set = xset_set_cb( "iso_mount", on_popup_mount_iso, data );
xset_add_menuitem( desktop, browser, submenu, accel_group, set );
set = xset_get( "iso_auto" );
xset_add_menuitem( desktop, browser, submenu, accel_group, set );
str = g_find_program_in_path( "udevil" );
set->disable = !str;
g_free( str );
}
g_signal_connect (submenu, "key-press-event",
G_CALLBACK (app_menu_keypress), data );
}
if ( mime_type )
vfs_mime_type_unref( mime_type );
// Go >
if ( browser )
{
set = xset_set_cb( "go_back", ptk_file_browser_go_back, browser );
set->disable = !( browser->curHistory && browser->curHistory->prev );
set = xset_set_cb( "go_forward", ptk_file_browser_go_forward, browser );
set->disable = !( browser->curHistory && browser->curHistory->next );
set = xset_set_cb( "go_up", ptk_file_browser_go_up, browser );
set->disable = !strcmp( cwd, "/" );
xset_set_cb( "go_home", ptk_file_browser_go_home, browser );
xset_set_cb( "go_default", ptk_file_browser_go_default, browser );
xset_set_cb( "go_set_default", ptk_file_browser_set_default_folder, browser );
xset_set_cb( "edit_canon", on_popup_canon, data );
xset_set_cb( "go_refresh", ptk_file_browser_refresh, browser );
set = xset_set_cb( "focus_path_bar", ptk_file_browser_focus, browser );
xset_set_ob1_int( set, "job", 0 );
set = xset_set_cb( "focus_filelist", ptk_file_browser_focus, browser );
xset_set_ob1_int( set, "job", 4 );
set = xset_set_cb( "focus_dirtree", ptk_file_browser_focus, browser );
xset_set_ob1_int( set, "job", 1 );
set = xset_set_cb( "focus_book", ptk_file_browser_focus, browser );
xset_set_ob1_int( set, "job", 2 );
set = xset_set_cb( "focus_device", ptk_file_browser_focus, browser );
xset_set_ob1_int( set, "job", 3 );
// Go > Tab >
set = xset_set_cb( "tab_prev", ptk_file_browser_go_tab, browser );
xset_set_ob1_int( set, "tab_num", -1 );
set->disable = ( tab_count < 2 );
set = xset_set_cb( "tab_next", ptk_file_browser_go_tab, browser );
xset_set_ob1_int( set, "tab_num", -2 );
set->disable = ( tab_count < 2 );
set = xset_set_cb( "tab_close", ptk_file_browser_go_tab, browser );
xset_set_ob1_int( set, "tab_num", -3 );
for ( i = 1; i < 11; i++ )
{
name = g_strdup_printf( "tab_%d", i );
set = xset_set_cb( name, ptk_file_browser_go_tab, browser );
xset_set_ob1_int( set, "tab_num", i );
set->disable = ( i > tab_count ) || ( i == tab_num );
g_free( name );
}
set = xset_get( "con_go" );
xset_add_menuitem( desktop, browser, popup, accel_group, set );
}
// New >
if ( desktop || browser )
{
set = xset_set_cb( "new_file", on_popup_new_text_file_activate, data );
set = xset_set_cb( "new_folder", on_popup_new_folder_activate, data );
set = xset_set_cb( "new_link", on_popup_new_link_activate, data );
if ( desktop )
{
xset_set_cb( "new_app", on_popup_desktop_new_app_activate, desktop );
set = xset_get( "open_new" );
xset_set_set( set, "desc", "new_file new_folder new_link sep_o1 new_app" );
}
else
{
set = xset_set_cb( "new_archive", on_popup_compress_activate, data );
set->disable = ( !sel_files || !browser );
set = xset_set_cb( "tab_new", on_shortcut_new_tab_activate, browser );
set->disable = !browser;
set = xset_set_cb( "tab_new_here", on_popup_open_in_new_tab_here, data );
set->disable = !browser;
set = xset_set_cb( "new_bookmark", on_add_bookmark, data );
set->disable = !browser;
set = xset_get( "open_new" );
xset_set_set( set, "desc", "new_file new_folder new_link new_archive sep_o1 tab_new tab_new_here new_bookmark" );
}
xset_add_menuitem( desktop, browser, popup, accel_group, set );
set = xset_get( "sep_new" );
xset_add_menuitem( desktop, browser, popup, accel_group, set );
}
// Edit
if ( browser || desktop )
{
set = xset_set_cb( "copy_name", on_popup_copy_name_activate, data );
set->disable = !sel_files;
set = xset_set_cb( "copy_path", on_popup_copy_text_activate, data );
set->disable = !sel_files;
set = xset_set_cb( "copy_parent", on_popup_copy_parent_activate, data );
set->disable = !sel_files;
set = xset_set_cb( "paste_link", on_popup_paste_link_activate, data );
set->disable = !is_clip || no_write_access;
set = xset_set_cb( "paste_target", on_popup_paste_target_activate, data );
set->disable = !is_clip || no_write_access;
set = xset_set_cb( "paste_as", on_popup_paste_as_activate, data );
set->disable = !is_clip;
set = xset_set_cb( "root_copy_loc", on_popup_rootcmd_activate, data );
xset_set_ob1( set, "set", set );
set->disable = !sel_files;
set = xset_set_cb( "root_move2", on_popup_rootcmd_activate, data );
xset_set_ob1( set, "set", set );
set->disable = !sel_files;
set = xset_set_cb( "root_delete", on_popup_rootcmd_activate, data );
xset_set_ob1( set, "set", set );
set->disable = !sel_files;
set = xset_set_cb( "edit_hide", on_hide_file, data );
set->disable = !sel_files || no_write_access || desktop || !browser;
if ( browser )
{
xset_set_cb( "select_all", ptk_file_browser_select_all, data->browser );
set = xset_set_cb( "select_un", ptk_file_browser_unselect_all, browser );
set->disable = !sel_files;
xset_set_cb( "select_invert", ptk_file_browser_invert_selection, browser );
xset_set_cb( "select_patt", on_popup_select_pattern, data );
}
else
{
xset_set_cb( "select_all", on_popup_desktop_select, desktop );
set = xset_set_cb( "select_un", on_popup_desktop_select, desktop );
set->disable = !sel_files;
xset_set_cb( "select_invert", on_popup_desktop_select, desktop );
xset_set_cb( "select_patt", on_popup_desktop_select, desktop );
}
static const char* copycmd[] =
{
"copy_loc",
"copy_loc_last",
"copy_tab_prev",
"copy_tab_next",
"copy_tab_1",
"copy_tab_2",
"copy_tab_3",
"copy_tab_4",
"copy_tab_5",
"copy_tab_6",
"copy_tab_7",
"copy_tab_8",
"copy_tab_9",
"copy_tab_10",
"copy_panel_prev",
"copy_panel_next",
"copy_panel_1",
"copy_panel_2",
"copy_panel_3",
"copy_panel_4",
"move_loc",
"move_loc_last",
"move_tab_prev",
"move_tab_next",
"move_tab_1",
"move_tab_2",
"move_tab_3",
"move_tab_4",
"move_tab_5",
"move_tab_6",
"move_tab_7",
"move_tab_8",
"move_tab_9",
"move_tab_10",
"move_panel_prev",
"move_panel_next",
"move_panel_1",
"move_panel_2",
"move_panel_3",
"move_panel_4"
};
for ( i = 0; i < G_N_ELEMENTS( copycmd ); i++ )
{
set = xset_set_cb( copycmd[i], on_copycmd, data );
xset_set_ob1( set, "set", set );
}
// enables
set = xset_get( "copy_loc_last" );
set2 = xset_get( "move_loc_last" );
if ( desktop )
{
set = xset_get( "copy_tab" );
set->disable = TRUE;
set = xset_get( "copy_panel" );
set->disable = TRUE;
set = xset_get( "move_tab" );
set->disable = TRUE;
set = xset_get( "move_panel" );
set->disable = TRUE;
}
else
{
set = xset_get( "copy_tab_prev" );
set->disable = ( tab_num == 1 );
set = xset_get( "copy_tab_next" );
set->disable = ( tab_num == tab_count );
set = xset_get( "move_tab_prev" );
set->disable = ( tab_num == 1 );
set = xset_get( "move_tab_next" );
set->disable = ( tab_num == tab_count );
set = xset_get( "copy_panel_prev" );
set->disable = ( panel_count < 2 );
set = xset_get( "copy_panel_next" );
set->disable = ( panel_count < 2 );
set = xset_get( "move_panel_prev" );
set->disable = ( panel_count < 2 );
set = xset_get( "move_panel_next" );
set->disable = ( panel_count < 2 );
gboolean b;
for ( i = 1; i < 11; i++ )
{
str = g_strdup_printf( "copy_tab_%d", i );
set = xset_get( str );
g_free( str );
set->disable = ( i > tab_count ) || ( i == tab_num );
str = g_strdup_printf( "move_tab_%d", i );
set = xset_get( str );
g_free( str );
set->disable = ( i > tab_count ) || ( i == tab_num );
if ( i > 4 )
continue;
b = main_window_panel_is_visible( browser, i );
str = g_strdup_printf( "copy_panel_%d", i );
set = xset_get( str );
g_free( str );
set->disable = ( i == p ) || !b;
str = g_strdup_printf( "move_panel_%d", i );
set = xset_get( str );
g_free( str );
set->disable = ( i == p ) || !b;
}
}
set = xset_get( "copy_to" );
set->disable = !sel_files;
set = xset_get( "move_to" );
set->disable = !sel_files;
set = xset_get( "edit_root" );
set->disable = ( geteuid() == 0 ) || !sel_files;
set = xset_get( "edit_submenu" );
xset_add_menuitem( desktop, browser, popup, accel_group, set );
}
set = xset_set_cb( "edit_cut", on_popup_cut_activate, data );
set->disable = !sel_files;
xset_add_menuitem( desktop, browser, popup, accel_group, set );
set = xset_set_cb( "edit_copy", on_popup_copy_activate, data );
set->disable = !sel_files;
xset_add_menuitem( desktop, browser, popup, accel_group, set );
set = xset_set_cb( "edit_paste", on_popup_paste_activate, data );
set->disable = !is_clip || no_write_access;
xset_add_menuitem( desktop, browser, popup, accel_group, set );
set = xset_set_cb( "edit_rename", on_popup_rename_activate, data );
set->disable = !sel_files;
xset_add_menuitem( desktop, browser, popup, accel_group, set );
set = xset_set_cb( "edit_delete", on_popup_delete_activate, data );
set->disable = !sel_files || no_write_access;
xset_add_menuitem( desktop, browser, popup, accel_group, set );
set = xset_get( "sep_edit" );
xset_add_menuitem( desktop, browser, popup, accel_group, set );
// View >
if ( browser )
{
gboolean show_side = FALSE;
xset_set_cb( "view_refresh", ptk_file_browser_refresh, browser );
xset_set_cb_panel( p, "show_toolbox", update_views_all_windows, browser );
set = xset_set_cb_panel( p, "show_devmon", update_views_all_windows, browser );
if ( set->b == XSET_B_TRUE ) show_side = TRUE;
set = xset_set_cb_panel( p, "show_dirtree", update_views_all_windows, browser );
if ( set->b == XSET_B_TRUE ) show_side = TRUE;
set = xset_set_cb_panel( p, "show_book", update_views_all_windows, browser );
if ( set->b == XSET_B_TRUE ) show_side = TRUE;
set = xset_set_cb_panel( p, "show_sidebar", update_views_all_windows, browser );
set->disable = !show_side;
xset_set_cb_panel( p, "show_hidden", on_popup_show_hidden, data );
if ( browser->view_mode == PTK_FB_LIST_VIEW )
{
xset_set_cb_panel( p, "detcol_size", on_popup_detailed_column, browser );
xset_set_cb_panel( p, "detcol_type", on_popup_detailed_column, browser );
xset_set_cb_panel( p, "detcol_perm", on_popup_detailed_column, browser );
xset_set_cb_panel( p, "detcol_owner", on_popup_detailed_column, browser );
xset_set_cb_panel( p, "detcol_date", on_popup_detailed_column, browser );
xset_set_cb( "view_reorder_col", on_reorder, browser );
set = xset_set( "view_columns", "disable", "0" );
desc = g_strdup_printf( "panel%d_detcol_size panel%d_detcol_type panel%d_detcol_perm panel%d_detcol_owner panel%d_detcol_date sep_v4 view_reorder_col", p, p, p, p, p );
xset_set_set( set, "desc", desc );
g_free( desc );
set = xset_set_cb( "rubberband", main_window_rubberband_all, NULL );
set->disable = FALSE;
}
else
{
xset_set( "view_columns", "disable", "1" );
xset_set( "rubberband", "disable", "1" );
}
set = xset_set_cb_panel( p, "list_detailed", on_popup_list_detailed, browser );
xset_set_ob2( set, NULL, NULL );
set_radio = set;
set = xset_set_cb_panel( p, "list_icons", on_popup_list_icons, browser );
xset_set_ob2( set, NULL, set_radio );
set = xset_set_cb_panel( p, "list_compact", on_popup_list_compact, browser );
xset_set_ob2( set, NULL, set_radio );
set = xset_set_cb( "sortby_name", on_popup_sortby, browser );
xset_set_ob1_int( set, "sortorder", PTK_FB_SORT_BY_NAME );
xset_set_ob2( set, NULL, NULL );
set->b = browser->sort_order == PTK_FB_SORT_BY_NAME ? XSET_B_TRUE : XSET_B_FALSE;
set_radio = set;
set = xset_set_cb( "sortby_size", on_popup_sortby, browser );
xset_set_ob1_int( set, "sortorder", PTK_FB_SORT_BY_SIZE );
xset_set_ob2( set, NULL, set_radio );
set->b = browser->sort_order == PTK_FB_SORT_BY_SIZE ? XSET_B_TRUE : XSET_B_FALSE;
set = xset_set_cb( "sortby_type", on_popup_sortby, browser );
xset_set_ob1_int( set, "sortorder", PTK_FB_SORT_BY_TYPE );
xset_set_ob2( set, NULL, set_radio );
set->b = browser->sort_order == PTK_FB_SORT_BY_TYPE ? XSET_B_TRUE : XSET_B_FALSE;
set = xset_set_cb( "sortby_perm", on_popup_sortby, browser );
xset_set_ob1_int( set, "sortorder", PTK_FB_SORT_BY_PERM );
xset_set_ob2( set, NULL, set_radio );
set->b = browser->sort_order == PTK_FB_SORT_BY_PERM ? XSET_B_TRUE : XSET_B_FALSE;
set = xset_set_cb( "sortby_owner", on_popup_sortby, browser );
xset_set_ob1_int( set, "sortorder", PTK_FB_SORT_BY_OWNER );
xset_set_ob2( set, NULL, set_radio );
set->b = browser->sort_order == PTK_FB_SORT_BY_OWNER ? XSET_B_TRUE : XSET_B_FALSE;
set = xset_set_cb( "sortby_date", on_popup_sortby, browser );
xset_set_ob1_int( set, "sortorder", PTK_FB_SORT_BY_MTIME );
xset_set_ob2( set, NULL, set_radio );
set->b = browser->sort_order == PTK_FB_SORT_BY_MTIME ? XSET_B_TRUE : XSET_B_FALSE;
set = xset_set_cb( "sortby_ascend", on_popup_sortby, browser );
xset_set_ob1_int( set, "sortorder", -1 );
xset_set_ob2( set, NULL, NULL );
set->b = browser->sort_type == GTK_SORT_ASCENDING ? XSET_B_TRUE : XSET_B_FALSE;
set_radio = set;
set = xset_set_cb( "sortby_descend", on_popup_sortby, browser );
xset_set_ob1_int( set, "sortorder", -2 );
xset_set_ob2( set, NULL, set_radio );
set->b = browser->sort_type == GTK_SORT_DESCENDING ? XSET_B_TRUE : XSET_B_FALSE;
set = xset_set_cb( "sortx_natural", on_popup_sort_extra, browser );
set->b = PTK_FILE_LIST( browser->file_list )->sort_natural ?
XSET_B_TRUE : XSET_B_FALSE;
set = xset_set_cb( "sortx_case", on_popup_sort_extra, browser );
set->b = PTK_FILE_LIST( browser->file_list )->sort_case ?
XSET_B_TRUE : XSET_B_FALSE;
set->disable = !PTK_FILE_LIST( browser->file_list )->sort_natural;
set = xset_set_cb( "sortx_folders", on_popup_sort_extra, browser );
xset_set_ob2( set, NULL, NULL );
set->b = PTK_FILE_LIST( browser->file_list )->sort_dir ==
PTK_LIST_SORT_DIR_FIRST ? XSET_B_TRUE : XSET_B_FALSE;
set_radio = set;
set = xset_set_cb( "sortx_files", on_popup_sort_extra, browser );
xset_set_ob2( set, NULL, set_radio );
set->b = PTK_FILE_LIST( browser->file_list )->sort_dir ==
PTK_LIST_SORT_DIR_LAST ? XSET_B_TRUE : XSET_B_FALSE;
set = xset_set_cb( "sortx_mix", on_popup_sort_extra, browser );
xset_set_ob2( set, NULL, set_radio );
set->b = PTK_FILE_LIST( browser->file_list )->sort_dir ==
PTK_LIST_SORT_DIR_MIXED ? XSET_B_TRUE : XSET_B_FALSE;
set = xset_set_cb( "sortx_hidfirst", on_popup_sort_extra, browser );
xset_set_ob2( set, NULL, NULL );
set->b = PTK_FILE_LIST( browser->file_list )->sort_hidden_first ?
XSET_B_TRUE : XSET_B_FALSE;
set_radio = set;
set = xset_set_cb( "sortx_hidlast", on_popup_sort_extra, browser );
xset_set_ob2( set, NULL, set_radio );
set->b = PTK_FILE_LIST( browser->file_list )->sort_hidden_first ?
XSET_B_FALSE : XSET_B_TRUE;
xset_set_cb_panel( p, "font_file", main_update_fonts, browser );
set = xset_get( "view_list_style" );
desc = g_strdup_printf( "panel%d_list_detailed panel%d_list_compact panel%d_list_icons sep_v5 view_columns rubberband sep_v6 panel%d_font_file",
p, p, p, p );
xset_set_set( set, "desc", desc );
g_free( desc );
set = xset_get( "view_fonts" );
desc = g_strdup_printf( "panel%d_font_device panel%d_font_dir panel%d_font_book panel%d_font_files panel%d_font_tabs panel%d_font_status panel%d_font_pathbar",
p, p, p, p, p, p ,p );
xset_set_set( set, "desc", desc );
g_free( desc );
set = xset_get( "con_view" );
desc = g_strdup_printf( "panel%d_show_toolbox panel%d_show_sidebar panel%d_show_devmon panel%d_show_book panel%d_show_dirtree sep_v7 panel%d_show_hidden view_list_style view_sortby sep_v8 view_refresh",
p, p, p, p, p, p );
xset_set_set( set, "desc", desc );
g_free( desc );
xset_add_menuitem( desktop, browser, popup, accel_group, set );
}
// Properties
if ( browser )
{
set = xset_set_cb( "prop_info", on_popup_file_properties_activate, data );
set = xset_set_cb( "prop_perm", on_popup_file_permissions_activate, data );
static const char* permcmd[] =
{
"perm_r",
"perm_rw",
"perm_rwx",
"perm_r_r",
"perm_rw_r",
"perm_rw_rw",
"perm_rwxr_x",
"perm_rwxrwx",
"perm_r_r_r",
"perm_rw_r_r",
"perm_rw_rw_rw",
"perm_rwxr_r",
"perm_rwxr_xr_x",
"perm_rwxrwxrwx",
"perm_rwxrwxrwt",
"perm_unstick",
"perm_stick",
"perm_go_w",
"perm_go_rwx",
"perm_ugo_w",
"perm_ugo_rx",
"perm_ugo_rwx",
"rperm_rw",
"rperm_rwx",
"rperm_rw_r",
"rperm_rw_rw",
"rperm_rwxr_x",
"rperm_rwxrwx",
"rperm_rw_r_r",
"rperm_rw_rw_rw",
"rperm_rwxr_r",
"rperm_rwxr_xr_x",
"rperm_rwxrwxrwx",
"rperm_rwxrwxrwt",
"rperm_unstick",
"rperm_stick",
"rperm_go_w",
"rperm_go_rwx",
"rperm_ugo_w",
"rperm_ugo_rx",
"rperm_ugo_rwx",
"own_myuser",
"own_myuser_users",
"own_user1",
"own_user1_users",
"own_user2",
"own_user2_users",
"own_root",
"own_root_users",
"own_root_myuser",
"own_root_user1",
"own_root_user2",
"rown_myuser",
"rown_myuser_users",
"rown_user1",
"rown_user1_users",
"rown_user2",
"rown_user2_users",
"rown_root",
"rown_root_users",
"rown_root_myuser",
"rown_root_user1",
"rown_root_user2"
};
for ( i = 0; i < G_N_ELEMENTS( permcmd ); i++ )
{
set = xset_set_cb( permcmd[i], on_permission, data );
xset_set_ob1( set, "set", set );
}
set = xset_get( "prop_quick" );
set->disable = no_write_access || !sel_files;
set = xset_get( "prop_root" );
set->disable = !sel_files;
set = xset_get( "con_prop" );
if ( geteuid() == 0 )
desc = g_strdup_printf( "prop_info prop_perm prop_root" );
else
desc = g_strdup_printf( "prop_info prop_perm prop_quick prop_root" );
xset_set_set( set, "desc", desc );
g_free( desc );
xset_add_menuitem( desktop, browser, popup, accel_group, set );
}
else if ( desktop )
{
// Desktop|Devices
set = xset_get( "desk_dev" );
item = GTK_MENU_ITEM( xset_add_menuitem( desktop, NULL, popup,
accel_group, set ) );
submenu = gtk_menu_item_get_submenu( item );
ptk_location_view_dev_menu( GTK_WIDGET( desktop ), submenu );
#ifndef HAVE_HAL
set = xset_get( "sep_dm3" );
xset_add_menuitem( desktop, NULL, submenu, accel_group, set );
set = xset_get( "dev_menu_settings" );
xset_add_menuitem( desktop, NULL, submenu, accel_group, set );
#endif
// Desktop|Bookmarks
set = xset_get( "desk_book" );
GtkMenuItem* book_item = GTK_MENU_ITEM( xset_add_menuitem( desktop,
NULL, popup,
accel_group, set ) );
submenu = gtk_menu_item_get_submenu( book_item );
GtkWidget* folder_image;
XSet* set = xset_get( "book_icon" );
const char* book_icon = set->icon;
int count = 0;
GList* l;
for ( l = app_settings.bookmarks->list; l; l = l->next )
{
item = GTK_MENU_ITEM( gtk_image_menu_item_new_with_label(
(char*)l->data ) );
if ( book_icon )
folder_image = xset_get_image( book_icon, GTK_ICON_SIZE_MENU );
else
folder_image = NULL;
if ( !folder_image )
folder_image = xset_get_image( "gtk-directory", GTK_ICON_SIZE_MENU );
if ( folder_image )
gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM ( item ),
folder_image );
g_signal_connect( item, "activate", G_CALLBACK( on_bookmark_activate ),
(char*)l->data );
gtk_menu_shell_append( GTK_MENU_SHELL( submenu ), GTK_WIDGET( item ) );
if ( ++count > 200 )
break;
}
if ( count == 0 )
gtk_widget_set_sensitive( GTK_WIDGET( book_item ), FALSE );
// Desktop|Icons >
set = xset_set_cb( "desk_sort_name", on_popup_desktop_sort_activate,
desktop );
set->b = app_settings.desktop_sort_by == DW_SORT_BY_NAME ?
XSET_B_TRUE : XSET_B_FALSE;
xset_set_ob2( set, NULL, NULL );
set_radio = set;
set = xset_set_cb( "desk_sort_type", on_popup_desktop_sort_activate,
desktop );
set->b = app_settings.desktop_sort_by == DW_SORT_BY_TYPE ?
XSET_B_TRUE : XSET_B_FALSE;
xset_set_ob2( set, NULL, set_radio );
set = xset_set_cb( "desk_sort_date", on_popup_desktop_sort_activate,
desktop );
set->b = app_settings.desktop_sort_by == DW_SORT_BY_MTIME ?
XSET_B_TRUE : XSET_B_FALSE;
xset_set_ob2( set, NULL, set_radio );
set = xset_set_cb( "desk_sort_size", on_popup_desktop_sort_activate,
desktop );
set->b = app_settings.desktop_sort_by == DW_SORT_BY_SIZE ?
XSET_B_TRUE : XSET_B_FALSE;
xset_set_ob2( set, NULL, set_radio );
set = xset_set_cb( "desk_sort_ascend", on_popup_desktop_sort_activate,
desktop );
set->b = app_settings.desktop_sort_type == GTK_SORT_ASCENDING ?
XSET_B_TRUE : XSET_B_FALSE;
xset_set_ob2( set, NULL, NULL );
set_radio = set;
set = xset_set_cb( "desk_sort_descend", on_popup_desktop_sort_activate,
desktop );
set->b = app_settings.desktop_sort_type == GTK_SORT_DESCENDING ?
XSET_B_TRUE : XSET_B_FALSE;
xset_set_ob2( set, NULL, set_radio );
set = xset_get( "desk_icons" );
item = GTK_MENU_ITEM( xset_add_menuitem( desktop, NULL, popup,
accel_group, set ) );
set = xset_set_cb( "desk_pref", on_popup_desktop_pref_activate, desktop );
xset_add_menuitem( desktop, NULL, popup, accel_group, set );
// Desktop|Info
set = xset_get( "sep_desk2" );
xset_add_menuitem( desktop, NULL, popup, accel_group, set );
set = xset_set_cb( "prop_info", on_popup_file_properties_activate, data );
xset_add_menuitem( desktop, NULL, popup, accel_group, set );
}
gtk_widget_show_all( GTK_WIDGET( popup ) );
g_signal_connect( popup, "selection-done",
G_CALLBACK( gtk_widget_destroy ), NULL );
g_signal_connect (popup, "key-press-event",
G_CALLBACK (xset_menu_keypress), NULL );
return popup;
}
void
on_popup_open_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
GList* sel_files = data->sel_files;
if( ! sel_files )
sel_files = g_list_prepend( sel_files, data->info );
ptk_open_files_with_app( data->cwd, sel_files,
NULL, data->browser, TRUE, FALSE ); //MOD
if( sel_files != data->sel_files )
g_list_free( sel_files );
}
void
on_popup_open_with_another_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
char * app = NULL;
VFSMimeType* mime_type;
if ( data->info )
{
mime_type = vfs_file_info_get_mime_type( data->info );
if ( G_LIKELY( ! mime_type ) )
{
mime_type = vfs_mime_type_get_from_type( XDG_MIME_TYPE_UNKNOWN );
}
}
else
{
mime_type = vfs_mime_type_get_from_type( XDG_MIME_TYPE_DIRECTORY );
}
GtkWidget* parent_win;
if ( data->browser )
parent_win = gtk_widget_get_toplevel( GTK_WIDGET( data->browser ) );
else
parent_win = GTK_WIDGET( data->desktop );
app = (char *) ptk_choose_app_for_mime_type( GTK_WINDOW( parent_win ),
mime_type, FALSE );
if ( app )
{
GList* sel_files = data->sel_files;
if( ! sel_files )
sel_files = g_list_prepend( sel_files, data->info );
ptk_open_files_with_app( data->cwd, sel_files,
app, data->browser, FALSE, FALSE ); //MOD
if( sel_files != data->sel_files )
g_list_free( sel_files );
g_free( app );
}
vfs_mime_type_unref( mime_type );
}
void on_popup_open_all( GtkMenuItem *menuitem, PtkFileMenu* data )
{
GList* sel_files;
sel_files = data->sel_files;
if( ! sel_files )
sel_files = g_list_prepend( sel_files, data->info );
ptk_open_files_with_app( data->cwd, sel_files,
NULL, data->browser, FALSE, TRUE );
if( sel_files != data->sel_files )
g_list_free( sel_files );
}
void on_popup_run_app( GtkMenuItem *menuitem, PtkFileMenu* data )
{
VFSAppDesktop * desktop_file;
const char* app = NULL;
GList* sel_files;
desktop_file = ( VFSAppDesktop* ) g_object_get_data( G_OBJECT( menuitem ),
"desktop_file" );
if ( !desktop_file )
return ;
app = vfs_app_desktop_get_name( desktop_file );
sel_files = data->sel_files;
if( ! sel_files )
sel_files = g_list_prepend( sel_files, data->info );
ptk_open_files_with_app( data->cwd, sel_files,
(char *) app, data->browser, FALSE, FALSE ); //MOD
if( sel_files != data->sel_files )
g_list_free( sel_files );
}
enum {
APP_JOB_NONE,
APP_JOB_DEFAULT,
APP_JOB_REMOVE,
APP_JOB_EDIT,
APP_JOB_EDIT_LIST,
APP_JOB_ADD,
APP_JOB_BROWSE,
APP_JOB_BROWSE_SHARED,
APP_JOB_EDIT_TYPE,
APP_JOB_VIEW,
APP_JOB_VIEW_TYPE,
APP_JOB_VIEW_OVER,
APP_JOB_UPDATE,
APP_JOB_BROWSE_MIME,
APP_JOB_BROWSE_MIME_USR,
APP_JOB_HELP,
APP_JOB_USR
};
char* get_shared_desktop_file_location( const char* name )
{
const gchar* const * dirs;
char* ret;
dirs = g_get_system_data_dirs();
for ( ; *dirs; ++dirs )
{
if ( ret = vfs_mime_type_locate_desktop_file( *dirs, name ) )
return ret;
}
return NULL;
}
void app_job( GtkWidget* item, GtkWidget* app_item )
{
char* path;
char* str;
VFSAppDesktop* desktop_file = ( VFSAppDesktop* ) g_object_get_data(
G_OBJECT( app_item ), "desktop_file" );
if ( !( desktop_file && desktop_file->file_name ) )
return;
int job = GPOINTER_TO_INT( g_object_get_data( G_OBJECT(item), "job" ) );
PtkFileMenu* data = (PtkFileMenu*)g_object_get_data( G_OBJECT(item), "data" );
if ( !( data && data->info ) )
return;
VFSMimeType* mime_type = vfs_file_info_get_mime_type( data->info );
if ( !mime_type )
mime_type = vfs_mime_type_get_from_type( XDG_MIME_TYPE_UNKNOWN );
switch ( job ) {
case APP_JOB_DEFAULT:
vfs_mime_type_set_default_action( mime_type, desktop_file->file_name );
break;
case APP_JOB_REMOVE:
// for text files, spacefm displays both the actions for the type
// and the actions for text/plain, so removing an app may appear to not
// work if that app is still associated with text/plain
vfs_mime_type_remove_action( mime_type, desktop_file->file_name );
if ( strcmp( mime_type->type, "text/plain" ) &&
g_str_has_prefix( mime_type->type, "text/" ) )
xset_msg_dialog( data->browser ? GTK_WIDGET( data->browser ) : GTK_WIDGET( data->desktop ), 0, _("Remove Text Type Association"), NULL, 0, _("NOTE: When compiling the list of applications to appear in the Open submenu for a text file, SpaceFM will include applications associated with the MIME type (eg text/html) AND applications associated with text/plain. If you select Remove on an application, it will be removed as an associated application for the MIME type (eg text/html), but will NOT be removed as an associated application for text/plain (unless the MIME type is text/plain). Thus using Remove may not remove the application from the Open submenu for this type, unless you also remove it from text/plain."), NULL, "#designmode-mime-remove" );
break;
case APP_JOB_EDIT:
path = g_build_filename( g_get_user_data_dir(), "applications",
desktop_file->file_name, NULL );
if ( !g_file_test( path, G_FILE_TEST_EXISTS ) )
{
// need to copy
char* share_desktop = vfs_mime_type_locate_desktop_file( NULL,
desktop_file->file_name );
if ( !( share_desktop && strcmp( share_desktop, path ) ) )
{
g_free( share_desktop );
g_free( path );
return;
}
xset_copy_file( share_desktop, path );
g_free( share_desktop );
if ( !g_file_test( path, G_FILE_TEST_EXISTS ) )
{
g_free( path );
return;
}
}
xset_edit( data->browser ? GTK_WIDGET( data->browser )
: GTK_WIDGET( data->desktop ), path, FALSE, FALSE );
g_free( path );
break;
case APP_JOB_VIEW:
path = get_shared_desktop_file_location( desktop_file->file_name );
if ( path )
xset_edit( data->browser ? GTK_WIDGET( data->browser )
: GTK_WIDGET( data->desktop ), path, FALSE, TRUE );
break;
case APP_JOB_EDIT_LIST:
path = g_build_filename( g_get_user_data_dir(), "applications",
"mimeapps.list", NULL );
xset_edit( data->browser ? GTK_WIDGET( data->browser )
: GTK_WIDGET( data->desktop ), path, FALSE, TRUE );
g_free( path );
break;
case APP_JOB_ADD:
path = ptk_choose_app_for_mime_type(
GTK_WINDOW( gtk_widget_get_toplevel( data->browser ?
GTK_WIDGET( data->browser ) :
GTK_WIDGET( data->desktop ) ) ),
mime_type, FALSE );
// ptk_choose_app_for_mime_type returns either a bare command that
// was already set as default, or a (custom or shared) desktop file
if ( path && g_str_has_suffix( path, ".desktop" ) && !strchr( path, '/' )
&& mime_type )
vfs_mime_type_append_action( mime_type->type, path );
g_free( path );
break;
case APP_JOB_BROWSE:
path = g_build_filename( g_get_user_data_dir(), "applications", NULL );
g_mkdir_with_parents( path, 0700 );
if ( data->browser )
ptk_file_browser_emit_open( data->browser, path, PTK_OPEN_NEW_TAB );
break;
case APP_JOB_BROWSE_SHARED:
str = get_shared_desktop_file_location( desktop_file->file_name );
if ( str )
path = g_path_get_dirname( str );
else
path = g_strdup( "/usr/share/applications" );
g_free( str );
if ( data->browser )
ptk_file_browser_emit_open( data->browser, path, PTK_OPEN_NEW_TAB );
break;
case APP_JOB_EDIT_TYPE:
path = g_build_filename( g_get_user_data_dir(), "mime/packages", NULL );
g_mkdir_with_parents( path, 0700 );
g_free( path );
str = replace_string( mime_type->type, "/", "-", FALSE );
path = str;
str = g_strdup_printf( "%s.xml", path );
g_free( path );
path = g_build_filename( g_get_user_data_dir(), "mime/packages", str, NULL );
g_free( str );
if ( !g_file_test( path, G_FILE_TEST_EXISTS ) )
{
// need to create
char* msg = g_strdup_printf( "<?xml version='1.0' encoding='utf-8'?>\n<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'>\n<mime-type type='%s'>\n\n<!-- This file was generated by SpaceFM to allow you to change the name of the\n above mime type and to change the filename or magic patterns that define\n this type.\n \n IMPORTANT: After saving this file, restart SpaceFM. You may need to run:\n update-mime-database ~/.local/share/mime\n\n Delete this file from ~/.local/share/mime/packages/ to revert to default.\n \n To make this definition file apply to all users, copy this file to \n /usr/share/mime/packages/ and: sudo update-mime-database /usr/share/mime\n\n For help editing this file:\n http://library.gnome.org/admin/system-admin-guide/stable/mimetypes-source-xml.html.en\n http://www.freedesktop.org/wiki/Specifications/AddingMIMETutor\n\n Example to define the name of a PNG file (with optional translations):\n\n <comment>Portable Network Graphics file</comment>\n <comment xml:lang=\"en\">Portable Network Graphics file</comment>\n \n Example to detect PNG files by glob pattern:\n\n <glob pattern=\"*.png\"/>\n\n Example to detect PNG files by file contents:\n\n <magic priority=\"50\">\n <match type=\"string\" value=\"\\x89PNG\" offset=\"0\"/> \n </magic>\n-->", mime_type->type );
// build from /usr/share/mime type ?
str = g_strdup_printf( "%s.xml", mime_type->type );
char* usr_path = g_build_filename( "/usr/share/mime", str, NULL );
g_free( str );
char* contents = NULL;
if ( g_file_get_contents ( usr_path, &contents, NULL, NULL ) )
{
char* start = NULL;
if ( str = strstr( contents, "\n<mime-type " ) )
{
if ( str = strstr( str, ">\n" ) )
{
str[1] = '\0';
start = contents;
if ( str = strstr( str + 2, "<!--Created automatically" ) )
{
if ( str = strstr( str, "-->" ) )
start = str + 4;
}
}
}
if ( start )
str = g_strdup_printf( "%s\n\n%s</mime-info>\n", msg, start );
else
str = NULL;
g_free( contents );
contents = str;
}
g_free( usr_path );
if ( !contents )
contents = g_strdup_printf( "%s\n\n<!-- insert your patterns below -->\n\n\n</mime-type>\n</mime-info>\n\n", msg );
g_free( msg );
// write file
FILE* file = fopen( path, "w" );
if ( file )
{
fputs( contents, file );
fclose( file );
}
g_free( contents );
}
if ( g_file_test( path, G_FILE_TEST_EXISTS ) )
{
xset_edit( data->browser ? GTK_WIDGET( data->browser )
: GTK_WIDGET( data->desktop ), path, FALSE, FALSE );
}
g_free( path );
vfs_dir_monitor_mime();
break;
case APP_JOB_VIEW_TYPE:
str = g_strdup_printf( "%s.xml", mime_type->type );
path = g_build_filename( "/usr/share/mime", str, NULL );
g_free( str );
if ( g_file_test( path, G_FILE_TEST_EXISTS ) )
{
xset_edit( data->browser ? GTK_WIDGET( data->browser )
: GTK_WIDGET( data->desktop ), path, FALSE, TRUE );
}
g_free( path );
break;
case APP_JOB_VIEW_OVER:
path = "/usr/share/mime/packages/Overrides.xml";
xset_edit( data->browser ? GTK_WIDGET( data->browser )
: GTK_WIDGET( data->desktop ), path, TRUE, FALSE );
break;
case APP_JOB_BROWSE_MIME_USR:
if ( data->browser )
ptk_file_browser_emit_open( data->browser, "/usr/share/mime/packages",
PTK_OPEN_NEW_TAB );
break;
case APP_JOB_BROWSE_MIME:
path = g_build_filename( g_get_user_data_dir(), "mime/packages", NULL );
g_mkdir_with_parents( path, 0700 );
if ( data->browser )
ptk_file_browser_emit_open( data->browser, path, PTK_OPEN_NEW_TAB );
vfs_dir_monitor_mime();
break;
case APP_JOB_UPDATE:
path = g_strdup_printf( "update-mime-database %s/mime",
g_get_user_data_dir() );
g_spawn_command_line_async( path, NULL );
g_free( path );
path = g_strdup_printf( "update-desktop-database %s/applications",
g_get_user_data_dir() );
g_spawn_command_line_async( path, NULL );
g_free( path );
break;
case APP_JOB_HELP:
xset_show_help( data->browser ? GTK_WIDGET( data->browser ) :
GTK_WIDGET( data->desktop ),
NULL, "#designmode-mime" );
break;
}
if ( mime_type )
vfs_mime_type_unref( mime_type );
}
gboolean app_menu_keypress( GtkWidget* menu, GdkEventKey* event,
PtkFileMenu* data )
{
int job = -1;
XSet* set;
PtkFileMenu* app_data = NULL;
VFSAppDesktop* desktop_file = NULL;
GtkWidget* item = gtk_menu_shell_get_selected_item( GTK_MENU_SHELL( menu ) );
if ( item )
{
// if original menu, desktop_file will be set
desktop_file = ( VFSAppDesktop* ) g_object_get_data(
G_OBJECT( item ), "desktop_file" );
// else if app menu, data will be set
app_data = (PtkFileMenu*)g_object_get_data( G_OBJECT(item), "data" );
if ( !desktop_file && !app_data )
return FALSE;
}
else
return FALSE;
int keymod = ( event->state & ( GDK_SHIFT_MASK | GDK_CONTROL_MASK |
GDK_MOD1_MASK | GDK_SUPER_MASK | GDK_HYPER_MASK | GDK_META_MASK ) );
if ( keymod == 0 )
{
if ( event->keyval == GDK_KEY_F1 )
{
char* help = NULL;
if ( app_data )
{
job = GPOINTER_TO_INT( g_object_get_data( G_OBJECT(item), "job" ) );
switch ( job ) {
case APP_JOB_DEFAULT:
help = "#designmode-mime-set";
break;
case APP_JOB_REMOVE:
help = "#designmode-mime-remove";
break;
case APP_JOB_ADD:
help = "#designmode-mime-add";
break;
case APP_JOB_EDIT:
help = "#designmode-mime-appdesktop";
break;
case APP_JOB_EDIT_LIST:
help = "#designmode-mime-mimeappslist";
break;
case APP_JOB_BROWSE:
help = "#designmode-mime-appdir";
break;
case APP_JOB_EDIT_TYPE:
help = "#designmode-mime-xml";
break;
case APP_JOB_BROWSE_MIME:
help = "#designmode-mime-mimedir";
break;
case APP_JOB_USR:
help = "#designmode-mime-usr";
break;
case APP_JOB_BROWSE_SHARED:
case APP_JOB_VIEW:
case APP_JOB_VIEW_TYPE:
case APP_JOB_VIEW_OVER:
case APP_JOB_BROWSE_MIME_USR:
help = "#designmode-mime-usr";
break;
}
}
if ( !help )
help = "#designmode-mime";
gtk_menu_shell_deactivate( GTK_MENU_SHELL( menu ) );
xset_show_help( NULL, NULL, help );
return TRUE;
}
else if ( desktop_file && event->keyval == GDK_KEY_F2 )
{
show_app_menu( menu, item, data, 0, event->time );
return TRUE;
}
else if ( event->keyval == GDK_KEY_F4 )
job = APP_JOB_EDIT;
else if ( event->keyval == GDK_KEY_Delete )
job = APP_JOB_REMOVE;
else if ( event->keyval == GDK_KEY_Insert )
job = APP_JOB_ADD;
}
if ( desktop_file && job != -1 )
{
gtk_menu_shell_deactivate( GTK_MENU_SHELL( menu ) );
g_object_set_data( G_OBJECT( item ), "job", GINT_TO_POINTER( job ) );
g_object_set_data( G_OBJECT( item ), "data", data );
app_job( item, item );
return TRUE;
}
return FALSE;
}
void on_app_menu_hide(GtkWidget *widget, GtkWidget* app_menu )
{
gtk_widget_set_sensitive( widget, TRUE );
gtk_menu_shell_deactivate( GTK_MENU_SHELL( app_menu ) );
}
GtkWidget* app_menu_additem( GtkWidget* menu, char* label, gchar* stock_icon,
int job, GtkWidget* app_item, PtkFileMenu* data )
{
GtkWidget* item;
if ( stock_icon )
{
if ( !strcmp( stock_icon, "@check" ) )
item = gtk_check_menu_item_new_with_mnemonic( label );
else
{
item = gtk_image_menu_item_new_with_mnemonic( label );
GtkWidget* image = gtk_image_new_from_stock( stock_icon,
GTK_ICON_SIZE_MENU );
if ( image )
gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM( item ),
image );
}
}
else
item = gtk_menu_item_new_with_mnemonic( label );
g_object_set_data( G_OBJECT(item), "job", GINT_TO_POINTER( job ) );
g_object_set_data( G_OBJECT(item), "data", data );
gtk_container_add ( GTK_CONTAINER ( menu ), item );
g_signal_connect( item, "activate", G_CALLBACK( app_job ), app_item );
return item;
}
static void show_app_menu( GtkWidget* menu, GtkWidget* app_item, PtkFileMenu* data,
guint button, guint32 time )
{
GtkWidget* newitem;
GtkWidget* submenu;
char* str;
char* str2;
char* path;
char* icon;
const char* type;
if ( !( data && data->info ) )
return;
VFSMimeType* mime_type = vfs_file_info_get_mime_type( data->info );
if ( mime_type )
{
type = vfs_mime_type_get_type( mime_type );
vfs_mime_type_unref( mime_type );
}
else
type = "unknown";
VFSAppDesktop* desktop_file = ( VFSAppDesktop* ) g_object_get_data(
G_OBJECT( app_item ), "desktop_file" );
if ( !desktop_file )
return ;
GtkWidget* app_menu = gtk_menu_new();
GtkAccelGroup* accel_group = gtk_accel_group_new();
// Set Default
newitem = app_menu_additem( app_menu, _("_Set As Default"),
GTK_STOCK_SAVE, APP_JOB_DEFAULT, app_item, data );
//gtk_widget_add_accelerator( newitem, "activate", accel_group,
// GDK_k, GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);
// Remove
newitem = app_menu_additem( app_menu, _("_Remove"),
GTK_STOCK_DELETE, APP_JOB_REMOVE, app_item, data );
// Add
newitem = app_menu_additem( app_menu, _("_Add..."),
GTK_STOCK_ADD, APP_JOB_ADD, app_item, data );
// Separator
gtk_container_add ( GTK_CONTAINER ( app_menu ), gtk_separator_menu_item_new() );
// *.desktop (missing)
if ( desktop_file->file_name )
{
path = g_build_filename( g_get_user_data_dir(), "applications",
desktop_file->file_name, NULL );
if ( g_file_test( path, G_FILE_TEST_EXISTS ) )
{
str = replace_string( desktop_file->file_name, ".desktop", "._desktop",
FALSE );
icon = GTK_STOCK_EDIT;
}
else
{
str2 = replace_string( desktop_file->file_name, ".desktop", "._desktop",
FALSE );
str = g_strdup_printf( "%s (*%s)", str2, _("copy") );
g_free( str2 );
icon = GTK_STOCK_NEW;
}
newitem = app_menu_additem( app_menu, str,
icon, APP_JOB_EDIT, app_item, data );
g_free( str );
g_free( path );
}
// mimeapps.list
newitem = app_menu_additem( app_menu, "_mimeapps.list",
GTK_STOCK_EDIT, APP_JOB_EDIT_LIST, app_item, data );
// applications/
newitem = app_menu_additem( app_menu, "appli_cations/",
GTK_STOCK_DIRECTORY, APP_JOB_BROWSE, app_item, data );
gtk_widget_set_sensitive( GTK_WIDGET( newitem ), !!data->browser );
// Separator
gtk_container_add ( GTK_CONTAINER ( app_menu ), gtk_separator_menu_item_new() );
// *.xml (missing)
str = replace_string( type, "/", "-", FALSE );
path = str;
str = g_strdup_printf( "%s.xml", path );
g_free( path );
path = g_build_filename( g_get_user_data_dir(), "mime/packages", str, NULL );
if ( path && g_file_test( path, G_FILE_TEST_EXISTS ) )
{
g_free( path );
str = replace_string( type, "/", "-", FALSE );
path = str;
str = g_strdup_printf( "%s._xml", path );
g_free( path );
icon = GTK_STOCK_EDIT;
}
else
{
g_free( path );
str = replace_string( type, "/", "-", FALSE );
path = str;
str = g_strdup_printf( "%s._xml (*%s)", path, _("new") );
g_free( path );
icon = GTK_STOCK_NEW;
}
newitem = app_menu_additem( app_menu, str,
icon, APP_JOB_EDIT_TYPE, app_item, data );
// mime/packages/
newitem = app_menu_additem( app_menu, "mime/pac_kages/",
GTK_STOCK_DIRECTORY, APP_JOB_BROWSE_MIME, app_item, data );
gtk_widget_set_sensitive( GTK_WIDGET( newitem ), !!data->browser );
// Run update-mime-database (now done automatically)
//str = g_strdup_printf( "%s update-mime-database", _("Ru_n") );
//newitem = app_menu_additem( app_menu, str,
// GTK_STOCK_EXECUTE, APP_JOB_UPDATE, app_item, data );
//g_free( str );
// Separator
gtk_container_add ( GTK_CONTAINER ( app_menu ), gtk_separator_menu_item_new() );
// /usr submenu
newitem = gtk_image_menu_item_new_with_mnemonic( "/_usr" );
submenu = gtk_menu_new();
gtk_menu_item_set_submenu( GTK_MENU_ITEM( newitem ), submenu );
gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM( newitem ),
gtk_image_new_from_stock( GTK_STOCK_DIRECTORY, GTK_ICON_SIZE_MENU ) );
gtk_container_add ( GTK_CONTAINER ( app_menu ), newitem );
g_object_set_data( G_OBJECT( newitem ), "job", GINT_TO_POINTER( APP_JOB_USR ) );
g_object_set_data( G_OBJECT( newitem ), "data", data );
g_signal_connect( submenu, "key_press_event",
G_CALLBACK( app_menu_keypress ), data );
// View /usr .desktop
if ( desktop_file->file_name )
{
newitem = app_menu_additem( submenu, desktop_file->file_name,
GTK_STOCK_FILE, APP_JOB_VIEW, app_item, data );
path = get_shared_desktop_file_location( desktop_file->file_name );
gtk_widget_set_sensitive( GTK_WIDGET( newitem ), !!path );
g_free( path );
}
// /usr applications/
newitem = app_menu_additem( submenu, "appli_cations/",
GTK_STOCK_DIRECTORY, APP_JOB_BROWSE_SHARED,
app_item, data );
gtk_widget_set_sensitive( GTK_WIDGET( newitem ), !!data->browser );
// Separator
gtk_container_add ( GTK_CONTAINER ( submenu ), gtk_separator_menu_item_new() );
// /usr *.xml
str = g_strdup_printf( "%s.xml", type );
path = g_build_filename( "/usr/share/mime", str, NULL );
g_free( str );
str = g_strdup_printf( "%s._xml", type );
newitem = app_menu_additem( submenu, str,
GTK_STOCK_FILE, APP_JOB_VIEW_TYPE, app_item,
data );
g_free( str );
gtk_widget_set_sensitive( GTK_WIDGET( newitem ),
g_file_test( path, G_FILE_TEST_EXISTS ) );
g_free( path );
// /usr *Overrides.xml
newitem = app_menu_additem( submenu, "_Overrides.xml",
GTK_STOCK_EDIT, APP_JOB_VIEW_OVER, app_item,
data );
gtk_widget_set_sensitive( GTK_WIDGET( newitem ),
g_file_test( "/usr/share/mime/packages/Overrides.xml",
G_FILE_TEST_EXISTS ) );
// mime/packages/
newitem = app_menu_additem( submenu, "mime/pac_kages/",
GTK_STOCK_DIRECTORY, APP_JOB_BROWSE_MIME_USR, app_item, data );
gtk_widget_set_sensitive( GTK_WIDGET( newitem ), !!data->browser &&
g_file_test( "/usr/share/mime/packages", G_FILE_TEST_IS_DIR ) );
// Separator
gtk_container_add ( GTK_CONTAINER ( app_menu ), gtk_separator_menu_item_new() );
// Help
newitem = app_menu_additem( app_menu, "_Help",
GTK_STOCK_HELP, APP_JOB_HELP,
app_item, data );
// show menu
gtk_widget_show_all( GTK_WIDGET( app_menu ) );
gtk_menu_popup( GTK_MENU( app_menu ), GTK_WIDGET( menu ), app_item, NULL, NULL,
button, time );
gtk_widget_set_sensitive( GTK_WIDGET( menu ), FALSE );
g_signal_connect( menu, "hide", G_CALLBACK( on_app_menu_hide ), app_menu );
g_signal_connect( app_menu, "selection-done",
G_CALLBACK( gtk_widget_destroy ), NULL );
g_signal_connect( app_menu, "key_press_event",
G_CALLBACK( app_menu_keypress ), data );
}
gboolean on_app_button_press( GtkWidget* item, GdkEventButton* event,
PtkFileMenu* data )
{
int job = -1;
GtkWidget* menu = (GtkWidget*)g_object_get_data( G_OBJECT(item), "menu" );
int keymod = ( event->state & ( GDK_SHIFT_MASK | GDK_CONTROL_MASK |
GDK_MOD1_MASK | GDK_SUPER_MASK | GDK_HYPER_MASK | GDK_META_MASK ) );
if ( event->type == GDK_BUTTON_RELEASE )
{
if ( event->button == 1 && keymod == 0 )
{
// user released left button - due to an apparent gtk bug, activate
// doesn't always fire on this event so handle it ourselves
// see also settings.c xset_design_cb()
// test: gtk2 Crux theme with touchpad on Edit|Copy To|Location
// https://github.com/IgnorantGuru/spacefm/issues/31
// https://github.com/IgnorantGuru/spacefm/issues/228
if ( menu )
gtk_menu_shell_deactivate( GTK_MENU_SHELL( menu ) );
gtk_menu_item_activate( GTK_MENU_ITEM( item ) );
return TRUE;
}
return FALSE;
}
else if ( event->type != GDK_BUTTON_PRESS )
return FALSE;
if ( event->button == 1 || event->button == 3 )
{
// left or right click
if ( keymod == 0 )
{
// no modifier
if ( event->button == 3 )
{
// right
show_app_menu( menu, item, data, event->button, event->time );
return TRUE;
}
}
/*
else if ( keymod == GDK_CONTROL_MASK )
{
// ctrl
job = XSET_JOB_COPY;
}
else if ( keymod == GDK_MOD1_MASK )
{
// alt
job = XSET_JOB_CUT;
}
else if ( keymod == GDK_SHIFT_MASK )
{
// shift
job = XSET_JOB_PASTE;
}
else if ( keymod == ( GDK_CONTROL_MASK | GDK_SHIFT_MASK ) )
{
// ctrl + shift
job = XSET_JOB_COMMAND;
}
*/
}
else if ( event->button == 2 )
{
// middle click
if ( keymod == 0 )
{
// no modifier
show_app_menu( menu, item, data, event->button, event->time );
return TRUE;
}
/*
else if ( keymod == GDK_CONTROL_MASK )
{
// ctrl
job = XSET_JOB_KEY;
}
else if ( keymod == GDK_MOD1_MASK )
{
// alt
job = XSET_JOB_HELP;
}
else if ( keymod == GDK_SHIFT_MASK )
{
// shift
job = XSET_JOB_ICON;
}
else if ( keymod == ( GDK_CONTROL_MASK | GDK_SHIFT_MASK ) )
{
// ctrl + shift
job = XSET_JOB_REMOVE;
}
else if ( keymod == ( GDK_CONTROL_MASK | GDK_MOD1_MASK ) )
{
// ctrl + alt
job = XSET_JOB_CONTEXT;
}
*/
}
/*
if ( job != -1 )
{
if ( xset_job_is_valid( set, job ) )
{
if ( menu )
gtk_menu_shell_deactivate( GTK_MENU_SHELL( menu ) );
g_object_set_data( G_OBJECT( item ), "job", GINT_TO_POINTER( job ) );
xset_design_job( item, set );
}
else
xset_design_show_menu( menu, set, event->button, event->time );
return TRUE;
}
*/
return FALSE; // TRUE won't stop activate on button-press (will on release)
}
void on_popup_open_in_new_tab_activate( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
GList * sel;
VFSFileInfo* file;
char* full_path;
if ( data->sel_files )
{
for ( sel = data->sel_files; sel; sel = sel->next )
{
file = ( VFSFileInfo* ) sel->data;
full_path = g_build_filename( data->cwd,
vfs_file_info_get_name( file ), NULL );
if ( data->browser && g_file_test( full_path, G_FILE_TEST_IS_DIR ) )
{
ptk_file_browser_emit_open( data->browser, full_path, PTK_OPEN_NEW_TAB );
}
g_free( full_path );
}
}
else if ( data->browser )
{
ptk_file_browser_emit_open( data->browser, data->file_path, PTK_OPEN_NEW_TAB );
}
}
void on_popup_open_in_new_tab_here( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
if ( data->browser && data->cwd && g_file_test( data->cwd, G_FILE_TEST_IS_DIR ) )
ptk_file_browser_emit_open( data->browser, data->cwd, PTK_OPEN_NEW_TAB );
}
/*
void on_popup_open_in_terminal_activate( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
ptk_file_browser_open_terminal( menuitem, data->browser );
}
void on_popup_run_command( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
ptk_file_browser_run_command( data->browser ); //MOD Ctrl-r
}
void on_popup_open_files_activate( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
ptk_file_browser_open_files( data->browser, NULL ); //MOD F4
}
void on_popup_user_6( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
ptk_file_browser_open_files( data->browser, "/F6" ); //MOD
}
void on_popup_user_7( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
ptk_file_browser_open_files( data->browser, "/F7" ); //MOD
}
void on_popup_user_8( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
ptk_file_browser_open_files( data->browser, "/F8" ); //MOD
}
void on_popup_user_9( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
ptk_file_browser_open_files( data->browser, "/F9" ); //MOD
}
void on_popup_open_in_new_win_activate( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
GList * sel;
GList* sel_files = data->sel_files;
VFSFileInfo* file;
char* full_path;
if ( sel_files )
{
for ( sel = sel_files; sel; sel = sel->next )
{
file = ( VFSFileInfo* ) sel->data;
full_path = g_build_filename( data->cwd,
vfs_file_info_get_name( file ), NULL );
if ( g_file_test( full_path, G_FILE_TEST_IS_DIR ) )
{
ptk_file_browser_emit_open( data->browser, full_path, PTK_OPEN_NEW_WINDOW );
}
g_free( full_path );
}
}
else
{
ptk_file_browser_emit_open( data->browser, data->file_path, PTK_OPEN_NEW_WINDOW );
}
}
*/
void
on_popup_cut_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
if ( data->sel_files )
ptk_clipboard_cut_or_copy_files( data->cwd,
data->sel_files, FALSE );
}
void
on_popup_copy_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
if ( data->sel_files )
ptk_clipboard_cut_or_copy_files( data->cwd,
data->sel_files, TRUE );
}
void
on_popup_paste_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
/*
if ( data->sel_files )
{
char* dest_dir;
GtkWidget* parent;
parent = (GtkWidget*)get_toplevel_win( data );
dest_dir = g_build_filename( data->cwd,
vfs_file_info_get_name( data->info ), NULL );
if( ! g_file_test( dest_dir, G_FILE_TEST_IS_DIR ) )
{
g_free( dest_dir );
dest_dir = NULL;
}
ptk_clipboard_paste_files( GTK_WINDOW( parent ), dest_dir ? dest_dir : data->cwd,
data->browser->task_view );
}
*/
if ( data->browser )
{
GtkWidget* parent_win = gtk_widget_get_toplevel(
GTK_WIDGET( data->browser ) );
ptk_clipboard_paste_files( GTK_WINDOW( parent_win ), data->cwd,
GTK_TREE_VIEW( data->browser->task_view ) );
}
else if ( data->desktop )
{
ptk_clipboard_paste_files( GTK_WINDOW( data->desktop ), data->cwd, NULL );
}
}
void
on_popup_paste_link_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data ) //MOD added
{
if ( data->browser )
ptk_file_browser_paste_link( data->browser );
else if ( data->desktop )
ptk_clipboard_paste_links(
GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( data->desktop ) ) ),
data->cwd, NULL );
}
void
on_popup_paste_target_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data ) //MOD added
{
if ( data->browser )
ptk_file_browser_paste_target( data->browser );
else if ( data->desktop )
ptk_clipboard_paste_targets(
GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( data->desktop ) ) ),
data->cwd,
NULL );
}
void
on_popup_copy_text_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data ) //MOD added
{
ptk_clipboard_copy_as_text( data->cwd, data->sel_files );
}
void
on_popup_copy_name_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data ) //MOD added
{
ptk_clipboard_copy_name( data->cwd, data->sel_files );
}
void
on_popup_copy_parent_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data ) //MOD added
{
if ( data->cwd )
ptk_clipboard_copy_text( data->cwd );
}
void
on_popup_paste_as_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data ) //sfm added
{
ptk_file_misc_paste_as( data->desktop, data->browser, data->cwd );
}
void
on_popup_delete_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
if ( data->sel_files )
{
if ( data->browser )
{
GtkWidget* parent_win = gtk_widget_get_toplevel(
GTK_WIDGET( data->browser ) );
ptk_delete_files( GTK_WINDOW( parent_win ),
data->cwd,
data->sel_files,
GTK_TREE_VIEW( data->browser->task_view ) );
}
else if ( data->desktop )
{
ptk_delete_files( GTK_WINDOW( data->desktop ),
data->cwd,
data->sel_files, NULL );
}
}
}
void
on_popup_rename_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
if ( data->browser )
ptk_file_browser_rename_selected_files( data->browser, data->sel_files,
data->cwd );
#ifdef DESKTOP_INTEGRATION
else if ( data->desktop && data->sel_files )
{
desktop_window_rename_selected_files( data->desktop, data->sel_files,
data->cwd );
}
#endif
}
void on_popup_compress_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
if ( data->browser )
ptk_file_archiver_create( data->browser, data->sel_files, data->cwd );
}
void on_popup_extract_to_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
ptk_file_archiver_extract( data->browser, data->sel_files, data->cwd, NULL );
}
void on_popup_extract_here_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
ptk_file_archiver_extract( data->browser, data->sel_files,
data->cwd, data->cwd );
}
void on_popup_extract_list_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
ptk_file_archiver_extract( data->browser, data->sel_files,
data->cwd, "////LIST" );
}
void on_autoopen_create_cb( gpointer task, AutoOpenCreate* ao )
{
VFSFileInfo* file;
if ( !ao )
return;
if ( ao->path && GTK_IS_WIDGET( ao->file_browser )
&& g_file_test( ao->path, G_FILE_TEST_EXISTS ) )
{
char* cwd = g_path_get_dirname( ao->path );
// select file
if ( !g_strcmp0( cwd, ptk_file_browser_get_cwd( ao->file_browser ) ) )
{
file = vfs_file_info_new();
vfs_file_info_get( file, ao->path, NULL );
vfs_dir_emit_file_created( ao->file_browser->dir,
vfs_file_info_get_name( file ), TRUE );
vfs_file_info_unref( file );
vfs_dir_flush_notify_cache();
ptk_file_browser_select_file( ao->file_browser, ao->path );
}
// open file
if ( ao->open_file )
{
if ( g_file_test( ao->path, G_FILE_TEST_IS_DIR ) )
{
ptk_file_browser_chdir( ao->file_browser, ao->path,
PTK_FB_CHDIR_ADD_HISTORY );
ao->path = NULL;
}
else
{
file = vfs_file_info_new();
vfs_file_info_get( file, ao->path, NULL );
GList* sel_files = NULL;
sel_files = g_list_prepend( sel_files, file );
ptk_open_files_with_app( cwd, sel_files,
NULL, ao->file_browser, FALSE, TRUE );
vfs_file_info_unref( file );
g_list_free( sel_files );
}
}
g_free( cwd );
}
g_free( ao->path );
g_slice_free( AutoOpenCreate, ao );
}
static void
create_new_file( PtkFileMenu* data, int create_new )
{
char* cwd;
AutoOpenCreate* ao = NULL;
if ( data->cwd )
{
if ( data->browser )
{
ao = g_slice_new0( AutoOpenCreate );
ao->path = NULL;
ao->file_browser = data->browser;
ao->callback = (GFunc)on_autoopen_create_cb;
ao->open_file = FALSE;
}
else if ( data->desktop )
{
ao = g_slice_new0( AutoOpenCreate );
ao->path = NULL;
ao->file_browser = (PtkFileBrowser*)data->desktop; // hack
#ifdef DESKTOP_INTEGRATION
ao->callback = (GFunc)desktop_window_on_autoopen_cb;
#endif
ao->open_file = FALSE;
}
int result = ptk_rename_file( data->desktop, data->browser, data->cwd,
data->sel_files ? (VFSFileInfo*)data->sel_files->data : NULL,
NULL, FALSE, create_new, ao );
if ( result == 0 )
{
ao->file_browser = NULL;
g_free( ao->path );
ao->path = NULL;
g_slice_free( AutoOpenCreate, ao );
ao = NULL;
}
}
}
void
on_popup_new_folder_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
create_new_file( data, 2 );
}
void
on_popup_new_text_file_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
create_new_file( data, 1 );
}
void
on_popup_new_link_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
create_new_file( data, 3 );
}
void
on_popup_file_properties_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
GtkWidget* parent_win;
if ( data->browser )
parent_win = gtk_widget_get_toplevel( GTK_WIDGET( data->browser ) );
else
parent_win = GTK_WIDGET( data->desktop );
ptk_show_file_properties( GTK_WINDOW( parent_win ),
data->cwd,
data->sel_files, 0 );
}
void
on_popup_file_permissions_activate ( GtkMenuItem *menuitem,
PtkFileMenu* data )
{
GtkWidget* parent_win;
if ( data->browser )
parent_win = gtk_widget_get_toplevel( GTK_WIDGET( data->browser ) );
else
parent_win = GTK_WIDGET( data->desktop );
ptk_show_file_properties( GTK_WINDOW( parent_win ),
data->cwd,
data->sel_files, 1 );
}
void
on_popup_canon ( GtkMenuItem *menuitem, PtkFileMenu* data )
{
if ( !data->browser )
return;
ptk_file_browser_canon( data->browser, data->file_path ? data->file_path : data->cwd );
}
void ptk_file_menu_action( DesktopWindow* desktop, PtkFileBrowser* browser,
char* setname )
{
const char * cwd;
char* file_path = NULL;
VFSFileInfo* info;
GList* sel_files = NULL;
int i;
char* xname;
if ( ( !browser && !desktop ) || !setname )
return;
XSet* set = xset_get( setname );
// setup data
if ( browser )
{
cwd = ptk_file_browser_get_cwd( browser );
sel_files = ptk_file_browser_get_selected_files( browser );
}
else
{
cwd = vfs_get_desktop_dir();
#ifdef DESKTOP_INTEGRATION
sel_files = desktop_window_get_selected_files( desktop );
#endif
}
if( !sel_files )
info = NULL;
else
{
info = vfs_file_info_ref( (VFSFileInfo*)sel_files->data );
file_path = g_build_filename( cwd, vfs_file_info_get_name( info ), NULL );
}
PtkFileMenu* data = g_slice_new0( PtkFileMenu );
data->cwd = g_strdup( cwd );
data->browser = browser;
data->desktop = desktop;
data->file_path = file_path;
if ( info )
data->info = vfs_file_info_ref( info );
else
data->info = NULL;
data->sel_files = sel_files;
data->accel_group = NULL;
// action
if ( g_str_has_prefix( set->name, "open_" ) )
{
xname = set->name + 5;
if ( !strcmp( xname, "edit" ) )
xset_edit( GTK_WIDGET( data->browser ), data->file_path, FALSE, TRUE );
else if ( !strcmp( xname, "edit_root" ) )
xset_edit( GTK_WIDGET( data->browser ), data->file_path, TRUE, FALSE );
else if ( !strcmp( xname, "other" ) )
on_popup_open_with_another_activate( NULL, data );
else if ( !strcmp( xname, "execute" ) )
on_popup_open_activate( NULL, data );
else if ( !strcmp( xname, "all" ) )
on_popup_open_all( NULL, data );
}
else if ( g_str_has_prefix( set->name, "arc_" ) )
{
xname = set->name + 4;
if ( !strcmp( xname, "extract" ) )
on_popup_extract_here_activate( NULL, data );
else if ( !strcmp( xname, "extractto" ) )
on_popup_extract_to_activate( NULL, data );
else if ( !strcmp( xname, "extract" ) )
on_popup_extract_list_activate( NULL, data );
}
else if ( g_str_has_prefix( set->name, "iso_" ) )
{
xname = set->name + 4;
if ( !strcmp( xname, "mount" ) )
on_popup_mount_iso( NULL, data );
}
else if ( g_str_has_prefix( set->name, "new_" ) )
{
xname = set->name + 4;
if ( !strcmp( xname, "file" ) )
on_popup_new_text_file_activate( NULL, data );
else if ( !strcmp( xname, "folder" ) )
on_popup_new_folder_activate( NULL, data );
else if ( !strcmp( xname, "link" ) )
on_popup_new_link_activate( NULL, data );
else if ( !strcmp( xname, "bookmark" ) )
on_add_bookmark( NULL, data );
else if ( !strcmp( xname, "archive" ) )
{
if ( browser )
on_popup_compress_activate( NULL, data );
}
}
else if ( !strcmp( set->name, "prop_info" ) )
on_popup_file_properties_activate( NULL, data );
else if ( !strcmp( set->name, "prop_perm" ) )
on_popup_file_permissions_activate( NULL, data );
else if ( g_str_has_prefix( set->name, "edit_" ) )
{
xname = set->name + 5;
if ( !strcmp( xname, "cut" ) )
on_popup_cut_activate( NULL, data );
else if ( !strcmp( xname, "copy" ) )
on_popup_copy_activate( NULL, data );
else if ( !strcmp( xname, "paste" ) )
on_popup_paste_activate( NULL, data );
else if ( !strcmp( xname, "rename" ) )
on_popup_rename_activate( NULL, data );
else if ( !strcmp( xname, "delete" ) )
on_popup_delete_activate( NULL, data );
else if ( !strcmp( xname, "hide" ) )
on_hide_file( NULL, data );
else if ( !strcmp( xname, "canon" ) )
{
if ( browser )
on_popup_canon( NULL, data );
}
}
else if ( !strcmp( set->name, "copy_name" ) )
on_popup_copy_name_activate( NULL, data );
else if ( !strcmp( set->name, "copy_path" ) )
on_popup_copy_text_activate( NULL, data );
else if ( !strcmp( set->name, "copy_parent" ) )
on_popup_copy_parent_activate( NULL, data );
else if ( g_str_has_prefix( set->name, "copy_loc" )
|| g_str_has_prefix( set->name, "copy_tab_" )
|| g_str_has_prefix( set->name, "copy_panel_" )
|| g_str_has_prefix( set->name, "move_loc" )
|| g_str_has_prefix( set->name, "move_tab_" )
|| g_str_has_prefix( set->name, "move_panel_" ) )
on_copycmd( NULL, data, set );
else if ( g_str_has_prefix( set->name, "root_" ) )
{
xname = set->name + 5;
if ( !strcmp( xname, "copy_loc" )
|| !strcmp( xname, "move2" )
|| !strcmp( xname, "delete" ) )
on_popup_rootcmd_activate( NULL, data, set );
}
else if ( browser )
{
// browser only
if ( g_str_has_prefix( set->name, "open_in_panel" ) )
{
xname = set->name + 13;
if ( !strcmp( xname, "prev" ) )
i = -1;
else if ( !strcmp( xname, "next" ) )
i = -2;
else
i = atoi( xname );
main_window_open_in_panel( data->browser, i, data->file_path );
}
else if ( g_str_has_prefix( set->name, "opentab_" ) )
{
xname = set->name + 8;
if ( !strcmp( xname, "new" ) )
on_popup_open_in_new_tab_activate( NULL, data );
else
{
if ( !strcmp( xname, "prev" ) )
i = -1;
else if ( !strcmp( xname, "next" ) )
i = -2;
else
i = atoi( xname );
ptk_file_browser_open_in_tab( data->browser, i, data->file_path );
}
}
else if ( !strcmp( set->name, "tab_new" ) )
on_shortcut_new_tab_activate( NULL, browser );
else if ( !strcmp( set->name, "tab_new_here" ) )
on_popup_open_in_new_tab_here( NULL, data );
}
else
{
// desktop only
}
ptk_file_menu_free( data );
}
|
189 | ./spacefm/src/ptk/ptk-file-icon-renderer.c | /*
* C Implementation: ptkfileiconrenderer
*
* Description: PtkFileIconRenderer is used to render file icons
*
*
* Author: Hong Jen Yee (PCMan) <pcman.tw (AT) gmail.com>, (C) 2006
*
* Copyright: See COPYING file that comes with this distribution
*
* Part of this class is taken from GtkCellRendererPixbuf written by
* Red Hat, Inc., Jonathan Blandford <jrb@redhat.com>
*
*/
#include "ptk-file-icon-renderer.h"
static void
ptk_file_icon_renderer_init ( PtkFileIconRenderer *renderer );
static void
ptk_file_icon_renderer_class_init ( PtkFileIconRendererClass *klass );
static void
ptk_file_icon_renderer_get_property ( GObject *object,
guint param_id,
GValue *value,
GParamSpec *pspec );
static void
ptk_file_icon_renderer_set_property ( GObject *object,
guint param_id,
const GValue *value,
GParamSpec *pspec );
static void
ptk_file_icon_renderer_finalize ( GObject *gobject );
static void
ptk_file_icon_renderer_get_size ( GtkCellRenderer *cell,
GtkWidget *widget,
#if GTK_CHECK_VERSION (3, 0, 0)
const GdkRectangle *cell_area,
#else
GdkRectangle *cell_area,
#endif
gint *x_offset,
gint *y_offset,
gint *width,
gint *height );
#if GTK_CHECK_VERSION (3, 0, 0)
static void
ptk_file_icon_renderer_render ( GtkCellRenderer *cell,
cairo_t *cr,
GtkWidget *widget,
const GdkRectangle *background_area,
const GdkRectangle *cell_area,
GtkCellRendererState flags );
#else
static void
ptk_file_icon_renderer_render ( GtkCellRenderer *cell,
GdkWindow *window,
GtkWidget *widget,
GdkRectangle *background_area,
GdkRectangle *cell_area,
GdkRectangle *expose_area,
guint flags );
#endif
enum
{
PROP_INFO = 1,
PROP_FLAGS,
PROP_FOLLOW_STATE
};
static gpointer parent_class;
static GdkPixbuf* link_icon = NULL;
/* GdkPixbuf RGBA C-Source image dump */
#ifdef __SUNPRO_C
#pragma align 4 (link_icon_data)
#endif
#ifdef __GNUC__
static const guint8 link_icon_data[] __attribute__ ((__aligned__ (4))) =
#else
static const guint8 link_icon_data[] =
#endif
{ ""
/* Pixbuf magic (0x47646b50) */
"GdkP"
/* length: header (24) + pixel_data (400) */
"\0\0\1\250"
/* pixdata_type (0x1010002) */
"\1\1\0\2"
/* rowstride (40) */
"\0\0\0("
/* width (10) */
"\0\0\0\12"
/* height (10) */
"\0\0\0\12"
/* pixel_data: */
"\200\200\200\377\200\200\200\377\200\200\200\377\200\200\200\377\200"
"\200\200\377\200\200\200\377\200\200\200\377\200\200\200\377\200\200"
"\200\377\0\0\0\377\200\200\200\377\377\377\377\377\377\377\377\377\377"
"\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377"
"\377\377\377\377\377\377\0\0\0\377\200\200\200\377\377\377\377\377\0"
"\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\377\377\377\377\377"
"\377\377\377\0\0\0\377\200\200\200\377\377\377\377\377\0\0\0\377\0\0"
"\0\377\0\0\0\377\0\0\0\377\377\377\377\377\377\377\377\377\377\377\377"
"\377\0\0\0\377\200\200\200\377\377\377\377\377\0\0\0\377\0\0\0\377\0"
"\0\0\377\0\0\0\377\0\0\0\377\377\377\377\377\377\377\377\377\0\0\0\377"
"\200\200\200\377\377\377\377\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0"
"\377\0\0\0\377\0\0\0\377\377\377\377\377\0\0\0\377\200\200\200\377\377"
"\377\377\377\0\0\0\377\377\377\377\377\377\377\377\377\0\0\0\377\0\0"
"\0\377\0\0\0\377\377\377\377\377\0\0\0\377\200\200\200\377\377\377\377"
"\377\377\377\377\377\377\377\377\377\377\377\377\377\0\0\0\377\0\0\0"
"\377\0\0\0\377\377\377\377\377\0\0\0\377\200\200\200\377\377\377\377"
"\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377"
"\377\377\377\377\377\377\377\377\377\377\377\377\0\0\0\377\0\0\0\377"
"\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377"
"\0\0\0\377\0\0\0\377"
};
/***************************************************************************
*
* ptk_file_icon_renderer_get_type: here we register our type with
* the GObject type system if we
* haven't done so yet. Everything
* else is done in the callbacks.
*
***************************************************************************/
GType
ptk_file_icon_renderer_get_type ( void )
{
static GType renderer_type = 0;
if ( G_UNLIKELY( !renderer_type ) )
{
static const GTypeInfo renderer_info =
{
sizeof ( PtkFileIconRendererClass ),
NULL, /* base_init */
NULL, /* base_finalize */
( GClassInitFunc ) ptk_file_icon_renderer_class_init,
NULL, /* class_finalize */
NULL, /* class_data */
sizeof ( PtkFileIconRenderer ),
0, /* n_preallocs */
( GInstanceInitFunc ) ptk_file_icon_renderer_init,
};
/* Derive from GtkCellRendererPixbuf */
renderer_type = g_type_register_static ( GTK_TYPE_CELL_RENDERER_PIXBUF,
"PtkFileIconRenderer",
&renderer_info,
0 );
}
return renderer_type;
}
/***************************************************************************
*
* ptk_file_icon_renderer_init: set some default properties of the
* parent (GtkCellRendererPixbuf).
*
***************************************************************************/
static void
ptk_file_icon_renderer_init ( PtkFileIconRenderer *renderer )
{
if ( !link_icon )
{
link_icon = gdk_pixbuf_new_from_inline(
sizeof(link_icon_data),
link_icon_data,
FALSE, NULL );
g_object_add_weak_pointer( G_OBJECT(link_icon), (gpointer)&link_icon );
}
else
g_object_ref( (link_icon) );
}
/***************************************************************************
*
* ptk_file_icon_renderer_class_init:
*
***************************************************************************/
static void
ptk_file_icon_renderer_class_init ( PtkFileIconRendererClass *klass )
{
GtkCellRendererClass * parent_renderer_class = GTK_CELL_RENDERER_CLASS( klass );
GObjectClass *object_class = G_OBJECT_CLASS( klass );
parent_class = g_type_class_peek_parent ( klass );
object_class->finalize = ptk_file_icon_renderer_finalize;
/* Hook up functions to set and get our
* custom cell renderer properties */
object_class->get_property = ptk_file_icon_renderer_get_property;
object_class->set_property = ptk_file_icon_renderer_set_property;
parent_renderer_class->get_size = ptk_file_icon_renderer_get_size;
parent_renderer_class->render = ptk_file_icon_renderer_render;
g_object_class_install_property ( object_class,
PROP_INFO,
g_param_spec_pointer ( "info",
"File info",
"File info",
G_PARAM_READWRITE ) );
g_object_class_install_property ( object_class,
PROP_FOLLOW_STATE,
g_param_spec_boolean ( "follow-state",
"Follow State",
"Whether the rendered pixbuf should be "
"colorized according to the state",
FALSE,
G_PARAM_READWRITE ) );
}
/***************************************************************************
*
* ptk_file_icon_renderer_finalize: free any resources here
*
***************************************************************************/
static void
ptk_file_icon_renderer_finalize ( GObject *object )
{
PtkFileIconRenderer* renderer = PTK_FILE_ICON_RENDERER(object);
if( renderer->info )
vfs_file_info_unref( renderer->info );
g_object_unref( (link_icon) );
( * G_OBJECT_CLASS ( parent_class ) ->finalize ) ( object );
}
/***************************************************************************
*
* ptk_file_icon_renderer_get_property: as it says
*
***************************************************************************/
static void
ptk_file_icon_renderer_get_property ( GObject *object,
guint param_id,
GValue *value,
GParamSpec *psec )
{
PtkFileIconRenderer * renderer = PTK_FILE_ICON_RENDERER( object );
switch ( param_id )
{
/* case PROP_FLAGS:
g_value_set_long(value, renderer->flags);
break;
*/
case PROP_INFO:
g_value_set_pointer( value, renderer->info ? vfs_file_info_ref(renderer->info) : NULL );
case PROP_FOLLOW_STATE:
g_value_set_boolean ( value, renderer->follow_state );
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID ( object, param_id, psec );
break;
}
}
/***************************************************************************
*
* ptk_file_icon_renderer_set_property: as it says
*
***************************************************************************/
static void
ptk_file_icon_renderer_set_property ( GObject *object,
guint param_id,
const GValue *value,
GParamSpec *pspec )
{
PtkFileIconRenderer * renderer = PTK_FILE_ICON_RENDERER ( object );
switch ( param_id )
{
case PROP_INFO:
if( renderer->info )
vfs_file_info_unref( renderer->info );
renderer->info = g_value_get_pointer( value );
break;
/*
case PROP_FLAGS:
renderer->flags = g_value_get_long(value);
break;
*/
case PROP_FOLLOW_STATE:
renderer->follow_state = g_value_get_boolean ( value );
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID( object, param_id, pspec );
break;
}
}
/***************************************************************************
*
* ptk_file_icon_renderer_new: return a new cell renderer instance
*
***************************************************************************/
GtkCellRenderer *
ptk_file_icon_renderer_new ( void )
{
return ( GtkCellRenderer* ) g_object_new( PTK_TYPE_FILE_ICON_RENDERER, NULL );
}
static GdkPixbuf *
create_colorized_pixbuf ( GdkPixbuf *src,
GdkColor *new_color )
{
gint i, j;
gint width, height, has_alpha, src_row_stride, dst_row_stride;
gint red_value, green_value, blue_value;
guchar *target_pixels;
guchar *original_pixels;
guchar *pixsrc;
guchar *pixdest;
GdkPixbuf *dest;
red_value = new_color->red / 255.0;
green_value = new_color->green / 255.0;
blue_value = new_color->blue / 255.0;
dest = gdk_pixbuf_new ( gdk_pixbuf_get_colorspace ( src ),
gdk_pixbuf_get_has_alpha ( src ),
gdk_pixbuf_get_bits_per_sample ( src ),
gdk_pixbuf_get_width ( src ),
gdk_pixbuf_get_height ( src ) );
has_alpha = gdk_pixbuf_get_has_alpha ( src );
width = gdk_pixbuf_get_width ( src );
height = gdk_pixbuf_get_height ( src );
src_row_stride = gdk_pixbuf_get_rowstride ( src );
dst_row_stride = gdk_pixbuf_get_rowstride ( dest );
target_pixels = gdk_pixbuf_get_pixels ( dest );
original_pixels = gdk_pixbuf_get_pixels ( src );
for ( i = 0; i < height; i++ )
{
pixdest = target_pixels + i * dst_row_stride;
pixsrc = original_pixels + i * src_row_stride;
for ( j = 0; j < width; j++ )
{
*pixdest++ = ( *pixsrc++ * red_value ) >> 8;
*pixdest++ = ( *pixsrc++ * green_value ) >> 8;
*pixdest++ = ( *pixsrc++ * blue_value ) >> 8;
if ( has_alpha )
{
*pixdest++ = *pixsrc++;
}
}
}
return dest;
}
/***************************************************************************
*
* ptk_file_icon_renderer_render: crucial - do the rendering.
*
***************************************************************************/
#if GTK_CHECK_VERSION (3, 0, 0)
static void
ptk_file_icon_renderer_render ( GtkCellRenderer *cell,
cairo_t *cr,
GtkWidget *widget,
const GdkRectangle *background_area,
const GdkRectangle *cell_area,
GtkCellRendererState flags )
#else
static void
ptk_file_icon_renderer_render ( GtkCellRenderer *cell,
GdkWindow *window,
GtkWidget *widget,
GdkRectangle *background_area,
GdkRectangle *cell_area,
GdkRectangle *expose_area,
guint flags )
#endif
{
GtkCellRendererPixbuf * cellpixbuf = ( GtkCellRendererPixbuf * ) cell;
GdkPixbuf *pixbuf;
GdkPixbuf *pixbuf_expander_open;
GdkPixbuf *pixbuf_expander_closed;
GdkPixbuf *invisible = NULL;
GdkPixbuf *colorized = NULL;
GdkRectangle pix_rect;
GdkRectangle draw_rect;
VFSFileInfo* file;
gint xpad, ypad;
gboolean is_expander, is_expanded;
GtkCellRendererClass* parent_renderer_class;
parent_renderer_class = GTK_CELL_RENDERER_CLASS( parent_class );
parent_renderer_class->get_size ( cell, widget, cell_area,
&pix_rect.x,
&pix_rect.y,
&pix_rect.width,
&pix_rect.height );
pix_rect.x += cell_area->x;
pix_rect.y += cell_area->y;
gtk_cell_renderer_get_padding (cell, &xpad, &ypad);
pix_rect.width -= xpad * 2;
pix_rect.height -= ypad * 2;
#if GTK_CHECK_VERSION (3, 0, 0)
if ( !gdk_rectangle_intersect ( cell_area, &pix_rect, &draw_rect ) )
return ;
#else
if ( !gdk_rectangle_intersect ( cell_area, &pix_rect, &draw_rect ) ||
!gdk_rectangle_intersect ( expose_area, &draw_rect, &draw_rect ) )
return ;
#endif
g_object_get ( G_OBJECT ( cellpixbuf ), "pixbuf", &pixbuf, NULL);
g_object_get ( G_OBJECT ( cellpixbuf ), "is-expander", &is_expander, NULL);
g_object_get ( G_OBJECT ( cellpixbuf ), "is-expanded", &is_expanded, NULL);
g_object_get ( G_OBJECT ( cellpixbuf ), "pixbuf-expander-open", &pixbuf_expander_open, NULL);
g_object_get ( G_OBJECT ( cellpixbuf ), "pixbuf-expander-closed", &pixbuf_expander_closed, NULL);
if ( is_expander )
{
g_object_get ( G_OBJECT ( cellpixbuf ), "is-expanded", &is_expanded, NULL);
if ( is_expanded &&
pixbuf_expander_open != NULL )
{
g_object_unref ( pixbuf );
pixbuf = pixbuf_expander_open;
if ( pixbuf_expander_closed )
g_object_unref ( pixbuf_expander_closed );
}
else if ( !is_expanded &&
pixbuf_expander_closed != NULL )
{
g_object_unref ( pixbuf );
pixbuf = pixbuf_expander_closed;
if ( pixbuf_expander_open )
g_object_unref ( pixbuf_expander_open );
}
}
else
{
if ( pixbuf_expander_open )
g_object_unref ( pixbuf_expander_open );
if ( pixbuf_expander_closed )
g_object_unref ( pixbuf_expander_closed );
}
if ( !pixbuf )
return ;
if ( PTK_FILE_ICON_RENDERER( cell ) ->follow_state )
{
if ( gtk_widget_get_state ( widget ) == GTK_STATE_INSENSITIVE || !gtk_cell_renderer_get_sensitive(cell) )
{
GtkIconSource * source;
source = gtk_icon_source_new ();
gtk_icon_source_set_pixbuf ( source, pixbuf );
/* The size here is arbitrary; since size isn't
* wildcarded in the source, it isn't supposed to be
* scaled by the engine function
*/
gtk_icon_source_set_size ( source, GTK_ICON_SIZE_SMALL_TOOLBAR );
gtk_icon_source_set_size_wildcarded ( source, FALSE );
invisible = gtk_style_render_icon ( gtk_widget_get_style (widget),
source,
gtk_widget_get_direction ( widget ),
GTK_STATE_INSENSITIVE,
/* arbitrary */
( GtkIconSize ) - 1,
widget,
"gtkcellrendererpixbuf" );
gtk_icon_source_free ( source );
pixbuf = invisible;
}
else if ( ( flags & ( GTK_CELL_RENDERER_SELECTED /*|GTK_CELL_RENDERER_PRELIT*/ ) ) != 0 )
{
GtkStateType state;
GdkColor* color;
if ( ( flags & GTK_CELL_RENDERER_SELECTED ) != 0 )
{
if ( gtk_widget_has_focus ( widget ) )
state = GTK_STATE_SELECTED;
else
#if GTK_CHECK_VERSION (3, 0, 0)
state = GTK_STATE_SELECTED;
#else
state = GTK_STATE_ACTIVE;
#endif
color = >k_widget_get_style(widget)->base[ state ];
}
else
{
state = GTK_STATE_PRELIGHT;
}
colorized = create_colorized_pixbuf ( pixbuf,
color );
pixbuf = colorized;
}
}
#if GTK_CHECK_VERSION (3, 0, 0)
cairo_save ( cr );
#else
cairo_t *cr = gdk_cairo_create ( window );
#endif
cairo_set_operator ( cr, CAIRO_OPERATOR_OVER );
gdk_cairo_set_source_pixbuf ( cr, pixbuf, pix_rect.x, pix_rect.y );
gdk_cairo_rectangle ( cr, &draw_rect );
cairo_fill ( cr );
file = PTK_FILE_ICON_RENDERER( cell )->info;
if ( file )
{
if ( vfs_file_info_is_symlink( file ) )
{
cairo_set_operator ( cr, CAIRO_OPERATOR_OVER );
gdk_cairo_set_source_pixbuf ( cr, link_icon,
pix_rect.x,
pix_rect.y );
draw_rect.x -= 2;
draw_rect.y -= 2;
gdk_cairo_rectangle ( cr, &draw_rect );
cairo_fill ( cr );
}
}
#if GTK_CHECK_VERSION (3, 0, 0)
cairo_restore ( cr );
#else
cairo_destroy ( cr );
#endif
if ( invisible )
g_object_unref ( invisible );
if ( colorized )
g_object_unref ( colorized );
}
void ptk_file_icon_renderer_get_size ( GtkCellRenderer *cell,
GtkWidget *widget,
#if GTK_CHECK_VERSION (3, 0, 0)
const GdkRectangle *cell_area,
#else
GdkRectangle *cell_area,
#endif
gint *x_offset,
gint *y_offset,
gint *width,
gint *height )
{
GTK_CELL_RENDERER_CLASS( parent_class )->get_size( cell, widget, cell_area,
x_offset, y_offset,
width, height );
if(!width || ! height)
return;
//g_debug( "w=%d, h=%d", *width, *height );
if ( *width > *height )
* height = *width;
else if ( *width < *height )
* width = *height;
}
|
190 | ./spacefm/src/ptk/ptk-file-list.c | /*
* C Implementation: ptk-file-list
*
* Description:
*
*
* Author: Hong Jen Yee (PCMan) <pcman.tw (AT) gmail.com>, (C) 2006
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#include "ptk-file-list.h"
#include <gdk/gdk.h>
#include "glib-mem.h"
#include "vfs-file-info.h"
#include "vfs-thumbnail-loader.h"
#include <string.h>
static void ptk_file_list_init ( PtkFileList *list );
static void ptk_file_list_class_init ( PtkFileListClass *klass );
static void ptk_file_list_tree_model_init ( GtkTreeModelIface *iface );
static void ptk_file_list_tree_sortable_init ( GtkTreeSortableIface *iface );
static void ptk_file_list_drag_source_init ( GtkTreeDragSourceIface *iface );
static void ptk_file_list_drag_dest_init ( GtkTreeDragDestIface *iface );
static void ptk_file_list_finalize ( GObject *object );
static GtkTreeModelFlags ptk_file_list_get_flags ( GtkTreeModel *tree_model );
static gint ptk_file_list_get_n_columns ( GtkTreeModel *tree_model );
static GType ptk_file_list_get_column_type ( GtkTreeModel *tree_model,
gint index );
static gboolean ptk_file_list_get_iter ( GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreePath *path );
static GtkTreePath *ptk_file_list_get_path ( GtkTreeModel *tree_model,
GtkTreeIter *iter );
static void ptk_file_list_get_value ( GtkTreeModel *tree_model,
GtkTreeIter *iter,
gint column,
GValue *value );
static gboolean ptk_file_list_iter_next ( GtkTreeModel *tree_model,
GtkTreeIter *iter );
static gboolean ptk_file_list_iter_children ( GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreeIter *parent );
static gboolean ptk_file_list_iter_has_child ( GtkTreeModel *tree_model,
GtkTreeIter *iter );
static gint ptk_file_list_iter_n_children ( GtkTreeModel *tree_model,
GtkTreeIter *iter );
static gboolean ptk_file_list_iter_nth_child ( GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreeIter *parent,
gint n );
static gboolean ptk_file_list_iter_parent ( GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreeIter *child );
static gboolean ptk_file_list_get_sort_column_id( GtkTreeSortable* sortable,
gint* sort_column_id,
GtkSortType* order );
static void ptk_file_list_set_sort_column_id( GtkTreeSortable* sortable,
gint sort_column_id,
GtkSortType order );
static void ptk_file_list_set_sort_func( GtkTreeSortable *sortable,
gint sort_column_id,
GtkTreeIterCompareFunc sort_func,
gpointer user_data,
GDestroyNotify destroy );
static void ptk_file_list_set_default_sort_func( GtkTreeSortable *sortable,
GtkTreeIterCompareFunc sort_func,
gpointer user_data,
GDestroyNotify destroy );
//static void ptk_file_list_sort ( PtkFileList* list ); //sfm made non-static
/* signal handlers */
static void on_thumbnail_loaded( VFSDir* dir, VFSFileInfo* file, PtkFileList* list );
/*
* already declared in ptk-file-list.h
void ptk_file_list_file_created( VFSDir* dir, VFSFileInfo* file,
PtkFileList* list );
void ptk_file_list_file_deleted( VFSDir* dir, VFSFileInfo* file,
PtkFileList* list );
void ptk_file_list_file_changed( VFSDir* dir, VFSFileInfo* file,
PtkFileList* list );
*/
static GObjectClass* parent_class = NULL;
static GType column_types[ N_FILE_LIST_COLS ];
GType ptk_file_list_get_type ( void )
{
static GType type = 0;
if ( G_UNLIKELY( !type ) )
{
static const GTypeInfo type_info =
{
sizeof ( PtkFileListClass ),
NULL, /* base_init */
NULL, /* base_finalize */
( GClassInitFunc ) ptk_file_list_class_init,
NULL, /* class finalize */
NULL, /* class_data */
sizeof ( PtkFileList ),
0, /* n_preallocs */
( GInstanceInitFunc ) ptk_file_list_init
};
static const GInterfaceInfo tree_model_info =
{
( GInterfaceInitFunc ) ptk_file_list_tree_model_init,
NULL,
NULL
};
static const GInterfaceInfo tree_sortable_info =
{
( GInterfaceInitFunc ) ptk_file_list_tree_sortable_init,
NULL,
NULL
};
static const GInterfaceInfo drag_src_info =
{
( GInterfaceInitFunc ) ptk_file_list_drag_source_init,
NULL,
NULL
};
static const GInterfaceInfo drag_dest_info =
{
( GInterfaceInitFunc ) ptk_file_list_drag_dest_init,
NULL,
NULL
};
type = g_type_register_static ( G_TYPE_OBJECT, "PtkFileList",
&type_info, ( GTypeFlags ) 0 );
g_type_add_interface_static ( type, GTK_TYPE_TREE_MODEL, &tree_model_info );
g_type_add_interface_static ( type, GTK_TYPE_TREE_SORTABLE, &tree_sortable_info );
g_type_add_interface_static ( type, GTK_TYPE_TREE_DRAG_SOURCE, &drag_src_info );
g_type_add_interface_static ( type, GTK_TYPE_TREE_DRAG_DEST, &drag_dest_info );
}
return type;
}
void ptk_file_list_init ( PtkFileList *list )
{
list->n_files = 0;
list->files = NULL;
list->sort_order = -1;
list->sort_col = -1;
/* Random int to check whether an iter belongs to our model */
list->stamp = g_random_int();
}
void ptk_file_list_class_init ( PtkFileListClass *klass )
{
GObjectClass * object_class;
parent_class = ( GObjectClass* ) g_type_class_peek_parent ( klass );
object_class = ( GObjectClass* ) klass;
object_class->finalize = ptk_file_list_finalize;
}
void ptk_file_list_tree_model_init ( GtkTreeModelIface *iface )
{
iface->get_flags = ptk_file_list_get_flags;
iface->get_n_columns = ptk_file_list_get_n_columns;
iface->get_column_type = ptk_file_list_get_column_type;
iface->get_iter = ptk_file_list_get_iter;
iface->get_path = ptk_file_list_get_path;
iface->get_value = ptk_file_list_get_value;
iface->iter_next = ptk_file_list_iter_next;
iface->iter_children = ptk_file_list_iter_children;
iface->iter_has_child = ptk_file_list_iter_has_child;
iface->iter_n_children = ptk_file_list_iter_n_children;
iface->iter_nth_child = ptk_file_list_iter_nth_child;
iface->iter_parent = ptk_file_list_iter_parent;
column_types [ COL_FILE_BIG_ICON ] = GDK_TYPE_PIXBUF;
column_types [ COL_FILE_SMALL_ICON ] = GDK_TYPE_PIXBUF;
column_types [ COL_FILE_NAME ] = G_TYPE_STRING;
column_types [ COL_FILE_DESC ] = G_TYPE_STRING;
column_types [ COL_FILE_SIZE ] = G_TYPE_STRING;
column_types [ COL_FILE_DESC ] = G_TYPE_STRING;
column_types [ COL_FILE_PERM ] = G_TYPE_STRING;
column_types [ COL_FILE_OWNER ] = G_TYPE_STRING;
column_types [ COL_FILE_MTIME ] = G_TYPE_STRING;
column_types [ COL_FILE_INFO ] = G_TYPE_POINTER;
}
void ptk_file_list_tree_sortable_init ( GtkTreeSortableIface *iface )
{
/* iface->sort_column_changed = ptk_file_list_sort_column_changed; */
iface->get_sort_column_id = ptk_file_list_get_sort_column_id;
iface->set_sort_column_id = ptk_file_list_set_sort_column_id;
iface->set_sort_func = ptk_file_list_set_sort_func;
iface->set_default_sort_func = ptk_file_list_set_default_sort_func;
iface->has_default_sort_func = (gboolean(*)(GtkTreeSortable *))gtk_false;
}
void ptk_file_list_drag_source_init ( GtkTreeDragSourceIface *iface )
{
/* FIXME: Unused. Will this cause any problem? */
}
void ptk_file_list_drag_dest_init ( GtkTreeDragDestIface *iface )
{
/* FIXME: Unused. Will this cause any problem? */
}
void ptk_file_list_finalize ( GObject *object )
{
PtkFileList *list = ( PtkFileList* ) object;
ptk_file_list_set_dir( list, NULL );
/* must chain up - finalize parent */
( * parent_class->finalize ) ( object );
}
PtkFileList *ptk_file_list_new ( VFSDir* dir, gboolean show_hidden )
{
PtkFileList * list;
list = ( PtkFileList* ) g_object_new ( PTK_TYPE_FILE_LIST, NULL );
list->show_hidden = show_hidden;
ptk_file_list_set_dir( list, dir );
return list;
}
static void _ptk_file_list_file_changed( VFSDir* dir, VFSFileInfo* file,
PtkFileList* list )
{
ptk_file_list_file_changed( dir, file, list );
/* check if reloading of thumbnail is needed. */
if( vfs_file_info_is_image( file )
&& vfs_file_info_get_size( file ) < list->max_thumbnail )
{
if( ! vfs_file_info_is_thumbnail_loaded( file, list->big_thumbnail ) )
vfs_thumbnail_loader_request( list->dir, file, list->big_thumbnail );
}
}
static void _ptk_file_list_file_created( VFSDir* dir, VFSFileInfo* file,
PtkFileList* list )
{
ptk_file_list_file_created( dir, file, list );
/* check if reloading of thumbnail is needed. */
if( vfs_file_info_is_image( file )
&& vfs_file_info_get_size( file ) < list->max_thumbnail )
{
if( ! vfs_file_info_is_thumbnail_loaded( file, list->big_thumbnail ) )
vfs_thumbnail_loader_request( list->dir, file, list->big_thumbnail );
}
}
void ptk_file_list_set_dir( PtkFileList* list, VFSDir* dir )
{
GList* l;
if( list->dir == dir )
return;
if ( list->dir )
{
if( list->max_thumbnail > 0 )
{
/* cancel all possible pending requests */
vfs_thumbnail_loader_cancel_all_requests( list->dir, list->big_thumbnail );
}
g_list_foreach( list->files, (GFunc)vfs_file_info_unref, NULL );
g_list_free( list->files );
g_signal_handlers_disconnect_by_func( list->dir,
_ptk_file_list_file_created, list );
g_signal_handlers_disconnect_by_func( list->dir,
ptk_file_list_file_deleted, list );
g_signal_handlers_disconnect_by_func( list->dir,
_ptk_file_list_file_changed, list );
g_signal_handlers_disconnect_by_func( list->dir,
on_thumbnail_loaded, list );
g_object_unref( list->dir );
}
list->dir = dir;
list->files = NULL;
list->n_files = 0;
if( ! dir )
return;
g_object_ref( list->dir );
g_signal_connect( list->dir, "file-created",
G_CALLBACK(_ptk_file_list_file_created),
list );
g_signal_connect( list->dir, "file-deleted",
G_CALLBACK(ptk_file_list_file_deleted),
list );
g_signal_connect( list->dir, "file-changed",
G_CALLBACK(_ptk_file_list_file_changed),
list );
if( dir && dir->file_list )
{
for( l = dir->file_list; l; l = l->next )
{
if( list->show_hidden ||
((VFSFileInfo*)l->data)->disp_name[0] != '.' )
{
list->files = g_list_prepend( list->files, vfs_file_info_ref( (VFSFileInfo*)l->data) );
++list->n_files;
}
}
}
}
GtkTreeModelFlags ptk_file_list_get_flags ( GtkTreeModel *tree_model )
{
g_return_val_if_fail ( PTK_IS_FILE_LIST( tree_model ), ( GtkTreeModelFlags ) 0 );
return ( GTK_TREE_MODEL_LIST_ONLY | GTK_TREE_MODEL_ITERS_PERSIST );
}
gint ptk_file_list_get_n_columns ( GtkTreeModel *tree_model )
{
return N_FILE_LIST_COLS;
}
GType ptk_file_list_get_column_type ( GtkTreeModel *tree_model,
gint index )
{
g_return_val_if_fail ( PTK_IS_FILE_LIST( tree_model ), G_TYPE_INVALID );
g_return_val_if_fail ( index < G_N_ELEMENTS( column_types ) && index >= 0, G_TYPE_INVALID );
return column_types[ index ];
}
gboolean ptk_file_list_get_iter ( GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreePath *path )
{
PtkFileList *list;
gint *indices, n, depth;
GList* l;
g_assert(PTK_IS_FILE_LIST(tree_model));
g_assert(path!=NULL);
list = PTK_FILE_LIST(tree_model);
indices = gtk_tree_path_get_indices(path);
depth = gtk_tree_path_get_depth(path);
/* we do not allow children */
g_assert(depth == 1); /* depth 1 = top level; a list only has top level nodes and no children */
n = indices[0]; /* the n-th top level row */
if ( n >= list->n_files || n < 0 )
return FALSE;
l = g_list_nth( list->files, n );
g_assert(l != NULL);
/* We simply store a pointer in the iter */
iter->stamp = list->stamp;
iter->user_data = l;
iter->user_data2 = l->data;
iter->user_data3 = NULL; /* unused */
return TRUE;
}
GtkTreePath *ptk_file_list_get_path ( GtkTreeModel *tree_model,
GtkTreeIter *iter )
{
GtkTreePath* path;
GList* l;
PtkFileList* list = PTK_FILE_LIST(tree_model);
g_return_val_if_fail (list, NULL);
g_return_val_if_fail (iter->stamp == list->stamp, NULL);
g_return_val_if_fail (iter != NULL, NULL);
g_return_val_if_fail (iter->user_data != NULL, NULL);
l = (GList*) iter->user_data;
path = gtk_tree_path_new();
gtk_tree_path_append_index(path, g_list_index(list->files, l->data) );
return path;
}
void ptk_file_list_get_value ( GtkTreeModel *tree_model,
GtkTreeIter *iter,
gint column,
GValue *value )
{
GList* l;
PtkFileList* list = PTK_FILE_LIST(tree_model);
VFSFileInfo* info;
GdkPixbuf* icon;
g_return_if_fail (PTK_IS_FILE_LIST (tree_model));
g_return_if_fail (iter != NULL);
g_return_if_fail (column < G_N_ELEMENTS(column_types) );
g_value_init (value, column_types[column] );
l = (GList*) iter->user_data;
g_return_if_fail ( l != NULL );
info = (VFSFileInfo*)iter->user_data2;
switch(column)
{
case COL_FILE_BIG_ICON:
icon = NULL;
/* special file can use special icons saved as thumbnails*/
if( list->max_thumbnail > vfs_file_info_get_size( info )
&& info->flags == VFS_FILE_INFO_NONE )
icon = vfs_file_info_get_big_thumbnail( info );
if( ! icon )
icon = vfs_file_info_get_big_icon( info );
if( icon )
{
g_value_set_object( value, icon );
g_object_unref( icon );
}
break;
case COL_FILE_SMALL_ICON:
icon = NULL;
/* special file can use special icons saved as thumbnails*/
if( list->max_thumbnail > vfs_file_info_get_size( info ) )
icon = vfs_file_info_get_small_thumbnail( info );
if( !icon )
icon = vfs_file_info_get_small_icon( info );
if( icon )
{
g_value_set_object( value, icon );
g_object_unref( icon );
}
break;
case COL_FILE_NAME:
g_value_set_string( value, vfs_file_info_get_disp_name(info) );
break;
case COL_FILE_SIZE:
if ( S_ISDIR( info->mode ) || ( S_ISLNK( info->mode ) &&
0 == strcmp( vfs_mime_type_get_type( info->mime_type ),
XDG_MIME_TYPE_DIRECTORY ) ) )
g_value_set_string( value, NULL );
else
g_value_set_string( value, vfs_file_info_get_disp_size(info) );
break;
case COL_FILE_DESC:
g_value_set_string( value, vfs_file_info_get_mime_type_desc( info ) );
break;
case COL_FILE_PERM:
g_value_set_string( value, vfs_file_info_get_disp_perm(info) );
break;
case COL_FILE_OWNER:
g_value_set_string( value, vfs_file_info_get_disp_owner(info) );
break;
case COL_FILE_MTIME:
g_value_set_string( value, vfs_file_info_get_disp_mtime(info) );
break;
case COL_FILE_INFO:
g_value_set_pointer( value, vfs_file_info_ref( info ) );
break;
}
}
gboolean ptk_file_list_iter_next ( GtkTreeModel *tree_model,
GtkTreeIter *iter )
{
GList* l;
PtkFileList* list;
g_return_val_if_fail (PTK_IS_FILE_LIST (tree_model), FALSE);
if (iter == NULL || iter->user_data == NULL)
return FALSE;
list = PTK_FILE_LIST(tree_model);
l = (GList *) iter->user_data;
/* Is this the last l in the list? */
if ( ! l->next )
return FALSE;
iter->stamp = list->stamp;
iter->user_data = l->next;
iter->user_data2 = l->next->data;
return TRUE;
}
gboolean ptk_file_list_iter_children ( GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreeIter *parent )
{
PtkFileList* list;
g_return_val_if_fail ( parent == NULL || parent->user_data != NULL, FALSE );
/* this is a list, nodes have no children */
if ( parent )
return FALSE;
/* parent == NULL is a special case; we need to return the first top-level row */
g_return_val_if_fail ( PTK_IS_FILE_LIST ( tree_model ), FALSE );
list = PTK_FILE_LIST( tree_model );
/* No rows => no first row */
if ( list->dir->n_files == 0 )
return FALSE;
/* Set iter to first item in list */
iter->stamp = list->stamp;
iter->user_data = list->files;
iter->user_data2 = list->files->data;
return TRUE;
}
gboolean ptk_file_list_iter_has_child ( GtkTreeModel *tree_model,
GtkTreeIter *iter )
{
return FALSE;
}
gint ptk_file_list_iter_n_children ( GtkTreeModel *tree_model,
GtkTreeIter *iter )
{
PtkFileList* list;
g_return_val_if_fail ( PTK_IS_FILE_LIST ( tree_model ), -1 );
g_return_val_if_fail ( iter == NULL || iter->user_data != NULL, FALSE );
list = PTK_FILE_LIST( tree_model );
/* special case: if iter == NULL, return number of top-level rows */
if ( !iter )
return list->n_files;
return 0; /* otherwise, this is easy again for a list */
}
gboolean ptk_file_list_iter_nth_child ( GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreeIter *parent,
gint n )
{
GList* l;
PtkFileList* list;
g_return_val_if_fail (PTK_IS_FILE_LIST (tree_model), FALSE);
list = PTK_FILE_LIST(tree_model);
/* a list has only top-level rows */
if(parent)
return FALSE;
/* special case: if parent == NULL, set iter to n-th top-level row */
if( n >= list->n_files || n < 0 )
return FALSE;
l = g_list_nth( list->files, n );
g_assert( l != NULL );
iter->stamp = list->stamp;
iter->user_data = l;
iter->user_data2 = l->data;
return TRUE;
}
gboolean ptk_file_list_iter_parent ( GtkTreeModel *tree_model,
GtkTreeIter *iter,
GtkTreeIter *child )
{
return FALSE;
}
gboolean ptk_file_list_get_sort_column_id( GtkTreeSortable* sortable,
gint* sort_column_id,
GtkSortType* order )
{
PtkFileList* list = (PtkFileList*)sortable;
if( sort_column_id )
*sort_column_id = list->sort_col;
if( order )
*order = list->sort_order;
return TRUE;
}
void ptk_file_list_set_sort_column_id( GtkTreeSortable* sortable,
gint sort_column_id,
GtkSortType order )
{
PtkFileList* list = (PtkFileList*)sortable;
if( list->sort_col == sort_column_id && list->sort_order == order )
return;
list->sort_col = sort_column_id;
list->sort_order = order;
gtk_tree_sortable_sort_column_changed (sortable);
ptk_file_list_sort (list);
}
void ptk_file_list_set_sort_func( GtkTreeSortable *sortable,
gint sort_column_id,
GtkTreeIterCompareFunc sort_func,
gpointer user_data,
GDestroyNotify destroy )
{
g_warning( "ptk_file_list_set_sort_func: Not supported\n" );
}
void ptk_file_list_set_default_sort_func( GtkTreeSortable *sortable,
GtkTreeIterCompareFunc sort_func,
gpointer user_data,
GDestroyNotify destroy )
{
g_warning( "ptk_file_list_set_default_sort_func: Not supported\n" );
}
static gint ptk_file_list_compare( gconstpointer a,
gconstpointer b,
gpointer user_data)
{
VFSFileInfo* file_a = (VFSFileInfo*)a;
VFSFileInfo* file_b = (VFSFileInfo*)b;
PtkFileList* list = (PtkFileList*)user_data;
int result;
// dirs before/after files
if ( list->sort_dir != PTK_LIST_SORT_DIR_MIXED )
{
result = vfs_file_info_is_dir( file_a ) - vfs_file_info_is_dir( file_b );
if ( result != 0 )
return list->sort_dir == PTK_LIST_SORT_DIR_FIRST ? -result : result;
}
// by column
switch ( list->sort_col )
{
case COL_FILE_SIZE:
if ( file_a->size > file_b->size )
result = 1;
else if ( file_a->size == file_b->size )
result = 0;
else
result = -1;
break;
case COL_FILE_MTIME:
if ( file_a->mtime > file_b->mtime )
result = 1;
else if ( file_a->mtime == file_b->mtime )
result = 0;
else
result = -1;
break;
case COL_FILE_DESC:
result = g_ascii_strcasecmp( vfs_file_info_get_mime_type_desc( file_a ),
vfs_file_info_get_mime_type_desc( file_b ) );
break;
case COL_FILE_PERM:
result = strcmp( file_a->disp_perm, file_b->disp_perm );
break;
case COL_FILE_OWNER:
result = g_ascii_strcasecmp( file_a->disp_owner, file_b->disp_owner );
break;
default:
result = 0;
}
if ( result != 0 )
return list->sort_order == GTK_SORT_ASCENDING ? result : -result;
// hidden first/last
gboolean hidden_a = file_a->disp_name[0] == '.' || file_a->disp_name[0] == '#';
gboolean hidden_b = file_b->disp_name[0] == '.' || file_b->disp_name[0] == '#';
if ( hidden_a && !hidden_b )
result = list->sort_hidden_first ? -1 : 1;
else if ( !hidden_a && hidden_b )
result = list->sort_hidden_first ? 1 : -1;
if ( result != 0 )
return result;
// by display name
if ( list->sort_natural )
{
// natural
if ( list->sort_case )
result = strcmp( file_a->collate_key, file_b->collate_key );
else
result = strcmp( file_a->collate_icase_key, file_b->collate_icase_key );
}
else
{
// non-natural FIXME: don't compare utf8 as ascii ?
// both g_ascii_strcasecmp and g_ascii_strncasecmp appear to be
// case insensitive when used on utf8?
result = g_ascii_strcasecmp( file_a->disp_name, file_b->disp_name );
}
return list->sort_order == GTK_SORT_ASCENDING ? result : -result;
}
#if 0
static gint ptk_file_list_compare( gconstpointer a,
gconstpointer b,
gpointer user_data)
{
VFSFileInfo* file1 = (VFSFileInfo*)a;
VFSFileInfo* file2 = (VFSFileInfo*)b;
PtkFileList* list = (PtkFileList*)user_data;
int ret;
/* put folders before files */
ret = vfs_file_info_is_dir(file1) - vfs_file_info_is_dir(file2);
if( ret )
return -ret;
/* FIXME: strings should not be treated as ASCII when sorted */
switch( list->sort_col )
{
case COL_FILE_NAME:
ret = g_ascii_strcasecmp( vfs_file_info_get_disp_name(file1),
vfs_file_info_get_disp_name(file2) );
break;
case COL_FILE_SIZE:
if ( file1->size > file2->size )
ret = 1;
else if ( file1->size == file2->size )
ret = 0;
else
ret = -1;
//ret = file1->size - file2->size;
break;
case COL_FILE_DESC:
ret = g_ascii_strcasecmp( vfs_file_info_get_mime_type_desc(file1),
vfs_file_info_get_mime_type_desc(file2) );
break;
case COL_FILE_PERM:
ret = g_ascii_strcasecmp( vfs_file_info_get_disp_perm(file1),
vfs_file_info_get_disp_perm(file2) );
break;
case COL_FILE_OWNER:
ret = g_ascii_strcasecmp( vfs_file_info_get_disp_owner(file1),
vfs_file_info_get_disp_owner(file2) );
break;
case COL_FILE_MTIME:
ret = file1->mtime - file2->mtime;
break;
}
return list->sort_order == GTK_SORT_ASCENDING ? ret : -ret;
}
#endif
void ptk_file_list_sort ( PtkFileList* list )
{
GHashTable* old_order;
gint *new_order;
GtkTreePath *path;
GList* l;
int i;
if( list->n_files <=1 )
return;
old_order = g_hash_table_new( g_direct_hash, g_direct_equal );
/* save old order */
for( i = 0, l = list->files; l; l = l->next, ++i )
g_hash_table_insert( old_order, l, GINT_TO_POINTER(i) );
/* sort the list */
list->files = g_list_sort_with_data( list->files,
ptk_file_list_compare, list );
/* save new order */
new_order = g_new( int, list->n_files );
for( i = 0, l = list->files; l; l = l->next, ++i )
new_order[i] = GPOINTER_TO_INT( g_hash_table_lookup( old_order, l ) );
g_hash_table_destroy( old_order );
path = gtk_tree_path_new ();
gtk_tree_model_rows_reordered (GTK_TREE_MODEL (list),
path, NULL, new_order);
gtk_tree_path_free (path);
g_free( new_order );
}
gboolean ptk_file_list_find_iter( PtkFileList* list, GtkTreeIter* it, VFSFileInfo* fi )
{
GList* l;
for( l = list->files; l; l = l->next )
{
VFSFileInfo* fi2 = (VFSFileInfo*)l->data;
if( G_UNLIKELY( fi2 == fi
|| 0 == strcmp( vfs_file_info_get_name(fi), vfs_file_info_get_name(fi2) ) ) )
{
it->stamp = list->stamp;
it->user_data = l;
it->user_data2 = fi2;
return TRUE;
}
}
return FALSE;
}
void ptk_file_list_file_created( VFSDir* dir,
VFSFileInfo* file,
PtkFileList* list )
{
GList* l, *ll = NULL;
GtkTreeIter it;
GtkTreePath* path;
VFSFileInfo* file2;
if( ! list->show_hidden && vfs_file_info_get_name(file)[0] == '.' )
return;
gboolean is_desktop = vfs_file_info_is_desktop_entry( file ); //sfm
gboolean is_desktop2;
for( l = list->files; l; l = l->next )
{
file2 = (VFSFileInfo*)l->data;
if( G_UNLIKELY( file == file2 ) )
{
/* The file is already in the list */
return;
}
is_desktop2 = vfs_file_info_is_desktop_entry( file2 );
if ( is_desktop || is_desktop2 )
{
// at least one is a desktop file, need to compare filenames
if ( file->name && file2->name )
{
if ( !strcmp( file->name, file2->name ) )
return;
}
}
else if ( ptk_file_list_compare( file2, file, list ) == 0 )
{
// disp_name matches ?
// ptk_file_list_compare may return 0 on differing display names
// if case-insensitive - need to compare filenames
if ( list->sort_natural && list->sort_case )
return;
else if ( !strcmp( file->name, file2->name ) )
return;
}
if ( !ll && ptk_file_list_compare( file2, file, list ) > 0 )
{
if ( !is_desktop && !is_desktop2 )
break;
else
ll = l; // store insertion location based on disp_name
}
}
if ( ll )
l = ll;
list->files = g_list_insert_before( list->files, l, vfs_file_info_ref( file ) );
++list->n_files;
if( l )
l = l->prev;
else
l = g_list_last( list->files );
it.stamp = list->stamp;
it.user_data = l;
it.user_data2 = file;
path = gtk_tree_path_new_from_indices( g_list_index(list->files, l->data), -1 );
gtk_tree_model_row_inserted( GTK_TREE_MODEL(list), path, &it );
gtk_tree_path_free( path );
}
void ptk_file_list_file_deleted( VFSDir* dir,
VFSFileInfo* file,
PtkFileList* list )
{
GList* l;
GtkTreePath* path;
/* If there is no file info, that means the dir itself was deleted. */
if( G_UNLIKELY( ! file ) )
{
/* Clear the whole list */
path = gtk_tree_path_new_from_indices(0, -1);
for( l = list->files; l; l = list->files )
{
gtk_tree_model_row_deleted( GTK_TREE_MODEL(list), path );
file = (VFSFileInfo*)l->data;
list->files = g_list_delete_link( list->files, l );
vfs_file_info_unref( file );
--list->n_files;
}
gtk_tree_path_free( path );
return;
}
if( ! list->show_hidden && vfs_file_info_get_name(file)[0] == '.' )
return;
l = g_list_find( list->files, file );
if( ! l )
return;
path = gtk_tree_path_new_from_indices( g_list_index(list->files, l->data), -1 );
gtk_tree_model_row_deleted( GTK_TREE_MODEL(list), path );
gtk_tree_path_free( path );
list->files = g_list_delete_link( list->files, l );
vfs_file_info_unref( file );
--list->n_files;
}
void ptk_file_list_file_changed( VFSDir* dir,
VFSFileInfo* file,
PtkFileList* list )
{
GList* l;
GtkTreeIter it;
GtkTreePath* path;
if( ! list->show_hidden && vfs_file_info_get_name(file)[0] == '.' )
return;
l = g_list_find( list->files, file );
if( ! l )
return;
it.stamp = list->stamp;
it.user_data = l;
it.user_data2 = l->data;
path = gtk_tree_path_new_from_indices( g_list_index(list->files, l->data), -1 );
gtk_tree_model_row_changed( GTK_TREE_MODEL(list), path, &it );
gtk_tree_path_free( path );
}
void on_thumbnail_loaded( VFSDir* dir, VFSFileInfo* file, PtkFileList* list )
{
/* g_debug( "LOADED: %s", file->name ); */
ptk_file_list_file_changed( dir, file, list );
}
void ptk_file_list_show_thumbnails( PtkFileList* list, gboolean is_big,
int max_file_size )
{
GList* l;
VFSFileInfo* file;
int old_max_thumbnail;
old_max_thumbnail = list->max_thumbnail;
list->max_thumbnail = max_file_size;
list->big_thumbnail = is_big;
/* FIXME: This is buggy!!! Further testing might be needed.
*/
if( 0 == max_file_size )
{
if( old_max_thumbnail > 0 ) /* cancel thumbnails */
{
vfs_thumbnail_loader_cancel_all_requests( list->dir, list->big_thumbnail );
g_signal_handlers_disconnect_by_func( list->dir, on_thumbnail_loaded, list );
for( l = list->files; l; l = l->next )
{
file = (VFSFileInfo*)l->data;
if( vfs_file_info_is_image( file )
&& vfs_file_info_is_thumbnail_loaded( file, is_big ) )
{
/* update the model */
ptk_file_list_file_changed( list->dir, file, list );
}
}
}
return;
}
g_signal_connect( list->dir, "thumbnail-loaded",
G_CALLBACK(on_thumbnail_loaded), list );
for( l = list->files; l; l = l->next )
{
file = (VFSFileInfo*)l->data;
if( vfs_file_info_is_image( file )
&& vfs_file_info_get_size( file ) < list->max_thumbnail )
{
if( vfs_file_info_is_thumbnail_loaded( file, is_big ) )
ptk_file_list_file_changed( list->dir, file, list );
else
{
vfs_thumbnail_loader_request( list->dir, file, is_big );
/* g_debug( "REQUEST: %s", file->name ); */
}
}
}
}
|
191 | ./spacefm/src/ptk/ptk-file-browser.c | #ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <unistd.h>
#include <gtk/gtk.h>
#include <glib.h>
#include <glib/gi18n.h>
#include <gdk/gdkkeysyms.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include <errno.h>
#include <fnmatch.h>
#include "ptk-file-browser.h"
#include "exo-icon-view.h"
#include "exo-tree-view.h"
#include "mime-type/mime-type.h"
#include "settings.h" //MOD
#include "ptk-app-chooser.h"
#include "ptk-file-icon-renderer.h"
#include "ptk-utils.h"
#include "ptk-input-dialog.h"
#include "ptk-file-task.h"
#include "ptk-file-misc.h"
#include "ptk-bookmarks.h"
#include "ptk-location-view.h"
#include "ptk-dir-tree-view.h"
#include "ptk-dir-tree.h"
#include "vfs-dir.h"
#include "vfs-utils.h" //MOD
#include "vfs-file-info.h"
#include "vfs-file-monitor.h"
#include "vfs-app-desktop.h"
#include "ptk-file-list.h"
#include "ptk-text-renderer.h"
#include "ptk-file-archiver.h"
#include "ptk-clipboard.h"
#include "ptk-file-menu.h"
#include "ptk-path-entry.h" //MOD
#include "find-files.h" //MOD
#include "main-window.h"
#include "gtk2-compat.h"
extern char* run_cmd; //MOD
static void ptk_file_browser_class_init( PtkFileBrowserClass* klass );
static void ptk_file_browser_init( PtkFileBrowser* file_browser );
static void ptk_file_browser_finalize( GObject *obj );
static void ptk_file_browser_get_property ( GObject *obj,
guint prop_id,
GValue *value,
GParamSpec *pspec );
static void ptk_file_browser_set_property ( GObject *obj,
guint prop_id,
const GValue *value,
GParamSpec *pspec );
/* Utility functions */
static GtkWidget* create_folder_view( PtkFileBrowser* file_browser,
PtkFBViewMode view_mode );
static void init_list_view( PtkFileBrowser* file_browser, GtkTreeView* list_view );
static GtkWidget* ptk_file_browser_create_dir_tree( PtkFileBrowser* file_browser );
static void on_dir_file_listed( VFSDir* dir,
gboolean is_cancelled,
PtkFileBrowser* file_browser );
void ptk_file_browser_open_selected_files_with_app( PtkFileBrowser* file_browser,
char* app_desktop );
static void
ptk_file_browser_cut_or_copy( PtkFileBrowser* file_browser,
gboolean copy );
static void
ptk_file_browser_update_model( PtkFileBrowser* file_browser );
static gboolean
is_latin_shortcut_key( guint keyval );
/* Get GtkTreePath of the item at coordinate x, y */
static GtkTreePath*
folder_view_get_tree_path_at_pos( PtkFileBrowser* file_browser, int x, int y );
#if 0
/* sort functions of folder view */
static gint sort_files_by_name ( GtkTreeModel *model,
GtkTreeIter *a,
GtkTreeIter *b,
gpointer user_data );
static gint sort_files_by_size ( GtkTreeModel *model,
GtkTreeIter *a,
GtkTreeIter *b,
gpointer user_data );
static gint sort_files_by_time ( GtkTreeModel *model,
GtkTreeIter *a,
GtkTreeIter *b,
gpointer user_data );
static gboolean filter_files ( GtkTreeModel *model,
GtkTreeIter *it,
gpointer user_data );
/* sort functions of dir tree */
static gint sort_dir_tree_by_name ( GtkTreeModel *model,
GtkTreeIter *a,
GtkTreeIter *b,
gpointer user_data );
#endif
/* signal handlers */
static void
on_folder_view_item_activated ( ExoIconView *iconview,
GtkTreePath *path,
PtkFileBrowser* file_browser );
static void
on_folder_view_row_activated ( GtkTreeView *tree_view,
GtkTreePath *path,
GtkTreeViewColumn* col,
PtkFileBrowser* file_browser );
static void
on_folder_view_item_sel_change ( ExoIconView *iconview,
PtkFileBrowser* file_browser );
/*
static gboolean
on_folder_view_key_press_event ( GtkWidget *widget,
GdkEventKey *event,
PtkFileBrowser* file_browser );
*/
static gboolean
on_folder_view_button_press_event ( GtkWidget *widget,
GdkEventButton *event,
PtkFileBrowser* file_browser );
static gboolean
on_folder_view_button_release_event ( GtkWidget *widget,
GdkEventButton *event,
PtkFileBrowser* file_browser );
static gboolean
on_folder_view_popup_menu ( GtkWidget *widget,
PtkFileBrowser* file_browser );
#if 0
static void
on_folder_view_scroll_scrolled ( GtkAdjustment *adjust,
PtkFileBrowser* file_browser );
#endif
static void
on_dir_tree_sel_changed ( GtkTreeSelection *treesel,
PtkFileBrowser* file_browser );
/*
static gboolean
on_location_view_button_press_event ( GtkTreeView* view,
GdkEventButton* evt,
PtkFileBrowser* file_browser );
*/
/* Drag & Drop */
static void
on_folder_view_drag_data_received ( GtkWidget *widget,
GdkDragContext *drag_context,
gint x,
gint y,
GtkSelectionData *sel_data,
guint info,
guint time,
gpointer user_data );
static void
on_folder_view_drag_data_get ( GtkWidget *widget,
GdkDragContext *drag_context,
GtkSelectionData *sel_data,
guint info,
guint time,
PtkFileBrowser *file_browser );
static void
on_folder_view_drag_begin ( GtkWidget *widget,
GdkDragContext *drag_context,
PtkFileBrowser* file_browser );
static gboolean
on_folder_view_drag_motion ( GtkWidget *widget,
GdkDragContext *drag_context,
gint x,
gint y,
guint time,
PtkFileBrowser* file_browser );
static gboolean
on_folder_view_drag_leave ( GtkWidget *widget,
GdkDragContext *drag_context,
guint time,
PtkFileBrowser* file_browser );
static gboolean
on_folder_view_drag_drop ( GtkWidget *widget,
GdkDragContext *drag_context,
gint x,
gint y,
guint time,
PtkFileBrowser* file_browser );
static void
on_folder_view_drag_end ( GtkWidget *widget,
GdkDragContext *drag_context,
PtkFileBrowser* file_browser );
/* Default signal handlers */
static void ptk_file_browser_before_chdir( PtkFileBrowser* file_browser,
const char* path,
gboolean* cancel );
static void ptk_file_browser_after_chdir( PtkFileBrowser* file_browser );
static void ptk_file_browser_content_change( PtkFileBrowser* file_browser );
static void ptk_file_browser_sel_change( PtkFileBrowser* file_browser );
static void ptk_file_browser_open_item( PtkFileBrowser* file_browser, const char* path, int action );
static void ptk_file_browser_pane_mode_change( PtkFileBrowser* file_browser );
void ptk_file_browser_update_views( GtkWidget* item, PtkFileBrowser* file_browser );
void focus_folder_view( PtkFileBrowser* file_browser );
void on_shortcut_new_tab_here( GtkMenuItem* item,
PtkFileBrowser* file_browser );
static void on_show_history_menu( GtkMenuToolButton* btn, PtkFileBrowser* file_browser );
void enable_toolbar( PtkFileBrowser* file_browser );
static int
file_list_order_from_sort_order( PtkFBSortOrder order );
static GtkPanedClass *parent_class = NULL;
enum {
BEFORE_CHDIR_SIGNAL,
BEGIN_CHDIR_SIGNAL,
AFTER_CHDIR_SIGNAL,
OPEN_ITEM_SIGNAL,
CONTENT_CHANGE_SIGNAL,
SEL_CHANGE_SIGNAL,
PANE_MODE_CHANGE_SIGNAL,
N_SIGNALS
};
enum{ //MOD
RESPONSE_RUN = 100,
RESPONSE_RUNTERMINAL = 101,
};
static void enter_callback( GtkEntry* entry, GtkDialog* dlg ); //MOD
static char *replace_str(char *str, char *orig, char *rep); //MOD
void ptk_file_browser_rebuild_toolbox( GtkWidget* widget, PtkFileBrowser* file_browser );
void ptk_file_browser_rebuild_side_toolbox( GtkWidget* widget, PtkFileBrowser* file_browser );
static guint signals[ N_SIGNALS ] = { 0 };
static guint folder_view_auto_scroll_timer = 0;
static GtkDirectionType folder_view_auto_scroll_direction = 0;
/* Drag & Drop/Clipboard targets */
static GtkTargetEntry drag_targets[] = {
{"text/uri-list", 0 , 0 }
};
#define GDK_ACTION_ALL (GDK_ACTION_MOVE|GDK_ACTION_COPY|GDK_ACTION_LINK)
GType ptk_file_browser_get_type()
{
static GType type = G_TYPE_INVALID;
if ( G_UNLIKELY ( type == G_TYPE_INVALID ) )
{
static const GTypeInfo info =
{
sizeof ( PtkFileBrowserClass ),
NULL,
NULL,
( GClassInitFunc ) ptk_file_browser_class_init,
NULL,
NULL,
sizeof ( PtkFileBrowser ),
0,
( GInstanceInitFunc ) ptk_file_browser_init,
NULL,
};
//type = g_type_register_static ( GTK_TYPE_HPANED, "PtkFileBrowser", &info, 0 );
type = g_type_register_static ( GTK_TYPE_VBOX, "PtkFileBrowser", &info, 0 );
}
return type;
}
/* These g_cclosure_marshal functions are from gtkmarshal.c, the deprecated
* functions renamed from gtk_* to g_cclosure_*, to match the naming convention
* of the non-deprecated glib functions. Added for gtk3 port. */
static void
g_cclosure_marshal_VOID__POINTER_POINTER (GClosure *closure,
GValue *return_value G_GNUC_UNUSED,
guint n_param_values,
const GValue *param_values,
gpointer invocation_hint G_GNUC_UNUSED,
gpointer marshal_data)
{
register GCClosure *cc = (GCClosure *) closure;
register gpointer data1, data2;
g_return_if_fail (n_param_values == 3);
if (G_CCLOSURE_SWAP_DATA (closure))
{
data1 = closure->data;
data2 = g_value_peek_pointer (param_values + 0);
}
else
{
data1 = g_value_peek_pointer (param_values + 0);
data2 = closure->data;
}
typedef void (*GMarshalFunc_VOID__POINTER_POINTER) (gpointer data1,
gpointer arg_1,
gpointer arg_2,
gpointer data2);
register GMarshalFunc_VOID__POINTER_POINTER callback = (GMarshalFunc_VOID__POINTER_POINTER) (marshal_data ? marshal_data : cc->callback);
callback (data1,
g_value_get_pointer (param_values + 1),
g_value_get_pointer (param_values + 2),
data2);
}
static void
g_cclosure_marshal_VOID__POINTER_INT (GClosure *closure,
GValue *return_value,
guint n_param_values,
const GValue *param_values,
gpointer invocation_hint,
gpointer marshal_data)
{
typedef void (*GMarshalFunc_VOID__POINTER_INT) (gpointer data1,
gpointer arg_1,
gint arg_2,
gpointer data2);
register GMarshalFunc_VOID__POINTER_INT callback;
register GCClosure *cc = (GCClosure*) closure;
register gpointer data1, data2;
g_return_if_fail (n_param_values == 3);
if (G_CCLOSURE_SWAP_DATA (closure))
{
data1 = closure->data;
data2 = g_value_peek_pointer (param_values + 0);
}
else
{
data1 = g_value_peek_pointer (param_values + 0);
data2 = closure->data;
}
callback = (GMarshalFunc_VOID__POINTER_INT) (marshal_data ? marshal_data : cc->callback);
callback (data1,
g_value_get_pointer (param_values + 1),
g_value_get_int (param_values + 2),
data2);
}
void ptk_file_browser_class_init( PtkFileBrowserClass* klass )
{
GObjectClass * object_class;
GtkWidgetClass *widget_class;
object_class = ( GObjectClass * ) klass;
parent_class = g_type_class_peek_parent ( klass );
object_class->set_property = ptk_file_browser_set_property;
object_class->get_property = ptk_file_browser_get_property;
object_class->finalize = ptk_file_browser_finalize;
widget_class = GTK_WIDGET_CLASS ( klass );
/* Signals */
klass->before_chdir = ptk_file_browser_before_chdir;
klass->after_chdir = ptk_file_browser_after_chdir;
klass->open_item = ptk_file_browser_open_item;
klass->content_change = ptk_file_browser_content_change;
klass->sel_change = ptk_file_browser_sel_change;
klass->pane_mode_change = ptk_file_browser_pane_mode_change;
/* before-chdir is emitted when PtkFileBrowser is about to change
* its working directory. The 1st param is the path of the dir (in UTF-8),
* and the 2nd param is a gboolean*, which can be filled by the
* signal handler with TRUE to cancel the operation.
*/
signals[ BEFORE_CHDIR_SIGNAL ] =
g_signal_new ( "before-chdir",
G_TYPE_FROM_CLASS ( klass ),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET ( PtkFileBrowserClass, before_chdir ),
NULL, NULL,
g_cclosure_marshal_VOID__POINTER_POINTER,
G_TYPE_NONE, 2, G_TYPE_POINTER, G_TYPE_POINTER );
signals[ BEGIN_CHDIR_SIGNAL ] =
g_signal_new ( "begin-chdir",
G_TYPE_FROM_CLASS ( klass ),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET ( PtkFileBrowserClass, begin_chdir ),
NULL, NULL,
g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0 );
signals[ AFTER_CHDIR_SIGNAL ] =
g_signal_new ( "after-chdir",
G_TYPE_FROM_CLASS ( klass ),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET ( PtkFileBrowserClass, after_chdir ),
NULL, NULL,
g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0 );
/*
* This signal is sent when a directory is about to be opened
* arg1 is the path to be opened, and arg2 is the type of action,
* ex: open in tab, open in terminal...etc.
*/
signals[ OPEN_ITEM_SIGNAL ] =
g_signal_new ( "open-item",
G_TYPE_FROM_CLASS ( klass ),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET ( PtkFileBrowserClass, open_item ),
NULL, NULL,
g_cclosure_marshal_VOID__POINTER_INT, G_TYPE_NONE, 2, G_TYPE_POINTER, G_TYPE_INT );
signals[ CONTENT_CHANGE_SIGNAL ] =
g_signal_new ( "content-change",
G_TYPE_FROM_CLASS ( klass ),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET ( PtkFileBrowserClass, content_change ),
NULL, NULL,
g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0 );
signals[ SEL_CHANGE_SIGNAL ] =
g_signal_new ( "sel-change",
G_TYPE_FROM_CLASS ( klass ),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET ( PtkFileBrowserClass, sel_change ),
NULL, NULL,
g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0 );
signals[ PANE_MODE_CHANGE_SIGNAL ] =
g_signal_new ( "pane-mode-change",
G_TYPE_FROM_CLASS ( klass ),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET ( PtkFileBrowserClass, pane_mode_change ),
NULL, NULL,
g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0 );
}
gboolean ptk_file_browser_slider_release( GtkWidget *widget,
GdkEventButton *event,
PtkFileBrowser* file_browser )
{
//printf("ptk_file_browser_slider_release fb=%#x\n", file_browser );
int pos;
gboolean fullscreen = xset_get_b( "main_full" );
XSet* set = xset_get_panel( file_browser->mypanel, "slider_positions" );
if ( widget == file_browser->hpane )
{
pos = gtk_paned_get_position( GTK_PANED( file_browser->hpane ) );
if ( !fullscreen )
{
g_free( set->x );
set->x = g_strdup_printf( "%d", pos );
}
*file_browser->slide_x = pos;
}
else
{
pos = gtk_paned_get_position( GTK_PANED( file_browser->side_vpane_top ) );
if ( !fullscreen )
{
g_free( set->y );
set->y = g_strdup_printf( "%d", pos );
}
*file_browser->slide_y = pos;
pos = gtk_paned_get_position( GTK_PANED( file_browser->side_vpane_bottom ) );
if ( !fullscreen )
{
g_free( set->s );
set->s = g_strdup_printf( "%d", pos );
}
*file_browser->slide_s = pos;
}
//printf("SAVEPOS %d %d\n", xset_get_int_panel( file_browser->mypanel, "slider_positions", "y" ),
// xset_get_int_panel( file_browser->mypanel, "slider_positions", "s" ) );
return FALSE;
}
void on_toolbar_hide( GtkWidget* widget, PtkFileBrowser* file_browser,
GtkWidget* toolbar2 )
{
GtkWidget* toolbar;
int i;
if ( widget )
toolbar = (GtkWidget*)g_object_get_data( G_OBJECT(widget), "toolbar" );
else
toolbar = toolbar2;
if ( !toolbar )
return;
focus_folder_view( file_browser );
if ( toolbar == file_browser->toolbar )
xset_set_b_panel( file_browser->mypanel, "show_toolbox", FALSE );
else
xset_set_b_panel( file_browser->mypanel, "show_sidebar", FALSE );
update_views_all_windows( NULL, file_browser );
}
void on_toolbar_help( GtkWidget* widget, PtkFileBrowser* file_browser )
{
xset_msg_dialog( GTK_WIDGET( file_browser ), 0, _("Toolbar Config Menu Help"), NULL, 0, _("These toolbar config menus allow you to customize the toolbars.\n\nEnter the Left Toolbar, Right Toolbar, or Side Toolbar submenu and right-click on an item to show or hide it, change the icon, or add a custom tool item.\n\nFor more information, click the Help button below."), NULL, "#designmode-toolbars" );
}
void on_toolbar_config_done( GtkWidget* widget, PtkFileBrowser* file_browser )
{
if ( !widget || !file_browser )
return;
if ( !GTK_IS_WIDGET( widget ) )
return;
GtkWidget* toolbar = (GtkWidget*)g_object_get_data( G_OBJECT(widget), "toolbar" );
gtk_widget_destroy( widget );
if ( toolbar == file_browser->toolbar )
rebuild_toolbar_all_windows( 0, file_browser );
else if ( toolbar == file_browser->side_toolbar )
rebuild_toolbar_all_windows( 1, file_browser );
}
void on_toolbar_config( GtkWidget* widget, PtkFileBrowser* file_browser )
{
XSet* set;
if ( !widget || !file_browser )
return;
GtkWidget* toolbar = (GtkWidget*)g_object_get_data( G_OBJECT(widget), "toolbar" );
if ( !toolbar )
return;
focus_folder_view( file_browser );
GtkWidget* popup = gtk_menu_new();
GtkAccelGroup* accel_group = gtk_accel_group_new();
xset_context_new();
// toolbar menus
if ( toolbar == file_browser->toolbar )
{
set = xset_get( "toolbar_left" );
xset_add_menuitem( NULL, file_browser, popup, accel_group, set );
set = xset_get( "toolbar_right" );
xset_add_menuitem( NULL, file_browser, popup, accel_group, set );
xset_add_menuitem( NULL, file_browser, popup, accel_group,
xset_get( "sep_tool1" ) );
}
else if ( toolbar == file_browser->side_toolbar )
{
set = xset_get( "toolbar_side" );
xset_add_menuitem( NULL, file_browser, popup, accel_group, set );
xset_add_menuitem( NULL, file_browser, popup, accel_group,
xset_get( "sep_tool2" ) );
}
else
return;
// Show/Hide Toolbars
if ( toolbar == file_browser->toolbar )
{
set = xset_set_cb_panel( file_browser->mypanel, "show_sidebar",
update_views_all_windows, file_browser );
set->disable = ( !file_browser->side_dir && !file_browser->side_book
&& !file_browser->side_dev );
xset_add_menuitem( NULL, file_browser, popup, accel_group, set );
set = xset_set_cb( "toolbar_hide", on_toolbar_hide, file_browser );
}
else
{
set = xset_set_cb_panel( file_browser->mypanel, "show_toolbox",
update_views_all_windows, file_browser );
xset_add_menuitem( NULL, file_browser, popup, accel_group, set );
set = xset_set_cb( "toolbar_hide_side", on_toolbar_hide, file_browser );
}
xset_set_ob1( set, "toolbar", toolbar );
xset_add_menuitem( NULL, file_browser, popup, accel_group, set );
// Help
if ( toolbar == file_browser->toolbar )
set = xset_get( "sep_tool3" );
else
set = xset_get( "sep_tool4" );
xset_add_menuitem( NULL, file_browser, popup, accel_group, set );
set = xset_set_cb( "toolbar_help", on_toolbar_help, file_browser );
xset_add_menuitem( NULL, file_browser, popup, accel_group, set );
// show
gtk_widget_show_all( GTK_WIDGET( popup ) );
g_object_set_data( G_OBJECT( popup ), "toolbar", toolbar );
g_signal_connect( popup, "selection-done",
G_CALLBACK( on_toolbar_config_done ), file_browser );
g_signal_connect( popup, "key-press-event",
G_CALLBACK( xset_menu_keypress ), NULL );
gtk_menu_popup( GTK_MENU( popup ), NULL, NULL, NULL, NULL, 0, gtk_get_current_event_time() );
}
void on_toggle_sideview( GtkMenuItem* item, PtkFileBrowser* file_browser, int job2 )
{
focus_folder_view( file_browser );
int job;
if ( item )
job = GPOINTER_TO_INT( g_object_get_data( G_OBJECT(item), "job" ) );
else
job = job2;
//printf("on_toggle_sideview %d\n", job);
if ( job == 0 )
xset_set_b_panel( file_browser->mypanel, "show_dirtree",
!xset_get_b_panel( file_browser->mypanel, "show_dirtree" ) );
else if ( job == 1 )
xset_set_b_panel( file_browser->mypanel, "show_book",
!xset_get_b_panel( file_browser->mypanel, "show_book" ) );
else if ( job == 2 )
xset_set_b_panel( file_browser->mypanel, "show_devmon",
!xset_get_b_panel( file_browser->mypanel, "show_devmon" ) );
update_views_all_windows( NULL, file_browser );
}
void ptk_file_browser_rebuild_side_toolbox( GtkWidget* widget,
PtkFileBrowser* file_browser )
{
XSet* set;
// destroy
if ( file_browser->side_toolbar )
gtk_widget_destroy( file_browser->side_toolbar );
// new
file_browser->side_toolbar = gtk_toolbar_new();
gtk_box_pack_start( GTK_BOX( file_browser->side_toolbox ),
file_browser->side_toolbar, TRUE, TRUE, 0 );
gtk_toolbar_set_style( GTK_TOOLBAR( file_browser->side_toolbar ), GTK_TOOLBAR_ICONS );
if ( app_settings.tool_icon_size > 0
&& app_settings.tool_icon_size <= GTK_ICON_SIZE_DIALOG )
gtk_toolbar_set_icon_size( GTK_TOOLBAR( file_browser->side_toolbar ),
app_settings.tool_icon_size );
// config
GtkIconSize icon_size = gtk_toolbar_get_icon_size( GTK_TOOLBAR (
file_browser->side_toolbar ) );
set = xset_set_cb( "toolbar_config", on_toolbar_config, file_browser );
xset_add_toolitem( GTK_WIDGET( file_browser ), file_browser, file_browser->side_toolbar,
icon_size, set );
// callbacks
set = xset_set_cb( "stool_dirtree", on_toggle_sideview, file_browser );
xset_set_b( "stool_dirtree", xset_get_b_panel( file_browser->mypanel,
"show_dirtree" ) );
xset_set_ob1_int( set, "job", 0 );
set->ob2_data = NULL;
set = xset_set_cb( "stool_book", on_toggle_sideview, file_browser );
xset_set_b( "stool_book", xset_get_b_panel( file_browser->mypanel,
"show_book" ) );
xset_set_ob1_int( set, "job", 1 );
set->ob2_data = NULL;
set = xset_set_cb( "stool_device", on_toggle_sideview, file_browser );
xset_set_b( "stool_device", xset_get_b_panel( file_browser->mypanel,
"show_devmon" ) );
xset_set_ob1_int( set, "job", 2 );
set->ob2_data = NULL;
xset_set_cb( "stool_newtab", on_shortcut_new_tab_activate, file_browser );
xset_set_cb( "stool_newtabhere", on_shortcut_new_tab_here, file_browser );
set = xset_set_cb( "stool_back", ptk_file_browser_go_back, file_browser );
set->ob2_data = NULL;
set = xset_set_cb( "stool_backmenu", ptk_file_browser_go_back, file_browser );
set->ob2_data = NULL;
set = xset_set_cb( "stool_forward", ptk_file_browser_go_forward, file_browser );
set->ob2_data = NULL;
set = xset_set_cb( "stool_forwardmenu", ptk_file_browser_go_forward, file_browser );
set->ob2_data = NULL;
set = xset_set_cb( "stool_up", ptk_file_browser_go_up, file_browser );
set->ob2_data = NULL;
xset_set_cb( "stool_refresh", ptk_file_browser_refresh, file_browser );
xset_set_cb( "stool_default", ptk_file_browser_go_default, file_browser );
xset_set_cb( "stool_home", ptk_file_browser_go_home, file_browser );
// side
set = xset_get( "toolbar_side" );
xset_add_toolbar( GTK_WIDGET( file_browser ), file_browser, file_browser->side_toolbar,
set->desc );
// get side buttons
set = xset_get( "stool_dirtree" );
file_browser->toggle_btns_side[0] = set->ob2_data;
set = xset_get( "stool_book" );
file_browser->toggle_btns_side[1] = set->ob2_data;
set = xset_get( "stool_device" );
file_browser->toggle_btns_side[2] = set->ob2_data;
set = xset_get( "stool_backmenu" );
if ( file_browser->back_menu_btn_side = set->ob2_data ) // shown?
g_signal_connect( G_OBJECT(file_browser->back_menu_btn_side), "show-menu",
G_CALLBACK(on_show_history_menu), file_browser );
set = xset_get( "stool_forwardmenu" );
if ( file_browser->forward_menu_btn_side = set->ob2_data )
g_signal_connect( G_OBJECT(file_browser->forward_menu_btn_side), "show-menu",
G_CALLBACK(on_show_history_menu), file_browser );
set = xset_get( "stool_back" );
file_browser->back_btn[2] = set->ob2_data;
set = xset_get( "stool_forward" );
file_browser->forward_btn[2] = set->ob2_data;
set = xset_get( "stool_up" );
file_browser->up_btn[2] = set->ob2_data;
// show
if ( xset_get_b_panel( file_browser->mypanel, "show_sidebar" ) )
gtk_widget_show_all( file_browser->side_toolbox );
enable_toolbar( file_browser );
}
void ptk_file_browser_select_file( PtkFileBrowser* file_browser, char* path )
{
GtkTreeIter it;
GtkTreePath* tree_path;
GtkTreeSelection* tree_sel;
GtkTreeModel* model = NULL;
VFSFileInfo* file;
const char* file_name;
PtkFileList* list = PTK_FILE_LIST( file_browser->file_list );
if ( file_browser->view_mode == PTK_FB_ICON_VIEW
|| file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
exo_icon_view_unselect_all( EXO_ICON_VIEW( file_browser->folder_view ) );
model = exo_icon_view_get_model( EXO_ICON_VIEW( file_browser->folder_view ) );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
model = gtk_tree_view_get_model( GTK_TREE_VIEW( file_browser->folder_view ) );
tree_sel = gtk_tree_view_get_selection( GTK_TREE_VIEW(
file_browser->folder_view ) );
gtk_tree_selection_unselect_all( tree_sel );
}
if ( !model )
return;
char* name = g_path_get_basename( path );
if ( gtk_tree_model_get_iter_first( model, &it ) )
{
do
{
gtk_tree_model_get( model, &it, COL_FILE_INFO, &file, -1 );
if ( file )
{
file_name = vfs_file_info_get_name( file );
if ( !strcmp( file_name, name ) )
{
tree_path = gtk_tree_model_get_path( GTK_TREE_MODEL(list), &it );
if ( file_browser->view_mode == PTK_FB_ICON_VIEW
|| file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
exo_icon_view_select_path( EXO_ICON_VIEW(
file_browser->folder_view ), tree_path );
exo_icon_view_set_cursor( EXO_ICON_VIEW(
file_browser->folder_view ), tree_path, NULL, FALSE );
exo_icon_view_scroll_to_path( EXO_ICON_VIEW(
file_browser->folder_view ), tree_path, TRUE, .25, 0 );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
gtk_tree_selection_select_path( tree_sel, tree_path );
gtk_tree_view_set_cursor(GTK_TREE_VIEW( file_browser->folder_view ),
tree_path, NULL, FALSE);
gtk_tree_view_scroll_to_cell( GTK_TREE_VIEW( file_browser->folder_view ),
tree_path, NULL, TRUE, .25, 0 );
}
gtk_tree_path_free( tree_path );
vfs_file_info_unref( file );
break;
}
vfs_file_info_unref( file );
}
}
while ( gtk_tree_model_iter_next( model, &it ) );
}
g_free( name );
}
void save_command_history( GtkEntry* entry )
{
GList* l;
EntryData* edata = (EntryData*)g_object_get_data( G_OBJECT( entry ), "edata" );
if ( !edata )
return;
const char* text = gtk_entry_get_text( GTK_ENTRY( entry ) );
// remove duplicates
while ( l = g_list_find_custom( xset_cmd_history, text, (GCompareFunc)g_strcmp0 ) )
{
g_free( (char*)l->data );
xset_cmd_history = g_list_delete_link( xset_cmd_history, l );
}
xset_cmd_history = g_list_prepend( xset_cmd_history, g_strdup( text ) );
// shorten to 200 entries
while ( g_list_length( xset_cmd_history ) > 200 )
{
l = g_list_last( xset_cmd_history );
g_free( (char*)l->data );
xset_cmd_history = g_list_delete_link( xset_cmd_history, l );
}
}
gboolean on_address_bar_focus_in( GtkWidget *entry, GdkEventFocus* evt,
PtkFileBrowser* file_browser )
{
ptk_file_browser_focus_me( file_browser );
return FALSE;
}
void on_address_bar_activate( GtkWidget* entry, PtkFileBrowser* file_browser )
{
const char* text;
gchar *dir_path, *final_path;
GList* l;
char* str;
text = gtk_entry_get_text( GTK_ENTRY( entry ) );
gtk_editable_select_region( (GtkEditable*)entry, 0, 0 ); // clear selection
// Convert to on-disk encoding
dir_path = g_filename_from_utf8( text, -1, NULL, NULL, NULL );
final_path = vfs_file_resolve_path( ptk_file_browser_get_cwd( file_browser ),
dir_path );
g_free( dir_path );
if ( text[0] == '\0' )
{
g_free( final_path );
return;
}
if ( !g_file_test( final_path, G_FILE_TEST_EXISTS ) &&
( text[0] == '$' || text[0] == '+' || text[0] == '&'
|| text[0] == '!' || text[0] == '\0' ) )
{
// command
char* command;
char* trim_command;
gboolean as_root = FALSE;
gboolean in_terminal = FALSE;
gboolean as_task = TRUE;
char* prefix = g_strdup( "" );
while ( text[0] == '$' || text[0] == '+' || text[0] == '&' || text[0] == '!' )
{
if ( text[0] == '+' )
in_terminal = TRUE;
else if ( text[0] == '&' )
as_task = FALSE;
else if ( text[0] == '!' )
as_root = TRUE;
str = prefix;
prefix = g_strdup_printf( "%s%c", str, text[0] );
g_free( str );
text++;
}
gboolean is_space = text[0] == ' ';
command = g_strdup( text );
trim_command = g_strstrip( command );
if ( trim_command[0] == '\0' )
{
g_free( command );
g_free( prefix );
ptk_path_entry_help( entry, GTK_WIDGET( file_browser ) );
gtk_editable_set_position( GTK_EDITABLE( entry ), -1 );
return;
}
save_command_history( GTK_ENTRY( entry ) );
// task
char* task_name = g_strdup( gtk_entry_get_text( GTK_ENTRY( entry ) ) );
const char* cwd = ptk_file_browser_get_cwd( file_browser );
PtkFileTask* task = ptk_file_exec_new( task_name, cwd, GTK_WIDGET( file_browser ),
file_browser->task_view );
g_free( task_name );
// don't free cwd!
task->task->exec_browser = file_browser;
task->task->exec_command = replace_line_subs( trim_command );
g_free( command );
if ( as_root )
task->task->exec_as_user = g_strdup_printf( "root" );
if ( !as_task )
task->task->exec_sync = FALSE;
else
task->task->exec_sync = !in_terminal;
task->task->exec_show_output = TRUE;
task->task->exec_show_error = TRUE;
task->task->exec_export = TRUE;
task->task->exec_terminal = in_terminal;
task->task->exec_keep_terminal = as_task;
//task->task->exec_keep_tmp = TRUE;
ptk_file_task_run( task );
//gtk_widget_grab_focus( GTK_WIDGET( file_browser->folder_view ) );
// reset entry text
str = prefix;
prefix = g_strdup_printf( "%s%s", str, is_space ? " " : "" );
g_free( str );
gtk_entry_set_text( GTK_ENTRY( entry ), prefix );
g_free( prefix );
gtk_editable_set_position( GTK_EDITABLE( entry ), -1 );
}
else if ( !g_file_test( final_path, G_FILE_TEST_EXISTS ) && text[0] == '%' )
{
str = g_strdup( ++text );
g_strstrip( str );
if ( str && str[0] != '\0' )
{
save_command_history( GTK_ENTRY( entry ) );
ptk_file_browser_select_pattern( NULL, file_browser, str );
}
g_free( str );
}
else if ( ( text[0] != '/' && strstr( text, ":/" ) ) || g_str_has_prefix( text, "//" ) )
{
save_command_history( GTK_ENTRY( entry ) );
str = g_strdup( text );
mount_network( file_browser, str, FALSE );
g_free( str );
return;
}
else
{
// path?
// clean double slashes
while ( strstr( final_path, "//" ) )
{
str = final_path;
final_path = replace_string( str, "//", "/", FALSE );
g_free( str );
}
if ( g_file_test( final_path, G_FILE_TEST_IS_DIR ) )
{
// open dir
if ( strcmp( final_path, ptk_file_browser_get_cwd( file_browser ) ) )
ptk_file_browser_chdir( file_browser, final_path, PTK_FB_CHDIR_ADD_HISTORY );
gtk_widget_grab_focus( GTK_WIDGET( file_browser->folder_view ) );
}
else if ( g_file_test( final_path, G_FILE_TEST_EXISTS ) )
{
// open dir and select file
dir_path = g_path_get_dirname( final_path );
if ( strcmp( dir_path, ptk_file_browser_get_cwd( file_browser ) ) )
{
file_browser->select_path = strdup( final_path );
ptk_file_browser_chdir( file_browser, dir_path, PTK_FB_CHDIR_ADD_HISTORY );
}
else
ptk_file_browser_select_file( file_browser, final_path );
g_free( dir_path );
gtk_widget_grab_focus( GTK_WIDGET( file_browser->folder_view ) );
}
gtk_editable_set_position( GTK_EDITABLE( entry ), -1 );
// inhibit auto seek because if multiple completions will change dir
EntryData* edata = (EntryData*)g_object_get_data(
G_OBJECT( entry ), "edata" );
if ( edata && edata->seek_timer )
{
g_source_remove( edata->seek_timer );
edata->seek_timer = 0;
}
}
g_free( final_path );
}
void ptk_file_browser_rebuild_toolbox( GtkWidget* widget, PtkFileBrowser* file_browser )
{
//printf(" ptk_file_browser_rebuild_toolbox\n");
XSet* set;
if ( !file_browser )
return;
// destroy
if ( file_browser->toolbar )
{
if ( GTK_IS_WIDGET( file_browser->toolbar ) )
{
//printf("gtk_widget_destroy( file_browser->toolbar = %#x )\n",
// file_browser->toolbar );
// crashing here? http://sourceforge.net/p/spacefm/tickets/88000/?page=0
gtk_widget_destroy( file_browser->toolbar );
//printf(" DONE\n" );
}
file_browser->toolbar = NULL;
file_browser->path_bar = NULL;
}
if ( !file_browser->path_bar )
{
file_browser->path_bar = ptk_path_entry_new( file_browser );
g_signal_connect( file_browser->path_bar, "activate",
G_CALLBACK(on_address_bar_activate), file_browser );
g_signal_connect( file_browser->path_bar, "focus-in-event",
G_CALLBACK(on_address_bar_focus_in), file_browser );
}
// new
file_browser->toolbar = gtk_toolbar_new();
gtk_box_pack_start( GTK_BOX( file_browser->toolbox ), file_browser->toolbar,
TRUE, TRUE, 0 );
gtk_toolbar_set_style( GTK_TOOLBAR( file_browser->toolbar ), GTK_TOOLBAR_ICONS );
if ( app_settings.tool_icon_size > 0
&& app_settings.tool_icon_size <= GTK_ICON_SIZE_DIALOG )
gtk_toolbar_set_icon_size( GTK_TOOLBAR( file_browser->toolbar ),
app_settings.tool_icon_size );
// config
GtkIconSize icon_size = gtk_toolbar_get_icon_size( GTK_TOOLBAR (
file_browser->toolbar ) );
set = xset_set_cb( "toolbar_config", on_toolbar_config, file_browser );
xset_add_toolitem( GTK_WIDGET( file_browser ), file_browser,
file_browser->toolbar, icon_size, set );
// callbacks
set = xset_set_cb( "tool_dirtree", on_toggle_sideview, file_browser );
xset_set_b( "tool_dirtree", xset_get_b_panel( file_browser->mypanel,
"show_dirtree" ) );
xset_set_ob1_int( set, "job", 0 );
set->ob2_data = NULL;
set = xset_set_cb( "tool_book", on_toggle_sideview, file_browser );
xset_set_b( "tool_book", xset_get_b_panel( file_browser->mypanel,
"show_book" ) );
xset_set_ob1_int( set, "job", 1 );
set->ob2_data = NULL;
set = xset_set_cb( "tool_device", on_toggle_sideview, file_browser );
xset_set_b( "tool_device", xset_get_b_panel( file_browser->mypanel,
"show_devmon" ) );
xset_set_ob1_int( set, "job", 2 );
set->ob2_data = NULL;
xset_set_cb( "tool_newtab", on_shortcut_new_tab_activate, file_browser );
xset_set_cb( "tool_newtabhere", on_shortcut_new_tab_here, file_browser );
set = xset_set_cb( "tool_back", ptk_file_browser_go_back, file_browser );
set->ob2_data = NULL;
set = xset_set_cb( "tool_backmenu", ptk_file_browser_go_back, file_browser );
set->ob2_data = NULL;
set = xset_set_cb( "tool_forward", ptk_file_browser_go_forward, file_browser );
set->ob2_data = NULL;
set = xset_set_cb( "tool_forwardmenu", ptk_file_browser_go_forward, file_browser );
set->ob2_data = NULL;
set = xset_set_cb( "tool_up", ptk_file_browser_go_up, file_browser );
set->ob2_data = NULL;
xset_set_cb( "tool_refresh", ptk_file_browser_refresh, file_browser );
xset_set_cb( "tool_default", ptk_file_browser_go_default, file_browser );
xset_set_cb( "tool_home", ptk_file_browser_go_home, file_browser );
// left
set = xset_get( "toolbar_left" );
xset_add_toolbar( GTK_WIDGET( file_browser ), file_browser,
file_browser->toolbar, set->desc );
// get left buttons
set = xset_get( "tool_dirtree" );
file_browser->toggle_btns_left[0] = set->ob2_data;
set = xset_get( "tool_book" );
file_browser->toggle_btns_left[1] = set->ob2_data;
set = xset_get( "tool_device" );
file_browser->toggle_btns_left[2] = set->ob2_data;
set = xset_get( "tool_backmenu" );
if ( file_browser->back_menu_btn_left = set->ob2_data )
g_signal_connect( G_OBJECT(file_browser->back_menu_btn_left), "show-menu",
G_CALLBACK(on_show_history_menu), file_browser );
set = xset_get( "tool_forwardmenu" );
if ( file_browser->forward_menu_btn_left = set->ob2_data )
g_signal_connect( G_OBJECT(file_browser->forward_menu_btn_left), "show-menu",
G_CALLBACK(on_show_history_menu), file_browser );
set = xset_get( "tool_back" );
file_browser->back_btn[0] = set->ob2_data;
set = xset_get( "tool_forward" );
file_browser->forward_btn[0] = set->ob2_data;
set = xset_get( "tool_up" );
file_browser->up_btn[0] = set->ob2_data;
// pathbar
GtkWidget* hbox = gtk_hbox_new( FALSE, 0 );
GtkToolItem* toolitem = gtk_tool_item_new();
gtk_tool_item_set_expand ( toolitem, TRUE );
gtk_toolbar_insert( GTK_TOOLBAR( file_browser->toolbar ), toolitem, -1 );
gtk_container_add ( GTK_CONTAINER ( toolitem ), hbox );
gtk_box_pack_start( GTK_BOX ( hbox ), GTK_WIDGET( file_browser->path_bar ),
TRUE, TRUE, 5 );
// callbacks right
set = xset_set_cb( "rtool_dirtree", on_toggle_sideview, file_browser );
xset_set_b( "rtool_dirtree", xset_get_b_panel( file_browser->mypanel, "show_dirtree" ) );
xset_set_ob1_int( set, "job", 0 );
set->ob2_data = NULL;
set = xset_set_cb( "rtool_book", on_toggle_sideview, file_browser );
xset_set_b( "rtool_book", xset_get_b_panel( file_browser->mypanel, "show_book" ) );
xset_set_ob1_int( set, "job", 1 );
set->ob2_data = NULL;
set = xset_set_cb( "rtool_device", on_toggle_sideview, file_browser );
xset_set_b( "rtool_device", xset_get_b_panel( file_browser->mypanel, "show_devmon" ) );
xset_set_ob1_int( set, "job", 2 );
set->ob2_data = NULL;
xset_set_cb( "rtool_newtab", on_shortcut_new_tab_activate, file_browser );
xset_set_cb( "rtool_newtabhere", on_shortcut_new_tab_here, file_browser );
set = xset_set_cb( "rtool_back", ptk_file_browser_go_back, file_browser );
set->ob2_data = NULL;
set = xset_set_cb( "rtool_backmenu", ptk_file_browser_go_back, file_browser );
set->ob2_data = NULL;
set = xset_set_cb( "rtool_forward", ptk_file_browser_go_forward, file_browser );
set->ob2_data = NULL;
set = xset_set_cb( "rtool_forwardmenu", ptk_file_browser_go_forward, file_browser );
set->ob2_data = NULL;
set = xset_set_cb( "rtool_up", ptk_file_browser_go_up, file_browser );
set->ob2_data = NULL;
xset_set_cb( "rtool_refresh", ptk_file_browser_refresh, file_browser );
xset_set_cb( "rtool_default", ptk_file_browser_go_default, file_browser );
xset_set_cb( "rtool_home", ptk_file_browser_go_home, file_browser );
// right
set = xset_get( "rtool_backmenu" );
set->ob2_data = NULL;
set = xset_get( "rtool_forwardmenu" );
set->ob2_data = NULL;
set = xset_get( "toolbar_right" );
xset_add_toolbar( GTK_WIDGET( file_browser ), file_browser, file_browser->toolbar, set->desc );
// get right buttons
set = xset_get( "rtool_dirtree" );
file_browser->toggle_btns_right[0] = set->ob2_data;
set = xset_get( "rtool_book" );
file_browser->toggle_btns_right[1] = set->ob2_data;
set = xset_get( "rtool_device" );
file_browser->toggle_btns_right[2] = set->ob2_data;
set = xset_get( "rtool_backmenu" );
if ( file_browser->back_menu_btn_right = set->ob2_data )
g_signal_connect( G_OBJECT(file_browser->back_menu_btn_right), "show-menu",
G_CALLBACK(on_show_history_menu), file_browser );
set = xset_get( "rtool_forwardmenu" );
if ( file_browser->forward_menu_btn_right = set->ob2_data )
g_signal_connect( G_OBJECT(file_browser->forward_menu_btn_right), "show-menu",
G_CALLBACK(on_show_history_menu), file_browser );
set = xset_get( "rtool_back" );
file_browser->back_btn[1] = set->ob2_data;
set = xset_get( "rtool_forward" );
file_browser->forward_btn[1] = set->ob2_data;
set = xset_get( "rtool_up" );
file_browser->up_btn[1] = set->ob2_data;
// show
if ( xset_get_b_panel( file_browser->mypanel, "show_toolbox" ) )
gtk_widget_show_all( file_browser->toolbox );
enable_toolbar( file_browser );
}
void ptk_file_browser_status_change( PtkFileBrowser* file_browser, gboolean panel_focus )
{
char* scolor;
GdkColor color;
// image
gtk_widget_set_sensitive( GTK_WIDGET( file_browser->status_image ), panel_focus );
// text color
if ( panel_focus )
{
scolor = xset_get_s( "status_text" );
if ( scolor && gdk_color_parse( scolor, &color ) )
gtk_widget_modify_fg( GTK_WIDGET( file_browser->status_label ),
GTK_STATE_NORMAL, &color );
else
gtk_widget_modify_fg( GTK_WIDGET( file_browser->status_label ),
GTK_STATE_NORMAL, NULL );
}
else
gtk_widget_modify_fg( GTK_WIDGET( file_browser->status_label ),
GTK_STATE_NORMAL, NULL );
// frame border color
if ( panel_focus )
{
scolor = xset_get_s( "status_border" );
if ( scolor && gdk_color_parse( scolor, &color ) )
gtk_widget_modify_bg( GTK_WIDGET( file_browser->status_frame ),
GTK_STATE_NORMAL, &color );
else
gtk_widget_modify_bg( GTK_WIDGET( file_browser->status_frame ),
GTK_STATE_NORMAL, NULL );
// below caused visibility issues with some themes
//gtk_widget_modify_bg( file_browser->status_frame, GTK_STATE_NORMAL,
// >K_WIDGET( file_browser->status_frame )
// ->style->fg[ GTK_STATE_SELECTED ] );
}
else
gtk_widget_modify_bg( GTK_WIDGET( file_browser->status_frame ),
GTK_STATE_NORMAL, NULL );
}
gboolean on_status_bar_button_press( GtkWidget *widget,
GdkEventButton *event,
PtkFileBrowser* file_browser )
{
focus_folder_view( file_browser );
if ( event->type == GDK_BUTTON_PRESS )
{
if ( ( evt_win_click->s || evt_win_click->ob2_data ) &&
main_window_event( file_browser->main_window, evt_win_click, "evt_win_click",
0, 0, "statusbar", 0, event->button, event->state,
TRUE ) )
return TRUE;
if ( event->button == 2 )
{
const char* setname[] =
{
"status_name",
"status_path",
"status_info",
"status_hide"
};
int i;
for ( i = 0; i < G_N_ELEMENTS( setname ); i++ )
{
if ( xset_get_b( setname[i] ) )
{
if ( i < 2 )
{
GList* sel_files = ptk_file_browser_get_selected_files(
file_browser );
if ( !sel_files )
return TRUE;
if ( i == 0 )
ptk_clipboard_copy_name( ptk_file_browser_get_cwd(
file_browser ), sel_files );
else
ptk_clipboard_copy_as_text( ptk_file_browser_get_cwd(
file_browser ), sel_files );
g_list_foreach( sel_files, ( GFunc ) vfs_file_info_unref, NULL );
g_list_free( sel_files );
}
else if ( i == 2 )
ptk_file_browser_file_properties( file_browser, 0 );
else if ( i == 3 )
focus_panel( NULL, file_browser->main_window, -3 );
}
}
return TRUE;
}
}
return FALSE;
}
void on_status_effect_change( GtkMenuItem* item, PtkFileBrowser* file_browser )
{
main_update_fonts( NULL, file_browser );
set_panel_focus( NULL, file_browser );
}
void on_status_middle_click_config( GtkMenuItem *menuitem, XSet* set )
{
const char* setname[] =
{
"status_name",
"status_path",
"status_info",
"status_hide"
};
int i;
for ( i = 0; i < G_N_ELEMENTS( setname ); i++ )
{
if ( !strcmp( set->name, setname[i] ) )
set->b = XSET_B_TRUE;
else
xset_set_b( setname[i], FALSE );
}
}
void on_status_bar_popup( GtkWidget *widget, GtkWidget *menu,
PtkFileBrowser* file_browser )
{
XSet* set_radio;
XSetContext* context = xset_context_new();
main_context_fill( file_browser, context );
GtkAccelGroup* accel_group = gtk_accel_group_new();
char* desc = g_strdup_printf( "sep_bar1 status_border status_text panel%d_icon_status panel%d_font_status status_middle", file_browser->mypanel, file_browser->mypanel );
xset_set_cb( "status_border", on_status_effect_change, file_browser );
xset_set_cb( "status_text", on_status_effect_change, file_browser );
xset_set_cb_panel( file_browser->mypanel, "icon_status",
on_status_effect_change, file_browser );
xset_set_cb_panel( file_browser->mypanel, "font_status",
on_status_effect_change, file_browser );
XSet* set = xset_get( "status_name" );
xset_set_cb( "status_name", on_status_middle_click_config, set );
xset_set_ob2( set, NULL, NULL );
set_radio = set;
set = xset_get( "status_path" );
xset_set_cb( "status_path", on_status_middle_click_config, set );
xset_set_ob2( set, NULL, set_radio );
set = xset_get( "status_info" );
xset_set_cb( "status_info", on_status_middle_click_config, set );
xset_set_ob2( set, NULL, set_radio );
set = xset_get( "status_hide" );
xset_set_cb( "status_hide", on_status_middle_click_config, set );
xset_set_ob2( set, NULL, set_radio );
xset_add_menu( NULL, file_browser, menu, accel_group, desc );
g_free( desc );
gtk_widget_show_all( menu );
g_signal_connect( menu, "key-press-event",
G_CALLBACK( xset_menu_keypress ), NULL );
}
/*
static gboolean on_status_bar_key_press( GtkWidget* widget, GdkEventKey* event,
gpointer user_data)
{
printf( "on_status_bar_key_press\n");
return FALSE;
}
*/
void ptk_file_browser_init( PtkFileBrowser* file_browser )
{
// toolbox
file_browser->path_bar = NULL;
file_browser->toolbar = NULL;
file_browser->toolbox = gtk_hbox_new( FALSE, 0 );
gtk_box_pack_start( GTK_BOX ( file_browser ), file_browser->toolbox, FALSE,
FALSE, 0 );
ptk_file_browser_rebuild_toolbox( NULL, file_browser );
// lists area
file_browser->hpane = gtk_hpaned_new();
file_browser->side_vbox = gtk_vbox_new( FALSE, 0 );
gtk_widget_set_size_request( file_browser->side_vbox, 140, -1 );
file_browser->folder_view_scroll = gtk_scrolled_window_new( NULL, NULL );
gtk_paned_pack1 ( GTK_PANED( file_browser->hpane ), file_browser->side_vbox,
FALSE, FALSE );
gtk_paned_pack2 ( GTK_PANED( file_browser->hpane ),
file_browser->folder_view_scroll, TRUE, TRUE );
// fill side
file_browser->side_toolbox = gtk_hbox_new( FALSE, 0 );
file_browser->side_toolbar = NULL;
file_browser->side_vpane_top = gtk_vpaned_new();
file_browser->side_vpane_bottom = gtk_vpaned_new();
file_browser->side_dir_scroll = gtk_scrolled_window_new( NULL, NULL );
file_browser->side_book_scroll = gtk_scrolled_window_new( NULL, NULL );
file_browser->side_dev_scroll = gtk_scrolled_window_new( NULL, NULL );
gtk_box_pack_start ( GTK_BOX( file_browser->side_vbox ),
file_browser->side_toolbox,
FALSE, FALSE, 0 );
gtk_box_pack_start ( GTK_BOX( file_browser->side_vbox ),
file_browser->side_vpane_top,
TRUE, TRUE, 0 );
#if GTK_CHECK_VERSION (3, 0, 0)
// see https://github.com/BwackNinja/spacefm/issues/21
gtk_paned_pack1 ( GTK_PANED( file_browser->side_vpane_top ),
file_browser->side_dev_scroll,
TRUE, FALSE );
gtk_paned_pack2 ( GTK_PANED( file_browser->side_vpane_top ),
file_browser->side_vpane_bottom,
TRUE, FALSE );
gtk_paned_pack1 ( GTK_PANED( file_browser->side_vpane_bottom ),
file_browser->side_book_scroll,
TRUE, FALSE );
gtk_paned_pack2 ( GTK_PANED( file_browser->side_vpane_bottom ),
file_browser->side_dir_scroll,
TRUE, FALSE );
#else
gtk_paned_pack1 ( GTK_PANED( file_browser->side_vpane_top ),
file_browser->side_dev_scroll,
TRUE, TRUE );
gtk_paned_pack2 ( GTK_PANED( file_browser->side_vpane_top ),
file_browser->side_vpane_bottom,
TRUE, TRUE );
gtk_paned_pack1 ( GTK_PANED( file_browser->side_vpane_bottom ),
file_browser->side_book_scroll,
TRUE, TRUE );
gtk_paned_pack2 ( GTK_PANED( file_browser->side_vpane_bottom ),
file_browser->side_dir_scroll,
TRUE, TRUE );
#endif
// status bar
file_browser->status_bar = gtk_statusbar_new();
GList* children = gtk_container_get_children( GTK_CONTAINER( file_browser->status_bar ) );
file_browser->status_frame = GTK_FRAME( children->data );
g_list_free( children );
children = gtk_container_get_children(
GTK_CONTAINER( gtk_statusbar_get_message_area( GTK_STATUSBAR(
file_browser->status_bar ) ) ) );
file_browser->status_label = GTK_LABEL( children->data );
g_list_free( children );
file_browser->status_image = xset_get_image( "gtk-yes", GTK_ICON_SIZE_MENU ); //don't know panel yet
gtk_box_pack_start ( GTK_BOX( file_browser->status_bar ), file_browser->status_image,
FALSE, FALSE, 0 );
gtk_label_set_selectable( file_browser->status_label, TRUE ); // required for button event
gtk_widget_set_can_focus( GTK_WIDGET( file_browser->status_label ), FALSE );
#if GTK_CHECK_VERSION (3, 0, 0)
gtk_widget_set_hexpand( GTK_WIDGET( file_browser->status_label ), TRUE );
gtk_widget_set_halign( GTK_WIDGET( file_browser->status_label ), GTK_ALIGN_FILL );
gtk_misc_set_alignment( GTK_MISC( file_browser->status_label ), 0, 0.5 );
#endif
g_signal_connect( G_OBJECT( file_browser->status_label ), "button-press-event",
G_CALLBACK( on_status_bar_button_press ), file_browser );
g_signal_connect( G_OBJECT( file_browser->status_label ), "populate-popup",
G_CALLBACK( on_status_bar_popup ), file_browser );
//g_signal_connect( G_OBJECT( file_browser->status_label ), "key-press-event",
// G_CALLBACK( on_status_bar_key_press ), file_browser );
if ( xset_get_s_panel( file_browser->mypanel, "font_status" ) )
{
PangoFontDescription* font_desc = pango_font_description_from_string(
xset_get_s_panel( file_browser->mypanel, "font_status" ) );
gtk_widget_modify_font( GTK_WIDGET( file_browser->status_label ), font_desc );
pango_font_description_free( font_desc );
}
// pack fb vbox
gtk_box_pack_start( GTK_BOX ( file_browser ), file_browser->hpane, TRUE, TRUE, 0 );
// TODO pack task frames
gtk_box_pack_start( GTK_BOX ( file_browser ), file_browser->status_bar, FALSE, FALSE, 0 );
gtk_scrolled_window_set_policy ( GTK_SCROLLED_WINDOW ( file_browser->folder_view_scroll ),
GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS );
gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( file_browser->side_dir_scroll ),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC );
gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( file_browser->side_book_scroll ),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC );
gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( file_browser->side_dev_scroll ),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC );
g_signal_connect( file_browser->hpane, "button-release-event",
G_CALLBACK( ptk_file_browser_slider_release ), file_browser );
g_signal_connect( file_browser->side_vpane_top, "button-release-event",
G_CALLBACK( ptk_file_browser_slider_release ), file_browser );
g_signal_connect( file_browser->side_vpane_bottom, "button-release-event",
G_CALLBACK( ptk_file_browser_slider_release ), file_browser );
/*
// these work but fire too often
g_signal_connect( file_browser->hpane, "notify::position",
G_CALLBACK( on_slider_change ), file_browser );
g_signal_connect( file_browser->side_vpane_top, "notify::position",
G_CALLBACK( on_slider_change ), file_browser );
g_signal_connect( file_browser->side_vpane_bottom, "notify::position",
G_CALLBACK( on_slider_change ), file_browser );
*/
}
void ptk_file_browser_finalize( GObject *obj )
{
PtkFileBrowser * file_browser = PTK_FILE_BROWSER( obj );
//printf("ptk_file_browser_finalize\n");
if ( file_browser->dir )
{
g_signal_handlers_disconnect_matched( file_browser->dir,
G_SIGNAL_MATCH_DATA,
0, 0, NULL, NULL,
file_browser );
g_object_unref( file_browser->dir );
}
/* Remove all idle handlers which are not called yet. */
do
{}
while ( g_source_remove_by_user_data( file_browser ) );
if ( file_browser->file_list )
{
g_signal_handlers_disconnect_matched( file_browser->file_list,
G_SIGNAL_MATCH_DATA,
0, 0, NULL, NULL,
file_browser );
g_object_unref( G_OBJECT( file_browser->file_list ) );
}
g_free( file_browser->status_bar_custom );
g_free( file_browser->seek_name );
file_browser->seek_name = NULL;
g_free( file_browser->select_path );
file_browser->select_path = NULL;
G_OBJECT_CLASS( parent_class ) ->finalize( obj );
}
void ptk_file_browser_get_property ( GObject *obj,
guint prop_id,
GValue *value,
GParamSpec *pspec )
{}
void ptk_file_browser_set_property ( GObject *obj,
guint prop_id,
const GValue *value,
GParamSpec *pspec )
{}
/* File Browser API */
/*
static gboolean side_pane_chdir( PtkFileBrowser* file_browser,
const char* folder_path )
{
if ( file_browser->side_dir )
return ptk_dir_tree_view_chdir( file_browser->side_dir, folder_path );
if ( file_browser->side_dev )
{
ptk_location_view_chdir( file_browser->side_dev, folder_path );
return TRUE;
}
if ( file_browser->side_pane_mode == PTK_FB_SIDE_PANE_BOOKMARKS )
{
ptk_location_view_chdir( file_browser->side_view, folder_path );
return TRUE;
}
else if ( file_browser->side_pane_mode == PTK_FB_SIDE_PANE_DIR_TREE )
{
return ptk_dir_tree_view_chdir( file_browser->side_view, folder_path );
}
return FALSE;
}
*/
/*
void create_side_views( PtkFileBrowser* file_browser, int mode )
{
GtkScrolledWindow* scroll;
GtkTreeView* view;
if ( !mode )
{
scroll = file_browser->side_dir_scroll;
view = file_browser->side_dir;
if ( !view )
view = ptk_file_browser_create_dir_tree( file_browser );
}
else if ( mode == 1 )
{
scroll = file_browser->side_book_scroll;
view = file_browser->side_book;
//if ( !view )
// view = ptk_file_browser_create_bookmarks_view( file_browser );
}
else
{
scroll = file_browser->side_dev_scroll;
view = file_browser->side_dev;
if ( !view )
view = ptk_file_browser_create_location_view( file_browser );
}
}
*/
void ptk_file_browser_update_views( GtkWidget* item, PtkFileBrowser* file_browser )
{
int i;
//printf("ptk_file_browser_update_views fb=%#x\n", file_browser );
FMMainWindow* main_window = (FMMainWindow*)file_browser->main_window;
// hide/show browser widgets based on user settings
int p = file_browser->mypanel;
if ( xset_get_b_panel( p, "show_toolbox" ) )
{
if ( ( evt_pnl_show->s || evt_pnl_show->ob2_data ) &&
( !file_browser->toolbox ||
!gtk_widget_get_visible( file_browser->toolbox ) ) )
main_window_event( main_window, evt_pnl_show, "evt_pnl_show", 0, 0,
"toolbar", 0, 0, 0, TRUE );
if ( !file_browser->toolbox )
ptk_file_browser_rebuild_toolbox( NULL, file_browser );
gtk_widget_show_all( file_browser->toolbox );
}
else
{
if ( ( evt_pnl_show->s || evt_pnl_show->ob2_data ) &&
file_browser->toolbox &&
gtk_widget_get_visible( file_browser->toolbox ) )
main_window_event( main_window, evt_pnl_show, "evt_pnl_show", 0, 0,
"toolbar", 0, 0, 0, FALSE );
gtk_widget_hide( file_browser->toolbox );
}
if ( xset_get_b_panel( p, "show_sidebar" ) )
{
if ( ( evt_pnl_show->s || evt_pnl_show->ob2_data ) &&
( !file_browser->side_toolbox ||
!gtk_widget_get_visible( file_browser->side_toolbox ) ) )
main_window_event( main_window, evt_pnl_show, "evt_pnl_show", 0, 0,
"sidetoolbar", 0, 0, 0, TRUE );
if ( !file_browser->side_toolbar )
ptk_file_browser_rebuild_side_toolbox( NULL, file_browser );
gtk_widget_show_all( file_browser->side_toolbox );
}
else
{
if ( ( evt_pnl_show->s || evt_pnl_show->ob2_data ) &&
file_browser->side_toolbar &&
file_browser->side_toolbox &&
gtk_widget_get_visible( file_browser->side_toolbox ) )
main_window_event( main_window, evt_pnl_show, "evt_pnl_show", 0, 0,
"sidetoolbar", 0, 0, 0, FALSE );
if ( file_browser->side_toolbar )
{
gtk_widget_destroy( file_browser->side_toolbar );
file_browser->side_toolbar = NULL;
for ( i = 0; i < 3; i++ )
file_browser->toggle_btns_side[i] = NULL;
}
gtk_widget_hide( file_browser->side_toolbox );
}
if ( xset_get_b_panel( p, "show_dirtree" ) )
{
if ( ( evt_pnl_show->s || evt_pnl_show->ob2_data ) &&
( !file_browser->side_dir_scroll ||
!gtk_widget_get_visible( file_browser->side_dir_scroll ) ) )
main_window_event( main_window, evt_pnl_show, "evt_pnl_show", 0, 0,
"dirtree", 0, 0, 0, TRUE );
if ( !file_browser->side_dir )
{
file_browser->side_dir = ptk_file_browser_create_dir_tree( file_browser );
gtk_container_add( GTK_CONTAINER( file_browser->side_dir_scroll ),
file_browser->side_dir );
}
gtk_widget_show_all( file_browser->side_dir_scroll );
if ( file_browser->side_dir && file_browser->file_list )
ptk_dir_tree_view_chdir( GTK_TREE_VIEW( file_browser->side_dir ),
ptk_file_browser_get_cwd( file_browser ) );
}
else
{
if ( ( evt_pnl_show->s || evt_pnl_show->ob2_data ) &&
file_browser->side_dir_scroll &&
gtk_widget_get_visible( file_browser->side_dir_scroll ) )
main_window_event( main_window, evt_pnl_show, "evt_pnl_show", 0, 0,
"dirtree", 0, 0, 0, FALSE );
gtk_widget_hide( file_browser->side_dir_scroll );
if ( file_browser->side_dir )
gtk_widget_destroy( file_browser->side_dir );
file_browser->side_dir = NULL;
}
if ( xset_get_b_panel( p, "show_book" ) )
{
if ( ( evt_pnl_show->s || evt_pnl_show->ob2_data ) &&
( !file_browser->side_book_scroll ||
!gtk_widget_get_visible( file_browser->side_book_scroll ) ) )
main_window_event( main_window, evt_pnl_show, "evt_pnl_show", 0, 0,
"bookmarks", 0, 0, 0, TRUE );
if ( !file_browser->side_book )
{
file_browser->side_book = ptk_bookmark_view_new( file_browser );
gtk_container_add( GTK_CONTAINER( file_browser->side_book_scroll ),
file_browser->side_book );
}
gtk_widget_show_all( file_browser->side_book_scroll );
}
else
{
if ( ( evt_pnl_show->s || evt_pnl_show->ob2_data ) &&
file_browser->side_book_scroll &&
gtk_widget_get_visible( file_browser->side_book_scroll ) )
main_window_event( main_window, evt_pnl_show, "evt_pnl_show", 0, 0,
"bookmarks", 0, 0, 0, FALSE );
gtk_widget_hide( file_browser->side_book_scroll );
if ( file_browser->side_book )
gtk_widget_destroy( file_browser->side_book );
file_browser->side_book = NULL;
}
if ( xset_get_b_panel( p, "show_devmon" ) )
{
if ( ( evt_pnl_show->s || evt_pnl_show->ob2_data ) &&
( !file_browser->side_dev_scroll ||
!gtk_widget_get_visible( file_browser->side_dev_scroll ) ) )
main_window_event( main_window, evt_pnl_show, "evt_pnl_show", 0, 0,
"devices", 0, 0, 0, TRUE );
if ( !file_browser->side_dev )
{
file_browser->side_dev = ptk_location_view_new( file_browser );
gtk_container_add( GTK_CONTAINER( file_browser->side_dev_scroll ),
file_browser->side_dev );
}
gtk_widget_show_all( file_browser->side_dev_scroll );
}
else
{
if ( ( evt_pnl_show->s || evt_pnl_show->ob2_data ) &&
file_browser->side_dev_scroll &&
gtk_widget_get_visible( file_browser->side_dev_scroll ) )
main_window_event( main_window, evt_pnl_show, "evt_pnl_show", 0, 0,
"devices", 0, 0, 0, FALSE );
gtk_widget_hide( file_browser->side_dev_scroll );
if ( file_browser->side_dev )
gtk_widget_destroy( file_browser->side_dev );
file_browser->side_dev = NULL;
}
if ( xset_get_b_panel( p, "show_book" ) || xset_get_b_panel( p, "show_dirtree" ) )
gtk_widget_show( file_browser->side_vpane_bottom );
else
gtk_widget_hide( file_browser->side_vpane_bottom );
if ( xset_get_b_panel( p, "show_devmon" ) || xset_get_b_panel( p, "show_dirtree" )
|| xset_get_b_panel( p, "show_book" ) )
gtk_widget_show( file_browser->side_vbox );
else
gtk_widget_hide( file_browser->side_vbox );
// toggle dirtree toolbar buttons
gboolean b;
for ( i = 0; i < 3; i++ )
{
if ( i == 0 )
b = xset_get_b_panel( p, "show_dirtree" );
else if ( i == 1 )
b = xset_get_b_panel( p, "show_book" );
else
b = xset_get_b_panel( p, "show_devmon" );
if ( file_browser->toggle_btns_left[i] )
{
g_signal_handlers_block_matched( file_browser->toggle_btns_left[i],
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_toggle_sideview, NULL );
gtk_toggle_tool_button_set_active( file_browser->toggle_btns_left[i], b );
g_signal_handlers_unblock_matched( file_browser->toggle_btns_left[i],
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_toggle_sideview, NULL );
}
if ( file_browser->toggle_btns_right[i] )
{
g_signal_handlers_block_matched( file_browser->toggle_btns_right[i],
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_toggle_sideview, NULL );
gtk_toggle_tool_button_set_active( file_browser->toggle_btns_right[i], b );
g_signal_handlers_unblock_matched( file_browser->toggle_btns_right[i],
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_toggle_sideview, NULL );
}
if ( file_browser->toggle_btns_side[i] )
{
g_signal_handlers_block_matched( file_browser->toggle_btns_side[i],
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_toggle_sideview, NULL );
gtk_toggle_tool_button_set_active( file_browser->toggle_btns_side[i], b );
g_signal_handlers_unblock_matched( file_browser->toggle_btns_side[i],
G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
on_toggle_sideview, NULL );
}
}
// set slider positions
/*
// don't need to block signals for release event method
g_signal_handlers_block_matched( file_browser->hpane, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
ptk_file_browser_slider_release, NULL );
g_signal_handlers_block_matched( file_browser->side_vpane_top, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
ptk_file_browser_slider_release, NULL );
g_signal_handlers_block_matched( file_browser->side_vpane_bottom, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
ptk_file_browser_slider_release, NULL );
*/
int pos;
//int pos = xset_get_int_panel( file_browser->mypanel, "slider_positions", "x" );
// read each slider's pos from dynamic
pos = *file_browser->slide_x;
if ( pos < 100 ) pos = -1;
gtk_paned_set_position( GTK_PANED( file_browser->hpane ), pos );
//pos = xset_get_int_panel( file_browser->mypanel, "slider_positions", "y" );
pos = *file_browser->slide_y;
if ( pos < 20 ) pos = -1;
gtk_paned_set_position( GTK_PANED( file_browser->side_vpane_top ), pos );
// hack to let other sliders adjust
// FIXME: this may allow close events to destroy fb, so make sure its
// still a widget after this - find a better way to do this
while (gtk_events_pending ())
gtk_main_iteration ();
if ( !( GTK_IS_WIDGET( file_browser ) && GTK_IS_PANED( file_browser->side_vpane_bottom ) ) )
return;
//pos = xset_get_int_panel( file_browser->mypanel, "slider_positions", "s" );
pos = *file_browser->slide_s;
if ( pos < 20 ) pos = -1;
gtk_paned_set_position( GTK_PANED( file_browser->side_vpane_bottom ), pos );
// save slider positions (they change when set)
ptk_file_browser_slider_release( NULL, NULL, file_browser );
/*
g_signal_handlers_unblock_matched( file_browser->hpane, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
ptk_file_browser_slider_release, NULL );
g_signal_handlers_unblock_matched( file_browser->side_vpane_top, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
ptk_file_browser_slider_release, NULL );
g_signal_handlers_unblock_matched( file_browser->side_vpane_bottom, G_SIGNAL_MATCH_FUNC, 0, 0, NULL,
ptk_file_browser_slider_release, NULL );
*/
// List Styles
if ( xset_get_b_panel( p, "list_detailed" ) )
ptk_file_browser_view_as_list( file_browser );
else if ( xset_get_b_panel( p, "list_icons" ) )
ptk_file_browser_view_as_icons( file_browser );
else if ( xset_get_b_panel( p, "list_compact" ) )
ptk_file_browser_view_as_compact_list( file_browser );
else
{
xset_set_panel( p, "list_detailed", "b", "1" );
ptk_file_browser_view_as_list( file_browser );
}
// Show Hidden
ptk_file_browser_show_hidden_files( file_browser,
xset_get_b_panel( p, "show_hidden" ) );
// Set column visibility, save widths
if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
on_folder_view_columns_changed( GTK_TREE_VIEW( file_browser->folder_view ),
file_browser );
//printf("ptk_file_browser_update_views fb=%#x DONE\n", file_browser);
}
GtkWidget* ptk_file_browser_new( int curpanel, GtkWidget* notebook,
GtkWidget* task_view,
gpointer main_window,
int* slide_x,
int* slide_y,
int* slide_s )
{
PtkFileBrowser * file_browser;
PtkFBViewMode view_mode;
PangoFontDescription* font_desc;
file_browser = ( PtkFileBrowser* ) g_object_new( PTK_TYPE_FILE_BROWSER, NULL );
file_browser->mypanel = curpanel;
file_browser->mynotebook = notebook;
file_browser->main_window = main_window;
file_browser->task_view = task_view;
file_browser->sel_change_idle = 0;
file_browser->inhibit_focus = FALSE;
file_browser->seek_name = NULL;
file_browser->slide_x = slide_x;
file_browser->slide_y = slide_y;
file_browser->slide_s = slide_s;
if ( xset_get_b_panel( curpanel, "list_detailed" ) )
view_mode = PTK_FB_LIST_VIEW;
else if ( xset_get_b_panel( curpanel, "list_icons" ) )
{
view_mode = PTK_FB_ICON_VIEW;
gtk_scrolled_window_set_policy(
GTK_SCROLLED_WINDOW( file_browser->folder_view_scroll ),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC );
}
else if ( xset_get_b_panel( curpanel, "list_compact" ) )
{
view_mode = PTK_FB_COMPACT_VIEW;
gtk_scrolled_window_set_policy(
GTK_SCROLLED_WINDOW( file_browser->folder_view_scroll ),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC );
}
else
{
xset_set_panel( curpanel, "list_detailed", "b", "1" );
view_mode = PTK_FB_LIST_VIEW;
}
file_browser->view_mode = view_mode; //sfm was after next line
file_browser->folder_view = create_folder_view( file_browser, view_mode );
gtk_container_add ( GTK_CONTAINER ( file_browser->folder_view_scroll ),
file_browser->folder_view );
file_browser->side_dir = NULL;
file_browser->side_book = NULL;
file_browser->side_dev = NULL;
file_browser->select_path = NULL;
file_browser->status_bar_custom = NULL;
//gtk_widget_show_all( file_browser->folder_view_scroll );
// set status bar icon
char* icon_name;
XSet* set = xset_get_panel( curpanel, "icon_status" );
if ( set->icon && set->icon[0] != '\0' )
icon_name = set->icon;
else
icon_name = "gtk-yes";
gtk_image_set_from_icon_name( GTK_IMAGE( file_browser->status_image ), icon_name,
GTK_ICON_SIZE_MENU );
// set status bar font
char* fontname = xset_get_s_panel( curpanel, "font_status" );
if ( fontname )
{
font_desc = pango_font_description_from_string( fontname );
gtk_widget_modify_font( GTK_WIDGET( file_browser->status_label ), font_desc );
pango_font_description_free( font_desc );
}
// set path bar font (is created before mypanel is set)
if ( file_browser->path_bar &&
( fontname = xset_get_s_panel( curpanel, "font_path" ) ) )
{
font_desc = pango_font_description_from_string( fontname );
gtk_widget_modify_font( GTK_WIDGET( file_browser->path_bar ), font_desc );
pango_font_description_free( font_desc );
}
gtk_widget_show_all( GTK_WIDGET( file_browser ) );
// PROBLEM: this may allow close events to destroy fb, so make sure its
// still a widget after this
ptk_file_browser_update_views( NULL, file_browser );
return GTK_IS_WIDGET( file_browser ) ? ( GtkWidget* ) file_browser : NULL;
}
gboolean ptk_file_restrict_homedir( const char* folder_path ) {
const char *homedir = NULL;
int ret=(1==0);
homedir = g_getenv("HOME");
if (!homedir) {
homedir = g_get_home_dir();
}
if (g_str_has_prefix(folder_path,homedir)) {
ret=(1==1);
}
if (g_str_has_prefix(folder_path,"/media")) {
ret=(1==1);
}
return ret;
}
void ptk_file_browser_update_tab_label( PtkFileBrowser* file_browser )
{
GtkWidget * label;
GtkContainer* hbox;
GtkImage* icon;
GtkLabel* text;
GList* children;
gchar* name;
label = gtk_notebook_get_tab_label ( GTK_NOTEBOOK( file_browser->mynotebook ),
GTK_WIDGET( file_browser ) );
hbox = GTK_CONTAINER( gtk_bin_get_child ( GTK_BIN( label ) ) );
children = gtk_container_get_children( hbox );
icon = GTK_IMAGE( children->data );
text = GTK_LABEL( children->next->data );
g_list_free( children );
/* TODO: Change the icon */
name = g_path_get_basename( ptk_file_browser_get_cwd( file_browser ) );
gtk_label_set_text( text, name );
#if GTK_CHECK_VERSION (3, 0, 0)
gtk_label_set_ellipsize( text, PANGO_ELLIPSIZE_MIDDLE );
if (strlen( name ) < 30)
{
gtk_label_set_ellipsize( text, PANGO_ELLIPSIZE_NONE );
gtk_label_set_width_chars( text, -1 );
}
else
gtk_label_set_width_chars( text, 30 );
#endif
g_free( name );
}
void ptk_file_browser_select_last( PtkFileBrowser* file_browser ) //MOD added
{
//printf("ptk_file_browser_select_last\n");
// select one file?
if ( file_browser->select_path )
{
ptk_file_browser_select_file( file_browser, file_browser->select_path );
g_free( file_browser->select_path );
file_browser->select_path = NULL;
return;
}
// select previously selected files
gint elementn = -1;
GList* l;
GList* element = NULL;
//printf(" search for %s\n", (char*)file_browser->curHistory->data );
if ( file_browser->history && file_browser->histsel && file_browser->curHistory &&
( l = g_list_last( file_browser->history ) ) )
{
if ( l->data && !strcmp( (char*)l->data, (char*)file_browser->curHistory->data ) )
{
elementn = g_list_position( file_browser->history, l );
if ( elementn != -1 )
{
element = g_list_nth( file_browser->histsel, elementn );
// skip the current history item if sellist empty since it was just created
if ( !element->data )
{
//printf( " found current empty\n");
element = NULL;
}
//else printf( " found current NON-empty\n");
}
}
if ( !element )
{
while ( l = l->prev )
{
if ( l->data && !strcmp( (char*)l->data, (char*)file_browser->curHistory->data ) )
{
elementn = g_list_position( file_browser->history, l );
//printf (" found elementn=%d\n", elementn );
if ( elementn != -1 )
element = g_list_nth( file_browser->histsel, elementn );
break;
}
}
}
}
/*
if ( element )
{
g_debug ("element OK" );
if ( element->data )
g_debug ("element->data OK" );
else
g_debug ("element->data NULL" );
}
else
g_debug ("element NULL" );
g_debug ("histsellen=%d", g_list_length( file_browser->histsel ) );
*/
if ( element && element->data )
{
//printf(" select files\n");
PtkFileList* list = PTK_FILE_LIST( file_browser->file_list );
GtkTreeIter it;
GtkTreePath* tp;
GtkTreeSelection* tree_sel;
gboolean firstsel = TRUE;
if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
tree_sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( file_browser->folder_view ) );
for ( l = element->data; l; l = l->next )
{
if ( l->data )
{
//g_debug ("find a file");
VFSFileInfo* file = l->data;
if( ptk_file_list_find_iter( list, &it, file ) )
{
//g_debug ("found file");
tp = gtk_tree_model_get_path( GTK_TREE_MODEL(list), &it );
if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
exo_icon_view_select_path( EXO_ICON_VIEW( file_browser->folder_view ), tp );
if ( firstsel )
{
exo_icon_view_set_cursor( EXO_ICON_VIEW( file_browser->folder_view ), tp, NULL, FALSE );
exo_icon_view_scroll_to_path( EXO_ICON_VIEW( file_browser->folder_view ),
tp, TRUE, .25, 0 );
firstsel = FALSE;
}
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
gtk_tree_selection_select_path( tree_sel, tp );
if ( firstsel )
{
gtk_tree_view_set_cursor(GTK_TREE_VIEW( file_browser->folder_view ), tp, NULL, FALSE);
gtk_tree_view_scroll_to_cell( GTK_TREE_VIEW( file_browser->folder_view ),
tp, NULL, TRUE, .25, 0 );
firstsel = FALSE;
}
}
gtk_tree_path_free( tp );
}
}
}
}
}
void enable_toolbar( PtkFileBrowser* file_browser )
{
const char* cwd = ptk_file_browser_get_cwd( file_browser ); // may be NULL
int i;
for ( i = 0; i < 3; i++ )
{
if ( i < 2 && !file_browser->toolbar )
continue;
else if ( i == 2 && !file_browser->side_toolbar )
continue;
if ( file_browser->back_btn[i] )
gtk_widget_set_sensitive( GTK_WIDGET( file_browser->back_btn[i] ),
file_browser->curHistory &&
file_browser->curHistory->prev );
if ( file_browser->forward_btn[i] )
gtk_widget_set_sensitive( GTK_WIDGET( file_browser->forward_btn[i] ),
file_browser->curHistory &&
file_browser->curHistory->next );
if ( file_browser->up_btn[i] )
gtk_widget_set_sensitive( GTK_WIDGET( file_browser->up_btn[i] ),
!cwd || ( cwd && strcmp( cwd, "/" ) ) );
}
if ( file_browser->toolbar && file_browser->back_menu_btn_left )
gtk_widget_set_sensitive( GTK_WIDGET( file_browser->back_menu_btn_left ),
file_browser->curHistory &&
file_browser->curHistory->prev );
if ( file_browser->toolbar && file_browser->forward_menu_btn_left )
gtk_widget_set_sensitive( GTK_WIDGET( file_browser->forward_menu_btn_left ),
file_browser->curHistory &&
file_browser->curHistory->next );
if ( file_browser->toolbar && file_browser->back_menu_btn_right )
gtk_widget_set_sensitive( GTK_WIDGET( file_browser->back_menu_btn_right ),
file_browser->curHistory &&
file_browser->curHistory->prev );
if ( file_browser->toolbar && file_browser->forward_menu_btn_right )
gtk_widget_set_sensitive( GTK_WIDGET( file_browser->forward_menu_btn_right ),
file_browser->curHistory &&
file_browser->curHistory->next );
if ( file_browser->side_toolbar && file_browser->back_menu_btn_side )
gtk_widget_set_sensitive( GTK_WIDGET( file_browser->back_menu_btn_side ),
file_browser->curHistory &&
file_browser->curHistory->prev );
if ( file_browser->side_toolbar && file_browser->forward_menu_btn_side )
gtk_widget_set_sensitive( GTK_WIDGET( file_browser->forward_menu_btn_side ),
file_browser->curHistory &&
file_browser->curHistory->next );
}
gboolean ptk_file_browser_chdir( PtkFileBrowser* file_browser,
const char* folder_path,
PtkFBChdirMode mode )
{
gboolean cancel = FALSE;
GtkWidget* folder_view = file_browser->folder_view;
//printf("ptk_file_browser_chdir\n");
char* path_end;
int test_access;
char* path;
char* msg;
gboolean inhibit_focus = file_browser->inhibit_focus;
//file_browser->button_press = FALSE;
file_browser->is_drag = FALSE;
file_browser->skip_release = FALSE;
if ( ! folder_path )
return FALSE;
if ( folder_path )
{
path = strdup( folder_path );
/* remove redundent '/' */
if ( strcmp( path, "/" ) )
{
path_end = path + strlen( path ) - 1;
for ( ; path_end > path; --path_end )
{
if ( *path_end != '/' )
break;
else
*path_end = '\0';
}
}
}
else
path = NULL;
if ( ! path || ! g_file_test( path, ( G_FILE_TEST_IS_DIR ) ) )
{
if ( !inhibit_focus )
{
msg = g_strdup_printf( _("Directory doesn't exist\n\n%s"), path );
ptk_show_error( GTK_WINDOW( gtk_widget_get_toplevel(
GTK_WIDGET( file_browser ) ) ),
_("Error"),
msg );
if ( path )
g_free( path );
g_free( msg );
}
return FALSE;
}
/* FIXME: check access */
#if defined(HAVE_EUIDACCESS)
test_access = euidaccess( path, R_OK | X_OK );
#elif defined(HAVE_EACCESS)
test_access = eaccess( path, R_OK | X_OK );
#else /* No check */
test_access = 0;
#endif
if ( test_access == -1 )
{
if ( !inhibit_focus )
{
msg = g_strdup_printf( _("Unable to access %s\n\n%s"), path,
g_markup_escape_text(g_strerror( errno ), -1) );
ptk_show_error( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET(
file_browser ) ) ),
_("Error"),
msg );
g_free(msg);
}
return FALSE;
}
g_signal_emit( file_browser, signals[ BEFORE_CHDIR_SIGNAL ], 0, path, &cancel );
if ( cancel )
return FALSE;
//MOD remember selected files
//g_debug ("@@@@@@@@@@@ remember: %s", ptk_file_browser_get_cwd( file_browser ) );
if ( file_browser->curhistsel && file_browser->curhistsel->data )
{
//g_debug ("free curhistsel");
g_list_foreach ( file_browser->curhistsel->data, ( GFunc ) vfs_file_info_unref, NULL );
g_list_free( file_browser->curhistsel->data );
}
if ( file_browser->curhistsel )
{
file_browser->curhistsel->data = ptk_file_browser_get_selected_files( file_browser );
//g_debug("set curhistsel %d", g_list_position( file_browser->histsel, file_browser->curhistsel ) );
//if ( file_browser->curhistsel->data )
// g_debug ("curhistsel->data OK" );
//else
// g_debug ("curhistsel->data NULL" );
}
if ( mode == PTK_FB_CHDIR_ADD_HISTORY )
{
if ( ! file_browser->curHistory || strcmp( (char*)file_browser->curHistory->data, path ) )
{
/* Has forward history */
if ( file_browser->curHistory && file_browser->curHistory->next )
{
/* clear old forward history */
g_list_foreach ( file_browser->curHistory->next, ( GFunc ) g_free, NULL );
g_list_free( file_browser->curHistory->next );
file_browser->curHistory->next = NULL;
}
//MOD added - make histsel shadow file_browser->history
if ( file_browser->curhistsel && file_browser->curhistsel->next )
{
//g_debug("@@@@@@@@@@@ free forward");
GList* l;
for ( l = file_browser->curhistsel->next; l; l = l->next )
{
if ( l->data )
{
//g_debug("free forward item");
g_list_foreach ( l->data, ( GFunc ) vfs_file_info_unref, NULL );
g_list_free( l->data );
}
}
g_list_free( file_browser->curhistsel->next );
file_browser->curhistsel->next = NULL;
}
/* Add path to history if there is no forward history */
file_browser->history = g_list_append( file_browser->history, path );
file_browser->curHistory = g_list_last( file_browser->history );
//MOD added - make histsel shadow file_browser->history
GList* sellist = NULL;
file_browser->histsel = g_list_append( file_browser->histsel, sellist );
file_browser->curhistsel = g_list_last( file_browser->histsel );
}
}
else if( mode == PTK_FB_CHDIR_BACK )
{
file_browser->curHistory = file_browser->curHistory->prev;
file_browser->curhistsel = file_browser->curhistsel->prev; //MOD
}
else if( mode == PTK_FB_CHDIR_FORWARD )
{
file_browser->curHistory = file_browser->curHistory->next;
file_browser->curhistsel = file_browser->curhistsel->next; //MOD
}
// remove old dir object
if ( file_browser->dir )
{
g_signal_handlers_disconnect_matched( file_browser->dir,
G_SIGNAL_MATCH_DATA,
0, 0, NULL, NULL,
file_browser );
g_object_unref( file_browser->dir );
}
if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
exo_icon_view_set_model( EXO_ICON_VIEW( folder_view ), NULL );
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
gtk_tree_view_set_model( GTK_TREE_VIEW( folder_view ), NULL );
file_browser->dir = vfs_dir_get_by_path( path );
if( ! file_browser->curHistory || path != (char*)file_browser->curHistory->data )
g_free( path );
g_signal_emit( file_browser, signals[ BEGIN_CHDIR_SIGNAL ], 0 );
if( vfs_dir_is_file_listed( file_browser->dir ) )
{
on_dir_file_listed( file_browser->dir, FALSE, file_browser );
}
else
file_browser->busy = TRUE;
g_signal_connect( file_browser->dir, "file-listed",
G_CALLBACK(on_dir_file_listed), file_browser );
ptk_file_browser_update_tab_label( file_browser );
char* disp_path = g_filename_display_name( ptk_file_browser_get_cwd( file_browser ) );
if ( !inhibit_focus )
gtk_entry_set_text( GTK_ENTRY( file_browser->path_bar ), disp_path );
g_free( disp_path );
enable_toolbar( file_browser );
return TRUE;
}
static void on_history_menu_item_activate( GtkWidget* menu_item,
PtkFileBrowser* file_browser )
{
GList* l = (GList*)g_object_get_data( G_OBJECT(menu_item), "path"), *tmp;
tmp = file_browser->curHistory;
file_browser->curHistory = l;
if( ! ptk_file_browser_chdir( file_browser, (char*)l->data,
PTK_FB_CHDIR_NO_HISTORY ) )
file_browser->curHistory = tmp;
else
{
//MOD sync curhistsel
gint elementn = -1;
elementn = g_list_position( file_browser->history, file_browser->curHistory );
if ( elementn != -1 )
file_browser->curhistsel = g_list_nth( file_browser->histsel, elementn );
else
g_debug("missing history item - ptk-file-browser.c");
}
}
static GtkWidget* add_history_menu_item( PtkFileBrowser* file_browser,
GtkWidget* menu, GList* l )
{
GtkWidget* menu_item, *folder_image;
char *disp_name;
disp_name = g_filename_display_basename( (char*)l->data );
menu_item = gtk_image_menu_item_new_with_label( disp_name );
g_object_set_data( G_OBJECT( menu_item ), "path", l );
folder_image = gtk_image_new_from_icon_name( "gnome-fs-directory",
GTK_ICON_SIZE_MENU );
gtk_image_menu_item_set_image ( GTK_IMAGE_MENU_ITEM ( menu_item ),
folder_image );
g_signal_connect( menu_item, "activate",
G_CALLBACK( on_history_menu_item_activate ), file_browser );
gtk_menu_shell_append( GTK_MENU_SHELL(menu), menu_item );
return menu_item;
}
static void on_show_history_menu( GtkMenuToolButton* btn, PtkFileBrowser* file_browser )
{
//GtkMenuShell* menu = (GtkMenuShell*)gtk_menu_tool_button_get_menu(btn);
GtkWidget* menu = gtk_menu_new();
GList *l;
if ( btn == (GtkMenuToolButton*)file_browser->back_menu_btn_left
|| btn == (GtkMenuToolButton*)file_browser->back_menu_btn_right
|| btn == (GtkMenuToolButton*)file_browser->back_menu_btn_side )
{
// back history
for( l = file_browser->curHistory->prev; l != NULL; l = l->prev )
add_history_menu_item( file_browser, GTK_WIDGET(menu), l );
}
else
{
// forward history
for( l = file_browser->curHistory->next; l != NULL; l = l->next )
add_history_menu_item( file_browser, GTK_WIDGET(menu), l );
}
gtk_menu_tool_button_set_menu( btn, menu );
gtk_widget_show_all( GTK_WIDGET(menu) );
}
#if 0
static gboolean
ptk_file_browser_delayed_content_change( PtkFileBrowser* file_browser )
{
GTimeVal t;
g_get_current_time( &t );
file_browser->prev_update_time = t.tv_sec;
g_signal_emit( file_browser, signals[ CONTENT_CHANGE_SIGNAL ], 0 );
file_browser->update_timeout = 0;
return FALSE;
}
#endif
#if 0
void on_folder_content_update ( FolderContent* content,
PtkFileBrowser* file_browser )
{
/* FIXME: Newly added or deleted files should not be delayed.
This must be fixed before 0.2.0 release. */
GTimeVal t;
g_get_current_time( &t );
/*
Previous update is < 5 seconds before.
Queue the update, and don't update the view too often
*/
if ( ( t.tv_sec - file_browser->prev_update_time ) < 5 )
{
/*
If the update timeout has been set, wait until the timeout happens, and
don't do anything here.
*/
if ( 0 == file_browser->update_timeout )
{ /* No timeout callback. Add one */
/* Delay the update */
file_browser->update_timeout = g_timeout_add( 5000,
( GSourceFunc ) ptk_file_browser_delayed_content_change, file_browser );
}
}
else if ( 0 == file_browser->update_timeout )
{ /* No timeout callback. Add one */
file_browser->prev_update_time = t.tv_sec;
g_signal_emit( file_browser, signals[ CONTENT_CHANGE_SIGNAL ], 0 );
}
}
#endif
static gboolean ptk_file_browser_content_changed( PtkFileBrowser* file_browser )
{
//gdk_threads_enter(); not needed because g_idle_add runs in main loop thread
g_signal_emit( file_browser, signals[ CONTENT_CHANGE_SIGNAL ], 0 );
//gdk_threads_leave();
return FALSE;
}
static void on_folder_content_changed( VFSDir* dir, VFSFileInfo* file,
PtkFileBrowser* file_browser )
{
g_idle_add( ( GSourceFunc ) ptk_file_browser_content_changed,
file_browser );
}
static void on_file_deleted( VFSDir* dir, VFSFileInfo* file,
PtkFileBrowser* file_browser )
{
/* The folder itself was deleted */
if( file == NULL )
{
// Note: on_close_notebook_page calls ptk_file_browser_update_views
// which may destroy fb here
on_close_notebook_page( NULL, file_browser );
//ptk_file_browser_chdir( file_browser, g_get_home_dir(), PTK_FB_CHDIR_ADD_HISTORY);
}
else
on_folder_content_changed( dir, file, file_browser );
}
static void on_sort_col_changed( GtkTreeSortable* sortable,
PtkFileBrowser* file_browser )
{
int col;
gtk_tree_sortable_get_sort_column_id( sortable,
&col, &file_browser->sort_type );
switch ( col )
{
case COL_FILE_NAME:
col = PTK_FB_SORT_BY_NAME;
break;
case COL_FILE_SIZE:
col = PTK_FB_SORT_BY_SIZE;
break;
case COL_FILE_MTIME:
col = PTK_FB_SORT_BY_MTIME;
break;
case COL_FILE_DESC:
col = PTK_FB_SORT_BY_TYPE;
break;
case COL_FILE_PERM:
col = PTK_FB_SORT_BY_PERM;
break;
case COL_FILE_OWNER:
col = PTK_FB_SORT_BY_OWNER;
break;
}
file_browser->sort_order = col;
//MOD enable following to make column click permanent sort
// app_settings.sort_order = col;
// if ( file_browser )
// ptk_file_browser_set_sort_order( PTK_FILE_BROWSER( file_browser ), app_settings.sort_order );
char* val = g_strdup_printf( "%d", col );
xset_set_panel( file_browser->mypanel, "list_detailed", "x", val );
g_free( val );
val = g_strdup_printf( "%d", file_browser->sort_type );
xset_set_panel( file_browser->mypanel, "list_detailed", "y", val );
g_free( val );
}
void ptk_file_browser_update_model( PtkFileBrowser* file_browser )
{
PtkFileList * list;
GtkTreeModel *old_list;
list = ptk_file_list_new( file_browser->dir,
file_browser->show_hidden_files );
old_list = file_browser->file_list;
file_browser->file_list = GTK_TREE_MODEL( list );
if ( old_list )
g_object_unref( G_OBJECT( old_list ) );
ptk_file_browser_read_sort_extra( file_browser ); //sfm
gtk_tree_sortable_set_sort_column_id(
GTK_TREE_SORTABLE( list ),
file_list_order_from_sort_order( file_browser->sort_order ),
file_browser->sort_type );
ptk_file_list_show_thumbnails( list,
( file_browser->view_mode == PTK_FB_ICON_VIEW ),
file_browser->max_thumbnail );
g_signal_connect( list, "sort-column-changed",
G_CALLBACK( on_sort_col_changed ), file_browser );
if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
exo_icon_view_set_model( EXO_ICON_VIEW( file_browser->folder_view ),
GTK_TREE_MODEL( list ) );
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
gtk_tree_view_set_model( GTK_TREE_VIEW( file_browser->folder_view ),
GTK_TREE_MODEL( list ) );
// try to smooth list bounce created by delayed re-appearance of column headers
//while( gtk_events_pending() )
// gtk_main_iteration();
}
void on_dir_file_listed( VFSDir* dir,
gboolean is_cancelled,
PtkFileBrowser* file_browser )
{
file_browser->n_sel_files = 0;
if ( G_LIKELY( ! is_cancelled ) )
{
g_signal_connect( dir, "file-created",
G_CALLBACK( on_folder_content_changed ), file_browser );
g_signal_connect( dir, "file-deleted",
G_CALLBACK( on_file_deleted ), file_browser );
g_signal_connect( dir, "file-changed",
G_CALLBACK( on_folder_content_changed ), file_browser );
}
ptk_file_browser_update_model( file_browser );
file_browser->busy = FALSE;
g_signal_emit( file_browser, signals[ AFTER_CHDIR_SIGNAL ], 0 );
//g_signal_emit( file_browser, signals[ CONTENT_CHANGE_SIGNAL ], 0 );
g_signal_emit( file_browser, signals[ SEL_CHANGE_SIGNAL ], 0 );
if ( file_browser->side_dir )
ptk_dir_tree_view_chdir( GTK_TREE_VIEW( file_browser->side_dir ),
ptk_file_browser_get_cwd( file_browser ) );
/*
if ( file_browser->side_pane )
if ( ptk_file_browser_is_side_pane_visible( file_browser ) )
{
side_pane_chdir( file_browser,
ptk_file_browser_get_cwd( file_browser ) );
}
*/
if ( file_browser->side_dev )
ptk_location_view_chdir( GTK_TREE_VIEW( file_browser->side_dev ),
ptk_file_browser_get_cwd( file_browser ) );
if ( file_browser->side_book )
ptk_bookmark_view_chdir( GTK_TREE_VIEW( file_browser->side_book ),
ptk_file_browser_get_cwd( file_browser ) );
//FIXME: This is already done in update_model, but is there any better way to
// reduce unnecessary code?
if ( file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{ //sfm why is this needed for compact view???
if ( G_LIKELY(! is_cancelled) && file_browser->file_list )
{
ptk_file_list_show_thumbnails( PTK_FILE_LIST( file_browser->file_list ),
file_browser->view_mode == PTK_FB_ICON_VIEW,
file_browser->max_thumbnail );
}
}
}
void ptk_file_browser_canon( PtkFileBrowser* file_browser, const char* path )
{
const char* cwd = ptk_file_browser_get_cwd( file_browser );
char buf[ PATH_MAX + 1 ];
char* canon = realpath( path, buf );
if ( !canon || !g_strcmp0( canon, cwd ) || !g_strcmp0( canon, path ) )
return;
if ( g_file_test( canon, G_FILE_TEST_IS_DIR ) )
{
// open dir
ptk_file_browser_chdir( file_browser, canon, PTK_FB_CHDIR_ADD_HISTORY );
gtk_widget_grab_focus( GTK_WIDGET( file_browser->folder_view ) );
}
else if ( g_file_test( canon, G_FILE_TEST_EXISTS ) )
{
// open dir and select file
char* dir_path = g_path_get_dirname( canon );
if ( dir_path && strcmp( dir_path, cwd ) )
{
file_browser->select_path = strdup( canon );
ptk_file_browser_chdir( file_browser, dir_path, PTK_FB_CHDIR_ADD_HISTORY );
}
else
ptk_file_browser_select_file( file_browser, canon );
g_free( dir_path );
gtk_widget_grab_focus( GTK_WIDGET( file_browser->folder_view ) );
}
}
const char* ptk_file_browser_get_cwd( PtkFileBrowser* file_browser )
{
if ( ! file_browser->curHistory )
return NULL;
return ( const char* ) file_browser->curHistory->data;
}
gboolean ptk_file_browser_is_busy( PtkFileBrowser* file_browser )
{
return file_browser->busy;
}
gboolean ptk_file_browser_can_back( PtkFileBrowser* file_browser )
{
/* there is back history */
return ( file_browser->curHistory && file_browser->curHistory->prev );
}
void ptk_file_browser_go_back( GtkWidget* item, PtkFileBrowser* file_browser )
{
const char * path;
focus_folder_view( file_browser );
/* there is no back history */
if ( ! file_browser->curHistory || ! file_browser->curHistory->prev )
return;
path = ( const char* ) file_browser->curHistory->prev->data;
ptk_file_browser_chdir( file_browser, path, PTK_FB_CHDIR_BACK );
}
gboolean ptk_file_browser_can_forward( PtkFileBrowser* file_browser )
{
/* If there is forward history */
return ( file_browser->curHistory && file_browser->curHistory->next );
}
void ptk_file_browser_go_forward( GtkWidget* item, PtkFileBrowser* file_browser )
{
const char * path;
focus_folder_view( file_browser );
/* If there is no forward history */
if ( ! file_browser->curHistory || ! file_browser->curHistory->next )
return ;
path = ( const char* ) file_browser->curHistory->next->data;
ptk_file_browser_chdir( file_browser, path, PTK_FB_CHDIR_FORWARD );
}
void ptk_file_browser_go_up( GtkWidget* item, PtkFileBrowser* file_browser )
{
char * parent_dir;
focus_folder_view( file_browser );
parent_dir = g_path_get_dirname( ptk_file_browser_get_cwd( file_browser ) );
if( strcmp( parent_dir, ptk_file_browser_get_cwd( file_browser ) ) )
ptk_file_browser_chdir( file_browser, parent_dir, PTK_FB_CHDIR_ADD_HISTORY);
g_free( parent_dir );
}
void ptk_file_browser_go_home( GtkWidget* item, PtkFileBrowser* file_browser )
{
// if ( app_settings.home_folder )
// ptk_file_browser_chdir( PTK_FILE_BROWSER( file_browser ), app_settings.home_folder, PTK_FB_CHDIR_ADD_HISTORY );
// else
focus_folder_view( file_browser );
ptk_file_browser_chdir( PTK_FILE_BROWSER( file_browser ), g_get_home_dir(), PTK_FB_CHDIR_ADD_HISTORY );
}
void ptk_file_browser_go_default( GtkWidget* item, PtkFileBrowser* file_browser )
{
focus_folder_view( file_browser );
char* path = xset_get_s( "go_set_default" );
if ( path && path[0] != '\0' )
ptk_file_browser_chdir( PTK_FILE_BROWSER( file_browser ), path,
PTK_FB_CHDIR_ADD_HISTORY );
else if ( geteuid() != 0 )
ptk_file_browser_chdir( PTK_FILE_BROWSER( file_browser ), g_get_home_dir(),
PTK_FB_CHDIR_ADD_HISTORY );
else
ptk_file_browser_chdir( PTK_FILE_BROWSER( file_browser ), "/",
PTK_FB_CHDIR_ADD_HISTORY );
}
void ptk_file_browser_set_default_folder( GtkWidget* item, PtkFileBrowser* file_browser )
{
xset_set( "go_set_default", "s", ptk_file_browser_get_cwd( file_browser ) );
}
GtkWidget* ptk_file_browser_get_folder_view( PtkFileBrowser* file_browser )
{
return file_browser->folder_view;
}
/* FIXME: unused function */
GtkTreeView* ptk_file_browser_get_dir_tree( PtkFileBrowser* file_browser )
{
return NULL;
}
void ptk_file_browser_select_all( GtkWidget* item, PtkFileBrowser* file_browser )
{
GtkTreeSelection * tree_sel;
if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
exo_icon_view_select_all( EXO_ICON_VIEW( file_browser->folder_view ) );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
tree_sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( file_browser->folder_view ) );
gtk_tree_selection_select_all( tree_sel );
}
}
void ptk_file_browser_unselect_all( GtkWidget* item, PtkFileBrowser* file_browser )
{
GtkTreeSelection * tree_sel;
if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
exo_icon_view_unselect_all( EXO_ICON_VIEW( file_browser->folder_view ) );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
tree_sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( file_browser->folder_view ) );
gtk_tree_selection_unselect_all( tree_sel );
}
}
static gboolean
invert_selection ( GtkTreeModel* model,
GtkTreePath *path,
GtkTreeIter* it,
PtkFileBrowser* file_browser )
{
GtkTreeSelection * tree_sel;
if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
if ( exo_icon_view_path_is_selected ( EXO_ICON_VIEW( file_browser->folder_view ), path ) )
exo_icon_view_unselect_path ( EXO_ICON_VIEW( file_browser->folder_view ), path );
else
exo_icon_view_select_path ( EXO_ICON_VIEW( file_browser->folder_view ), path );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
tree_sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( file_browser->folder_view ) );
if ( gtk_tree_selection_path_is_selected ( tree_sel, path ) )
gtk_tree_selection_unselect_path ( tree_sel, path );
else
gtk_tree_selection_select_path ( tree_sel, path );
}
return FALSE;
}
void ptk_file_browser_invert_selection( GtkWidget* item, PtkFileBrowser* file_browser )
{
GtkTreeModel * model;
if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
model = exo_icon_view_get_model( EXO_ICON_VIEW( file_browser->folder_view ) );
g_signal_handlers_block_matched( file_browser->folder_view,
G_SIGNAL_MATCH_FUNC,
0, 0, NULL,
on_folder_view_item_sel_change, NULL );
gtk_tree_model_foreach ( model,
( GtkTreeModelForeachFunc ) invert_selection, file_browser );
g_signal_handlers_unblock_matched( file_browser->folder_view,
G_SIGNAL_MATCH_FUNC,
0, 0, NULL,
on_folder_view_item_sel_change, NULL );
on_folder_view_item_sel_change( EXO_ICON_VIEW( file_browser->folder_view ),
file_browser );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
GtkTreeSelection* tree_sel;
tree_sel = gtk_tree_view_get_selection(GTK_TREE_VIEW( file_browser->folder_view ));
g_signal_handlers_block_matched( tree_sel,
G_SIGNAL_MATCH_FUNC,
0, 0, NULL,
on_folder_view_item_sel_change, NULL );
model = gtk_tree_view_get_model( GTK_TREE_VIEW( file_browser->folder_view ) );
gtk_tree_model_foreach ( model,
( GtkTreeModelForeachFunc ) invert_selection, file_browser );
g_signal_handlers_unblock_matched( tree_sel,
G_SIGNAL_MATCH_FUNC,
0, 0, NULL,
on_folder_view_item_sel_change, NULL );
on_folder_view_item_sel_change( (ExoIconView*)tree_sel,
file_browser );
}
}
void ptk_file_browser_select_pattern( GtkWidget* item, PtkFileBrowser* file_browser,
const char* search_key )
{
GtkTreeModel* model;
GtkTreePath* path;
GtkTreeIter it;
GtkTreeSelection* tree_sel;
VFSFileInfo* file;
gboolean select;
char* name;
const char* key;
if ( search_key )
key = search_key;
else
{
// get pattern from user (store in ob1 so it's not saved)
XSet* set = xset_get( "select_patt" );
if ( !xset_text_dialog( GTK_WIDGET( file_browser ), _("Select By Pattern"), NULL, FALSE, _("Enter pattern to select files and folders:\n\nIf your pattern contains any uppercase characters, the matching will be case sensitive.\n\nExample: *sp*e?m*\n\nTIP: You can also enter '%% PATTERN' in the path bar."),
NULL, set->ob1, &set->ob1,
NULL, FALSE, NULL ) || !set->ob1 )
return;
key = set->ob1;
}
// case insensitive search ?
gboolean icase = FALSE;
char* lower_key = g_utf8_strdown( key, -1 );
if ( !strcmp( lower_key, key ) )
{
// key is all lowercase so do icase search
icase = TRUE;
}
g_free( lower_key );
// get model, treesel, and stop signals
if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
model = exo_icon_view_get_model( EXO_ICON_VIEW( file_browser->folder_view ) );
g_signal_handlers_block_matched( file_browser->folder_view,
G_SIGNAL_MATCH_FUNC,
0, 0, NULL,
on_folder_view_item_sel_change, NULL );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
tree_sel = gtk_tree_view_get_selection(GTK_TREE_VIEW( file_browser->folder_view ));
g_signal_handlers_block_matched( tree_sel,
G_SIGNAL_MATCH_FUNC,
0, 0, NULL,
on_folder_view_item_sel_change, NULL );
model = gtk_tree_view_get_model( GTK_TREE_VIEW( file_browser->folder_view ) );
}
// test rows
gboolean first_select = TRUE;
if ( gtk_tree_model_get_iter_first( model, &it ) )
{
do
{
// get file
gtk_tree_model_get( model, &it, COL_FILE_INFO, &file, -1 );
if ( !file )
continue;
// test name
name = (char*)vfs_file_info_get_disp_name( file );
if ( icase )
name = g_utf8_strdown( name, -1 );
select = fnmatch( key, name, 0 ) == 0;
if ( icase )
g_free( name );
// do selection and scroll to first selected
path = gtk_tree_model_get_path( GTK_TREE_MODEL( PTK_FILE_LIST(
file_browser->file_list ) ), &it );
if ( file_browser->view_mode == PTK_FB_ICON_VIEW
|| file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
// select
if ( exo_icon_view_path_is_selected(
EXO_ICON_VIEW( file_browser->folder_view ), path ) )
{
if ( !select )
exo_icon_view_unselect_path(
EXO_ICON_VIEW( file_browser->folder_view ), path );
}
else if ( select )
exo_icon_view_select_path(
EXO_ICON_VIEW( file_browser->folder_view ), path );
// scroll to first and set cursor
if ( first_select && select )
{
exo_icon_view_set_cursor( EXO_ICON_VIEW(
file_browser->folder_view ), path, NULL, FALSE );
exo_icon_view_scroll_to_path( EXO_ICON_VIEW(
file_browser->folder_view ), path, TRUE, .25, 0 );
first_select = FALSE;
}
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
// select
if ( gtk_tree_selection_path_is_selected ( tree_sel, path ) )
{
if ( !select )
gtk_tree_selection_unselect_path( tree_sel, path );
}
else if ( select )
gtk_tree_selection_select_path( tree_sel, path );
// scroll to first and set cursor
if ( first_select && select )
{
gtk_tree_view_set_cursor(GTK_TREE_VIEW( file_browser->folder_view ),
path, NULL, FALSE);
gtk_tree_view_scroll_to_cell( GTK_TREE_VIEW( file_browser->folder_view ),
path, NULL, TRUE, .25, 0 );
first_select = FALSE;
}
}
gtk_tree_path_free( path );
}
while ( gtk_tree_model_iter_next( model, &it ) );
}
// restore signals and trigger sel change
if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
g_signal_handlers_unblock_matched( file_browser->folder_view,
G_SIGNAL_MATCH_FUNC,
0, 0, NULL,
on_folder_view_item_sel_change, NULL );
on_folder_view_item_sel_change( EXO_ICON_VIEW( file_browser->folder_view ),
file_browser );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
g_signal_handlers_unblock_matched( tree_sel,
G_SIGNAL_MATCH_FUNC,
0, 0, NULL,
on_folder_view_item_sel_change, NULL );
on_folder_view_item_sel_change( (ExoIconView*)tree_sel,
file_browser );
}
focus_folder_view( file_browser );
}
void ptk_file_browser_select_file_list( PtkFileBrowser* file_browser,
char** filename,
gboolean do_select )
{
// If do_select, select all filenames, unselect others
// if !do_select, unselect filenames, leave others unchanged
// If !*filename select or unselect all
GtkTreeModel* model;
GtkTreePath* path;
GtkTreeIter it;
GtkTreeSelection* tree_sel;
VFSFileInfo* file;
gboolean select;
char* name;
char** test_name;
if ( !filename || ! *filename )
{
if ( do_select )
ptk_file_browser_select_all( NULL, file_browser );
else
ptk_file_browser_unselect_all( NULL, file_browser );
return;
}
// get model, treesel, and stop signals
if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
model = exo_icon_view_get_model( EXO_ICON_VIEW( file_browser->folder_view ) );
g_signal_handlers_block_matched( file_browser->folder_view,
G_SIGNAL_MATCH_FUNC,
0, 0, NULL,
on_folder_view_item_sel_change, NULL );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
tree_sel = gtk_tree_view_get_selection(GTK_TREE_VIEW( file_browser->folder_view ));
g_signal_handlers_block_matched( tree_sel,
G_SIGNAL_MATCH_FUNC,
0, 0, NULL,
on_folder_view_item_sel_change, NULL );
model = gtk_tree_view_get_model( GTK_TREE_VIEW( file_browser->folder_view ) );
}
// test rows
gboolean first_select = TRUE;
if ( gtk_tree_model_get_iter_first( model, &it ) )
{
do
{
// get file
gtk_tree_model_get( model, &it, COL_FILE_INFO, &file, -1 );
if ( !file )
continue;
// test name
name = (char*)vfs_file_info_get_disp_name( file );
test_name = filename;
while ( *test_name )
{
if ( !strcmp( *test_name, name ) )
break;
test_name++;
}
if ( *test_name )
select = do_select;
else
select = !do_select;
// do selection and scroll to first selected
path = gtk_tree_model_get_path( GTK_TREE_MODEL( PTK_FILE_LIST(
file_browser->file_list ) ), &it );
if ( file_browser->view_mode == PTK_FB_ICON_VIEW
|| file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
// select
if ( exo_icon_view_path_is_selected(
EXO_ICON_VIEW( file_browser->folder_view ), path ) )
{
if ( !select )
exo_icon_view_unselect_path(
EXO_ICON_VIEW( file_browser->folder_view ), path );
}
else if ( select && do_select )
exo_icon_view_select_path(
EXO_ICON_VIEW( file_browser->folder_view ), path );
// scroll to first and set cursor
if ( first_select && select && do_select )
{
exo_icon_view_set_cursor( EXO_ICON_VIEW(
file_browser->folder_view ), path, NULL, FALSE );
exo_icon_view_scroll_to_path( EXO_ICON_VIEW(
file_browser->folder_view ), path, TRUE, .25, 0 );
first_select = FALSE;
}
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
// select
if ( gtk_tree_selection_path_is_selected ( tree_sel, path ) )
{
if ( !select )
gtk_tree_selection_unselect_path( tree_sel, path );
}
else if ( select && do_select )
gtk_tree_selection_select_path( tree_sel, path );
// scroll to first and set cursor
if ( first_select && select && do_select )
{
gtk_tree_view_set_cursor(GTK_TREE_VIEW( file_browser->folder_view ),
path, NULL, FALSE);
gtk_tree_view_scroll_to_cell( GTK_TREE_VIEW( file_browser->folder_view ),
path, NULL, TRUE, .25, 0 );
first_select = FALSE;
}
}
gtk_tree_path_free( path );
}
while ( gtk_tree_model_iter_next( model, &it ) );
}
// restore signals and trigger sel change
if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
g_signal_handlers_unblock_matched( file_browser->folder_view,
G_SIGNAL_MATCH_FUNC,
0, 0, NULL,
on_folder_view_item_sel_change, NULL );
on_folder_view_item_sel_change( EXO_ICON_VIEW( file_browser->folder_view ),
file_browser );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
g_signal_handlers_unblock_matched( tree_sel,
G_SIGNAL_MATCH_FUNC,
0, 0, NULL,
on_folder_view_item_sel_change, NULL );
on_folder_view_item_sel_change( (ExoIconView*)tree_sel,
file_browser );
}
focus_folder_view( file_browser );
}
void ptk_file_browser_seek_path( PtkFileBrowser* file_browser,
const char* seek_dir,
const char* seek_name )
{
// change to dir seek_dir if needed; select first dir or else file with
// prefix seek_name
const char* cwd = ptk_file_browser_get_cwd( file_browser );
if ( seek_dir && g_strcmp0( cwd, seek_dir ) )
{
// change dir
g_free( file_browser->seek_name );
file_browser->seek_name = g_strdup( seek_name );
file_browser->inhibit_focus = TRUE;
if ( !ptk_file_browser_chdir( file_browser, seek_dir,
PTK_FB_CHDIR_ADD_HISTORY ) )
{
file_browser->inhibit_focus = FALSE;
g_free( file_browser->seek_name );
file_browser->seek_name = NULL;
}
// return here to allow dir to load
// finishes seek in main-window.c on_file_browser_after_chdir()
return;
}
// no change dir was needed or was called from on_file_browser_after_chdir()
// select seek name
ptk_file_browser_unselect_all( NULL, file_browser );
if ( !( seek_name && seek_name[0] ) )
return;
// get model, treesel, and stop signals
GtkTreeModel* model;
GtkTreePath* path;
GtkTreeIter it;
GtkTreeIter it_file;
GtkTreeIter it_dir;
it_file.stamp = 0;
it_dir.stamp = 0;
GtkTreeSelection* tree_sel;
VFSFileInfo* file;
gboolean select;
char* name;
if ( file_browser->view_mode == PTK_FB_ICON_VIEW ||
file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
model = exo_icon_view_get_model( EXO_ICON_VIEW( file_browser->folder_view ) );
g_signal_handlers_block_matched( file_browser->folder_view,
G_SIGNAL_MATCH_FUNC,
0, 0, NULL,
on_folder_view_item_sel_change, NULL );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
tree_sel = gtk_tree_view_get_selection(GTK_TREE_VIEW( file_browser->folder_view ));
g_signal_handlers_block_matched( tree_sel,
G_SIGNAL_MATCH_FUNC,
0, 0, NULL,
on_folder_view_item_sel_change, NULL );
model = gtk_tree_view_get_model( GTK_TREE_VIEW( file_browser->folder_view ) );
}
if ( !GTK_IS_TREE_MODEL( model ) )
goto _restore_sig;
// test rows - give preference to matching dir, else match file
if ( gtk_tree_model_get_iter_first( model, &it ) )
{
do
{
// get file
gtk_tree_model_get( model, &it, COL_FILE_INFO, &file, -1 );
if ( !file )
continue;
// test name
name = (char*)vfs_file_info_get_disp_name( file );
if ( !g_strcmp0( name, seek_name ) )
{
// exact match (may be file or dir)
it_dir = it;
break;
}
if ( g_str_has_prefix( name, seek_name ) )
{
// prefix found
if ( vfs_file_info_is_dir( file ) )
{
if ( !it_dir.stamp )
it_dir = it;
}
else if ( !it_file.stamp )
it_file = it;
}
}
while ( gtk_tree_model_iter_next( model, &it ) );
}
if ( it_dir.stamp )
it = it_dir;
else
it = it_file;
if ( !it.stamp )
goto _restore_sig;
// do selection and scroll to selected
path = gtk_tree_model_get_path( GTK_TREE_MODEL( PTK_FILE_LIST(
file_browser->file_list ) ), &it );
if ( !path )
goto _restore_sig;
if ( file_browser->view_mode == PTK_FB_ICON_VIEW
|| file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
// select
exo_icon_view_select_path(
EXO_ICON_VIEW( file_browser->folder_view ), path );
// scroll and set cursor
exo_icon_view_set_cursor( EXO_ICON_VIEW(
file_browser->folder_view ), path, NULL, FALSE );
exo_icon_view_scroll_to_path( EXO_ICON_VIEW(
file_browser->folder_view ), path, TRUE, .25, 0 );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
// select
gtk_tree_selection_select_path( tree_sel, path );
// scroll and set cursor
gtk_tree_view_set_cursor(GTK_TREE_VIEW( file_browser->folder_view ),
path, NULL, FALSE);
gtk_tree_view_scroll_to_cell( GTK_TREE_VIEW( file_browser->folder_view ),
path, NULL, TRUE, .25, 0 );
}
gtk_tree_path_free( path );
_restore_sig:
// restore signals and trigger sel change
if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
g_signal_handlers_unblock_matched( file_browser->folder_view,
G_SIGNAL_MATCH_FUNC,
0, 0, NULL,
on_folder_view_item_sel_change, NULL );
on_folder_view_item_sel_change( EXO_ICON_VIEW( file_browser->folder_view ),
file_browser );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
g_signal_handlers_unblock_matched( tree_sel,
G_SIGNAL_MATCH_FUNC,
0, 0, NULL,
on_folder_view_item_sel_change, NULL );
on_folder_view_item_sel_change( (ExoIconView*)tree_sel,
file_browser );
}
}
/* signal handlers */
void
on_folder_view_item_activated ( ExoIconView *iconview,
GtkTreePath *path,
PtkFileBrowser* file_browser )
{
ptk_file_browser_open_selected_files_with_app( file_browser, NULL );
}
void
on_folder_view_row_activated ( GtkTreeView *tree_view,
GtkTreePath *path,
GtkTreeViewColumn* col,
PtkFileBrowser* file_browser )
{
//file_browser->button_press = FALSE;
ptk_file_browser_open_selected_files_with_app( file_browser, NULL );
}
gboolean on_folder_view_item_sel_change_idle( PtkFileBrowser* file_browser )
{
GList * sel_files;
GList* sel;
GtkTreeIter it;
GtkTreeModel* model;
VFSFileInfo* file;
if ( !GTK_IS_WIDGET( file_browser ) )
return FALSE;
file_browser->n_sel_files = 0;
file_browser->sel_size = 0;
sel_files = folder_view_get_selected_items( file_browser, &model );
for ( sel = sel_files; sel; sel = g_list_next( sel ) )
{
if ( gtk_tree_model_get_iter( model, &it, ( GtkTreePath* ) sel->data ) )
{
gtk_tree_model_get( model, &it, COL_FILE_INFO, &file, -1 );
if ( file )
{
file_browser->sel_size += vfs_file_info_get_size( file );
vfs_file_info_unref( file );
}
++file_browser->n_sel_files;
}
}
g_list_foreach( sel_files,
( GFunc ) gtk_tree_path_free,
NULL );
g_list_free( sel_files );
g_signal_emit( file_browser, signals[ SEL_CHANGE_SIGNAL ], 0 );
file_browser->sel_change_idle = 0;
return FALSE;
}
void on_folder_view_item_sel_change( ExoIconView *iconview,
PtkFileBrowser* file_browser )
{
/* //sfm on_folder_view_item_sel_change fires for each selected file
* when a file is clicked - causes hang if thousands of files are selected
* So add only one g_idle_add at a time
*/
if ( file_browser->sel_change_idle )
return;
file_browser->sel_change_idle = g_idle_add(
(GSourceFunc)on_folder_view_item_sel_change_idle,
file_browser );
}
#if 0
static gboolean
is_latin_shortcut_key ( guint keyval )
{
return ((GDK_0 <= keyval && keyval <= GDK_9) ||
(GDK_A <= keyval && keyval <= GDK_Z) ||
(GDK_a <= keyval && keyval <= GDK_z));
}
gboolean
on_folder_view_key_press_event ( GtkWidget *widget,
GdkEventKey *event,
PtkFileBrowser* file_browser )
{
int modifier = ( event->state & ( GDK_SHIFT_MASK | GDK_CONTROL_MASK | GDK_MOD1_MASK ) );
if ( ! gtk_widget_is_focus( widget ) )
return FALSE;
//printf("on_folder_view_key_press_event\n");
// Make key bindings work when the current keyboard layout is not latin
if ( modifier != 0 && !is_latin_shortcut_key( event->keyval ) ) {
// We have a non-latin char, try other keyboard groups
GdkKeymapKey *keys;
guint *keyvals;
gint n_entries;
gint level;
if ( gdk_keymap_translate_keyboard_state( NULL,
event->hardware_keycode,
(GdkModifierType)event->state,
event->group,
NULL, NULL, &level, NULL )
&& gdk_keymap_get_entries_for_keycode( NULL,
event->hardware_keycode,
&keys, &keyvals,
&n_entries ) ) {
gint n;
for ( n=0; n<n_entries; n++ ) {
if ( keys[n].group == event->group ) {
// Skip keys from the same group
continue;
}
if ( keys[n].level != level ) {
// Allow only same level keys
continue;
}
if ( is_latin_shortcut_key( keyvals[n] ) ) {
// Latin character found
event->keyval = keyvals[n];
break;
}
}
g_free( keys );
g_free( keyvals );
}
}
if ( modifier == GDK_CONTROL_MASK )
{
switch ( event->keyval )
{
case GDK_x:
ptk_file_browser_cut( file_browser );
break;
case GDK_c:
ptk_file_browser_copy( file_browser );
break;
case GDK_v:
ptk_file_browser_paste( file_browser );
return TRUE;
break;
case GDK_i:
//ptk_file_browser_invert_selection( file_browser );
break;
case GDK_a:
//ptk_file_browser_select_all( file_browser );
break;
case GDK_h:
ptk_file_browser_show_hidden_files(
file_browser,
! file_browser->show_hidden_files );
break;
default:
return FALSE;
}
}
else if ( modifier == GDK_MOD1_MASK )
{
switch ( event->keyval )
{
case GDK_Return:
ptk_file_browser_file_properties( file_browser, 0 );
break;
default:
return FALSE;
}
}
else if ( modifier == GDK_SHIFT_MASK )
{
switch ( event->keyval )
{
case GDK_Delete:
ptk_file_browser_delete( file_browser );
break;
default:
return FALSE;
}
}
else if ( modifier == 0 )
{
switch ( event->keyval )
{
case GDK_F2:
//ptk_file_browser_rename_selected_files( file_browser );
break;
case GDK_Delete:
ptk_file_browser_delete( file_browser );
break;
case GDK_BackSpace:
ptk_file_browser_go_up( NULL, file_browser );
break;
default:
return FALSE;
}
}
/* else if ( modifier == ( GDK_SHIFT_MASK | GDK_MOD1_MASK ) ) //MOD added
{
switch ( event->keyval )
{
case GDK_C:
ptk_file_browser_copy_name( file_browser );
return TRUE;
break;
case GDK_V:
ptk_file_browser_paste_target( file_browser );
return TRUE;
break;
default:
return FALSE;
}
}
else if ( modifier == ( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) //MOD added
{
switch ( event->keyval )
{
case GDK_C:
ptk_file_browser_copy_text( file_browser );
return TRUE;
break;
case GDK_V:
ptk_file_browser_paste_link( file_browser );
return TRUE;
break;
default:
return FALSE;
}
}
*/
else
{
return FALSE;
}
return TRUE;
}
#endif
static void show_popup_menu( PtkFileBrowser* file_browser,
GdkEventButton *event )
{
const char * cwd;
char* dir_name = NULL;
guint32 time;
gint button;
GtkWidget* popup;
char* file_path = NULL;
VFSFileInfo* file;
GList* sel_files;
cwd = ptk_file_browser_get_cwd( file_browser );
sel_files = ptk_file_browser_get_selected_files( file_browser );
if( ! sel_files )
{
file = NULL;
/*
file = vfs_file_info_new();
vfs_file_info_get( file, cwd, NULL );
sel_files = g_list_prepend( NULL, vfs_file_info_ref( file ) );
file_path = g_strdup( cwd );
*/ /* dir_name = g_path_get_dirname( cwd ); */
}
else
{
file = vfs_file_info_ref( (VFSFileInfo*)sel_files->data );
file_path = g_build_filename( cwd, vfs_file_info_get_name( file ), NULL );
}
//MOD added G_FILE_TEST_IS_SYMLINK for dangling symlink popup menu
// if ( g_file_test( file_path, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_SYMLINK ) )
// {
if ( event )
{
button = event->button;
time = event->time;
}
else
{
button = 0;
time = gtk_get_current_event_time();
}
popup = ptk_file_menu_new( NULL, file_browser,
file_path, file,
dir_name ? dir_name : cwd,
sel_files );
if ( popup )
gtk_menu_popup( GTK_MENU( popup ), NULL, NULL, NULL, NULL,
button, time );
// }
// else if ( sel_files )
// {
// vfs_file_info_list_free( sel_files );
// }
if ( file )
vfs_file_info_unref( file );
if ( file_path )
g_free( file_path );
if ( dir_name )
g_free( dir_name );
}
/* invoke popup menu via shortcut key */
gboolean
on_folder_view_popup_menu ( GtkWidget* widget, PtkFileBrowser* file_browser )
{
show_popup_menu( file_browser, NULL );
return TRUE;
}
gboolean
on_folder_view_button_press_event ( GtkWidget *widget,
GdkEventButton *event,
PtkFileBrowser* file_browser )
{
VFSFileInfo * file;
GtkTreeModel * model = NULL;
GtkTreePath *tree_path = NULL;
GtkTreeViewColumn* col = NULL;
GtkTreeIter it;
gchar *file_path;
GtkTreeSelection* tree_sel;
gboolean ret = FALSE;
if ( event->type == GDK_BUTTON_PRESS )
{
focus_folder_view( file_browser );
//file_browser->button_press = TRUE;
if ( ( evt_win_click->s || evt_win_click->ob2_data ) &&
main_window_event( file_browser->main_window, evt_win_click, "evt_win_click",
0, 0, "filelist", 0, event->button,
event->state, TRUE ) )
{
file_browser->skip_release = TRUE;
return TRUE;
}
if ( event->button > 3 && event->button < 10 ) //sfm
{
if ( event->button == 4 || event->button == 6 || event->button == 8 )
ptk_file_browser_go_back( NULL, file_browser );
else
ptk_file_browser_go_forward( NULL, file_browser );
return TRUE;
}
// Alt - Left/Right Click
if ( ( ( event->state & ( GDK_SHIFT_MASK | GDK_CONTROL_MASK | GDK_MOD1_MASK ) )
== GDK_MOD1_MASK ) &&
( event->button == 1 || event->button == 3 ) ) //sfm
{
if ( event->button == 1 )
ptk_file_browser_go_back( NULL, file_browser );
else
ptk_file_browser_go_forward( NULL, file_browser );
return TRUE;
}
if ( file_browser->view_mode == PTK_FB_ICON_VIEW
|| file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
tree_path = exo_icon_view_get_path_at_pos( EXO_ICON_VIEW( widget ),
event->x, event->y );
model = exo_icon_view_get_model( EXO_ICON_VIEW( widget ) );
/* deselect selected files when right click on blank area */
if ( !tree_path && event->button == 3 )
exo_icon_view_unselect_all ( EXO_ICON_VIEW( widget ) );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
model = gtk_tree_view_get_model( GTK_TREE_VIEW( widget ) );
gtk_tree_view_get_path_at_pos( GTK_TREE_VIEW( widget ),
event->x, event->y, &tree_path, &col,
NULL, NULL );
tree_sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( widget ) );
if( col && gtk_tree_view_column_get_sort_column_id(col) !=
COL_FILE_NAME && tree_path ) //MOD
{
gtk_tree_path_free( tree_path );
tree_path = NULL;
}
}
/* an item is clicked, get its file path */
if ( tree_path && gtk_tree_model_get_iter( model, &it, tree_path ) )
{
gtk_tree_model_get( model, &it, COL_FILE_INFO, &file, -1 );
file_path = g_build_filename( ptk_file_browser_get_cwd( file_browser ),
vfs_file_info_get_name( file ), NULL );
}
else /* no item is clicked */
{
file = NULL;
file_path = NULL;
}
/* middle button */
if ( event->button == 2 && file_path ) /* middle click on a item */
{
/* open in new tab if its a folder */
if ( G_LIKELY( file_path ) )
{
if ( g_file_test( file_path, G_FILE_TEST_IS_DIR ) )
{
g_signal_emit( file_browser, signals[ OPEN_ITEM_SIGNAL ], 0,
file_path, PTK_OPEN_NEW_TAB );
}
}
ret = TRUE;
}
else if ( event->button == 3 ) /* right click */
{
/* cancel all selection, and select the item if it's not selected */
if ( file_browser->view_mode == PTK_FB_ICON_VIEW
|| file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
if ( tree_path &&
!exo_icon_view_path_is_selected ( EXO_ICON_VIEW( widget ),
tree_path ) )
{
exo_icon_view_unselect_all ( EXO_ICON_VIEW( widget ) );
exo_icon_view_select_path( EXO_ICON_VIEW( widget ), tree_path );
}
}
else if( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
if ( tree_path &&
!gtk_tree_selection_path_is_selected( tree_sel, tree_path ) )
{
gtk_tree_selection_unselect_all( tree_sel );
gtk_tree_selection_select_path( tree_sel, tree_path );
}
}
show_popup_menu( file_browser, event );
/* FIXME if approx 5000 are selected, right-click sometimes unselects all
* after this button_press function returns - why? a gtk or exo bug?
* Always happens with above show_popup_menu call disabled
* Only when this occurs, cursor is automatically set to current row and
* treesel 'changed' signal fires
* Stopping changed signal had no effect
* Using connect rather than connect_after had no effect
* Removing signal connect had no effect */
ret = TRUE;
}
if ( file )
vfs_file_info_unref( file );
g_free( file_path );
gtk_tree_path_free( tree_path );
}
else if ( event->type == GDK_2BUTTON_PRESS && event->button == 1 )
{
// double click event - button = 0
if ( ( evt_win_click->s || evt_win_click->ob2_data ) &&
main_window_event( file_browser->main_window, evt_win_click, "evt_win_click",
0, 0, "filelist", 0, 0,
event->state, TRUE ) )
return TRUE;
}
/* go up if double-click in blank area of file list - this was disabled due
* to complaints about accidental clicking
else if ( file_browser->button_press && event->type == GDK_2BUTTON_PRESS
&& event->button == 1 )
{
if ( file_browser->view_mode == PTK_FB_ICON_VIEW
* || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
tree_path = exo_icon_view_get_path_at_pos( EXO_ICON_VIEW( widget ),
event->x, event->y );
if ( !tree_path )
{
ptk_file_browser_go_up( NULL, file_browser );
ret = TRUE;
}
else
gtk_tree_path_free( tree_path );
}
else if( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
// row_activated occurs before GDK_2BUTTON_PRESS so use
// file_browser->button_press to determine if row was already activated
// or user clicked on non-row
ptk_file_browser_go_up( NULL, file_browser );
ret = TRUE;
}
}
*/
return ret;
}
gboolean
on_folder_view_button_release_event ( GtkWidget *widget,
GdkEventButton *event,
PtkFileBrowser* file_browser ) //sfm
{ // on left-click release on file, if not dnd or rubberbanding, unselect files
GtkTreeModel* model;
GtkTreePath* tree_path = NULL;
GtkTreeSelection* tree_sel;
if ( file_browser->is_drag || event->button != 1 || file_browser->skip_release ||
( event->state & ( GDK_SHIFT_MASK | GDK_CONTROL_MASK | GDK_MOD1_MASK ) ) )
{
if ( file_browser->skip_release )
file_browser->skip_release = FALSE;
return FALSE;
}
if ( file_browser->view_mode == PTK_FB_ICON_VIEW
|| file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
if ( exo_icon_view_is_rubber_banding_active( EXO_ICON_VIEW( widget ) ) )
return FALSE;
tree_path = exo_icon_view_get_path_at_pos( EXO_ICON_VIEW( widget ),
event->x, event->y );
model = exo_icon_view_get_model( EXO_ICON_VIEW( widget ) );
if ( tree_path )
{
// unselect all but one file
exo_icon_view_unselect_all( EXO_ICON_VIEW( widget ) );
exo_icon_view_select_path( EXO_ICON_VIEW( widget ), tree_path );
}
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
if ( gtk_tree_view_is_rubber_banding_active( GTK_TREE_VIEW( widget ) ) )
return FALSE;
if ( app_settings.single_click )
{
model = gtk_tree_view_get_model( GTK_TREE_VIEW( widget ) );
gtk_tree_view_get_path_at_pos( GTK_TREE_VIEW( widget ),
event->x, event->y, &tree_path,
NULL, NULL, NULL );
tree_sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( widget ) );
if ( tree_path && tree_sel &&
gtk_tree_selection_count_selected_rows( tree_sel ) > 1 )
{
// unselect all but one file
gtk_tree_selection_unselect_all( tree_sel );
gtk_tree_selection_select_path( tree_sel, tree_path );
}
}
}
gtk_tree_path_free( tree_path );
return FALSE;
}
static gboolean on_dir_tree_update_sel ( PtkFileBrowser* file_browser )
{
char * dir_path;
if ( !file_browser->side_dir )
return FALSE;
dir_path = ptk_dir_tree_view_get_selected_dir( GTK_TREE_VIEW(
file_browser->side_dir ) );
if ( dir_path )
{
if ( strcmp( dir_path, ptk_file_browser_get_cwd( file_browser ) ) )
{
gdk_threads_enter(); // needed for gtk_dialog_run in ptk_show_error
ptk_file_browser_chdir( file_browser, dir_path, PTK_FB_CHDIR_ADD_HISTORY);
gdk_threads_leave();
}
g_free( dir_path );
}
return FALSE;
}
void
on_dir_tree_sel_changed ( GtkTreeSelection *treesel,
PtkFileBrowser* file_browser )
{
g_idle_add( ( GSourceFunc ) on_dir_tree_update_sel, file_browser );
}
void on_shortcut_new_tab_activate( GtkMenuItem* item,
PtkFileBrowser* file_browser )
{
const char* dir_path;
focus_folder_view( file_browser );
if ( xset_get_s( "go_set_default" ) )
dir_path = xset_get_s( "go_set_default" );
else
dir_path = g_get_home_dir();
if ( !g_file_test( dir_path, G_FILE_TEST_IS_DIR ) )
g_signal_emit( file_browser,
signals[ OPEN_ITEM_SIGNAL ],
0, "/", PTK_OPEN_NEW_TAB );
else
{
g_signal_emit( file_browser,
signals[ OPEN_ITEM_SIGNAL ],
0, dir_path, PTK_OPEN_NEW_TAB );
}
}
void on_shortcut_new_tab_here( GtkMenuItem* item,
PtkFileBrowser* file_browser )
{
const char* dir_path;
focus_folder_view( file_browser );
dir_path = ptk_file_browser_get_cwd( file_browser );
if ( !g_file_test( dir_path, G_FILE_TEST_IS_DIR ) )
{
if ( xset_get_s( "go_set_default" ) )
dir_path = xset_get_s( "go_set_default" );
else
dir_path = g_get_home_dir();
}
if ( !g_file_test( dir_path, G_FILE_TEST_IS_DIR ) )
g_signal_emit( file_browser,
signals[ OPEN_ITEM_SIGNAL ],
0, "/", PTK_OPEN_NEW_TAB );
else
{
g_signal_emit( file_browser,
signals[ OPEN_ITEM_SIGNAL ],
0, dir_path, PTK_OPEN_NEW_TAB );
}
}
/*
void on_shortcut_new_window_activate( GtkMenuItem* item,
PtkFileBrowser* file_browser )
{
char * dir_path;
dir_path = ptk_location_view_get_selected_dir( file_browser->side_dir );
if ( dir_path )
{
g_signal_emit( file_browser,
signals[ OPEN_ITEM_SIGNAL ],
0, dir_path, PTK_OPEN_NEW_WINDOW );
g_free( dir_path );
}
}
static void on_shortcut_remove_activate( GtkMenuItem* item,
PtkFileBrowser* file_browser )
{
char * dir_path;
dir_path = ptk_location_view_get_selected_dir( file_browser->side_dir );
if ( dir_path )
{
ptk_bookmarks_remove( dir_path );
g_free( dir_path );
}
}
static void on_shortcut_rename_activate( GtkMenuItem* item,
PtkFileBrowser* file_browser )
{
ptk_location_view_rename_selected_bookmark( file_browser->side_dir );
}
static PtkMenuItemEntry shortcut_popup_menu[] =
{
PTK_MENU_ITEM( N_( "Open in New _Tab" ), on_shortcut_new_tab_activate, 0, 0 ),
PTK_MENU_ITEM( N_( "Open in New _Window" ), on_shortcut_new_window_activate, 0, 0 ),
PTK_SEPARATOR_MENU_ITEM,
PTK_STOCK_MENU_ITEM( GTK_STOCK_REMOVE, on_shortcut_remove_activate ),
PTK_IMG_MENU_ITEM( N_( "_Rename" ), "gtk-edit", on_shortcut_rename_activate, GDK_F2, 0 ),
PTK_MENU_END
};
*/
void on_folder_view_columns_changed( GtkTreeView *view,
PtkFileBrowser* file_browser )
{
const char* title;
char* pos;
XSet* set = NULL;
int i, j, width;
GtkTreeViewColumn* col;
if ( !( GTK_IS_WIDGET( file_browser ) && GTK_IS_TREE_VIEW( view ) ) )
return;
if ( file_browser->view_mode != PTK_FB_LIST_VIEW )
return;
gboolean fullscreen = xset_get_b( "main_full" );
const char* titles[] = // also change main_window_socket_command col_titles[]
{
N_( "Name" ), N_( "Size" ), N_( "Type" ),
N_( "Permission" ), N_( "Owner" ), N_( "Modified" )
};
const char* set_names[] =
{
"detcol_name", "detcol_size", "detcol_type",
"detcol_perm", "detcol_owner", "detcol_date"
};
for ( i = 0; i < 6; i++ )
{
col = gtk_tree_view_get_column( view, i );
if ( !col )
return;
title = gtk_tree_view_column_get_title( col );
for ( j = 0; j < 6; j++ )
{
if ( !strcmp( title, _(titles[j]) ) )
break;
}
if ( j != 6 )
{
set = xset_get_panel( file_browser->mypanel, set_names[j] );
// save column position
pos = g_strdup_printf( "%d", i );
xset_set_set( set, "x", pos );
g_free( pos );
// save column width
if ( !fullscreen && ( width = gtk_tree_view_column_get_width( col ) ) )
{
pos = g_strdup_printf( "%d", width );
xset_set_set( set, "y", pos );
g_free( pos );
}
// set column visibility
gtk_tree_view_column_set_visible( col,
xset_get_b_panel( file_browser->mypanel, set_names[j] ) );
}
}
}
void on_folder_view_destroy( GtkTreeView *view, PtkFileBrowser* file_browser )
{
guint id = g_signal_lookup ("columns-changed", G_TYPE_FROM_INSTANCE(view) );
if ( id )
{
gulong hand = g_signal_handler_find( ( gpointer ) view, G_SIGNAL_MATCH_ID,
id, 0, NULL, NULL, NULL );
if ( hand )
g_signal_handler_disconnect( ( gpointer ) view, hand );
}
//on_folder_view_columns_changed( view, file_browser ); // save widths
}
gboolean folder_view_search_equal( GtkTreeModel* model, gint col,
const gchar* key,
GtkTreeIter* it,
gpointer search_data )
{
char* name;
char* lower_name = NULL;
char* lower_key;
gboolean no_match;
if ( col != COL_FILE_NAME )
return TRUE;
gtk_tree_model_get( model, it, col, &name, -1 );
if ( !name || !key )
return TRUE;
lower_key = g_utf8_strdown( key, -1 );
if ( !strcmp( lower_key, key ) )
{
// key is all lowercase so do icase search
lower_name = g_utf8_strdown( name, -1 );
name = lower_name;
}
if ( strchr( key, '*' ) || strchr( key, '?' ) )
{
char* key2 = g_strdup_printf( "*%s*", key );
no_match = fnmatch( key2, name, 0 ) != 0;
g_free( key2 );
}
else
{
gboolean start = ( key[0] == '^' );
gboolean end = g_str_has_suffix( key, "$" );
char* key2 = g_strdup( key );
char* keyp = key2;
if ( start )
keyp++;
if ( end )
key2[strlen( key2 )-1] = '\0';
if ( start && end )
no_match = !strstr( name, keyp );
else if (start )
no_match = !g_str_has_prefix( name, keyp );
else if ( end )
no_match = !g_str_has_suffix( name, keyp );
else
no_match = !strstr( name, key );
g_free( key2 );
}
g_free( lower_name );
g_free( lower_key );
return no_match; //return FALSE for match
}
static GtkWidget* create_folder_view( PtkFileBrowser* file_browser,
PtkFBViewMode view_mode )
{
GtkWidget * folder_view = NULL;
GtkTreeSelection* tree_sel;
GtkCellRenderer* renderer;
int big_icon_size, small_icon_size, icon_size = 0;
vfs_mime_type_get_icon_size( &big_icon_size, &small_icon_size );
switch ( view_mode )
{
case PTK_FB_ICON_VIEW:
case PTK_FB_COMPACT_VIEW:
folder_view = exo_icon_view_new();
if( view_mode == PTK_FB_COMPACT_VIEW )
{
exo_icon_view_set_layout_mode( (ExoIconView*)folder_view, EXO_ICON_VIEW_LAYOUT_COLS );
exo_icon_view_set_orientation( (ExoIconView*)folder_view, GTK_ORIENTATION_HORIZONTAL );
}
else
{
exo_icon_view_set_column_spacing( (ExoIconView*)folder_view, 4 );
exo_icon_view_set_item_width ( (ExoIconView*)folder_view, 110 );
}
exo_icon_view_set_selection_mode ( (ExoIconView*)folder_view,
GTK_SELECTION_MULTIPLE );
exo_icon_view_set_pixbuf_column ( (ExoIconView*)folder_view, COL_FILE_BIG_ICON );
exo_icon_view_set_text_column ( (ExoIconView*)folder_view, COL_FILE_NAME );
// search
exo_icon_view_set_enable_search( (ExoIconView*)folder_view, TRUE );
exo_icon_view_set_search_column( (ExoIconView*)folder_view, COL_FILE_NAME );
exo_icon_view_set_search_equal_func( (ExoIconView*)folder_view,
folder_view_search_equal, NULL, NULL );
exo_icon_view_set_single_click( (ExoIconView*)folder_view, file_browser->single_click );
exo_icon_view_set_single_click_timeout( (ExoIconView*)folder_view,
SINGLE_CLICK_TIMEOUT );
gtk_cell_layout_clear ( GTK_CELL_LAYOUT ( folder_view ) );
/* renderer = gtk_cell_renderer_pixbuf_new (); */
file_browser->icon_render = renderer = ptk_file_icon_renderer_new();
/* add the icon renderer */
g_object_set ( G_OBJECT ( renderer ),
"follow_state", TRUE,
NULL );
gtk_cell_layout_pack_start ( GTK_CELL_LAYOUT ( folder_view ), renderer, FALSE );
gtk_cell_layout_add_attribute ( GTK_CELL_LAYOUT ( folder_view ), renderer,
"pixbuf", view_mode == PTK_FB_COMPACT_VIEW ? COL_FILE_SMALL_ICON : COL_FILE_BIG_ICON );
gtk_cell_layout_add_attribute ( GTK_CELL_LAYOUT ( folder_view ), renderer,
"info", COL_FILE_INFO );
/* add the name renderer */
renderer = ptk_text_renderer_new ();
if( view_mode == PTK_FB_COMPACT_VIEW )
{
g_object_set ( G_OBJECT ( renderer ),
"xalign", 0.0,
"yalign", 0.5,
NULL );
icon_size = small_icon_size;
}
else
{
g_object_set ( G_OBJECT ( renderer ),
"wrap-mode", PANGO_WRAP_WORD_CHAR,
"wrap-width", 109,
"xalign", 0.5,
"yalign", 0.0,
NULL );
icon_size = big_icon_size;
}
gtk_cell_layout_pack_start ( GTK_CELL_LAYOUT ( folder_view ), renderer, TRUE );
gtk_cell_layout_add_attribute ( GTK_CELL_LAYOUT ( folder_view ), renderer,
"text", COL_FILE_NAME );
exo_icon_view_enable_model_drag_source (
EXO_ICON_VIEW( folder_view ),
( GDK_CONTROL_MASK | GDK_BUTTON1_MASK | GDK_BUTTON3_MASK ),
drag_targets, G_N_ELEMENTS( drag_targets ), GDK_ACTION_ALL );
exo_icon_view_enable_model_drag_dest (
EXO_ICON_VIEW( folder_view ),
drag_targets, G_N_ELEMENTS( drag_targets ), GDK_ACTION_ALL );
g_signal_connect ( ( gpointer ) folder_view,
"item-activated",
G_CALLBACK ( on_folder_view_item_activated ),
file_browser );
g_signal_connect_after ( ( gpointer ) folder_view,
"selection-changed",
G_CALLBACK ( on_folder_view_item_sel_change ),
file_browser );
break;
case PTK_FB_LIST_VIEW:
folder_view = exo_tree_view_new ();
init_list_view( file_browser, GTK_TREE_VIEW( folder_view ) );
tree_sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( folder_view ) );
gtk_tree_selection_set_mode( tree_sel, GTK_SELECTION_MULTIPLE );
if ( xset_get_b( "rubberband" ) )
gtk_tree_view_set_rubber_banding( (GtkTreeView*)folder_view, TRUE );
// Search
gtk_tree_view_set_enable_search( (GtkTreeView*)folder_view, TRUE );
gtk_tree_view_set_search_column( (GtkTreeView*)folder_view, COL_FILE_NAME );
gtk_tree_view_set_search_equal_func( (GtkTreeView*)folder_view,
folder_view_search_equal, NULL, NULL );
exo_tree_view_set_single_click( (ExoTreeView*)folder_view, file_browser->single_click );
exo_tree_view_set_single_click_timeout( (ExoTreeView*)folder_view,
SINGLE_CLICK_TIMEOUT );
icon_size = small_icon_size;
gtk_tree_view_enable_model_drag_source (
GTK_TREE_VIEW( folder_view ),
( GDK_CONTROL_MASK | GDK_BUTTON1_MASK | GDK_BUTTON3_MASK ),
drag_targets, G_N_ELEMENTS( drag_targets ), GDK_ACTION_ALL );
gtk_tree_view_enable_model_drag_dest (
GTK_TREE_VIEW( folder_view ),
drag_targets, G_N_ELEMENTS( drag_targets ), GDK_ACTION_ALL );
g_signal_connect ( ( gpointer ) folder_view,
"row_activated",
G_CALLBACK ( on_folder_view_row_activated ),
file_browser );
g_signal_connect_after ( ( gpointer ) tree_sel,
"changed",
G_CALLBACK ( on_folder_view_item_sel_change ),
file_browser );
//MOD
g_signal_connect ( ( gpointer ) folder_view, "columns-changed",
G_CALLBACK ( on_folder_view_columns_changed ),
file_browser );
g_signal_connect ( ( gpointer ) folder_view, "destroy",
G_CALLBACK ( on_folder_view_destroy ),
file_browser );
break;
}
gtk_cell_renderer_set_fixed_size( file_browser->icon_render, icon_size, icon_size );
g_signal_connect ( ( gpointer ) folder_view,
"button-press-event",
G_CALLBACK ( on_folder_view_button_press_event ),
file_browser );
g_signal_connect ( ( gpointer ) folder_view,
"button-release-event",
G_CALLBACK ( on_folder_view_button_release_event ),
file_browser );
//g_signal_connect ( ( gpointer ) folder_view,
// "key_press_event",
// G_CALLBACK ( on_folder_view_key_press_event ),
// file_browser );
g_signal_connect ( ( gpointer ) folder_view,
"popup-menu",
G_CALLBACK ( on_folder_view_popup_menu ),
file_browser );
/* init drag & drop support */
g_signal_connect ( ( gpointer ) folder_view, "drag-data-received",
G_CALLBACK ( on_folder_view_drag_data_received ),
file_browser );
g_signal_connect ( ( gpointer ) folder_view, "drag-data-get",
G_CALLBACK ( on_folder_view_drag_data_get ),
file_browser );
g_signal_connect ( ( gpointer ) folder_view, "drag-begin",
G_CALLBACK ( on_folder_view_drag_begin ),
file_browser );
g_signal_connect ( ( gpointer ) folder_view, "drag-motion",
G_CALLBACK ( on_folder_view_drag_motion ),
file_browser );
g_signal_connect ( ( gpointer ) folder_view, "drag-leave",
G_CALLBACK ( on_folder_view_drag_leave ),
file_browser );
g_signal_connect ( ( gpointer ) folder_view, "drag-drop",
G_CALLBACK ( on_folder_view_drag_drop ),
file_browser );
g_signal_connect ( ( gpointer ) folder_view, "drag-end",
G_CALLBACK ( on_folder_view_drag_end ),
file_browser );
// set font
if ( xset_get_s_panel( file_browser->mypanel, "font_file" ) )
{
PangoFontDescription* font_desc = pango_font_description_from_string(
xset_get_s_panel( file_browser->mypanel, "font_file" ) );
gtk_widget_modify_font( folder_view, font_desc );
pango_font_description_free( font_desc );
}
return folder_view;
}
void init_list_view( PtkFileBrowser* file_browser, GtkTreeView* list_view )
{
GtkTreeViewColumn * col;
GtkCellRenderer *renderer;
GtkCellRenderer *pix_renderer;
int i, j, width;
int cols[] = { COL_FILE_NAME, COL_FILE_SIZE, COL_FILE_DESC,
COL_FILE_PERM, COL_FILE_OWNER, COL_FILE_MTIME };
const char* titles[] =
{
N_( "Name" ), N_( "Size" ), N_( "Type" ),
N_( "Permission" ), N_( "Owner" ), N_( "Modified" )
};
const char* set_names[] =
{
"detcol_name", "detcol_size", "detcol_type",
"detcol_perm", "detcol_owner", "detcol_date"
};
for ( i = 0; i < G_N_ELEMENTS( cols ); i++ )
{
col = gtk_tree_view_column_new ();
gtk_tree_view_column_set_resizable ( col, TRUE );
renderer = gtk_cell_renderer_text_new();
for ( j = 0; j < G_N_ELEMENTS( cols ); j++ )
{
if ( xset_get_int_panel( file_browser->mypanel, set_names[j], "x" ) == i )
break;
}
if ( j == G_N_ELEMENTS( cols ) )
j = i; // failsafe
else
{
width = xset_get_int_panel( file_browser->mypanel, set_names[j], "y" );
if ( width )
{
gtk_tree_view_column_set_sizing( col, GTK_TREE_VIEW_COLUMN_FIXED );
gtk_tree_view_column_set_min_width( col, 50 );
if ( cols[j] == COL_FILE_NAME && !app_settings.always_show_tabs
&& file_browser->view_mode == PTK_FB_LIST_VIEW
&& gtk_notebook_get_n_pages(
GTK_NOTEBOOK( file_browser->mynotebook ) ) == 1 )
{
// when tabs are added, the width of the notebook decreases
// by a few pixels, meaning there is not enough space for
// all columns - this causes a horizontal scrollbar to
// appear on new and sometimes first tab
// so shave some pixels off first columns
gtk_tree_view_column_set_fixed_width ( col, width - 6 );
// below causes increasing reduction of column every time new tab is
// added and closed - undesirable
PtkFileBrowser* first_fb = (PtkFileBrowser*)
gtk_notebook_get_nth_page( GTK_NOTEBOOK(
file_browser->mynotebook ), 0 );
if ( first_fb && first_fb->view_mode == PTK_FB_LIST_VIEW &&
GTK_IS_TREE_VIEW( first_fb->folder_view ) )
{
GtkTreeViewColumn* first_col = gtk_tree_view_get_column(
GTK_TREE_VIEW( first_fb->folder_view ), 0 );
if ( first_col )
{
int first_width = gtk_tree_view_column_get_width( first_col );
if ( first_width > 10 )
gtk_tree_view_column_set_fixed_width( first_col,
first_width - 6 );
}
}
}
else
gtk_tree_view_column_set_fixed_width ( col, width );
}
}
if ( cols[j] == COL_FILE_NAME )
{
g_object_set( G_OBJECT( renderer ),
/* "editable", TRUE, */
"ellipsize", PANGO_ELLIPSIZE_END, NULL );
/*
g_signal_connect( renderer, "editing-started",
G_CALLBACK( on_filename_editing_started ), NULL );
*/
file_browser->icon_render = pix_renderer = ptk_file_icon_renderer_new();
gtk_tree_view_column_pack_start( col, pix_renderer, FALSE );
gtk_tree_view_column_set_attributes( col, pix_renderer,
"pixbuf", COL_FILE_SMALL_ICON,
"info", COL_FILE_INFO, NULL );
gtk_tree_view_column_set_expand ( col, TRUE );
gtk_tree_view_column_set_sizing( col, GTK_TREE_VIEW_COLUMN_FIXED );
gtk_tree_view_column_set_min_width( col, 150 );
gtk_tree_view_column_set_reorderable( col, FALSE );
exo_tree_view_set_activable_column( (ExoTreeView*)list_view, col );
}
else
{
gtk_tree_view_column_set_reorderable( col, TRUE );
gtk_tree_view_column_set_visible( col,
xset_get_b_panel( file_browser->mypanel, set_names[j] ) );
}
if ( cols[j] == COL_FILE_SIZE )
gtk_cell_renderer_set_alignment( renderer, 1, 0 );
gtk_tree_view_column_pack_start( col, renderer, TRUE );
gtk_tree_view_column_set_attributes( col, renderer, "text", cols[ j ], NULL );
gtk_tree_view_append_column ( list_view, col );
gtk_tree_view_column_set_title( col, _( titles[ j ] ) );
gtk_tree_view_column_set_sort_indicator( col, TRUE );
gtk_tree_view_column_set_sort_column_id( col, cols[ j ] );
gtk_tree_view_column_set_sort_order( col, GTK_SORT_DESCENDING );
}
gtk_tree_view_set_rules_hint ( list_view, TRUE );
}
void ptk_file_browser_refresh( GtkWidget* item, PtkFileBrowser* file_browser )
{
const char* tmpcwd; //MOD
/*
* FIXME:
* Do nothing when there is unfinished task running in the
* working thread.
* This should be fixed with a better way in the future.
*/
// if ( file_browser->busy ) //MOD
// return ;
//MOD try to trigger real reload
tmpcwd = ptk_file_browser_get_cwd( file_browser );
ptk_file_browser_chdir( file_browser,
"/",
PTK_FB_CHDIR_NO_HISTORY );
ptk_file_browser_update_model( file_browser );
if ( !ptk_file_browser_chdir( file_browser,
tmpcwd,
PTK_FB_CHDIR_NO_HISTORY ) )
{
char* path = xset_get_s( "go_set_default" );
if ( path && path[0] != '\0' )
ptk_file_browser_chdir( PTK_FILE_BROWSER( file_browser ), path,
PTK_FB_CHDIR_ADD_HISTORY );
else
ptk_file_browser_chdir( PTK_FILE_BROWSER( file_browser ), g_get_home_dir(),
PTK_FB_CHDIR_ADD_HISTORY );
}
else if ( file_browser->max_thumbnail )
{
// clear thumbnails
ptk_file_list_show_thumbnails( PTK_FILE_LIST( file_browser->file_list ),
file_browser->view_mode == PTK_FB_ICON_VIEW,
0 );
while( gtk_events_pending() )
gtk_main_iteration();
}
ptk_file_browser_update_model( file_browser );
}
guint ptk_file_browser_get_n_all_files( PtkFileBrowser* file_browser )
{
return file_browser->dir ? file_browser->dir->n_files : 0;
}
guint ptk_file_browser_get_n_visible_files( PtkFileBrowser* file_browser )
{
return file_browser->file_list ?
gtk_tree_model_iter_n_children( file_browser->file_list, NULL ) : 0;
}
GList* folder_view_get_selected_items( PtkFileBrowser* file_browser,
GtkTreeModel** model )
{
GtkTreeSelection * tree_sel;
if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
*model = exo_icon_view_get_model( EXO_ICON_VIEW( file_browser->folder_view ) );
return exo_icon_view_get_selected_items( EXO_ICON_VIEW( file_browser->folder_view ) );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
tree_sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( file_browser->folder_view ) );
return gtk_tree_selection_get_selected_rows( tree_sel, model );
}
return NULL;
}
static char* folder_view_get_drop_dir( PtkFileBrowser* file_browser, int x, int y )
{
GtkTreePath * tree_path = NULL;
GtkTreeModel *model = NULL;
GtkTreeViewColumn* col;
GtkTreeIter it;
VFSFileInfo* file;
char* dest_path = NULL;
if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
exo_icon_view_widget_to_icon_coords ( EXO_ICON_VIEW( file_browser->folder_view ),
x, y, &x, &y );
tree_path = folder_view_get_tree_path_at_pos( file_browser, x, y );
model = exo_icon_view_get_model( EXO_ICON_VIEW( file_browser->folder_view ) );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
// if drag is in progress, get the dest row path
gtk_tree_view_get_drag_dest_row( GTK_TREE_VIEW( file_browser->folder_view ),
&tree_path, NULL );
if ( !tree_path )
{
// no drag in progress, get drop path
gtk_tree_view_get_path_at_pos( GTK_TREE_VIEW( file_browser->folder_view ), x, y,
NULL, &col, NULL, NULL );
if ( col == gtk_tree_view_get_column( GTK_TREE_VIEW( file_browser->folder_view ), 0 ) )
{
gtk_tree_view_get_dest_row_at_pos ( GTK_TREE_VIEW( file_browser->folder_view ), x, y,
&tree_path, NULL );
model = gtk_tree_view_get_model( GTK_TREE_VIEW( file_browser->folder_view ) );
}
}
else
model = gtk_tree_view_get_model( GTK_TREE_VIEW( file_browser->folder_view ) );
}
if ( tree_path )
{
if ( G_UNLIKELY( ! gtk_tree_model_get_iter( model, &it, tree_path ) ) )
return NULL;
gtk_tree_model_get( model, &it, COL_FILE_INFO, &file, -1 );
if ( file )
{
if ( vfs_file_info_is_dir( file ) )
{
dest_path = g_build_filename( ptk_file_browser_get_cwd( file_browser ),
vfs_file_info_get_name( file ), NULL );
/* this isn't needed?
// dest_path is a link? resolve
if ( g_file_test( dest_path, G_FILE_TEST_IS_SYMLINK ) )
{
char* old_dest = dest_path;
dest_path = g_file_read_link( old_dest, NULL );
g_free( old_dest );
}
*/
}
else /* Drop on a file, not folder */
{
/* Return current directory */
dest_path = g_strdup( ptk_file_browser_get_cwd( file_browser ) );
}
vfs_file_info_unref( file );
}
gtk_tree_path_free( tree_path );
}
else
{
dest_path = g_strdup( ptk_file_browser_get_cwd( file_browser ) );
}
return dest_path;
}
void on_folder_view_drag_data_received ( GtkWidget *widget,
GdkDragContext *drag_context,
gint x,
gint y,
GtkSelectionData *sel_data,
guint info,
guint time,
gpointer user_data )
{
gchar **list, **puri;
GList* files = NULL;
PtkFileTask* task;
VFSFileTaskType file_action = VFS_FILE_TASK_MOVE;
PtkFileBrowser* file_browser = ( PtkFileBrowser* ) user_data;
char* dest_dir;
char* file_path;
GtkWidget* parent_win;
/* Don't call the default handler */
g_signal_stop_emission_by_name( widget, "drag-data-received" );
if ( ( gtk_selection_data_get_length(sel_data) >= 0 ) && ( gtk_selection_data_get_format(sel_data) == 8 ) )
{
if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
dest_dir = folder_view_get_drop_dir( file_browser, x, y );
else
// use stored x and y because exo_icon_view has no get_drag_dest_row
dest_dir = folder_view_get_drop_dir( file_browser,
file_browser->drag_x, file_browser->drag_y );
//printf("FB dest_dir = %s\n", dest_dir );
if ( dest_dir )
{
puri = list = gtk_selection_data_get_uris( sel_data );
if( file_browser->pending_drag_status )
{
// We only want to update drag status, not really want to drop
dev_t dest_dev;
struct stat statbuf; // skip stat64
if( stat( dest_dir, &statbuf ) == 0 )
{
dest_dev = statbuf.st_dev;
if( 0 == file_browser->drag_source_dev )
{
file_browser->drag_source_dev = dest_dev;
for( ; *puri; ++puri )
{
file_path = g_filename_from_uri( *puri, NULL, NULL );
if( stat( file_path, &statbuf ) == 0 && statbuf.st_dev != dest_dev )
{
file_browser->drag_source_dev = statbuf.st_dev;
g_free( file_path );
break;
}
g_free( file_path );
}
}
if( file_browser->drag_source_dev != dest_dev )
// src and dest are on different devices */
gdk_drag_status (drag_context, GDK_ACTION_COPY, time);
else
gdk_drag_status (drag_context, GDK_ACTION_MOVE, time);
}
else
// stat failed
gdk_drag_status (drag_context, GDK_ACTION_COPY, time);
g_free( dest_dir );
g_strfreev( list );
file_browser->pending_drag_status = 0;
return;
}
if ( puri )
{
if ( 0 == ( gdk_drag_context_get_selected_action(drag_context) &
( GDK_ACTION_MOVE | GDK_ACTION_COPY | GDK_ACTION_LINK ) ) )
{
gdk_drag_status (drag_context, GDK_ACTION_COPY, time); //sfm correct? was MOVE
}
gtk_drag_finish ( drag_context, TRUE, FALSE, time );
while ( *puri )
{
if ( **puri == '/' )
file_path = g_strdup( *puri );
else
file_path = g_filename_from_uri( *puri, NULL, NULL );
if ( file_path )
files = g_list_prepend( files, file_path );
++puri;
}
g_strfreev( list );
switch ( gdk_drag_context_get_selected_action(drag_context) )
{
case GDK_ACTION_COPY:
file_action = VFS_FILE_TASK_COPY;
break;
case GDK_ACTION_LINK:
file_action = VFS_FILE_TASK_LINK;
break;
/* FIXME:
GDK_ACTION_DEFAULT, GDK_ACTION_PRIVATE, and GDK_ACTION_ASK are not handled */
default:
break;
}
if ( files )
{
/* g_print( "dest_dir = %s\n", dest_dir ); */
/* We only want to update drag status, not really want to drop */
if( file_browser->pending_drag_status )
{
struct stat statbuf; // skip stat64
if( stat( dest_dir, &statbuf ) == 0 )
{
file_browser->pending_drag_status = 0;
}
g_list_foreach( files, (GFunc)g_free, NULL );
g_list_free( files );
g_free( dest_dir );
return;
}
else /* Accept the drop and perform file actions */
{
parent_win = gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) );
task = ptk_file_task_new( file_action,
files,
dest_dir,
GTK_WINDOW( parent_win ),
file_browser->task_view );
ptk_file_task_run( task );
}
}
g_free( dest_dir );
gtk_drag_finish ( drag_context, TRUE, FALSE, time );
return ;
}
}
g_free( dest_dir );
}
/* If we are only getting drag status, not finished. */
if( file_browser->pending_drag_status )
{
file_browser->pending_drag_status = 0;
return;
}
gtk_drag_finish ( drag_context, FALSE, FALSE, time );
}
void on_folder_view_drag_data_get ( GtkWidget *widget,
GdkDragContext *drag_context,
GtkSelectionData *sel_data,
guint info,
guint time,
PtkFileBrowser *file_browser )
{
GdkAtom type = gdk_atom_intern( "text/uri-list", FALSE );
gchar* uri;
GString* uri_list = g_string_sized_new( 8192 );
GList* sels = ptk_file_browser_get_selected_files( file_browser );
GList* sel;
VFSFileInfo* file;
char* full_path;
/* Don't call the default handler */
g_signal_stop_emission_by_name( widget, "drag-data-get" );
// drag_context->suggested_action = GDK_ACTION_MOVE;
for ( sel = sels; sel; sel = g_list_next( sel ) )
{
file = ( VFSFileInfo* ) sel->data;
full_path = g_build_filename( ptk_file_browser_get_cwd( file_browser ),
vfs_file_info_get_name( file ), NULL );
uri = g_filename_to_uri( full_path, NULL, NULL );
g_free( full_path );
g_string_append( uri_list, uri );
g_free( uri );
g_string_append( uri_list, "\r\n" );
}
g_list_foreach( sels, ( GFunc ) vfs_file_info_unref, NULL );
g_list_free( sels );
gtk_selection_data_set ( sel_data, type, 8,
( guchar* ) uri_list->str, uri_list->len + 1 );
g_string_free( uri_list, TRUE );
}
void on_folder_view_drag_begin ( GtkWidget *widget,
GdkDragContext *drag_context,
PtkFileBrowser* file_browser )
{
/* Don't call the default handler */
g_signal_stop_emission_by_name ( widget, "drag-begin" );
/* gtk_drag_set_icon_stock ( drag_context, GTK_STOCK_DND_MULTIPLE, 1, 1 ); */
gtk_drag_set_icon_default( drag_context );
file_browser->is_drag = TRUE;
}
static GtkTreePath*
folder_view_get_tree_path_at_pos( PtkFileBrowser* file_browser, int x, int y )
{
GtkTreePath *tree_path;
if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
tree_path = exo_icon_view_get_path_at_pos( EXO_ICON_VIEW( file_browser->folder_view ), x, y );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
gtk_tree_view_get_path_at_pos( GTK_TREE_VIEW( file_browser->folder_view ), x, y,
&tree_path, NULL, NULL, NULL );
}
return tree_path;
}
gboolean on_folder_view_auto_scroll( GtkScrolledWindow* scroll )
{
GtkAdjustment * vadj;
gdouble vpos;
//gdk_threads_enter(); //sfm why is this here?
vadj = gtk_scrolled_window_get_vadjustment( scroll ) ;
vpos = gtk_adjustment_get_value( vadj );
if ( folder_view_auto_scroll_direction == GTK_DIR_UP )
{
vpos -= gtk_adjustment_get_step_increment ( vadj );
if ( vpos > gtk_adjustment_get_lower ( vadj ) )
gtk_adjustment_set_value ( vadj, vpos );
else
gtk_adjustment_set_value ( vadj, gtk_adjustment_get_lower ( vadj ) );
}
else
{
vpos += gtk_adjustment_get_step_increment ( vadj );
if ( ( vpos + gtk_adjustment_get_page_size ( vadj ) ) < gtk_adjustment_get_upper ( vadj ) )
gtk_adjustment_set_value ( vadj, vpos );
else
gtk_adjustment_set_value ( vadj, ( gtk_adjustment_get_upper ( vadj ) - gtk_adjustment_get_page_size ( vadj ) ) );
}
//gdk_threads_leave();
return TRUE;
}
gboolean on_folder_view_drag_motion ( GtkWidget *widget,
GdkDragContext *drag_context,
gint x,
gint y,
guint time,
PtkFileBrowser* file_browser )
{
GtkScrolledWindow * scroll;
GtkAdjustment *vadj;
gdouble vpos;
GtkTreeModel* model = NULL;
GtkTreePath *tree_path;
GtkTreeViewColumn* col;
GtkTreeIter it;
VFSFileInfo* file;
GdkDragAction suggested_action;
GdkAtom target;
GtkTargetList* target_list;
GtkAllocation allocation;
/* Don't call the default handler */
g_signal_stop_emission_by_name ( widget, "drag-motion" );
scroll = GTK_SCROLLED_WINDOW( gtk_widget_get_parent ( widget ) );
vadj = gtk_scrolled_window_get_vadjustment( scroll ) ;
vpos = gtk_adjustment_get_value( vadj );
gtk_widget_get_allocation( widget, &allocation );
if ( y < 32 )
{
/* Auto scroll up */
if ( ! folder_view_auto_scroll_timer )
{
folder_view_auto_scroll_direction = GTK_DIR_UP;
folder_view_auto_scroll_timer = g_timeout_add(
150,
( GSourceFunc ) on_folder_view_auto_scroll,
scroll );
}
}
else if ( y > ( allocation.height - 32 ) )
{
if ( ! folder_view_auto_scroll_timer )
{
folder_view_auto_scroll_direction = GTK_DIR_DOWN;
folder_view_auto_scroll_timer = g_timeout_add(
150,
( GSourceFunc ) on_folder_view_auto_scroll,
scroll );
}
}
else if ( folder_view_auto_scroll_timer )
{
g_source_remove( folder_view_auto_scroll_timer );
folder_view_auto_scroll_timer = 0;
}
tree_path = NULL;
if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
// store x and y because exo_icon_view has no get_drag_dest_row
file_browser->drag_x = x;
file_browser->drag_y = y;
exo_icon_view_widget_to_icon_coords( EXO_ICON_VIEW( widget ), x, y, &x, &y );
tree_path = exo_icon_view_get_path_at_pos( EXO_ICON_VIEW( widget ), x, y );
model = exo_icon_view_get_model( EXO_ICON_VIEW( widget ) );
}
else
{
if ( gtk_tree_view_get_path_at_pos( GTK_TREE_VIEW( widget ), x, y,
NULL, &col, NULL, NULL ) )
{
if ( gtk_tree_view_get_column ( GTK_TREE_VIEW( widget ), 0 ) == col )
{
gtk_tree_view_get_dest_row_at_pos ( GTK_TREE_VIEW( widget ), x, y,
&tree_path, NULL );
model = gtk_tree_view_get_model( GTK_TREE_VIEW( widget ) );
}
}
}
if ( tree_path )
{
if ( gtk_tree_model_get_iter( model, &it, tree_path ) )
{
gtk_tree_model_get( model, &it, COL_FILE_INFO, &file, -1 );
if ( ! file || ! vfs_file_info_is_dir( file ) )
{
gtk_tree_path_free( tree_path );
tree_path = NULL;
}
vfs_file_info_unref( file );
}
}
if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
exo_icon_view_set_drag_dest_item ( EXO_ICON_VIEW( widget ),
tree_path, EXO_ICON_VIEW_DROP_INTO );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
gtk_tree_view_set_drag_dest_row( GTK_TREE_VIEW( widget ),
tree_path,
GTK_TREE_VIEW_DROP_INTO_OR_AFTER );
}
if ( tree_path )
gtk_tree_path_free( tree_path );
/* FIXME: Creating a new target list everytime is very inefficient,
but currently gtk_drag_dest_get_target_list always returns NULL
due to some strange reason, and cannot be used currently. */
target_list = gtk_target_list_new( drag_targets, G_N_ELEMENTS(drag_targets) );
target = gtk_drag_dest_find_target( widget, drag_context, target_list );
gtk_target_list_unref( target_list );
if (target == GDK_NONE)
gdk_drag_status( drag_context, 0, time);
else
{
/* Only 'move' is available. The user force move action by pressing Shift key */
if( ( gdk_drag_context_get_actions ( drag_context ) & GDK_ACTION_ALL) == GDK_ACTION_MOVE )
suggested_action = GDK_ACTION_MOVE;
/* Only 'copy' is available. The user force copy action by pressing Ctrl key */
else if( (gdk_drag_context_get_actions ( drag_context ) & GDK_ACTION_ALL) == GDK_ACTION_COPY )
suggested_action = GDK_ACTION_COPY;
/* Only 'link' is available. The user force link action by pressing Shift+Ctrl key */
else if( (gdk_drag_context_get_actions ( drag_context ) & GDK_ACTION_ALL) == GDK_ACTION_LINK )
suggested_action = GDK_ACTION_LINK;
/* Several different actions are available. We have to figure out a good default action. */
else
{
int drag_action = xset_get_int( "drag_action", "x" );
if ( drag_action == 1 )
suggested_action = GDK_ACTION_COPY;
else if ( drag_action == 2 )
suggested_action = GDK_ACTION_MOVE;
else if ( drag_action == 3 )
suggested_action = GDK_ACTION_LINK;
else
{
// automatic
file_browser->pending_drag_status = 1;
gtk_drag_get_data (widget, drag_context, target, time);
suggested_action = gdk_drag_context_get_selected_action ( drag_context );
}
}
gdk_drag_status( drag_context, suggested_action, time );
}
return TRUE;
}
gboolean on_folder_view_drag_leave ( GtkWidget *widget,
GdkDragContext *drag_context,
guint time,
PtkFileBrowser* file_browser )
{
/* Don't call the default handler */
g_signal_stop_emission_by_name( widget, "drag-leave" );
file_browser->drag_source_dev = 0;
if ( folder_view_auto_scroll_timer )
{
g_source_remove( folder_view_auto_scroll_timer );
folder_view_auto_scroll_timer = 0;
}
return TRUE;
}
gboolean on_folder_view_drag_drop ( GtkWidget *widget,
GdkDragContext *drag_context,
gint x,
gint y,
guint time,
PtkFileBrowser* file_browser )
{
GdkAtom target = gdk_atom_intern( "text/uri-list", FALSE );
/* Don't call the default handler */
g_signal_stop_emission_by_name( widget, "drag-drop" );
gtk_drag_get_data ( widget, drag_context, target, time );
return TRUE;
}
void on_folder_view_drag_end ( GtkWidget *widget,
GdkDragContext *drag_context,
PtkFileBrowser* file_browser )
{
if ( folder_view_auto_scroll_timer )
{
g_source_remove( folder_view_auto_scroll_timer );
folder_view_auto_scroll_timer = 0;
}
if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
exo_icon_view_set_drag_dest_item( EXO_ICON_VIEW( widget ), NULL, 0 );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
gtk_tree_view_set_drag_dest_row( GTK_TREE_VIEW( widget ), NULL, 0 );
}
file_browser->is_drag = FALSE;
}
void ptk_file_browser_rename_selected_files( PtkFileBrowser* file_browser,
GList* files, char* cwd )
{
GtkWidget * parent;
VFSFileInfo* file;
GList* l;
if ( !file_browser )
return;
gtk_widget_grab_focus( file_browser->folder_view );
parent = gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) );
if ( ! files )
return;
for ( l = files; l; l = l->next )
{
file = (VFSFileInfo*)l->data;
if ( !ptk_rename_file( NULL, file_browser, cwd, file, NULL, FALSE, 0, NULL ) )
break;
}
}
#if 0
void ptk_file_browser_rename_selected_file( PtkFileBrowser* file_browser )
{
GtkWidget * parent;
GList* files;
VFSFileInfo* file;
gtk_widget_grab_focus( file_browser->folder_view );
files = ptk_file_browser_get_selected_files( file_browser );
if ( ! files )
return ;
file = vfs_file_info_ref( ( VFSFileInfo* ) files->data );
g_list_foreach( files, ( GFunc ) vfs_file_info_unref, NULL );
g_list_free( files );
parent = gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) );
ptk_rename_file( NULL, file_browser, ptk_file_browser_get_cwd( file_browser ),
file, NULL, FALSE );
vfs_file_info_unref( file );
//#if 0
// In place editing causes problems. So, I disable it.
if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
gtk_tree_view_get_cursor( GTK_TREE_VIEW( file_browser->folder_view ),
&tree_path, NULL );
if ( ! tree_path )
return ;
col = gtk_tree_view_get_column( GTK_TREE_VIEW( file_browser->folder_view ), 0 );
renderers = gtk_tree_view_column_get_cell_renderers( col );
for ( l = renderers; l; l = l->next )
{
if ( GTK_IS_CELL_RENDERER_TEXT( l->data ) )
{
renderer = GTK_CELL_RENDERER( l->data );
gtk_tree_view_set_cursor_on_cell( GTK_TREE_VIEW( file_browser->folder_view ),
tree_path,
col, renderer,
TRUE );
break;
}
}
g_list_free( renderers );
gtk_tree_path_free( tree_path );
}
else if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
exo_icon_view_get_cursor( EXO_ICON_VIEW( file_browser->folder_view ),
&tree_path, &renderer );
if ( ! tree_path || !renderer )
return ;
g_object_set( G_OBJECT( renderer ), "editable", TRUE, NULL );
exo_icon_view_set_cursor( EXO_ICON_VIEW( file_browser->folder_view ),
tree_path,
renderer,
TRUE );
gtk_tree_path_free( tree_path );
}
//#endif
}
#endif
gboolean ptk_file_browser_can_paste( PtkFileBrowser* file_browser )
{
/* FIXME: return FALSE when we don't have write permission */
return FALSE;
}
void ptk_file_browser_paste( PtkFileBrowser* file_browser )
{
GList * sel_files;
VFSFileInfo* file;
gchar* dest_dir = NULL;
sel_files = ptk_file_browser_get_selected_files( file_browser );
//MOD removed - if you want this then at least make sure src != dest
/* if ( sel_files && sel_files->next == NULL &&
( file = ( VFSFileInfo* ) sel_files->data ) &&
vfs_file_info_is_dir( ( VFSFileInfo* ) sel_files->data ) )
{
dest_dir = g_build_filename( ptk_file_browser_get_cwd( file_browser ),
vfs_file_info_get_name( file ), NULL );
}
*/
ptk_clipboard_paste_files(
GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) ) ),
dest_dir ? dest_dir : ptk_file_browser_get_cwd( file_browser ),
GTK_TREE_VIEW( file_browser->task_view ) );
if ( dest_dir )
g_free( dest_dir );
if ( sel_files )
{
g_list_foreach( sel_files, ( GFunc ) vfs_file_info_unref, NULL );
g_list_free( sel_files );
}
}
void ptk_file_browser_paste_link( PtkFileBrowser* file_browser ) //MOD added
{
ptk_clipboard_paste_links(
GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) ) ),
ptk_file_browser_get_cwd( file_browser ),
GTK_TREE_VIEW( file_browser->task_view ) );
}
void ptk_file_browser_paste_target( PtkFileBrowser* file_browser ) //MOD added
{
ptk_clipboard_paste_targets(
GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) ) ),
ptk_file_browser_get_cwd( file_browser ),
GTK_TREE_VIEW( file_browser->task_view ) );
}
gboolean ptk_file_browser_can_cut_or_copy( PtkFileBrowser* file_browser )
{
return FALSE;
}
void ptk_file_browser_cut( PtkFileBrowser* file_browser )
{
/* What "cut" and "copy" do are the same.
* The only difference is clipboard_action = GDK_ACTION_MOVE.
*/
ptk_file_browser_cut_or_copy( file_browser, FALSE );
}
void ptk_file_browser_cut_or_copy( PtkFileBrowser* file_browser,
gboolean copy )
{
GList * sels;
sels = ptk_file_browser_get_selected_files( file_browser );
if ( ! sels )
return ;
ptk_clipboard_cut_or_copy_files( ptk_file_browser_get_cwd( file_browser ),
sels, copy );
vfs_file_info_list_free( sels );
}
void ptk_file_browser_copy( PtkFileBrowser* file_browser )
{
ptk_file_browser_cut_or_copy( file_browser, TRUE );
}
gboolean ptk_file_browser_can_delete( PtkFileBrowser* file_browser )
{
/* FIXME: return FALSE when we don't have write permission. */
return TRUE;
}
void ptk_file_browser_delete( PtkFileBrowser* file_browser )
{
GList * sel_files;
GtkWidget* parent_win;
if ( ! file_browser->n_sel_files )
return ;
sel_files = ptk_file_browser_get_selected_files( file_browser );
parent_win = gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) );
ptk_delete_files( GTK_WINDOW( parent_win ),
ptk_file_browser_get_cwd( file_browser ),
sel_files, GTK_TREE_VIEW( file_browser->task_view ) );
vfs_file_info_list_free( sel_files );
}
GList* ptk_file_browser_get_selected_files( PtkFileBrowser* file_browser )
{
GList * sel_files;
GList* sel;
GList* file_list = NULL;
GtkTreeModel* model;
GtkTreeIter it;
VFSFileInfo* file;
sel_files = folder_view_get_selected_items( file_browser, &model );
if ( !sel_files )
return NULL;
for ( sel = sel_files; sel; sel = g_list_next( sel ) )
{
gtk_tree_model_get_iter( model, &it, ( GtkTreePath* ) sel->data );
gtk_tree_model_get( model, &it, COL_FILE_INFO, &file, -1 );
file_list = g_list_append( file_list, file );
}
g_list_foreach( sel_files,
( GFunc ) gtk_tree_path_free,
NULL );
g_list_free( sel_files );
return file_list;
}
void ptk_file_browser_open_selected_files( PtkFileBrowser* file_browser )
{
ptk_file_browser_open_selected_files_with_app( file_browser, NULL );
}
void ptk_file_browser_open_selected_files_with_app( PtkFileBrowser* file_browser,
char* app_desktop )
{
GList * sel_files;
sel_files = ptk_file_browser_get_selected_files( file_browser );
char* path = NULL;
VFSMimeType* mime_type = NULL;
// archive?
if( sel_files && !xset_get_b( "arc_def_open" ) )
{
VFSFileInfo* file = vfs_file_info_ref( (VFSFileInfo*)sel_files->data );
mime_type = vfs_file_info_get_mime_type( file );
path = g_build_filename( ptk_file_browser_get_cwd( file_browser ),
vfs_file_info_get_name( file ), NULL );
vfs_file_info_unref( file );
if ( ptk_file_archiver_is_format_supported( mime_type, TRUE ) )
{
int no_write_access = 0;
#if defined(HAVE_EUIDACCESS)
no_write_access = euidaccess( ptk_file_browser_get_cwd( file_browser ), W_OK );
#elif defined(HAVE_EACCESS)
no_write_access = eaccess( ptk_file_browser_get_cwd( file_browser ), W_OK );
#endif
// first file is archive - use default archive action
if ( xset_get_b( "arc_def_ex" ) && !no_write_access )
{
ptk_file_archiver_extract( file_browser, sel_files,
ptk_file_browser_get_cwd( file_browser ),
ptk_file_browser_get_cwd( file_browser ) );
goto _done;
}
else if ( xset_get_b( "arc_def_exto" ) ||
( xset_get_b( "arc_def_ex" ) && no_write_access &&
!( g_str_has_suffix( path, ".gz" ) &&
!g_str_has_suffix( path, ".tar.gz" ) ) ) )
{
ptk_file_archiver_extract( file_browser, sel_files,
ptk_file_browser_get_cwd( file_browser ), NULL );
goto _done;
}
else if ( xset_get_b( "arc_def_list" ) &&
!( g_str_has_suffix( path, ".gz" ) &&
!g_str_has_suffix( path, ".tar.gz" ) ) )
{
ptk_file_archiver_extract( file_browser, sel_files,
ptk_file_browser_get_cwd( file_browser ), "////LIST" );
goto _done;
}
}
}
if ( sel_files && xset_get_b( "iso_auto" ) )
{
VFSFileInfo* file = vfs_file_info_ref( (VFSFileInfo*)sel_files->data );
mime_type = vfs_file_info_get_mime_type( file );
if ( mime_type && (
!strcmp( vfs_mime_type_get_type( mime_type ), "application/x-cd-image" ) ||
!strcmp( vfs_mime_type_get_type( mime_type ), "application/x-iso9660-image" ) ||
g_str_has_suffix( vfs_file_info_get_name( file ), ".iso" ) ||
g_str_has_suffix( vfs_file_info_get_name( file ), ".img" ) ) )
{
char* str = g_find_program_in_path( "udevil" );
if ( str )
{
g_free( str );
str = g_build_filename( ptk_file_browser_get_cwd( file_browser ),
vfs_file_info_get_name( file ), NULL );
mount_iso( file_browser, str );
g_free( str );
vfs_file_info_unref( file );
goto _done;
}
}
vfs_file_info_unref( file );
}
ptk_open_files_with_app( ptk_file_browser_get_cwd( file_browser ),
sel_files, app_desktop, file_browser, FALSE, FALSE );
_done:
g_free( path );
if ( mime_type )
vfs_mime_type_unref( mime_type );
vfs_file_info_list_free( sel_files );
}
/*
void ptk_file_browser_paste_move( PtkFileBrowser* file_browser, char* setname )
{
GtkClipboard * clip = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD );
GdkAtom gnome_target;
GdkAtom uri_list_target;
gchar **uri_list, **puri;
GtkSelectionData* sel_data = NULL;
GList* files = NULL;
gchar* file_path;
gint missing_targets = 0;
char* str;
gboolean is_cut = FALSE;
char* uri_list_str;
VFSFileInfo* file;
char* file_dir;
char* cwd = ptk_file_browser_get_cwd( file_browser );
// get files from clip
gnome_target = gdk_atom_intern( "x-special/gnome-copied-files", FALSE );
sel_data = gtk_clipboard_wait_for_contents( clip, gnome_target );
if ( sel_data )
{
if ( sel_data->length <= 0 || sel_data->format != 8 )
return ;
uri_list_str = ( char* ) sel_data->data;
is_cut = ( 0 == strncmp( ( char* ) sel_data->data, "cut", 3 ) );
if ( uri_list_str )
{
while ( *uri_list_str && *uri_list_str != '\n' )
++uri_list_str;
}
}
else
{
uri_list_target = gdk_atom_intern( "text/uri-list", FALSE );
sel_data = gtk_clipboard_wait_for_contents( clip, uri_list_target );
if ( ! sel_data )
return ;
if ( sel_data->length <= 0 || sel_data->format != 8 )
return ;
uri_list_str = ( char* ) sel_data->data;
}
if ( !uri_list_str )
return;
// create file list
puri = uri_list = g_uri_list_extract_uris( uri_list_str );
while ( *puri )
{
file_path = g_filename_from_uri( *puri, NULL, NULL );
if ( file_path )
{
if ( strstr( setname, "_2target" ) &&
g_file_test( file_path, G_FILE_TEST_IS_SYMLINK ) )
{
str = file_path;
file_path = g_file_read_link( file_path, NULL );
g_free( str );
}
if ( file_path )
{
if ( g_file_test( file_path, G_FILE_TEST_EXISTS ) )
{
files = g_list_prepend( files, file_path );
}
else
missing_targets++;
}
}
++puri;
}
g_strfreev( uri_list );
gtk_selection_data_free( sel_data );
// rename/move/copy/link
GList* l;
int job;
gboolean as_root = FALSE;
GtkWidget* parent = gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) );
// set job
if ( strstr( setname, "_2link" ) )
job = 2; // link ( ignore is_cut )
else if ( strstr( setname, "_2target" ) )
job = 1; // copy ( ignore is_cut )
else if ( strstr( setname, "_2file" ) )
{
if ( is_cut )
job = 0; // move
else
job = 1; // copy
}
else
job = 1; // failsafe copy
// as root
if ( !strncmp( setname, "root_", 5 ) )
as_root = TRUE;
for ( l = files; l; l = l->next )
{
file_path = (char*)l->data;
file = vfs_file_info_new();
vfs_file_info_get( file, file_path, NULL );
file_dir = g_path_get_dirname( file_path );
if ( !ptk_rename_file( NULL, file_browser,
job, file_dir, file, cwd, as_root ) )
{
vfs_file_info_unref( file );
g_free( file_dir );
missing_targets = 0;
break;
}
vfs_file_info_unref( file );
g_free( file_dir );
}
g_list_foreach( files, ( GFunc ) g_free, NULL );
g_list_free( files );
if ( missing_targets > 0 )
ptk_show_error( GTK_WINDOW( parent ),
g_strdup_printf ( "Error" ),
g_strdup_printf ( "%i target%s missing",
missing_targets,
missing_targets > 1 ? g_strdup_printf ( "s are" ) :
g_strdup_printf ( " is" ) ) );
}
*/
/*
void ptk_file_browser_copy_rename( PtkFileBrowser* file_browser, GList* sel_files,
char* cwd, char* setname )
{
//
//copy_rename copy to name
//copy_link copy to link
//root_copy_rename root copy to name
//root_copy_link root copy to link
//root_move root move
//
GList* l;
VFSFileInfo* file;
GtkWidget* parent = gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) );
if ( !sel_files )
return;
gboolean as_root = FALSE;
int job;
if ( strstr( setname, "copy_rename" ) )
job = 1; //copy
else if ( strstr( setname, "copy_link" ) )
job = 2; //link
else
job = 0; //move
if ( !strncmp( setname, "root_", 5 ) )
as_root = TRUE;
for ( l = sel_files; l; l = l->next )
{
file = (VFSFileInfo*)l->data;
if ( !ptk_rename_file( NULL, file_browser,
job, cwd, file, NULL, as_root ) )
break;
}
}
*/
void ptk_file_browser_copycmd( PtkFileBrowser* file_browser, GList* sel_files,
char* cwd, char* setname )
{
if ( !setname || !file_browser || !sel_files )
return;
XSet* set2;
char* copy_dest = NULL;
char* move_dest = NULL;
char* path;
if ( !strcmp( setname, "copy_tab_prev" ) )
copy_dest = main_window_get_tab_cwd( file_browser, -1 );
else if ( !strcmp( setname, "copy_tab_next" ) )
copy_dest = main_window_get_tab_cwd( file_browser, -2 );
else if ( !strncmp( setname, "copy_tab_", 9 ) )
copy_dest = main_window_get_tab_cwd( file_browser, atoi( setname + 9 ) );
else if ( !strcmp( setname, "copy_panel_prev" ) )
copy_dest = main_window_get_panel_cwd( file_browser, -1 );
else if ( !strcmp( setname, "copy_panel_next" ) )
copy_dest = main_window_get_panel_cwd( file_browser, -2 );
else if ( !strncmp( setname, "copy_panel_", 11 ) )
copy_dest = main_window_get_panel_cwd( file_browser, atoi( setname + 11 ) );
else if ( !strcmp( setname, "copy_loc_last" ) )
{
set2 = xset_get( "copy_loc_last" );
copy_dest = g_strdup( set2->desc );
}
else if ( !strcmp( setname, "move_tab_prev" ) )
move_dest = main_window_get_tab_cwd( file_browser, -1 );
else if ( !strcmp( setname, "move_tab_next" ) )
move_dest = main_window_get_tab_cwd( file_browser, -2 );
else if ( !strncmp( setname, "move_tab_", 9 ) )
move_dest = main_window_get_tab_cwd( file_browser, atoi( setname + 9 ) );
else if ( !strcmp( setname, "move_panel_prev" ) )
move_dest = main_window_get_panel_cwd( file_browser, -1 );
else if ( !strcmp( setname, "move_panel_next" ) )
move_dest = main_window_get_panel_cwd( file_browser, -2 );
else if ( !strncmp( setname, "move_panel_", 11 ) )
move_dest = main_window_get_panel_cwd( file_browser, atoi( setname + 11 ) );
else if ( !strcmp( setname, "move_loc_last" ) )
{
set2 = xset_get( "copy_loc_last" );
move_dest = g_strdup( set2->desc );
}
if ( ( g_str_has_prefix( setname, "copy_loc" ) ||
g_str_has_prefix( setname, "move_loc" ) ) &&
!copy_dest && !move_dest )
{
char* folder;
set2 = xset_get( "copy_loc_last" );
if ( set2->desc )
folder = set2->desc;
else
folder = cwd;
path = xset_file_dialog( GTK_WIDGET( file_browser ),
GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER,
_("Choose Location"), folder, NULL );
if ( path && g_file_test( path, G_FILE_TEST_IS_DIR ) )
{
if ( g_str_has_prefix( setname, "copy_loc" ) )
copy_dest = path;
else
move_dest = path;
set2 = xset_get( "copy_loc_last" );
xset_set_set( set2, "desc", path );
}
else
return;
}
if ( copy_dest || move_dest )
{
int file_action;
char* dest_dir;
if ( copy_dest )
{
file_action = VFS_FILE_TASK_COPY;
dest_dir = copy_dest;
}
else
{
file_action = VFS_FILE_TASK_MOVE;
dest_dir = move_dest;
}
if ( !strcmp( dest_dir, cwd ) )
{
xset_msg_dialog( GTK_WIDGET( file_browser ), GTK_MESSAGE_ERROR,
_("Invalid Destination"), NULL, 0,
_("Destination same as source"), NULL, NULL );
g_free( dest_dir );
return;
}
// rebuild sel_files with full paths
GList* file_list = NULL;
GList* sel;
char* file_path;
VFSFileInfo* file;
for ( sel = sel_files; sel; sel = sel->next )
{
file = ( VFSFileInfo* ) sel->data;
file_path = g_build_filename( cwd,
vfs_file_info_get_name( file ), NULL );
file_list = g_list_prepend( file_list, file_path );
}
// task
PtkFileTask* task = ptk_file_task_new( file_action,
file_list,
dest_dir,
GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET(
file_browser ) ) ),
file_browser->task_view );
ptk_file_task_run( task );
g_free( dest_dir );
}
else
{
xset_msg_dialog( GTK_WIDGET( file_browser ), GTK_MESSAGE_ERROR,
_("Invalid Destination"), NULL, 0,
_("Invalid destination"), NULL, NULL );
}
}
void ptk_file_browser_open_terminal( GtkWidget* item, PtkFileBrowser* file_browser )
{
//MOD just open a single terminal for the current folder
/*
GList * sel;
GList* sel_files = ptk_file_browser_get_selected_files( file_browser );
VFSFileInfo* file;
char* full_path;
char* dir;
if ( sel_files )
{
for ( sel = sel_files; sel; sel = sel->next )
{
file = ( VFSFileInfo* ) sel->data;
full_path = g_build_filename( ptk_file_browser_get_cwd( file_browser ),
vfs_file_info_get_name( file ), NULL );
if ( g_file_test( full_path, G_FILE_TEST_IS_DIR ) )
{
g_signal_emit( file_browser, signals[ OPEN_ITEM_SIGNAL ], 0, full_path, PTK_OPEN_TERMINAL );
}
else
{
dir = g_path_get_dirname( full_path );
g_signal_emit( file_browser, signals[ OPEN_ITEM_SIGNAL ], 0, dir, PTK_OPEN_TERMINAL );
g_free( dir );
}
g_free( full_path );
}
g_list_foreach( sel_files, ( GFunc ) vfs_file_info_unref, NULL );
g_list_free( sel_files );
}
else
{
*/
g_signal_emit( file_browser, signals[ OPEN_ITEM_SIGNAL ], 0,
ptk_file_browser_get_cwd( file_browser ), PTK_OPEN_TERMINAL );
// }
}
void ptk_file_browser_hide_selected( PtkFileBrowser* file_browser,
GList* files, char* cwd )
{
if ( xset_msg_dialog( GTK_WIDGET( file_browser ), 0, _("Hide File"), NULL, GTK_BUTTONS_OK_CANCEL, _("The names of the selected files will be added to the '.hidden' file located in this folder, which will hide them from view in SpaceFM. You may need to refresh the view or restart SpaceFM for the files to disappear.\n\nTo unhide a file, open the .hidden file in your text editor, remove the name of the file, and refresh."), NULL, NULL ) != GTK_RESPONSE_OK )
return;
VFSFileInfo* file;
GList *l;
if ( files )
{
for ( l = files; l; l = l->next )
{
file = ( VFSFileInfo* ) l->data;
if ( !vfs_dir_add_hidden( cwd, vfs_file_info_get_name( file ) ) )
ptk_show_error( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET ( file_browser ) ) ),
_("Error"), _("Error hiding files") );
}
// refresh from here causes a segfault occasionally
//ptk_file_browser_refresh( NULL, file_browser );
}
else
ptk_show_error( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET ( file_browser ) ) ),
_("Error"), _( "No files are selected" ) );
}
#if 0
static void on_properties_dlg_destroy( GtkObject* dlg, GList* sel_files )
{
g_list_foreach( sel_files, ( GFunc ) vfs_file_info_unref, NULL );
g_list_free( sel_files );
}
#endif
void ptk_file_browser_file_properties( PtkFileBrowser* file_browser, int page )
{
GtkWidget * parent;
GList* sel_files = NULL;
char* dir_name = NULL;
const char* cwd;
if ( ! file_browser )
return ;
sel_files = ptk_file_browser_get_selected_files( file_browser );
cwd = ptk_file_browser_get_cwd( file_browser );
if ( !sel_files )
{
VFSFileInfo * file = vfs_file_info_new();
vfs_file_info_get( file, ptk_file_browser_get_cwd( file_browser ), NULL );
sel_files = g_list_prepend( NULL, file );
dir_name = g_path_get_dirname( cwd );
}
parent = gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) );
ptk_show_file_properties( GTK_WINDOW( parent ),
dir_name ? dir_name : cwd,
sel_files, page );
vfs_file_info_list_free( sel_files );
g_free( dir_name );
}
void
on_popup_file_properties_activate ( GtkMenuItem *menuitem,
gpointer user_data )
{
GObject * popup = G_OBJECT( user_data );
PtkFileBrowser* file_browser = ( PtkFileBrowser* ) g_object_get_data( popup,
"PtkFileBrowser" );
ptk_file_browser_file_properties( file_browser, 0 );
}
void ptk_file_browser_show_hidden_files( PtkFileBrowser* file_browser,
gboolean show )
{
if ( !!file_browser->show_hidden_files == show )
return;
file_browser->show_hidden_files = show;
if ( file_browser->file_list )
{
ptk_file_browser_update_model( file_browser );
g_signal_emit( file_browser, signals[ SEL_CHANGE_SIGNAL ], 0 );
}
if ( file_browser->side_dir )
{
ptk_dir_tree_view_show_hidden_files( GTK_TREE_VIEW( file_browser->side_dir ),
file_browser->show_hidden_files );
}
}
static gboolean on_dir_tree_button_press( GtkWidget* view,
GdkEventButton* evt,
PtkFileBrowser* file_browser )
{
ptk_file_browser_focus_me( file_browser );
if ( ( evt_win_click->s || evt_win_click->ob2_data ) &&
main_window_event( file_browser->main_window, evt_win_click, "evt_win_click", 0, 0,
"dirtree", 0, evt->button, evt->state, TRUE ) )
return FALSE;
//MOD Added left click
/* if ( evt->type == GDK_BUTTON_PRESS && evt->button == 1 ) // left click
{
//startup_mode = FALSE;
return FALSE;
}
*/
if ( evt->type == GDK_BUTTON_PRESS && evt->button == 2 ) /* middle click */
{
GtkTreeModel * model;
GtkTreePath* tree_path;
GtkTreeIter it;
model = gtk_tree_view_get_model( GTK_TREE_VIEW( view ) );
if ( gtk_tree_view_get_path_at_pos( GTK_TREE_VIEW( view ),
evt->x, evt->y, &tree_path, NULL, NULL, NULL ) )
{
if ( gtk_tree_model_get_iter( model, &it, tree_path ) )
{
VFSFileInfo * file;
gtk_tree_model_get( model, &it,
COL_DIR_TREE_INFO,
&file, -1 );
if ( file )
{
char* file_path;
file_path = ptk_dir_view_get_dir_path( model, &it );
g_signal_emit( file_browser, signals[ OPEN_ITEM_SIGNAL ], 0,
file_path, PTK_OPEN_NEW_TAB );
g_free( file_path );
vfs_file_info_unref( file );
}
}
gtk_tree_path_free( tree_path );
}
return TRUE;
}
return FALSE;
}
GtkWidget* ptk_file_browser_create_dir_tree( PtkFileBrowser* file_browser )
{
GtkWidget * dir_tree;
GtkTreeSelection* dir_tree_sel;
dir_tree = ptk_dir_tree_view_new( file_browser,
file_browser->show_hidden_files );
dir_tree_sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( dir_tree ) );
g_signal_connect ( dir_tree_sel, "changed",
G_CALLBACK ( on_dir_tree_sel_changed ),
file_browser );
g_signal_connect ( dir_tree, "button-press-event",
G_CALLBACK ( on_dir_tree_button_press ),
file_browser );
// set font
if ( xset_get_s_panel( file_browser->mypanel, "font_file" ) )
{
PangoFontDescription* font_desc = pango_font_description_from_string(
xset_get_s_panel( file_browser->mypanel, "font_file" ) );
gtk_widget_modify_font( dir_tree, font_desc );
pango_font_description_free( font_desc );
}
return dir_tree;
}
int file_list_order_from_sort_order( PtkFBSortOrder order )
{
int col;
switch ( order )
{
case PTK_FB_SORT_BY_NAME:
col = COL_FILE_NAME;
break;
case PTK_FB_SORT_BY_SIZE:
col = COL_FILE_SIZE;
break;
case PTK_FB_SORT_BY_MTIME:
col = COL_FILE_MTIME;
break;
case PTK_FB_SORT_BY_TYPE:
col = COL_FILE_DESC;
break;
case PTK_FB_SORT_BY_PERM:
col = COL_FILE_PERM;
break;
case PTK_FB_SORT_BY_OWNER:
col = COL_FILE_OWNER;
break;
default:
col = COL_FILE_NAME;
}
return col;
}
void ptk_file_browser_read_sort_extra( PtkFileBrowser* file_browser )
{
PtkFileList* list = PTK_FILE_LIST( file_browser->file_list );
if ( !list )
return;
list->sort_natural = xset_get_b_panel( file_browser->mypanel, "sort_extra" );
list->sort_case = xset_get_int_panel( file_browser->mypanel, "sort_extra",
"x" ) == XSET_B_TRUE;
list->sort_dir = xset_get_int_panel( file_browser->mypanel, "sort_extra", "y" );
list->sort_hidden_first = xset_get_int_panel( file_browser->mypanel,
"sort_extra", "z" ) == XSET_B_TRUE;
}
void ptk_file_browser_set_sort_extra( PtkFileBrowser* file_browser,
const char* setname )
{
if ( !file_browser || !setname )
return;
XSet* set = xset_get( setname );
if ( !g_str_has_prefix( set->name, "sortx_" ) )
return;
const char* name = set->name + 6;
PtkFileList* list = PTK_FILE_LIST( file_browser->file_list );
if ( !list )
return;
int panel = file_browser->mypanel;
char* val = NULL;
if ( !strcmp( name, "natural" ) )
{
list->sort_natural = set->b == XSET_B_TRUE;
xset_set_b_panel( panel, "sort_extra", list->sort_natural );
}
else if ( !strcmp( name, "case" ) )
{
list->sort_case = set->b == XSET_B_TRUE;
val = g_strdup_printf( "%d", set->b );
xset_set_panel( panel, "sort_extra", "x", val );
}
else if ( !strcmp( name, "folders" ) )
{
list->sort_dir = PTK_LIST_SORT_DIR_FIRST;
val = g_strdup_printf( "%d", PTK_LIST_SORT_DIR_FIRST );
xset_set_panel( panel, "sort_extra", "y", val );
}
else if ( !strcmp( name, "files" ) )
{
list->sort_dir = PTK_LIST_SORT_DIR_LAST;
val = g_strdup_printf( "%d", PTK_LIST_SORT_DIR_LAST );
xset_set_panel( panel, "sort_extra", "y", val );
}
else if ( !strcmp( name, "mix" ) )
{
list->sort_dir = PTK_LIST_SORT_DIR_MIXED;
val = g_strdup_printf( "%d", PTK_LIST_SORT_DIR_MIXED );
xset_set_panel( panel, "sort_extra", "y", val );
}
else if ( !strcmp( name, "hidfirst" ) )
{
list->sort_hidden_first = set->b == XSET_B_TRUE;
val = g_strdup_printf( "%d", set->b );
xset_set_panel( panel, "sort_extra", "z", val );
}
else if ( !strcmp( name, "hidlast" ) )
{
list->sort_hidden_first = set->b != XSET_B_TRUE;
val = g_strdup_printf( "%d", set->b == XSET_B_TRUE ?
XSET_B_FALSE : XSET_B_TRUE );
xset_set_panel( panel, "sort_extra", "z", val );
}
g_free( val );
ptk_file_list_sort( list );
}
void ptk_file_browser_set_sort_order( PtkFileBrowser* file_browser,
PtkFBSortOrder order )
{
int col;
if ( order == file_browser->sort_order )
return ;
file_browser->sort_order = order;
col = file_list_order_from_sort_order( order );
if ( file_browser->file_list )
{
gtk_tree_sortable_set_sort_column_id(
GTK_TREE_SORTABLE( file_browser->file_list ),
col,
file_browser->sort_type );
}
}
void ptk_file_browser_set_sort_type( PtkFileBrowser* file_browser,
GtkSortType order )
{
int col;
GtkSortType old_order;
if ( order != file_browser->sort_type )
{
file_browser->sort_type = order;
if ( file_browser->file_list )
{
gtk_tree_sortable_get_sort_column_id(
GTK_TREE_SORTABLE( file_browser->file_list ),
&col, &old_order );
gtk_tree_sortable_set_sort_column_id(
GTK_TREE_SORTABLE( file_browser->file_list ),
col, order );
}
}
}
PtkFBSortOrder ptk_file_browser_get_sort_order( PtkFileBrowser* file_browser )
{
return file_browser->sort_order;
}
GtkSortType ptk_file_browser_get_sort_type( PtkFileBrowser* file_browser )
{
return file_browser->sort_type;
}
/* FIXME: Don't recreate the view if previous view is compact view */
void ptk_file_browser_view_as_icons( PtkFileBrowser* file_browser )
{
if ( file_browser->view_mode == PTK_FB_ICON_VIEW )
return ;
ptk_file_list_show_thumbnails( PTK_FILE_LIST( file_browser->file_list ), TRUE,
file_browser->max_thumbnail );
file_browser->view_mode = PTK_FB_ICON_VIEW;
gtk_widget_destroy( file_browser->folder_view );
file_browser->folder_view = create_folder_view( file_browser, PTK_FB_ICON_VIEW );
exo_icon_view_set_model( EXO_ICON_VIEW( file_browser->folder_view ),
file_browser->file_list );
gtk_scrolled_window_set_policy(
GTK_SCROLLED_WINDOW( file_browser->folder_view_scroll ),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC );
gtk_widget_show( file_browser->folder_view );
gtk_container_add( GTK_CONTAINER( file_browser->folder_view_scroll ), file_browser->folder_view );
}
/* FIXME: Don't recreate the view if previous view is icon view */
void ptk_file_browser_view_as_compact_list( PtkFileBrowser* file_browser )
{
if ( file_browser->view_mode == PTK_FB_COMPACT_VIEW )
return ;
ptk_file_list_show_thumbnails( PTK_FILE_LIST( file_browser->file_list ), FALSE,
file_browser->max_thumbnail );
file_browser->view_mode = PTK_FB_COMPACT_VIEW;
gtk_widget_destroy( file_browser->folder_view );
file_browser->folder_view = create_folder_view( file_browser, PTK_FB_COMPACT_VIEW );
exo_icon_view_set_model( EXO_ICON_VIEW( file_browser->folder_view ),
file_browser->file_list );
gtk_scrolled_window_set_policy(
GTK_SCROLLED_WINDOW( file_browser->folder_view_scroll ),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC );
gtk_widget_show( file_browser->folder_view );
gtk_container_add( GTK_CONTAINER( file_browser->folder_view_scroll ), file_browser->folder_view );
}
void ptk_file_browser_view_as_list ( PtkFileBrowser* file_browser )
{
if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
return ;
ptk_file_list_show_thumbnails( PTK_FILE_LIST( file_browser->file_list ), FALSE,
file_browser->max_thumbnail );
file_browser->view_mode = PTK_FB_LIST_VIEW;
gtk_widget_destroy( file_browser->folder_view );
file_browser->folder_view = create_folder_view( file_browser, PTK_FB_LIST_VIEW );
gtk_tree_view_set_model( GTK_TREE_VIEW( file_browser->folder_view ),
file_browser->file_list );
gtk_scrolled_window_set_policy(
GTK_SCROLLED_WINDOW( file_browser->folder_view_scroll ),
GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS );
gtk_widget_show( file_browser->folder_view );
gtk_container_add( GTK_CONTAINER( file_browser->folder_view_scroll ), file_browser->folder_view );
}
void ptk_file_browser_create_new_file( PtkFileBrowser* file_browser,
gboolean create_folder )
{
VFSFileInfo *file = NULL;
if( ptk_create_new_file( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) ) ),
ptk_file_browser_get_cwd( file_browser ), create_folder, &file ) )
{
PtkFileList* list = PTK_FILE_LIST( file_browser->file_list );
GtkTreeIter it;
/* generate created event before FAM to enhance responsiveness. */
vfs_dir_emit_file_created( file_browser->dir, vfs_file_info_get_name(file),
TRUE );
/* select the created file */
if( ptk_file_list_find_iter( list, &it, file ) )
{
GtkTreePath* tp = gtk_tree_model_get_path( GTK_TREE_MODEL(list), &it );
if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
exo_icon_view_select_path( EXO_ICON_VIEW( file_browser->folder_view ), tp );
exo_icon_view_set_cursor( EXO_ICON_VIEW( file_browser->folder_view ), tp, NULL, FALSE );
/* NOTE for dirty hack:
* Layout of icon view is done in idle handler,
* so we have to let it re-layout after the insertion of new item.
* or we cannot scroll to the specified path correctly. */
while( gtk_events_pending() )
gtk_main_iteration();
exo_icon_view_scroll_to_path( EXO_ICON_VIEW( file_browser->folder_view ),
tp, FALSE, 0, 0 );
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
//MOD give new folder/file focus
//GtkTreeSelection * tree_sel;
//tree_sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( file_browser->folder_view ) );
//gtk_tree_selection_select_iter( tree_sel, &it );
GtkTreeSelection *selection;
GList *selected_paths = NULL;
GList *lp;
/* save selected paths */
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW( file_browser->folder_view ));
selected_paths = gtk_tree_selection_get_selected_rows (selection, NULL);
gtk_tree_view_set_cursor(GTK_TREE_VIEW( file_browser->folder_view ), tp, NULL, FALSE);
/* select all previously selected paths */
for (lp = selected_paths; lp != NULL; lp = lp->next)
gtk_tree_selection_select_path (selection, lp->data);
/*
while( gtk_events_pending() )
gtk_main_iteration();
*/
gtk_tree_view_scroll_to_cell( GTK_TREE_VIEW( file_browser->folder_view ),
tp, NULL, FALSE, 0, 0 );
}
gtk_widget_grab_focus( GTK_WIDGET( file_browser->folder_view ) ); //MOD
gtk_tree_path_free( tp );
}
vfs_file_info_unref( file );
}
}
guint ptk_file_browser_get_n_sel( PtkFileBrowser* file_browser,
guint64* sel_size )
{
if ( sel_size )
*sel_size = file_browser->sel_size;
return file_browser->n_sel_files;
}
void ptk_file_browser_before_chdir( PtkFileBrowser* file_browser,
const char* path,
gboolean* cancel )
{}
void ptk_file_browser_after_chdir( PtkFileBrowser* file_browser )
{}
void ptk_file_browser_content_change( PtkFileBrowser* file_browser )
{}
void ptk_file_browser_sel_change( PtkFileBrowser* file_browser )
{}
void ptk_file_browser_pane_mode_change( PtkFileBrowser* file_browser )
{}
void ptk_file_browser_open_item( PtkFileBrowser* file_browser, const char* path, int action )
{}
/* Side pane */
/*
void ptk_file_browser_set_side_pane_mode( PtkFileBrowser* file_browser,
PtkFBSidePaneMode mode )
{
GtkAdjustment * adj;
if ( file_browser->side_pane_mode == mode )
return ;
file_browser->side_pane_mode = mode;
// if ( ! file_browser->side_pane )
if ( !ptk_file_browser_is_side_pane_visible( file_browser ) )
return ;
gtk_widget_destroy( GTK_WIDGET( file_browser->side_view ) );
adj = gtk_scrolled_window_get_hadjustment(
GTK_SCROLLED_WINDOW( file_browser->side_view_scroll ) );
gtk_adjustment_set_value( adj, 0 );
switch ( file_browser->side_pane_mode )
{
case PTK_FB_SIDE_PANE_DIR_TREE:
gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( file_browser->side_view_scroll ),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC );
file_browser->side_view = ptk_file_browser_create_dir_tree( file_browser );
gtk_toggle_tool_button_set_active ( file_browser->dir_tree_btn, TRUE );
break;
case PTK_FB_SIDE_PANE_BOOKMARKS:
gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( file_browser->side_view_scroll ),
GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC );
file_browser->side_view = ptk_file_browser_create_location_view( file_browser );
gtk_toggle_tool_button_set_active ( file_browser->location_btn, TRUE );
break;
}
gtk_container_add( GTK_CONTAINER( file_browser->side_view_scroll ),
GTK_WIDGET( file_browser->side_view ) );
gtk_widget_show( GTK_WIDGET( file_browser->side_view ) );
// if ( file_browser->side_pane && file_browser->file_list )
if ( ptk_file_browser_is_side_pane_visible( file_browser ) && file_browser->file_list )
{
side_pane_chdir( file_browser, ptk_file_browser_get_cwd( file_browser ) );
}
g_signal_emit( file_browser, signals[ PANE_MODE_CHANGE_SIGNAL ], 0 );
}
PtkFBSidePaneMode
ptk_file_browser_get_side_pane_mode( PtkFileBrowser* file_browser )
{
return file_browser->side_pane_mode;
}
static void on_show_location_view( GtkWidget* item, PtkFileBrowser* file_browser )
{
if ( gtk_toggle_tool_button_get_active( GTK_TOGGLE_TOOL_BUTTON( item ) ) )
ptk_file_browser_set_side_pane_mode( file_browser, PTK_FB_SIDE_PANE_BOOKMARKS );
}
static void on_show_dir_tree( GtkWidget* item, PtkFileBrowser* file_browser )
{
if ( gtk_toggle_tool_button_get_active( GTK_TOGGLE_TOOL_BUTTON( item ) ) )
ptk_file_browser_set_side_pane_mode( file_browser, PTK_FB_SIDE_PANE_DIR_TREE );
}
static PtkToolItemEntry side_pane_bar[] = {
PTK_RADIO_TOOL_ITEM( NULL, "gtk-harddisk", N_( "Location" ), on_show_location_view ),
PTK_RADIO_TOOL_ITEM( NULL, "gtk-open", N_( "Directory Tree" ), on_show_dir_tree ),
PTK_TOOL_END
};
static void ptk_file_browser_create_side_pane( PtkFileBrowser* file_browser )
{
GtkTooltips* tooltips = gtk_tooltips_new();
file_browser->side_pane_buttons = gtk_toolbar_new();
file_browser->side_pane = gtk_vbox_new( FALSE, 0 );
file_browser->side_view_scroll = gtk_scrolled_window_new( NULL, NULL );
gtk_scrolled_window_set_shadow_type( GTK_SCROLLED_WINDOW( file_browser->side_view_scroll ),
GTK_SHADOW_IN );
switch ( file_browser->side_pane_mode )
{
case PTK_FB_SIDE_PANE_DIR_TREE:
gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( file_browser->side_view_scroll ),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC );
file_browser->side_view = ptk_file_browser_create_dir_tree( file_browser );
break;
case PTK_FB_SIDE_PANE_BOOKMARKS:
default:
gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( file_browser->side_view_scroll ),
GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC );
file_browser->side_view = ptk_file_browser_create_location_view( file_browser );
break;
}
gtk_container_add( GTK_CONTAINER( file_browser->side_view_scroll ),
GTK_WIDGET( file_browser->side_view ) );
gtk_box_pack_start( GTK_BOX( file_browser->side_pane ),
GTK_WIDGET( file_browser->side_view_scroll ),
TRUE, TRUE, 0 );
gtk_toolbar_set_style( GTK_TOOLBAR( file_browser->side_pane_buttons ), GTK_TOOLBAR_ICONS );
side_pane_bar[ 0 ].ret = ( GtkWidget** ) ( GtkWidget * ) & file_browser->location_btn;
side_pane_bar[ 1 ].ret = ( GtkWidget** ) ( GtkWidget * ) & file_browser->dir_tree_btn;
ptk_toolbar_add_items_from_data( file_browser->side_pane_buttons,
side_pane_bar, file_browser, tooltips );
gtk_box_pack_start( GTK_BOX( file_browser->side_pane ),
file_browser->side_pane_buttons, FALSE, FALSE, 0 );
gtk_widget_show_all( file_browser->side_pane );
if ( !file_browser->show_side_pane_buttons )
{
gtk_widget_hide( file_browser->side_pane_buttons );
}
gtk_paned_pack1( GTK_PANED( file_browser ),
file_browser->side_pane, FALSE, TRUE );
}
void ptk_file_browser_show_side_pane( PtkFileBrowser* file_browser,
PtkFBSidePaneMode mode )
{
file_browser->side_pane_mode = mode;
if ( ! file_browser->side_pane )
{
ptk_file_browser_create_side_pane( file_browser );
if ( file_browser->file_list )
{
side_pane_chdir( file_browser, ptk_file_browser_get_cwd( file_browser ) );
}
switch ( mode )
{
case PTK_FB_SIDE_PANE_BOOKMARKS:
gtk_toggle_tool_button_set_active( file_browser->location_btn, TRUE );
break;
case PTK_FB_SIDE_PANE_DIR_TREE:
gtk_toggle_tool_button_set_active( file_browser->dir_tree_btn, TRUE );
break;
}
}
//gtk_widget_show( file_browser->side_pane );
gtk_widget_show( file_browser->side_vbox );
file_browser->show_side_pane = TRUE;
}
void ptk_file_browser_hide_side_pane( PtkFileBrowser* file_browser )
{
//if ( file_browser->side_pane )
// {
file_browser->show_side_pane = FALSE;
//gtk_widget_destroy( file_browser->side_pane );
gtk_widget_destroy( file_browser->side_view );
//file_browser->side_pane = NULL;
file_browser->side_view = NULL;
//file_browser->side_view_scroll = NULL;
//file_browser->side_pane_buttons = NULL;
//file_browser->location_btn = NULL;
//file_browser->dir_tree_btn = NULL;
// }
}
gboolean ptk_file_browser_is_side_pane_visible( PtkFileBrowser* file_browser )
{
return file_browser->show_side_pane;
}
void ptk_file_browser_show_side_pane_buttons( PtkFileBrowser* file_browser )
{
file_browser->show_side_pane_buttons = TRUE;
if ( file_browser->side_pane )
{
gtk_widget_show( file_browser->side_pane_buttons );
}
}
void ptk_file_browser_hide_side_pane_buttons( PtkFileBrowser* file_browser )
{
file_browser->show_side_pane_buttons = FALSE;
if ( file_browser->side_pane )
{
gtk_widget_hide( file_browser->side_pane_buttons );
}
}
*/
void ptk_file_browser_show_shadow( PtkFileBrowser* file_browser )
{
gtk_scrolled_window_set_shadow_type ( GTK_SCROLLED_WINDOW ( file_browser->folder_view_scroll ),
GTK_SHADOW_IN );
}
void ptk_file_browser_hide_shadow( PtkFileBrowser* file_browser )
{
gtk_scrolled_window_set_shadow_type ( GTK_SCROLLED_WINDOW ( file_browser->folder_view_scroll ),
GTK_SHADOW_NONE );
}
void ptk_file_browser_show_thumbnails( PtkFileBrowser* file_browser,
int max_file_size )
{
file_browser->max_thumbnail = max_file_size;
if ( file_browser->file_list )
{
ptk_file_list_show_thumbnails( PTK_FILE_LIST( file_browser->file_list ),
file_browser->view_mode == PTK_FB_ICON_VIEW,
max_file_size );
}
}
void ptk_file_browser_update_display( PtkFileBrowser* file_browser )
{
GtkTreeSelection * tree_sel;
GList *sel = NULL, *l;
GtkTreePath* tree_path;
int big_icon_size, small_icon_size;
if ( ! file_browser->file_list )
return ;
g_object_ref( G_OBJECT( file_browser->file_list ) );
if ( file_browser->max_thumbnail )
ptk_file_list_show_thumbnails( PTK_FILE_LIST( file_browser->file_list ),
file_browser->view_mode == PTK_FB_ICON_VIEW,
file_browser->max_thumbnail );
vfs_mime_type_get_icon_size( &big_icon_size, &small_icon_size );
if ( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
{
sel = exo_icon_view_get_selected_items( EXO_ICON_VIEW( file_browser->folder_view ) );
exo_icon_view_set_model( EXO_ICON_VIEW( file_browser->folder_view ), NULL );
if( file_browser->view_mode == PTK_FB_ICON_VIEW )
gtk_cell_renderer_set_fixed_size( file_browser->icon_render, big_icon_size, big_icon_size );
else if( file_browser->view_mode == PTK_FB_COMPACT_VIEW )
gtk_cell_renderer_set_fixed_size( file_browser->icon_render, small_icon_size, small_icon_size );
exo_icon_view_set_model( EXO_ICON_VIEW( file_browser->folder_view ),
GTK_TREE_MODEL( file_browser->file_list ) );
for ( l = sel; l; l = l->next )
{
tree_path = ( GtkTreePath* ) l->data;
exo_icon_view_select_path( EXO_ICON_VIEW( file_browser->folder_view ),
tree_path );
gtk_tree_path_free( tree_path );
}
}
else if ( file_browser->view_mode == PTK_FB_LIST_VIEW )
{
tree_sel = gtk_tree_view_get_selection( GTK_TREE_VIEW( file_browser->folder_view ) );
sel = gtk_tree_selection_get_selected_rows( tree_sel, NULL );
gtk_tree_view_set_model( GTK_TREE_VIEW( file_browser->folder_view ), NULL );
gtk_cell_renderer_set_fixed_size( file_browser->icon_render, small_icon_size, small_icon_size );
gtk_tree_view_set_model( GTK_TREE_VIEW( file_browser->folder_view ),
GTK_TREE_MODEL( file_browser->file_list ) );
for ( l = sel; l; l = l->next )
{
tree_path = ( GtkTreePath* ) l->data;
gtk_tree_selection_select_path( tree_sel, tree_path );
gtk_tree_path_free( tree_path );
}
}
g_list_free( sel );
g_object_unref( G_OBJECT( file_browser->file_list ) );
}
void ptk_file_browser_emit_open( PtkFileBrowser* file_browser,
const char* path,
PtkOpenAction action )
{
g_signal_emit( file_browser, signals[ OPEN_ITEM_SIGNAL ], 0, path, action );
}
void ptk_file_browser_set_single_click( PtkFileBrowser* file_browser, gboolean single_click )
{
if( single_click == file_browser->single_click )
return;
if( file_browser->view_mode == PTK_FB_LIST_VIEW )
exo_tree_view_set_single_click( (ExoTreeView*)file_browser->folder_view, single_click );
else if( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
exo_icon_view_set_single_click( (ExoIconView*)file_browser->folder_view, single_click );
file_browser->single_click = single_click;
}
void ptk_file_browser_set_single_click_timeout( PtkFileBrowser* file_browser, guint timeout )
{
if( timeout == file_browser->single_click_timeout )
return;
if( file_browser->view_mode == PTK_FB_LIST_VIEW )
exo_tree_view_set_single_click_timeout( (ExoTreeView*)file_browser->folder_view, timeout );
else if( file_browser->view_mode == PTK_FB_ICON_VIEW || file_browser->view_mode == PTK_FB_COMPACT_VIEW )
exo_icon_view_set_single_click_timeout( (ExoIconView*)file_browser->folder_view, timeout );
file_browser->single_click_timeout = timeout;
}
////////////////////////////////////////////////////////////////////////////
int ptk_file_browser_no_access( const char* cwd, const char* smode )
{
int mode;
if ( !smode )
mode = W_OK;
else if ( !strcmp( smode, "R_OK" ) )
mode = R_OK;
else
mode = W_OK;
int no_access = 0;
#if defined(HAVE_EUIDACCESS)
no_access = euidaccess( cwd, mode );
#elif defined(HAVE_EACCESS)
no_access = eaccess( cwd, mode );
#endif
return no_access;
}
int bookmark_item_comp( const char* item, const char* path )
{
return strcmp( ptk_bookmarks_item_get_path( item ), path );
}
void ptk_file_browser_add_bookmark( GtkMenuItem *menuitem, PtkFileBrowser* file_browser )
{
const char* path = ptk_file_browser_get_cwd( PTK_FILE_BROWSER( file_browser ) );
gchar* name;
if ( ! g_list_find_custom( app_settings.bookmarks->list,
path,
( GCompareFunc ) bookmark_item_comp ) )
{
name = g_path_get_basename( path );
ptk_bookmarks_append( name, path );
g_free( name );
}
else
xset_msg_dialog( GTK_WIDGET( file_browser ), GTK_MESSAGE_INFO,
_("Bookmark Exists"), NULL, 0,
_("Bookmark already exists"), NULL, NULL );
}
void ptk_file_browser_find_file( GtkMenuItem *menuitem, PtkFileBrowser* file_browser )
{
const char* cwd;
const char* dirs[2];
cwd = ptk_file_browser_get_cwd( file_browser );
dirs[0] = cwd;
dirs[1] = NULL;
fm_find_files( dirs );
}
/*
void ptk_file_browser_open_folder_as_root( GtkMenuItem *menuitem,
PtkFileBrowser* file_browser )
{
const char* cwd;
//char* cmd_line;
GError *err = NULL;
char* argv[5]; //MOD
cwd = ptk_file_browser_get_cwd( file_browser );
//MOD separate arguments for ktsuss compatibility
//cmd_line = g_strdup_printf( "%s --no-desktop '%s'", g_get_prgname(), cwd );
argv[1] = g_get_prgname();
argv[2] = g_strdup_printf ( "--no-desktop" );
argv[3] = cwd;
argv[4] = NULL;
if( ! vfs_sudo_cmd_async( cwd, argv, &err ) ) //MOD
{
ptk_show_error( gtk_widget_get_toplevel( file_browser ), _("Error"), err->message );
g_error_free( err );
}
//g_free( cmd_line );
}
*/
void ptk_file_browser_focus( GtkMenuItem *item, PtkFileBrowser* file_browser, int job2 )
{
GtkWidget* widget;
int job;
if ( item )
job = GPOINTER_TO_INT( g_object_get_data( G_OBJECT( item ), "job" ) );
else
job = job2;
switch ( job )
{
case 0:
// path bar
if ( !xset_get_b_panel( file_browser->mypanel, "show_pathbar" ) )
{
xset_set_panel( file_browser->mypanel, "show_pathbar", "b", "1" );
update_views_all_windows( NULL, file_browser );
}
widget = file_browser->path_bar;
break;
case 1:
if ( !xset_get_b_panel( file_browser->mypanel, "show_dirtree" ) )
{
xset_set_panel( file_browser->mypanel, "show_dirtree", "b", "1" );
update_views_all_windows( NULL, file_browser );
}
widget = file_browser->side_dir;
break;
case 2:
if ( !xset_get_b_panel( file_browser->mypanel, "show_book" ) )
{
xset_set_panel( file_browser->mypanel, "show_book", "b", "1" );
update_views_all_windows( NULL, file_browser );
}
widget = file_browser->side_book;
break;
case 3:
if ( !xset_get_b_panel( file_browser->mypanel, "show_devmon" ) )
{
xset_set_panel( file_browser->mypanel, "show_devmon", "b", "1" );
update_views_all_windows( NULL, file_browser );
}
widget = file_browser->side_dev;
break;
case 4:
widget = file_browser->folder_view;
break;
default:
return;
}
if ( gtk_widget_get_visible( widget ) )
gtk_widget_grab_focus( GTK_WIDGET( widget ) );
}
void focus_folder_view( PtkFileBrowser* file_browser )
{
gtk_widget_grab_focus( GTK_WIDGET( file_browser->folder_view ) );
g_signal_emit( file_browser, signals[ PANE_MODE_CHANGE_SIGNAL ], 0 );
}
void ptk_file_browser_focus_me( PtkFileBrowser* file_browser )
{
g_signal_emit( file_browser, signals[ PANE_MODE_CHANGE_SIGNAL ], 0 );
}
void ptk_file_browser_go_tab( GtkMenuItem *item, PtkFileBrowser* file_browser,
int t )
{
//printf( "ptk_file_browser_go_tab fb=%#x\n", file_browser );
GtkWidget* notebook = file_browser->mynotebook;
int tab_num;
if ( item )
tab_num = GPOINTER_TO_INT( g_object_get_data( G_OBJECT( item ), "tab_num" ) );
else
tab_num = t;
if ( tab_num == -1 ) // prev
{
if ( gtk_notebook_get_current_page( GTK_NOTEBOOK( notebook ) ) == 0 )
gtk_notebook_set_current_page( GTK_NOTEBOOK( notebook ),
gtk_notebook_get_n_pages(
GTK_NOTEBOOK( notebook ) ) - 1 );
else
gtk_notebook_prev_page( GTK_NOTEBOOK( notebook ) );
}
else if ( tab_num == -2 ) // next
{
if ( gtk_notebook_get_current_page( GTK_NOTEBOOK( notebook ) ) + 1 ==
gtk_notebook_get_n_pages( GTK_NOTEBOOK( notebook ) ) )
gtk_notebook_set_current_page( GTK_NOTEBOOK( notebook ), 0 );
else
gtk_notebook_next_page( GTK_NOTEBOOK( notebook ) );
}
else if ( tab_num == -3 ) // close
{
on_close_notebook_page( NULL, file_browser );
}
else
{
if ( tab_num <= gtk_notebook_get_n_pages( GTK_NOTEBOOK( notebook ) ) &&
tab_num > 0 )
gtk_notebook_set_current_page( GTK_NOTEBOOK( notebook ), tab_num - 1 );
}
}
void ptk_file_browser_open_in_tab( PtkFileBrowser* file_browser, int tab_num,
char* file_path )
{
int page_x;
GtkWidget* notebook = file_browser->mynotebook;
int cur_page = gtk_notebook_get_current_page( GTK_NOTEBOOK( notebook ) );
int pages = gtk_notebook_get_n_pages( GTK_NOTEBOOK( notebook ) );
if ( tab_num == -1 ) // prev
page_x = cur_page - 1;
else if ( tab_num == -2 ) // next
page_x = cur_page + 1;
else
page_x = tab_num - 1;
if ( page_x > -1 && page_x < pages && page_x != cur_page )
{
PtkFileBrowser* a_browser = (PtkFileBrowser*)gtk_notebook_get_nth_page(
GTK_NOTEBOOK( notebook ), page_x );
ptk_file_browser_chdir( a_browser, file_path, PTK_FB_CHDIR_ADD_HISTORY );
}
}
void ptk_file_browser_on_permission( GtkMenuItem* item, PtkFileBrowser* file_browser,
GList* sel_files, char* cwd )
{
char* name;
char* cmd;
const char* prog;
gboolean as_root = FALSE;
char* user1 = "1000";
char* user2 = "1001";
char* myuser = g_strdup_printf( "%d", geteuid() );
if ( !sel_files )
return;
XSet* set = (XSet*)g_object_get_data( G_OBJECT( item ), "set" );
if ( !set || !file_browser )
return;
if ( !strncmp( set->name, "perm_", 5 ) )
{
name = set->name + 5;
if ( !strncmp( name, "go", 2 ) || !strncmp( name, "ugo", 3 ) )
prog = "chmod -R";
else
prog = "chmod";
}
else if ( !strncmp( set->name, "rperm_", 6 ) )
{
name = set->name + 6;
if ( !strncmp( name, "go", 2 ) || !strncmp( name, "ugo", 3 ) )
prog = "chmod -R";
else
prog = "chmod";
as_root = TRUE;
}
else if ( !strncmp( set->name, "own_", 4 ) )
{
name = set->name + 4;
prog = "chown";
as_root = TRUE;
}
else if ( !strncmp( set->name, "rown_", 5 ) )
{
name = set->name + 5;
prog = "chown -R";
as_root = TRUE;
}
else
return;
if ( !strcmp( name, "r" ) )
cmd = g_strdup_printf( "u+r-wx,go-rwx" );
else if ( !strcmp( name, "rw" ) )
cmd = g_strdup_printf( "u+rw-x,go-rwx" );
else if ( !strcmp( name, "rwx" ) )
cmd = g_strdup_printf( "u+rwx,go-rwx" );
else if ( !strcmp( name, "r_r" ) )
cmd = g_strdup_printf( "u+r-wx,g+r-wx,o-rwx" );
else if ( !strcmp( name, "rw_r" ) )
cmd = g_strdup_printf( "u+rw-x,g+r-wx,o-rwx" );
else if ( !strcmp( name, "rw_rw" ) )
cmd = g_strdup_printf( "u+rw-x,g+rw-x,o-rwx" );
else if ( !strcmp( name, "rwxr_x" ) )
cmd = g_strdup_printf( "u+rwx,g+rx-w,o-rwx" );
else if ( !strcmp( name, "rwxrwx" ) )
cmd = g_strdup_printf( "u+rwx,g+rwx,o-rwx" );
else if ( !strcmp( name, "r_r_r" ) )
cmd = g_strdup_printf( "ugo+r,ugo-wx" );
else if ( !strcmp( name, "rw_r_r" ) )
cmd = g_strdup_printf( "u+rw-x,go+r-wx" );
else if ( !strcmp( name, "rw_rw_rw" ) )
cmd = g_strdup_printf( "ugo+rw-x" );
else if ( !strcmp( name, "rwxr_r" ) )
cmd = g_strdup_printf( "u+rwx,go+r-wx" );
else if ( !strcmp( name, "rwxr_xr_x" ) )
cmd = g_strdup_printf( "u+rwx,go+rx-w" );
else if ( !strcmp( name, "rwxrwxrwx" ) )
cmd = g_strdup_printf( "ugo+rwx,-t" );
else if ( !strcmp( name, "rwxrwxrwt" ) )
cmd = g_strdup_printf( "ugo+rwx,+t" );
else if ( !strcmp( name, "unstick" ) )
cmd = g_strdup_printf( "-t" );
else if ( !strcmp( name, "stick" ) )
cmd = g_strdup_printf( "+t" );
else if ( !strcmp( name, "go_w" ) )
cmd = g_strdup_printf( "go-w" );
else if ( !strcmp( name, "go_rwx" ) )
cmd = g_strdup_printf( "go-rwx" );
else if ( !strcmp( name, "ugo_w" ) )
cmd = g_strdup_printf( "ugo+w" );
else if ( !strcmp( name, "ugo_rx" ) )
cmd = g_strdup_printf( "ugo+rX" );
else if ( !strcmp( name, "ugo_rwx" ) )
cmd = g_strdup_printf( "ugo+rwX" );
else if ( !strcmp( name, "myuser" ) )
cmd = g_strdup_printf( "%s:%s", myuser, myuser );
else if ( !strcmp( name, "myuser_users" ) )
cmd = g_strdup_printf( "%s:users", myuser );
else if ( !strcmp( name, "user1" ) )
cmd = g_strdup_printf( "%s:%s", user1, user1 );
else if ( !strcmp( name, "user1_users" ) )
cmd = g_strdup_printf( "%s:users", user1 );
else if ( !strcmp( name, "user2" ) )
cmd = g_strdup_printf( "%s:%s", user2, user2 );
else if ( !strcmp( name, "user2_users" ) )
cmd = g_strdup_printf( "%s:users", user2 );
else if ( !strcmp( name, "root" ) )
cmd = g_strdup_printf( "root:root" );
else if ( !strcmp( name, "root_users" ) )
cmd = g_strdup_printf( "root:users" );
else if ( !strcmp( name, "root_myuser" ) )
cmd = g_strdup_printf( "root:%s", myuser );
else if ( !strcmp( name, "root_user1" ) )
cmd = g_strdup_printf( "root:%s", user1 );
else if ( !strcmp( name, "root_user2" ) )
cmd = g_strdup_printf( "root:%s", user2 );
else
return;
char* file_paths = g_strdup( "" );
GList* sel;
char* file_path;
char* str;
for ( sel = sel_files; sel; sel = sel->next )
{
file_path = bash_quote( vfs_file_info_get_name( ( VFSFileInfo* ) sel->data ) );
str = file_paths;
file_paths = g_strdup_printf( "%s %s", file_paths, file_path );
g_free( str );
g_free( file_path );
}
// task
PtkFileTask* task = ptk_file_exec_new( set->menu_label,
cwd,
GTK_WIDGET( file_browser ),
file_browser->task_view );
task->task->exec_command = g_strdup_printf( "%s %s %s", prog, cmd, file_paths );
g_free( cmd );
g_free( file_paths );
task->task->exec_browser = file_browser;
task->task->exec_sync = TRUE;
task->task->exec_show_error = TRUE;
task->task->exec_show_output = FALSE;
task->task->exec_export = FALSE;
if ( as_root )
task->task->exec_as_user = g_strdup_printf( "root" );
ptk_file_task_run( task );
}
void ptk_file_browser_on_action( PtkFileBrowser* browser, char* setname )
{
char* xname;
int i;
XSet* set = xset_get( setname );
//printf("ptk_file_browser_on_action\n");
if ( g_str_has_prefix( set->name, "book_" ) )
{
xname = set->name + 5;
if ( !strcmp( xname, "icon" ) )
update_bookmark_icons();
else if ( !strcmp( xname, "new" ) )
ptk_file_browser_add_bookmark( NULL, browser );
else if ( !strcmp( xname, "rename" ) )
on_bookmark_rename( NULL, browser );
else if ( !strcmp( xname, "edit" ) )
on_bookmark_edit( NULL, browser );
else if ( !strcmp( xname, "remove" ) )
on_bookmark_remove( NULL, browser );
else if ( !strcmp( xname, "open" ) )
on_bookmark_open( NULL, browser );
else if ( !strcmp( xname, "tab" ) )
on_bookmark_open_tab( NULL, browser );
}
else if ( g_str_has_prefix( set->name, "tool_" )
|| g_str_has_prefix( set->name, "stool_" )
|| g_str_has_prefix( set->name, "rtool_" ) )
{
if ( g_str_has_prefix( set->name, "tool_" ) )
xname = set->name + 5;
else
xname = set->name + 6;
if ( !strcmp( xname, "dirtree" ) )
{
xset_set_b( set->name, xset_get_b_panel( browser->mypanel,
"show_dirtree" ) );
on_toggle_sideview( NULL, browser, 0 );
}
else if ( !strcmp( xname, "book" ) )
{
xset_set_b( set->name, xset_get_b_panel( browser->mypanel,
"show_book" ) );
on_toggle_sideview( NULL, browser, 1 );
}
else if ( !strcmp( xname, "device" ) )
{
xset_set_b( set->name, xset_get_b_panel( browser->mypanel,
"show_devmon" ) );
on_toggle_sideview( NULL, browser, 2 );
}
else if ( !strcmp( xname, "newtab" ) )
on_shortcut_new_tab_activate( NULL, browser );
else if ( !strcmp( xname, "newtabhere" ) )
on_shortcut_new_tab_here( NULL, browser );
else if ( !strcmp( xname, "back" ) )
ptk_file_browser_go_back( NULL, browser );
else if ( !strcmp( xname, "backmenu" ) )
ptk_file_browser_go_back( NULL, browser );
else if ( !strcmp( xname, "forward" ) )
ptk_file_browser_go_forward( NULL, browser );
else if ( !strcmp( xname, "forwardmenu" ) )
ptk_file_browser_go_forward( NULL, browser );
else if ( !strcmp( xname, "up" ) )
ptk_file_browser_go_up( NULL, browser );
else if ( !strcmp( xname, "default" ) )
ptk_file_browser_go_default( NULL, browser );
else if ( !strcmp( xname, "home" ) )
ptk_file_browser_go_home( NULL, browser );
else if ( !strcmp( xname, "refresh" ) )
ptk_file_browser_refresh( NULL, browser );
}
else if ( !strcmp( set->name, "toolbar_hide" ) )
on_toolbar_hide( NULL, browser, browser->toolbar );
else if ( !strcmp( set->name, "toolbar_hide_side" ) )
on_toolbar_hide( NULL, browser, browser->side_toolbar );
else if ( !strcmp( set->name, "toolbar_help" ) )
on_toolbar_help( NULL, browser );
else if ( g_str_has_prefix( set->name, "go_" ) )
{
xname = set->name + 3;
if ( !strcmp( xname, "back" ) )
ptk_file_browser_go_back( NULL, browser );
else if ( !strcmp( xname, "forward" ) )
ptk_file_browser_go_forward( NULL, browser );
else if ( !strcmp( xname, "up" ) )
ptk_file_browser_go_up( NULL, browser );
else if ( !strcmp( xname, "home" ) )
ptk_file_browser_go_home( NULL, browser );
else if ( !strcmp( xname, "default" ) )
ptk_file_browser_go_default( NULL, browser );
else if ( !strcmp( xname, "set_default" ) )
ptk_file_browser_set_default_folder( NULL, browser );
}
else if ( g_str_has_prefix( set->name, "tab_" ) )
{
xname = set->name + 4;
if ( !strcmp( xname, "new" ) )
on_shortcut_new_tab_activate( NULL, browser );
else if ( !strcmp( xname, "new_here" ) )
on_shortcut_new_tab_here( NULL, browser );
else
{
if ( !strcmp( xname, "prev" ) )
i = -1;
else if ( !strcmp( xname, "next" ) )
i = -2;
else if ( !strcmp( xname, "close" ) )
i = -3;
else
i = atoi( xname );
ptk_file_browser_go_tab( NULL, browser, i );
}
}
else if ( g_str_has_prefix( set->name, "focus_" ) )
{
xname = set->name + 6;
if ( !strcmp( xname, "path_bar" ) )
i = 0;
else if ( !strcmp( xname, "filelist" ) )
i = 4;
else if ( !strcmp( xname, "dirtree" ) )
i = 1;
else if ( !strcmp( xname, "book" ) )
i = 2;
else if ( !strcmp( xname, "device" ) )
i = 3;
ptk_file_browser_focus( NULL, browser, i );
}
else if ( !strcmp( set->name, "view_reorder_col" ) )
on_reorder( NULL, GTK_WIDGET( browser ) );
else if ( !strcmp( set->name, "view_refresh" ) )
ptk_file_browser_refresh( NULL, browser );
else if ( g_str_has_prefix( set->name, "sortby_" ) )
{
xname = set->name + 7;
i = -3;
if ( !strcmp( xname, "name" ) )
i = PTK_FB_SORT_BY_NAME;
else if ( !strcmp( xname, "size" ) )
i = PTK_FB_SORT_BY_SIZE;
else if ( !strcmp( xname, "type" ) )
i = PTK_FB_SORT_BY_TYPE;
else if ( !strcmp( xname, "perm" ) )
i = PTK_FB_SORT_BY_PERM;
else if ( !strcmp( xname, "owner" ) )
i = PTK_FB_SORT_BY_OWNER;
else if ( !strcmp( xname, "date" ) )
i = PTK_FB_SORT_BY_MTIME;
else if ( !strcmp( xname, "ascend" ) )
{
i = -1;
set->b = browser->sort_type == GTK_SORT_ASCENDING ? XSET_B_TRUE : XSET_B_FALSE;
}
else if ( !strcmp( xname, "descend" ) )
{
i = -2;
set->b = browser->sort_type == GTK_SORT_DESCENDING ? XSET_B_TRUE : XSET_B_FALSE;
}
if ( i > 0 )
set->b = browser->sort_order == i ? XSET_B_TRUE : XSET_B_FALSE;
on_popup_sortby( NULL, browser, i );
}
else if ( g_str_has_prefix( set->name, "sortx_" ) )
ptk_file_browser_set_sort_extra( browser, set->name );
else if ( !strcmp( set->name, "path_help" ) )
ptk_path_entry_help( NULL, GTK_WIDGET( browser ) );
else if ( g_str_has_prefix( set->name, "panel" ) )
{
i = 0;
if ( strlen( set->name ) > 6 )
{
xname = g_strdup( set->name + 5 );
xname[1] = '\0';
i = atoi( xname );
xname[1] = '_';
g_free( xname );
}
//printf( "ACTION panelN=%d %c\n", i, set->name[5] );
if ( i > 0 && i < 5 )
{
xname = set->name + 7;
if ( !strcmp( xname, "show_hidden" ) ) // shared key
{
ptk_file_browser_show_hidden_files( browser,
xset_get_b_panel( browser->mypanel, "show_hidden" ) );
}
else if ( !strcmp( xname, "show" ) ) // main View|Panel N
show_panels_all_windows( NULL, (FMMainWindow*)browser->main_window );
else if ( g_str_has_prefix( xname, "show_" ) ) // shared key
update_views_all_windows( NULL, browser );
else if ( !strcmp( xname, "list_detailed" ) ) // shared key
on_popup_list_detailed( NULL, browser );
else if ( !strcmp( xname, "list_icons" ) ) // shared key
on_popup_list_icons( NULL, browser );
else if ( !strcmp( xname, "list_compact" ) ) // shared key
on_popup_list_compact( NULL, browser );
else if ( !strcmp( xname, "icon_tab" )
|| g_str_has_prefix( xname, "font_" ) )
main_update_fonts( NULL, browser );
else if ( g_str_has_prefix( xname, "detcol_" ) // shared key
&& browser->view_mode == PTK_FB_LIST_VIEW )
on_folder_view_columns_changed( GTK_TREE_VIEW( browser->folder_view ),
browser );
else if ( !strcmp( xname, "icon_status" ) ) // shared key
on_status_effect_change( NULL, browser );
else if ( !strcmp( xname, "font_status" ) ) // shared key
on_status_effect_change( NULL, browser );
}
}
else if ( g_str_has_prefix( set->name, "status_" ) )
{
xname = set->name + 7;
if ( !strcmp( xname, "border" )
|| !strcmp( xname, "text" ) )
on_status_effect_change( NULL, browser );
else if ( !strcmp( xname, "name" )
|| !strcmp( xname, "path" )
|| !strcmp( xname, "info" )
|| !strcmp( xname, "hide" ) )
on_status_middle_click_config( NULL, set );
}
else if ( g_str_has_prefix( set->name, "paste_" ) )
{
xname = set->name + 6;
if ( !strcmp( xname, "link" ) )
ptk_file_browser_paste_link( browser );
else if ( !strcmp( xname, "target" ) )
ptk_file_browser_paste_target( browser );
else if ( !strcmp( xname, "as" ) )
ptk_file_misc_paste_as( NULL, browser,
ptk_file_browser_get_cwd( browser ) );
}
else if ( g_str_has_prefix( set->name, "select_" ) )
{
xname = set->name + 7;
if ( !strcmp( xname, "all" ) )
ptk_file_browser_select_all( NULL, browser );
else if ( !strcmp( xname, "un" ) )
ptk_file_browser_unselect_all( NULL, browser );
else if ( !strcmp( xname, "invert" ) )
ptk_file_browser_invert_selection( NULL, browser );
else if ( !strcmp( xname, "patt" ) )
ptk_file_browser_select_pattern( NULL, browser, NULL );
}
else // all the rest require ptkfilemenu data
ptk_file_menu_action( NULL, browser, set->name );
}
|
192 | ./spacefm/src/ptk/ptk-dir-tree-view.c | /*
* C Implementation: ptkdirtreeview
*
* Description:
*
*
* Author: Hong Jen Yee (PCMan) <pcman.tw (AT) gmail.com>, (C) 2006
*
* Copyright: See COPYING file that comes with this distribution
*
*/
#include "ptk-dir-tree-view.h"
#include "ptk-file-icon-renderer.h"
#include <glib.h>
#include <glib/gi18n.h>
#include <gdk/gdkkeysyms.h>
#include "glib-mem.h"
#include <string.h>
#include "ptk-dir-tree.h"
#include "ptk-file-menu.h"
#include "ptk-file-task.h" //MOD
#include "vfs-file-info.h"
#include "vfs-file-monitor.h"
#include "gtk2-compat.h"
static GQuark dir_tree_view_data = 0;
static GtkTreeModel* get_dir_tree_model();
static void
on_dir_tree_view_row_expanded( GtkTreeView *treeview,
GtkTreeIter *iter,
GtkTreePath *path,
gpointer user_data );
static void
on_dir_tree_view_row_collapsed( GtkTreeView *treeview,
GtkTreeIter *iter,
GtkTreePath *path,
gpointer user_data );
static gboolean
on_dir_tree_view_button_press( GtkWidget* view,
GdkEventButton* evt,
PtkFileBrowser* browser );
static gboolean
on_dir_tree_view_key_press( GtkWidget* view,
GdkEventKey* evt,
gpointer user_data );
static gboolean sel_func ( GtkTreeSelection *selection,
GtkTreeModel *model,
GtkTreePath *path,
gboolean path_currently_selected,
gpointer data );
struct _DirTreeNode
{
VFSFileInfo* file;
GList* children;
int n_children;
VFSFileMonitor* monitor;
int n_expand;
};
//MOD #if 0
/* Drag & Drop/Clipboard targets */
static GtkTargetEntry drag_targets[] =
{
{ "text/uri-list", 0 , 0 }
};
// #endif
//MOD drag n drop...
static void
on_dir_tree_view_drag_data_received ( GtkWidget *widget,
GdkDragContext *drag_context,
gint x,
gint y,
GtkSelectionData *sel_data,
guint info,
guint time,
gpointer user_data );
static gboolean
on_dir_tree_view_drag_motion ( GtkWidget *widget,
GdkDragContext *drag_context,
gint x,
gint y,
guint time,
PtkFileBrowser* file_browser );
static gboolean on_dir_tree_view_drag_leave ( GtkWidget *widget,
GdkDragContext *drag_context,
guint time,
PtkFileBrowser* file_browser );
static gboolean
on_dir_tree_view_drag_drop ( GtkWidget *widget,
GdkDragContext *drag_context,
gint x,
gint y,
guint time,
PtkFileBrowser* file_browser );
#define GDK_ACTION_ALL (GDK_ACTION_MOVE|GDK_ACTION_COPY|GDK_ACTION_LINK)
static gboolean filter_func( GtkTreeModel *model,
GtkTreeIter *iter,
gpointer data )
{
VFSFileInfo * file;
const char* name;
GtkTreeView* view = ( GtkTreeView* ) data;
gboolean show_hidden = GPOINTER_TO_INT( g_object_get_qdata( G_OBJECT( view ),
dir_tree_view_data ) );
if ( show_hidden )
return TRUE;
gtk_tree_model_get( model, iter, COL_DIR_TREE_INFO, &file, -1 );
if ( G_LIKELY( file ) )
{
name = vfs_file_info_get_name( file );
if ( G_UNLIKELY( name && name[ 0 ] == '.' ) )
{
vfs_file_info_unref( file );
return FALSE;
}
vfs_file_info_unref( file );
}
return TRUE;
}
static void on_destroy(GtkWidget* w)
{
do{
}while( g_source_remove_by_user_data(w) );
}
/* Create a new dir tree view */
GtkWidget* ptk_dir_tree_view_new( PtkFileBrowser* browser,
gboolean show_hidden )
{
GtkTreeView * dir_tree_view;
GtkTreeViewColumn* col;
GtkCellRenderer* renderer;
GtkTreeModel* model;
GtkTreeSelection* tree_sel;
GtkTreePath* tree_path;
GtkTreeModel* filter;
dir_tree_view = GTK_TREE_VIEW( gtk_tree_view_new () );
gtk_tree_view_set_headers_visible( dir_tree_view, FALSE );
gtk_tree_view_set_enable_tree_lines(dir_tree_view, TRUE);
//MOD enabled DND FIXME: Temporarily disable drag & drop since it doesn't work right now.
/* exo_icon_view_enable_model_drag_dest (
EXO_ICON_VIEW( dir_tree_view ),
drag_targets, G_N_ELEMENTS( drag_targets ), GDK_ACTION_ALL ); */
gtk_tree_view_enable_model_drag_dest ( dir_tree_view,
drag_targets,
sizeof( drag_targets ) / sizeof( GtkTargetEntry ),
GDK_ACTION_MOVE | GDK_ACTION_COPY | GDK_ACTION_LINK );
/*
gtk_tree_view_enable_model_drag_source ( dir_tree_view,
( GDK_CONTROL_MASK | GDK_BUTTON1_MASK | GDK_BUTTON3_MASK ),
drag_targets,
sizeof( drag_targets ) / sizeof( GtkTargetEntry ),
GDK_ACTION_DEFAULT | GDK_ACTION_COPY | GDK_ACTION_MOVE | GDK_ACTION_LINK );
*/
col = gtk_tree_view_column_new ();
renderer = ( GtkCellRenderer* ) ptk_file_icon_renderer_new();
gtk_tree_view_column_pack_start( col, renderer, FALSE );
gtk_tree_view_column_set_attributes( col, renderer, "pixbuf", COL_DIR_TREE_ICON,
"info", COL_DIR_TREE_INFO, NULL );
renderer = gtk_cell_renderer_text_new();
gtk_tree_view_column_pack_start( col, renderer, TRUE );
gtk_tree_view_column_set_attributes( col, renderer, "text", COL_DIR_TREE_DISP_NAME, NULL );
gtk_tree_view_append_column ( dir_tree_view, col );
tree_sel = gtk_tree_view_get_selection( dir_tree_view );
gtk_tree_selection_set_select_function( tree_sel, sel_func, NULL, NULL );
if ( G_UNLIKELY( !dir_tree_view_data ) )
dir_tree_view_data = g_quark_from_static_string( "show_hidden" );
g_object_set_qdata( G_OBJECT( dir_tree_view ),
dir_tree_view_data, GINT_TO_POINTER( show_hidden ) );
model = get_dir_tree_model();
filter = gtk_tree_model_filter_new( model, NULL );
g_object_unref( G_OBJECT( model ) );
gtk_tree_model_filter_set_visible_func( GTK_TREE_MODEL_FILTER( filter ),
filter_func, dir_tree_view, NULL );
gtk_tree_view_set_model( dir_tree_view, filter );
g_object_unref( G_OBJECT( filter ) );
g_signal_connect ( dir_tree_view, "row-expanded",
G_CALLBACK ( on_dir_tree_view_row_expanded ),
model );
g_signal_connect_data ( dir_tree_view, "row-collapsed",
G_CALLBACK ( on_dir_tree_view_row_collapsed ),
model, NULL, G_CONNECT_AFTER );
g_signal_connect ( dir_tree_view, "button-press-event",
G_CALLBACK ( on_dir_tree_view_button_press ),
browser );
g_signal_connect ( dir_tree_view, "key-press-event",
G_CALLBACK ( on_dir_tree_view_key_press ),
NULL );
//MOD drag n drop
g_signal_connect ( ( gpointer ) dir_tree_view, "drag-data-received",
G_CALLBACK ( on_dir_tree_view_drag_data_received ),
browser );
g_signal_connect ( ( gpointer ) dir_tree_view, "drag-motion",
G_CALLBACK ( on_dir_tree_view_drag_motion ),
browser );
g_signal_connect ( ( gpointer ) dir_tree_view, "drag-leave",
G_CALLBACK ( on_dir_tree_view_drag_leave ),
browser );
g_signal_connect ( ( gpointer ) dir_tree_view, "drag-drop",
G_CALLBACK ( on_dir_tree_view_drag_drop ),
browser );
tree_path = gtk_tree_path_new_first();
gtk_tree_view_expand_row( dir_tree_view, tree_path, FALSE );
gtk_tree_path_free( tree_path );
g_signal_connect( dir_tree_view, "destroy", G_CALLBACK(on_destroy), NULL );
return GTK_WIDGET( dir_tree_view );
}
gboolean ptk_dir_tree_view_chdir( GtkTreeView* dir_tree_view, const char* path )
{
GtkTreeModel * model;
GtkTreeIter it, parent_it;
GtkTreePath* tree_path = NULL;
gchar **dirs, **dir;
gboolean found;
VFSFileInfo* info;
if ( !path || *path != '/' )
return FALSE;
dirs = g_strsplit( path + 1, "/", -1 );
if ( !dirs )
return FALSE;
model = gtk_tree_view_get_model( dir_tree_view );
if ( ! gtk_tree_model_iter_children ( model, &parent_it, NULL ) )
{
g_strfreev( dirs );
return FALSE;
}
/* special case: root dir */
if ( ! dirs[ 0 ] )
{
it = parent_it;
tree_path = gtk_tree_model_get_path ( model, &parent_it );
goto _found;
}
for ( dir = dirs; *dir; ++dir )
{
if ( ! gtk_tree_model_iter_children ( model, &it, &parent_it ) )
{
g_strfreev( dirs );
return FALSE;
}
found = FALSE;
do
{
gtk_tree_model_get( model, &it, COL_DIR_TREE_INFO, &info, -1 );
if ( !info )
continue;
if ( 0 == strcmp( vfs_file_info_get_name( info ), *dir ) )
{
tree_path = gtk_tree_model_get_path( model, &it );
if( dir[1] ) {
gtk_tree_view_expand_row ( dir_tree_view, tree_path, FALSE );
gtk_tree_model_get_iter( model, &parent_it, tree_path );
}
found = TRUE;
vfs_file_info_unref( info );
break;
}
vfs_file_info_unref( info );
}
while ( gtk_tree_model_iter_next( model, &it ) );
if ( ! found )
return FALSE; /* Error! */
if ( tree_path && dir[ 1 ] )
{
gtk_tree_path_free( tree_path );
tree_path = NULL;
}
}
_found:
g_strfreev( dirs );
gtk_tree_selection_select_path (
gtk_tree_view_get_selection( dir_tree_view ), tree_path );
gtk_tree_view_scroll_to_cell ( dir_tree_view, tree_path, NULL, FALSE, 0.5, 0.5 );
gtk_tree_path_free( tree_path );
return TRUE;
}
/* FIXME: should this API be put here? Maybe it belongs to prk-dir-tree.c */
char* ptk_dir_view_get_dir_path( GtkTreeModel* model, GtkTreeIter* it )
{
GtkTreeModel * tree;
GtkTreeIter real_it;
gtk_tree_model_filter_convert_iter_to_child_iter(
GTK_TREE_MODEL_FILTER( model ), &real_it, it );
tree = gtk_tree_model_filter_get_model( GTK_TREE_MODEL_FILTER( model ) );
return ptk_dir_tree_get_dir_path( PTK_DIR_TREE( tree ), &real_it );
}
/* Return a newly allocated string containing path of current selected dir. */
char* ptk_dir_tree_view_get_selected_dir( GtkTreeView* dir_tree_view )
{
GtkTreeModel * model;
GtkTreeIter it;
GtkTreeSelection* tree_sel;
tree_sel = gtk_tree_view_get_selection( dir_tree_view );
if ( gtk_tree_selection_get_selected( tree_sel, &model, &it ) )
return ptk_dir_view_get_dir_path( model, &it );
return NULL;
}
GtkTreeModel* get_dir_tree_model()
{
static PtkDirTree * dir_tree_model = NULL;
if ( G_UNLIKELY( ! dir_tree_model ) )
{
dir_tree_model = ptk_dir_tree_new( TRUE );
g_object_add_weak_pointer( G_OBJECT( dir_tree_model ),
( gpointer * ) (GtkWidget *) & dir_tree_model );
}
else
{
g_object_ref( G_OBJECT( dir_tree_model ) );
}
return GTK_TREE_MODEL( dir_tree_model );
}
gboolean sel_func ( GtkTreeSelection *selection,
GtkTreeModel *model,
GtkTreePath *path,
gboolean path_currently_selected,
gpointer data )
{
GtkTreeIter it;
VFSFileInfo* file;
if ( ! gtk_tree_model_get_iter( model, &it, path ) )
return FALSE;
gtk_tree_model_get( model, &it, COL_DIR_TREE_INFO, &file, -1 );
if ( !file )
return FALSE;
vfs_file_info_unref( file );
return TRUE;
}
void ptk_dir_tree_view_show_hidden_files( GtkTreeView* dir_tree_view,
gboolean show_hidden )
{
GtkTreeModel * filter;
g_object_set_qdata( G_OBJECT( dir_tree_view ),
dir_tree_view_data, GINT_TO_POINTER( show_hidden ) );
filter = gtk_tree_view_get_model( dir_tree_view );
gtk_tree_model_filter_refilter( GTK_TREE_MODEL_FILTER( filter ) );
}
void on_dir_tree_view_row_expanded( GtkTreeView *treeview,
GtkTreeIter *iter,
GtkTreePath *path,
gpointer user_data )
{
GtkTreeIter real_it;
GtkTreePath* real_path;
GtkTreeModel* filter = gtk_tree_view_get_model( treeview );
PtkDirTree* tree = PTK_DIR_TREE( user_data );
gtk_tree_model_filter_convert_iter_to_child_iter(
GTK_TREE_MODEL_FILTER( filter ), &real_it, iter );
real_path = gtk_tree_model_filter_convert_path_to_child_path(
GTK_TREE_MODEL_FILTER( filter ), path );
ptk_dir_tree_expand_row( tree, &real_it, real_path );
gtk_tree_path_free( real_path );
}
void on_dir_tree_view_row_collapsed( GtkTreeView *treeview,
GtkTreeIter *iter,
GtkTreePath *path,
gpointer user_data )
{
GtkTreeIter real_it;
GtkTreePath* real_path;
GtkTreeModel* filter = gtk_tree_view_get_model( treeview );
PtkDirTree* tree = PTK_DIR_TREE( user_data );
gtk_tree_model_filter_convert_iter_to_child_iter(
GTK_TREE_MODEL_FILTER( filter ), &real_it, iter );
real_path = gtk_tree_model_filter_convert_path_to_child_path(
GTK_TREE_MODEL_FILTER( filter ), path );
ptk_dir_tree_collapse_row( tree, &real_it, real_path );
gtk_tree_path_free( real_path );
}
gboolean on_dir_tree_view_button_press( GtkWidget* view,
GdkEventButton* evt,
PtkFileBrowser* browser )
{
if ( evt->type == GDK_BUTTON_PRESS && evt->button == 3 )
{
GtkTreeModel * model;
GtkTreePath* tree_path;
GtkTreeIter it;
model = gtk_tree_view_get_model( GTK_TREE_VIEW( view ) );
if ( gtk_tree_view_get_path_at_pos( GTK_TREE_VIEW( view ),
evt->x, evt->y, &tree_path, NULL, NULL, NULL ) )
{
if ( gtk_tree_model_get_iter( model, &it, tree_path ) )
{
VFSFileInfo * file;
gtk_tree_model_get( model, &it,
COL_DIR_TREE_INFO,
&file, -1 );
if ( file )
{
GtkWidget * popup;
char* file_path;
GList* sel_files;
char* dir_name;
file_path = ptk_dir_view_get_dir_path( model, &it );
sel_files = g_list_prepend( NULL, vfs_file_info_ref(file) );
dir_name = g_path_get_dirname( file_path );
popup = ptk_file_menu_new( NULL, browser,
file_path, file,
dir_name, sel_files );
g_free( dir_name );
g_free( file_path );
if ( popup )
gtk_menu_popup( GTK_MENU( popup ), NULL, NULL,
NULL, NULL, 3, evt->time );
vfs_file_info_unref( file );
}
}
gtk_tree_path_free( tree_path );
}
}
return FALSE;
}
gboolean on_dir_tree_view_key_press( GtkWidget* view,
GdkEventKey* evt,
gpointer user_data )
{
switch(evt->keyval) {
case GDK_KEY_Left:
case GDK_KEY_Right:
break;
default:
return FALSE;
}
GtkTreeSelection *select = gtk_tree_view_get_selection(GTK_TREE_VIEW(view));
GtkTreeModel *model;
GtkTreeIter iter;
if(!gtk_tree_selection_get_selected(select, &model, &iter))
return FALSE;
GtkTreePath *path = gtk_tree_model_get_path(model, &iter);
switch( evt->keyval ) {
case GDK_KEY_Left:
if(gtk_tree_view_row_expanded(GTK_TREE_VIEW(view), path)) {
gtk_tree_view_collapse_row(GTK_TREE_VIEW(view), path);
} else if(gtk_tree_path_up(path)) {
gtk_tree_selection_select_path(select, path);
gtk_tree_view_set_cursor(GTK_TREE_VIEW(view), path, NULL, FALSE);
} else {
gtk_tree_path_free( path );
return FALSE;
}
break;
case GDK_KEY_Right:
if(!gtk_tree_view_row_expanded(GTK_TREE_VIEW(view), path)) {
gtk_tree_view_expand_row(GTK_TREE_VIEW(view), path, FALSE);
} else {
gtk_tree_path_down(path);
gtk_tree_selection_select_path(select, path);
gtk_tree_view_set_cursor(GTK_TREE_VIEW(view), path, NULL, FALSE);
}
break;
}
gtk_tree_path_free( path );
return TRUE;
}
//MOD drag n drop
static char* dir_tree_view_get_drop_dir( GtkWidget* view, int x, int y )
{
GtkTreePath *tree_path = NULL;
GtkTreeModel *model;
GtkTreeIter it;
VFSFileInfo* file;
char* dest_path = NULL;
// if drag is in progress, get the dest row path
gtk_tree_view_get_drag_dest_row( GTK_TREE_VIEW( view ), &tree_path, NULL );
if ( !tree_path )
{
// no drag in progress, get drop path
if ( !gtk_tree_view_get_path_at_pos( GTK_TREE_VIEW( view ),
x, y, &tree_path, NULL, NULL, NULL ) )
tree_path = NULL;
}
if ( tree_path )
{
model = gtk_tree_view_get_model( GTK_TREE_VIEW( view ) );
if ( gtk_tree_model_get_iter( model, &it, tree_path ) )
{
gtk_tree_model_get( model, &it,
COL_DIR_TREE_INFO,
&file, -1 );
if ( file )
{
dest_path = ptk_dir_view_get_dir_path( model, &it );
vfs_file_info_unref( file );
}
}
gtk_tree_path_free( tree_path );
}
/* this isn't needed?
// dest_path is a link? resolve
if ( dest_path && g_file_test( dest_path, G_FILE_TEST_IS_SYMLINK ) )
{
char* old_dest = dest_path;
dest_path = g_file_read_link( old_dest, NULL );
g_free( old_dest );
}
*/
return dest_path;
}
void on_dir_tree_view_drag_data_received ( GtkWidget *widget,
GdkDragContext *drag_context,
gint x,
gint y,
GtkSelectionData *sel_data,
guint info,
guint time,
gpointer user_data ) //MOD added
{
gchar **list, **puri;
GList* files = NULL;
PtkFileTask* task;
VFSFileTaskType file_action = VFS_FILE_TASK_MOVE;
PtkFileBrowser* file_browser = ( PtkFileBrowser* ) user_data;
char* dest_dir;
char* file_path;
GtkWidget* parent_win;
/* Don't call the default handler */
g_signal_stop_emission_by_name( widget, "drag-data-received" );
if ( ( gtk_selection_data_get_length( sel_data ) >= 0 ) && ( gtk_selection_data_get_format( sel_data ) == 8 ) )
{
dest_dir = dir_tree_view_get_drop_dir( widget, x, y );
if ( dest_dir )
{
puri = list = gtk_selection_data_get_uris( sel_data );
if( file_browser->pending_drag_status_tree )
{
// We only want to update drag status, not really want to drop
dev_t dest_dev;
struct stat statbuf; // skip stat64
if( stat( dest_dir, &statbuf ) == 0 )
{
dest_dev = statbuf.st_dev;
if( 0 == file_browser->drag_source_dev_tree )
{
file_browser->drag_source_dev_tree = dest_dev;
for( ; *puri; ++puri )
{
file_path = g_filename_from_uri( *puri, NULL, NULL );
if( stat( file_path, &statbuf ) == 0 && statbuf.st_dev != dest_dev )
{
file_browser->drag_source_dev_tree = statbuf.st_dev;
g_free( file_path );
break;
}
g_free( file_path );
}
}
if( file_browser->drag_source_dev_tree != dest_dev )
// src and dest are on different devices */
gdk_drag_status( drag_context, GDK_ACTION_COPY, time);
else
gdk_drag_status( drag_context, GDK_ACTION_MOVE, time);
}
else
// stat failed
gdk_drag_status( drag_context, GDK_ACTION_COPY, time);
g_free( dest_dir );
g_strfreev( list );
file_browser->pending_drag_status_tree = 0;
return;
}
if ( puri )
{
if ( 0 == ( gdk_drag_context_get_selected_action ( drag_context ) &
( GDK_ACTION_MOVE | GDK_ACTION_COPY | GDK_ACTION_LINK ) ) )
{
gdk_drag_status( drag_context, GDK_ACTION_MOVE, time);
}
gtk_drag_finish ( drag_context, TRUE, FALSE, time );
while ( *puri )
{
if ( **puri == '/' )
file_path = g_strdup( *puri );
else
file_path = g_filename_from_uri( *puri, NULL, NULL );
if ( file_path )
files = g_list_prepend( files, file_path );
++puri;
}
g_strfreev( list );
switch ( gdk_drag_context_get_selected_action ( drag_context ) )
{
case GDK_ACTION_COPY:
file_action = VFS_FILE_TASK_COPY;
break;
case GDK_ACTION_LINK:
file_action = VFS_FILE_TASK_LINK;
break;
/* FIXME:
GDK_ACTION_DEFAULT, GDK_ACTION_PRIVATE, and GDK_ACTION_ASK are not handled */
default:
break;
}
if ( files )
{
/* Accept the drop and perform file actions */
{
parent_win = gtk_widget_get_toplevel( GTK_WIDGET( file_browser ) );
task = ptk_file_task_new( file_action,
files,
dest_dir,
GTK_WINDOW( parent_win ),
file_browser->task_view );
ptk_file_task_run( task );
}
}
g_free( dest_dir );
gtk_drag_finish ( drag_context, TRUE, FALSE, time );
return ;
}
g_free( dest_dir );
}
//else
// g_warning ("bad dest_dir in on_dir_tree_view_drag_data_received");
}
/* If we are only getting drag status, not finished. */
if( file_browser->pending_drag_status_tree )
{
gdk_drag_status ( drag_context, GDK_ACTION_COPY, time );
file_browser->pending_drag_status_tree = 0;
return;
}
gtk_drag_finish ( drag_context, FALSE, FALSE, time );
}
gboolean on_dir_tree_view_drag_drop ( GtkWidget *widget,
GdkDragContext *drag_context,
gint x,
gint y,
guint time,
PtkFileBrowser* file_browser ) //MOD added
{
GdkAtom target = gdk_atom_intern( "text/uri-list", FALSE );
/* Don't call the default handler */
g_signal_stop_emission_by_name( widget, "drag-drop" );
gtk_drag_get_data ( widget, drag_context, target, time );
return TRUE;
}
gboolean on_dir_tree_view_drag_motion ( GtkWidget *widget,
GdkDragContext *drag_context,
gint x,
gint y,
guint time,
PtkFileBrowser* file_browser ) //MOD added
{
GdkDragAction suggested_action;
GdkAtom target;
GtkTargetList* target_list;
target_list = gtk_target_list_new( drag_targets, G_N_ELEMENTS(drag_targets) );
target = gtk_drag_dest_find_target( widget, drag_context, target_list );
gtk_target_list_unref( target_list );
if (target == GDK_NONE)
gdk_drag_status( drag_context, 0, time);
else
{
// Need to set suggested_action because default handler assumes copy
/* Only 'move' is available. The user force move action by pressing Shift key */
if( (gdk_drag_context_get_actions ( drag_context ) & GDK_ACTION_ALL) == GDK_ACTION_MOVE )
suggested_action = GDK_ACTION_MOVE;
/* Only 'copy' is available. The user force copy action by pressing Ctrl key */
else if( (gdk_drag_context_get_actions ( drag_context ) & GDK_ACTION_ALL) == GDK_ACTION_COPY )
suggested_action = GDK_ACTION_COPY;
/* Only 'link' is available. The user force link action by pressing Shift+Ctrl key */
else if( (gdk_drag_context_get_actions ( drag_context ) & GDK_ACTION_ALL) == GDK_ACTION_LINK )
suggested_action = GDK_ACTION_LINK;
/* Several different actions are available. We have to figure out a good default action. */
else
{
int drag_action = xset_get_int( "drag_action", "x" );
if ( drag_action == 1 )
suggested_action = GDK_ACTION_COPY;
else if ( drag_action == 2 )
suggested_action = GDK_ACTION_MOVE;
else if ( drag_action == 3 )
suggested_action = GDK_ACTION_LINK;
else
{
// automatic
file_browser->pending_drag_status_tree = 1;
gtk_drag_get_data (widget, drag_context, target, time);
suggested_action = gdk_drag_context_get_selected_action( drag_context );
}
}
#if GTK_CHECK_VERSION (3, 0, 0)
/* hack to be able to call the default handler with the correct suggested_action */
struct _GdkDragContext {
GObject parent_instance;
/*< private >*/
GdkDragProtocol protocol;
gboolean is_source;
GdkWindow *source_window;
GdkWindow *dest_window;
GList *targets;
GdkDragAction actions;
GdkDragAction suggested_action;
GdkDragAction action;
guint32 start_time;
GdkDevice *device;
};
((struct _GdkDragContext *)drag_context)->suggested_action = suggested_action;
#else
drag_context->suggested_action = suggested_action; // needed for default handler
#endif
gdk_drag_status( drag_context, suggested_action, gtk_get_current_event_time() );
}
return FALSE;
}
static gboolean on_dir_tree_view_drag_leave ( GtkWidget *widget,
GdkDragContext *drag_context,
guint time,
PtkFileBrowser* file_browser )
{
file_browser->drag_source_dev_tree = 0;
return FALSE;
}
|
193 | ./spacefm/src/mime-type/mime-cache.c | /*
* mime-cache.c
*
* Copyright 2007 PCMan <pcman.tw@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "mime-cache.h"
#include <glib.h>
#include "glib-mem.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#ifdef HAVE_MMAP
#include <sys/mman.h>
#endif
#include <fcntl.h>
#include <unistd.h>
#include <fnmatch.h>
#define LIB_MAJOR_VERSION 1
/* FIXME: since mime-cache 1.2, weight is splitted into three parts
* only lower 8 bit contains weight, and higher bits are flags and case-sensitivity.
* anyway, since we don't support weight at all, it'll be fixed later.
* We claimed that we support 1.2 to cheat pcmanfm as a temporary quick dirty fix
* for the broken file manager, but this should be correctly done in the future.
* Weight and case-sensitivity are not handled now. */
#define LIB_MAX_MINOR_VERSION 2
#define LIB_MIN_MINOR_VERSION 0
/* handle byte order here */
#define VAL16(buffrer, idx) GUINT16_FROM_BE(*(guint16*)(buffer + idx))
#define VAL32(buffer, idx) GUINT32_FROM_BE(*(guint32*)(buffer + idx))
/* cache header */
#define MAJOR_VERSION 0
#define MINOR_VERSION 2
#define ALIAS_LIST 4
#define PARENT_LIST 8
#define LITERAL_LIST 12
#define SUFFIX_TREE 16
#define GLOB_LIST 20
#define MAGIC_LIST 24
#define NAMESPACE_LIST 28
MimeCache* mime_cache_new( const char* file_path )
{
MimeCache* cache = NULL;
cache = g_slice_new0( MimeCache );
if( G_LIKELY( file_path ) )
mime_cache_load( cache, file_path );
return cache;
}
static void mime_cache_unload( MimeCache* cache, gboolean clear )
{
if( G_LIKELY(cache->buffer) )
{
#ifdef HAVE_MMAP
munmap( (char*)cache->buffer, cache->size );
#else
g_free( cache->buffer );
#endif
}
g_free( cache->file_path );
if( clear )
memset( cache, 0, sizeof(MimeCache) );
}
void mime_cache_free( MimeCache* cache )
{
mime_cache_unload( cache, FALSE );
g_slice_free( MimeCache, cache );
}
gboolean mime_cache_load( MimeCache* cache, const char* file_path )
{
guint majv, minv;
int fd = -1;
struct stat statbuf;
char* buffer = NULL;
guint32 offset;
/* Unload old cache first if needed */
if( file_path == cache->file_path )
cache->file_path = NULL; /* steal the string to prevent it from being freed during unload */
mime_cache_unload( cache, TRUE );
/* Store the file path */
cache->file_path = g_strdup( file_path );
/* Open the file and map it into memory */
fd = open ( file_path, O_RDONLY, 0 );
if ( fd < 0 )
return FALSE;
if( fstat ( fd, &statbuf ) < 0 )
{
close( fd );
return FALSE;
}
#ifdef HAVE_MMAP
buffer = mmap( NULL, statbuf.st_size, PROT_READ, MAP_SHARED, fd, 0 );
#else
buffer = g_malloc( statbuf.st_size );
if( buffer )
read( fd, buffer, statbuf.st_size );
else
buffer = (void*)-1;
#endif
close( fd );
if ( buffer == (void*)-1 )
return FALSE;
majv = VAL16( buffer, MAJOR_VERSION );
minv = VAL16( buffer, MINOR_VERSION);
/* Check version */
if ( majv > LIB_MAJOR_VERSION || minv > LIB_MAX_MINOR_VERSION || minv < LIB_MIN_MINOR_VERSION )
{
#ifdef HAVE_MMAP
munmap ( buffer, statbuf.st_size );
#else
g_free( buffer );
#endif
return FALSE;
}
/* Since mime.cache v1.1, shared mime info v0.4
* suffix tree is replaced with reverse suffix tree,
* and glob and literal strings are sorted by weight. */
if( minv >= 1 )
{
cache->has_reverse_suffix = TRUE;
cache->has_str_weight = TRUE;
}
cache->buffer = buffer;
cache->size = statbuf.st_size;
offset = VAL32(buffer, ALIAS_LIST);
cache->alias = buffer + offset + 4;
cache->n_alias = VAL32( buffer, offset );
offset = VAL32(buffer, PARENT_LIST);
cache->parents = buffer + offset + 4;
cache->n_parents = VAL32( buffer, offset );
offset = VAL32(buffer, LITERAL_LIST);
cache->literals = buffer + offset + 4;
cache->n_literals = VAL32( buffer, offset );
offset = VAL32(buffer, GLOB_LIST);
cache->globs = buffer + offset + 4;
cache->n_globs = VAL32( buffer, offset );
offset = VAL32(buffer, SUFFIX_TREE);
cache->suffix_roots = buffer + VAL32( buffer + offset, 4 );
cache->n_suffix_roots = VAL32( buffer, offset );
offset = VAL32(buffer, MAGIC_LIST);
cache->n_magics = VAL32( buffer, offset );
cache->magic_max_extent = VAL32( buffer + offset, 4 );
cache->magics = buffer + VAL32( buffer + offset, 8 );
return TRUE;
}
static gboolean magic_rule_match( const char* buf, const char* rule, const char* data, int len )
{
gboolean match = FALSE;
guint32 offset = VAL32( rule, 0 );
guint32 range = VAL32( rule, 4 );
guint32 max_offset = offset + range;
guint32 val_len = VAL32( rule, 12 );
for( ; offset < max_offset && (offset + val_len) <= len ; ++offset )
{
guint32 val_off = VAL32( rule, 16 );
guint32 mask_off = VAL32( rule, 20 );
const char* value = buf + val_off;
/* FIXME: word_size and byte order are not supported! */
if( G_UNLIKELY( mask_off > 0 ) ) /* compare with mask applied */
{
int i = 0;
const char* mask = buf + mask_off;
for( ; i < val_len; ++i )
{
if( (data[offset + i] & mask[i]) != value[i] )
break;
}
if( i >= val_len )
match = TRUE;
}
else /* direct comparison */
{
if( 0 == memcmp( value, data + offset, val_len ) )
match = TRUE;
}
if( match )
{
guint32 n_children = VAL32( rule, 24 );
if( n_children > 0 )
{
guint32 first_child_off = VAL32( rule, 28 );
guint i;
rule = buf + first_child_off;
for( i = 0; i < n_children; ++i, rule += 32 )
{
if( magic_rule_match( buf, rule, data, len ) )
return TRUE;
}
}
else
return TRUE;
}
}
return FALSE;
}
static gboolean magic_match( const char* buf, const char* magic, const char* data, int len )
{
guint32 n_rules = VAL32( magic, 8 );
guint32 rules_off = VAL32( magic, 12 );
const char* rule = buf + rules_off;
int i;
for( i = 0; i < n_rules; ++i, rule += 32 )
if( magic_rule_match( buf, rule, data, len ) )
return TRUE;
return FALSE;
}
const char* mime_cache_lookup_magic( MimeCache* cache, const char* data, int len )
{
const char* magic = cache->magics;
int i;
if( G_UNLIKELY( ! data || (0 == len) || ! magic ) )
return NULL;
for( i = 0; i < cache->n_magics; ++i, magic += 16 )
{
if( magic_match( cache->buffer, magic, data, len ) )
{
return cache->buffer + VAL32( magic, 4 );
}
}
return NULL;
}
static const char* lookup_suffix_nodes( const char* buf, const char* nodes, guint32 n, const char* name )
{
gunichar uchar;
uchar = g_unichar_tolower( g_utf8_get_char( name ) );
/* binary search */
int upper = n, lower = 0;
int middle = n/2;
while( upper >= lower )
{
const char* node =nodes + middle * 16;
guint32 ch = VAL32(node, 0);
if( uchar < ch )
upper = middle - 1;
else if( uchar > ch )
lower = middle + 1;
else /* uchar == ch */
{
guint32 n_children = VAL32(node, 8);
name =g_utf8_next_char(name);
if( n_children > 0 )
{
guint32 first_child_off;
if( uchar == 0 )
return NULL;
if( ! name || 0 == name[0] )
{
guint32 offset = VAL32(node, 4);
return offset ? buf + offset : NULL;
}
first_child_off = VAL32(node, 12);
return lookup_suffix_nodes( buf, (buf + first_child_off), n_children, name );
}
else
{
if( ! name || 0 == name[0] )
{
guint32 offset = VAL32(node, 4);
return offset ? buf + offset : NULL;
}
return NULL;
}
}
middle = (upper + lower) / 2;
}
return NULL;
}
/* Reverse suffix tree is used since mime.cache 1.1 (shared mime info 0.4)
* Returns the address of the found "node", not mime-type.
* FIXME: 1. Should be optimized with binary search
* 2. Should consider weight of suffix nodes
*/
static const char* lookup_reverse_suffix_nodes( const char* buf, const char* nodes, guint32 n, const char* name, const char* suffix, const char** suffix_pos )
{
const char *ret = NULL;
const char *_suffix_pos = NULL, *cur_suffix_pos = (const char*)suffix + 1;
const char* leaf_node = NULL;
gunichar uchar;
uchar = suffix ? g_unichar_tolower( g_utf8_get_char( suffix ) ) : 0;
/* g_debug("%s: suffix= '%s'", name, suffix); */
int i;
for( i = 0; i < n; ++i )
{
const char* node =nodes + i * 12;
guint32 ch = VAL32(node, 0);
_suffix_pos = suffix;
if( G_LIKELY( ch ) )
{
if( ch == uchar )
{
guint32 n_children = VAL32(node, 4);
guint32 first_child_off = VAL32(node, 8);
leaf_node = lookup_reverse_suffix_nodes( buf,
buf + first_child_off,
n_children,
name,
g_utf8_find_prev_char(name, suffix),
&_suffix_pos );
if( leaf_node && _suffix_pos < cur_suffix_pos )
{
ret = leaf_node;
cur_suffix_pos = _suffix_pos;
}
}
}
else /* ch == 0 */
{
/* guint32 weight = VAL32(node, 8); */
/* suffix is found in the tree! */
if( suffix < cur_suffix_pos )
{
ret = node;
cur_suffix_pos = suffix;
}
}
}
*suffix_pos = cur_suffix_pos;
return ret;
}
const char* mime_cache_lookup_suffix( MimeCache* cache, const char* filename, const char** suffix_pos )
{
const char* root = cache->suffix_roots;
int i, n = cache->n_suffix_roots;
const char* mime_type = NULL, *ret = NULL, *prev_suffix_pos = (const char*)-1;
int fn_len, n_nodes;
if( G_UNLIKELY( ! filename || ! *filename || 0 == n ) )
return NULL;
if( cache->has_reverse_suffix ) /* since mime.cache ver: 1.1 */
{
const char *suffix, *leaf_node, *_suffix_pos = (const char*)-1;
fn_len = strlen( filename );
suffix = g_utf8_find_prev_char( filename, filename + fn_len );
leaf_node = lookup_reverse_suffix_nodes( cache->buffer, root, n, filename, suffix, &_suffix_pos );
if( leaf_node )
{
mime_type = cache->buffer + VAL32( leaf_node, 4 );
/* g_debug( "found: %s", mime_type ); */
*suffix_pos = _suffix_pos;
ret = mime_type;
}
}
else /* before mime.cache ver: 1.1 */
{
for( i = 0; i <n; ++i, root += 16 )
{
guint32 first_child_off;
guint32 ch = VAL32( root, 0 );
const char* suffix;
suffix = strchr( filename, ch );
if( ! suffix )
continue;
first_child_off = VAL32( root, 12 );
// FIXME: is this correct???
n = VAL32( root, 8 );
do{
mime_type = lookup_suffix_nodes( cache->buffer, cache->buffer + first_child_off, n, g_utf8_next_char(suffix) );
if( mime_type && suffix < prev_suffix_pos ) /* we want the longest suffix matched. */
{
ret = mime_type;
prev_suffix_pos = suffix;
}
}while( (suffix = strchr( suffix + 1, ch )) );
}
*suffix_pos = ret ? prev_suffix_pos : (const char*)-1;
}
return ret;
}
static const char* lookup_str_in_entries( MimeCache* cache, const char* entries, int n, const char* str )
{
int upper = n, lower = 0;
int middle = upper/2;
if( G_LIKELY( entries && str && *str ) )
{
/* binary search */
while( upper >= lower )
{
const char* entry = entries + middle * 8;
const char* str2 = cache->buffer + VAL32(entry, 0);
int comp = strcmp( str, str2 );
if( comp < 0 )
upper = middle - 1;
else if( comp > 0 )
lower = middle + 1;
else /* comp == 0 */
return ( cache->buffer+ VAL32(entry, 4) );
middle = (upper + lower) / 2;
}
}
return NULL;
}
const char* mime_cache_lookup_alias( MimeCache* cache, const char* mime_type )
{
return lookup_str_in_entries( cache, cache->alias, cache->n_alias, mime_type );
}
const char* mime_cache_lookup_literal( MimeCache* cache, const char* filename )
{
/* FIXME: weight is used in literal lookup after mime.cache v1.1.
* However, it's poorly documented. So I've no idea how to implement this. */
if( cache->has_str_weight )
{
const char* entries = cache->literals;
int n = cache->n_literals;
int upper = n, lower = 0;
int middle = upper/2;
if( G_LIKELY( entries && filename && *filename ) )
{
/* binary search */
while( upper >= lower )
{
/* The entry size is different in v 1.1 */
const char* entry = entries + middle * 12;
const char* str2 = cache->buffer + VAL32(entry, 0);
int comp = strcmp( filename, str2 );
if( comp < 0 )
upper = middle - 1;
else if( comp > 0 )
lower = middle + 1;
else /* comp == 0 */
return ( cache->buffer+ VAL32(entry, 4) );
middle = (upper + lower) / 2;
}
}
return NULL;
}
return lookup_str_in_entries( cache, cache->literals, cache->n_literals, filename );
}
const char* mime_cache_lookup_glob( MimeCache* cache, const char* filename, int *glob_len )
{
const char* entry = cache->globs, *type = NULL;
int i;
int max_glob_len = 0;
/* entry size is changed in mime.cache 1.1 */
size_t entry_size = cache->has_str_weight ? 12 : 8;
for( i = 0; i < cache->n_globs; ++i )
{
const char* glob = cache->buffer + VAL32( entry, 0 );
int _glob_len;
if( 0 == fnmatch( glob, filename, 0 ) && (_glob_len = strlen(glob)) > max_glob_len )
{
max_glob_len = _glob_len;
type = (cache->buffer + VAL32( entry, 4 ));
}
entry += entry_size;
}
*glob_len = max_glob_len;
return type;
}
const char** mime_cache_lookup_parents( MimeCache* cache, const char* mime_type )
{
guint32 n, i;
const char** result;
const char* parents;
parents = lookup_str_in_entries( cache, cache->parents, cache->n_parents, mime_type );
if( ! parents )
return NULL;
n = VAL32(parents, 0);
parents += 4;
result = (const char**)g_new( char*, n + 1 );
for( i = 0; i < n; ++i )
{
guint32 parent_off = VAL32( parents, i * 4 );
const char* parent = cache->buffer + parent_off;
result[i] = parent;
}
result[ n ] = NULL;
return result;
}
|
194 | ./spacefm/src/mime-type/mime-action.c | /*
* mime-action.c
*
* Copyright 2007 PCMan <pcman.tw@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "mime-action.h"
#include "glib-utils.h"
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
gboolean save_to_file( const char* path, const char* data, gssize len )
{
int fd = creat( path, 0644 );
if( fd == -1 )
return FALSE;
if( write( fd, data, len ) == -1 )
{
close( fd );
return FALSE;
}
close( fd );
return TRUE;
}
const char group_desktop[] = "Desktop Entry";
const char key_mime_type[] = "MimeType";
typedef char* (*DataDirFunc) ( const char* dir, const char* mime_type, gpointer user_data );
static char* data_dir_foreach( DataDirFunc func, const char* mime_type, gpointer user_data )
{
char* ret = NULL;
const gchar* const * dirs;
const char* dir = g_get_user_data_dir();
if( (ret = func( dir, mime_type, user_data )) )
return ret;
dirs = g_get_system_data_dirs();
for( ; *dirs; ++dirs )
{
if( (ret = func( *dirs, mime_type, user_data )) )
return ret;
}
return NULL;
}
static void update_desktop_database()
{
char* argv[3];
argv[0] = g_find_program_in_path( "update-desktop-database" );
if( G_UNLIKELY( ! argv[0] ) )
return;
argv[1] = g_build_filename( g_get_user_data_dir(), "applications", NULL );
argv[2] = NULL;
g_spawn_sync( NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL);
g_free( argv[0] );
g_free( argv[1] );
}
static int strv_index( char** strv, const char* str )
{
char**p;
if( G_LIKELY( strv && str ) )
{
for( p = strv; *p; ++p )
{
if( 0 == strcmp( *p, str ) )
return (p - strv);
}
}
return -1;
}
static void remove_actions( const char* type, GArray* actions )
{ //sfm 0.7.7+ added
char** removed = NULL;
gsize n_removed = 0, r;
int i;
//g_print( "remove_actions( %s )\n", type );
char* path = g_build_filename( g_get_user_data_dir(),
"applications/mimeapps.list", NULL );
GKeyFile* file = g_key_file_new();
if ( g_key_file_load_from_file( file, path, 0, NULL ) )
{
removed = g_key_file_get_string_list( file, "Removed Associations",
type, &n_removed, NULL );
if ( removed )
{
for ( r = 0; r < n_removed; ++r )
{
g_strstrip( removed[r] );
//g_print( " %s\n", removed[r] );
i = strv_index( (char**)actions->data, removed[r] );
if ( i != -1 )
{
//g_print( " ACTION-REMOVED\n" );
g_array_remove_index( actions, i );
}
}
}
g_strfreev( removed );
}
g_key_file_free( file );
g_free( path );
}
static char* get_actions( const char* dir, const char* type, GArray* actions )
{
//g_print( "get_actions( %s, %s )\n", dir, type );
GKeyFile* file;
gboolean opened;
int n;
char** apps = NULL;
char** removed = NULL;
gboolean is_removed;
gsize n_removed = 0, r;
char* names[] = { "applications/mimeapps.list", "applications/mimeinfo.cache" };
char* sections[] = { "Added Associations", "MIME Cache" };
for ( n = 0; n < G_N_ELEMENTS( names ); n++ )
{
char* path = g_build_filename( dir, names[n], NULL );
//g_print( " path = %s\n", path );
file = g_key_file_new();
opened = g_key_file_load_from_file( file, path, 0, NULL );
g_free( path );
if( G_LIKELY( opened ) )
{
gsize n_apps = 0, i;
apps = g_key_file_get_string_list( file, sections[n], type, &n_apps, NULL );
if ( n == 0 )
{
// get removed associations in this dir
removed = g_key_file_get_string_list( file, "Removed Associations",
type, &n_removed, NULL );
}
for ( i = 0; i < n_apps; ++i )
{
g_strstrip( apps[i] );
//g_print( " %s\n", apps[i] );
// check if removed
is_removed = FALSE;
if ( removed && n > 0 )
{
for ( r = 0; r < n_removed; ++r )
{
g_strstrip( removed[r] );
if ( !strcmp( removed[r], apps[i] ) )
{
//g_print( " REMOVED\n" );
is_removed = TRUE;
break;
}
}
}
if( !is_removed && -1 == strv_index( (char**)actions->data, apps[i] ) )
{
/* check for app existence */
path = mime_type_locate_desktop_file( NULL, apps[i] );
if( G_LIKELY(path) )
{
//g_print( " EXISTS\n");
g_array_append_val( actions, apps[i] );
g_free( path );
}
else
g_free( apps[i] );
apps[i] = NULL; /* steal the string */
}
else
{
g_free( apps[i] );
apps[i] = NULL;
}
}
g_free( apps ); /* don't call g_strfreev since all strings in the array was stolen. */
}
g_key_file_free( file );
}
g_strfreev( removed );
return NULL; /* return NULL so the for_each operation doesn't stop. */
}
/*
* Get a list of applications supporting this mime-type
* The returned string array was newly allocated, and should be
* freed with g_strfreev() when no longer used.
*/
char** mime_type_get_actions( const char* type )
{
GArray* actions = g_array_sized_new( TRUE, FALSE, sizeof(char*), 10 );
char* default_app = NULL;
/* FIXME: actions of parent types should be added, too. */
/* get all actions for this file type */
data_dir_foreach( (DataDirFunc)get_actions, type, actions );
/* remove actions for this file type */ //sfm
remove_actions( type, actions );
/* ensure default app is in the list */
if( G_LIKELY( ( default_app = mime_type_get_default_action( type ) ) ) )
{
int i = strv_index( (char**)actions->data, default_app );
if( i == -1 ) /* default app is not in the list, add it! */
{
g_array_prepend_val( actions, default_app );
}
else /* default app is in the list, move it to the first. */
{
if( i != 0 )
{
char** pdata = (char**)actions->data;
char* tmp = pdata[i];
g_array_remove_index( actions, i );
g_array_prepend_val( actions, tmp );
}
g_free( default_app );
}
}
return (char**)g_array_free( actions, actions->len == 0 );
}
/*
* NOTE:
* This API is very time consuming, but unfortunately, due to the damn poor design of
* Freedesktop.org spec, all the insane checks here are necessary. Sigh... :-(
*/
gboolean mime_type_has_action( const char* type, const char* desktop_id )
{
char** actions, **action;
char *cmd = NULL, *name = NULL;
gboolean found = FALSE;
gboolean is_desktop = g_str_has_suffix( desktop_id, ".desktop" );
if( is_desktop )
{
char** types;
GKeyFile* kf = g_key_file_new();
char* filename = mime_type_locate_desktop_file( NULL, desktop_id );
if( filename && g_key_file_load_from_file( kf, filename, 0, NULL ) )
{
types = g_key_file_get_string_list( kf, group_desktop, key_mime_type, NULL, NULL );
if( -1 != strv_index( types, type ) )
{
/* our mime-type is already found in the desktop file. no further check is needed */
found = TRUE;
}
g_strfreev( types );
if( ! found ) /* get the content of desktop file for comparison */
{
cmd = g_key_file_get_string( kf, group_desktop, "Exec", NULL );
name = g_key_file_get_string( kf, group_desktop, "Name", NULL );
}
}
g_free( filename );
g_key_file_free( kf );
}
else
{
cmd = (char*)desktop_id;
}
actions = mime_type_get_actions( type );
if( actions )
{
for( action = actions; ! found && *action; ++action )
{
/* Try to match directly by desktop_id first */
if( is_desktop && 0 == strcmp( *action, desktop_id ) )
{
found = TRUE;
}
else /* Then, try to match by "Exec" and "Name" keys */
{
char *name2 = NULL, *cmd2 = NULL, *filename = NULL;
GKeyFile* kf = g_key_file_new();
filename = mime_type_locate_desktop_file( NULL, *action );
if( filename && g_key_file_load_from_file( kf, filename, 0, NULL ) )
{
cmd2 = g_key_file_get_string( kf, group_desktop, "Exec", NULL );
if( cmd && cmd2 && 0 == strcmp( cmd, cmd2 ) ) /* 2 desktop files have same "Exec" */
{
if( is_desktop )
{
name2 = g_key_file_get_string( kf, group_desktop, "Name", NULL );
/* Then, check if the "Name" keys of 2 desktop files are the same. */
if( name && name2 && 0 == strcmp( name, name2 ) )
{
/* Both "Exec" and "Name" keys of the 2 desktop files are
* totally the same. So, despite having different desktop id
* They actually refer to the same application. */
found = TRUE;
}
g_free( name2 );
}
else
found = TRUE;
}
}
g_free( filename );
g_free( cmd2 );
g_key_file_free( kf );
}
}
g_strfreev( actions );
}
if( is_desktop )
{
g_free( cmd );
g_free( name );
}
return found;
}
#if 0
static gboolean is_custom_desktop_file( const char* desktop_id )
{
char* path = g_build_filename( g_get_user_data_dir(), "applications", desktop_id, NULL );
gboolean ret = g_file_test( path, G_FILE_TEST_EXISTS );
g_free( path );
return ret;
}
#endif
static char* make_custom_desktop_file( const char* desktop_id, const char* mime_type )
{
char *name = NULL, *cust_template = NULL, *cust = NULL, *path, *dir;
char* file_content = NULL;
gsize len = 0;
guint i;
if( G_LIKELY( g_str_has_suffix(desktop_id, ".desktop") ) )
{
GKeyFile *kf = g_key_file_new();
char* name = mime_type_locate_desktop_file( NULL, desktop_id );
if( G_UNLIKELY( ! name || ! g_key_file_load_from_file( kf, name,
G_KEY_FILE_KEEP_TRANSLATIONS, NULL ) ) )
{
g_free( name );
return NULL; /* not a valid desktop file */
}
g_free( name );
/*
FIXME: If the source desktop_id refers to a custom desktop file, and
value of the MimeType key equals to our mime-type, there is no
need to generate a new desktop file.
if( G_UNLIKELY( is_custom_desktop_file( desktop_id ) ) )
{
}
*/
/* set our mime-type */
g_key_file_set_string_list( kf, group_desktop, key_mime_type, &mime_type, 1 );
/* store id of original desktop file, for future use. */
g_key_file_set_string( kf, group_desktop, "X-MimeType-Derived", desktop_id );
g_key_file_set_string( kf, group_desktop, "NoDisplay", "true" );
name = g_strndup( desktop_id, strlen(desktop_id) - 8 );
cust_template = g_strdup_printf( "%s-usercustom-%%d.desktop", name );
g_free( name );
file_content = g_key_file_to_data( kf, &len, NULL );
g_key_file_free( kf );
}
else /* it's not a desktop_id, but a command */
{
char* p;
const char file_templ[] =
"[Desktop Entry]\n"
"Encoding=UTF-8\n"
"Name=%s\n"
"Exec=%s\n"
"MimeType=%s\n"
"Icon=exec\n"
"NoDisplay=true\n"; /* FIXME: Terminal? */
/* Make a user-created desktop file for the command */
name = g_path_get_basename( desktop_id );
if( (p = strchr(name, ' ')) ) /* FIXME: skip command line arguments. is this safe? */
*p = '\0';
file_content = g_strdup_printf( file_templ, name, desktop_id, mime_type );
len = strlen( file_content );
cust_template = g_strdup_printf( "%s-usercreated-%%d.desktop", name );
g_free( name );
}
/* generate unique file name */
dir = g_build_filename( g_get_user_data_dir(), "applications", NULL );
g_mkdir_with_parents( dir, 0700 );
for( i = 0; ; ++i )
{
/* generate the basename */
cust = g_strdup_printf( cust_template, i );
path = g_build_filename( dir, cust, NULL ); /* test if the filename already exists */
if( g_file_test( path, G_FILE_TEST_EXISTS ) )
{
g_free( cust );
g_free( path );
}
else /* this generated filename can be used */
break;
}
g_free( dir );
if( G_LIKELY( path ) )
{
save_to_file( path, file_content, len );
g_free( path );
/* execute update-desktop-database" to update mimeinfo.cache */
update_desktop_database();
}
return cust;
}
/*
* Add an applications used to open this mime-type
* desktop_id is the name of *.desktop file.
*
* custom_desktop: used to store name of the newly created user-custom desktop file, can be NULL.
*/
void mime_type_add_action( const char* type, const char* desktop_id, char** custom_desktop )
{
char* cust;
if( mime_type_has_action( type, desktop_id ) )
{
if( custom_desktop )
*custom_desktop = g_strdup( desktop_id );
return;
}
cust = make_custom_desktop_file( desktop_id, type );
if( custom_desktop )
*custom_desktop = cust;
else
g_free( cust );
}
static char* _locate_desktop_file_recursive( const char* path,
const char* desktop_id, gboolean first )
{ // if first is true, just search for subdirs not desktop_id (already searched)
const char* name;
char* sub_path;
GDir* dir = g_dir_open( path, 0, NULL );
if ( !dir )
return NULL;
char* found = NULL;
while ( name = g_dir_read_name( dir ) )
{
sub_path = g_build_filename( path, name, NULL );
if ( g_file_test( sub_path, G_FILE_TEST_IS_DIR ) )
{
if ( found = _locate_desktop_file_recursive( sub_path, desktop_id,
FALSE ) )
{
g_free( sub_path );
break;
}
}
else if ( !first && !strcmp( name, desktop_id ) &&
g_file_test( sub_path, G_FILE_TEST_IS_REGULAR ) )
{
found = sub_path;
break;
}
g_free( sub_path );
}
g_dir_close( dir );
return found;
}
static char* _locate_desktop_file( const char* dir, const char* unused,
const gpointer desktop_id )
{ //sfm 0.7.8 modified + 0.8.7 modified
gboolean found = FALSE;
char *path = g_build_filename( dir, "applications", (const char*)desktop_id,
NULL );
char* sep = strchr( (const char*)desktop_id, '-' );
if( sep )
sep = strrchr( path, '-' );
do
{
if ( g_file_test( path, G_FILE_TEST_IS_REGULAR ) )
{
found = TRUE;
break;
}
if ( sep )
{
*sep = '/';
sep = strchr( sep + 1, '-' );
}
else
break;
} while( !found );
if ( found )
return path;
g_free( path );
//sfm 0.8.7 some desktop files listed by the app chooser are in subdirs
path = g_build_filename( dir, "applications", NULL );
sep = _locate_desktop_file_recursive( path, desktop_id, TRUE );
g_free( path );
return sep;
}
char* mime_type_locate_desktop_file( const char* dir, const char* desktop_id )
{
if( dir )
return _locate_desktop_file( dir, NULL, (gpointer) desktop_id );
return data_dir_foreach( _locate_desktop_file, NULL, (gpointer) desktop_id );
}
static char* get_default_action( const char* dir, const char* type, gpointer user_data )
{ //sfm 0.7.7+ modified
// spec is not final - this implementation is a blend of the old and new
// http://www.freedesktop.org/wiki/Specifications/mime-actions-spec
// https://wiki.archlinux.org/index.php/Default_Applications
GKeyFile* file;
char* path;
char** apps;
gsize n_apps, i;
int n;
gboolean opened;
//g_print( "get_default_action( %s, %s )\n", dir, type );
// search these files in dir for the first existing default app
char* names[] = { "applications/mimeapps.list", "applications/defaults.list" };
char* sections[] = { "Added Associations", "Default Applications" };
for ( n = 0; n < G_N_ELEMENTS( names ); n++ )
{
char* path = g_build_filename( dir, names[n], NULL );
//g_print( " path = %s\n", path );
file = g_key_file_new();
opened = g_key_file_load_from_file( file, path, 0, NULL );
g_free( path );
if ( opened )
{
apps = g_key_file_get_string_list( file, sections[n], type, &n_apps, NULL );
if ( apps )
{
for ( i = 0; i < n_apps; ++i )
{
g_strstrip( apps[i] );
if ( apps[i][0] != '\0' )
{
//g_print( " %s\n", apps[i] );
if ( path = mime_type_locate_desktop_file( NULL, apps[i] ) )
{
//g_print( " EXISTS\n" );
g_free( path );
path = g_strdup( apps[i] );
g_strfreev( apps );
g_key_file_free( file );
return path;
}
}
}
}
g_strfreev( apps );
}
g_key_file_free( file );
}
return NULL;
}
/*
* Get default applications used to open this mime-type
* The returned string was newly allocated, and should be
* freed when no longer used.
* If NULL is returned, that means default app is not set for this mime-type.
*/
char* mime_type_get_default_action( const char* type )
{
/* FIXME: need to check parent types if default action of current type is not set. */
return data_dir_foreach( (DataDirFunc)get_default_action, type, NULL );
}
/*
* Set default application used to open this mime-type
* desktop_id is the name of *.desktop file to be new default
*/
void mime_type_set_default_action( const char* type, const char* desktop_id )
{ //sfm 0.7.7+ modified
// http://www.freedesktop.org/wiki/Specifications/mime-actions-spec
GKeyFile* file;
gsize len = 0;
char* data = NULL;
char** apps;
gsize n_apps, i;
char* str;
if ( !( type && type[0] != '\0' && desktop_id && desktop_id[0] != '\0' ) )
return;
char* dir = g_build_filename( g_get_user_data_dir(), "applications", NULL );
char* path = g_build_filename( dir, "mimeapps.list", NULL );
g_mkdir_with_parents( dir, 0700 );
g_free( dir );
// Load old file content, if available
file = g_key_file_new();
g_key_file_load_from_file( file, path, 0, NULL );
// add new default to first position in [Added Associations]
char* new_action = g_strdup_printf( "%s;", desktop_id );
apps = g_key_file_get_string_list( file, "Added Associations", type, &n_apps,
NULL );
if ( apps )
{
for ( i = 0; i < n_apps; ++i )
{
g_strstrip( apps[i] );
if ( apps[i][0] != '\0' && strcmp( apps[i], desktop_id ) )
{
str = new_action;
new_action = g_strdup_printf( "%s%s;", str, apps[i] );
g_free( str );
}
}
g_strfreev( apps );
}
// update key file - added
g_key_file_set_string( file, "Added Associations", type, new_action );
g_free( new_action );
// remove new default from [Removed Associations]
char* removed = NULL;
apps = g_key_file_get_string_list( file, "Removed Associations", type, &n_apps,
NULL );
if ( apps )
{
for ( i = 0; i < n_apps; ++i )
{
g_strstrip( apps[i] );
if ( apps[i][0] != '\0' && strcmp( apps[i], desktop_id ) )
{
str = removed;
removed = g_strdup_printf( "%s%s;", str ? str : "", apps[i] );
g_free( str );
}
}
g_strfreev( apps );
}
// update key file - removed
if ( removed )
g_key_file_set_string( file, "Removed Associations", type, removed );
else
g_key_file_remove_key( file, "Removed Associations", type, NULL );
g_free( removed );
// save
data = g_key_file_to_data( file, &len, NULL );
g_key_file_free( file );
save_to_file( path, data, len );
g_free( path );
g_free( data );
}
/* adds application to [Removed Associations] */
void mime_type_remove_action( const char* type, const char* desktop_id )
{ //sfm 0.7.7+ added
GKeyFile* file;
gsize len = 0;
char* data = NULL;
char** apps;
gsize n_apps, i;
char* str;
if ( !( type && type[0] != '\0' && desktop_id && desktop_id[0] != '\0' ) )
return;
char* dir = g_build_filename( g_get_user_data_dir(), "applications", NULL );
char* path = g_build_filename( dir, "mimeapps.list", NULL );
g_mkdir_with_parents( dir, 0700 );
g_free( dir );
// Load old file content, if available
file = g_key_file_new();
g_key_file_load_from_file( file, path, 0, NULL );
// remove app from [Added Associations]
char* new_action = NULL;
apps = g_key_file_get_string_list( file, "Added Associations", type, &n_apps,
NULL );
if ( apps )
{
for ( i = 0; i < n_apps; ++i )
{
g_strstrip( apps[i] );
if ( apps[i][0] != '\0' && strcmp( apps[i], desktop_id ) )
{
str = new_action;
new_action = g_strdup_printf( "%s%s;", str ? str : "", apps[i] );
g_free( str );
}
}
g_strfreev( apps );
}
// update key file - added
if ( new_action )
g_key_file_set_string( file, "Added Associations", type, new_action );
else
g_key_file_remove_key( file, "Added Associations", type, NULL );
g_free( new_action );
// add app to [Removed Associations]
char* removed = NULL;
gboolean is_removed = FALSE;
apps = g_key_file_get_string_list( file, "Removed Associations", type, &n_apps,
NULL );
if ( apps )
{
for ( i = 0; i < n_apps; ++i )
{
g_strstrip( apps[i] );
if ( apps[i][0] != '\0' )
{
if ( !strcmp( apps[i], desktop_id ) )
{
is_removed = TRUE;
break;
}
str = removed;
removed = g_strdup_printf( "%s%s;", str ? str : "", apps[i] );
g_free( str );
}
}
g_strfreev( apps );
}
// update key file
if ( !is_removed )
{
str = removed;
removed = g_strdup_printf( "%s%s;", str ? str : "", desktop_id );
g_free( str );
g_key_file_set_string( file, "Removed Associations", type, removed );
}
g_free( removed );
// save
data = g_key_file_to_data( file, &len, NULL );
g_key_file_free( file );
save_to_file( path, data, len );
g_free( path );
g_free( data );
}
/* appends app to type in Added Associations */
void mime_type_append_action( const char* type, const char* desktop_id )
{ //sfm 0.7.7+ added
// http://www.freedesktop.org/wiki/Specifications/mime-actions-spec
GKeyFile* file;
gsize len = 0;
char* data = NULL;
char** apps;
gsize n_apps, i;
char* str;
if ( !( type && type[0] != '\0' && desktop_id && desktop_id[0] != '\0' ) )
return;
char* dir = g_build_filename( g_get_user_data_dir(), "applications", NULL );
char* path = g_build_filename( dir, "mimeapps.list", NULL );
g_mkdir_with_parents( dir, 0700 );
g_free( dir );
// Load old file content, if available
file = g_key_file_new();
g_key_file_load_from_file( file, path, 0, NULL );
// append app to [Added Associations]
char* new_action = NULL;
gboolean is_present = FALSE;
apps = g_key_file_get_string_list( file, "Added Associations", type, &n_apps,
NULL );
if ( apps )
{
for ( i = 0; i < n_apps; ++i )
{
g_strstrip( apps[i] );
if ( apps[i][0] != '\0' )
{
if ( !strcmp( apps[i], desktop_id ) )
{
is_present = TRUE;
break;
}
str = new_action;
new_action = g_strdup_printf( "%s%s;", str ? str : "", apps[i] );
g_free( str );
}
}
g_strfreev( apps );
}
// update key file - added
if ( !is_present )
{
str = new_action;
new_action = g_strdup_printf( "%s%s;", str ? str : "", desktop_id );
g_free( str );
g_key_file_set_string( file, "Added Associations", type, new_action );
}
g_free( new_action );
// remove app from [Removed Associations]
char* removed = NULL;
apps = g_key_file_get_string_list( file, "Removed Associations", type, &n_apps,
NULL );
if ( apps )
{
for ( i = 0; i < n_apps; ++i )
{
g_strstrip( apps[i] );
if ( apps[i][0] != '\0' && strcmp( apps[i], desktop_id ) )
{
str = removed;
removed = g_strdup_printf( "%s%s;", str ? str : "", apps[i] );
g_free( str );
}
}
g_strfreev( apps );
}
// update key file - removed
if ( removed )
g_key_file_set_string( file, "Removed Associations", type, removed );
else
g_key_file_remove_key( file, "Removed Associations", type, NULL );
g_free( removed );
// save
data = g_key_file_to_data( file, &len, NULL );
g_key_file_free( file );
save_to_file( path, data, len );
g_free( path );
g_free( data );
}
|
195 | ./spacefm/src/mime-type/mime-type.c | /*
* mime-type.c
*
* Copyright 2007 Houng Jen Yee (PCMan) <pcman.tw@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
/* Currently this library is NOT MT-safe */
#ifndef _GNU_SOURCE
#define _GNU_SOURCE // euidaccess
#endif
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "mime-type.h"
#include "mime-cache.h"
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "glib-mem.h"
/*
* FIXME:
* Currently, mmap cannot be used because of the limitation of mmap.
* When a file is mapped for mime-type sniffing (checking file magic),
* they could be deleted during the check and hence result in Bus error.
* (Refer to the man page of mmap for detail)
* So here I undef HAVE_MMAP to disable the implementation using mmap.
*/
#undef HAVE_MMAP
#ifdef HAVE_MMAP
#include <sys/mman.h>
#endif
/* max extent used to checking text files */
#define TEXT_MAX_EXTENT 512
const char xdg_mime_type_unknown[] = "application/octet-stream";
const char xdg_mime_type_directory[] = "inode/directory";
const char xdg_mime_type_executable[] = "application/x-executable";
const char xdg_mime_type_plain_text[] = "text/plain";
static MimeCache** caches = NULL;
static guint n_caches = 0;
guint32 mime_cache_max_extent = 0;
/* allocated buffer used for mime magic checking to
prevent frequent memory allocation */
static char* mime_magic_buf = NULL;
/* for MT safety, the buffer should be locked */
G_LOCK_DEFINE_STATIC(mime_magic_buf);
/* load all mime.cache files on the system,
* including /usr/share/mime/mime.cache,
* /usr/local/share/mime/mime.cache,
* and $HOME/.local/share/mime/mime.cache. */
static void mime_cache_load_all();
/* free all mime.cache files on the system */
static void mime_cache_free_all();
static gboolean mime_type_is_data_plain_text( const char* data, int len );
/*
* Get mime-type of the specified file (quick, but less accurate):
* Mime-type of the file is determined by cheking the filename only.
* If statbuf != NULL, it will be used to determine if the file is a directory.
*/
const char* mime_type_get_by_filename( const char* filename, struct stat64* statbuf )
{
const char* type = NULL, *suffix_pos = NULL, *prev_suffix_pos = (const char*)-1;
int i;
MimeCache* cache;
if( G_UNLIKELY( statbuf && S_ISDIR( statbuf->st_mode ) ) )
return XDG_MIME_TYPE_DIRECTORY;
for( i = 0; ! type && i < n_caches; ++i )
{
cache = caches[i];
type = mime_cache_lookup_literal( cache, filename );
if( G_LIKELY( ! type ) )
{
const char* _type = mime_cache_lookup_suffix( cache, filename, &suffix_pos );
if( _type && suffix_pos < prev_suffix_pos )
{
type = _type;
prev_suffix_pos = suffix_pos;
}
}
}
if( G_UNLIKELY( ! type ) ) /* glob matching */
{
int max_glob_len = 0, glob_len = 0;
for( i = 0; ! type && i < n_caches; ++i )
{
cache = caches[i];
const char* matched_type;
matched_type = mime_cache_lookup_glob( cache, filename, &glob_len );
/* according to the mime.cache 1.0 spec, we should use the longest glob matched. */
if( matched_type && glob_len > max_glob_len )
{
type = matched_type;
max_glob_len = glob_len;
}
}
}
return type && *type ? type : XDG_MIME_TYPE_UNKNOWN;
}
/*
* Get mime-type info of the specified file (slow, but more accurate):
* To determine the mime-type of the file, mime_type_get_by_filename() is
* tried first. If the mime-type couldn't be determined, the content of
* the file will be checked, which is much more time-consuming.
* If statbuf is not NULL, it will be used to determine if the file is a directory,
* or if the file is an executable file; otherwise, the function will call stat()
* to gather this info itself. So if you already have stat info of the file,
* pass it to the function to prevent checking the file stat again.
* If you have basename of the file, pass it to the function can improve the
* efifciency, too. Otherwise, the function will try to get the basename of
* the specified file again.
*/
const char* mime_type_get_by_file( const char* filepath, struct stat64* statbuf, const char* basename )
{
const char* type;
struct stat64 _statbuf;
if( statbuf == NULL || G_UNLIKELY( S_ISLNK(statbuf->st_mode) ) )
{
statbuf = &_statbuf;
if( stat64 ( filepath, statbuf ) == -1 )
return XDG_MIME_TYPE_UNKNOWN;
}
if( S_ISDIR( statbuf->st_mode ) )
return XDG_MIME_TYPE_DIRECTORY;
if( basename == NULL )
{
basename = g_utf8_strrchr( filepath, -1, '/' );
if( G_LIKELY( basename ) )
++basename;
else
basename = filepath;
}
if( G_LIKELY(basename) )
{
type = mime_type_get_by_filename( basename, statbuf );
if( G_LIKELY( strcmp( type, XDG_MIME_TYPE_UNKNOWN ) ) )
return type;
type = NULL;
}
//sfm added check for fifo due to hang on one system with a particular pipe
// - is this needed?
if( G_LIKELY(statbuf->st_size > 0 && !S_ISFIFO( statbuf->st_mode ) ) )
{
int fd = -1;
char* data;
/* Open the file and map it into memory */
fd = open ( filepath, O_RDONLY, 0 );
if ( fd != -1 )
{
int len = mime_cache_max_extent < statbuf->st_size ? mime_cache_max_extent : statbuf->st_size;
#ifdef HAVE_MMAP
data = (char*) mmap( NULL, len, PROT_READ, MAP_SHARED, fd, 0 );
#else
/*
* FIXME: Can g_alloca() be used here? It's very fast, but is it safe?
* Actually, we can allocate a block of memory with the size of mime_cache_max_extent,
* then we don't need to do dynamic allocation/free every time, but multi-threading
* will be a nightmare, so...
*/
/* try to lock the common buffer */
if( G_LIKELY( G_TRYLOCK( mime_magic_buf ) ) )
data = mime_magic_buf;
else /* the buffer is in use, allocate new one */
data = g_malloc( len );
len = read( fd, data, len );
if( G_UNLIKELY( len == -1 ) )
{
if( G_LIKELY( data == mime_magic_buf ) )
G_UNLOCK( mime_magic_buf );
else
g_free( data );
data = (void*)-1;
}
#endif
if( data != (void*)-1 )
{
int i;
for( i = 0; ! type && i < n_caches; ++i )
type = mime_cache_lookup_magic( caches[i], data, len );
/* Check for executable file */
if( ! type && g_file_test( filepath, G_FILE_TEST_IS_EXECUTABLE ) )
type = XDG_MIME_TYPE_EXECUTABLE;
/* fallback: check for plain text */
if( ! type )
{
if( mime_type_is_data_plain_text( data, len > TEXT_MAX_EXTENT ? TEXT_MAX_EXTENT : len ) )
type = XDG_MIME_TYPE_PLAIN_TEXT;
}
#ifdef HAVE_MMAP
munmap ( (char*)data, len );
#else
if( G_LIKELY( data == mime_magic_buf ) )
G_UNLOCK( mime_magic_buf ); /* unlock the common buffer */
else /* we use our own buffer */
g_free( data );
#endif
}
close( fd );
}
}
else
{
/* empty file can be viewed as text file */
type = XDG_MIME_TYPE_PLAIN_TEXT;
}
return type && *type ? type : XDG_MIME_TYPE_UNKNOWN;
}
/* Get the name of mime-type */
/*const char* mime_type_get_type( MimeInfo* info )
{
return info->type_name;
}
*/
static char* parse_xml_desc( const char* buf, size_t len, const char* locale )
{
const char *buf_end = buf + len;
const char *comment = NULL, *comment_end, *eng_comment;
size_t eng_comment_len = 0, comment_len = 0;
char target[64];
static const char end_comment_tag[]="</comment>";
eng_comment = g_strstr_len( buf, len, "<comment>" ); /* default English comment */
if( G_UNLIKELY( ! eng_comment ) ) /* This xml file is invalid */
return NULL;
len -= 9;
eng_comment += 9;
comment_end = g_strstr_len( eng_comment, len, end_comment_tag ); /* find </comment> */
if( G_UNLIKELY( ! comment_end ) )
return NULL;
eng_comment_len = comment_end - eng_comment;
if( G_LIKELY( locale ) )
{
int target_len = g_snprintf( target, 64, "<comment xml:lang=\"%s\">", locale);
buf = comment_end + 10;
len = (buf_end - buf);
if( G_LIKELY( ( comment = g_strstr_len( buf, len, target ) ) ) )
{
len -= target_len;
comment += target_len;
comment_end = g_strstr_len( comment, len, end_comment_tag ); /* find </comment> */
if( G_LIKELY( comment_end ) )
comment_len = (comment_end - comment);
else
comment = NULL;
}
}
if( G_LIKELY( comment ) )
return g_strndup( comment, comment_len );
return g_strndup( eng_comment, eng_comment_len );
}
static char* _mime_type_get_desc( const char* file_path, const char* locale )
{
int fd;
struct stat statbuf; // skip stat64
char *buffer, *_locale, *desc;
//char file_path[ 256 ]; //sfm to improve speed, file_path is passed
//g_snprintf( file_path, 256, "%s/mime/%s.xml", data_dir, type );
fd = open ( file_path, O_RDONLY, 0 );
if ( G_UNLIKELY( fd == -1 ) )
return NULL;
if( G_UNLIKELY( fstat ( fd, &statbuf ) == -1 ) )
{
close( fd );
return NULL;
}
#ifdef HAVE_MMAP
buffer = (char*)mmap( NULL, statbuf.st_size, PROT_READ, MAP_SHARED, fd, 0 );
#else
buffer = (char*)g_malloc( statbuf.st_size );
if( read( fd, buffer, statbuf.st_size ) == -1 )
{
g_free( buffer );
buffer = (char*)-1;
}
#endif
close( fd );
if ( G_UNLIKELY( buffer == (void*)-1 ) )
return NULL;
_locale = NULL;
if( ! locale )
{
const char* const * langs = g_get_language_names();
char* dot = strchr( langs[0], '.' );
if( dot )
locale = _locale = g_strndup( langs[0], (size_t)(dot - langs[0]) );
else
locale = langs[0];
}
desc = parse_xml_desc( buffer, statbuf.st_size, locale );
g_free( _locale );
#ifdef HAVE_MMAP
munmap ( buffer, statbuf.st_size );
#else
g_free( buffer );
#endif
return desc;
}
/*
* Get human-readable description of the mime-type
* If locale is NULL, current locale will be used.
* The returned string should be freed when no longer used.
*/
char* mime_type_get_desc( const char* type, const char* locale )
{
char* desc;
const gchar* const * dir;
char file_path[ 256 ];
int acc;
/* //sfm 0.7.7+ FIXED
* FIXME: According to specs on freedesktop.org, user_data_dir has
* higher priority than system_data_dirs, but in most cases, there was
* no file, or very few files in user_data_dir, so checking it first will
* result in many unnecessary open() system calls, yealding bad performance.
* Since the spec really sucks, we don't follow it here.
*/
/* FIXME: This path shouldn't be hard-coded. */
g_snprintf( file_path, 256, "%s/mime/%s.xml", g_get_user_data_dir(), type );
#if defined(HAVE_EUIDACCESS)
acc = euidaccess( file_path, F_OK );
#elif defined(HAVE_EACCESS)
acc = eaccess( file_path, F_OK );
#else
acc = 0;
#endif
if ( acc != -1 )
{
desc = _mime_type_get_desc( file_path, locale );
if ( desc )
return desc;
}
// look in system dirs
dir = g_get_system_data_dirs();
for( ; *dir; ++dir )
{
/* FIXME: This path shouldn't be hard-coded. */
g_snprintf( file_path, 256, "%s/mime/%s.xml", *dir, type );
#if defined(HAVE_EUIDACCESS)
acc = euidaccess( file_path, F_OK );
#elif defined(HAVE_EACCESS)
acc = eaccess( file_path, F_OK );
#else
acc = 0;
#endif
if ( acc != -1 )
{
desc = _mime_type_get_desc( file_path, locale );
if( G_LIKELY(desc) )
return desc;
}
}
return NULL;
}
void mime_type_finalize()
{
/*
if( G_LIKELY( table ) )
{
g_hash_table_destroy( table );
table = NULL;
}
*/
mime_cache_free_all();
}
#if 0
void test_parents(const char* type)
{
int i;
const char** parents = NULL;
const char** p;
for( i = 0; i < n_caches; ++i )
{
parents = mime_cache_lookup_parents( caches[i], type );
if( parents )
break;
}
if( parents )
for( p = parents; *p; ++p )
{
g_debug( "%s is parent of %s", *p, type );
}
else
g_debug( "no parent found" );
}
void test_alias( const char* type )
{
int i;
const char* alias = NULL;
for( i = 0; i < n_caches; ++i )
{
alias = mime_cache_lookup_alias( caches[i], type );
if( alias )
break;
}
g_debug("test:\nalias of %s is %s", type, alias );
}
#endif
void mime_type_init()
{
mime_cache_load_all();
// table = g_hash_table_new_full( g_str_hash, g_str_equal, g_free, (GDestroyNotify)mime_type_unref );
}
/* load all mime.cache files on the system,
* including /usr/share/mime/mime.cache,
* /usr/local/share/mime/mime.cache,
* and $HOME/.local/share/mime/mime.cache. */
void mime_cache_load_all()
{
const char* const * dirs;
int i;
const char filename[] = "/mime/mime.cache";
char* path;
dirs = g_get_system_data_dirs();
n_caches = g_strv_length( (char**)dirs ) + 1;
caches = (MimeCache**)g_slice_alloc( n_caches * sizeof(MimeCache*) );
path = g_build_filename( g_get_user_data_dir(), filename, NULL );
caches[0] = mime_cache_new( path );
g_free( path );
if( caches[0]->magic_max_extent > mime_cache_max_extent )
mime_cache_max_extent = caches[0]->magic_max_extent;
for( i = 1; i < n_caches; ++i )
{
path = g_build_filename( dirs[i - 1], filename, NULL );
caches[ i ] = mime_cache_new( path );
g_free( path );
if( caches[i]->magic_max_extent > mime_cache_max_extent )
mime_cache_max_extent = caches[i]->magic_max_extent;
}
mime_magic_buf = g_malloc( mime_cache_max_extent );
return ;
}
/* free all mime.cache files on the system */
void mime_cache_free_all()
{
mime_cache_foreach( (GFunc)mime_cache_free, NULL );
g_slice_free1( n_caches * sizeof(MimeCache*), caches );
n_caches = 0;
caches = NULL;
mime_cache_max_extent = 0;
g_free( mime_magic_buf );
mime_magic_buf = NULL;
}
/* Iterate through all mime caches */
void mime_cache_foreach( GFunc func, gpointer user_data )
{
int i;
for( i = 0; i < n_caches; ++i )
func( caches[i], user_data );
}
gboolean mime_cache_reload( MimeCache* cache )
{
int i;
gboolean ret = mime_cache_load( cache, cache->file_path );
/* recalculate max magic extent */
for( i = 0; i < n_caches; ++i )
{
if( caches[i]->magic_max_extent > mime_cache_max_extent )
mime_cache_max_extent = caches[i]->magic_max_extent;
}
G_LOCK( mime_magic_buf );
mime_magic_buf = g_realloc( mime_magic_buf, mime_cache_max_extent );
G_UNLOCK( mime_magic_buf );
return ret;
}
gboolean mime_type_is_data_plain_text( const char* data, int len )
{
int i;
if ( G_LIKELY( len >= 0 && data ) )
{
for ( i = 0; i < len; ++i )
{
if ( data[ i ] == '\0' )
return FALSE;
}
return TRUE;
}
return FALSE;
}
gboolean mime_type_is_text_file( const char *file_path, const char* mime_type )
{
int file;
int rlen;
gboolean ret = FALSE;
if( mime_type )
{
if( mime_type_is_subclass( mime_type, XDG_MIME_TYPE_PLAIN_TEXT ) )
return TRUE;
if( ! g_str_has_prefix( mime_type, "text/" ) && ! g_str_has_prefix( mime_type, "application/" ) )
return FALSE;
}
if( !file_path )
return FALSE;
file = open ( file_path, O_RDONLY );
if ( file != -1 )
{
struct stat64 statbuf;
if( fstat64( file, &statbuf ) != -1 )
{
if( S_ISREG( statbuf.st_mode ) )
{
#ifdef HAVE_MMAP
char* data;
rlen = statbuf.st_size < TEXT_MAX_EXTENT ? statbuf.st_size : TEXT_MAX_EXTENT;
data = (char*) mmap( NULL, rlen, PROT_READ, MAP_SHARED, file, 0 );
ret = mime_type_is_data_plain_text( data, rlen );
munmap ( (char*)data, rlen );
#else
unsigned char data[ TEXT_MAX_EXTENT ];
rlen = read ( file, data, sizeof( data ) );
ret = mime_type_is_data_plain_text( (char*) data, rlen );
#endif
}
}
close ( file );
}
return ret;
}
gboolean mime_type_is_executable_file( const char *file_path, const char* mime_type )
{
if ( !mime_type )
{
mime_type = mime_type_get_by_file( file_path, NULL, NULL );
}
/*
* Only executable types can be executale.
* Since some common types, such as application/x-shellscript,
* are not in mime database, we have to add them ourselves.
*/
if ( mime_type != XDG_MIME_TYPE_UNKNOWN &&
(mime_type_is_subclass( mime_type, XDG_MIME_TYPE_EXECUTABLE ) ||
mime_type_is_subclass( mime_type, "application/x-shellscript" ) ) )
{
if ( file_path )
{
if ( ! g_file_test( file_path, G_FILE_TEST_IS_EXECUTABLE ) )
return FALSE;
}
return TRUE;
}
return FALSE;
}
/* Check if the specified mime_type is the subclass of the specified parent type */
gboolean mime_type_is_subclass( const char* type, const char* parent )
{
int i;
const char** parents = NULL;
const char** p;
/* special case, the type specified is identical to the parent type. */
if( G_UNLIKELY( 0 == strcmp(type, parent) ) )
return TRUE;
for( i = 0; i < n_caches; ++i )
{
parents = mime_cache_lookup_parents( caches[i], type );
if( parents )
{
for( p = parents; *p; ++p )
{
if( 0 == strcmp( parent, *p ) )
return TRUE;
}
}
}
return FALSE;
}
/*
* Get all parent type of this mime_type
* The returned string array should be freed with g_strfreev().
*/
char** mime_type_get_parents( const char* type )
{
int i;
const char** parents = NULL;
const char** p;
GArray* ret = g_array_sized_new( TRUE, TRUE, sizeof(char*), 5 );
for( i = 0; i < n_caches; ++i )
{
parents = mime_cache_lookup_parents( caches[i], type );
if( parents )
{
for( p = parents; *p; ++p )
{
char* parent = g_strdup( *p );
g_array_append_val( ret, parent );
}
}
}
return (char**)g_array_free( ret, (0 == ret->len) );
}
/*
* Get all alias types of this mime_type
* The returned string array should be freed with g_strfreev().
*/
char** mime_type_get_alias( const char* type )
{
int i;
const char** alias = NULL;
const char** p;
GArray* ret = g_array_sized_new( TRUE, TRUE, sizeof(char*), 5 );
for( i = 0; i < n_caches; ++i )
{
alias = (const char **) mime_cache_lookup_alias( caches[i], type );
if( alias )
{
for( p = alias; *p; ++p )
{
char* type = g_strdup( *p );
g_array_append_val( ret, type );
}
}
}
return (char**)g_array_free( ret, (0 == ret->len) );
}
/*
* Get mime caches
*/
MimeCache** mime_type_get_caches( int* n )
{
*n = n_caches;
return caches;
}
|
196 | ./sleepd/src/main.c | /* @@@LICENSE
*
* Copyright (c) 2011-2012 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* LICENSE@@@ */
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <glib.h>
#include <pthread.h>
#include <stdbool.h>
#include <getopt.h>
#include <stdlib.h>
#include <cjson/json.h>
#include <luna-service2/lunaservice.h>
#include "init.h"
#include "logging.h"
#include "main.h"
static GMainLoop *mainloop = NULL;
static LSHandle* private_sh = NULL;
static LSPalmService *psh = NULL;
bool ChargerConnected(LSHandle *sh,LSMessage *message, void *user_data); // defined in machine.c
bool ChargerStatus(LSHandle *sh,LSMessage *message, void *user_data); // defined in machine.c
#define LOG_DOMAIN "SLEEPD-INIT: "
void
term_handler(int signal)
{
g_main_loop_quit(mainloop);
}
GMainContext *
GetMainLoopContext(void)
{
return g_main_loop_get_context(mainloop);
}
LSHandle *
GetLunaServiceHandle(void)
{
return private_sh;
}
LSPalmService *
GetPalmService(void)
{
return psh;
}
static nyx_device_handle_t nyxSystem = NULL;
nyx_device_handle_t
GetNyxSystemDevice(void)
{
return nyxSystem;
}
int
main(int argc, char **argv)
{
bool retVal;
// FIXME integrate this into TheOneInit()
LOGInit();
LOGSetHandler(LOGSyslog);
signal(SIGTERM, term_handler);
signal(SIGINT, term_handler);
if (!g_thread_supported ()) g_thread_init (NULL);
mainloop = g_main_loop_new(NULL, FALSE);
/**
* initialize the lunaservice and we want it before all the init
* stuff happening.
*/
LSError lserror;
LSErrorInit(&lserror);
retVal = LSRegisterPalmService("com.palm.sleep", &psh, &lserror);
if (!retVal)
{
goto ls_error;
}
retVal = LSGmainAttachPalmService(psh, mainloop, &lserror);
if (!retVal)
{
goto ls_error;
}
private_sh = LSPalmServiceGetPrivateConnection(psh);
retVal = LSCall(private_sh,"luna://com.palm.lunabus/signal/addmatch","{\"category\":\"/com/palm/power\","
"\"method\":\"USBDockStatus\"}", ChargerStatus, NULL, NULL, &lserror);
if (!retVal) {
SLEEPDLOG(LOG_CRIT,"Error in registering for luna-signal \"chargerStatus\"");
goto ls_error;
}
int ret = nyx_device_open(NYX_DEVICE_SYSTEM, "Main", &nyxSystem);
if(ret != NYX_ERROR_NONE)
{
SLEEPDLOG(LOG_CRIT,"Sleepd: Unable to open the nyx device system");
abort();
}
TheOneInit();
LSCall(private_sh,"luna://com.palm.power/com/palm/power/chargerStatusQuery","{}",ChargerStatus,NULL,NULL,&lserror);
SLEEPDLOG(LOG_INFO,"Sleepd daemon started\n");
g_main_loop_run(mainloop);
end:
g_main_loop_unref(mainloop);
return 0;
ls_error:
SLEEPDLOG(LOG_CRIT,"Fatal - Could not initialize sleepd. Is LunaService Down?. %s",
lserror.message);
LSErrorFree(&lserror);
goto end;
}
|
197 | ./sleepd/src/pwrevents/suspend_ipc.c | /* @@@LICENSE
*
* Copyright (c) 2011-2012 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* LICENSE@@@ */
/**
* @file suspend_ipc.c
*
* @brief Power Events Luna calls.
*
*/
#include <syslog.h>
#include <cjson/json.h>
#include <luna-service2/lunaservice.h>
#include "wait.h"
#include "init.h"
#include "main.h"
#include "debug.h"
#include "client.h"
#include "shutdown.h"
#include "suspend.h"
#include "activity.h"
#include "logging.h"
#include "lunaservice_utils.h"
#include "config.h"
#define LOG_DOMAIN "PWREVENT-SUSPEND: "
extern WaitObj gWaitSuspendResponse;
extern WaitObj gWaitPrepareSuspend;
extern bool visual_leds_suspend;
/**
* @defgroup SuspendIPC Luna methods & signals
* @ingroup SuspendLogic
* @brief Various luna methods & signals to support suspend/resume logic in sleepd, like registering clients
* for suspend request or prepare suspend signals, start or end activity.
*
*/
/**
* @addtogroup SuspendIPC
* @{
*/
/**
* @brief Unregister the client by its name. This is required for requests redirected from powerd, since the
* unique token generated from message will be different for such requests.
*
* @param sh
* @param message
* @param ctx
*/
bool
clientCancelByName(LSHandle *sh, LSMessage *message, void *ctx)
{
struct json_object *object = json_tokener_parse(LSMessageGetPayload(message));
if (is_error(object)) goto out;
char *clientName = json_object_get_string(
json_object_object_get(object, "clientName"));
PwrEventClientUnregisterByName(clientName);
shutdown_client_cancel_registration_by_name(clientName);
out:
return true;
}
/**
* @brief Unregister a client by its id generated from the message. This will work for direct requests.
*
* @param sh
* @param message
* @param ctx
*/
bool
clientCancel(LSHandle *sh, LSMessage *msg, void *ctx)
{
const char *clientId = LSMessageGetUniqueToken(msg);
PwrEventClientUnregister(clientId);
shutdown_client_cancel_registration(clientId);
return true;
}
/**
* @brief Start an activity with its "id" and "duration" passed in "message"
*
* @param sh
* @param message
* @param user_data
*/
bool
activityStartCallback(LSHandle *sh, LSMessage *message, void *user_data)
{
LSError lserror;
LSErrorInit(&lserror);
const char *payload = LSMessageGetPayload(message);
struct json_object *object = json_tokener_parse(payload);
if (is_error(object)) goto malformed_json;
const char *activity_id = json_object_get_string(
json_object_object_get(object, "id"));
int duration_ms = json_object_get_int(
json_object_object_get(object, "duration_ms"));
if (!activity_id || !strlen(activity_id) || duration_ms <=0) goto malformed_json;
bool ret = PwrEventActivityStart(activity_id, duration_ms);
if (!ret)
{
LSError lserror;
LSErrorInit(&lserror);
bool retVal = LSMessageReply(sh, message,
"{\"returnValue\":false, \"errorText\":\"Activities Frozen\"}", &lserror);
if (!retVal)
{
LSErrorPrint(&lserror, stderr);
LSErrorFree(&lserror);
}
}
else
{
LSMessageReplySuccess(sh, message);
}
goto end;
malformed_json:
LSMessageReplyErrorBadJSON(sh, message);
goto end;
end:
if (!is_error(object)) json_object_put(object);
return true;
}
/**
* @brief End the activity with the "id" specified in "message"
*
* @param sh
* @param message
* @param user_data
*/
bool
activityEndCallback(LSHandle *sh, LSMessage *message, void *user_data)
{
LSError lserror;
LSErrorInit(&lserror);
const char *payload = LSMessageGetPayload(message);
struct json_object *object = json_tokener_parse(payload);
if (is_error(object)) goto malformed_json;
const char *activity_id = json_object_get_string(
json_object_object_get(object, "id"));
if (!activity_id || !strlen(activity_id)) goto malformed_json;
PwrEventActivityStop(activity_id);
LSMessageReplySuccess(sh, message);
goto end;
malformed_json:
LSMessageReplyErrorBadJSON(sh, message);
goto end;
end:
if (!is_error(object)) json_object_put(object);
return true;
}
/**
* @brief Register a new client with the given name.
*
* @param sh
* @param message
* @param data
*/
bool
identifyCallback(LSHandle *sh, LSMessage *message, void *data)
{
bool retVal;
LSError lserror;
LSErrorInit(&lserror);
const char *payload = LSMessageGetPayload(message);
struct json_object *object = json_tokener_parse(payload);
if (is_error(object)) goto malformed_json;
const char *applicationName = LSMessageGetApplicationID(message);
const char *clientId = LSMessageGetUniqueToken(message);
bool subscribe = json_object_get_boolean(
json_object_object_get(object, "subscribe"));
const char *clientName = json_object_get_string(
json_object_object_get(object, "clientName"));
if (!subscribe || !clientName) goto invalid_syntax;
if (!LSSubscriptionAdd(sh, "PwrEventsClients", message, &lserror))
{
goto lserror;
}
if (!PwrEventClientRegister(clientId)) goto error;
struct PwrEventClientInfo *info = PwrEventClientLookup(clientId);
if (!info)
{
goto error;
}
info->clientName = g_strdup(clientName);
info->clientId = g_strdup(clientId);
info->applicationName = g_strdup(applicationName);
char *reply = g_strdup_printf(
"{\"subscribed\":true,\"clientId\":\"%s\"}", clientId);
g_debug("Pwrevents received identify, reply with %s", reply);
retVal = LSMessageReply(sh, message, reply, &lserror);
g_free(reply);
if (!retVal)
{
goto lserror;
}
goto end;
lserror:
LSErrorPrint(&lserror, stderr);
LSErrorFree(&lserror);
goto end;
error:
LSMessageReplyErrorUnknown(sh, message);
goto end;
invalid_syntax:
LSMessageReplyErrorInvalidParams(sh, message);
goto end;
malformed_json:
LSMessageReplyErrorBadJSON(sh, message);
goto end;
end:
if (!is_error(object)) json_object_put(object);
return true;
}
/**
* @brief Force the device to go into suspend even with charger connected or any activity is still active.
* (Used for testing purposes).
*
* @param sh
* @param message
* @param user_data
*/
bool
forceSuspendCallback(LSHandle *sh, LSMessage *message, void *user_data)
{
TRACE("\tReceived force suspend\n");
TriggerSuspend("forced suspend", kPowerEventForceSuspend);
LSMessageReplySuccess(sh, message);
return true;
}
/**
* @brief Schedule the IdleCheck thread to check if the device can suspend
* (Used for testing purposes).
*
* @param sh
* @param message
* @param user_data
*/
bool
TESTSuspendCallback(LSHandle *sh, LSMessage *message, void *user_data)
{
TRACE("\tReceived TESTSuspend\n");
ScheduleIdleCheck(100, false);
LSMessageReplySuccess(sh, message);
return true;
}
/**
* @brief Broadcast the suspend request signal to all registered clients.
*/
int
SendSuspendRequest(const char *message)
{
bool retVal;
LSError lserror;
LSErrorInit(&lserror);
retVal = LSSignalSend(GetLunaServiceHandle(),
"luna://com.palm.sleep/com/palm/power/suspendRequest",
"{}", &lserror);
if (!retVal)
{
LSErrorPrint(&lserror, stderr);
LSErrorFree(&lserror);
}
return retVal;
}
/**
* @brief Broadcast the prepare suspend signal to all registered clients.
*/
int
SendPrepareSuspend(const char *message)
{
bool retVal;
LSError lserror;
LSErrorInit(&lserror);
retVal = LSSignalSend(GetLunaServiceHandle(),
"luna://com.palm.sleep/com/palm/power/prepareSuspend",
"{}", &lserror);
if (!retVal)
{
LSErrorPrint(&lserror, stderr);
LSErrorFree(&lserror);
}
return retVal;
}
/**
* @brief Broadcast the "resume" signal when the device wakes up from sleep, or the
* suspend action is aborted on the system.
*/
int
SendResume(int resumetype, char *message)
{
bool retVal;
LSError lserror;
LSErrorInit(&lserror);
SLEEPDLOG(LOG_INFO, "%s: sending \"resume\" because %s", __func__, message);
char *payload = g_strdup_printf(
"{\"resumetype\":%d}", resumetype);
retVal = LSSignalSend(GetLunaServiceHandle(),
"luna://com.palm.sleep/com/palm/power/resume",
payload, &lserror);
if (!retVal)
{
LSErrorPrint(&lserror, stderr);
LSErrorFree(&lserror);
}
g_free(payload);
return retVal;
}
/**
* @brief Broadcast the "suspended" signal when the system is just about to go to sleep.
*/
int
SendSuspended(const char *message)
{
bool retVal;
LSError lserror;
LSErrorInit(&lserror);
SLEEPDLOG(LOG_INFO, "%s: sending \"suspended\" because %s", __func__, message);
retVal = LSSignalSend(GetLunaServiceHandle(),
"luna://com.palm.sleep/com/palm/power/suspended",
"{}", &lserror);
if (!retVal)
{
LSErrorPrint(&lserror, stderr);
LSErrorFree(&lserror);
}
return retVal;
}
/**
* @brief Register a client (already registered with "identify" call) for "suspend request" signal.
* This will add to the counter "sNumSuspendRequest" before every polling to make a decision to proceed
* with the suspend action or postpone it later.
*
* @param sh
* @param message
* @param data
*/
bool
suspendRequestRegister(LSHandle *sh, LSMessage *message, void *data)
{
bool reg;
g_debug("PwrEvent %s %s", __FUNCTION__, LSMessageGetPayload(message));
struct json_object *object = json_tokener_parse(
LSMessageGetPayload(message));
if (is_error(object)) goto malformed_json;
const char *clientId = json_object_get_string(
json_object_object_get(object, "clientId"));
if (!clientId) goto invalid_syntax;
struct json_object *json_reg =
json_object_object_get(object, "register");
if (!json_reg) goto invalid_syntax;
reg = json_object_get_boolean(json_reg);
g_debug("PwrEvent received %s ---%s from %s",
LSMessageGetPayload(message),
__FUNCTION__, clientId);
PwrEventClientSuspendRequestRegister(clientId, reg);
goto end;
invalid_syntax:
LSMessageReplyErrorInvalidParams(sh, message);
goto end;
malformed_json:
LSMessageReplyErrorBadJSON(sh, message);
goto end;
end:
if (!is_error(object)) json_object_put(object);
return true;
}
/**
* @brief Add the client's count in the total number of ACKs received for the "suspend request" signal.
*
* @param sh
* @param message
* @param data
*/
bool
suspendRequestAck(LSHandle *sh, LSMessage *message, void *data)
{
bool ack;
g_debug("PwrEvent %s %s", __FUNCTION__, LSMessageGetPayload(message));
struct json_object *object = json_tokener_parse(
LSMessageGetPayload(message));
if (is_error(object)) goto malformed_json;
const char *clientId = json_object_get_string(
json_object_object_get(object, "clientId"));
struct json_object *json_ack =
json_object_object_get(object, "ack");
if (!json_ack) goto invalid_syntax;
ack = json_object_get_boolean(json_ack);
struct PwrEventClientInfo *clientInfo = PwrEventClientLookup(clientId);
#if 0
if (gPowerConfig.debug)
{
SLEEPDLOG(LOG_WARNING,
"PWREVENT-SUSPEND_REQUEST_%s from \"%s\" (%s)",
ack ? "ACK" : "NACK",
clientInfo && clientInfo->clientName ? clientInfo->clientName : "",
clientId);
}
#endif
if (!ack)
{
PwrEventClientSuspendRequestNACKIncr(clientInfo);
}
// returns true when all clients have acked.
if (PwrEventVoteSuspendRequest(clientId, ack))
{
WaitObjectSignal(&gWaitSuspendResponse);
}
goto end;
malformed_json:
LSMessageReplyErrorBadJSON(sh, message);
goto end;
invalid_syntax:
LSMessageReplyErrorInvalidParams(sh, message);
goto end;
end:
if (!is_error(object)) json_object_put(object);
return true;
}
/**
* @brief Register a client (already registered with "identify" call) for "prepare suspend" signal.
* This will add to the counter "sNumPrepareSuspend" before every polling to make a decision to proceed
* with the suspend action or postpone it later.
*
* @param sh
* @param message
* @param data
*/
bool
prepareSuspendRegister(LSHandle *sh, LSMessage *message, void *data)
{
bool reg;
struct json_object *object = json_tokener_parse(
LSMessageGetPayload(message));
if (is_error(object)) goto malformed_json;
const char *clientId = json_object_get_string(
json_object_object_get(object, "clientId"));
if (!clientId) goto invalid_syntax;
struct json_object *json_reg =
json_object_object_get(object, "register");
if (!json_reg) goto invalid_syntax;
reg = json_object_get_boolean(json_reg);
g_debug("PwrEvent %s reg=%d from %s", __FUNCTION__, reg, clientId);
PwrEventClientPrepareSuspendRegister(clientId, reg);
goto end;
invalid_syntax:
LSMessageReplyErrorInvalidParams(sh, message);
goto end;
malformed_json:
LSMessageReplyErrorBadJSON(sh, message);
goto end;
end:
if (!is_error(object)) json_object_put(object);
return true;
}
/**
* @brief Add the client's count in the total number of ACKs received for the "suspend request" signal.
*
* @param sh
* @param message
* @param data
*/
bool
prepareSuspendAck(LSHandle *sh, LSMessage *message, void *data)
{
bool ack;
struct json_object *object = json_tokener_parse(
LSMessageGetPayload(message));
if (is_error(object)) goto malformed_json;
const char *clientId = json_object_get_string(
json_object_object_get(object, "clientId"));
struct json_object *json_ack =
json_object_object_get(object, "ack");
if (!json_ack) goto invalid_syntax;
ack = json_object_get_boolean(json_ack);
struct PwrEventClientInfo *clientInfo = PwrEventClientLookup(clientId);
#if 0
if (gPowerConfig.debug)
{
SLEEPDLOG(LOG_WARNING,
"PWREVENT-PREPARE_SUSPEND_%s from \"%s\" (%s)",
ack ? "ACK" : "NACK",
clientInfo && clientInfo->clientName ? clientInfo->clientName : "",
clientId);
}
#endif
if (!ack)
{
PwrEventClientPrepareSuspendNACKIncr(clientInfo);
}
// returns true when all clients have acked.
if (PwrEventVotePrepareSuspend(clientId, ack))
{
WaitObjectSignal(&gWaitPrepareSuspend);
}
goto end;
invalid_syntax:
LSMessageReplyErrorInvalidParams(sh, message);
goto end;
malformed_json:
LSMessageReplyErrorBadJSON(sh, message);
goto end;
end:
if (!is_error(object)) json_object_put(object);
return true;
}
/**
* @brief Turn on/off visual leds suspend via luna-service.
*
* @param sh
* @param message
* @param data
*
* @retval
*/
bool
visualLedSuspendCallback(LSHandle *sh, LSMessage *message, void *data)
{
struct json_object *object = json_tokener_parse(
LSMessageGetPayload(message));
if (is_error(object)) goto malformed_json;
struct json_object *json_on = json_object_object_get(object, "on");
if (!json_on) goto invalid_syntax;
bool on = json_object_get_boolean(json_on);
gSleepConfig.visual_leds_suspend = on;
goto end;
invalid_syntax:
LSMessageReplyErrorInvalidParams(sh, message);
goto end;
malformed_json:
LSMessageReplyErrorBadJSON(sh, message);
goto end;
end:
if (!is_error(object)) json_object_put(object);
return true;
}
void
SuspendIPCInit(void)
{
bool retVal;
LSError lserror;
LSErrorInit(&lserror);
retVal = LSSubscriptionSetCancelFunction(GetLunaServiceHandle(),
clientCancel, NULL, &lserror);
if (!retVal)
{
SLEEPDLOG(LOG_CRIT,"Error in setting cancel function");
goto ls_error;
}
ls_error:
LSErrorPrint(&lserror, stderr);
LSErrorFree(&lserror);
}
LSMethod com_palm_suspend_methods[] = {
/* suspend methods*/
{ "suspendRequestRegister", suspendRequestRegister },
{ "prepareSuspendRegister", prepareSuspendRegister },
{ "suspendRequestAck", suspendRequestAck },
{ "prepareSuspendAck", prepareSuspendAck },
{ "forceSuspend", forceSuspendCallback },
{ "identify", identifyCallback },
{ "clientCancelByName", clientCancelByName },
{ "visualLedSuspend", visualLedSuspendCallback },
{ "TESTSuspend", TESTSuspendCallback },
{ },
};
LSMethod com_palm_suspend_public_methods[] = {
{ "activityStart", activityStartCallback },
{ "activityEnd", activityEndCallback },
};
LSSignal com_palm_suspend_signals[] = {
/* Suspend signals */
{ "suspendRequest" },
{ "prepareSuspend" },
{ "suspended" },
{ "resume" },
{ },
};
int com_palm_suspend_lunabus_init(void)
{
LSError lserror;
LSErrorInit(&lserror);
if (!LSPalmServiceRegisterCategory(GetPalmService(), "/com/palm/power",
com_palm_suspend_public_methods, com_palm_suspend_methods, com_palm_suspend_signals,
NULL, &lserror))
{
goto error;
}
return 0;
error:
LSErrorPrint(&lserror, stderr);
LSErrorFree(&lserror);
return -1;
}
INIT_FUNC(INIT_FUNC_END, com_palm_suspend_lunabus_init);
/* @} END OF SuspendIPC */
|
198 | ./sleepd/src/pwrevents/activity.c | /* @@@LICENSE
*
* Copyright (c) 2011-2012 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* LICENSE@@@ */
/**
* @file activity.c
*
* @brief This file contains functions to manage activities, which are entities that can be
* registered with sleepd to prevent the system from suspending for a certain time duration.
*
*/
#include <glib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <luna-service2/lunaservice.h>
#include "suspend.h"
#include "main.h"
#include "clock.h"
#include "logging.h"
#include "activity.h"
#include "init.h"
//#include "metrics.h"
//#define CONFIG_ACTIVITY_TIMEOUT_RDX_REPORT
// Max duration at 15 minutes.
#define ACTIVITY_MAX_DURATION_MS (15*60*1000)
#define ACTIVITY_HIGH_DURATION_MS (10*60*1000)
#define LOG_DOMAIN "PWREVENT-ACTIVITY: "
/**
* @defgroup PowerEvents Power Events
* @ingroup Sleepd
* @brief Power events are all the events that affect system power.
*/
/**
* @defgroup PowerActivities Power Activities
* @ingroup PowerEvents
* @brief Duration of time to prevent the system from sleeping
*/
/**
* @addtogroup PowerActivities
* @{
*/
/**
* @brief Structure for maintaining all registered activities.
*/
typedef struct {
struct timespec start_time;
struct timespec end_time;
int duration_ms;
char *activity_id;
} Activity;
GQueue *activity_roster = NULL;
pthread_mutex_t activity_mutex = PTHREAD_MUTEX_INITIALIZER;
bool gFrozen = false;
/**
* @brief Initialize the activity queue
*/
static int
_activity_init(void)
{
if (!activity_roster)
{
activity_roster = g_queue_new();
}
return 0;
}
/**
* @brief Add a new activity to the global activity queue (activity_roster)
*
* @param activity_id Passed by the caller
* @param duration_ms Duration for which the system cannot suspend with this activity
*
* @retval The new activity added
*/
static Activity *
_activity_new(const char *activity_id, int duration_ms)
{
if (duration_ms >= ACTIVITY_MAX_DURATION_MS)
{
duration_ms = ACTIVITY_MAX_DURATION_MS;
}
Activity *activity = g_new0(Activity, 1);
activity->activity_id = g_strdup(activity_id);
activity->duration_ms = duration_ms;
// end += duration
ClockGetTime(&activity->start_time);
activity->end_time.tv_sec = activity->start_time.tv_sec;
activity->end_time.tv_nsec = activity->start_time.tv_nsec;
ClockAccumMs(&activity->end_time, activity->duration_ms);
return activity;
}
/**
* @brief Free the activity specified.
*
* @param activity The activity to be freed
*
* @retval
*/
static void
_activity_free(Activity *activity)
{
if (activity)
{
g_free(activity->activity_id);
g_free(activity);
}
}
/**
* @brief Compare the expiry time of two activities
*
* @param a
* @param b
*
* @retval 1 if expiry time of a is greater than b
* 0 otherwise
*/
static int
_activity_compare(Activity *a, Activity *b)
{
if (ClockTimeIsGreater(&a->end_time, &b->end_time))
{
return 1;
}
else
{
return -1;
}
}
/**
* @brief Count the number of activities beyond the timespec passed as argument
*
* @param from Start counting activities from this time
*
* @retval The number of activities beyond "from"
*/
static int
_activity_count(struct timespec *from)
{
int count = 0;
pthread_mutex_lock(&activity_mutex);
GList *iter;
for (iter = activity_roster->head; iter != NULL; iter = iter->next)
{
Activity *a = (Activity*)iter->data;
// now > activity.end_time
if (ClockTimeIsGreater(from, &a->end_time))
{
continue;
}
count++;
}
pthread_mutex_unlock(&activity_mutex);
return count;
}
/**
* @brief Insert an activity into sorted list.
*
* @param activity
* @return false if the activity cannot be created (if activities are frozen).
*/
static bool
_activity_insert(const char *activity_id, int duration_ms)
{
bool ret = true;
pthread_mutex_lock(&activity_mutex);
if (gFrozen)
{
ret = false;
goto end;
}
Activity *activity = _activity_new(activity_id, duration_ms);
g_queue_insert_sorted(activity_roster, activity,
(GCompareDataFunc)_activity_compare, NULL);
end:
pthread_mutex_unlock(&activity_mutex);
return ret;
}
/**
* @brief Delete the activity from the global activity queue.
*
* @param activity_id The activity which needs to be deleted.
*
* @retval The activity that was deleted.
*/
static Activity *
_activity_remove_id(const char *activity_id)
{
Activity *ret_activity = NULL;
pthread_mutex_lock(&activity_mutex);
GList *iter;
for (iter = activity_roster->head; iter != NULL; iter = iter->next)
{
Activity *a = (Activity*)iter->data;
if (strcmp(a->activity_id, activity_id) == 0)
{
ret_activity = a;
g_queue_delete_link(activity_roster, iter);
break;
}
}
pthread_mutex_unlock(&activity_mutex);
return ret_activity;
}
/**
* @brief Check whether the activity has expired
*
* @param a Activity whose expiry is to be checked
* @param now Current time
*
* @retval True if the activity expired
*/
static bool
_activity_expired(Activity *a, struct timespec *now)
{
// end > now
return ClockTimeIsGreater(now, &a->end_time);
}
/**
* @brief Retrieve the first activiy (from beginning or from end) that hasn't expired (without
* locking the activity mutex)
*
* @param now Current time
* @param getmax If True start from the end of acitivty queue, else start from the head
*
* @retval Activity.
*/
static Activity *
_activity_obtain_unlocked(struct timespec *now, bool getmax)
{
Activity *ret_activity = NULL;
GList *iter;
if (getmax)
iter = activity_roster->tail;
else
iter = activity_roster->head;
while (iter != NULL)
{
Activity *a = (Activity*)iter->data;
// return first activity that is not expired.
if (!_activity_expired(a, now))
{
ret_activity = a;
goto end;
}
if (getmax)
iter = iter->prev;
else
iter = iter->next;
}
end:
return ret_activity;
}
/**
* @brief Get the activity which will expire first (without
* locking the activity mutex)
*
* @param now
*
* @retval Activity
*/
static Activity *
_activity_obtain_min_unlocked(struct timespec *now)
{
return _activity_obtain_unlocked(now, false);
}
/**
* @brief Get the activity which will expire last (without
* locking the activity mutex)
*
* @param now
*
* @retval Activity
*/
static Activity *
_activity_obtain_max_unlocked(struct timespec *now)
{
return _activity_obtain_unlocked(now, true);
}
/**
* @brief Get the first activity expiring by locking activity_mutex.
*
* @param now
*
* @retval Activity
*/
static Activity *
_activity_obtain_min(struct timespec *now)
{
Activity *ret_activity = NULL;
pthread_mutex_lock(&activity_mutex);
ret_activity = _activity_obtain_min_unlocked(now);
pthread_mutex_unlock(&activity_mutex);
return ret_activity;
}
/**
* @brief Get the last activity expiring by locking activity_mutex.
*
* @param now
*
* @retval Activity
*/
static Activity *
_activity_obtain_max(struct timespec *now)
{
Activity *max_activity = NULL;
pthread_mutex_lock(&activity_mutex);
max_activity = _activity_obtain_max_unlocked(now);
pthread_mutex_unlock(&activity_mutex);
return max_activity;
}
/**
* @brief Print the details of all the activities starting from a specified time
*
* @param from Activities starting from this time stamp
* @param now Current time
*
* @retval
*/
static void
_activity_print(struct timespec *from, struct timespec *now)
{
struct timespec diff;
int diff_ms;
pthread_mutex_lock(&activity_mutex);
GList *iter;
for (iter = activity_roster->head; iter != NULL; iter = iter->next)
{
Activity *a = (Activity*)iter->data;
// now > activity.end_time
if (ClockTimeIsGreater(from, &a->end_time))
{
continue;
}
// end_time - now
ClockDiff(&diff, &a->end_time, now);
diff_ms = diff.tv_sec * 1000 + diff.tv_nsec / 1000000;
SLEEPDLOG(LOG_INFO, "(%s) for %d ms, expiry in %d ms",
a->activity_id, a->duration_ms,
diff_ms);
}
pthread_mutex_unlock(&activity_mutex);
}
/**
* @brief Free the memory for an activity.
*
* @param Activity
*/
static void
_activity_stop_activity(Activity *a)
{
if (!a) return;
_activity_free(a);
}
/**
* @brief Stop and free an activity.
*
* @param activity_id
*/
static void
_activity_stop(const char *activity_id)
{
Activity *a = _activity_remove_id(activity_id);
if (!a) { return; }
_activity_stop_activity(a);
}
/**
* @brief Starts an activity.
*
* @param activity_id
* @param duration_ms
*/
static bool
_activity_start(const char * activity_id, int duration_ms)
{
/* replace exising *activity_id' */
_activity_stop(activity_id);
return _activity_insert(activity_id, duration_ms);
}
/**
* @brief Start an activity by the name of 'activity_id'.
*
* @param activity_id Should be in format com.domain.reverse-serial.
* @param duration_ms
*
* @return false if the activity could not be created... (activities may be frozen).
*/
bool
PwrEventActivityStart(const char *activity_id, int duration_ms)
{
bool retVal;
retVal = _activity_start(activity_id, duration_ms);
SLEEPDLOG(LOG_INFO, "%s: (%s) for %dms => %s",
__FUNCTION__, activity_id, duration_ms, retVal ? "true" : "false");
if (retVal)
{
/*
Force IdleCheck to run in case this activity is the same as
the current "long pole" activity but with a shorter life.
*/
ScheduleIdleCheck(0, false);
}
return retVal;
}
/**
* @brief Stop an activity
*
* @param activity_id of the activity than needs to be stopped
*
* @param activity_id
*/
void
PwrEventActivityStop(const char *activity_id)
{
SLEEPDLOG(LOG_INFO, "%s: (%s)", __FUNCTION__, activity_id);
_activity_stop(activity_id);
ScheduleIdleCheck(0, false);
}
/**
* @brief Remove all expired activities...
* This assumes the list is sorted.
*
* @param now
*/
void
PwrEventActivityRemoveExpired(struct timespec *now)
{
pthread_mutex_lock(&activity_mutex);
GList *iter;
for (iter = activity_roster->head; iter != NULL; )
{
Activity *a = (Activity*)iter->data;
// remove expired
if (_activity_expired(a, now))
{
GList *current_iter = iter;
iter = iter->next;
if (a->duration_ms >= ACTIVITY_HIGH_DURATION_MS)
{
LSError lserror;
LSErrorInit(&lserror);
SLEEPDLOG(LOG_WARNING,
"%s Long activity %s of duration %d ms expired... sending RDX report.",
__FUNCTION__,
a->activity_id, a->duration_ms);
}
_activity_stop_activity(a);
g_queue_delete_link(activity_roster, current_iter);
}
else
{
break;
}
}
pthread_mutex_unlock(&activity_mutex);
}
/*
* @brief Count the number of activities from "from"
*
* @param from
*
* @retval Number of activities
*
*/
int
PwrEventActivityCount(struct timespec *from)
{
return _activity_count(from);
}
/**
* @brief Prints the activities active in range from
* time 'start' to now.
*
* @param from
*/
void
PwrEventActivityPrintFrom(struct timespec *start)
{
struct timespec now;
ClockGetTime(&now);
_activity_print(start, &now);
}
/*
* @brief Print all the pending activities in the system
*/
void
PwrEventActivityPrint(void)
{
struct timespec now;
ClockGetTime(&now);
_activity_print(&now, &now);
}
/**
* @brief Tells us if there are any activities that prevent suspend.
*
* @param now
*
* @retval
*/
bool
PwrEventActivityCanSleep(struct timespec *now)
{
Activity *a = _activity_obtain_min(now);
return NULL == a;
}
/**
* @brief Returns the max duration for which the system cannot suspend due to an activity
*
* @param now
*
* @retval Duration
*
*/
long
PwrEventActivityGetMaxDuration(struct timespec *now)
{
Activity *a = _activity_obtain_max(now);
if (!a) return 0;
struct timespec diff;
ClockDiff(&diff, &a->end_time, now);
return ClockGetMs(&diff);
}
/*
* @brief Stop any new activity.
* Called when the system is about to suspend.
*
* @param now
*/
bool
PwrEventFreezeActivities(struct timespec *now)
{
pthread_mutex_lock(&activity_mutex);
if (_activity_obtain_min_unlocked(now) != NULL)
{
pthread_mutex_unlock(&activity_mutex);
return false;
}
gFrozen = true;
return true;
}
/**
* @brief Again allow creation og new activities
* Called when the system resumes
*/
void
PwrEventThawActivities(void)
{
gFrozen = false;
pthread_mutex_unlock(&activity_mutex);
}
INIT_FUNC(INIT_FUNC_EARLY, _activity_init);
/* @} END OF PowerActivities */
|
199 | ./sleepd/src/pwrevents/client.c | /* @@@LICENSE
*
* Copyright (c) 2011-2012 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* LICENSE@@@ */
/**
* @file client.c
*
* @brief This file contains functions to manage clients registered with sleepd to
* veto suspend requests. All the added clients account for the decision by the system to
* suspend or not to suspend. If any client NACKS the suspend request, sleepd will not suspend
* the system.
*
*/
#include <glib.h>
#include <stdlib.h>
#include "logging.h"
#include "debug.h"
#include "client.h"
#define LOG_DOMAIN "PWREVENT-CLIENT: "
/**
* @defgroup SuspendClient Suspend Clients
* @ingroup PowerEvents
* @brief Clients registering for device suspend polling
*/
/**
* @addtogroup SuspendClient
* @{
*/
/**
* @brief Global hash table for managing all clients registering to participate in polling
* for device suspend decision.
*/
static GHashTable *sClientList = NULL;
static int sNumSuspendRequest = 0;
static int sNumSuspendRequestAck = 0;
static int sNumPrepareSuspend = 0;
static int sNumPrepareSuspendAck = 0;
static int sNumNACK = 0;
/**
* @brief Increment the client's total suspend request NACK response as well as total NACK responses for the
* current polling for suspend request.
*
* @param info The client which responded with NACK for suspend request
*/
void
PwrEventClientSuspendRequestNACKIncr(struct PwrEventClientInfo *info)
{
if (info) {
info->num_NACK_suspendRequest++;
sNumNACK++;
}
}
/**
* @brief Increment the client's total prepare suspend NACK response as well as total NACK responses for the
* current polling for prepare suspend.
*
* @param info The client which responded with NACK for prepare suspend
*/
void
PwrEventClientPrepareSuspendNACKIncr(struct PwrEventClientInfo *info)
{
if (info) {
info->num_NACK_prepareSuspend++;
sNumNACK++;
}
}
/**
* @brief Add a new client
*
* @retval The new added client
*/
static struct PwrEventClientInfo*
PwrEventClientInfoCreate(void)
{
struct PwrEventClientInfo *ret_client;
ret_client = malloc(sizeof(struct PwrEventClientInfo));
if (!ret_client)
return NULL;
ret_client->clientName = NULL;
ret_client->clientId = NULL;
ret_client->requireSuspendRequest = false;
ret_client->requirePrepareSuspend = false;
ret_client->num_NACK_suspendRequest = 0;
ret_client->num_NACK_prepareSuspend = 0;
return ret_client;
}
/**
* @brief Free a client
*
* @param client
*/
static void
PwrEventClientInfoDestroy(struct PwrEventClientInfo *client)
{
if (!client) return;
g_free(client->clientName);
g_free(client->clientId);
g_free(client->applicationName);
free(client);
}
/**
* @brief Register a new client with sleepd
*
* @param uid (char *) ID of the client thats registering
*/
bool
PwrEventClientRegister(ClientUID uid)
{
if (PwrEventClientLookup(uid))
PwrEventClientUnregister(uid);
struct PwrEventClientInfo* clientInfo = PwrEventClientInfoCreate();
if (!clientInfo) return false;
TRACE("\t%s Registering client %s\n", __FUNCTION__, uid);
g_hash_table_replace(sClientList, g_strdup(uid), clientInfo);
return true;
}
/**
* @brief Unregister a client
*
* @param uid (char *) ID of the client to be unregistered
*/
bool
PwrEventClientUnregister(ClientUID uid)
{
g_hash_table_remove(sClientList, uid);
return true;
}
/**
* @brief Function to free the memory allocated for the value used when removing the entry from the
* GHashTable "sClientList".
*/
static void
ClientTableValueDestroy(gpointer value)
{
struct PwrEventClientInfo *info = (struct PwrEventClientInfo*)value;
PwrEventClientInfoDestroy(info);
}
/**
* @brief Get the pointer to "sClientList" hash table.
*/
GHashTable *
PwrEventClientGetTable(void)
{
return sClientList;
}
/**
* @brief Create the new hash table "sClientList".
*/
void
PwrEventClientTableCreate(void)
{
sClientList = g_hash_table_new_full(g_str_hash, g_str_equal,
g_free, ClientTableValueDestroy);
}
/**
* @brief Destroy the "sClientList" hash table
*/
void
PwrEventClientTableDestroy(void)
{
g_hash_table_remove_all(sClientList);
g_hash_table_destroy(sClientList);
}
/**
* @brief Retrieve the client information from its id
*
* @param uid
*
* @retval PwrEventClientInfo
*/
struct PwrEventClientInfo*
PwrEventClientLookup(ClientUID uid)
{
if (NULL == uid)
return NULL;
struct PwrEventClientInfo *clientInfo;
clientInfo = (struct PwrEventClientInfo*)
g_hash_table_lookup(sClientList, uid);
if (!clientInfo)
goto error;
return clientInfo;
error:
return NULL;
}
/**
* Unregister a client by its name
*
* @param Client Name
*
* @retval TRUE if client with the given name found and unregistered
*/
bool PwrEventClientUnregisterByName(char * clientName)
{
if (NULL == clientName)
return NULL;
struct PwrEventClientInfo *clientInfo=NULL;
GHashTableIter iter;
gpointer key, value;
g_hash_table_iter_init (&iter, sClientList);
while (g_hash_table_iter_next (&iter, &key, &value))
{
clientInfo=value;
if(!strcmp(clientInfo->clientName,clientName))
{
PwrEventClientUnregister(clientInfo->clientId);
return true;
}
}
return false;
}
/**
* @brief Map client response in int to string
*/
static const char *
AckToString(int ack)
{
const char *ret;
switch (ack)
{
case PWREVENT_CLIENT_ACK:
ret = "ACK";
break;
case PWREVENT_CLIENT_NACK:
ret = "NACK";
break;
case PWREVENT_CLIENT_NORSP:
ret = "NORSP";
break;
default:
ret = "Unknown";
}
return ret;
}
/**
* @brief Helper function for printing each of the client information
*/
static void
get_client_table_str_helper(gpointer key, gpointer value, gpointer data)
{
GString * str = (GString *) data;
g_return_if_fail(str != NULL);
struct PwrEventClientInfo* info =
(struct PwrEventClientInfo*)value;
g_return_if_fail(info != NULL);
g_string_append_printf(str, " %s/%s - %s (%s) - NACKS: %d/%d\n",
info->requireSuspendRequest ?
AckToString(info->ackSuspendRequest) : "###",
info->requirePrepareSuspend ?
AckToString(info->ackPrepareSuspend) : "###",
info->clientName,
info->clientId,
info->num_NACK_suspendRequest,
info->num_NACK_prepareSuspend);
}
/**
* @brief Go through each client in the hash table and get their details
*/
gchar *
PwrEventGetClientTable()
{
GString * ret = g_string_sized_new(32);
g_hash_table_foreach(sClientList, get_client_table_str_helper, ret);
return g_string_free(ret, false);
}
/**
* @brief Helper function for adding all clients who did not respond to suspend request message
* to the string pointer passed.
*/
static void
get_SuspendRequest_NORSP_list_helper(gpointer key, gpointer value, gpointer data)
{
GString * str = (GString *) data;
g_return_if_fail(str != NULL);
struct PwrEventClientInfo* info =
(struct PwrEventClientInfo*)value;
g_return_if_fail(info != NULL);
if ((info->requireSuspendRequest) && (info->ackSuspendRequest == PWREVENT_CLIENT_NORSP)) {
g_string_append_printf(str, "%s%s(%s)",
str->len > 0 ? ", " : "",
info->clientName,
info->clientId);
}
}
/**
* @brief Go through each client in the hash table and print their details if they have not responded
* back to suspend request message.
*/
gchar *
PwrEventGetSuspendRequestNORSPList()
{
GString * ret = g_string_sized_new(32);
g_hash_table_foreach(sClientList, get_SuspendRequest_NORSP_list_helper, ret);
return g_string_free(ret, false);
}
/**
* @brief Helper function for printing all clients who did not respond to prepare suspend message
*/
static void
get_PrepareSuspend_NORSP_list_helper(gpointer key, gpointer value, gpointer data)
{
GString * str = (GString *) data;
g_return_if_fail(str != NULL);
struct PwrEventClientInfo* info =
(struct PwrEventClientInfo*)value;
g_return_if_fail(info != NULL);
if ((info->requirePrepareSuspend) && (info->ackPrepareSuspend == PWREVENT_CLIENT_NORSP)) {
g_string_append_printf(str, "%s%s(%s)",
str->len > 0 ? ", " : "",
info->clientName,
info->clientId);
}
}
/**
* @brief Go through each client in the hash table and print their details if they have not responded
* back to prepare suspend message.
*/
gchar *
PwrEventGetPrepareSuspendNORSPList()
{
GString * ret = g_string_sized_new(32);
g_hash_table_foreach(sClientList, get_PrepareSuspend_NORSP_list_helper, ret);
return g_string_free(ret, false);
}
/**
* @brief Helper function for printing information about all clients registered.
*/
void
PwrEventClientTablePrintHelper(gpointer key, gpointer value, gpointer data)
{
GLogLevelFlags lvl = GPOINTER_TO_UINT(data);
struct PwrEventClientInfo* info =
(struct PwrEventClientInfo*)value;
if (!info) return;
g_log(G_LOG_DOMAIN, lvl, " %s/%s - %s (%s) - NACKS: %d/%d\n",
info->requireSuspendRequest ?
AckToString(info->ackSuspendRequest) : "###",
info->requirePrepareSuspend ?
AckToString(info->ackPrepareSuspend) : "###",
info->clientName,
info->clientId,
info->num_NACK_suspendRequest,
info->num_NACK_prepareSuspend);
}
/**
* @brief Go through each client in the hash table and print their details
*/
void
PwrEventClientTablePrint(GLogLevelFlags lvl)
{
g_log(G_LOG_DOMAIN, lvl, "PwrEvent clients:");
g_hash_table_foreach(sClientList, PwrEventClientTablePrintHelper, GUINT_TO_POINTER(lvl));
}
/**
* @brief If the client's total NACK count is greater than 0, then log it.
*/
void
_PwrEventClientPrintNACKHelper(gpointer key, gpointer value, gpointer ctx)
{
struct PwrEventClientInfo* info =
(struct PwrEventClientInfo*)value;
if (!info) return;
int num_nacks = info->num_NACK_suspendRequest + info->num_NACK_prepareSuspend;
if (num_nacks > 0)
{
SLEEPDLOG(LOG_CRIT, " %s (%s) NACKs: %d",
info->clientName, info->clientId, num_nacks);
}
}
/**
* Log the details of each new client who NACK'ed either the suspend request of prepare suspend message
*/
void
PwrEventClientPrintNACKRateLimited(void)
{
static int num_NACK = 0;
if (sNumNACK > num_NACK) {
num_NACK = sNumNACK;
g_hash_table_foreach(sClientList, _PwrEventClientPrintNACKHelper, NULL);
}
}
/**
* @brief Register/Unregister the client with the given uid for suspend request message
*
* @param uid of the client
* @param reg TRUE for registering and FALSE for unregistering
*
*/
void
PwrEventClientSuspendRequestRegister(ClientUID uid, bool reg)
{
struct PwrEventClientInfo *info = PwrEventClientLookup(uid);
if (!info)
{
TRACE("\t%s could not find uid %s\n", __FUNCTION__, uid);
return;
}
if (info->requireSuspendRequest != reg)
{
info->requireSuspendRequest = reg;
sNumSuspendRequest += reg ? 1 : -1;
}
SLEEPDLOG(LOG_NOTICE, "%s %sregistering for suspend_request",
info->clientName, reg ? "" : "de-");
}
/**
* @brief Register/Unregister the client with the given uid for prepare suspend message
*
* @param uid of the client
* @param reg TRUE for registering and FALSE for unregistering
*
*/
void
PwrEventClientPrepareSuspendRegister(ClientUID uid, bool reg)
{
struct PwrEventClientInfo *info = PwrEventClientLookup(uid);
if (!info)
{
TRACE("\t%s could not find uid %s\n", __FUNCTION__, uid);
return;
}
if (info->requirePrepareSuspend != reg)
{
info->requirePrepareSuspend = reg;
sNumPrepareSuspend += reg ? 1 : -1;
}
SLEEPDLOG(LOG_NOTICE, "%s %sregistering for prepare_suspend",
info->clientName, reg ? "" : "de-");
}
/**
* Helper function for initializing all counts before device suspend polling.
* The counts sNumSuspendRequest and sNumPrepareSuspend keep a track of the
* total expected responses for the suspend request and prepare suspend rounds
* respectively.
*/
void
PwrEventVoteInitHelper(gpointer key, gpointer value, gpointer ctx)
{
struct PwrEventClientInfo* info = (struct PwrEventClientInfo*)value;
if (!info) return;
info->ackSuspendRequest = PWREVENT_CLIENT_NORSP;
info->ackPrepareSuspend = PWREVENT_CLIENT_NORSP;
if (info->requireSuspendRequest) sNumSuspendRequest++;
if (info->requirePrepareSuspend) sNumPrepareSuspend++;
}
/**
* @brief Intialize all counts before the first polling round i.e the suspend request polling.
*/
void
PwrEventVoteInit(void)
{
sNumSuspendRequestAck = 0;
sNumSuspendRequest = 0;
sNumPrepareSuspendAck = 0;
sNumPrepareSuspend = 0;
g_hash_table_foreach(sClientList, PwrEventVoteInitHelper, NULL);
}
/**
* @brief Updates the response for the client with given id for the suspend request polling.
*
* @param uid
* @param ack TRUE if an ack, FALSE if NACK.
*
* @retval true when all clients have acked.
*/
bool
PwrEventVoteSuspendRequest(ClientUID uid, bool ack)
{
struct PwrEventClientInfo *info = PwrEventClientLookup(uid);
if (!info)
{
TRACE("\t%s could not find uid %s\n", __FUNCTION__, uid);
return false;
}
if (!ack)
g_warning("%s(%s) SuspendRequestNACK.", info->clientName, info->clientId);
TRACE("%s %sACK suspend response.\n",
info->clientName, ack ? "" : "N");
if (info->ackSuspendRequest != ack)
{
info->ackSuspendRequest = ack;
sNumSuspendRequestAck += ack ? 1 : 0;
}
return (!ack || PwrEventClientsApproveSuspendRequest());
}
/**
* @brief Updates the response for the client with given id for the prepare suspend polling.
*
* @param uid
* @param ack TRUE if an ack, FALSE if NACK.
*
* @retval true when all clients have acked.
*/
bool
PwrEventVotePrepareSuspend(ClientUID uid, bool ack)
{
struct PwrEventClientInfo *info = PwrEventClientLookup(uid);
if (!info)
{
TRACE("\t%s could not find uid %s\n", __FUNCTION__, uid);
return false;
}
if (!ack)
g_warning("%s(%s) PrepareSuspendNACK", info->clientName, info->clientId);
TRACE("%s %sACK prepare suspend.\n",
info->clientName, ack ? "" : "N");
if (info->ackPrepareSuspend != ack)
{
info->ackPrepareSuspend = ack;
sNumPrepareSuspendAck += ack ? 1 : 0;
}
return (!ack || PwrEventClientsApprovePrepareSuspend());
}
/**
* @brief Returns TRUE if the total number of received ACKs for suspend request round is greater
* than the expected count.
*/
bool
PwrEventClientsApproveSuspendRequest(void)
{
return sNumSuspendRequestAck >= sNumSuspendRequest;
}
/**
* @brief Returns TRUE if the total number of received ACKs for prepare suspend round is greater
* than the expected count.
*/
bool
PwrEventClientsApprovePrepareSuspend(void)
{
return sNumPrepareSuspendAck >= sNumPrepareSuspend;
}
/* @} END OF SuspendClient */
|
200 | ./sleepd/src/pwrevents/suspend.c | /* @@@LICENSE
*
* Copyright (c) 2011-2012 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* LICENSE@@@ */
/**
* @file suspend.c
*
* @brief Suspend/Resume logic to conserve battery when device is idle.
*
*/
/***
* PwrEvent State Machine.
*/
#include <stdbool.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <syslog.h>
#include "suspend.h"
#include "clock.h"
#include "wait.h"
#include "machine.h"
#include "debug.h"
#include "main.h"
#include "timersource.h"
#include "activity.h"
#include "logging.h"
#include "client.h"
#include "timesaver.h"
#include "sysfs.h"
#include "init.h"
#include "timeout_alarm.h"
#include "config.h"
#include "sawmill_logger.h"
#include "nyx/nyx_client.h"
#include <cjson/json.h>
#include <luna-service2/lunaservice.h>
#define LOG_DOMAIN "PWREVENT-SUSPEND: "
#define kPowerBatteryCheckReasonSysfs "/sys/power/batterycheck_wakeup"
#define kPowerWakeupSourcesSysfs "/sys/power/wakeup_event_list"
#define MIN_IDLE_SEC 5
/*
* @brief Power States
*/
enum {
kPowerStateOn,
kPowerStateOnIdle,
kPowerStateSuspendRequest,
kPowerStatePrepareSuspend,
kPowerStateSleep,
kPowerStateKernelResume,
kPowerStateActivityResume,
kPowerStateAbortSuspend,
kPowerStateLast
};
typedef int PowerState;
enum {
kResumeTypeKernel,
kResumeTypeActivity,
kResumeAbortSuspend
};
static char *resume_type_descriptions[] =
{
"kernel",
"pwrevent_activity",
"pwrevent_non_idle",
"abort_suspend",
};
// A PowerStateProc processes the current state and returns the next state
typedef PowerState (*PowerStateProc)(void);
typedef struct {
PowerState state; // currently unused
PowerStateProc function;
} PowerStateNode;
/*
* @brief State Functions
*/
static PowerState StateOn(void);
static PowerState StateOnIdle(void);
static PowerState StateSuspendRequest(void);
static PowerState StatePrepareSuspend(void);
static PowerState StateSleep(void);
static PowerState StateKernelResume(void);
static PowerState StateActivityResume(void);
static PowerState StateAbortSuspend(void);
/**
* @defgroup SuspendLogic Suspend/Resume State Machine
* @ingroup PowerEvents
* @brief Suspend/Resume state machine:
*
* A separate thread "SuspendThread" handles the device suspend/resume logic, and maintains
* a state machine with the following states:
*
* 1. On: This is the first state , in which the device stays as long as display is on, or
* some activity is active or the device has been awake for less than after_resume_idle_ms.
*
* 2. OnIdle: The device goes into this state from "On" state, if the IdleCheck thread thinks that
* the device can now suspend. However if the device is connected to charger and the "suspend_with_charger"
* option is "false", the device will again go back to the "On" state, else the device will go into the next
* state i.e the "SuspendRequest" state.
*
* 3. SuspendRequest: In this state the device will broadcast the "SuspendRequest" signal, to which all the
* registered clients are supposed to respond back with an ACK / NACK. The device will stay in this state for
* a max of 30 sec waiting for all responses. If all clients respond back with an ACK or it timesout, it will go
* to the next state i.e "PrepareSuspend" state. However if any client responds back with a NACK it goes back
* to the "On" state again.
*
* 4. PrepareSuspend: In this state, the device will broadcast the "PrepareSuspend" signal, with a max wait
* of 5 sec for all responses. If all clients respond back with an ACK or it timesout, it will go
* to the next state i.e "Sleep" state. However if any client responds back with NACK, it goes to the
* "AbortSuspend" state.
*
* 5. Sleep: In this state it will first send the "Suspended" signal to everybody. If any activity is active
* at this point it will go resume by going to the "ActivityResume" state, else it will set the next state to
* "KernelResume" and let the machine sleep.
*
* 6. KernelResume: This is the default state in which the system will be after waking up from sleep. It will
* broadcast the "Resume" signal , schedule the next IdleCheck sequence and go to the "On" state.
*
* 7. ActivityResume: It will broadcast the "Resume" signal schedule the next IdleCheck sequence and go back
* to "On" state.
*
* 8. AbortSuspend: It will broadcast the "Resume" signal and go back to the "On" state.
*/
/**
* @addtogroup SuspendLogic
* @{
*/
// Mapping from state to function handling state.
static const PowerStateNode kStateMachine[kPowerStateLast] = {
[kPowerStateOn] = { kPowerStateOn, StateOn },
[kPowerStateOnIdle] = { kPowerStateOnIdle, StateOnIdle },
[kPowerStateSuspendRequest] = { kPowerStateSuspendRequest, StateSuspendRequest },
[kPowerStatePrepareSuspend] = { kPowerStatePrepareSuspend, StatePrepareSuspend },
[kPowerStateSleep] = { kPowerStateSleep, StateSleep },
[kPowerStateKernelResume] = { kPowerStateKernelResume, StateKernelResume },
[kPowerStateActivityResume] = { kPowerStateActivityResume, StateActivityResume },
[kPowerStateAbortSuspend] = { kPowerStateAbortSuspend, StateAbortSuspend }
};
// current state
static PowerStateNode gCurrentStateNode;
//static PowerState gCurrentState;
WaitObj gWaitResumeMessage;
PowerEvent gSuspendEvent = kPowerEventNone;
GTimerSource *idle_scheduler = NULL;
GMainLoop *suspend_loop = NULL;
WaitObj gWaitSuspendResponse;
WaitObj gWaitPrepareSuspend;
struct timespec sTimeOnStartSuspend;
struct timespec sTimeOnSuspended;
struct timespec sTimeOnWake;
struct timespec sSuspendRTC;
struct timespec sWakeRTC;
void SuspendIPCInit(void);
int SendSuspendRequest(const char *message);
int SendPrepareSuspend(const char *message);
int SendResume(int resumetype, char *message);
int SendSuspended(const char *message);
void
StateLoopShutdown(void)
{
WaitObjectSignal(&gWaitSuspendResponse);
WaitObjectSignal(&gWaitPrepareSuspend);
}
/**
* @brief Schedule the IdleCheck thread after interval_ms from fromPoll
*/
void
ScheduleIdleCheck(int interval_ms, bool fromPoll)
{
if (idle_scheduler)
{
g_timer_source_set_interval(idle_scheduler, interval_ms, fromPoll);
}
else
{
g_warning("%s: idle_scheduler not yet initialized", __func__);
}
}
static nyx_device_handle_t nyxDev = NULL;
/**
* @brief Get display status using NYX interface.
*/
static bool
IsDisplayOn(void)
{
nyx_led_controller_state_t state = NYX_LED_CONTROLLER_STATE_UNKNOWN;
if(nyxDev)
nyx_led_controller_get_state(nyxDev,NYX_LED_CONTROLLER_LCD, &state);
else
state = NYX_LED_CONTROLLER_STATE_ON;
return (state == NYX_LED_CONTROLLER_STATE_ON);
}
/**
* @brief Turn off display using NYX interface.
*/
void
switchoffDisplay(void)
{
if(nyxDev)
{
nyx_led_controller_effect_t effect;
effect.required.effect = NYX_LED_CONTROLLER_EFFECT_LED_SET;
effect.required.led = NYX_LED_CONTROLLER_LCD;
effect.backlight.callback = NULL;
effect.backlight.brightness_lcd = -1;
nyx_led_controller_execute_effect(nyxDev, effect);
}
return;
}
/**
* @brief Thread that's scheduled periodically to check if the system has been idle for
* specified time, to trigger the next state in the state machine.
*/
gboolean
IdleCheck(gpointer ctx)
{
bool suspend_active;
bool activity_idle;
struct timespec now;
int next_idle_ms = 0;
if (IsDisplayOn()) goto resched;
ClockGetTime(&now);
/*
* Enforce that the minimum time awake must be at least
* after_resume_idle_ms.
*/
struct timespec last_wake;
last_wake.tv_sec = sTimeOnWake.tv_sec;
last_wake.tv_nsec = sTimeOnWake.tv_nsec;
ClockAccumMs(&last_wake, gSleepConfig.after_resume_idle_ms);
if (ClockTimeIsGreater(&last_wake, &now))
{
struct timespec diff;
ClockDiff(&diff, &last_wake, &now);
next_idle_ms = ClockGetMs(&diff);
goto resched;
}
/*
* Do not sleep if any activity is still active
*/
activity_idle = PwrEventActivityCanSleep(&now);
if (!activity_idle)
{
SLEEPDLOG(LOG_WARNING,
"%s: can't sleep because an activity is active: ",
__FUNCTION__);
}
if (PwrEventActivityCount(&sTimeOnWake))
{
SLEEPDLOG(LOG_INFO, "Activities since wake: ");
PwrEventActivityPrintFrom(&sTimeOnWake);
}
PwrEventActivityRemoveExpired(&now);
{
time_t expiry = 0;
gchar * app_id = NULL;
gchar * key = NULL;
if (timeout_get_next_wakeup(&expiry,&app_id,&key)) {
g_free(app_id);
g_free(key);
int next_wake = expiry - rtc_wall_time();
if(next_wake >= 0 && next_wake <= gSleepConfig.wait_alarms_s)
{
SLEEPDLOG(LOG_DEBUG, "%s: Not going to sleep because an alarm is "
"about to fire in %d sec\n", __func__,next_wake);
goto resched;
}
}
}
/*
* Wait for LunaSysMgr to deposit suspend_active token
* to signify that the system is completely booted and ready for
* suspend activity.
*/
suspend_active = (access("/tmp/suspend_active", R_OK) == 0);
if (suspend_active && activity_idle)
{
TriggerSuspend("device is idle.", kPowerEventIdleEvent);
}
resched:
{
long wait_idle_ms = gSleepConfig.wait_idle_ms;
long max_duration_ms = PwrEventActivityGetMaxDuration(&now);
if (max_duration_ms > wait_idle_ms)
wait_idle_ms = max_duration_ms;
if (next_idle_ms > wait_idle_ms)
wait_idle_ms = next_idle_ms;
ScheduleIdleCheck(wait_idle_ms, true);
}
return TRUE;
}
static gboolean
SuspendStateUpdate(PowerEvent power_event)
{
gSuspendEvent = power_event;
PowerState next_state = kPowerStateLast;
do {
next_state = gCurrentStateNode.function();
if (next_state != kPowerStateLast)
{
gCurrentStateNode = kStateMachine[next_state];
}
} while (next_state != kPowerStateLast);
return FALSE;
}
/**
* @brief Suspend state machine is run in this thread.
*
* @param ctx
*
* @retval
*/
void *
SuspendThread(void *ctx)
{
GMainContext *context;
context = g_main_context_new();
suspend_loop = g_main_loop_new(context, FALSE);
g_main_context_unref(context);
idle_scheduler = g_timer_source_new(
gSleepConfig.wait_idle_ms, gSleepConfig.wait_idle_granularity_ms);
g_source_set_callback((GSource*)idle_scheduler,
IdleCheck, NULL, NULL);
g_source_attach((GSource*)idle_scheduler,
g_main_loop_get_context(suspend_loop));
g_source_unref((GSource*)idle_scheduler);
g_main_loop_run(suspend_loop);
g_main_loop_unref(suspend_loop);
return NULL;
}
/**
* @brief This is the first state , in which the device stays as long as display is on, or
* some activity is active or the device has been awake for less than after_resume_idle_ms.
*
* @retval PowerState Next state
*/
static PowerState
StateOn(void)
{
PowerState next_state;
switch (gSuspendEvent) {
case kPowerEventForceSuspend:
next_state = kPowerStateSuspendRequest;
break;
case kPowerEventIdleEvent:
next_state = kPowerStateOnIdle;
break;
case kPowerEventNone:
default:
next_state = kPowerStateLast;
break;
}
gSuspendEvent = kPowerEventNone;
return next_state;
}
/**
* @brief The device goes into this state from "On" state, if the IdleCheck thread thinks that
* the device can now suspend. However if the device is connected to charger and the "suspend_with_charger"
* option is "false", the device will again go back to the "On" state, else the device will go into the next
* state i.e the "SuspendRequest" state.
*
* @retval PowerState Next state
*/
static PowerState
StateOnIdle(void)
{
if (!MachineCanSleep())
{
return kPowerStateOn;
}
return kPowerStateSuspendRequest;
}
#define START_LOG_COUNT 8
#define MAX_LOG_COUNT_INCREASE_RATE 512
/**
* @brief In this state the device will broadcast the "SuspendRequest" signal, to which all the
* registered clients are supposed to respond back with an ACK / NACK. The device will stay in this state for
* a max of 30 sec waiting for all responses. If all clients respond back with an ACK or it timesout, it will go
* to the next state i.e "PrepareSuspend" state. However if any client responds back with a NACK it goes back
* to the "On" state again.
*
* @retval PowerState Next state.
*/
static PowerState
StateSuspendRequest(void)
{
int timeout = 0;
static int successive_ons=0;
static int log_count = START_LOG_COUNT;
PowerState ret;
ClockGetTime(&sTimeOnStartSuspend);
WaitObjectLock(&gWaitSuspendResponse);
PwrEventVoteInit();
SendSuspendRequest("");
// send msg to ask for permission to sleep
TRACE("\tSent \"suspend request\", waiting up to %dms",
gSleepConfig.wait_suspend_response_ms);
if (!PwrEventClientsApproveSuspendRequest())
{
// wait for the message to arrive
timeout = WaitObjectWait(&gWaitSuspendResponse,
gSleepConfig.wait_suspend_response_ms);
}
WaitObjectUnlock(&gWaitSuspendResponse);
PwrEventClientTablePrint(G_LOG_LEVEL_DEBUG);
if (timeout)
{
gchar * silent_clients = PwrEventGetSuspendRequestNORSPList();
g_warning("\tWe timed-out waiting for daemons (%s) to acknowledge SuspendRequest.", silent_clients);
g_free(silent_clients);
ret = kPowerStatePrepareSuspend;
}
else if (PwrEventClientsApproveSuspendRequest())
{
TRACE("\tSuspend response: go to prepare_suspend.");
ret = kPowerStatePrepareSuspend;
}
else
{
TRACE("\tSuspend response: stay awake.");
ret = kPowerStateOn;
}
if (ret == kPowerStateOn) {
successive_ons++;
if (successive_ons >= log_count) {
g_warning("%s: %d successive votes to NACK SuspendRequest since previous suspend", __func__, successive_ons);
PwrEventClientTablePrint(G_LOG_LEVEL_WARNING);
if (log_count >= MAX_LOG_COUNT_INCREASE_RATE)
log_count += MAX_LOG_COUNT_INCREASE_RATE;
else
log_count *= 2;
g_warning("%s: next count before logging is %d", __func__, log_count);
}
} else {
// reset the exponential counter
successive_ons = 0;
log_count = START_LOG_COUNT;
}
return ret;
}
/**
* @brief In this state, the device will broadcast the "PrepareSuspend" signal, with a max wait of 5 sec
* for all responses. If all clients respond back with an ACK or it timesout, it will go to the next state
* i.e "Sleep" state. However if any client responds back with NACK, it goes to the "AbortSuspend" state.
*
* @retval PowerState Next state.
*/
static PowerState
StatePrepareSuspend(void)
{
int timeout = 0;
static int successive_ons=0;
static int log_count = START_LOG_COUNT;
WaitObjectLock(&gWaitPrepareSuspend);
// send suspend request to all power-aware daemons.
SendPrepareSuspend("");
TRACE("\tSent \"prepare suspend\", waiting up to %dms",
gSleepConfig.wait_prepare_suspend_ms);
if (!PwrEventClientsApprovePrepareSuspend())
{
timeout = WaitObjectWait(&gWaitPrepareSuspend,
gSleepConfig.wait_prepare_suspend_ms);
}
WaitObjectUnlock(&gWaitPrepareSuspend);
PwrEventClientTablePrint(G_LOG_LEVEL_DEBUG);
if (timeout)
{
gchar * silent_clients = PwrEventGetPrepareSuspendNORSPList();
g_warning("\tWe timed-out waiting for daemons (%s) to acknowledge PrepareSuspend.", silent_clients);
gchar * clients = PwrEventGetClientTable();
SLEEPDLOG(LOG_CRIT,"== NORSP clients ==\n %s\n == client table ==\n %s", silent_clients, clients);
g_free(clients);
g_free(silent_clients);
// reset the exponential counter
successive_ons = 0;
log_count = START_LOG_COUNT;
return kPowerStateSleep;
}
else if (PwrEventClientsApprovePrepareSuspend())
{
TRACE("\tClients all approved prepare_suspend.");
// reset the exponential counter
successive_ons = 0;
log_count = START_LOG_COUNT;
return kPowerStateSleep;
}
else
{
// if any daemons nacked, quit suspend...
TRACE("\tSome daemon nacked prepare_suspend: stay awake.");
successive_ons++;
if (successive_ons >= log_count) {
g_warning("%s: %d successive votes to NACK PrepareSuspend since previous suspend", __func__, successive_ons);
PwrEventClientTablePrint(G_LOG_LEVEL_WARNING);
if (log_count >= MAX_LOG_COUNT_INCREASE_RATE)
log_count += MAX_LOG_COUNT_INCREASE_RATE;
else
log_count *= 2;
g_warning("%s: next count before logging is %d", __func__, log_count);
}
return kPowerStateAbortSuspend;
}
}
/**
* @brief Instrument how much time it took to sleep.
*/
void
InstrumentOnSleep(void)
{
struct timespec diff;
struct timespec diffAwake;
ClockGetTime(&sTimeOnSuspended);
get_time_now(&sSuspendRTC);
ClockDiff(&diff, &sTimeOnSuspended, &sTimeOnStartSuspend);
ClockDiff(&diffAwake, &sTimeOnSuspended, &sTimeOnWake);
GString *str = g_string_new ("");
g_string_append_printf(str, "PWREVENT-SLEEP after ");
ClockStr(str, &diffAwake);
g_string_append(str, "... decision took ");
ClockStr(str, &diff);
SLEEPDLOG(LOG_INFO, "%s", str->str);
g_string_free(str, TRUE);
/* Rate-limited print NACK sources. */
PwrEventClientPrintNACKRateLimited();
sawmill_logger_record_sleep(diffAwake);
}
/**
* @brief Instrument how much time it took to wake back up.
*/
void
InstrumentOnWake(int resumeType)
{
ClockGetTime(&sTimeOnWake);
get_time_now(&sWakeRTC);
struct timespec diffAsleep;
ClockDiff(&diffAsleep, &sWakeRTC, &sSuspendRTC);
struct tm tm;
gmtime_r(&(diffAsleep.tv_sec), &tm);
if (tm.tm_year >= 70)
tm.tm_year -= 70; // EPOCH returned by time() starts at 1970
GString *str = g_string_new("PWREVENT-WOKE after ");
g_string_append_printf(str, "%lds : ", diffAsleep.tv_sec);
if (tm.tm_year > 0)
{
g_string_append_printf(str, "%d years, ", tm.tm_year);
}
g_string_append_printf(str, "%d days, %dh-%dm-%ds\n", tm.tm_yday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
SLEEPDLOG(LOG_INFO, "%s (%s)", str->str, resume_type_descriptions[resumeType]);
g_string_free(str, TRUE);
sawmill_logger_record_wake(diffAsleep);
}
/**
* @brief In this state it will first send the "Suspended" signal to everybody. If any activity is active
* at this point it will go resume by going to the "ActivityResume" state, else it will set the next state
* to "KernelResume" and let the machine sleep.
*
* @retval PowerState Next state.
*/
static PowerState
StateSleep(void)
{
int nextState = kPowerStateKernelResume; // assume a normal sleep ended by some kernel event
TRACE("State Sleep");
TRACE("\tWe will try to go to sleep now");
SendSuspended("attempting to suspend (We are trying to sleep)");
{
time_t expiry = 0;
gchar * app_id = NULL;
gchar * key = NULL;
if (timeout_get_next_wakeup(&expiry,&app_id,&key)) {
SLEEPDLOG(LOG_INFO, "%s: waking in %ld seconds for %s\n", __func__, expiry - rtc_wall_time(), key);
}
g_free(app_id);
g_free(key);
}
InstrumentOnSleep();
// save the current time to disk in case battery is pulled.
timesaver_save();
// if any activities were started, abort suspend.
if (gSuspendEvent != kPowerEventForceSuspend &&
!PwrEventFreezeActivities(&sTimeOnSuspended))
{
SLEEPDLOG(LOG_WARNING,
"%s: aborting sleep because of current activity: ", __FUNCTION__);
PwrEventActivityPrintFrom(&sTimeOnSuspended);
nextState = kPowerStateActivityResume;
goto resume;
}
if(MachineCanSleep()) {
// let the system sleep now.
_queue_next_timeout(false);
MachineSleep();
}
else {
SLEEPDLOG(LOG_INFO,"We couldn't sleep because a new gadget_event was received");
nextState= kPowerStateAbortSuspend;
}
// We woke up from sleep.
PwrEventThawActivities();
resume:
return nextState;
}
/**
* @brief In this state the "Resume" signal will be broadcasted and the device will go back to the "On" state.
*
* @retval PowerState Next state.
*/
static PowerState
StateAbortSuspend(void)
{
TRACE("\tAbort suspend.");
SendResume(kResumeAbortSuspend,"resume (suspend aborted)");
return kPowerStateOn;
}
/**
* @brief Broadcast the resume signal when we wake up ( due to kernel sleep or activity)
*
* @retval PowerState Next state
*/
static PowerState
_stateResume(int resumeType)
{
TRACE("\tWe awoke");
char *resumeDesc = g_strdup_printf("resume (%s)", resume_type_descriptions[resumeType]);
SendResume(resumeType, resumeDesc);
g_free(resumeDesc);
#ifdef ASSERT_ON_BUG
WaitObjectSignal(&gWaitSuspendResponse);
#endif
InstrumentOnWake(resumeType);
// if we are inactive in 1s, go back to sleep.
ScheduleIdleCheck(gSleepConfig.after_resume_idle_ms, false);
return kPowerStateOn;
}
/**
* @brief This is the default state in which the system will be after waking up from sleep. It will
* broadcast the "Resume" signal , schedule the next IdleCheck sequence and go to the "On" state.
*
* @retval PowerState Next state
*/
static PowerState
StateKernelResume(void)
{
return _stateResume(kResumeTypeKernel);
}
/**
* @brief We are in this state if the system did not really sleep but had to prevent the sleep because
* an activity as active. It does so by broadcasting the "Resume" signal , schedule the next IdleCheck
* sequence and go to the "On" state.
*
* @retval PowerState Next state
*/
static PowerState
StateActivityResume(void)
{
return _stateResume(kResumeTypeActivity);
}
/**
* @brief Initialize the Suspend/Resume state machine.
*/
static int
SuspendInit(void)
{
pthread_t suspend_tid;
// initialize wake time.
ClockGetTime(&sTimeOnWake);
WaitObjectInit(&gWaitSuspendResponse);
WaitObjectInit(&gWaitPrepareSuspend);
WaitObjectInit(&gWaitResumeMessage);
com_palm_suspend_lunabus_init();
PwrEventClientTableCreate();
SuspendIPCInit();
if (gSleepConfig.visual_leds_suspend)
{
if(SysfsWriteString("/sys/class/leds/core_navi_center/brightness", "15") < 0)
{
SysfsWriteString(
"/sys/class/leds/core_navi_left/brightness", "100");
SysfsWriteString(
"/sys/class/leds/core_navi_right/brightness", "100");
}
}
gCurrentStateNode = kStateMachine[kPowerStateOn];
if (pthread_create(&suspend_tid, NULL, SuspendThread, NULL))
{
g_critical("%s Could not create SuspendThread\n", __FUNCTION__);
abort();
}
int ret = nyx_device_open(NYX_DEVICE_LED_CONTROLLER, "Default", &nyxDev);
if(ret != NYX_ERROR_NONE)
{
SLEEPDLOG(LOG_CRIT,"Sleepd: Unable to open the nyx device led controller");
}
return 0;
}
/**
* @brief Iterate through the state machine
*/
void
TriggerSuspend(const char *reason, PowerEvent event)
{
GSource *source = g_idle_source_new ();
g_source_set_callback (source,
(GSourceFunc)SuspendStateUpdate, (void*)event, NULL);
g_source_attach (source, g_main_loop_get_context(suspend_loop));
g_source_unref (source);
}
INIT_FUNC(INIT_FUNC_END, SuspendInit);
/* @} END OF SuspendLogic */
|