id
int64 1
722k
| file_path
stringlengths 8
177
| funcs
stringlengths 1
35.8M
|
---|---|---|
301 | ./android_firewall/external/iptables/extensions/libipt_ECN.c | /* Shared library add-on to iptables for ECN, $Version$
*
* (C) 2002 by Harald Welte <[email protected]>
*
* This program is distributed under the terms of GNU GPL v2, 1991
*
* libipt_ECN.c borrowed heavily from libipt_DSCP.c
*/
#include <stdio.h>
#include <xtables.h>
#include <linux/netfilter_ipv4/ipt_ECN.h>
enum {
O_ECN_TCP_REMOVE = 0,
O_ECN_TCP_CWR,
O_ECN_TCP_ECE,
O_ECN_IP_ECT,
F_ECN_TCP_REMOVE = 1 << O_ECN_TCP_REMOVE,
F_ECN_TCP_CWR = 1 << O_ECN_TCP_CWR,
F_ECN_TCP_ECE = 1 << O_ECN_TCP_ECE,
};
static void ECN_help(void)
{
printf(
"ECN target options\n"
" --ecn-tcp-remove Remove all ECN bits from TCP header\n");
}
#if 0
"ECN target v%s EXPERIMENTAL options (use with extreme care!)\n"
" --ecn-ip-ect Set the IPv4 ECT codepoint (0 to 3)\n"
" --ecn-tcp-cwr Set the IPv4 CWR bit (0 or 1)\n"
" --ecn-tcp-ece Set the IPv4 ECE bit (0 or 1)\n",
#endif
static const struct xt_option_entry ECN_opts[] = {
{.name = "ecn-tcp-remove", .id = O_ECN_TCP_REMOVE, .type = XTTYPE_NONE,
.excl = F_ECN_TCP_CWR | F_ECN_TCP_ECE},
{.name = "ecn-tcp-cwr", .id = O_ECN_TCP_CWR, .type = XTTYPE_UINT8,
.min = 0, .max = 1, .excl = F_ECN_TCP_REMOVE},
{.name = "ecn-tcp-ece", .id = O_ECN_TCP_ECE, .type = XTTYPE_UINT8,
.min = 0, .max = 1, .excl = F_ECN_TCP_REMOVE},
{.name = "ecn-ip-ect", .id = O_ECN_IP_ECT, .type = XTTYPE_UINT8,
.min = 0, .max = 3},
XTOPT_TABLEEND,
};
static void ECN_parse(struct xt_option_call *cb)
{
struct ipt_ECN_info *einfo = cb->data;
xtables_option_parse(cb);
switch (cb->entry->id) {
case O_ECN_TCP_REMOVE:
einfo->operation = IPT_ECN_OP_SET_ECE | IPT_ECN_OP_SET_CWR;
einfo->proto.tcp.ece = 0;
einfo->proto.tcp.cwr = 0;
break;
case O_ECN_TCP_CWR:
einfo->operation |= IPT_ECN_OP_SET_CWR;
einfo->proto.tcp.cwr = cb->val.u8;
break;
case O_ECN_TCP_ECE:
einfo->operation |= IPT_ECN_OP_SET_ECE;
einfo->proto.tcp.ece = cb->val.u8;
break;
case O_ECN_IP_ECT:
einfo->operation |= IPT_ECN_OP_SET_IP;
einfo->ip_ect = cb->val.u8;
break;
}
}
static void ECN_check(struct xt_fcheck_call *cb)
{
if (cb->xflags == 0)
xtables_error(PARAMETER_PROBLEM,
"ECN target: An operation is required");
}
static void ECN_print(const void *ip, const struct xt_entry_target *target,
int numeric)
{
const struct ipt_ECN_info *einfo =
(const struct ipt_ECN_info *)target->data;
printf(" ECN");
if (einfo->operation == (IPT_ECN_OP_SET_ECE|IPT_ECN_OP_SET_CWR)
&& einfo->proto.tcp.ece == 0
&& einfo->proto.tcp.cwr == 0)
printf(" TCP remove");
else {
if (einfo->operation & IPT_ECN_OP_SET_ECE)
printf(" ECE=%u", einfo->proto.tcp.ece);
if (einfo->operation & IPT_ECN_OP_SET_CWR)
printf(" CWR=%u", einfo->proto.tcp.cwr);
if (einfo->operation & IPT_ECN_OP_SET_IP)
printf(" ECT codepoint=%u", einfo->ip_ect);
}
}
static void ECN_save(const void *ip, const struct xt_entry_target *target)
{
const struct ipt_ECN_info *einfo =
(const struct ipt_ECN_info *)target->data;
if (einfo->operation == (IPT_ECN_OP_SET_ECE|IPT_ECN_OP_SET_CWR)
&& einfo->proto.tcp.ece == 0
&& einfo->proto.tcp.cwr == 0)
printf(" --ecn-tcp-remove");
else {
if (einfo->operation & IPT_ECN_OP_SET_ECE)
printf(" --ecn-tcp-ece %d", einfo->proto.tcp.ece);
if (einfo->operation & IPT_ECN_OP_SET_CWR)
printf(" --ecn-tcp-cwr %d", einfo->proto.tcp.cwr);
if (einfo->operation & IPT_ECN_OP_SET_IP)
printf(" --ecn-ip-ect %d", einfo->ip_ect);
}
}
static struct xtables_target ecn_tg_reg = {
.name = "ECN",
.version = XTABLES_VERSION,
.family = NFPROTO_IPV4,
.size = XT_ALIGN(sizeof(struct ipt_ECN_info)),
.userspacesize = XT_ALIGN(sizeof(struct ipt_ECN_info)),
.help = ECN_help,
.print = ECN_print,
.save = ECN_save,
.x6_parse = ECN_parse,
.x6_fcheck = ECN_check,
.x6_options = ECN_opts,
};
void _init(void)
{
xtables_register_target(&ecn_tg_reg);
}
|
302 | ./android_firewall/external/iptables/extensions/libxt_cluster.c | /*
* (C) 2009 by Pablo Neira Ayuso <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <stdio.h>
#include <xtables.h>
#include <linux/netfilter/xt_cluster.h>
static void
cluster_help(void)
{
printf(
"cluster match options:\n"
" --cluster-total-nodes <num> Set number of total nodes in cluster\n"
" [!] --cluster-local-node <num> Set the local node number\n"
" [!] --cluster-local-nodemask <num> Set the local node mask\n"
" --cluster-hash-seed <num> Set seed value of the Jenkins hash\n");
}
enum {
O_CL_TOTAL_NODES = 0,
O_CL_LOCAL_NODE,
O_CL_LOCAL_NODEMASK,
O_CL_HASH_SEED,
F_CL_TOTAL_NODES = 1 << O_CL_TOTAL_NODES,
F_CL_LOCAL_NODE = 1 << O_CL_LOCAL_NODE,
F_CL_LOCAL_NODEMASK = 1 << O_CL_LOCAL_NODEMASK,
F_CL_HASH_SEED = 1 << O_CL_HASH_SEED,
};
#define s struct xt_cluster_match_info
static const struct xt_option_entry cluster_opts[] = {
{.name = "cluster-total-nodes", .id = O_CL_TOTAL_NODES,
.type = XTTYPE_UINT32, .min = 1, .max = XT_CLUSTER_NODES_MAX,
.flags = XTOPT_MAND | XTOPT_PUT, XTOPT_POINTER(s, total_nodes)},
{.name = "cluster-local-node", .id = O_CL_LOCAL_NODE,
.excl = F_CL_LOCAL_NODEMASK, .flags = XTOPT_INVERT,
.type = XTTYPE_UINT32, .min = 1, .max = XT_CLUSTER_NODES_MAX},
{.name = "cluster-local-nodemask", .id = O_CL_LOCAL_NODEMASK,
.excl = F_CL_LOCAL_NODE, .type = XTTYPE_UINT32,
.min = 1, .max = XT_CLUSTER_NODES_MAX,
.flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, node_mask)},
{.name = "cluster-hash-seed", .id = O_CL_HASH_SEED,
.type = XTTYPE_UINT32, .flags = XTOPT_MAND | XTOPT_PUT,
XTOPT_POINTER(s, hash_seed)},
XTOPT_TABLEEND,
};
static void cluster_parse(struct xt_option_call *cb)
{
struct xt_cluster_match_info *info = cb->data;
xtables_option_parse(cb);
switch (cb->entry->id) {
case O_CL_LOCAL_NODE:
if (cb->invert)
info->flags |= XT_CLUSTER_F_INV;
info->node_mask = 1 << (cb->val.u32 - 1);
break;
case O_CL_LOCAL_NODEMASK:
if (cb->invert)
info->flags |= XT_CLUSTER_F_INV;
break;
}
}
static void cluster_check(struct xt_fcheck_call *cb)
{
const struct xt_cluster_match_info *info = cb->data;
unsigned int test;
test = F_CL_TOTAL_NODES | F_CL_LOCAL_NODE | F_CL_HASH_SEED;
if ((cb->xflags & test) == test) {
if (info->node_mask >= (1ULL << info->total_nodes))
xtables_error(PARAMETER_PROBLEM,
"cluster match: "
"`--cluster-local-node' "
"must be <= `--cluster-total-nodes'");
return;
}
test = F_CL_TOTAL_NODES | F_CL_LOCAL_NODEMASK | F_CL_HASH_SEED;
if ((cb->xflags & test) == test) {
if (info->node_mask >= (1ULL << info->total_nodes))
xtables_error(PARAMETER_PROBLEM,
"cluster match: "
"`--cluster-local-nodemask' too big "
"for `--cluster-total-nodes'");
return;
}
if (!(cb->xflags & (F_CL_LOCAL_NODE | F_CL_LOCAL_NODEMASK)))
xtables_error(PARAMETER_PROBLEM,
"cluster match: `--cluster-local-node' or"
"`--cluster-local-nodemask' is missing");
}
static void
cluster_print(const void *ip, const struct xt_entry_match *match, int numeric)
{
const struct xt_cluster_match_info *info = (void *)match->data;
printf(" cluster ");
if (info->flags & XT_CLUSTER_F_INV)
printf("!node_mask=0x%08x", info->node_mask);
else
printf("node_mask=0x%08x", info->node_mask);
printf(" total_nodes=%u hash_seed=0x%08x",
info->total_nodes, info->hash_seed);
}
static void
cluster_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_cluster_match_info *info = (void *)match->data;
if (info->flags & XT_CLUSTER_F_INV)
printf(" ! --cluster-local-nodemask 0x%08x", info->node_mask);
else
printf(" --cluster-local-nodemask 0x%08x", info->node_mask);
printf(" --cluster-total-nodes %u --cluster-hash-seed 0x%08x",
info->total_nodes, info->hash_seed);
}
static struct xtables_match cluster_mt_reg = {
.family = NFPROTO_UNSPEC,
.name = "cluster",
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof(struct xt_cluster_match_info)),
.userspacesize = XT_ALIGN(sizeof(struct xt_cluster_match_info)),
.help = cluster_help,
.print = cluster_print,
.save = cluster_save,
.x6_parse = cluster_parse,
.x6_fcheck = cluster_check,
.x6_options = cluster_opts,
};
void _init(void)
{
xtables_register_match(&cluster_mt_reg);
}
|
303 | ./android_firewall/external/iptables/extensions/libxt_ipvs.c | /*
* Shared library add-on to iptables to add IPVS matching.
*
* Detailed doc is in the kernel module source net/netfilter/xt_ipvs.c
*
* Author: Hannes Eder <[email protected]>
*/
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <xtables.h>
#include <linux/ip_vs.h>
#include <linux/netfilter/xt_ipvs.h>
enum {
/* For xt_ipvs: make sure this matches up with %XT_IPVS_*'s order */
O_IPVS = 0,
O_VPROTO,
O_VADDR,
O_VPORT,
O_VDIR,
O_VMETHOD,
O_VPORTCTL,
};
#define s struct xt_ipvs_mtinfo
static const struct xt_option_entry ipvs_mt_opts[] = {
{.name = "ipvs", .id = O_IPVS, .type = XTTYPE_NONE,
.flags = XTOPT_INVERT},
{.name = "vproto", .id = O_VPROTO, .type = XTTYPE_STRING,
.flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, l4proto)},
{.name = "vaddr", .id = O_VADDR, .type = XTTYPE_HOSTMASK,
.flags = XTOPT_INVERT},
{.name = "vport", .id = O_VPORT, .type = XTTYPE_PORT,
.flags = XTOPT_NBO | XTOPT_INVERT | XTOPT_PUT,
XTOPT_POINTER(s, vport)},
{.name = "vdir", .id = O_VDIR, .type = XTTYPE_STRING},
{.name = "vmethod", .id = O_VMETHOD, .type = XTTYPE_STRING,
.flags = XTOPT_INVERT},
{.name = "vportctl", .id = O_VPORTCTL, .type = XTTYPE_PORT,
.flags = XTOPT_NBO | XTOPT_INVERT | XTOPT_PUT,
XTOPT_POINTER(s, vportctl)},
XTOPT_TABLEEND,
};
#undef s
static void ipvs_mt_help(void)
{
printf(
"IPVS match options:\n"
"[!] --ipvs packet belongs to an IPVS connection\n"
"\n"
"Any of the following options implies --ipvs (even negated)\n"
"[!] --vproto protocol VIP protocol to match; by number or name,\n"
" e.g. \"tcp\"\n"
"[!] --vaddr address[/mask] VIP address to match\n"
"[!] --vport port VIP port to match; by number or name,\n"
" e.g. \"http\"\n"
" --vdir {ORIGINAL|REPLY} flow direction of packet\n"
"[!] --vmethod {GATE|IPIP|MASQ} IPVS forwarding method used\n"
"[!] --vportctl port VIP port of the controlling connection to\n"
" match, e.g. 21 for FTP\n"
);
}
static void ipvs_mt_parse(struct xt_option_call *cb)
{
struct xt_ipvs_mtinfo *data = cb->data;
xtables_option_parse(cb);
switch (cb->entry->id) {
case O_VPROTO:
data->l4proto = cb->val.protocol;
break;
case O_VADDR:
memcpy(&data->vaddr, &cb->val.haddr, sizeof(cb->val.haddr));
memcpy(&data->vmask, &cb->val.hmask, sizeof(cb->val.hmask));
break;
case O_VDIR:
if (strcasecmp(cb->arg, "ORIGINAL") == 0) {
data->bitmask |= XT_IPVS_DIR;
data->invert &= ~XT_IPVS_DIR;
} else if (strcasecmp(cb->arg, "REPLY") == 0) {
data->bitmask |= XT_IPVS_DIR;
data->invert |= XT_IPVS_DIR;
} else {
xtables_param_act(XTF_BAD_VALUE,
"ipvs", "--vdir", cb->arg);
}
break;
case O_VMETHOD:
if (strcasecmp(cb->arg, "GATE") == 0)
data->fwd_method = IP_VS_CONN_F_DROUTE;
else if (strcasecmp(cb->arg, "IPIP") == 0)
data->fwd_method = IP_VS_CONN_F_TUNNEL;
else if (strcasecmp(cb->arg, "MASQ") == 0)
data->fwd_method = IP_VS_CONN_F_MASQ;
else
xtables_param_act(XTF_BAD_VALUE,
"ipvs", "--vmethod", cb->arg);
break;
}
data->bitmask |= 1 << cb->entry->id;
if (cb->invert)
data->invert |= 1 << cb->entry->id;
}
static void ipvs_mt_check(struct xt_fcheck_call *cb)
{
struct xt_ipvs_mtinfo *info = cb->data;
if (cb->xflags == 0)
xtables_error(PARAMETER_PROBLEM,
"IPVS: At least one option is required");
if (info->bitmask & XT_IPVS_ONCE_MASK) {
if (info->invert & XT_IPVS_IPVS_PROPERTY)
xtables_error(PARAMETER_PROBLEM,
"! --ipvs cannot be together with"
" other options");
info->bitmask |= XT_IPVS_IPVS_PROPERTY;
}
}
/* Shamelessly copied from libxt_conntrack.c */
static void ipvs_mt_dump_addr(const union nf_inet_addr *addr,
const union nf_inet_addr *mask,
unsigned int family, bool numeric)
{
char buf[BUFSIZ];
if (family == NFPROTO_IPV4) {
if (!numeric && addr->ip == 0) {
printf(" anywhere");
return;
}
if (numeric)
strcpy(buf, xtables_ipaddr_to_numeric(&addr->in));
else
strcpy(buf, xtables_ipaddr_to_anyname(&addr->in));
strcat(buf, xtables_ipmask_to_numeric(&mask->in));
printf(" %s", buf);
} else if (family == NFPROTO_IPV6) {
if (!numeric && addr->ip6[0] == 0 && addr->ip6[1] == 0 &&
addr->ip6[2] == 0 && addr->ip6[3] == 0) {
printf(" anywhere");
return;
}
if (numeric)
strcpy(buf, xtables_ip6addr_to_numeric(&addr->in6));
else
strcpy(buf, xtables_ip6addr_to_anyname(&addr->in6));
strcat(buf, xtables_ip6mask_to_numeric(&mask->in6));
printf(" %s", buf);
}
}
static void ipvs_mt_dump(const void *ip, const struct xt_ipvs_mtinfo *data,
unsigned int family, bool numeric, const char *prefix)
{
if (data->bitmask == XT_IPVS_IPVS_PROPERTY) {
if (data->invert & XT_IPVS_IPVS_PROPERTY)
printf(" !");
printf(" %sipvs", prefix);
}
if (data->bitmask & XT_IPVS_PROTO) {
if (data->invert & XT_IPVS_PROTO)
printf(" !");
printf(" %sproto %u", prefix, data->l4proto);
}
if (data->bitmask & XT_IPVS_VADDR) {
if (data->invert & XT_IPVS_VADDR)
printf(" !");
printf(" %svaddr", prefix);
ipvs_mt_dump_addr(&data->vaddr, &data->vmask, family, numeric);
}
if (data->bitmask & XT_IPVS_VPORT) {
if (data->invert & XT_IPVS_VPORT)
printf(" !");
printf(" %svport %u", prefix, ntohs(data->vport));
}
if (data->bitmask & XT_IPVS_DIR) {
if (data->invert & XT_IPVS_DIR)
printf(" %svdir REPLY", prefix);
else
printf(" %svdir ORIGINAL", prefix);
}
if (data->bitmask & XT_IPVS_METHOD) {
if (data->invert & XT_IPVS_METHOD)
printf(" !");
printf(" %svmethod", prefix);
switch (data->fwd_method) {
case IP_VS_CONN_F_DROUTE:
printf(" GATE");
break;
case IP_VS_CONN_F_TUNNEL:
printf(" IPIP");
break;
case IP_VS_CONN_F_MASQ:
printf(" MASQ");
break;
default:
/* Hu? */
printf(" UNKNOWN");
break;
}
}
if (data->bitmask & XT_IPVS_VPORTCTL) {
if (data->invert & XT_IPVS_VPORTCTL)
printf(" !");
printf(" %svportctl %u", prefix, ntohs(data->vportctl));
}
}
static void ipvs_mt4_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
const struct xt_ipvs_mtinfo *data = (const void *)match->data;
ipvs_mt_dump(ip, data, NFPROTO_IPV4, numeric, "");
}
static void ipvs_mt6_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
const struct xt_ipvs_mtinfo *data = (const void *)match->data;
ipvs_mt_dump(ip, data, NFPROTO_IPV6, numeric, "");
}
static void ipvs_mt4_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_ipvs_mtinfo *data = (const void *)match->data;
ipvs_mt_dump(ip, data, NFPROTO_IPV4, true, "--");
}
static void ipvs_mt6_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_ipvs_mtinfo *data = (const void *)match->data;
ipvs_mt_dump(ip, data, NFPROTO_IPV6, true, "--");
}
static struct xtables_match ipvs_matches_reg[] = {
{
.version = XTABLES_VERSION,
.name = "ipvs",
.revision = 0,
.family = NFPROTO_IPV4,
.size = XT_ALIGN(sizeof(struct xt_ipvs_mtinfo)),
.userspacesize = XT_ALIGN(sizeof(struct xt_ipvs_mtinfo)),
.help = ipvs_mt_help,
.x6_parse = ipvs_mt_parse,
.x6_fcheck = ipvs_mt_check,
.print = ipvs_mt4_print,
.save = ipvs_mt4_save,
.x6_options = ipvs_mt_opts,
},
{
.version = XTABLES_VERSION,
.name = "ipvs",
.revision = 0,
.family = NFPROTO_IPV6,
.size = XT_ALIGN(sizeof(struct xt_ipvs_mtinfo)),
.userspacesize = XT_ALIGN(sizeof(struct xt_ipvs_mtinfo)),
.help = ipvs_mt_help,
.x6_parse = ipvs_mt_parse,
.x6_fcheck = ipvs_mt_check,
.print = ipvs_mt6_print,
.save = ipvs_mt6_save,
.x6_options = ipvs_mt_opts,
},
};
void _init(void)
{
xtables_register_matches(ipvs_matches_reg,
ARRAY_SIZE(ipvs_matches_reg));
}
|
304 | ./android_firewall/external/iptables/extensions/libxt_CONNSECMARK.c | /*
* Shared library add-on to iptables to add CONNSECMARK target support.
*
* Based on the MARK and CONNMARK targets.
*
* Copyright (C) 2006 Red Hat, Inc., James Morris <[email protected]>
*/
#include <stdio.h>
#include <xtables.h>
#include <linux/netfilter/xt_CONNSECMARK.h>
#define PFX "CONNSECMARK target: "
enum {
O_SAVE = 0,
O_RESTORE,
F_SAVE = 1 << O_SAVE,
F_RESTORE = 1 << O_RESTORE,
};
static void CONNSECMARK_help(void)
{
printf(
"CONNSECMARK target options:\n"
" --save Copy security mark from packet to conntrack\n"
" --restore Copy security mark from connection to packet\n");
}
static const struct xt_option_entry CONNSECMARK_opts[] = {
{.name = "save", .id = O_SAVE, .excl = F_RESTORE, .type = XTTYPE_NONE},
{.name = "restore", .id = O_RESTORE, .excl = F_SAVE,
.type = XTTYPE_NONE},
XTOPT_TABLEEND,
};
static void CONNSECMARK_parse(struct xt_option_call *cb)
{
struct xt_connsecmark_target_info *info = cb->data;
xtables_option_parse(cb);
switch (cb->entry->id) {
case O_SAVE:
info->mode = CONNSECMARK_SAVE;
break;
case O_RESTORE:
info->mode = CONNSECMARK_RESTORE;
break;
}
}
static void CONNSECMARK_check(struct xt_fcheck_call *cb)
{
if (cb->xflags == 0)
xtables_error(PARAMETER_PROBLEM, PFX "parameter required");
}
static void print_connsecmark(const struct xt_connsecmark_target_info *info)
{
switch (info->mode) {
case CONNSECMARK_SAVE:
printf("save");
break;
case CONNSECMARK_RESTORE:
printf("restore");
break;
default:
xtables_error(OTHER_PROBLEM, PFX "invalid mode %hhu\n", info->mode);
}
}
static void
CONNSECMARK_print(const void *ip, const struct xt_entry_target *target,
int numeric)
{
const struct xt_connsecmark_target_info *info =
(struct xt_connsecmark_target_info*)(target)->data;
printf(" CONNSECMARK ");
print_connsecmark(info);
}
static void
CONNSECMARK_save(const void *ip, const struct xt_entry_target *target)
{
const struct xt_connsecmark_target_info *info =
(struct xt_connsecmark_target_info*)target->data;
printf(" --");
print_connsecmark(info);
}
static struct xtables_target connsecmark_target = {
.family = NFPROTO_UNSPEC,
.name = "CONNSECMARK",
.version = XTABLES_VERSION,
.revision = 0,
.size = XT_ALIGN(sizeof(struct xt_connsecmark_target_info)),
.userspacesize = XT_ALIGN(sizeof(struct xt_connsecmark_target_info)),
.help = CONNSECMARK_help,
.print = CONNSECMARK_print,
.save = CONNSECMARK_save,
.x6_parse = CONNSECMARK_parse,
.x6_fcheck = CONNSECMARK_check,
.x6_options = CONNSECMARK_opts,
};
void _init(void)
{
xtables_register_target(&connsecmark_target);
}
|
305 | ./android_firewall/external/iptables/extensions/libipt_realm.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#if defined(__GLIBC__) && __GLIBC__ == 2
#include <net/ethernet.h>
#else
#include <linux/if_ether.h>
#endif
#include <xtables.h>
#include <linux/netfilter_ipv4/ipt_realm.h>
enum {
O_REALM = 0,
};
static void realm_help(void)
{
printf(
"realm match options:\n"
"[!] --realm value[/mask]\n"
" Match realm\n");
}
static const struct xt_option_entry realm_opts[] = {
{.name = "realm", .id = O_REALM, .type = XTTYPE_STRING,
.flags = XTOPT_MAND | XTOPT_INVERT},
XTOPT_TABLEEND,
};
/* array of realms from /etc/iproute2/rt_realms */
static struct xtables_lmap *realms;
static void realm_init(struct xt_entry_match *m)
{
const char file[] = "/etc/iproute2/rt_realms";
realms = xtables_lmap_init(file);
if (realms == NULL && errno != ENOENT)
fprintf(stderr, "Warning: %s: %s\n", file, strerror(errno));
}
static void realm_parse(struct xt_option_call *cb)
{
struct xt_realm_info *realminfo = cb->data;
int id;
char *end;
xtables_option_parse(cb);
realminfo->id = strtoul(cb->arg, &end, 0);
if (end != cb->arg && (*end == '/' || *end == '\0')) {
if (*end == '/')
realminfo->mask = strtoul(end+1, &end, 0);
else
realminfo->mask = 0xffffffff;
if (*end != '\0' || end == cb->arg)
xtables_error(PARAMETER_PROBLEM,
"Bad realm value \"%s\"", cb->arg);
} else {
id = xtables_lmap_name2id(realms, cb->arg);
if (id == -1)
xtables_error(PARAMETER_PROBLEM,
"Realm \"%s\" not found", cb->arg);
realminfo->id = id;
realminfo->mask = 0xffffffff;
}
if (cb->invert)
realminfo->invert = 1;
}
static void
print_realm(unsigned long id, unsigned long mask, int numeric)
{
const char* name = NULL;
if (mask != 0xffffffff)
printf(" 0x%lx/0x%lx", id, mask);
else {
if (numeric == 0)
name = xtables_lmap_id2name(realms, id);
if (name)
printf(" %s", name);
else
printf(" 0x%lx", id);
}
}
static void realm_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
const struct xt_realm_info *ri = (const void *)match->data;
if (ri->invert)
printf(" !");
printf(" realm");
print_realm(ri->id, ri->mask, numeric);
}
static void realm_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_realm_info *ri = (const void *)match->data;
if (ri->invert)
printf(" !");
printf(" --realm");
print_realm(ri->id, ri->mask, 0);
}
static struct xtables_match realm_mt_reg = {
.name = "realm",
.version = XTABLES_VERSION,
.family = NFPROTO_IPV4,
.size = XT_ALIGN(sizeof(struct xt_realm_info)),
.userspacesize = XT_ALIGN(sizeof(struct xt_realm_info)),
.help = realm_help,
.init = realm_init,
.print = realm_print,
.save = realm_save,
.x6_parse = realm_parse,
.x6_options = realm_opts,
};
void _init(void)
{
xtables_register_match(&realm_mt_reg);
}
|
306 | ./android_firewall/external/iptables/extensions/libxt_CONNMARK.c | /* Shared library add-on to iptables to add CONNMARK target support.
*
* (C) 2002,2004 MARA Systems AB <http://www.marasystems.com>
* by Henrik Nordstrom <[email protected]>
*
* Version 1.1
*
* 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
*/
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <xtables.h>
#include <linux/netfilter/xt_CONNMARK.h>
struct xt_connmark_target_info {
unsigned long mark;
unsigned long mask;
uint8_t mode;
};
enum {
O_SET_MARK = 0,
O_SAVE_MARK,
O_RESTORE_MARK,
O_AND_MARK,
O_OR_MARK,
O_XOR_MARK,
O_SET_XMARK,
O_CTMASK,
O_NFMASK,
O_MASK,
F_SET_MARK = 1 << O_SET_MARK,
F_SAVE_MARK = 1 << O_SAVE_MARK,
F_RESTORE_MARK = 1 << O_RESTORE_MARK,
F_AND_MARK = 1 << O_AND_MARK,
F_OR_MARK = 1 << O_OR_MARK,
F_XOR_MARK = 1 << O_XOR_MARK,
F_SET_XMARK = 1 << O_SET_XMARK,
F_CTMASK = 1 << O_CTMASK,
F_NFMASK = 1 << O_NFMASK,
F_MASK = 1 << O_MASK,
F_OP_ANY = F_SET_MARK | F_SAVE_MARK | F_RESTORE_MARK |
F_AND_MARK | F_OR_MARK | F_XOR_MARK | F_SET_XMARK,
};
static void CONNMARK_help(void)
{
printf(
"CONNMARK target options:\n"
" --set-mark value[/mask] Set conntrack mark value\n"
" --save-mark [--mask mask] Save the packet nfmark in the connection\n"
" --restore-mark [--mask mask] Restore saved nfmark value\n");
}
#define s struct xt_connmark_target_info
static const struct xt_option_entry CONNMARK_opts[] = {
{.name = "set-mark", .id = O_SET_MARK, .type = XTTYPE_MARKMASK32,
.excl = F_OP_ANY},
{.name = "save-mark", .id = O_SAVE_MARK, .type = XTTYPE_NONE,
.excl = F_OP_ANY},
{.name = "restore-mark", .id = O_RESTORE_MARK, .type = XTTYPE_NONE,
.excl = F_OP_ANY},
{.name = "mask", .id = O_MASK, .type = XTTYPE_UINT32},
XTOPT_TABLEEND,
};
#undef s
#define s struct xt_connmark_tginfo1
static const struct xt_option_entry connmark_tg_opts[] = {
{.name = "set-xmark", .id = O_SET_XMARK, .type = XTTYPE_MARKMASK32,
.excl = F_OP_ANY},
{.name = "set-mark", .id = O_SET_MARK, .type = XTTYPE_MARKMASK32,
.excl = F_OP_ANY},
{.name = "and-mark", .id = O_AND_MARK, .type = XTTYPE_UINT32,
.excl = F_OP_ANY},
{.name = "or-mark", .id = O_OR_MARK, .type = XTTYPE_UINT32,
.excl = F_OP_ANY},
{.name = "xor-mark", .id = O_XOR_MARK, .type = XTTYPE_UINT32,
.excl = F_OP_ANY},
{.name = "save-mark", .id = O_SAVE_MARK, .type = XTTYPE_NONE,
.excl = F_OP_ANY},
{.name = "restore-mark", .id = O_RESTORE_MARK, .type = XTTYPE_NONE,
.excl = F_OP_ANY},
{.name = "ctmask", .id = O_CTMASK, .type = XTTYPE_UINT32,
.excl = F_MASK, .flags = XTOPT_PUT, XTOPT_POINTER(s, ctmask)},
{.name = "nfmask", .id = O_NFMASK, .type = XTTYPE_UINT32,
.excl = F_MASK, .flags = XTOPT_PUT, XTOPT_POINTER(s, nfmask)},
{.name = "mask", .id = O_MASK, .type = XTTYPE_UINT32,
.excl = F_CTMASK | F_NFMASK},
XTOPT_TABLEEND,
};
#undef s
static void connmark_tg_help(void)
{
printf(
"CONNMARK target options:\n"
" --set-xmark value[/ctmask] Zero mask bits and XOR ctmark with value\n"
" --save-mark [--ctmask mask] [--nfmask mask]\n"
" Copy ctmark to nfmark using masks\n"
" --restore-mark [--ctmask mask] [--nfmask mask]\n"
" Copy nfmark to ctmark using masks\n"
" --set-mark value[/mask] Set conntrack mark value\n"
" --save-mark [--mask mask] Save the packet nfmark in the connection\n"
" --restore-mark [--mask mask] Restore saved nfmark value\n"
" --and-mark value Binary AND the ctmark with bits\n"
" --or-mark value Binary OR the ctmark with bits\n"
" --xor-mark value Binary XOR the ctmark with bits\n"
);
}
static void connmark_tg_init(struct xt_entry_target *target)
{
struct xt_connmark_tginfo1 *info = (void *)target->data;
/*
* Need these defaults for --save-mark/--restore-mark if no
* --ctmark or --nfmask is given.
*/
info->ctmask = UINT32_MAX;
info->nfmask = UINT32_MAX;
}
static void CONNMARK_parse(struct xt_option_call *cb)
{
struct xt_connmark_target_info *markinfo = cb->data;
xtables_option_parse(cb);
switch (cb->entry->id) {
case O_SET_MARK:
markinfo->mode = XT_CONNMARK_SET;
markinfo->mark = cb->val.mark;
markinfo->mask = cb->val.mask;
break;
case O_SAVE_MARK:
markinfo->mode = XT_CONNMARK_SAVE;
break;
case O_RESTORE_MARK:
markinfo->mode = XT_CONNMARK_RESTORE;
break;
case O_MASK:
markinfo->mask = cb->val.u32;
break;
}
}
static void connmark_tg_parse(struct xt_option_call *cb)
{
struct xt_connmark_tginfo1 *info = cb->data;
xtables_option_parse(cb);
switch (cb->entry->id) {
case O_SET_XMARK:
info->mode = XT_CONNMARK_SET;
info->ctmark = cb->val.mark;
info->ctmask = cb->val.mask;
break;
case O_SET_MARK:
info->mode = XT_CONNMARK_SET;
info->ctmark = cb->val.mark;
info->ctmask = cb->val.mark | cb->val.mask;
break;
case O_AND_MARK:
info->mode = XT_CONNMARK_SET;
info->ctmark = 0;
info->ctmask = ~cb->val.u32;
break;
case O_OR_MARK:
info->mode = XT_CONNMARK_SET;
info->ctmark = cb->val.u32;
info->ctmask = cb->val.u32;
break;
case O_XOR_MARK:
info->mode = XT_CONNMARK_SET;
info->ctmark = cb->val.u32;
info->ctmask = 0;
break;
case O_SAVE_MARK:
info->mode = XT_CONNMARK_SAVE;
break;
case O_RESTORE_MARK:
info->mode = XT_CONNMARK_RESTORE;
break;
case O_MASK:
info->nfmask = info->ctmask = cb->val.u32;
break;
}
}
static void connmark_tg_check(struct xt_fcheck_call *cb)
{
if (!(cb->xflags & F_OP_ANY))
xtables_error(PARAMETER_PROBLEM,
"CONNMARK target: No operation specified");
}
static void
print_mark(unsigned long mark)
{
printf("0x%lx", mark);
}
static void
print_mask(const char *text, unsigned long mask)
{
if (mask != 0xffffffffUL)
printf("%s0x%lx", text, mask);
}
static void CONNMARK_print(const void *ip,
const struct xt_entry_target *target, int numeric)
{
const struct xt_connmark_target_info *markinfo =
(const struct xt_connmark_target_info *)target->data;
switch (markinfo->mode) {
case XT_CONNMARK_SET:
printf(" CONNMARK set ");
print_mark(markinfo->mark);
print_mask("/", markinfo->mask);
break;
case XT_CONNMARK_SAVE:
printf(" CONNMARK save ");
print_mask("mask ", markinfo->mask);
break;
case XT_CONNMARK_RESTORE:
printf(" CONNMARK restore ");
print_mask("mask ", markinfo->mask);
break;
default:
printf(" ERROR: UNKNOWN CONNMARK MODE");
break;
}
}
static void
connmark_tg_print(const void *ip, const struct xt_entry_target *target,
int numeric)
{
const struct xt_connmark_tginfo1 *info = (const void *)target->data;
switch (info->mode) {
case XT_CONNMARK_SET:
if (info->ctmark == 0)
printf(" CONNMARK and 0x%x",
(unsigned int)(uint32_t)~info->ctmask);
else if (info->ctmark == info->ctmask)
printf(" CONNMARK or 0x%x", info->ctmark);
else if (info->ctmask == 0)
printf(" CONNMARK xor 0x%x", info->ctmark);
else if (info->ctmask == 0xFFFFFFFFU)
printf(" CONNMARK set 0x%x", info->ctmark);
else
printf(" CONNMARK xset 0x%x/0x%x",
info->ctmark, info->ctmask);
break;
case XT_CONNMARK_SAVE:
if (info->nfmask == UINT32_MAX && info->ctmask == UINT32_MAX)
printf(" CONNMARK save");
else if (info->nfmask == info->ctmask)
printf(" CONNMARK save mask 0x%x", info->nfmask);
else
printf(" CONNMARK save nfmask 0x%x ctmask ~0x%x",
info->nfmask, info->ctmask);
break;
case XT_CONNMARK_RESTORE:
if (info->ctmask == UINT32_MAX && info->nfmask == UINT32_MAX)
printf(" CONNMARK restore");
else if (info->ctmask == info->nfmask)
printf(" CONNMARK restore mask 0x%x", info->ctmask);
else
printf(" CONNMARK restore ctmask 0x%x nfmask ~0x%x",
info->ctmask, info->nfmask);
break;
default:
printf(" ERROR: UNKNOWN CONNMARK MODE");
break;
}
}
static void CONNMARK_save(const void *ip, const struct xt_entry_target *target)
{
const struct xt_connmark_target_info *markinfo =
(const struct xt_connmark_target_info *)target->data;
switch (markinfo->mode) {
case XT_CONNMARK_SET:
printf(" --set-mark ");
print_mark(markinfo->mark);
print_mask("/", markinfo->mask);
break;
case XT_CONNMARK_SAVE:
printf(" --save-mark ");
print_mask("--mask ", markinfo->mask);
break;
case XT_CONNMARK_RESTORE:
printf(" --restore-mark ");
print_mask("--mask ", markinfo->mask);
break;
default:
printf(" ERROR: UNKNOWN CONNMARK MODE");
break;
}
}
static void CONNMARK_init(struct xt_entry_target *t)
{
struct xt_connmark_target_info *markinfo
= (struct xt_connmark_target_info *)t->data;
markinfo->mask = 0xffffffffUL;
}
static void
connmark_tg_save(const void *ip, const struct xt_entry_target *target)
{
const struct xt_connmark_tginfo1 *info = (const void *)target->data;
switch (info->mode) {
case XT_CONNMARK_SET:
printf(" --set-xmark 0x%x/0x%x", info->ctmark, info->ctmask);
break;
case XT_CONNMARK_SAVE:
printf(" --save-mark --nfmask 0x%x --ctmask 0x%x",
info->nfmask, info->ctmask);
break;
case XT_CONNMARK_RESTORE:
printf(" --restore-mark --nfmask 0x%x --ctmask 0x%x",
info->nfmask, info->ctmask);
break;
default:
printf(" ERROR: UNKNOWN CONNMARK MODE");
break;
}
}
static struct xtables_target connmark_tg_reg[] = {
{
.family = NFPROTO_UNSPEC,
.name = "CONNMARK",
.revision = 0,
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof(struct xt_connmark_target_info)),
.userspacesize = XT_ALIGN(sizeof(struct xt_connmark_target_info)),
.help = CONNMARK_help,
.init = CONNMARK_init,
.print = CONNMARK_print,
.save = CONNMARK_save,
.x6_parse = CONNMARK_parse,
.x6_fcheck = connmark_tg_check,
.x6_options = CONNMARK_opts,
},
{
.version = XTABLES_VERSION,
.name = "CONNMARK",
.revision = 1,
.family = NFPROTO_UNSPEC,
.size = XT_ALIGN(sizeof(struct xt_connmark_tginfo1)),
.userspacesize = XT_ALIGN(sizeof(struct xt_connmark_tginfo1)),
.help = connmark_tg_help,
.init = connmark_tg_init,
.print = connmark_tg_print,
.save = connmark_tg_save,
.x6_parse = connmark_tg_parse,
.x6_fcheck = connmark_tg_check,
.x6_options = connmark_tg_opts,
},
};
void _init(void)
{
xtables_register_targets(connmark_tg_reg, ARRAY_SIZE(connmark_tg_reg));
}
|
307 | ./android_firewall/external/iptables/extensions/libip6t_ah.c | #include <stdio.h>
#include <xtables.h>
#include <linux/netfilter_ipv6/ip6t_ah.h>
enum {
O_AHSPI = 0,
O_AHLEN,
O_AHRES,
};
static void ah_help(void)
{
printf(
"ah match options:\n"
"[!] --ahspi spi[:spi] match spi (range)\n"
"[!] --ahlen length total length of this header\n"
" --ahres check the reserved field too\n");
}
#define s struct ip6t_ah
static const struct xt_option_entry ah_opts[] = {
{.name = "ahspi", .id = O_AHSPI, .type = XTTYPE_UINT32RC,
.flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, spis)},
{.name = "ahlen", .id = O_AHLEN, .type = XTTYPE_UINT32,
.flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, hdrlen)},
{.name = "ahres", .id = O_AHRES, .type = XTTYPE_NONE},
XTOPT_TABLEEND,
};
#undef s
static void ah_parse(struct xt_option_call *cb)
{
struct ip6t_ah *ahinfo = cb->data;
xtables_option_parse(cb);
switch (cb->entry->id) {
case O_AHSPI:
if (cb->nvals == 1)
ahinfo->spis[1] = ahinfo->spis[0];
if (cb->invert)
ahinfo->invflags |= IP6T_AH_INV_SPI;
break;
case O_AHLEN:
if (cb->invert)
ahinfo->invflags |= IP6T_AH_INV_LEN;
break;
case O_AHRES:
ahinfo->hdrres = 1;
break;
}
}
static void
print_spis(const char *name, uint32_t min, uint32_t max,
int invert)
{
const char *inv = invert ? "!" : "";
if (min != 0 || max != 0xFFFFFFFF || invert) {
if (min == max)
printf("%s:%s%u", name, inv, min);
else
printf("%ss:%s%u:%u", name, inv, min, max);
}
}
static void
print_len(const char *name, uint32_t len, int invert)
{
const char *inv = invert ? "!" : "";
if (len != 0 || invert)
printf("%s:%s%u", name, inv, len);
}
static void ah_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
const struct ip6t_ah *ah = (struct ip6t_ah *)match->data;
printf(" ah ");
print_spis("spi", ah->spis[0], ah->spis[1],
ah->invflags & IP6T_AH_INV_SPI);
print_len("length", ah->hdrlen,
ah->invflags & IP6T_AH_INV_LEN);
if (ah->hdrres)
printf(" reserved");
if (ah->invflags & ~IP6T_AH_INV_MASK)
printf(" Unknown invflags: 0x%X",
ah->invflags & ~IP6T_AH_INV_MASK);
}
static void ah_save(const void *ip, const struct xt_entry_match *match)
{
const struct ip6t_ah *ahinfo = (struct ip6t_ah *)match->data;
if (!(ahinfo->spis[0] == 0
&& ahinfo->spis[1] == 0xFFFFFFFF)) {
printf("%s --ahspi ",
(ahinfo->invflags & IP6T_AH_INV_SPI) ? " !" : "");
if (ahinfo->spis[0]
!= ahinfo->spis[1])
printf("%u:%u",
ahinfo->spis[0],
ahinfo->spis[1]);
else
printf("%u",
ahinfo->spis[0]);
}
if (ahinfo->hdrlen != 0 || (ahinfo->invflags & IP6T_AH_INV_LEN) ) {
printf("%s --ahlen %u",
(ahinfo->invflags & IP6T_AH_INV_LEN) ? " !" : "",
ahinfo->hdrlen);
}
if (ahinfo->hdrres != 0 )
printf(" --ahres");
}
static struct xtables_match ah_mt6_reg = {
.name = "ah",
.version = XTABLES_VERSION,
.family = NFPROTO_IPV6,
.size = XT_ALIGN(sizeof(struct ip6t_ah)),
.userspacesize = XT_ALIGN(sizeof(struct ip6t_ah)),
.help = ah_help,
.print = ah_print,
.save = ah_save,
.x6_parse = ah_parse,
.x6_options = ah_opts,
};
void
_init(void)
{
xtables_register_match(&ah_mt6_reg);
}
|
308 | ./android_firewall/external/iptables/extensions/libxt_iprange.c | #include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <xtables.h>
#include <linux/netfilter.h>
#include <linux/netfilter/xt_iprange.h>
struct ipt_iprange {
/* Inclusive: network order. */
__be32 min_ip, max_ip;
};
struct ipt_iprange_info {
struct ipt_iprange src;
struct ipt_iprange dst;
/* Flags from above */
uint8_t flags;
};
enum {
O_SRC_RANGE = 0,
O_DST_RANGE,
};
static void iprange_mt_help(void)
{
printf(
"iprange match options:\n"
"[!] --src-range ip[-ip] Match source IP in the specified range\n"
"[!] --dst-range ip[-ip] Match destination IP in the specified range\n");
}
static const struct xt_option_entry iprange_mt_opts[] = {
{.name = "src-range", .id = O_SRC_RANGE, .type = XTTYPE_STRING,
.flags = XTOPT_INVERT},
{.name = "dst-range", .id = O_DST_RANGE, .type = XTTYPE_STRING,
.flags = XTOPT_INVERT},
XTOPT_TABLEEND,
};
static void
iprange_parse_spec(const char *from, const char *to, union nf_inet_addr *range,
uint8_t family, const char *optname)
{
const char *spec[2] = {from, to};
struct in6_addr *ia6;
struct in_addr *ia4;
unsigned int i;
memset(range, 0, sizeof(union nf_inet_addr) * 2);
if (family == NFPROTO_IPV6) {
for (i = 0; i < ARRAY_SIZE(spec); ++i) {
ia6 = xtables_numeric_to_ip6addr(spec[i]);
if (ia6 == NULL)
xtables_param_act(XTF_BAD_VALUE, "iprange",
optname, spec[i]);
range[i].in6 = *ia6;
}
} else {
for (i = 0; i < ARRAY_SIZE(spec); ++i) {
ia4 = xtables_numeric_to_ipaddr(spec[i]);
if (ia4 == NULL)
xtables_param_act(XTF_BAD_VALUE, "iprange",
optname, spec[i]);
range[i].in = *ia4;
}
}
}
static void iprange_parse_range(const char *oarg, union nf_inet_addr *range,
uint8_t family, const char *optname)
{
char *arg = strdup(oarg);
char *dash;
if (arg == NULL)
xtables_error(RESOURCE_PROBLEM, "strdup");
dash = strchr(arg, '-');
if (dash == NULL) {
iprange_parse_spec(arg, arg, range, family, optname);
free(arg);
return;
}
*dash = '\0';
iprange_parse_spec(arg, dash + 1, range, family, optname);
if (memcmp(&range[0], &range[1], sizeof(*range)) > 0)
fprintf(stderr, "xt_iprange: range %s-%s is reversed and "
"will never match\n", arg, dash + 1);
free(arg);
}
static void iprange_parse(struct xt_option_call *cb)
{
struct ipt_iprange_info *info = cb->data;
union nf_inet_addr range[2];
xtables_option_parse(cb);
switch (cb->entry->id) {
case O_SRC_RANGE:
info->flags |= IPRANGE_SRC;
if (cb->invert)
info->flags |= IPRANGE_SRC_INV;
iprange_parse_range(cb->arg, range, NFPROTO_IPV4, "--src-range");
info->src.min_ip = range[0].ip;
info->src.max_ip = range[1].ip;
break;
case O_DST_RANGE:
info->flags |= IPRANGE_DST;
if (cb->invert)
info->flags |= IPRANGE_DST_INV;
iprange_parse_range(cb->arg, range, NFPROTO_IPV4, "--dst-range");
info->dst.min_ip = range[0].ip;
info->dst.max_ip = range[1].ip;
break;
}
}
static void iprange_mt_parse(struct xt_option_call *cb, uint8_t nfproto)
{
struct xt_iprange_mtinfo *info = cb->data;
xtables_option_parse(cb);
switch (cb->entry->id) {
case O_SRC_RANGE:
iprange_parse_range(cb->arg, &info->src_min, nfproto,
"--src-range");
info->flags |= IPRANGE_SRC;
if (cb->invert)
info->flags |= IPRANGE_SRC_INV;
break;
case O_DST_RANGE:
iprange_parse_range(cb->arg, &info->dst_min, nfproto,
"--dst-range");
info->flags |= IPRANGE_DST;
if (cb->invert)
info->flags |= IPRANGE_DST_INV;
break;
}
}
static void iprange_mt4_parse(struct xt_option_call *cb)
{
iprange_mt_parse(cb, NFPROTO_IPV4);
}
static void iprange_mt6_parse(struct xt_option_call *cb)
{
iprange_mt_parse(cb, NFPROTO_IPV6);
}
static void iprange_mt_check(struct xt_fcheck_call *cb)
{
if (cb->xflags == 0)
xtables_error(PARAMETER_PROBLEM,
"iprange match: You must specify `--src-range' or `--dst-range'");
}
static void
print_iprange(const struct ipt_iprange *range)
{
const unsigned char *byte_min, *byte_max;
byte_min = (const unsigned char *)&range->min_ip;
byte_max = (const unsigned char *)&range->max_ip;
printf(" %u.%u.%u.%u-%u.%u.%u.%u",
byte_min[0], byte_min[1], byte_min[2], byte_min[3],
byte_max[0], byte_max[1], byte_max[2], byte_max[3]);
}
static void iprange_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
const struct ipt_iprange_info *info = (const void *)match->data;
if (info->flags & IPRANGE_SRC) {
printf(" source IP range");
if (info->flags & IPRANGE_SRC_INV)
printf(" !");
print_iprange(&info->src);
}
if (info->flags & IPRANGE_DST) {
printf(" destination IP range");
if (info->flags & IPRANGE_DST_INV)
printf(" !");
print_iprange(&info->dst);
}
}
static void
iprange_mt4_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
const struct xt_iprange_mtinfo *info = (const void *)match->data;
if (info->flags & IPRANGE_SRC) {
printf(" source IP range");
if (info->flags & IPRANGE_SRC_INV)
printf(" !");
/*
* ipaddr_to_numeric() uses a static buffer, so cannot
* combine the printf() calls.
*/
printf(" %s", xtables_ipaddr_to_numeric(&info->src_min.in));
printf("-%s", xtables_ipaddr_to_numeric(&info->src_max.in));
}
if (info->flags & IPRANGE_DST) {
printf(" destination IP range");
if (info->flags & IPRANGE_DST_INV)
printf(" !");
printf(" %s", xtables_ipaddr_to_numeric(&info->dst_min.in));
printf("-%s", xtables_ipaddr_to_numeric(&info->dst_max.in));
}
}
static void
iprange_mt6_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
const struct xt_iprange_mtinfo *info = (const void *)match->data;
if (info->flags & IPRANGE_SRC) {
printf(" source IP range");
if (info->flags & IPRANGE_SRC_INV)
printf(" !");
/*
* ipaddr_to_numeric() uses a static buffer, so cannot
* combine the printf() calls.
*/
printf(" %s", xtables_ip6addr_to_numeric(&info->src_min.in6));
printf("-%s", xtables_ip6addr_to_numeric(&info->src_max.in6));
}
if (info->flags & IPRANGE_DST) {
printf(" destination IP range");
if (info->flags & IPRANGE_DST_INV)
printf(" !");
printf(" %s", xtables_ip6addr_to_numeric(&info->dst_min.in6));
printf("-%s", xtables_ip6addr_to_numeric(&info->dst_max.in6));
}
}
static void iprange_save(const void *ip, const struct xt_entry_match *match)
{
const struct ipt_iprange_info *info = (const void *)match->data;
if (info->flags & IPRANGE_SRC) {
if (info->flags & IPRANGE_SRC_INV)
printf(" !");
printf(" --src-range");
print_iprange(&info->src);
}
if (info->flags & IPRANGE_DST) {
if (info->flags & IPRANGE_DST_INV)
printf(" !");
printf(" --dst-range");
print_iprange(&info->dst);
}
}
static void iprange_mt4_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_iprange_mtinfo *info = (const void *)match->data;
if (info->flags & IPRANGE_SRC) {
if (info->flags & IPRANGE_SRC_INV)
printf(" !");
printf(" --src-range %s", xtables_ipaddr_to_numeric(&info->src_min.in));
printf("-%s", xtables_ipaddr_to_numeric(&info->src_max.in));
}
if (info->flags & IPRANGE_DST) {
if (info->flags & IPRANGE_DST_INV)
printf(" !");
printf(" --dst-range %s", xtables_ipaddr_to_numeric(&info->dst_min.in));
printf("-%s", xtables_ipaddr_to_numeric(&info->dst_max.in));
}
}
static void iprange_mt6_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_iprange_mtinfo *info = (const void *)match->data;
if (info->flags & IPRANGE_SRC) {
if (info->flags & IPRANGE_SRC_INV)
printf(" !");
printf(" --src-range %s", xtables_ip6addr_to_numeric(&info->src_min.in6));
printf("-%s", xtables_ip6addr_to_numeric(&info->src_max.in6));
}
if (info->flags & IPRANGE_DST) {
if (info->flags & IPRANGE_DST_INV)
printf(" !");
printf(" --dst-range %s", xtables_ip6addr_to_numeric(&info->dst_min.in6));
printf("-%s", xtables_ip6addr_to_numeric(&info->dst_max.in6));
}
}
static struct xtables_match iprange_mt_reg[] = {
{
.version = XTABLES_VERSION,
.name = "iprange",
.revision = 0,
.family = NFPROTO_IPV4,
.size = XT_ALIGN(sizeof(struct ipt_iprange_info)),
.userspacesize = XT_ALIGN(sizeof(struct ipt_iprange_info)),
.help = iprange_mt_help,
.x6_parse = iprange_parse,
.x6_fcheck = iprange_mt_check,
.print = iprange_print,
.save = iprange_save,
.x6_options = iprange_mt_opts,
},
{
.version = XTABLES_VERSION,
.name = "iprange",
.revision = 1,
.family = NFPROTO_IPV4,
.size = XT_ALIGN(sizeof(struct xt_iprange_mtinfo)),
.userspacesize = XT_ALIGN(sizeof(struct xt_iprange_mtinfo)),
.help = iprange_mt_help,
.x6_parse = iprange_mt4_parse,
.x6_fcheck = iprange_mt_check,
.print = iprange_mt4_print,
.save = iprange_mt4_save,
.x6_options = iprange_mt_opts,
},
{
.version = XTABLES_VERSION,
.name = "iprange",
.revision = 1,
.family = NFPROTO_IPV6,
.size = XT_ALIGN(sizeof(struct xt_iprange_mtinfo)),
.userspacesize = XT_ALIGN(sizeof(struct xt_iprange_mtinfo)),
.help = iprange_mt_help,
.x6_parse = iprange_mt6_parse,
.x6_fcheck = iprange_mt_check,
.print = iprange_mt6_print,
.save = iprange_mt6_save,
.x6_options = iprange_mt_opts,
},
};
void _init(void)
{
xtables_register_matches(iprange_mt_reg, ARRAY_SIZE(iprange_mt_reg));
}
|
309 | ./android_firewall/external/iptables/extensions/libxt_socket.c | /*
* Shared library add-on to iptables to add early socket matching support.
*
* Copyright (C) 2007 BalaBit IT Ltd.
*/
#include <stdio.h>
#include <xtables.h>
#include <linux/netfilter/xt_socket.h>
enum {
O_TRANSPARENT = 0,
};
static const struct xt_option_entry socket_mt_opts[] = {
{.name = "transparent", .id = O_TRANSPARENT, .type = XTTYPE_NONE},
XTOPT_TABLEEND,
};
static void socket_mt_help(void)
{
printf(
"socket match options:\n"
" --transparent Ignore non-transparent sockets\n\n");
}
static void socket_mt_parse(struct xt_option_call *cb)
{
struct xt_socket_mtinfo1 *info = cb->data;
xtables_option_parse(cb);
switch (cb->entry->id) {
case O_TRANSPARENT:
info->flags |= XT_SOCKET_TRANSPARENT;
break;
}
}
static void
socket_mt_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_socket_mtinfo1 *info = (const void *)match->data;
if (info->flags & XT_SOCKET_TRANSPARENT)
printf(" --transparent");
}
static void
socket_mt_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
printf(" socket");
socket_mt_save(ip, match);
}
static struct xtables_match socket_mt_reg[] = {
{
.name = "socket",
.revision = 0,
.family = NFPROTO_IPV4,
.version = XTABLES_VERSION,
.size = XT_ALIGN(0),
.userspacesize = XT_ALIGN(0),
},
{
.name = "socket",
.revision = 1,
.family = NFPROTO_UNSPEC,
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof(struct xt_socket_mtinfo1)),
.userspacesize = XT_ALIGN(sizeof(struct xt_socket_mtinfo1)),
.help = socket_mt_help,
.print = socket_mt_print,
.save = socket_mt_save,
.x6_parse = socket_mt_parse,
.x6_options = socket_mt_opts,
},
};
void _init(void)
{
xtables_register_matches(socket_mt_reg, ARRAY_SIZE(socket_mt_reg));
}
|
310 | ./android_firewall/external/iptables/extensions/libxt_CHECKSUM.c | /* Shared library add-on to xtables for CHECKSUM
*
* (C) 2002 by Harald Welte <[email protected]>
* (C) 2010 by Red Hat, Inc
* Author: Michael S. Tsirkin <[email protected]>
*
* This program is distributed under the terms of GNU GPL v2, 1991
*
* libxt_CHECKSUM.c borrowed some bits from libipt_ECN.c
*/
#include <stdio.h>
#include <xtables.h>
#include <linux/netfilter/xt_CHECKSUM.h>
enum {
O_CHECKSUM_FILL = 0,
};
static void CHECKSUM_help(void)
{
printf(
"CHECKSUM target options\n"
" --checksum-fill Fill in packet checksum.\n");
}
static const struct xt_option_entry CHECKSUM_opts[] = {
{.name = "checksum-fill", .id = O_CHECKSUM_FILL,
.flags = XTOPT_MAND, .type = XTTYPE_NONE},
XTOPT_TABLEEND,
};
static void CHECKSUM_parse(struct xt_option_call *cb)
{
struct xt_CHECKSUM_info *einfo = cb->data;
xtables_option_parse(cb);
einfo->operation = XT_CHECKSUM_OP_FILL;
}
static void CHECKSUM_print(const void *ip, const struct xt_entry_target *target,
int numeric)
{
const struct xt_CHECKSUM_info *einfo =
(const struct xt_CHECKSUM_info *)target->data;
printf(" CHECKSUM");
if (einfo->operation & XT_CHECKSUM_OP_FILL)
printf(" fill");
}
static void CHECKSUM_save(const void *ip, const struct xt_entry_target *target)
{
const struct xt_CHECKSUM_info *einfo =
(const struct xt_CHECKSUM_info *)target->data;
if (einfo->operation & XT_CHECKSUM_OP_FILL)
printf(" --checksum-fill");
}
static struct xtables_target checksum_tg_reg = {
.name = "CHECKSUM",
.version = XTABLES_VERSION,
.family = NFPROTO_UNSPEC,
.size = XT_ALIGN(sizeof(struct xt_CHECKSUM_info)),
.userspacesize = XT_ALIGN(sizeof(struct xt_CHECKSUM_info)),
.help = CHECKSUM_help,
.print = CHECKSUM_print,
.save = CHECKSUM_save,
.x6_parse = CHECKSUM_parse,
.x6_options = CHECKSUM_opts,
};
void _init(void)
{
xtables_register_target(&checksum_tg_reg);
}
|
311 | ./android_firewall/external/iptables/extensions/libxt_connbytes.c | #include <stdio.h>
#include <string.h>
#include <xtables.h>
#include <linux/netfilter/xt_connbytes.h>
enum {
O_CONNBYTES = 0,
O_CONNBYTES_DIR,
O_CONNBYTES_MODE,
};
static void connbytes_help(void)
{
printf(
"connbytes match options:\n"
" [!] --connbytes from:[to]\n"
" --connbytes-dir [original, reply, both]\n"
" --connbytes-mode [packets, bytes, avgpkt]\n");
}
static const struct xt_option_entry connbytes_opts[] = {
{.name = "connbytes", .id = O_CONNBYTES, .type = XTTYPE_UINT64RC,
.flags = XTOPT_MAND | XTOPT_INVERT},
{.name = "connbytes-dir", .id = O_CONNBYTES_DIR, .type = XTTYPE_STRING,
.flags = XTOPT_MAND},
{.name = "connbytes-mode", .id = O_CONNBYTES_MODE,
.type = XTTYPE_STRING, .flags = XTOPT_MAND},
XTOPT_TABLEEND,
};
static void connbytes_parse(struct xt_option_call *cb)
{
struct xt_connbytes_info *sinfo = cb->data;
unsigned long long i;
xtables_option_parse(cb);
switch (cb->entry->id) {
case O_CONNBYTES:
sinfo->count.from = cb->val.u64_range[0];
sinfo->count.to = UINT64_MAX;
if (cb->nvals == 2)
sinfo->count.to = cb->val.u64_range[1];
if (sinfo->count.to < sinfo->count.from)
xtables_error(PARAMETER_PROBLEM, "%llu should be less than %llu",
(unsigned long long)sinfo->count.from,
(unsigned long long)sinfo->count.to);
if (cb->invert) {
i = sinfo->count.from;
sinfo->count.from = sinfo->count.to;
sinfo->count.to = i;
}
break;
case O_CONNBYTES_DIR:
if (strcmp(cb->arg, "original") == 0)
sinfo->direction = XT_CONNBYTES_DIR_ORIGINAL;
else if (strcmp(cb->arg, "reply") == 0)
sinfo->direction = XT_CONNBYTES_DIR_REPLY;
else if (strcmp(cb->arg, "both") == 0)
sinfo->direction = XT_CONNBYTES_DIR_BOTH;
else
xtables_error(PARAMETER_PROBLEM,
"Unknown --connbytes-dir `%s'", cb->arg);
break;
case O_CONNBYTES_MODE:
if (strcmp(cb->arg, "packets") == 0)
sinfo->what = XT_CONNBYTES_PKTS;
else if (strcmp(cb->arg, "bytes") == 0)
sinfo->what = XT_CONNBYTES_BYTES;
else if (strcmp(cb->arg, "avgpkt") == 0)
sinfo->what = XT_CONNBYTES_AVGPKT;
else
xtables_error(PARAMETER_PROBLEM,
"Unknown --connbytes-mode `%s'", cb->arg);
break;
}
}
static void print_mode(const struct xt_connbytes_info *sinfo)
{
switch (sinfo->what) {
case XT_CONNBYTES_PKTS:
fputs(" packets", stdout);
break;
case XT_CONNBYTES_BYTES:
fputs(" bytes", stdout);
break;
case XT_CONNBYTES_AVGPKT:
fputs(" avgpkt", stdout);
break;
default:
fputs(" unknown", stdout);
break;
}
}
static void print_direction(const struct xt_connbytes_info *sinfo)
{
switch (sinfo->direction) {
case XT_CONNBYTES_DIR_ORIGINAL:
fputs(" original", stdout);
break;
case XT_CONNBYTES_DIR_REPLY:
fputs(" reply", stdout);
break;
case XT_CONNBYTES_DIR_BOTH:
fputs(" both", stdout);
break;
default:
fputs(" unknown", stdout);
break;
}
}
static void print_from_to(const struct xt_connbytes_info *sinfo, const char *prefix)
{
unsigned long long from, to;
if (sinfo->count.from > sinfo->count.to) {
fputs(" !", stdout);
from = sinfo->count.to;
to = sinfo->count.from;
} else {
to = sinfo->count.to;
from = sinfo->count.from;
}
printf(" %sconnbytes %llu", prefix, from);
if (to && to < UINT64_MAX)
printf(":%llu", to);
}
static void
connbytes_print(const void *ip, const struct xt_entry_match *match, int numeric)
{
const struct xt_connbytes_info *sinfo = (const void *)match->data;
print_from_to(sinfo, "");
fputs(" connbytes mode", stdout);
print_mode(sinfo);
fputs(" connbytes direction", stdout);
print_direction(sinfo);
}
static void connbytes_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_connbytes_info *sinfo = (const void *)match->data;
print_from_to(sinfo, "--");
fputs(" --connbytes-mode", stdout);
print_mode(sinfo);
fputs(" --connbytes-dir", stdout);
print_direction(sinfo);
}
static struct xtables_match connbytes_match = {
.family = NFPROTO_UNSPEC,
.name = "connbytes",
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof(struct xt_connbytes_info)),
.userspacesize = XT_ALIGN(sizeof(struct xt_connbytes_info)),
.help = connbytes_help,
.print = connbytes_print,
.save = connbytes_save,
.x6_parse = connbytes_parse,
.x6_options = connbytes_opts,
};
void _init(void)
{
xtables_register_match(&connbytes_match);
}
|
312 | ./android_firewall/external/iptables/extensions/tos_values.c | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <linux/ip.h>
#ifndef IPTOS_NORMALSVC
# define IPTOS_NORMALSVC 0
#endif
struct tos_value_mask {
uint8_t value, mask;
};
static const struct tos_symbol_info {
unsigned char value;
const char *name;
} tos_symbol_names[] = {
{IPTOS_LOWDELAY, "Minimize-Delay"},
{IPTOS_THROUGHPUT, "Maximize-Throughput"},
{IPTOS_RELIABILITY, "Maximize-Reliability"},
{IPTOS_MINCOST, "Minimize-Cost"},
{IPTOS_NORMALSVC, "Normal-Service"},
{},
};
static bool tos_try_print_symbolic(const char *prefix,
uint8_t value, uint8_t mask)
{
const struct tos_symbol_info *symbol;
if (mask != 0x3F)
return false;
for (symbol = tos_symbol_names; symbol->name != NULL; ++symbol)
if (value == symbol->value) {
printf(" %s%s", prefix, symbol->name);
return true;
}
return false;
}
|
313 | ./android_firewall/external/iptables/extensions/libxt_multiport.c | #include <stdio.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <xtables.h>
#include <limits.h> /* INT_MAX in ip_tables.h/ip6_tables.h */
#include <linux/netfilter_ipv4/ip_tables.h>
#include <linux/netfilter_ipv6/ip6_tables.h>
#include <linux/netfilter/xt_multiport.h>
enum {
O_SOURCE_PORTS = 0,
O_DEST_PORTS,
O_SD_PORTS,
F_SOURCE_PORTS = 1 << O_SOURCE_PORTS,
F_DEST_PORTS = 1 << O_DEST_PORTS,
F_SD_PORTS = 1 << O_SD_PORTS,
F_ANY = F_SOURCE_PORTS | F_DEST_PORTS | F_SD_PORTS,
};
/* Function which prints out usage message. */
static void multiport_help(void)
{
printf(
"multiport match options:\n"
" --source-ports port[,port,port...]\n"
" --sports ...\n"
" match source port(s)\n"
" --destination-ports port[,port,port...]\n"
" --dports ...\n"
" match destination port(s)\n"
" --ports port[,port,port]\n"
" match both source and destination port(s)\n"
" NOTE: this kernel does not support port ranges in multiport.\n");
}
static void multiport_help_v1(void)
{
printf(
"multiport match options:\n"
"[!] --source-ports port[,port:port,port...]\n"
" --sports ...\n"
" match source port(s)\n"
"[!] --destination-ports port[,port:port,port...]\n"
" --dports ...\n"
" match destination port(s)\n"
"[!] --ports port[,port:port,port]\n"
" match both source and destination port(s)\n");
}
static const struct xt_option_entry multiport_opts[] = {
{.name = "source-ports", .id = O_SOURCE_PORTS, .type = XTTYPE_STRING,
.excl = F_ANY, .flags = XTOPT_INVERT},
{.name = "sports", .id = O_SOURCE_PORTS, .type = XTTYPE_STRING,
.excl = F_ANY, .flags = XTOPT_INVERT},
{.name = "destination-ports", .id = O_DEST_PORTS,
.type = XTTYPE_STRING, .excl = F_ANY, .flags = XTOPT_INVERT},
{.name = "dports", .id = O_DEST_PORTS, .type = XTTYPE_STRING,
.excl = F_ANY, .flags = XTOPT_INVERT},
{.name = "ports", .id = O_SD_PORTS, .type = XTTYPE_STRING,
.excl = F_ANY, .flags = XTOPT_INVERT},
XTOPT_TABLEEND,
};
static const char *
proto_to_name(uint8_t proto)
{
switch (proto) {
case IPPROTO_TCP:
return "tcp";
case IPPROTO_UDP:
return "udp";
case IPPROTO_UDPLITE:
return "udplite";
case IPPROTO_SCTP:
return "sctp";
case IPPROTO_DCCP:
return "dccp";
default:
return NULL;
}
}
static unsigned int
parse_multi_ports(const char *portstring, uint16_t *ports, const char *proto)
{
char *buffer, *cp, *next;
unsigned int i;
buffer = strdup(portstring);
if (!buffer) xtables_error(OTHER_PROBLEM, "strdup failed");
for (cp=buffer, i=0; cp && i<XT_MULTI_PORTS; cp=next,i++)
{
next=strchr(cp, ',');
if (next) *next++='\0';
ports[i] = xtables_parse_port(cp, proto);
}
if (cp) xtables_error(PARAMETER_PROBLEM, "too many ports specified");
free(buffer);
return i;
}
static void
parse_multi_ports_v1(const char *portstring,
struct xt_multiport_v1 *multiinfo,
const char *proto)
{
char *buffer, *cp, *next, *range;
unsigned int i;
uint16_t m;
buffer = strdup(portstring);
if (!buffer) xtables_error(OTHER_PROBLEM, "strdup failed");
for (i=0; i<XT_MULTI_PORTS; i++)
multiinfo->pflags[i] = 0;
for (cp=buffer, i=0; cp && i<XT_MULTI_PORTS; cp=next, i++) {
next=strchr(cp, ',');
if (next) *next++='\0';
range = strchr(cp, ':');
if (range) {
if (i == XT_MULTI_PORTS-1)
xtables_error(PARAMETER_PROBLEM,
"too many ports specified");
*range++ = '\0';
}
multiinfo->ports[i] = xtables_parse_port(cp, proto);
if (range) {
multiinfo->pflags[i] = 1;
multiinfo->ports[++i] = xtables_parse_port(range, proto);
if (multiinfo->ports[i-1] >= multiinfo->ports[i])
xtables_error(PARAMETER_PROBLEM,
"invalid portrange specified");
m <<= 1;
}
}
multiinfo->count = i;
if (cp) xtables_error(PARAMETER_PROBLEM, "too many ports specified");
free(buffer);
}
static const char *
check_proto(uint16_t pnum, uint8_t invflags)
{
const char *proto;
if (invflags & XT_INV_PROTO)
xtables_error(PARAMETER_PROBLEM,
"multiport only works with TCP, UDP, UDPLITE, SCTP and DCCP");
if ((proto = proto_to_name(pnum)) != NULL)
return proto;
else if (!pnum)
xtables_error(PARAMETER_PROBLEM,
"multiport needs `-p tcp', `-p udp', `-p udplite', "
"`-p sctp' or `-p dccp'");
else
xtables_error(PARAMETER_PROBLEM,
"multiport only works with TCP, UDP, UDPLITE, SCTP and DCCP");
}
static void __multiport_parse(struct xt_option_call *cb, uint16_t pnum,
uint8_t invflags)
{
const char *proto;
struct xt_multiport *multiinfo = cb->data;
xtables_option_parse(cb);
switch (cb->entry->id) {
case O_SOURCE_PORTS:
proto = check_proto(pnum, invflags);
multiinfo->count = parse_multi_ports(cb->arg,
multiinfo->ports, proto);
multiinfo->flags = XT_MULTIPORT_SOURCE;
break;
case O_DEST_PORTS:
proto = check_proto(pnum, invflags);
multiinfo->count = parse_multi_ports(cb->arg,
multiinfo->ports, proto);
multiinfo->flags = XT_MULTIPORT_DESTINATION;
break;
case O_SD_PORTS:
proto = check_proto(pnum, invflags);
multiinfo->count = parse_multi_ports(cb->arg,
multiinfo->ports, proto);
multiinfo->flags = XT_MULTIPORT_EITHER;
break;
}
if (cb->invert)
xtables_error(PARAMETER_PROBLEM,
"multiport.0 does not support invert");
}
static void multiport_parse(struct xt_option_call *cb)
{
const struct ipt_entry *entry = cb->xt_entry;
return __multiport_parse(cb,
entry->ip.proto, entry->ip.invflags);
}
static void multiport_parse6(struct xt_option_call *cb)
{
const struct ip6t_entry *entry = cb->xt_entry;
return __multiport_parse(cb,
entry->ipv6.proto, entry->ipv6.invflags);
}
static void __multiport_parse_v1(struct xt_option_call *cb, uint16_t pnum,
uint8_t invflags)
{
const char *proto;
struct xt_multiport_v1 *multiinfo = cb->data;
xtables_option_parse(cb);
switch (cb->entry->id) {
case O_SOURCE_PORTS:
proto = check_proto(pnum, invflags);
parse_multi_ports_v1(cb->arg, multiinfo, proto);
multiinfo->flags = XT_MULTIPORT_SOURCE;
break;
case O_DEST_PORTS:
proto = check_proto(pnum, invflags);
parse_multi_ports_v1(cb->arg, multiinfo, proto);
multiinfo->flags = XT_MULTIPORT_DESTINATION;
break;
case O_SD_PORTS:
proto = check_proto(pnum, invflags);
parse_multi_ports_v1(cb->arg, multiinfo, proto);
multiinfo->flags = XT_MULTIPORT_EITHER;
break;
}
if (cb->invert)
multiinfo->invert = 1;
}
static void multiport_parse_v1(struct xt_option_call *cb)
{
const struct ipt_entry *entry = cb->xt_entry;
return __multiport_parse_v1(cb,
entry->ip.proto, entry->ip.invflags);
}
static void multiport_parse6_v1(struct xt_option_call *cb)
{
const struct ip6t_entry *entry = cb->xt_entry;
return __multiport_parse_v1(cb,
entry->ipv6.proto, entry->ipv6.invflags);
}
static void multiport_check(struct xt_fcheck_call *cb)
{
if (cb->xflags == 0)
xtables_error(PARAMETER_PROBLEM, "multiport expection an option");
}
static const char *
port_to_service(int port, uint8_t proto)
{
const struct servent *service;
if ((service = getservbyport(htons(port), proto_to_name(proto))))
return service->s_name;
return NULL;
}
static void
print_port(uint16_t port, uint8_t protocol, int numeric)
{
const char *service;
if (numeric || (service = port_to_service(port, protocol)) == NULL)
printf("%u", port);
else
printf("%s", service);
}
static void
__multiport_print(const struct xt_entry_match *match, int numeric,
uint16_t proto)
{
const struct xt_multiport *multiinfo
= (const struct xt_multiport *)match->data;
unsigned int i;
printf(" multiport ");
switch (multiinfo->flags) {
case XT_MULTIPORT_SOURCE:
printf("sports ");
break;
case XT_MULTIPORT_DESTINATION:
printf("dports ");
break;
case XT_MULTIPORT_EITHER:
printf("ports ");
break;
default:
printf("ERROR ");
break;
}
for (i=0; i < multiinfo->count; i++) {
printf("%s", i ? "," : "");
print_port(multiinfo->ports[i], proto, numeric);
}
}
static void multiport_print(const void *ip_void,
const struct xt_entry_match *match, int numeric)
{
const struct ipt_ip *ip = ip_void;
__multiport_print(match, numeric, ip->proto);
}
static void multiport_print6(const void *ip_void,
const struct xt_entry_match *match, int numeric)
{
const struct ip6t_ip6 *ip = ip_void;
__multiport_print(match, numeric, ip->proto);
}
static void __multiport_print_v1(const struct xt_entry_match *match,
int numeric, uint16_t proto)
{
const struct xt_multiport_v1 *multiinfo
= (const struct xt_multiport_v1 *)match->data;
unsigned int i;
printf(" multiport ");
switch (multiinfo->flags) {
case XT_MULTIPORT_SOURCE:
printf("sports ");
break;
case XT_MULTIPORT_DESTINATION:
printf("dports ");
break;
case XT_MULTIPORT_EITHER:
printf("ports ");
break;
default:
printf("ERROR ");
break;
}
if (multiinfo->invert)
printf(" !");
for (i=0; i < multiinfo->count; i++) {
printf("%s", i ? "," : "");
print_port(multiinfo->ports[i], proto, numeric);
if (multiinfo->pflags[i]) {
printf(":");
print_port(multiinfo->ports[++i], proto, numeric);
}
}
}
static void multiport_print_v1(const void *ip_void,
const struct xt_entry_match *match, int numeric)
{
const struct ipt_ip *ip = ip_void;
__multiport_print_v1(match, numeric, ip->proto);
}
static void multiport_print6_v1(const void *ip_void,
const struct xt_entry_match *match, int numeric)
{
const struct ip6t_ip6 *ip = ip_void;
__multiport_print_v1(match, numeric, ip->proto);
}
static void __multiport_save(const struct xt_entry_match *match,
uint16_t proto)
{
const struct xt_multiport *multiinfo
= (const struct xt_multiport *)match->data;
unsigned int i;
switch (multiinfo->flags) {
case XT_MULTIPORT_SOURCE:
printf(" --sports ");
break;
case XT_MULTIPORT_DESTINATION:
printf(" --dports ");
break;
case XT_MULTIPORT_EITHER:
printf(" --ports ");
break;
}
for (i=0; i < multiinfo->count; i++) {
printf("%s", i ? "," : "");
print_port(multiinfo->ports[i], proto, 1);
}
}
static void multiport_save(const void *ip_void,
const struct xt_entry_match *match)
{
const struct ipt_ip *ip = ip_void;
__multiport_save(match, ip->proto);
}
static void multiport_save6(const void *ip_void,
const struct xt_entry_match *match)
{
const struct ip6t_ip6 *ip = ip_void;
__multiport_save(match, ip->proto);
}
static void __multiport_save_v1(const struct xt_entry_match *match,
uint16_t proto)
{
const struct xt_multiport_v1 *multiinfo
= (const struct xt_multiport_v1 *)match->data;
unsigned int i;
if (multiinfo->invert)
printf(" !");
switch (multiinfo->flags) {
case XT_MULTIPORT_SOURCE:
printf(" --sports ");
break;
case XT_MULTIPORT_DESTINATION:
printf(" --dports ");
break;
case XT_MULTIPORT_EITHER:
printf(" --ports ");
break;
}
for (i=0; i < multiinfo->count; i++) {
printf("%s", i ? "," : "");
print_port(multiinfo->ports[i], proto, 1);
if (multiinfo->pflags[i]) {
printf(":");
print_port(multiinfo->ports[++i], proto, 1);
}
}
}
static void multiport_save_v1(const void *ip_void,
const struct xt_entry_match *match)
{
const struct ipt_ip *ip = ip_void;
__multiport_save_v1(match, ip->proto);
}
static void multiport_save6_v1(const void *ip_void,
const struct xt_entry_match *match)
{
const struct ip6t_ip6 *ip = ip_void;
__multiport_save_v1(match, ip->proto);
}
static struct xtables_match multiport_mt_reg[] = {
{
.family = NFPROTO_IPV4,
.name = "multiport",
.revision = 0,
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof(struct xt_multiport)),
.userspacesize = XT_ALIGN(sizeof(struct xt_multiport)),
.help = multiport_help,
.x6_parse = multiport_parse,
.x6_fcheck = multiport_check,
.print = multiport_print,
.save = multiport_save,
.x6_options = multiport_opts,
},
{
.family = NFPROTO_IPV6,
.name = "multiport",
.revision = 0,
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof(struct xt_multiport)),
.userspacesize = XT_ALIGN(sizeof(struct xt_multiport)),
.help = multiport_help,
.x6_parse = multiport_parse6,
.x6_fcheck = multiport_check,
.print = multiport_print6,
.save = multiport_save6,
.x6_options = multiport_opts,
},
{
.family = NFPROTO_IPV4,
.name = "multiport",
.version = XTABLES_VERSION,
.revision = 1,
.size = XT_ALIGN(sizeof(struct xt_multiport_v1)),
.userspacesize = XT_ALIGN(sizeof(struct xt_multiport_v1)),
.help = multiport_help_v1,
.x6_parse = multiport_parse_v1,
.x6_fcheck = multiport_check,
.print = multiport_print_v1,
.save = multiport_save_v1,
.x6_options = multiport_opts,
},
{
.family = NFPROTO_IPV6,
.name = "multiport",
.version = XTABLES_VERSION,
.revision = 1,
.size = XT_ALIGN(sizeof(struct xt_multiport_v1)),
.userspacesize = XT_ALIGN(sizeof(struct xt_multiport_v1)),
.help = multiport_help_v1,
.x6_parse = multiport_parse6_v1,
.x6_fcheck = multiport_check,
.print = multiport_print6_v1,
.save = multiport_save6_v1,
.x6_options = multiport_opts,
},
};
void
_init(void)
{
xtables_register_matches(multiport_mt_reg, ARRAY_SIZE(multiport_mt_reg));
}
|
314 | ./android_firewall/external/iptables/extensions/libxt_conntrack.c | /*
* libxt_conntrack
* Shared library add-on to iptables for conntrack matching support.
*
* GPL (C) 2001 Marc Boucher ([email protected]).
* Copyright © CC Computer Consultants GmbH, 2007 - 2008
* Jan Engelhardt <[email protected]>
*/
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <xtables.h>
#include <linux/netfilter/xt_conntrack.h>
#include <linux/netfilter/xt_state.h>
#include <linux/netfilter/nf_conntrack_common.h>
#ifndef XT_STATE_UNTRACKED
#define XT_STATE_UNTRACKED (1 << (IP_CT_NUMBER + 1))
#endif
struct ip_conntrack_old_tuple {
struct {
__be32 ip;
union {
__u16 all;
} u;
} src;
struct {
__be32 ip;
union {
__u16 all;
} u;
/* The protocol. */
__u16 protonum;
} dst;
};
struct xt_conntrack_info {
unsigned int statemask, statusmask;
struct ip_conntrack_old_tuple tuple[IP_CT_DIR_MAX];
struct in_addr sipmsk[IP_CT_DIR_MAX], dipmsk[IP_CT_DIR_MAX];
unsigned long expires_min, expires_max;
/* Flags word */
uint8_t flags;
/* Inverse flags */
uint8_t invflags;
};
enum {
O_CTSTATE = 0,
O_CTPROTO,
O_CTORIGSRC,
O_CTORIGDST,
O_CTREPLSRC,
O_CTREPLDST,
O_CTORIGSRCPORT,
O_CTORIGDSTPORT,
O_CTREPLSRCPORT,
O_CTREPLDSTPORT,
O_CTSTATUS,
O_CTEXPIRE,
O_CTDIR,
};
static void conntrack_mt_help(void)
{
printf(
"conntrack match options:\n"
"[!] --ctstate {INVALID|ESTABLISHED|NEW|RELATED|UNTRACKED|SNAT|DNAT}[,...]\n"
" State(s) to match\n"
"[!] --ctproto proto Protocol to match; by number or name, e.g. \"tcp\"\n"
"[!] --ctorigsrc address[/mask]\n"
"[!] --ctorigdst address[/mask]\n"
"[!] --ctreplsrc address[/mask]\n"
"[!] --ctrepldst address[/mask]\n"
" Original/Reply source/destination address\n"
"[!] --ctorigsrcport port\n"
"[!] --ctorigdstport port\n"
"[!] --ctreplsrcport port\n"
"[!] --ctrepldstport port\n"
" TCP/UDP/SCTP orig./reply source/destination port\n"
"[!] --ctstatus {NONE|EXPECTED|SEEN_REPLY|ASSURED|CONFIRMED}[,...]\n"
" Status(es) to match\n"
"[!] --ctexpire time[:time] Match remaining lifetime in seconds against\n"
" value or range of values (inclusive)\n"
" --ctdir {ORIGINAL|REPLY} Flow direction of packet\n");
}
#define s struct xt_conntrack_info /* for v0 */
static const struct xt_option_entry conntrack_mt_opts_v0[] = {
{.name = "ctstate", .id = O_CTSTATE, .type = XTTYPE_STRING,
.flags = XTOPT_INVERT},
{.name = "ctproto", .id = O_CTPROTO, .type = XTTYPE_PROTOCOL,
.flags = XTOPT_INVERT},
{.name = "ctorigsrc", .id = O_CTORIGSRC, .type = XTTYPE_HOST,
.flags = XTOPT_INVERT},
{.name = "ctorigdst", .id = O_CTORIGDST, .type = XTTYPE_HOST,
.flags = XTOPT_INVERT},
{.name = "ctreplsrc", .id = O_CTREPLSRC, .type = XTTYPE_HOST,
.flags = XTOPT_INVERT},
{.name = "ctrepldst", .id = O_CTREPLDST, .type = XTTYPE_HOST,
.flags = XTOPT_INVERT},
{.name = "ctstatus", .id = O_CTSTATUS, .type = XTTYPE_STRING,
.flags = XTOPT_INVERT},
{.name = "ctexpire", .id = O_CTEXPIRE, .type = XTTYPE_UINT32RC,
.flags = XTOPT_INVERT},
XTOPT_TABLEEND,
};
#undef s
#define s struct xt_conntrack_mtinfo2
/* We exploit the fact that v1-v2 share the same xt_o_e layout */
static const struct xt_option_entry conntrack2_mt_opts[] = {
{.name = "ctstate", .id = O_CTSTATE, .type = XTTYPE_STRING,
.flags = XTOPT_INVERT},
{.name = "ctproto", .id = O_CTPROTO, .type = XTTYPE_PROTOCOL,
.flags = XTOPT_INVERT},
{.name = "ctorigsrc", .id = O_CTORIGSRC, .type = XTTYPE_HOSTMASK,
.flags = XTOPT_INVERT},
{.name = "ctorigdst", .id = O_CTORIGDST, .type = XTTYPE_HOSTMASK,
.flags = XTOPT_INVERT},
{.name = "ctreplsrc", .id = O_CTREPLSRC, .type = XTTYPE_HOSTMASK,
.flags = XTOPT_INVERT},
{.name = "ctrepldst", .id = O_CTREPLDST, .type = XTTYPE_HOSTMASK,
.flags = XTOPT_INVERT},
{.name = "ctstatus", .id = O_CTSTATUS, .type = XTTYPE_STRING,
.flags = XTOPT_INVERT},
{.name = "ctexpire", .id = O_CTEXPIRE, .type = XTTYPE_UINT32RC,
.flags = XTOPT_INVERT},
/*
* Rev 1 and 2 only store one port, and we would normally use
* %XTTYPE_PORT (rather than %XTTYPE_PORTRC) for that. The resulting
* error message - in case a user passed a range nevertheless -
* "port 22:23 resolved to nothing" is not quite as useful as using
* %XTTYPE_PORTC and libxt_conntrack's own range test.
*/
{.name = "ctorigsrcport", .id = O_CTORIGSRCPORT, .type = XTTYPE_PORTRC,
.flags = XTOPT_INVERT | XTOPT_NBO},
{.name = "ctorigdstport", .id = O_CTORIGDSTPORT, .type = XTTYPE_PORTRC,
.flags = XTOPT_INVERT | XTOPT_NBO},
{.name = "ctreplsrcport", .id = O_CTREPLSRCPORT, .type = XTTYPE_PORTRC,
.flags = XTOPT_INVERT | XTOPT_NBO},
{.name = "ctrepldstport", .id = O_CTREPLDSTPORT, .type = XTTYPE_PORTRC,
.flags = XTOPT_INVERT | XTOPT_NBO},
{.name = "ctdir", .id = O_CTDIR, .type = XTTYPE_STRING},
XTOPT_TABLEEND,
};
#undef s
#define s struct xt_conntrack_mtinfo3
/* Difference from v2 is the non-NBO form. */
static const struct xt_option_entry conntrack3_mt_opts[] = {
{.name = "ctstate", .id = O_CTSTATE, .type = XTTYPE_STRING,
.flags = XTOPT_INVERT},
{.name = "ctproto", .id = O_CTPROTO, .type = XTTYPE_PROTOCOL,
.flags = XTOPT_INVERT},
{.name = "ctorigsrc", .id = O_CTORIGSRC, .type = XTTYPE_HOSTMASK,
.flags = XTOPT_INVERT},
{.name = "ctorigdst", .id = O_CTORIGDST, .type = XTTYPE_HOSTMASK,
.flags = XTOPT_INVERT},
{.name = "ctreplsrc", .id = O_CTREPLSRC, .type = XTTYPE_HOSTMASK,
.flags = XTOPT_INVERT},
{.name = "ctrepldst", .id = O_CTREPLDST, .type = XTTYPE_HOSTMASK,
.flags = XTOPT_INVERT},
{.name = "ctstatus", .id = O_CTSTATUS, .type = XTTYPE_STRING,
.flags = XTOPT_INVERT},
{.name = "ctexpire", .id = O_CTEXPIRE, .type = XTTYPE_UINT32RC,
.flags = XTOPT_INVERT},
{.name = "ctorigsrcport", .id = O_CTORIGSRCPORT, .type = XTTYPE_PORTRC,
.flags = XTOPT_INVERT},
{.name = "ctorigdstport", .id = O_CTORIGDSTPORT, .type = XTTYPE_PORTRC,
.flags = XTOPT_INVERT},
{.name = "ctreplsrcport", .id = O_CTREPLSRCPORT, .type = XTTYPE_PORTRC,
.flags = XTOPT_INVERT},
{.name = "ctrepldstport", .id = O_CTREPLDSTPORT, .type = XTTYPE_PORTRC,
.flags = XTOPT_INVERT},
{.name = "ctdir", .id = O_CTDIR, .type = XTTYPE_STRING},
XTOPT_TABLEEND,
};
#undef s
static int
parse_state(const char *state, size_t len, struct xt_conntrack_info *sinfo)
{
if (strncasecmp(state, "INVALID", len) == 0)
sinfo->statemask |= XT_CONNTRACK_STATE_INVALID;
else if (strncasecmp(state, "NEW", len) == 0)
sinfo->statemask |= XT_CONNTRACK_STATE_BIT(IP_CT_NEW);
else if (strncasecmp(state, "ESTABLISHED", len) == 0)
sinfo->statemask |= XT_CONNTRACK_STATE_BIT(IP_CT_ESTABLISHED);
else if (strncasecmp(state, "RELATED", len) == 0)
sinfo->statemask |= XT_CONNTRACK_STATE_BIT(IP_CT_RELATED);
else if (strncasecmp(state, "UNTRACKED", len) == 0)
sinfo->statemask |= XT_CONNTRACK_STATE_UNTRACKED;
else if (strncasecmp(state, "SNAT", len) == 0)
sinfo->statemask |= XT_CONNTRACK_STATE_SNAT;
else if (strncasecmp(state, "DNAT", len) == 0)
sinfo->statemask |= XT_CONNTRACK_STATE_DNAT;
else
return 0;
return 1;
}
static void
parse_states(const char *arg, struct xt_conntrack_info *sinfo)
{
const char *comma;
while ((comma = strchr(arg, ',')) != NULL) {
if (comma == arg || !parse_state(arg, comma-arg, sinfo))
xtables_error(PARAMETER_PROBLEM, "Bad ctstate \"%s\"", arg);
arg = comma+1;
}
if (!*arg)
xtables_error(PARAMETER_PROBLEM, "\"--ctstate\" requires a list of "
"states with no spaces, e.g. "
"ESTABLISHED,RELATED");
if (strlen(arg) == 0 || !parse_state(arg, strlen(arg), sinfo))
xtables_error(PARAMETER_PROBLEM, "Bad ctstate \"%s\"", arg);
}
static bool
conntrack_ps_state(struct xt_conntrack_mtinfo3 *info, const char *state,
size_t z)
{
if (strncasecmp(state, "INVALID", z) == 0)
info->state_mask |= XT_CONNTRACK_STATE_INVALID;
else if (strncasecmp(state, "NEW", z) == 0)
info->state_mask |= XT_CONNTRACK_STATE_BIT(IP_CT_NEW);
else if (strncasecmp(state, "ESTABLISHED", z) == 0)
info->state_mask |= XT_CONNTRACK_STATE_BIT(IP_CT_ESTABLISHED);
else if (strncasecmp(state, "RELATED", z) == 0)
info->state_mask |= XT_CONNTRACK_STATE_BIT(IP_CT_RELATED);
else if (strncasecmp(state, "UNTRACKED", z) == 0)
info->state_mask |= XT_CONNTRACK_STATE_UNTRACKED;
else if (strncasecmp(state, "SNAT", z) == 0)
info->state_mask |= XT_CONNTRACK_STATE_SNAT;
else if (strncasecmp(state, "DNAT", z) == 0)
info->state_mask |= XT_CONNTRACK_STATE_DNAT;
else
return false;
return true;
}
static void
conntrack_ps_states(struct xt_conntrack_mtinfo3 *info, const char *arg)
{
const char *comma;
while ((comma = strchr(arg, ',')) != NULL) {
if (comma == arg || !conntrack_ps_state(info, arg, comma - arg))
xtables_error(PARAMETER_PROBLEM,
"Bad ctstate \"%s\"", arg);
arg = comma + 1;
}
if (strlen(arg) == 0 || !conntrack_ps_state(info, arg, strlen(arg)))
xtables_error(PARAMETER_PROBLEM, "Bad ctstate \"%s\"", arg);
}
static int
parse_status(const char *status, size_t len, struct xt_conntrack_info *sinfo)
{
if (strncasecmp(status, "NONE", len) == 0)
sinfo->statusmask |= 0;
else if (strncasecmp(status, "EXPECTED", len) == 0)
sinfo->statusmask |= IPS_EXPECTED;
else if (strncasecmp(status, "SEEN_REPLY", len) == 0)
sinfo->statusmask |= IPS_SEEN_REPLY;
else if (strncasecmp(status, "ASSURED", len) == 0)
sinfo->statusmask |= IPS_ASSURED;
#ifdef IPS_CONFIRMED
else if (strncasecmp(status, "CONFIRMED", len) == 0)
sinfo->statusmask |= IPS_CONFIRMED;
#endif
else
return 0;
return 1;
}
static void
parse_statuses(const char *arg, struct xt_conntrack_info *sinfo)
{
const char *comma;
while ((comma = strchr(arg, ',')) != NULL) {
if (comma == arg || !parse_status(arg, comma-arg, sinfo))
xtables_error(PARAMETER_PROBLEM, "Bad ctstatus \"%s\"", arg);
arg = comma+1;
}
if (strlen(arg) == 0 || !parse_status(arg, strlen(arg), sinfo))
xtables_error(PARAMETER_PROBLEM, "Bad ctstatus \"%s\"", arg);
}
static bool
conntrack_ps_status(struct xt_conntrack_mtinfo3 *info, const char *status,
size_t z)
{
if (strncasecmp(status, "NONE", z) == 0)
info->status_mask |= 0;
else if (strncasecmp(status, "EXPECTED", z) == 0)
info->status_mask |= IPS_EXPECTED;
else if (strncasecmp(status, "SEEN_REPLY", z) == 0)
info->status_mask |= IPS_SEEN_REPLY;
else if (strncasecmp(status, "ASSURED", z) == 0)
info->status_mask |= IPS_ASSURED;
else if (strncasecmp(status, "CONFIRMED", z) == 0)
info->status_mask |= IPS_CONFIRMED;
else
return false;
return true;
}
static void
conntrack_ps_statuses(struct xt_conntrack_mtinfo3 *info, const char *arg)
{
const char *comma;
while ((comma = strchr(arg, ',')) != NULL) {
if (comma == arg || !conntrack_ps_status(info, arg, comma - arg))
xtables_error(PARAMETER_PROBLEM,
"Bad ctstatus \"%s\"", arg);
arg = comma + 1;
}
if (strlen(arg) == 0 || !conntrack_ps_status(info, arg, strlen(arg)))
xtables_error(PARAMETER_PROBLEM, "Bad ctstatus \"%s\"", arg);
}
static void conntrack_parse(struct xt_option_call *cb)
{
struct xt_conntrack_info *sinfo = cb->data;
xtables_option_parse(cb);
switch (cb->entry->id) {
case O_CTSTATE:
parse_states(cb->arg, sinfo);
if (cb->invert)
sinfo->invflags |= XT_CONNTRACK_STATE;
break;
case O_CTPROTO:
sinfo->tuple[IP_CT_DIR_ORIGINAL].dst.protonum = cb->val.protocol;
if (cb->invert)
sinfo->invflags |= XT_CONNTRACK_PROTO;
if (sinfo->tuple[IP_CT_DIR_ORIGINAL].dst.protonum == 0
&& (sinfo->invflags & XT_INV_PROTO))
xtables_error(PARAMETER_PROBLEM,
"rule would never match protocol");
sinfo->flags |= XT_CONNTRACK_PROTO;
break;
case O_CTORIGSRC:
if (cb->invert)
sinfo->invflags |= XT_CONNTRACK_ORIGSRC;
sinfo->tuple[IP_CT_DIR_ORIGINAL].src.ip = cb->val.haddr.ip;
sinfo->flags |= XT_CONNTRACK_ORIGSRC;
break;
case O_CTORIGDST:
if (cb->invert)
sinfo->invflags |= XT_CONNTRACK_ORIGDST;
sinfo->tuple[IP_CT_DIR_ORIGINAL].dst.ip = cb->val.haddr.ip;
sinfo->flags |= XT_CONNTRACK_ORIGDST;
break;
case O_CTREPLSRC:
if (cb->invert)
sinfo->invflags |= XT_CONNTRACK_REPLSRC;
sinfo->tuple[IP_CT_DIR_REPLY].src.ip = cb->val.haddr.ip;
sinfo->flags |= XT_CONNTRACK_REPLSRC;
break;
case O_CTREPLDST:
if (cb->invert)
sinfo->invflags |= XT_CONNTRACK_REPLDST;
sinfo->tuple[IP_CT_DIR_REPLY].dst.ip = cb->val.haddr.ip;
sinfo->flags |= XT_CONNTRACK_REPLDST;
break;
case O_CTSTATUS:
parse_statuses(cb->arg, sinfo);
if (cb->invert)
sinfo->invflags |= XT_CONNTRACK_STATUS;
sinfo->flags |= XT_CONNTRACK_STATUS;
break;
case O_CTEXPIRE:
sinfo->expires_min = cb->val.u32_range[0];
sinfo->expires_max = cb->val.u32_range[0];
if (cb->nvals >= 2)
sinfo->expires_max = cb->val.u32_range[1];
if (cb->invert)
sinfo->invflags |= XT_CONNTRACK_EXPIRES;
sinfo->flags |= XT_CONNTRACK_EXPIRES;
break;
}
}
static void conntrack_mt_parse(struct xt_option_call *cb, uint8_t rev)
{
struct xt_conntrack_mtinfo3 *info = cb->data;
xtables_option_parse(cb);
switch (cb->entry->id) {
case O_CTSTATE:
conntrack_ps_states(info, cb->arg);
info->match_flags |= XT_CONNTRACK_STATE;
if (cb->invert)
info->invert_flags |= XT_CONNTRACK_STATE;
break;
case O_CTPROTO:
info->l4proto = cb->val.protocol;
if (info->l4proto == 0 && (info->invert_flags & XT_INV_PROTO))
xtables_error(PARAMETER_PROBLEM, "conntrack: rule would "
"never match protocol");
info->match_flags |= XT_CONNTRACK_PROTO;
if (cb->invert)
info->invert_flags |= XT_CONNTRACK_PROTO;
break;
case O_CTORIGSRC:
info->origsrc_addr = cb->val.haddr;
info->origsrc_mask = cb->val.hmask;
info->match_flags |= XT_CONNTRACK_ORIGSRC;
if (cb->invert)
info->invert_flags |= XT_CONNTRACK_ORIGSRC;
break;
case O_CTORIGDST:
info->origdst_addr = cb->val.haddr;
info->origdst_mask = cb->val.hmask;
info->match_flags |= XT_CONNTRACK_ORIGDST;
if (cb->invert)
info->invert_flags |= XT_CONNTRACK_ORIGDST;
break;
case O_CTREPLSRC:
info->replsrc_addr = cb->val.haddr;
info->replsrc_mask = cb->val.hmask;
info->match_flags |= XT_CONNTRACK_REPLSRC;
if (cb->invert)
info->invert_flags |= XT_CONNTRACK_REPLSRC;
break;
case O_CTREPLDST:
info->repldst_addr = cb->val.haddr;
info->repldst_mask = cb->val.hmask;
info->match_flags |= XT_CONNTRACK_REPLDST;
if (cb->invert)
info->invert_flags |= XT_CONNTRACK_REPLDST;
break;
case O_CTSTATUS:
conntrack_ps_statuses(info, cb->arg);
info->match_flags |= XT_CONNTRACK_STATUS;
if (cb->invert)
info->invert_flags |= XT_CONNTRACK_STATUS;
break;
case O_CTEXPIRE:
info->expires_min = cb->val.u32_range[0];
info->expires_max = cb->val.u32_range[0];
if (cb->nvals >= 2)
info->expires_max = cb->val.u32_range[1];
info->match_flags |= XT_CONNTRACK_EXPIRES;
if (cb->invert)
info->invert_flags |= XT_CONNTRACK_EXPIRES;
break;
case O_CTORIGSRCPORT:
info->origsrc_port = cb->val.port_range[0];
info->origsrc_port_high = cb->val.port_range[cb->nvals >= 2];
info->match_flags |= XT_CONNTRACK_ORIGSRC_PORT;
if (cb->invert)
info->invert_flags |= XT_CONNTRACK_ORIGSRC_PORT;
break;
case O_CTORIGDSTPORT:
info->origdst_port = cb->val.port_range[0];
info->origdst_port_high = cb->val.port_range[cb->nvals >= 2];
info->match_flags |= XT_CONNTRACK_ORIGDST_PORT;
if (cb->invert)
info->invert_flags |= XT_CONNTRACK_ORIGDST_PORT;
break;
case O_CTREPLSRCPORT:
info->replsrc_port = cb->val.port_range[0];
info->replsrc_port_high = cb->val.port_range[cb->nvals >= 2];
info->match_flags |= XT_CONNTRACK_REPLSRC_PORT;
if (cb->invert)
info->invert_flags |= XT_CONNTRACK_REPLSRC_PORT;
break;
case O_CTREPLDSTPORT:
info->repldst_port = cb->val.port_range[0];
info->repldst_port_high = cb->val.port_range[cb->nvals >= 2];
info->match_flags |= XT_CONNTRACK_REPLDST_PORT;
if (cb->invert)
info->invert_flags |= XT_CONNTRACK_REPLDST_PORT;
break;
case O_CTDIR:
if (strcasecmp(cb->arg, "ORIGINAL") == 0) {
info->match_flags |= XT_CONNTRACK_DIRECTION;
info->invert_flags &= ~XT_CONNTRACK_DIRECTION;
} else if (strcasecmp(cb->arg, "REPLY") == 0) {
info->match_flags |= XT_CONNTRACK_DIRECTION;
info->invert_flags |= XT_CONNTRACK_DIRECTION;
} else {
xtables_param_act(XTF_BAD_VALUE, "conntrack", "--ctdir", cb->arg);
}
break;
}
}
#define cinfo_transform(r, l) \
do { \
memcpy((r), (l), offsetof(typeof(*(l)), state_mask)); \
(r)->state_mask = (l)->state_mask; \
(r)->status_mask = (l)->status_mask; \
} while (false);
static void conntrack1_mt_parse(struct xt_option_call *cb)
{
struct xt_conntrack_mtinfo1 *info = cb->data;
struct xt_conntrack_mtinfo3 up;
memset(&up, 0, sizeof(up));
cinfo_transform(&up, info);
up.origsrc_port_high = up.origsrc_port;
up.origdst_port_high = up.origdst_port;
up.replsrc_port_high = up.replsrc_port;
up.repldst_port_high = up.repldst_port;
cb->data = &up;
conntrack_mt_parse(cb, 3);
if (up.origsrc_port != up.origsrc_port_high ||
up.origdst_port != up.origdst_port_high ||
up.replsrc_port != up.replsrc_port_high ||
up.repldst_port != up.repldst_port_high)
xtables_error(PARAMETER_PROBLEM,
"conntrack rev 1 does not support port ranges");
cinfo_transform(info, &up);
cb->data = info;
}
static void conntrack2_mt_parse(struct xt_option_call *cb)
{
#define cinfo2_transform(r, l) \
memcpy((r), (l), offsetof(typeof(*(l)), sizeof(*info));
struct xt_conntrack_mtinfo2 *info = cb->data;
struct xt_conntrack_mtinfo3 up;
memset(&up, 0, sizeof(up));
memcpy(&up, info, sizeof(*info));
up.origsrc_port_high = up.origsrc_port;
up.origdst_port_high = up.origdst_port;
up.replsrc_port_high = up.replsrc_port;
up.repldst_port_high = up.repldst_port;
cb->data = &up;
conntrack_mt_parse(cb, 3);
if (up.origsrc_port != up.origsrc_port_high ||
up.origdst_port != up.origdst_port_high ||
up.replsrc_port != up.replsrc_port_high ||
up.repldst_port != up.repldst_port_high)
xtables_error(PARAMETER_PROBLEM,
"conntrack rev 2 does not support port ranges");
memcpy(info, &up, sizeof(*info));
cb->data = info;
#undef cinfo2_transform
}
static void conntrack3_mt_parse(struct xt_option_call *cb)
{
conntrack_mt_parse(cb, 3);
}
static void conntrack_mt_check(struct xt_fcheck_call *cb)
{
if (cb->xflags == 0)
xtables_error(PARAMETER_PROBLEM, "conntrack: At least one option "
"is required");
}
static void
print_state(unsigned int statemask)
{
const char *sep = " ";
if (statemask & XT_CONNTRACK_STATE_INVALID) {
printf("%sINVALID", sep);
sep = ",";
}
if (statemask & XT_CONNTRACK_STATE_BIT(IP_CT_NEW)) {
printf("%sNEW", sep);
sep = ",";
}
if (statemask & XT_CONNTRACK_STATE_BIT(IP_CT_RELATED)) {
printf("%sRELATED", sep);
sep = ",";
}
if (statemask & XT_CONNTRACK_STATE_BIT(IP_CT_ESTABLISHED)) {
printf("%sESTABLISHED", sep);
sep = ",";
}
if (statemask & XT_CONNTRACK_STATE_UNTRACKED) {
printf("%sUNTRACKED", sep);
sep = ",";
}
if (statemask & XT_CONNTRACK_STATE_SNAT) {
printf("%sSNAT", sep);
sep = ",";
}
if (statemask & XT_CONNTRACK_STATE_DNAT) {
printf("%sDNAT", sep);
sep = ",";
}
}
static void
print_status(unsigned int statusmask)
{
const char *sep = " ";
if (statusmask & IPS_EXPECTED) {
printf("%sEXPECTED", sep);
sep = ",";
}
if (statusmask & IPS_SEEN_REPLY) {
printf("%sSEEN_REPLY", sep);
sep = ",";
}
if (statusmask & IPS_ASSURED) {
printf("%sASSURED", sep);
sep = ",";
}
if (statusmask & IPS_CONFIRMED) {
printf("%sCONFIRMED", sep);
sep = ",";
}
if (statusmask == 0)
printf("%sNONE", sep);
}
static void
conntrack_dump_addr(const union nf_inet_addr *addr,
const union nf_inet_addr *mask,
unsigned int family, bool numeric)
{
if (family == NFPROTO_IPV4) {
if (!numeric && addr->ip == 0) {
printf(" anywhere");
return;
}
if (numeric)
printf(" %s%s",
xtables_ipaddr_to_numeric(&addr->in),
xtables_ipmask_to_numeric(&mask->in));
else
printf(" %s%s",
xtables_ipaddr_to_anyname(&addr->in),
xtables_ipmask_to_numeric(&mask->in));
} else if (family == NFPROTO_IPV6) {
if (!numeric && addr->ip6[0] == 0 && addr->ip6[1] == 0 &&
addr->ip6[2] == 0 && addr->ip6[3] == 0) {
printf(" anywhere");
return;
}
if (numeric)
printf(" %s%s",
xtables_ip6addr_to_numeric(&addr->in6),
xtables_ip6mask_to_numeric(&mask->in6));
else
printf(" %s%s",
xtables_ip6addr_to_anyname(&addr->in6),
xtables_ip6mask_to_numeric(&mask->in6));
}
}
static void
print_addr(const struct in_addr *addr, const struct in_addr *mask,
int inv, int numeric)
{
char buf[BUFSIZ];
if (inv)
printf(" !");
if (mask->s_addr == 0L && !numeric)
printf(" %s", "anywhere");
else {
if (numeric)
strcpy(buf, xtables_ipaddr_to_numeric(addr));
else
strcpy(buf, xtables_ipaddr_to_anyname(addr));
strcat(buf, xtables_ipmask_to_numeric(mask));
printf(" %s", buf);
}
}
static void
matchinfo_print(const void *ip, const struct xt_entry_match *match, int numeric, const char *optpfx)
{
const struct xt_conntrack_info *sinfo = (const void *)match->data;
if(sinfo->flags & XT_CONNTRACK_STATE) {
if (sinfo->invflags & XT_CONNTRACK_STATE)
printf(" !");
printf(" %sctstate", optpfx);
print_state(sinfo->statemask);
}
if(sinfo->flags & XT_CONNTRACK_PROTO) {
if (sinfo->invflags & XT_CONNTRACK_PROTO)
printf(" !");
printf(" %sctproto", optpfx);
printf(" %u", sinfo->tuple[IP_CT_DIR_ORIGINAL].dst.protonum);
}
if(sinfo->flags & XT_CONNTRACK_ORIGSRC) {
if (sinfo->invflags & XT_CONNTRACK_ORIGSRC)
printf(" !");
printf(" %sctorigsrc", optpfx);
print_addr(
(struct in_addr *)&sinfo->tuple[IP_CT_DIR_ORIGINAL].src.ip,
&sinfo->sipmsk[IP_CT_DIR_ORIGINAL],
false,
numeric);
}
if(sinfo->flags & XT_CONNTRACK_ORIGDST) {
if (sinfo->invflags & XT_CONNTRACK_ORIGDST)
printf(" !");
printf(" %sctorigdst", optpfx);
print_addr(
(struct in_addr *)&sinfo->tuple[IP_CT_DIR_ORIGINAL].dst.ip,
&sinfo->dipmsk[IP_CT_DIR_ORIGINAL],
false,
numeric);
}
if(sinfo->flags & XT_CONNTRACK_REPLSRC) {
if (sinfo->invflags & XT_CONNTRACK_REPLSRC)
printf(" !");
printf(" %sctreplsrc", optpfx);
print_addr(
(struct in_addr *)&sinfo->tuple[IP_CT_DIR_REPLY].src.ip,
&sinfo->sipmsk[IP_CT_DIR_REPLY],
false,
numeric);
}
if(sinfo->flags & XT_CONNTRACK_REPLDST) {
if (sinfo->invflags & XT_CONNTRACK_REPLDST)
printf(" !");
printf(" %sctrepldst", optpfx);
print_addr(
(struct in_addr *)&sinfo->tuple[IP_CT_DIR_REPLY].dst.ip,
&sinfo->dipmsk[IP_CT_DIR_REPLY],
false,
numeric);
}
if(sinfo->flags & XT_CONNTRACK_STATUS) {
if (sinfo->invflags & XT_CONNTRACK_STATUS)
printf(" !");
printf(" %sctstatus", optpfx);
print_status(sinfo->statusmask);
}
if(sinfo->flags & XT_CONNTRACK_EXPIRES) {
if (sinfo->invflags & XT_CONNTRACK_EXPIRES)
printf(" !");
printf(" %sctexpire ", optpfx);
if (sinfo->expires_max == sinfo->expires_min)
printf("%lu", sinfo->expires_min);
else
printf("%lu:%lu", sinfo->expires_min, sinfo->expires_max);
}
if (sinfo->flags & XT_CONNTRACK_DIRECTION) {
if (sinfo->invflags & XT_CONNTRACK_DIRECTION)
printf(" %sctdir REPLY", optpfx);
else
printf(" %sctdir ORIGINAL", optpfx);
}
}
static void
conntrack_dump_ports(const char *prefix, const char *opt,
u_int16_t port_low, u_int16_t port_high)
{
if (port_high == 0 || port_low == port_high)
printf(" %s%s %u", prefix, opt, port_low);
else
printf(" %s%s %u:%u", prefix, opt, port_low, port_high);
}
static void
conntrack_dump(const struct xt_conntrack_mtinfo3 *info, const char *prefix,
unsigned int family, bool numeric, bool v3)
{
if (info->match_flags & XT_CONNTRACK_STATE) {
if (info->invert_flags & XT_CONNTRACK_STATE)
printf(" !");
printf(" %sctstate", prefix);
print_state(info->state_mask);
}
if (info->match_flags & XT_CONNTRACK_PROTO) {
if (info->invert_flags & XT_CONNTRACK_PROTO)
printf(" !");
printf(" %sctproto %u", prefix, info->l4proto);
}
if (info->match_flags & XT_CONNTRACK_ORIGSRC) {
if (info->invert_flags & XT_CONNTRACK_ORIGSRC)
printf(" !");
printf(" %sctorigsrc", prefix);
conntrack_dump_addr(&info->origsrc_addr, &info->origsrc_mask,
family, numeric);
}
if (info->match_flags & XT_CONNTRACK_ORIGDST) {
if (info->invert_flags & XT_CONNTRACK_ORIGDST)
printf(" !");
printf(" %sctorigdst", prefix);
conntrack_dump_addr(&info->origdst_addr, &info->origdst_mask,
family, numeric);
}
if (info->match_flags & XT_CONNTRACK_REPLSRC) {
if (info->invert_flags & XT_CONNTRACK_REPLSRC)
printf(" !");
printf(" %sctreplsrc", prefix);
conntrack_dump_addr(&info->replsrc_addr, &info->replsrc_mask,
family, numeric);
}
if (info->match_flags & XT_CONNTRACK_REPLDST) {
if (info->invert_flags & XT_CONNTRACK_REPLDST)
printf(" !");
printf(" %sctrepldst", prefix);
conntrack_dump_addr(&info->repldst_addr, &info->repldst_mask,
family, numeric);
}
if (info->match_flags & XT_CONNTRACK_ORIGSRC_PORT) {
if (info->invert_flags & XT_CONNTRACK_ORIGSRC_PORT)
printf(" !");
conntrack_dump_ports(prefix, "ctorigsrcport",
v3 ? info->origsrc_port : ntohs(info->origsrc_port),
v3 ? info->origsrc_port_high : 0);
}
if (info->match_flags & XT_CONNTRACK_ORIGDST_PORT) {
if (info->invert_flags & XT_CONNTRACK_ORIGDST_PORT)
printf(" !");
conntrack_dump_ports(prefix, "ctorigdstport",
v3 ? info->origdst_port : ntohs(info->origdst_port),
v3 ? info->origdst_port_high : 0);
}
if (info->match_flags & XT_CONNTRACK_REPLSRC_PORT) {
if (info->invert_flags & XT_CONNTRACK_REPLSRC_PORT)
printf(" !");
conntrack_dump_ports(prefix, "ctreplsrcport",
v3 ? info->replsrc_port : ntohs(info->replsrc_port),
v3 ? info->replsrc_port_high : 0);
}
if (info->match_flags & XT_CONNTRACK_REPLDST_PORT) {
if (info->invert_flags & XT_CONNTRACK_REPLDST_PORT)
printf(" !");
conntrack_dump_ports(prefix, "ctrepldstport",
v3 ? info->repldst_port : ntohs(info->repldst_port),
v3 ? info->repldst_port_high : 0);
}
if (info->match_flags & XT_CONNTRACK_STATUS) {
if (info->invert_flags & XT_CONNTRACK_STATUS)
printf(" !");
printf(" %sctstatus", prefix);
print_status(info->status_mask);
}
if (info->match_flags & XT_CONNTRACK_EXPIRES) {
if (info->invert_flags & XT_CONNTRACK_EXPIRES)
printf(" !");
printf(" %sctexpire ", prefix);
if (info->expires_max == info->expires_min)
printf("%u", (unsigned int)info->expires_min);
else
printf("%u:%u", (unsigned int)info->expires_min,
(unsigned int)info->expires_max);
}
if (info->match_flags & XT_CONNTRACK_DIRECTION) {
if (info->invert_flags & XT_CONNTRACK_DIRECTION)
printf(" %sctdir REPLY", prefix);
else
printf(" %sctdir ORIGINAL", prefix);
}
}
static void conntrack_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
matchinfo_print(ip, match, numeric, "");
}
static void
conntrack1_mt4_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
const struct xt_conntrack_mtinfo1 *info = (void *)match->data;
struct xt_conntrack_mtinfo3 up;
cinfo_transform(&up, info);
conntrack_dump(&up, "", NFPROTO_IPV4, numeric, false);
}
static void
conntrack1_mt6_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
const struct xt_conntrack_mtinfo1 *info = (void *)match->data;
struct xt_conntrack_mtinfo3 up;
cinfo_transform(&up, info);
conntrack_dump(&up, "", NFPROTO_IPV6, numeric, false);
}
static void
conntrack2_mt_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
conntrack_dump((const void *)match->data, "", NFPROTO_IPV4, numeric, false);
}
static void
conntrack2_mt6_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
conntrack_dump((const void *)match->data, "", NFPROTO_IPV6, numeric, false);
}
static void
conntrack3_mt_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
conntrack_dump((const void *)match->data, "", NFPROTO_IPV4, numeric, true);
}
static void
conntrack3_mt6_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
conntrack_dump((const void *)match->data, "", NFPROTO_IPV6, numeric, true);
}
static void conntrack_save(const void *ip, const struct xt_entry_match *match)
{
matchinfo_print(ip, match, 1, "--");
}
static void conntrack3_mt_save(const void *ip,
const struct xt_entry_match *match)
{
conntrack_dump((const void *)match->data, "--", NFPROTO_IPV4, true, true);
}
static void conntrack3_mt6_save(const void *ip,
const struct xt_entry_match *match)
{
conntrack_dump((const void *)match->data, "--", NFPROTO_IPV6, true, true);
}
static void conntrack2_mt_save(const void *ip,
const struct xt_entry_match *match)
{
conntrack_dump((const void *)match->data, "--", NFPROTO_IPV4, true, false);
}
static void conntrack2_mt6_save(const void *ip,
const struct xt_entry_match *match)
{
conntrack_dump((const void *)match->data, "--", NFPROTO_IPV6, true, false);
}
static void
conntrack1_mt4_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_conntrack_mtinfo1 *info = (void *)match->data;
struct xt_conntrack_mtinfo3 up;
cinfo_transform(&up, info);
conntrack_dump(&up, "--", NFPROTO_IPV4, true, false);
}
static void
conntrack1_mt6_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_conntrack_mtinfo1 *info = (void *)match->data;
struct xt_conntrack_mtinfo3 up;
cinfo_transform(&up, info);
conntrack_dump(&up, "--", NFPROTO_IPV6, true, false);
}
static void
state_help(void)
{
printf(
"state match options:\n"
" [!] --state [INVALID|ESTABLISHED|NEW|RELATED|UNTRACKED][,...]\n"
" State(s) to match\n");
}
static const struct xt_option_entry state_opts[] = {
{.name = "state", .id = O_CTSTATE, .type = XTTYPE_STRING,
.flags = XTOPT_MAND | XTOPT_INVERT},
XTOPT_TABLEEND,
};
static unsigned int
state_parse_state(const char *state, size_t len)
{
if (strncasecmp(state, "INVALID", len) == 0)
return XT_STATE_INVALID;
else if (strncasecmp(state, "NEW", len) == 0)
return XT_STATE_BIT(IP_CT_NEW);
else if (strncasecmp(state, "ESTABLISHED", len) == 0)
return XT_STATE_BIT(IP_CT_ESTABLISHED);
else if (strncasecmp(state, "RELATED", len) == 0)
return XT_STATE_BIT(IP_CT_RELATED);
else if (strncasecmp(state, "UNTRACKED", len) == 0)
return XT_STATE_UNTRACKED;
return 0;
}
static unsigned int
state_parse_states(const char *arg)
{
const char *comma;
unsigned int mask = 0, flag;
while ((comma = strchr(arg, ',')) != NULL) {
if (comma == arg)
goto badstate;
flag = state_parse_state(arg, comma-arg);
if (flag == 0)
goto badstate;
mask |= flag;
arg = comma+1;
}
if (!*arg)
xtables_error(PARAMETER_PROBLEM, "\"--state\" requires a list of "
"states with no spaces, e.g. "
"ESTABLISHED,RELATED");
if (strlen(arg) == 0)
goto badstate;
flag = state_parse_state(arg, strlen(arg));
if (flag == 0)
goto badstate;
mask |= flag;
return mask;
badstate:
xtables_error(PARAMETER_PROBLEM, "Bad state \"%s\"", arg);
}
static void state_parse(struct xt_option_call *cb)
{
struct xt_state_info *sinfo = cb->data;
xtables_option_parse(cb);
sinfo->statemask = state_parse_states(cb->arg);
if (cb->invert)
sinfo->statemask = ~sinfo->statemask;
}
static void state_ct1_parse(struct xt_option_call *cb)
{
struct xt_conntrack_mtinfo1 *sinfo = cb->data;
xtables_option_parse(cb);
sinfo->match_flags = XT_CONNTRACK_STATE;
sinfo->state_mask = state_parse_states(cb->arg);
if (cb->invert)
sinfo->invert_flags |= XT_CONNTRACK_STATE;
}
static void state_ct23_parse(struct xt_option_call *cb)
{
struct xt_conntrack_mtinfo3 *sinfo = cb->data;
xtables_option_parse(cb);
sinfo->match_flags = XT_CONNTRACK_STATE;
sinfo->state_mask = state_parse_states(cb->arg);
if (cb->invert)
sinfo->invert_flags |= XT_CONNTRACK_STATE;
}
static void state_print_state(unsigned int statemask)
{
const char *sep = "";
if (statemask & XT_STATE_INVALID) {
printf("%sINVALID", sep);
sep = ",";
}
if (statemask & XT_STATE_BIT(IP_CT_NEW)) {
printf("%sNEW", sep);
sep = ",";
}
if (statemask & XT_STATE_BIT(IP_CT_RELATED)) {
printf("%sRELATED", sep);
sep = ",";
}
if (statemask & XT_STATE_BIT(IP_CT_ESTABLISHED)) {
printf("%sESTABLISHED", sep);
sep = ",";
}
if (statemask & XT_STATE_UNTRACKED) {
printf("%sUNTRACKED", sep);
sep = ",";
}
}
static void
state_print(const void *ip,
const struct xt_entry_match *match,
int numeric)
{
const struct xt_state_info *sinfo = (const void *)match->data;
printf(" state ");
state_print_state(sinfo->statemask);
}
static void state_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_state_info *sinfo = (const void *)match->data;
printf(" --state ");
state_print_state(sinfo->statemask);
}
static struct xtables_match conntrack_mt_reg[] = {
{
.version = XTABLES_VERSION,
.name = "conntrack",
.revision = 0,
.family = NFPROTO_IPV4,
.size = XT_ALIGN(sizeof(struct xt_conntrack_info)),
.userspacesize = XT_ALIGN(sizeof(struct xt_conntrack_info)),
.help = conntrack_mt_help,
.x6_parse = conntrack_parse,
.x6_fcheck = conntrack_mt_check,
.print = conntrack_print,
.save = conntrack_save,
.x6_options = conntrack_mt_opts_v0,
},
{
.version = XTABLES_VERSION,
.name = "conntrack",
.revision = 1,
.family = NFPROTO_IPV4,
.size = XT_ALIGN(sizeof(struct xt_conntrack_mtinfo1)),
.userspacesize = XT_ALIGN(sizeof(struct xt_conntrack_mtinfo1)),
.help = conntrack_mt_help,
.x6_parse = conntrack1_mt_parse,
.x6_fcheck = conntrack_mt_check,
.print = conntrack1_mt4_print,
.save = conntrack1_mt4_save,
.x6_options = conntrack2_mt_opts,
},
{
.version = XTABLES_VERSION,
.name = "conntrack",
.revision = 1,
.family = NFPROTO_IPV6,
.size = XT_ALIGN(sizeof(struct xt_conntrack_mtinfo1)),
.userspacesize = XT_ALIGN(sizeof(struct xt_conntrack_mtinfo1)),
.help = conntrack_mt_help,
.x6_parse = conntrack1_mt_parse,
.x6_fcheck = conntrack_mt_check,
.print = conntrack1_mt6_print,
.save = conntrack1_mt6_save,
.x6_options = conntrack2_mt_opts,
},
{
.version = XTABLES_VERSION,
.name = "conntrack",
.revision = 2,
.family = NFPROTO_IPV4,
.size = XT_ALIGN(sizeof(struct xt_conntrack_mtinfo2)),
.userspacesize = XT_ALIGN(sizeof(struct xt_conntrack_mtinfo2)),
.help = conntrack_mt_help,
.x6_parse = conntrack2_mt_parse,
.x6_fcheck = conntrack_mt_check,
.print = conntrack2_mt_print,
.save = conntrack2_mt_save,
.x6_options = conntrack2_mt_opts,
},
{
.version = XTABLES_VERSION,
.name = "conntrack",
.revision = 2,
.family = NFPROTO_IPV6,
.size = XT_ALIGN(sizeof(struct xt_conntrack_mtinfo2)),
.userspacesize = XT_ALIGN(sizeof(struct xt_conntrack_mtinfo2)),
.help = conntrack_mt_help,
.x6_parse = conntrack2_mt_parse,
.x6_fcheck = conntrack_mt_check,
.print = conntrack2_mt6_print,
.save = conntrack2_mt6_save,
.x6_options = conntrack2_mt_opts,
},
{
.version = XTABLES_VERSION,
.name = "conntrack",
.revision = 3,
.family = NFPROTO_IPV4,
.size = XT_ALIGN(sizeof(struct xt_conntrack_mtinfo3)),
.userspacesize = XT_ALIGN(sizeof(struct xt_conntrack_mtinfo3)),
.help = conntrack_mt_help,
.x6_parse = conntrack3_mt_parse,
.x6_fcheck = conntrack_mt_check,
.print = conntrack3_mt_print,
.save = conntrack3_mt_save,
.x6_options = conntrack3_mt_opts,
},
{
.version = XTABLES_VERSION,
.name = "conntrack",
.revision = 3,
.family = NFPROTO_IPV6,
.size = XT_ALIGN(sizeof(struct xt_conntrack_mtinfo3)),
.userspacesize = XT_ALIGN(sizeof(struct xt_conntrack_mtinfo3)),
.help = conntrack_mt_help,
.x6_parse = conntrack3_mt_parse,
.x6_fcheck = conntrack_mt_check,
.print = conntrack3_mt6_print,
.save = conntrack3_mt6_save,
.x6_options = conntrack3_mt_opts,
},
{
.family = NFPROTO_UNSPEC,
.name = "state",
.real_name = "conntrack",
.revision = 1,
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof(struct xt_conntrack_mtinfo1)),
.userspacesize = XT_ALIGN(sizeof(struct xt_conntrack_mtinfo1)),
.help = state_help,
.x6_parse = state_ct1_parse,
.x6_options = state_opts,
},
{
.family = NFPROTO_UNSPEC,
.name = "state",
.real_name = "conntrack",
.revision = 2,
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof(struct xt_conntrack_mtinfo2)),
.userspacesize = XT_ALIGN(sizeof(struct xt_conntrack_mtinfo2)),
.help = state_help,
.x6_parse = state_ct23_parse,
.x6_options = state_opts,
},
{
.family = NFPROTO_UNSPEC,
.name = "state",
.real_name = "conntrack",
.revision = 3,
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof(struct xt_conntrack_mtinfo3)),
.userspacesize = XT_ALIGN(sizeof(struct xt_conntrack_mtinfo3)),
.help = state_help,
.x6_parse = state_ct23_parse,
.x6_options = state_opts,
},
{
.family = NFPROTO_UNSPEC,
.name = "state",
.revision = 0,
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof(struct xt_state_info)),
.userspacesize = XT_ALIGN(sizeof(struct xt_state_info)),
.help = state_help,
.print = state_print,
.save = state_save,
.x6_parse = state_parse,
.x6_options = state_opts,
},
};
void _init(void)
{
xtables_register_matches(conntrack_mt_reg, ARRAY_SIZE(conntrack_mt_reg));
}
|
315 | ./android_firewall/external/iptables/extensions/libip6t_rt.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <xtables.h>
#include <linux/netfilter_ipv6/ip6t_rt.h>
#include <arpa/inet.h>
enum {
O_RT_TYPE = 0,
O_RT_SEGSLEFT,
O_RT_LEN,
O_RT0RES,
O_RT0ADDRS,
O_RT0NSTRICT,
F_RT_TYPE = 1 << O_RT_TYPE,
F_RT0ADDRS = 1 << O_RT0ADDRS,
};
static void rt_help(void)
{
printf(
"rt match options:\n"
"[!] --rt-type type match the type\n"
"[!] --rt-segsleft num[:num] match the Segments Left field (range)\n"
"[!] --rt-len length total length of this header\n"
" --rt-0-res check the reserved field too (type 0)\n"
" --rt-0-addrs ADDR[,ADDR...] Type=0 addresses (list, max: %d)\n"
" --rt-0-not-strict List of Type=0 addresses not a strict list\n",
IP6T_RT_HOPS);
}
#define s struct ip6t_rt
static const struct xt_option_entry rt_opts[] = {
{.name = "rt-type", .id = O_RT_TYPE, .type = XTTYPE_UINT32,
.flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, rt_type)},
{.name = "rt-segsleft", .id = O_RT_SEGSLEFT, .type = XTTYPE_UINT32RC,
.flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, segsleft)},
{.name = "rt-len", .id = O_RT_LEN, .type = XTTYPE_UINT32,
.flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, hdrlen)},
{.name = "rt-0-res", .id = O_RT0RES, .type = XTTYPE_NONE},
{.name = "rt-0-addrs", .id = O_RT0ADDRS, .type = XTTYPE_STRING},
{.name = "rt-0-not-strict", .id = O_RT0NSTRICT, .type = XTTYPE_NONE},
XTOPT_TABLEEND,
};
#undef s
static const char *
addr_to_numeric(const struct in6_addr *addrp)
{
static char buf[50+1];
return inet_ntop(AF_INET6, addrp, buf, sizeof(buf));
}
static struct in6_addr *
numeric_to_addr(const char *num)
{
static struct in6_addr ap;
int err;
if ((err=inet_pton(AF_INET6, num, &ap)) == 1)
return ≈
#ifdef DEBUG
fprintf(stderr, "\nnumeric2addr: %d\n", err);
#endif
xtables_error(PARAMETER_PROBLEM, "bad address: %s", num);
return (struct in6_addr *)NULL;
}
static int
parse_addresses(const char *addrstr, struct in6_addr *addrp)
{
char *buffer, *cp, *next;
unsigned int i;
buffer = strdup(addrstr);
if (!buffer) xtables_error(OTHER_PROBLEM, "strdup failed");
for (cp=buffer, i=0; cp && i<IP6T_RT_HOPS; cp=next,i++)
{
next=strchr(cp, ',');
if (next) *next++='\0';
memcpy(&(addrp[i]), numeric_to_addr(cp), sizeof(struct in6_addr));
#if DEBUG
printf("addr str: %s\n", cp);
printf("addr ip6: %s\n", addr_to_numeric((numeric_to_addr(cp))));
printf("addr [%d]: %s\n", i, addr_to_numeric(&(addrp[i])));
#endif
}
if (cp) xtables_error(PARAMETER_PROBLEM, "too many addresses specified");
free(buffer);
#if DEBUG
printf("addr nr: %d\n", i);
#endif
return i;
}
static void rt_parse(struct xt_option_call *cb)
{
struct ip6t_rt *rtinfo = cb->data;
xtables_option_parse(cb);
switch (cb->entry->id) {
case O_RT_TYPE:
if (cb->invert)
rtinfo->invflags |= IP6T_RT_INV_TYP;
rtinfo->flags |= IP6T_RT_TYP;
break;
case O_RT_SEGSLEFT:
if (cb->nvals == 1)
rtinfo->segsleft[1] = rtinfo->segsleft[0];
if (cb->invert)
rtinfo->invflags |= IP6T_RT_INV_SGS;
rtinfo->flags |= IP6T_RT_SGS;
break;
case O_RT_LEN:
if (cb->invert)
rtinfo->invflags |= IP6T_RT_INV_LEN;
rtinfo->flags |= IP6T_RT_LEN;
break;
case O_RT0RES:
if (!(cb->xflags & F_RT_TYPE) || rtinfo->rt_type != 0 ||
rtinfo->invflags & IP6T_RT_INV_TYP)
xtables_error(PARAMETER_PROBLEM,
"`--rt-type 0' required before `--rt-0-res'");
rtinfo->flags |= IP6T_RT_RES;
break;
case O_RT0ADDRS:
if (!(cb->xflags & F_RT_TYPE) || rtinfo->rt_type != 0 ||
rtinfo->invflags & IP6T_RT_INV_TYP)
xtables_error(PARAMETER_PROBLEM,
"`--rt-type 0' required before `--rt-0-addrs'");
rtinfo->addrnr = parse_addresses(cb->arg, rtinfo->addrs);
rtinfo->flags |= IP6T_RT_FST;
break;
case O_RT0NSTRICT:
if (!(cb->xflags & F_RT0ADDRS))
xtables_error(PARAMETER_PROBLEM,
"`--rt-0-addr ...' required before `--rt-0-not-strict'");
rtinfo->flags |= IP6T_RT_FST_NSTRICT;
break;
}
}
static void
print_nums(const char *name, uint32_t min, uint32_t max,
int invert)
{
const char *inv = invert ? "!" : "";
if (min != 0 || max != 0xFFFFFFFF || invert) {
printf(" %s", name);
if (min == max) {
printf(":%s", inv);
printf("%u", min);
} else {
printf("s:%s", inv);
printf("%u",min);
printf(":");
printf("%u",max);
}
}
}
static void
print_addresses(unsigned int addrnr, struct in6_addr *addrp)
{
unsigned int i;
for(i=0; i<addrnr; i++){
printf("%c%s", (i==0)?' ':',', addr_to_numeric(&(addrp[i])));
}
}
static void rt_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
const struct ip6t_rt *rtinfo = (struct ip6t_rt *)match->data;
printf(" rt");
if (rtinfo->flags & IP6T_RT_TYP)
printf(" type:%s%d", rtinfo->invflags & IP6T_RT_INV_TYP ? "!" : "",
rtinfo->rt_type);
print_nums("segsleft", rtinfo->segsleft[0], rtinfo->segsleft[1],
rtinfo->invflags & IP6T_RT_INV_SGS);
if (rtinfo->flags & IP6T_RT_LEN) {
printf(" length");
printf(":%s", rtinfo->invflags & IP6T_RT_INV_LEN ? "!" : "");
printf("%u", rtinfo->hdrlen);
}
if (rtinfo->flags & IP6T_RT_RES) printf(" reserved");
if (rtinfo->flags & IP6T_RT_FST) printf(" 0-addrs");
print_addresses(rtinfo->addrnr, (struct in6_addr *)rtinfo->addrs);
if (rtinfo->flags & IP6T_RT_FST_NSTRICT) printf(" 0-not-strict");
if (rtinfo->invflags & ~IP6T_RT_INV_MASK)
printf(" Unknown invflags: 0x%X",
rtinfo->invflags & ~IP6T_RT_INV_MASK);
}
static void rt_save(const void *ip, const struct xt_entry_match *match)
{
const struct ip6t_rt *rtinfo = (struct ip6t_rt *)match->data;
if (rtinfo->flags & IP6T_RT_TYP) {
printf("%s --rt-type %u",
(rtinfo->invflags & IP6T_RT_INV_TYP) ? " !" : "",
rtinfo->rt_type);
}
if (!(rtinfo->segsleft[0] == 0
&& rtinfo->segsleft[1] == 0xFFFFFFFF)) {
printf("%s --rt-segsleft ",
(rtinfo->invflags & IP6T_RT_INV_SGS) ? " !" : "");
if (rtinfo->segsleft[0]
!= rtinfo->segsleft[1])
printf("%u:%u",
rtinfo->segsleft[0],
rtinfo->segsleft[1]);
else
printf("%u",
rtinfo->segsleft[0]);
}
if (rtinfo->flags & IP6T_RT_LEN) {
printf("%s --rt-len %u",
(rtinfo->invflags & IP6T_RT_INV_LEN) ? " !" : "",
rtinfo->hdrlen);
}
if (rtinfo->flags & IP6T_RT_RES) printf(" --rt-0-res");
if (rtinfo->flags & IP6T_RT_FST) printf(" --rt-0-addrs");
print_addresses(rtinfo->addrnr, (struct in6_addr *)rtinfo->addrs);
if (rtinfo->flags & IP6T_RT_FST_NSTRICT) printf(" --rt-0-not-strict");
}
static struct xtables_match rt_mt6_reg = {
.name = "rt",
.version = XTABLES_VERSION,
.family = NFPROTO_IPV6,
.size = XT_ALIGN(sizeof(struct ip6t_rt)),
.userspacesize = XT_ALIGN(sizeof(struct ip6t_rt)),
.help = rt_help,
.x6_parse = rt_parse,
.print = rt_print,
.save = rt_save,
.x6_options = rt_opts,
};
void
_init(void)
{
xtables_register_match(&rt_mt6_reg);
}
|
316 | ./android_firewall/external/iptables/extensions/libxt_string.c | /* Shared library add-on to iptables to add string matching support.
*
* Copyright (C) 2000 Emmanuel Roger <[email protected]>
*
* 2005-08-05 Pablo Neira Ayuso <[email protected]>
* - reimplemented to use new string matching iptables match
* - add functionality to match packets by using window offsets
* - add functionality to select the string matching algorithm
*
* ChangeLog
* 29.12.2003: Michael Rash <[email protected]>
* Fixed iptables save/restore for ascii strings
* that contain space chars, and hex strings that
* contain embedded NULL chars. Updated to print
* strings in hex mode if any non-printable char
* is contained within the string.
*
* 27.01.2001: Gianni Tedesco <[email protected]>
* Changed --tos to --string in save(). Also
* updated to work with slightly modified
* ipt_string_info.
*/
#define _GNU_SOURCE 1 /* strnlen for older glibcs */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <xtables.h>
#include <linux/netfilter/xt_string.h>
enum {
O_FROM = 0,
O_TO,
O_ALGO,
O_ICASE,
O_STRING,
O_HEX_STRING,
F_STRING = 1 << O_STRING,
F_HEX_STRING = 1 << O_HEX_STRING,
F_OP_ANY = F_STRING | F_HEX_STRING,
};
static void string_help(void)
{
printf(
"string match options:\n"
"--from Offset to start searching from\n"
"--to Offset to stop searching\n"
"--algo Algorithm\n"
"--icase Ignore case (default: 0)\n"
"[!] --string string Match a string in a packet\n"
"[!] --hex-string string Match a hex string in a packet\n");
}
#define s struct xt_string_info
static const struct xt_option_entry string_opts[] = {
{.name = "from", .id = O_FROM, .type = XTTYPE_UINT16,
.flags = XTOPT_PUT, XTOPT_POINTER(s, from_offset)},
{.name = "to", .id = O_TO, .type = XTTYPE_UINT16,
.flags = XTOPT_PUT, XTOPT_POINTER(s, to_offset)},
{.name = "algo", .id = O_ALGO, .type = XTTYPE_STRING,
.flags = XTOPT_MAND | XTOPT_PUT, XTOPT_POINTER(s, algo)},
{.name = "string", .id = O_STRING, .type = XTTYPE_STRING,
.flags = XTOPT_INVERT, .excl = F_HEX_STRING},
{.name = "hex-string", .id = O_HEX_STRING, .type = XTTYPE_STRING,
.flags = XTOPT_INVERT, .excl = F_STRING},
{.name = "icase", .id = O_ICASE, .type = XTTYPE_NONE},
XTOPT_TABLEEND,
};
#undef s
static void string_init(struct xt_entry_match *m)
{
struct xt_string_info *i = (struct xt_string_info *) m->data;
i->to_offset = UINT16_MAX;
}
static void
parse_string(const char *s, struct xt_string_info *info)
{
/* xt_string does not need \0 at the end of the pattern */
if (strlen(s) <= XT_STRING_MAX_PATTERN_SIZE) {
strncpy(info->pattern, s, XT_STRING_MAX_PATTERN_SIZE);
info->patlen = strnlen(s, XT_STRING_MAX_PATTERN_SIZE);
return;
}
xtables_error(PARAMETER_PROBLEM, "STRING too long \"%s\"", s);
}
static void
parse_hex_string(const char *s, struct xt_string_info *info)
{
int i=0, slen, sindex=0, schar;
short hex_f = 0, literal_f = 0;
char hextmp[3];
slen = strlen(s);
if (slen == 0) {
xtables_error(PARAMETER_PROBLEM,
"STRING must contain at least one char");
}
while (i < slen) {
if (s[i] == '\\' && !hex_f) {
literal_f = 1;
} else if (s[i] == '\\') {
xtables_error(PARAMETER_PROBLEM,
"Cannot include literals in hex data");
} else if (s[i] == '|') {
if (hex_f)
hex_f = 0;
else {
hex_f = 1;
/* get past any initial whitespace just after the '|' */
while (s[i+1] == ' ')
i++;
}
if (i+1 >= slen)
break;
else
i++; /* advance to the next character */
}
if (literal_f) {
if (i+1 >= slen) {
xtables_error(PARAMETER_PROBLEM,
"Bad literal placement at end of string");
}
info->pattern[sindex] = s[i+1];
i += 2; /* skip over literal char */
literal_f = 0;
} else if (hex_f) {
if (i+1 >= slen) {
xtables_error(PARAMETER_PROBLEM,
"Odd number of hex digits");
}
if (i+2 >= slen) {
/* must end with a "|" */
xtables_error(PARAMETER_PROBLEM, "Invalid hex block");
}
if (! isxdigit(s[i])) /* check for valid hex char */
xtables_error(PARAMETER_PROBLEM, "Invalid hex char '%c'", s[i]);
if (! isxdigit(s[i+1])) /* check for valid hex char */
xtables_error(PARAMETER_PROBLEM, "Invalid hex char '%c'", s[i+1]);
hextmp[0] = s[i];
hextmp[1] = s[i+1];
hextmp[2] = '\0';
if (! sscanf(hextmp, "%x", &schar))
xtables_error(PARAMETER_PROBLEM,
"Invalid hex char `%c'", s[i]);
info->pattern[sindex] = (char) schar;
if (s[i+2] == ' ')
i += 3; /* spaces included in the hex block */
else
i += 2;
} else { /* the char is not part of hex data, so just copy */
info->pattern[sindex] = s[i];
i++;
}
if (sindex > XT_STRING_MAX_PATTERN_SIZE)
xtables_error(PARAMETER_PROBLEM, "STRING too long \"%s\"", s);
sindex++;
}
info->patlen = sindex;
}
static void string_parse(struct xt_option_call *cb)
{
struct xt_string_info *stringinfo = cb->data;
const unsigned int revision = (*cb->match)->u.user.revision;
xtables_option_parse(cb);
switch (cb->entry->id) {
case O_STRING:
parse_string(cb->arg, stringinfo);
if (cb->invert) {
if (revision == 0)
stringinfo->u.v0.invert = 1;
else
stringinfo->u.v1.flags |= XT_STRING_FLAG_INVERT;
}
break;
case O_HEX_STRING:
parse_hex_string(cb->arg, stringinfo); /* sets length */
if (cb->invert) {
if (revision == 0)
stringinfo->u.v0.invert = 1;
else
stringinfo->u.v1.flags |= XT_STRING_FLAG_INVERT;
}
break;
case O_ICASE:
if (revision == 0)
xtables_error(VERSION_PROBLEM,
"Kernel doesn't support --icase");
stringinfo->u.v1.flags |= XT_STRING_FLAG_IGNORECASE;
break;
}
}
static void string_check(struct xt_fcheck_call *cb)
{
if (!(cb->xflags & F_OP_ANY))
xtables_error(PARAMETER_PROBLEM,
"STRING match: You must specify `--string' or "
"`--hex-string'");
}
/* Test to see if the string contains non-printable chars or quotes */
static unsigned short int
is_hex_string(const char *str, const unsigned short int len)
{
unsigned int i;
for (i=0; i < len; i++)
if (! isprint(str[i]))
return 1; /* string contains at least one non-printable char */
/* use hex output if the last char is a "\" */
if (str[len-1] == '\\')
return 1;
return 0;
}
/* Print string with "|" chars included as one would pass to --hex-string */
static void
print_hex_string(const char *str, const unsigned short int len)
{
unsigned int i;
/* start hex block */
printf(" \"|");
for (i=0; i < len; i++)
printf("%02x", (unsigned char)str[i]);
/* close hex block */
printf("|\"");
}
static void
print_string(const char *str, const unsigned short int len)
{
unsigned int i;
printf(" \"");
for (i=0; i < len; i++) {
if (str[i] == '\"' || str[i] == '\\')
putchar('\\');
printf("%c", (unsigned char) str[i]);
}
printf("\""); /* closing quote */
}
static void
string_print(const void *ip, const struct xt_entry_match *match, int numeric)
{
const struct xt_string_info *info =
(const struct xt_string_info*) match->data;
const int revision = match->u.user.revision;
int invert = (revision == 0 ? info->u.v0.invert :
info->u.v1.flags & XT_STRING_FLAG_INVERT);
if (is_hex_string(info->pattern, info->patlen)) {
printf(" STRING match %s", invert ? "!" : "");
print_hex_string(info->pattern, info->patlen);
} else {
printf(" STRING match %s", invert ? "!" : "");
print_string(info->pattern, info->patlen);
}
printf(" ALGO name %s", info->algo);
if (info->from_offset != 0)
printf(" FROM %u", info->from_offset);
if (info->to_offset != 0)
printf(" TO %u", info->to_offset);
if (revision > 0 && info->u.v1.flags & XT_STRING_FLAG_IGNORECASE)
printf(" ICASE");
}
static void string_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_string_info *info =
(const struct xt_string_info*) match->data;
const int revision = match->u.user.revision;
int invert = (revision == 0 ? info->u.v0.invert :
info->u.v1.flags & XT_STRING_FLAG_INVERT);
if (is_hex_string(info->pattern, info->patlen)) {
printf("%s --hex-string", (invert) ? " !" : "");
print_hex_string(info->pattern, info->patlen);
} else {
printf("%s --string", (invert) ? " !": "");
print_string(info->pattern, info->patlen);
}
printf(" --algo %s", info->algo);
if (info->from_offset != 0)
printf(" --from %u", info->from_offset);
if (info->to_offset != 0)
printf(" --to %u", info->to_offset);
if (revision > 0 && info->u.v1.flags & XT_STRING_FLAG_IGNORECASE)
printf(" --icase");
}
static struct xtables_match string_mt_reg[] = {
{
.name = "string",
.revision = 0,
.family = NFPROTO_UNSPEC,
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof(struct xt_string_info)),
.userspacesize = offsetof(struct xt_string_info, config),
.help = string_help,
.init = string_init,
.print = string_print,
.save = string_save,
.x6_parse = string_parse,
.x6_fcheck = string_check,
.x6_options = string_opts,
},
{
.name = "string",
.revision = 1,
.family = NFPROTO_UNSPEC,
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof(struct xt_string_info)),
.userspacesize = offsetof(struct xt_string_info, config),
.help = string_help,
.init = string_init,
.print = string_print,
.save = string_save,
.x6_parse = string_parse,
.x6_fcheck = string_check,
.x6_options = string_opts,
},
};
void _init(void)
{
xtables_register_matches(string_mt_reg, ARRAY_SIZE(string_mt_reg));
}
|
317 | ./android_firewall/external/iptables/extensions/libipt_ttl.c | /* Shared library add-on to iptables to add TTL matching support
* (C) 2000 by Harald Welte <[email protected]>
*
* This program is released under the terms of GNU GPL */
#include <stdio.h>
#include <xtables.h>
#include <linux/netfilter_ipv4/ipt_ttl.h>
enum {
O_TTL_EQ = 0,
O_TTL_LT,
O_TTL_GT,
F_TTL_EQ = 1 << O_TTL_EQ,
F_TTL_LT = 1 << O_TTL_LT,
F_TTL_GT = 1 << O_TTL_GT,
F_ANY = F_TTL_EQ | F_TTL_LT | F_TTL_GT,
};
static void ttl_help(void)
{
printf(
"ttl match options:\n"
"[!] --ttl-eq value Match time to live value\n"
" --ttl-lt value Match TTL < value\n"
" --ttl-gt value Match TTL > value\n");
}
static void ttl_parse(struct xt_option_call *cb)
{
struct ipt_ttl_info *info = cb->data;
xtables_option_parse(cb);
switch (cb->entry->id) {
case O_TTL_EQ:
info->mode = cb->invert ? IPT_TTL_NE : IPT_TTL_EQ;
break;
case O_TTL_LT:
info->mode = IPT_TTL_LT;
break;
case O_TTL_GT:
info->mode = IPT_TTL_GT;
break;
}
}
static void ttl_check(struct xt_fcheck_call *cb)
{
if (!(cb->xflags & F_ANY))
xtables_error(PARAMETER_PROBLEM,
"TTL match: You must specify one of "
"`--ttl-eq', `--ttl-lt', `--ttl-gt");
}
static void ttl_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
const struct ipt_ttl_info *info =
(struct ipt_ttl_info *) match->data;
printf(" TTL match ");
switch (info->mode) {
case IPT_TTL_EQ:
printf("TTL ==");
break;
case IPT_TTL_NE:
printf("TTL !=");
break;
case IPT_TTL_LT:
printf("TTL <");
break;
case IPT_TTL_GT:
printf("TTL >");
break;
}
printf(" %u", info->ttl);
}
static void ttl_save(const void *ip, const struct xt_entry_match *match)
{
const struct ipt_ttl_info *info =
(struct ipt_ttl_info *) match->data;
switch (info->mode) {
case IPT_TTL_EQ:
printf(" --ttl-eq");
break;
case IPT_TTL_NE:
printf(" ! --ttl-eq");
break;
case IPT_TTL_LT:
printf(" --ttl-lt");
break;
case IPT_TTL_GT:
printf(" --ttl-gt");
break;
default:
/* error */
break;
}
printf(" %u", info->ttl);
}
#define s struct ipt_ttl_info
static const struct xt_option_entry ttl_opts[] = {
{.name = "ttl-lt", .id = O_TTL_LT, .excl = F_ANY, .type = XTTYPE_UINT8,
.flags = XTOPT_PUT, XTOPT_POINTER(s, ttl)},
{.name = "ttl-gt", .id = O_TTL_GT, .excl = F_ANY, .type = XTTYPE_UINT8,
.flags = XTOPT_PUT, XTOPT_POINTER(s, ttl)},
{.name = "ttl-eq", .id = O_TTL_EQ, .excl = F_ANY, .type = XTTYPE_UINT8,
.flags = XTOPT_INVERT | XTOPT_PUT, XTOPT_POINTER(s, ttl)},
{.name = "ttl", .id = O_TTL_EQ, .excl = F_ANY, .type = XTTYPE_UINT8,
.flags = XTOPT_PUT, XTOPT_POINTER(s, ttl)},
XTOPT_TABLEEND,
};
#undef s
static struct xtables_match ttl_mt_reg = {
.name = "ttl",
.version = XTABLES_VERSION,
.family = NFPROTO_IPV4,
.size = XT_ALIGN(sizeof(struct ipt_ttl_info)),
.userspacesize = XT_ALIGN(sizeof(struct ipt_ttl_info)),
.help = ttl_help,
.print = ttl_print,
.save = ttl_save,
.x6_parse = ttl_parse,
.x6_fcheck = ttl_check,
.x6_options = ttl_opts,
};
void _init(void)
{
xtables_register_match(&ttl_mt_reg);
}
|
318 | ./android_firewall/external/iptables/extensions/libxt_SECMARK.c | /*
* Shared library add-on to iptables to add SECMARK target support.
*
* Based on the MARK target.
*
* Copyright (C) 2006 Red Hat, Inc., James Morris <[email protected]>
*/
#include <stdio.h>
#include <xtables.h>
#include <linux/netfilter/xt_SECMARK.h>
#define PFX "SECMARK target: "
enum {
O_SELCTX = 0,
};
static void SECMARK_help(void)
{
printf(
"SECMARK target options:\n"
" --selctx value Set the SELinux security context\n");
}
static const struct xt_option_entry SECMARK_opts[] = {
{.name = "selctx", .id = O_SELCTX, .type = XTTYPE_STRING,
.flags = XTOPT_MAND | XTOPT_PUT,
XTOPT_POINTER(struct xt_secmark_target_info, secctx)},
XTOPT_TABLEEND,
};
static void SECMARK_parse(struct xt_option_call *cb)
{
struct xt_secmark_target_info *info = cb->data;
xtables_option_parse(cb);
info->mode = SECMARK_MODE_SEL;
}
static void print_secmark(const struct xt_secmark_target_info *info)
{
switch (info->mode) {
case SECMARK_MODE_SEL:
printf("selctx %s", info->secctx);
break;
default:
xtables_error(OTHER_PROBLEM, PFX "invalid mode %hhu\n", info->mode);
}
}
static void SECMARK_print(const void *ip, const struct xt_entry_target *target,
int numeric)
{
const struct xt_secmark_target_info *info =
(struct xt_secmark_target_info*)(target)->data;
printf(" SECMARK ");
print_secmark(info);
}
static void SECMARK_save(const void *ip, const struct xt_entry_target *target)
{
const struct xt_secmark_target_info *info =
(struct xt_secmark_target_info*)target->data;
printf(" --");
print_secmark(info);
}
static struct xtables_target secmark_target = {
.family = NFPROTO_UNSPEC,
.name = "SECMARK",
.version = XTABLES_VERSION,
.revision = 0,
.size = XT_ALIGN(sizeof(struct xt_secmark_target_info)),
.userspacesize = XT_ALIGN(sizeof(struct xt_secmark_target_info)),
.help = SECMARK_help,
.print = SECMARK_print,
.save = SECMARK_save,
.x6_parse = SECMARK_parse,
.x6_options = SECMARK_opts,
};
void _init(void)
{
xtables_register_target(&secmark_target);
}
|
319 | ./android_firewall/external/iptables/extensions/libipt_SAME.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <xtables.h>
#include <net/netfilter/nf_nat.h>
#include <linux/netfilter_ipv4/ipt_SAME.h>
enum {
O_TO_ADDR = 0,
O_NODST,
O_RANDOM,
F_TO_ADDR = 1 << O_TO_ADDR,
F_RANDOM = 1 << O_RANDOM,
};
static void SAME_help(void)
{
printf(
"SAME target options:\n"
" --to <ipaddr>-<ipaddr>\n"
" Addresses to map source to.\n"
" May be specified more than\n"
" once for multiple ranges.\n"
" --nodst\n"
" Don't use destination-ip in\n"
" source selection\n"
" --random\n"
" Randomize source port\n");
}
static const struct xt_option_entry SAME_opts[] = {
{.name = "to", .id = O_TO_ADDR, .type = XTTYPE_STRING,
.flags = XTOPT_MAND},
{.name = "nodst", .id = O_NODST, .type = XTTYPE_NONE},
{.name = "random", .id = O_RANDOM, .type = XTTYPE_NONE},
XTOPT_TABLEEND,
};
/* Parses range of IPs */
static void parse_to(const char *orig_arg, struct nf_nat_range *range)
{
char *dash, *arg;
const struct in_addr *ip;
arg = strdup(orig_arg);
if (arg == NULL)
xtables_error(RESOURCE_PROBLEM, "strdup");
range->flags |= IP_NAT_RANGE_MAP_IPS;
dash = strchr(arg, '-');
if (dash)
*dash = '\0';
ip = xtables_numeric_to_ipaddr(arg);
if (!ip)
xtables_error(PARAMETER_PROBLEM, "Bad IP address \"%s\"\n",
arg);
range->min_ip = ip->s_addr;
if (dash) {
ip = xtables_numeric_to_ipaddr(dash+1);
if (!ip)
xtables_error(PARAMETER_PROBLEM, "Bad IP address \"%s\"\n",
dash+1);
}
range->max_ip = ip->s_addr;
if (dash)
if (range->min_ip > range->max_ip)
xtables_error(PARAMETER_PROBLEM, "Bad IP range \"%s-%s\"\n",
arg, dash+1);
free(arg);
}
static void SAME_parse(struct xt_option_call *cb)
{
struct ipt_same_info *mr = cb->data;
xtables_option_parse(cb);
switch (cb->entry->id) {
case O_TO_ADDR:
if (mr->rangesize == IPT_SAME_MAX_RANGE)
xtables_error(PARAMETER_PROBLEM,
"Too many ranges specified, maximum "
"is %i ranges.\n",
IPT_SAME_MAX_RANGE);
parse_to(cb->arg, &mr->range[mr->rangesize]);
mr->rangesize++;
break;
case O_NODST:
mr->info |= IPT_SAME_NODST;
break;
}
}
static void SAME_fcheck(struct xt_fcheck_call *cb)
{
static const unsigned int f = F_TO_ADDR | F_RANDOM;
struct ipt_same_info *mr = cb->data;
unsigned int count;
if ((cb->xflags & f) == f)
for (count = 0; count < mr->rangesize; ++count)
mr->range[count].flags |= IP_NAT_RANGE_PROTO_RANDOM;
}
static void SAME_print(const void *ip, const struct xt_entry_target *target,
int numeric)
{
unsigned int count;
const struct ipt_same_info *mr = (const void *)target->data;
int random_selection = 0;
printf(" same:");
for (count = 0; count < mr->rangesize; count++) {
const struct nf_nat_range *r = &mr->range[count];
struct in_addr a;
a.s_addr = r->min_ip;
printf("%s", xtables_ipaddr_to_numeric(&a));
a.s_addr = r->max_ip;
if (r->min_ip != r->max_ip)
printf("-%s", xtables_ipaddr_to_numeric(&a));
if (r->flags & IP_NAT_RANGE_PROTO_RANDOM)
random_selection = 1;
}
if (mr->info & IPT_SAME_NODST)
printf(" nodst");
if (random_selection)
printf(" random");
}
static void SAME_save(const void *ip, const struct xt_entry_target *target)
{
unsigned int count;
const struct ipt_same_info *mr = (const void *)target->data;
int random_selection = 0;
for (count = 0; count < mr->rangesize; count++) {
const struct nf_nat_range *r = &mr->range[count];
struct in_addr a;
a.s_addr = r->min_ip;
printf(" --to %s", xtables_ipaddr_to_numeric(&a));
a.s_addr = r->max_ip;
if (r->min_ip != r->max_ip)
printf("-%s", xtables_ipaddr_to_numeric(&a));
if (r->flags & IP_NAT_RANGE_PROTO_RANDOM)
random_selection = 1;
}
if (mr->info & IPT_SAME_NODST)
printf(" --nodst");
if (random_selection)
printf(" --random");
}
static struct xtables_target same_tg_reg = {
.name = "SAME",
.version = XTABLES_VERSION,
.family = NFPROTO_IPV4,
.size = XT_ALIGN(sizeof(struct ipt_same_info)),
.userspacesize = XT_ALIGN(sizeof(struct ipt_same_info)),
.help = SAME_help,
.x6_parse = SAME_parse,
.x6_fcheck = SAME_fcheck,
.print = SAME_print,
.save = SAME_save,
.x6_options = SAME_opts,
};
void _init(void)
{
xtables_register_target(&same_tg_reg);
}
|
320 | ./android_firewall/external/iptables/extensions/libxt_tos.c | /*
* Shared library add-on to iptables to add tos match support
*
* Copyright © CC Computer Consultants GmbH, 2007
* Contact: Jan Engelhardt <[email protected]>
*/
#include <getopt.h>
#include <netdb.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <xtables.h>
#include <linux/netfilter/xt_dscp.h>
#include "tos_values.c"
struct ipt_tos_info {
uint8_t tos;
uint8_t invert;
};
enum {
O_TOS = 1 << 0,
};
static const struct xt_option_entry tos_mt_opts_v0[] = {
{.name = "tos", .id = O_TOS, .type = XTTYPE_TOSMASK,
.flags = XTOPT_INVERT | XTOPT_MAND, .max = 0xFF},
XTOPT_TABLEEND,
};
static const struct xt_option_entry tos_mt_opts[] = {
{.name = "tos", .id = O_TOS, .type = XTTYPE_TOSMASK,
.flags = XTOPT_INVERT | XTOPT_MAND, .max = 0x3F},
XTOPT_TABLEEND,
};
static void tos_mt_help(void)
{
const struct tos_symbol_info *symbol;
printf(
"tos match options:\n"
"[!] --tos value[/mask] Match Type of Service/Priority field value\n"
"[!] --tos symbol Match TOS field (IPv4 only) by symbol\n"
" Accepted symbolic names for value are:\n");
for (symbol = tos_symbol_names; symbol->name != NULL; ++symbol)
printf(" (0x%02x) %2u %s\n",
symbol->value, symbol->value, symbol->name);
printf("\n");
}
static void tos_mt_parse_v0(struct xt_option_call *cb)
{
struct ipt_tos_info *info = cb->data;
xtables_option_parse(cb);
if (cb->val.tos_mask != 0xFF)
xtables_error(PARAMETER_PROBLEM, "tos: Your kernel is "
"too old to support anything besides /0xFF "
"as a mask.");
info->tos = cb->val.tos_value;
if (cb->invert)
info->invert = true;
}
static void tos_mt_parse(struct xt_option_call *cb)
{
struct xt_tos_match_info *info = cb->data;
xtables_option_parse(cb);
info->tos_value = cb->val.tos_value;
info->tos_mask = cb->val.tos_mask;
if (cb->invert)
info->invert = true;
}
static void tos_mt_print_v0(const void *ip, const struct xt_entry_match *match,
int numeric)
{
const struct ipt_tos_info *info = (const void *)match->data;
printf(" tos match ");
if (info->invert)
printf("!");
if (numeric || !tos_try_print_symbolic("", info->tos, 0x3F))
printf("0x%02x", info->tos);
}
static void tos_mt_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
const struct xt_tos_match_info *info = (const void *)match->data;
printf(" tos match");
if (info->invert)
printf("!");
if (numeric ||
!tos_try_print_symbolic("", info->tos_value, info->tos_mask))
printf("0x%02x/0x%02x", info->tos_value, info->tos_mask);
}
static void tos_mt_save_v0(const void *ip, const struct xt_entry_match *match)
{
const struct ipt_tos_info *info = (const void *)match->data;
if (info->invert)
printf(" !");
printf(" --tos 0x%02x", info->tos);
}
static void tos_mt_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_tos_match_info *info = (const void *)match->data;
if (info->invert)
printf(" !");
printf(" --tos 0x%02x/0x%02x", info->tos_value, info->tos_mask);
}
static struct xtables_match tos_mt_reg[] = {
{
.version = XTABLES_VERSION,
.name = "tos",
.family = NFPROTO_IPV4,
.revision = 0,
.size = XT_ALIGN(sizeof(struct ipt_tos_info)),
.userspacesize = XT_ALIGN(sizeof(struct ipt_tos_info)),
.help = tos_mt_help,
.print = tos_mt_print_v0,
.save = tos_mt_save_v0,
.x6_parse = tos_mt_parse_v0,
.x6_options = tos_mt_opts_v0,
},
{
.version = XTABLES_VERSION,
.name = "tos",
.family = NFPROTO_UNSPEC,
.revision = 1,
.size = XT_ALIGN(sizeof(struct xt_tos_match_info)),
.userspacesize = XT_ALIGN(sizeof(struct xt_tos_match_info)),
.help = tos_mt_help,
.print = tos_mt_print,
.save = tos_mt_save,
.x6_parse = tos_mt_parse,
.x6_options = tos_mt_opts,
},
};
void _init(void)
{
xtables_register_matches(tos_mt_reg, ARRAY_SIZE(tos_mt_reg));
}
|
321 | ./android_firewall/external/iptables/extensions/libxt_tcp.c | /* Shared library add-on to iptables to add TCP support. */
#include <stdbool.h>
#include <stdio.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <getopt.h>
#include <netinet/in.h>
#include <xtables.h>
#include <linux/netfilter/xt_tcpudp.h>
static void tcp_help(void)
{
printf(
"tcp match options:\n"
"[!] --tcp-flags mask comp match when TCP flags & mask == comp\n"
" (Flags: SYN ACK FIN RST URG PSH ALL NONE)\n"
"[!] --syn match when only SYN flag set\n"
" (equivalent to --tcp-flags SYN,RST,ACK,FIN SYN)\n"
"[!] --source-port port[:port]\n"
" --sport ...\n"
" match source port(s)\n"
"[!] --destination-port port[:port]\n"
" --dport ...\n"
" match destination port(s)\n"
"[!] --tcp-option number match if TCP option set\n");
}
static const struct option tcp_opts[] = {
{.name = "source-port", .has_arg = true, .val = '1'},
{.name = "sport", .has_arg = true, .val = '1'}, /* synonym */
{.name = "destination-port", .has_arg = true, .val = '2'},
{.name = "dport", .has_arg = true, .val = '2'}, /* synonym */
{.name = "syn", .has_arg = false, .val = '3'},
{.name = "tcp-flags", .has_arg = true, .val = '4'},
{.name = "tcp-option", .has_arg = true, .val = '5'},
XT_GETOPT_TABLEEND,
};
static void
parse_tcp_ports(const char *portstring, uint16_t *ports)
{
char *buffer;
char *cp;
buffer = strdup(portstring);
if ((cp = strchr(buffer, ':')) == NULL)
ports[0] = ports[1] = xtables_parse_port(buffer, "tcp");
else {
*cp = '\0';
cp++;
ports[0] = buffer[0] ? xtables_parse_port(buffer, "tcp") : 0;
ports[1] = cp[0] ? xtables_parse_port(cp, "tcp") : 0xFFFF;
if (ports[0] > ports[1])
xtables_error(PARAMETER_PROBLEM,
"invalid portrange (min > max)");
}
free(buffer);
}
struct tcp_flag_names {
const char *name;
unsigned int flag;
};
static const struct tcp_flag_names tcp_flag_names[]
= { { "FIN", 0x01 },
{ "SYN", 0x02 },
{ "RST", 0x04 },
{ "PSH", 0x08 },
{ "ACK", 0x10 },
{ "URG", 0x20 },
{ "ALL", 0x3F },
{ "NONE", 0 },
};
static unsigned int
parse_tcp_flag(const char *flags)
{
unsigned int ret = 0;
char *ptr;
char *buffer;
buffer = strdup(flags);
for (ptr = strtok(buffer, ","); ptr; ptr = strtok(NULL, ",")) {
unsigned int i;
for (i = 0; i < ARRAY_SIZE(tcp_flag_names); ++i)
if (strcasecmp(tcp_flag_names[i].name, ptr) == 0) {
ret |= tcp_flag_names[i].flag;
break;
}
if (i == ARRAY_SIZE(tcp_flag_names))
xtables_error(PARAMETER_PROBLEM,
"Unknown TCP flag `%s'", ptr);
}
free(buffer);
return ret;
}
static void
parse_tcp_flags(struct xt_tcp *tcpinfo,
const char *mask,
const char *cmp,
int invert)
{
tcpinfo->flg_mask = parse_tcp_flag(mask);
tcpinfo->flg_cmp = parse_tcp_flag(cmp);
if (invert)
tcpinfo->invflags |= XT_TCP_INV_FLAGS;
}
static void
parse_tcp_option(const char *option, uint8_t *result)
{
unsigned int ret;
if (!xtables_strtoui(option, NULL, &ret, 1, UINT8_MAX))
xtables_error(PARAMETER_PROBLEM, "Bad TCP option \"%s\"", option);
*result = ret;
}
static void tcp_init(struct xt_entry_match *m)
{
struct xt_tcp *tcpinfo = (struct xt_tcp *)m->data;
tcpinfo->spts[1] = tcpinfo->dpts[1] = 0xFFFF;
}
#define TCP_SRC_PORTS 0x01
#define TCP_DST_PORTS 0x02
#define TCP_FLAGS 0x04
#define TCP_OPTION 0x08
static int
tcp_parse(int c, char **argv, int invert, unsigned int *flags,
const void *entry, struct xt_entry_match **match)
{
struct xt_tcp *tcpinfo = (struct xt_tcp *)(*match)->data;
switch (c) {
case '1':
if (*flags & TCP_SRC_PORTS)
xtables_error(PARAMETER_PROBLEM,
"Only one `--source-port' allowed");
parse_tcp_ports(optarg, tcpinfo->spts);
if (invert)
tcpinfo->invflags |= XT_TCP_INV_SRCPT;
*flags |= TCP_SRC_PORTS;
break;
case '2':
if (*flags & TCP_DST_PORTS)
xtables_error(PARAMETER_PROBLEM,
"Only one `--destination-port' allowed");
parse_tcp_ports(optarg, tcpinfo->dpts);
if (invert)
tcpinfo->invflags |= XT_TCP_INV_DSTPT;
*flags |= TCP_DST_PORTS;
break;
case '3':
if (*flags & TCP_FLAGS)
xtables_error(PARAMETER_PROBLEM,
"Only one of `--syn' or `--tcp-flags' "
" allowed");
parse_tcp_flags(tcpinfo, "SYN,RST,ACK,FIN", "SYN", invert);
*flags |= TCP_FLAGS;
break;
case '4':
if (*flags & TCP_FLAGS)
xtables_error(PARAMETER_PROBLEM,
"Only one of `--syn' or `--tcp-flags' "
" allowed");
if (!argv[optind]
|| argv[optind][0] == '-' || argv[optind][0] == '!')
xtables_error(PARAMETER_PROBLEM,
"--tcp-flags requires two args.");
parse_tcp_flags(tcpinfo, optarg, argv[optind],
invert);
optind++;
*flags |= TCP_FLAGS;
break;
case '5':
if (*flags & TCP_OPTION)
xtables_error(PARAMETER_PROBLEM,
"Only one `--tcp-option' allowed");
parse_tcp_option(optarg, &tcpinfo->option);
if (invert)
tcpinfo->invflags |= XT_TCP_INV_OPTION;
*flags |= TCP_OPTION;
break;
}
return 1;
}
static const char *
port_to_service(int port)
{
const struct servent *service;
if ((service = getservbyport(htons(port), "tcp")))
return service->s_name;
return NULL;
}
static void
print_port(uint16_t port, int numeric)
{
const char *service;
if (numeric || (service = port_to_service(port)) == NULL)
printf("%u", port);
else
printf("%s", service);
}
static void
print_ports(const char *name, uint16_t min, uint16_t max,
int invert, int numeric)
{
const char *inv = invert ? "!" : "";
if (min != 0 || max != 0xFFFF || invert) {
printf(" %s", name);
if (min == max) {
printf(":%s", inv);
print_port(min, numeric);
} else {
printf("s:%s", inv);
print_port(min, numeric);
printf(":");
print_port(max, numeric);
}
}
}
static void
print_option(uint8_t option, int invert, int numeric)
{
if (option || invert)
printf(" option=%s%u", invert ? "!" : "", option);
}
static void
print_tcpf(uint8_t flags)
{
int have_flag = 0;
while (flags) {
unsigned int i;
for (i = 0; (flags & tcp_flag_names[i].flag) == 0; i++);
if (have_flag)
printf(",");
printf("%s", tcp_flag_names[i].name);
have_flag = 1;
flags &= ~tcp_flag_names[i].flag;
}
if (!have_flag)
printf("NONE");
}
static void
print_flags(uint8_t mask, uint8_t cmp, int invert, int numeric)
{
if (mask || invert) {
printf(" flags:%s", invert ? "!" : "");
if (numeric)
printf("0x%02X/0x%02X", mask, cmp);
else {
print_tcpf(mask);
printf("/");
print_tcpf(cmp);
}
}
}
static void
tcp_print(const void *ip, const struct xt_entry_match *match, int numeric)
{
const struct xt_tcp *tcp = (struct xt_tcp *)match->data;
printf(" tcp");
print_ports("spt", tcp->spts[0], tcp->spts[1],
tcp->invflags & XT_TCP_INV_SRCPT,
numeric);
print_ports("dpt", tcp->dpts[0], tcp->dpts[1],
tcp->invflags & XT_TCP_INV_DSTPT,
numeric);
print_option(tcp->option,
tcp->invflags & XT_TCP_INV_OPTION,
numeric);
print_flags(tcp->flg_mask, tcp->flg_cmp,
tcp->invflags & XT_TCP_INV_FLAGS,
numeric);
if (tcp->invflags & ~XT_TCP_INV_MASK)
printf(" Unknown invflags: 0x%X",
tcp->invflags & ~XT_TCP_INV_MASK);
}
static void tcp_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_tcp *tcpinfo = (struct xt_tcp *)match->data;
if (tcpinfo->spts[0] != 0
|| tcpinfo->spts[1] != 0xFFFF) {
if (tcpinfo->invflags & XT_TCP_INV_SRCPT)
printf(" !");
if (tcpinfo->spts[0]
!= tcpinfo->spts[1])
printf(" --sport %u:%u",
tcpinfo->spts[0],
tcpinfo->spts[1]);
else
printf(" --sport %u",
tcpinfo->spts[0]);
}
if (tcpinfo->dpts[0] != 0
|| tcpinfo->dpts[1] != 0xFFFF) {
if (tcpinfo->invflags & XT_TCP_INV_DSTPT)
printf(" !");
if (tcpinfo->dpts[0]
!= tcpinfo->dpts[1])
printf(" --dport %u:%u",
tcpinfo->dpts[0],
tcpinfo->dpts[1]);
else
printf(" --dport %u",
tcpinfo->dpts[0]);
}
if (tcpinfo->option
|| (tcpinfo->invflags & XT_TCP_INV_OPTION)) {
if (tcpinfo->invflags & XT_TCP_INV_OPTION)
printf(" !");
printf(" --tcp-option %u", tcpinfo->option);
}
if (tcpinfo->flg_mask
|| (tcpinfo->invflags & XT_TCP_INV_FLAGS)) {
if (tcpinfo->invflags & XT_TCP_INV_FLAGS)
printf(" !");
printf(" --tcp-flags ");
print_tcpf(tcpinfo->flg_mask);
printf(" ");
print_tcpf(tcpinfo->flg_cmp);
}
}
static struct xtables_match tcp_match = {
.family = NFPROTO_UNSPEC,
.name = "tcp",
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof(struct xt_tcp)),
.userspacesize = XT_ALIGN(sizeof(struct xt_tcp)),
.help = tcp_help,
.init = tcp_init,
.parse = tcp_parse,
.print = tcp_print,
.save = tcp_save,
.extra_opts = tcp_opts,
};
void
_init(void)
{
xtables_register_match(&tcp_match);
}
|
322 | ./android_firewall/external/iptables/extensions/libxt_tcpmss.c | #include <stdio.h>
#include <xtables.h>
#include <linux/netfilter/xt_tcpmss.h>
enum {
O_TCPMSS = 0,
};
static void tcpmss_help(void)
{
printf(
"tcpmss match options:\n"
"[!] --mss value[:value] Match TCP MSS range.\n"
" (only valid for TCP SYN or SYN/ACK packets)\n");
}
static const struct xt_option_entry tcpmss_opts[] = {
{.name = "mss", .id = O_TCPMSS, .type = XTTYPE_UINT16RC,
.flags = XTOPT_MAND | XTOPT_INVERT},
XTOPT_TABLEEND,
};
static void tcpmss_parse(struct xt_option_call *cb)
{
struct xt_tcpmss_match_info *mssinfo = cb->data;
xtables_option_parse(cb);
mssinfo->mss_min = cb->val.u16_range[0];
mssinfo->mss_max = mssinfo->mss_min;
if (cb->nvals == 2)
mssinfo->mss_max = cb->val.u16_range[1];
if (cb->invert)
mssinfo->invert = 1;
}
static void
tcpmss_print(const void *ip, const struct xt_entry_match *match, int numeric)
{
const struct xt_tcpmss_match_info *info = (void *)match->data;
printf(" tcpmss match %s", info->invert ? "!" : "");
if (info->mss_min == info->mss_max)
printf("%u", info->mss_min);
else
printf("%u:%u", info->mss_min, info->mss_max);
}
static void tcpmss_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_tcpmss_match_info *info = (void *)match->data;
printf("%s --mss ", info->invert ? " !" : "");
if (info->mss_min == info->mss_max)
printf("%u", info->mss_min);
else
printf("%u:%u", info->mss_min, info->mss_max);
}
static struct xtables_match tcpmss_match = {
.family = NFPROTO_UNSPEC,
.name = "tcpmss",
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof(struct xt_tcpmss_match_info)),
.userspacesize = XT_ALIGN(sizeof(struct xt_tcpmss_match_info)),
.help = tcpmss_help,
.print = tcpmss_print,
.save = tcpmss_save,
.x6_parse = tcpmss_parse,
.x6_options = tcpmss_opts,
};
void _init(void)
{
xtables_register_match(&tcpmss_match);
}
|
323 | ./android_firewall/external/iptables/extensions/libip6t_ipv6header.c | /* ipv6header match - matches IPv6 packets based
on whether they contain certain headers */
/* Original idea: Brad Chapman
* Rewritten by: Andras Kis-Szabo <[email protected]> */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <xtables.h>
#include <linux/netfilter_ipv6/ip6t_ipv6header.h>
enum {
O_HEADER = 0,
O_SOFT,
};
/* A few hardcoded protocols for 'all' and in case the user has no
* /etc/protocols */
struct pprot {
char *name;
uint8_t num;
};
struct numflag {
uint8_t proto;
uint8_t flag;
};
static const struct pprot chain_protos[] = {
{ "hop-by-hop", IPPROTO_HOPOPTS },
{ "protocol", IPPROTO_RAW },
{ "hop", IPPROTO_HOPOPTS },
{ "dst", IPPROTO_DSTOPTS },
{ "route", IPPROTO_ROUTING },
{ "frag", IPPROTO_FRAGMENT },
{ "auth", IPPROTO_AH },
{ "esp", IPPROTO_ESP },
{ "none", IPPROTO_NONE },
{ "prot", IPPROTO_RAW },
{ "0", IPPROTO_HOPOPTS },
{ "60", IPPROTO_DSTOPTS },
{ "43", IPPROTO_ROUTING },
{ "44", IPPROTO_FRAGMENT },
{ "51", IPPROTO_AH },
{ "50", IPPROTO_ESP },
{ "59", IPPROTO_NONE },
{ "255", IPPROTO_RAW },
/* { "all", 0 }, */
};
static const struct numflag chain_flags[] = {
{ IPPROTO_HOPOPTS, MASK_HOPOPTS },
{ IPPROTO_DSTOPTS, MASK_DSTOPTS },
{ IPPROTO_ROUTING, MASK_ROUTING },
{ IPPROTO_FRAGMENT, MASK_FRAGMENT },
{ IPPROTO_AH, MASK_AH },
{ IPPROTO_ESP, MASK_ESP },
{ IPPROTO_NONE, MASK_NONE },
{ IPPROTO_RAW, MASK_PROTO },
};
static const char *
proto_to_name(uint8_t proto, int nolookup)
{
unsigned int i;
if (proto && !nolookup) {
const struct protoent *pent = getprotobynumber(proto);
if (pent)
return pent->p_name;
}
for (i = 0; i < ARRAY_SIZE(chain_protos); ++i)
if (chain_protos[i].num == proto)
return chain_protos[i].name;
return NULL;
}
static uint16_t
name_to_proto(const char *s)
{
unsigned int proto=0;
const struct protoent *pent;
if ((pent = getprotobyname(s)))
proto = pent->p_proto;
else {
unsigned int i;
for (i = 0; i < ARRAY_SIZE(chain_protos); ++i)
if (strcmp(s, chain_protos[i].name) == 0) {
proto = chain_protos[i].num;
break;
}
if (i == ARRAY_SIZE(chain_protos))
xtables_error(PARAMETER_PROBLEM,
"unknown header `%s' specified",
s);
}
return proto;
}
static unsigned int
add_proto_to_mask(int proto){
unsigned int i=0, flag=0;
for (i = 0; i < ARRAY_SIZE(chain_flags); ++i)
if (proto == chain_flags[i].proto){
flag = chain_flags[i].flag;
break;
}
if (i == ARRAY_SIZE(chain_flags))
xtables_error(PARAMETER_PROBLEM,
"unknown header `%d' specified",
proto);
return flag;
}
static void ipv6header_help(void)
{
printf(
"ipv6header match options:\n"
"[!] --header headers Type of header to match, by name\n"
" names: hop,dst,route,frag,auth,esp,none,proto\n"
" long names: hop-by-hop,ipv6-opts,ipv6-route,\n"
" ipv6-frag,ah,esp,ipv6-nonxt,protocol\n"
" numbers: 0,60,43,44,51,50,59\n"
"--soft The header CONTAINS the specified extensions\n");
}
static const struct xt_option_entry ipv6header_opts[] = {
{.name = "header", .id = O_HEADER, .type = XTTYPE_STRING,
.flags = XTOPT_MAND | XTOPT_INVERT},
{.name = "soft", .id = O_SOFT, .type = XTTYPE_NONE},
XTOPT_TABLEEND,
};
static unsigned int
parse_header(const char *flags) {
unsigned int ret = 0;
char *ptr;
char *buffer;
buffer = strdup(flags);
for (ptr = strtok(buffer, ","); ptr; ptr = strtok(NULL, ","))
ret |= add_proto_to_mask(name_to_proto(ptr));
free(buffer);
return ret;
}
static void ipv6header_parse(struct xt_option_call *cb)
{
struct ip6t_ipv6header_info *info = cb->data;
xtables_option_parse(cb);
switch (cb->entry->id) {
case O_HEADER:
if (!(info->matchflags = parse_header(cb->arg)))
xtables_error(PARAMETER_PROBLEM, "ip6t_ipv6header: cannot parse header names");
if (cb->invert)
info->invflags |= 0xFF;
break;
case O_SOFT:
info->modeflag |= 0xFF;
break;
}
}
static void
print_header(uint8_t flags){
int have_flag = 0;
while (flags) {
unsigned int i;
for (i = 0; (flags & chain_flags[i].flag) == 0; i++);
if (have_flag)
printf(",");
printf("%s", proto_to_name(chain_flags[i].proto,0));
have_flag = 1;
flags &= ~chain_flags[i].flag;
}
if (!have_flag)
printf("NONE");
}
static void ipv6header_print(const void *ip,
const struct xt_entry_match *match, int numeric)
{
const struct ip6t_ipv6header_info *info = (const struct ip6t_ipv6header_info *)match->data;
printf(" ipv6header");
if (info->matchflags || info->invflags) {
printf(" flags:%s", info->invflags ? "!" : "");
if (numeric)
printf("0x%02X", info->matchflags);
else {
print_header(info->matchflags);
}
}
if (info->modeflag)
printf(" soft");
}
static void ipv6header_save(const void *ip, const struct xt_entry_match *match)
{
const struct ip6t_ipv6header_info *info = (const struct ip6t_ipv6header_info *)match->data;
printf("%s --header ", info->invflags ? " !" : "");
print_header(info->matchflags);
if (info->modeflag)
printf(" --soft");
}
static struct xtables_match ipv6header_mt6_reg = {
.name = "ipv6header",
.version = XTABLES_VERSION,
.family = NFPROTO_IPV6,
.size = XT_ALIGN(sizeof(struct ip6t_ipv6header_info)),
.userspacesize = XT_ALIGN(sizeof(struct ip6t_ipv6header_info)),
.help = ipv6header_help,
.print = ipv6header_print,
.save = ipv6header_save,
.x6_parse = ipv6header_parse,
.x6_options = ipv6header_opts,
};
void _init(void)
{
xtables_register_match(&ipv6header_mt6_reg);
}
|
324 | ./android_firewall/external/iptables/extensions/libipt_ah.c | #include <stdio.h>
#include <xtables.h>
#include <linux/netfilter_ipv4/ipt_ah.h>
enum {
O_AHSPI = 0,
};
static void ah_help(void)
{
printf(
"ah match options:\n"
"[!] --ahspi spi[:spi]\n"
" match spi (range)\n");
}
static const struct xt_option_entry ah_opts[] = {
{.name = "ahspi", .id = O_AHSPI, .type = XTTYPE_UINT32RC,
.flags = XTOPT_INVERT | XTOPT_PUT,
XTOPT_POINTER(struct ipt_ah, spis)},
XTOPT_TABLEEND,
};
static void ah_parse(struct xt_option_call *cb)
{
struct ipt_ah *ahinfo = cb->data;
xtables_option_parse(cb);
if (cb->nvals == 1)
ahinfo->spis[1] = ahinfo->spis[0];
if (cb->invert)
ahinfo->invflags |= IPT_AH_INV_SPI;
}
static void
print_spis(const char *name, uint32_t min, uint32_t max,
int invert)
{
const char *inv = invert ? "!" : "";
if (min != 0 || max != 0xFFFFFFFF || invert) {
printf("%s", name);
if (min == max) {
printf(":%s", inv);
printf("%u", min);
} else {
printf("s:%s", inv);
printf("%u",min);
printf(":");
printf("%u",max);
}
}
}
static void ah_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
const struct ipt_ah *ah = (struct ipt_ah *)match->data;
printf(" ah ");
print_spis("spi", ah->spis[0], ah->spis[1],
ah->invflags & IPT_AH_INV_SPI);
if (ah->invflags & ~IPT_AH_INV_MASK)
printf(" Unknown invflags: 0x%X",
ah->invflags & ~IPT_AH_INV_MASK);
}
static void ah_save(const void *ip, const struct xt_entry_match *match)
{
const struct ipt_ah *ahinfo = (struct ipt_ah *)match->data;
if (!(ahinfo->spis[0] == 0
&& ahinfo->spis[1] == 0xFFFFFFFF)) {
printf("%s --ahspi ",
(ahinfo->invflags & IPT_AH_INV_SPI) ? " !" : "");
if (ahinfo->spis[0]
!= ahinfo->spis[1])
printf("%u:%u",
ahinfo->spis[0],
ahinfo->spis[1]);
else
printf("%u",
ahinfo->spis[0]);
}
}
static struct xtables_match ah_mt_reg = {
.name = "ah",
.version = XTABLES_VERSION,
.family = NFPROTO_IPV4,
.size = XT_ALIGN(sizeof(struct ipt_ah)),
.userspacesize = XT_ALIGN(sizeof(struct ipt_ah)),
.help = ah_help,
.print = ah_print,
.save = ah_save,
.x6_parse = ah_parse,
.x6_options = ah_opts,
};
void
_init(void)
{
xtables_register_match(&ah_mt_reg);
}
|
325 | ./android_firewall/external/iptables/extensions/libxt_TRACE.c | /* Shared library add-on to iptables to add TRACE target support. */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <getopt.h>
#include <xtables.h>
#include <linux/netfilter/x_tables.h>
static struct xtables_target trace_target = {
.family = NFPROTO_UNSPEC,
.name = "TRACE",
.version = XTABLES_VERSION,
.size = XT_ALIGN(0),
.userspacesize = XT_ALIGN(0),
};
void _init(void)
{
xtables_register_target(&trace_target);
}
|
326 | ./android_firewall/external/iptables/extensions/libxt_mac.c | #include <stdio.h>
#if defined(__GLIBC__) && __GLIBC__ == 2
#include <net/ethernet.h>
#else
#include <linux/if_ether.h>
#endif
#include <xtables.h>
#include <linux/netfilter/xt_mac.h>
enum {
O_MAC = 0,
};
static void mac_help(void)
{
printf(
"mac match options:\n"
"[!] --mac-source XX:XX:XX:XX:XX:XX\n"
" Match source MAC address\n");
}
#define s struct xt_mac_info
static const struct xt_option_entry mac_opts[] = {
{.name = "mac-source", .id = O_MAC, .type = XTTYPE_ETHERMAC,
.flags = XTOPT_MAND | XTOPT_INVERT | XTOPT_PUT,
XTOPT_POINTER(s, srcaddr)},
XTOPT_TABLEEND,
};
#undef s
static void mac_parse(struct xt_option_call *cb)
{
struct xt_mac_info *macinfo = cb->data;
xtables_option_parse(cb);
if (cb->invert)
macinfo->invert = 1;
}
static void print_mac(const unsigned char *macaddress)
{
unsigned int i;
printf(" %02X", macaddress[0]);
for (i = 1; i < ETH_ALEN; ++i)
printf(":%02X", macaddress[i]);
}
static void
mac_print(const void *ip, const struct xt_entry_match *match, int numeric)
{
const struct xt_mac_info *info = (void *)match->data;
printf(" MAC");
if (info->invert)
printf(" !");
print_mac(info->srcaddr);
}
static void mac_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_mac_info *info = (void *)match->data;
if (info->invert)
printf(" !");
printf(" --mac-source");
print_mac(info->srcaddr);
}
static struct xtables_match mac_match = {
.family = NFPROTO_UNSPEC,
.name = "mac",
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof(struct xt_mac_info)),
.userspacesize = XT_ALIGN(sizeof(struct xt_mac_info)),
.help = mac_help,
.x6_parse = mac_parse,
.print = mac_print,
.save = mac_save,
.x6_options = mac_opts,
};
void _init(void)
{
xtables_register_match(&mac_match);
}
|
327 | ./newsblur/vendor/cjson/cjson.c | /*
* Copyright (C) 2006-2007 Dan Pascu
* Author: Dan Pascu <[email protected]>
*
* Fast JSON encoder/decoder implementation for Python
*
* Original version: Dan Pascu <[email protected]>
*
* 2007-03-16: Viktor Ferenczi <[email protected]>
*
* Added extension keyword arguments to encode and decode functions.
* These functions can specify encoding/decoding of non-atomic data,
* such as Date objects. For example:
*
* decode('[1,new Date(2007,1,2),2]', extension=dateDecoder)
* encode([1, datetime.date(2007,1,2), 2], extension=dateEncoder)
*
* See the unit tests (jsontest.py) for detailed example.
*
* Both encoder and decoder now has a context struct.
* Very small optimizations for the decoder (switch order).
*
* 2007-03-28: Qiangning Hong <[email protected]>
*
* Segfault with Python 2.5 on 64 bit platforms is fixed by using the correct
* Py_ssize_t type for one of the parameters of PyDict_Next(). More testing
* with Python 2.5 on 64 bit platform required.
*
* 2007-04-01: Fixing exception handling bug
*
* When a decoder extension function was called after the failure of an
* internal decoder (for example after failing to interpret new Date(...)
* as null) the internal exception was propagated (not cleared) and could
* be incorrectly raised in the decoder extension function pointing to en
* otherwise correct statement in that function. This could cause severe
* confusion to the programmer and prevented execution of such extension
* functions.
*
* 2007-04-02: Added optional automatic conversion of dict keys to string.
*
* Since JSON specification does not allow non-string keys in objects,
* it's very useful to add optional automatic conversion of dictionary keys.
* This could be useful when porting code originally written for simplejson
* that does this by default. The feature can be enabled by passing
* key2str=True keyword argument to the encode() function. Default behaviour
* of python-cjson has been preserved, so without this keyword argument
* encoding of non-string dictionary keys will raise EncodeError.
*
* 2007-05-05: Added automatic charset encoding/decoding for strings
*
* Added keyword argument named encoding for automatic str object handling.
* Small performance optimizations. More realistic throughput test data.
* Compatibility with MS C compilers from VC++ Toolkit 2003.
*
* 2007-07-12: Fixed segmentation fault
*
* Fixed a rare, but reproducible segmentation fault when decoding specially
* crafted unicode strings. Bug reported by: Liu Cougar - China
*
*/
#include <Python.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#if (PY_VERSION_HEX < 0x02050000)
typedef int Py_ssize_t;
#endif
typedef struct EncoderContext {
PyObject *extension; /* callable to extend the encoder (encode user defined objects) */
int key2str; /* flag to enable automatic dict key to string conversion */
const char *encoding; /* encoding used to decode str objects, only ASCII is accepted if NULL */
} EncoderContext;
typedef struct DecoderContext {
char *str; /* the actual json string */
char *end; /* pointer to the string end */
char *ptr; /* pointer to the current parsing position */
int all_unicode; /* make all output strings unicode if true */
PyObject *extension; /* callable to extend the decoder (decode user defined sequences) or NULL */
PyObject *jsonstr; /* the original JSON string */
const char *encoding; /* encoding used to automatically encode unicode objects, they are left unicode if NULL */
} DecoderContext;
static PyObject* encode_object(EncoderContext *ctx, PyObject *object);
static PyObject* encode_string(PyObject *object);
static PyObject* encode_string_with_recoding(EncoderContext *ctx, PyObject *object);
static PyObject* encode_unicode(PyObject *object);
static PyObject* encode_tuple(EncoderContext *ctx, PyObject *object);
static PyObject* encode_list(EncoderContext *ctx, PyObject *object);
static PyObject* encode_dict(EncoderContext *ctx, PyObject *object);
static PyObject* decode_json(DecoderContext *ctx);
static PyObject* decode_null(DecoderContext *ctx);
static PyObject* decode_bool(DecoderContext *ctx);
static PyObject* decode_string(DecoderContext *ctx);
static PyObject* decode_inf(DecoderContext *ctx);
static PyObject* decode_nan(DecoderContext *ctx);
static PyObject* decode_number(DecoderContext *ctx);
static PyObject* decode_array(DecoderContext *ctx);
static PyObject* decode_object(DecoderContext *ctx);
static PyObject* decode_using_extension(DecoderContext *ctx);
static PyObject *JSON_Error;
static PyObject *JSON_EncodeError;
static PyObject *JSON_DecodeError;
static const char *hexdigit = "0123456789abcdef";
#define True 1
#define False 0
#ifndef INFINITY
# define INFINITY HUGE_VAL
#endif
#ifndef NAN
# define NAN (HUGE_VAL - HUGE_VAL)
#endif
#ifndef Py_IS_NAN
# define Py_IS_NAN(X) ((X) != (X))
#endif
#define skipSpaces(d) while((d)->ptr<(d)->end && *((d)->ptr) && isspace(*((d)->ptr))) (d)->ptr++
/* ------------------------------ Decoding ----------------------------- */
static PyObject*
decode_null(DecoderContext *ctx)
{
int left;
left = ctx->end - ctx->ptr;
if (left >= 4 && strncmp(ctx->ptr, "null", 4)==0) {
ctx->ptr += 4;
Py_INCREF(Py_None);
return Py_None;
} else {
PyErr_Format(JSON_DecodeError, "cannot parse JSON description: %.20s",
ctx->ptr);
return NULL;
}
}
static PyObject*
decode_bool(DecoderContext *ctx)
{
int left;
left = ctx->end - ctx->ptr;
if (left >= 4 && strncmp(ctx->ptr, "true", 4)==0) {
ctx->ptr += 4;
Py_INCREF(Py_True);
return Py_True;
} else if (left >= 5 && strncmp(ctx->ptr, "false", 5)==0) {
ctx->ptr += 5;
Py_INCREF(Py_False);
return Py_False;
} else {
PyErr_Format(JSON_DecodeError, "cannot parse JSON description: %.20s",
ctx->ptr);
return NULL;
}
}
static PyObject*
decode_string(DecoderContext *ctx)
{
PyObject *object;
register char *ptr;
register char c, escaping, string_escape, has_unicode;
int len;
/* look for the closing quote */
escaping = string_escape = False;
has_unicode = ctx->all_unicode;
ptr = ctx->ptr + 1;
while (True) {
c = *ptr;
if (c == 0) {
PyErr_Format(JSON_DecodeError,
"unterminated string starting at position %d",
ctx->ptr - ctx->str);
return NULL;
}
if (escaping) {
switch(c) {
case 'u':
has_unicode = True;
break;
case '"':
case 'r':
case 'n':
case 't':
case 'b':
case 'f':
case '\\':
string_escape = True;
break;
}
escaping = False;
} else {
if (c == '\\') {
escaping = True;
} else if (c == '"') {
break;
} else if (!isascii(c)) {
has_unicode = True;
}
}
ptr++;
}
len = ptr - ctx->ptr - 1;
if (has_unicode)
object = PyUnicode_DecodeUnicodeEscape(ctx->ptr+1, len, NULL);
else if (string_escape)
object = PyString_DecodeEscape(ctx->ptr+1, len, NULL, 0, NULL);
else
object = PyString_FromStringAndSize(ctx->ptr+1, len);
if (object == NULL) {
PyObject *type, *value, *tb, *reason;
PyErr_Fetch(&type, &value, &tb);
if (type == NULL) {
PyErr_Format(JSON_DecodeError,
"invalid string starting at position %d",
ctx->ptr - ctx->str);
} else {
if (PyErr_GivenExceptionMatches(type, PyExc_UnicodeDecodeError)) {
reason = PyObject_GetAttrString(value, "reason");
PyErr_Format(JSON_DecodeError, "cannot decode string starting"
" at position %d: %s",
ctx->ptr - ctx->str,
reason ? PyString_AsString(reason) : "bad format");
Py_XDECREF(reason);
} else {
PyErr_Format(JSON_DecodeError,
"invalid string starting at position %d",
ctx->ptr - ctx->str);
}
}
Py_XDECREF(type);
Py_XDECREF(value);
Py_XDECREF(tb);
return NULL;
}
/* Encode unicode into a specific encoding if specified */
if (has_unicode && ctx->encoding) {
PyObject *strobject = PyUnicode_Encode(
PyUnicode_AS_UNICODE(object),
PyUnicode_GET_SIZE(object),
ctx->encoding, "strict"
);
Py_DECREF(object);
object=strobject;
if(strobject==NULL) {
PyErr_SetString(JSON_DecodeError, "error encoding unicode object to the specified encoding after successful JSON decoding");
}
}
/* Go to the end of the string */
ctx->ptr = ptr+1;
return object;
}
static PyObject*
decode_inf(DecoderContext *ctx)
{
PyObject *object;
int left;
left = ctx->end - ctx->ptr;
if (left >= 8 && strncmp(ctx->ptr, "Infinity", 8)==0) {
ctx->ptr += 8;
object = PyFloat_FromDouble(INFINITY);
return object;
} else if (left >= 9 && strncmp(ctx->ptr, "+Infinity", 9)==0) {
ctx->ptr += 9;
object = PyFloat_FromDouble(INFINITY);
return object;
} else if (left >= 9 && strncmp(ctx->ptr, "-Infinity", 9)==0) {
ctx->ptr += 9;
object = PyFloat_FromDouble(-INFINITY);
return object;
} else {
PyErr_Format(JSON_DecodeError, "cannot parse JSON description: %.20s",
ctx->ptr);
return NULL;
}
}
static PyObject*
decode_nan(DecoderContext *ctx)
{
PyObject *object;
int left;
left = ctx->end - ctx->ptr;
if (left >= 3 && strncmp(ctx->ptr, "NaN", 3)==0) {
ctx->ptr += 3;
object = PyFloat_FromDouble(NAN);
return object;
} else {
PyErr_Format(JSON_DecodeError, "cannot parse JSON description: %.20s",
ctx->ptr);
return NULL;
}
}
static PyObject*
decode_number(DecoderContext *ctx)
{
PyObject *object, *str;
int c, is_float, should_stop;
char *ptr;
/* check if we got a floating point number */
ptr = ctx->ptr;
is_float = should_stop = False;
while (True) {
c = *ptr;
if (c == 0)
break;
switch(c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
case '+':
break;
case '.':
case 'e':
case 'E':
is_float = True;
break;
default:
should_stop = True;
}
if (should_stop) {
break;
}
ptr++;
}
str = PyString_FromStringAndSize(ctx->ptr, ptr - ctx->ptr);
if (str == NULL)
return NULL;
if (is_float) {
object = PyFloat_FromString(str, NULL);
} else {
object = PyInt_FromString(PyString_AS_STRING(str), NULL, 10);
}
Py_DECREF(str);
if (object == NULL) {
PyErr_Format(JSON_DecodeError, "invalid number starting at position %d",
ctx->ptr - ctx->str);
puts(ptr);
} else {
ctx->ptr = ptr;
}
return object;
}
static PyObject*
decode_array(DecoderContext *ctx)
{
PyObject *object, *item;
int c, expect_item, items, result;
char *start;
object = PyList_New(0);
start = ctx->ptr;
ctx->ptr++;
expect_item = True;
items = 0;
while (True) {
skipSpaces(ctx);
c = *ctx->ptr;
if (c == 0) {
PyErr_Format(JSON_DecodeError, "unterminated array starting at "
"position %d", start - ctx->str);
goto failure;;
} else if (c == ']') {
if (expect_item && items>0) {
PyErr_Format(JSON_DecodeError, "expecting array item at "
"position %d", ctx->ptr - ctx->str);
goto failure;
}
ctx->ptr++;
break;
} else if (c == ',') {
if (expect_item) {
PyErr_Format(JSON_DecodeError, "expecting array item at "
"position %d", ctx->ptr - ctx->str);
goto failure;
}
expect_item = True;
ctx->ptr++;
continue;
} else {
item = decode_json(ctx);
if (item == NULL)
goto failure;
result = PyList_Append(object, item);
Py_DECREF(item);
if (result == -1)
goto failure;
expect_item = False;
items++;
}
}
return object;
failure:
Py_DECREF(object);
return NULL;
}
static PyObject*
decode_object(DecoderContext *ctx)
{
PyObject *object, *key, *value;
int c, expect_key, items, result;
char *start;
object = PyDict_New();
expect_key = True;
items = 0;
start = ctx->ptr;
ctx->ptr++;
while (True) {
skipSpaces(ctx);
c = *ctx->ptr;
if (c == 0) {
PyErr_Format(JSON_DecodeError, "unterminated object starting at "
"position %d", start - ctx->str);
goto failure;;
} else if (c == '}') {
if (expect_key && items>0) {
PyErr_Format(JSON_DecodeError, "expecting object property name"
" at position %d", ctx->ptr - ctx->str);
goto failure;
}
ctx->ptr++;
break;
} else if (c == ',') {
if (expect_key) {
PyErr_Format(JSON_DecodeError, "expecting object property name"
"at position %d", ctx->ptr - ctx->str);
goto failure;
}
expect_key = True;
ctx->ptr++;
continue;
} else {
if (c != '"') {
PyErr_Format(JSON_DecodeError,
"expecting property name in object at "
"position %d", ctx->ptr - ctx->str);
goto failure;
}
key = decode_json(ctx);
if (key == NULL)
goto failure;
skipSpaces(ctx);
if (*ctx->ptr != ':') {
PyErr_Format(JSON_DecodeError,
"missing colon after object property name at "
"position %d", ctx->ptr - ctx->str);
Py_DECREF(key);
goto failure;
} else {
ctx->ptr++;
}
value = decode_json(ctx);
if (value == NULL) {
Py_DECREF(key);
goto failure;
}
result = PyDict_SetItem(object, key, value);
Py_DECREF(key);
Py_DECREF(value);
if (result == -1)
goto failure;
expect_key = False;
items++;
}
}
return object;
failure:
Py_DECREF(object);
return NULL;
}
static PyObject*
decode_using_extension(DecoderContext *ctx)
{
PyObject *object, *index, *tuple, *delta;
long chars;
index = PyInt_FromLong(ctx->ptr - ctx->str);
tuple = PyObject_CallFunctionObjArgs(ctx->extension, ctx->jsonstr, index, NULL);
Py_DECREF(index);
if(!tuple) return NULL;
if(!PyTuple_Check(tuple) || PyTuple_Size(tuple)!=2) {
Py_DECREF(tuple);
PyErr_SetString(JSON_DecodeError, "extension function should return tuple: (object, parsed_chars)");
return NULL;
}
object = PyTuple_GET_ITEM(tuple,0);
delta = PyTuple_GET_ITEM(tuple,1);
chars = PyInt_AsLong(delta);
Py_INCREF(object);
Py_DECREF(tuple);
if(chars<1) {
Py_DECREF(object);
PyErr_SetString(JSON_DecodeError, "extension function should return positive integer as number of parsed characters");
return NULL;
}
ctx->ptr += chars;
if(ctx->ptr > ctx->end) {
Py_DECREF(object);
PyErr_SetString(JSON_DecodeError, "extension function returned parsed character count beyond the end of the JSON string");
return NULL;
}
return object;
}
static PyObject*
decode_json(DecoderContext *ctx)
{
PyObject *object;
skipSpaces(ctx);
switch(*ctx->ptr) {
case 0:
PyErr_SetString(JSON_DecodeError, "empty JSON description");
return NULL;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
object = decode_number(ctx);
break;
case '-':
case '+':
if (*(ctx->ptr+1) == 'I') {
object = decode_inf(ctx);
} else {
object = decode_number(ctx);
}
break;
case '"':
object = decode_string(ctx);
break;
case 't':
case 'f':
object = decode_bool(ctx);
break;
case 'n':
object = decode_null(ctx);
break;
case '{':
object = decode_object(ctx);
break;
case '[':
object = decode_array(ctx);
break;
case 'N':
object = decode_nan(ctx);
break;
case 'I':
object = decode_inf(ctx);
break;
default:
if ( ctx->extension ) {
return decode_using_extension(ctx);
}
PyErr_SetString(JSON_DecodeError, "cannot parse JSON description");
return NULL;
}
if( !object && ctx->extension ) {
PyErr_Clear();
object = decode_using_extension(ctx);
}
return object;
}
/* ------------------------------ Encoding ----------------------------- */
/*
* This function is an almost verbatim copy of PyString_Repr() from
* Python's stringobject.c with the following differences:
*
* - it always quotes the output using double quotes.
* - it also quotes \b and \f
* - it replaces any non ASCII character hh with \u00hh instead of \xhh
*/
static PyObject*
encode_string(PyObject *string)
{
register int i;
register char c;
register char *p;
PyStringObject* op = (PyStringObject*) string;
char quote = '"';
size_t newsize = 2 + 6 * op->ob_size;
PyObject *v;
int sl;
if (newsize > INT_MAX) {
PyErr_SetString(PyExc_OverflowError,
"string is too large to make repr");
}
v = PyString_FromStringAndSize((char *)NULL, newsize);
if (v == NULL) {
return NULL;
}
p = PyString_AS_STRING(v);
*p++ = quote;
sl = op->ob_size;
for (i = 0; i < sl; i++) {
/* There's at least enough room for a hex escape
and a closing quote. */
assert(newsize - (p - PyString_AS_STRING(v)) >= 7);
c = op->ob_sval[i];
if (c == quote || c == '\\')
*p++ = '\\', *p++ = c;
else if (c == '\t')
*p++ = '\\', *p++ = 't';
else if (c == '\n')
*p++ = '\\', *p++ = 'n';
else if (c == '\r')
*p++ = '\\', *p++ = 'r';
else if (c == '\f')
*p++ = '\\', *p++ = 'f';
else if (c == '\b')
*p++ = '\\', *p++ = 'b';
else if (c < ' ' || c >= 0x7f) {
*p++='\\'; *p++='u'; *p++='0'; *p++='0';
*p++=hexdigit[((unsigned char)c>>4)&15];
*p++=hexdigit[(unsigned char)c&15];
}
else
*p++ = c;
}
assert(newsize - (p - PyString_AS_STRING(v)) >= 1);
*p++ = quote;
*p = '\0';
_PyString_Resize(&v, (int) (p - PyString_AS_STRING(v)));
return v;
}
static PyObject*
encode_string_with_recoding(EncoderContext *ctx, PyObject *object)
{
PyObject *unicode;
PyObject *result;
unicode=PyUnicode_Decode(
PyString_AS_STRING(object),
PyString_GET_SIZE(object),
ctx->encoding, "strict"
);
if(unicode==NULL) {
PyErr_SetString(JSON_EncodeError, "error decoding str object with the specified encoding before actual JSON encoding");
return NULL;
}
result=encode_unicode(unicode);
Py_DECREF(unicode);
return result;
}
/*
* This function is an almost verbatim copy of unicodeescape_string() from
* Python's unicodeobject.c with the following differences:
*
* - it always quotes the output using double quotes.
* - it uses \u00hh instead of \xhh in output.
* - it also quotes \b and \f
*/
static PyObject*
encode_unicode(PyObject *unicode)
{
PyObject *repr;
Py_UNICODE *s;
int size;
char *p;
s = PyUnicode_AS_UNICODE(unicode);
size = PyUnicode_GET_SIZE(unicode);
repr = PyString_FromStringAndSize(NULL, 2 + 6*size + 1);
if (repr == NULL)
return NULL;
p = PyString_AS_STRING(repr);
*p++ = '"';
while (size-- > 0) {
Py_UNICODE ch = *s++;
/* Escape quotes */
if ((ch == (Py_UNICODE) PyString_AS_STRING(repr)[0] || ch == '\\')) {
*p++ = '\\';
*p++ = (char) ch;
continue;
}
#ifdef Py_UNICODE_WIDE
/* Map 21-bit characters to '\U00xxxxxx' */
else if (ch >= 0x10000) {
int offset = p - PyString_AS_STRING(repr);
/* Resize the string if necessary */
if (offset + 12 > PyString_GET_SIZE(repr)) {
if (_PyString_Resize(&repr, PyString_GET_SIZE(repr) + 100))
return NULL;
p = PyString_AS_STRING(repr) + offset;
}
*p++ = '\\';
*p++ = 'U';
*p++ = hexdigit[(ch >> 28) & 0x0000000F];
*p++ = hexdigit[(ch >> 24) & 0x0000000F];
*p++ = hexdigit[(ch >> 20) & 0x0000000F];
*p++ = hexdigit[(ch >> 16) & 0x0000000F];
*p++ = hexdigit[(ch >> 12) & 0x0000000F];
*p++ = hexdigit[(ch >> 8) & 0x0000000F];
*p++ = hexdigit[(ch >> 4) & 0x0000000F];
*p++ = hexdigit[ch & 0x0000000F];
continue;
}
#endif
/* Map UTF-16 surrogate pairs to Unicode \UXXXXXXXX escapes */
else if (ch >= 0xD800 && ch < 0xDC00) {
Py_UNICODE ch2;
Py_UCS4 ucs;
ch2 = *s++;
size--;
if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
*p++ = '\\';
*p++ = 'U';
*p++ = hexdigit[(ucs >> 28) & 0x0000000F];
*p++ = hexdigit[(ucs >> 24) & 0x0000000F];
*p++ = hexdigit[(ucs >> 20) & 0x0000000F];
*p++ = hexdigit[(ucs >> 16) & 0x0000000F];
*p++ = hexdigit[(ucs >> 12) & 0x0000000F];
*p++ = hexdigit[(ucs >> 8) & 0x0000000F];
*p++ = hexdigit[(ucs >> 4) & 0x0000000F];
*p++ = hexdigit[ucs & 0x0000000F];
continue;
}
/* Fall through: isolated surrogates are copied as-is */
s--;
size++;
}
/* Map 16-bit characters to '\uxxxx' */
if (ch >= 256) {
*p++ = '\\';
*p++ = 'u';
*p++ = hexdigit[(ch >> 12) & 0x000F];
*p++ = hexdigit[(ch >> 8) & 0x000F];
*p++ = hexdigit[(ch >> 4) & 0x000F];
*p++ = hexdigit[ch & 0x000F];
}
/* Map special whitespace to '\t', \n', '\r', '\f', '\b' */
else if (ch == '\t') {
*p++ = '\\';
*p++ = 't';
}
else if (ch == '\n') {
*p++ = '\\';
*p++ = 'n';
}
else if (ch == '\r') {
*p++ = '\\';
*p++ = 'r';
}
else if (ch == '\f') {
*p++ = '\\';
*p++ = 'f';
}
else if (ch == '\b') {
*p++ = '\\';
*p++ = 'b';
}
/* Map non-printable US ASCII to '\u00hh' */
else if (ch < ' ' || ch >= 0x7F) {
*p++ = '\\';
*p++ = 'u';
*p++ = '0';
*p++ = '0';
*p++ = hexdigit[(ch >> 4) & 0x000F];
*p++ = hexdigit[ch & 0x000F];
}
/* Copy everything else as-is */
else
*p++ = (char) ch;
}
*p++ = PyString_AS_STRING(repr)[0];
*p = '\0';
_PyString_Resize(&repr, p - PyString_AS_STRING(repr));
return repr;
}
/*
* This function is an almost verbatim copy of tuplerepr() from
* Python's tupleobject.c with the following differences:
*
* - it uses encode_object() to get the object's JSON reprezentation.
* - it uses [] as decorations isntead of () (to masquerade as a JSON array).
*/
static PyObject*
encode_tuple(EncoderContext *ctx, PyObject *tuple)
{
int i, n;
PyObject *s, *temp;
PyObject *pieces, *result = NULL;
PyTupleObject *v = (PyTupleObject*) tuple;
n = v->ob_size;
if (n == 0)
return PyString_FromString("[]");
pieces = PyTuple_New(n);
if (pieces == NULL)
return NULL;
/* Do repr() on each element. */
for (i = 0; i < n; ++i) {
s = encode_object(ctx, v->ob_item[i]);
if (s == NULL)
goto Done;
PyTuple_SET_ITEM(pieces, i, s);
}
/* Add "[]" decorations to the first and last items. */
assert(n > 0);
s = PyString_FromString("[");
if (s == NULL)
goto Done;
temp = PyTuple_GET_ITEM(pieces, 0);
PyString_ConcatAndDel(&s, temp);
PyTuple_SET_ITEM(pieces, 0, s);
if (s == NULL)
goto Done;
s = PyString_FromString("]");
if (s == NULL)
goto Done;
temp = PyTuple_GET_ITEM(pieces, n-1);
PyString_ConcatAndDel(&temp, s);
PyTuple_SET_ITEM(pieces, n-1, temp);
if (temp == NULL)
goto Done;
/* Paste them all together with ", " between. */
s = PyString_FromString(", ");
if (s == NULL)
goto Done;
result = _PyString_Join(s, pieces);
Py_DECREF(s);
Done:
Py_DECREF(pieces);
return result;
}
/*
* This function is an almost verbatim copy of list_repr() from
* Python's listobject.c with the following differences:
*
* - it uses encode_object() to get the object's JSON reprezentation.
* - it doesn't use the ellipsis to represent a list with references
* to itself, instead it raises an exception as such lists cannot be
* represented in JSON.
*/
static PyObject*
encode_list(EncoderContext *ctx, PyObject *list)
{
int i;
PyObject *s, *temp;
PyObject *pieces = NULL, *result = NULL;
PyListObject *v = (PyListObject*) list;
i = Py_ReprEnter((PyObject*)v);
if (i != 0) {
if (i > 0) {
PyErr_SetString(JSON_EncodeError, "a list with references to "
"itself is not JSON encodable");
}
return NULL;
}
if (v->ob_size == 0) {
result = PyString_FromString("[]");
goto Done;
}
pieces = PyList_New(0);
if (pieces == NULL)
goto Done;
/* Do repr() on each element. Note that this may mutate the list,
* so must refetch the list size on each iteration. */
for (i = 0; i < v->ob_size; ++i) {
int status;
s = encode_object(ctx, v->ob_item[i]);
if (s == NULL)
goto Done;
status = PyList_Append(pieces, s);
Py_DECREF(s); /* append created a new ref */
if (status < 0)
goto Done;
}
/* Add "[]" decorations to the first and last items. */
assert(PyList_GET_SIZE(pieces) > 0);
s = PyString_FromString("[");
if (s == NULL)
goto Done;
temp = PyList_GET_ITEM(pieces, 0);
PyString_ConcatAndDel(&s, temp);
PyList_SET_ITEM(pieces, 0, s);
if (s == NULL)
goto Done;
s = PyString_FromString("]");
if (s == NULL)
goto Done;
temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
PyString_ConcatAndDel(&temp, s);
PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
if (temp == NULL)
goto Done;
/* Paste them all together with ", " between. */
s = PyString_FromString(", ");
if (s == NULL)
goto Done;
result = _PyString_Join(s, pieces);
Py_DECREF(s);
Done:
Py_XDECREF(pieces);
Py_ReprLeave((PyObject *)v);
return result;
}
/*
* This function is an almost verbatim copy of dict_repr() from
* Python's dictobject.c with the following differences:
*
* - it uses encode_object() to get the object's JSON reprezentation.
* - only accept strings for keys or convert non-string keys to string if
* this feature is enabled (raises exception if cannot be converted)
* - it doesn't use the ellipsis to represent a dictionary with references
* to itself, instead it raises an exception as such dictionaries cannot
* be represented in JSON.
*/
static PyObject*
encode_dict(EncoderContext *ctx, PyObject *dict)
{
Py_ssize_t i;
PyObject *s, *temp, *colon = NULL;
PyObject *pieces = NULL, *result = NULL;
PyObject *key, *value, *strkey = NULL;
PyDictObject *mp = (PyDictObject*) dict;
i = Py_ReprEnter((PyObject *)mp);
if (i != 0) {
if (i > 0) {
PyErr_SetString(JSON_EncodeError, "a dict with references to "
"itself is not JSON encodable");
}
return NULL;
}
if (mp->ma_used == 0) {
result = PyString_FromString("{}");
goto Done;
}
pieces = PyList_New(0);
if (pieces == NULL)
goto Done;
colon = PyString_FromString(": ");
if (colon == NULL)
goto Done;
/* Do repr() on each key+value pair, and insert ": " between them.
* Note that repr may mutate the dict. */
i = 0;
while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
int status;
strkey = NULL;
if (!PyString_Check(key) && !PyUnicode_Check(key)) {
if (ctx->key2str) {
/* Auto convert keys to strings */
strkey = PyObject_Str(key);
if( strkey == NULL ) {
PyErr_SetString(JSON_EncodeError, "Cannot convert dictionary key to string");
goto Done;
}
} else {
PyErr_SetString(JSON_EncodeError, "JSON encodable dictionaries "
"must have string/unicode keys");
goto Done;
}
}
/* Prevent repr from deleting value during key format. */
Py_INCREF(value);
if( strkey ) {
s = encode_object(ctx, strkey);
Py_DECREF(strkey);
strkey = NULL;
} else {
s = encode_object(ctx, key);
}
PyString_Concat(&s, colon);
PyString_ConcatAndDel(&s, encode_object(ctx, value));
Py_DECREF(value);
if (s == NULL)
goto Done;
status = PyList_Append(pieces, s);
Py_DECREF(s); /* append created a new ref */
if (status < 0)
goto Done;
}
/* Add "{}" decorations to the first and last items. */
assert(PyList_GET_SIZE(pieces) > 0);
s = PyString_FromString("{");
if (s == NULL)
goto Done;
temp = PyList_GET_ITEM(pieces, 0);
PyString_ConcatAndDel(&s, temp);
PyList_SET_ITEM(pieces, 0, s);
if (s == NULL)
goto Done;
s = PyString_FromString("}");
if (s == NULL)
goto Done;
temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
PyString_ConcatAndDel(&temp, s);
PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
if (temp == NULL)
goto Done;
/* Paste them all together with ", " between. */
s = PyString_FromString(", ");
if (s == NULL)
goto Done;
result = _PyString_Join(s, pieces);
Py_DECREF(s);
Done:
Py_XDECREF(strkey);
Py_XDECREF(pieces);
Py_XDECREF(colon);
Py_ReprLeave((PyObject *)mp);
return result;
}
static PyObject*
encode_object(EncoderContext *ctx, PyObject *object)
{
if (object == Py_True) {
return PyString_FromString("true");
} else if (object == Py_False) {
return PyString_FromString("false");
} else if (object == Py_None) {
return PyString_FromString("null");
} else if (PyString_Check(object)) {
if ( ctx->encoding ) {
/* Recode string from the str encoding specified to unicode */
return encode_string_with_recoding(ctx, object);
} else {
/* No encoding specified, string must be ASCII */
return encode_string(object);
}
} else if (PyUnicode_Check(object)) {
return encode_unicode(object);
} else if (PyFloat_Check(object)) {
double val = PyFloat_AS_DOUBLE(object);
if (Py_IS_NAN(val)) {
return PyString_FromString("NaN");
} else if (Py_IS_INFINITY(val)) {
if (val > 0) {
return PyString_FromString("Infinity");
} else {
return PyString_FromString("-Infinity");
}
} else {
return PyObject_Str(object);
}
} else if (PyInt_Check(object) || PyLong_Check(object)) {
return PyObject_Str(object);
} else if (PyList_Check(object)) {
return encode_list(ctx, object);
} else if (PyTuple_Check(object)) {
return encode_tuple(ctx, object);
} else if (PyDict_Check(object)) { /* use PyMapping_Check(object) instead? -Dan */
return encode_dict(ctx, object);
} else if (ctx->extension) {
return PyObject_CallFunctionObjArgs(ctx->extension, object, NULL);
} else {
PyErr_SetString(JSON_EncodeError, "object is not JSON encodable");
return NULL;
}
}
/* Encode object into its JSON representation */
static PyObject*
JSON_encode(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *kwlist[] = {"obj", "extension", "key2str", "encoding", NULL};
PyObject *object, *key2str = NULL;
EncoderContext ctx;
ctx.extension=NULL;
ctx.encoding=NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|OOz:encode", kwlist,
&object, &ctx.extension, &key2str, &ctx.encoding))
return NULL;
if (ctx.extension==Py_None) ctx.extension=NULL;
ctx.key2str=key2str?PyObject_IsTrue(key2str):0;
if(ctx.extension && !PyCallable_Check(ctx.extension)) {
PyErr_SetString(JSON_EncodeError, "extension is not callable");
return NULL;
}
return encode_object(&ctx, object);
}
/* Decode JSON representation into python objects */
static PyObject*
JSON_decode(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *kwlist[] = {"json", "all_unicode", "extension", "encoding", NULL};
int all_unicode = False; /* by default return unicode only when needed */
PyObject *object, *string, *str, *oAllUnicode = NULL;
DecoderContext ctx;
ctx.extension=NULL;
ctx.jsonstr=NULL;
ctx.encoding=NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|OOz:decode", kwlist,
&string, &oAllUnicode, &ctx.extension, &ctx.encoding))
return NULL;
all_unicode=oAllUnicode?PyObject_IsTrue(oAllUnicode):0;
if (PyUnicode_Check(string)) {
str = PyUnicode_AsRawUnicodeEscapeString(string);
if (str == NULL) {
return NULL;
}
} else {
Py_INCREF(string);
str = string;
}
if (PyString_AsStringAndSize(str, &(ctx.str), NULL) == -1) {
Py_DECREF(str);
return NULL; /* not a string object or it contains null bytes */
}
ctx.ptr = ctx.str;
ctx.end = ctx.str + strlen(ctx.str);
ctx.all_unicode = all_unicode;
ctx.jsonstr = str;
if (ctx.extension==Py_None) ctx.extension=NULL;
if (ctx.extension && !PyCallable_Check(ctx.extension)) {
PyErr_SetString(JSON_DecodeError, "extension is not callable");
Py_DECREF(str);
return NULL;
}
object = decode_json(&ctx);
Py_DECREF(str);
if (object != NULL) {
skipSpaces(&ctx);
if (ctx.ptr < ctx.end) {
Py_DECREF(object);
PyErr_Format(JSON_DecodeError, "extra data after JSON description"
" at position %d", ctx.ptr-ctx.str);
return NULL;
}
}
return object;
}
/* List of functions defined in the module */
static PyMethodDef cjson_methods[] = {
{"encode", (PyCFunction)JSON_encode, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("encode(object, extension=None, key2str=False, encoding='ascii') -> \n"
"generate the JSON representation for object. The optional argument\n"
"`extension' defines a function to encode objects not in the original\n"
"JSON specification. For example this can be used to convert\n"
"datetime.date objects to new Date(...) expressions. The extension\n"
"function must have a single argument and must return the JSON\n"
"representation of the object passed or raise EncodeError if the\n"
"object cannot be converted to JSON format. Automatically convert\n"
"dictionary keys to str if key2str is True, otherwise EncodeError\n"
"is raised whenever a non-str and non-unicode dictinary key is found.\n"
"The encoding argument must specify the encoding used to decode\n"
"python str objects."
)},
{"decode", (PyCFunction)JSON_decode, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("decode(string, all_unicode=False, extension=None, encoding=None) -> \n"
"parse the JSON representation into python objects.\n"
"The optional argument `all_unicode', specifies how to\n"
"convert the strings in the JSON representation into python objects.\n"
"If it is False (default), it will return strings everywhere possible\n"
"and unicode objects only where necessary, else it will return unicode\n"
"objects everywhere (this is slower). The optional argument\n"
"`extension' defines a function to decode objects not in the original\n"
"JSON specification. For example this can be used to convert\n"
"new Date(...) expressions to datetime.date objects. The extension\n"
"function must have a two arguments: json, idx. The `json' argument\n"
"receives the original JSON string under conversion. The `idx' argument\n"
"receives the index of the first character of the substring to be\n"
"parsed as an extended object. The extension function must return a\n"
"2-tuple: (obj,count) or raise DecodeError if the string cannot be\n"
"parsed to an extended object. `obj' must be the object parsed,\n"
"`count' must be the (positive integer) number of characters consumed\n"
"from the JSON string (length of the object's representation).\n"
"All unicode strings will be encoded to the specified encoding\n"
"automatically if encoding is not None. Unicode objects are returned\n"
"if encoding is None (this is the default). It's encouraged to set\n"
"all_unicode=True or define an encoding to prevent mixing of str and\n"
"unicode objects in the decoder output."
)},
{NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(module_doc,
"Fast JSON encoder/decoder module."
);
/* Initialization function for the module (*must* be called initcjson) */
PyMODINIT_FUNC
initcjson(void)
{
PyObject *m;
/* Create the module and add the functions */
m = Py_InitModule3("cjson", cjson_methods, module_doc);
/* Add some symbolic constants to the module */
if (JSON_Error == NULL) {
JSON_Error = PyErr_NewException("cjson.Error", NULL, NULL);
if (JSON_Error == NULL)
return;
/*Py_INCREF(JSON_Error);*/
PyModule_AddObject(m, "Error", JSON_Error);
}
if (JSON_EncodeError == NULL) {
JSON_EncodeError = PyErr_NewException("cjson.EncodeError",
JSON_Error, NULL);
if (JSON_EncodeError == NULL)
return;
/*Py_INCREF(JSON_EncodeError);*/
PyModule_AddObject(m, "EncodeError", JSON_EncodeError);
}
if (JSON_DecodeError == NULL) {
JSON_DecodeError = PyErr_NewException("cjson.DecodeError",
JSON_Error, NULL);
if (JSON_DecodeError == NULL)
return;
/*Py_INCREF(JSON_DecodeError);*/
PyModule_AddObject(m, "DecodeError", JSON_DecodeError);
}
}
|
328 | ./cinnamon-control-center/panels/common/list-languages.c | #include "config.h"
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <locale.h>
#include <glib-object.h>
#include "gdm-languages.h"
int main (int argc, char **argv)
{
char **langs;
guint i;
setlocale (LC_ALL, NULL);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
g_type_init ();
if (argc > 1) {
guint i;
for (i = 1; i < argc; i++) {
char *lang, *norm;
norm = gdm_normalize_language_name (argv[i]);
lang = gdm_get_language_from_name (norm, NULL);
g_print ("%s (norm: %s) == %s\n", argv[i], norm, lang);
g_free (norm);
g_free (lang);
}
return 0;
}
langs = gdm_get_all_language_names ();
if (langs == NULL) {
g_warning ("No languages found");
return 1;
}
for (i = 0; langs[i] != NULL; i++)
g_print ("%s == %s\n", langs[i], gdm_get_language_from_name (langs[i], NULL));
g_strfreev (langs);
return 0;
}
|
329 | ./cinnamon-control-center/panels/common/cc-common-language.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright 2009-2010 Red Hat, Inc,
*
* 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.
*
* Written by: Matthias Clasen <[email protected]>
*/
#include "config.h"
#include <stdlib.h>
#include <locale.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <gtk/gtk.h>
#include <fontconfig/fontconfig.h>
#include "cc-common-language.h"
#include "gdm-languages.h"
static gint
cc_common_language_sort_languages (GtkTreeModel *model,
GtkTreeIter *a,
GtkTreeIter *b,
gpointer data)
{
char *ca, *cb;
char *la, *lb;
gboolean sa, ula;
gboolean sb, ulb;
gint result;
gtk_tree_model_get (model, a,
LOCALE_COL, &ca,
DISPLAY_LOCALE_COL, &la,
SEPARATOR_COL, &sa,
USER_LANGUAGE, &ula,
-1);
gtk_tree_model_get (model, b,
LOCALE_COL, &cb,
DISPLAY_LOCALE_COL, &lb,
SEPARATOR_COL, &sb,
USER_LANGUAGE, &ulb,
-1);
/* Sort before and after separator first */
if (sa && sb)
result = 0;
else if (sa)
result = ulb ? 1 : -1;
else if (sb)
result = ula ? -1 : 1;
/* Sort user-languages first */
else if (ula != ulb) {
if (ula)
result = -1;
else
result = 1;
}
else if (!ca)
result = 1;
else if (!cb)
result = -1;
else
result = strcmp (la, lb);
g_free (ca);
g_free (cb);
g_free (la);
g_free (lb);
return result;
}
static gboolean
iter_for_language (GtkTreeModel *model,
const gchar *lang,
GtkTreeIter *iter,
gboolean region)
{
char *l;
char *name;
char *language;
gtk_tree_model_get_iter_first (model, iter);
do {
gtk_tree_model_get (model, iter, LOCALE_COL, &l, -1);
if (g_strcmp0 (l, lang) == 0) {
g_free (l);
return TRUE;
}
g_free (l);
} while (gtk_tree_model_iter_next (model, iter));
name = gdm_normalize_language_name (lang);
if (name != NULL) {
if (region) {
language = gdm_get_region_from_name (name, NULL);
}
else {
language = gdm_get_language_from_name (name, NULL);
}
gtk_list_store_insert_with_values (GTK_LIST_STORE (model),
iter,
-1,
LOCALE_COL, name,
DISPLAY_LOCALE_COL, language,
-1);
g_free (name);
g_free (language);
return TRUE;
}
return FALSE;
}
gboolean
cc_common_language_get_iter_for_language (GtkTreeModel *model,
const gchar *lang,
GtkTreeIter *iter)
{
return iter_for_language (model, lang, iter, FALSE);
}
gboolean
cc_common_language_get_iter_for_region (GtkTreeModel *model,
const gchar *lang,
GtkTreeIter *iter)
{
return iter_for_language (model, lang, iter, TRUE);
}
gboolean
cc_common_language_has_font (const gchar *locale)
{
const FcCharSet *charset;
FcPattern *pattern;
FcObjectSet *object_set;
FcFontSet *font_set;
gchar *language_code;
gboolean is_displayable;
is_displayable = FALSE;
pattern = NULL;
object_set = NULL;
font_set = NULL;
if (!gdm_parse_language_name (locale, &language_code, NULL, NULL, NULL))
return FALSE;
charset = FcLangGetCharSet ((FcChar8 *) language_code);
if (!charset) {
/* fontconfig does not know about this language */
is_displayable = TRUE;
}
else {
/* see if any fonts support rendering it */
pattern = FcPatternBuild (NULL, FC_LANG, FcTypeString, language_code, NULL);
if (pattern == NULL)
goto done;
object_set = FcObjectSetCreate ();
if (object_set == NULL)
goto done;
font_set = FcFontList (NULL, pattern, object_set);
if (font_set == NULL)
goto done;
is_displayable = (font_set->nfont > 0);
}
done:
if (font_set != NULL)
FcFontSetDestroy (font_set);
if (object_set != NULL)
FcObjectSetDestroy (object_set);
if (pattern != NULL)
FcPatternDestroy (pattern);
g_free (language_code);
return is_displayable;
}
typedef struct
{
GtkListStore *store;
GHashTable *user_langs;
gchar **languages;
gboolean regions;
gint position;
} AsyncLangData;
static void
async_lang_data_free (AsyncLangData *data)
{
g_object_unref (data->store);
g_hash_table_unref (data->user_langs);
g_strfreev (data->languages);
g_free (data);
}
static gboolean
add_one_language (gpointer d)
{
AsyncLangData *data = d;
char *name;
char *language;
GtkTreeIter iter;
if (data->languages[data->position] == NULL) {
/* we are done */
async_lang_data_free (data);
return FALSE;
}
name = gdm_normalize_language_name (data->languages[data->position]);
if (g_hash_table_lookup (data->user_langs, name) != NULL) {
g_free (name);
goto next;
}
if (!cc_common_language_has_font (data->languages[data->position])) {
g_free (name);
goto next;
}
if (data->regions) {
language = gdm_get_region_from_name (name, NULL);
}
else {
language = gdm_get_language_from_name (name, NULL);
}
if (!language) {
g_debug ("Ignoring '%s' as a locale, because we couldn't figure the language name", name);
g_free (name);
goto next;
}
/* Add separator between initial languages and new additions */
if (g_object_get_data (G_OBJECT (data->store), "needs-separator")) {
GtkTreeIter iter;
gtk_list_store_insert_with_values (GTK_LIST_STORE (data->store),
&iter,
-1,
LOCALE_COL, NULL,
DISPLAY_LOCALE_COL, "Don't show",
SEPARATOR_COL, TRUE,
USER_LANGUAGE, FALSE,
-1);
g_object_set_data (G_OBJECT (data->store), "needs-separator", NULL);
}
gtk_list_store_insert_with_values (data->store,
&iter,
-1,
LOCALE_COL, name,
DISPLAY_LOCALE_COL, language,
-1);
g_free (name);
g_free (language);
next:
data->position++;
return TRUE;
}
guint
cc_common_language_add_available_languages (GtkListStore *store,
gboolean regions,
GHashTable *user_langs)
{
AsyncLangData *data;
data = g_new0 (AsyncLangData, 1);
data->store = g_object_ref (store);
data->user_langs = g_hash_table_ref (user_langs);
data->languages = gdm_get_all_language_names ();
data->regions = regions;
data->position = 0;
return gdk_threads_add_idle (add_one_language, data);
}
gchar *
cc_common_language_get_current_language (void)
{
gchar *language;
const gchar *locale;
locale = (const gchar *) setlocale (LC_MESSAGES, NULL);
if (locale)
language = gdm_normalize_language_name (locale);
else
language = NULL;
return language;
}
static void
languages_foreach_cb (gpointer key,
gpointer value,
gpointer user_data)
{
GtkListStore *store = (GtkListStore *) user_data;
const char *locale = (const char *) key;
const char *display_locale = (const char *) value;
GtkTreeIter iter;
gtk_list_store_insert_with_values (store,
&iter,
-1,
LOCALE_COL, locale,
DISPLAY_LOCALE_COL, display_locale,
SEPARATOR_COL, FALSE,
USER_LANGUAGE, TRUE,
-1);
}
static gboolean
separator_func (GtkTreeModel *model,
GtkTreeIter *iter,
gpointer data)
{
gboolean is_sep;
gtk_tree_model_get (model, iter,
SEPARATOR_COL, &is_sep,
-1);
return is_sep;
}
void
cc_common_language_setup_list (GtkWidget *treeview,
GHashTable *initial)
{
GtkCellRenderer *cell;
GtkTreeViewColumn *column;
GtkListStore *store;
cell = gtk_cell_renderer_text_new ();
g_object_set (cell,
"width-chars", 40,
"ellipsize", PANGO_ELLIPSIZE_END,
NULL);
column = gtk_tree_view_column_new_with_attributes (NULL, cell, "text", DISPLAY_LOCALE_COL, NULL);
gtk_tree_view_append_column (GTK_TREE_VIEW (treeview), column);
store = gtk_list_store_new (NUM_COLS, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN);
gtk_tree_sortable_set_default_sort_func (GTK_TREE_SORTABLE (store),
cc_common_language_sort_languages, NULL, NULL);
gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (store),
GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID,
GTK_SORT_ASCENDING);
gtk_tree_view_set_row_separator_func (GTK_TREE_VIEW (treeview),
separator_func,
NULL, NULL);
gtk_tree_view_set_model (GTK_TREE_VIEW (treeview), GTK_TREE_MODEL (store));
/* Add languages from the initial hashtable */
g_hash_table_foreach (initial, (GHFunc) languages_foreach_cb, store);
/* Mark the need for a separator if we had any languages added */
if (initial != NULL &&
g_hash_table_size (initial) > 0) {
g_object_set_data (G_OBJECT (store), "needs-separator", GINT_TO_POINTER (TRUE));
}
}
void
cc_common_language_select_current_language (GtkTreeView *treeview)
{
GtkTreeModel *model;
GtkTreeIter iter;
gboolean cont;
char *lang;
gboolean found;
lang = cc_common_language_get_current_language ();
g_debug ("Trying to select lang '%s' in treeview", lang);
model = gtk_tree_view_get_model (treeview);
found = FALSE;
cont = gtk_tree_model_get_iter_first (model, &iter);
while (cont) {
char *locale;
gtk_tree_model_get (model, &iter,
LOCALE_COL, &locale,
-1);
if (locale != NULL &&
g_str_equal (locale, lang)) {
GtkTreeSelection *selection;
g_debug ("Found '%s' in treeview", locale);
found = TRUE;
selection = gtk_tree_view_get_selection (treeview);
gtk_tree_selection_select_iter (selection, &iter);
g_free (locale);
break;
}
g_free (locale);
cont = gtk_tree_model_iter_next (model, &iter);
}
g_free (lang);
if (found == FALSE)
g_warning ("Could not find current language '%s' in the treeview", lang);
}
static void
add_other_users_language (GHashTable *ht)
{
GVariant *variant;
GVariantIter *vi;
GError *error = NULL;
const char *str;
GDBusProxy *proxy;
proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM,
G_DBUS_PROXY_FLAGS_NONE,
NULL,
"org.freedesktop.Accounts",
"/org/freedesktop/Accounts",
"org.freedesktop.Accounts",
NULL,
NULL);
if (proxy == NULL)
return;
variant = g_dbus_proxy_call_sync (proxy,
"ListCachedUsers",
NULL,
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
&error);
if (variant == NULL) {
g_warning ("Failed to list existing users: %s", error->message);
g_error_free (error);
g_object_unref (proxy);
return;
}
g_variant_get (variant, "(ao)", &vi);
while (g_variant_iter_loop (vi, "o", &str)) {
GDBusProxy *user;
GVariant *props;
const char *lang;
char *name;
char *language;
user = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM,
G_DBUS_PROXY_FLAGS_NONE,
NULL,
"org.freedesktop.Accounts",
str,
"org.freedesktop.Accounts.User",
NULL,
&error);
if (user == NULL) {
g_warning ("Failed to get proxy for user '%s': %s",
str, error->message);
g_error_free (error);
error = NULL;
continue;
}
props = g_dbus_proxy_get_cached_property (user, "Language");
lang = g_variant_get_string (props, NULL);
if (lang != NULL && *lang != '\0' &&
cc_common_language_has_font (lang) &&
gdm_language_has_translations (lang)) {
name = gdm_normalize_language_name (lang);
if (!g_hash_table_lookup (ht, name)) {
language = gdm_get_language_from_name (name, NULL);
g_hash_table_insert (ht, name, language);
}
else {
g_free (name);
}
}
g_variant_unref (props);
g_object_unref (user);
}
g_variant_iter_free (vi);
g_variant_unref (variant);
g_object_unref (proxy);
}
GHashTable *
cc_common_language_get_initial_languages (void)
{
GHashTable *ht;
char *name;
char *language;
ht = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
/* Add some common languages first */
g_hash_table_insert (ht, g_strdup ("en_US.utf8"), g_strdup (_("English")));
if (gdm_language_has_translations ("en_GB"))
g_hash_table_insert (ht, g_strdup ("en_GB.utf8"), g_strdup (_("British English")));
if (gdm_language_has_translations ("de") ||
gdm_language_has_translations ("de_DE"))
g_hash_table_insert (ht, g_strdup ("de_DE.utf8"), g_strdup (_("German")));
if (gdm_language_has_translations ("fr") ||
gdm_language_has_translations ("fr_FR"))
g_hash_table_insert (ht, g_strdup ("fr_FR.utf8"), g_strdup (_("French")));
if (gdm_language_has_translations ("es") ||
gdm_language_has_translations ("es_ES"))
g_hash_table_insert (ht, g_strdup ("es_ES.utf8"), g_strdup (_("Spanish")));
if (gdm_language_has_translations ("zh_CN"))
g_hash_table_insert (ht, g_strdup ("zh_CN.utf8"), g_strdup (_("Chinese (simplified)")));
if (gdm_language_has_translations ("ru") ||
gdm_language_has_translations ("ru_RU"))
g_hash_table_insert (ht, g_strdup ("ru_RU.utf8"), g_strdup (_("Russian")));
if (gdm_language_has_translations ("ar") ||
gdm_language_has_translations ("ar_EG"))
g_hash_table_insert (ht, g_strdup ("ar_EG.utf8"), g_strdup (_("Arabic")));
/* Add the languages used by other users on the system */
add_other_users_language (ht);
/* Add current locale */
name = cc_common_language_get_current_language ();
if (g_hash_table_lookup (ht, name) == NULL) {
language = gdm_get_language_from_name (name, NULL);
g_hash_table_insert (ht, name, language);
} else {
g_free (name);
}
return ht;
}
GHashTable *
cc_common_language_get_initial_regions (const gchar *lang)
{
GHashTable *ht;
char *language;
gchar **langs;
gint i;
ht = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
#if 0
/* Add some common regions */
g_hash_table_insert (ht, g_strdup ("en_US.utf8"), g_strdup (_("United States")));
g_hash_table_insert (ht, g_strdup ("de_DE.utf8"), g_strdup (_("Germany")));
g_hash_table_insert (ht, g_strdup ("fr_FR.utf8"), g_strdup (_("France")));
g_hash_table_insert (ht, g_strdup ("es_ES.utf8"), g_strdup (_("Spain")));
g_hash_table_insert (ht, g_strdup ("zh_CN.utf8"), g_strdup (_("China")));
#endif
gdm_parse_language_name (lang, &language, NULL, NULL, NULL);
langs = gdm_get_all_language_names ();
for (i = 0; langs[i]; i++) {
gchar *l, *s;
gdm_parse_language_name (langs[i], &l, NULL, NULL, NULL);
if (g_strcmp0 (language, l) == 0) {
if (!g_hash_table_lookup (ht, langs[i])) {
s = gdm_get_region_from_name (langs[i], NULL);
g_hash_table_insert (ht, g_strdup (langs[i]), s);
}
}
g_free (l);
}
g_strfreev (langs);
g_free (language);
return ht;
}
|
330 | ./cinnamon-control-center/panels/common/gdm-languages.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright 2008 Red Hat, Inc,
* 2007 William Jon McCann <[email protected]>
*
* 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.
*
* Written by : William Jon McCann <[email protected]>
* Ray Strode <[email protected]>
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <dirent.h>
#include <locale.h>
#include <langinfo.h>
#include <sys/stat.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <glib/gstdio.h>
#include "gdm-languages.h"
#include <langinfo.h>
#ifndef __LC_LAST
#define __LC_LAST 13
#endif
#include "locarchive.h"
#define ALIASES_FILE DATADIR "/gdm/locale.alias"
#define ARCHIVE_FILE LIBLOCALEDIR "/locale-archive"
#define SYSTEM_ARCHIVE_FILE "/usr/lib/locale/locale-archive"
#define ISO_CODES_DATADIR ISO_CODES_PREFIX "/share/xml/iso-codes"
#define ISO_CODES_LOCALESDIR ISO_CODES_PREFIX "/share/locale"
typedef struct _GdmLocale {
char *id;
char *name;
char *language_code;
char *territory_code;
char *codeset;
char *modifier;
} GdmLocale;
static GHashTable *gdm_languages_map;
static GHashTable *gdm_territories_map;
static GHashTable *gdm_available_locales_map;
static GHashTable *gdm_language_count_map;
static GHashTable *gdm_territory_count_map;
static char * construct_language_name (const char *language,
const char *territory,
const char *codeset,
const char *modifier);
static gboolean language_name_is_valid (const char *language_name);
static void
gdm_locale_free (GdmLocale *locale)
{
if (locale == NULL) {
return;
}
g_free (locale->id);
g_free (locale->name);
g_free (locale->codeset);
g_free (locale->modifier);
g_free (locale);
}
static char *
normalize_codeset (const char *codeset)
{
char *normalized_codeset;
const char *p;
char *q;
normalized_codeset = g_strdup (codeset);
if (codeset != NULL) {
for (p = codeset, q = normalized_codeset;
*p != '\0'; p++) {
if (*p == '-' || *p == '_') {
continue;
}
*q = g_ascii_tolower (*p);
q++;
}
*q = '\0';
}
return normalized_codeset;
}
/*
* According to http://en.wikipedia.org/wiki/Locale
* locale names are of the form:
* [language[_territory][.codeset][@modifier]]
*/
gboolean
gdm_parse_language_name (const char *name,
char **language_codep,
char **territory_codep,
char **codesetp,
char **modifierp)
{
GRegex *re;
GMatchInfo *match_info;
gboolean res;
GError *error;
gchar *normalized_codeset = NULL;
gchar *normalized_name = NULL;
gboolean retval;
match_info = NULL;
retval = FALSE;
error = NULL;
re = g_regex_new ("^(?P<language>[^_.@[:space:]]+)"
"(_(?P<territory>[[:upper:]]+))?"
"(\\.(?P<codeset>[-_0-9a-zA-Z]+))?"
"(@(?P<modifier>[[:ascii:]]+))?$",
0, 0, &error);
if (re == NULL) {
g_warning ("%s", error->message);
goto out;
}
if (!g_regex_match (re, name, 0, &match_info) ||
g_match_info_is_partial_match (match_info)) {
g_warning ("locale '%s' isn't valid\n", name);
goto out;
}
res = g_match_info_matches (match_info);
if (! res) {
g_warning ("Unable to parse locale: %s", name);
goto out;
}
retval = TRUE;
if (language_codep != NULL) {
*language_codep = g_match_info_fetch_named (match_info, "language");
}
if (territory_codep != NULL) {
*territory_codep = g_match_info_fetch_named (match_info, "territory");
if (*territory_codep != NULL &&
*territory_codep[0] == '\0') {
g_free (*territory_codep);
*territory_codep = NULL;
}
}
if (codesetp != NULL) {
*codesetp = g_match_info_fetch_named (match_info, "codeset");
if (*codesetp != NULL &&
*codesetp[0] == '\0') {
g_free (*codesetp);
*codesetp = NULL;
}
}
if (modifierp != NULL) {
*modifierp = g_match_info_fetch_named (match_info, "modifier");
if (*modifierp != NULL &&
*modifierp[0] == '\0') {
g_free (*modifierp);
*modifierp = NULL;
}
}
if (codesetp != NULL && *codesetp != NULL) {
normalized_codeset = normalize_codeset (*codesetp);
normalized_name = construct_language_name (language_codep ? *language_codep : NULL,
territory_codep ? *territory_codep : NULL,
normalized_codeset,
modifierp ? *modifierp : NULL);
if (language_name_is_valid (normalized_name)) {
g_free (*codesetp);
*codesetp = normalized_codeset;
} else {
g_free (normalized_codeset);
}
g_free (normalized_name);
}
out:
g_match_info_free (match_info);
g_regex_unref (re);
return retval;
}
static char *
construct_language_name (const char *language,
const char *territory,
const char *codeset,
const char *modifier)
{
char *name;
g_assert (language[0] != 0);
g_assert (territory == NULL || territory[0] != 0);
g_assert (codeset == NULL || codeset[0] != 0);
g_assert (modifier == NULL || modifier[0] != 0);
name = g_strdup_printf ("%s%s%s%s%s%s%s",
language,
territory != NULL? "_" : "",
territory != NULL? territory : "",
codeset != NULL? "." : "",
codeset != NULL? codeset : "",
modifier != NULL? "@" : "",
modifier != NULL? modifier : "");
return name;
}
char *
gdm_normalize_language_name (const char *name)
{
char *normalized_name;
char *language_code;
char *territory_code;
char *codeset;
char *modifier;
if (name[0] == '\0') {
return NULL;
}
gdm_parse_language_name (name,
&language_code,
&territory_code,
&codeset, &modifier);
normalized_name = construct_language_name (language_code,
territory_code,
codeset, modifier);
g_free (language_code);
g_free (territory_code);
g_free (codeset);
g_free (modifier);
return normalized_name;
}
static gboolean
language_name_is_valid (const char *language_name)
{
char *old_locale;
gboolean is_valid;
#ifdef WITH_INCOMPLETE_LOCALES
int lc_type_id = LC_CTYPE;
#else
int lc_type_id = LC_MESSAGES;
#endif
old_locale = g_strdup (setlocale (lc_type_id, NULL));
is_valid = setlocale (lc_type_id, language_name) != NULL;
setlocale (lc_type_id, old_locale);
g_free (old_locale);
return is_valid;
}
static void
language_name_get_codeset_details (const char *language_name,
char **pcodeset,
gboolean *is_utf8)
{
char *old_locale;
char *codeset;
old_locale = g_strdup (setlocale (LC_CTYPE, NULL));
if (setlocale (LC_CTYPE, language_name) == NULL) {
g_free (old_locale);
return;
}
codeset = nl_langinfo (CODESET);
if (pcodeset != NULL) {
*pcodeset = g_strdup (codeset);
}
if (is_utf8 != NULL) {
codeset = normalize_codeset (codeset);
*is_utf8 = strcmp (codeset, "utf8") == 0;
g_free (codeset);
}
setlocale (LC_CTYPE, old_locale);
g_free (old_locale);
}
gboolean
gdm_language_has_translations (const char *language_name)
{
GDir *dir;
char *path;
const char *name;
gboolean has_translations;
path = g_build_filename (LOCALE_DIR, language_name, "LC_MESSAGES", NULL);
has_translations = FALSE;
dir = g_dir_open (path, 0, NULL);
g_free (path);
if (dir == NULL) {
goto out;
}
do {
name = g_dir_read_name (dir);
if (name == NULL) {
break;
}
if (g_str_has_suffix (name, ".mo")) {
has_translations = TRUE;
break;
}
} while (name != NULL);
g_dir_close (dir);
out:
return has_translations;
}
static gboolean
add_locale (const char *language_name,
gboolean utf8_only)
{
GdmLocale *locale;
GdmLocale *old_locale;
char *name;
gboolean is_utf8 = FALSE;
g_return_val_if_fail (language_name != NULL, FALSE);
g_return_val_if_fail (*language_name != '\0', FALSE);
language_name_get_codeset_details (language_name, NULL, &is_utf8);
if (is_utf8) {
name = g_strdup (language_name);
} else if (utf8_only) {
name = g_strdup_printf ("%s.utf8", language_name);
language_name_get_codeset_details (name, NULL, &is_utf8);
if (!is_utf8) {
g_free (name);
return FALSE;
}
} else {
name = g_strdup (language_name);
}
if (!language_name_is_valid (name)) {
g_debug ("Ignoring '%s' as a locale, since it's invalid", name);
g_free (name);
return FALSE;
}
locale = g_new0 (GdmLocale, 1);
gdm_parse_language_name (name,
&locale->language_code,
&locale->territory_code,
&locale->codeset,
&locale->modifier);
g_free (name);
name = NULL;
#ifdef WITH_INCOMPLETE_LOCALES
if (utf8_only) {
if (locale->territory_code == NULL || locale->modifier) {
g_debug ("Ignoring '%s' as a locale, since it lacks territory code or modifier", name);
gdm_locale_free (locale);
return FALSE;
}
}
#endif
locale->id = construct_language_name (locale->language_code, locale->territory_code,
NULL, locale->modifier);
locale->name = construct_language_name (locale->language_code, locale->territory_code,
locale->codeset, locale->modifier);
#ifndef WITH_INCOMPLETE_LOCALES
if (!gdm_language_has_translations (locale->name) &&
!gdm_language_has_translations (locale->id) &&
!gdm_language_has_translations (locale->language_code) &&
utf8_only) {
g_debug ("Ignoring '%s' as a locale, since it lacks translations", locale->name);
gdm_locale_free (locale);
return FALSE;
}
#endif
if (!utf8_only) {
g_free (locale->id);
locale->id = g_strdup (locale->name);
}
old_locale = g_hash_table_lookup (gdm_available_locales_map, locale->id);
if (old_locale != NULL) {
if (strlen (old_locale->name) > strlen (locale->name)) {
gdm_locale_free (locale);
return FALSE;
}
}
g_hash_table_insert (gdm_available_locales_map, g_strdup (locale->id), locale);
return TRUE;
}
struct nameent
{
char *name;
uint32_t locrec_offset;
};
static gboolean
collect_locales_from_archive (void)
{
GMappedFile *mapped;
GError *error;
char *addr;
struct locarhead *head;
struct namehashent *namehashtab;
struct nameent *names;
uint32_t used;
uint32_t cnt;
gsize len;
gboolean locales_collected;
error = NULL;
mapped = g_mapped_file_new (ARCHIVE_FILE, FALSE, &error);
if (mapped == NULL) {
mapped = g_mapped_file_new (SYSTEM_ARCHIVE_FILE, FALSE, NULL);
if (mapped == NULL) {
g_warning ("Mapping failed for %s: %s", ARCHIVE_FILE, error->message);
g_error_free (error);
return FALSE;
}
g_error_free (error);
}
locales_collected = FALSE;
addr = g_mapped_file_get_contents (mapped);
len = g_mapped_file_get_length (mapped);
head = (struct locarhead *) addr;
if (head->namehash_offset + head->namehash_size > len
|| head->string_offset + head->string_size > len
|| head->locrectab_offset + head->locrectab_size > len
|| head->sumhash_offset + head->sumhash_size > len) {
goto out;
}
namehashtab = (struct namehashent *) (addr + head->namehash_offset);
names = (struct nameent *) g_new0 (struct nameent, head->namehash_used);
for (cnt = used = 0; cnt < head->namehash_size; ++cnt) {
if (namehashtab[cnt].locrec_offset != 0) {
names[used].name = addr + namehashtab[cnt].name_offset;
names[used++].locrec_offset = namehashtab[cnt].locrec_offset;
}
}
for (cnt = 0; cnt < used; ++cnt) {
add_locale (names[cnt].name, TRUE);
}
g_free (names);
locales_collected = TRUE;
out:
g_mapped_file_unref (mapped);
return locales_collected;
}
static int
select_dirs (const struct dirent *dirent)
{
int result = 0;
if (strcmp (dirent->d_name, ".") != 0 && strcmp (dirent->d_name, "..") != 0) {
mode_t mode = 0;
#ifdef _DIRENT_HAVE_D_TYPE
if (dirent->d_type != DT_UNKNOWN && dirent->d_type != DT_LNK) {
mode = DTTOIF (dirent->d_type);
} else
#endif
{
struct stat st;
char *path;
path = g_build_filename (LIBLOCALEDIR, dirent->d_name, NULL);
if (g_stat (path, &st) == 0) {
mode = st.st_mode;
}
g_free (path);
}
result = S_ISDIR (mode);
}
return result;
}
static void
collect_locales_from_directory (void)
{
struct dirent **dirents;
int ndirents;
int cnt;
ndirents = scandir (LIBLOCALEDIR, &dirents, select_dirs, alphasort);
for (cnt = 0; cnt < ndirents; ++cnt) {
add_locale (dirents[cnt]->d_name, TRUE);
}
if (ndirents > 0) {
free (dirents);
}
}
static void
collect_locales_from_locale_file (const char *locale_file)
{
FILE *langlist;
char curline[256];
char *getsret;
if (locale_file == NULL)
return;
langlist = fopen (locale_file, "r");
if (langlist == NULL)
return;
for (;;) {
char *name;
char *lang;
char **lang_list;
int i;
getsret = fgets (curline, sizeof (curline), langlist);
if (getsret == NULL)
break;
if (curline[0] <= ' ' ||
curline[0] == '#')
continue;
name = strtok (curline, " \t\r\n");
if (name == NULL)
continue;
lang = strtok (NULL, " \t\r\n");
if (lang == NULL)
continue;
lang_list = g_strsplit (lang, ",", -1);
if (lang_list == NULL)
continue;
lang = NULL;
for (i = 0; lang_list[i] != NULL; i++) {
if (add_locale (lang_list[i], FALSE)) {
break;
}
}
g_strfreev (lang_list);
}
fclose (langlist);
}
static void
count_languages_and_territories (void)
{
gpointer value;
GHashTableIter iter;
gdm_language_count_map = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
gdm_territory_count_map = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
g_hash_table_iter_init (&iter, gdm_available_locales_map);
while (g_hash_table_iter_next (&iter, NULL, &value)) {
GdmLocale *locale;
locale = (GdmLocale *) value;
if (locale->language_code != NULL) {
int count;
count = GPOINTER_TO_INT (g_hash_table_lookup (gdm_language_count_map, locale->language_code));
count++;
g_hash_table_insert (gdm_language_count_map, g_strdup (locale->language_code), GINT_TO_POINTER (count));
}
if (locale->territory_code != NULL) {
int count;
count = GPOINTER_TO_INT (g_hash_table_lookup (gdm_territory_count_map, locale->territory_code));
count++;
g_hash_table_insert (gdm_territory_count_map, g_strdup (locale->territory_code), GINT_TO_POINTER (count));
}
}
}
static void
collect_locales (void)
{
if (gdm_available_locales_map == NULL) {
gdm_available_locales_map = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) gdm_locale_free);
}
if (!collect_locales_from_archive ()) {
#ifndef WITH_INCOMPLETE_LOCALES
g_warning ("Could not read list of available locales from libc, "
"guessing possible locales from available translations, "
"but list may be incomplete!");
#endif
}
collect_locales_from_directory ();
collect_locales_from_locale_file (ALIASES_FILE);
count_languages_and_territories ();
}
static gint
get_language_count (const char *language)
{
if (gdm_language_count_map == NULL) {
collect_locales ();
}
return GPOINTER_TO_INT (g_hash_table_lookup (gdm_language_count_map, language));
}
static gboolean
is_unique_language (const char *language)
{
return get_language_count (language) == 1;
}
static gint
get_territory_count (const char *territory)
{
if (gdm_territory_count_map == NULL) {
collect_locales ();
}
return GPOINTER_TO_INT (g_hash_table_lookup (gdm_territory_count_map, territory));
}
static gboolean
is_unique_territory (const char *territory)
{
return get_territory_count (territory) == 1;
}
static gboolean
is_fallback_language (const char *code)
{
const char *fallback_language_names[] = { "C", "POSIX", NULL };
int i;
for (i = 0; fallback_language_names[i] != NULL; i++) {
if (strcmp (code, fallback_language_names[i]) == 0) {
return TRUE;
}
}
return FALSE;
}
static const char *
get_language (const char *code)
{
const char *name;
int len;
g_assert (code != NULL);
if (is_fallback_language (code)) {
return "Unspecified";
}
len = strlen (code);
if (len != 2 && len != 3) {
return NULL;
}
name = (const char *) g_hash_table_lookup (gdm_languages_map, code);
return name;
}
static char *
get_first_item_in_semicolon_list (const char *list)
{
char **items;
char *item;
/* Some entries in iso codes have multiple values, separated
* by semicolons. Not really sure which one to pick, so
* we just arbitrarily pick the first one.
*/
items = g_strsplit (list, "; ", 2);
item = g_strdup (items[0]);
g_strfreev (items);
return item;
}
static char *
get_translated_language (const char *code,
const char *locale)
{
const char *language;
char *name;
language = get_language (code);
name = NULL;
if (language != NULL) {
const char *translated_name;
char *old_locale;
if (locale != NULL) {
old_locale = g_strdup (setlocale (LC_MESSAGES, NULL));
setlocale (LC_MESSAGES, locale);
}
if (is_fallback_language (code)) {
name = g_strdup (_("Unspecified"));
} else {
translated_name = dgettext ("iso_639", language);
name = get_first_item_in_semicolon_list (translated_name);
}
if (locale != NULL) {
setlocale (LC_MESSAGES, old_locale);
g_free (old_locale);
}
}
return name;
}
static const char *
get_territory (const char *code)
{
const char *name;
int len;
g_assert (code != NULL);
len = strlen (code);
if (len != 2 && len != 3) {
return NULL;
}
name = (const char *) g_hash_table_lookup (gdm_territories_map, code);
return name;
}
static char *
get_translated_territory (const char *code,
const char *locale)
{
const char *territory;
char *name;
territory = get_territory (code);
name = NULL;
if (territory != NULL) {
const char *translated_territory;
char *old_locale;
if (locale != NULL) {
old_locale = g_strdup (setlocale (LC_MESSAGES, NULL));
setlocale (LC_MESSAGES, locale);
}
translated_territory = dgettext ("iso_3166", territory);
name = get_first_item_in_semicolon_list (translated_territory);
if (locale != NULL) {
setlocale (LC_MESSAGES, old_locale);
g_free (old_locale);
}
}
return name;
}
static void
languages_parse_start_tag (GMarkupParseContext *ctx,
const char *element_name,
const char **attr_names,
const char **attr_values,
gpointer user_data,
GError **error)
{
const char *ccode_longB;
const char *ccode_longT;
const char *ccode;
const char *ccode_id;
const char *lang_name;
if (! (g_str_equal (element_name, "iso_639_entry") || g_str_equal (element_name, "iso_639_3_entry"))
|| attr_names == NULL || attr_values == NULL) {
return;
}
ccode = NULL;
ccode_longB = NULL;
ccode_longT = NULL;
ccode_id = NULL;
lang_name = NULL;
while (*attr_names && *attr_values) {
if (g_str_equal (*attr_names, "iso_639_1_code")) {
/* skip if empty */
if (**attr_values) {
if (strlen (*attr_values) != 2) {
return;
}
ccode = *attr_values;
}
} else if (g_str_equal (*attr_names, "iso_639_2B_code")) {
/* skip if empty */
if (**attr_values) {
if (strlen (*attr_values) != 3) {
return;
}
ccode_longB = *attr_values;
}
} else if (g_str_equal (*attr_names, "iso_639_2T_code")) {
/* skip if empty */
if (**attr_values) {
if (strlen (*attr_values) != 3) {
return;
}
ccode_longT = *attr_values;
}
} else if (g_str_equal (*attr_names, "id")) {
/* skip if empty */
if (**attr_values) {
if (strlen (*attr_values) != 2 &&
strlen (*attr_values) != 3) {
return;
}
ccode_id = *attr_values;
}
} else if (g_str_equal (*attr_names, "name")) {
lang_name = *attr_values;
}
++attr_names;
++attr_values;
}
if (lang_name == NULL) {
return;
}
if (ccode != NULL) {
g_hash_table_insert (gdm_languages_map,
g_strdup (ccode),
g_strdup (lang_name));
}
if (ccode_longB != NULL) {
g_hash_table_insert (gdm_languages_map,
g_strdup (ccode_longB),
g_strdup (lang_name));
}
if (ccode_longT != NULL) {
g_hash_table_insert (gdm_languages_map,
g_strdup (ccode_longT),
g_strdup (lang_name));
}
if (ccode_id != NULL) {
g_hash_table_insert (gdm_languages_map,
g_strdup (ccode_id),
g_strdup (lang_name));
}
}
static void
territories_parse_start_tag (GMarkupParseContext *ctx,
const char *element_name,
const char **attr_names,
const char **attr_values,
gpointer user_data,
GError **error)
{
const char *acode_2;
const char *acode_3;
const char *ncode;
const char *territory_common_name;
const char *territory_name;
if (! g_str_equal (element_name, "iso_3166_entry") || attr_names == NULL || attr_values == NULL) {
return;
}
acode_2 = NULL;
acode_3 = NULL;
ncode = NULL;
territory_common_name = NULL;
territory_name = NULL;
while (*attr_names && *attr_values) {
if (g_str_equal (*attr_names, "alpha_2_code")) {
/* skip if empty */
if (**attr_values) {
if (strlen (*attr_values) != 2) {
return;
}
acode_2 = *attr_values;
}
} else if (g_str_equal (*attr_names, "alpha_3_code")) {
/* skip if empty */
if (**attr_values) {
if (strlen (*attr_values) != 3) {
return;
}
acode_3 = *attr_values;
}
} else if (g_str_equal (*attr_names, "numeric_code")) {
/* skip if empty */
if (**attr_values) {
if (strlen (*attr_values) != 3) {
return;
}
ncode = *attr_values;
}
} else if (g_str_equal (*attr_names, "common_name")) {
/* skip if empty */
if (**attr_values) {
territory_common_name = *attr_values;
}
} else if (g_str_equal (*attr_names, "name")) {
territory_name = *attr_values;
}
++attr_names;
++attr_values;
}
if (territory_common_name != NULL) {
territory_name = territory_common_name;
}
if (territory_name == NULL) {
return;
}
if (acode_2 != NULL) {
g_hash_table_insert (gdm_territories_map,
g_strdup (acode_2),
g_strdup (territory_name));
}
if (acode_3 != NULL) {
g_hash_table_insert (gdm_territories_map,
g_strdup (acode_3),
g_strdup (territory_name));
}
if (ncode != NULL) {
g_hash_table_insert (gdm_territories_map,
g_strdup (ncode),
g_strdup (territory_name));
}
}
static void
languages_variant_init (const char *variant)
{
GError *error;
gboolean res;
char *buf;
gsize buf_len;
char *filename;
bindtextdomain (variant, ISO_CODES_LOCALESDIR);
bind_textdomain_codeset (variant, "UTF-8");
error = NULL;
filename = g_strdup_printf (ISO_CODES_DATADIR "/%s.xml", variant);
res = g_file_get_contents (filename,
&buf,
&buf_len,
&error);
if (res) {
GMarkupParseContext *ctx;
GMarkupParser parser = { languages_parse_start_tag, NULL, NULL, NULL, NULL };
ctx = g_markup_parse_context_new (&parser, 0, NULL, NULL);
error = NULL;
res = g_markup_parse_context_parse (ctx, buf, buf_len, &error);
if (! res) {
g_warning ("Failed to parse '%s': %s\n",
filename,
error->message);
g_error_free (error);
g_free (filename);
}
g_markup_parse_context_free (ctx);
g_free (buf);
} else {
g_warning ("Failed to load '%s': %s\n",
filename,
error->message);
g_error_free (error);
}
}
static void
languages_init (void)
{
gdm_languages_map = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
languages_variant_init ("iso_639");
languages_variant_init ("iso_639_3");
}
static void
territories_init (void)
{
GError *error;
gboolean res;
char *buf;
gsize buf_len;
bindtextdomain ("iso_3166", ISO_CODES_LOCALESDIR);
bind_textdomain_codeset ("iso_3166", "UTF-8");
gdm_territories_map = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
error = NULL;
res = g_file_get_contents (ISO_CODES_DATADIR "/iso_3166.xml",
&buf,
&buf_len,
&error);
if (res) {
GMarkupParseContext *ctx;
GMarkupParser parser = { territories_parse_start_tag, NULL, NULL, NULL, NULL };
ctx = g_markup_parse_context_new (&parser, 0, NULL, NULL);
error = NULL;
res = g_markup_parse_context_parse (ctx, buf, buf_len, &error);
if (! res) {
g_warning ("Failed to parse '%s': %s\n",
ISO_CODES_DATADIR "/iso_3166.xml",
error->message);
g_error_free (error);
}
g_markup_parse_context_free (ctx);
g_free (buf);
} else {
g_warning ("Failed to load '%s': %s\n",
ISO_CODES_DATADIR "/iso_3166.xml",
error->message);
g_error_free (error);
}
}
char *
gdm_get_language_from_name (const char *name,
const char *locale)
{
GString *full_language;
char *language_code;
char *territory_code;
char *codeset_code;
char *langinfo_codeset;
char *translated_language;
char *translated_territory;
char *modifier;
gboolean is_utf8 = TRUE;
g_return_val_if_fail (name != NULL, NULL);
g_return_val_if_fail (*name != '\0', NULL);
translated_territory = NULL;
translated_language = NULL;
langinfo_codeset = NULL;
full_language = g_string_new (NULL);
if (gdm_languages_map == NULL) {
languages_init ();
}
if (gdm_territories_map == NULL) {
territories_init ();
}
language_code = NULL;
territory_code = NULL;
codeset_code = NULL;
modifier = NULL;
gdm_parse_language_name (name,
&language_code,
&territory_code,
&codeset_code,
&modifier);
if (language_code == NULL) {
goto out;
}
translated_language = get_translated_language (language_code, locale);
if (translated_language == NULL) {
goto out;
}
full_language = g_string_append (full_language, translated_language);
if (is_unique_language (language_code)) {
goto out;
}
if (territory_code != NULL) {
translated_territory = get_translated_territory (territory_code, locale);
}
if (translated_territory != NULL) {
g_string_append_printf (full_language,
" (%s)",
translated_territory);
}
// language_name_get_codeset_details (name, &langinfo_codeset, &is_utf8);
if (codeset_code == NULL && langinfo_codeset != NULL) {
codeset_code = g_strdup (langinfo_codeset);
}
if (!is_utf8 && codeset_code) {
g_string_append_printf (full_language,
" [%s]",
codeset_code);
}
if (modifier != NULL) {
g_string_append_printf (full_language, " - %s", modifier);
}
out:
g_free (language_code);
g_free (territory_code);
g_free (codeset_code);
g_free (langinfo_codeset);
g_free (translated_language);
g_free (translated_territory);
g_free (modifier);
if (full_language->len == 0) {
g_string_free (full_language, TRUE);
return NULL;
}
return g_string_free (full_language, FALSE);
}
char *
gdm_get_region_from_name (const char *name,
const char *locale)
{
GString *full_name;
char *language_code;
char *territory_code;
char *codeset_code;
char *langinfo_codeset;
char *translated_language;
char *translated_territory;
gboolean is_utf8 = TRUE;
g_return_val_if_fail (name != NULL, NULL);
g_return_val_if_fail (*name != '\0', NULL);
translated_territory = NULL;
translated_language = NULL;
langinfo_codeset = NULL;
full_name = g_string_new (NULL);
if (gdm_languages_map == NULL) {
languages_init ();
}
if (gdm_territories_map == NULL) {
territories_init ();
}
language_code = NULL;
territory_code = NULL;
codeset_code = NULL;
gdm_parse_language_name (name,
&language_code,
&territory_code,
&codeset_code,
NULL);
if (territory_code == NULL) {
goto out;
}
translated_territory = get_translated_territory (territory_code, locale);
g_string_append (full_name, translated_territory);
if (is_unique_territory (territory_code)) {
goto out;
}
if (language_code != NULL) {
translated_language = get_translated_language (language_code, locale);
}
if (translated_language != NULL) {
g_string_append_printf (full_name,
" (%s)",
translated_language);
}
language_name_get_codeset_details (name, &langinfo_codeset, &is_utf8);
if (codeset_code == NULL && langinfo_codeset != NULL) {
codeset_code = g_strdup (langinfo_codeset);
}
if (!is_utf8 && codeset_code) {
g_string_append_printf (full_name,
" [%s]",
codeset_code);
}
out:
g_free (language_code);
g_free (territory_code);
g_free (codeset_code);
g_free (langinfo_codeset);
g_free (translated_language);
g_free (translated_territory);
if (full_name->len == 0) {
g_string_free (full_name, TRUE);
return NULL;
}
return g_string_free (full_name, FALSE);
}
char **
gdm_get_all_language_names (void)
{
GHashTableIter iter;
gpointer key, value;
GPtrArray *array;
if (gdm_available_locales_map == NULL) {
collect_locales ();
}
array = g_ptr_array_new ();
g_hash_table_iter_init (&iter, gdm_available_locales_map);
while (g_hash_table_iter_next (&iter, &key, &value)) {
GdmLocale *locale;
locale = (GdmLocale *) value;
g_ptr_array_add (array, g_strdup (locale->name));
}
g_ptr_array_add (array, NULL);
return (char **) g_ptr_array_free (array, FALSE);
}
|
331 | ./cinnamon-control-center/panels/common/cc-language-chooser.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright 2009-2010 Red Hat, Inc,
*
* 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.
*
* Written by: Matthias Clasen <[email protected]>
*/
#include "config.h"
#include <stdlib.h>
#include <locale.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <gio/gio.h>
#include <gtk/gtk.h>
#include <fontconfig/fontconfig.h>
#include "cc-language-chooser.h"
#include "cc-common-language.h"
#include "gdm-languages.h"
gchar *
cc_language_chooser_get_language (GtkWidget *chooser)
{
GtkTreeView *tv;
GtkTreeSelection *selection;
GtkTreeModel *model;
GtkTreeIter iter;
gchar *lang;
tv = (GtkTreeView *) g_object_get_data (G_OBJECT (chooser), "list");
selection = gtk_tree_view_get_selection (tv);
gdk_threads_enter ();
if (gtk_tree_selection_get_selected (selection, &model, &iter))
gtk_tree_model_get (model, &iter, LOCALE_COL, &lang, -1);
else
lang = NULL;
gdk_threads_leave ();
return lang;
}
void
cc_language_chooser_clear_filter (GtkWidget *chooser)
{
GtkEntry *entry;
entry = (GtkEntry *) g_object_get_data (G_OBJECT (chooser), "filter-entry");
gtk_entry_set_text (entry, "");
}
static void
row_activated (GtkTreeView *tree_view,
GtkTreePath *path,
GtkTreeViewColumn *column,
GtkWidget *chooser)
{
gtk_dialog_response (GTK_DIALOG (chooser), GTK_RESPONSE_OK);
}
static void
languages_foreach_cb (gpointer key,
gpointer value,
gpointer user_data)
{
GtkListStore *store = (GtkListStore *) user_data;
const char *locale = (const char *) key;
const char *display_locale = (const char *) value;
GtkTreeIter iter;
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter,
LOCALE_COL, locale,
DISPLAY_LOCALE_COL, display_locale,
-1);
}
void
cc_add_user_languages (GtkTreeModel *model)
{
char *name;
GtkTreeIter iter;
GtkListStore *store = GTK_LIST_STORE (model);
GHashTable *user_langs;
const char *display;
gtk_list_store_clear (store);
user_langs = cc_common_language_get_initial_languages ();
/* Add the current locale first */
// name = cc_common_language_get_current_language ();
// display = g_hash_table_lookup (user_langs, name);
name = g_strdup ("en");
display = gdm_get_language_from_name (name, NULL);
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, LOCALE_COL, name, DISPLAY_LOCALE_COL, display, -1);
if (g_hash_table_lookup (user_langs, name) != NULL)
g_hash_table_remove (user_langs, name);
g_free (name);
/* The rest of the languages */
g_hash_table_foreach (user_langs, (GHFunc) languages_foreach_cb, store);
/* And now the "Other..." selection */
// gtk_list_store_append (store, &iter);
// gtk_list_store_set (store, &iter, LOCALE_COL, NULL, DISPLAY_LOCALE_COL, _("Other..."), -1);
g_hash_table_destroy (user_langs);
}
static void
remove_timeout (gpointer data,
GObject *where_the_object_was)
{
guint timeout = GPOINTER_TO_UINT (data);
g_source_remove (timeout);
}
static void
remove_async (gpointer data)
{
guint async_id = GPOINTER_TO_UINT (data);
g_source_remove (async_id);
}
static void
selection_changed (GtkTreeSelection *selection,
GtkWidget *chooser)
{
gtk_dialog_set_response_sensitive (GTK_DIALOG (chooser),
GTK_RESPONSE_OK,
gtk_tree_selection_get_selected (selection, NULL, NULL));
}
static gboolean
finish_language_chooser (gpointer user_data)
{
GtkWidget *chooser = (GtkWidget *) user_data;
GtkWidget *list;
GtkTreeModel *model;
GtkWindow *parent;
GHashTable *user_langs;
guint timeout;
guint async_id;
GtkTreeSelection *selection;
gboolean regions;
/* Did we get called after the widget was destroyed? */
if (chooser == NULL)
return FALSE;
regions = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (chooser), "regions"));
list = g_object_get_data (G_OBJECT (chooser), "list");
model = gtk_tree_view_get_model (GTK_TREE_VIEW (list));
model = gtk_tree_model_filter_get_model (GTK_TREE_MODEL_FILTER (model));
user_langs = g_object_get_data (G_OBJECT (chooser), "user-langs");
async_id = cc_common_language_add_available_languages (GTK_LIST_STORE (model), regions, user_langs);
g_object_set_data_full (G_OBJECT (chooser), "language-async", GUINT_TO_POINTER (async_id), remove_async);
parent = gtk_window_get_transient_for (GTK_WINDOW (chooser));
gdk_window_set_cursor (gtk_widget_get_window (GTK_WIDGET (parent)), NULL);
g_object_set_data (G_OBJECT (chooser), "user-langs", NULL);
timeout = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (chooser), "timeout"));
g_object_weak_unref (G_OBJECT (chooser), (GWeakNotify) remove_timeout, GUINT_TO_POINTER (timeout));
/* And now listen for changes */
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (list));
g_signal_connect (G_OBJECT (selection), "changed",
G_CALLBACK (selection_changed), chooser);
return FALSE;
}
static void
filter_clear (GtkEntry *entry, GtkEntryIconPosition icon_pos, GdkEvent *event, gpointer user_data)
{
gtk_entry_set_text (entry, "");
}
static void
filter_changed (GtkWidget *entry, GParamSpec *pspec, GtkWidget *list)
{
const gchar *pattern;
GtkTreeModel *filter_model;
GtkTreeModel *model;
pattern = gtk_entry_get_text (GTK_ENTRY (entry));
filter_model = gtk_tree_view_get_model (GTK_TREE_VIEW (list));
model = gtk_tree_model_filter_get_model (GTK_TREE_MODEL_FILTER (filter_model));
if (g_strcmp0 (pattern, "") == 0) {
g_object_set (G_OBJECT (entry),
"secondary-icon-name", "edit-find-symbolic",
"secondary-icon-activatable", FALSE,
"secondary-icon-sensitive", FALSE,
NULL);
g_object_set_data_full (G_OBJECT (model), "filter-string",
g_strdup (""), g_free);
} else {
g_object_set (G_OBJECT (entry),
"secondary-icon-name", "edit-clear-symbolic",
"secondary-icon-activatable", TRUE,
"secondary-icon-sensitive", TRUE,
NULL);
g_object_set_data_full (G_OBJECT (model), "filter-string",
g_utf8_casefold (pattern, -1), g_free);
}
gtk_tree_model_filter_refilter (GTK_TREE_MODEL_FILTER (filter_model));
}
static gboolean
filter_languages (GtkTreeModel *model,
GtkTreeIter *iter,
gpointer data)
{
const gchar *filter_string;
gchar *locale, *l;
gboolean visible;
filter_string = g_object_get_data (G_OBJECT (model), "filter-string");
if (filter_string == NULL) {
return TRUE;
}
gdk_threads_enter ();
gtk_tree_model_get (model, iter, DISPLAY_LOCALE_COL, &locale, -1);
gdk_threads_leave ();
l = g_utf8_casefold (locale, -1);
visible = strstr (l, filter_string) != NULL;
g_free (locale);
g_free (l);
return visible;
}
GtkWidget *
cc_language_chooser_new (GtkWidget *parent, gboolean regions)
{
GtkBuilder *builder;
const char *filename;
GError *error = NULL;
GtkWidget *chooser;
GtkWidget *list;
GtkWidget *button;
GtkWidget *entry;
GtkWidget *widget;
GHashTable *user_langs;
GdkCursor *cursor;
guint timeout;
GtkTreeModel *model;
GtkTreeModel *filter_model;
builder = gtk_builder_new ();
gtk_builder_set_translation_domain (builder, GETTEXT_PACKAGE);
filename = UIDIR "/language-chooser.ui";
if (!g_file_test (filename, G_FILE_TEST_EXISTS))
filename = "data/language-chooser.ui";
if (!gtk_builder_add_from_file (builder, filename, &error)) {
g_warning ("failed to load language chooser: %s", error->message);
g_error_free (error);
return NULL;
}
chooser = (GtkWidget *) gtk_builder_get_object (builder, "dialog");
if (regions) {
widget = (GtkWidget *) gtk_builder_get_object (builder, "title");
gtk_label_set_text (GTK_LABEL (widget), _("Select a region"));
/* communicate the preference to finish_language_chooser() */
g_object_set_data (G_OBJECT (chooser), "regions", GINT_TO_POINTER (TRUE));
}
list = (GtkWidget *) gtk_builder_get_object (builder, "language-list");
g_object_set_data (G_OBJECT (chooser), "list", list);
g_signal_connect (list, "row-activated",
G_CALLBACK (row_activated), chooser);
button = (GtkWidget *) gtk_builder_get_object (builder, "ok-button");
gtk_widget_grab_default (button);
entry = (GtkWidget *) gtk_builder_get_object (builder, "filter-entry");
g_object_set_data (G_OBJECT (chooser), "filter-entry", entry);
g_signal_connect (entry, "notify::text",
G_CALLBACK (filter_changed), list);
g_signal_connect (entry, "icon-release",
G_CALLBACK (filter_clear), NULL);
gtk_widget_grab_focus (entry);
user_langs = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
cc_common_language_setup_list (list, user_langs);
model = gtk_tree_view_get_model (GTK_TREE_VIEW (list));
filter_model = gtk_tree_model_filter_new (model, NULL);
gtk_tree_model_filter_set_visible_func (GTK_TREE_MODEL_FILTER (filter_model), filter_languages,
NULL, NULL);
gtk_tree_view_set_model (GTK_TREE_VIEW (list), filter_model);
/* Setup so that the list is added after the dialogue is shown */
cursor = gdk_cursor_new (GDK_WATCH);
gdk_window_set_cursor (gtk_widget_get_window (parent), cursor);
g_object_unref (cursor);
gtk_window_set_transient_for (GTK_WINDOW (chooser), GTK_WINDOW (parent));
g_object_set_data_full (G_OBJECT (chooser), "user-langs",
user_langs, (GDestroyNotify) g_hash_table_destroy);
timeout = g_idle_add ((GSourceFunc) finish_language_chooser, chooser);
g_object_set_data (G_OBJECT (chooser), "timeout", GUINT_TO_POINTER (timeout));
g_object_weak_ref (G_OBJECT (chooser), (GWeakNotify) remove_timeout, GUINT_TO_POINTER (timeout));
g_object_unref (builder);
return chooser;
}
|
332 | ./cinnamon-control-center/panels/universal-access/cc-ua-panel.c | /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
*
* Copyright (C) 2010 Intel, Inc
* Copyright (C) 2008 William Jon McCann <[email protected]>
*
* 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.
*
* Authors: Thomas Wood <[email protected]>
* Rodrigo Moya <[email protected]>
*
*/
#include <config.h>
#include <math.h>
#include <glib/gi18n-lib.h>
#include <gdesktop-enums.h>
#include "cc-ua-panel.h"
#include "zoom-options.h"
#define WID(b, w) (GtkWidget *) gtk_builder_get_object (b, w)
#define DPI_FACTOR_LARGE 1.25
#define DPI_FACTOR_NORMAL 1.0
#define HIGH_CONTRAST_THEME "HighContrast"
#define KEY_TEXT_SCALING_FACTOR "text-scaling-factor"
#define KEY_GTK_THEME "gtk-theme"
#define KEY_ICON_THEME "icon-theme"
#define KEY_WM_THEME "theme"
CC_PANEL_REGISTER (CcUaPanel, cc_ua_panel)
#define UA_PANEL_PRIVATE(o) \
(G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_UA_PANEL, CcUaPanelPrivate))
struct _CcUaPanelPrivate
{
GtkBuilder *builder;
GSettings *wm_settings;
GSettings *interface_settings;
GSettings *kb_settings;
GSettings *mouse_settings;
GSettings *application_settings;
GSettings *mediakeys_settings;
ZoomOptions *zoom_options;
guint shell_watch_id;
};
static void
cc_ua_panel_get_property (GObject *object,
guint property_id,
GValue *value,
GParamSpec *pspec)
{
switch (property_id)
{
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}
}
static void
cc_ua_panel_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec)
{
switch (property_id)
{
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}
}
static void
cc_ua_panel_dispose (GObject *object)
{
CcUaPanelPrivate *priv = CC_UA_PANEL (object)->priv;
if (priv->shell_watch_id)
{
g_bus_unwatch_name (priv->shell_watch_id);
priv->shell_watch_id = 0;
}
if (priv->builder)
{
g_object_unref (priv->builder);
priv->builder = NULL;
}
if (priv->wm_settings)
{
g_object_unref (priv->wm_settings);
priv->wm_settings = NULL;
}
if (priv->interface_settings)
{
g_object_unref (priv->interface_settings);
priv->interface_settings = NULL;
}
if (priv->kb_settings)
{
g_object_unref (priv->kb_settings);
priv->kb_settings = NULL;
}
if (priv->mouse_settings)
{
g_object_unref (priv->mouse_settings);
priv->mouse_settings = NULL;
}
if (priv->application_settings)
{
g_object_unref (priv->application_settings);
priv->application_settings = NULL;
}
if (priv->mediakeys_settings)
{
g_object_unref (priv->mediakeys_settings);
priv->mediakeys_settings = NULL;
}
if (priv->zoom_options)
{
g_object_unref (priv->zoom_options);
priv->zoom_options = NULL;
}
G_OBJECT_CLASS (cc_ua_panel_parent_class)->dispose (object);
}
static void
cc_ua_panel_finalize (GObject *object)
{
G_OBJECT_CLASS (cc_ua_panel_parent_class)->finalize (object);
}
static const char *
cc_ua_panel_get_help_uri (CcPanel *panel)
{
if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity"))
return "help:ubuntu-help/a11y";
else
return "help:gnome-help/a11y";
}
static void
cc_ua_panel_class_init (CcUaPanelClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
CcPanelClass *panel_class = CC_PANEL_CLASS (klass);
g_type_class_add_private (klass, sizeof (CcUaPanelPrivate));
panel_class->get_help_uri = cc_ua_panel_get_help_uri;
object_class->get_property = cc_ua_panel_get_property;
object_class->set_property = cc_ua_panel_set_property;
object_class->dispose = cc_ua_panel_dispose;
object_class->finalize = cc_ua_panel_finalize;
}
static gchar *sticky_keys_section[] = {
"typing_sticky_keys_disable_two_keys_checkbutton",
"typing_sticky_keys_beep_modifier_checkbutton",
NULL
};
static gchar *slow_keys_section[]= {
"typing_slowkeys_delay_box",
"typing_slow_keys_beeb_box",
NULL
};
static gchar *bounce_keys_section[] = {
"typing_bouncekeys_delay_box",
"typing_bounce_keys_beep_rejected_checkbutton",
NULL
};
static gchar *secondary_click_section[] = {
"pointing_secondary_click_scale_box",
NULL
};
static gchar *dwell_click_section[] = {
"pointing_hover_click_delay_scale_box",
"pointing_hover_click_threshold_scale_box",
NULL
};
static gchar *visual_alerts_section[] = {
"hearing_test_flash_button",
"hearing_flash_window_title_button",
"hearing_flash_screen_button",
NULL
};
/* zoom options dialog */
static void
zoom_options_launch_cb (GtkWidget *options_button, CcUaPanel *self)
{
if (self->priv->zoom_options == NULL)
self->priv->zoom_options = zoom_options_new ();
if (self->priv->zoom_options != NULL)
zoom_options_set_parent (self->priv->zoom_options,
GTK_WINDOW (gtk_widget_get_toplevel (GTK_WIDGET (self))));
}
static void
cc_ua_panel_section_switched (GObject *object,
GParamSpec *pspec,
GtkBuilder *builder)
{
GtkWidget *w;
gboolean enabled;
gchar **widgets, **s;
widgets = g_object_get_data (object, "section-widgets");
g_object_get (object, "active", &enabled, NULL);
for (s = widgets; *s; s++)
{
w = WID (builder, *s);
gtk_widget_set_sensitive (w, enabled);
}
}
static void
settings_on_off_editor_new (CcUaPanelPrivate *priv,
GSettings *settings,
const gchar *key,
GtkWidget *widget,
gchar **section)
{
/* set data to enable/disable the section this on/off switch controls */
if (section)
{
g_object_set_data (G_OBJECT (widget), "section-widgets", section);
g_signal_connect (widget, "notify::active",
G_CALLBACK (cc_ua_panel_section_switched),
priv->builder);
}
/* set up the boolean editor */
g_settings_bind (settings, key, widget, "active", G_SETTINGS_BIND_DEFAULT);
}
/* seeing section */
static void
cc_ua_panel_set_shortcut_label (CcUaPanel *self,
const char *label,
const char *key)
{
GtkWidget *widget;
char *value;
char *text;
guint accel_key, *keycode;
GdkModifierType mods;
widget = WID (self->priv->builder, label);
value = g_settings_get_string (self->priv->mediakeys_settings, key);
if (value == NULL || *value == '\0') {
gtk_label_set_text (GTK_LABEL (widget), _("No shortcut set"));
g_free (value);
return;
}
gtk_accelerator_parse_with_keycode (value, &accel_key, &keycode, &mods);
if (accel_key == 0 && keycode == NULL && mods == 0) {
gtk_label_set_text (GTK_LABEL (widget), _("No shortcut set"));
g_free (value);
g_warning ("Failed to parse keyboard shortcut: '%s'", value);
return;
}
g_free (value);
text = gtk_accelerator_get_label_with_keycode (gtk_widget_get_display (widget), accel_key, *keycode, mods);
g_free (keycode);
gtk_label_set_text (GTK_LABEL (widget), text);
g_free (text);
}
static void
shell_vanished_cb (GDBusConnection *connection,
const gchar *name,
CcUaPanel *self)
{
CcUaPanelPrivate *priv = self->priv;
gtk_widget_hide (WID (priv->builder, "zoom_label_box"));
gtk_widget_hide (WID (priv->builder, "zoom_value_box"));
}
static void
shell_appeared_cb (GDBusConnection *connection,
const gchar *name,
const gchar *name_owner,
CcUaPanel *self)
{
CcUaPanelPrivate *priv = self->priv;
gtk_widget_show (WID (priv->builder, "zoom_label_box"));
gtk_widget_show (WID (priv->builder, "zoom_value_box"));
}
static gboolean
get_large_text_mapping (GValue *value,
GVariant *variant,
gpointer user_data)
{
gdouble factor;
gboolean large;
factor = g_variant_get_double (variant);
large = factor > DPI_FACTOR_NORMAL;
g_value_set_boolean (value, large);
return TRUE;
}
static GVariant *
set_large_text_mapping (const GValue *value,
const GVariantType *expected_type,
gpointer user_data)
{
gboolean large;
GSettings *settings = user_data;
GVariant *ret = NULL;
large = g_value_get_boolean (value);
if (large)
ret = g_variant_new_double (DPI_FACTOR_LARGE);
else
g_settings_reset (settings, KEY_TEXT_SCALING_FACTOR);
return ret;
}
static gboolean
get_contrast_mapping (GValue *value,
GVariant *variant,
gpointer user_data)
{
const char *theme;
gboolean hc;
theme = g_variant_get_string (variant, NULL);
hc = (g_strcmp0 (theme, HIGH_CONTRAST_THEME) == 0);
g_value_set_boolean (value, hc);
return TRUE;
}
static GVariant *
set_contrast_mapping (const GValue *value,
const GVariantType *expected_type,
gpointer user_data)
{
gboolean hc;
CcUaPanel *self = user_data;
CcUaPanelPrivate *priv = self->priv;
GVariant *ret = NULL;
hc = g_value_get_boolean (value);
if (hc)
{
ret = g_variant_new_string (HIGH_CONTRAST_THEME);
g_settings_set_string (priv->interface_settings, KEY_ICON_THEME, HIGH_CONTRAST_THEME);
g_settings_set_string (priv->wm_settings, KEY_WM_THEME, HIGH_CONTRAST_THEME);
}
else
{
g_settings_reset (priv->interface_settings, KEY_GTK_THEME);
g_settings_reset (priv->interface_settings, KEY_ICON_THEME);
g_settings_reset (priv->wm_settings, KEY_WM_THEME);
}
return ret;
}
static void
cc_ua_panel_init_seeing (CcUaPanel *self)
{
CcUaPanelPrivate *priv = self->priv;
g_settings_bind_with_mapping (priv->interface_settings, KEY_GTK_THEME,
WID (priv->builder, "seeing_contrast_switch"),
"active", G_SETTINGS_BIND_DEFAULT,
get_contrast_mapping,
set_contrast_mapping,
self,
NULL);
g_settings_bind_with_mapping (priv->interface_settings, KEY_TEXT_SCALING_FACTOR,
WID (priv->builder, "seeing_large_text_switch"),
"active", G_SETTINGS_BIND_DEFAULT,
get_large_text_mapping,
set_large_text_mapping,
priv->interface_settings,
NULL);
g_settings_bind (priv->kb_settings, "togglekeys-enable",
WID (priv->builder, "seeing_toggle_keys_switch"), "active",
G_SETTINGS_BIND_DEFAULT);
priv->shell_watch_id = g_bus_watch_name (G_BUS_TYPE_SESSION,
"org.gnome.Shell",
G_BUS_NAME_WATCHER_FLAGS_NONE,
(GBusNameAppearedCallback) shell_appeared_cb,
(GBusNameVanishedCallback) shell_vanished_cb,
self,
NULL);
g_signal_connect (WID (priv->builder, "seeing_zoom_preferences_button"),
"clicked",
G_CALLBACK (zoom_options_launch_cb), self);
g_settings_bind (priv->application_settings, "screen-magnifier-enabled",
WID (priv->builder, "seeing_zoom_switch"), "active",
G_SETTINGS_BIND_DEFAULT);
settings_on_off_editor_new (priv, priv->application_settings,
"screen-reader-enabled",
WID (priv->builder, "seeing_reader_switch"),
NULL);
cc_ua_panel_set_shortcut_label (self, "seeing_zoom_enable_keybinding_label", "magnifier");
cc_ua_panel_set_shortcut_label (self, "seeing_zoom_in_keybinding_label", "magnifier-zoom-in");
cc_ua_panel_set_shortcut_label (self, "seeing_zoom_out_keybinding_label", "magnifier-zoom-out");
cc_ua_panel_set_shortcut_label (self, "seeing_reader_enable_keybinding_label", "screenreader");
}
/* hearing/sound section */
static void
visual_bell_type_notify_cb (GSettings *settings,
const gchar *key,
CcUaPanel *panel)
{
GtkWidget *widget;
GDesktopVisualBellType type;
type = g_settings_get_enum (panel->priv->wm_settings, "visual-bell-type");
if (type == G_DESKTOP_VISUAL_BELL_FRAME_FLASH)
widget = WID (panel->priv->builder, "hearing_flash_window_title_button");
else
widget = WID (panel->priv->builder, "hearing_flash_screen_button");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (widget), TRUE);
}
static void
visual_bell_type_toggle_cb (GtkWidget *button,
CcUaPanel *panel)
{
gboolean frame_flash;
GDesktopVisualBellType type;
frame_flash = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (button));
if (frame_flash)
type = G_DESKTOP_VISUAL_BELL_FRAME_FLASH;
else
type = G_DESKTOP_VISUAL_BELL_FULLSCREEN_FLASH;
g_settings_set_enum (panel->priv->wm_settings, "visual-bell-type", type);
}
static void
cc_ua_panel_init_hearing (CcUaPanel *self)
{
CcUaPanelPrivate *priv = self->priv;
GtkWidget *w;
/* set the initial visual bell values */
visual_bell_type_notify_cb (NULL, NULL, self);
/* and listen */
w = WID (priv->builder, "hearing_visual_alerts_switch");
settings_on_off_editor_new (priv, priv->wm_settings, "visual-bell", w, visual_alerts_section);
g_signal_connect (priv->wm_settings, "changed::visual-bell-type",
G_CALLBACK (visual_bell_type_notify_cb), self);
g_signal_connect (WID (priv->builder, "hearing_flash_window_title_button"),
"toggled", G_CALLBACK (visual_bell_type_toggle_cb), self);
/* test flash */
g_signal_connect (WID (priv->builder, "hearing_test_flash_button"),
"clicked", G_CALLBACK (gdk_beep), NULL);
}
/* typing/keyboard section */
static void
cc_ua_panel_init_keyboard (CcUaPanel *self)
{
CcUaPanelPrivate *priv = self->priv;
GtkWidget *w;
/* Typing assistant (on-screen keyboard) */
w = WID (priv->builder, "typing_assistant_switch");
g_settings_bind (priv->application_settings, "screen-keyboard-enabled",
w, "active", G_SETTINGS_BIND_DEFAULT);
/* enable shortcuts */
w = WID (priv->builder, "typing_keyboard_toggle_switch");
g_settings_bind (priv->kb_settings, "enable", w, "active", G_SETTINGS_BIND_DEFAULT);
/* sticky keys */
w = WID (priv->builder, "typing_sticky_keys_switch");
settings_on_off_editor_new (priv, priv->kb_settings, "stickykeys-enable", w, sticky_keys_section);
w = WID (priv->builder, "typing_sticky_keys_disable_two_keys_checkbutton");
g_settings_bind (priv->kb_settings, "stickykeys-two-key-off", w, "active", G_SETTINGS_BIND_NO_SENSITIVITY);
w = WID (priv->builder, "typing_sticky_keys_beep_modifier_checkbutton");
g_settings_bind (priv->kb_settings, "stickykeys-modifier-beep", w, "active", G_SETTINGS_BIND_NO_SENSITIVITY);
/* slow keys */
w = WID (priv->builder, "typing_slow_keys_switch");
settings_on_off_editor_new (priv, priv->kb_settings, "slowkeys-enable", w, slow_keys_section);
w = WID (priv->builder, "typing_slowkeys_delay_scale");
g_settings_bind (priv->kb_settings, "slowkeys-delay",
gtk_range_get_adjustment (GTK_RANGE (w)), "value",
G_SETTINGS_BIND_DEFAULT);
w = WID (priv->builder, "typing_slow_keys_beep_pressed_checkbutton");
g_settings_bind (priv->kb_settings, "slowkeys-beep-press", w, "active", G_SETTINGS_BIND_DEFAULT);
w = WID (priv->builder, "typing_slow_keys_beep_accepted_checkbutton");
g_settings_bind (priv->kb_settings, "slowkeys-beep-accept", w, "active", G_SETTINGS_BIND_DEFAULT);
w = WID (priv->builder, "typing_slow_keys_beep_rejected_checkbutton");
g_settings_bind (priv->kb_settings, "slowkeys-beep-reject", w, "active", G_SETTINGS_BIND_DEFAULT);
/* bounce keys */
w = WID (priv->builder, "typing_bounce_keys_switch");
settings_on_off_editor_new (priv, priv->kb_settings, "bouncekeys-enable", w, bounce_keys_section);
w = WID (priv->builder, "typing_bouncekeys_delay_scale");
g_settings_bind (priv->kb_settings, "bouncekeys-delay",
gtk_range_get_adjustment (GTK_RANGE (w)), "value",
G_SETTINGS_BIND_DEFAULT);
w = WID (priv->builder, "typing_bounce_keys_beep_rejected_checkbutton");
g_settings_bind (priv->kb_settings, "bouncekeys-beep-reject", w, "active", G_SETTINGS_BIND_NO_SENSITIVITY);
}
/* mouse/pointing & clicking section */
static gboolean
pointing_mouse_preferences_clicked_cb (GtkButton *button,
CcUaPanel *panel)
{
gchar *argv[3];
argv[0] = "cinnamon-settings";
argv[1] = "mouse";
argv[3] = NULL;
g_spawn_async(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, NULL);
return TRUE;
}
static void
cc_ua_panel_init_mouse (CcUaPanel *self)
{
CcUaPanelPrivate *priv = self->priv;
GtkWidget *w;
/* mouse keys */
w = WID (priv->builder, "pointing_mouse_keys_switch");
settings_on_off_editor_new (priv, priv->kb_settings, "mousekeys-enable", w, NULL);
/* simulated secondary click */
w = WID (priv->builder, "pointing_second_click_switch");
settings_on_off_editor_new (priv, priv->mouse_settings, "secondary-click-enabled", w, secondary_click_section);
w = WID (priv->builder, "pointing_secondary_click_delay_scale");
g_settings_bind (priv->mouse_settings, "secondary-click-time",
gtk_range_get_adjustment (GTK_RANGE (w)), "value",
G_SETTINGS_BIND_DEFAULT);
/* dwell click */
w = WID (priv->builder, "pointing_hover_click_switch");
settings_on_off_editor_new (priv, priv->mouse_settings, "dwell-click-enabled", w, dwell_click_section);
w = WID (priv->builder, "pointing_dwell_delay_scale");
g_settings_bind (priv->mouse_settings, "dwell-time",
gtk_range_get_adjustment (GTK_RANGE (w)), "value",
G_SETTINGS_BIND_DEFAULT);
w = WID (priv->builder, "pointing_dwell_threshold_scale");
g_settings_bind (priv->mouse_settings, "dwell-threshold",
gtk_range_get_adjustment (GTK_RANGE (w)), "value",
G_SETTINGS_BIND_DEFAULT);
/* mouse preferences button */
g_signal_connect (WID (priv->builder, "pointing_mouse_preferences_link"),
"activate-link",
G_CALLBACK (pointing_mouse_preferences_clicked_cb), self);
}
static void
cc_ua_panel_init (CcUaPanel *self)
{
CcUaPanelPrivate *priv;
GtkWidget *widget;
GError *err = NULL;
gchar *objects[] = { "universal_access_box", "contrast_model",
"text_size_model", "slowkeys_delay_adjustment",
"bouncekeys_delay_adjustment", "click_delay_adjustment",
"dwell_time_adjustment", "dwell_threshold_adjustment",
"seeing_sizegroup", "typing_sizegroup",
"pointing_sizegroup", "pointing_sizegroup2",
"pointing_scale_sizegroup", "sizegroup1",
"hearing_sizegroup",
NULL };
priv = self->priv = UA_PANEL_PRIVATE (self);
priv->builder = gtk_builder_new ();
gtk_builder_set_translation_domain (priv->builder, GETTEXT_PACKAGE);
gtk_builder_add_objects_from_file (priv->builder,
CINNAMONCC_UI_DIR "/uap.ui",
objects,
&err);
if (err)
{
g_warning ("Could not load interface file: %s", err->message);
g_error_free (err);
g_object_unref (priv->builder);
priv->builder = NULL;
return;
}
priv->interface_settings = g_settings_new ("org.gnome.desktop.interface");
priv->wm_settings = g_settings_new ("org.gnome.desktop.wm.preferences");
priv->kb_settings = g_settings_new ("org.gnome.desktop.a11y.keyboard");
priv->mouse_settings = g_settings_new ("org.gnome.desktop.a11y.mouse");
priv->application_settings = g_settings_new ("org.gnome.desktop.a11y.applications");
priv->mediakeys_settings = g_settings_new ("org.cinnamon.settings-daemon.plugins.media-keys");
cc_ua_panel_init_keyboard (self);
cc_ua_panel_init_mouse (self);
cc_ua_panel_init_hearing (self);
cc_ua_panel_init_seeing (self);
widget = (GtkWidget*) gtk_builder_get_object (priv->builder,
"universal_access_box");
gtk_container_add (GTK_CONTAINER (self), widget);
}
void
cc_ua_panel_register (GIOModule *module)
{
bindtextdomain (GETTEXT_PACKAGE, LOCALE_DIR);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
cc_ua_panel_register_type (G_TYPE_MODULE (module));
g_io_extension_point_implement (CC_SHELL_PANEL_EXTENSION_POINT,
CC_TYPE_UA_PANEL,
"universal-access", 0);
}
|
333 | ./cinnamon-control-center/panels/universal-access/zoom-options.c | /*
* Copyright 2011 Inclusive Design Research Centre, OCAD University.
*
* 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.1 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 Lesser 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
*
* Author: Joseph Scheuhammer <[email protected]>
*/
#include "zoom-options.h"
#include <gdk/gdk.h>
#include "config.h"
#include <glib/gi18n-lib.h>
#include <string.h>
#define WID(w) (GtkWidget *) gtk_builder_get_object (priv->builder, w)
#define POSITION_MODEL_VALUE_COLUMN 2
#define FONT_SCALE 1.25
struct _ZoomOptionsPrivate
{
GtkBuilder *builder;
GSettings *settings;
GSettings *application_settings;
GtkWidget *position_combobox;
GtkWidget *follow_mouse_radio;
GtkWidget *screen_part_radio;
GtkWidget *centered_radio;
GtkWidget *push_radio;
GtkWidget *proportional_radio;
GtkWidget *extend_beyond_checkbox;
GtkWidget *brightness_slider;
GtkWidget *contrast_slider;
GtkWidget *dialog;
};
G_DEFINE_TYPE (ZoomOptions, zoom_options, G_TYPE_OBJECT);
static gchar *brightness_keys[] = {
"brightness-red",
"brightness-green",
"brightness-blue",
NULL
};
static gchar *contrast_keys[] = {
"contrast-red",
"contrast-green",
"contrast-blue",
NULL
};
inline void set_active (GtkWidget* toggle, gboolean sense);
inline gboolean get_active (GtkWidget* toggle);
inline void set_sensitive (GtkWidget *widget, gboolean sense);
static void set_enable_screen_part_ui (GtkWidget *widget, ZoomOptionsPrivate *priv);
static void mouse_tracking_notify_cb (GSettings *settings, const gchar *key, ZoomOptionsPrivate *priv);
static void scale_label (GtkBin *toggle, PangoAttrList *attrs);
static void xhairs_color_opacity_changed (GtkColorButton *button, ZoomOptionsPrivate *priv);
static void xhairs_length_add_marks (GtkScale *scale);
static void effects_slider_set_value (GtkRange *slider, GSettings *settings);
static void brightness_slider_notify_cb (GSettings *settings, const gchar *key, ZoomOptionsPrivate *priv);
static void contrast_slider_notify_cb (GSettings *settings, const gchar *key, ZoomOptionsPrivate *priv);
static void effects_slider_changed (GtkRange *slider, ZoomOptionsPrivate *priv);
/* Utilties to save on line length */
inline void
set_active (GtkWidget* toggle, gboolean sense)
{
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (toggle), sense);
}
inline gboolean
get_active (GtkWidget* toggle)
{
return gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (toggle));
}
inline void
set_sensitive (GtkWidget *widget, gboolean sense)
{
gtk_widget_set_sensitive (widget, sense);
}
static void
mouse_tracking_radio_toggled_cb (GtkWidget *widget, ZoomOptionsPrivate *priv)
{
if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)) == TRUE)
{
g_settings_set_string (priv->settings, "mouse-tracking",
gtk_buildable_get_name (GTK_BUILDABLE (widget)));
}
}
static void
init_mouse_mode_radio_group (GSList *mode_group, ZoomOptionsPrivate *priv)
{
gchar *mode;
gchar *name;
mode = g_settings_get_string (priv->settings, "mouse-tracking");
for (; mode_group != NULL; mode_group = mode_group->next)
{
name = (gchar *) gtk_buildable_get_name (GTK_BUILDABLE (mode_group->data));
if (g_strcmp0 (name, mode) == 0)
set_active (GTK_WIDGET (mode_group->data), TRUE);
else
set_active (GTK_WIDGET (mode_group->data), FALSE);
g_signal_connect (G_OBJECT (mode_group->data), "toggled",
G_CALLBACK(mouse_tracking_radio_toggled_cb),
priv);
}
}
static void
init_screen_part_section (ZoomOptionsPrivate *priv, PangoAttrList *pango_attrs)
{
gboolean lens_mode;
GSList *mouse_mode_group;
priv->follow_mouse_radio = WID ("moveableLens");
priv->screen_part_radio = WID ("screenPart");
priv->centered_radio = WID ("centered");
priv->push_radio = WID ("push");
priv->proportional_radio = WID ("proportional");
priv->extend_beyond_checkbox = WID ("scrollAtEdges");
/* Scale the labels of the toggles */
scale_label (GTK_BIN(priv->follow_mouse_radio), pango_attrs);
scale_label (GTK_BIN(priv->screen_part_radio), pango_attrs);
scale_label (GTK_BIN(priv->centered_radio), pango_attrs);
scale_label (GTK_BIN(priv->push_radio), pango_attrs);
scale_label (GTK_BIN(priv->proportional_radio), pango_attrs);
scale_label (GTK_BIN(priv->extend_beyond_checkbox), pango_attrs);
lens_mode = g_settings_get_boolean (priv->settings, "lens-mode");
set_active (priv->follow_mouse_radio, lens_mode);
set_active (priv->screen_part_radio, !lens_mode);
mouse_mode_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (priv->centered_radio));
init_mouse_mode_radio_group (mouse_mode_group, priv);
set_enable_screen_part_ui (priv->screen_part_radio, priv);
g_settings_bind (priv->settings, "lens-mode",
priv->follow_mouse_radio, "active",
G_SETTINGS_BIND_DEFAULT);
g_settings_bind (priv->settings, "scroll-at-edges",
priv->extend_beyond_checkbox, "active",
G_SETTINGS_BIND_DEFAULT);
g_signal_connect (G_OBJECT (priv->screen_part_radio), "toggled",
G_CALLBACK (set_enable_screen_part_ui), priv);
g_signal_connect (G_OBJECT (priv->settings), "changed::mouse-tracking",
G_CALLBACK (mouse_tracking_notify_cb), priv);
}
static void
set_enable_screen_part_ui (GtkWidget *widget, ZoomOptionsPrivate *priv)
{
gboolean screen_part;
/* If the "screen part" radio is not checked, then the "follow mouse" radio
* is checked (== lens mode). Set mouse tracking back to the default.
*/
screen_part = get_active (priv->screen_part_radio);
if (!screen_part)
{
g_settings_set_string (priv->settings,
"mouse-tracking", "proportional");
}
set_sensitive (priv->centered_radio, screen_part);
set_sensitive (priv->push_radio, screen_part);
set_sensitive (priv->proportional_radio, screen_part);
set_sensitive (priv->extend_beyond_checkbox, screen_part);
}
static void
mouse_tracking_notify_cb (GSettings *settings,
const gchar *key,
ZoomOptionsPrivate *priv)
{
gchar *tracking;
tracking = g_settings_get_string (settings, key);
if (g_strcmp0 (tracking, "proportional") == 0)
{
set_active (priv->proportional_radio, TRUE);
}
else if (g_strcmp0 (tracking, "centered") == 0)
{
set_active (priv->centered_radio, TRUE);
}
else
{
set_active (priv->push_radio, TRUE);
}
}
static void
scale_label (GtkBin *toggle, PangoAttrList *attrs)
{
GtkWidget *label;
label = gtk_bin_get_child (toggle);
gtk_label_set_attributes (GTK_LABEL (label), attrs);
}
static void
screen_position_combo_changed_cb (GtkWidget *combobox, ZoomOptions *options)
{
ZoomOptionsPrivate *priv = options->priv;
gchar *combo_value = NULL;
GtkTreeIter iter;
gtk_combo_box_get_active_iter (GTK_COMBO_BOX (combobox), &iter);
gtk_tree_model_get (gtk_combo_box_get_model (GTK_COMBO_BOX (combobox)), &iter,
POSITION_MODEL_VALUE_COLUMN, &combo_value,
-1);
if (g_strcmp0 (combo_value, ""))
{
g_settings_set_string (priv->settings, "screen-position", combo_value);
}
g_free (combo_value);
}
static void
screen_position_notify_cb (GSettings *settings,
const gchar *key,
ZoomOptions *options)
{
ZoomOptionsPrivate *priv = options->priv;
gchar *position;
GtkTreeIter iter;
GtkTreeModel *model;
GtkComboBox *combobox;
gboolean valid;
gchar *combo_value;
position = g_settings_get_string (settings, key);
position = g_settings_get_string (priv->settings, key);
combobox = GTK_COMBO_BOX (WID ("screen_position_combo_box"));
model = gtk_combo_box_get_model (combobox);
/* Find the matching screen position value in the combobox model. If nothing
* matches, leave the combobox as is.
*/
valid = gtk_tree_model_get_iter_first (model, &iter);
while (valid)
{
gtk_tree_model_get (model, &iter,
POSITION_MODEL_VALUE_COLUMN, &combo_value,
-1);
if (!g_strcmp0 (combo_value, position))
{
g_signal_handlers_block_by_func (combobox, screen_position_combo_changed_cb, priv);
gtk_combo_box_set_active_iter (combobox, &iter);
g_signal_handlers_unblock_by_func (combobox, screen_position_combo_changed_cb, priv);
g_free (combo_value);
break;
}
g_free (combo_value);
valid = gtk_tree_model_iter_next (model, &iter);
}
}
static void
init_xhairs_color_opacity (GtkColorButton *color_button, GSettings *settings)
{
gchar *color_setting;
GdkRGBA rgba;
color_setting = g_settings_get_string (settings, "cross-hairs-color");
gdk_rgba_parse (&rgba, color_setting);
rgba.alpha = g_settings_get_double (settings, "cross-hairs-opacity");
gtk_color_chooser_set_rgba (GTK_COLOR_CHOOSER (color_button), &rgba);
}
static void
xhairs_color_notify_cb (GSettings *settings, gchar *key, GtkColorButton *button)
{
init_xhairs_color_opacity (button, settings);
}
static void
xhairs_opacity_notify_cb (GSettings *settings, gchar *key, GtkColorButton *button)
{
GdkRGBA rgba;
gdouble opacity;
opacity = g_settings_get_double (settings, key);
gtk_color_chooser_get_rgba (GTK_COLOR_CHOOSER (button), &rgba);
rgba.alpha = opacity * 65535;
gtk_color_chooser_set_rgba (GTK_COLOR_CHOOSER (button), &rgba);
}
#define TO_HEX(x) (int) ((gdouble) x * 255.0)
static void
xhairs_color_opacity_changed (GtkColorButton *button, ZoomOptionsPrivate *priv)
{
GdkRGBA rgba;
gchar *color_string;
gtk_color_chooser_get_rgba (GTK_COLOR_CHOOSER (button), &rgba);
color_string = g_strdup_printf ("#%02x%02x%02x",
TO_HEX(rgba.red),
TO_HEX(rgba.green),
TO_HEX(rgba.blue));
g_settings_set_string (priv->settings, "cross-hairs-color", color_string);
g_free (color_string);
g_settings_set_double (priv->settings, "cross-hairs-opacity", rgba.alpha);
}
static void xhairs_length_add_marks (GtkScale *scale)
{
gint length, quarter_length;
GtkAdjustment *scale_model;
/* Get maximum dimension of screen */
length = MAX(gdk_screen_width(), gdk_screen_height());
scale_model = gtk_range_get_adjustment (GTK_RANGE (scale));
if (length < gtk_adjustment_get_upper(scale_model))
{
gtk_adjustment_set_upper (scale_model, length);
}
/* The crosshair is made up of four lines in pairs (top, bottom) and
(left, right). Stipulating: "quarter of the screen" means that the
length of one hair is 25% of the screen. */
quarter_length = length / 4;
gtk_scale_add_mark (scale, 0, GTK_POS_BOTTOM, C_("Distance", "Short"));
gtk_scale_add_mark (scale, quarter_length, GTK_POS_BOTTOM, C_("Distance", "┬╝ Screen"));
gtk_scale_add_mark (scale, quarter_length * 2 , GTK_POS_BOTTOM, C_("Distance", "┬╜ Screen"));
gtk_scale_add_mark (scale, quarter_length * 3, GTK_POS_BOTTOM, C_("Distance", "┬╛ Screen"));
gtk_scale_add_mark (scale, length, GTK_POS_BOTTOM, C_("Distance", "Long"));
}
static void
init_effects_slider (GtkRange *slider,
ZoomOptionsPrivate *priv,
gchar **keys,
GCallback notify_cb)
{
gchar **key;
gchar *signal;
g_object_set_data (G_OBJECT (slider), "settings-keys", keys);
effects_slider_set_value (slider, priv->settings);
for (key = keys; *key; key++)
{
signal = g_strdup_printf ("changed::%s", *key);
g_signal_connect (G_OBJECT (priv->settings), signal, notify_cb, priv);
g_free (signal);
}
g_signal_connect (G_OBJECT (slider), "value-changed",
G_CALLBACK (effects_slider_changed),
priv);
gtk_scale_add_mark (GTK_SCALE (slider), 0, GTK_POS_BOTTOM, NULL);
}
static void
effects_slider_set_value (GtkRange *slider, GSettings *settings)
{
gchar **keys;
gdouble red, green, blue;
gdouble value;
keys = g_object_get_data (G_OBJECT (slider), "settings-keys");
red = g_settings_get_double (settings, keys[0]);
green = g_settings_get_double (settings, keys[1]);
blue = g_settings_get_double (settings, keys[2]);
if (red == green && green == blue)
value = red;
else
/* use NTSC conversion weights for reasonable average */
value = 0.299 * red + 0.587 * green + 0.114 * blue;
gtk_range_set_value (slider, value);
}
static void
brightness_slider_notify_cb (GSettings *settings,
const gchar *key,
ZoomOptionsPrivate *priv)
{
GtkRange *slider = GTK_RANGE (priv->brightness_slider);
g_signal_handlers_block_by_func (slider, effects_slider_changed, priv);
effects_slider_set_value (slider, settings);
g_signal_handlers_unblock_by_func (slider, effects_slider_changed, priv);
}
static void
contrast_slider_notify_cb (GSettings *settings,
const gchar *key,
ZoomOptionsPrivate *priv)
{
GtkRange *slider = GTK_RANGE (priv->contrast_slider);
g_signal_handlers_block_by_func (slider, effects_slider_changed, priv);
effects_slider_set_value (slider, settings);
g_signal_handlers_unblock_by_func (slider, effects_slider_changed, priv);
}
static void
effects_slider_changed (GtkRange *slider, ZoomOptionsPrivate *priv)
{
gchar **keys, **key;
gdouble value;
keys = g_object_get_data (G_OBJECT (slider), "settings-keys");
value = gtk_range_get_value (slider);
for (key = keys; *key; key++)
{
g_settings_set_double (priv->settings, *key, value);
}
}
static void
zoom_option_close_dialog_cb (GtkWidget *closer, ZoomOptionsPrivate *priv)
{
if (priv->dialog != NULL)
gtk_widget_hide (priv->dialog);
}
static void
zoom_options_dispose (GObject *object)
{
g_return_if_fail (object != NULL);
g_return_if_fail (ZOOM_IS_OPTIONS (object));
ZoomOptionsPrivate *priv = ZOOM_OPTIONS (object)->priv;
if (priv->builder)
{
g_object_unref (priv->builder);
priv->builder = NULL;
}
if (priv->settings)
{
g_object_unref (priv->settings);
priv->settings = NULL;
}
g_clear_object (&priv->application_settings);
if (priv->dialog)
{
gtk_widget_destroy (priv->dialog);
priv->dialog = NULL;
}
G_OBJECT_CLASS (zoom_options_parent_class)->dispose (object);
}
static void
zoom_options_finalize (GObject *object)
{
G_OBJECT_CLASS (zoom_options_parent_class)->finalize (object);
}
static void
zoom_options_class_init (ZoomOptionsClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->dispose = zoom_options_dispose;
object_class->finalize = zoom_options_finalize;
g_type_class_add_private (klass, sizeof (ZoomOptionsPrivate));
}
static void
zoom_options_init (ZoomOptions *self)
{
ZoomOptionsPrivate *priv;
GtkWidget *w;
PangoAttrList *pango_attrs;
PangoAttribute *attr;
GError *err = NULL;
priv = self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, ZOOM_TYPE_OPTIONS, ZoomOptionsPrivate);
priv->builder = gtk_builder_new ();
gtk_builder_set_translation_domain (priv->builder, GETTEXT_PACKAGE);
gtk_builder_add_from_file (priv->builder,
CINNAMONCC_UI_DIR "/zoom-options.ui",
&err);
if (err)
{
g_warning ("Could not load interface file: %s", err->message);
g_error_free (err);
g_object_unref (priv->builder);
priv->builder = NULL;
return;
}
priv->settings = g_settings_new ("org.gnome.desktop.a11y.magnifier");
priv->application_settings = g_settings_new ("org.gnome.desktop.a11y.applications");
pango_attrs = pango_attr_list_new ();
attr = pango_attr_scale_new (FONT_SCALE);
pango_attr_list_insert (pango_attrs, attr);
/* Zoom switch */
g_settings_bind (priv->application_settings, "screen-magnifier-enabled",
WID ("seeing_zoom_switch"), "active",
G_SETTINGS_BIND_DEFAULT);
/* Magnification factor */
w = WID ("magFactorSpinButton");
g_settings_bind (priv->settings, "mag-factor",
gtk_spin_button_get_adjustment (GTK_SPIN_BUTTON (w)),
"value", G_SETTINGS_BIND_DEFAULT);
/* Screen position combo */
w = WID ("screen_position_combo_box");
screen_position_notify_cb (priv->settings, "screen-position", self);
g_signal_connect (G_OBJECT (priv->settings), "changed::screen-position",
G_CALLBACK (screen_position_notify_cb), self);
g_signal_connect (G_OBJECT (w), "changed",
G_CALLBACK (screen_position_combo_changed_cb), self);
/* Screen part section */
init_screen_part_section (priv, pango_attrs);
/* Cross hairs: show/hide ... */
w = WID ("xhairsEnabledSwitch");
g_settings_bind (priv->settings, "show-cross-hairs", w, "active",
G_SETTINGS_BIND_DEFAULT);
/* ... Cross hairs: color and opacity */
w = WID ("xHairsPicker");
init_xhairs_color_opacity (GTK_COLOR_BUTTON (w), priv->settings);
g_signal_connect (G_OBJECT (priv->settings), "changed::cross-hairs-color",
G_CALLBACK (xhairs_color_notify_cb), w);
g_signal_connect (G_OBJECT (priv->settings), "changed::cross-hairs-opacity",
G_CALLBACK (xhairs_opacity_notify_cb), w);
g_signal_connect (G_OBJECT (w), "color-set",
G_CALLBACK (xhairs_color_opacity_changed),
priv);
/* ... Cross hairs: thickness ... */
w = WID ("xHairsThicknessSlider");
g_settings_bind (priv->settings, "cross-hairs-thickness",
gtk_range_get_adjustment (GTK_RANGE (w)), "value",
G_SETTINGS_BIND_DEFAULT);
/* ... Cross hairs: clip ... */
w = WID ("xHairsClipCheckbox");
scale_label (GTK_BIN(w), pango_attrs);
g_settings_bind (priv->settings, "cross-hairs-clip", w, "active",
G_SETTINGS_BIND_INVERT_BOOLEAN);
/* ... Cross hairs: length ... */
w = WID ("xHairsLengthSlider");
xhairs_length_add_marks (GTK_SCALE (w));
g_settings_bind (priv->settings, "cross-hairs-length",
gtk_range_get_adjustment (GTK_RANGE (w)), "value",
G_SETTINGS_BIND_DEFAULT);
/* ... Color effects ... */
w = WID ("inverseEnabledSwitch");
g_settings_bind (priv->settings, "invert-lightness", w, "active",
G_SETTINGS_BIND_DEFAULT);
w = WID ("brightnessSlider");
priv->brightness_slider = w;
init_effects_slider (GTK_RANGE(w), priv, brightness_keys,
G_CALLBACK (brightness_slider_notify_cb));
w = WID ("contrastSlider");
priv->contrast_slider = w;
init_effects_slider (GTK_RANGE(w), priv, contrast_keys,
G_CALLBACK (contrast_slider_notify_cb));
w = WID ("grayscale_slider");
g_settings_bind (priv->settings, "color-saturation",
gtk_range_get_adjustment (GTK_RANGE (w)), "value",
G_SETTINGS_BIND_DEFAULT);
gtk_scale_add_mark (GTK_SCALE(w), 1.0, GTK_POS_BOTTOM, NULL);
/* ... Window itself ... */
priv->dialog = WID ("magPrefsDialog");
w = WID ("closeButton");
g_signal_connect (G_OBJECT (w), "clicked",
G_CALLBACK (zoom_option_close_dialog_cb),
priv);
g_signal_connect (G_OBJECT (priv->dialog), "delete-event",
G_CALLBACK (gtk_widget_hide_on_delete),
NULL);
pango_attr_list_unref (pango_attrs);
}
/**
* zoom_options_set_parent:
* @self: the #ZoomOptions object
* @parent: the parent #GtkWindow
*
* Activate the dialog associated with this ZoomOptions.
*/
void
zoom_options_set_parent (ZoomOptions *self,
GtkWindow *parent)
{
g_return_if_fail (ZOOM_IS_OPTIONS (self));
gtk_window_set_transient_for (GTK_WINDOW (self->priv->dialog), parent);
gtk_window_set_modal (GTK_WINDOW (self->priv->dialog), TRUE);
gtk_widget_show (self->priv->dialog);
}
ZoomOptions *
zoom_options_new (void)
{
return g_object_new (ZOOM_TYPE_OPTIONS, NULL);
}
|
334 | ./cinnamon-control-center/panels/universal-access/universal-access-module.c | /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
*
* Copyright (C) 2010 Intel, Inc
*
* 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.
*
* Author: Thomas Wood <[email protected]>
*
*/
#include <config.h>
#include "cc-ua-panel.h"
#include <glib/gi18n-lib.h>
void
g_io_module_load (GIOModule *module)
{
/* register the panel */
cc_ua_panel_register (module);
}
void
g_io_module_unload (GIOModule *module)
{
}
|
335 | ./cinnamon-control-center/panels/universal-access/cc-marshal.c | #include <glib.h>
#include <glib-object.h>
#include "cc-marshal.h"
/* VOID:STRING,POINTER (peditor-marshal.list:25) */
void
cc_marshal_VOID__STRING_POINTER (GClosure *closure,
GValue *return_value,
guint n_param_values,
const GValue *param_values,
gpointer invocation_hint,
gpointer marshal_data)
{
typedef void (*GMarshalFunc_VOID__STRING_POINTER) (gpointer data1,
gpointer arg_1,
gpointer arg_2,
gpointer data2);
register GMarshalFunc_VOID__STRING_POINTER 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__STRING_POINTER) (marshal_data ? marshal_data : cc->callback);
callback (data1,
(char*) g_value_get_string (param_values + 1),
g_value_get_pointer (param_values + 2),
data2);
}
|
336 | ./cinnamon-control-center/panels/user-accounts/um-fingerprint-dialog.c | /* cinnamon-about-me-fingerprint.h
* Copyright (C) 2008 Bastien Nocera <[email protected]>
*
* 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, 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.
*/
#include "config.h"
#include <stdlib.h>
#include <glib/gi18n-lib.h>
#include <gio/gio.h>
#include <gtk/gtk.h>
#include "um-fingerprint-dialog.h"
#include "fingerprint-strings.h"
/* Retrieve a widget from the UI object */
#define WID(s) GTK_WIDGET (gtk_builder_get_object (dialog, s))
/* Translate fprintd strings */
#define TR(s) dgettext("fprintd", s)
/* This must match the number of images on the 2nd page in the UI file */
#define MAX_ENROLL_STAGES 5
static GDBusProxy *manager = NULL;
static GDBusConnection *connection = NULL;
static gboolean is_disable = FALSE;
enum {
STATE_NONE,
STATE_CLAIMED,
STATE_ENROLLING
};
typedef struct {
GtkWidget *label1;
GtkWidget *label2;
GtkWidget *ass;
GtkBuilder *dialog;
GDBusProxy *device;
gboolean is_swipe;
int num_enroll_stages;
int num_stages_done;
char *name;
const char *finger;
gint state;
} EnrollData;
static void create_manager (void)
{
GError *error = NULL;
connection = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error);
if (connection == NULL) {
g_warning ("Failed to connect to session bus: %s", error->message);
g_error_free (error);
return;
}
manager = g_dbus_proxy_new_sync (connection,
G_DBUS_PROXY_FLAGS_NONE,
NULL,
"net.reactivated.Fprint",
"/net/reactivated/Fprint/Manager",
"net.reactivated.Fprint.Manager",
NULL,
&error);
if (manager == NULL) {
g_warning ("Failed to create fingerprint manager proxy: %s", error->message);
g_error_free (error);
}
}
static GDBusProxy *
get_first_device (void)
{
GDBusProxy *device;
GVariant *result;
char *device_str = NULL;
GError *error = NULL;
result = g_dbus_proxy_call_sync (manager,
"GetDefaultDevice",
g_variant_new ("()"),
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
NULL);
if (result == NULL)
return NULL;
if (!g_variant_is_of_type (result, G_VARIANT_TYPE ("(o)")))
g_warning ("net.reactivated.Fprint.Manager.GetDefaultDevice returns unknown result %s", g_variant_get_type_string (result));
else
g_variant_get (result, "(o)", &device_str);
g_variant_unref (result);
if (device_str == NULL)
return NULL;
device = g_dbus_proxy_new_sync (connection,
G_DBUS_PROXY_FLAGS_NONE,
NULL,
"net.reactivated.Fprint",
device_str,
"net.reactivated.Fprint.Device",
NULL,
&error);
if (device == NULL) {
g_warning ("Failed to create fingerprint device proxy: %s", error->message);
g_error_free (error);
}
g_free (device_str);
return device;
}
static const char *
get_reason_for_error (const char *dbus_error)
{
if (g_str_equal (dbus_error, "net.reactivated.Fprint.Error.PermissionDenied"))
return N_("You are not allowed to access the device. Contact your system administrator.");
if (g_str_equal (dbus_error, "net.reactivated.Fprint.Error.AlreadyInUse"))
return N_("The device is already in use.");
if (g_str_equal (dbus_error, "net.reactivated.Fprint.Error.Internal"))
return N_("An internal error occurred.");
return NULL;
}
static GtkWidget *
get_error_dialog (const char *title,
const char *dbus_error,
GtkWindow *parent)
{
GtkWidget *error_dialog;
const char *reason;
if (dbus_error == NULL)
g_warning ("get_error_dialog called with reason == NULL");
error_dialog =
gtk_message_dialog_new (parent,
GTK_DIALOG_MODAL,
GTK_MESSAGE_ERROR,
GTK_BUTTONS_OK,
"%s", title);
reason = get_reason_for_error (dbus_error);
gtk_message_dialog_format_secondary_text
(GTK_MESSAGE_DIALOG (error_dialog), "%s", reason ? _(reason) : _(dbus_error));
gtk_window_set_title (GTK_WINDOW (error_dialog), ""); /* as per HIG */
gtk_container_set_border_width (GTK_CONTAINER (error_dialog), 5);
gtk_dialog_set_default_response (GTK_DIALOG (error_dialog),
GTK_RESPONSE_OK);
gtk_window_set_modal (GTK_WINDOW (error_dialog), TRUE);
gtk_window_set_position (GTK_WINDOW (error_dialog), GTK_WIN_POS_CENTER_ON_PARENT);
return error_dialog;
}
gboolean
set_fingerprint_label (GtkWidget *label1,
GtkWidget *label2)
{
GDBusProxy *device;
GVariant *result;
GVariantIter *fingers;
GError *error = NULL;
if (manager == NULL) {
create_manager ();
if (manager == NULL) {
return FALSE;
}
}
device = get_first_device ();
if (device == NULL)
return FALSE;
result = g_dbus_proxy_call_sync (device, "ListEnrolledFingers", g_variant_new ("(s)", ""), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
if (!result) {
if (!g_dbus_error_is_remote_error (error) ||
strcmp (g_dbus_error_get_remote_error(error), "net.reactivated.Fprint.Error.NoEnrolledPrints") != 0) {
g_object_unref (device);
return FALSE;
}
}
if (result && g_variant_is_of_type (result, G_VARIANT_TYPE ("(as)")))
g_variant_get (result, "(as)", &fingers);
else
fingers = NULL;
if (fingers == NULL || g_variant_iter_n_children (fingers) == 0) {
is_disable = FALSE;
gtk_label_set_text (GTK_LABEL (label1), _("Disabled"));
gtk_label_set_text (GTK_LABEL (label2), _("Disabled"));
} else {
is_disable = TRUE;
gtk_label_set_text (GTK_LABEL (label1), _("Enabled"));
gtk_label_set_text (GTK_LABEL (label2), _("Enabled"));
}
if (result != NULL)
g_variant_unref (result);
if (fingers != NULL)
g_variant_iter_free (fingers);
g_object_unref (device);
return TRUE;
}
static void
delete_fingerprints (void)
{
GDBusProxy *device;
GVariant *result;
if (manager == NULL) {
create_manager ();
if (manager == NULL)
return;
}
device = get_first_device ();
if (device == NULL)
return;
result = g_dbus_proxy_call_sync (device, "DeleteEnrolledFingers", g_variant_new ("(s)", ""), G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL);
if (result)
g_variant_unref (result);
g_object_unref (device);
}
static void
delete_fingerprints_question (GtkWindow *parent,
GtkWidget *label1,
GtkWidget *label2,
UmUser *user)
{
GtkWidget *question;
GtkWidget *button;
question = gtk_message_dialog_new (parent,
GTK_DIALOG_MODAL,
GTK_MESSAGE_QUESTION,
GTK_BUTTONS_NONE,
_("Delete registered fingerprints?"));
gtk_dialog_add_button (GTK_DIALOG (question), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL);
gtk_window_set_modal (GTK_WINDOW (question), TRUE);
button = gtk_button_new_with_mnemonic (_("_Delete Fingerprints"));
gtk_button_set_image (GTK_BUTTON (button), gtk_image_new_from_stock (GTK_STOCK_DELETE, GTK_ICON_SIZE_BUTTON));
gtk_widget_set_can_default (button, TRUE);
gtk_widget_show (button);
gtk_dialog_add_action_widget (GTK_DIALOG (question), button, GTK_RESPONSE_OK);
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (question),
_("Do you want to delete your registered fingerprints so fingerprint login is disabled?"));
gtk_container_set_border_width (GTK_CONTAINER (question), 5);
gtk_dialog_set_default_response (GTK_DIALOG (question), GTK_RESPONSE_OK);
gtk_window_set_position (GTK_WINDOW (question), GTK_WIN_POS_CENTER_ON_PARENT);
gtk_window_set_modal (GTK_WINDOW (question), TRUE);
if (gtk_dialog_run (GTK_DIALOG (question)) == GTK_RESPONSE_OK) {
delete_fingerprints ();
set_fingerprint_label (label1, label2);
}
gtk_widget_destroy (question);
}
static gboolean
enroll_start (EnrollData *data, GError **error)
{
GVariant *result;
result = g_dbus_proxy_call_sync (data->device, "EnrollStart", g_variant_new ("(s)", data->finger), G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
if (result == NULL)
return FALSE;
g_variant_unref (result);
return TRUE;
}
static gboolean
enroll_stop (EnrollData *data, GError **error)
{
GVariant *result;
result = g_dbus_proxy_call_sync (data->device, "EnrollStop", g_variant_new ("()"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
if (result == NULL)
return FALSE;
g_variant_unref (result);
return TRUE;
}
static gboolean
claim (EnrollData *data, GError **error)
{
GVariant *result;
result = g_dbus_proxy_call_sync (data->device, "Claim", g_variant_new ("(s)", ""), G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
if (result == NULL)
return FALSE;
g_variant_unref (result);
return TRUE;
}
static gboolean
release (EnrollData *data, GError **error)
{
GVariant *result;
result = g_dbus_proxy_call_sync (data->device, "Release", g_variant_new ("()"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
if (result == NULL)
return FALSE;
g_variant_unref (result);
return TRUE;
}
static void
enroll_data_destroy (EnrollData *data)
{
switch (data->state) {
case STATE_ENROLLING:
enroll_stop (data, NULL);
/* fall-through */
case STATE_CLAIMED:
release (data, NULL);
/* fall-through */
case STATE_NONE:
g_free (data->name);
g_object_unref (data->device);
g_object_unref (data->dialog);
gtk_widget_destroy (data->ass);
g_free (data);
}
}
static const char *
selected_finger (GtkBuilder *dialog)
{
int index;
if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (WID ("radiobutton1")))) {
gtk_widget_set_sensitive (WID ("finger_combobox"), FALSE);
return "right-index-finger";
}
if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (WID ("radiobutton2")))) {
gtk_widget_set_sensitive (WID ("finger_combobox"), FALSE);
return "left-index-finger";
}
gtk_widget_set_sensitive (WID ("finger_combobox"), TRUE);
index = gtk_combo_box_get_active (GTK_COMBO_BOX (WID ("finger_combobox")));
switch (index) {
case 0:
return "left-thumb";
case 1:
return "left-middle-finger";
case 2:
return "left-ring-finger";
case 3:
return "left-little-finger";
case 4:
return "right-thumb";
case 5:
return "right-middle-finger";
case 6:
return "right-ring-finger";
case 7:
return "right-little-finger";
default:
g_assert_not_reached ();
}
return NULL;
}
static void
finger_radio_button_toggled (GtkToggleButton *button, EnrollData *data)
{
GtkBuilder *dialog = data->dialog;
char *msg;
data->finger = selected_finger (data->dialog);
msg = g_strdup_printf (TR(finger_str_to_msg (data->finger, data->is_swipe)), data->name);
gtk_label_set_text (GTK_LABEL (WID("enroll-label")), msg);
g_free (msg);
}
static void
finger_combobox_changed (GtkComboBox *combobox, EnrollData *data)
{
GtkBuilder *dialog = data->dialog;
char *msg;
data->finger = selected_finger (data->dialog);
msg = g_strdup_printf (TR(finger_str_to_msg (data->finger, data->is_swipe)), data->name);
gtk_label_set_text (GTK_LABEL (WID("enroll-label")), msg);
g_free (msg);
}
static void
assistant_cancelled (GtkAssistant *ass, EnrollData *data)
{
GtkWidget *label1, *label2;
label1 = data->label1;
label2 = data->label2;
enroll_data_destroy (data);
set_fingerprint_label (label1, label2);
}
static void
enroll_result (EnrollData *data, const char *result, gboolean done)
{
GtkBuilder *dialog = data->dialog;
char *msg;
if (g_str_equal (result, "enroll-completed") || g_str_equal (result, "enroll-stage-passed")) {
char *name, *path;
data->num_stages_done++;
name = g_strdup_printf ("image%d", data->num_stages_done);
path = g_build_filename (UM_PIXMAP_DIR, "print_ok.png", NULL);
gtk_image_set_from_file (GTK_IMAGE (WID (name)), path);
g_free (name);
g_free (path);
}
if (g_str_equal (result, "enroll-completed")) {
gtk_label_set_text (GTK_LABEL (WID ("status-label")), _("Done!"));
gtk_label_set_text (GTK_LABEL (WID("enroll-label")), "");
gtk_assistant_set_page_complete (GTK_ASSISTANT (data->ass), WID ("page2"), TRUE);
}
if (done != FALSE) {
enroll_stop (data, NULL);
data->state = STATE_CLAIMED;
if (g_str_equal (result, "enroll-completed") == FALSE) {
/* The enrollment failed, restart it */
enroll_start (data, NULL);
data->state = STATE_ENROLLING;
result = "enroll-retry-scan";
} else {
return;
}
}
msg = g_strdup_printf (TR(enroll_result_str_to_msg (result, data->is_swipe)), data->name);
gtk_label_set_text (GTK_LABEL (WID ("status-label")), msg);
g_free (msg);
}
static void
device_signal_cb (GDBusProxy *proxy, gchar *sender_name, gchar *signal_name, GVariant *parameters, EnrollData *data)
{
if (strcmp (signal_name, "EnrollStatus") == 0) {
if (g_variant_is_of_type (parameters, G_VARIANT_TYPE ("(sb)"))) {
gchar *result;
gboolean done;
g_variant_get (parameters, "(&sb)", &result, &done);
enroll_result (data, result, done);
}
}
}
static void
assistant_prepare (GtkAssistant *ass, GtkWidget *page, EnrollData *data)
{
const char *name;
name = g_object_get_data (G_OBJECT (page), "name");
if (name == NULL)
return;
if (g_str_equal (name, "enroll")) {
GError *error = NULL;
GtkBuilder *dialog = data->dialog;
char *path;
guint i;
GVariant *result;
gint num_enroll_stages;
if (!claim (data, &error)) {
GtkWidget *d;
char *msg;
/* translators:
* The variable is the name of the device, for example:
* "Could you not access "Digital Persona U.are.U 4000/4000B" device */
msg = g_strdup_printf (_("Could not access '%s' device"), data->name);
d = get_error_dialog (msg, error->message, GTK_WINDOW (data->ass));
g_error_free (error);
gtk_dialog_run (GTK_DIALOG (d));
gtk_widget_destroy (d);
g_free (msg);
enroll_data_destroy (data);
return;
}
data->state = STATE_CLAIMED;
result = g_dbus_connection_call_sync (connection,
"net.reactivated.Fprint",
g_dbus_proxy_get_object_path (data->device),
"org.freedesktop.DBus.Properties",
"Get",
g_variant_new ("(ss)", "net.reactivated.Fprint.Device", "num-enroll-stages"),
G_VARIANT_TYPE ("(v)"),
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
&error);
num_enroll_stages = 0;
if (result) {
GVariant *v;
g_variant_get (result, "(v)", &v);
num_enroll_stages = g_variant_get_int32 (v);
g_variant_unref (result);
g_variant_unref (v);
}
if (num_enroll_stages < 1) {
GtkWidget *d;
char *msg;
/* translators:
* The variable is the name of the device, for example:
* "Could you not access "Digital Persona U.are.U 4000/4000B" device */
msg = g_strdup_printf (_("Could not access '%s' device"), data->name);
d = get_error_dialog (msg, "net.reactivated.Fprint.Error.Internal", GTK_WINDOW (data->ass));
gtk_dialog_run (GTK_DIALOG (d));
gtk_widget_destroy (d);
g_free (msg);
enroll_data_destroy (data);
return;
}
data->num_enroll_stages = num_enroll_stages;
/* Hide the extra "bulbs" if not needed */
for (i = MAX_ENROLL_STAGES; i > data->num_enroll_stages; i--) {
char *name;
name = g_strdup_printf ("image%d", i);
gtk_widget_hide (WID (name));
g_free (name);
}
/* And set the right image */
{
char *filename;
filename = g_strdup_printf ("%s.png", data->finger);
path = g_build_filename (UM_PIXMAP_DIR, filename, NULL);
g_free (filename);
}
for (i = 1; i <= data->num_enroll_stages; i++) {
char *name;
name = g_strdup_printf ("image%d", i);
gtk_image_set_from_file (GTK_IMAGE (WID (name)), path);
g_free (name);
}
g_free (path);
g_signal_connect (data->device, "g-signal", G_CALLBACK (device_signal_cb), data);
if (!enroll_start (data, &error)) {
GtkWidget *d;
char *msg;
/* translators:
* The variable is the name of the device, for example:
* "Could you not access "Digital Persona U.are.U 4000/4000B" device */
msg = g_strdup_printf (_("Could not start finger capture on '%s' device"), data->name);
d = get_error_dialog (msg, error->message, GTK_WINDOW (data->ass));
g_error_free (error);
gtk_dialog_run (GTK_DIALOG (d));
gtk_widget_destroy (d);
g_free (msg);
enroll_data_destroy (data);
return;
}
data->state = STATE_ENROLLING;;
} else {
if (data->state == STATE_ENROLLING) {
enroll_stop (data, NULL);
data->state = STATE_CLAIMED;
}
if (data->state == STATE_CLAIMED) {
release (data, NULL);
data->state = STATE_NONE;
}
}
}
static void
enroll_fingerprints (GtkWindow *parent,
GtkWidget *label1,
GtkWidget *label2,
UmUser *user)
{
GDBusProxy *device;
GtkBuilder *dialog;
EnrollData *data;
GtkWidget *ass;
const char *filename;
char *msg;
GVariant *result;
GError *error = NULL;
device = NULL;
if (manager == NULL) {
create_manager ();
if (manager != NULL)
device = get_first_device ();
} else {
device = get_first_device ();
}
if (manager == NULL || device == NULL) {
GtkWidget *d;
d = get_error_dialog (_("Could not access any fingerprint readers"),
_("Please contact your system administrator for help."),
parent);
gtk_dialog_run (GTK_DIALOG (d));
gtk_widget_destroy (d);
return;
}
data = g_new0 (EnrollData, 1);
data->device = device;
data->label1 = label1;
data->label2 = label2;
/* Get some details about the device */
result = g_dbus_connection_call_sync (connection,
"net.reactivated.Fprint",
g_dbus_proxy_get_object_path (data->device),
"org.freedesktop.DBus.Properties",
"GetAll",
g_variant_new ("(s)", "net.reactivated.Fprint.Device"),
G_VARIANT_TYPE ("(a{sv})"),
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
NULL);
if (result) {
GVariant *props;
gchar *scan_type;
g_variant_get (result, "(@a{sv})", &props);
g_variant_lookup (props, "name", "s", &data->name);
g_variant_lookup (props, "scan-type", "s", &scan_type);
if (g_strcmp0 (scan_type, "swipe") == 0)
data->is_swipe = TRUE;
g_free (scan_type);
g_variant_unref (props);
g_variant_unref (result);
}
dialog = gtk_builder_new ();
gtk_builder_set_translation_domain (dialog, GETTEXT_PACKAGE);
filename = UIDIR "/account-fingerprint.ui";
if (!g_file_test (filename, G_FILE_TEST_EXISTS))
filename = "data/account-fingerprint.ui";
if (!gtk_builder_add_from_file (dialog, filename, &error)) {
g_error ("%s", error->message);
g_error_free (error);
return;
}
data->dialog = dialog;
ass = WID ("assistant");
gtk_window_set_title (GTK_WINDOW (ass), _("Enable Fingerprint Login"));
gtk_window_set_transient_for (GTK_WINDOW (ass), parent);
gtk_window_set_modal (GTK_WINDOW (ass), TRUE);
gtk_window_set_resizable (GTK_WINDOW (ass), FALSE);
gtk_window_set_type_hint (GTK_WINDOW (ass), GDK_WINDOW_TYPE_HINT_DIALOG);
g_signal_connect (G_OBJECT (ass), "cancel",
G_CALLBACK (assistant_cancelled), data);
g_signal_connect (G_OBJECT (ass), "close",
G_CALLBACK (assistant_cancelled), data);
g_signal_connect (G_OBJECT (ass), "prepare",
G_CALLBACK (assistant_prepare), data);
/* Page 1 */
gtk_combo_box_set_active (GTK_COMBO_BOX (WID ("finger_combobox")), 0);
g_signal_connect (G_OBJECT (WID ("radiobutton1")), "toggled",
G_CALLBACK (finger_radio_button_toggled), data);
g_signal_connect (G_OBJECT (WID ("radiobutton2")), "toggled",
G_CALLBACK (finger_radio_button_toggled), data);
g_signal_connect (G_OBJECT (WID ("radiobutton3")), "toggled",
G_CALLBACK (finger_radio_button_toggled), data);
g_signal_connect (G_OBJECT (WID ("finger_combobox")), "changed",
G_CALLBACK (finger_combobox_changed), data);
data->finger = selected_finger (dialog);
g_object_set_data (G_OBJECT (WID("page1")), "name", "intro");
/* translators:
* The variable is the name of the device, for example:
* "To enable fingerprint login, you need to save one of your fingerprints, using the
* 'Digital Persona U.are.U 4000/4000B' device."
*/
msg = g_strdup_printf (_("To enable fingerprint login, you need to save one of your fingerprints, using the '%s' device."),
data->name);
gtk_label_set_text (GTK_LABEL (WID("intro-label")), msg);
g_free (msg);
gtk_assistant_set_page_complete (GTK_ASSISTANT (ass), WID("page1"), TRUE);
gtk_assistant_set_page_title (GTK_ASSISTANT (ass), WID("page1"), _("Selecting finger"));
gtk_assistant_set_page_title (GTK_ASSISTANT (ass), WID("page2"), _("Enrolling fingerprints"));
gtk_assistant_set_page_title (GTK_ASSISTANT (ass), WID("page3"), _("Summary"));
/* Page 2 */
g_object_set_data (G_OBJECT (WID("page2")), "name", "enroll");
msg = g_strdup_printf (TR(finger_str_to_msg (data->finger, data->is_swipe)), data->name);
gtk_label_set_text (GTK_LABEL (WID("enroll-label")), msg);
g_free (msg);
/* Page 3 */
g_object_set_data (G_OBJECT (WID("page3")), "name", "summary");
data->ass = ass;
gtk_widget_show_all (ass);
}
void
fingerprint_button_clicked (GtkWindow *parent,
GtkWidget *label1,
GtkWidget *label2,
UmUser *user)
{
bindtextdomain ("fprintd", LOCALE_DIR);
bind_textdomain_codeset ("fprintd", "UTF-8");
if (is_disable != FALSE) {
delete_fingerprints_question (parent, label1, label2, user);
} else {
enroll_fingerprints (parent, label1, label2, user);
}
}
|
337 | ./cinnamon-control-center/panels/user-accounts/um-photo-dialog.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright 2009-2010 Red Hat, Inc,
*
* 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.
*
* Written by: Matthias Clasen <[email protected]>
*/
#include "config.h"
#include <stdlib.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <gtk/gtk.h>
#define GNOME_DESKTOP_USE_UNSTABLE_API
#include <libgnome-desktop/gnome-desktop-thumbnail.h>
#ifdef HAVE_CHEESE
#include <cheese-avatar-chooser.h>
#include <cheese-camera-device.h>
#include <cheese-camera-device-monitor.h>
#endif
#include "um-photo-dialog.h"
#include "um-user-manager.h"
#include "um-crop-area.h"
#include "um-utils.h"
#define ROW_SPAN 6
struct _UmPhotoDialog {
GtkWidget *photo_popup;
GtkWidget *popup_button;
GtkWidget *crop_area;
#ifdef HAVE_CHEESE
CheeseCameraDeviceMonitor *monitor;
GtkWidget *take_photo_menuitem;
guint num_cameras;
#endif
GnomeDesktopThumbnailFactory *thumb_factory;
UmUser *user;
};
static void
crop_dialog_response (GtkWidget *dialog,
gint response_id,
UmPhotoDialog *um)
{
GdkPixbuf *pb, *pb2;
if (response_id != GTK_RESPONSE_ACCEPT) {
um->crop_area = NULL;
gtk_widget_destroy (dialog);
return;
}
pb = um_crop_area_get_picture (UM_CROP_AREA (um->crop_area));
pb2 = gdk_pixbuf_scale_simple (pb, 96, 96, GDK_INTERP_BILINEAR);
um_user_set_icon_data (um->user, pb2);
g_object_unref (pb2);
g_object_unref (pb);
um->crop_area = NULL;
gtk_widget_destroy (dialog);
}
static void
um_photo_dialog_crop (UmPhotoDialog *um,
GdkPixbuf *pixbuf)
{
GtkWidget *dialog;
GtkWidget *frame;
dialog = gtk_dialog_new_with_buttons ("",
GTK_WINDOW (gtk_widget_get_toplevel (um->popup_button)),
0,
GTK_STOCK_CANCEL,
GTK_RESPONSE_REJECT,
_("Select"),
GTK_RESPONSE_ACCEPT,
NULL);
gtk_window_set_modal (GTK_WINDOW (dialog), TRUE);
gtk_window_set_icon_name (GTK_WINDOW (dialog), "system-users");
g_signal_connect (G_OBJECT (dialog), "response",
G_CALLBACK (crop_dialog_response), um);
/* Content */
um->crop_area = um_crop_area_new ();
um_crop_area_set_min_size (UM_CROP_AREA (um->crop_area), 48, 48);
um_crop_area_set_constrain_aspect (UM_CROP_AREA (um->crop_area), TRUE);
um_crop_area_set_picture (UM_CROP_AREA (um->crop_area), pixbuf);
frame = gtk_frame_new (NULL);
gtk_container_add (GTK_CONTAINER (frame), um->crop_area);
gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_ETCHED_IN);
gtk_box_pack_start (GTK_BOX (gtk_dialog_get_content_area (GTK_DIALOG (dialog))),
frame,
TRUE, TRUE, 8);
gtk_window_set_default_size (GTK_WINDOW (dialog), 400, 300);
gtk_widget_show_all (dialog);
}
static void
file_chooser_response (GtkDialog *chooser,
gint response,
UmPhotoDialog *um)
{
gchar *filename;
GError *error;
GdkPixbuf *pixbuf;
if (response != GTK_RESPONSE_ACCEPT) {
gtk_widget_destroy (GTK_WIDGET (chooser));
return;
}
filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (chooser));
error = NULL;
pixbuf = gdk_pixbuf_new_from_file (filename, &error);
if (pixbuf == NULL) {
g_warning ("Failed to load %s: %s", filename, error->message);
g_error_free (error);
}
g_free (filename);
gtk_widget_destroy (GTK_WIDGET (chooser));
um_photo_dialog_crop (um, pixbuf);
g_object_unref (pixbuf);
}
static void
update_preview (GtkFileChooser *chooser,
GnomeDesktopThumbnailFactory *thumb_factory)
{
gchar *uri;
uri = gtk_file_chooser_get_preview_uri (chooser);
if (uri) {
gchar *filename = g_filename_from_uri (uri, NULL, NULL);
gboolean is_dir = g_file_test (filename, G_FILE_TEST_IS_DIR);
g_free (filename);
if (!is_dir) {
GdkPixbuf *pixbuf = NULL;
gchar *mime_type = NULL;
GFile *file;
GFileInfo *file_info;
GtkWidget *preview;
preview = gtk_file_chooser_get_preview_widget (chooser);
file = g_file_new_for_uri (uri);
file_info = g_file_query_info (file,
G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE,
G_FILE_QUERY_INFO_NONE,
NULL, NULL);
g_object_unref (file);
if (file_info != NULL) {
mime_type = g_strdup (g_file_info_get_content_type (file_info));
g_object_unref (file_info);
}
if (mime_type && g_str_has_prefix (mime_type, "image/")) {
pixbuf = gnome_desktop_thumbnail_factory_generate_thumbnail (thumb_factory,
uri,
mime_type);
}
g_free (mime_type);
gtk_dialog_set_response_sensitive (GTK_DIALOG (chooser),
GTK_RESPONSE_ACCEPT,
(pixbuf != NULL));
if (pixbuf != NULL) {
gtk_image_set_from_pixbuf (GTK_IMAGE (preview), pixbuf);
g_object_unref (pixbuf);
}
else {
gtk_image_set_from_stock (GTK_IMAGE (preview),
GTK_STOCK_DIALOG_QUESTION,
GTK_ICON_SIZE_DIALOG);
}
} else {
GtkWidget *preview = gtk_file_chooser_get_preview_widget (chooser);
gtk_image_set_from_stock (GTK_IMAGE (preview),
GTK_STOCK_DIRECTORY,
GTK_ICON_SIZE_DIALOG);
}
g_free (uri);
}
gtk_file_chooser_set_preview_widget_active (chooser, TRUE);
}
static void
um_photo_dialog_select_file (UmPhotoDialog *um)
{
GtkWidget *chooser;
const gchar *folder;
GtkWidget *preview;
chooser = gtk_file_chooser_dialog_new (_("Browse for more pictures"),
GTK_WINDOW (gtk_widget_get_toplevel (um->popup_button)),
GTK_FILE_CHOOSER_ACTION_OPEN,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
NULL);
gtk_window_set_modal (GTK_WINDOW (chooser), TRUE);
preview = gtk_image_new ();
gtk_widget_set_size_request (preview, 256, -1);
gtk_file_chooser_set_preview_widget (GTK_FILE_CHOOSER (chooser), preview);
gtk_file_chooser_set_use_preview_label (GTK_FILE_CHOOSER (chooser), FALSE);
gtk_widget_show (preview);
g_signal_connect (chooser, "update-preview",
G_CALLBACK (update_preview), um->thumb_factory);
folder = g_get_user_special_dir (G_USER_DIRECTORY_PICTURES);
if (folder)
gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (chooser),
folder);
g_signal_connect (chooser, "response",
G_CALLBACK (file_chooser_response), um);
gtk_window_present (GTK_WINDOW (chooser));
}
static void
none_icon_selected (GtkMenuItem *menuitem,
UmPhotoDialog *um)
{
um_user_set_icon_file (um->user, NULL);
}
static void
file_icon_selected (GtkMenuItem *menuitem,
UmPhotoDialog *um)
{
um_photo_dialog_select_file (um);
}
#ifdef HAVE_CHEESE
static gboolean
destroy_chooser (GtkWidget *chooser)
{
gtk_widget_destroy (chooser);
return FALSE;
}
static void
webcam_response_cb (GtkDialog *dialog,
int response,
UmPhotoDialog *um)
{
if (response == GTK_RESPONSE_ACCEPT) {
GdkPixbuf *pb, *pb2;
g_object_get (G_OBJECT (dialog), "pixbuf", &pb, NULL);
pb2 = gdk_pixbuf_scale_simple (pb, 96, 96, GDK_INTERP_BILINEAR);
um_user_set_icon_data (um->user, pb2);
g_object_unref (pb2);
g_object_unref (pb);
}
if (response != GTK_RESPONSE_DELETE_EVENT &&
response != GTK_RESPONSE_NONE)
g_idle_add ((GSourceFunc) destroy_chooser, dialog);
}
static void
webcam_icon_selected (GtkMenuItem *menuitem,
UmPhotoDialog *um)
{
GtkWidget *window;
window = cheese_avatar_chooser_new ();
gtk_window_set_transient_for (GTK_WINDOW (window),
GTK_WINDOW (gtk_widget_get_toplevel (um->popup_button)));
gtk_window_set_modal (GTK_WINDOW (window), TRUE);
g_signal_connect (G_OBJECT (window), "response",
G_CALLBACK (webcam_response_cb), um);
gtk_widget_show (window);
}
static void
update_photo_menu_status (UmPhotoDialog *um)
{
if (um->num_cameras == 0)
gtk_widget_set_sensitive (um->take_photo_menuitem, FALSE);
else
gtk_widget_set_sensitive (um->take_photo_menuitem, TRUE);
}
static void
device_added (CheeseCameraDeviceMonitor *monitor,
CheeseCameraDevice *device,
UmPhotoDialog *um)
{
um->num_cameras++;
update_photo_menu_status (um);
}
static void
device_removed (CheeseCameraDeviceMonitor *monitor,
const char *id,
UmPhotoDialog *um)
{
um->num_cameras--;
update_photo_menu_status (um);
}
#endif
static void
stock_icon_selected (GtkMenuItem *menuitem,
UmPhotoDialog *um)
{
const char *filename;
filename = g_object_get_data (G_OBJECT (menuitem), "filename");
um_user_set_icon_file (um->user, filename);
}
static GtkWidget *
menu_item_for_filename (UmPhotoDialog *um,
const char *filename)
{
GtkWidget *image, *menuitem;
GFile *file;
GIcon *icon;
file = g_file_new_for_path (filename);
icon = g_file_icon_new (file);
g_object_unref (file);
image = gtk_image_new_from_gicon (icon, GTK_ICON_SIZE_DIALOG);
g_object_unref (icon);
menuitem = gtk_menu_item_new ();
gtk_container_add (GTK_CONTAINER (menuitem), image);
gtk_widget_show_all (menuitem);
g_object_set_data_full (G_OBJECT (menuitem), "filename",
g_strdup (filename), (GDestroyNotify) g_free);
g_signal_connect (G_OBJECT (menuitem), "activate",
G_CALLBACK (stock_icon_selected), um);
return menuitem;
}
static void
setup_photo_popup (UmPhotoDialog *um)
{
GtkWidget *menu, *menuitem, *image;
guint x, y;
const gchar * const * dirs;
guint i;
GDir *dir;
const char *face;
gboolean none_item_shown;
gboolean added_faces;
menu = gtk_menu_new ();
x = 0;
y = 0;
none_item_shown = added_faces = FALSE;
dirs = g_get_system_data_dirs ();
for (i = 0; dirs[i] != NULL; i++) {
char *path;
path = g_build_filename (dirs[i], "pixmaps", "cinnamon", "faces", NULL);
dir = g_dir_open (path, 0, NULL);
if (dir == NULL) {
g_free (path);
continue;
}
while ((face = g_dir_read_name (dir)) != NULL) {
char *filename;
added_faces = TRUE;
filename = g_build_filename (path, face, NULL);
menuitem = menu_item_for_filename (um, filename);
g_free (filename);
if (menuitem == NULL)
continue;
gtk_menu_attach (GTK_MENU (menu), GTK_WIDGET (menuitem),
x, x + 1, y, y + 1);
gtk_widget_show (menuitem);
x++;
if (x >= ROW_SPAN - 1) {
y++;
x = 0;
}
}
g_dir_close (dir);
g_free (path);
if (added_faces)
break;
}
if (!added_faces)
goto skip_faces;
image = gtk_image_new_from_icon_name ("avatar-default", GTK_ICON_SIZE_DIALOG);
menuitem = gtk_menu_item_new ();
gtk_container_add (GTK_CONTAINER (menuitem), image);
gtk_widget_show_all (menuitem);
gtk_menu_attach (GTK_MENU (menu), GTK_WIDGET (menuitem),
x, x + 1, y, y + 1);
g_signal_connect (G_OBJECT (menuitem), "activate",
G_CALLBACK (none_icon_selected), um);
gtk_widget_show (menuitem);
none_item_shown = TRUE;
y++;
skip_faces:
if (!none_item_shown) {
menuitem = gtk_menu_item_new_with_label (_("Disable image"));
gtk_menu_attach (GTK_MENU (menu), GTK_WIDGET (menuitem),
0, ROW_SPAN - 1, y, y + 1);
g_signal_connect (G_OBJECT (menuitem), "activate",
G_CALLBACK (none_icon_selected), um);
gtk_widget_show (menuitem);
y++;
}
/* Separator */
menuitem = gtk_separator_menu_item_new ();
gtk_menu_attach (GTK_MENU (menu), GTK_WIDGET (menuitem),
0, ROW_SPAN - 1, y, y + 1);
gtk_widget_show (menuitem);
y++;
#ifdef HAVE_CHEESE
um->take_photo_menuitem = gtk_menu_item_new_with_label (_("Take a photo..."));
gtk_menu_attach (GTK_MENU (menu), GTK_WIDGET (um->take_photo_menuitem),
0, ROW_SPAN - 1, y, y + 1);
g_signal_connect (G_OBJECT (um->take_photo_menuitem), "activate",
G_CALLBACK (webcam_icon_selected), um);
gtk_widget_set_sensitive (um->take_photo_menuitem, FALSE);
gtk_widget_show (um->take_photo_menuitem);
um->monitor = cheese_camera_device_monitor_new ();
g_signal_connect (G_OBJECT (um->monitor), "added",
G_CALLBACK (device_added), um);
g_signal_connect (G_OBJECT (um->monitor), "removed",
G_CALLBACK (device_removed), um);
cheese_camera_device_monitor_coldplug (um->monitor);
y++;
#endif
menuitem = gtk_menu_item_new_with_label (_("Browse for more pictures..."));
gtk_menu_attach (GTK_MENU (menu), GTK_WIDGET (menuitem),
0, ROW_SPAN - 1, y, y + 1);
g_signal_connect (G_OBJECT (menuitem), "activate",
G_CALLBACK (file_icon_selected), um);
gtk_widget_show (menuitem);
um->photo_popup = menu;
}
static void
popup_icon_menu (GtkToggleButton *button, UmPhotoDialog *um)
{
if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (button)) && !gtk_widget_get_visible (um->photo_popup)) {
gtk_menu_popup (GTK_MENU (um->photo_popup),
NULL, NULL,
(GtkMenuPositionFunc) popup_menu_below_button, um->popup_button,
0, gtk_get_current_event_time ());
} else {
gtk_menu_popdown (GTK_MENU (um->photo_popup));
}
}
static gboolean
on_popup_button_button_pressed (GtkToggleButton *button,
GdkEventButton *event,
UmPhotoDialog *um)
{
if (event->button == 1) {
if (!gtk_widget_get_visible (um->photo_popup)) {
popup_icon_menu (button, um);
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button), TRUE);
} else {
gtk_menu_popdown (GTK_MENU (um->photo_popup));
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button), FALSE);
}
return TRUE;
}
return FALSE;
}
static void
on_photo_popup_unmap (GtkWidget *popup_menu,
UmPhotoDialog *um)
{
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (um->popup_button), FALSE);
}
static void
popup_button_draw (GtkWidget *widget,
cairo_t *cr,
UmPhotoDialog *um)
{
if (gtk_widget_get_state (gtk_bin_get_child (GTK_BIN (widget))) != GTK_STATE_PRELIGHT &&
!gtk_widget_is_focus (widget)) {
return;
}
down_arrow (gtk_widget_get_style_context (widget),
cr,
gtk_widget_get_allocated_width (widget) - 12,
gtk_widget_get_allocated_height (widget) - 12,
12, 12);
}
static void
popup_button_focus_changed (GObject *button,
GParamSpec *pspec,
UmPhotoDialog *um)
{
gtk_widget_queue_draw (gtk_bin_get_child (GTK_BIN (button)));
}
UmPhotoDialog *
um_photo_dialog_new (GtkWidget *button)
{
UmPhotoDialog *um;
um = g_new0 (UmPhotoDialog, 1);
um->thumb_factory = gnome_desktop_thumbnail_factory_new (GNOME_DESKTOP_THUMBNAIL_SIZE_LARGE);
/* Set up the popup */
um->popup_button = button;
setup_photo_popup (um);
g_signal_connect (button, "toggled",
G_CALLBACK (popup_icon_menu), um);
g_signal_connect (button, "button-press-event",
G_CALLBACK (on_popup_button_button_pressed), um);
g_signal_connect (button, "notify::is-focus",
G_CALLBACK (popup_button_focus_changed), um);
g_signal_connect_after (button, "draw",
G_CALLBACK (popup_button_draw), um);
g_signal_connect (um->photo_popup, "unmap",
G_CALLBACK (on_photo_popup_unmap), um);
return um;
}
void
um_photo_dialog_free (UmPhotoDialog *um)
{
gtk_widget_destroy (um->photo_popup);
if (um->thumb_factory)
g_object_unref (um->thumb_factory);
#ifdef HAVE_CHEESE
if (um->monitor)
g_object_unref (um->monitor);
#endif
if (um->user)
g_object_unref (um->user);
g_free (um);
}
static void
clear_tip (GtkMenuItem *item,
gpointer user_data)
{
GList *children;
GtkWidget *image;
GIcon *icon, *icon2;
const char *filename;
/* Not a stock icon? */
filename = g_object_get_data (G_OBJECT (item), "filename");
if (filename == NULL)
return;
children = gtk_container_get_children (GTK_CONTAINER (item));
image = children->data;
g_assert (image != NULL);
g_list_free (children);
gtk_image_get_gicon (GTK_IMAGE (image), &icon, NULL);
if (G_IS_EMBLEMED_ICON (icon))
icon2 = g_emblemed_icon_get_icon (G_EMBLEMED_ICON (icon));
else
return;
gtk_image_set_from_gicon (GTK_IMAGE (image), icon2, GTK_ICON_SIZE_DIALOG);
g_object_unref (icon);
}
static void
set_tip (GtkWidget *item,
const char *tip,
GEmblem *emblem)
{
GList *children;
GtkWidget *image;
GIcon *icon, *icon2;
children = gtk_container_get_children (GTK_CONTAINER (item));
image = children->data;
g_assert (image != NULL);
g_list_free (children);
gtk_image_get_gicon (GTK_IMAGE (image), &icon, NULL);
if (G_IS_EMBLEMED_ICON (icon)) {
return;
}
icon2 = g_emblemed_icon_new (icon, emblem);
gtk_image_set_from_gicon (GTK_IMAGE (image), icon2, GTK_ICON_SIZE_DIALOG);
gtk_widget_set_tooltip_text (GTK_WIDGET (item), tip);
}
void
um_photo_dialog_set_user (UmPhotoDialog *um,
UmUser *user)
{
UmUserManager *manager;
GSList *list, *l;
UmUser *u;
GIcon *icon;
GEmblem *emblem;
GList *children, *c;
g_return_if_fail (um != NULL);
if (um->user) {
g_object_unref (um->user);
um->user = NULL;
}
um->user = user;
if (um->user) {
g_object_ref (um->user);
children = gtk_container_get_children (GTK_CONTAINER (um->photo_popup));
g_list_foreach (children, (GFunc) clear_tip, NULL);
manager = um_user_manager_ref_default ();
list = um_user_manager_list_users (manager);
g_object_unref (manager);
icon = g_themed_icon_new ("avatar-default");
emblem = g_emblem_new (icon);
g_object_unref (icon);
for (l = list; l; l = l->next) {
const char *filename;
u = l->data;
if (u == user)
continue;
filename = um_user_get_icon_file (u);
if (filename == NULL)
continue;
for (c = children; c; c = c->next) {
const char *f;
f = g_object_get_data (G_OBJECT (c->data), "filename");
if (f == NULL)
continue;
if (strcmp (f, filename) == 0) {
char *tip;
tip = g_strdup_printf (_("Used by %s"),
um_user_get_real_name (u));
set_tip (GTK_WIDGET (c->data), tip, emblem);
g_free (tip);
break;
}
}
}
g_slist_free (list);
g_object_unref (emblem);
}
}
|
338 | ./cinnamon-control-center/panels/user-accounts/um-realm-manager.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright 2009-2012 Red Hat, Inc.
*
* 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.
*
* Written by: Stef Walter <[email protected]>
*/
#include "config.h"
#include "um-realm-manager.h"
#include <krb5/krb5.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <glib/gstdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
struct _UmRealmManager {
UmRealmObjectManagerClient parent;
UmRealmProvider *provider;
guint diagnostics_sig;
};
typedef struct {
UmRealmProviderProxyClass parent_class;
} UmRealmManagerClass;
enum {
REALM_ADDED,
NUM_SIGNALS,
};
static gint signals[NUM_SIGNALS] = { 0, };
G_DEFINE_TYPE (UmRealmManager, um_realm_manager, UM_REALM_TYPE_OBJECT_MANAGER_CLIENT);
GQuark
um_realm_error_get_quark (void)
{
static GQuark quark = 0;
if (quark == 0)
quark = g_quark_from_static_string ("um-realm-error");
return quark;
}
static gboolean
is_realm_with_kerberos_and_membership (gpointer object)
{
GDBusInterface *interface;
if (!G_IS_DBUS_OBJECT (object))
return FALSE;
interface = g_dbus_object_get_interface (object, "org.freedesktop.realmd.Kerberos");
if (interface == NULL)
return FALSE;
g_object_unref (interface);
interface = g_dbus_object_get_interface (object, "org.freedesktop.realmd.KerberosMembership");
if (interface == NULL)
return FALSE;
g_object_unref (interface);
return TRUE;
}
static void
on_interface_added (GDBusObjectManager *manager,
GDBusObject *object,
GDBusInterface *interface)
{
g_dbus_proxy_set_default_timeout (G_DBUS_PROXY (interface), G_MAXINT);
}
static void
on_object_added (GDBusObjectManager *manager,
GDBusObject *object,
gpointer user_data)
{
GList *interfaces, *l;
interfaces = g_dbus_object_get_interfaces (object);
for (l = interfaces; l != NULL; l = g_list_next (l))
on_interface_added (manager, object, l->data);
g_list_free_full (interfaces, g_object_unref);
if (is_realm_with_kerberos_and_membership (object)) {
g_debug ("Saw realm: %s", g_dbus_object_get_object_path (object));
g_signal_emit (user_data, signals[REALM_ADDED], 0, object);
}
}
static void
um_realm_manager_init (UmRealmManager *self)
{
g_signal_connect (self, "object-added", G_CALLBACK (on_object_added), self);
g_signal_connect (self, "interface-added", G_CALLBACK (on_interface_added), self);
}
static void
um_realm_manager_dispose (GObject *obj)
{
UmRealmManager *self = UM_REALM_MANAGER (obj);
GDBusConnection *connection;
g_clear_object (&self->provider);
if (self->diagnostics_sig) {
connection = g_dbus_object_manager_client_get_connection (G_DBUS_OBJECT_MANAGER_CLIENT (self));
if (connection != NULL)
g_dbus_connection_signal_unsubscribe (connection, self->diagnostics_sig);
self->diagnostics_sig = 0;
}
G_OBJECT_CLASS (um_realm_manager_parent_class)->dispose (obj);
}
static void
um_realm_manager_class_init (UmRealmManagerClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->dispose = um_realm_manager_dispose;
signals[REALM_ADDED] = g_signal_new ("realm-added", UM_TYPE_REALM_MANAGER,
G_SIGNAL_RUN_FIRST, 0, NULL, NULL,
g_cclosure_marshal_generic,
G_TYPE_NONE, 1, UM_REALM_TYPE_OBJECT);
}
static void
on_realm_diagnostics (GDBusConnection *connection,
const gchar *sender_name,
const gchar *object_path,
const gchar *interface_name,
const gchar *signal_name,
GVariant *parameters,
gpointer user_data)
{
const gchar *message;
const gchar *unused;
if (g_variant_is_of_type (parameters, G_VARIANT_TYPE ("(ss)"))) {
/* Data is already formatted appropriately for stderr */
g_variant_get (parameters, "(&s&s)", &message, &unused);
g_printerr ("%s", message);
}
}
typedef struct {
GCancellable *cancellable;
UmRealmManager *manager;
} NewClosure;
static void
new_closure_free (gpointer data)
{
NewClosure *closure = data;
g_clear_object (&closure->cancellable);
g_clear_object (&closure->manager);
g_slice_free (NewClosure, closure);
}
static void
on_provider_new (GObject *source,
GAsyncResult *result,
gpointer user_data)
{
GSimpleAsyncResult *async = G_SIMPLE_ASYNC_RESULT (user_data);
NewClosure *closure = g_simple_async_result_get_op_res_gpointer (async);
GError *error = NULL;
UmRealmProvider *provider;
provider = um_realm_provider_proxy_new_finish (result, &error);
closure->manager->provider = provider;
if (error == NULL) {
g_dbus_proxy_set_default_timeout (G_DBUS_PROXY (closure->manager->provider), -1);
g_debug ("Created realm manager");
} else {
g_simple_async_result_take_error (async, error);
}
g_simple_async_result_complete (async);
g_object_unref (async);
}
static void
on_manager_new (GObject *source,
GAsyncResult *result,
gpointer user_data)
{
GSimpleAsyncResult *async = G_SIMPLE_ASYNC_RESULT (user_data);
NewClosure *closure = g_simple_async_result_get_op_res_gpointer (async);
GDBusConnection *connection;
GError *error = NULL;
GObject *object;
guint sig;
object = g_async_initable_new_finish (G_ASYNC_INITABLE (source), result, &error);
if (error == NULL) {
closure->manager = UM_REALM_MANAGER (object);
connection = g_dbus_object_manager_client_get_connection (G_DBUS_OBJECT_MANAGER_CLIENT (object));
g_debug ("Connected to realmd");
sig = g_dbus_connection_signal_subscribe (connection,
"org.freedesktop.realmd",
"org.freedesktop.realmd.Service",
"Diagnostics",
NULL,
NULL,
G_DBUS_SIGNAL_FLAGS_NONE,
on_realm_diagnostics,
NULL,
NULL);
closure->manager->diagnostics_sig = sig;
um_realm_provider_proxy_new (connection,
G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES,
"org.freedesktop.realmd",
"/org/freedesktop/realmd",
closure->cancellable,
on_provider_new, g_object_ref (async));
} else {
g_simple_async_result_take_error (async, error);
g_simple_async_result_complete (async);
}
g_object_unref (async);
}
void
um_realm_manager_new (GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data)
{
GSimpleAsyncResult *async;
NewClosure *closure;
g_debug ("Connecting to realmd...");
async = g_simple_async_result_new (NULL, callback, user_data,
um_realm_manager_new);
closure = g_slice_new (NewClosure);
closure->cancellable = cancellable ? g_object_ref (cancellable) : NULL;
g_simple_async_result_set_op_res_gpointer (async, closure, new_closure_free);
g_async_initable_new_async (UM_TYPE_REALM_MANAGER, G_PRIORITY_DEFAULT,
cancellable, on_manager_new, g_object_ref (async),
"flags", G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE,
"name", "org.freedesktop.realmd",
"bus-type", G_BUS_TYPE_SYSTEM,
"object-path", "/org/freedesktop/realmd",
"get-proxy-type-func", um_realm_object_manager_client_get_proxy_type,
NULL);
g_object_unref (async);
}
UmRealmManager *
um_realm_manager_new_finish (GAsyncResult *result,
GError **error)
{
GSimpleAsyncResult *async;
NewClosure *closure;
g_return_val_if_fail (g_simple_async_result_is_valid (result, NULL,
um_realm_manager_new), NULL);
async = G_SIMPLE_ASYNC_RESULT (result);
if (g_simple_async_result_propagate_error (async, error))
return NULL;
closure = g_simple_async_result_get_op_res_gpointer (async);
return g_object_ref (closure->manager);
}
typedef struct {
GDBusObjectManager *manager;
GCancellable *cancellable;
GList *realms;
} DiscoverClosure;
static void
discover_closure_free (gpointer data)
{
DiscoverClosure *discover = data;
g_object_unref (discover->manager);
g_clear_object (&discover->cancellable);
g_list_free_full (discover->realms, g_object_unref);
g_slice_free (DiscoverClosure, discover);
}
static void
on_provider_discover (GObject *source,
GAsyncResult *result,
gpointer user_data)
{
GSimpleAsyncResult *async = G_SIMPLE_ASYNC_RESULT (user_data);
DiscoverClosure *discover = g_simple_async_result_get_op_res_gpointer (async);
GDBusObject *object;
GError *error = NULL;
gchar **realms;
gint relevance;
gint i;
um_realm_provider_call_discover_finish (UM_REALM_PROVIDER (source), &relevance,
&realms, result, &error);
if (error == NULL) {
for (i = 0; realms[i]; i++) {
object = g_dbus_object_manager_get_object (discover->manager, realms[i]);
if (object == NULL) {
g_warning ("Realm is not in object manager: %s", realms[i]);
} else {
if (is_realm_with_kerberos_and_membership (object)) {
g_debug ("Discovered realm: %s", realms[i]);
discover->realms = g_list_prepend (discover->realms, object);
} else {
g_debug ("Realm does not support kerberos membership: %s", realms[i]);
g_object_unref (object);
}
}
}
g_strfreev (realms);
} else {
g_simple_async_result_take_error (async, error);
}
g_simple_async_result_complete (async);
g_object_unref (async);
}
void
um_realm_manager_discover (UmRealmManager *self,
const gchar *input,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data)
{
GSimpleAsyncResult *res;
DiscoverClosure *discover;
GVariant *options;
g_return_if_fail (UM_IS_REALM_MANAGER (self));
g_return_if_fail (input != NULL);
g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
g_debug ("Discovering realms for: %s", input);
res = g_simple_async_result_new (G_OBJECT (self), callback, user_data,
um_realm_manager_discover);
discover = g_slice_new0 (DiscoverClosure);
discover->manager = g_object_ref (self);
discover->cancellable = cancellable ? g_object_ref (cancellable) : NULL;
g_simple_async_result_set_op_res_gpointer (res, discover, discover_closure_free);
options = g_variant_new_array (G_VARIANT_TYPE ("{sv}"), NULL, 0);
um_realm_provider_call_discover (self->provider, input, options, cancellable,
on_provider_discover, g_object_ref (res));
g_object_unref (res);
}
GList *
um_realm_manager_discover_finish (UmRealmManager *self,
GAsyncResult *result,
GError **error)
{
GSimpleAsyncResult *async;
DiscoverClosure *discover;
GList *realms;
g_return_val_if_fail (UM_IS_REALM_MANAGER (self), NULL);
g_return_val_if_fail (g_simple_async_result_is_valid (result, G_OBJECT (self),
um_realm_manager_discover), NULL);
g_return_val_if_fail (error == NULL || *error == NULL, NULL);
async = G_SIMPLE_ASYNC_RESULT (result);
if (g_simple_async_result_propagate_error (async, error))
return NULL;
discover = g_simple_async_result_get_op_res_gpointer (async);
if (!discover->realms) {
g_set_error (error, UM_REALM_ERROR, UM_REALM_ERROR_GENERIC,
_("No such domain or realm found"));
return NULL;
}
realms = g_list_reverse (discover->realms);
discover->realms = NULL;
return realms;
}
GList *
um_realm_manager_get_realms (UmRealmManager *self)
{
GList *objects;
GList *realms = NULL;
GList *l;
g_return_val_if_fail (UM_IS_REALM_MANAGER (self), NULL);
objects = g_dbus_object_manager_get_objects (G_DBUS_OBJECT_MANAGER (self));
for (l = objects; l != NULL; l = g_list_next (l)) {
if (is_realm_with_kerberos_and_membership (l->data))
realms = g_list_prepend (realms, g_object_ref (l->data));
}
g_list_free_full (objects, g_object_unref);
return realms;
}
static void
string_replace (GString *string,
const gchar *find,
const gchar *replace)
{
const gchar *at;
gssize pos;
at = strstr (string->str, find);
if (at != NULL) {
pos = at - string->str;
g_string_erase (string, pos, strlen (find));
g_string_insert (string, pos, replace);
}
}
gchar *
um_realm_calculate_login (UmRealmCommon *realm,
const gchar *username)
{
GString *string;
const gchar *const *formats;
gchar *login = NULL;
formats = um_realm_common_get_login_formats (realm);
if (formats[0] != NULL) {
string = g_string_new (formats[0]);
string_replace (string, "%U", username);
string_replace (string, "%D", um_realm_common_get_name (realm));
login = g_string_free (string, FALSE);
}
return login;
}
gboolean
um_realm_is_configured (UmRealmObject *realm)
{
UmRealmCommon *common;
const gchar *configured;
gboolean is;
common = um_realm_object_get_common (realm);
configured = um_realm_common_get_configured (common);
is = configured != NULL && !g_str_equal (configured, "");
g_object_unref (common);
return is;
}
static const gchar *
find_supported_credentials (UmRealmKerberosMembership *membership,
const gchar *owner)
{
const gchar *cred_owner;
const gchar *cred_type;
GVariant *supported;
GVariantIter iter;
supported = um_realm_kerberos_membership_get_supported_join_credentials (membership);
g_return_val_if_fail (supported != NULL, NULL);
g_variant_iter_init (&iter, supported);
while (g_variant_iter_loop (&iter, "(&s&s)", &cred_type, &cred_owner)) {
if (g_str_equal (owner, cred_owner)) {
if (g_str_equal (cred_type, "ccache") ||
g_str_equal (cred_type, "password")) {
return g_intern_string (cred_type);
}
}
}
return NULL;
}
static void
on_realm_join_complete (GObject *source,
GAsyncResult *result,
gpointer user_data)
{
GSimpleAsyncResult *async = G_SIMPLE_ASYNC_RESULT (user_data);
g_debug ("Completed Join() method call");
g_simple_async_result_set_op_res_gpointer (async, g_object_ref (result), g_object_unref);
g_simple_async_result_complete_in_idle (async);
g_object_unref (async);
}
static gboolean
realm_join_as_owner (UmRealmObject *realm,
const gchar *owner,
const gchar *login,
const gchar *password,
GBytes *credentials,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data)
{
UmRealmKerberosMembership *membership;
GSimpleAsyncResult *async;
GVariant *contents;
GVariant *options;
GVariant *creds;
const gchar *type;
membership = um_realm_object_get_kerberos_membership (realm);
g_return_val_if_fail (membership != NULL, FALSE);
type = find_supported_credentials (membership, owner);
if (type == NULL) {
g_debug ("Couldn't find supported credential type for owner: %s", owner);
g_object_unref (membership);
return FALSE;
}
async = g_simple_async_result_new (G_OBJECT (realm), callback, user_data,
realm_join_as_owner);
if (g_str_equal (type, "ccache")) {
g_debug ("Using a kerberos credential cache to join the realm");
contents = g_variant_new_from_data (G_VARIANT_TYPE ("ay"),
g_bytes_get_data (credentials, NULL),
g_bytes_get_size (credentials),
TRUE, (GDestroyNotify)g_bytes_unref, credentials);
} else if (g_str_equal (type, "password")) {
g_debug ("Using a user/password to join the realm");
contents = g_variant_new ("(ss)", login, password);
} else {
g_assert_not_reached ();
}
creds = g_variant_new ("(ssv)", type, owner, contents);
options = g_variant_new_array (G_VARIANT_TYPE ("{sv}"), NULL, 0);
g_debug ("Calling the Join() method with %s credentials", owner);
um_realm_kerberos_membership_call_join (membership, creds, options,
cancellable, on_realm_join_complete,
g_object_ref (async));
g_object_unref (async);
g_object_unref (membership);
return TRUE;
}
gboolean
um_realm_join_as_user (UmRealmObject *realm,
const gchar *login,
const gchar *password,
GBytes *credentials,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data)
{
g_return_val_if_fail (UM_REALM_IS_OBJECT (realm), FALSE);
g_return_val_if_fail (credentials != NULL, FALSE);
g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
g_return_val_if_fail (login != NULL, FALSE);
g_return_val_if_fail (password != NULL, FALSE);
g_return_val_if_fail (credentials != NULL, FALSE);
return realm_join_as_owner (realm, "user", login, password,
credentials, cancellable, callback, user_data);
}
gboolean
um_realm_join_as_admin (UmRealmObject *realm,
const gchar *login,
const gchar *password,
GBytes *credentials,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data)
{
g_return_val_if_fail (UM_REALM_IS_OBJECT (realm), FALSE);
g_return_val_if_fail (credentials != NULL, FALSE);
g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
g_return_val_if_fail (login != NULL, FALSE);
g_return_val_if_fail (password != NULL, FALSE);
g_return_val_if_fail (credentials != NULL, FALSE);
return realm_join_as_owner (realm, "administrator", login, password, credentials,
cancellable, callback, user_data);
}
gboolean
um_realm_join_finish (UmRealmObject *realm,
GAsyncResult *result,
GError **error)
{
UmRealmKerberosMembership *membership;
GError *call_error = NULL;
gchar *dbus_error;
GAsyncResult *async;
g_return_val_if_fail (UM_REALM_IS_OBJECT (realm), FALSE);
g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
membership = um_realm_object_get_kerberos_membership (realm);
g_return_val_if_fail (membership != NULL, FALSE);
async = g_simple_async_result_get_op_res_gpointer (G_SIMPLE_ASYNC_RESULT (result));
um_realm_kerberos_membership_call_join_finish (membership, async, &call_error);
g_object_unref (membership);
if (call_error == NULL)
return TRUE;
dbus_error = g_dbus_error_get_remote_error (call_error);
if (dbus_error == NULL) {
g_debug ("Join() failed because of %s", call_error->message);
g_propagate_error (error, call_error);
return FALSE;
}
g_dbus_error_strip_remote_error (call_error);
if (g_str_equal (dbus_error, "org.freedesktop.realmd.Error.AuthenticationFailed")) {
g_debug ("Join() failed because of invalid/insufficient credentials");
g_set_error (error, UM_REALM_ERROR, UM_REALM_ERROR_BAD_LOGIN,
"%s", call_error->message);
g_error_free (call_error);
} else {
g_debug ("Join() failed because of %s", call_error->message);
g_propagate_error (error, call_error);
}
g_free (dbus_error);
return FALSE;
}
typedef struct {
gchar *domain;
gchar *realm;
gchar *user;
gchar *password;
GBytes *credentials;
} LoginClosure;
static void
login_closure_free (gpointer data)
{
LoginClosure *login = data;
g_free (login->domain);
g_free (login->realm);
g_free (login->user);
g_free (login->password);
g_bytes_unref (login->credentials);
g_slice_free (LoginClosure, login);
}
static krb5_error_code
login_perform_kinit (krb5_context k5,
const gchar *realm,
const gchar *login,
const gchar *password,
const gchar *filename)
{
krb5_get_init_creds_opt *opts;
krb5_error_code code;
krb5_principal principal;
krb5_ccache ccache;
krb5_creds creds;
gchar *name;
name = g_strdup_printf ("%s@%s", login, realm);
code = krb5_parse_name (k5, name, &principal);
if (code != 0) {
g_debug ("Couldn't parse principal name: %s: %s",
name, krb5_get_error_message (k5, code));
g_free (name);
return code;
}
g_debug ("Using principal name to kinit: %s", name);
g_free (name);
if (filename == NULL)
code = krb5_cc_default (k5, &ccache);
else
code = krb5_cc_resolve (k5, filename, &ccache);
if (code != 0) {
krb5_free_principal (k5, principal);
g_debug ("Couldn't open credential cache: %s: %s",
filename ? filename : "<default>",
krb5_get_error_message (k5, code));
return code;
}
code = krb5_get_init_creds_opt_alloc (k5, &opts);
g_return_val_if_fail (code == 0, code);
code = krb5_get_init_creds_opt_set_out_ccache (k5, opts, ccache);
g_return_val_if_fail (code == 0, code);
code = krb5_get_init_creds_password (k5, &creds, principal,
(char *)password,
NULL, 0, 0, NULL, opts);
krb5_get_init_creds_opt_free (k5, opts);
krb5_cc_close (k5, ccache);
krb5_free_principal (k5, principal);
if (code == 0) {
g_debug ("kinit succeeded");
krb5_free_cred_contents (k5, &creds);
} else {
g_debug ("kinit failed: %s", krb5_get_error_message (k5, code));
}
return code;
}
static void
kinit_thread_func (GSimpleAsyncResult *async,
GObject *object,
GCancellable *cancellable)
{
LoginClosure *login = g_simple_async_result_get_op_res_gpointer (async);
krb5_context k5 = NULL;
krb5_error_code code;
GError *error = NULL;
gchar *filename = NULL;
gchar *contents;
gsize length;
gint temp_fd;
filename = g_build_filename (g_get_user_runtime_dir (),
"um-krb5-creds.XXXXXX", NULL);
temp_fd = g_mkstemp_full (filename, O_RDWR, S_IRUSR | S_IWUSR);
if (temp_fd == -1) {
g_warning ("Couldn't create credential cache file: %s: %s",
filename, g_strerror (errno));
g_free (filename);
filename = NULL;
} else {
close (temp_fd);
}
code = krb5_init_context (&k5);
if (code == 0) {
code = login_perform_kinit (k5, login->realm, login->user,
login->password, filename);
}
switch (code) {
case 0:
if (filename != NULL) {
g_file_get_contents (filename, &contents, &length, &error);
if (error == NULL) {
login->credentials = g_bytes_new_take (contents, length);
g_debug ("Read in credential cache: %s", filename);
} else {
g_warning ("Couldn't read credential cache: %s: %s",
filename, error->message);
g_error_free (error);
}
}
break;
case KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN:
case KRB5KDC_ERR_CLIENT_REVOKED:
case KRB5KDC_ERR_KEY_EXP:
case KRB5KDC_ERR_POLICY:
case KRB5KDC_ERR_ETYPE_NOSUPP:
g_simple_async_result_set_error (async, UM_REALM_ERROR, UM_REALM_ERROR_BAD_LOGIN,
_("Cannot log in as %s at the %s domain"),
login->user, login->domain);
break;
case KRB5KDC_ERR_PREAUTH_FAILED:
g_simple_async_result_set_error (async, UM_REALM_ERROR, UM_REALM_ERROR_BAD_PASSWORD,
_("Invalid password, please try again"));
break;
default:
g_simple_async_result_set_error (async, UM_REALM_ERROR, UM_REALM_ERROR_GENERIC,
_("Couldn't connect to the %s domain: %s"),
login->domain, krb5_get_error_message (k5, code));
break;
}
if (filename) {
g_unlink (filename);
g_debug ("Deleted credential cache: %s", filename);
g_free (filename);
}
if (k5)
krb5_free_context (k5);
}
void
um_realm_login (UmRealmObject *realm,
const gchar *user,
const gchar *password,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data)
{
GSimpleAsyncResult *async;
LoginClosure *login;
UmRealmKerberos *kerberos;
g_return_if_fail (UM_REALM_IS_OBJECT (realm));
g_return_if_fail (user != NULL);
g_return_if_fail (password != NULL);
g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
kerberos = um_realm_object_get_kerberos (realm);
g_return_if_fail (kerberos != NULL);
async = g_simple_async_result_new (NULL, callback, user_data,
um_realm_login);
login = g_slice_new0 (LoginClosure);
login->domain = g_strdup (um_realm_kerberos_get_domain_name (kerberos));
login->realm = g_strdup (um_realm_kerberos_get_realm_name (kerberos));
login->user = g_strdup (user);
login->password = g_strdup (password);
g_simple_async_result_set_op_res_gpointer (async, login, login_closure_free);
g_simple_async_result_set_handle_cancellation (async, TRUE);
g_simple_async_result_run_in_thread (async, kinit_thread_func,
G_PRIORITY_DEFAULT, cancellable);
g_object_unref (async);
g_object_unref (kerberos);
}
gboolean
um_realm_login_finish (GAsyncResult *result,
GBytes **credentials,
GError **error)
{
GSimpleAsyncResult *async;
LoginClosure *login;
g_return_val_if_fail (g_simple_async_result_is_valid (result, NULL,
um_realm_login), FALSE);
g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
async = G_SIMPLE_ASYNC_RESULT (result);
if (g_simple_async_result_propagate_error (async, error))
return FALSE;
login = g_simple_async_result_get_op_res_gpointer (async);
if (credentials) {
if (login->credentials)
*credentials = g_bytes_ref (login->credentials);
else
*credentials = NULL;
}
return TRUE;
}
|
339 | ./cinnamon-control-center/panels/user-accounts/um-account-type.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright 2009-2010 Red Hat, Inc,
*
* 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.
*
* Written by: Matthias Clasen <[email protected]>
*/
#include "config.h"
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <glib-object.h>
#include "um-account-type.h"
const gchar *
um_account_type_get_name (UmAccountType account_type)
{
switch (account_type) {
case UM_ACCOUNT_TYPE_STANDARD:
return C_("Account type", "Standard");
case UM_ACCOUNT_TYPE_ADMINISTRATOR:
return C_("Account type", "Administrator");
default:
g_assert_not_reached ();
}
}
|
340 | ./cinnamon-control-center/panels/user-accounts/um-utils.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright 2009-2010 Red Hat, Inc,
*
* 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.
*
* Written by: Matthias Clasen <[email protected]>
*/
#include "config.h"
#include <math.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pwd.h>
#include <utmp.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include "um-utils.h"
typedef struct {
gchar *text;
gchar *placeholder_str;
GIcon *icon;
gunichar placeholder;
gulong query_id;
} IconShapeData;
static IconShapeData *
icon_shape_data_new (const gchar *text,
const gchar *placeholder,
GIcon *icon)
{
IconShapeData *data;
data = g_new0 (IconShapeData, 1);
data->text = g_strdup (text);
data->placeholder_str = g_strdup (placeholder);
data->placeholder = g_utf8_get_char_validated (placeholder, -1);
data->icon = g_object_ref (icon);
return data;
}
static void
icon_shape_data_free (gpointer user_data)
{
IconShapeData *data = user_data;
g_free (data->text);
g_free (data->placeholder_str);
g_object_unref (data->icon);
g_free (data);
}
static void
icon_shape_renderer (cairo_t *cr,
PangoAttrShape *attr,
gboolean do_path,
gpointer user_data)
{
IconShapeData *data = user_data;
gdouble x, y;
cairo_get_current_point (cr, &x, &y);
if (GPOINTER_TO_UINT (attr->data) == data->placeholder) {
gdouble ascent;
gdouble height;
GdkPixbuf *pixbuf;
GtkIconInfo *info;
ascent = pango_units_to_double (attr->ink_rect.y);
height = pango_units_to_double (attr->ink_rect.height);
info = gtk_icon_theme_lookup_by_gicon (gtk_icon_theme_get_default (),
data->icon,
(gint)height,
GTK_ICON_LOOKUP_FORCE_SIZE | GTK_ICON_LOOKUP_USE_BUILTIN);
pixbuf = gtk_icon_info_load_icon (info, NULL);
gtk_icon_info_free (info);
cairo_set_operator (cr, CAIRO_OPERATOR_OVER);
cairo_reset_clip (cr);
gdk_cairo_set_source_pixbuf (cr, pixbuf, x, y + ascent);
cairo_paint (cr);
g_object_unref (pixbuf);
}
}
static PangoAttrList *
create_shape_attr_list_for_layout (PangoLayout *layout,
IconShapeData *data)
{
PangoAttrList *attrs;
PangoFontMetrics *metrics;
gint ascent, descent;
PangoRectangle ink_rect, logical_rect;
const gchar *p;
const gchar *text;
gint placeholder_len;
/* Get font metrics and prepare fancy shape size */
metrics = pango_context_get_metrics (pango_layout_get_context (layout),
pango_layout_get_font_description (layout),
NULL);
ascent = pango_font_metrics_get_ascent (metrics);
descent = pango_font_metrics_get_descent (metrics);
pango_font_metrics_unref (metrics);
logical_rect.x = 0;
logical_rect.y = - ascent;
logical_rect.width = ascent + descent;
logical_rect.height = ascent + descent;
ink_rect = logical_rect;
attrs = pango_attr_list_new ();
text = pango_layout_get_text (layout);
placeholder_len = strlen (data->placeholder_str);
for (p = text; (p = strstr (p, data->placeholder_str)); p += placeholder_len) {
PangoAttribute *attr;
attr = pango_attr_shape_new_with_data (&ink_rect,
&logical_rect,
GUINT_TO_POINTER (g_utf8_get_char (p)),
NULL, NULL);
attr->start_index = p - text;
attr->end_index = attr->start_index + placeholder_len;
pango_attr_list_insert (attrs, attr);
}
return attrs;
}
static gboolean
query_unlock_tooltip (GtkWidget *widget,
gint x,
gint y,
gboolean keyboard_tooltip,
GtkTooltip *tooltip,
gpointer user_data)
{
GtkWidget *label;
PangoLayout *layout;
PangoAttrList *attrs;
IconShapeData *data;
data = g_object_get_data (G_OBJECT (widget), "icon-shape-data");
label = g_object_get_data (G_OBJECT (widget), "tooltip-label");
if (label == NULL) {
label = gtk_label_new (data->text);
g_object_ref_sink (label);
g_object_set_data_full (G_OBJECT (widget),
"tooltip-label", label, g_object_unref);
}
layout = gtk_label_get_layout (GTK_LABEL (label));
pango_cairo_context_set_shape_renderer (pango_layout_get_context (layout),
icon_shape_renderer,
data, NULL);
attrs = create_shape_attr_list_for_layout (layout, data);
gtk_label_set_attributes (GTK_LABEL (label), attrs);
pango_attr_list_unref (attrs);
gtk_tooltip_set_custom (tooltip, label);
return TRUE;
}
void
setup_tooltip_with_embedded_icon (GtkWidget *widget,
const gchar *text,
const gchar *placeholder,
GIcon *icon)
{
IconShapeData *data;
data = g_object_get_data (G_OBJECT (widget), "icon-shape-data");
if (data) {
gtk_widget_set_has_tooltip (widget, FALSE);
g_signal_handler_disconnect (widget, data->query_id);
g_object_set_data (G_OBJECT (widget), "icon-shape-data", NULL);
g_object_set_data (G_OBJECT (widget), "tooltip-label", NULL);
}
if (!placeholder) {
gtk_widget_set_tooltip_text (widget, text);
return;
}
data = icon_shape_data_new (text, placeholder, icon);
g_object_set_data_full (G_OBJECT (widget),
"icon-shape-data",
data,
icon_shape_data_free);
gtk_widget_set_has_tooltip (widget, TRUE);
data->query_id = g_signal_connect (widget, "query-tooltip",
G_CALLBACK (query_unlock_tooltip), NULL);
}
gboolean
show_tooltip_now (GtkWidget *widget,
GdkEvent *event)
{
GtkSettings *settings;
gint timeout;
settings = gtk_widget_get_settings (widget);
g_object_get (settings, "gtk-tooltip-timeout", &timeout, NULL);
g_object_set (settings, "gtk-tooltip-timeout", 1, NULL);
gtk_tooltip_trigger_tooltip_query (gtk_widget_get_display (widget));
g_object_set (settings, "gtk-tooltip-timeout", timeout, NULL);
return FALSE;
}
static gboolean
query_tooltip (GtkWidget *widget,
gint x,
gint y,
gboolean keyboard_mode,
GtkTooltip *tooltip,
gpointer user_data)
{
gchar *tip;
if (GTK_ENTRY_ICON_SECONDARY == gtk_entry_get_icon_at_pos (GTK_ENTRY (widget), x, y)) {
tip = gtk_entry_get_icon_tooltip_text (GTK_ENTRY (widget),
GTK_ENTRY_ICON_SECONDARY);
gtk_tooltip_set_text (tooltip, tip);
g_free (tip);
return TRUE;
}
else {
return FALSE;
}
}
static void
icon_released (GtkEntry *entry,
GtkEntryIconPosition pos,
GdkEvent *event,
gpointer user_data)
{
GtkSettings *settings;
gint timeout;
settings = gtk_widget_get_settings (GTK_WIDGET (entry));
g_object_get (settings, "gtk-tooltip-timeout", &timeout, NULL);
g_object_set (settings, "gtk-tooltip-timeout", 1, NULL);
gtk_tooltip_trigger_tooltip_query (gtk_widget_get_display (GTK_WIDGET (entry)));
g_object_set (settings, "gtk-tooltip-timeout", timeout, NULL);
}
void
set_entry_validation_error (GtkEntry *entry,
const gchar *text)
{
g_object_set (entry, "caps-lock-warning", FALSE, NULL);
gtk_entry_set_icon_from_icon_name (entry,
GTK_ENTRY_ICON_SECONDARY,
"dialog-error-symbolic");
gtk_entry_set_icon_activatable (entry,
GTK_ENTRY_ICON_SECONDARY,
TRUE);
g_signal_connect (entry, "icon-release",
G_CALLBACK (icon_released), FALSE);
g_signal_connect (entry, "query-tooltip",
G_CALLBACK (query_tooltip), NULL);
g_object_set (entry, "has-tooltip", TRUE, NULL);
gtk_entry_set_icon_tooltip_text (entry,
GTK_ENTRY_ICON_SECONDARY,
text);
}
void
clear_entry_validation_error (GtkEntry *entry)
{
gboolean warning;
g_object_get (entry, "caps-lock-warning", &warning, NULL);
if (warning)
return;
g_object_set (entry, "has-tooltip", FALSE, NULL);
gtk_entry_set_icon_from_pixbuf (entry,
GTK_ENTRY_ICON_SECONDARY,
NULL);
g_object_set (entry, "caps-lock-warning", TRUE, NULL);
}
void
popup_menu_below_button (GtkMenu *menu,
gint *x,
gint *y,
gboolean *push_in,
GtkWidget *button)
{
GtkRequisition menu_req;
GtkTextDirection direction;
GtkAllocation allocation;
gtk_widget_get_preferred_size (GTK_WIDGET (menu), NULL, &menu_req);
direction = gtk_widget_get_direction (button);
gdk_window_get_origin (gtk_widget_get_window (button), x, y);
gtk_widget_get_allocation (button, &allocation);
*x += allocation.x;
*y += allocation.y + allocation.height;
if (direction == GTK_TEXT_DIR_LTR)
*x += MAX (allocation.width - menu_req.width, 0);
else if (menu_req.width > allocation.width)
*x -= menu_req.width - allocation.width;
*push_in = TRUE;
}
void
rounded_rectangle (cairo_t *cr,
gdouble aspect,
gdouble x,
gdouble y,
gdouble corner_radius,
gdouble width,
gdouble height)
{
gdouble radius;
gdouble degrees;
radius = corner_radius / aspect;
degrees = G_PI / 180.0;
cairo_new_sub_path (cr);
cairo_arc (cr,
x + width - radius,
y + radius,
radius,
-90 * degrees,
0 * degrees);
cairo_arc (cr,
x + width - radius,
y + height - radius,
radius,
0 * degrees,
90 * degrees);
cairo_arc (cr,
x + radius,
y + height - radius,
radius,
90 * degrees,
180 * degrees);
cairo_arc (cr,
x + radius,
y + radius,
radius,
180 * degrees,
270 * degrees);
cairo_close_path (cr);
}
void
down_arrow (GtkStyleContext *context,
cairo_t *cr,
gint x,
gint y,
gint width,
gint height)
{
GtkStateFlags flags;
GdkRGBA fg_color;
GdkRGBA outline_color;
gdouble vertical_overshoot;
gint diameter;
gdouble radius;
gdouble x_double, y_double;
gdouble angle;
gint line_width;
flags = gtk_style_context_get_state (context);
gtk_style_context_get_color (context, flags, &fg_color);
gtk_style_context_get_border_color (context, flags, &outline_color);
line_width = 1;
angle = G_PI / 2;
vertical_overshoot = line_width / 2.0 * (1. / tan (G_PI / 8));
if (line_width % 2 == 1)
vertical_overshoot = ceil (0.5 + vertical_overshoot) - 0.5;
else
vertical_overshoot = ceil (vertical_overshoot);
diameter = (gint) MAX (3, width - 2 * vertical_overshoot);
diameter -= (1 - (diameter + line_width) % 2);
radius = diameter / 2.;
x_double = floor ((x + width / 2) - (radius + line_width) / 2.) + (radius + line_width) / 2.;
y_double = (y + height / 2) - 0.5;
cairo_save (cr);
cairo_translate (cr, x_double, y_double);
cairo_rotate (cr, angle);
cairo_move_to (cr, - radius / 2., - radius);
cairo_line_to (cr, radius / 2., 0);
cairo_line_to (cr, - radius / 2., radius);
cairo_close_path (cr);
cairo_set_line_width (cr, line_width);
gdk_cairo_set_source_rgba (cr, &fg_color);
cairo_fill_preserve (cr);
gdk_cairo_set_source_rgba (cr, &outline_color);
cairo_stroke (cr);
cairo_restore (cr);
}
#define MAXNAMELEN (UT_NAMESIZE - 1)
static gboolean
is_username_used (const gchar *username)
{
struct passwd *pwent;
if (username == NULL || username[0] == '\0') {
return FALSE;
}
pwent = getpwnam (username);
return pwent != NULL;
}
gboolean
is_valid_name (const gchar *name)
{
gboolean valid;
valid = (strlen (name) > 0);
return valid;
}
gboolean
is_valid_username (const gchar *username, gchar **tip)
{
gboolean empty;
gboolean in_use;
gboolean too_long;
gboolean valid;
const gchar *c;
if (username == NULL || username[0] == '\0') {
empty = TRUE;
in_use = FALSE;
too_long = FALSE;
} else {
empty = FALSE;
in_use = is_username_used (username);
too_long = strlen (username) > MAXNAMELEN;
}
valid = TRUE;
if (!in_use && !empty && !too_long) {
/* First char must be a letter, and it must only composed
* of ASCII letters, digits, and a '.', '-', '_'
*/
for (c = username; *c; c++) {
if (! ((*c >= 'a' && *c <= 'z') ||
(*c >= 'A' && *c <= 'Z') ||
(*c >= '0' && *c <= '9') ||
(*c == '_') || (*c == '.') ||
(*c == '-' && c != username)))
valid = FALSE;
}
}
valid = !empty && !in_use && !too_long && valid;
if (!empty && (in_use || too_long || !valid)) {
if (in_use) {
*tip = g_strdup_printf (_("A user with the username '%s' already exists"),
username);
}
else if (too_long) {
*tip = g_strdup_printf (_("The username is too long"));
}
else if (username[0] == '-') {
*tip = g_strdup (_("The username cannot start with a '-'"));
}
else {
*tip = g_strdup (_("The username must only consist of:\n"
" \xe2\x9e\xa3 letters from the English alphabet\n"
" \xe2\x9e\xa3 digits\n"
" \xe2\x9e\xa3 any of the characters '.', '-' and '_'"));
}
}
else {
*tip = NULL;
}
return valid;
}
void
generate_username_choices (const gchar *name,
GtkListStore *store)
{
gboolean in_use;
char *lc_name, *ascii_name, *stripped_name;
char **words1;
char **words2 = NULL;
char **w1, **w2;
char *c;
char *unicode_fallback = "?";
GString *first_word, *last_word;
GString *item0, *item1, *item2, *item3, *item4;
int len;
int nwords1, nwords2, i;
GHashTable *items;
GtkTreeIter iter;
gtk_list_store_clear (store);
ascii_name = g_convert_with_fallback (name, -1, "ASCII//TRANSLIT", "UTF-8",
unicode_fallback, NULL, NULL, NULL);
lc_name = g_ascii_strdown (ascii_name, -1);
/* Remove all non ASCII alphanumeric chars from the name,
* apart from the few allowed symbols.
*
* We do remove '.', even though it is usually allowed,
* since it often comes in via an abbreviated middle name,
* and the dot looks just wrong in the proposals then.
*/
stripped_name = g_strnfill (strlen (lc_name) + 1, '\0');
i = 0;
for (c = lc_name; *c; c++) {
if (!(g_ascii_isdigit (*c) || g_ascii_islower (*c) ||
*c == ' ' || *c == '-' || *c == '_' ||
/* used to track invalid words, removed below */
*c == '?') )
continue;
stripped_name[i] = *c;
i++;
}
if (strlen (stripped_name) == 0) {
g_free (ascii_name);
g_free (lc_name);
g_free (stripped_name);
return;
}
/* we split name on spaces, and then on dashes, so that we can treat
* words linked with dashes the same way, i.e. both fully shown, or
* both abbreviated
*/
words1 = g_strsplit_set (stripped_name, " ", -1);
len = g_strv_length (words1);
/* The default item is a concatenation of all words without ? */
item0 = g_string_sized_new (strlen (stripped_name));
g_free (ascii_name);
g_free (lc_name);
g_free (stripped_name);
/* Concatenate the whole first word with the first letter of each
* word (item1), and the last word with the first letter of each
* word (item2). item3 and item4 are symmetrical respectively to
* item1 and item2.
*
* Constant 5 is the max reasonable number of words we may get when
* splitting on dashes, since we can't guess it at this point,
* and reallocating would be too bad.
*/
item1 = g_string_sized_new (strlen (words1[0]) + len - 1 + 5);
item3 = g_string_sized_new (strlen (words1[0]) + len - 1 + 5);
item2 = g_string_sized_new (strlen (words1[len - 1]) + len - 1 + 5);
item4 = g_string_sized_new (strlen (words1[len - 1]) + len - 1 + 5);
/* again, guess at the max size of names */
first_word = g_string_sized_new (20);
last_word = g_string_sized_new (20);
nwords1 = 0;
nwords2 = 0;
for (w1 = words1; *w1; w1++) {
if (strlen (*w1) == 0)
continue;
/* skip words with string '?', most likely resulting
* from failed transliteration to ASCII
*/
if (strstr (*w1, unicode_fallback) != NULL)
continue;
nwords1++; /* count real words, excluding empty string */
item0 = g_string_append (item0, *w1);
words2 = g_strsplit_set (*w1, "-", -1);
/* reset last word if a new non-empty word has been found */
if (strlen (*words2) > 0)
last_word = g_string_set_size (last_word, 0);
for (w2 = words2; *w2; w2++) {
if (strlen (*w2) == 0)
continue;
nwords2++;
/* part of the first "toplevel" real word */
if (nwords1 == 1) {
item1 = g_string_append (item1, *w2);
first_word = g_string_append (first_word, *w2);
}
else {
item1 = g_string_append_unichar (item1,
g_utf8_get_char (*w2));
item3 = g_string_append_unichar (item3,
g_utf8_get_char (*w2));
}
/* not part of the last "toplevel" word */
if (w1 != words1 + len - 1) {
item2 = g_string_append_unichar (item2,
g_utf8_get_char (*w2));
item4 = g_string_append_unichar (item4,
g_utf8_get_char (*w2));
}
/* always save current word so that we have it if last one reveals empty */
last_word = g_string_append (last_word, *w2);
}
g_strfreev (words2);
}
item2 = g_string_append (item2, last_word->str);
item3 = g_string_append (item3, first_word->str);
item4 = g_string_prepend (item4, last_word->str);
items = g_hash_table_new (g_str_hash, g_str_equal);
in_use = is_username_used (item0->str);
if (!in_use && !g_ascii_isdigit (item0->str[0])) {
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, 0, item0->str, -1);
g_hash_table_insert (items, item0->str, item0->str);
}
in_use = is_username_used (item1->str);
if (nwords2 > 0 && !in_use && !g_ascii_isdigit (item1->str[0])) {
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, 0, item1->str, -1);
g_hash_table_insert (items, item1->str, item1->str);
}
/* if there's only one word, would be the same as item1 */
if (nwords2 > 1) {
/* add other items */
in_use = is_username_used (item2->str);
if (!in_use && !g_ascii_isdigit (item2->str[0]) &&
!g_hash_table_lookup (items, item2->str)) {
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, 0, item2->str, -1);
g_hash_table_insert (items, item2->str, item2->str);
}
in_use = is_username_used (item3->str);
if (!in_use && !g_ascii_isdigit (item3->str[0]) &&
!g_hash_table_lookup (items, item3->str)) {
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, 0, item3->str, -1);
g_hash_table_insert (items, item3->str, item3->str);
}
in_use = is_username_used (item4->str);
if (!in_use && !g_ascii_isdigit (item4->str[0]) &&
!g_hash_table_lookup (items, item4->str)) {
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, 0, item4->str, -1);
g_hash_table_insert (items, item4->str, item4->str);
}
/* add the last word */
in_use = is_username_used (last_word->str);
if (!in_use && !g_ascii_isdigit (last_word->str[0]) &&
!g_hash_table_lookup (items, last_word->str)) {
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, 0, last_word->str, -1);
g_hash_table_insert (items, last_word->str, last_word->str);
}
/* ...and the first one */
in_use = is_username_used (first_word->str);
if (!in_use && !g_ascii_isdigit (first_word->str[0]) &&
!g_hash_table_lookup (items, first_word->str)) {
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, 0, first_word->str, -1);
g_hash_table_insert (items, first_word->str, first_word->str);
}
}
g_hash_table_destroy (items);
g_strfreev (words1);
g_string_free (first_word, TRUE);
g_string_free (last_word, TRUE);
g_string_free (item0, TRUE);
g_string_free (item1, TRUE);
g_string_free (item2, TRUE);
g_string_free (item3, TRUE);
g_string_free (item4, TRUE);
}
gboolean
is_using_ecryptfs (const gchar *name)
{
gboolean using_ecryptfs = FALSE;
int status;
gchar *prog;
gchar *cmd;
prog = g_find_program_in_path ("ecryptfs-verify");
if (prog != NULL) {
gchar *cmd = g_strdup_printf("'%s' -h -u '%s'", prog, name);
if (g_spawn_command_line_sync (cmd, NULL, NULL, &status, NULL)) {
if (status == 0)
using_ecryptfs = TRUE;
}
g_free (prog);
g_free (cmd);
}
return using_ecryptfs;
}
|
341 | ./cinnamon-control-center/panels/user-accounts/um-crop-area.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright 2009 Red Hat, Inc,
*
* 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.
*
* Written by: Matthias Clasen <[email protected]>
*/
#include "config.h"
#include <stdlib.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <gtk/gtk.h>
#include "um-crop-area.h"
struct _UmCropAreaPrivate {
GdkPixbuf *browse_pixbuf;
GdkPixbuf *pixbuf;
GdkPixbuf *color_shifted;
gdouble scale;
GdkRectangle image;
GdkCursorType current_cursor;
GdkRectangle crop;
gint active_region;
gint last_press_x;
gint last_press_y;
gint base_width;
gint base_height;
gdouble aspect;
};
G_DEFINE_TYPE (UmCropArea, um_crop_area, GTK_TYPE_DRAWING_AREA);
static inline guchar
shift_color_byte (guchar b,
int shift)
{
return CLAMP(b + shift, 0, 255);
}
static void
shift_colors (GdkPixbuf *pixbuf,
gint red,
gint green,
gint blue,
gint alpha)
{
gint x, y, offset, y_offset, rowstride, width, height;
guchar *pixels;
gint channels;
width = gdk_pixbuf_get_width (pixbuf);
height = gdk_pixbuf_get_height (pixbuf);
rowstride = gdk_pixbuf_get_rowstride (pixbuf);
pixels = gdk_pixbuf_get_pixels (pixbuf);
channels = gdk_pixbuf_get_n_channels (pixbuf);
for (y = 0; y < height; y++) {
y_offset = y * rowstride;
for (x = 0; x < width; x++) {
offset = y_offset + x * channels;
if (red != 0)
pixels[offset] = shift_color_byte (pixels[offset], red);
if (green != 0)
pixels[offset + 1] = shift_color_byte (pixels[offset + 1], green);
if (blue != 0)
pixels[offset + 2] = shift_color_byte (pixels[offset + 2], blue);
if (alpha != 0 && channels >= 4)
pixels[offset + 3] = shift_color_byte (pixels[offset + 3], blue);
}
}
}
static void
update_pixbufs (UmCropArea *area)
{
gint width;
gint height;
GtkAllocation allocation;
gdouble scale;
GdkRGBA color;
guint32 pixel;
gint dest_x, dest_y, dest_width, dest_height;
GtkWidget *widget;
GtkStyleContext *context;
widget = GTK_WIDGET (area);
gtk_widget_get_allocation (widget, &allocation);
context = gtk_widget_get_style_context (widget);
if (area->priv->pixbuf == NULL ||
gdk_pixbuf_get_width (area->priv->pixbuf) != allocation.width ||
gdk_pixbuf_get_height (area->priv->pixbuf) != allocation.height) {
if (area->priv->pixbuf != NULL)
g_object_unref (area->priv->pixbuf);
area->priv->pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB,
gdk_pixbuf_get_has_alpha (area->priv->browse_pixbuf),
8,
allocation.width, allocation.height);
gtk_style_context_get_background_color (context, gtk_style_context_get_state (context), &color);
pixel = (((gint)(color.red * 1.0)) << 16) |
(((gint)(color.green * 1.0)) << 8) |
((gint)(color.blue * 1.0));
gdk_pixbuf_fill (area->priv->pixbuf, pixel);
width = gdk_pixbuf_get_width (area->priv->browse_pixbuf);
height = gdk_pixbuf_get_height (area->priv->browse_pixbuf);
scale = allocation.height / (gdouble)height;
if (scale * width > allocation.width)
scale = allocation.width / (gdouble)width;
dest_width = width * scale;
dest_height = height * scale;
dest_x = (allocation.width - dest_width) / 2;
dest_y = (allocation.height - dest_height) / 2,
gdk_pixbuf_scale (area->priv->browse_pixbuf,
area->priv->pixbuf,
dest_x, dest_y,
dest_width, dest_height,
dest_x, dest_y,
scale, scale,
GDK_INTERP_BILINEAR);
if (area->priv->color_shifted)
g_object_unref (area->priv->color_shifted);
area->priv->color_shifted = gdk_pixbuf_copy (area->priv->pixbuf);
shift_colors (area->priv->color_shifted, -32, -32, -32, 0);
if (area->priv->scale == 0.0) {
area->priv->crop.width = 2 * area->priv->base_width / scale;
area->priv->crop.height = 2 * area->priv->base_height / scale;
area->priv->crop.x = (gdk_pixbuf_get_width (area->priv->browse_pixbuf) - area->priv->crop.width) / 2;
area->priv->crop.y = (gdk_pixbuf_get_height (area->priv->browse_pixbuf) - area->priv->crop.height) / 2;
}
area->priv->scale = scale;
area->priv->image.x = dest_x;
area->priv->image.y = dest_y;
area->priv->image.width = dest_width;
area->priv->image.height = dest_height;
}
}
static void
crop_to_widget (UmCropArea *area,
GdkRectangle *crop)
{
crop->x = area->priv->image.x + area->priv->crop.x * area->priv->scale;
crop->y = area->priv->image.y + area->priv->crop.y * area->priv->scale;
crop->width = area->priv->crop.width * area->priv->scale;
crop->height = area->priv->crop.height * area->priv->scale;
}
typedef enum {
OUTSIDE,
INSIDE,
TOP,
TOP_LEFT,
TOP_RIGHT,
BOTTOM,
BOTTOM_LEFT,
BOTTOM_RIGHT,
LEFT,
RIGHT
} Location;
static gboolean
um_crop_area_draw (GtkWidget *widget,
cairo_t *cr)
{
GdkRectangle crop;
gint width, height;
UmCropArea *uarea = UM_CROP_AREA (widget);
if (uarea->priv->browse_pixbuf == NULL)
return FALSE;
update_pixbufs (uarea);
width = gdk_pixbuf_get_width (uarea->priv->pixbuf);
height = gdk_pixbuf_get_height (uarea->priv->pixbuf);
crop_to_widget (uarea, &crop);
gdk_cairo_set_source_pixbuf (cr, uarea->priv->color_shifted, 0, 0);
cairo_rectangle (cr, 0, 0, width, crop.y);
cairo_rectangle (cr, 0, crop.y, crop.x, crop.height);
cairo_rectangle (cr, crop.x + crop.width, crop.y, width - crop.x - crop.width, crop.height);
cairo_rectangle (cr, 0, crop.y + crop.height, width, height - crop.y - crop.height);
cairo_fill (cr);
gdk_cairo_set_source_pixbuf (cr, uarea->priv->pixbuf, 0, 0);
cairo_rectangle (cr, crop.x, crop.y, crop.width, crop.height);
cairo_fill (cr);
if (uarea->priv->active_region != OUTSIDE) {
gint x1, x2, y1, y2;
cairo_set_source_rgb (cr, 1, 1, 1);
cairo_set_line_width (cr, 1.0);
x1 = crop.x + crop.width / 3.0;
x2 = crop.x + 2 * crop.width / 3.0;
y1 = crop.y + crop.height / 3.0;
y2 = crop.y + 2 * crop.height / 3.0;
cairo_move_to (cr, x1 + 0.5, crop.y);
cairo_line_to (cr, x1 + 0.5, crop.y + crop.height);
cairo_move_to (cr, x2 + 0.5, crop.y);
cairo_line_to (cr, x2 + 0.5, crop.y + crop.height);
cairo_move_to (cr, crop.x, y1 + 0.5);
cairo_line_to (cr, crop.x + crop.width, y1 + 0.5);
cairo_move_to (cr, crop.x, y2 + 0.5);
cairo_line_to (cr, crop.x + crop.width, y2 + 0.5);
cairo_stroke (cr);
}
cairo_set_source_rgb (cr, 0, 0, 0);
cairo_set_line_width (cr, 1.0);
cairo_rectangle (cr,
crop.x + 0.5,
crop.y + 0.5,
crop.width - 1.0,
crop.height - 1.0);
cairo_stroke (cr);
cairo_set_source_rgb (cr, 1, 1, 1);
cairo_set_line_width (cr, 2.0);
cairo_rectangle (cr,
crop.x + 2.0,
crop.y + 2.0,
crop.width - 4.0,
crop.height - 4.0);
cairo_stroke (cr);
return FALSE;
}
typedef enum {
BELOW,
LOWER,
BETWEEN,
UPPER,
ABOVE
} Range;
static Range
find_range (gint x,
gint min,
gint max)
{
gint tolerance = 12;
if (x < min - tolerance)
return BELOW;
if (x <= min + tolerance)
return LOWER;
if (x < max - tolerance)
return BETWEEN;
if (x <= max + tolerance)
return UPPER;
return ABOVE;
}
static Location
find_location (GdkRectangle *rect,
gint x,
gint y)
{
Range x_range, y_range;
Location location[5][5] = {
{ OUTSIDE, OUTSIDE, OUTSIDE, OUTSIDE, OUTSIDE },
{ OUTSIDE, TOP_LEFT, TOP, TOP_RIGHT, OUTSIDE },
{ OUTSIDE, LEFT, INSIDE, RIGHT, OUTSIDE },
{ OUTSIDE, BOTTOM_LEFT, BOTTOM, BOTTOM_RIGHT, OUTSIDE },
{ OUTSIDE, OUTSIDE, OUTSIDE, OUTSIDE, OUTSIDE }
};
x_range = find_range (x, rect->x, rect->x + rect->width);
y_range = find_range (y, rect->y, rect->y + rect->height);
return location[y_range][x_range];
}
static void
update_cursor (UmCropArea *area,
gint x,
gint y)
{
gint cursor_type;
GdkRectangle crop;
gint region;
region = area->priv->active_region;
if (region == OUTSIDE) {
crop_to_widget (area, &crop);
region = find_location (&crop, x, y);
}
switch (region) {
case OUTSIDE:
cursor_type = GDK_LEFT_PTR;
break;
case TOP_LEFT:
cursor_type = GDK_TOP_LEFT_CORNER;
break;
case TOP:
cursor_type = GDK_TOP_SIDE;
break;
case TOP_RIGHT:
cursor_type = GDK_TOP_RIGHT_CORNER;
break;
case LEFT:
cursor_type = GDK_LEFT_SIDE;
break;
case INSIDE:
cursor_type = GDK_FLEUR;
break;
case RIGHT:
cursor_type = GDK_RIGHT_SIDE;
break;
case BOTTOM_LEFT:
cursor_type = GDK_BOTTOM_LEFT_CORNER;
break;
case BOTTOM:
cursor_type = GDK_BOTTOM_SIDE;
break;
case BOTTOM_RIGHT:
cursor_type = GDK_BOTTOM_RIGHT_CORNER;
break;
default:
g_assert_not_reached ();
}
if (cursor_type != area->priv->current_cursor) {
GdkCursor *cursor = gdk_cursor_new (cursor_type);
gdk_window_set_cursor (gtk_widget_get_window (GTK_WIDGET (area)), cursor);
g_object_unref (cursor);
area->priv->current_cursor = cursor_type;
}
}
static int
eval_radial_line (gdouble center_x, gdouble center_y,
gdouble bounds_x, gdouble bounds_y,
gdouble user_x)
{
gdouble decision_slope;
gdouble decision_intercept;
decision_slope = (bounds_y - center_y) / (bounds_x - center_x);
decision_intercept = -(decision_slope * bounds_x);
return (int) (decision_slope * user_x + decision_intercept);
}
static gboolean
um_crop_area_motion_notify_event (GtkWidget *widget,
GdkEventMotion *event)
{
UmCropArea *area = UM_CROP_AREA (widget);
gint x, y;
gint delta_x, delta_y;
gint width, height;
gint adj_width, adj_height;
gint pb_width, pb_height;
GdkRectangle damage;
gint left, right, top, bottom;
gdouble new_width, new_height;
gdouble center_x, center_y;
gint min_width, min_height;
if (area->priv->browse_pixbuf == NULL)
return FALSE;
update_cursor (area, event->x, event->y);
crop_to_widget (area, &damage);
gtk_widget_queue_draw_area (widget,
damage.x - 1, damage.y - 1,
damage.width + 2, damage.height + 2);
pb_width = gdk_pixbuf_get_width (area->priv->browse_pixbuf);
pb_height = gdk_pixbuf_get_height (area->priv->browse_pixbuf);
x = (event->x - area->priv->image.x) / area->priv->scale;
y = (event->y - area->priv->image.y) / area->priv->scale;
delta_x = x - area->priv->last_press_x;
delta_y = y - area->priv->last_press_y;
area->priv->last_press_x = x;
area->priv->last_press_y = y;
left = area->priv->crop.x;
right = area->priv->crop.x + area->priv->crop.width - 1;
top = area->priv->crop.y;
bottom = area->priv->crop.y + area->priv->crop.height - 1;
center_x = (left + right) / 2.0;
center_y = (top + bottom) / 2.0;
switch (area->priv->active_region) {
case INSIDE:
width = right - left + 1;
height = bottom - top + 1;
left += delta_x;
right += delta_x;
top += delta_y;
bottom += delta_y;
if (left < 0)
left = 0;
if (top < 0)
top = 0;
if (right > pb_width)
right = pb_width;
if (bottom > pb_height)
bottom = pb_height;
adj_width = right - left + 1;
adj_height = bottom - top + 1;
if (adj_width != width) {
if (delta_x < 0)
right = left + width - 1;
else
left = right - width + 1;
}
if (adj_height != height) {
if (delta_y < 0)
bottom = top + height - 1;
else
top = bottom - height + 1;
}
break;
case TOP_LEFT:
if (area->priv->aspect < 0) {
top = y;
left = x;
}
else if (y < eval_radial_line (center_x, center_y, left, top, x)) {
top = y;
new_width = (bottom - top) * area->priv->aspect;
left = right - new_width;
}
else {
left = x;
new_height = (right - left) / area->priv->aspect;
top = bottom - new_height;
}
break;
case TOP:
top = y;
if (area->priv->aspect > 0) {
new_width = (bottom - top) * area->priv->aspect;
right = left + new_width;
}
break;
case TOP_RIGHT:
if (area->priv->aspect < 0) {
top = y;
right = x;
}
else if (y < eval_radial_line (center_x, center_y, right, top, x)) {
top = y;
new_width = (bottom - top) * area->priv->aspect;
right = left + new_width;
}
else {
right = x;
new_height = (right - left) / area->priv->aspect;
top = bottom - new_height;
}
break;
case LEFT:
left = x;
if (area->priv->aspect > 0) {
new_height = (right - left) / area->priv->aspect;
bottom = top + new_height;
}
break;
case BOTTOM_LEFT:
if (area->priv->aspect < 0) {
bottom = y;
left = x;
}
else if (y < eval_radial_line (center_x, center_y, left, bottom, x)) {
left = x;
new_height = (right - left) / area->priv->aspect;
bottom = top + new_height;
}
else {
bottom = y;
new_width = (bottom - top) * area->priv->aspect;
left = right - new_width;
}
break;
case RIGHT:
right = x;
if (area->priv->aspect > 0) {
new_height = (right - left) / area->priv->aspect;
bottom = top + new_height;
}
break;
case BOTTOM_RIGHT:
if (area->priv->aspect < 0) {
bottom = y;
right = x;
}
else if (y < eval_radial_line (center_x, center_y, right, bottom, x)) {
right = x;
new_height = (right - left) / area->priv->aspect;
bottom = top + new_height;
}
else {
bottom = y;
new_width = (bottom - top) * area->priv->aspect;
right = left + new_width;
}
break;
case BOTTOM:
bottom = y;
if (area->priv->aspect > 0) {
new_width = (bottom - top) * area->priv->aspect;
right= left + new_width;
}
break;
default:
return FALSE;
}
min_width = area->priv->base_width / area->priv->scale;
min_height = area->priv->base_height / area->priv->scale;
width = right - left + 1;
height = bottom - top + 1;
if (area->priv->aspect < 0) {
if (left < 0)
left = 0;
if (top < 0)
top = 0;
if (right > pb_width)
right = pb_width;
if (bottom > pb_height)
bottom = pb_height;
width = right - left + 1;
height = bottom - top + 1;
switch (area->priv->active_region) {
case LEFT:
case TOP_LEFT:
case BOTTOM_LEFT:
if (width < min_width)
left = right - min_width;
break;
case RIGHT:
case TOP_RIGHT:
case BOTTOM_RIGHT:
if (width < min_width)
right = left + min_width;
break;
default: ;
}
switch (area->priv->active_region) {
case TOP:
case TOP_LEFT:
case TOP_RIGHT:
if (height < min_height)
top = bottom - min_height;
break;
case BOTTOM:
case BOTTOM_LEFT:
case BOTTOM_RIGHT:
if (height < min_height)
bottom = top + min_height;
break;
default: ;
}
}
else {
if (left < 0 || top < 0 ||
right > pb_width || bottom > pb_height ||
width < min_width || height < min_height) {
left = area->priv->crop.x;
right = area->priv->crop.x + area->priv->crop.width - 1;
top = area->priv->crop.y;
bottom = area->priv->crop.y + area->priv->crop.height - 1;
}
}
area->priv->crop.x = left;
area->priv->crop.y = top;
area->priv->crop.width = right - left + 1;
area->priv->crop.height = bottom - top + 1;
crop_to_widget (area, &damage);
gtk_widget_queue_draw_area (widget,
damage.x - 1, damage.y - 1,
damage.width + 2, damage.height + 2);
return FALSE;
}
static gboolean
um_crop_area_button_press_event (GtkWidget *widget,
GdkEventButton *event)
{
UmCropArea *area = UM_CROP_AREA (widget);
GdkRectangle crop;
if (area->priv->browse_pixbuf == NULL)
return FALSE;
crop_to_widget (area, &crop);
area->priv->last_press_x = (event->x - area->priv->image.x) / area->priv->scale;
area->priv->last_press_y = (event->y - area->priv->image.y) / area->priv->scale;
area->priv->active_region = find_location (&crop, event->x, event->y);
gtk_widget_queue_draw_area (widget,
crop.x - 1, crop.y - 1,
crop.width + 2, crop.height + 2);
return FALSE;
}
static gboolean
um_crop_area_button_release_event (GtkWidget *widget,
GdkEventButton *event)
{
UmCropArea *area = UM_CROP_AREA (widget);
GdkRectangle crop;
if (area->priv->browse_pixbuf == NULL)
return FALSE;
crop_to_widget (area, &crop);
area->priv->last_press_x = -1;
area->priv->last_press_y = -1;
area->priv->active_region = OUTSIDE;
gtk_widget_queue_draw_area (widget,
crop.x - 1, crop.y - 1,
crop.width + 2, crop.height + 2);
return FALSE;
}
static void
um_crop_area_finalize (GObject *object)
{
UmCropArea *area = UM_CROP_AREA (object);
if (area->priv->browse_pixbuf) {
g_object_unref (area->priv->browse_pixbuf);
area->priv->browse_pixbuf = NULL;
}
if (area->priv->pixbuf) {
g_object_unref (area->priv->pixbuf);
area->priv->pixbuf = NULL;
}
if (area->priv->color_shifted) {
g_object_unref (area->priv->color_shifted);
area->priv->color_shifted = NULL;
}
}
static void
um_crop_area_class_init (UmCropAreaClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);
object_class->finalize = um_crop_area_finalize;
widget_class->draw = um_crop_area_draw;
widget_class->button_press_event = um_crop_area_button_press_event;
widget_class->button_release_event = um_crop_area_button_release_event;
widget_class->motion_notify_event = um_crop_area_motion_notify_event;
g_type_class_add_private (klass, sizeof (UmCropAreaPrivate));
}
static void
um_crop_area_init (UmCropArea *area)
{
area->priv = (G_TYPE_INSTANCE_GET_PRIVATE ((area), UM_TYPE_CROP_AREA,
UmCropAreaPrivate));
gtk_widget_add_events (GTK_WIDGET (area), GDK_POINTER_MOTION_MASK |
GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK);
area->priv->scale = 0.0;
area->priv->image.x = 0;
area->priv->image.y = 0;
area->priv->image.width = 0;
area->priv->image.height = 0;
area->priv->active_region = OUTSIDE;
area->priv->base_width = 48;
area->priv->base_height = 48;
area->priv->aspect = 1;
}
GtkWidget *
um_crop_area_new (void)
{
return g_object_new (UM_TYPE_CROP_AREA, NULL);
}
GdkPixbuf *
um_crop_area_get_picture (UmCropArea *area)
{
gint width, height;
width = gdk_pixbuf_get_width (area->priv->browse_pixbuf);
height = gdk_pixbuf_get_height (area->priv->browse_pixbuf);
width = MIN (area->priv->crop.width, width - area->priv->crop.x);
height = MIN (area->priv->crop.height, height - area->priv->crop.y);
return gdk_pixbuf_new_subpixbuf (area->priv->browse_pixbuf,
area->priv->crop.x,
area->priv->crop.y,
width, height);
}
void
um_crop_area_set_picture (UmCropArea *area,
GdkPixbuf *pixbuf)
{
int width;
int height;
if (area->priv->browse_pixbuf) {
g_object_unref (area->priv->browse_pixbuf);
area->priv->browse_pixbuf = NULL;
}
if (pixbuf) {
area->priv->browse_pixbuf = g_object_ref (pixbuf);
width = gdk_pixbuf_get_width (pixbuf);
height = gdk_pixbuf_get_height (pixbuf);
} else {
width = 0;
height = 0;
}
area->priv->crop.width = 2 * area->priv->base_width;
area->priv->crop.height = 2 * area->priv->base_height;
area->priv->crop.x = (width - area->priv->crop.width) / 2;
area->priv->crop.y = (height - area->priv->crop.height) / 2;
area->priv->scale = 0.0;
area->priv->image.x = 0;
area->priv->image.y = 0;
area->priv->image.width = 0;
area->priv->image.height = 0;
gtk_widget_queue_draw (GTK_WIDGET (area));
}
void
um_crop_area_set_min_size (UmCropArea *area,
gint width,
gint height)
{
area->priv->base_width = width;
area->priv->base_height = height;
if (area->priv->aspect > 0) {
area->priv->aspect = area->priv->base_width / (gdouble)area->priv->base_height;
}
}
void
um_crop_area_set_constrain_aspect (UmCropArea *area,
gboolean constrain)
{
if (constrain) {
area->priv->aspect = area->priv->base_width / (gdouble)area->priv->base_height;
}
else {
area->priv->aspect = -1;
}
}
|
342 | ./cinnamon-control-center/panels/user-accounts/um-user-manager.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2009-2010 Red Hat, Inc.
*
* 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.
*
* Written by: Matthias Clasen <[email protected]>
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <pwd.h>
#ifdef HAVE_PATHS_H
#include <paths.h>
#endif /* HAVE_PATHS_H */
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <glib/gstdio.h>
#include <glib-object.h>
#include <gio/gio.h>
#include "um-user-manager.h"
enum {
USERS_LOADED,
USER_ADDED,
USER_REMOVED,
USER_CHANGED,
LAST_SIGNAL
};
static guint signals [LAST_SIGNAL] = { 0, };
static void um_user_manager_class_init (UmUserManagerClass *klass);
static void um_user_manager_init (UmUserManager *user_manager);
static void um_user_manager_finalize (GObject *object);
static gpointer user_manager_object = NULL;
G_DEFINE_TYPE (UmUserManager, um_user_manager, G_TYPE_OBJECT)
static void
um_user_manager_class_init (UmUserManagerClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->finalize = um_user_manager_finalize;
signals [USERS_LOADED] =
g_signal_new ("users-loaded",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (UmUserManagerClass, users_loaded),
NULL, NULL,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
signals [USER_ADDED] =
g_signal_new ("user-added",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (UmUserManagerClass, user_added),
NULL, NULL,
g_cclosure_marshal_VOID__OBJECT,
G_TYPE_NONE, 1, UM_TYPE_USER);
signals [USER_REMOVED] =
g_signal_new ("user-removed",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (UmUserManagerClass, user_removed),
NULL, NULL,
g_cclosure_marshal_VOID__OBJECT,
G_TYPE_NONE, 1, UM_TYPE_USER);
signals [USER_CHANGED] =
g_signal_new ("user-changed",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (UmUserManagerClass, user_changed),
NULL, NULL,
g_cclosure_marshal_VOID__OBJECT,
G_TYPE_NONE, 1, UM_TYPE_USER);
}
/* We maintain a ring for each group of users with the same real name.
* We need this to pick the right display names.
*/
static void
remove_user_from_dupe_ring (UmUserManager *manager,
UmUser *user)
{
GList *dupes;
UmUser *dup;
dup = NULL;
dupes = g_object_get_data (G_OBJECT (user), "dupes");
if (!dupes) {
goto out;
}
if (dupes->next == dupes->prev) {
dup = dupes->next->data;
g_list_free_1 (dupes->next);
g_object_set_data (G_OBJECT (dup), "dupes", NULL);
}
else {
dupes->next->prev = dupes->prev;
dupes->prev->next = dupes->next;
}
g_list_free_1 (dupes);
g_object_set_data (G_OBJECT (user), "dupes", NULL);
out:
if (dup) {
um_user_show_short_display_name (dup);
g_signal_emit (manager, signals[USER_CHANGED], 0, dup);
}
um_user_show_short_display_name (user);
g_signal_emit (manager, signals[USER_CHANGED], 0, user);
}
static gboolean
match_real_name_hrfunc (gpointer key,
gpointer value,
gpointer user)
{
return (value != user && g_strcmp0 (um_user_get_real_name (user), um_user_get_real_name (value)) == 0);
}
static void
add_user_to_dupe_ring (UmUserManager *manager,
UmUser *user)
{
UmUser *dup;
GList *dupes;
GList *l;
dup = g_hash_table_find (manager->user_by_object_path,
match_real_name_hrfunc, user);
if (!dup) {
return;
}
dupes = g_object_get_data (G_OBJECT (dup), "dupes");
if (!dupes) {
dupes = g_list_append (NULL, dup);
g_object_set_data (G_OBJECT (dup), "dupes", dupes);
dupes->next = dupes->prev = dupes;
}
else {
dup = NULL;
}
l = g_list_append (NULL, user);
g_object_set_data (G_OBJECT (user), "dupes", l);
l->prev = dupes->prev;
dupes->prev->next = l;
l->next = dupes;
dupes->prev = l;
if (dup) {
um_user_show_full_display_name (dup);
g_signal_emit (manager, signals[USER_CHANGED], 0, dup);
}
um_user_show_full_display_name (user);
g_signal_emit (manager, signals[USER_CHANGED], 0, user);
}
static void
user_changed_handler (UmUser *user,
UmUserManager *manager)
{
remove_user_from_dupe_ring (manager, user);
add_user_to_dupe_ring (manager, user);
g_signal_emit (manager, signals[USER_CHANGED], 0, user);
}
static void
user_added_handler (UmUserManager *manager,
const char *object_path)
{
UmUser *user;
if (g_hash_table_lookup (manager->user_by_object_path, object_path))
return;
user = um_user_new_from_object_path (object_path);
if (!user)
return;
if (um_user_is_system_account (user)) {
g_object_unref (user);
return;
}
add_user_to_dupe_ring (manager, user);
g_signal_connect (user, "changed",
G_CALLBACK (user_changed_handler), manager);
g_hash_table_insert (manager->user_by_object_path, g_strdup (um_user_get_object_path (user)), g_object_ref (user));
g_hash_table_insert (manager->user_by_name, g_strdup (um_user_get_user_name (user)), g_object_ref (user));
g_signal_emit (manager, signals[USER_ADDED], 0, user);
g_object_unref (user);
}
static void
user_deleted_handler (UmUserManager *manager,
const char *object_path)
{
UmUser *user;
user = g_hash_table_lookup (manager->user_by_object_path, object_path);
if (!user)
return;
g_object_ref (user);
g_signal_handlers_disconnect_by_func (user, user_changed_handler, manager);
remove_user_from_dupe_ring (manager, user);
g_hash_table_remove (manager->user_by_object_path, um_user_get_object_path (user));
g_hash_table_remove (manager->user_by_name, um_user_get_user_name (user));
g_signal_emit (manager, signals[USER_REMOVED], 0, user);
g_object_unref (user);
}
static void
manager_signal_cb (GDBusProxy *proxy, gchar *sender_name, gchar *signal_name, GVariant *parameters, UmUserManager *manager)
{
if (strcmp (signal_name, "UserAdded") == 0) {
if (g_variant_is_of_type (parameters, G_VARIANT_TYPE ("(o)"))) {
gchar *object_path;
g_variant_get (parameters, "(&o)", &object_path);
user_added_handler (manager, object_path);
}
}
else if (strcmp (signal_name, "UserDeleted") == 0) {
if (g_variant_is_of_type (parameters, G_VARIANT_TYPE ("(o)"))) {
gchar *object_path;
g_variant_get (parameters, "(&o)", &object_path);
user_deleted_handler (manager, object_path);
}
}
}
static void
got_users (GObject *object,
GAsyncResult *res,
gpointer data)
{
UmUserManager *manager = data;
GVariant *result;
GError *error = NULL;
result = g_dbus_proxy_call_finish (G_DBUS_PROXY (object), res, &error);
if (!result) {
manager->no_service = TRUE;
g_error_free (error);
goto done;
}
if (g_variant_is_of_type (result, G_VARIANT_TYPE ("(ao)"))) {
GVariantIter *iter;
gchar *object_path;
g_variant_get (result, "(ao)", &iter);
while (g_variant_iter_loop (iter, "&o", &object_path))
user_added_handler (manager, object_path);
g_variant_iter_free (iter);
}
g_variant_unref (result);
done:
g_signal_emit (G_OBJECT (manager), signals[USERS_LOADED], 0);
}
static void
get_users (UmUserManager *manager)
{
g_debug ("calling 'ListCachedUsers'");
g_dbus_proxy_call (manager->proxy,
"ListCachedUsers",
g_variant_new ("()"),
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
got_users,
manager);
}
static void
um_user_manager_init (UmUserManager *manager)
{
GError *error = NULL;
GDBusConnection *bus;
manager->user_by_object_path = g_hash_table_new_full (g_str_hash,
g_str_equal,
g_free,
g_object_unref);
manager->user_by_name = g_hash_table_new_full (g_str_hash,
g_str_equal,
g_free,
g_object_unref);
bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error);
if (bus == NULL) {
g_warning ("Couldn't connect to system bus: %s", error->message);
g_error_free (error);
return;
}
manager->proxy = g_dbus_proxy_new_sync (bus,
G_DBUS_PROXY_FLAGS_NONE,
NULL,
"org.freedesktop.Accounts",
"/org/freedesktop/Accounts",
"org.freedesktop.Accounts",
NULL,
&error);
if (manager->proxy == NULL) {
g_warning ("Couldn't get accounts proxy: %s", error->message);
g_error_free (error);
return;
}
g_signal_connect (manager->proxy, "g-signal", G_CALLBACK (manager_signal_cb), manager);
get_users (manager);
}
static void
clear_dup (gpointer key,
gpointer value,
gpointer data)
{
GList *dupes;
/* don't bother maintaining the ring, we're destroying the
* entire hash table anyway
*/
dupes = g_object_get_data (G_OBJECT (value), "dupes");
if (dupes) {
g_list_free_1 (dupes);
g_object_set_data (G_OBJECT (value), "dupes", NULL);
}
}
static void
um_user_manager_finalize (GObject *object)
{
UmUserManager *manager;
manager = UM_USER_MANAGER (object);
g_hash_table_foreach (manager->user_by_object_path, clear_dup, NULL);
g_hash_table_destroy (manager->user_by_object_path);
g_hash_table_destroy (manager->user_by_name);
g_object_unref (manager->proxy);
G_OBJECT_CLASS (um_user_manager_parent_class)->finalize (object);
}
UmUserManager *
um_user_manager_ref_default (void)
{
if (user_manager_object != NULL) {
g_object_ref (user_manager_object);
} else {
user_manager_object = g_object_new (UM_TYPE_USER_MANAGER, NULL);
g_object_add_weak_pointer (user_manager_object,
(gpointer *) &user_manager_object);
}
return UM_USER_MANAGER (user_manager_object);
}
typedef struct {
UmUserManager *manager;
gchar *user_name;
GAsyncReadyCallback callback;
gpointer data;
GDestroyNotify destroy;
} AsyncUserOpData;
static void
async_user_op_data_free (gpointer d)
{
AsyncUserOpData *data = d;
g_object_unref (data->manager);
g_free (data->user_name);
if (data->destroy)
data->destroy (data->data);
g_free (data);
}
/* Used for both create_user and cache_user */
static void
user_call_done (GObject *proxy,
GAsyncResult *r,
gpointer user_data)
{
AsyncUserOpData *data = user_data;
GSimpleAsyncResult *res;
GVariant *result;
GError *error = NULL;
gchar *remote;
res = g_simple_async_result_new (G_OBJECT (data->manager),
data->callback,
data->data,
um_user_manager_create_user);
result = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), r, &error);
if (!result) {
/* dbus-glib fail:
* We have to translate the errors manually here, since
* calling dbus_g_error_has_name on the error returned in
* um_user_manager_create_user_finish doesn't work.
*/
remote = g_dbus_error_get_remote_error (error);
if (g_dbus_error_is_remote_error (error) &&
strcmp (remote, "org.freedesktop.Accounts.Error.PermissionDenied") == 0) {
g_simple_async_result_set_error (res,
UM_USER_MANAGER_ERROR,
UM_USER_MANAGER_ERROR_PERMISSION_DENIED,
"Not authorized");
}
if (g_dbus_error_is_remote_error (error) &&
strcmp (remote, "org.freedesktop.Accounts.Error.UserExists") == 0) {
g_simple_async_result_set_error (res,
UM_USER_MANAGER_ERROR,
UM_USER_MANAGER_ERROR_USER_EXISTS,
_("A user with name '%s' already exists."),
data->user_name);
} else if (g_dbus_error_is_remote_error (error) &&
strcmp (remote, "org.freedesktop.Accounts.Error.UserDoesNotExist") == 0) {
g_simple_async_result_set_error (res,
UM_USER_MANAGER_ERROR,
UM_USER_MANAGER_ERROR_USER_DOES_NOT_EXIST,
_("No user with the name '%s' exists."),
data->user_name);
}
else {
g_simple_async_result_set_from_error (res, error);
}
g_error_free (error);
g_free (remote);
}
else {
if (g_variant_is_of_type (result, G_VARIANT_TYPE ("(o)"))) {
gchar *path;
g_variant_get (result, "(o)", &path);
g_simple_async_result_set_op_res_gpointer (res, path, g_free);
}
else
g_simple_async_result_set_error (res,
UM_USER_MANAGER_ERROR,
UM_USER_MANAGER_ERROR_FAILED,
"Got invalid response from AccountsService");
g_variant_unref (result);
}
data->callback (G_OBJECT (data->manager), G_ASYNC_RESULT (res), data->data);
async_user_op_data_free (data);
g_object_unref (res);
}
gboolean
um_user_manager_create_user_finish (UmUserManager *manager,
GAsyncResult *result,
UmUser **user,
GError **error)
{
gchar *path;
GSimpleAsyncResult *res;
res = G_SIMPLE_ASYNC_RESULT (result);
*user = NULL;
if (g_simple_async_result_propagate_error (res, error)) {
return FALSE;
}
path = g_simple_async_result_get_op_res_gpointer (res);
*user = g_hash_table_lookup (manager->user_by_object_path, path);
return TRUE;
}
void
um_user_manager_create_user (UmUserManager *manager,
const char *user_name,
const char *real_name,
gint account_type,
GCancellable *cancellable,
GAsyncReadyCallback done,
gpointer done_data,
GDestroyNotify destroy)
{
AsyncUserOpData *data;
data = g_new0 (AsyncUserOpData, 1);
data->manager = g_object_ref (manager);
data->user_name = g_strdup (user_name);
data->callback = done;
data->data = done_data;
data->destroy = destroy;
g_dbus_proxy_call (manager->proxy,
"CreateUser",
g_variant_new ("(ssi)", user_name, real_name, account_type),
G_DBUS_CALL_FLAGS_NONE,
-1,
cancellable,
user_call_done,
data);
}
gboolean
um_user_manager_cache_user_finish (UmUserManager *manager,
GAsyncResult *result,
UmUser **user,
GError **error)
{
gchar *path;
GSimpleAsyncResult *res;
res = G_SIMPLE_ASYNC_RESULT (result);
*user = NULL;
if (g_simple_async_result_propagate_error (res, error)) {
return FALSE;
}
path = g_simple_async_result_get_op_res_gpointer (res);
*user = g_hash_table_lookup (manager->user_by_object_path, path);
return TRUE;
}
void
um_user_manager_cache_user (UmUserManager *manager,
const char *user_name,
GCancellable *cancellable,
GAsyncReadyCallback done,
gpointer done_data,
GDestroyNotify destroy)
{
AsyncUserOpData *data;
data = g_new0 (AsyncUserOpData, 1);
data->manager = g_object_ref (manager);
data->user_name = g_strdup (user_name);
data->callback = done;
data->data = done_data;
data->destroy = destroy;
g_dbus_proxy_call (manager->proxy,
"CacheUser",
g_variant_new ("(s)", user_name),
G_DBUS_CALL_FLAGS_NONE,
-1,
cancellable,
user_call_done,
data);
}
static void
delete_user_done (GObject *proxy,
GAsyncResult *r,
gpointer user_data)
{
AsyncUserOpData *data = user_data;
GSimpleAsyncResult *res;
GVariant *result;
GError *error = NULL;
res = g_simple_async_result_new (G_OBJECT (data->manager),
data->callback,
data->data,
um_user_manager_delete_user);
result = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), r, &error);
if (!result) {
if (g_dbus_error_is_remote_error (error) &&
strcmp (g_dbus_error_get_remote_error(error), "org.freedesktop.Accounts.Error.PermissionDenied") == 0) {
g_simple_async_result_set_error (res,
UM_USER_MANAGER_ERROR,
UM_USER_MANAGER_ERROR_PERMISSION_DENIED,
"Not authorized");
}
else if (g_dbus_error_is_remote_error (error) &&
strcmp (g_dbus_error_get_remote_error(error), "org.freedesktop.Accounts.Error.UserExists") == 0) {
g_simple_async_result_set_error (res,
UM_USER_MANAGER_ERROR,
UM_USER_MANAGER_ERROR_USER_DOES_NOT_EXIST,
_("This user does not exist."));
}
else {
g_simple_async_result_set_from_error (res, error);
g_error_free (error);
}
}
else
g_variant_unref (result);
data->callback (G_OBJECT (data->manager), G_ASYNC_RESULT (res), data->data);
async_user_op_data_free (data);
g_object_unref (res);
}
gboolean
um_user_manager_delete_user_finish (UmUserManager *manager,
GAsyncResult *result,
GError **error)
{
GSimpleAsyncResult *res;
res = G_SIMPLE_ASYNC_RESULT (result);
if (g_simple_async_result_propagate_error (res, error)) {
return FALSE;
}
return TRUE;
}
void
um_user_manager_delete_user (UmUserManager *manager,
UmUser *user,
gboolean remove_files,
GAsyncReadyCallback done,
gpointer done_data,
GDestroyNotify destroy)
{
AsyncUserOpData *data;
data = g_new0 (AsyncUserOpData, 1);
data->manager = g_object_ref (manager);
data->callback = done;
data->data = done_data;
data->destroy = destroy;
g_dbus_proxy_call (manager->proxy,
"DeleteUser",
g_variant_new ("(xb)", (gint64) um_user_get_uid (user), remove_files),
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
delete_user_done,
data);
}
GSList *
um_user_manager_list_users (UmUserManager *manager)
{
GSList *list = NULL;
GHashTableIter iter;
gpointer value;
g_hash_table_iter_init (&iter, manager->user_by_name);
while (g_hash_table_iter_next (&iter, NULL, &value)) {
list = g_slist_prepend (list, value);
}
return g_slist_sort (list, (GCompareFunc) um_user_collate);
}
UmUser *
um_user_manager_get_user (UmUserManager *manager,
const gchar *name)
{
return g_hash_table_lookup (manager->user_by_name, name);
}
UmUser *
um_user_manager_get_user_by_id (UmUserManager *manager,
uid_t uid)
{
struct passwd *pwent;
pwent = getpwuid (uid);
if (!pwent) {
return NULL;
}
return um_user_manager_get_user (manager, pwent->pw_name);
}
gboolean
um_user_manager_no_service (UmUserManager *manager)
{
return manager->no_service;
}
GQuark
um_user_manager_error_quark (void)
{
return g_quark_from_static_string ("um-user-manager-error-quark");
}
|
343 | ./cinnamon-control-center/panels/user-accounts/um-user-module.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright 2009-2010 Red Hat, Inc,
*
* 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.
*
* Written by: Matthias Clasen <[email protected]>
*/
#include <config.h>
#include "um-user-panel.h"
void
g_io_module_load (GIOModule *module)
{
/* register the panel */
um_user_panel_register (module);
}
void
g_io_module_unload (GIOModule *module)
{
}
|
344 | ./cinnamon-control-center/panels/user-accounts/um-password-dialog.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright 2009-2010 Red Hat, Inc,
*
* 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.
*
* Written by: Matthias Clasen <[email protected]>
*/
#include "config.h"
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <gtk/gtk.h>
#include "um-password-dialog.h"
#include "um-user-manager.h"
#include "um-utils.h"
#include "run-passwd.h"
#include "pw-utils.h"
struct _UmPasswordDialog {
GtkWidget *dialog;
GtkWidget *user_icon;
GtkWidget *user_name;
GtkWidget *action_label;
GtkWidget *action_combo;
GtkWidget *password_entry;
GtkWidget *verify_entry;
GtkWidget *strength_indicator;
GtkWidget *strength_indicator_label;
GtkWidget *normal_hint_entry;
GtkWidget *normal_hint_label;
GtkWidget *show_password_button;
GtkWidget *ok_button;
UmUser *user;
gboolean using_ecryptfs;
GtkWidget *old_password_label;
GtkWidget *old_password_entry;
gboolean old_password_ok;
PasswdHandler *passwd_handler;
gchar **generated;
gint next_generated;
};
static void
generate_one_password (GtkWidget *widget,
UmPasswordDialog *um)
{
gchar *key = g_strdup ("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
gint i;
GString *s = g_string_new("");
for (i = 0; i < MIN_PW_LENGTH; i++) {
g_string_append_c (s, key[g_random_int_range (0, strlen(key) - 1)]);
}
gtk_entry_set_text (GTK_ENTRY (um->password_entry), s->str);
gtk_entry_set_text (GTK_ENTRY (um->verify_entry), "");
g_free (key);
g_string_free (s, FALSE);
}
static void
activate_icon (GtkEntry *entry,
GtkEntryIconPosition pos,
GdkEventButton *event,
UmPasswordDialog *um)
{
generate_one_password (GTK_WIDGET (entry), um);
}
static void
populate_menu (GtkEntry *entry,
GtkMenu *menu,
UmPasswordDialog *um)
{
GtkWidget *item;
item = gtk_menu_item_new_with_mnemonic (_("_Generate a password"));
g_signal_connect (item, "activate",
G_CALLBACK (generate_one_password), um);
gtk_widget_show (item);
gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);
}
static void
finish_password_change (UmPasswordDialog *um)
{
gtk_widget_hide (um->dialog);
gtk_entry_set_text (GTK_ENTRY (um->password_entry), " ");
gtk_entry_set_text (GTK_ENTRY (um->verify_entry), "");
gtk_entry_set_text (GTK_ENTRY (um->normal_hint_entry), "");
gtk_entry_set_text (GTK_ENTRY (um->old_password_entry), "");
um_password_dialog_set_user (um, NULL);
}
static void
cancel_password_dialog (GtkButton *button,
UmPasswordDialog *um)
{
finish_password_change (um);
}
static void
dialog_closed (GtkWidget *dialog,
gint response_id,
UmPasswordDialog *um)
{
gtk_widget_destroy (dialog);
}
static void
password_changed_cb (PasswdHandler *handler,
GError *error,
UmPasswordDialog *um)
{
GtkWidget *dialog;
const gchar *primary_text;
const gchar *secondary_text;
gtk_widget_set_sensitive (um->dialog, TRUE);
gdk_window_set_cursor (gtk_widget_get_window (um->dialog), NULL);
if (!error) {
finish_password_change (um);
return;
}
if (error->code == PASSWD_ERROR_REJECTED) {
primary_text = error->message;
secondary_text = _("Please choose another password.");
gtk_entry_set_text (GTK_ENTRY (um->password_entry), "");
gtk_widget_grab_focus (um->password_entry);
gtk_entry_set_text (GTK_ENTRY (um->verify_entry), "");
}
else if (error->code == PASSWD_ERROR_AUTH_FAILED) {
primary_text = error->message;
secondary_text = _("Please type your current password again.");
gtk_entry_set_text (GTK_ENTRY (um->old_password_entry), "");
gtk_widget_grab_focus (um->old_password_entry);
}
else {
primary_text = _("Password could not be changed");
secondary_text = error->message;
}
dialog = gtk_message_dialog_new (GTK_WINDOW (um->dialog),
GTK_DIALOG_MODAL,
GTK_MESSAGE_ERROR,
GTK_BUTTONS_CLOSE,
"%s", primary_text);
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
"%s", secondary_text);
g_signal_connect (dialog, "response",
G_CALLBACK (dialog_closed), um);
gtk_window_present (GTK_WINDOW (dialog));
}
static void
accept_password_dialog (GtkButton *button,
UmPasswordDialog *um)
{
GtkTreeModel *model;
GtkTreeIter iter;
gint mode;
const gchar *hint;
const gchar *password;
model = gtk_combo_box_get_model (GTK_COMBO_BOX (um->action_combo));
gtk_combo_box_get_active_iter (GTK_COMBO_BOX (um->action_combo), &iter);
gtk_tree_model_get (model, &iter, 1, &mode, -1);
password = gtk_entry_get_text (GTK_ENTRY (um->password_entry));
hint = gtk_entry_get_text (GTK_ENTRY (um->normal_hint_entry));
if (mode == 0 && um_user_get_uid (um->user) == getuid ()) {
GdkDisplay *display;
GdkCursor *cursor;
/* When setting a password for the current user,
* use passwd directly, to preserve the audit trail
* and to e.g. update the keyring password.
*/
passwd_change_password (um->passwd_handler, password, (PasswdCallback) password_changed_cb, um);
gtk_widget_set_sensitive (um->dialog, FALSE);
display = gtk_widget_get_display (um->dialog);
cursor = gdk_cursor_new_for_display (display, GDK_WATCH);
gdk_window_set_cursor (gtk_widget_get_window (um->dialog), cursor);
gdk_display_flush (display);
g_object_unref (cursor);
}
else {
um_user_set_password (um->user, mode, password, hint);
finish_password_change (um);
}
}
static void
update_sensitivity (UmPasswordDialog *um)
{
const gchar *password, *verify;
const gchar *old_password;
const gchar *tooltip;
gboolean can_change;
password = gtk_entry_get_text (GTK_ENTRY (um->password_entry));
verify = gtk_entry_get_text (GTK_ENTRY (um->verify_entry));
old_password = gtk_entry_get_text (GTK_ENTRY (um->old_password_entry));
if (strlen (password) < MIN_PW_LENGTH) {
can_change = FALSE;
if (password[0] == '\0') {
tooltip = _("You need to enter a new password");
}
else {
tooltip = _("The new password is too short");
}
}
else if (strcmp (password, verify) != 0) {
can_change = FALSE;
if (verify[0] == '\0') {
tooltip = _("You need to confirm the password");
}
else {
tooltip = _("The passwords do not match");
}
}
else if (!um->old_password_ok) {
can_change = FALSE;
if (old_password[0] == '\0') {
tooltip = _("You need to enter your current password");
}
else {
tooltip = _("The current password is not correct");
}
}
else {
can_change = TRUE;
tooltip = NULL;
}
gtk_widget_set_sensitive (um->ok_button, can_change);
gtk_widget_set_tooltip_text (um->ok_button, tooltip);
}
static void
action_changed (GtkComboBox *combo,
UmPasswordDialog *um)
{
gint active;
active = gtk_combo_box_get_active (combo);
if (active == 0) {
gtk_widget_set_sensitive (um->password_entry, TRUE);
gtk_entry_set_icon_sensitive (GTK_ENTRY (um->password_entry), GTK_ENTRY_ICON_SECONDARY, TRUE);
gtk_widget_set_sensitive (um->verify_entry, TRUE);
gtk_widget_set_sensitive (um->old_password_entry, TRUE);
gtk_widget_set_sensitive (um->normal_hint_entry, TRUE);
gtk_widget_set_sensitive (um->normal_hint_label, TRUE);
gtk_widget_set_sensitive (um->strength_indicator_label, TRUE);
gtk_widget_set_sensitive (um->show_password_button, TRUE);
update_sensitivity (um);
}
else {
gtk_widget_set_sensitive (um->password_entry, FALSE);
gtk_entry_set_icon_sensitive (GTK_ENTRY (um->password_entry), GTK_ENTRY_ICON_SECONDARY, FALSE);
gtk_widget_set_sensitive (um->verify_entry, FALSE);
gtk_widget_set_sensitive (um->old_password_entry, FALSE);
gtk_widget_set_sensitive (um->normal_hint_entry, FALSE);
gtk_widget_set_sensitive (um->normal_hint_label, FALSE);
gtk_widget_set_sensitive (um->strength_indicator_label, FALSE);
gtk_widget_set_sensitive (um->show_password_button, FALSE);
gtk_widget_set_sensitive (um->ok_button, TRUE);
}
}
static void
show_password_toggled (GtkToggleButton *button,
UmPasswordDialog *um)
{
gboolean active;
active = gtk_toggle_button_get_active (button);
gtk_entry_set_visibility (GTK_ENTRY (um->password_entry), active);
gtk_entry_set_visibility (GTK_ENTRY (um->verify_entry), active);
}
static void
update_password_strength (UmPasswordDialog *um)
{
const gchar *password;
const gchar *old_password;
const gchar *username;
gdouble strength_level;
const gchar *hint;
const gchar *long_hint;
password = gtk_entry_get_text (GTK_ENTRY (um->password_entry));
old_password = gtk_entry_get_text (GTK_ENTRY (um->old_password_entry));
username = um_user_get_user_name (um->user);
strength_level = pw_strength (password, old_password, username,
&hint, &long_hint);
gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (um->strength_indicator), strength_level);
gtk_label_set_label (GTK_LABEL (um->strength_indicator_label), hint);
gtk_widget_set_tooltip_text (um->strength_indicator, long_hint);
gtk_widget_set_tooltip_text (um->strength_indicator_label, long_hint);
}
static void
update_password_match (UmPasswordDialog *um)
{
const char *password;
const char *verify;
password = gtk_entry_get_text (GTK_ENTRY (um->password_entry));
verify = gtk_entry_get_text (GTK_ENTRY (um->verify_entry));
if (strlen (password) > 0 && strlen (verify) > 0) {
if (strcmp (password, verify) != 0) {
set_entry_validation_error (GTK_ENTRY (um->verify_entry),
_("Passwords do not match"));
}
else {
clear_entry_validation_error (GTK_ENTRY (um->verify_entry));
}
}
}
static void
password_entry_changed (GtkEntry *entry,
GParamSpec *pspec,
UmPasswordDialog *um)
{
update_password_strength (um);
update_sensitivity (um);
update_password_match (um);
}
static gboolean
password_entry_focus_out (GtkWidget *entry,
GdkEventFocus *event,
UmPasswordDialog *um)
{
update_password_match (um);
return FALSE;
}
static void
verify_entry_changed (GtkEntry *entry,
GParamSpec *pspec,
UmPasswordDialog *um)
{
clear_entry_validation_error (GTK_ENTRY (entry));
update_password_strength (um);
update_sensitivity (um);
}
static gboolean
verify_entry_focus_out (GtkWidget *entry,
GdkEventFocus *event,
UmPasswordDialog *um)
{
update_password_match (um);
return FALSE;
}
static void
entry_size_changed (GtkWidget *entry,
GtkAllocation *allocation,
GtkWidget *label)
{
gtk_widget_set_size_request (label, allocation->width, -1);
}
static void
auth_cb (PasswdHandler *handler,
GError *error,
UmPasswordDialog *um)
{
if (error) {
um->old_password_ok = FALSE;
set_entry_validation_error (GTK_ENTRY (um->old_password_entry),
_("Wrong password"));
}
else {
um->old_password_ok = TRUE;
clear_entry_validation_error (GTK_ENTRY (um->old_password_entry));
}
update_sensitivity (um);
}
static gboolean
old_password_entry_focus_out (GtkWidget *entry,
GdkEventFocus *event,
UmPasswordDialog *um)
{
const char *text;
text = gtk_entry_get_text (GTK_ENTRY (entry));
if (strlen (text) > 0) {
passwd_authenticate (um->passwd_handler, text,
(PasswdCallback)auth_cb, um);
}
return FALSE;
}
static void
old_password_entry_activate (GtkWidget *entry,
UmPasswordDialog *um)
{
const char *text;
text = gtk_entry_get_text (GTK_ENTRY (entry));
if (strlen (text) > 0) {
passwd_authenticate (um->passwd_handler, text,
(PasswdCallback)auth_cb, um);
}
}
static void
old_password_entry_changed (GtkEntry *entry,
GParamSpec *pspec,
UmPasswordDialog *um)
{
clear_entry_validation_error (GTK_ENTRY (entry));
um->old_password_ok = FALSE;
update_sensitivity (um);
}
void
um_password_dialog_set_privileged (UmPasswordDialog *um,
gboolean privileged)
{
if (privileged) {
gtk_widget_set_visible (um->action_label, TRUE);
gtk_widget_set_visible (um->action_combo, TRUE);
}
else {
gtk_combo_box_set_active (GTK_COMBO_BOX (um->action_combo), 0);
gtk_widget_set_visible (um->action_label, FALSE);
gtk_widget_set_visible (um->action_combo, FALSE);
}
}
int _is_gdm_running = -1;
gboolean
is_gdm_running (void)
{
if (_is_gdm_running == -1) {
GDBusProxy *proxy;
gchar *owner_name;
proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM,
G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES |
G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS |
G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START,
NULL,
"org.gnome.DisplayManager",
"/org/gnome/DisplayManager/Manager",
"org.gnome.DisplayManager.Manager",
NULL, NULL);
if (proxy == NULL)
return FALSE;
owner_name = g_dbus_proxy_get_name_owner (proxy);
g_object_unref (proxy);
g_free (owner_name);
_is_gdm_running = (owner_name != NULL) ? 1 : 0;
}
return _is_gdm_running;
}
UmPasswordDialog *
um_password_dialog_new (void)
{
GtkBuilder *builder;
GError *error;
const gchar *filename;
UmPasswordDialog *um;
GtkWidget *widget;
const char *old_label;
char *label;
gint len;
builder = gtk_builder_new ();
gtk_builder_set_translation_domain (builder, GETTEXT_PACKAGE);
error = NULL;
filename = UIDIR "/password-dialog.ui";
if (!g_file_test (filename, G_FILE_TEST_EXISTS))
filename = "data/password-dialog.ui";
if (!gtk_builder_add_from_file (builder, filename, &error)) {
g_error ("%s", error->message);
g_error_free (error);
return NULL;
}
um = g_new0 (UmPasswordDialog, 1);
um->action_label = (GtkWidget *) gtk_builder_get_object (builder, "action-label");
widget = (GtkWidget *) gtk_builder_get_object (builder, "action-combo");
g_signal_connect (widget, "changed",
G_CALLBACK (action_changed), um);
um->action_combo = widget;
widget = (GtkWidget *) gtk_builder_get_object (builder, "dialog");
g_signal_connect (widget, "delete-event",
G_CALLBACK (gtk_widget_hide_on_delete), NULL);
um->dialog = widget;
um->user_icon = (GtkWidget *) gtk_builder_get_object (builder, "user-icon");
um->user_name = (GtkWidget *) gtk_builder_get_object (builder, "user-name");
widget = (GtkWidget *) gtk_builder_get_object (builder, "cancel-button");
g_signal_connect (widget, "clicked",
G_CALLBACK (cancel_password_dialog), um);
widget = (GtkWidget *) gtk_builder_get_object (builder, "ok-button");
g_signal_connect (widget, "clicked",
G_CALLBACK (accept_password_dialog), um);
gtk_widget_grab_default (widget);
um->ok_button = widget;
widget = (GtkWidget *) gtk_builder_get_object (builder, "password-normal-strength-hints-label");
old_label = gtk_label_get_label (GTK_LABEL (widget));
if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity"))
label = g_strdup_printf ("<a href=\"%s\">%s</a>",
"help:ubuntu-help/user-goodpassword",
old_label);
else
label = g_strdup_printf ("<a href=\"%s\">%s</a>",
"help:gnome-help/user-goodpassword",
old_label);
gtk_label_set_markup (GTK_LABEL (widget), label);
g_free (label);
widget = (GtkWidget *) gtk_builder_get_object (builder, "show-password-checkbutton");
g_signal_connect (widget, "toggled",
G_CALLBACK (show_password_toggled), um);
um->show_password_button = widget;
widget = (GtkWidget *) gtk_builder_get_object (builder, "password-entry");
g_signal_connect (widget, "notify::text",
G_CALLBACK (password_entry_changed), um);
g_signal_connect_after (widget, "focus-out-event",
G_CALLBACK (password_entry_focus_out), um);
gtk_entry_set_visibility (GTK_ENTRY (widget), FALSE);
g_signal_connect (widget, "icon-press",
G_CALLBACK (activate_icon), um);
g_signal_connect (widget, "populate-popup",
G_CALLBACK (populate_menu), um);
um->password_entry = widget;
widget = (GtkWidget *) gtk_builder_get_object (builder, "old-password-entry");
g_signal_connect_after (widget, "focus-out-event",
G_CALLBACK (old_password_entry_focus_out), um);
g_signal_connect (widget, "notify::text",
G_CALLBACK (old_password_entry_changed), um);
g_signal_connect (widget, "activate",
G_CALLBACK (old_password_entry_activate), um);
um->old_password_entry = widget;
um->old_password_label = (GtkWidget *) gtk_builder_get_object (builder, "old-password-label");
widget = (GtkWidget *) gtk_builder_get_object (builder, "verify-entry");
g_signal_connect (widget, "notify::text",
G_CALLBACK (verify_entry_changed), um);
g_signal_connect_after (widget, "focus-out-event",
G_CALLBACK (verify_entry_focus_out), um);
um->verify_entry = widget;
len = 0;
len = MAX (len, strlen (C_("Password strength", "Too short")));
len = MAX (len, strlen (C_("Password strength", "Weak")));
len = MAX (len, strlen (C_("Password strength", "Fair")));
len = MAX (len, strlen (C_("Password strength", "Good")));
len = MAX (len, strlen (C_("Password strength", "Strong")));
len += 2;
widget = (GtkWidget *) gtk_builder_get_object (builder, "strength-indicator-label");
gtk_label_set_width_chars (GTK_LABEL (widget), len);
um->normal_hint_entry = (GtkWidget *) gtk_builder_get_object (builder, "normal-hint-entry");
/* Label size hack.
* This only sort-of works because the dialog is non-resizable.
*/
widget = (GtkWidget *)gtk_builder_get_object (builder, "password-normal-hint-description-label");
g_signal_connect (um->normal_hint_entry, "size-allocate",
G_CALLBACK (entry_size_changed), widget);
um->normal_hint_label = widget;
if (!is_gdm_running ()) {
widget = (GtkWidget *) gtk_builder_get_object (builder, "password-normal-hint-label");
gtk_widget_hide (widget);
gtk_widget_hide (um->normal_hint_entry);
gtk_widget_hide (um->normal_hint_label);
}
um->strength_indicator = (GtkWidget *) gtk_builder_get_object (builder, "strength-indicator");
um->strength_indicator_label = (GtkWidget *) gtk_builder_get_object (builder, "strength-indicator-label");
g_object_unref (builder);
return um;
}
void
um_password_dialog_free (UmPasswordDialog *um)
{
gtk_widget_destroy (um->dialog);
if (um->user)
g_object_unref (um->user);
if (um->passwd_handler)
passwd_destroy (um->passwd_handler);
g_free (um);
}
static gboolean
visible_func (GtkTreeModel *model,
GtkTreeIter *iter,
UmPasswordDialog *um)
{
if (um->user) {
gint mode;
gboolean locked = um_user_get_locked (um->user);
gtk_tree_model_get (model, iter, 1, &mode, -1);
if (mode == 1 && !is_gdm_running ())
return FALSE;
if (mode == 2 && um->using_ecryptfs)
return FALSE;
if (mode == 3 && locked)
return FALSE;
if (mode == 4 && !locked)
return FALSE;
return TRUE;
}
return TRUE;
}
void
um_password_dialog_set_user (UmPasswordDialog *um,
UmUser *user)
{
GdkPixbuf *pixbuf;
GtkTreeModel *model;
if (um->user) {
g_object_unref (um->user);
um->user = NULL;
}
if (user) {
um->user = g_object_ref (user);
um->using_ecryptfs = is_using_ecryptfs (um_user_get_user_name (user));
pixbuf = um_user_render_icon (user, FALSE, 48);
gtk_image_set_from_pixbuf (GTK_IMAGE (um->user_icon), pixbuf);
g_object_unref (pixbuf);
gtk_label_set_label (GTK_LABEL (um->user_name),
um_user_get_real_name (user));
gtk_entry_set_text (GTK_ENTRY (um->password_entry), "");
gtk_entry_set_text (GTK_ENTRY (um->verify_entry), "");
gtk_entry_set_text (GTK_ENTRY (um->normal_hint_entry), "");
gtk_entry_set_text (GTK_ENTRY (um->old_password_entry), "");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (um->show_password_button), FALSE);
if (um_user_get_uid (um->user) == getuid () &&
um_user_get_password_mode (um->user) == UM_PASSWORD_MODE_REGULAR) {
gtk_widget_show (um->old_password_label);
gtk_widget_show (um->old_password_entry);
um->old_password_ok = FALSE;
}
else {
gtk_widget_hide (um->old_password_label);
gtk_widget_hide (um->old_password_entry);
um->old_password_ok = TRUE;
}
if (um_user_get_uid (um->user) == getuid()) {
if (um->passwd_handler != NULL)
passwd_destroy (um->passwd_handler);
um->passwd_handler = passwd_init ();
}
}
model = gtk_combo_box_get_model (GTK_COMBO_BOX (um->action_combo));
if (!GTK_IS_TREE_MODEL_FILTER (model)) {
model = gtk_tree_model_filter_new (model, NULL);
gtk_combo_box_set_model (GTK_COMBO_BOX (um->action_combo), model);
gtk_tree_model_filter_set_visible_func (GTK_TREE_MODEL_FILTER (model),
(GtkTreeModelFilterVisibleFunc) visible_func,
um, NULL);
}
gtk_tree_model_filter_refilter (GTK_TREE_MODEL_FILTER (model));
gtk_combo_box_set_active (GTK_COMBO_BOX (um->action_combo), 0);
}
void
um_password_dialog_show (UmPasswordDialog *um,
GtkWindow *parent)
{
gtk_window_set_transient_for (GTK_WINDOW (um->dialog), parent);
gtk_window_present (GTK_WINDOW (um->dialog));
if (um->old_password_ok == FALSE)
gtk_widget_grab_focus (um->old_password_entry);
else
gtk_widget_grab_focus (um->password_entry);
}
|
345 | ./cinnamon-control-center/panels/user-accounts/um-editable-combo.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright 2009-2010 Red Hat, Inc,
*
* 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.
*
* Written by: Matthias Clasen <[email protected]>
*/
#include <gdk/gdkkeysyms.h>
#include "um-editable-combo.h"
#define EMPTY_TEXT "\xe2\x80\x94"
struct _UmEditableComboPrivate {
GtkNotebook *notebook;
GtkLabel *label;
GtkButton *button;
GtkComboBox *combo;
GtkWidget *toplevel;
gint active;
gint editable;
gint text_column;
};
#define UM_EDITABLE_COMBO_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), UM_TYPE_EDITABLE_COMBO, UmEditableComboPrivate))
enum {
PROP_0,
PROP_EDITABLE,
PROP_MODEL,
PROP_TEXT_COLUMN
};
enum {
EDITING_DONE,
ACTIVATE,
LAST_SIGNAL
};
static guint signals [LAST_SIGNAL] = { 0, };
G_DEFINE_TYPE (UmEditableCombo, um_editable_combo, GTK_TYPE_ALIGNMENT);
void
um_editable_combo_set_editable (UmEditableCombo *combo,
gboolean editable)
{
UmEditableComboPrivate *priv;
priv = combo->priv;
if (priv->editable != editable) {
priv->editable = editable;
gtk_notebook_set_current_page (priv->notebook, editable ? 1 : 0);
g_object_notify (G_OBJECT (combo), "editable");
}
}
gboolean
um_editable_combo_get_editable (UmEditableCombo *combo)
{
return combo->priv->editable;
}
void
um_editable_combo_set_model (UmEditableCombo *combo,
GtkTreeModel *model)
{
gtk_combo_box_set_model (combo->priv->combo, model);
g_object_notify (G_OBJECT (combo), "model");
}
GtkTreeModel *
um_editable_combo_get_model (UmEditableCombo *combo)
{
return gtk_combo_box_get_model (combo->priv->combo);
}
void
um_editable_combo_set_text_column (UmEditableCombo *combo,
gint text_column)
{
UmEditableComboPrivate *priv = combo->priv;
GList *cells;
if (priv->text_column == text_column)
return;
priv->text_column = text_column;
cells = gtk_cell_layout_get_cells (GTK_CELL_LAYOUT (priv->combo));
gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (priv->combo),
cells->data,
"text", text_column,
NULL);
g_list_free (cells);
g_object_notify (G_OBJECT (combo), "text-column");
}
gint
um_editable_combo_get_text_column (UmEditableCombo *combo)
{
return combo->priv->text_column;
}
void
um_editable_combo_set_active (UmEditableCombo *combo,
gint active)
{
GtkTreeModel *model;
GtkTreePath *path;
GtkTreeIter iter;
if (active == -1)
um_editable_combo_set_active_iter (combo, NULL);
else {
model = gtk_combo_box_get_model (combo->priv->combo);
path = gtk_tree_path_new_from_indices (active, -1);
gtk_tree_model_get_iter (model, &iter, path);
gtk_tree_path_free (path);
um_editable_combo_set_active_iter (combo, &iter);
}
}
void
um_editable_combo_set_active_iter (UmEditableCombo *combo,
GtkTreeIter *iter)
{
UmEditableComboPrivate *priv = combo->priv;
GtkWidget *label;
gchar *text;
GtkTreeModel *model;
gtk_combo_box_set_active_iter (priv->combo, iter);
priv->active = gtk_combo_box_get_active (priv->combo);
if (priv->text_column == -1)
return;
if (iter) {
model = gtk_combo_box_get_model (priv->combo);
gtk_tree_model_get (model, iter, priv->text_column, &text, -1);
}
else {
text = g_strdup (EMPTY_TEXT);
}
gtk_label_set_text (priv->label, text);
label = gtk_bin_get_child ((GtkBin*)priv->button);
gtk_label_set_text (GTK_LABEL (label), text);
g_free (text);
}
gboolean
um_editable_combo_get_active_iter (UmEditableCombo *combo,
GtkTreeIter *iter)
{
return gtk_combo_box_get_active_iter (combo->priv->combo, iter);
}
gint
um_editable_combo_get_active (UmEditableCombo *combo)
{
return combo->priv->active;
}
static void
um_editable_combo_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
UmEditableCombo *combo = UM_EDITABLE_COMBO (object);
switch (prop_id) {
case PROP_EDITABLE:
um_editable_combo_set_editable (combo, g_value_get_boolean (value));
break;
case PROP_MODEL:
um_editable_combo_set_model (combo, g_value_get_object (value));
break;
case PROP_TEXT_COLUMN:
um_editable_combo_set_text_column (combo, g_value_get_int (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
um_editable_combo_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
UmEditableCombo *combo = UM_EDITABLE_COMBO (object);
switch (prop_id) {
case PROP_EDITABLE:
g_value_set_boolean (value,
um_editable_combo_get_editable (combo));
break;
case PROP_MODEL:
g_value_set_object (value,
um_editable_combo_get_model (combo));
break;
case PROP_TEXT_COLUMN:
g_value_set_int (value,
um_editable_combo_get_text_column (combo));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void um_editable_combo_activate (UmEditableCombo *combo);
static void
um_editable_combo_class_init (UmEditableComboClass *class)
{
GObjectClass *object_class;
GtkWidgetClass *widget_class;
object_class = G_OBJECT_CLASS (class);
widget_class = GTK_WIDGET_CLASS (class);
object_class->set_property = um_editable_combo_set_property;
object_class->get_property = um_editable_combo_get_property;
signals[EDITING_DONE] =
g_signal_new ("editing-done",
G_TYPE_FROM_CLASS (class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (UmEditableComboClass, editing_done),
NULL, NULL,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
signals[ACTIVATE] =
g_signal_new ("activate",
G_TYPE_FROM_CLASS (class),
G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
G_STRUCT_OFFSET (UmEditableComboClass, activate),
NULL, NULL,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
widget_class->activate_signal = signals[ACTIVATE];
class->activate = um_editable_combo_activate;
g_object_class_install_property (object_class, PROP_MODEL,
g_param_spec_object ("model",
"Model", "The options to present in the combobox",
GTK_TYPE_TREE_MODEL,
G_PARAM_READWRITE));
g_object_class_install_property (object_class, PROP_TEXT_COLUMN,
g_param_spec_int ("text-column",
"Text Column", "The model column that contains the displayable text",
-1, G_MAXINT, -1,
G_PARAM_READWRITE));
g_object_class_install_property (object_class, PROP_EDITABLE,
g_param_spec_boolean ("editable",
"Editable", "Whether the text can be edited",
FALSE,
G_PARAM_READWRITE));
g_type_class_add_private (class, sizeof (UmEditableComboPrivate));
}
static void
start_editing (UmEditableCombo *combo)
{
gtk_notebook_set_current_page (combo->priv->notebook, 2);
gtk_combo_box_popup (combo->priv->combo);
}
static void
stop_editing (UmEditableCombo *combo)
{
um_editable_combo_set_active (combo,
gtk_combo_box_get_active (combo->priv->combo));
gtk_notebook_set_current_page (combo->priv->notebook, 1);
g_signal_emit (combo, signals[EDITING_DONE], 0);
}
static void
cancel_editing (UmEditableCombo *combo)
{
gtk_combo_box_set_active (combo->priv->combo,
um_editable_combo_get_active (combo));
gtk_notebook_set_current_page (combo->priv->notebook, 1);
}
static void
um_editable_combo_activate (UmEditableCombo *combo)
{
if (combo->priv->editable) {
gtk_notebook_set_current_page (combo->priv->notebook, 2);
gtk_widget_grab_focus (GTK_WIDGET (combo->priv->combo));
}
}
static void
button_clicked (GtkWidget *widget,
UmEditableCombo *combo)
{
if (combo->priv->editable)
start_editing (combo);
}
static void
combo_changed (GtkWidget *widget,
UmEditableCombo *combo)
{
if (combo->priv->editable)
stop_editing (combo);
}
static gboolean
combo_key_press (GtkWidget *widget,
GdkEventKey *event,
UmEditableCombo *combo)
{
if (event->keyval == GDK_KEY_Escape) {
cancel_editing (combo);
return TRUE;
}
return FALSE;
}
static void
focus_moved (GtkWindow *window,
GtkWidget *widget,
UmEditableCombo *combo)
{
if (gtk_notebook_get_current_page (combo->priv->notebook) == 2 &&
(!widget || !gtk_widget_is_ancestor (widget, (GtkWidget *)combo)))
stop_editing (combo);
}
static void
combo_hierarchy_changed (GtkWidget *widget,
GtkWidget *previous_toplevel,
UmEditableCombo *combo)
{
UmEditableComboPrivate *priv;
GtkWidget *toplevel;
priv = combo->priv;
toplevel = gtk_widget_get_toplevel (widget);
if (priv->toplevel != toplevel) {
if (priv->toplevel)
g_signal_handlers_disconnect_by_func (priv->toplevel,
focus_moved, combo);
if (GTK_IS_WINDOW (toplevel))
priv->toplevel = toplevel;
else
priv->toplevel = NULL;
if (priv->toplevel)
g_signal_connect (priv->toplevel, "set-focus",
G_CALLBACK (focus_moved), combo);
}
}
static void
update_button_padding (GtkWidget *widget,
GtkAllocation *allocation,
UmEditableCombo *combo)
{
UmEditableComboPrivate *priv = combo->priv;
GtkAllocation parent_allocation;
gint offset;
gint pad;
gtk_widget_get_allocation (gtk_widget_get_parent (widget), &parent_allocation);
offset = allocation->x - parent_allocation.x;
gtk_misc_get_padding (GTK_MISC (priv->label), &pad, NULL);
if (offset != pad)
gtk_misc_set_padding (GTK_MISC (priv->label), offset, 0);
}
static void
um_editable_combo_init (UmEditableCombo *combo)
{
UmEditableComboPrivate *priv;
GtkCellRenderer *cell;
priv = combo->priv = UM_EDITABLE_COMBO_GET_PRIVATE (combo);
priv->active = -1;
priv->text_column = -1;
priv->notebook = (GtkNotebook*)gtk_notebook_new ();
gtk_notebook_set_show_tabs (priv->notebook, FALSE);
gtk_notebook_set_show_border (priv->notebook, FALSE);
priv->label = (GtkLabel*)gtk_label_new ("");
gtk_misc_set_alignment (GTK_MISC (priv->label), 0.0, 0.5);
gtk_notebook_append_page (priv->notebook, (GtkWidget*)priv->label, NULL);
priv->button = (GtkButton*)gtk_button_new_with_label ("");
gtk_widget_set_receives_default ((GtkWidget*)priv->button, TRUE);
gtk_button_set_relief (priv->button, GTK_RELIEF_NONE);
gtk_button_set_alignment (priv->button, 0.0, 0.5);
gtk_notebook_append_page (priv->notebook, (GtkWidget*)priv->button, NULL);
g_signal_connect (priv->button, "clicked", G_CALLBACK (button_clicked), combo);
priv->combo = (GtkComboBox*)gtk_combo_box_new ();
cell = gtk_cell_renderer_text_new ();
gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (priv->combo), cell, TRUE);
gtk_notebook_append_page (priv->notebook, (GtkWidget*)priv->combo, NULL);
g_signal_connect (priv->combo, "changed", G_CALLBACK (combo_changed), combo);
g_signal_connect (priv->combo, "key-press-event", G_CALLBACK (combo_key_press), combo);
g_signal_connect (gtk_bin_get_child (GTK_BIN (priv->button)), "size-allocate", G_CALLBACK (update_button_padding), combo);
gtk_container_add (GTK_CONTAINER (combo), (GtkWidget*)priv->notebook);
gtk_widget_show ((GtkWidget*)priv->notebook);
gtk_widget_show ((GtkWidget*)priv->label);
gtk_widget_show ((GtkWidget*)priv->button);
gtk_widget_show ((GtkWidget*)priv->combo);
gtk_notebook_set_current_page (priv->notebook, 0);
/* ugly hack to catch the combo box losing focus */
g_signal_connect (combo, "hierarchy-changed",
G_CALLBACK (combo_hierarchy_changed), combo);
}
GtkWidget *
um_editable_combo_new (void)
{
return (GtkWidget *) g_object_new (UM_TYPE_EDITABLE_COMBO, NULL);
}
|
346 | ./cinnamon-control-center/panels/user-accounts/pw-utils.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright 2012 Red Hat, Inc,
*
* 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.
*
* Written by: Matthias Clasen <[email protected]>
*/
#include "config.h"
#include "pw-utils.h"
#include <glib.h>
#include <glib/gi18n-lib.h>
gdouble
pw_strength (const gchar *password,
const gchar *old_password,
const gchar *username,
const gchar **hint,
const gchar **long_hint)
{
gint rv = 0;
gdouble level = 0.0;
gdouble strength = 0.0;
void *auxerror;
if (g_strcmp0(password, old_password) == 0) {
*hint = C_("Password strength", "Duplicate");
*long_hint = _("Your new password is the same as the old one");
level=0.0;
goto out;
} else if (strlen (password) < MIN_PW_LENGTH) {
*hint = C_("Password strength", "Too short");
*long_hint = g_strdup_printf(_("Your new password needs to be at least %d characters long"), MIN_PW_LENGTH);
level=0.0;
goto out;
} else {
level=1.0;
*hint = C_("Password strength", "OK");
*long_hint = NULL;
goto out;
}
out:
return level;
}
|
347 | ./cinnamon-control-center/panels/user-accounts/run-passwd.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/* run-passwd.c: this file is part of users-admin, a cinnamon-system-tools frontend
* for user administration.
*
* Copyright (C) 2002 Diego Gonzalez
* Copyright (C) 2006 Johannes H. Jensen
* Copyright (C) 2010 Milan Bouchet-Valat
*
* Written by: Diego Gonzalez <[email protected]>
* Modified by: Johannes H. Jensen <[email protected]>,
* Milan Bouchet-Valat <[email protected]>.
*
* 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, 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.
*
* Most of this code originally comes from cinnamon-about-me-password.c,
* from cinnamon-control-center.
*/
#include <config.h>
#include <glib/gi18n-lib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/wait.h>
#if __sun
#include <sys/types.h>
#include <signal.h>
#endif
#include "run-passwd.h"
/* Passwd states */
typedef enum {
PASSWD_STATE_NONE, /* Passwd is not asking for anything */
PASSWD_STATE_AUTH, /* Passwd is asking for our current password */
PASSWD_STATE_NEW, /* Passwd is asking for our new password */
PASSWD_STATE_RETYPE, /* Passwd is asking for our retyped new password */
PASSWD_STATE_DONE, /* Passwd succeeded but has not yet exited */
PASSWD_STATE_ERR /* Passwd reported an error but has not yet exited */
} PasswdState;
struct PasswdHandler {
const char *current_password;
const char *new_password;
/* Communication with the passwd program */
GPid backend_pid;
GIOChannel *backend_stdin;
GIOChannel *backend_stdout;
GQueue *backend_stdin_queue; /* Write queue to backend_stdin */
/* GMainLoop IDs */
guint backend_child_watch_id; /* g_child_watch_add (PID) */
guint backend_stdout_watch_id; /* g_io_add_watch (stdout) */
/* State of the passwd program */
PasswdState backend_state;
gboolean changing_password;
PasswdCallback auth_cb;
gpointer auth_cb_data;
PasswdCallback chpasswd_cb;
gpointer chpasswd_cb_data;
};
/* Buffer size for backend output */
#define BUFSIZE 64
static GQuark
passwd_error_quark (void)
{
static GQuark q = 0;
if (q == 0) {
q = g_quark_from_static_string("passwd_error");
}
return q;
}
/* Error handling */
#define PASSWD_ERROR (passwd_error_quark ())
static void
stop_passwd (PasswdHandler *passwd_handler);
static void
free_passwd_resources (PasswdHandler *passwd_handler);
static gboolean
io_watch_stdout (GIOChannel *source, GIOCondition condition, PasswdHandler *passwd_handler);
/*
* Spawning and closing of backend {{
*/
/* Child watcher */
static void
child_watch_cb (GPid pid, gint status, PasswdHandler *passwd_handler)
{
if (WIFEXITED (status)) {
if (WEXITSTATUS (status) >= 255) {
g_warning ("Child exited unexpectedly");
}
if (WEXITSTATUS (status) == 0) {
if (passwd_handler->backend_state == PASSWD_STATE_RETYPE) {
passwd_handler->backend_state = PASSWD_STATE_DONE;
if (passwd_handler->chpasswd_cb)
passwd_handler->chpasswd_cb (passwd_handler,
NULL,
passwd_handler->auth_cb_data);
}
}
}
free_passwd_resources (passwd_handler);
}
static void
ignore_sigpipe (gpointer data)
{
signal (SIGPIPE, SIG_IGN);
}
/* Spawn passwd backend
* Returns: TRUE on success, FALSE otherwise and sets error appropriately */
static gboolean
spawn_passwd (PasswdHandler *passwd_handler, GError **error)
{
gchar *argv[2];
gchar **envp;
gint my_stdin, my_stdout, my_stderr;
argv[0] = "/usr/bin/passwd"; /* Is it safe to rely on a hard-coded path? */
argv[1] = NULL;
envp = g_get_environ ();
envp = g_environ_setenv (envp, "LC_ALL", "C", TRUE);
if (!g_spawn_async_with_pipes (NULL, /* Working directory */
argv, /* Argument vector */
envp, /* Environment */
G_SPAWN_DO_NOT_REAP_CHILD, /* Flags */
ignore_sigpipe, /* Child setup */
NULL, /* Data to child setup */
&passwd_handler->backend_pid, /* PID */
&my_stdin, /* Stdin */
&my_stdout, /* Stdout */
&my_stderr, /* Stderr */
error)) { /* GError */
/* An error occured */
free_passwd_resources (passwd_handler);
g_strfreev (envp);
return FALSE;
}
g_strfreev (envp);
/* 2>&1 */
if (dup2 (my_stderr, my_stdout) == -1) {
/* Failed! */
g_set_error_literal (error,
PASSWD_ERROR,
PASSWD_ERROR_BACKEND,
strerror (errno));
/* Clean up */
stop_passwd (passwd_handler);
return FALSE;
}
/* Open IO Channels */
passwd_handler->backend_stdin = g_io_channel_unix_new (my_stdin);
passwd_handler->backend_stdout = g_io_channel_unix_new (my_stdout);
/* Set raw encoding */
/* Set nonblocking mode */
if (g_io_channel_set_encoding (passwd_handler->backend_stdin, NULL, error) != G_IO_STATUS_NORMAL ||
g_io_channel_set_encoding (passwd_handler->backend_stdout, NULL, error) != G_IO_STATUS_NORMAL ||
g_io_channel_set_flags (passwd_handler->backend_stdin, G_IO_FLAG_NONBLOCK, error) != G_IO_STATUS_NORMAL ||
g_io_channel_set_flags (passwd_handler->backend_stdout, G_IO_FLAG_NONBLOCK, error) != G_IO_STATUS_NORMAL ) {
/* Clean up */
stop_passwd (passwd_handler);
return FALSE;
}
/* Turn off buffering */
g_io_channel_set_buffered (passwd_handler->backend_stdin, FALSE);
g_io_channel_set_buffered (passwd_handler->backend_stdout, FALSE);
/* Add IO Channel watcher */
passwd_handler->backend_stdout_watch_id = g_io_add_watch (passwd_handler->backend_stdout,
G_IO_IN | G_IO_PRI,
(GIOFunc) io_watch_stdout, passwd_handler);
/* Add child watcher */
passwd_handler->backend_child_watch_id = g_child_watch_add (passwd_handler->backend_pid, (GChildWatchFunc) child_watch_cb, passwd_handler);
/* Success! */
return TRUE;
}
/* Stop passwd backend */
static void
stop_passwd (PasswdHandler *passwd_handler)
{
/* This is the standard way of returning from the dialog with passwd.
* If we return this way we can safely kill passwd as it has completed
* its task.
*/
if (passwd_handler->backend_pid != -1) {
kill (passwd_handler->backend_pid, 9);
}
/* We must run free_passwd_resources here and not let our child
* watcher do it, since it will access invalid memory after the
* dialog has been closed and cleaned up.
*
* If we had more than a single thread we'd need to remove
* the child watch before trying to kill the child.
*/
free_passwd_resources (passwd_handler);
}
/* Clean up passwd resources */
static void
free_passwd_resources (PasswdHandler *passwd_handler)
{
GError *error = NULL;
/* Remove the child watcher */
if (passwd_handler->backend_child_watch_id != 0) {
g_source_remove (passwd_handler->backend_child_watch_id);
passwd_handler->backend_child_watch_id = 0;
}
/* Close IO channels (internal file descriptors are automatically closed) */
if (passwd_handler->backend_stdin != NULL) {
if (g_io_channel_shutdown (passwd_handler->backend_stdin, TRUE, &error) != G_IO_STATUS_NORMAL) {
g_warning ("Could not shutdown backend_stdin IO channel: %s", error->message);
g_error_free (error);
error = NULL;
}
g_io_channel_unref (passwd_handler->backend_stdin);
passwd_handler->backend_stdin = NULL;
}
if (passwd_handler->backend_stdout != NULL) {
if (g_io_channel_shutdown (passwd_handler->backend_stdout, TRUE, &error) != G_IO_STATUS_NORMAL) {
g_warning ("Could not shutdown backend_stdout IO channel: %s", error->message);
g_error_free (error);
error = NULL;
}
g_io_channel_unref (passwd_handler->backend_stdout);
passwd_handler->backend_stdout = NULL;
}
/* Remove IO watcher */
if (passwd_handler->backend_stdout_watch_id != 0) {
g_source_remove (passwd_handler->backend_stdout_watch_id);
passwd_handler->backend_stdout_watch_id = 0;
}
/* Close PID */
if (passwd_handler->backend_pid != -1) {
g_spawn_close_pid (passwd_handler->backend_pid);
passwd_handler->backend_pid = -1;
}
/* Clear backend state */
passwd_handler->backend_state = PASSWD_STATE_NONE;
}
/*
* }} Spawning and closing of backend
*/
/*
* Backend communication code {{
*/
/* Write the first element of queue through channel */
static void
io_queue_pop (GQueue *queue, GIOChannel *channel)
{
gchar *buf;
gsize bytes_written;
GError *error = NULL;
buf = g_queue_pop_head (queue);
if (buf != NULL) {
if (g_io_channel_write_chars (channel, buf, -1, &bytes_written, &error) != G_IO_STATUS_NORMAL) {
g_warning ("Could not write queue element \"%s\" to channel: %s", buf, error->message);
g_error_free (error);
}
/* Ensure passwords are cleared from memory */
memset (buf, 0, strlen (buf));
g_free (buf);
}
}
/* Goes through the argument list, checking if one of them occurs in str
* Returns: TRUE as soon as an element is found to match, FALSE otherwise */
static gboolean
is_string_complete (gchar *str, ...)
{
va_list ap;
gchar *arg;
if (strlen (str) == 0) {
return FALSE;
}
va_start (ap, str);
while ((arg = va_arg (ap, char *)) != NULL) {
if (strstr (str, arg) != NULL) {
va_end (ap);
return TRUE;
}
}
va_end (ap);
return FALSE;
}
/*
* IO watcher for stdout, called whenever there is data to read from the backend.
* This is where most of the actual IO handling happens.
*/
static gboolean
io_watch_stdout (GIOChannel *source, GIOCondition condition, PasswdHandler *passwd_handler)
{
static GString *str = NULL; /* Persistent buffer */
gchar buf[BUFSIZE]; /* Temporary buffer */
gsize bytes_read;
GError *gio_error = NULL; /* Error returned by functions */
GError *error = NULL; /* Error sent to callbacks */
gboolean reinit = FALSE;
/* Initialize buffer */
if (str == NULL) {
str = g_string_new ("");
}
if (g_io_channel_read_chars (source, buf, BUFSIZE, &bytes_read, &gio_error)
!= G_IO_STATUS_NORMAL) {
g_warning ("IO Channel read error: %s", gio_error->message);
g_error_free (gio_error);
return TRUE;
}
str = g_string_append_len (str, buf, bytes_read);
/* In which state is the backend? */
switch (passwd_handler->backend_state) {
case PASSWD_STATE_AUTH:
/* Passwd is asking for our current password */
if (is_string_complete (str->str, "assword: ", "failure", "wrong", "error", NULL)) {
if (strstr (str->str, "assword: ") != NULL && strstr (str->str, "incorrect") == NULL) {
/* Authentication successful */
passwd_handler->backend_state = PASSWD_STATE_NEW;
/* Trigger callback to update authentication status */
if (passwd_handler->auth_cb)
passwd_handler->auth_cb (passwd_handler,
NULL,
passwd_handler->auth_cb_data);
} else {
/* Authentication failed */
error = g_error_new_literal (PASSWD_ERROR, PASSWD_ERROR_AUTH_FAILED,
_("Authentication failed"));
passwd_handler->changing_password = FALSE;
/* This error can happen both while authenticating or while changing password:
* if chpasswd_cb is set, this means we're already changing password */
if (passwd_handler->chpasswd_cb)
passwd_handler->chpasswd_cb (passwd_handler,
error,
passwd_handler->auth_cb_data);
else if (passwd_handler->auth_cb)
passwd_handler->auth_cb (passwd_handler,
error,
passwd_handler->auth_cb_data);
g_error_free (error);
}
reinit = TRUE;
}
break;
case PASSWD_STATE_NEW:
/* Passwd is asking for our new password */
if (is_string_complete (str->str, "assword: ", NULL)) {
/* Advance to next state */
passwd_handler->backend_state = PASSWD_STATE_RETYPE;
/* Pop retyped password from queue and into IO channel */
io_queue_pop (passwd_handler->backend_stdin_queue, passwd_handler->backend_stdin);
reinit = TRUE;
}
break;
case PASSWD_STATE_RETYPE:
/* Passwd is asking for our retyped new password */
if (is_string_complete (str->str,
"successfully",
"short",
"longer",
"palindrome",
"dictionary",
"simple",
"simplistic",
"similar",
"case",
"different",
"wrapped",
"recovered",
"recent",
"unchanged",
"match",
"1 numeric or special",
"failure",
"DIFFERENT",
"BAD PASSWORD",
NULL)) {
if (strstr (str->str, "successfully") != NULL) {
/* Hooray! */
passwd_handler->backend_state = PASSWD_STATE_DONE;
/* Trigger callback to update status */
if (passwd_handler->chpasswd_cb)
passwd_handler->chpasswd_cb (passwd_handler,
NULL,
passwd_handler->chpasswd_cb_data);
}
else {
/* Ohnoes! */
if (strstr (str->str, "recovered") != NULL) {
/* What does this indicate?
* "Authentication information cannot be recovered?" from libpam? */
error = g_error_new_literal (PASSWD_ERROR, PASSWD_ERROR_UNKNOWN,
str->str);
} else if (strstr (str->str, "short") != NULL ||
strstr (str->str, "longer") != NULL) {
error = g_error_new (PASSWD_ERROR, PASSWD_ERROR_REJECTED,
_("The new password is too short"));
} else if (strstr (str->str, "palindrome") != NULL ||
strstr (str->str, "simple") != NULL ||
strstr (str->str, "simplistic") != NULL ||
strstr (str->str, "dictionary") != NULL) {
error = g_error_new (PASSWD_ERROR, PASSWD_ERROR_REJECTED,
_("The new password is too simple"));
} else if (strstr (str->str, "similar") != NULL ||
strstr (str->str, "different") != NULL ||
strstr (str->str, "case") != NULL ||
strstr (str->str, "wrapped") != NULL) {
error = g_error_new (PASSWD_ERROR, PASSWD_ERROR_REJECTED,
_("The old and new passwords are too similar"));
} else if (strstr (str->str, "recent") != NULL) {
error = g_error_new (PASSWD_ERROR, PASSWD_ERROR_REJECTED,
_("The new password has already been used recently."));
} else if (strstr (str->str, "1 numeric or special") != NULL) {
error = g_error_new (PASSWD_ERROR, PASSWD_ERROR_REJECTED,
_("The new password must contain numeric or special characters"));
} else if (strstr (str->str, "unchanged") != NULL ||
strstr (str->str, "match") != NULL) {
error = g_error_new (PASSWD_ERROR, PASSWD_ERROR_REJECTED,
_("The old and new passwords are the same"));
} else if (strstr (str->str, "failure") != NULL) {
/* Authentication failure */
error = g_error_new (PASSWD_ERROR, PASSWD_ERROR_AUTH_FAILED,
_("Your password has been changed since you initially authenticated!"));
}
else if (strstr (str->str, "DIFFERENT")) {
error = g_error_new (PASSWD_ERROR, PASSWD_ERROR_REJECTED,
_("The new password does not contain enough different characters"));
}
else {
error = g_error_new (PASSWD_ERROR, PASSWD_ERROR_UNKNOWN,
_("Unknown error"));
}
/* At this point, passwd might have exited, in which case
* child_watch_cb should clean up for us and remove this watcher.
* On some error conditions though, passwd just re-prompts us
* for our new password. */
passwd_handler->backend_state = PASSWD_STATE_ERR;
passwd_handler->changing_password = FALSE;
/* Trigger callback to update status */
if (passwd_handler->chpasswd_cb)
passwd_handler->chpasswd_cb (passwd_handler,
error,
passwd_handler->chpasswd_cb_data);
g_error_free (error);
}
reinit = TRUE;
/* child_watch_cb should clean up for us now */
}
break;
case PASSWD_STATE_NONE:
/* Passwd is not asking for anything yet */
if (is_string_complete (str->str, "assword: ", NULL)) {
/* If the user does not have a password set,
* passwd will immediately ask for the new password,
* so skip the AUTH phase */
if (is_string_complete (str->str, "new", "New", NULL)) {
gchar *pw;
passwd_handler->backend_state = PASSWD_STATE_NEW;
/* since passwd didn't ask for our old password
* in this case, simply remove it from the queue */
pw = g_queue_pop_head (passwd_handler->backend_stdin_queue);
g_free (pw);
/* Pop the IO queue, i.e. send new password */
io_queue_pop (passwd_handler->backend_stdin_queue, passwd_handler->backend_stdin);
} else {
passwd_handler->backend_state = PASSWD_STATE_AUTH;
/* Pop the IO queue, i.e. send current password */
io_queue_pop (passwd_handler->backend_stdin_queue, passwd_handler->backend_stdin);
}
reinit = TRUE;
}
break;
default:
/* Passwd has returned an error */
reinit = TRUE;
break;
}
if (reinit) {
g_string_free (str, TRUE);
str = NULL;
}
/* Continue calling us */
return TRUE;
}
/*
* }} Backend communication code
*/
/* Adds the current password to the IO queue */
static void
authenticate (PasswdHandler *passwd_handler)
{
gchar *s;
s = g_strdup_printf ("%s\n", passwd_handler->current_password);
g_queue_push_tail (passwd_handler->backend_stdin_queue, s);
}
/* Adds the new password twice to the IO queue */
static void
update_password (PasswdHandler *passwd_handler)
{
gchar *s;
s = g_strdup_printf ("%s\n", passwd_handler->new_password);
g_queue_push_tail (passwd_handler->backend_stdin_queue, s);
/* We need to allocate new space because io_queue_pop() g_free()s
* every element of the queue after it's done */
g_queue_push_tail (passwd_handler->backend_stdin_queue, g_strdup (s));
}
PasswdHandler *
passwd_init (void)
{
PasswdHandler *passwd_handler;
passwd_handler = g_new0 (PasswdHandler, 1);
/* Initialize backend_pid. -1 means the backend is not running */
passwd_handler->backend_pid = -1;
/* Initialize IO Channels */
passwd_handler->backend_stdin = NULL;
passwd_handler->backend_stdout = NULL;
/* Initialize write queue */
passwd_handler->backend_stdin_queue = g_queue_new ();
/* Initialize watchers */
passwd_handler->backend_child_watch_id = 0;
passwd_handler->backend_stdout_watch_id = 0;
/* Initialize backend state */
passwd_handler->backend_state = PASSWD_STATE_NONE;
passwd_handler->changing_password = FALSE;
return passwd_handler;
}
void
passwd_destroy (PasswdHandler *passwd_handler)
{
g_queue_free (passwd_handler->backend_stdin_queue);
stop_passwd (passwd_handler);
g_free (passwd_handler);
}
void
passwd_authenticate (PasswdHandler *passwd_handler,
const char *current_password,
PasswdCallback cb,
const gpointer user_data)
{
GError *error = NULL;
/* Don't stop if we've already started chaging password */
if (passwd_handler->changing_password)
return;
/* Clear data from possible previous attempts to change password */
passwd_handler->new_password = NULL;
passwd_handler->chpasswd_cb = NULL;
passwd_handler->chpasswd_cb_data = NULL;
g_queue_foreach (passwd_handler->backend_stdin_queue, (GFunc) g_free, NULL);
g_queue_clear (passwd_handler->backend_stdin_queue);
passwd_handler->current_password = current_password;
passwd_handler->auth_cb = cb;
passwd_handler->auth_cb_data = user_data;
/* Spawn backend */
stop_passwd (passwd_handler);
if (!spawn_passwd (passwd_handler, &error)) {
g_warning ("%s", error->message);
g_error_free (error);
return;
}
authenticate (passwd_handler);
/* Our IO watcher should now handle the rest */
}
gboolean
passwd_change_password (PasswdHandler *passwd_handler,
const char *new_password,
PasswdCallback cb,
const gpointer user_data)
{
GError *error = NULL;
passwd_handler->changing_password = TRUE;
passwd_handler->new_password = new_password;
passwd_handler->chpasswd_cb = cb;
passwd_handler->chpasswd_cb_data = user_data;
/* Stop passwd if an error occured and it is still running */
if (passwd_handler->backend_state == PASSWD_STATE_ERR) {
/* Stop passwd, free resources */
stop_passwd (passwd_handler);
}
/* Check that the backend is still running, or that an error
* has occured but it has not yet exited */
if (passwd_handler->backend_pid == -1) {
/* If it is not, re-run authentication */
/* Spawn backend */
stop_passwd (passwd_handler);
if (!spawn_passwd (passwd_handler, &error)) {
g_warning ("%s", error->message);
g_error_free (error);
return FALSE;
}
/* Add current and new passwords to queue */
authenticate (passwd_handler);
update_password (passwd_handler);
} else {
/* Only add new passwords to queue */
update_password (passwd_handler);
}
/* Pop new password through the backend.
* If user has no password, popping the queue would output current
* password, while 'passwd' is waiting for the new one. So wait for
* io_watch_stdout() to remove current password from the queue,
* and output the new one for us.
*/
if (passwd_handler->current_password)
io_queue_pop (passwd_handler->backend_stdin_queue, passwd_handler->backend_stdin);
/* Our IO watcher should now handle the rest */
return TRUE;
}
|
348 | ./cinnamon-control-center/panels/user-accounts/frob-account-dialog.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2012 Red Hat, Inc.
*
* 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
*/
#include "um-account-dialog.h"
#include <gtk/gtk.h>
static void
on_dialog_complete (GObject *object,
GAsyncResult *result,
gpointer user_data)
{
GMainLoop *loop = user_data;
UmUser *user;
user = um_account_dialog_finish (UM_ACCOUNT_DIALOG (object), result);
if (user == NULL) {
g_printerr ("No user created\n");
} else {
g_printerr ("User created: %s\n", um_user_get_user_name (user));
g_object_unref (user);
}
g_main_loop_quit (loop);
}
int
main (int argc,
char *argv[])
{
UmAccountDialog *dialog;
GMainLoop *loop;
gtk_init (&argc, &argv);
dialog = um_account_dialog_new ();
loop = g_main_loop_new (NULL, FALSE);
um_account_dialog_show (dialog, NULL, on_dialog_complete, loop);
g_main_loop_run (loop);
g_main_loop_unref (loop);
return 0;
}
|
349 | ./cinnamon-control-center/panels/user-accounts/um-editable-button.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright 2009-2010 Red Hat, Inc,
*
* 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.
*
* Written by: Matthias Clasen <[email protected]>
*/
#include <gdk/gdkkeysyms.h>
#include "um-editable-button.h"
#define EMPTY_TEXT "\xe2\x80\x94"
struct _UmEditableButtonPrivate {
GtkNotebook *notebook;
GtkLabel *label;
GtkButton *button;
gchar *text;
gboolean editable;
gint weight;
gboolean weight_set;
gdouble scale;
gboolean scale_set;
};
#define UM_EDITABLE_BUTTON_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), UM_TYPE_EDITABLE_BUTTON, UmEditableButtonPrivate))
enum {
PROP_0,
PROP_TEXT,
PROP_EDITABLE,
PROP_SCALE,
PROP_SCALE_SET,
PROP_WEIGHT,
PROP_WEIGHT_SET
};
enum {
START_EDITING,
ACTIVATE,
LAST_SIGNAL
};
static guint signals [LAST_SIGNAL] = { 0, };
G_DEFINE_TYPE (UmEditableButton, um_editable_button, GTK_TYPE_ALIGNMENT);
void
um_editable_button_set_text (UmEditableButton *button,
const gchar *text)
{
UmEditableButtonPrivate *priv;
gchar *tmp;
GtkWidget *label;
priv = button->priv;
tmp = g_strdup (text);
g_free (priv->text);
priv->text = tmp;
if (tmp == NULL || tmp[0] == '\0')
tmp = EMPTY_TEXT;
gtk_label_set_text (priv->label, tmp);
label = gtk_bin_get_child (GTK_BIN (priv->button));
gtk_label_set_text (GTK_LABEL (label), tmp);
g_object_notify (G_OBJECT (button), "text");
}
const gchar *
um_editable_button_get_text (UmEditableButton *button)
{
return button->priv->text;
}
void
um_editable_button_set_editable (UmEditableButton *button,
gboolean editable)
{
UmEditableButtonPrivate *priv;
priv = button->priv;
if (priv->editable != editable) {
priv->editable = editable;
gtk_notebook_set_current_page (priv->notebook, editable ? 1 : 0);
g_object_notify (G_OBJECT (button), "editable");
}
}
gboolean
um_editable_button_get_editable (UmEditableButton *button)
{
return button->priv->editable;
}
static void
update_fonts (UmEditableButton *button)
{
PangoAttrList *attrs;
PangoAttribute *attr;
GtkWidget *label;
UmEditableButtonPrivate *priv = button->priv;
attrs = pango_attr_list_new ();
if (priv->scale_set) {
attr = pango_attr_scale_new (priv->scale);
pango_attr_list_insert (attrs, attr);
}
if (priv->weight_set) {
attr = pango_attr_weight_new (priv->weight);
pango_attr_list_insert (attrs, attr);
}
gtk_label_set_attributes (priv->label, attrs);
label = gtk_bin_get_child (GTK_BIN (priv->button));
gtk_label_set_attributes (GTK_LABEL (label), attrs);
pango_attr_list_unref (attrs);
}
void
um_editable_button_set_weight (UmEditableButton *button,
gint weight)
{
UmEditableButtonPrivate *priv = button->priv;
if (priv->weight == weight && priv->weight_set)
return;
priv->weight = weight;
priv->weight_set = TRUE;
update_fonts (button);
g_object_notify (G_OBJECT (button), "weight");
g_object_notify (G_OBJECT (button), "weight-set");
}
gint
um_editable_button_get_weight (UmEditableButton *button)
{
return button->priv->weight;
}
void
um_editable_button_set_scale (UmEditableButton *button,
gdouble scale)
{
UmEditableButtonPrivate *priv = button->priv;
if (priv->scale == scale && priv->scale_set)
return;
priv->scale = scale;
priv->scale_set = TRUE;
update_fonts (button);
g_object_notify (G_OBJECT (button), "scale");
g_object_notify (G_OBJECT (button), "scale-set");
}
gdouble
um_editable_button_get_scale (UmEditableButton *button)
{
return button->priv->scale;
}
static void
um_editable_button_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
UmEditableButton *button = UM_EDITABLE_BUTTON (object);
switch (prop_id) {
case PROP_TEXT:
um_editable_button_set_text (button, g_value_get_string (value));
break;
case PROP_EDITABLE:
um_editable_button_set_editable (button, g_value_get_boolean (value));
break;
case PROP_WEIGHT:
um_editable_button_set_weight (button, g_value_get_int (value));
break;
case PROP_WEIGHT_SET:
button->priv->weight_set = g_value_get_boolean (value);
break;
case PROP_SCALE:
um_editable_button_set_scale (button, g_value_get_double (value));
break;
case PROP_SCALE_SET:
button->priv->scale_set = g_value_get_boolean (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
um_editable_button_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
UmEditableButton *button = UM_EDITABLE_BUTTON (object);
switch (prop_id) {
case PROP_TEXT:
g_value_set_string (value,
um_editable_button_get_text (button));
break;
case PROP_EDITABLE:
g_value_set_boolean (value,
um_editable_button_get_editable (button));
break;
case PROP_WEIGHT:
g_value_set_int (value,
um_editable_button_get_weight (button));
break;
case PROP_WEIGHT_SET:
g_value_set_boolean (value,
button->priv->weight_set);
break;
case PROP_SCALE:
g_value_set_double (value,
um_editable_button_get_scale (button));
break;
case PROP_SCALE_SET:
g_value_set_boolean (value,
button->priv->scale_set);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
um_editable_button_finalize (GObject *object)
{
UmEditableButton *button = (UmEditableButton*)object;
g_free (button->priv->text);
G_OBJECT_CLASS (um_editable_button_parent_class)->finalize (object);
}
static void um_editable_button_activate (UmEditableButton *button);
static void
um_editable_button_class_init (UmEditableButtonClass *class)
{
GObjectClass *object_class;
GtkWidgetClass *widget_class;
object_class = G_OBJECT_CLASS (class);
widget_class = GTK_WIDGET_CLASS (class);
object_class->set_property = um_editable_button_set_property;
object_class->get_property = um_editable_button_get_property;
object_class->finalize = um_editable_button_finalize;
signals[START_EDITING] =
g_signal_new ("start-editing",
G_TYPE_FROM_CLASS (class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (UmEditableButtonClass, start_editing),
NULL, NULL,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
signals[ACTIVATE] =
g_signal_new ("activate",
G_TYPE_FROM_CLASS (class),
G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
G_STRUCT_OFFSET (UmEditableButtonClass, activate),
NULL, NULL,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
widget_class->activate_signal = signals[ACTIVATE];
class->activate = um_editable_button_activate;
g_object_class_install_property (object_class, PROP_TEXT,
g_param_spec_string ("text",
"Text", "The text of the button",
NULL,
G_PARAM_READWRITE));
g_object_class_install_property (object_class, PROP_EDITABLE,
g_param_spec_boolean ("editable",
"Editable", "Whether the text can be edited",
FALSE,
G_PARAM_READWRITE));
g_object_class_install_property (object_class, PROP_WEIGHT,
g_param_spec_int ("weight",
"Font Weight", "The font weight to use",
0, G_MAXINT, PANGO_WEIGHT_NORMAL,
G_PARAM_READWRITE));
g_object_class_install_property (object_class, PROP_WEIGHT_SET,
g_param_spec_boolean ("weight-set",
"Font Weight Set", "Whether a font weight is set",
FALSE,
G_PARAM_READWRITE));
g_object_class_install_property (object_class, PROP_SCALE,
g_param_spec_double ("scale",
"Font Scale", "The font scale to use",
0.0, G_MAXDOUBLE, 1.0,
G_PARAM_READWRITE));
g_object_class_install_property (object_class, PROP_SCALE_SET,
g_param_spec_boolean ("scale-set",
"Font Scale Set", "Whether a font scale is set",
FALSE,
G_PARAM_READWRITE));
g_type_class_add_private (class, sizeof (UmEditableButtonPrivate));
}
static void
start_editing (UmEditableButton *button)
{
g_signal_emit (button, signals[START_EDITING], 0);
}
static void
um_editable_button_activate (UmEditableButton *button)
{
UmEditableButtonPrivate *priv = button->priv;
if (priv->editable) {
gtk_widget_grab_focus (GTK_WIDGET (button->priv->button));
}
}
static void
button_clicked (GtkWidget *widget,
UmEditableButton *button)
{
start_editing (button);
}
static void
update_button_padding (GtkWidget *widget,
GtkAllocation *allocation,
UmEditableButton *button)
{
UmEditableButtonPrivate *priv = button->priv;
GtkAllocation parent_allocation;
gint offset;
gint pad;
gtk_widget_get_allocation (gtk_widget_get_parent (widget), &parent_allocation);
offset = allocation->x - parent_allocation.x;
gtk_misc_get_padding (GTK_MISC (priv->label), &pad, NULL);
if (offset != pad)
gtk_misc_set_padding (GTK_MISC (priv->label), offset, 0);
}
static void
um_editable_button_init (UmEditableButton *button)
{
UmEditableButtonPrivate *priv;
priv = button->priv = UM_EDITABLE_BUTTON_GET_PRIVATE (button);
priv->weight = PANGO_WEIGHT_NORMAL;
priv->weight_set = FALSE;
priv->scale = 1.0;
priv->scale_set = FALSE;
priv->notebook = (GtkNotebook*)gtk_notebook_new ();
gtk_notebook_set_show_tabs (priv->notebook, FALSE);
gtk_notebook_set_show_border (priv->notebook, FALSE);
priv->label = (GtkLabel*)gtk_label_new (EMPTY_TEXT);
gtk_misc_set_alignment (GTK_MISC (priv->label), 0.0, 0.5);
gtk_notebook_append_page (priv->notebook, (GtkWidget*)priv->label, NULL);
priv->button = (GtkButton*)gtk_button_new_with_label (EMPTY_TEXT);
gtk_widget_set_receives_default ((GtkWidget*)priv->button, TRUE);
gtk_button_set_relief (priv->button, GTK_RELIEF_NONE);
gtk_button_set_alignment (priv->button, 0.0, 0.5);
gtk_notebook_append_page (priv->notebook, (GtkWidget*)priv->button, NULL);
g_signal_connect (priv->button, "clicked", G_CALLBACK (button_clicked), button);
g_signal_connect (gtk_bin_get_child (GTK_BIN (priv->button)), "size-allocate", G_CALLBACK (update_button_padding), button);
gtk_container_add (GTK_CONTAINER (button), (GtkWidget*)priv->notebook);
gtk_widget_show ((GtkWidget*)priv->notebook);
gtk_widget_show ((GtkWidget*)priv->label);
gtk_widget_show ((GtkWidget*)priv->button);
gtk_notebook_set_current_page (priv->notebook, 0);
}
GtkWidget *
um_editable_button_new (void)
{
return (GtkWidget *) g_object_new (UM_TYPE_EDITABLE_BUTTON, NULL);
}
|
350 | ./cinnamon-control-center/panels/user-accounts/um-account-dialog.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright 2009-2010 Red Hat, Inc,
*
* 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.
*
* Written by: Matthias Clasen <[email protected]>
*/
#include "config.h"
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <gtk/gtk.h>
#include "um-account-dialog.h"
#include "um-realm-manager.h"
#include "um-user-manager.h"
#include "um-utils.h"
typedef enum {
UM_LOCAL,
UM_ENTERPRISE,
NUM_MODES
} UmAccountMode;
static void mode_change (UmAccountDialog *self,
UmAccountMode mode);
static void dialog_validate (UmAccountDialog *self);
static void on_join_login (GObject *source,
GAsyncResult *result,
gpointer user_data);
static void on_realm_joined (GObject *source,
GAsyncResult *result,
gpointer user_data);
#define UM_ACCOUNT_DIALOG_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), UM_TYPE_ACCOUNT_DIALOG, \
UmAccountDialogClass))
#define UM_IS_ACCOUNT_DIALOG_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), UM_TYPE_ACCOUNT_DIALOG))
#define UM_ACCOUNT_DIALOG_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), UM_TYPE_ACCOUNT_DIALOG, \
UmAccountDialogClass))
struct _UmAccountDialog {
GtkDialog parent;
GtkWidget *container_widget;
GSimpleAsyncResult *async;
GCancellable *cancellable;
GtkSpinner *spinner;
/* Buttons to switch modes between local/enterprise */
UmAccountMode mode;
GtkWidget *mode_container;
gboolean mode_updating;
GtkWidget *mode_buttons[NUM_MODES];
GtkWidget *mode_areas[NUM_MODES];
/* Local user account widgets */
GtkWidget *local_username;
GtkWidget *local_name;
GtkWidget *local_account_type;
/* Enterprise widgets */
guint realmd_watch;
GtkWidget *enterprise_button;
GtkListStore *enterprise_realms;
GtkComboBox *enterprise_domain;
GtkEntry *enterprise_domain_entry;
gboolean enterprise_domain_chosen;
GtkEntry *enterprise_login;
GtkEntry *enterprise_password;
UmRealmManager *realm_manager;
UmRealmObject *selected_realm;
/* Join credential dialog */
GtkDialog *join_dialog;
GtkLabel *join_domain;
GtkEntry *join_name;
GtkEntry *join_password;
gboolean join_prompted;
};
struct _UmAccountDialogClass {
GtkDialogClass parent_class;
};
G_DEFINE_TYPE (UmAccountDialog, um_account_dialog, GTK_TYPE_DIALOG);
static void
show_error_dialog (UmAccountDialog *self,
const gchar *message,
GError *error)
{
GtkWidget *dialog;
dialog = gtk_message_dialog_new (GTK_WINDOW (self),
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_ERROR,
GTK_BUTTONS_CLOSE,
"%s", message);
if (error != NULL) {
g_dbus_error_strip_remote_error (error);
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
"%s", error->message);
}
g_signal_connect (dialog, "response", G_CALLBACK (gtk_widget_destroy), NULL);
gtk_window_present (GTK_WINDOW (dialog));
}
static void
begin_action (UmAccountDialog *self)
{
g_debug ("Beginning action, disabling dialog controls");
gtk_widget_set_sensitive (self->container_widget, FALSE);
gtk_dialog_set_response_sensitive (GTK_DIALOG (self), GTK_RESPONSE_OK, FALSE);
gtk_widget_show (GTK_WIDGET (self->spinner));
gtk_spinner_start (self->spinner);
}
static void
finish_action (UmAccountDialog *self)
{
g_debug ("Completed action, enabling dialog controls");
gtk_widget_set_sensitive (self->container_widget, TRUE);
gtk_dialog_set_response_sensitive (GTK_DIALOG (self), GTK_RESPONSE_OK, TRUE);
gtk_widget_hide (GTK_WIDGET (self->spinner));
gtk_spinner_stop (self->spinner);
}
static void
complete_dialog (UmAccountDialog *self,
UmUser *user)
{
if (user != NULL) {
g_simple_async_result_set_op_res_gpointer (self->async,
g_object_ref (user),
g_object_unref);
}
g_simple_async_result_complete_in_idle (self->async);
gtk_widget_hide (GTK_WIDGET (self));
}
static void
create_user_done (UmUserManager *manager,
GAsyncResult *res,
UmAccountDialog *self)
{
UmUser *user;
GError *error;
finish_action (self);
/* Note that user is returned without an extra reference */
error = NULL;
if (!um_user_manager_create_user_finish (manager, res, &user, &error)) {
g_debug ("Failed to create user: %s", error->message);
if (!g_error_matches (error, UM_USER_MANAGER_ERROR, UM_USER_MANAGER_ERROR_PERMISSION_DENIED))
show_error_dialog (self, _("Failed to add account"), error);
g_error_free (error);
gtk_widget_grab_focus (self->local_name);
} else {
g_debug ("Created user: %s", um_user_get_user_name (user));
complete_dialog (self, user);
}
}
static void
local_create_user (UmAccountDialog *self)
{
UmUserManager *manager;
const gchar *username;
const gchar *name;
gint account_type;
GtkTreeModel *model;
GtkTreeIter iter;
begin_action (self);
name = gtk_entry_get_text (GTK_ENTRY (self->local_name));
username = gtk_combo_box_text_get_active_text (GTK_COMBO_BOX_TEXT (self->local_username));
model = gtk_combo_box_get_model (GTK_COMBO_BOX (self->local_account_type));
gtk_combo_box_get_active_iter (GTK_COMBO_BOX (self->local_account_type), &iter);
gtk_tree_model_get (model, &iter, 1, &account_type, -1);
g_debug ("Creating local user: %s", username);
manager = um_user_manager_ref_default ();
um_user_manager_create_user (manager,
username,
name,
account_type,
self->cancellable,
(GAsyncReadyCallback)create_user_done,
self,
NULL);
g_object_unref (manager);
}
static gboolean
local_validate (UmAccountDialog *self)
{
gboolean valid_login;
gboolean valid_name;
GtkWidget *entry;
const gchar *name;
gchar *tip;
name = gtk_combo_box_text_get_active_text (GTK_COMBO_BOX_TEXT (self->local_username));
valid_login = is_valid_username (name, &tip);
entry = gtk_bin_get_child (GTK_BIN (self->local_username));
if (tip) {
set_entry_validation_error (GTK_ENTRY (entry), tip);
g_free (tip);
} else {
clear_entry_validation_error (GTK_ENTRY (entry));
}
name = gtk_entry_get_text (GTK_ENTRY (self->local_name));
valid_name = is_valid_name (name);
return valid_name && valid_login;
}
static void
on_username_changed (GtkComboBoxText *combo,
gpointer user_data)
{
dialog_validate (UM_ACCOUNT_DIALOG (user_data));
}
static void
on_name_changed (GtkEditable *editable,
gpointer user_data)
{
UmAccountDialog *self = UM_ACCOUNT_DIALOG (user_data);
GtkTreeModel *model;
const char *name;
model = gtk_combo_box_get_model (GTK_COMBO_BOX (self->local_username));
gtk_list_store_clear (GTK_LIST_STORE (model));
name = gtk_entry_get_text (GTK_ENTRY (editable));
generate_username_choices (name, GTK_LIST_STORE (model));
gtk_combo_box_set_active (GTK_COMBO_BOX (self->local_username), 0);
dialog_validate (self);
}
static void
local_init (UmAccountDialog *self,
GtkBuilder *builder)
{
GtkWidget *widget;
widget = (GtkWidget *) gtk_builder_get_object (builder, "local-username");
g_signal_connect (widget, "changed",
G_CALLBACK (on_username_changed), self);
self->local_username = widget;
widget = (GtkWidget *) gtk_builder_get_object (builder, "local-name");
g_signal_connect (widget, "changed", G_CALLBACK (on_name_changed), self);
self->local_name = widget;
widget = (GtkWidget *) gtk_builder_get_object (builder, "local-account-type");
self->local_account_type = widget;
}
static void
local_prepare (UmAccountDialog *self)
{
GtkTreeModel *model;
gtk_entry_set_text (GTK_ENTRY (self->local_name), "");
gtk_entry_set_text (GTK_ENTRY (gtk_bin_get_child (GTK_BIN (self->local_username))), "");
model = gtk_combo_box_get_model (GTK_COMBO_BOX (self->local_username));
gtk_list_store_clear (GTK_LIST_STORE (model));
gtk_combo_box_set_active (GTK_COMBO_BOX (self->local_account_type), 0);
}
static gboolean
enterprise_validate (UmAccountDialog *self)
{
const gchar *name;
gboolean valid_name;
gboolean valid_domain;
GtkTreeIter iter;
name = gtk_entry_get_text (GTK_ENTRY (self->enterprise_login));
valid_name = is_valid_name (name);
if (gtk_combo_box_get_active_iter (self->enterprise_domain, &iter)) {
gtk_tree_model_get (gtk_combo_box_get_model (self->enterprise_domain),
&iter, 0, &name, -1);
} else {
name = gtk_entry_get_text (self->enterprise_domain_entry);
}
valid_domain = is_valid_name (name);
return valid_name && valid_domain;
}
static void
enterprise_add_realm (UmAccountDialog *self,
UmRealmObject *realm)
{
GtkTreeModel *model;
GtkTreeIter iter;
UmRealmCommon *common;
const gchar *realm_name;
gboolean match;
gboolean ret;
gchar *name;
common = um_realm_object_get_common (realm);
realm_name = um_realm_common_get_name (common);
/*
* Don't add a second realm if we already have one with this name.
* Sometimes realmd returns to realms for the same name, if it has
* different ways to use that realm. The first one that realmd
* returns is the one it prefers.
*/
model = GTK_TREE_MODEL (self->enterprise_realms);
ret = gtk_tree_model_get_iter_first (model, &iter);
while (ret) {
gtk_tree_model_get (model, &iter, 0, &name, -1);
match = (g_strcmp0 (name, realm_name) == 0);
g_free (name);
if (match) {
g_debug ("ignoring duplicate realm: %s", realm_name);
return;
}
ret = gtk_tree_model_iter_next (model, &iter);
}
gtk_list_store_append (self->enterprise_realms, &iter);
gtk_list_store_set (self->enterprise_realms, &iter,
0, realm_name,
1, realm,
-1);
g_debug ("added realm to drop down: %s %s", realm_name,
g_dbus_object_get_object_path (G_DBUS_OBJECT (realm)));
if (!self->enterprise_domain_chosen && um_realm_is_configured (realm))
gtk_combo_box_set_active_iter (self->enterprise_domain, &iter);
g_object_unref (common);
}
static void
on_manager_realm_added (UmRealmManager *manager,
UmRealmObject *realm,
gpointer user_data)
{
UmAccountDialog *self = UM_ACCOUNT_DIALOG (user_data);
enterprise_add_realm (self, realm);
}
static void
on_register_user (GObject *source,
GAsyncResult *result,
gpointer user_data)
{
UmAccountDialog *self = UM_ACCOUNT_DIALOG (user_data);
GError *error = NULL;
UmUser *user = NULL;
um_user_manager_cache_user_finish (UM_USER_MANAGER (source),
result, &user, &error);
/* This is where we're finally done */
if (error == NULL) {
g_debug ("Successfully cached remote user: %s", um_user_get_user_name (user));
finish_action (self);
complete_dialog (self, user);
} else {
show_error_dialog (self, _("Failed to register account"), error);
g_message ("Couldn't cache user account: %s", error->message);
finish_action (self);
g_error_free (error);
}
}
static void
on_permit_user_login (GObject *source,
GAsyncResult *result,
gpointer user_data)
{
UmAccountDialog *self = UM_ACCOUNT_DIALOG (user_data);
UmRealmCommon *common;
UmUserManager *manager;
GError *error = NULL;
gchar *login;
common = UM_REALM_COMMON (source);
um_realm_common_call_change_login_policy_finish (common, result, &error);
if (error == NULL) {
/*
* Now tell the account service about this user. The account service
* should also lookup information about this via the realm and make
* sure all that is functional.
*/
manager = um_user_manager_ref_default ();
login = um_realm_calculate_login (common, gtk_entry_get_text (self->enterprise_login));
g_return_if_fail (login != NULL);
g_debug ("Caching remote user: %s", login);
um_user_manager_cache_user (manager, login, self->cancellable,
on_register_user, g_object_ref (self),
g_object_unref);
g_free (login);
g_object_unref (manager);
} else {
show_error_dialog (self, _("Failed to register account"), error);
g_message ("Couldn't permit logins on account: %s", error->message);
finish_action (self);
}
g_object_unref (self);
}
static void
enterprise_permit_user_login (UmAccountDialog *self)
{
UmRealmCommon *common;
gchar *login;
const gchar *add[2];
const gchar *remove[1];
GVariant *options;
common = um_realm_object_get_common (self->selected_realm);
login = um_realm_calculate_login (common, gtk_entry_get_text (self->enterprise_login));
g_return_if_fail (login != NULL);
add[0] = login;
add[1] = NULL;
remove[0] = NULL;
g_debug ("Permitting login for: %s", login);
options = g_variant_new_array (G_VARIANT_TYPE ("{sv}"), NULL, 0);
um_realm_common_call_change_login_policy (common, "",
add, remove, options,
self->cancellable,
on_permit_user_login,
g_object_ref (self));
g_object_unref (common);
g_free (login);
}
static void
on_join_response (GtkDialog *dialog,
gint response,
gpointer user_data)
{
UmAccountDialog *self = UM_ACCOUNT_DIALOG (user_data);
gtk_widget_hide (GTK_WIDGET (dialog));
if (response != GTK_RESPONSE_OK) {
finish_action (self);
return;
}
g_debug ("Logging in as admin user: %s", gtk_entry_get_text (self->join_name));
/* Prompted for some admin credentials, try to use them to log in */
um_realm_login (self->selected_realm,
gtk_entry_get_text (self->join_name),
gtk_entry_get_text (self->join_password),
self->cancellable,
on_join_login,
g_object_ref (self));
}
static void
join_show_prompt (UmAccountDialog *self,
GError *error)
{
UmRealmKerberosMembership *membership;
UmRealmKerberos *kerberos;
const gchar *name;
gtk_entry_set_text (self->join_password, "");
gtk_widget_grab_focus (GTK_WIDGET (self->join_password));
kerberos = um_realm_object_get_kerberos (self->selected_realm);
membership = um_realm_object_get_kerberos_membership (self->selected_realm);
gtk_label_set_text (self->join_domain,
um_realm_kerberos_get_domain_name (kerberos));
clear_entry_validation_error (self->join_name);
clear_entry_validation_error (self->join_password);
if (!self->join_prompted) {
name = um_realm_kerberos_membership_get_suggested_administrator (membership);
if (name && !g_str_equal (name, "")) {
g_debug ("Suggesting admin user: %s", name);
gtk_entry_set_text (self->join_name, name);
} else {
gtk_widget_grab_focus (GTK_WIDGET (self->join_name));
}
} else if (g_error_matches (error, UM_REALM_ERROR, UM_REALM_ERROR_BAD_PASSWORD)) {
g_debug ("Bad admin password: %s", error->message);
set_entry_validation_error (self->join_password, error->message);
} else {
g_debug ("Admin login failure: %s", error->message);
g_dbus_error_strip_remote_error (error);
set_entry_validation_error (self->join_name, error->message);
}
g_debug ("Showing admin password dialog");
gtk_window_set_transient_for (GTK_WINDOW (self->join_dialog), GTK_WINDOW (self));
gtk_window_set_modal (GTK_WINDOW (self->join_dialog), TRUE);
gtk_window_present (GTK_WINDOW (self->join_dialog));
self->join_prompted = TRUE;
g_object_unref (kerberos);
g_object_unref (membership);
/* And now we wait for on_join_response() */
}
static void
on_join_login (GObject *source,
GAsyncResult *result,
gpointer user_data)
{
UmAccountDialog *self = UM_ACCOUNT_DIALOG (user_data);
GError *error = NULL;
GBytes *creds;
um_realm_login_finish (result, &creds, &error);
/* Logged in as admin successfully, use creds to join domain */
if (error == NULL) {
if (!um_realm_join_as_admin (self->selected_realm,
gtk_entry_get_text (self->join_name),
gtk_entry_get_text (self->join_password),
creds, self->cancellable, on_realm_joined,
g_object_ref (self))) {
show_error_dialog (self, _("No supported way to authenticate with this domain"), NULL);
g_message ("Authenticating as admin is not supported by the realm");
finish_action (self);
}
g_bytes_unref (creds);
/* Couldn't login as admin, show prompt again */
} else {
join_show_prompt (self, error);
g_message ("Couldn't log in as admin to join domain: %s", error->message);
g_error_free (error);
}
g_object_unref (self);
}
static void
join_init (UmAccountDialog *self,
GtkBuilder *builder)
{
self->join_dialog = GTK_DIALOG (gtk_builder_get_object (builder, "join-dialog"));
self->join_domain = GTK_LABEL (gtk_builder_get_object (builder, "join-domain"));
self->join_name = GTK_ENTRY (gtk_builder_get_object (builder, "join-name"));
self->join_password = GTK_ENTRY (gtk_builder_get_object (builder, "join-password"));
g_signal_connect (self->join_dialog, "response",
G_CALLBACK (on_join_response), self);
}
static void
on_realm_joined (GObject *source,
GAsyncResult *result,
gpointer user_data)
{
UmAccountDialog *self = UM_ACCOUNT_DIALOG (user_data);
GError *error = NULL;
um_realm_join_finish (self->selected_realm,
result, &error);
/* Yay, joined the domain, register the user locally */
if (error == NULL) {
g_debug ("Joining realm completed successfully");
enterprise_permit_user_login (self);
/* Credential failure while joining domain, prompt for admin creds */
} else if (g_error_matches (error, UM_REALM_ERROR, UM_REALM_ERROR_BAD_LOGIN) ||
g_error_matches (error, UM_REALM_ERROR, UM_REALM_ERROR_BAD_PASSWORD)) {
g_debug ("Joining realm failed due to credentials");
join_show_prompt (self, error);
/* Other failure */
} else {
show_error_dialog (self, _("Failed to join domain"), error);
g_message ("Failed to join the domain: %s", error->message);
finish_action (self);
g_error_free (error);
}
g_object_unref (self);
}
static void
on_realm_login (GObject *source,
GAsyncResult *result,
gpointer user_data)
{
UmAccountDialog *self = UM_ACCOUNT_DIALOG (user_data);
GError *error = NULL;
GBytes *creds;
um_realm_login_finish (result, &creds, &error);
if (error == NULL) {
/* Already joined to the domain, just register this user */
if (um_realm_is_configured (self->selected_realm)) {
g_debug ("Already joined to this realm");
enterprise_permit_user_login (self);
/* Join the domain, try using the user's creds */
} else if (!um_realm_join_as_user (self->selected_realm,
gtk_entry_get_text (self->enterprise_login),
gtk_entry_get_text (self->enterprise_password),
creds, self->cancellable,
on_realm_joined,
g_object_ref (self))) {
/* If we can't do user auth, try to authenticate as admin */
g_debug ("Cannot join with user credentials");
join_show_prompt (self, NULL);
}
g_bytes_unref (creds);
/* A problem with the user's login name or password */
} else if (g_error_matches (error, UM_REALM_ERROR, UM_REALM_ERROR_BAD_LOGIN)) {
g_debug ("Problem with the user's login: %s", error->message);
set_entry_validation_error (self->enterprise_login, error->message);
finish_action (self);
gtk_widget_grab_focus (GTK_WIDGET (self->enterprise_login));
} else if (g_error_matches (error, UM_REALM_ERROR, UM_REALM_ERROR_BAD_PASSWORD)) {
g_debug ("Problem with the user's password: %s", error->message);
set_entry_validation_error (self->enterprise_password, error->message);
finish_action (self);
gtk_widget_grab_focus (GTK_WIDGET (self->enterprise_password));
/* Other login failure */
} else {
g_dbus_error_strip_remote_error (error);
show_error_dialog (self, _("Failed to log into domain"), error);
g_message ("Couldn't log in as user: %s", error->message);
finish_action (self);
}
g_clear_error (&error);
g_object_unref (self);
}
static void
enterprise_check_login (UmAccountDialog *self)
{
g_assert (self->selected_realm);
um_realm_login (self->selected_realm,
gtk_entry_get_text (self->enterprise_login),
gtk_entry_get_text (self->enterprise_password),
self->cancellable,
on_realm_login,
g_object_ref (self));
}
static void
on_realm_discover_input (GObject *source,
GAsyncResult *result,
gpointer user_data)
{
UmAccountDialog *self = UM_ACCOUNT_DIALOG (user_data);
GError *error = NULL;
GList *realms;
realms = um_realm_manager_discover_finish (self->realm_manager,
result, &error);
/* Found a realm, log user into domain */
if (error == NULL) {
g_assert (realms != NULL);
self->selected_realm = g_object_ref (realms->data);
enterprise_check_login (self);
g_list_free_full (realms, g_object_unref);
/* The domain is likely invalid*/
} else {
finish_action (self);
g_message ("Couldn't discover domain: %s", error->message);
gtk_widget_grab_focus (GTK_WIDGET (self->enterprise_domain_entry));
g_dbus_error_strip_remote_error (error);
set_entry_validation_error (self->enterprise_domain_entry,
error->message);
g_error_free (error);
}
g_object_unref (self);
}
static void
enterprise_add_user (UmAccountDialog *self)
{
GtkTreeIter iter;
begin_action (self);
g_clear_object (&self->selected_realm);
self->join_prompted = FALSE;
/* Already know about this realm, try to login as user */
if (gtk_combo_box_get_active_iter (self->enterprise_domain, &iter)) {
gtk_tree_model_get (gtk_combo_box_get_model (self->enterprise_domain),
&iter, 1, &self->selected_realm, -1);
enterprise_check_login (self);
/* Something the user typed, we need to discover realm */
} else {
um_realm_manager_discover (self->realm_manager,
gtk_entry_get_text (self->enterprise_domain_entry),
self->cancellable,
on_realm_discover_input,
g_object_ref (self));
}
}
static void
on_realm_manager_created (GObject *source,
GAsyncResult *result,
gpointer user_data)
{
UmAccountDialog *self = UM_ACCOUNT_DIALOG (user_data);
GError *error = NULL;
GList *realms, *l;
g_clear_object (&self->realm_manager);
self->realm_manager = um_realm_manager_new_finish (result, &error);
if (error != NULL) {
g_warning ("Couldn't contact realmd service: %s", error->message);
g_error_free (error);
return;
}
/* Lookup all the realm objects */
realms = um_realm_manager_get_realms (self->realm_manager);
for (l = realms; l != NULL; l = g_list_next (l))
enterprise_add_realm (self, l->data);
g_list_free (realms);
g_signal_connect (self->realm_manager, "realm-added",
G_CALLBACK (on_manager_realm_added), self);
/* When no realms try to discover a sensible default, triggers realm-added signal */
um_realm_manager_discover (self->realm_manager, "", self->cancellable,
NULL, NULL);
/* Show the 'Enterprise Login' stuff, and update mode */
gtk_widget_show (self->enterprise_button);
mode_change (self, self->mode);
}
static void
on_realmd_appeared (GDBusConnection *connection,
const gchar *name,
const gchar *name_owner,
gpointer user_data)
{
UmAccountDialog *self = UM_ACCOUNT_DIALOG (user_data);
um_realm_manager_new (self->cancellable, on_realm_manager_created, self);
}
static void
on_realmd_disappeared (GDBusConnection *unused1,
const gchar *unused2,
gpointer user_data)
{
UmAccountDialog *self = UM_ACCOUNT_DIALOG (user_data);
if (self->realm_manager) {
g_signal_handlers_disconnect_by_func (self->realm_manager,
on_manager_realm_added,
self);
g_object_unref (self->realm_manager);
self->realm_manager = NULL;
}
gtk_list_store_clear (self->enterprise_realms);
gtk_widget_hide (self->enterprise_button);
mode_change (self, UM_LOCAL);
}
static void
on_domain_changed (GtkComboBox *widget,
gpointer user_data)
{
UmAccountDialog *self = UM_ACCOUNT_DIALOG (user_data);
dialog_validate (self);
self->enterprise_domain_chosen = TRUE;
clear_entry_validation_error (self->enterprise_domain_entry);
}
static void
on_entry_changed (GtkEditable *editable,
gpointer user_data)
{
UmAccountDialog *self = UM_ACCOUNT_DIALOG (user_data);
dialog_validate (self);
clear_entry_validation_error (GTK_ENTRY (editable));
}
static void
enterprise_init (UmAccountDialog *self,
GtkBuilder *builder)
{
GtkWidget *widget;
self->enterprise_realms = gtk_list_store_new (2, G_TYPE_STRING, G_TYPE_OBJECT);
widget = (GtkWidget *) gtk_builder_get_object (builder, "enterprise-domain");
g_signal_connect (widget, "changed", G_CALLBACK (on_domain_changed), self);
self->enterprise_domain = GTK_COMBO_BOX (widget);
gtk_combo_box_set_model (self->enterprise_domain,
GTK_TREE_MODEL (self->enterprise_realms));
gtk_combo_box_set_entry_text_column (self->enterprise_domain, 0);
self->enterprise_domain_entry = GTK_ENTRY (gtk_bin_get_child (GTK_BIN (widget)));
widget = (GtkWidget *) gtk_builder_get_object (builder, "enterprise-login");
g_signal_connect (widget, "changed", G_CALLBACK (on_entry_changed), self);
self->enterprise_login = GTK_ENTRY (widget);
widget = (GtkWidget *) gtk_builder_get_object (builder, "enterprise-password");
g_signal_connect (widget, "changed", G_CALLBACK (on_entry_changed), self);
self->enterprise_password = GTK_ENTRY (widget);
/* Initially we hide the 'Enterprise Login' stuff */
widget = (GtkWidget *) gtk_builder_get_object (builder, "enterprise-button");
self->enterprise_button = widget;
gtk_widget_hide (widget);
self->realmd_watch = g_bus_watch_name (G_BUS_TYPE_SYSTEM, "org.freedesktop.realmd",
G_BUS_NAME_WATCHER_FLAGS_AUTO_START,
on_realmd_appeared, on_realmd_disappeared,
self, NULL);
}
static void
enterprise_prepare (UmAccountDialog *self)
{
gtk_entry_set_text (GTK_ENTRY (self->enterprise_login), "");
gtk_entry_set_text (GTK_ENTRY (self->enterprise_password), "");
}
static void
dialog_validate (UmAccountDialog *self)
{
gboolean valid = FALSE;
switch (self->mode) {
case UM_LOCAL:
valid = local_validate (self);
break;
case UM_ENTERPRISE:
valid = enterprise_validate (self);
break;
default:
valid = FALSE;
break;
}
gtk_dialog_set_response_sensitive (GTK_DIALOG (self), GTK_RESPONSE_OK, valid);
}
static void
label_set_bold (GtkLabel *label,
gboolean bold)
{
PangoAttrList *attrs;
PangoAttribute *attr;
attrs = pango_attr_list_new ();
attr = pango_attr_weight_new (bold ? PANGO_WEIGHT_BOLD : PANGO_WEIGHT_NORMAL);
pango_attr_list_insert (attrs, attr);
gtk_label_set_attributes (label, attrs);
pango_attr_list_unref (attrs);
}
static void
mode_change (UmAccountDialog *self,
UmAccountMode mode)
{
GtkWidget *button;
gint visible_count = 0;
gboolean active;
gint i;
g_assert (!self->mode_updating);
self->mode_updating = TRUE;
for (i = 0; i < NUM_MODES; i++) {
button = self->mode_buttons[i];
active = (i == (gint)mode);
/* The toggle state */
if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (button)) != active)
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button), active);
/* Make toggled buttons bold */
label_set_bold (GTK_LABEL (gtk_bin_get_child (GTK_BIN (button))), active);
/* Show the correct area */
gtk_widget_set_visible (GTK_WIDGET (self->mode_areas[i]), active);
if (gtk_widget_get_visible (button))
visible_count++;
}
/* Show mode container if more than one visible */
gtk_widget_set_visible (GTK_WIDGET (self->mode_container), visible_count > 1);
self->mode = mode;
self->mode_updating = FALSE;
dialog_validate (self);
}
static void
mode_toggled (UmAccountDialog *self,
GtkToggleButton *toggle,
UmAccountMode mode)
{
if (self->mode_updating)
return;
/* Undo the toggle if already pressed */
if (!gtk_toggle_button_get_active (toggle))
gtk_toggle_button_set_active (toggle, TRUE);
/* Otherwise update mode */
else
mode_change (self, mode);
}
static void
on_local_toggle (GtkToggleButton *toggle,
gpointer user_data)
{
mode_toggled (UM_ACCOUNT_DIALOG (user_data), toggle, UM_LOCAL);
}
static void
on_enterprise_toggle (GtkToggleButton *toggle,
gpointer user_data)
{
mode_toggled (UM_ACCOUNT_DIALOG (user_data), toggle, UM_ENTERPRISE);
}
static void
mode_init (UmAccountDialog *self,
GtkBuilder *builder)
{
GtkWidget *widget;
self->mode_container = (GtkWidget *) gtk_builder_get_object (builder, "account-mode");
widget = (GtkWidget *) gtk_builder_get_object (builder, "local-area");
self->mode_areas[UM_LOCAL] = widget;
widget = (GtkWidget *) gtk_builder_get_object (builder, "enterprise-area");
self->mode_areas[UM_ENTERPRISE] = widget;
widget = (GtkWidget *) gtk_builder_get_object (builder, "local-button");
g_signal_connect (widget, "toggled", G_CALLBACK (on_local_toggle), self);
self->mode_buttons[UM_LOCAL] = widget;
widget = (GtkWidget *) gtk_builder_get_object (builder, "enterprise-button");
g_signal_connect (widget, "toggled", G_CALLBACK (on_enterprise_toggle), self);
self->mode_buttons[UM_ENTERPRISE] = widget;
}
static void
um_account_dialog_init (UmAccountDialog *self)
{
GtkBuilder *builder;
GtkWidget *widget;
const gchar *filename;
GError *error = NULL;
GtkDialog *dialog;
GtkWidget *content;
GtkWidget *actions;
GtkWidget *box;
builder = gtk_builder_new ();
gtk_builder_set_translation_domain (builder, GETTEXT_PACKAGE);
filename = UIDIR "/account-dialog.ui";
if (!g_file_test (filename, G_FILE_TEST_EXISTS))
filename = "data/account-dialog.ui";
if (!gtk_builder_add_from_file (builder, filename, &error)) {
g_error ("%s", error->message);
g_error_free (error);
return;
}
dialog = GTK_DIALOG (self);
actions = gtk_dialog_get_action_area (dialog);
content = gtk_dialog_get_content_area (dialog);
gtk_container_set_border_width (GTK_CONTAINER (dialog), 5);
gtk_window_set_resizable (GTK_WINDOW (dialog), FALSE);
gtk_window_set_title (GTK_WINDOW (dialog), " ");
gtk_window_set_icon_name (GTK_WINDOW (dialog), "system-users");
/* Rearrange the bottom of dialog, so we can have spinner on left */
g_object_ref (actions);
box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 10);
gtk_container_remove (GTK_CONTAINER (content), actions);
gtk_box_pack_end (GTK_BOX (box), actions, FALSE, TRUE, 0);
gtk_box_pack_end (GTK_BOX (content), box, TRUE, TRUE, 0);
gtk_widget_show (box);
g_object_unref (actions);
/* Create the spinner, but don't show it yet */
self->spinner = GTK_SPINNER (gtk_spinner_new ());
widget = gtk_alignment_new (0.5, 0.5, 1.0, 1.0);
gtk_alignment_set_padding (GTK_ALIGNMENT (widget), 0, 0, 12, 6);
gtk_box_pack_start (GTK_BOX (box), widget, FALSE, FALSE, 0);
gtk_container_add (GTK_CONTAINER (widget), GTK_WIDGET (self->spinner));
gtk_widget_show (widget);
gtk_dialog_add_button (dialog, _("Cancel"), GTK_RESPONSE_CANCEL);
widget = gtk_dialog_add_button (dialog, _("_Add"), GTK_RESPONSE_OK);
gtk_widget_grab_default (widget);
widget = (GtkWidget *) gtk_builder_get_object (builder, "account-dialog");
gtk_container_add (GTK_CONTAINER (content), widget);
self->container_widget = widget;
local_init (self, builder);
enterprise_init (self, builder);
join_init (self, builder);
mode_init (self, builder);
g_object_unref (builder);
}
static void
um_account_dialog_response (GtkDialog *dialog,
gint response_id)
{
UmAccountDialog *self = UM_ACCOUNT_DIALOG (dialog);
switch (response_id) {
case GTK_RESPONSE_OK:
switch (self->mode) {
case UM_LOCAL:
local_create_user (self);
break;
case UM_ENTERPRISE:
enterprise_add_user (self);
break;
default:
g_assert_not_reached ();
}
break;
case GTK_RESPONSE_CANCEL:
case GTK_RESPONSE_DELETE_EVENT:
g_cancellable_cancel (self->cancellable);
complete_dialog (self, NULL);
break;
}
}
static void
um_account_dialog_dispose (GObject *obj)
{
UmAccountDialog *self = UM_ACCOUNT_DIALOG (obj);
if (self->cancellable)
g_cancellable_cancel (self->cancellable);
if (self->realmd_watch)
g_bus_unwatch_name (self->realmd_watch);
self->realmd_watch = 0;
if (self->realm_manager) {
g_signal_handlers_disconnect_by_func (self->realm_manager,
on_manager_realm_added,
self);
g_object_unref (self->realm_manager);
self->realm_manager = NULL;
}
G_OBJECT_CLASS (um_account_dialog_parent_class)->dispose (obj);
}
static void
um_account_dialog_finalize (GObject *obj)
{
UmAccountDialog *self = UM_ACCOUNT_DIALOG (obj);
if (self->cancellable)
g_object_unref (self->cancellable);
g_object_unref (self->enterprise_realms);
G_OBJECT_CLASS (um_account_dialog_parent_class)->finalize (obj);
}
static void
um_account_dialog_class_init (UmAccountDialogClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
GtkDialogClass *dialog_class = GTK_DIALOG_CLASS (klass);
object_class->dispose = um_account_dialog_dispose;
object_class->finalize = um_account_dialog_finalize;
dialog_class->response = um_account_dialog_response;
}
UmAccountDialog *
um_account_dialog_new (void)
{
return g_object_new (UM_TYPE_ACCOUNT_DIALOG, NULL);
}
void
um_account_dialog_show (UmAccountDialog *self,
GtkWindow *parent,
GAsyncReadyCallback callback,
gpointer user_data)
{
g_return_if_fail (UM_IS_ACCOUNT_DIALOG (self));
/* Make sure not already doing an operation */
g_return_if_fail (self->async == NULL);
self->async = g_simple_async_result_new (G_OBJECT (self), callback, user_data,
um_account_dialog_show);
if (self->cancellable)
g_object_unref (self->cancellable);
self->cancellable = g_cancellable_new ();
local_prepare (self);
enterprise_prepare (self);
mode_change (self, UM_LOCAL);
dialog_validate (self);
gtk_window_set_modal (GTK_WINDOW (self), parent != NULL);
gtk_window_set_transient_for (GTK_WINDOW (self), parent);
gtk_window_present (GTK_WINDOW (self));
gtk_widget_grab_focus (self->local_name);
}
UmUser *
um_account_dialog_finish (UmAccountDialog *self,
GAsyncResult *result)
{
UmUser *user;
g_return_val_if_fail (UM_IS_ACCOUNT_DIALOG (self), NULL);
g_return_val_if_fail (g_simple_async_result_is_valid (result, G_OBJECT (self),
um_account_dialog_show), NULL);
g_return_val_if_fail (result == G_ASYNC_RESULT (self->async), NULL);
user = g_simple_async_result_get_op_res_gpointer (self->async);
if (user != NULL)
g_object_ref (user);
g_clear_object (&self->async);
return user;
}
|
351 | ./cinnamon-control-center/panels/user-accounts/um-user-panel.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright 2009-2010 Red Hat, Inc,
*
* 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.
*
* Written by: Matthias Clasen <[email protected]>
*/
#include "config.h"
#include "um-user-panel.h"
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <gtk/gtk.h>
#include <polkit/polkit.h>
#include "shell/cc-editable-entry.h"
#include "um-user.h"
#include "um-user-manager.h"
#include "um-editable-button.h"
#include "um-editable-combo.h"
#include "um-account-dialog.h"
#include "cc-language-chooser.h"
#include "um-password-dialog.h"
#include "um-photo-dialog.h"
#include "um-fingerprint-dialog.h"
#include "um-utils.h"
#ifdef HAVE_CHEESE
#include <cheese/cheese-gtk.h>
#endif /* HAVE_CHEESE */
#include "cc-common-language.h"
#define USER_ACCOUNTS_PERMISSION "org.cinnamon.controlcenter.user-accounts.administration"
CC_PANEL_REGISTER (UmUserPanel, um_user_panel)
#define UM_USER_PANEL_PRIVATE(o) \
(G_TYPE_INSTANCE_GET_PRIVATE ((o), UM_TYPE_USER_PANEL, UmUserPanelPrivate))
struct _UmUserPanelPrivate {
UmUserManager *um;
GtkBuilder *builder;
GtkWidget *main_box;
GPermission *permission;
GtkWidget *language_chooser;
UmPasswordDialog *password_dialog;
UmPhotoDialog *photo_dialog;
};
static GtkWidget *
get_widget (UmUserPanelPrivate *d, const char *name)
{
return (GtkWidget *)gtk_builder_get_object (d->builder, name);
}
enum {
USER_COL,
FACE_COL,
NAME_COL,
USER_ROW_COL,
TITLE_COL,
HEADING_ROW_COL,
SORT_KEY_COL,
AUTOLOGIN_COL,
NUM_USER_LIST_COLS
};
static UmUser *
get_selected_user (UmUserPanelPrivate *d)
{
GtkTreeView *tv;
GtkTreeIter iter;
GtkTreeSelection *selection;
GtkTreeModel *model;
UmUser *user;
tv = (GtkTreeView *)get_widget (d, "list-treeview");
selection = gtk_tree_view_get_selection (tv);
if (gtk_tree_selection_get_selected (selection, &model, &iter)) {
gtk_tree_model_get (model, &iter, USER_COL, &user, -1);
return user;
}
return NULL;
}
static char *
get_name_col_str (UmUser *user)
{
return g_markup_printf_escaped ("<b>%s</b>\n<small>%s</small>",
um_user_get_display_name (user),
um_user_get_user_name (user));
}
static void
user_added (UmUserManager *um, UmUser *user, UmUserPanelPrivate *d)
{
GtkWidget *widget;
GtkTreeModel *model;
GtkListStore *store;
GtkTreeIter iter;
GtkTreeIter dummy;
GdkPixbuf *pixbuf;
gchar *text;
GtkTreeSelection *selection;
gint sort_key;
g_debug ("user added: %d %s\n", um_user_get_uid (user), um_user_get_real_name (user));
widget = get_widget (d, "list-treeview");
model = gtk_tree_view_get_model (GTK_TREE_VIEW (widget));
store = GTK_LIST_STORE (model);
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (widget));
pixbuf = um_user_render_icon (user, TRUE, 48);
text = get_name_col_str (user);
if (um_user_get_uid (user) == getuid ()) {
sort_key = 1;
}
else {
sort_key = 3;
}
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter,
USER_COL, user,
FACE_COL, pixbuf,
NAME_COL, text,
USER_ROW_COL, TRUE,
TITLE_COL, NULL,
HEADING_ROW_COL, FALSE,
SORT_KEY_COL, sort_key,
-1);
g_object_unref (pixbuf);
g_free (text);
if (sort_key == 1 &&
!gtk_tree_selection_get_selected (selection, &model, &dummy)) {
gtk_tree_selection_select_iter (selection, &iter);
}
}
static void
get_previous_user_row (GtkTreeModel *model,
GtkTreeIter *iter,
GtkTreeIter *prev)
{
GtkTreePath *path;
UmUser *user;
path = gtk_tree_model_get_path (model, iter);
while (gtk_tree_path_prev (path)) {
gtk_tree_model_get_iter (model, prev, path);
gtk_tree_model_get (model, prev, USER_COL, &user, -1);
if (user) {
g_object_unref (user);
break;
}
}
gtk_tree_path_free (path);
}
static gboolean
get_next_user_row (GtkTreeModel *model,
GtkTreeIter *iter,
GtkTreeIter *next)
{
UmUser *user;
*next = *iter;
while (gtk_tree_model_iter_next (model, next)) {
gtk_tree_model_get (model, next, USER_COL, &user, -1);
if (user) {
g_object_unref (user);
return TRUE;
}
}
return FALSE;
}
static void
user_removed (UmUserManager *um, UmUser *user, UmUserPanelPrivate *d)
{
GtkTreeView *tv;
GtkTreeModel *model;
GtkTreeSelection *selection;
GtkListStore *store;
GtkTreeIter iter, next;
UmUser *u;
g_debug ("user removed: %s\n", um_user_get_user_name (user));
tv = (GtkTreeView *)get_widget (d, "list-treeview");
selection = gtk_tree_view_get_selection (tv);
model = gtk_tree_view_get_model (tv);
store = GTK_LIST_STORE (model);
if (gtk_tree_model_get_iter_first (model, &iter)) {
do {
gtk_tree_model_get (model, &iter, USER_COL, &u, -1);
if (u != NULL) {
if (um_user_get_uid (user) == um_user_get_uid (u)) {
if (!get_next_user_row (model, &iter, &next))
get_previous_user_row (model, &iter, &next);
gtk_list_store_remove (store, &iter);
gtk_tree_selection_select_iter (selection, &next);
g_object_unref (u);
break;
}
g_object_unref (u);
}
} while (gtk_tree_model_iter_next (model, &iter));
}
}
static void show_user (UmUser *user, UmUserPanelPrivate *d);
static void
user_changed (UmUserManager *um, UmUser *user, UmUserPanelPrivate *d)
{
GtkTreeView *tv;
GtkTreeSelection *selection;
GtkTreeModel *model;
GtkTreeIter iter;
UmUser *current;
GdkPixbuf *pixbuf;
char *text;
tv = (GtkTreeView *)get_widget (d, "list-treeview");
model = gtk_tree_view_get_model (tv);
selection = gtk_tree_view_get_selection (tv);
gtk_tree_model_get_iter_first (model, &iter);
do {
gtk_tree_model_get (model, &iter, USER_COL, ¤t, -1);
if (current == user) {
pixbuf = um_user_render_icon (user, TRUE, 48);
text = get_name_col_str (user);
gtk_list_store_set (GTK_LIST_STORE (model), &iter,
USER_COL, user,
FACE_COL, pixbuf,
NAME_COL, text,
-1);
g_object_unref (pixbuf);
g_free (text);
g_object_unref (current);
break;
}
if (current)
g_object_unref (current);
} while (gtk_tree_model_iter_next (model, &iter));
if (gtk_tree_selection_get_selected (selection, &model, &iter)) {
gtk_tree_model_get (model, &iter, USER_COL, ¤t, -1);
if (current == user) {
show_user (user, d);
}
if (current)
g_object_unref (current);
}
}
static void
select_created_user (GObject *object,
GAsyncResult *result,
gpointer user_data)
{
UmUserPanelPrivate *d = user_data;
UmAccountDialog *dialog;
GtkTreeView *tv;
GtkTreeModel *model;
GtkTreeSelection *selection;
GtkTreeIter iter;
UmUser *current;
GtkTreePath *path;
UmUser *user;
dialog = UM_ACCOUNT_DIALOG (object);
user = um_account_dialog_finish (dialog, result);
gtk_widget_destroy (GTK_WIDGET (dialog));
if (user == NULL)
return;
tv = (GtkTreeView *)get_widget (d, "list-treeview");
model = gtk_tree_view_get_model (tv);
selection = gtk_tree_view_get_selection (tv);
gtk_tree_model_get_iter_first (model, &iter);
do {
gtk_tree_model_get (model, &iter, USER_COL, ¤t, -1);
if (user == current) {
path = gtk_tree_model_get_path (model, &iter);
gtk_tree_view_scroll_to_cell (tv, path, NULL, FALSE, 0.0, 0.0);
gtk_tree_selection_select_path (selection, path);
gtk_tree_path_free (path);
g_object_unref (current);
break;
}
if (current)
g_object_unref (current);
} while (gtk_tree_model_iter_next (model, &iter));
g_object_unref (user);
}
static void
add_user (GtkButton *button, UmUserPanelPrivate *d)
{
UmAccountDialog *dialog;
dialog = um_account_dialog_new ();
um_account_dialog_show (dialog, GTK_WINDOW (gtk_widget_get_toplevel (d->main_box)),
select_created_user, d);
}
static void
delete_user_done (UmUserManager *manager,
GAsyncResult *res,
UmUserPanelPrivate *d)
{
GError *error;
error = NULL;
if (!um_user_manager_delete_user_finish (manager, res, &error)) {
if (!g_error_matches (error, UM_USER_MANAGER_ERROR, UM_USER_MANAGER_ERROR_PERMISSION_DENIED)) {
GtkWidget *dialog;
dialog = gtk_message_dialog_new (GTK_WINDOW (gtk_widget_get_toplevel (d->main_box)),
GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_ERROR,
GTK_BUTTONS_CLOSE,
_("Failed to delete user"));
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
"%s", error->message);
g_signal_connect (G_OBJECT (dialog), "response",
G_CALLBACK (gtk_widget_destroy), NULL);
gtk_window_present (GTK_WINDOW (dialog));
}
g_error_free (error);
}
}
static void
delete_user_response (GtkWidget *dialog,
gint response_id,
UmUserPanelPrivate *d)
{
UmUser *user;
gboolean remove_files;
gtk_widget_destroy (dialog);
if (response_id == GTK_RESPONSE_CANCEL) {
return;
}
else if (response_id == GTK_RESPONSE_NO) {
remove_files = TRUE;
}
else {
remove_files = FALSE;
}
user = get_selected_user (d);
um_user_manager_delete_user (d->um,
user,
remove_files,
(GAsyncReadyCallback)delete_user_done,
d,
NULL);
g_object_unref (user);
}
static void
delete_user (GtkButton *button, UmUserPanelPrivate *d)
{
UmUser *user;
GtkWidget *dialog;
user = get_selected_user (d);
if (user == NULL) {
return;
}
else if (um_user_get_uid (user) == getuid ()) {
dialog = gtk_message_dialog_new (GTK_WINDOW (gtk_widget_get_toplevel (d->main_box)),
0,
GTK_MESSAGE_INFO,
GTK_BUTTONS_CLOSE,
_("You cannot delete your own account."));
g_signal_connect (dialog, "response",
G_CALLBACK (gtk_widget_destroy), NULL);
}
else if (um_user_is_logged_in (user)) {
dialog = gtk_message_dialog_new (GTK_WINDOW (gtk_widget_get_toplevel (d->main_box)),
0,
GTK_MESSAGE_INFO,
GTK_BUTTONS_CLOSE,
_("%s is still logged in"),
um_user_get_real_name (user));
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
_("Deleting a user while they are logged in can leave the system in an inconsistent state."));
g_signal_connect (dialog, "response",
G_CALLBACK (gtk_widget_destroy), NULL);
}
else {
dialog = gtk_message_dialog_new (GTK_WINDOW (gtk_widget_get_toplevel (d->main_box)),
0,
GTK_MESSAGE_QUESTION,
GTK_BUTTONS_NONE,
_("Do you want to keep %s's files?"),
um_user_get_real_name (user));
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
_("It is possible to keep the home directory, mail spool and temporary files around when deleting a user account."));
gtk_dialog_add_buttons (GTK_DIALOG (dialog),
_("_Delete Files"), GTK_RESPONSE_NO,
_("_Keep Files"), GTK_RESPONSE_YES,
_("_Cancel"), GTK_RESPONSE_CANCEL,
NULL);
gtk_window_set_icon_name (GTK_WINDOW (dialog), "system-users");
g_signal_connect (dialog, "response",
G_CALLBACK (delete_user_response), d);
}
g_signal_connect (dialog, "close",
G_CALLBACK (gtk_widget_destroy), NULL);
gtk_window_set_modal (GTK_WINDOW (dialog), TRUE);
gtk_window_present (GTK_WINDOW (dialog));
g_object_unref (user);
}
static const gchar *
get_invisible_text (void)
{
GtkWidget *entry;
gunichar invisible_char;
static gchar invisible_text[40];
gchar *p;
gint i;
entry = gtk_entry_new ();
invisible_char = gtk_entry_get_invisible_char (GTK_ENTRY (entry));
if (invisible_char == 0)
invisible_char = 0x2022;
g_object_ref_sink (entry);
g_object_unref (entry);
/* five bullets */
p = invisible_text;
for (i = 0; i < 5; i++)
p += g_unichar_to_utf8 (invisible_char, p);
*p = 0;
return invisible_text;
}
static const gchar *
get_password_mode_text (UmUser *user)
{
const gchar *text;
if (um_user_get_locked (user)) {
text = C_("Password mode", "Account disabled");
}
else {
switch (um_user_get_password_mode (user)) {
case UM_PASSWORD_MODE_REGULAR:
text = get_invisible_text ();
break;
case UM_PASSWORD_MODE_SET_AT_LOGIN:
text = C_("Password mode", "To be set at next login");
break;
case UM_PASSWORD_MODE_NONE:
text = C_("Password mode", "None");
break;
default:
g_assert_not_reached ();
}
}
return text;
}
static void
show_user (UmUser *user, UmUserPanelPrivate *d)
{
GtkWidget *image;
GtkWidget *label;
GtkWidget *label2;
GtkWidget *label3;
GdkPixbuf *pixbuf;
gchar *lang;
GtkWidget *widget;
GtkTreeModel *model;
GtkTreeIter iter;
gboolean show, enable;
pixbuf = um_user_render_icon (user, FALSE, 48);
image = get_widget (d, "user-icon-image");
gtk_image_set_from_pixbuf (GTK_IMAGE (image), pixbuf);
image = get_widget (d, "user-icon-image2");
gtk_image_set_from_pixbuf (GTK_IMAGE (image), pixbuf);
g_object_unref (pixbuf);
um_photo_dialog_set_user (d->photo_dialog, user);
widget = get_widget (d, "full-name-entry");
cc_editable_entry_set_text (CC_EDITABLE_ENTRY (widget), um_user_get_real_name (user));
gtk_widget_set_tooltip_text (widget, um_user_get_user_name (user));
widget = get_widget (d, "account-type-combo");
um_editable_combo_set_active (UM_EDITABLE_COMBO (widget), um_user_get_account_type (user));
widget = get_widget (d, "account-password-button");
um_editable_button_set_text (UM_EDITABLE_BUTTON (widget), get_password_mode_text (user));
enable = um_user_is_local_account (user);
gtk_widget_set_sensitive (widget, enable);
widget = get_widget (d, "account-language-combo");
model = um_editable_combo_get_model (UM_EDITABLE_COMBO (widget));
cc_add_user_languages (model);
lang = g_strdup (um_user_get_language (user));
if (!lang)
lang = cc_common_language_get_current_language ();
cc_common_language_get_iter_for_language (model, lang, &iter);
um_editable_combo_set_active_iter (UM_EDITABLE_COMBO (widget), &iter);
g_free (lang);
/* Fingerprint: show when self, possible, and local account */
widget = get_widget (d, "account-fingerprint-notebook");
label = get_widget (d, "account-fingerprint-label");
label2 = get_widget (d, "account-fingerprint-value-label");
label3 = get_widget (d, "account-fingerprint-button-label");
show = (um_user_get_uid (user) == getuid() &&
um_user_is_local_account (user) &&
set_fingerprint_label (label2, label3));
gtk_widget_set_visible (label, show);
gtk_widget_set_visible (widget, show);
}
static void on_permission_changed (GPermission *permission, GParamSpec *pspec, gpointer data);
static void
selected_user_changed (GtkTreeSelection *selection, UmUserPanelPrivate *d)
{
GtkTreeModel *model;
GtkTreeIter iter;
UmUser *user;
if (gtk_tree_selection_get_selected (selection, &model, &iter)) {
gtk_tree_model_get (model, &iter, USER_COL, &user, -1);
show_user (user, d);
if (d->permission != NULL)
on_permission_changed (d->permission, NULL, d);
gtk_widget_set_sensitive (get_widget (d, "main-user-vbox"), TRUE);
g_object_unref (user);
} else {
gtk_widget_set_sensitive (get_widget (d, "main-user-vbox"), FALSE);
}
}
static void
change_name_done (GtkWidget *entry,
UmUserPanelPrivate *d)
{
const gchar *text;
UmUser *user;
user = get_selected_user (d);
text = cc_editable_entry_get_text (CC_EDITABLE_ENTRY (entry));
if (g_strcmp0 (text, um_user_get_real_name (user)) != 0) {
um_user_set_real_name (user, text);
}
g_object_unref (user);
}
static void
account_type_changed (UmEditableCombo *combo,
UmUserPanelPrivate *d)
{
UmUser *user;
GtkTreeModel *model;
GtkTreeIter iter;
gint account_type;
user = get_selected_user (d);
model = um_editable_combo_get_model (combo);
um_editable_combo_get_active_iter (combo, &iter);
gtk_tree_model_get (model, &iter, 1, &account_type, -1);
if (account_type != um_user_get_account_type (user)) {
um_user_set_account_type (user, account_type);
}
g_object_unref (user);
}
static void
language_response (GtkDialog *dialog,
gint response_id,
UmUserPanelPrivate *d)
{
GtkWidget *combo;
UmUser *user;
gchar *lang;
GtkTreeModel *model;
GtkTreeIter iter;
user = get_selected_user (d);
combo = get_widget (d, "account-language-combo");
model = um_editable_combo_get_model (UM_EDITABLE_COMBO (combo));
if (response_id == GTK_RESPONSE_OK) {
lang = cc_language_chooser_get_language (GTK_WIDGET (dialog));
um_user_set_language (user, lang);
}
else {
lang = g_strdup (um_user_get_language (user));
if (!lang)
lang = cc_common_language_get_current_language ();
}
cc_common_language_get_iter_for_language (model, lang, &iter);
um_editable_combo_set_active_iter (UM_EDITABLE_COMBO (combo), &iter);
g_free (lang);
gtk_widget_hide (GTK_WIDGET (dialog));
gtk_widget_set_sensitive (combo, TRUE);
g_object_unref (user);
}
static void
language_changed (UmEditableCombo *combo,
UmUserPanelPrivate *d)
{
GtkTreeModel *model;
GtkTreeIter iter;
gchar *lang;
UmUser *user;
if (!um_editable_combo_get_active_iter (combo, &iter))
return;
user = get_selected_user (d);
model = um_editable_combo_get_model (combo);
gtk_tree_model_get (model, &iter, 0, &lang, -1);
if (lang) {
if (g_strcmp0 (lang, um_user_get_language (user)) != 0) {
um_user_set_language (user, lang);
}
g_free (lang);
goto out;
}
if (d->language_chooser) {
cc_language_chooser_clear_filter (d->language_chooser);
gtk_window_present (GTK_WINDOW (d->language_chooser));
gtk_widget_set_sensitive (GTK_WIDGET (combo), FALSE);
goto out;
}
d->language_chooser = cc_language_chooser_new (gtk_widget_get_toplevel (d->main_box), FALSE);
g_signal_connect (d->language_chooser, "response",
G_CALLBACK (language_response), d);
g_signal_connect (d->language_chooser, "delete-event",
G_CALLBACK (gtk_widget_hide_on_delete), NULL);
gdk_window_set_cursor (gtk_widget_get_window (gtk_widget_get_toplevel (d->main_box)), NULL);
gtk_window_present (GTK_WINDOW (d->language_chooser));
gtk_widget_set_sensitive (GTK_WIDGET (combo), FALSE);
out:
g_object_unref (user);
}
static void
change_password (GtkButton *button, UmUserPanelPrivate *d)
{
UmUser *user;
user = get_selected_user (d);
um_password_dialog_set_user (d->password_dialog, user);
um_password_dialog_show (d->password_dialog,
GTK_WINDOW (gtk_widget_get_toplevel (d->main_box)));
g_object_unref (user);
}
static void
change_fingerprint (GtkButton *button, UmUserPanelPrivate *d)
{
GtkWidget *label, *label2;
UmUser *user;
user = get_selected_user (d);
g_assert (g_strcmp0 (g_get_user_name (), um_user_get_user_name (user)) == 0);
label = get_widget (d, "account-fingerprint-value-label");
label2 = get_widget (d, "account-fingerprint-button-label");
fingerprint_button_clicked (GTK_WINDOW (gtk_widget_get_toplevel (d->main_box)), label, label2, user);
g_object_unref (user);
}
static gint
sort_users (GtkTreeModel *model,
GtkTreeIter *a,
GtkTreeIter *b,
gpointer data)
{
UmUser *ua, *ub;
gint sa, sb;
gint result;
gtk_tree_model_get (model, a, USER_COL, &ua, SORT_KEY_COL, &sa, -1);
gtk_tree_model_get (model, b, USER_COL, &ub, SORT_KEY_COL, &sb, -1);
if (sa < sb) {
result = -1;
}
else if (sa > sb) {
result = 1;
}
else {
result = um_user_collate (ua, ub);
}
if (ua) {
g_object_unref (ua);
}
if (ub) {
g_object_unref (ub);
}
return result;
}
static gboolean
dont_select_headings (GtkTreeSelection *selection,
GtkTreeModel *model,
GtkTreePath *path,
gboolean selected,
gpointer data)
{
GtkTreeIter iter;
gboolean is_user;
gtk_tree_model_get_iter (model, &iter, path);
gtk_tree_model_get (model, &iter, USER_ROW_COL, &is_user, -1);
return is_user;
}
static void
users_loaded (UmUserManager *manager,
UmUserPanelPrivate *d)
{
GSList *list, *l;
UmUser *user;
GtkWidget *dialog;
if (um_user_manager_no_service (d->um)) {
dialog = gtk_message_dialog_new (GTK_WINDOW (gtk_widget_get_toplevel (d->main_box)),
GTK_DIALOG_MODAL,
GTK_MESSAGE_OTHER,
GTK_BUTTONS_CLOSE,
_("Failed to contact the accounts service"));
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
_("Please make sure that the AccountService is installed and enabled."));
g_signal_connect_swapped (dialog, "response",
G_CALLBACK (gtk_widget_destroy),
dialog);
gtk_widget_show (dialog);
gtk_widget_set_sensitive (d->main_box, FALSE);
}
list = um_user_manager_list_users (d->um);
g_debug ("Got %d users\n", g_slist_length (list));
g_signal_connect (d->um, "user-changed", G_CALLBACK (user_changed), d);
for (l = list; l; l = l->next) {
user = l->data;
g_debug ("adding user %s\n", um_user_get_real_name (user));
user_added (d->um, user, d);
}
g_slist_free (list);
g_signal_connect (d->um, "user-added", G_CALLBACK (user_added), d);
g_signal_connect (d->um, "user-removed", G_CALLBACK (user_removed), d);
}
static void
add_unlock_tooltip (GtkWidget *button)
{
gchar *names[3];
GIcon *icon;
names[0] = "changes-allow-symbolic";
names[1] = "changes-allow";
names[2] = NULL;
icon = (GIcon *)g_themed_icon_new_from_names (names, -1);
/* Translator comments:
* We split the line in 2 here to "make it look good", as there's
* no good way to do this in GTK+ for tooltips. See:
* https://bugzilla.gnome.org/show_bug.cgi?id=657168 */
setup_tooltip_with_embedded_icon (button,
_("To make changes,\nclick the * icon first"),
"*",
icon);
g_object_unref (icon);
g_signal_connect (button, "button-release-event",
G_CALLBACK (show_tooltip_now), NULL);
}
static void
remove_unlock_tooltip (GtkWidget *button)
{
setup_tooltip_with_embedded_icon (button, NULL, NULL, NULL);
g_signal_handlers_disconnect_by_func (button,
G_CALLBACK (show_tooltip_now), NULL);
}
static void
on_permission_changed (GPermission *permission,
GParamSpec *pspec,
gpointer data)
{
UmUserPanelPrivate *d = data;
gboolean is_authorized;
gboolean self_selected;
UmUser *user;
GtkWidget *widget;
user = get_selected_user (d);
if (!user) {
return;
}
is_authorized = g_permission_get_allowed (G_PERMISSION (d->permission));
self_selected = um_user_get_uid (user) == geteuid ();
widget = get_widget (d, "add-user-toolbutton");
gtk_widget_set_sensitive (widget, is_authorized);
if (is_authorized) {
setup_tooltip_with_embedded_icon (widget, _("Create a user account"), NULL, NULL);
}
else {
gchar *names[3];
GIcon *icon;
names[0] = "changes-allow-symbolic";
names[1] = "changes-allow";
names[2] = NULL;
icon = (GIcon *)g_themed_icon_new_from_names (names, -1);
setup_tooltip_with_embedded_icon (widget,
_("To create a user account,\nclick the * icon first"),
"*",
icon);
g_object_unref (icon);
}
widget = get_widget (d, "remove-user-toolbutton");
gtk_widget_set_sensitive (widget, is_authorized && !self_selected);
if (is_authorized) {
setup_tooltip_with_embedded_icon (widget, _("Delete the selected user account"), NULL, NULL);
}
else {
gchar *names[3];
GIcon *icon;
names[0] = "changes-allow-symbolic";
names[1] = "changes-allow";
names[2] = NULL;
icon = (GIcon *)g_themed_icon_new_from_names (names, -1);
setup_tooltip_with_embedded_icon (widget,
_("To delete the selected user account,\nclick the * icon first"),
"*",
icon);
g_object_unref (icon);
}
if (!um_user_is_local_account (user)) {
um_editable_combo_set_editable (UM_EDITABLE_COMBO (get_widget (d, "account-type-combo")), FALSE);
remove_unlock_tooltip (get_widget (d, "account-type-combo"));
} else if (is_authorized && um_user_is_local_account (user)) {
um_editable_combo_set_editable (UM_EDITABLE_COMBO (get_widget (d, "account-type-combo")), TRUE);
remove_unlock_tooltip (get_widget (d, "account-type-combo"));
}
else {
um_editable_combo_set_editable (UM_EDITABLE_COMBO (get_widget (d, "account-type-combo")), FALSE);
add_unlock_tooltip (get_widget (d, "account-type-combo"));
}
/* The full name entry: insensitive if remote or not authorized and not self */
widget = get_widget (d, "full-name-entry");
if (!um_user_is_local_account (user)) {
cc_editable_entry_set_editable (CC_EDITABLE_ENTRY (widget), FALSE);
remove_unlock_tooltip (widget);
} else if (is_authorized || self_selected) {
cc_editable_entry_set_editable (CC_EDITABLE_ENTRY (widget), TRUE);
remove_unlock_tooltip (widget);
} else {
cc_editable_entry_set_editable (CC_EDITABLE_ENTRY (widget), FALSE);
add_unlock_tooltip (widget);
}
if (is_authorized || self_selected) {
gtk_widget_show (get_widget (d, "user-icon-button"));
gtk_widget_hide (get_widget (d, "user-icon-nonbutton"));
um_editable_combo_set_editable (UM_EDITABLE_COMBO (get_widget (d, "account-language-combo")), TRUE);
remove_unlock_tooltip (get_widget (d, "account-language-combo"));
um_editable_button_set_editable (UM_EDITABLE_BUTTON (get_widget (d, "account-password-button")), TRUE);
remove_unlock_tooltip (get_widget (d, "account-password-button"));
gtk_notebook_set_current_page (GTK_NOTEBOOK (get_widget (d, "account-fingerprint-notebook")), 1);
}
else {
gtk_widget_hide (get_widget (d, "user-icon-button"));
gtk_widget_show (get_widget (d, "user-icon-nonbutton"));
um_editable_combo_set_editable (UM_EDITABLE_COMBO (get_widget (d, "account-language-combo")), FALSE);
add_unlock_tooltip (get_widget (d, "account-language-combo"));
um_editable_button_set_editable (UM_EDITABLE_BUTTON (get_widget (d, "account-password-button")), FALSE);
add_unlock_tooltip (get_widget (d, "account-password-button"));
gtk_notebook_set_current_page (GTK_NOTEBOOK (get_widget (d, "account-fingerprint-notebook")), 0);
}
um_password_dialog_set_privileged (d->password_dialog, is_authorized);
g_object_unref (user);
}
static gboolean
match_user (GtkTreeModel *model,
gint column,
const gchar *key,
GtkTreeIter *iter,
gpointer search_data)
{
UmUser *user;
const gchar *name;
gchar *normalized_key = NULL;
gchar *normalized_name = NULL;
gchar *case_normalized_key = NULL;
gchar *case_normalized_name = NULL;
gchar *p;
gboolean result = TRUE;
gint i;
gtk_tree_model_get (model, iter, USER_COL, &user, -1);
if (!user) {
goto out;
}
normalized_key = g_utf8_normalize (key, -1, G_NORMALIZE_ALL);
if (!normalized_key) {
goto out;
}
case_normalized_key = g_utf8_casefold (normalized_key, -1);
for (i = 0; i < 2; i++) {
if (i == 0) {
name = um_user_get_real_name (user);
}
else {
name = um_user_get_user_name (user);
}
g_free (normalized_name);
normalized_name = g_utf8_normalize (name, -1, G_NORMALIZE_ALL);
if (normalized_name) {
g_free (case_normalized_name);
case_normalized_name = g_utf8_casefold (normalized_name, -1);
p = strstr (case_normalized_name, case_normalized_key);
/* poor man's \b */
if (p == case_normalized_name || (p && p[-1] == ' ')) {
result = FALSE;
break;
}
}
}
out:
if (user) {
g_object_unref (user);
}
g_free (normalized_key);
g_free (case_normalized_key);
g_free (normalized_name);
g_free (case_normalized_name);
return result;
}
static void
login_options_cb (GtkWidget *widget, UmUserPanelPrivate *private)
{
gchar *argv[3];
argv[0] = "gksu";
argv[1] = "/usr/sbin/mdmsetup";
argv[3] = NULL;
g_spawn_async(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, NULL);
}
static gboolean
activate_link_cb (GtkLinkButton *button, gpointer user_data)
{
return TRUE;
}
static void
setup_main_window (UmUserPanelPrivate *d)
{
GtkWidget *userlist;
GtkTreeModel *model;
GtkListStore *store;
GtkTreeViewColumn *column;
GtkCellRenderer *cell;
GtkTreeSelection *selection;
GtkWidget *button;
GtkTreeIter iter;
gint expander_size;
gchar *title;
GIcon *icon;
GError *error = NULL;
gchar *names[3];
userlist = get_widget (d, "list-treeview");
store = gtk_list_store_new (NUM_USER_LIST_COLS,
UM_TYPE_USER,
GDK_TYPE_PIXBUF,
G_TYPE_STRING,
G_TYPE_BOOLEAN,
G_TYPE_STRING,
G_TYPE_BOOLEAN,
G_TYPE_INT,
G_TYPE_BOOLEAN);
model = (GtkTreeModel *)store;
gtk_tree_sortable_set_default_sort_func (GTK_TREE_SORTABLE (model), sort_users, NULL, NULL);
gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (model), GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID, GTK_SORT_ASCENDING);
gtk_tree_view_set_model (GTK_TREE_VIEW (userlist), model);
gtk_tree_view_set_search_column (GTK_TREE_VIEW (userlist), USER_COL);
gtk_tree_view_set_search_equal_func (GTK_TREE_VIEW (userlist),
match_user, NULL, NULL);
g_object_unref (model);
g_signal_connect (d->um, "users-loaded", G_CALLBACK (users_loaded), d);
gtk_widget_style_get (userlist, "expander-size", &expander_size, NULL);
gtk_tree_view_set_level_indentation (GTK_TREE_VIEW (userlist), - (expander_size + 6));
title = g_strdup_printf ("<small><span foreground=\"#555555\">%s</span></small>", _("My Account"));
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter,
TITLE_COL, title,
HEADING_ROW_COL, TRUE,
SORT_KEY_COL, 0,
AUTOLOGIN_COL, FALSE,
-1);
g_free (title);
title = g_strdup_printf ("<small><span foreground=\"#555555\">%s</span></small>", _("Other Accounts"));
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter,
TITLE_COL, title,
HEADING_ROW_COL, TRUE,
SORT_KEY_COL, 2,
AUTOLOGIN_COL, FALSE,
-1);
g_free (title);
column = gtk_tree_view_column_new ();
cell = gtk_cell_renderer_pixbuf_new ();
gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (column), cell, FALSE);
gtk_cell_layout_add_attribute (GTK_CELL_LAYOUT (column), cell, "pixbuf", FACE_COL);
gtk_cell_layout_add_attribute (GTK_CELL_LAYOUT (column), cell, "visible", USER_ROW_COL);
cell = gtk_cell_renderer_text_new ();
g_object_set (cell, "ellipsize", PANGO_ELLIPSIZE_END, NULL);
gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (column), cell, TRUE);
gtk_cell_layout_add_attribute (GTK_CELL_LAYOUT (column), cell, "markup", NAME_COL);
gtk_cell_layout_add_attribute (GTK_CELL_LAYOUT (column), cell, "visible", USER_ROW_COL);
cell = gtk_cell_renderer_text_new ();
gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (column), cell, TRUE);
gtk_cell_layout_add_attribute (GTK_CELL_LAYOUT (column), cell, "markup", TITLE_COL);
gtk_cell_layout_add_attribute (GTK_CELL_LAYOUT (column), cell, "visible", HEADING_ROW_COL);
gtk_tree_view_append_column (GTK_TREE_VIEW (userlist), column);
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (userlist));
gtk_tree_selection_set_mode (selection, GTK_SELECTION_BROWSE);
g_signal_connect (selection, "changed", G_CALLBACK (selected_user_changed), d);
gtk_tree_selection_set_select_function (selection, dont_select_headings, NULL, NULL);
gtk_scrolled_window_set_min_content_width (GTK_SCROLLED_WINDOW (get_widget (d, "list-scrolledwindow")), 300);
gtk_widget_set_size_request (get_widget (d, "list-scrolledwindow"), 200, -1);
button = get_widget (d, "add-user-toolbutton");
g_signal_connect (button, "clicked", G_CALLBACK (add_user), d);
button = get_widget (d, "remove-user-toolbutton");
g_signal_connect (button, "clicked", G_CALLBACK (delete_user), d);
button = get_widget (d, "user-icon-nonbutton");
add_unlock_tooltip (button);
button = get_widget (d, "full-name-entry");
g_signal_connect (button, "editing-done", G_CALLBACK (change_name_done), d);
button = get_widget (d, "account-type-combo");
g_signal_connect (button, "editing-done", G_CALLBACK (account_type_changed), d);
button = get_widget (d, "account-password-button");
g_signal_connect (button, "start-editing", G_CALLBACK (change_password), d);
button = get_widget (d, "account-language-combo");
g_signal_connect (button, "editing-done", G_CALLBACK (language_changed), d);
button = get_widget (d, "account-fingerprint-button");
g_signal_connect (button, "clicked",
G_CALLBACK (change_fingerprint), d);
GtkWidget *box = get_widget (d, "accounts-vbox");
d->permission = (GPermission *)polkit_permission_new_sync (USER_ACCOUNTS_PERMISSION, NULL, NULL, &error);
if (d->permission != NULL) {
g_signal_connect (d->permission, "notify",
G_CALLBACK (on_permission_changed), d);
on_permission_changed (d->permission, NULL, d);
button = gtk_lock_button_new (d->permission);
gtk_box_pack_start (GTK_BOX (box), button, FALSE, FALSE, 2);
gtk_widget_show (GTK_WIDGET (button));
} else {
g_warning ("Cannot create '%s' permission: %s", USER_ACCOUNTS_PERMISSION, error->message);
g_error_free (error);
}
gchar *path = g_find_program_in_path ("mdmsetup");
if (path != NULL) {
g_free (path);
button = gtk_link_button_new_with_label ("", _("Login Options"));
g_signal_connect (GTK_LINK_BUTTON (button), "clicked",
G_CALLBACK (login_options_cb), d);
g_signal_connect (GTK_LINK_BUTTON (button), "activate-link",
G_CALLBACK (activate_link_cb), d);
gtk_box_pack_start (GTK_BOX (box), button, FALSE, FALSE, 2);
gtk_widget_show (GTK_WIDGET (button));
gtk_widget_set_has_tooltip (GTK_WIDGET (button), FALSE);
}
button = get_widget (d, "add-user-toolbutton");
names[0] = "changes-allow-symbolic";
names[1] = "changes-allow";
names[2] = NULL;
icon = (GIcon *)g_themed_icon_new_from_names (names, -1);
setup_tooltip_with_embedded_icon (button,
_("To create a user account,\nclick the * icon first"),
"*",
icon);
button = get_widget (d, "remove-user-toolbutton");
setup_tooltip_with_embedded_icon (button,
_("To delete the selected user account,\nclick the * icon first"),
"*",
icon);
g_object_unref (icon);
}
static void
um_user_panel_init (UmUserPanel *self)
{
UmUserPanelPrivate *d;
GError *error;
volatile GType type G_GNUC_UNUSED;
const gchar *filename;
GtkWidget *button;
GtkStyleContext *context;
#ifdef HAVE_CHEESE
cheese_gtk_init (NULL, NULL);
#endif
d = self->priv = UM_USER_PANEL_PRIVATE (self);
/* register types that the builder might need */
type = um_editable_button_get_type ();
type = cc_editable_entry_get_type ();
type = um_editable_combo_get_type ();
gtk_widget_set_size_request (GTK_WIDGET (self), -1, 350);
d->builder = gtk_builder_new ();
gtk_builder_set_translation_domain (d->builder, GETTEXT_PACKAGE);
d->um = um_user_manager_ref_default ();
GtkWidget *dummy = cc_editable_entry_new (); /* Needed before UI file is loaded, or else
* the custom widget fails to load. */
g_object_ref_sink (dummy);
filename = UIDIR "/user-accounts-dialog.ui";
if (!g_file_test (filename, G_FILE_TEST_EXISTS)) {
filename = "data/user-accounts-dialog.ui";
}
error = NULL;
if (!gtk_builder_add_from_file (d->builder, filename, &error)) {
g_error ("%s", error->message);
g_error_free (error);
return;
}
setup_main_window (d);
d->password_dialog = um_password_dialog_new ();
button = get_widget (d, "user-icon-button");
d->photo_dialog = um_photo_dialog_new (button);
d->main_box = get_widget (d, "accounts-vbox");
gtk_widget_reparent (d->main_box, GTK_WIDGET (self));
context = gtk_widget_get_style_context (get_widget (d, "list-scrolledwindow"));
gtk_style_context_set_junction_sides (context, GTK_JUNCTION_BOTTOM);
context = gtk_widget_get_style_context (get_widget (d, "add-remove-toolbar"));
gtk_style_context_set_junction_sides (context, GTK_JUNCTION_TOP);
g_object_unref (dummy);
}
static void
um_user_panel_dispose (GObject *object)
{
UmUserPanelPrivate *priv = UM_USER_PANEL (object)->priv;
if (priv->um) {
g_object_unref (priv->um);
priv->um = NULL;
}
if (priv->builder) {
g_object_unref (priv->builder);
priv->builder = NULL;
}
if (priv->password_dialog) {
um_password_dialog_free (priv->password_dialog);
priv->password_dialog = NULL;
}
if (priv->photo_dialog) {
um_photo_dialog_free (priv->photo_dialog);
priv->photo_dialog = NULL;
}
if (priv->language_chooser) {
gtk_widget_destroy (priv->language_chooser);
priv->language_chooser = NULL;
}
if (priv->permission) {
g_object_unref (priv->permission);
priv->permission = NULL;
}
G_OBJECT_CLASS (um_user_panel_parent_class)->dispose (object);
}
static GPermission *
um_user_panel_get_permission (CcPanel *panel)
{
UmUserPanelPrivate *priv = UM_USER_PANEL (panel)->priv;
return priv->permission;
}
static const char *
um_user_panel_get_help_uri (CcPanel *panel)
{
if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity"))
return "help:ubuntu-help/user-accounts";
else
return "help:gnome-help/user-accounts";
}
static void
um_user_panel_class_init (UmUserPanelClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
CcPanelClass *panel_class = CC_PANEL_CLASS (klass);
object_class->dispose = um_user_panel_dispose;
panel_class->get_permission = um_user_panel_get_permission;
panel_class->get_help_uri = um_user_panel_get_help_uri;
g_type_class_add_private (klass, sizeof (UmUserPanelPrivate));
}
void
um_user_panel_register (GIOModule *module)
{
bindtextdomain (GETTEXT_PACKAGE, LOCALE_DIR);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
um_user_panel_register_type (G_TYPE_MODULE (module));
g_io_extension_point_implement (CC_SHELL_PANEL_EXTENSION_POINT,
UM_TYPE_USER_PANEL, "user-accounts", 0);
}
|
352 | ./cinnamon-control-center/panels/user-accounts/um-user.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2004-2005 James M. Cape <[email protected]>.
* Copyright (C) 2007-2008 William Jon McCann <[email protected]>
* Copyright (C) 2009 Red Hat, Inc.
*
* 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
*/
#define _XOPEN_SOURCE
#include "config.h"
#include <float.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <glib/gstdio.h>
#include <gio/gio.h>
#include <gtk/gtk.h>
#include <gio/gunixoutputstream.h>
#include "um-user.h"
#include "um-account-type.h"
#include "um-utils.h"
#define UM_USER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), UM_TYPE_USER, UmUserClass))
#define UM_IS_USER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), UM_TYPE_USER))
#define UM_USER_GET_CLASS(object) (G_TYPE_INSTANCE_GET_CLASS ((object), UM_TYPE_USER, UmUserClass))
#define MAX_FILE_SIZE 65536
typedef struct {
uid_t uid;
gchar *user_name;
gchar *real_name;
gint account_type;
gint password_mode;
gchar *password_hint;
gchar *email;
gchar *language;
gchar *location;
guint64 login_frequency;
gchar *icon_file;
gboolean locked;
gboolean automatic_login;
gboolean system_account;
gboolean local_account;
gchar *home_dir;
} UserProperties;
static void
user_properties_free (UserProperties *props)
{
g_free (props->user_name);
g_free (props->real_name);
g_free (props->password_hint);
g_free (props->email);
g_free (props->language);
g_free (props->location);
g_free (props->icon_file);
g_free (props);
}
static UserProperties *
user_properties_get (GDBusConnection *bus,
const gchar *object_path)
{
GVariant *result;
GVariantIter *iter;
gchar *key;
GVariant *value;
UserProperties *props;
GError *error = NULL;
result = g_dbus_connection_call_sync (bus,
"org.freedesktop.Accounts",
object_path,
"org.freedesktop.DBus.Properties",
"GetAll",
g_variant_new ("(s)", "org.freedesktop.Accounts.User"),
G_VARIANT_TYPE ("(a{sv})"),
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
&error);
if (!result) {
g_debug ("Error calling GetAll() when retrieving properties for %s: %s", object_path, error->message);
g_error_free (error);
return NULL;
}
/* Add some defaults that may not be received from some AccountsService versions */
props = g_new0 (UserProperties, 1);
props->local_account = TRUE;
g_variant_get (result, "(a{sv})", &iter);
while (g_variant_iter_loop (iter, "{&sv}", &key, &value)) {
if (strcmp (key, "Uid") == 0) {
g_variant_get (value, "t", &props->uid);
}
else if (strcmp (key, "UserName") == 0) {
g_variant_get (value, "s", &props->user_name);
}
else if (strcmp (key, "RealName") == 0) {
g_variant_get (value, "s", &props->real_name);
}
else if (strcmp (key, "AccountType") == 0) {
g_variant_get (value, "i", &props->account_type);
}
else if (strcmp (key, "Email") == 0) {
g_variant_get (value, "s", &props->email);
}
else if (strcmp (key, "Language") == 0) {
g_variant_get (value, "s", &props->language);
}
else if (strcmp (key, "Location") == 0) {
g_variant_get (value, "s", &props->location);
}
else if (strcmp (key, "LoginFrequency") == 0) {
g_variant_get (value, "t", &props->login_frequency);
}
else if (strcmp (key, "IconFile") == 0) {
g_variant_get (value, "s", &props->icon_file);
}
else if (strcmp (key, "Locked") == 0) {
g_variant_get (value, "b", &props->locked);
}
else if (strcmp (key, "AutomaticLogin") == 0) {
g_variant_get (value, "b", &props->automatic_login);
}
else if (strcmp (key, "SystemAccount") == 0) {
g_variant_get (value, "b", &props->system_account);
}
else if (strcmp (key, "LocalAccount") == 0) {
g_variant_get (value, "b", &props->local_account);
}
else if (strcmp (key, "PasswordMode") == 0) {
g_variant_get (value, "i", &props->password_mode);
}
else if (strcmp (key, "PasswordHint") == 0) {
g_variant_get (value, "s", &props->password_hint);
}
else if (strcmp (key, "HomeDirectory") == 0) {
g_variant_get (value, "s", &props->home_dir);
}
else if (strcmp (key, "Shell") == 0) {
/* ignore */
}
else {
g_debug ("unhandled property %s", key);
}
}
g_variant_iter_free (iter);
g_variant_unref (result);
return props;
}
struct _UmUser {
GObject parent;
GDBusConnection *bus;
GDBusProxy *proxy;
gchar *object_path;
UserProperties *props;
gchar *display_name;
};
typedef struct _UmUserClass
{
GObjectClass parent_class;
} UmUserClass;
enum {
CHANGED,
LAST_SIGNAL
};
static guint signals[LAST_SIGNAL] = { 0 };
static void um_user_finalize (GObject *object);
G_DEFINE_TYPE (UmUser, um_user, G_TYPE_OBJECT)
static void
um_user_class_init (UmUserClass *class)
{
GObjectClass *gobject_class;
gobject_class = G_OBJECT_CLASS (class);
gobject_class->finalize = um_user_finalize;
signals[CHANGED] = g_signal_new ("changed",
G_TYPE_FROM_CLASS (class),
G_SIGNAL_RUN_LAST,
0,
NULL, NULL,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
}
static void
um_user_init (UmUser *user)
{
}
static void
um_user_finalize (GObject *object)
{
UmUser *user;
user = UM_USER (object);
g_free (user->display_name);
g_object_unref (user->bus);
g_free (user->object_path);
if (user->proxy != NULL)
g_object_unref (user->proxy);
if (user->props != NULL)
user_properties_free (user->props);
(*G_OBJECT_CLASS (um_user_parent_class)->finalize) (object);
}
uid_t
um_user_get_uid (UmUser *user)
{
g_return_val_if_fail (UM_IS_USER (user), -1);
return user->props->uid;
}
const gchar *
um_user_get_real_name (UmUser *user)
{
g_return_val_if_fail (UM_IS_USER (user), NULL);
return user->props->real_name;
}
const gchar *
um_user_get_display_name (UmUser *user)
{
g_return_val_if_fail (UM_IS_USER (user), NULL);
if (user->display_name)
return user->display_name;
if (user->props->real_name &&
*user->props->real_name != '\0')
return user->props->real_name;
return user->props->user_name;
}
const gchar *
um_user_get_user_name (UmUser *user)
{
g_return_val_if_fail (UM_IS_USER (user), NULL);
return user->props->user_name;
}
gint
um_user_get_account_type (UmUser *user)
{
g_return_val_if_fail (UM_IS_USER (user), UM_ACCOUNT_TYPE_STANDARD);
return user->props->account_type;
}
gulong
um_user_get_login_frequency (UmUser *user)
{
g_return_val_if_fail (UM_IS_USER (user), 0);
return user->props->login_frequency;
}
gint
um_user_collate (UmUser *user1,
UmUser *user2)
{
const char *str1;
const char *str2;
gulong num1;
gulong num2;
g_return_val_if_fail (UM_IS_USER (user1), 0);
g_return_val_if_fail (UM_IS_USER (user2), 0);
num1 = user1->props->login_frequency;
num2 = user2->props->login_frequency;
if (num1 > num2) {
return -1;
}
if (num1 < num2) {
return 1;
}
/* if login frequency is equal try names */
if (user1->props->real_name != NULL) {
str1 = user1->props->real_name;
} else {
str1 = user1->props->user_name;
}
if (user2->props->real_name != NULL) {
str2 = user2->props->real_name;
} else {
str2 = user2->props->user_name;
}
if (str1 == NULL && str2 != NULL) {
return -1;
}
if (str1 != NULL && str2 == NULL) {
return 1;
}
if (str1 == NULL && str2 == NULL) {
return 0;
}
return g_utf8_collate (str1, str2);
}
static gboolean
check_user_file (const char *filename,
gssize max_file_size)
{
struct stat fileinfo;
if (max_file_size < 0) {
max_file_size = G_MAXSIZE;
}
/* Exists/Readable? */
if (stat (filename, &fileinfo) < 0) {
g_debug ("File does not exist");
return FALSE;
}
/* Is a regular file */
if (G_UNLIKELY (!S_ISREG (fileinfo.st_mode))) {
g_debug ("File is not a regular file");
return FALSE;
}
/* Size is kosher? */
if (G_UNLIKELY (fileinfo.st_size > max_file_size)) {
g_debug ("File is too large");
return FALSE;
}
return TRUE;
}
static GdkPixbuf *
frame_pixbuf (GdkPixbuf *source)
{
GdkPixbuf *dest;
cairo_t *cr;
cairo_surface_t *surface;
guint w;
guint h;
int frame_width;
double radius;
frame_width = 2;
w = gdk_pixbuf_get_width (source) + frame_width * 2;
h = gdk_pixbuf_get_height (source) + frame_width * 2;
radius = w / 10;
surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
w, h);
cr = cairo_create (surface);
cairo_surface_destroy (surface);
/* set up image */
cairo_rectangle (cr, 0, 0, w, h);
cairo_set_source_rgba (cr, 1.0, 1.0, 1.0, 0.0);
cairo_fill (cr);
rounded_rectangle (cr, 1.0, 0.5, 0.5, radius, w - 1, h - 1);
cairo_set_source_rgba (cr, 0.5, 0.5, 0.5, 0.3);
cairo_fill_preserve (cr);
gdk_cairo_set_source_pixbuf (cr, source, frame_width, frame_width);
cairo_fill (cr);
dest = gdk_pixbuf_get_from_surface (surface, 0, 0, w, h);
cairo_destroy (cr);
return dest;
}
GdkPixbuf *
um_user_render_icon (UmUser *user,
gboolean with_frame,
gint icon_size)
{
GdkPixbuf *pixbuf;
GdkPixbuf *framed;
gboolean res;
GError *error;
g_return_val_if_fail (UM_IS_USER (user), NULL);
g_return_val_if_fail (icon_size > 12, NULL);
pixbuf = NULL;
if (user->props->icon_file) {
res = check_user_file (user->props->icon_file,
MAX_FILE_SIZE);
if (res) {
pixbuf = gdk_pixbuf_new_from_file_at_size (user->props->icon_file,
icon_size,
icon_size,
NULL);
}
else {
pixbuf = NULL;
}
}
if (pixbuf != NULL) {
goto out;
}
error = NULL;
pixbuf = gtk_icon_theme_load_icon (gtk_icon_theme_get_default (),
"avatar-default",
icon_size,
GTK_ICON_LOOKUP_FORCE_SIZE,
&error);
if (error) {
g_warning ("%s", error->message);
g_error_free (error);
}
out:
if (pixbuf != NULL && with_frame) {
framed = frame_pixbuf (pixbuf);
if (framed != NULL) {
g_object_unref (pixbuf);
pixbuf = framed;
}
}
return pixbuf;
}
const gchar *
um_user_get_email (UmUser *user)
{
g_return_val_if_fail (UM_IS_USER (user), NULL);
return user->props->email;
}
const gchar *
um_user_get_language (UmUser *user)
{
g_return_val_if_fail (UM_IS_USER (user), NULL);
if (*user->props->language == '\0')
return NULL;
return user->props->language;
}
const gchar *
um_user_get_location (UmUser *user)
{
g_return_val_if_fail (UM_IS_USER (user), NULL);
return user->props->location;
}
gint
um_user_get_password_mode (UmUser *user)
{
g_return_val_if_fail (UM_IS_USER (user), UM_PASSWORD_MODE_NONE);
return user->props->password_mode;
}
const char *
um_user_get_password_hint (UmUser *user)
{
g_return_val_if_fail (UM_IS_USER (user), NULL);
return user->props->password_hint;
}
const char *
um_user_get_icon_file (UmUser *user)
{
g_return_val_if_fail (UM_IS_USER (user), NULL);
return user->props->icon_file;
}
gboolean
um_user_get_locked (UmUser *user)
{
g_return_val_if_fail (UM_IS_USER (user), FALSE);
return user->props->locked;
}
gboolean
um_user_get_automatic_login (UmUser *user)
{
g_return_val_if_fail (UM_IS_USER (user), FALSE);
return user->props->automatic_login;
}
gboolean
um_user_is_system_account (UmUser *user)
{
g_return_val_if_fail (UM_IS_USER (user), FALSE);
return user->props->system_account;
}
gboolean
um_user_is_local_account (UmUser *user)
{
g_return_val_if_fail (UM_IS_USER (user), FALSE);
return user->props->local_account;
}
const gchar *
um_user_get_object_path (UmUser *user)
{
g_return_val_if_fail (UM_IS_USER (user), NULL);
return user->object_path;
}
const gchar *
um_user_get_home_directory (UmUser *user)
{
g_return_val_if_fail (UM_IS_USER (user), NULL);
return user->props->home_dir;
}
static gboolean
update_info (UmUser *user)
{
UserProperties *props;
props = user_properties_get (user->bus, user->object_path);
if (props != NULL) {
if (user->props != NULL)
user_properties_free (user->props);
user->props = props;
return TRUE;
}
else {
return FALSE;
}
}
static void
user_signal_cb (GDBusProxy *proxy, gchar *sender_name, gchar *signal_name, GVariant *parameters, UmUser *user)
{
if (strcmp (signal_name, "Changed") == 0) {
if (update_info (user)) {
if (user->display_name != NULL) {
um_user_show_full_display_name (user);
}
g_signal_emit (user, signals[CHANGED], 0);
}
}
}
UmUser *
um_user_new_from_object_path (const gchar *object_path)
{
UmUser *user;
GError *error = NULL;
user = (UmUser *)g_object_new (UM_TYPE_USER, NULL);
user->object_path = g_strdup (object_path);
user->bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error);
if (user->bus == NULL) {
g_warning ("Couldn't connect to system bus: %s", error->message);
g_error_free (error);
goto error;
}
user->proxy = g_dbus_proxy_new_sync (user->bus,
G_DBUS_PROXY_FLAGS_NONE,
NULL,
"org.freedesktop.Accounts",
user->object_path,
"org.freedesktop.Accounts.User",
NULL,
&error);
if (user->proxy == NULL) {
g_warning ("Couldn't get user proxy: %s", error->message);
g_error_free (error);
goto error;
}
g_dbus_proxy_set_default_timeout (user->proxy, INT_MAX);
g_signal_connect (user->proxy, "g-signal", G_CALLBACK (user_signal_cb), user);
if (!update_info (user))
goto error;
return user;
error:
g_object_unref (user);
return NULL;
}
void
um_user_set_email (UmUser *user,
const gchar *email)
{
GVariant *result;
GError *error = NULL;
result = g_dbus_proxy_call_sync (user->proxy, "SetEmail", g_variant_new ("(s)", email), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
if (!result) {
g_warning ("SetEmail call failed: %s", error->message);
g_error_free (error);
return;
}
g_variant_unref (result);
}
void
um_user_set_language (UmUser *user,
const gchar *language)
{
GVariant *result;
GError *error = NULL;
result = g_dbus_proxy_call_sync (user->proxy, "SetLanguage", g_variant_new ("(s)", language), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
if (!result) {
g_warning ("SetLanguage call failed: %s", error->message);
g_error_free (error);
return;
}
g_variant_unref (result);
}
void
um_user_set_location (UmUser *user,
const gchar *location)
{
GVariant *result;
GError *error = NULL;
result = g_dbus_proxy_call_sync (user->proxy, "SetLocation", g_variant_new ("(s)", location), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
if (!result) {
g_warning ("SetLocation call failed: %s", error->message);
g_error_free (error);
return;
}
g_variant_unref (result);
}
void
um_user_set_user_name (UmUser *user,
const gchar *user_name)
{
GVariant *result;
GError *error = NULL;
result = g_dbus_proxy_call_sync (user->proxy, "SetUserName", g_variant_new ("(s)", user_name), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
if (!result) {
g_warning ("SetUserName call failed: %s", error->message);
g_error_free (error);
return;
}
g_variant_unref (result);
}
void
um_user_set_real_name (UmUser *user,
const gchar *real_name)
{
GVariant *result;
GError *error = NULL;
result = g_dbus_proxy_call_sync (user->proxy, "SetRealName", g_variant_new ("(s)", real_name), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
if (!result) {
g_warning ("SetRealName call failed: %s", error->message);
g_error_free (error);
return;
}
g_variant_unref (result);
}
void
um_user_set_icon_file (UmUser *user,
const gchar *icon_file)
{
GVariant *result;
GError *error = NULL;
result = g_dbus_proxy_call_sync (user->proxy, "SetIconFile", g_variant_new ("(s)", icon_file ? icon_file : ""), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
if (!result) {
g_warning ("SetIconFile call failed: %s", error->message);
g_error_free (error);
return;
}
g_variant_unref (result);
if (um_user_is_logged_in (user)) {
gchar *target = g_build_filename (user->props->home_dir, ".face", NULL);
GFile *face_file = g_file_new_for_path (target);
g_file_delete (face_file, NULL, NULL);
if (icon_file != NULL) {
GFile *source_file = g_file_new_for_path (icon_file);
if (!g_file_copy (source_file,
face_file,
G_FILE_COPY_TARGET_DEFAULT_PERMS | G_FILE_COPY_OVERWRITE,
NULL,
NULL,
NULL,
&error)) {
g_warning ("failed to copy account pic to .face file: %s", error->message);
g_error_free (error);
}
g_object_unref (source_file);
}
g_free (target);
g_object_unref (face_file);
}
}
void
um_user_set_icon_data (UmUser *user,
GdkPixbuf *pixbuf)
{
gint fd;
GOutputStream *stream;
GError *error;
gchar *path;
path = g_build_filename (g_get_tmp_dir (), "usericonXXXXXX", NULL);
fd = g_mkstemp (path);
if (fd == -1) {
g_warning ("failed to create temporary file for image data");
g_free (path);
}
stream = g_unix_output_stream_new (fd, TRUE);
error = NULL;
if (!gdk_pixbuf_save_to_stream (pixbuf, stream, "png", NULL, &error, NULL)) {
g_warning ("failed to save image: %s", error->message);
g_error_free (error);
g_object_unref (stream);
return;
}
g_object_unref (stream);
um_user_set_icon_file (user, path);
g_free (path);
}
void
um_user_set_account_type (UmUser *user,
gint account_type)
{
GVariant *result;
GError *error = NULL;
result = g_dbus_proxy_call_sync (user->proxy, "SetAccountType", g_variant_new ("(i)", account_type), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
if (!result) {
g_warning ("SetAccountType call failed: %s", error->message);
g_error_free (error);
return;
}
g_variant_unref (result);
}
static gchar
salt_char (GRand *rand)
{
gchar salt[] = "ABCDEFGHIJKLMNOPQRSTUVXYZ"
"abcdefghijklmnopqrstuvxyz"
"./0123456789";
return salt[g_rand_int_range (rand, 0, G_N_ELEMENTS (salt))];
}
static gchar *
make_crypted (const gchar *plain)
{
GString *salt;
gchar *result;
GRand *rand;
gint i;
rand = g_rand_new ();
salt = g_string_sized_new (21);
/* SHA 256 */
g_string_append (salt, "$6$");
for (i = 0; i < 16; i++) {
g_string_append_c (salt, salt_char (rand));
}
g_string_append_c (salt, '$');
result = g_strdup (crypt (plain, salt->str));
g_string_free (salt, TRUE);
g_rand_free (rand);
return result;
}
void
um_user_set_password (UmUser *user,
gint password_mode,
const gchar *password,
const gchar *hint)
{
GError *error = NULL;
gchar *crypted;
if (password_mode == 0) {
GVariant *result;
crypted = make_crypted (password);
result = g_dbus_proxy_call_sync (user->proxy, "SetPassword", g_variant_new ("(ss)", crypted, hint), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
if (!result) {
g_warning ("SetPassword call failed: %s", error->message);
g_error_free (error);
}
else
g_variant_unref (result);
memset (crypted, 0, strlen (crypted));
g_free (crypted);
}
else if (password_mode == 3 || password_mode == 4) {
GVariant *result;
/* FIXME: this is a slightly odd side-effect:
* you disable the account, and autologin flips
* we should remove that once gdm knows to
* ignore autologin for disabled accounts
*/
if (password_mode == 3 &&
um_user_get_automatic_login (user)) {
um_user_set_automatic_login (user, FALSE);
}
result = g_dbus_proxy_call_sync (user->proxy, "SetLocked", g_variant_new ("(b)", password_mode == 3), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
if (!result) {
g_warning ("SetLocked call failed: %s", error->message);
g_error_free (error);
}
else
g_variant_unref (result);
}
else {
GVariant *result;
result = g_dbus_proxy_call_sync (user->proxy, "SetPasswordMode", g_variant_new ("(i)", password_mode), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
if (!result) {
g_warning ("SetPasswordMode call failed: %s", error->message);
g_error_free (error);
}
else
g_variant_unref (result);
}
}
#ifdef HAVE_SYSTEMD
#include <systemd/sd-login.h>
gboolean
um_user_is_logged_in (UmUser *user)
{
int n_sessions;
n_sessions = sd_uid_get_sessions (um_user_get_uid (user), 0, NULL) > 0;
return n_sessions > 0;
}
#else
gboolean
um_user_is_logged_in (UmUser *user)
{
GVariant *result;
GVariantIter *iter;
gint n_sessions;
GError *error = NULL;
result = g_dbus_connection_call_sync (user->bus,
"org.freedesktop.ConsoleKit",
"/org/freedesktop/ConsoleKit/Manager",
"org.freedesktop.ConsoleKit.Manager",
"GetSessionsForUnixUser",
g_variant_new ("(u)", um_user_get_uid (user)),
G_VARIANT_TYPE ("(ao)"),
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
&error);
if (!result) {
g_warning ("GetSessionsForUnixUser failed: %s", error->message);
g_error_free (error);
return FALSE;
}
g_variant_get (result, "(ao)", &iter);
n_sessions = g_variant_iter_n_children (iter);
g_variant_iter_free (iter);
g_variant_unref (result);
return n_sessions > 0;
}
#endif
void
um_user_set_automatic_login (UmUser *user,
gboolean enabled)
{
GVariant *result;
GError *error = NULL;
result = g_dbus_proxy_call_sync (user->proxy, "SetAutomaticLogin", g_variant_new ("(b)", enabled), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
if (!result) {
g_warning ("SetAutomaticLogin call failed: %s", error->message);
g_error_free (error);
return;
}
g_variant_unref (result);
}
void
um_user_show_full_display_name (UmUser *user)
{
char *uniq_name;
g_return_if_fail (UM_IS_USER (user));
if (user->props->real_name != NULL) {
uniq_name = g_strdup_printf ("%s (%s)",
user->props->real_name,
user->props->user_name);
} else {
uniq_name = NULL;
}
if (uniq_name && g_strcmp0 (uniq_name, user->display_name) != 0) {
g_free (user->display_name);
user->display_name = uniq_name;
}
else {
g_free (uniq_name);
}
}
void
um_user_show_short_display_name (UmUser *user)
{
g_return_if_fail (UM_IS_USER (user));
if (user->display_name) {
g_free (user->display_name);
user->display_name = NULL;
}
}
|
353 | ./cinnamon-control-center/panels/sound/gvc-mixer-stream.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2008 William Jon McCann
*
* 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.
*
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <pulse/pulseaudio.h>
#include "gvc-mixer-stream.h"
#include "gvc-mixer-stream-private.h"
#include "gvc-channel-map-private.h"
#define GVC_MIXER_STREAM_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GVC_TYPE_MIXER_STREAM, GvcMixerStreamPrivate))
static guint32 stream_serial = 1;
struct GvcMixerStreamPrivate
{
pa_context *pa_context;
guint id;
guint index;
gint card_index;
GvcChannelMap *channel_map;
char *name;
char *description;
char *application_id;
char *icon_name;
char *sysfs_path;
gboolean is_muted;
gboolean can_decibel;
gboolean is_event_stream;
gboolean is_virtual;
pa_volume_t base_volume;
pa_operation *change_volume_op;
char *port;
char *human_port;
GList *ports;
};
enum
{
PROP_0,
PROP_ID,
PROP_PA_CONTEXT,
PROP_CHANNEL_MAP,
PROP_INDEX,
PROP_NAME,
PROP_DESCRIPTION,
PROP_APPLICATION_ID,
PROP_ICON_NAME,
PROP_SYSFS_PATH,
PROP_VOLUME,
PROP_DECIBEL,
PROP_IS_MUTED,
PROP_CAN_DECIBEL,
PROP_IS_EVENT_STREAM,
PROP_IS_VIRTUAL,
PROP_CARD_INDEX,
PROP_PORT,
};
static void gvc_mixer_stream_class_init (GvcMixerStreamClass *klass);
static void gvc_mixer_stream_init (GvcMixerStream *mixer_stream);
static void gvc_mixer_stream_finalize (GObject *object);
G_DEFINE_ABSTRACT_TYPE (GvcMixerStream, gvc_mixer_stream, G_TYPE_OBJECT)
static guint32
get_next_stream_serial (void)
{
guint32 serial;
serial = stream_serial++;
if ((gint32)stream_serial < 0) {
stream_serial = 1;
}
return serial;
}
pa_context *
gvc_mixer_stream_get_pa_context (GvcMixerStream *stream)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), 0);
return stream->priv->pa_context;
}
guint
gvc_mixer_stream_get_index (GvcMixerStream *stream)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), 0);
return stream->priv->index;
}
guint
gvc_mixer_stream_get_id (GvcMixerStream *stream)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), 0);
return stream->priv->id;
}
const GvcChannelMap *
gvc_mixer_stream_get_channel_map (GvcMixerStream *stream)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), NULL);
return stream->priv->channel_map;
}
/**
* gvc_mixer_stream_get_volume:
*
* @stream:
*
* Returns: (type guint32) (transfer none):
*/
pa_volume_t
gvc_mixer_stream_get_volume (GvcMixerStream *stream)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), 0);
return (pa_volume_t) gvc_channel_map_get_volume(stream->priv->channel_map)[VOLUME];
}
gdouble
gvc_mixer_stream_get_decibel (GvcMixerStream *stream)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), 0);
return pa_sw_volume_to_dB(
(pa_volume_t) gvc_channel_map_get_volume(stream->priv->channel_map)[VOLUME]);
}
/**
* gvc_mixer_stream_set_volume:
*
* @stream:
* @volume: (type guint32):
*
* Returns:
*/
gboolean
gvc_mixer_stream_set_volume (GvcMixerStream *stream,
pa_volume_t volume)
{
pa_cvolume cv;
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
cv = *gvc_channel_map_get_cvolume(stream->priv->channel_map);
pa_cvolume_scale(&cv, volume);
if (!pa_cvolume_equal(gvc_channel_map_get_cvolume(stream->priv->channel_map), &cv)) {
gvc_channel_map_volume_changed(stream->priv->channel_map, &cv, FALSE);
g_object_notify (G_OBJECT (stream), "volume");
return TRUE;
}
return FALSE;
}
gboolean
gvc_mixer_stream_set_decibel (GvcMixerStream *stream,
gdouble db)
{
pa_cvolume cv;
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
cv = *gvc_channel_map_get_cvolume(stream->priv->channel_map);
pa_cvolume_scale(&cv, pa_sw_volume_from_dB(db));
if (!pa_cvolume_equal(gvc_channel_map_get_cvolume(stream->priv->channel_map), &cv)) {
gvc_channel_map_volume_changed(stream->priv->channel_map, &cv, FALSE);
g_object_notify (G_OBJECT (stream), "volume");
}
return TRUE;
}
gboolean
gvc_mixer_stream_get_is_muted (GvcMixerStream *stream)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
return stream->priv->is_muted;
}
gboolean
gvc_mixer_stream_get_can_decibel (GvcMixerStream *stream)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
return stream->priv->can_decibel;
}
gboolean
gvc_mixer_stream_set_is_muted (GvcMixerStream *stream,
gboolean is_muted)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
if (is_muted != stream->priv->is_muted) {
stream->priv->is_muted = is_muted;
g_object_notify (G_OBJECT (stream), "is-muted");
}
return TRUE;
}
gboolean
gvc_mixer_stream_set_can_decibel (GvcMixerStream *stream,
gboolean can_decibel)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
if (can_decibel != stream->priv->can_decibel) {
stream->priv->can_decibel = can_decibel;
g_object_notify (G_OBJECT (stream), "can-decibel");
}
return TRUE;
}
const char *
gvc_mixer_stream_get_name (GvcMixerStream *stream)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), NULL);
return stream->priv->name;
}
const char *
gvc_mixer_stream_get_description (GvcMixerStream *stream)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), NULL);
return stream->priv->description;
}
gboolean
gvc_mixer_stream_set_name (GvcMixerStream *stream,
const char *name)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
g_free (stream->priv->name);
stream->priv->name = g_strdup (name);
g_object_notify (G_OBJECT (stream), "name");
return TRUE;
}
gboolean
gvc_mixer_stream_set_description (GvcMixerStream *stream,
const char *description)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
g_free (stream->priv->description);
stream->priv->description = g_strdup (description);
g_object_notify (G_OBJECT (stream), "description");
return TRUE;
}
gboolean
gvc_mixer_stream_is_event_stream (GvcMixerStream *stream)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
return stream->priv->is_event_stream;
}
gboolean
gvc_mixer_stream_set_is_event_stream (GvcMixerStream *stream,
gboolean is_event_stream)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
stream->priv->is_event_stream = is_event_stream;
g_object_notify (G_OBJECT (stream), "is-event-stream");
return TRUE;
}
gboolean
gvc_mixer_stream_is_virtual (GvcMixerStream *stream)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
return stream->priv->is_virtual;
}
gboolean
gvc_mixer_stream_set_is_virtual (GvcMixerStream *stream,
gboolean is_virtual)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
stream->priv->is_virtual = is_virtual;
g_object_notify (G_OBJECT (stream), "is-virtual");
return TRUE;
}
const char *
gvc_mixer_stream_get_application_id (GvcMixerStream *stream)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), NULL);
return stream->priv->application_id;
}
gboolean
gvc_mixer_stream_set_application_id (GvcMixerStream *stream,
const char *application_id)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
g_free (stream->priv->application_id);
stream->priv->application_id = g_strdup (application_id);
g_object_notify (G_OBJECT (stream), "application-id");
return TRUE;
}
static void
on_channel_map_volume_changed (GvcChannelMap *channel_map,
gboolean set,
GvcMixerStream *stream)
{
if (set == TRUE)
gvc_mixer_stream_push_volume (stream);
g_object_notify (G_OBJECT (stream), "volume");
}
static gboolean
gvc_mixer_stream_set_channel_map (GvcMixerStream *stream,
GvcChannelMap *channel_map)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
if (channel_map != NULL) {
g_object_ref (channel_map);
}
if (stream->priv->channel_map != NULL) {
g_signal_handlers_disconnect_by_func (stream->priv->channel_map,
on_channel_map_volume_changed,
stream);
g_object_unref (stream->priv->channel_map);
}
stream->priv->channel_map = channel_map;
if (stream->priv->channel_map != NULL) {
g_signal_connect (stream->priv->channel_map,
"volume-changed",
G_CALLBACK (on_channel_map_volume_changed),
stream);
g_object_notify (G_OBJECT (stream), "channel-map");
}
return TRUE;
}
const char *
gvc_mixer_stream_get_icon_name (GvcMixerStream *stream)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), NULL);
return stream->priv->icon_name;
}
const char *
gvc_mixer_stream_get_sysfs_path (GvcMixerStream *stream)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), NULL);
return stream->priv->sysfs_path;
}
/**
* gvc_mixer_stream_get_gicon:
* @stream: a #GvcMixerStream
*
* Returns: (transfer full): a new #GIcon
*/
GIcon *
gvc_mixer_stream_get_gicon (GvcMixerStream *stream)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), NULL);
if (stream->priv->icon_name == NULL)
return NULL;
return g_themed_icon_new_with_default_fallbacks (stream->priv->icon_name);
}
gboolean
gvc_mixer_stream_set_icon_name (GvcMixerStream *stream,
const char *icon_name)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
g_free (stream->priv->icon_name);
stream->priv->icon_name = g_strdup (icon_name);
g_object_notify (G_OBJECT (stream), "icon-name");
return TRUE;
}
gboolean
gvc_mixer_stream_set_sysfs_path (GvcMixerStream *stream,
const char *sysfs_path)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
g_free (stream->priv->sysfs_path);
stream->priv->sysfs_path = g_strdup (sysfs_path);
g_object_notify (G_OBJECT (stream), "sysfs-path");
return TRUE;
}
/**
* gvc_mixer_stream_get_base_volume:
*
* @stream:
*
* Returns: (type guint32) (transfer none):
*/
pa_volume_t
gvc_mixer_stream_get_base_volume (GvcMixerStream *stream)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), 0);
return stream->priv->base_volume;
}
/**
* gvc_mixer_stream_set_base_volume:
*
* @stream:
* @base_volume: (type guint32):
*
* Returns:
*/
gboolean
gvc_mixer_stream_set_base_volume (GvcMixerStream *stream,
pa_volume_t base_volume)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
stream->priv->base_volume = base_volume;
return TRUE;
}
const GvcMixerStreamPort *
gvc_mixer_stream_get_port (GvcMixerStream *stream)
{
GList *l;
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), NULL);
g_return_val_if_fail (stream->priv->ports != NULL, NULL);
for (l = stream->priv->ports; l != NULL; l = l->next) {
GvcMixerStreamPort *p = l->data;
if (g_strcmp0 (stream->priv->port, p->port) == 0) {
return p;
}
}
g_assert_not_reached ();
return NULL;
}
gboolean
gvc_mixer_stream_set_port (GvcMixerStream *stream,
const char *port)
{
GList *l;
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
g_return_val_if_fail (stream->priv->ports != NULL, FALSE);
g_free (stream->priv->port);
stream->priv->port = g_strdup (port);
g_free (stream->priv->human_port);
stream->priv->human_port = NULL;
for (l = stream->priv->ports; l != NULL; l = l->next) {
GvcMixerStreamPort *p = l->data;
if (g_str_equal (stream->priv->port, p->port)) {
stream->priv->human_port = g_strdup (p->human_port);
break;
}
}
g_object_notify (G_OBJECT (stream), "port");
return TRUE;
}
gboolean
gvc_mixer_stream_change_port (GvcMixerStream *stream,
const char *port)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
return GVC_MIXER_STREAM_GET_CLASS (stream)->change_port (stream, port);
}
/**
* gvc_mixer_stream_get_ports:
*
* Return value: (transfer none) (element-type GvcMixerStreamPort):
*/
const GList *
gvc_mixer_stream_get_ports (GvcMixerStream *stream)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), NULL);
return stream->priv->ports;
}
static int
sort_ports (GvcMixerStreamPort *a,
GvcMixerStreamPort *b)
{
if (a->priority == b->priority)
return 0;
if (a->priority > b->priority)
return 1;
return -1;
}
/**
* gvc_mixer_stream_set_ports:
* @ports: (transfer full) (element-type GvcMixerStreamPort):
*/
gboolean
gvc_mixer_stream_set_ports (GvcMixerStream *stream,
GList *ports)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
g_return_val_if_fail (stream->priv->ports == NULL, FALSE);
stream->priv->ports = g_list_sort (ports, (GCompareFunc) sort_ports);
return TRUE;
}
gint
gvc_mixer_stream_get_card_index (GvcMixerStream *stream)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), PA_INVALID_INDEX);
return stream->priv->card_index;
}
gboolean
gvc_mixer_stream_set_card_index (GvcMixerStream *stream,
gint card_index)
{
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
stream->priv->card_index = card_index;
g_object_notify (G_OBJECT (stream), "card-index");
return TRUE;
}
static void
gvc_mixer_stream_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GvcMixerStream *self = GVC_MIXER_STREAM (object);
switch (prop_id) {
case PROP_PA_CONTEXT:
self->priv->pa_context = g_value_get_pointer (value);
break;
case PROP_INDEX:
self->priv->index = g_value_get_ulong (value);
break;
case PROP_ID:
self->priv->id = g_value_get_ulong (value);
break;
case PROP_CHANNEL_MAP:
gvc_mixer_stream_set_channel_map (self, g_value_get_object (value));
break;
case PROP_NAME:
gvc_mixer_stream_set_name (self, g_value_get_string (value));
break;
case PROP_DESCRIPTION:
gvc_mixer_stream_set_description (self, g_value_get_string (value));
break;
case PROP_APPLICATION_ID:
gvc_mixer_stream_set_application_id (self, g_value_get_string (value));
break;
case PROP_ICON_NAME:
gvc_mixer_stream_set_icon_name (self, g_value_get_string (value));
break;
case PROP_SYSFS_PATH:
gvc_mixer_stream_set_sysfs_path (self, g_value_get_string (value));
break;
case PROP_VOLUME:
gvc_mixer_stream_set_volume (self, g_value_get_ulong (value));
break;
case PROP_DECIBEL:
gvc_mixer_stream_set_decibel (self, g_value_get_double (value));
break;
case PROP_IS_MUTED:
gvc_mixer_stream_set_is_muted (self, g_value_get_boolean (value));
break;
case PROP_IS_EVENT_STREAM:
gvc_mixer_stream_set_is_event_stream (self, g_value_get_boolean (value));
break;
case PROP_IS_VIRTUAL:
gvc_mixer_stream_set_is_virtual (self, g_value_get_boolean (value));
break;
case PROP_CAN_DECIBEL:
gvc_mixer_stream_set_can_decibel (self, g_value_get_boolean (value));
break;
case PROP_PORT:
gvc_mixer_stream_set_port (self, g_value_get_string (value));
break;
case PROP_CARD_INDEX:
self->priv->card_index = g_value_get_long (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gvc_mixer_stream_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GvcMixerStream *self = GVC_MIXER_STREAM (object);
switch (prop_id) {
case PROP_PA_CONTEXT:
g_value_set_pointer (value, self->priv->pa_context);
break;
case PROP_INDEX:
g_value_set_ulong (value, self->priv->index);
break;
case PROP_ID:
g_value_set_ulong (value, self->priv->id);
break;
case PROP_CHANNEL_MAP:
g_value_set_object (value, self->priv->channel_map);
break;
case PROP_NAME:
g_value_set_string (value, self->priv->name);
break;
case PROP_DESCRIPTION:
g_value_set_string (value, self->priv->description);
break;
case PROP_APPLICATION_ID:
g_value_set_string (value, self->priv->application_id);
break;
case PROP_ICON_NAME:
g_value_set_string (value, self->priv->icon_name);
break;
case PROP_SYSFS_PATH:
g_value_set_string (value, self->priv->sysfs_path);
break;
case PROP_VOLUME:
g_value_set_ulong (value,
pa_cvolume_max(gvc_channel_map_get_cvolume(self->priv->channel_map)));
break;
case PROP_DECIBEL:
g_value_set_double (value,
pa_sw_volume_to_dB(pa_cvolume_max(gvc_channel_map_get_cvolume(self->priv->channel_map))));
break;
case PROP_IS_MUTED:
g_value_set_boolean (value, self->priv->is_muted);
break;
case PROP_IS_EVENT_STREAM:
g_value_set_boolean (value, self->priv->is_event_stream);
break;
case PROP_IS_VIRTUAL:
g_value_set_boolean (value, self->priv->is_virtual);
break;
case PROP_CAN_DECIBEL:
g_value_set_boolean (value, self->priv->can_decibel);
break;
case PROP_PORT:
g_value_set_string (value, self->priv->port);
break;
case PROP_CARD_INDEX:
g_value_set_long (value, self->priv->card_index);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static GObject *
gvc_mixer_stream_constructor (GType type,
guint n_construct_properties,
GObjectConstructParam *construct_params)
{
GObject *object;
GvcMixerStream *self;
object = G_OBJECT_CLASS (gvc_mixer_stream_parent_class)->constructor (type, n_construct_properties, construct_params);
self = GVC_MIXER_STREAM (object);
self->priv->id = get_next_stream_serial ();
return object;
}
static gboolean
gvc_mixer_stream_real_change_port (GvcMixerStream *stream,
const char *port)
{
return FALSE;
}
static gboolean
gvc_mixer_stream_real_push_volume (GvcMixerStream *stream, gpointer *op)
{
return FALSE;
}
static gboolean
gvc_mixer_stream_real_change_is_muted (GvcMixerStream *stream,
gboolean is_muted)
{
return FALSE;
}
gboolean
gvc_mixer_stream_push_volume (GvcMixerStream *stream)
{
pa_operation *op;
gboolean ret;
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
if (stream->priv->is_event_stream != FALSE)
return TRUE;
g_debug ("Pushing new volume to stream '%s' (%s)",
stream->priv->description, stream->priv->name);
ret = GVC_MIXER_STREAM_GET_CLASS (stream)->push_volume (stream, (gpointer *) &op);
if (ret) {
if (stream->priv->change_volume_op != NULL)
pa_operation_unref (stream->priv->change_volume_op);
stream->priv->change_volume_op = op;
}
return ret;
}
gboolean
gvc_mixer_stream_change_is_muted (GvcMixerStream *stream,
gboolean is_muted)
{
gboolean ret;
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
ret = GVC_MIXER_STREAM_GET_CLASS (stream)->change_is_muted (stream, is_muted);
return ret;
}
gboolean
gvc_mixer_stream_is_running (GvcMixerStream *stream)
{
if (stream->priv->change_volume_op == NULL)
return FALSE;
if ((pa_operation_get_state(stream->priv->change_volume_op) == PA_OPERATION_RUNNING))
return TRUE;
pa_operation_unref(stream->priv->change_volume_op);
stream->priv->change_volume_op = NULL;
return FALSE;
}
static void
gvc_mixer_stream_class_init (GvcMixerStreamClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
gobject_class->constructor = gvc_mixer_stream_constructor;
gobject_class->finalize = gvc_mixer_stream_finalize;
gobject_class->set_property = gvc_mixer_stream_set_property;
gobject_class->get_property = gvc_mixer_stream_get_property;
klass->push_volume = gvc_mixer_stream_real_push_volume;
klass->change_port = gvc_mixer_stream_real_change_port;
klass->change_is_muted = gvc_mixer_stream_real_change_is_muted;
g_object_class_install_property (gobject_class,
PROP_INDEX,
g_param_spec_ulong ("index",
"Index",
"The index for this stream",
0, G_MAXULONG, 0,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT_ONLY));
g_object_class_install_property (gobject_class,
PROP_ID,
g_param_spec_ulong ("id",
"id",
"The id for this stream",
0, G_MAXULONG, 0,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT_ONLY));
g_object_class_install_property (gobject_class,
PROP_CHANNEL_MAP,
g_param_spec_object ("channel-map",
"channel map",
"The channel map for this stream",
GVC_TYPE_CHANNEL_MAP,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (gobject_class,
PROP_PA_CONTEXT,
g_param_spec_pointer ("pa-context",
"PulseAudio context",
"The PulseAudio context for this stream",
G_PARAM_READWRITE|G_PARAM_CONSTRUCT_ONLY));
g_object_class_install_property (gobject_class,
PROP_VOLUME,
g_param_spec_ulong ("volume",
"Volume",
"The volume for this stream",
0, G_MAXULONG, 0,
G_PARAM_READWRITE));
g_object_class_install_property (gobject_class,
PROP_DECIBEL,
g_param_spec_double ("decibel",
"Decibel",
"The decibel level for this stream",
-G_MAXDOUBLE, G_MAXDOUBLE, 0,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (gobject_class,
PROP_NAME,
g_param_spec_string ("name",
"Name",
"Name to display for this stream",
NULL,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (gobject_class,
PROP_DESCRIPTION,
g_param_spec_string ("description",
"Description",
"Description to display for this stream",
NULL,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (gobject_class,
PROP_APPLICATION_ID,
g_param_spec_string ("application-id",
"Application identifier",
"Application identifier for this stream",
NULL,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (gobject_class,
PROP_ICON_NAME,
g_param_spec_string ("icon-name",
"Icon Name",
"Name of icon to display for this stream",
NULL,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (gobject_class,
PROP_SYSFS_PATH,
g_param_spec_string ("sysfs-path",
"Sysfs path",
"Sysfs path for the device associated with this stream",
NULL,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (gobject_class,
PROP_IS_MUTED,
g_param_spec_boolean ("is-muted",
"is muted",
"Whether stream is muted",
FALSE,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (gobject_class,
PROP_CAN_DECIBEL,
g_param_spec_boolean ("can-decibel",
"can decibel",
"Whether stream volume can be converted to decibel units",
FALSE,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (gobject_class,
PROP_IS_EVENT_STREAM,
g_param_spec_boolean ("is-event-stream",
"is event stream",
"Whether stream's role is to play an event",
FALSE,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (gobject_class,
PROP_IS_VIRTUAL,
g_param_spec_boolean ("is-virtual",
"is virtual stream",
"Whether the stream is virtual",
FALSE,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (gobject_class,
PROP_PORT,
g_param_spec_string ("port",
"Port",
"The name of the current port for this stream",
NULL,
G_PARAM_READWRITE));
g_object_class_install_property (gobject_class,
PROP_CARD_INDEX,
g_param_spec_long ("card-index",
"Card index",
"The index of the card for this stream",
PA_INVALID_INDEX, G_MAXLONG, PA_INVALID_INDEX,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_type_class_add_private (klass, sizeof (GvcMixerStreamPrivate));
}
static void
gvc_mixer_stream_init (GvcMixerStream *stream)
{
stream->priv = GVC_MIXER_STREAM_GET_PRIVATE (stream);
}
static void
free_port (GvcMixerStreamPort *p)
{
g_free (p->port);
g_free (p->human_port);
g_free (p);
}
static void
gvc_mixer_stream_finalize (GObject *object)
{
GvcMixerStream *mixer_stream;
g_return_if_fail (object != NULL);
g_return_if_fail (GVC_IS_MIXER_STREAM (object));
mixer_stream = GVC_MIXER_STREAM (object);
g_return_if_fail (mixer_stream->priv != NULL);
g_object_unref (mixer_stream->priv->channel_map);
mixer_stream->priv->channel_map = NULL;
g_free (mixer_stream->priv->name);
mixer_stream->priv->name = NULL;
g_free (mixer_stream->priv->description);
mixer_stream->priv->description = NULL;
g_free (mixer_stream->priv->application_id);
mixer_stream->priv->application_id = NULL;
g_free (mixer_stream->priv->icon_name);
mixer_stream->priv->icon_name = NULL;
g_free (mixer_stream->priv->sysfs_path);
mixer_stream->priv->sysfs_path = NULL;
g_free (mixer_stream->priv->port);
mixer_stream->priv->port = NULL;
g_free (mixer_stream->priv->human_port);
mixer_stream->priv->human_port = NULL;
g_list_foreach (mixer_stream->priv->ports, (GFunc) free_port, NULL);
g_list_free (mixer_stream->priv->ports);
mixer_stream->priv->ports = NULL;
if (mixer_stream->priv->change_volume_op) {
pa_operation_unref(mixer_stream->priv->change_volume_op);
mixer_stream->priv->change_volume_op = NULL;
}
G_OBJECT_CLASS (gvc_mixer_stream_parent_class)->finalize (object);
}
|
354 | ./cinnamon-control-center/panels/sound/gvc-combo-box.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2009 Bastien Nocera
*
* 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.
*
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <gtk/gtk.h>
#include <canberra-gtk.h>
#include <pulse/pulseaudio.h>
#include "gvc-combo-box.h"
#include "gvc-mixer-stream.h"
#include "gvc-mixer-card.h"
#define GVC_COMBO_BOX_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GVC_TYPE_COMBO_BOX, GvcComboBoxPrivate))
struct GvcComboBoxPrivate
{
GtkWidget *drop_box;
GtkWidget *start_box;
GtkWidget *end_box;
GtkWidget *label;
GtkWidget *button;
GtkTreeModel *model;
GtkWidget *combobox;
gboolean set_called;
GtkSizeGroup *size_group;
gboolean symmetric;
};
enum {
COL_NAME,
COL_HUMAN_NAME,
NUM_COLS
};
enum {
CHANGED,
BUTTON_CLICKED,
LAST_SIGNAL
};
enum {
PROP_0,
PROP_LABEL,
PROP_SHOW_BUTTON,
PROP_BUTTON_LABEL
};
static guint signals [LAST_SIGNAL] = { 0, };
static void gvc_combo_box_class_init (GvcComboBoxClass *klass);
static void gvc_combo_box_init (GvcComboBox *combo_box);
static void gvc_combo_box_finalize (GObject *object);
G_DEFINE_TYPE (GvcComboBox, gvc_combo_box, GTK_TYPE_HBOX)
void
gvc_combo_box_set_size_group (GvcComboBox *combo_box,
GtkSizeGroup *group,
gboolean symmetric)
{
g_return_if_fail (GVC_IS_COMBO_BOX (combo_box));
combo_box->priv->size_group = group;
combo_box->priv->symmetric = symmetric;
if (combo_box->priv->size_group != NULL) {
gtk_size_group_add_widget (combo_box->priv->size_group,
combo_box->priv->start_box);
if (combo_box->priv->symmetric) {
gtk_size_group_add_widget (combo_box->priv->size_group,
combo_box->priv->end_box);
}
}
gtk_widget_queue_draw (GTK_WIDGET (combo_box));
}
static void
gvc_combo_box_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GvcComboBox *self = GVC_COMBO_BOX (object);
switch (prop_id) {
case PROP_LABEL:
gtk_label_set_text_with_mnemonic (GTK_LABEL (self->priv->label), g_value_get_string (value));
break;
case PROP_BUTTON_LABEL:
gtk_button_set_label (GTK_BUTTON (self->priv->button), g_value_get_string (value));
break;
case PROP_SHOW_BUTTON:
gtk_widget_set_visible (self->priv->button, g_value_get_boolean (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gvc_combo_box_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GvcComboBox *self = GVC_COMBO_BOX (object);
switch (prop_id) {
case PROP_LABEL:
g_value_set_string (value,
gtk_label_get_text (GTK_LABEL (self->priv->label)));
break;
case PROP_BUTTON_LABEL:
g_value_set_string (value,
gtk_button_get_label (GTK_BUTTON (self->priv->button)));
break;
case PROP_SHOW_BUTTON:
g_value_set_boolean (value,
gtk_widget_get_visible (self->priv->button));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gvc_combo_box_class_init (GvcComboBoxClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->finalize = gvc_combo_box_finalize;
object_class->set_property = gvc_combo_box_set_property;
object_class->get_property = gvc_combo_box_get_property;
g_object_class_install_property (object_class,
PROP_LABEL,
g_param_spec_string ("label",
"label",
"The combo box label",
_("_Profile:"),
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (object_class,
PROP_SHOW_BUTTON,
g_param_spec_boolean ("show-button",
"show-button",
"Whether to show the button",
FALSE,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (object_class,
PROP_BUTTON_LABEL,
g_param_spec_string ("button-label",
"button-label",
"The button's label",
"APPLICATION BUG",
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
signals [CHANGED] =
g_signal_new ("changed",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GvcComboBoxClass, changed),
NULL, NULL,
g_cclosure_marshal_VOID__STRING,
G_TYPE_NONE, 1, G_TYPE_STRING);
signals [BUTTON_CLICKED] =
g_signal_new ("button-clicked",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GvcComboBoxClass, button_clicked),
NULL, NULL,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0, G_TYPE_NONE);
g_type_class_add_private (klass, sizeof (GvcComboBoxPrivate));
}
void
gvc_combo_box_set_profiles (GvcComboBox *combo_box,
const GList *profiles)
{
const GList *l;
g_return_if_fail (GVC_IS_COMBO_BOX (combo_box));
g_return_if_fail (combo_box->priv->set_called == FALSE);
for (l = profiles; l != NULL; l = l->next) {
GvcMixerCardProfile *p = l->data;
gtk_list_store_insert_with_values (GTK_LIST_STORE (combo_box->priv->model),
NULL,
G_MAXINT,
COL_NAME, p->profile,
COL_HUMAN_NAME, p->human_profile,
-1);
}
combo_box->priv->set_called = TRUE;
}
void
gvc_combo_box_set_ports (GvcComboBox *combo_box,
const GList *ports)
{
const GList *l;
g_return_if_fail (GVC_IS_COMBO_BOX (combo_box));
g_return_if_fail (combo_box->priv->set_called == FALSE);
for (l = ports; l != NULL; l = l->next) {
GvcMixerStreamPort *p = l->data;
gtk_list_store_insert_with_values (GTK_LIST_STORE (combo_box->priv->model),
NULL,
G_MAXINT,
COL_NAME, p->port,
COL_HUMAN_NAME, p->human_port,
-1);
}
combo_box->priv->set_called = TRUE;
}
void
gvc_combo_box_set_active (GvcComboBox *combo_box,
const char *id)
{
GtkTreeIter iter;
gboolean cont;
cont = gtk_tree_model_get_iter_first (combo_box->priv->model, &iter);
while (cont != FALSE) {
char *name;
gtk_tree_model_get (combo_box->priv->model, &iter,
COL_NAME, &name,
-1);
if (g_strcmp0 (name, id) == 0) {
gtk_combo_box_set_active_iter (GTK_COMBO_BOX (combo_box->priv->combobox), &iter);
return;
}
cont = gtk_tree_model_iter_next (combo_box->priv->model, &iter);
}
g_warning ("Could not find id '%s' in combo box", id);
}
static void
on_combo_box_changed (GtkComboBox *widget,
GvcComboBox *combo_box)
{
GtkTreeIter iter;
char *profile;
if (gtk_combo_box_get_active_iter (GTK_COMBO_BOX (widget), &iter) == FALSE) {
g_warning ("Could not find an active profile or port");
return;
}
gtk_tree_model_get (combo_box->priv->model, &iter,
COL_NAME, &profile,
-1);
g_signal_emit (combo_box, signals[CHANGED], 0, profile);
g_free (profile);
}
static void
on_combo_box_button_clicked (GtkButton *button,
GvcComboBox *combo_box)
{
g_signal_emit (combo_box, signals[BUTTON_CLICKED], 0);
}
static void
gvc_combo_box_init (GvcComboBox *combo_box)
{
GtkWidget *frame;
GtkWidget *box;
GtkWidget *sbox;
GtkWidget *ebox;
GtkCellRenderer *renderer;
combo_box->priv = GVC_COMBO_BOX_GET_PRIVATE (combo_box);
combo_box->priv->model = GTK_TREE_MODEL (gtk_list_store_new (NUM_COLS,
G_TYPE_STRING,
G_TYPE_STRING));
combo_box->priv->label = gtk_label_new (NULL);
gtk_misc_set_alignment (GTK_MISC (combo_box->priv->label),
0.0,
0.5);
/* frame */
frame = gtk_frame_new (NULL);
gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_NONE);
gtk_container_add (GTK_CONTAINER (combo_box), frame);
combo_box->priv->drop_box = box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 6);
combo_box->priv->combobox = gtk_combo_box_new_with_model (combo_box->priv->model);
renderer = gtk_cell_renderer_text_new ();
gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo_box->priv->combobox),
renderer, TRUE);
gtk_cell_layout_add_attribute (GTK_CELL_LAYOUT (combo_box->priv->combobox),
renderer,
"text", COL_HUMAN_NAME);
/* Make sure that the combo box isn't too wide when human names are overly long,
* but that we can still read the full length of it */
g_object_set (G_OBJECT (renderer), "ellipsize", PANGO_ELLIPSIZE_END, NULL);
g_object_set (G_OBJECT (combo_box->priv->combobox), "popup-fixed-width", FALSE, NULL);
combo_box->priv->start_box = sbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 6);
gtk_box_pack_start (GTK_BOX (box), sbox, FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (sbox), combo_box->priv->label, FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (box), combo_box->priv->combobox, TRUE, TRUE, 0);
combo_box->priv->button = gtk_button_new_with_label ("APPLICATION BUG");
gtk_button_set_use_underline (GTK_BUTTON (combo_box->priv->button), TRUE);
gtk_widget_set_no_show_all (combo_box->priv->button, TRUE);
gtk_box_pack_start (GTK_BOX (box), combo_box->priv->button, FALSE, FALSE, 0);
combo_box->priv->end_box = ebox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 6);
gtk_box_pack_start (GTK_BOX (box), ebox, FALSE, FALSE, 0);
if (combo_box->priv->size_group != NULL) {
gtk_size_group_add_widget (combo_box->priv->size_group, sbox);
if (combo_box->priv->symmetric) {
gtk_size_group_add_widget (combo_box->priv->size_group, ebox);
}
}
gtk_container_add (GTK_CONTAINER (frame), combo_box->priv->drop_box);
gtk_widget_show_all (frame);
gtk_label_set_mnemonic_widget (GTK_LABEL (combo_box->priv->label),
combo_box->priv->combobox);
g_signal_connect (G_OBJECT (combo_box->priv->combobox), "changed",
G_CALLBACK (on_combo_box_changed), combo_box);
g_signal_connect (G_OBJECT (combo_box->priv->button), "clicked",
G_CALLBACK (on_combo_box_button_clicked), combo_box);
}
static void
gvc_combo_box_finalize (GObject *object)
{
GvcComboBox *combo_box;
g_return_if_fail (object != NULL);
g_return_if_fail (GVC_IS_COMBO_BOX (object));
combo_box = GVC_COMBO_BOX (object);
g_return_if_fail (combo_box->priv != NULL);
g_object_unref (combo_box->priv->model);
combo_box->priv->model = NULL;
G_OBJECT_CLASS (gvc_combo_box_parent_class)->finalize (object);
}
GtkWidget *
gvc_combo_box_new (const char *label)
{
GObject *combo_box;
combo_box = g_object_new (GVC_TYPE_COMBO_BOX,
"label", label,
NULL);
return GTK_WIDGET (combo_box);
}
|
355 | ./cinnamon-control-center/panels/sound/gvc-log.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2009 Red Hat, Inc.
*
* 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.
*
*/
#include "config.h"
#include <glib.h>
#include <glib/gstdio.h>
#include "gvc-log.h"
static int log_levels = G_LOG_LEVEL_CRITICAL |
G_LOG_LEVEL_ERROR |
G_LOG_LEVEL_WARNING |
G_LOG_LEVEL_MESSAGE |
G_LOG_LEVEL_INFO |
G_LOG_LEVEL_DEBUG;
static void
gvc_log_default_handler (const gchar *log_domain,
GLogLevelFlags log_level,
const gchar *message,
gpointer unused_data)
{
if ((log_level & log_levels) == 0)
return;
g_log_default_handler (log_domain, log_level, message, unused_data);
}
void
gvc_log_init (void)
{
g_log_set_default_handler (gvc_log_default_handler, NULL);
}
void
gvc_log_set_debug (gboolean debug)
{
if (debug) {
log_levels |= (G_LOG_LEVEL_DEBUG | G_LOG_LEVEL_INFO);
g_debug ("Enabling debugging");
} else {
log_levels &= ~ (G_LOG_LEVEL_DEBUG | G_LOG_LEVEL_INFO);
}
}
|
356 | ./cinnamon-control-center/panels/sound/gvc-mixer-card.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2008 William Jon McCann
* Copyright (C) 2009 Bastien Nocera
* Copyright (C) Conor Curran 2011 <[email protected]>
*
* 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.
*
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <pulse/pulseaudio.h>
#include "gvc-mixer-card.h"
#include "gvc-mixer-card-private.h"
#define GVC_MIXER_CARD_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GVC_TYPE_MIXER_CARD, GvcMixerCardPrivate))
static guint32 card_serial = 1;
struct GvcMixerCardPrivate
{
pa_context *pa_context;
guint id;
guint index;
char *name;
char *icon_name;
char *profile;
char *target_profile;
char *human_profile;
GList *profiles;
pa_operation *profile_op;
GList *ports;
};
enum
{
PROP_0,
PROP_ID,
PROP_PA_CONTEXT,
PROP_INDEX,
PROP_NAME,
PROP_ICON_NAME,
PROP_PROFILE,
PROP_HUMAN_PROFILE,
};
static void gvc_mixer_card_class_init (GvcMixerCardClass *klass);
static void gvc_mixer_card_init (GvcMixerCard *mixer_card);
static void gvc_mixer_card_finalize (GObject *object);
G_DEFINE_TYPE (GvcMixerCard, gvc_mixer_card, G_TYPE_OBJECT)
static guint32
get_next_card_serial (void)
{
guint32 serial;
serial = card_serial++;
if ((gint32)card_serial < 0) {
card_serial = 1;
}
return serial;
}
pa_context *
gvc_mixer_card_get_pa_context (GvcMixerCard *card)
{
g_return_val_if_fail (GVC_IS_MIXER_CARD (card), 0);
return card->priv->pa_context;
}
guint
gvc_mixer_card_get_index (GvcMixerCard *card)
{
g_return_val_if_fail (GVC_IS_MIXER_CARD (card), 0);
return card->priv->index;
}
guint
gvc_mixer_card_get_id (GvcMixerCard *card)
{
g_return_val_if_fail (GVC_IS_MIXER_CARD (card), 0);
return card->priv->id;
}
const char *
gvc_mixer_card_get_name (GvcMixerCard *card)
{
g_return_val_if_fail (GVC_IS_MIXER_CARD (card), NULL);
return card->priv->name;
}
gboolean
gvc_mixer_card_set_name (GvcMixerCard *card,
const char *name)
{
g_return_val_if_fail (GVC_IS_MIXER_CARD (card), FALSE);
g_free (card->priv->name);
card->priv->name = g_strdup (name);
g_object_notify (G_OBJECT (card), "name");
return TRUE;
}
const char *
gvc_mixer_card_get_icon_name (GvcMixerCard *card)
{
g_return_val_if_fail (GVC_IS_MIXER_CARD (card), NULL);
return card->priv->icon_name;
}
gboolean
gvc_mixer_card_set_icon_name (GvcMixerCard *card,
const char *icon_name)
{
g_return_val_if_fail (GVC_IS_MIXER_CARD (card), FALSE);
g_free (card->priv->icon_name);
card->priv->icon_name = g_strdup (icon_name);
g_object_notify (G_OBJECT (card), "icon-name");
return TRUE;
}
/**
* gvc_mixer_card_get_profile: (skip)
*
* @card:
*
* Returns:
*/
GvcMixerCardProfile *
gvc_mixer_card_get_profile (GvcMixerCard *card)
{
GList *l;
g_return_val_if_fail (GVC_IS_MIXER_CARD (card), NULL);
g_return_val_if_fail (card->priv->profiles != NULL, NULL);
for (l = card->priv->profiles; l != NULL; l = l->next) {
GvcMixerCardProfile *p = l->data;
if (g_str_equal (card->priv->profile, p->profile)) {
return p;
}
}
g_assert_not_reached ();
return NULL;
}
gboolean
gvc_mixer_card_set_profile (GvcMixerCard *card,
const char *profile)
{
GList *l;
g_return_val_if_fail (GVC_IS_MIXER_CARD (card), FALSE);
g_return_val_if_fail (card->priv->profiles != NULL, FALSE);
g_free (card->priv->profile);
card->priv->profile = g_strdup (profile);
g_free (card->priv->human_profile);
card->priv->human_profile = NULL;
for (l = card->priv->profiles; l != NULL; l = l->next) {
GvcMixerCardProfile *p = l->data;
if (g_str_equal (card->priv->profile, p->profile)) {
card->priv->human_profile = g_strdup (p->human_profile);
break;
}
}
g_object_notify (G_OBJECT (card), "profile");
return TRUE;
}
static void
_pa_context_set_card_profile_by_index_cb (pa_context *context,
int success,
void *userdata)
{
GvcMixerCard *card = GVC_MIXER_CARD (userdata);
g_assert (card->priv->target_profile);
if (success > 0) {
gvc_mixer_card_set_profile (card, card->priv->target_profile);
} else {
g_debug ("Failed to switch profile on '%s' from '%s' to '%s'",
card->priv->name,
card->priv->profile,
card->priv->target_profile);
}
g_free (card->priv->target_profile);
card->priv->target_profile = NULL;
pa_operation_unref (card->priv->profile_op);
card->priv->profile_op = NULL;
}
gboolean
gvc_mixer_card_change_profile (GvcMixerCard *card,
const char *profile)
{
g_return_val_if_fail (GVC_IS_MIXER_CARD (card), FALSE);
g_return_val_if_fail (card->priv->profiles != NULL, FALSE);
/* Same profile, or already requested? */
if (g_strcmp0 (card->priv->profile, profile) == 0)
return TRUE;
if (g_strcmp0 (profile, card->priv->target_profile) == 0)
return TRUE;
if (card->priv->profile_op != NULL) {
pa_operation_cancel (card->priv->profile_op);
pa_operation_unref (card->priv->profile_op);
card->priv->profile_op = NULL;
}
if (card->priv->profile != NULL) {
g_free (card->priv->target_profile);
card->priv->target_profile = g_strdup (profile);
card->priv->profile_op = pa_context_set_card_profile_by_index (card->priv->pa_context,
card->priv->index,
card->priv->target_profile,
_pa_context_set_card_profile_by_index_cb,
card);
if (card->priv->profile_op == NULL) {
g_warning ("pa_context_set_card_profile_by_index() failed");
return FALSE;
}
} else {
g_assert (card->priv->human_profile == NULL);
card->priv->profile = g_strdup (profile);
}
return TRUE;
}
/**
* gvc_mixer_card_get_profiles:
*
* Return value: (transfer none) (element-type GvcMixerCardProfile):
*/
const GList *
gvc_mixer_card_get_profiles (GvcMixerCard *card)
{
g_return_val_if_fail (GVC_IS_MIXER_CARD (card), NULL);
return card->priv->profiles;
}
/**
* gvc_mixer_card_get_ports:
*
* Return value: (transfer none) (element-type GvcMixerCardPort):
*/
const GList *
gvc_mixer_card_get_ports (GvcMixerCard *card)
{
g_return_val_if_fail (GVC_IS_MIXER_CARD (card), NULL);
return card->priv->ports;
}
/**
* gvc_mixer_card_profile_compare:
*
* Return value: 1 if @a has a higher priority, -1 if @b has a higher
* priority, 0 if @a and @b have the same priority.
*/
int
gvc_mixer_card_profile_compare (GvcMixerCardProfile *a,
GvcMixerCardProfile *b)
{
if (a->priority == b->priority)
return 0;
if (a->priority > b->priority)
return 1;
return -1;
}
/**
* gvc_mixer_card_set_profiles:
* @profiles: (transfer full) (element-type GvcMixerCardProfile):
*/
gboolean
gvc_mixer_card_set_profiles (GvcMixerCard *card,
GList *profiles)
{
g_return_val_if_fail (GVC_IS_MIXER_CARD (card), FALSE);
g_return_val_if_fail (card->priv->profiles == NULL, FALSE);
card->priv->profiles = g_list_sort (profiles, (GCompareFunc) gvc_mixer_card_profile_compare);
return TRUE;
}
/**
* gvc_mixer_card_get_gicon:
*
* @card:
*
* Return value: (transfer full) (element-type GIcon):
*/
GIcon *
gvc_mixer_card_get_gicon (GvcMixerCard *card)
{
g_return_val_if_fail (GVC_IS_MIXER_CARD (card), NULL);
if (card->priv->icon_name == NULL)
return NULL;
return g_themed_icon_new_with_default_fallbacks (card->priv->icon_name);
}
/**
* gvc_mixer_card_set_ports:
* @profiles: (transfer full) (element-type GvcMixerCardPort):
*/
gboolean
gvc_mixer_card_set_ports (GvcMixerCard *card,
GList *ports)
{
g_return_val_if_fail (GVC_IS_MIXER_CARD (card), FALSE);
g_return_val_if_fail (card->priv->ports == NULL, FALSE);
card->priv->ports = ports;
return TRUE;
}
static void
gvc_mixer_card_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GvcMixerCard *self = GVC_MIXER_CARD (object);
switch (prop_id) {
case PROP_PA_CONTEXT:
self->priv->pa_context = g_value_get_pointer (value);
break;
case PROP_INDEX:
self->priv->index = g_value_get_ulong (value);
break;
case PROP_ID:
self->priv->id = g_value_get_ulong (value);
break;
case PROP_NAME:
gvc_mixer_card_set_name (self, g_value_get_string (value));
break;
case PROP_ICON_NAME:
gvc_mixer_card_set_icon_name (self, g_value_get_string (value));
break;
case PROP_PROFILE:
gvc_mixer_card_set_profile (self, g_value_get_string (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gvc_mixer_card_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GvcMixerCard *self = GVC_MIXER_CARD (object);
switch (prop_id) {
case PROP_PA_CONTEXT:
g_value_set_pointer (value, self->priv->pa_context);
break;
case PROP_INDEX:
g_value_set_ulong (value, self->priv->index);
break;
case PROP_ID:
g_value_set_ulong (value, self->priv->id);
break;
case PROP_NAME:
g_value_set_string (value, self->priv->name);
break;
case PROP_ICON_NAME:
g_value_set_string (value, self->priv->icon_name);
break;
case PROP_PROFILE:
g_value_set_string (value, self->priv->profile);
break;
case PROP_HUMAN_PROFILE:
g_value_set_string (value, self->priv->human_profile);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static GObject *
gvc_mixer_card_constructor (GType type,
guint n_construct_properties,
GObjectConstructParam *construct_params)
{
GObject *object;
GvcMixerCard *self;
object = G_OBJECT_CLASS (gvc_mixer_card_parent_class)->constructor (type, n_construct_properties, construct_params);
self = GVC_MIXER_CARD (object);
self->priv->id = get_next_card_serial ();
return object;
}
static void
gvc_mixer_card_class_init (GvcMixerCardClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
gobject_class->constructor = gvc_mixer_card_constructor;
gobject_class->finalize = gvc_mixer_card_finalize;
gobject_class->set_property = gvc_mixer_card_set_property;
gobject_class->get_property = gvc_mixer_card_get_property;
g_object_class_install_property (gobject_class,
PROP_INDEX,
g_param_spec_ulong ("index",
"Index",
"The index for this card",
0, G_MAXULONG, 0,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT_ONLY));
g_object_class_install_property (gobject_class,
PROP_ID,
g_param_spec_ulong ("id",
"id",
"The id for this card",
0, G_MAXULONG, 0,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT_ONLY));
g_object_class_install_property (gobject_class,
PROP_PA_CONTEXT,
g_param_spec_pointer ("pa-context",
"PulseAudio context",
"The PulseAudio context for this card",
G_PARAM_READWRITE|G_PARAM_CONSTRUCT_ONLY));
g_object_class_install_property (gobject_class,
PROP_NAME,
g_param_spec_string ("name",
"Name",
"Name to display for this card",
NULL,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (gobject_class,
PROP_ICON_NAME,
g_param_spec_string ("icon-name",
"Icon Name",
"Name of icon to display for this card",
NULL,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (gobject_class,
PROP_PROFILE,
g_param_spec_string ("profile",
"Profile",
"Name of current profile for this card",
NULL,
G_PARAM_READWRITE));
g_object_class_install_property (gobject_class,
PROP_HUMAN_PROFILE,
g_param_spec_string ("human-profile",
"Profile (Human readable)",
"Name of current profile for this card in human readable form",
NULL,
G_PARAM_READABLE));
g_type_class_add_private (klass, sizeof (GvcMixerCardPrivate));
}
static void
gvc_mixer_card_init (GvcMixerCard *card)
{
card->priv = GVC_MIXER_CARD_GET_PRIVATE (card);
}
GvcMixerCard *
gvc_mixer_card_new (pa_context *context,
guint index)
{
GObject *object;
object = g_object_new (GVC_TYPE_MIXER_CARD,
"index", index,
"pa-context", context,
NULL);
return GVC_MIXER_CARD (object);
}
static void
free_profile (GvcMixerCardProfile *p)
{
g_free (p->profile);
g_free (p->human_profile);
g_free (p->status);
g_free (p);
}
static void
gvc_mixer_card_finalize (GObject *object)
{
GvcMixerCard *mixer_card;
g_return_if_fail (object != NULL);
g_return_if_fail (GVC_IS_MIXER_CARD (object));
mixer_card = GVC_MIXER_CARD (object);
g_return_if_fail (mixer_card->priv != NULL);
g_free (mixer_card->priv->name);
mixer_card->priv->name = NULL;
g_free (mixer_card->priv->icon_name);
mixer_card->priv->icon_name = NULL;
g_free (mixer_card->priv->target_profile);
mixer_card->priv->target_profile = NULL;
g_free (mixer_card->priv->profile);
mixer_card->priv->profile = NULL;
g_free (mixer_card->priv->human_profile);
mixer_card->priv->human_profile = NULL;
g_list_foreach (mixer_card->priv->profiles, (GFunc) free_profile, NULL);
g_list_free (mixer_card->priv->profiles);
mixer_card->priv->profiles = NULL;
G_OBJECT_CLASS (gvc_mixer_card_parent_class)->finalize (object);
}
|
357 | ./cinnamon-control-center/panels/sound/gvc-mixer-event-role.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2008 William Jon McCann
*
* 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.
*
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <pulse/pulseaudio.h>
#include <pulse/ext-stream-restore.h>
#include "gvc-mixer-event-role.h"
#include "gvc-mixer-stream-private.h"
#include "gvc-channel-map-private.h"
#define GVC_MIXER_EVENT_ROLE_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GVC_TYPE_MIXER_EVENT_ROLE, GvcMixerEventRolePrivate))
struct GvcMixerEventRolePrivate
{
char *device;
};
enum
{
PROP_0,
PROP_DEVICE
};
static void gvc_mixer_event_role_class_init (GvcMixerEventRoleClass *klass);
static void gvc_mixer_event_role_init (GvcMixerEventRole *mixer_event_role);
static void gvc_mixer_event_role_finalize (GObject *object);
G_DEFINE_TYPE (GvcMixerEventRole, gvc_mixer_event_role, GVC_TYPE_MIXER_STREAM)
static gboolean
update_settings (GvcMixerEventRole *role,
gboolean is_muted,
gpointer *op)
{
pa_operation *o;
const GvcChannelMap *map;
pa_context *context;
pa_ext_stream_restore_info info;
map = gvc_mixer_stream_get_channel_map (GVC_MIXER_STREAM(role));
info.volume = *gvc_channel_map_get_cvolume(map);
info.name = "sink-input-by-media-role:event";
info.channel_map = *gvc_channel_map_get_pa_channel_map(map);
info.device = role->priv->device;
info.mute = is_muted;
context = gvc_mixer_stream_get_pa_context (GVC_MIXER_STREAM (role));
o = pa_ext_stream_restore_write (context,
PA_UPDATE_REPLACE,
&info,
1,
TRUE,
NULL,
NULL);
if (o == NULL) {
g_warning ("pa_ext_stream_restore_write() failed");
return FALSE;
}
if (op != NULL)
*op = o;
return TRUE;
}
static gboolean
gvc_mixer_event_role_push_volume (GvcMixerStream *stream, gpointer *op)
{
return update_settings (GVC_MIXER_EVENT_ROLE (stream),
gvc_mixer_stream_get_is_muted (stream), op);
}
static gboolean
gvc_mixer_event_role_change_is_muted (GvcMixerStream *stream,
gboolean is_muted)
{
/* Apply change straight away so that we don't get a race with
* gvc_mixer_event_role_push_volume().
* See https://bugs.freedesktop.org/show_bug.cgi?id=51413 */
gvc_mixer_stream_set_is_muted (stream, is_muted);
return update_settings (GVC_MIXER_EVENT_ROLE (stream),
is_muted, NULL);
}
static gboolean
gvc_mixer_event_role_set_device (GvcMixerEventRole *role,
const char *device)
{
g_return_val_if_fail (GVC_IS_MIXER_EVENT_ROLE (role), FALSE);
g_free (role->priv->device);
role->priv->device = g_strdup (device);
g_object_notify (G_OBJECT (role), "device");
return TRUE;
}
static void
gvc_mixer_event_role_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GvcMixerEventRole *self = GVC_MIXER_EVENT_ROLE (object);
switch (prop_id) {
case PROP_DEVICE:
gvc_mixer_event_role_set_device (self, g_value_get_string (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gvc_mixer_event_role_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GvcMixerEventRole *self = GVC_MIXER_EVENT_ROLE (object);
switch (prop_id) {
case PROP_DEVICE:
g_value_set_string (value, self->priv->device);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gvc_mixer_event_role_class_init (GvcMixerEventRoleClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
GvcMixerStreamClass *stream_class = GVC_MIXER_STREAM_CLASS (klass);
object_class->finalize = gvc_mixer_event_role_finalize;
object_class->set_property = gvc_mixer_event_role_set_property;
object_class->get_property = gvc_mixer_event_role_get_property;
stream_class->push_volume = gvc_mixer_event_role_push_volume;
stream_class->change_is_muted = gvc_mixer_event_role_change_is_muted;
g_object_class_install_property (object_class,
PROP_DEVICE,
g_param_spec_string ("device",
"Device",
"Device",
NULL,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_type_class_add_private (klass, sizeof (GvcMixerEventRolePrivate));
}
static void
gvc_mixer_event_role_init (GvcMixerEventRole *event_role)
{
event_role->priv = GVC_MIXER_EVENT_ROLE_GET_PRIVATE (event_role);
}
static void
gvc_mixer_event_role_finalize (GObject *object)
{
GvcMixerEventRole *mixer_event_role;
g_return_if_fail (object != NULL);
g_return_if_fail (GVC_IS_MIXER_EVENT_ROLE (object));
mixer_event_role = GVC_MIXER_EVENT_ROLE (object);
g_return_if_fail (mixer_event_role->priv != NULL);
g_free (mixer_event_role->priv->device);
G_OBJECT_CLASS (gvc_mixer_event_role_parent_class)->finalize (object);
}
/**
* gvc_mixer_event_role_new: (skip)
*
* @context:
* @index:
* @channel_map:
*
* Returns:
*/
GvcMixerStream *
gvc_mixer_event_role_new (pa_context *context,
const char *device,
GvcChannelMap *channel_map)
{
GObject *object;
object = g_object_new (GVC_TYPE_MIXER_EVENT_ROLE,
"pa-context", context,
"index", 0,
"device", device,
"channel-map", channel_map,
NULL);
return GVC_MIXER_STREAM (object);
}
|
358 | ./cinnamon-control-center/panels/sound/cc-sound-panel.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2008 Red Hat, Inc.
*
* 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
* Lesser 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.
*/
#include "config.h"
#include <libintl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <glib/gi18n-lib.h>
#include <glib.h>
#include <gtk/gtk.h>
#include <pulse/pulseaudio.h>
#include "cc-sound-panel.h"
#include "gvc-mixer-dialog.h"
CC_PANEL_REGISTER (CcSoundPanel, cc_sound_panel)
enum {
PROP_0,
PROP_ARGV
};
static void cc_sound_panel_finalize (GObject *object);
static void
cc_sound_panel_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec)
{
CcSoundPanel *self = CC_SOUND_PANEL (object);
switch (property_id) {
case PROP_ARGV: {
gchar **args;
args = g_value_get_boxed (value);
if (args && args[0]) {
gvc_mixer_dialog_set_page (self->dialog, args[0]);
}
break;
}
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}
}
static const char *
cc_sound_panel_get_help_uri (CcPanel *panel)
{
if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity"))
return "help:ubuntu-help/media#sound";
else
return "help:gnome-help/media#sound";
}
static void
cc_sound_panel_class_init (CcSoundPanelClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
CcPanelClass *panel_class = CC_PANEL_CLASS (klass);
panel_class->get_help_uri = cc_sound_panel_get_help_uri;
object_class->finalize = cc_sound_panel_finalize;
object_class->set_property = cc_sound_panel_set_property;
g_object_class_override_property (object_class, PROP_ARGV, "argv");
}
static void
cc_sound_panel_finalize (GObject *object)
{
CcSoundPanel *panel = CC_SOUND_PANEL (object);
if (panel->dialog != NULL)
panel->dialog = NULL;
if (panel->connecting_label != NULL)
panel->connecting_label = NULL;
if (panel->control != NULL) {
g_object_unref (panel->control);
panel->control = NULL;
}
G_OBJECT_CLASS (cc_sound_panel_parent_class)->finalize (object);
}
static void
cc_sound_panel_init (CcSoundPanel *self)
{
gtk_icon_theme_append_search_path (gtk_icon_theme_get_default (),
ICON_DATA_DIR);
gtk_window_set_default_icon_name ("cin-multimedia-volume-control");
self->control = gvc_mixer_control_new ("Cinnamon Volume Control Dialog");
gvc_mixer_control_open (self->control);
self->dialog = gvc_mixer_dialog_new (self->control);
gtk_container_add (GTK_CONTAINER (self), GTK_WIDGET (self->dialog));
gtk_widget_show (GTK_WIDGET (self->dialog));
}
void
cc_sound_panel_register (GIOModule *module)
{
cc_sound_panel_register_type (G_TYPE_MODULE (module));
g_io_extension_point_implement (CC_SHELL_PANEL_EXTENSION_POINT,
CC_TYPE_SOUND_PANEL,
"gnome-sound", 0);
}
/* GIO extension stuff */
void
g_io_module_load (GIOModule *module)
{
bindtextdomain (GETTEXT_PACKAGE, LOCALE_DIR);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
/* register the panel */
cc_sound_panel_register (module);
}
void
g_io_module_unload (GIOModule *module)
{
}
|
359 | ./cinnamon-control-center/panels/sound/gvc-mixer-ui-device.c | /* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
* gvc-mixer-ui-device.c
* Copyright (C) Conor Curran 2011 <[email protected]>
* Copyright (C) 2012 David Henningsson, Canonical Ltd. <[email protected]>
*
* gvc-mixer-ui-device.c 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.
*
* gvc-mixer-ui-device.c 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, see <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#include "gvc-mixer-ui-device.h"
#include "gvc-mixer-card.h"
#define GVC_MIXER_UI_DEVICE_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GVC_TYPE_MIXER_UI_DEVICE, GvcMixerUIDevicePrivate))
struct GvcMixerUIDevicePrivate
{
gchar *first_line_desc;
gchar *second_line_desc;
GvcMixerCard *card;
gchar *port_name;
gint stream_id;
guint id;
gboolean port_available;
/* These two lists contain pointers to GvcMixerCardProfile objects. Those objects are owned by GvcMixerCard. *
* TODO: Do we want to add a weak reference to the GvcMixerCard for this reason? */
GList *supported_profiles; /* all profiles supported by this port.*/
GList *profiles; /* profiles to be added to combobox, subset of supported_profiles. */
GvcMixerUIDeviceDirection type;
gboolean disable_profile_swapping;
gchar *user_preferred_profile;
};
enum
{
PROP_0,
PROP_DESC_LINE_1,
PROP_DESC_LINE_2,
PROP_CARD,
PROP_PORT_NAME,
PROP_STREAM_ID,
PROP_UI_DEVICE_TYPE,
PROP_PORT_AVAILABLE,
};
static void gvc_mixer_ui_device_class_init (GvcMixerUIDeviceClass *klass);
static void gvc_mixer_ui_device_init (GvcMixerUIDevice *device);
static void gvc_mixer_ui_device_finalize (GObject *object);
G_DEFINE_TYPE (GvcMixerUIDevice, gvc_mixer_ui_device, G_TYPE_OBJECT);
static guint32
get_next_output_serial (void)
{
static guint32 output_serial = 1;
guint32 serial;
serial = output_serial++;
if ((gint32)output_serial < 0)
output_serial = 1;
return serial;
}
static void
gvc_mixer_ui_device_get_property (GObject *object,
guint property_id,
GValue *value,
GParamSpec *pspec)
{
GvcMixerUIDevice *self = GVC_MIXER_UI_DEVICE (object);
switch (property_id) {
case PROP_DESC_LINE_1:
g_value_set_string (value, self->priv->first_line_desc);
break;
case PROP_DESC_LINE_2:
g_value_set_string (value, self->priv->second_line_desc);
break;
case PROP_CARD:
g_value_set_pointer (value, self->priv->card);
break;
case PROP_PORT_NAME:
g_value_set_string (value, self->priv->port_name);
break;
case PROP_STREAM_ID:
g_value_set_int (value, self->priv->stream_id);
break;
case PROP_UI_DEVICE_TYPE:
g_value_set_uint (value, (guint)self->priv->type);
break;
case PROP_PORT_AVAILABLE:
g_value_set_boolean (value, self->priv->port_available);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
static void
gvc_mixer_ui_device_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec)
{
GvcMixerUIDevice *self = GVC_MIXER_UI_DEVICE (object);
switch (property_id) {
case PROP_DESC_LINE_1:
g_free (self->priv->first_line_desc);
self->priv->first_line_desc = g_value_dup_string (value);
g_debug ("gvc-mixer-output-set-property - 1st line: %s\n",
self->priv->first_line_desc);
break;
case PROP_DESC_LINE_2:
g_free (self->priv->second_line_desc);
self->priv->second_line_desc = g_value_dup_string (value);
g_debug ("gvc-mixer-output-set-property - 2nd line: %s\n",
self->priv->second_line_desc);
break;
case PROP_CARD:
self->priv->card = g_value_get_pointer (value);
g_debug ("gvc-mixer-output-set-property - card: %p\n",
self->priv->card);
break;
case PROP_PORT_NAME:
g_free (self->priv->port_name);
self->priv->port_name = g_value_dup_string (value);
g_debug ("gvc-mixer-output-set-property - card port name: %s\n",
self->priv->port_name);
break;
case PROP_STREAM_ID:
self->priv->stream_id = g_value_get_int (value);
g_debug ("gvc-mixer-output-set-property - sink/source id: %i\n",
self->priv->stream_id);
break;
case PROP_UI_DEVICE_TYPE:
self->priv->type = (GvcMixerUIDeviceDirection) g_value_get_uint (value);
break;
case PROP_PORT_AVAILABLE:
self->priv->port_available = g_value_get_boolean (value);
g_debug ("gvc-mixer-output-set-property - port available %i, value passed in %i \n",
self->priv->port_available, g_value_get_boolean (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
static GObject *
gvc_mixer_ui_device_constructor (GType type,
guint n_construct_properties,
GObjectConstructParam *construct_params)
{
GObject *object;
GvcMixerUIDevice *self;
object = G_OBJECT_CLASS (gvc_mixer_ui_device_parent_class)->constructor (type, n_construct_properties, construct_params);
self = GVC_MIXER_UI_DEVICE (object);
self->priv->id = get_next_output_serial ();
self->priv->stream_id = GVC_MIXER_UI_DEVICE_INVALID;
return object;
}
static void
gvc_mixer_ui_device_init (GvcMixerUIDevice *device)
{
device->priv = GVC_MIXER_UI_DEVICE_GET_PRIVATE (device);
}
static void
char_clear_pointer (gchar *pointer)
{
if (pointer) {
g_free (pointer);
pointer = NULL;
}
}
static void
list_clear_pointer (GList *pointer)
{
if (pointer) {
g_list_free (pointer);
pointer = NULL;
}
}
static void
gvc_mixer_ui_device_dispose (GObject *object)
{
GvcMixerUIDevice *device;
g_return_if_fail (object != NULL);
g_return_if_fail (GVC_MIXER_UI_DEVICE (object));
device = GVC_MIXER_UI_DEVICE (object);
char_clear_pointer (device->priv->port_name);
char_clear_pointer (device->priv->first_line_desc);
char_clear_pointer (device->priv->second_line_desc);
list_clear_pointer (device->priv->profiles);
list_clear_pointer (device->priv->supported_profiles);
char_clear_pointer (device->priv->user_preferred_profile);
G_OBJECT_CLASS (gvc_mixer_ui_device_parent_class)->dispose (object);
}
static void
gvc_mixer_ui_device_finalize (GObject *object)
{
G_OBJECT_CLASS (gvc_mixer_ui_device_parent_class)->finalize (object);
}
static void
gvc_mixer_ui_device_class_init (GvcMixerUIDeviceClass *klass)
{
GObjectClass* object_class = G_OBJECT_CLASS (klass);
GParamSpec *pspec;
object_class->constructor = gvc_mixer_ui_device_constructor;
object_class->dispose = gvc_mixer_ui_device_dispose;
object_class->finalize = gvc_mixer_ui_device_finalize;
object_class->set_property = gvc_mixer_ui_device_set_property;
object_class->get_property = gvc_mixer_ui_device_get_property;
pspec = g_param_spec_string ("description",
"Description construct prop",
"Set first line description",
"no-name-set",
G_PARAM_READWRITE);
g_object_class_install_property (object_class, PROP_DESC_LINE_1, pspec);
pspec = g_param_spec_string ("origin",
"origin construct prop",
"Set second line description name",
"no-name-set",
G_PARAM_READWRITE);
g_object_class_install_property (object_class, PROP_DESC_LINE_2, pspec);
pspec = g_param_spec_pointer ("card",
"Card from pulse",
"Set/Get card",
G_PARAM_READWRITE);
g_object_class_install_property (object_class, PROP_CARD, pspec);
pspec = g_param_spec_string ("port-name",
"port-name construct prop",
"Set port-name",
NULL,
G_PARAM_READWRITE);
g_object_class_install_property (object_class, PROP_PORT_NAME, pspec);
pspec = g_param_spec_int ("stream-id",
"stream id assigned by gvc-stream",
"Set/Get stream id",
-1,
G_MAXINT,
GVC_MIXER_UI_DEVICE_INVALID,
G_PARAM_READWRITE);
g_object_class_install_property (object_class, PROP_STREAM_ID, pspec);
pspec = g_param_spec_uint ("type",
"ui-device type",
"determine whether its an input and output",
0, 1, 0, G_PARAM_READWRITE);
g_object_class_install_property (object_class, PROP_UI_DEVICE_TYPE, pspec);
pspec = g_param_spec_boolean ("port-available",
"available",
"determine whether this port is available",
FALSE,
G_PARAM_READWRITE);
g_object_class_install_property (object_class, PROP_PORT_AVAILABLE, pspec);
g_type_class_add_private (klass, sizeof (GvcMixerUIDevicePrivate));
}
/* Removes the part of the string that starts with skip_prefix
* ie. corresponding to the other direction.
* Normally either "input:" or "output:"
*
* Example: if given the input string "output:hdmi-stereo+input:analog-stereo" and
* skip_prefix "input:", the resulting string is "output:hdmi-stereo".
*
* The returned string must be freed with g_free().
*/
static gchar *
get_profile_canonical_name (const gchar *profile_name, const gchar *skip_prefix)
{
gchar *result = NULL;
gchar **s;
int i;
/* optimisation for the simple case. */
if (strstr (profile_name, skip_prefix) == NULL)
return g_strdup (profile_name);
s = g_strsplit (profile_name, "+", 0);
for (i = 0; i < g_strv_length (s); i++) {
if (g_str_has_prefix (s[i], skip_prefix))
continue;
if (result == NULL)
result = g_strdup (s[i]);
else {
gchar *c = g_strdup_printf("%s+%s", result, s[i]);
g_free(result);
result = c;
}
}
g_strfreev(s);
if (!result)
return g_strdup("off");
return result;
}
const gchar *
gvc_mixer_ui_device_get_matching_profile (GvcMixerUIDevice *device, const gchar *profile)
{
gchar *skip_prefix = device->priv->type == UIDeviceInput ? "output:" : "input:";
gchar *target_cname = get_profile_canonical_name (profile, skip_prefix);
GList *l;
gchar *result = NULL;
for (l = device->priv->profiles; l != NULL; l = l->next) {
gchar *canonical_name;
GvcMixerCardProfile* p = l->data;
canonical_name = get_profile_canonical_name (p->profile, skip_prefix);
if (strcmp (canonical_name, target_cname) == 0)
result = p->profile;
g_free (canonical_name);
}
g_free (target_cname);
g_debug ("Matching profile for '%s' is '%s'", profile, result ? result : "(null)");
return result;
}
static void
add_canonical_names_of_profiles (GvcMixerUIDevice *device,
const GList *in_profiles,
GHashTable *added_profiles,
const gchar *skip_prefix,
gboolean only_canonical)
{
const GList *l;
for (l = in_profiles; l != NULL; l = l->next) {
gchar *canonical_name;
GvcMixerCardProfile* p = l->data;
canonical_name = get_profile_canonical_name (p->profile, skip_prefix);
g_debug ("The canonical name for '%s' is '%s'", p->profile, canonical_name);
/* Have we already added the canonical version of this profile? */
if (g_hash_table_contains (added_profiles, canonical_name)) {
g_free (canonical_name);
continue;
}
if (only_canonical && strcmp (p->profile, canonical_name) != 0) {
g_free (canonical_name);
continue;
}
g_free (canonical_name);
g_debug ("Adding profile to combobox: '%s' - '%s'", p->profile, p->human_profile);
g_hash_table_insert (added_profiles, g_strdup (p->profile), p);
device->priv->profiles = g_list_append (device->priv->profiles, p);
}
}
/**
* gvc_mixer_ui_device_set_profiles:
*
* @in_profiles: a list of GvcMixerCardProfile
*
* Assigns value to
* - device->priv->profiles (profiles to be added to combobox)
* - device->priv->supported_profiles (all profiles of this port)
* - device->priv->disable_profile_swapping (whether to show the combobox)
*
* This method attempts to reduce the list of profiles visible to the user by figuring out
* from the context of that device (whether it's an input or an output) what profiles
* actually provide an alternative.
*
* It does this by the following.
* - It ignores off profiles.
* - It takes the canonical name of the profile. That name is what you get when you
* ignore the other direction.
* - In the first iteration, it only adds the names of canonical profiles - i e
* when the other side is turned off.
* - Normally the first iteration covers all cases, but sometimes (e g bluetooth)
* it doesn't, so add other profiles whose canonical name isn't already added
* in a second iteration.
*/
void
gvc_mixer_ui_device_set_profiles (GvcMixerUIDevice *device,
const GList *in_profiles)
{
GHashTable *added_profiles;
gchar *skip_prefix = device->priv->type == UIDeviceInput ? "output:" : "input:";
g_debug ("Set profiles for '%s'", gvc_mixer_ui_device_get_description(device));
if (in_profiles == NULL)
return;
device->priv->supported_profiles = g_list_copy ((GList*) in_profiles);
added_profiles = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
/* Run two iterations: First, add profiles which are canonical themselves,
* Second, add profiles for which the canonical name is not added already. */
add_canonical_names_of_profiles(device, in_profiles, added_profiles, skip_prefix, TRUE);
add_canonical_names_of_profiles(device, in_profiles, added_profiles, skip_prefix, FALSE);
/* TODO: Consider adding the "Off" profile here */
device->priv->disable_profile_swapping = g_hash_table_size (added_profiles) <= 1;
g_hash_table_destroy (added_profiles);
}
/**
* gvc_mixer_ui_device_get_best_profile:
*
* @selected: The selected profile or its canonical name or %NULL for any profile
* @current: The currently selected profile
*
* Returns: (transfer none): a profile name, valid as long as the UI device profiles are.
*/
const gchar *
gvc_mixer_ui_device_get_best_profile (GvcMixerUIDevice *device,
const gchar *selected,
const gchar *current)
{
GList *candidates, *l;
const gchar *result;
gchar *skip_prefix;
gchar *canonical_name_selected;
if (device->priv->type == UIDeviceInput)
skip_prefix = "output:";
else
skip_prefix = "input:";
/* First make a list of profiles acceptable to switch to */
canonical_name_selected = NULL;
if (selected)
canonical_name_selected = get_profile_canonical_name (selected, skip_prefix);
candidates = NULL;
for (l = device->priv->supported_profiles; l != NULL; l = l->next) {
gchar *canonical_name;
GvcMixerCardProfile* p = l->data;
canonical_name = get_profile_canonical_name (p->profile, skip_prefix);
if (!canonical_name_selected || strcmp (canonical_name, canonical_name_selected) == 0) {
candidates = g_list_append (candidates, p);
g_debug ("Candidate for profile switching: '%s'", p->profile);
}
}
if (!candidates) {
g_warning ("No suitable profile candidates for '%s'", selected ? selected : "(null)");
g_free (canonical_name_selected);
return current;
}
/* 1) Maybe we can skip profile switching altogether? */
result = NULL;
for (l = candidates; (result == NULL) && (l != NULL); l = l->next) {
GvcMixerCardProfile* p = l->data;
if (strcmp (current, p->profile) == 0)
result = p->profile;
}
/* 2) Try to keep the other side unchanged if possible */
if (result == NULL) {
guint prio = 0;
gchar *skip_prefix_reverse = device->priv->type == UIDeviceInput ? "input:" : "output:";
gchar *current_reverse = get_profile_canonical_name (current, skip_prefix_reverse);
for (l = candidates; l != NULL; l = l->next) {
gchar *p_reverse;
GvcMixerCardProfile* p = l->data;
p_reverse = get_profile_canonical_name (p->profile, skip_prefix_reverse);
g_debug ("Comparing '%s' (from '%s') with '%s', prio %d", p_reverse, p->profile, current_reverse, p->priority);
if (strcmp (p_reverse, current_reverse) == 0 && (!result || p->priority > prio)) {
result = p->profile;
prio = p->priority;
}
g_free (p_reverse);
}
g_free (current_reverse);
}
/* 3) All right, let's just pick the profile with highest priority.
* TODO: We could consider asking a GUI question if this stops streams
* in the other direction */
if (result == NULL) {
guint prio = 0;
for (l = candidates; l != NULL; l = l->next) {
GvcMixerCardProfile* p = l->data;
if ((p->priority > prio) || !result) {
result = p->profile;
prio = p->priority;
}
}
}
g_list_free (candidates);
g_free (canonical_name_selected);
return result;
}
const gchar *
gvc_mixer_ui_device_get_active_profile (GvcMixerUIDevice* device)
{
GvcMixerCardProfile *profile;
g_return_val_if_fail (GVC_IS_MIXER_UI_DEVICE (device), NULL);
if (device->priv->card == NULL) {
g_warning ("Device did not have an appropriate card");
return NULL;
}
profile = gvc_mixer_card_get_profile (device->priv->card);
return gvc_mixer_ui_device_get_matching_profile (device, profile->profile);
}
gboolean
gvc_mixer_ui_device_should_profiles_be_hidden (GvcMixerUIDevice *device)
{
g_return_val_if_fail (GVC_IS_MIXER_UI_DEVICE (device), FALSE);
return device->priv->disable_profile_swapping;
}
GList*
gvc_mixer_ui_device_get_profiles (GvcMixerUIDevice *device)
{
g_return_val_if_fail (GVC_IS_MIXER_UI_DEVICE (device), NULL);
return device->priv->profiles;
}
GList*
gvc_mixer_ui_device_get_supported_profiles (GvcMixerUIDevice *device)
{
g_return_val_if_fail (GVC_IS_MIXER_UI_DEVICE (device), NULL);
return device->priv->supported_profiles;
}
guint
gvc_mixer_ui_device_get_id (GvcMixerUIDevice *device)
{
g_return_val_if_fail (GVC_IS_MIXER_UI_DEVICE (device), 0);
return device->priv->id;
}
gint
gvc_mixer_ui_device_get_stream_id (GvcMixerUIDevice *device)
{
g_return_val_if_fail (GVC_IS_MIXER_UI_DEVICE (device), 0);
return device->priv->stream_id;
}
void
gvc_mixer_ui_device_invalidate_stream (GvcMixerUIDevice *self)
{
g_return_if_fail (GVC_IS_MIXER_UI_DEVICE (self));
self->priv->stream_id = GVC_MIXER_UI_DEVICE_INVALID;
}
const gchar *
gvc_mixer_ui_device_get_description (GvcMixerUIDevice *device)
{
g_return_val_if_fail (GVC_IS_MIXER_UI_DEVICE (device), NULL);
return device->priv->first_line_desc;
}
const gchar *
gvc_mixer_ui_device_get_origin (GvcMixerUIDevice *device)
{
g_return_val_if_fail (GVC_IS_MIXER_UI_DEVICE (device), NULL);
return device->priv->second_line_desc;
}
const gchar*
gvc_mixer_ui_device_get_user_preferred_profile (GvcMixerUIDevice *device)
{
g_return_val_if_fail (GVC_IS_MIXER_UI_DEVICE (device), NULL);
return device->priv->user_preferred_profile;
}
const gchar *
gvc_mixer_ui_device_get_top_priority_profile (GvcMixerUIDevice *device)
{
GList *last;
GvcMixerCardProfile *profile;
g_return_val_if_fail (GVC_IS_MIXER_UI_DEVICE (device), NULL);
last = g_list_last (device->priv->supported_profiles);
profile = last->data;
return profile->profile;
}
void
gvc_mixer_ui_device_set_user_preferred_profile (GvcMixerUIDevice *device,
const gchar *profile)
{
g_return_if_fail (GVC_IS_MIXER_UI_DEVICE (device));
g_free (device->priv->user_preferred_profile);
device->priv->user_preferred_profile = g_strdup (profile);
}
const gchar *
gvc_mixer_ui_device_get_port (GvcMixerUIDevice *device)
{
g_return_val_if_fail (GVC_IS_MIXER_UI_DEVICE (device), NULL);
return device->priv->port_name;
}
gboolean
gvc_mixer_ui_device_has_ports (GvcMixerUIDevice *device)
{
g_return_val_if_fail (GVC_IS_MIXER_UI_DEVICE (device), FALSE);
return (device->priv->port_name != NULL);
}
gboolean
gvc_mixer_ui_device_is_output (GvcMixerUIDevice *device)
{
g_return_val_if_fail (GVC_IS_MIXER_UI_DEVICE (device), FALSE);
return (device->priv->type == UIDeviceOutput);
}
|
360 | ./cinnamon-control-center/panels/sound/gvc-mixer-source-output.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2008 William Jon McCann
*
* 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.
*
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <pulse/pulseaudio.h>
#include "gvc-mixer-source-output.h"
#define GVC_MIXER_SOURCE_OUTPUT_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GVC_TYPE_MIXER_SOURCE_OUTPUT, GvcMixerSourceOutputPrivate))
struct GvcMixerSourceOutputPrivate
{
gpointer dummy;
};
static void gvc_mixer_source_output_class_init (GvcMixerSourceOutputClass *klass);
static void gvc_mixer_source_output_init (GvcMixerSourceOutput *mixer_source_output);
static void gvc_mixer_source_output_finalize (GObject *object);
G_DEFINE_TYPE (GvcMixerSourceOutput, gvc_mixer_source_output, GVC_TYPE_MIXER_STREAM)
static gboolean
gvc_mixer_source_output_push_volume (GvcMixerStream *stream, gpointer *op)
{
/* FIXME: */
*op = NULL;
return TRUE;
}
static gboolean
gvc_mixer_source_output_change_is_muted (GvcMixerStream *stream,
gboolean is_muted)
{
/* FIXME: */
return TRUE;
}
static void
gvc_mixer_source_output_class_init (GvcMixerSourceOutputClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
GvcMixerStreamClass *stream_class = GVC_MIXER_STREAM_CLASS (klass);
object_class->finalize = gvc_mixer_source_output_finalize;
stream_class->push_volume = gvc_mixer_source_output_push_volume;
stream_class->change_is_muted = gvc_mixer_source_output_change_is_muted;
g_type_class_add_private (klass, sizeof (GvcMixerSourceOutputPrivate));
}
static void
gvc_mixer_source_output_init (GvcMixerSourceOutput *source_output)
{
source_output->priv = GVC_MIXER_SOURCE_OUTPUT_GET_PRIVATE (source_output);
}
static void
gvc_mixer_source_output_finalize (GObject *object)
{
GvcMixerSourceOutput *mixer_source_output;
g_return_if_fail (object != NULL);
g_return_if_fail (GVC_IS_MIXER_SOURCE_OUTPUT (object));
mixer_source_output = GVC_MIXER_SOURCE_OUTPUT (object);
g_return_if_fail (mixer_source_output->priv != NULL);
G_OBJECT_CLASS (gvc_mixer_source_output_parent_class)->finalize (object);
}
/**
* gvc_mixer_source_output_new: (skip)
*
* @context:
* @index:
* @channel_map:
*
* Returns:
*/
GvcMixerStream *
gvc_mixer_source_output_new (pa_context *context,
guint index,
GvcChannelMap *channel_map)
{
GObject *object;
object = g_object_new (GVC_TYPE_MIXER_SOURCE_OUTPUT,
"pa-context", context,
"index", index,
"channel-map", channel_map,
NULL);
return GVC_MIXER_STREAM (object);
}
|
361 | ./cinnamon-control-center/panels/sound/applet-main.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2008 Red Hat, Inc.
*
* 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
* Lesser 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.
*/
#include "config.h"
#include <libintl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <glib/gi18n-lib.h>
#include <glib.h>
#include <gtk/gtk.h>
#include <gio/gio.h>
#include "gvc-applet.h"
#include "gvc-log.h"
#define GVCA_DBUS_NAME "org.gnome.VolumeControlApplet"
static gboolean show_version = FALSE;
static gboolean debug = FALSE;
int
main (int argc, char **argv)
{
GError *error;
GvcApplet *applet;
GApplication *app = NULL;
static GOptionEntry entries[] = {
{ "debug", 0, 0, G_OPTION_ARG_NONE, &debug, N_("Enable debugging code"), NULL },
{ "version", 0, 0, G_OPTION_ARG_NONE, &show_version, N_("Version of this application"), NULL },
{ NULL, 0, 0, 0, NULL, NULL, NULL }
};
bindtextdomain (GETTEXT_PACKAGE, LOCALE_DIR);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
textdomain (GETTEXT_PACKAGE);
gvc_log_init ();
error = NULL;
gtk_init_with_args (&argc, &argv,
(char *) _(" ΓÇö Cinnamon Volume Control Applet"),
entries, GETTEXT_PACKAGE,
&error);
if (error != NULL) {
g_warning ("%s", error->message);
exit (1);
}
if (show_version) {
g_print ("%s %s\n", argv [0], VERSION);
exit (1);
}
gvc_log_set_debug (debug);
if (debug == FALSE) {
GError *error = NULL;
app = g_application_new (GVCA_DBUS_NAME,
G_APPLICATION_FLAGS_NONE);
if (!g_application_register (app, NULL, &error)) {
g_warning ("%s", error->message);
g_error_free (error);
return 1;
}
if (g_application_get_is_remote (app)) {
g_warning ("Applet is already running, exiting");
return 0;
}
}
gtk_icon_theme_append_search_path (gtk_icon_theme_get_default (),
ICON_DATA_DIR);
applet = gvc_applet_new ();
gvc_applet_start (applet);
gtk_main ();
if (applet != NULL) {
g_object_unref (applet);
}
if (app != NULL) {
g_object_unref (app);
}
return 0;
}
|
362 | ./cinnamon-control-center/panels/sound/gvc-mixer-sink-input.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2008 William Jon McCann
*
* 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.
*
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <pulse/pulseaudio.h>
#include "gvc-mixer-sink-input.h"
#include "gvc-mixer-stream-private.h"
#include "gvc-channel-map-private.h"
#define GVC_MIXER_SINK_INPUT_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GVC_TYPE_MIXER_SINK_INPUT, GvcMixerSinkInputPrivate))
struct GvcMixerSinkInputPrivate
{
gpointer dummy;
};
static void gvc_mixer_sink_input_class_init (GvcMixerSinkInputClass *klass);
static void gvc_mixer_sink_input_init (GvcMixerSinkInput *mixer_sink_input);
static void gvc_mixer_sink_input_finalize (GObject *object);
G_DEFINE_TYPE (GvcMixerSinkInput, gvc_mixer_sink_input, GVC_TYPE_MIXER_STREAM)
static gboolean
gvc_mixer_sink_input_push_volume (GvcMixerStream *stream, gpointer *op)
{
pa_operation *o;
guint index;
const GvcChannelMap *map;
pa_context *context;
const pa_cvolume *cv;
index = gvc_mixer_stream_get_index (stream);
map = gvc_mixer_stream_get_channel_map (stream);
cv = gvc_channel_map_get_cvolume(map);
context = gvc_mixer_stream_get_pa_context (stream);
o = pa_context_set_sink_input_volume (context,
index,
cv,
NULL,
NULL);
if (o == NULL) {
g_warning ("pa_context_set_sink_input_volume() failed");
return FALSE;
}
*op = o;
return TRUE;
}
static gboolean
gvc_mixer_sink_input_change_is_muted (GvcMixerStream *stream,
gboolean is_muted)
{
pa_operation *o;
guint index;
pa_context *context;
index = gvc_mixer_stream_get_index (stream);
context = gvc_mixer_stream_get_pa_context (stream);
o = pa_context_set_sink_input_mute (context,
index,
is_muted,
NULL,
NULL);
if (o == NULL) {
g_warning ("pa_context_set_sink_input_mute_by_index() failed");
return FALSE;
}
pa_operation_unref(o);
return TRUE;
}
static void
gvc_mixer_sink_input_class_init (GvcMixerSinkInputClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
GvcMixerStreamClass *stream_class = GVC_MIXER_STREAM_CLASS (klass);
object_class->finalize = gvc_mixer_sink_input_finalize;
stream_class->push_volume = gvc_mixer_sink_input_push_volume;
stream_class->change_is_muted = gvc_mixer_sink_input_change_is_muted;
g_type_class_add_private (klass, sizeof (GvcMixerSinkInputPrivate));
}
static void
gvc_mixer_sink_input_init (GvcMixerSinkInput *sink_input)
{
sink_input->priv = GVC_MIXER_SINK_INPUT_GET_PRIVATE (sink_input);
}
static void
gvc_mixer_sink_input_finalize (GObject *object)
{
GvcMixerSinkInput *mixer_sink_input;
g_return_if_fail (object != NULL);
g_return_if_fail (GVC_IS_MIXER_SINK_INPUT (object));
mixer_sink_input = GVC_MIXER_SINK_INPUT (object);
g_return_if_fail (mixer_sink_input->priv != NULL);
G_OBJECT_CLASS (gvc_mixer_sink_input_parent_class)->finalize (object);
}
/**
* gvc_mixer_sink_input_new: (skip)
*
* @context:
* @index:
* @channel_map:
*
* Returns:
*/
GvcMixerStream *
gvc_mixer_sink_input_new (pa_context *context,
guint index,
GvcChannelMap *channel_map)
{
GObject *object;
object = g_object_new (GVC_TYPE_MIXER_SINK_INPUT,
"pa-context", context,
"index", index,
"channel-map", channel_map,
NULL);
return GVC_MIXER_STREAM (object);
}
|
363 | ./cinnamon-control-center/panels/sound/gvc-channel-map.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2008 William Jon McCann
*
* 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.
*
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <pulse/pulseaudio.h>
#include "gvc-channel-map.h"
#include "gvc-channel-map-private.h"
#define GVC_CHANNEL_MAP_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GVC_TYPE_CHANNEL_MAP, GvcChannelMapPrivate))
struct GvcChannelMapPrivate
{
pa_channel_map pa_map;
gboolean pa_volume_is_set;
pa_cvolume pa_volume;
gdouble extern_volume[NUM_TYPES]; /* volume, balance, fade, lfe */
gboolean can_balance;
gboolean can_fade;
};
enum {
VOLUME_CHANGED,
LAST_SIGNAL
};
static guint signals [LAST_SIGNAL] = { 0, };
static void gvc_channel_map_class_init (GvcChannelMapClass *klass);
static void gvc_channel_map_init (GvcChannelMap *channel_map);
static void gvc_channel_map_finalize (GObject *object);
G_DEFINE_TYPE (GvcChannelMap, gvc_channel_map, G_TYPE_OBJECT)
guint
gvc_channel_map_get_num_channels (const GvcChannelMap *map)
{
g_return_val_if_fail (GVC_IS_CHANNEL_MAP (map), 0);
if (!pa_channel_map_valid(&map->priv->pa_map))
return 0;
return map->priv->pa_map.channels;
}
const gdouble *
gvc_channel_map_get_volume (GvcChannelMap *map)
{
g_return_val_if_fail (GVC_IS_CHANNEL_MAP (map), NULL);
if (!pa_channel_map_valid(&map->priv->pa_map))
return NULL;
map->priv->extern_volume[VOLUME] = (gdouble) pa_cvolume_max (&map->priv->pa_volume);
if (gvc_channel_map_can_balance (map))
map->priv->extern_volume[BALANCE] = (gdouble) pa_cvolume_get_balance (&map->priv->pa_volume, &map->priv->pa_map);
else
map->priv->extern_volume[BALANCE] = 0;
if (gvc_channel_map_can_fade (map))
map->priv->extern_volume[FADE] = (gdouble) pa_cvolume_get_fade (&map->priv->pa_volume, &map->priv->pa_map);
else
map->priv->extern_volume[FADE] = 0;
if (gvc_channel_map_has_lfe (map))
map->priv->extern_volume[LFE] = (gdouble) pa_cvolume_get_position (&map->priv->pa_volume, &map->priv->pa_map, PA_CHANNEL_POSITION_LFE);
else
map->priv->extern_volume[LFE] = 0;
return map->priv->extern_volume;
}
gboolean
gvc_channel_map_can_balance (const GvcChannelMap *map)
{
g_return_val_if_fail (GVC_IS_CHANNEL_MAP (map), FALSE);
return map->priv->can_balance;
}
gboolean
gvc_channel_map_can_fade (const GvcChannelMap *map)
{
g_return_val_if_fail (GVC_IS_CHANNEL_MAP (map), FALSE);
return map->priv->can_fade;
}
const char *
gvc_channel_map_get_mapping (const GvcChannelMap *map)
{
g_return_val_if_fail (GVC_IS_CHANNEL_MAP (map), NULL);
if (!pa_channel_map_valid(&map->priv->pa_map))
return NULL;
return pa_channel_map_to_pretty_name (&map->priv->pa_map);
}
/**
* gvc_channel_map_has_position: (skip)
*
* @map:
* @position:
*
* Returns:
*/
gboolean
gvc_channel_map_has_position (const GvcChannelMap *map,
pa_channel_position_t position)
{
g_return_val_if_fail (GVC_IS_CHANNEL_MAP (map), FALSE);
return pa_channel_map_has_position (&(map->priv->pa_map), position);
}
const pa_channel_map *
gvc_channel_map_get_pa_channel_map (const GvcChannelMap *map)
{
g_return_val_if_fail (GVC_IS_CHANNEL_MAP (map), NULL);
if (!pa_channel_map_valid(&map->priv->pa_map))
return NULL;
return &map->priv->pa_map;
}
const pa_cvolume *
gvc_channel_map_get_cvolume (const GvcChannelMap *map)
{
g_return_val_if_fail (GVC_IS_CHANNEL_MAP (map), NULL);
if (!pa_channel_map_valid(&map->priv->pa_map))
return NULL;
return &map->priv->pa_volume;
}
static void
gvc_channel_map_class_init (GvcChannelMapClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
gobject_class->finalize = gvc_channel_map_finalize;
signals [VOLUME_CHANGED] =
g_signal_new ("volume-changed",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GvcChannelMapClass, volume_changed),
NULL, NULL,
g_cclosure_marshal_VOID__BOOLEAN,
G_TYPE_NONE, 1, G_TYPE_BOOLEAN);
g_type_class_add_private (klass, sizeof (GvcChannelMapPrivate));
}
void
gvc_channel_map_volume_changed (GvcChannelMap *map,
const pa_cvolume *cv,
gboolean set)
{
g_return_if_fail (GVC_IS_CHANNEL_MAP (map));
g_return_if_fail (cv != NULL);
g_return_if_fail (pa_cvolume_compatible_with_channel_map(cv, &map->priv->pa_map));
if (pa_cvolume_equal(cv, &map->priv->pa_volume))
return;
map->priv->pa_volume = *cv;
if (map->priv->pa_volume_is_set == FALSE) {
map->priv->pa_volume_is_set = TRUE;
return;
}
g_signal_emit (map, signals[VOLUME_CHANGED], 0, set);
}
static void
gvc_channel_map_init (GvcChannelMap *map)
{
map->priv = GVC_CHANNEL_MAP_GET_PRIVATE (map);
map->priv->pa_volume_is_set = FALSE;
}
static void
gvc_channel_map_finalize (GObject *object)
{
GvcChannelMap *channel_map;
g_return_if_fail (object != NULL);
g_return_if_fail (GVC_IS_CHANNEL_MAP (object));
channel_map = GVC_CHANNEL_MAP (object);
g_return_if_fail (channel_map->priv != NULL);
G_OBJECT_CLASS (gvc_channel_map_parent_class)->finalize (object);
}
GvcChannelMap *
gvc_channel_map_new (void)
{
GObject *map;
map = g_object_new (GVC_TYPE_CHANNEL_MAP, NULL);
return GVC_CHANNEL_MAP (map);
}
static void
set_from_pa_map (GvcChannelMap *map,
const pa_channel_map *pa_map)
{
g_assert (pa_channel_map_valid(pa_map));
map->priv->can_balance = pa_channel_map_can_balance (pa_map);
map->priv->can_fade = pa_channel_map_can_fade (pa_map);
map->priv->pa_map = *pa_map;
pa_cvolume_set(&map->priv->pa_volume, pa_map->channels, PA_VOLUME_NORM);
}
GvcChannelMap *
gvc_channel_map_new_from_pa_channel_map (const pa_channel_map *pa_map)
{
GObject *map;
map = g_object_new (GVC_TYPE_CHANNEL_MAP, NULL);
set_from_pa_map (GVC_CHANNEL_MAP (map), pa_map);
return GVC_CHANNEL_MAP (map);
}
|
364 | ./cinnamon-control-center/panels/sound/sound-theme-file-utils.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
* Copyright (C) 2008 Bastien Nocera <[email protected]>
*
* 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, 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.
*/
#include <config.h>
#include <glib/gstdio.h>
#include <glib/gi18n-lib.h>
#include <gio/gio.h>
#include <utime.h>
#include <strings.h>
#include "sound-theme-file-utils.h"
#define CUSTOM_THEME_NAME "__custom"
/* This function needs to be called after each individual
* changeset to the theme */
void
custom_theme_update_time (void)
{
char *path;
path = custom_theme_dir_path (NULL);
utime (path, NULL);
g_free (path);
}
char *
custom_theme_dir_path (const char *child)
{
static char *dir = NULL;
const char *data_dir;
if (dir == NULL) {
data_dir = g_get_user_data_dir ();
dir = g_build_filename (data_dir, "sounds", CUSTOM_THEME_NAME, NULL);
}
if (child == NULL)
return g_strdup (dir);
return g_build_filename (dir, child, NULL);
}
static gboolean
directory_delete_recursive (GFile *directory, GError **error)
{
GFileEnumerator *enumerator;
GFileInfo *info;
gboolean success = TRUE;
enumerator = g_file_enumerate_children (directory,
G_FILE_ATTRIBUTE_STANDARD_NAME ","
G_FILE_ATTRIBUTE_STANDARD_TYPE,
G_FILE_QUERY_INFO_NONE,
NULL, error);
if (enumerator == NULL)
return FALSE;
while (success &&
(info = g_file_enumerator_next_file (enumerator, NULL, NULL))) {
GFile *child;
child = g_file_get_child (directory, g_file_info_get_name (info));
if (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY) {
success = directory_delete_recursive (child, error);
}
g_object_unref (info);
if (success)
success = g_file_delete (child, NULL, error);
}
g_file_enumerator_close (enumerator, NULL, NULL);
if (success)
success = g_file_delete (directory, NULL, error);
return success;
}
/**
* capplet_file_delete_recursive :
* @file :
* @error :
*
* A utility routine to delete files and/or directories,
* including non-empty directories.
**/
static gboolean
capplet_file_delete_recursive (GFile *file, GError **error)
{
GFileInfo *info;
GFileType type;
g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
info = g_file_query_info (file,
G_FILE_ATTRIBUTE_STANDARD_TYPE,
G_FILE_QUERY_INFO_NONE,
NULL, error);
if (info == NULL)
return FALSE;
type = g_file_info_get_file_type (info);
g_object_unref (info);
if (type == G_FILE_TYPE_DIRECTORY)
return directory_delete_recursive (file, error);
else
return g_file_delete (file, NULL, error);
}
void
delete_custom_theme_dir (void)
{
char *dir;
GFile *file;
dir = custom_theme_dir_path (NULL);
file = g_file_new_for_path (dir);
g_free (dir);
capplet_file_delete_recursive (file, NULL);
g_object_unref (file);
g_debug ("deleted the custom theme dir");
}
gboolean
custom_theme_dir_is_empty (void)
{
char *dir;
GFile *file;
gboolean is_empty;
GFileEnumerator *enumerator;
GFileInfo *info;
GError *error = NULL;
dir = custom_theme_dir_path (NULL);
file = g_file_new_for_path (dir);
g_free (dir);
is_empty = TRUE;
enumerator = g_file_enumerate_children (file,
G_FILE_ATTRIBUTE_STANDARD_NAME ","
G_FILE_ATTRIBUTE_STANDARD_TYPE,
G_FILE_QUERY_INFO_NONE,
NULL, &error);
if (enumerator == NULL) {
g_warning ("Unable to enumerate files: %s", error->message);
g_error_free (error);
goto out;
}
while (is_empty &&
(info = g_file_enumerator_next_file (enumerator, NULL, NULL))) {
if (strcmp ("index.theme", g_file_info_get_name (info)) != 0) {
is_empty = FALSE;
}
g_object_unref (info);
}
g_file_enumerator_close (enumerator, NULL, NULL);
out:
g_object_unref (file);
return is_empty;
}
static void
delete_one_file (const char *sound_name, const char *pattern)
{
GFile *file;
char *name, *filename;
name = g_strdup_printf (pattern, sound_name);
filename = custom_theme_dir_path (name);
g_free (name);
file = g_file_new_for_path (filename);
g_free (filename);
capplet_file_delete_recursive (file, NULL);
g_object_unref (file);
}
void
delete_old_files (const char **sounds)
{
guint i;
for (i = 0; sounds[i] != NULL; i++) {
delete_one_file (sounds[i], "%s.ogg");
}
}
void
delete_disabled_files (const char **sounds)
{
guint i;
for (i = 0; sounds[i] != NULL; i++)
delete_one_file (sounds[i], "%s.disabled");
}
static void
create_one_file (GFile *file)
{
GFileOutputStream* stream;
stream = g_file_create (file, G_FILE_CREATE_NONE, NULL, NULL);
if (stream != NULL) {
g_output_stream_close (G_OUTPUT_STREAM (stream), NULL, NULL);
g_object_unref (stream);
}
}
void
add_disabled_file (const char **sounds)
{
guint i;
for (i = 0; sounds[i] != NULL; i++) {
GFile *file;
char *name, *filename;
name = g_strdup_printf ("%s.disabled", sounds[i]);
filename = custom_theme_dir_path (name);
g_free (name);
file = g_file_new_for_path (filename);
g_free (filename);
create_one_file (file);
g_object_unref (file);
}
}
void
add_custom_file (const char **sounds, const char *filename)
{
guint i;
for (i = 0; sounds[i] != NULL; i++) {
GFile *file;
char *name, *path;
/* We use *.ogg because it's the first type of file that
* libcanberra looks at */
name = g_strdup_printf ("%s.ogg", sounds[i]);
path = custom_theme_dir_path (name);
g_free (name);
/* In case there's already a link there, delete it */
g_unlink (path);
file = g_file_new_for_path (path);
g_free (path);
/* Create the link */
g_file_make_symbolic_link (file, filename, NULL, NULL);
g_object_unref (file);
}
}
void
create_custom_theme (const char *parent)
{
GKeyFile *keyfile;
char *data;
char *path;
/* Create the custom directory */
path = custom_theme_dir_path (NULL);
g_mkdir_with_parents (path, 0755);
g_free (path);
/* Set the data for index.theme */
keyfile = g_key_file_new ();
g_key_file_set_string (keyfile, "Sound Theme", "Name", _("Custom"));
g_key_file_set_string (keyfile, "Sound Theme", "Inherits", parent);
g_key_file_set_string (keyfile, "Sound Theme", "Directories", ".");
data = g_key_file_to_data (keyfile, NULL, NULL);
g_key_file_free (keyfile);
/* Save the index.theme */
path = custom_theme_dir_path ("index.theme");
g_file_set_contents (path, data, -1, NULL);
g_free (path);
g_free (data);
custom_theme_update_time ();
}
|
365 | ./cinnamon-control-center/panels/sound/gvc-mixer-control.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2006-2008 Lennart Poettering
* Copyright (C) 2008 Sjoerd Simons <[email protected]>
* Copyright (C) 2008 William Jon McCann
* Copyright (C) 2012 Conor Curran
*
* 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.
*
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <pulse/pulseaudio.h>
#include <pulse/glib-mainloop.h>
#include <pulse/ext-stream-restore.h>
#include "gvc-mixer-control.h"
#include "gvc-mixer-sink.h"
#include "gvc-mixer-source.h"
#include "gvc-mixer-sink-input.h"
#include "gvc-mixer-source-output.h"
#include "gvc-mixer-event-role.h"
#include "gvc-mixer-card.h"
#include "gvc-mixer-card-private.h"
#include "gvc-channel-map-private.h"
#include "gvc-mixer-control-private.h"
#include "gvc-mixer-ui-device.h"
#define GVC_MIXER_CONTROL_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GVC_TYPE_MIXER_CONTROL, GvcMixerControlPrivate))
#define RECONNECT_DELAY 5
enum {
PROP_0,
PROP_NAME
};
struct GvcMixerControlPrivate
{
pa_glib_mainloop *pa_mainloop;
pa_mainloop_api *pa_api;
pa_context *pa_context;
int n_outstanding;
guint reconnect_id;
char *name;
gboolean default_sink_is_set;
guint default_sink_id;
char *default_sink_name;
gboolean default_source_is_set;
guint default_source_id;
char *default_source_name;
gboolean event_sink_input_is_set;
guint event_sink_input_id;
GHashTable *all_streams;
GHashTable *sinks; /* fixed outputs */
GHashTable *sources; /* fixed inputs */
GHashTable *sink_inputs; /* routable output streams */
GHashTable *source_outputs; /* routable input streams */
GHashTable *clients;
GHashTable *cards;
GvcMixerStream *new_default_sink_stream; /* new default sink stream, used in gvc_mixer_control_set_default_sink () */
GvcMixerStream *new_default_source_stream; /* new default source stream, used in gvc_mixer_control_set_default_source () */
GHashTable *ui_outputs; /* UI visible outputs */
GHashTable *ui_inputs; /* UI visible inputs */
/* When we change profile on a device that is not the server default sink,
* it will jump back to the default sink set by the server to prevent the
* audio setup from being 'outputless'.
*
* All well and good but then when we get the new stream created for the
* new profile how do we know that this is the intended default or selected
* device the user wishes to use. */
guint profile_swapping_device_id;
GvcMixerControlState state;
};
enum {
STATE_CHANGED,
STREAM_ADDED,
STREAM_REMOVED,
CARD_ADDED,
CARD_REMOVED,
DEFAULT_SINK_CHANGED,
DEFAULT_SOURCE_CHANGED,
ACTIVE_OUTPUT_UPDATE,
ACTIVE_INPUT_UPDATE,
OUTPUT_ADDED,
INPUT_ADDED,
OUTPUT_REMOVED,
INPUT_REMOVED,
LAST_SIGNAL
};
static guint signals [LAST_SIGNAL] = { 0, };
static void gvc_mixer_control_class_init (GvcMixerControlClass *klass);
static void gvc_mixer_control_init (GvcMixerControl *mixer_control);
static void gvc_mixer_control_finalize (GObject *object);
G_DEFINE_TYPE (GvcMixerControl, gvc_mixer_control, G_TYPE_OBJECT)
pa_context *
gvc_mixer_control_get_pa_context (GvcMixerControl *control)
{
g_return_val_if_fail (GVC_IS_MIXER_CONTROL (control), NULL);
return control->priv->pa_context;
}
/**
* gvc_mixer_control_get_event_sink_input:
*
* @control:
*
* Returns: (transfer none):
*/
GvcMixerStream *
gvc_mixer_control_get_event_sink_input (GvcMixerControl *control)
{
GvcMixerStream *stream;
g_return_val_if_fail (GVC_IS_MIXER_CONTROL (control), NULL);
stream = g_hash_table_lookup (control->priv->all_streams,
GUINT_TO_POINTER (control->priv->event_sink_input_id));
return stream;
}
static void
gvc_mixer_control_stream_restore_cb (pa_context *c,
GvcMixerStream *new_stream,
const pa_ext_stream_restore_info *info,
GvcMixerControl *control)
{
pa_operation *o;
pa_ext_stream_restore_info new_info;
if (new_stream == NULL)
return;
new_info.name = info->name;
new_info.channel_map = info->channel_map;
new_info.volume = info->volume;
new_info.mute = info->mute;
new_info.device = gvc_mixer_stream_get_name (new_stream);
o = pa_ext_stream_restore_write (control->priv->pa_context,
PA_UPDATE_REPLACE,
&new_info, 1,
TRUE, NULL, NULL);
if (o == NULL) {
g_warning ("pa_ext_stream_restore_write() failed: %s",
pa_strerror (pa_context_errno (control->priv->pa_context)));
return;
}
g_debug ("Changed default device for %s to %s", info->name, new_info.device);
pa_operation_unref (o);
}
static void
gvc_mixer_control_stream_restore_sink_cb (pa_context *c,
const pa_ext_stream_restore_info *info,
int eol,
void *userdata)
{
GvcMixerControl *control = (GvcMixerControl *) userdata;
if (eol || info == NULL || !g_str_has_prefix(info->name, "sink-input-by"))
return;
gvc_mixer_control_stream_restore_cb (c, control->priv->new_default_sink_stream, info, control);
}
static void
gvc_mixer_control_stream_restore_source_cb (pa_context *c,
const pa_ext_stream_restore_info *info,
int eol,
void *userdata)
{
GvcMixerControl *control = (GvcMixerControl *) userdata;
if (eol || info == NULL || !g_str_has_prefix(info->name, "source-output-by"))
return;
gvc_mixer_control_stream_restore_cb (c, control->priv->new_default_source_stream, info, control);
}
/**
* gvc_mixer_control_lookup_device_from_stream:
* @control:
* @stream:
* Returns: (transfer none): a #GvcUIDevice or %NULL
*/
GvcMixerUIDevice *
gvc_mixer_control_lookup_device_from_stream (GvcMixerControl *control,
GvcMixerStream *stream)
{
GList *devices, *d;
gboolean is_network_stream;
const GList *ports;
GvcMixerUIDevice *ret;
if (GVC_IS_MIXER_SOURCE (stream))
devices = g_hash_table_get_values (control->priv->ui_inputs);
else
devices = g_hash_table_get_values (control->priv->ui_outputs);
ret = NULL;
ports = gvc_mixer_stream_get_ports (stream);
is_network_stream = (ports == NULL);
for (d = devices; d != NULL; d = d->next) {
GvcMixerUIDevice *device = d->data;
gint stream_id = G_MAXINT;
g_object_get (G_OBJECT (device),
"stream-id", &stream_id,
NULL);
if (is_network_stream &&
stream_id == gvc_mixer_stream_get_id (stream)) {
g_debug ("lookup device from stream - %s - it is a network_stream ",
gvc_mixer_ui_device_get_description (device));
ret = device;
break;
} else if (!is_network_stream) {
const GvcMixerStreamPort *port;
port = gvc_mixer_stream_get_port (stream);
if (stream_id == gvc_mixer_stream_get_id (stream) &&
g_strcmp0 (gvc_mixer_ui_device_get_port (device),
port->port) == 0) {
g_debug ("lookup-device-from-stream found device: device description '%s', device port = '%s', device stream id %i AND stream port = '%s' stream id '%u' and stream description '%s'",
gvc_mixer_ui_device_get_description (device),
gvc_mixer_ui_device_get_port (device),
stream_id,
port->port,
gvc_mixer_stream_get_id (stream),
gvc_mixer_stream_get_description (stream));
ret = device;
break;
}
}
}
g_debug ("gvc_mixer_control_lookup_device_from_stream - Could not find a device for stream '%s'",gvc_mixer_stream_get_description (stream));
g_list_free (devices);
return ret;
}
gboolean
gvc_mixer_control_set_default_sink (GvcMixerControl *control,
GvcMixerStream *stream)
{
pa_operation *o;
g_return_val_if_fail (GVC_IS_MIXER_CONTROL (control), FALSE);
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
g_debug ("about to set default sink on server");
o = pa_context_set_default_sink (control->priv->pa_context,
gvc_mixer_stream_get_name (stream),
NULL,
NULL);
if (o == NULL) {
g_warning ("pa_context_set_default_sink() failed: %s",
pa_strerror (pa_context_errno (control->priv->pa_context)));
return FALSE;
}
pa_operation_unref (o);
control->priv->new_default_sink_stream = stream;
g_object_add_weak_pointer (G_OBJECT (stream), (gpointer *) &control->priv->new_default_sink_stream);
o = pa_ext_stream_restore_read (control->priv->pa_context,
gvc_mixer_control_stream_restore_sink_cb,
control);
if (o == NULL) {
g_warning ("pa_ext_stream_restore_read() failed: %s",
pa_strerror (pa_context_errno (control->priv->pa_context)));
return FALSE;
}
pa_operation_unref (o);
return TRUE;
}
gboolean
gvc_mixer_control_set_default_source (GvcMixerControl *control,
GvcMixerStream *stream)
{
GvcMixerUIDevice* input;
pa_operation *o;
g_return_val_if_fail (GVC_IS_MIXER_CONTROL (control), FALSE);
g_return_val_if_fail (GVC_IS_MIXER_STREAM (stream), FALSE);
o = pa_context_set_default_source (control->priv->pa_context,
gvc_mixer_stream_get_name (stream),
NULL,
NULL);
if (o == NULL) {
g_warning ("pa_context_set_default_source() failed");
return FALSE;
}
pa_operation_unref (o);
control->priv->new_default_source_stream = stream;
g_object_add_weak_pointer (G_OBJECT (stream), (gpointer *) &control->priv->new_default_source_stream);
o = pa_ext_stream_restore_read (control->priv->pa_context,
gvc_mixer_control_stream_restore_source_cb,
control);
if (o == NULL) {
g_warning ("pa_ext_stream_restore_read() failed: %s",
pa_strerror (pa_context_errno (control->priv->pa_context)));
return FALSE;
}
pa_operation_unref (o);
/* source change successful, update the UI. */
input = gvc_mixer_control_lookup_device_from_stream (control, stream);
g_signal_emit (G_OBJECT (control),
signals[ACTIVE_INPUT_UPDATE],
0,
gvc_mixer_ui_device_get_id (input));
return TRUE;
}
/**
* gvc_mixer_control_get_default_sink:
*
* @control:
*
* Returns: (transfer none):
*/
GvcMixerStream *
gvc_mixer_control_get_default_sink (GvcMixerControl *control)
{
GvcMixerStream *stream;
g_return_val_if_fail (GVC_IS_MIXER_CONTROL (control), NULL);
if (control->priv->default_sink_is_set) {
stream = g_hash_table_lookup (control->priv->all_streams,
GUINT_TO_POINTER (control->priv->default_sink_id));
} else {
stream = NULL;
}
return stream;
}
/**
* gvc_mixer_control_get_default_source:
*
* @control:
*
* Returns: (transfer none):
*/
GvcMixerStream *
gvc_mixer_control_get_default_source (GvcMixerControl *control)
{
GvcMixerStream *stream;
g_return_val_if_fail (GVC_IS_MIXER_CONTROL (control), NULL);
if (control->priv->default_source_is_set) {
stream = g_hash_table_lookup (control->priv->all_streams,
GUINT_TO_POINTER (control->priv->default_source_id));
} else {
stream = NULL;
}
return stream;
}
static gpointer
gvc_mixer_control_lookup_id (GHashTable *hash_table,
guint id)
{
return g_hash_table_lookup (hash_table,
GUINT_TO_POINTER (id));
}
/**
* gvc_mixer_control_lookup_stream_id:
*
* @control:
* @id:
*
* Returns: (transfer none):
*/
GvcMixerStream *
gvc_mixer_control_lookup_stream_id (GvcMixerControl *control,
guint id)
{
g_return_val_if_fail (GVC_IS_MIXER_CONTROL (control), NULL);
return gvc_mixer_control_lookup_id (control->priv->all_streams, id);
}
/**
* gvc_mixer_control_lookup_card_id:
*
* @control:
* @id:
*
* Returns: (transfer none):
*/
GvcMixerCard *
gvc_mixer_control_lookup_card_id (GvcMixerControl *control,
guint id)
{
g_return_val_if_fail (GVC_IS_MIXER_CONTROL (control), NULL);
return gvc_mixer_control_lookup_id (control->priv->cards, id);
}
/**
* gvc_mixer_control_lookup_output_id:
* @control:
* @id:
* Returns: (transfer none):
*/
GvcMixerUIDevice *
gvc_mixer_control_lookup_output_id (GvcMixerControl *control,
guint id)
{
g_return_val_if_fail (GVC_IS_MIXER_CONTROL (control), NULL);
return gvc_mixer_control_lookup_id (control->priv->ui_outputs, id);
}
/**
* gvc_mixer_control_lookup_input_id:
* @control:
* @id:
* Returns: (transfer none):
*/
GvcMixerUIDevice *
gvc_mixer_control_lookup_input_id (GvcMixerControl *control,
guint id)
{
g_return_val_if_fail (GVC_IS_MIXER_CONTROL (control), NULL);
return gvc_mixer_control_lookup_id (control->priv->ui_inputs, id);
}
/**
* gvc_mixer_control_get_stream_from_device:
* @control:
* @device:
* Returns: (transfer none):
*/
GvcMixerStream *
gvc_mixer_control_get_stream_from_device (GvcMixerControl *control,
GvcMixerUIDevice *device)
{
gint stream_id;
g_return_val_if_fail (GVC_IS_MIXER_CONTROL (control), NULL);
g_return_val_if_fail (GVC_IS_MIXER_UI_DEVICE (device), NULL);
stream_id = gvc_mixer_ui_device_get_stream_id (device);
if (stream_id == GVC_MIXER_UI_DEVICE_INVALID) {
g_debug ("gvc_mixer_control_get_stream_from_device - device has a null stream");
return NULL;
}
return gvc_mixer_control_lookup_stream_id (control, stream_id);
}
/**
* gvc_mixer_control_change_profile_on_selected_device:
* @control:
* @device:
* @profile: Can be null if any profile present on this port is okay
* Returns: This method will attempt to swap the profile on the card of
* the device with given profile name. If successfull it will set the
* preferred profile on that device so as we know the next time the user
* moves to that device it should have this profile active.
*/
gboolean
gvc_mixer_control_change_profile_on_selected_device (GvcMixerControl *control,
GvcMixerUIDevice *device,
const gchar *profile)
{
const gchar *best_profile;
GvcMixerCardProfile *current_profile;
GvcMixerCard *card;
g_object_get (G_OBJECT (device), "card", &card, NULL);
current_profile = gvc_mixer_card_get_profile (card);
if (current_profile)
best_profile = gvc_mixer_ui_device_get_best_profile (device, profile, current_profile->profile);
else
best_profile = profile;
g_assert (best_profile);
g_debug ("Selected '%s', moving to profile '%s' on card '%s' on stream id %i",
profile ? profile : "(any)", best_profile,
gvc_mixer_card_get_name (card),
gvc_mixer_ui_device_get_stream_id (device));
g_debug ("default sink name = %s and default sink id %u",
control->priv->default_sink_name,
control->priv->default_sink_id);
control->priv->profile_swapping_device_id = gvc_mixer_ui_device_get_id (device);
if (gvc_mixer_card_change_profile (card, best_profile)) {
gvc_mixer_ui_device_set_user_preferred_profile (device, best_profile);
return TRUE;
}
return FALSE;
}
/**
* gvc_mixer_control_change_output:
* @control:
* @output:
* This method is called from the UI when the user selects a previously unselected device.
* - Firstly it queries the stream from the device.
* - It assumes that if the stream is null that it cannot be a bluetooth or network stream (they never show unless they have valid sinks and sources)
* In the scenario of a NULL stream on the device
* - It fetches the device's preferred profile or if NUll the profile with the highest priority on that device.
* - It then caches this device in control->priv->cached_desired_output_id so that when the update_sink triggered
* from when we attempt to change profile we will know exactly what device to highlight on that stream.
* - It attempts to swap the profile on the card from that device and returns.
* - Next, it handles network or bluetooth streams that only require their stream to be made the default.
* - Next it deals with port changes so if the stream's active port is not the same as the port on the device
* it will attempt to change the port on that stream to be same as the device. If this fails it will return.
* - Finally it will set this new stream to be the default stream and emit a signal for the UI confirming the active output device.
*/
void
gvc_mixer_control_change_output (GvcMixerControl *control,
GvcMixerUIDevice* output)
{
GvcMixerStream *stream;
GvcMixerStream *default_stream;
const GvcMixerStreamPort *active_port;
const gchar *output_port;
g_debug ("control change output");
stream = gvc_mixer_control_get_stream_from_device (control, output);
if (stream == NULL) {
gvc_mixer_control_change_profile_on_selected_device (control,
output, NULL);
return;
}
/* Handle a network sink as a portless or cardless device */
if (!gvc_mixer_ui_device_has_ports (output)) {
g_debug ("Did we try to move to a software/bluetooth sink ?");
if (gvc_mixer_control_set_default_sink (control, stream)) {
/* sink change was successful, update the UI.*/
g_signal_emit (G_OBJECT (control),
signals[ACTIVE_OUTPUT_UPDATE],
0,
gvc_mixer_ui_device_get_id (output));
}
else {
g_warning ("Failed to set default sink with stream from output %s",
gvc_mixer_ui_device_get_description (output));
}
return;
}
active_port = gvc_mixer_stream_get_port (stream);
output_port = gvc_mixer_ui_device_get_port (output);
/* First ensure the correct port is active on the sink */
if (g_strcmp0 (active_port->port, output_port) != 0) {
g_debug ("Port change, switch to = %s", output_port);
if (gvc_mixer_stream_change_port (stream, output_port) == FALSE) {
g_warning ("Could not change port !");
return;
}
}
default_stream = gvc_mixer_control_get_default_sink (control);
/* Finally if we are not on the correct stream, swap over. */
if (stream != default_stream) {
GvcMixerUIDevice* output;
g_debug ("Attempting to swap over to stream %s ",
gvc_mixer_stream_get_description (stream));
if (gvc_mixer_control_set_default_sink (control, stream)) {
output = gvc_mixer_control_lookup_device_from_stream (control, stream);
g_signal_emit (G_OBJECT (control),
signals[ACTIVE_OUTPUT_UPDATE],
0,
gvc_mixer_ui_device_get_id (output));
} else {
/* If the move failed for some reason reset the UI. */
output = gvc_mixer_control_lookup_device_from_stream (control, default_stream);
g_signal_emit (G_OBJECT (control),
signals[ACTIVE_OUTPUT_UPDATE],
0,
gvc_mixer_ui_device_get_id (output));
}
}
}
/**
* gvc_mixer_control_change_input:
* @control:
* @input:
* This method is called from the UI when the user selects a previously unselected device.
* - Firstly it queries the stream from the device.
* - It assumes that if the stream is null that it cannot be a bluetooth or network stream (they never show unless they have valid sinks and sources)
* In the scenario of a NULL stream on the device
* - It fetches the device's preferred profile or if NUll the profile with the highest priority on that device.
* - It then caches this device in control->priv->cached_desired_input_id so that when the update_source triggered
* from when we attempt to change profile we will know exactly what device to highlight on that stream.
* - It attempts to swap the profile on the card from that device and returns.
* - Next, it handles network or bluetooth streams that only require their stream to be made the default.
* - Next it deals with port changes so if the stream's active port is not the same as the port on the device
* it will attempt to change the port on that stream to be same as the device. If this fails it will return.
* - Finally it will set this new stream to be the default stream and emit a signal for the UI confirming the active input device.
*/
void
gvc_mixer_control_change_input (GvcMixerControl *control,
GvcMixerUIDevice* input)
{
GvcMixerStream *stream;
GvcMixerStream *default_stream;
const GvcMixerStreamPort *active_port;
const gchar *input_port;
stream = gvc_mixer_control_get_stream_from_device (control, input);
if (stream == NULL) {
gvc_mixer_control_change_profile_on_selected_device (control,
input, NULL);
return;
}
/* Handle a network sink as a portless/cardless device */
if (!gvc_mixer_ui_device_has_ports (input)) {
g_debug ("Did we try to move to a software/bluetooth source ?");
if (! gvc_mixer_control_set_default_source (control, stream)) {
g_warning ("Failed to set default source with stream from input %s",
gvc_mixer_ui_device_get_description (input));
}
return;
}
active_port = gvc_mixer_stream_get_port (stream);
input_port = gvc_mixer_ui_device_get_port (input);
/* First ensure the correct port is active on the sink */
if (g_strcmp0 (active_port->port, input_port) != 0) {
g_debug ("Port change, switch to = %s", input_port);
if (gvc_mixer_stream_change_port (stream, input_port) == FALSE) {
g_warning ("Could not change port!");
return;
}
}
default_stream = gvc_mixer_control_get_default_source (control);
/* Finally if we are not on the correct stream, swap over. */
if (stream != default_stream) {
g_debug ("change-input - attempting to swap over to stream %s",
gvc_mixer_stream_get_description (stream));
gvc_mixer_control_set_default_source (control, stream);
}
}
static void
listify_hash_values_hfunc (gpointer key,
gpointer value,
gpointer user_data)
{
GSList **list = user_data;
*list = g_slist_prepend (*list, value);
}
static int
gvc_name_collate (const char *namea,
const char *nameb)
{
if (nameb == NULL && namea == NULL)
return 0;
if (nameb == NULL)
return 1;
if (namea == NULL)
return -1;
return g_utf8_collate (namea, nameb);
}
static int
gvc_card_collate (GvcMixerCard *a,
GvcMixerCard *b)
{
const char *namea;
const char *nameb;
g_return_val_if_fail (a == NULL || GVC_IS_MIXER_CARD (a), 0);
g_return_val_if_fail (b == NULL || GVC_IS_MIXER_CARD (b), 0);
namea = gvc_mixer_card_get_name (a);
nameb = gvc_mixer_card_get_name (b);
return gvc_name_collate (namea, nameb);
}
/**
* gvc_mixer_control_get_cards:
*
* @control:
*
* Returns: (transfer container) (element-type Gvc.MixerCard):
*/
GSList *
gvc_mixer_control_get_cards (GvcMixerControl *control)
{
GSList *retval;
g_return_val_if_fail (GVC_IS_MIXER_CONTROL (control), NULL);
retval = NULL;
g_hash_table_foreach (control->priv->cards,
listify_hash_values_hfunc,
&retval);
return g_slist_sort (retval, (GCompareFunc) gvc_card_collate);
}
static int
gvc_stream_collate (GvcMixerStream *a,
GvcMixerStream *b)
{
const char *namea;
const char *nameb;
g_return_val_if_fail (a == NULL || GVC_IS_MIXER_STREAM (a), 0);
g_return_val_if_fail (b == NULL || GVC_IS_MIXER_STREAM (b), 0);
namea = gvc_mixer_stream_get_name (a);
nameb = gvc_mixer_stream_get_name (b);
return gvc_name_collate (namea, nameb);
}
/**
* gvc_mixer_control_get_streams:
*
* @control:
*
* Returns: (transfer container) (element-type Gvc.MixerStream):
*/
GSList *
gvc_mixer_control_get_streams (GvcMixerControl *control)
{
GSList *retval;
g_return_val_if_fail (GVC_IS_MIXER_CONTROL (control), NULL);
retval = NULL;
g_hash_table_foreach (control->priv->all_streams,
listify_hash_values_hfunc,
&retval);
return g_slist_sort (retval, (GCompareFunc) gvc_stream_collate);
}
/**
* gvc_mixer_control_get_sinks:
*
* @control:
*
* Returns: (transfer container) (element-type Gvc.MixerSink):
*/
GSList *
gvc_mixer_control_get_sinks (GvcMixerControl *control)
{
GSList *retval;
g_return_val_if_fail (GVC_IS_MIXER_CONTROL (control), NULL);
retval = NULL;
g_hash_table_foreach (control->priv->sinks,
listify_hash_values_hfunc,
&retval);
return g_slist_sort (retval, (GCompareFunc) gvc_stream_collate);
}
/**
* gvc_mixer_control_get_sources:
*
* @control:
*
* Returns: (transfer container) (element-type Gvc.MixerSource):
*/
GSList *
gvc_mixer_control_get_sources (GvcMixerControl *control)
{
GSList *retval;
g_return_val_if_fail (GVC_IS_MIXER_CONTROL (control), NULL);
retval = NULL;
g_hash_table_foreach (control->priv->sources,
listify_hash_values_hfunc,
&retval);
return g_slist_sort (retval, (GCompareFunc) gvc_stream_collate);
}
/**
* gvc_mixer_control_get_sink_inputs:
*
* @control:
*
* Returns: (transfer container) (element-type Gvc.MixerSinkInput):
*/
GSList *
gvc_mixer_control_get_sink_inputs (GvcMixerControl *control)
{
GSList *retval;
g_return_val_if_fail (GVC_IS_MIXER_CONTROL (control), NULL);
retval = NULL;
g_hash_table_foreach (control->priv->sink_inputs,
listify_hash_values_hfunc,
&retval);
return g_slist_sort (retval, (GCompareFunc) gvc_stream_collate);
}
/**
* gvc_mixer_control_get_source_outputs:
*
* @control:
*
* Returns: (transfer container) (element-type Gvc.MixerSourceOutput):
*/
GSList *
gvc_mixer_control_get_source_outputs (GvcMixerControl *control)
{
GSList *retval;
g_return_val_if_fail (GVC_IS_MIXER_CONTROL (control), NULL);
retval = NULL;
g_hash_table_foreach (control->priv->source_outputs,
listify_hash_values_hfunc,
&retval);
return g_slist_sort (retval, (GCompareFunc) gvc_stream_collate);
}
static void
dec_outstanding (GvcMixerControl *control)
{
if (control->priv->n_outstanding <= 0) {
return;
}
if (--control->priv->n_outstanding <= 0) {
control->priv->state = GVC_STATE_READY;
g_signal_emit (G_OBJECT (control), signals[STATE_CHANGED], 0, GVC_STATE_READY);
}
}
GvcMixerControlState
gvc_mixer_control_get_state (GvcMixerControl *control)
{
g_return_val_if_fail (GVC_IS_MIXER_CONTROL (control), FALSE);
return control->priv->state;
}
static void
on_default_source_port_notify (GObject *object,
GParamSpec *pspec,
GvcMixerControl *control)
{
char *port;
GvcMixerUIDevice *input;
g_object_get (object, "port", &port, NULL);
input = gvc_mixer_control_lookup_device_from_stream (control,
GVC_MIXER_STREAM (object));
g_debug ("on_default_source_port_notify - moved to port '%s' which SHOULD ?? correspond to output '%s'",
port,
gvc_mixer_ui_device_get_description (input));
g_signal_emit (G_OBJECT (control),
signals[ACTIVE_INPUT_UPDATE],
0,
gvc_mixer_ui_device_get_id (input));
g_free (port);
}
static void
_set_default_source (GvcMixerControl *control,
GvcMixerStream *stream)
{
guint new_id;
if (stream == NULL) {
control->priv->default_source_id = 0;
control->priv->default_source_is_set = FALSE;
g_signal_emit (control,
signals[DEFAULT_SOURCE_CHANGED],
0,
PA_INVALID_INDEX);
return;
}
new_id = gvc_mixer_stream_get_id (stream);
if (control->priv->default_source_id != new_id) {
GvcMixerUIDevice *input;
control->priv->default_source_id = new_id;
control->priv->default_source_is_set = TRUE;
g_signal_emit (control,
signals[DEFAULT_SOURCE_CHANGED],
0,
new_id);
if (control->priv->default_source_is_set) {
g_signal_handlers_disconnect_by_func (gvc_mixer_control_get_default_source (control),
on_default_source_port_notify,
control);
}
g_signal_connect (stream,
"notify::port",
G_CALLBACK (on_default_source_port_notify),
control);
input = gvc_mixer_control_lookup_device_from_stream (control, stream);
g_signal_emit (G_OBJECT (control),
signals[ACTIVE_INPUT_UPDATE],
0,
gvc_mixer_ui_device_get_id (input));
}
}
static void
on_default_sink_port_notify (GObject *object,
GParamSpec *pspec,
GvcMixerControl *control)
{
char *port;
GvcMixerUIDevice *output;
g_object_get (object, "port", &port, NULL);
output = gvc_mixer_control_lookup_device_from_stream (control,
GVC_MIXER_STREAM (object));
if (output != NULL) {
g_debug ("on_default_sink_port_notify - moved to port %s - which SHOULD correspond to output %s",
port,
gvc_mixer_ui_device_get_description (output));
g_signal_emit (G_OBJECT (control),
signals[ACTIVE_OUTPUT_UPDATE],
0,
gvc_mixer_ui_device_get_id (output));
}
g_free (port);
}
static void
_set_default_sink (GvcMixerControl *control,
GvcMixerStream *stream)
{
guint new_id;
if (stream == NULL) {
/* Don't tell front-ends about an unset default
* sink if it's already unset */
if (control->priv->default_sink_is_set == FALSE)
return;
control->priv->default_sink_id = 0;
control->priv->default_sink_is_set = FALSE;
g_signal_emit (control,
signals[DEFAULT_SINK_CHANGED],
0,
PA_INVALID_INDEX);
return;
}
new_id = gvc_mixer_stream_get_id (stream);
if (control->priv->default_sink_id != new_id) {
GvcMixerUIDevice *output;
if (control->priv->default_sink_is_set) {
g_signal_handlers_disconnect_by_func (gvc_mixer_control_get_default_sink (control),
on_default_sink_port_notify,
control);
}
control->priv->default_sink_id = new_id;
control->priv->default_sink_is_set = TRUE;
g_signal_emit (control,
signals[DEFAULT_SINK_CHANGED],
0,
new_id);
g_signal_connect (stream,
"notify::port",
G_CALLBACK (on_default_sink_port_notify),
control);
output = gvc_mixer_control_lookup_device_from_stream (control, stream);
g_debug ("active_sink change");
g_signal_emit (G_OBJECT (control),
signals[ACTIVE_OUTPUT_UPDATE],
0,
gvc_mixer_ui_device_get_id (output));
}
}
static gboolean
_stream_has_name (gpointer key,
GvcMixerStream *stream,
const char *name)
{
const char *t_name;
t_name = gvc_mixer_stream_get_name (stream);
if (t_name != NULL
&& name != NULL
&& strcmp (t_name, name) == 0) {
return TRUE;
}
return FALSE;
}
static GvcMixerStream *
find_stream_for_name (GvcMixerControl *control,
const char *name)
{
GvcMixerStream *stream;
stream = g_hash_table_find (control->priv->all_streams,
(GHRFunc)_stream_has_name,
(char *)name);
return stream;
}
static void
update_default_source_from_name (GvcMixerControl *control,
const char *name)
{
gboolean changed = FALSE;
if ((control->priv->default_source_name == NULL
&& name != NULL)
|| (control->priv->default_source_name != NULL
&& name == NULL)
|| (name != NULL && strcmp (control->priv->default_source_name, name) != 0)) {
changed = TRUE;
}
if (changed) {
GvcMixerStream *stream;
g_free (control->priv->default_source_name);
control->priv->default_source_name = g_strdup (name);
stream = find_stream_for_name (control, name);
_set_default_source (control, stream);
}
}
static void
update_default_sink_from_name (GvcMixerControl *control,
const char *name)
{
gboolean changed = FALSE;
if ((control->priv->default_sink_name == NULL
&& name != NULL)
|| (control->priv->default_sink_name != NULL
&& name == NULL)
|| (name != NULL && strcmp (control->priv->default_sink_name, name) != 0)) {
changed = TRUE;
}
if (changed) {
GvcMixerStream *stream;
g_free (control->priv->default_sink_name);
control->priv->default_sink_name = g_strdup (name);
stream = find_stream_for_name (control, name);
_set_default_sink (control, stream);
}
}
static void
update_server (GvcMixerControl *control,
const pa_server_info *info)
{
if (info->default_source_name != NULL) {
update_default_source_from_name (control, info->default_source_name);
}
if (info->default_sink_name != NULL) {
g_debug ("update server");
update_default_sink_from_name (control, info->default_sink_name);
}
}
static void
remove_stream (GvcMixerControl *control,
GvcMixerStream *stream)
{
guint id;
g_object_ref (stream);
id = gvc_mixer_stream_get_id (stream);
if (id == control->priv->default_sink_id) {
_set_default_sink (control, NULL);
} else if (id == control->priv->default_source_id) {
_set_default_source (control, NULL);
}
g_hash_table_remove (control->priv->all_streams,
GUINT_TO_POINTER (id));
g_signal_emit (G_OBJECT (control),
signals[STREAM_REMOVED],
0,
gvc_mixer_stream_get_id (stream));
g_object_unref (stream);
}
static void
add_stream (GvcMixerControl *control,
GvcMixerStream *stream)
{
g_hash_table_insert (control->priv->all_streams,
GUINT_TO_POINTER (gvc_mixer_stream_get_id (stream)),
stream);
g_signal_emit (G_OBJECT (control),
signals[STREAM_ADDED],
0,
gvc_mixer_stream_get_id (stream));
}
/* This method will match individual stream ports against its corresponding device
* It does this by:
* - iterates through our devices and finds the one where the card-id on the device is the same as the card-id on the stream
* and the port-name on the device is the same as the streamport-name.
* This should always find a match and is used exclusively by sync_devices().
*/
static gboolean
match_stream_with_devices (GvcMixerControl *control,
GvcMixerStreamPort *stream_port,
GvcMixerStream *stream)
{
GList *devices, *d;
guint stream_card_id;
guint stream_id;
gboolean in_possession = FALSE;
stream_id = gvc_mixer_stream_get_id (stream);
stream_card_id = gvc_mixer_stream_get_card_index (stream);
devices = g_hash_table_get_values (GVC_IS_MIXER_SOURCE (stream) ? control->priv->ui_inputs : control->priv->ui_outputs);
for (d = devices; d != NULL; d = d->next) {
GvcMixerUIDevice *device;
gint device_stream_id;
gchar *device_port_name;
gchar *origin;
gchar *description;
GvcMixerCard *card;
gint card_id;
device = d->data;
g_object_get (G_OBJECT (device),
"stream-id", &device_stream_id,
"card", &card,
"origin", &origin,
"description", &description,
"port-name", &device_port_name,
NULL);
card_id = gvc_mixer_card_get_index (card);
g_debug ("Attempt to match_stream update_with_existing_outputs - Try description : '%s', origin : '%s', device port name : '%s', card : %p, AGAINST stream port: '%s', sink card id %i",
description,
origin,
device_port_name,
card,
stream_port->port,
stream_card_id);
if (stream_card_id == card_id &&
g_strcmp0 (device_port_name, stream_port->port) == 0) {
g_debug ("Match device with stream: We have a match with description: '%s', origin: '%s', cached already with device id %u, so set stream id to %i",
description,
origin,
gvc_mixer_ui_device_get_id (device),
stream_id);
g_object_set (G_OBJECT (device),
"stream-id", (gint)stream_id,
NULL);
in_possession = TRUE;
}
g_free (device_port_name);
g_free (origin);
g_free (description);
if (in_possession == TRUE)
break;
}
g_list_free (devices);
return in_possession;
}
/*
* This method attempts to match a sink or source with its relevant UI device.
* GvcMixerStream can represent both a sink or source.
* Using static card port introspection implies that we know beforehand what
* outputs and inputs are available to the user.
* But that does not mean that all of these inputs and outputs are available to be used.
* For instance we might be able to see that there is a HDMI port available but if
* we are on the default analog stereo output profile there is no valid sink for
* that HDMI device. We first need to change profile and when update_sink() is called
* only then can we match the new hdmi sink with its corresponding device.
*
* Firstly it checks to see if the incoming stream has no ports.
* - If a stream has no ports but has a valid card ID (bluetooth), it will attempt
* to match the device with the stream using the card id.
* - If a stream has no ports and no valid card id, it goes ahead and makes a new
* device (software/network devices are only detectable at the sink/source level)
* If the stream has ports it will match each port against the stream using match_stream_with_devices().
*
* This method should always find a match.
*/
static void
sync_devices (GvcMixerControl *control,
GvcMixerStream* stream)
{
/* Go through ports to see what outputs can be created. */
const GList *stream_ports;
const GList *n = NULL;
gboolean is_output = !GVC_IS_MIXER_SOURCE (stream);
gint stream_port_count = 0;
stream_ports = gvc_mixer_stream_get_ports (stream);
if (stream_ports == NULL) {
GvcMixerUIDevice *device;
/* Bluetooth, no ports but a valid card */
if (gvc_mixer_stream_get_card_index (stream) != PA_INVALID_INDEX) {
GList *devices, *d;
gboolean in_possession = FALSE;
devices = g_hash_table_get_values (is_output ? control->priv->ui_outputs : control->priv->ui_inputs);
for (d = devices; d != NULL; d = d->next) {
GvcMixerCard *card;
gint card_id;
device = d->data;
g_object_get (G_OBJECT (device),
"card", &card,
NULL);
card_id = gvc_mixer_card_get_index (card);
g_debug ("sync devices, device description - '%s', device card id - %i, stream description - %s, stream card id - %i",
gvc_mixer_ui_device_get_description (device),
card_id,
gvc_mixer_stream_get_description (stream),
gvc_mixer_stream_get_card_index (stream));
if (card_id == gvc_mixer_stream_get_card_index (stream)) {
in_possession = TRUE;
break;
}
}
g_list_free (devices);
if (!in_possession) {
g_warning ("Couldn't match the portless stream (with card) - '%s' is it an input ? -> %i, streams card id -> %i",
gvc_mixer_stream_get_description (stream),
GVC_IS_MIXER_SOURCE (stream),
gvc_mixer_stream_get_card_index (stream));
return;
}
g_object_set (G_OBJECT (device),
"stream-id", (gint)gvc_mixer_stream_get_id (stream),
"description", gvc_mixer_stream_get_description (stream),
"origin", "", /*Leave it empty for these special cases*/
"port-name", NULL,
"port-available", TRUE,
NULL);
} else { /* Network sink/source has no ports and no card. */
GObject *object;
object = g_object_new (GVC_TYPE_MIXER_UI_DEVICE,
"stream-id", (gint)gvc_mixer_stream_get_id (stream),
"description", gvc_mixer_stream_get_description (stream),
"origin", "", /* Leave it empty for these special cases */
"port-name", NULL,
"port-available", TRUE,
NULL);
device = GVC_MIXER_UI_DEVICE (object);
g_hash_table_insert (is_output ? control->priv->ui_outputs : control->priv->ui_inputs,
GUINT_TO_POINTER (gvc_mixer_ui_device_get_id (device)),
g_object_ref (device));
}
g_signal_emit (G_OBJECT (control),
signals[is_output ? OUTPUT_ADDED : INPUT_ADDED],
0,
gvc_mixer_ui_device_get_id (device));
return;
}
/* Go ahead and make sure to match each port against a previously created device */
for (n = stream_ports; n != NULL; n = n->next) {
GvcMixerStreamPort *stream_port;
stream_port = n->data;
stream_port_count ++;
if (match_stream_with_devices (control, stream_port, stream))
continue;
g_warning ("Sync_devices: Failed to match stream id: %u, description: '%s', origin: '%s'",
gvc_mixer_stream_get_id (stream),
stream_port->human_port,
gvc_mixer_stream_get_description (stream));
}
}
static void
set_icon_name_from_proplist (GvcMixerStream *stream,
pa_proplist *l,
const char *default_icon_name)
{
const char *t;
if ((t = pa_proplist_gets (l, PA_PROP_DEVICE_ICON_NAME))) {
goto finish;
}
if ((t = pa_proplist_gets (l, PA_PROP_MEDIA_ICON_NAME))) {
goto finish;
}
if ((t = pa_proplist_gets (l, PA_PROP_WINDOW_ICON_NAME))) {
goto finish;
}
if ((t = pa_proplist_gets (l, PA_PROP_APPLICATION_ICON_NAME))) {
goto finish;
}
if ((t = pa_proplist_gets (l, PA_PROP_MEDIA_ROLE))) {
if (strcmp (t, "video") == 0 ||
strcmp (t, "phone") == 0) {
goto finish;
}
if (strcmp (t, "music") == 0) {
t = "audio";
goto finish;
}
if (strcmp (t, "game") == 0) {
t = "applications-games";
goto finish;
}
if (strcmp (t, "event") == 0) {
t = "dialog-information";
goto finish;
}
}
t = default_icon_name;
finish:
gvc_mixer_stream_set_icon_name (stream, t);
}
/*
* Called when anything changes with a sink.
*/
static void
update_sink (GvcMixerControl *control,
const pa_sink_info *info)
{
GvcMixerStream *stream;
gboolean is_new;
pa_volume_t max_volume;
GvcChannelMap *map;
char map_buff[PA_CHANNEL_MAP_SNPRINT_MAX];
pa_channel_map_snprint (map_buff, PA_CHANNEL_MAP_SNPRINT_MAX, &info->channel_map);
#if 1
g_debug ("Updating sink: index=%u name='%s' description='%s' map='%s'",
info->index,
info->name,
info->description,
map_buff);
#endif
map = NULL;
is_new = FALSE;
stream = g_hash_table_lookup (control->priv->sinks,
GUINT_TO_POINTER (info->index));
if (stream == NULL) {
GList *list = NULL;
guint i;
map = gvc_channel_map_new_from_pa_channel_map (&info->channel_map);
stream = gvc_mixer_sink_new (control->priv->pa_context,
info->index,
map);
for (i = 0; i < info->n_ports; i++) {
GvcMixerStreamPort *port;
port = g_new0 (GvcMixerStreamPort, 1);
port->port = g_strdup (info->ports[i]->name);
port->human_port = g_strdup (info->ports[i]->description);
port->priority = info->ports[i]->priority;
port->available = info->ports[i]->available != PA_PORT_AVAILABLE_NO;
list = g_list_prepend (list, port);
}
gvc_mixer_stream_set_ports (stream, list);
g_object_unref (map);
is_new = TRUE;
} else if (gvc_mixer_stream_is_running (stream)) {
/* Ignore events if volume changes are outstanding */
g_debug ("Ignoring event, volume changes are outstanding");
return;
}
max_volume = pa_cvolume_max (&info->volume);
gvc_mixer_stream_set_name (stream, info->name);
gvc_mixer_stream_set_card_index (stream, info->card);
gvc_mixer_stream_set_description (stream, info->description);
set_icon_name_from_proplist (stream, info->proplist, "audio-card");
gvc_mixer_stream_set_sysfs_path (stream, pa_proplist_gets (info->proplist, "sysfs.path"));
gvc_mixer_stream_set_volume (stream, (guint)max_volume);
gvc_mixer_stream_set_is_muted (stream, info->mute);
gvc_mixer_stream_set_can_decibel (stream, !!(info->flags & PA_SINK_DECIBEL_VOLUME));
gvc_mixer_stream_set_base_volume (stream, (guint32) info->base_volume);
/* Messy I know but to set the port everytime regardless of whether it has changed will cost us a
* port change notify signal which causes the frontend to resync.
* Only update the UI when something has changed. */
if (info->active_port != NULL) {
if (is_new)
gvc_mixer_stream_set_port (stream, info->active_port->name);
else {
const GvcMixerStreamPort *active_port;
active_port = gvc_mixer_stream_get_port (stream);
if (active_port == NULL ||
g_strcmp0 (active_port->port, info->active_port->name) != 0) {
g_debug ("update sink - apparently a port update");
gvc_mixer_stream_set_port (stream, info->active_port->name);
}
}
}
if (is_new) {
g_debug ("update sink - is new");
g_hash_table_insert (control->priv->sinks,
GUINT_TO_POINTER (info->index),
g_object_ref (stream));
add_stream (control, stream);
/* Always sink on a new stream to able to assign the right stream id
* to the appropriate outputs (multiple potential outputs per stream). */
sync_devices (control, stream);
}
/*
* When we change profile on a device that is not the server default sink,
* it will jump back to the default sink set by the server to prevent the audio setup from being 'outputless'.
* All well and good but then when we get the new stream created for the new profile how do we know
* that this is the intended default or selected device the user wishes to use.
* This is messy but it's the only reliable way that it can be done without ripping the whole thing apart.
*/
if (control->priv->profile_swapping_device_id != GVC_MIXER_UI_DEVICE_INVALID) {
GvcMixerUIDevice *dev = NULL;
dev = gvc_mixer_control_lookup_output_id (control, control->priv->profile_swapping_device_id);
if (dev != NULL) {
/* now check to make sure this new stream is the same stream just matched and set on the device object */
if (gvc_mixer_ui_device_get_stream_id (dev) == gvc_mixer_stream_get_id (stream)) {
g_debug ("Looks like we profile swapped on a non server default sink");
gvc_mixer_control_set_default_sink (control, stream);
}
}
control->priv->profile_swapping_device_id = GVC_MIXER_UI_DEVICE_INVALID;
}
if (control->priv->default_sink_name != NULL
&& info->name != NULL
&& strcmp (control->priv->default_sink_name, info->name) == 0) {
_set_default_sink (control, stream);
}
if (map == NULL)
map = (GvcChannelMap *) gvc_mixer_stream_get_channel_map (stream);
gvc_channel_map_volume_changed (map, &info->volume, FALSE);
}
static void
update_source (GvcMixerControl *control,
const pa_source_info *info)
{
GvcMixerStream *stream;
gboolean is_new;
pa_volume_t max_volume;
#if 1
g_debug ("Updating source: index=%u name='%s' description='%s'",
info->index,
info->name,
info->description);
#endif
/* completely ignore monitors, they're not real sources */
if (info->monitor_of_sink != PA_INVALID_INDEX) {
return;
}
is_new = FALSE;
stream = g_hash_table_lookup (control->priv->sources,
GUINT_TO_POINTER (info->index));
if (stream == NULL) {
GList *list = NULL;
guint i;
GvcChannelMap *map;
map = gvc_channel_map_new_from_pa_channel_map (&info->channel_map);
stream = gvc_mixer_source_new (control->priv->pa_context,
info->index,
map);
for (i = 0; i < info->n_ports; i++) {
GvcMixerStreamPort *port;
port = g_new0 (GvcMixerStreamPort, 1);
port->port = g_strdup (info->ports[i]->name);
port->human_port = g_strdup (info->ports[i]->description);
port->priority = info->ports[i]->priority;
list = g_list_prepend (list, port);
}
gvc_mixer_stream_set_ports (stream, list);
g_object_unref (map);
is_new = TRUE;
} else if (gvc_mixer_stream_is_running (stream)) {
/* Ignore events if volume changes are outstanding */
g_debug ("Ignoring event, volume changes are outstanding");
return;
}
max_volume = pa_cvolume_max (&info->volume);
gvc_mixer_stream_set_name (stream, info->name);
gvc_mixer_stream_set_card_index (stream, info->card);
gvc_mixer_stream_set_description (stream, info->description);
set_icon_name_from_proplist (stream, info->proplist, "audio-input-microphone");
gvc_mixer_stream_set_volume (stream, (guint)max_volume);
gvc_mixer_stream_set_is_muted (stream, info->mute);
gvc_mixer_stream_set_can_decibel (stream, !!(info->flags & PA_SOURCE_DECIBEL_VOLUME));
gvc_mixer_stream_set_base_volume (stream, (guint32) info->base_volume);
g_debug ("update source");
if (info->active_port != NULL) {
if (is_new)
gvc_mixer_stream_set_port (stream, info->active_port->name);
else {
const GvcMixerStreamPort *active_port;
active_port = gvc_mixer_stream_get_port (stream);
if (active_port == NULL ||
g_strcmp0 (active_port->port, info->active_port->name) != 0) {
g_debug ("update source - apparently a port update");
gvc_mixer_stream_set_port (stream, info->active_port->name);
}
}
}
if (is_new) {
g_hash_table_insert (control->priv->sources,
GUINT_TO_POINTER (info->index),
g_object_ref (stream));
add_stream (control, stream);
sync_devices (control, stream);
}
if (control->priv->profile_swapping_device_id != GVC_MIXER_UI_DEVICE_INVALID) {
GvcMixerUIDevice *dev = NULL;
dev = gvc_mixer_control_lookup_input_id (control, control->priv->profile_swapping_device_id);
if (dev != NULL) {
/* now check to make sure this new stream is the same stream just matched and set on the device object */
if (gvc_mixer_ui_device_get_stream_id (dev) == gvc_mixer_stream_get_id (stream)) {
g_debug ("Looks like we profile swapped on a non server default sink");
gvc_mixer_control_set_default_source (control, stream);
}
}
control->priv->profile_swapping_device_id = GVC_MIXER_UI_DEVICE_INVALID;
}
if (control->priv->default_source_name != NULL
&& info->name != NULL
&& strcmp (control->priv->default_source_name, info->name) == 0) {
_set_default_source (control, stream);
}
}
static void
set_is_event_stream_from_proplist (GvcMixerStream *stream,
pa_proplist *l)
{
const char *t;
gboolean is_event_stream;
is_event_stream = FALSE;
if ((t = pa_proplist_gets (l, PA_PROP_MEDIA_ROLE))) {
if (g_str_equal (t, "event"))
is_event_stream = TRUE;
}
gvc_mixer_stream_set_is_event_stream (stream, is_event_stream);
}
static void
set_application_id_from_proplist (GvcMixerStream *stream,
pa_proplist *l)
{
const char *t;
if ((t = pa_proplist_gets (l, PA_PROP_APPLICATION_ID))) {
gvc_mixer_stream_set_application_id (stream, t);
}
}
static void
update_sink_input (GvcMixerControl *control,
const pa_sink_input_info *info)
{
GvcMixerStream *stream;
gboolean is_new;
pa_volume_t max_volume;
const char *name;
#if 0
g_debug ("Updating sink input: index=%u name='%s' client=%u sink=%u",
info->index,
info->name,
info->client,
info->sink);
#endif
is_new = FALSE;
stream = g_hash_table_lookup (control->priv->sink_inputs,
GUINT_TO_POINTER (info->index));
if (stream == NULL) {
GvcChannelMap *map;
map = gvc_channel_map_new_from_pa_channel_map (&info->channel_map);
stream = gvc_mixer_sink_input_new (control->priv->pa_context,
info->index,
map);
g_object_unref (map);
is_new = TRUE;
} else if (gvc_mixer_stream_is_running (stream)) {
/* Ignore events if volume changes are outstanding */
g_debug ("Ignoring event, volume changes are outstanding");
return;
}
max_volume = pa_cvolume_max (&info->volume);
name = (const char *)g_hash_table_lookup (control->priv->clients,
GUINT_TO_POINTER (info->client));
gvc_mixer_stream_set_name (stream, name);
gvc_mixer_stream_set_description (stream, info->name);
set_application_id_from_proplist (stream, info->proplist);
set_is_event_stream_from_proplist (stream, info->proplist);
set_icon_name_from_proplist (stream, info->proplist, "applications-multimedia");
gvc_mixer_stream_set_volume (stream, (guint)max_volume);
gvc_mixer_stream_set_is_muted (stream, info->mute);
gvc_mixer_stream_set_is_virtual (stream, info->client == PA_INVALID_INDEX);
if (is_new) {
g_hash_table_insert (control->priv->sink_inputs,
GUINT_TO_POINTER (info->index),
g_object_ref (stream));
add_stream (control, stream);
}
}
static void
update_source_output (GvcMixerControl *control,
const pa_source_output_info *info)
{
GvcMixerStream *stream;
gboolean is_new;
const char *name;
#if 1
g_debug ("Updating source output: index=%u name='%s' client=%u source=%u",
info->index,
info->name,
info->client,
info->source);
#endif
is_new = FALSE;
stream = g_hash_table_lookup (control->priv->source_outputs,
GUINT_TO_POINTER (info->index));
if (stream == NULL) {
GvcChannelMap *map;
map = gvc_channel_map_new_from_pa_channel_map (&info->channel_map);
stream = gvc_mixer_source_output_new (control->priv->pa_context,
info->index,
map);
g_object_unref (map);
is_new = TRUE;
}
name = (const char *)g_hash_table_lookup (control->priv->clients,
GUINT_TO_POINTER (info->client));
gvc_mixer_stream_set_name (stream, name);
gvc_mixer_stream_set_description (stream, info->name);
set_application_id_from_proplist (stream, info->proplist);
set_is_event_stream_from_proplist (stream, info->proplist);
set_icon_name_from_proplist (stream, info->proplist, "audio-input-microphone");
if (is_new) {
g_hash_table_insert (control->priv->source_outputs,
GUINT_TO_POINTER (info->index),
g_object_ref (stream));
add_stream (control, stream);
}
}
static void
update_client (GvcMixerControl *control,
const pa_client_info *info)
{
#if 1
g_debug ("Updating client: index=%u name='%s'",
info->index,
info->name);
#endif
g_hash_table_insert (control->priv->clients,
GUINT_TO_POINTER (info->index),
g_strdup (info->name));
}
static char *
card_num_streams_to_status (guint sinks,
guint sources)
{
char *sinks_str;
char *sources_str;
char *ret;
if (sinks == 0 && sources == 0) {
/* translators:
* The device has been disabled */
return g_strdup (_("Disabled"));
}
if (sinks == 0) {
sinks_str = NULL;
} else {
/* translators:
* The number of sound outputs on a particular device */
sinks_str = g_strdup_printf (ngettext ("%u Output",
"%u Outputs",
sinks),
sinks);
}
if (sources == 0) {
sources_str = NULL;
} else {
/* translators:
* The number of sound inputs on a particular device */
sources_str = g_strdup_printf (ngettext ("%u Input",
"%u Inputs",
sources),
sources);
}
if (sources_str == NULL)
return sinks_str;
if (sinks_str == NULL)
return sources_str;
ret = g_strdup_printf ("%s / %s", sinks_str, sources_str);
g_free (sinks_str);
g_free (sources_str);
return ret;
}
/**
* A utility method to gather which card profiles are relevant to the port .
*/
static GList *
determine_profiles_for_port (pa_card_port_info *port,
GList* card_profiles)
{
gint i;
GList *supported_profiles = NULL;
GList *p;
for (i = 0; i < port->n_profiles; i++) {
for (p = card_profiles; p != NULL; p = p->next) {
GvcMixerCardProfile *prof;
prof = p->data;
if (g_strcmp0 (port->profiles[i]->name, prof->profile) == 0)
supported_profiles = g_list_append (supported_profiles, prof);
}
}
g_debug ("%i profiles supported on port %s",
g_list_length (supported_profiles),
port->description);
return g_list_sort (supported_profiles, (GCompareFunc) gvc_mixer_card_profile_compare);
}
static gboolean
is_card_port_an_output (GvcMixerCardPort* port)
{
return port->direction == PA_DIRECTION_OUTPUT ? TRUE : FALSE;
}
/*
* This method will create a ui device for the given port.
*/
static void
create_ui_device_from_port (GvcMixerControl* control,
GvcMixerCardPort* port,
GvcMixerCard* card)
{
GvcMixerUIDeviceDirection direction;
GObject *object;
GvcMixerUIDevice *uidevice;
gboolean available = port->available != PA_PORT_AVAILABLE_NO;
direction = (is_card_port_an_output (port) == TRUE) ? UIDeviceOutput : UIDeviceInput;
object = g_object_new (GVC_TYPE_MIXER_UI_DEVICE,
"type", (uint)direction,
"card", card,
"port-name", port->port,
"description", port->human_port,
"origin", gvc_mixer_card_get_name (card),
"port-available", available,
NULL);
uidevice = GVC_MIXER_UI_DEVICE (object);
gvc_mixer_ui_device_set_profiles (uidevice, port->profiles);
g_hash_table_insert (is_card_port_an_output (port) ? control->priv->ui_outputs : control->priv->ui_inputs,
GUINT_TO_POINTER (gvc_mixer_ui_device_get_id (uidevice)),
g_object_ref (uidevice));
if (available) {
g_signal_emit (G_OBJECT (control),
signals[is_card_port_an_output (port) ? OUTPUT_ADDED : INPUT_ADDED],
0,
gvc_mixer_ui_device_get_id (uidevice));
}
g_debug ("create_ui_device_from_port, direction %u, description '%s', origin '%s', port available %i",
direction,
port->human_port,
gvc_mixer_card_get_name (card),
available);
}
/*
* This method will match up GvcMixerCardPorts with existing devices.
* A match is achieved if the device's card-id and the port's card-id are the same
* && the device's port-name and the card-port's port member are the same.
* A signal is then sent adding or removing that device from the UI depending on the availability of the port.
*/
static void
match_card_port_with_existing_device (GvcMixerControl *control,
GvcMixerCardPort *card_port,
GvcMixerCard *card,
gboolean available)
{
GList *d;
GList *devices;
GvcMixerUIDevice *device;
gboolean is_output = is_card_port_an_output (card_port);
devices = g_hash_table_get_values (is_output ? control->priv->ui_outputs : control->priv->ui_inputs);
for (d = devices; d != NULL; d = d->next) {
GvcMixerCard *device_card;
gchar *device_port_name;
device = d->data;
g_object_get (G_OBJECT (device),
"card", &device_card,
"port-name", &device_port_name,
NULL);
if (g_strcmp0 (card_port->port, device_port_name) == 0 &&
device_card == card) {
g_debug ("Found the relevant device %s, update its port availability flag to %i, is_output %i",
device_port_name,
available,
is_output);
g_object_set (G_OBJECT (device),
"port-available", available, NULL);
g_signal_emit (G_OBJECT (control),
is_output ? signals[available ? OUTPUT_ADDED : OUTPUT_REMOVED] : signals[available ? INPUT_ADDED : INPUT_REMOVED],
0,
gvc_mixer_ui_device_get_id (device));
}
g_free (device_port_name);
}
g_list_free (devices);
}
static void
create_ui_device_from_card (GvcMixerControl *control,
GvcMixerCard *card)
{
GObject *object;
GvcMixerUIDevice *in;
GvcMixerUIDevice *out;
const GList *profiles;
/* For now just create two devices and presume this device is multi directional
* Ensure to remove both on card removal (available to false by default) */
profiles = gvc_mixer_card_get_profiles (card);
g_debug ("Portless card just registered - %i", gvc_mixer_card_get_index (card));
object = g_object_new (GVC_TYPE_MIXER_UI_DEVICE,
"type", UIDeviceInput,
"description", gvc_mixer_card_get_name (card),
"origin", "", /* Leave it empty for these special cases */
"port-name", NULL,
"port-available", FALSE,
"card", card,
NULL);
in = GVC_MIXER_UI_DEVICE (object);
gvc_mixer_ui_device_set_profiles (in, profiles);
g_hash_table_insert (control->priv->ui_inputs,
GUINT_TO_POINTER (gvc_mixer_ui_device_get_id (in)),
g_object_ref (in));
object = g_object_new (GVC_TYPE_MIXER_UI_DEVICE,
"type", UIDeviceOutput,
"description", gvc_mixer_card_get_name (card),
"origin", "", /* Leave it empty for these special cases */
"port-name", NULL,
"port-available", FALSE,
"card", card,
NULL);
out = GVC_MIXER_UI_DEVICE (object);
gvc_mixer_ui_device_set_profiles (out, profiles);
g_hash_table_insert (control->priv->ui_outputs,
GUINT_TO_POINTER (gvc_mixer_ui_device_get_id (out)),
g_object_ref (out));
}
/*
* At this point we can determine all devices available to us (besides network 'ports')
* This is done by the following:
*
* - gvc_mixer_card and gvc_mixer_card_ports are created and relevant setters are called.
* - First it checks to see if it's a portless card. Bluetooth devices are portless AFAIHS.
* If so it creates two devices, an input and an output.
* - If it's a 'normal' card with ports it will create a new ui-device or
* synchronise port availability with the existing device cached for that port on this card. */
static void
update_card (GvcMixerControl *control,
const pa_card_info *info)
{
const GList *card_ports = NULL;
const GList *m = NULL;
GvcMixerCard *card;
gboolean is_new = FALSE;
#if 1
guint i;
const char *key;
void *state;
g_debug ("Udpating card %s (index: %u driver: %s):",
info->name, info->index, info->driver);
for (i = 0; i < info->n_profiles; i++) {
struct pa_card_profile_info pi = info->profiles[i];
gboolean is_default;
is_default = (g_strcmp0 (pi.name, info->active_profile->name) == 0);
g_debug ("\tProfile '%s': %d sources %d sinks%s",
pi.name, pi.n_sources, pi.n_sinks,
is_default ? " (Current)" : "");
}
state = NULL;
key = pa_proplist_iterate (info->proplist, &state);
while (key != NULL) {
g_debug ("\tProperty: '%s' = '%s'",
key, pa_proplist_gets (info->proplist, key));
key = pa_proplist_iterate (info->proplist, &state);
}
#endif
card = g_hash_table_lookup (control->priv->cards,
GUINT_TO_POINTER (info->index));
if (card == NULL) {
GList *profile_list = NULL;
GList *port_list = NULL;
for (i = 0; i < info->n_profiles; i++) {
GvcMixerCardProfile *profile;
struct pa_card_profile_info pi = info->profiles[i];
profile = g_new0 (GvcMixerCardProfile, 1);
profile->profile = g_strdup (pi.name);
profile->human_profile = g_strdup (pi.description);
profile->status = card_num_streams_to_status (pi.n_sinks, pi.n_sources);
profile->n_sinks = pi.n_sinks;
profile->n_sources = pi.n_sources;
profile->priority = pi.priority;
profile_list = g_list_prepend (profile_list, profile);
}
card = gvc_mixer_card_new (control->priv->pa_context,
info->index);
gvc_mixer_card_set_profiles (card, profile_list);
for (i = 0; i < info->n_ports; i++) {
GvcMixerCardPort *port;
port = g_new0 (GvcMixerCardPort, 1);
port->port = g_strdup (info->ports[i]->name);
port->human_port = g_strdup (info->ports[i]->description);
port->priority = info->ports[i]->priority;
port->available = info->ports[i]->available;
port->direction = info->ports[i]->direction;
port->profiles = determine_profiles_for_port (info->ports[i], profile_list);
port_list = g_list_prepend (port_list, port);
}
gvc_mixer_card_set_ports (card, port_list);
is_new = TRUE;
}
gvc_mixer_card_set_name (card, pa_proplist_gets (info->proplist, "device.description"));
gvc_mixer_card_set_icon_name (card, pa_proplist_gets (info->proplist, "device.icon_name"));
gvc_mixer_card_set_profile (card, info->active_profile->name);
if (is_new) {
g_hash_table_insert (control->priv->cards,
GUINT_TO_POINTER (info->index),
g_object_ref (card));
}
card_ports = gvc_mixer_card_get_ports (card);
if (card_ports == NULL && is_new) {
g_debug ("Portless card just registered - %s", gvc_mixer_card_get_name (card));
create_ui_device_from_card (control, card);
}
for (m = card_ports; m != NULL; m = m->next) {
GvcMixerCardPort *card_port;
card_port = m->data;
if (is_new)
create_ui_device_from_port (control, card_port, card);
else {
for (i = 0; i < info->n_ports; i++) {
if (g_strcmp0 (card_port->port, info->ports[i]->name) == 0) {
if ((card_port->available == PA_PORT_AVAILABLE_NO) != (info->ports[i]->available == PA_PORT_AVAILABLE_NO)) {
card_port->available = info->ports[i]->available;
g_debug ("sync port availability on card %i, card port name '%s', new available value %i",
gvc_mixer_card_get_index (card),
card_port->port,
card_port->available);
match_card_port_with_existing_device (control,
card_port,
card,
card_port->available != PA_PORT_AVAILABLE_NO);
}
}
}
}
}
g_signal_emit (G_OBJECT (control),
signals[CARD_ADDED],
0,
info->index);
}
static void
_pa_context_get_sink_info_cb (pa_context *context,
const pa_sink_info *i,
int eol,
void *userdata)
{
GvcMixerControl *control = GVC_MIXER_CONTROL (userdata);
if (eol < 0) {
if (pa_context_errno (context) == PA_ERR_NOENTITY) {
return;
}
g_warning ("Sink callback failure");
return;
}
if (eol > 0) {
dec_outstanding (control);
return;
}
update_sink (control, i);
}
static void
_pa_context_get_source_info_cb (pa_context *context,
const pa_source_info *i,
int eol,
void *userdata)
{
GvcMixerControl *control = GVC_MIXER_CONTROL (userdata);
if (eol < 0) {
if (pa_context_errno (context) == PA_ERR_NOENTITY) {
return;
}
g_warning ("Source callback failure");
return;
}
if (eol > 0) {
dec_outstanding (control);
return;
}
update_source (control, i);
}
static void
_pa_context_get_sink_input_info_cb (pa_context *context,
const pa_sink_input_info *i,
int eol,
void *userdata)
{
GvcMixerControl *control = GVC_MIXER_CONTROL (userdata);
if (eol < 0) {
if (pa_context_errno (context) == PA_ERR_NOENTITY) {
return;
}
g_warning ("Sink input callback failure");
return;
}
if (eol > 0) {
dec_outstanding (control);
return;
}
update_sink_input (control, i);
}
static void
_pa_context_get_source_output_info_cb (pa_context *context,
const pa_source_output_info *i,
int eol,
void *userdata)
{
GvcMixerControl *control = GVC_MIXER_CONTROL (userdata);
if (eol < 0) {
if (pa_context_errno (context) == PA_ERR_NOENTITY) {
return;
}
g_warning ("Source output callback failure");
return;
}
if (eol > 0) {
dec_outstanding (control);
return;
}
update_source_output (control, i);
}
static void
_pa_context_get_client_info_cb (pa_context *context,
const pa_client_info *i,
int eol,
void *userdata)
{
GvcMixerControl *control = GVC_MIXER_CONTROL (userdata);
if (eol < 0) {
if (pa_context_errno (context) == PA_ERR_NOENTITY) {
return;
}
g_warning ("Client callback failure");
return;
}
if (eol > 0) {
dec_outstanding (control);
return;
}
update_client (control, i);
}
static void
_pa_context_get_card_info_by_index_cb (pa_context *context,
const pa_card_info *i,
int eol,
void *userdata)
{
GvcMixerControl *control = GVC_MIXER_CONTROL (userdata);
if (eol < 0) {
if (pa_context_errno (context) == PA_ERR_NOENTITY)
return;
g_warning ("Card callback failure");
return;
}
if (eol > 0) {
dec_outstanding (control);
return;
}
update_card (control, i);
}
static void
_pa_context_get_server_info_cb (pa_context *context,
const pa_server_info *i,
void *userdata)
{
GvcMixerControl *control = GVC_MIXER_CONTROL (userdata);
if (i == NULL) {
g_warning ("Server info callback failure");
return;
}
g_debug ("get server info");
update_server (control, i);
dec_outstanding (control);
}
static void
remove_event_role_stream (GvcMixerControl *control)
{
g_debug ("Removing event role");
}
static void
update_event_role_stream (GvcMixerControl *control,
const pa_ext_stream_restore_info *info)
{
GvcMixerStream *stream;
gboolean is_new;
pa_volume_t max_volume;
if (strcmp (info->name, "sink-input-by-media-role:event") != 0) {
return;
}
#if 0
g_debug ("Updating event role: name='%s' device='%s'",
info->name,
info->device);
#endif
is_new = FALSE;
if (!control->priv->event_sink_input_is_set) {
pa_channel_map pa_map;
GvcChannelMap *map;
pa_map.channels = 1;
pa_map.map[0] = PA_CHANNEL_POSITION_MONO;
map = gvc_channel_map_new_from_pa_channel_map (&pa_map);
stream = gvc_mixer_event_role_new (control->priv->pa_context,
info->device,
map);
control->priv->event_sink_input_id = gvc_mixer_stream_get_id (stream);
control->priv->event_sink_input_is_set = TRUE;
is_new = TRUE;
} else {
stream = g_hash_table_lookup (control->priv->all_streams,
GUINT_TO_POINTER (control->priv->event_sink_input_id));
}
max_volume = pa_cvolume_max (&info->volume);
gvc_mixer_stream_set_name (stream, _("System Sounds"));
gvc_mixer_stream_set_icon_name (stream, "cin-multimedia-volume-control");
gvc_mixer_stream_set_volume (stream, (guint)max_volume);
gvc_mixer_stream_set_is_muted (stream, info->mute);
if (is_new) {
add_stream (control, stream);
}
}
static void
_pa_ext_stream_restore_read_cb (pa_context *context,
const pa_ext_stream_restore_info *i,
int eol,
void *userdata)
{
GvcMixerControl *control = GVC_MIXER_CONTROL (userdata);
if (eol < 0) {
g_debug ("Failed to initialized stream_restore extension: %s",
pa_strerror (pa_context_errno (context)));
remove_event_role_stream (control);
return;
}
if (eol > 0) {
dec_outstanding (control);
/* If we don't have an event stream to restore, then
* set one up with a default 100% volume */
if (!control->priv->event_sink_input_is_set) {
pa_ext_stream_restore_info info;
memset (&info, 0, sizeof(info));
info.name = "sink-input-by-media-role:event";
info.volume.channels = 1;
info.volume.values[0] = PA_VOLUME_NORM;
update_event_role_stream (control, &info);
}
return;
}
update_event_role_stream (control, i);
}
static void
_pa_ext_stream_restore_subscribe_cb (pa_context *context,
void *userdata)
{
GvcMixerControl *control = GVC_MIXER_CONTROL (userdata);
pa_operation *o;
o = pa_ext_stream_restore_read (context,
_pa_ext_stream_restore_read_cb,
control);
if (o == NULL) {
g_warning ("pa_ext_stream_restore_read() failed");
return;
}
pa_operation_unref (o);
}
static void
req_update_server_info (GvcMixerControl *control,
int index)
{
pa_operation *o;
o = pa_context_get_server_info (control->priv->pa_context,
_pa_context_get_server_info_cb,
control);
if (o == NULL) {
g_warning ("pa_context_get_server_info() failed");
return;
}
pa_operation_unref (o);
}
static void
req_update_client_info (GvcMixerControl *control,
int index)
{
pa_operation *o;
if (index < 0) {
o = pa_context_get_client_info_list (control->priv->pa_context,
_pa_context_get_client_info_cb,
control);
} else {
o = pa_context_get_client_info (control->priv->pa_context,
index,
_pa_context_get_client_info_cb,
control);
}
if (o == NULL) {
g_warning ("pa_context_client_info_list() failed");
return;
}
pa_operation_unref (o);
}
static void
req_update_card (GvcMixerControl *control,
int index)
{
pa_operation *o;
if (index < 0) {
o = pa_context_get_card_info_list (control->priv->pa_context,
_pa_context_get_card_info_by_index_cb,
control);
} else {
o = pa_context_get_card_info_by_index (control->priv->pa_context,
index,
_pa_context_get_card_info_by_index_cb,
control);
}
if (o == NULL) {
g_warning ("pa_context_get_card_info_by_index() failed");
return;
}
pa_operation_unref (o);
}
static void
req_update_sink_info (GvcMixerControl *control,
int index)
{
pa_operation *o;
if (index < 0) {
o = pa_context_get_sink_info_list (control->priv->pa_context,
_pa_context_get_sink_info_cb,
control);
} else {
o = pa_context_get_sink_info_by_index (control->priv->pa_context,
index,
_pa_context_get_sink_info_cb,
control);
}
if (o == NULL) {
g_warning ("pa_context_get_sink_info_list() failed");
return;
}
pa_operation_unref (o);
}
static void
req_update_source_info (GvcMixerControl *control,
int index)
{
pa_operation *o;
if (index < 0) {
o = pa_context_get_source_info_list (control->priv->pa_context,
_pa_context_get_source_info_cb,
control);
} else {
o = pa_context_get_source_info_by_index(control->priv->pa_context,
index,
_pa_context_get_source_info_cb,
control);
}
if (o == NULL) {
g_warning ("pa_context_get_source_info_list() failed");
return;
}
pa_operation_unref (o);
}
static void
req_update_sink_input_info (GvcMixerControl *control,
int index)
{
pa_operation *o;
if (index < 0) {
o = pa_context_get_sink_input_info_list (control->priv->pa_context,
_pa_context_get_sink_input_info_cb,
control);
} else {
o = pa_context_get_sink_input_info (control->priv->pa_context,
index,
_pa_context_get_sink_input_info_cb,
control);
}
if (o == NULL) {
g_warning ("pa_context_get_sink_input_info_list() failed");
return;
}
pa_operation_unref (o);
}
static void
req_update_source_output_info (GvcMixerControl *control,
int index)
{
pa_operation *o;
if (index < 0) {
o = pa_context_get_source_output_info_list (control->priv->pa_context,
_pa_context_get_source_output_info_cb,
control);
} else {
o = pa_context_get_source_output_info (control->priv->pa_context,
index,
_pa_context_get_source_output_info_cb,
control);
}
if (o == NULL) {
g_warning ("pa_context_get_source_output_info_list() failed");
return;
}
pa_operation_unref (o);
}
static void
remove_client (GvcMixerControl *control,
guint index)
{
g_hash_table_remove (control->priv->clients,
GUINT_TO_POINTER (index));
}
static void
remove_card (GvcMixerControl *control,
guint index)
{
GList *devices, *d;
devices = g_list_concat (g_hash_table_get_values (control->priv->ui_inputs),
g_hash_table_get_values (control->priv->ui_outputs));
for (d = devices; d != NULL; d = d->next) {
GvcMixerCard *card;
GvcMixerUIDevice *device = d->data;
g_object_get (G_OBJECT (device), "card", &card, NULL);
if (gvc_mixer_card_get_index (card) == index) {
g_signal_emit (G_OBJECT (control),
signals[gvc_mixer_ui_device_is_output (device) ? OUTPUT_REMOVED : INPUT_REMOVED],
0,
gvc_mixer_ui_device_get_id (device));
g_debug ("Card removal remove device %s",
gvc_mixer_ui_device_get_description (device));
g_hash_table_remove (gvc_mixer_ui_device_is_output (device) ? control->priv->ui_outputs : control->priv->ui_inputs,
GUINT_TO_POINTER (gvc_mixer_ui_device_get_id (device)));
}
}
g_list_free (devices);
g_hash_table_remove (control->priv->cards,
GUINT_TO_POINTER (index));
g_signal_emit (G_OBJECT (control),
signals[CARD_REMOVED],
0,
index);
}
static void
remove_sink (GvcMixerControl *control,
guint index)
{
GvcMixerStream *stream;
GvcMixerUIDevice *device;
g_debug ("Removing sink: index=%u", index);
stream = g_hash_table_lookup (control->priv->sinks,
GUINT_TO_POINTER (index));
if (stream == NULL)
return;
device = gvc_mixer_control_lookup_device_from_stream (control, stream);
if (device != NULL) {
gvc_mixer_ui_device_invalidate_stream (device);
if (!gvc_mixer_ui_device_has_ports (device)) {
g_signal_emit (G_OBJECT (control),
signals[OUTPUT_REMOVED],
0,
gvc_mixer_ui_device_get_id (device));
} else {
GList *devices, *d;
devices = g_hash_table_get_values (control->priv->ui_outputs);
for (d = devices; d != NULL; d = d->next) {
gint stream_id = GVC_MIXER_UI_DEVICE_INVALID;
device = d->data;
g_object_get (G_OBJECT (device),
"stream-id", &stream_id,
NULL);
if (stream_id == gvc_mixer_stream_get_id (stream))
gvc_mixer_ui_device_invalidate_stream (device);
}
g_list_free (devices);
}
}
g_hash_table_remove (control->priv->sinks,
GUINT_TO_POINTER (index));
remove_stream (control, stream);
}
static void
remove_source (GvcMixerControl *control,
guint index)
{
GvcMixerStream *stream;
GvcMixerUIDevice *device;
g_debug ("Removing source: index=%u", index);
stream = g_hash_table_lookup (control->priv->sources,
GUINT_TO_POINTER (index));
if (stream == NULL)
return;
device = gvc_mixer_control_lookup_device_from_stream (control, stream);
if (device != NULL) {
gvc_mixer_ui_device_invalidate_stream (device);
if (!gvc_mixer_ui_device_has_ports (device)) {
g_signal_emit (G_OBJECT (control),
signals[INPUT_REMOVED],
0,
gvc_mixer_ui_device_get_id (device));
} else {
GList *devices, *d;
devices = g_hash_table_get_values (control->priv->ui_inputs);
for (d = devices; d != NULL; d = d->next) {
gint stream_id = GVC_MIXER_UI_DEVICE_INVALID;
device = d->data;
g_object_get (G_OBJECT (device),
"stream-id", &stream_id,
NULL);
if (stream_id == gvc_mixer_stream_get_id (stream))
gvc_mixer_ui_device_invalidate_stream (device);
}
g_list_free (devices);
}
}
g_hash_table_remove (control->priv->sources,
GUINT_TO_POINTER (index));
remove_stream (control, stream);
}
static void
remove_sink_input (GvcMixerControl *control,
guint index)
{
GvcMixerStream *stream;
g_debug ("Removing sink input: index=%u", index);
stream = g_hash_table_lookup (control->priv->sink_inputs,
GUINT_TO_POINTER (index));
if (stream == NULL) {
return;
}
g_hash_table_remove (control->priv->sink_inputs,
GUINT_TO_POINTER (index));
remove_stream (control, stream);
}
static void
remove_source_output (GvcMixerControl *control,
guint index)
{
GvcMixerStream *stream;
g_debug ("Removing source output: index=%u", index);
stream = g_hash_table_lookup (control->priv->source_outputs,
GUINT_TO_POINTER (index));
if (stream == NULL) {
return;
}
g_hash_table_remove (control->priv->source_outputs,
GUINT_TO_POINTER (index));
remove_stream (control, stream);
}
static void
_pa_context_subscribe_cb (pa_context *context,
pa_subscription_event_type_t t,
uint32_t index,
void *userdata)
{
GvcMixerControl *control = GVC_MIXER_CONTROL (userdata);
switch (t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK) {
case PA_SUBSCRIPTION_EVENT_SINK:
if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) {
remove_sink (control, index);
} else {
req_update_sink_info (control, index);
}
break;
case PA_SUBSCRIPTION_EVENT_SOURCE:
if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) {
remove_source (control, index);
} else {
req_update_source_info (control, index);
}
break;
case PA_SUBSCRIPTION_EVENT_SINK_INPUT:
if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) {
remove_sink_input (control, index);
} else {
req_update_sink_input_info (control, index);
}
break;
case PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT:
if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) {
remove_source_output (control, index);
} else {
req_update_source_output_info (control, index);
}
break;
case PA_SUBSCRIPTION_EVENT_CLIENT:
if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) {
remove_client (control, index);
} else {
req_update_client_info (control, index);
}
break;
case PA_SUBSCRIPTION_EVENT_SERVER:
req_update_server_info (control, index);
break;
case PA_SUBSCRIPTION_EVENT_CARD:
if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) {
remove_card (control, index);
} else {
req_update_card (control, index);
}
break;
}
}
static void
gvc_mixer_control_ready (GvcMixerControl *control)
{
pa_operation *o;
pa_context_set_subscribe_callback (control->priv->pa_context,
_pa_context_subscribe_cb,
control);
o = pa_context_subscribe (control->priv->pa_context,
(pa_subscription_mask_t)
(PA_SUBSCRIPTION_MASK_SINK|
PA_SUBSCRIPTION_MASK_SOURCE|
PA_SUBSCRIPTION_MASK_SINK_INPUT|
PA_SUBSCRIPTION_MASK_SOURCE_OUTPUT|
PA_SUBSCRIPTION_MASK_CLIENT|
PA_SUBSCRIPTION_MASK_SERVER|
PA_SUBSCRIPTION_MASK_CARD),
NULL,
NULL);
if (o == NULL) {
g_warning ("pa_context_subscribe() failed");
return;
}
pa_operation_unref (o);
req_update_server_info (control, -1);
req_update_card (control, -1);
req_update_client_info (control, -1);
req_update_sink_info (control, -1);
req_update_source_info (control, -1);
req_update_sink_input_info (control, -1);
req_update_source_output_info (control, -1);
control->priv->n_outstanding = 6;
/* This call is not always supported */
o = pa_ext_stream_restore_read (control->priv->pa_context,
_pa_ext_stream_restore_read_cb,
control);
if (o != NULL) {
pa_operation_unref (o);
control->priv->n_outstanding++;
pa_ext_stream_restore_set_subscribe_cb (control->priv->pa_context,
_pa_ext_stream_restore_subscribe_cb,
control);
o = pa_ext_stream_restore_subscribe (control->priv->pa_context,
1,
NULL,
NULL);
if (o != NULL) {
pa_operation_unref (o);
}
} else {
g_debug ("Failed to initialized stream_restore extension: %s",
pa_strerror (pa_context_errno (control->priv->pa_context)));
}
}
static void
gvc_mixer_new_pa_context (GvcMixerControl *self)
{
pa_proplist *proplist;
g_return_if_fail (self);
g_return_if_fail (!self->priv->pa_context);
proplist = pa_proplist_new ();
pa_proplist_sets (proplist,
PA_PROP_APPLICATION_NAME,
self->priv->name);
pa_proplist_sets (proplist,
PA_PROP_APPLICATION_ID,
"org.gnome.VolumeControl");
pa_proplist_sets (proplist,
PA_PROP_APPLICATION_ICON_NAME,
"cin-multimedia-volume-control");
pa_proplist_sets (proplist,
PA_PROP_APPLICATION_VERSION,
PACKAGE_VERSION);
self->priv->pa_context = pa_context_new_with_proplist (self->priv->pa_api, NULL, proplist);
pa_proplist_free (proplist);
g_assert (self->priv->pa_context);
}
static void
remove_all_streams (GvcMixerControl *control, GHashTable *hash_table)
{
GHashTableIter iter;
gpointer key, value;
g_hash_table_iter_init (&iter, hash_table);
while (g_hash_table_iter_next (&iter, &key, &value)) {
remove_stream (control, value);
g_hash_table_iter_remove (&iter);
}
}
static gboolean
idle_reconnect (gpointer data)
{
GvcMixerControl *control = GVC_MIXER_CONTROL (data);
GHashTableIter iter;
gpointer key, value;
g_return_val_if_fail (control, FALSE);
if (control->priv->pa_context) {
pa_context_unref (control->priv->pa_context);
control->priv->pa_context = NULL;
gvc_mixer_new_pa_context (control);
}
remove_all_streams (control, control->priv->sinks);
remove_all_streams (control, control->priv->sources);
remove_all_streams (control, control->priv->sink_inputs);
remove_all_streams (control, control->priv->source_outputs);
g_hash_table_iter_init (&iter, control->priv->clients);
while (g_hash_table_iter_next (&iter, &key, &value))
g_hash_table_iter_remove (&iter);
gvc_mixer_control_open (control); /* cannot fail */
control->priv->reconnect_id = 0;
return FALSE;
}
static void
_pa_context_state_cb (pa_context *context,
void *userdata)
{
GvcMixerControl *control = GVC_MIXER_CONTROL (userdata);
switch (pa_context_get_state (context)) {
case PA_CONTEXT_UNCONNECTED:
case PA_CONTEXT_CONNECTING:
case PA_CONTEXT_AUTHORIZING:
case PA_CONTEXT_SETTING_NAME:
break;
case PA_CONTEXT_READY:
gvc_mixer_control_ready (control);
break;
case PA_CONTEXT_FAILED:
control->priv->state = GVC_STATE_FAILED;
g_signal_emit (control, signals[STATE_CHANGED], 0, GVC_STATE_FAILED);
if (control->priv->reconnect_id == 0)
control->priv->reconnect_id = g_timeout_add_seconds (RECONNECT_DELAY, idle_reconnect, control);
break;
case PA_CONTEXT_TERMINATED:
default:
/* FIXME: */
break;
}
}
gboolean
gvc_mixer_control_open (GvcMixerControl *control)
{
int res;
g_return_val_if_fail (GVC_IS_MIXER_CONTROL (control), FALSE);
g_return_val_if_fail (control->priv->pa_context != NULL, FALSE);
g_return_val_if_fail (pa_context_get_state (control->priv->pa_context) == PA_CONTEXT_UNCONNECTED, FALSE);
pa_context_set_state_callback (control->priv->pa_context,
_pa_context_state_cb,
control);
control->priv->state = GVC_STATE_CONNECTING;
g_signal_emit (G_OBJECT (control), signals[STATE_CHANGED], 0, GVC_STATE_CONNECTING);
res = pa_context_connect (control->priv->pa_context, NULL, (pa_context_flags_t) PA_CONTEXT_NOFAIL, NULL);
if (res < 0) {
g_warning ("Failed to connect context: %s",
pa_strerror (pa_context_errno (control->priv->pa_context)));
}
return res;
}
gboolean
gvc_mixer_control_close (GvcMixerControl *control)
{
g_return_val_if_fail (GVC_IS_MIXER_CONTROL (control), FALSE);
g_return_val_if_fail (control->priv->pa_context != NULL, FALSE);
pa_context_disconnect (control->priv->pa_context);
control->priv->state = GVC_STATE_CLOSED;
g_signal_emit (G_OBJECT (control), signals[STATE_CHANGED], 0, GVC_STATE_CLOSED);
return TRUE;
}
static void
gvc_mixer_control_dispose (GObject *object)
{
GvcMixerControl *control = GVC_MIXER_CONTROL (object);
if (control->priv->reconnect_id != 0) {
g_source_remove (control->priv->reconnect_id);
control->priv->reconnect_id = 0;
}
if (control->priv->pa_context != NULL) {
pa_context_unref (control->priv->pa_context);
control->priv->pa_context = NULL;
}
if (control->priv->default_source_name != NULL) {
g_free (control->priv->default_source_name);
control->priv->default_source_name = NULL;
}
if (control->priv->default_sink_name != NULL) {
g_free (control->priv->default_sink_name);
control->priv->default_sink_name = NULL;
}
if (control->priv->pa_mainloop != NULL) {
pa_glib_mainloop_free (control->priv->pa_mainloop);
control->priv->pa_mainloop = NULL;
}
if (control->priv->all_streams != NULL) {
g_hash_table_destroy (control->priv->all_streams);
control->priv->all_streams = NULL;
}
if (control->priv->sinks != NULL) {
g_hash_table_destroy (control->priv->sinks);
control->priv->sinks = NULL;
}
if (control->priv->sources != NULL) {
g_hash_table_destroy (control->priv->sources);
control->priv->sources = NULL;
}
if (control->priv->sink_inputs != NULL) {
g_hash_table_destroy (control->priv->sink_inputs);
control->priv->sink_inputs = NULL;
}
if (control->priv->source_outputs != NULL) {
g_hash_table_destroy (control->priv->source_outputs);
control->priv->source_outputs = NULL;
}
if (control->priv->clients != NULL) {
g_hash_table_destroy (control->priv->clients);
control->priv->clients = NULL;
}
if (control->priv->cards != NULL) {
g_hash_table_destroy (control->priv->cards);
control->priv->cards = NULL;
}
if (control->priv->ui_outputs != NULL) {
g_hash_table_destroy (control->priv->ui_outputs);
control->priv->ui_outputs = NULL;
}
if (control->priv->ui_inputs != NULL) {
g_hash_table_destroy (control->priv->ui_inputs);
control->priv->ui_inputs = NULL;
}
G_OBJECT_CLASS (gvc_mixer_control_parent_class)->dispose (object);
}
static void
gvc_mixer_control_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GvcMixerControl *self = GVC_MIXER_CONTROL (object);
switch (prop_id) {
case PROP_NAME:
g_free (self->priv->name);
self->priv->name = g_value_dup_string (value);
g_object_notify (G_OBJECT (self), "name");
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gvc_mixer_control_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GvcMixerControl *self = GVC_MIXER_CONTROL (object);
switch (prop_id) {
case PROP_NAME:
g_value_set_string (value, self->priv->name);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static GObject *
gvc_mixer_control_constructor (GType type,
guint n_construct_properties,
GObjectConstructParam *construct_params)
{
GObject *object;
GvcMixerControl *self;
object = G_OBJECT_CLASS (gvc_mixer_control_parent_class)->constructor (type, n_construct_properties, construct_params);
self = GVC_MIXER_CONTROL (object);
gvc_mixer_new_pa_context (self);
self->priv->profile_swapping_device_id = GVC_MIXER_UI_DEVICE_INVALID;
return object;
}
static void
gvc_mixer_control_class_init (GvcMixerControlClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->constructor = gvc_mixer_control_constructor;
object_class->dispose = gvc_mixer_control_dispose;
object_class->finalize = gvc_mixer_control_finalize;
object_class->set_property = gvc_mixer_control_set_property;
object_class->get_property = gvc_mixer_control_get_property;
g_object_class_install_property (object_class,
PROP_NAME,
g_param_spec_string ("name",
"Name",
"Name to display for this mixer control",
NULL,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT_ONLY));
signals [STATE_CHANGED] =
g_signal_new ("state-changed",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GvcMixerControlClass, state_changed),
NULL, NULL,
g_cclosure_marshal_VOID__UINT,
G_TYPE_NONE, 1, G_TYPE_UINT);
signals [STREAM_ADDED] =
g_signal_new ("stream-added",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GvcMixerControlClass, stream_added),
NULL, NULL,
g_cclosure_marshal_VOID__UINT,
G_TYPE_NONE, 1, G_TYPE_UINT);
signals [STREAM_REMOVED] =
g_signal_new ("stream-removed",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GvcMixerControlClass, stream_removed),
NULL, NULL,
g_cclosure_marshal_VOID__UINT,
G_TYPE_NONE, 1, G_TYPE_UINT);
signals [CARD_ADDED] =
g_signal_new ("card-added",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GvcMixerControlClass, card_added),
NULL, NULL,
g_cclosure_marshal_VOID__UINT,
G_TYPE_NONE, 1, G_TYPE_UINT);
signals [CARD_REMOVED] =
g_signal_new ("card-removed",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GvcMixerControlClass, card_removed),
NULL, NULL,
g_cclosure_marshal_VOID__UINT,
G_TYPE_NONE, 1, G_TYPE_UINT);
signals [DEFAULT_SINK_CHANGED] =
g_signal_new ("default-sink-changed",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GvcMixerControlClass, default_sink_changed),
NULL, NULL,
g_cclosure_marshal_VOID__UINT,
G_TYPE_NONE, 1, G_TYPE_UINT);
signals [DEFAULT_SOURCE_CHANGED] =
g_signal_new ("default-source-changed",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GvcMixerControlClass, default_source_changed),
NULL, NULL,
g_cclosure_marshal_VOID__UINT,
G_TYPE_NONE, 1, G_TYPE_UINT);
signals [ACTIVE_OUTPUT_UPDATE] =
g_signal_new ("active-output-update",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GvcMixerControlClass, active_output_update),
NULL, NULL,
g_cclosure_marshal_VOID__UINT,
G_TYPE_NONE, 1, G_TYPE_UINT);
signals [ACTIVE_INPUT_UPDATE] =
g_signal_new ("active-input-update",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GvcMixerControlClass, active_input_update),
NULL, NULL,
g_cclosure_marshal_VOID__UINT,
G_TYPE_NONE, 1, G_TYPE_UINT);
signals [OUTPUT_ADDED] =
g_signal_new ("output-added",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GvcMixerControlClass, output_added),
NULL, NULL,
g_cclosure_marshal_VOID__UINT,
G_TYPE_NONE, 1, G_TYPE_UINT);
signals [INPUT_ADDED] =
g_signal_new ("input-added",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GvcMixerControlClass, input_added),
NULL, NULL,
g_cclosure_marshal_VOID__UINT,
G_TYPE_NONE, 1, G_TYPE_UINT);
signals [OUTPUT_REMOVED] =
g_signal_new ("output-removed",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GvcMixerControlClass, output_removed),
NULL, NULL,
g_cclosure_marshal_VOID__UINT,
G_TYPE_NONE, 1, G_TYPE_UINT);
signals [INPUT_REMOVED] =
g_signal_new ("input-removed",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GvcMixerControlClass, input_removed),
NULL, NULL,
g_cclosure_marshal_VOID__UINT,
G_TYPE_NONE, 1, G_TYPE_UINT);
g_type_class_add_private (klass, sizeof (GvcMixerControlPrivate));
}
static void
gvc_mixer_control_init (GvcMixerControl *control)
{
control->priv = GVC_MIXER_CONTROL_GET_PRIVATE (control);
control->priv->pa_mainloop = pa_glib_mainloop_new (g_main_context_default ());
g_assert (control->priv->pa_mainloop);
control->priv->pa_api = pa_glib_mainloop_get_api (control->priv->pa_mainloop);
g_assert (control->priv->pa_api);
control->priv->all_streams = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify)g_object_unref);
control->priv->sinks = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify)g_object_unref);
control->priv->sources = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify)g_object_unref);
control->priv->sink_inputs = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify)g_object_unref);
control->priv->source_outputs = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify)g_object_unref);
control->priv->cards = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify)g_object_unref);
control->priv->ui_outputs = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify)g_object_unref);
control->priv->ui_inputs = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify)g_object_unref);
control->priv->clients = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify)g_free);
control->priv->state = GVC_STATE_CLOSED;
}
static void
gvc_mixer_control_finalize (GObject *object)
{
GvcMixerControl *mixer_control;
g_return_if_fail (object != NULL);
g_return_if_fail (GVC_IS_MIXER_CONTROL (object));
mixer_control = GVC_MIXER_CONTROL (object);
g_free (mixer_control->priv->name);
mixer_control->priv->name = NULL;
g_return_if_fail (mixer_control->priv != NULL);
G_OBJECT_CLASS (gvc_mixer_control_parent_class)->finalize (object);
}
GvcMixerControl *
gvc_mixer_control_new (const char *name)
{
GObject *control;
control = g_object_new (GVC_TYPE_MIXER_CONTROL,
"name", name,
NULL);
return GVC_MIXER_CONTROL (control);
}
gdouble
gvc_mixer_control_get_vol_max_norm (GvcMixerControl *control)
{
return (gdouble) PA_VOLUME_NORM;
}
gdouble
gvc_mixer_control_get_vol_max_amplified (GvcMixerControl *control)
{
return (gdouble) PA_VOLUME_UI_MAX;
}
|
366 | ./cinnamon-control-center/panels/sound/gvc-channel-bar.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2008 William Jon McCann
*
* 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.
*
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pulse/pulseaudio.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <gtk/gtk.h>
#include <canberra-gtk.h>
#include "gvc-channel-bar.h"
#include "gvc-mixer-control.h"
#define SCALE_SIZE 128
#define ADJUSTMENT_MAX_NORMAL gvc_mixer_control_get_vol_max_norm(NULL)
#define ADJUSTMENT_MAX_AMPLIFIED gvc_mixer_control_get_vol_max_amplified(NULL)
#define ADJUSTMENT_MAX (bar->priv->is_amplified ? ADJUSTMENT_MAX_AMPLIFIED : ADJUSTMENT_MAX_NORMAL)
#define SCROLLSTEP (ADJUSTMENT_MAX / 100.0 * 5.0)
#define GVC_CHANNEL_BAR_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GVC_TYPE_CHANNEL_BAR, GvcChannelBarPrivate))
struct GvcChannelBarPrivate
{
GtkOrientation orientation;
GtkWidget *scale_box;
GtkWidget *start_box;
GtkWidget *end_box;
GtkWidget *image;
GtkWidget *label;
GtkWidget *low_image;
GtkWidget *scale;
GtkWidget *high_image;
GtkWidget *mute_box;
GtkWidget *mute_switch;
GtkAdjustment *adjustment;
GtkAdjustment *zero_adjustment;
gboolean show_mute;
gboolean is_muted;
char *name;
char *icon_name;
char *low_icon_name;
char *high_icon_name;
GtkSizeGroup *size_group;
gboolean symmetric;
gboolean click_lock;
gboolean is_amplified;
guint32 base_volume;
};
enum
{
PROP_0,
PROP_ORIENTATION,
PROP_SHOW_MUTE,
PROP_IS_MUTED,
PROP_ADJUSTMENT,
PROP_NAME,
PROP_ICON_NAME,
PROP_LOW_ICON_NAME,
PROP_HIGH_ICON_NAME,
PROP_IS_AMPLIFIED,
PROP_ELLIPSIZE
};
static void gvc_channel_bar_class_init (GvcChannelBarClass *klass);
static void gvc_channel_bar_init (GvcChannelBar *channel_bar);
static void gvc_channel_bar_finalize (GObject *object);
static gboolean on_scale_button_press_event (GtkWidget *widget,
GdkEventButton *event,
GvcChannelBar *bar);
static gboolean on_scale_button_release_event (GtkWidget *widget,
GdkEventButton *event,
GvcChannelBar *bar);
static gboolean on_scale_scroll_event (GtkWidget *widget,
GdkEventScroll *event,
GvcChannelBar *bar);
G_DEFINE_TYPE (GvcChannelBar, gvc_channel_bar, GTK_TYPE_HBOX)
static GtkWidget *
_scale_box_new (GvcChannelBar *bar)
{
GvcChannelBarPrivate *priv = bar->priv;
GtkWidget *box;
GtkWidget *sbox;
GtkWidget *ebox;
if (priv->orientation == GTK_ORIENTATION_VERTICAL) {
bar->priv->scale_box = box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 6);
priv->scale = gtk_scale_new (GTK_ORIENTATION_VERTICAL, priv->adjustment);
gtk_widget_set_size_request (priv->scale, -1, SCALE_SIZE);
gtk_range_set_inverted (GTK_RANGE (priv->scale), TRUE);
bar->priv->start_box = sbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 6);
gtk_box_pack_start (GTK_BOX (box), sbox, FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (sbox), priv->image, FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (sbox), priv->label, FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (sbox), priv->high_image, FALSE, FALSE, 0);
gtk_widget_hide (priv->high_image);
gtk_box_pack_start (GTK_BOX (box), priv->scale, TRUE, TRUE, 0);
bar->priv->end_box = ebox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 6);
gtk_box_pack_start (GTK_BOX (box), ebox, FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (ebox), priv->low_image, FALSE, FALSE, 0);
gtk_widget_hide (priv->low_image);
gtk_box_pack_start (GTK_BOX (ebox), priv->mute_box, FALSE, FALSE, 0);
} else {
bar->priv->scale_box = box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 6);
gtk_box_pack_start (GTK_BOX (box), priv->image, FALSE, FALSE, 0);
priv->scale = gtk_scale_new (GTK_ORIENTATION_HORIZONTAL, priv->adjustment);
gtk_widget_set_size_request (priv->scale, SCALE_SIZE, -1);
bar->priv->start_box = sbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 6);
gtk_box_pack_start (GTK_BOX (box), sbox, FALSE, FALSE, 0);
gtk_box_pack_end (GTK_BOX (sbox), priv->low_image, FALSE, FALSE, 0);
gtk_widget_show (priv->low_image);
gtk_box_pack_start (GTK_BOX (sbox), priv->label, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (box), priv->scale, TRUE, TRUE, 0);
bar->priv->end_box = ebox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 6);
gtk_box_pack_start (GTK_BOX (box), ebox, FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (ebox), priv->high_image, FALSE, FALSE, 0);
gtk_widget_show (priv->high_image);
gtk_box_pack_start (GTK_BOX (ebox), priv->mute_box, FALSE, FALSE, 0);
}
ca_gtk_widget_disable_sounds (bar->priv->scale, FALSE);
gtk_widget_add_events (bar->priv->scale, GDK_SCROLL_MASK);
g_signal_connect (G_OBJECT (bar->priv->scale), "button-press-event",
G_CALLBACK (on_scale_button_press_event), bar);
g_signal_connect (G_OBJECT (bar->priv->scale), "button-release-event",
G_CALLBACK (on_scale_button_release_event), bar);
g_signal_connect (G_OBJECT (bar->priv->scale), "scroll-event",
G_CALLBACK (on_scale_scroll_event), bar);
if (bar->priv->size_group != NULL) {
gtk_size_group_add_widget (bar->priv->size_group, sbox);
if (bar->priv->symmetric) {
gtk_size_group_add_widget (bar->priv->size_group, ebox);
}
}
gtk_scale_set_draw_value (GTK_SCALE (priv->scale), FALSE);
return box;
}
static void
update_image (GvcChannelBar *bar)
{
gtk_image_set_from_icon_name (GTK_IMAGE (bar->priv->image),
bar->priv->icon_name,
GTK_ICON_SIZE_DIALOG);
if (bar->priv->icon_name != NULL) {
gtk_widget_show (bar->priv->image);
} else {
gtk_widget_hide (bar->priv->image);
}
}
static void
update_label (GvcChannelBar *bar)
{
if (bar->priv->name != NULL) {
gtk_label_set_text_with_mnemonic (GTK_LABEL (bar->priv->label),
bar->priv->name);
gtk_label_set_mnemonic_widget (GTK_LABEL (bar->priv->label),
bar->priv->scale);
gtk_widget_show (bar->priv->label);
} else {
gtk_label_set_text (GTK_LABEL (bar->priv->label), NULL);
gtk_widget_hide (bar->priv->label);
}
}
static void
update_layout (GvcChannelBar *bar)
{
GtkWidget *box;
GtkWidget *frame;
if (bar->priv->scale == NULL) {
return;
}
box = bar->priv->scale_box;
frame = gtk_widget_get_parent (box);
g_object_ref (bar->priv->image);
g_object_ref (bar->priv->label);
g_object_ref (bar->priv->mute_box);
g_object_ref (bar->priv->low_image);
g_object_ref (bar->priv->high_image);
gtk_container_remove (GTK_CONTAINER (bar->priv->start_box), bar->priv->image);
gtk_container_remove (GTK_CONTAINER (bar->priv->start_box), bar->priv->label);
gtk_container_remove (GTK_CONTAINER (bar->priv->end_box), bar->priv->mute_box);
if (bar->priv->orientation == GTK_ORIENTATION_VERTICAL) {
gtk_container_remove (GTK_CONTAINER (bar->priv->start_box), bar->priv->low_image);
gtk_container_remove (GTK_CONTAINER (bar->priv->end_box), bar->priv->high_image);
} else {
gtk_container_remove (GTK_CONTAINER (bar->priv->end_box), bar->priv->low_image);
gtk_container_remove (GTK_CONTAINER (bar->priv->start_box), bar->priv->high_image);
}
gtk_container_remove (GTK_CONTAINER (box), bar->priv->start_box);
gtk_container_remove (GTK_CONTAINER (box), bar->priv->scale);
gtk_container_remove (GTK_CONTAINER (box), bar->priv->end_box);
gtk_container_remove (GTK_CONTAINER (frame), box);
bar->priv->scale_box = _scale_box_new (bar);
gtk_container_add (GTK_CONTAINER (frame), bar->priv->scale_box);
g_object_unref (bar->priv->image);
g_object_unref (bar->priv->label);
g_object_unref (bar->priv->mute_box);
g_object_unref (bar->priv->low_image);
g_object_unref (bar->priv->high_image);
gtk_widget_show_all (frame);
}
void
gvc_channel_bar_set_size_group (GvcChannelBar *bar,
GtkSizeGroup *group,
gboolean symmetric)
{
g_return_if_fail (GVC_IS_CHANNEL_BAR (bar));
bar->priv->size_group = group;
bar->priv->symmetric = symmetric;
if (bar->priv->size_group != NULL) {
gtk_size_group_add_widget (bar->priv->size_group,
bar->priv->start_box);
if (bar->priv->symmetric) {
gtk_size_group_add_widget (bar->priv->size_group,
bar->priv->end_box);
}
}
gtk_widget_queue_draw (GTK_WIDGET (bar));
}
void
gvc_channel_bar_set_name (GvcChannelBar *bar,
const char *name)
{
g_return_if_fail (GVC_IS_CHANNEL_BAR (bar));
g_free (bar->priv->name);
bar->priv->name = g_strdup (name);
update_label (bar);
g_object_notify (G_OBJECT (bar), "name");
}
void
gvc_channel_bar_set_icon_name (GvcChannelBar *bar,
const char *name)
{
g_return_if_fail (GVC_IS_CHANNEL_BAR (bar));
g_free (bar->priv->icon_name);
bar->priv->icon_name = g_strdup (name);
update_image (bar);
g_object_notify (G_OBJECT (bar), "icon-name");
}
void
gvc_channel_bar_set_low_icon_name (GvcChannelBar *bar,
const char *name)
{
g_return_if_fail (GVC_IS_CHANNEL_BAR (bar));
if (name != NULL && strcmp (bar->priv->low_icon_name, name) != 0) {
g_free (bar->priv->low_icon_name);
bar->priv->low_icon_name = g_strdup (name);
gtk_image_set_from_icon_name (GTK_IMAGE (bar->priv->low_image),
bar->priv->low_icon_name,
GTK_ICON_SIZE_MENU);
g_object_notify (G_OBJECT (bar), "low-icon-name");
}
}
void
gvc_channel_bar_set_high_icon_name (GvcChannelBar *bar,
const char *name)
{
g_return_if_fail (GVC_IS_CHANNEL_BAR (bar));
if (name != NULL && strcmp (bar->priv->high_icon_name, name) != 0) {
g_free (bar->priv->high_icon_name);
bar->priv->high_icon_name = g_strdup (name);
gtk_image_set_from_icon_name (GTK_IMAGE (bar->priv->high_image),
bar->priv->high_icon_name,
GTK_ICON_SIZE_MENU);
g_object_notify (G_OBJECT (bar), "high-icon-name");
}
}
void
gvc_channel_bar_set_orientation (GvcChannelBar *bar,
GtkOrientation orientation)
{
g_return_if_fail (GVC_IS_CHANNEL_BAR (bar));
if (orientation != bar->priv->orientation) {
bar->priv->orientation = orientation;
update_layout (bar);
g_object_notify (G_OBJECT (bar), "orientation");
}
}
static void
gvc_channel_bar_set_adjustment (GvcChannelBar *bar,
GtkAdjustment *adjustment)
{
g_return_if_fail (GVC_CHANNEL_BAR (bar));
g_return_if_fail (GTK_IS_ADJUSTMENT (adjustment));
if (bar->priv->adjustment != NULL) {
g_object_unref (bar->priv->adjustment);
}
bar->priv->adjustment = g_object_ref_sink (adjustment);
if (bar->priv->scale != NULL) {
gtk_range_set_adjustment (GTK_RANGE (bar->priv->scale), adjustment);
}
g_object_notify (G_OBJECT (bar), "adjustment");
}
GtkAdjustment *
gvc_channel_bar_get_adjustment (GvcChannelBar *bar)
{
g_return_val_if_fail (GVC_IS_CHANNEL_BAR (bar), NULL);
return bar->priv->adjustment;
}
static gboolean
on_scale_button_press_event (GtkWidget *widget,
GdkEventButton *event,
GvcChannelBar *bar)
{
bar->priv->click_lock = TRUE;
return FALSE;
}
static gboolean
on_scale_button_release_event (GtkWidget *widget,
GdkEventButton *event,
GvcChannelBar *bar)
{
GtkAdjustment *adj;
gdouble value;
bar->priv->click_lock = FALSE;
adj = gtk_range_get_adjustment (GTK_RANGE (widget));
value = gtk_adjustment_get_value (adj);
/* this means the adjustment moved away from zero and
* therefore we should unmute and set the volume. */
gvc_channel_bar_set_is_muted (bar, (value == 0.0));
/* Play a sound! */
ca_gtk_play_for_widget (GTK_WIDGET (bar), 0,
CA_PROP_EVENT_ID, "audio-volume-change",
CA_PROP_EVENT_DESCRIPTION, "foobar event happened",
CA_PROP_APPLICATION_ID, "org.gnome.VolumeControl",
NULL);
return FALSE;
}
gboolean
gvc_channel_bar_scroll (GvcChannelBar *bar, GdkEventScroll *event)
{
GtkAdjustment *adj;
gdouble value;
GdkScrollDirection direction;
gdouble dx, dy;
g_return_val_if_fail (bar != NULL, FALSE);
g_return_val_if_fail (GVC_IS_CHANNEL_BAR (bar), FALSE);
direction = event->direction;
if (bar->priv->orientation == GTK_ORIENTATION_VERTICAL) {
if (direction == GDK_SCROLL_LEFT || direction == GDK_SCROLL_RIGHT)
return FALSE;
} else {
/* Switch direction for RTL */
if (gtk_widget_get_direction (GTK_WIDGET (bar)) == GTK_TEXT_DIR_RTL) {
if (direction == GDK_SCROLL_RIGHT)
direction = GDK_SCROLL_LEFT;
else if (direction == GDK_SCROLL_LEFT)
direction = GDK_SCROLL_RIGHT;
}
/* Switch side scroll to vertical */
if (direction == GDK_SCROLL_RIGHT)
direction = GDK_SCROLL_UP;
else if (direction == GDK_SCROLL_LEFT)
direction = GDK_SCROLL_DOWN;
}
if (!gdk_event_get_scroll_deltas ((GdkEvent*)event, &dx, &dy)) {
dx = 0.0;
dy = 0.0;
switch (direction) {
case GDK_SCROLL_UP:
case GDK_SCROLL_LEFT:
dy = 1.0;
break;
case GDK_SCROLL_DOWN:
case GDK_SCROLL_RIGHT:
dy = -1.0;
break;
default:
;
}
}
adj = gtk_range_get_adjustment (GTK_RANGE (bar->priv->scale));
if (adj == bar->priv->zero_adjustment) {
if (dy > 0)
gvc_channel_bar_set_is_muted (bar, FALSE);
return TRUE;
}
value = gtk_adjustment_get_value (adj);
if (dy > 0) {
if (value + dy * SCROLLSTEP > ADJUSTMENT_MAX)
value = ADJUSTMENT_MAX;
else
value = value + dy * SCROLLSTEP;
} else if (dy < 0) {
if (value + dy * SCROLLSTEP < 0)
value = 0.0;
else
value = value + dy * SCROLLSTEP;
}
gvc_channel_bar_set_is_muted (bar, (value == 0.0));
adj = gtk_range_get_adjustment (GTK_RANGE (bar->priv->scale));
gtk_adjustment_set_value (adj, value);
return TRUE;
}
static gboolean
on_scale_scroll_event (GtkWidget *widget,
GdkEventScroll *event,
GvcChannelBar *bar)
{
return gvc_channel_bar_scroll (bar, event);
}
static void
on_zero_adjustment_value_changed (GtkAdjustment *adjustment,
GvcChannelBar *bar)
{
gdouble value;
if (bar->priv->click_lock != FALSE) {
return;
}
value = gtk_adjustment_get_value (bar->priv->zero_adjustment);
gtk_adjustment_set_value (bar->priv->adjustment, value);
if (bar->priv->show_mute == FALSE) {
/* this means the adjustment moved away from zero and
* therefore we should unmute and set the volume. */
gvc_channel_bar_set_is_muted (bar, value > 0.0);
}
}
static void
update_mute_switch (GvcChannelBar *bar)
{
if (bar->priv->show_mute) {
gtk_widget_show (bar->priv->mute_switch);
gtk_switch_set_active (GTK_SWITCH (bar->priv->mute_switch),
!bar->priv->is_muted);
} else {
gtk_widget_hide (bar->priv->mute_switch);
}
if (bar->priv->is_muted) {
/* If we aren't showing the mute button then
* move slider to the zero. But we don't want to
* change the adjustment. */
g_signal_handlers_block_by_func (bar->priv->zero_adjustment,
on_zero_adjustment_value_changed,
bar);
gtk_adjustment_set_value (bar->priv->zero_adjustment, 0);
g_signal_handlers_unblock_by_func (bar->priv->zero_adjustment,
on_zero_adjustment_value_changed,
bar);
gtk_range_set_adjustment (GTK_RANGE (bar->priv->scale),
bar->priv->zero_adjustment);
} else {
/* no longer muted so restore the original adjustment
* and tell the front-end that the value changed */
gtk_range_set_adjustment (GTK_RANGE (bar->priv->scale),
bar->priv->adjustment);
gtk_adjustment_value_changed (bar->priv->adjustment);
}
}
void
gvc_channel_bar_set_is_muted (GvcChannelBar *bar,
gboolean is_muted)
{
g_return_if_fail (GVC_IS_CHANNEL_BAR (bar));
if (is_muted != bar->priv->is_muted) {
/* Update our internal state before telling the
* front-end about our changes */
bar->priv->is_muted = is_muted;
update_mute_switch (bar);
g_object_notify (G_OBJECT (bar), "is-muted");
}
}
gboolean
gvc_channel_bar_get_is_muted (GvcChannelBar *bar)
{
g_return_val_if_fail (GVC_IS_CHANNEL_BAR (bar), FALSE);
return bar->priv->is_muted;
}
void
gvc_channel_bar_set_show_mute (GvcChannelBar *bar,
gboolean show_mute)
{
g_return_if_fail (GVC_IS_CHANNEL_BAR (bar));
if (show_mute != bar->priv->show_mute) {
bar->priv->show_mute = show_mute;
g_object_notify (G_OBJECT (bar), "show-mute");
update_mute_switch (bar);
}
}
gboolean
gvc_channel_bar_get_show_mute (GvcChannelBar *bar)
{
g_return_val_if_fail (GVC_IS_CHANNEL_BAR (bar), FALSE);
return bar->priv->show_mute;
}
void
gvc_channel_bar_set_is_amplified (GvcChannelBar *bar, gboolean amplified)
{
g_return_if_fail (GVC_IS_CHANNEL_BAR (bar));
bar->priv->is_amplified = amplified;
gtk_adjustment_set_upper (bar->priv->adjustment, ADJUSTMENT_MAX);
gtk_adjustment_set_upper (bar->priv->zero_adjustment, ADJUSTMENT_MAX);
gtk_scale_clear_marks (GTK_SCALE (bar->priv->scale));
if (amplified) {
char *str;
if (bar->priv->base_volume == ADJUSTMENT_MAX_NORMAL) {
str = g_strdup_printf ("<small>%s</small>", C_("volume", "100%"));
gtk_scale_add_mark (GTK_SCALE (bar->priv->scale), ADJUSTMENT_MAX_NORMAL,
GTK_POS_BOTTOM, str);
} else {
str = g_strdup_printf ("<small>%s</small>", C_("volume", "Unamplified"));
gtk_scale_add_mark (GTK_SCALE (bar->priv->scale), bar->priv->base_volume,
GTK_POS_BOTTOM, str);
/* Only show 100% if it's higher than the base volume */
if (bar->priv->base_volume < ADJUSTMENT_MAX_NORMAL) {
str = g_strdup_printf ("<small>%s</small>", C_("volume", "100%"));
gtk_scale_add_mark (GTK_SCALE (bar->priv->scale), ADJUSTMENT_MAX_NORMAL,
GTK_POS_BOTTOM, str);
}
}
g_free (str);
gtk_alignment_set (GTK_ALIGNMENT (bar->priv->mute_box), 0.5, 0, 0, 0);
gtk_misc_set_alignment (GTK_MISC (bar->priv->low_image), 0.5, 0.15);
gtk_misc_set_alignment (GTK_MISC (bar->priv->high_image), 0.5, 0.15);
gtk_misc_set_alignment (GTK_MISC (bar->priv->label), 0, 0);
} else {
gtk_alignment_set (GTK_ALIGNMENT (bar->priv->mute_box), 0.5, 0.5, 0, 0);
gtk_misc_set_alignment (GTK_MISC (bar->priv->low_image), 0.5, 0.5);
gtk_misc_set_alignment (GTK_MISC (bar->priv->high_image), 0.5, 0.5);
gtk_misc_set_alignment (GTK_MISC (bar->priv->label), 0, 0.5);
}
}
gboolean
gvc_channel_bar_get_ellipsize (GvcChannelBar *bar)
{
g_return_val_if_fail (GVC_IS_CHANNEL_BAR (bar), FALSE);
return gtk_label_get_ellipsize (GTK_LABEL (bar->priv->label)) != PANGO_ELLIPSIZE_NONE;
}
void
gvc_channel_bar_set_ellipsize (GvcChannelBar *bar,
gboolean ellipsized)
{
g_return_if_fail (GVC_IS_CHANNEL_BAR (bar));
if (ellipsized)
gtk_label_set_ellipsize (GTK_LABEL (bar->priv->label), PANGO_ELLIPSIZE_END);
else
gtk_label_set_ellipsize (GTK_LABEL (bar->priv->label), PANGO_ELLIPSIZE_NONE);
}
void
gvc_channel_bar_set_base_volume (GvcChannelBar *bar,
pa_volume_t base_volume)
{
g_return_if_fail (GVC_IS_CHANNEL_BAR (bar));
if (base_volume == 0) {
bar->priv->base_volume = ADJUSTMENT_MAX_NORMAL;
return;
}
/* Note that you need to call _is_amplified() afterwards to update the marks */
bar->priv->base_volume = base_volume;
}
static void
gvc_channel_bar_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GvcChannelBar *self = GVC_CHANNEL_BAR (object);
switch (prop_id) {
case PROP_ORIENTATION:
gvc_channel_bar_set_orientation (self, g_value_get_enum (value));
break;
case PROP_IS_MUTED:
gvc_channel_bar_set_is_muted (self, g_value_get_boolean (value));
break;
case PROP_SHOW_MUTE:
gvc_channel_bar_set_show_mute (self, g_value_get_boolean (value));
break;
case PROP_NAME:
gvc_channel_bar_set_name (self, g_value_get_string (value));
break;
case PROP_ICON_NAME:
gvc_channel_bar_set_icon_name (self, g_value_get_string (value));
break;
case PROP_LOW_ICON_NAME:
gvc_channel_bar_set_low_icon_name (self, g_value_get_string (value));
break;
case PROP_HIGH_ICON_NAME:
gvc_channel_bar_set_high_icon_name (self, g_value_get_string (value));
break;
case PROP_ADJUSTMENT:
gvc_channel_bar_set_adjustment (self, g_value_get_object (value));
break;
case PROP_IS_AMPLIFIED:
gvc_channel_bar_set_is_amplified (self, g_value_get_boolean (value));
break;
case PROP_ELLIPSIZE:
gvc_channel_bar_set_ellipsize (self, g_value_get_boolean (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gvc_channel_bar_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GvcChannelBar *self = GVC_CHANNEL_BAR (object);
GvcChannelBarPrivate *priv = self->priv;
switch (prop_id) {
case PROP_ORIENTATION:
g_value_set_enum (value, priv->orientation);
break;
case PROP_IS_MUTED:
g_value_set_boolean (value, priv->is_muted);
break;
case PROP_SHOW_MUTE:
g_value_set_boolean (value, priv->show_mute);
break;
case PROP_NAME:
g_value_set_string (value, priv->name);
break;
case PROP_ICON_NAME:
g_value_set_string (value, priv->icon_name);
break;
case PROP_LOW_ICON_NAME:
g_value_set_string (value, priv->low_icon_name);
break;
case PROP_HIGH_ICON_NAME:
g_value_set_string (value, priv->high_icon_name);
break;
case PROP_ADJUSTMENT:
g_value_set_object (value, gvc_channel_bar_get_adjustment (self));
break;
case PROP_IS_AMPLIFIED:
g_value_set_boolean (value, priv->is_amplified);
break;
case PROP_ELLIPSIZE:
g_value_set_boolean (value, gvc_channel_bar_get_ellipsize (self));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static GObject *
gvc_channel_bar_constructor (GType type,
guint n_construct_properties,
GObjectConstructParam *construct_params)
{
GObject *object;
GvcChannelBar *self;
object = G_OBJECT_CLASS (gvc_channel_bar_parent_class)->constructor (type, n_construct_properties, construct_params);
self = GVC_CHANNEL_BAR (object);
update_mute_switch (self);
return object;
}
static void
gvc_channel_bar_class_init (GvcChannelBarClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->constructor = gvc_channel_bar_constructor;
object_class->finalize = gvc_channel_bar_finalize;
object_class->set_property = gvc_channel_bar_set_property;
object_class->get_property = gvc_channel_bar_get_property;
g_object_class_install_property (object_class,
PROP_ORIENTATION,
g_param_spec_enum ("orientation",
"Orientation",
"The orientation of the scale",
GTK_TYPE_ORIENTATION,
GTK_ORIENTATION_VERTICAL,
G_PARAM_READWRITE));
g_object_class_install_property (object_class,
PROP_IS_MUTED,
g_param_spec_boolean ("is-muted",
"is muted",
"Whether stream is muted",
FALSE,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (object_class,
PROP_SHOW_MUTE,
g_param_spec_boolean ("show-mute",
"show mute",
"Whether stream is muted",
FALSE,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (object_class,
PROP_ADJUSTMENT,
g_param_spec_object ("adjustment",
"Adjustment",
"The GtkAdjustment that contains the current value of this scale button object",
GTK_TYPE_ADJUSTMENT,
G_PARAM_READWRITE));
g_object_class_install_property (object_class,
PROP_NAME,
g_param_spec_string ("name",
"Name",
"Name to display for this stream",
NULL,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (object_class,
PROP_ICON_NAME,
g_param_spec_string ("icon-name",
"Icon Name",
"Name of icon to display for this stream",
NULL,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (object_class,
PROP_LOW_ICON_NAME,
g_param_spec_string ("low-icon-name",
"Icon Name",
"Name of icon to display for this stream",
"audio-volume-low-symbolic",
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (object_class,
PROP_HIGH_ICON_NAME,
g_param_spec_string ("high-icon-name",
"Icon Name",
"Name of icon to display for this stream",
"audio-volume-high-symbolic",
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (object_class,
PROP_IS_AMPLIFIED,
g_param_spec_boolean ("is-amplified",
"Is amplified",
"Whether the stream is digitally amplified",
FALSE,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (object_class,
PROP_ELLIPSIZE,
g_param_spec_boolean ("ellipsize",
"Label is ellipsized",
"Whether the label is ellipsized",
FALSE,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_type_class_add_private (klass, sizeof (GvcChannelBarPrivate));
}
static void
on_mute_switch_toggled (GtkSwitch *sw,
GParamSpec *pspec,
GvcChannelBar *bar)
{
gboolean is_muted;
is_muted = gtk_switch_get_active (sw);
gvc_channel_bar_set_is_muted (bar, !is_muted);
}
static void
gvc_channel_bar_init (GvcChannelBar *bar)
{
GtkWidget *frame;
bar->priv = GVC_CHANNEL_BAR_GET_PRIVATE (bar);
bar->priv->base_volume = ADJUSTMENT_MAX_NORMAL;
bar->priv->low_icon_name = g_strdup ("cin-audio-volume-low-symbolic");
bar->priv->high_icon_name = g_strdup ("cin-audio-volume-high-symbolic");
bar->priv->orientation = GTK_ORIENTATION_VERTICAL;
bar->priv->adjustment = GTK_ADJUSTMENT (gtk_adjustment_new (0.0,
0.0,
ADJUSTMENT_MAX_NORMAL,
ADJUSTMENT_MAX_NORMAL/100.0,
ADJUSTMENT_MAX_NORMAL/10.0,
0.0));
g_object_ref_sink (bar->priv->adjustment);
bar->priv->zero_adjustment = GTK_ADJUSTMENT (gtk_adjustment_new (0.0,
0.0,
ADJUSTMENT_MAX_NORMAL,
ADJUSTMENT_MAX_NORMAL/100.0,
ADJUSTMENT_MAX_NORMAL/10.0,
0.0));
g_object_ref_sink (bar->priv->zero_adjustment);
g_signal_connect (bar->priv->zero_adjustment,
"value-changed",
G_CALLBACK (on_zero_adjustment_value_changed),
bar);
bar->priv->mute_switch = gtk_switch_new ();
gtk_widget_set_no_show_all (bar->priv->mute_switch, TRUE);
g_signal_connect (bar->priv->mute_switch,
"notify::active",
G_CALLBACK (on_mute_switch_toggled),
bar);
bar->priv->mute_box = gtk_alignment_new (0.5, 0.5, 0, 0);
gtk_container_add (GTK_CONTAINER (bar->priv->mute_box), bar->priv->mute_switch);
bar->priv->low_image = gtk_image_new_from_icon_name ("cin-audio-volume-low-symbolic",
GTK_ICON_SIZE_MENU);
gtk_widget_set_no_show_all (bar->priv->low_image, TRUE);
bar->priv->high_image = gtk_image_new_from_icon_name ("cin-audio-volume-high-symbolic",
GTK_ICON_SIZE_MENU);
gtk_widget_set_no_show_all (bar->priv->high_image, TRUE);
bar->priv->image = gtk_image_new ();
gtk_widget_set_no_show_all (bar->priv->image, TRUE);
bar->priv->label = gtk_label_new (NULL);
gtk_misc_set_alignment (GTK_MISC (bar->priv->label), 0.0, 0.5);
gtk_widget_set_no_show_all (bar->priv->label, TRUE);
/* frame */
frame = gtk_frame_new (NULL);
gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_NONE);
gtk_container_add (GTK_CONTAINER (bar), frame);
gtk_widget_show_all (frame);
/* box with scale */
bar->priv->scale_box = _scale_box_new (bar);
gtk_container_add (GTK_CONTAINER (frame), bar->priv->scale_box);
}
static void
gvc_channel_bar_finalize (GObject *object)
{
GvcChannelBar *channel_bar;
g_return_if_fail (object != NULL);
g_return_if_fail (GVC_IS_CHANNEL_BAR (object));
channel_bar = GVC_CHANNEL_BAR (object);
g_return_if_fail (channel_bar->priv != NULL);
g_free (channel_bar->priv->name);
g_free (channel_bar->priv->icon_name);
g_free (channel_bar->priv->low_icon_name);
g_free (channel_bar->priv->high_icon_name);
G_OBJECT_CLASS (gvc_channel_bar_parent_class)->finalize (object);
}
GtkWidget *
gvc_channel_bar_new (void)
{
GObject *bar;
bar = g_object_new (GVC_TYPE_CHANNEL_BAR,
NULL);
return GTK_WIDGET (bar);
}
|
367 | ./cinnamon-control-center/panels/sound/gvc-applet.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2008 Red Hat, Inc.
*
* 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.
*
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <gtk/gtk.h>
#include <pulse/pulseaudio.h>
#include "gvc-applet.h"
#include "gvc-mixer-control.h"
#include "gvc-stream-status-icon.h"
#define GVC_APPLET_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GVC_TYPE_APPLET, GvcAppletPrivate))
#define SCALE_SIZE 128
static const char *output_icon_names[] = {
"cin-audio-volume-muted-symbolic",
"cin-audio-volume-low-symbolic",
"cin-audio-volume-medium-symbolic",
"cin-audio-volume-high-symbolic",
NULL
};
static const char *input_icon_names[] = {
"cin-audio-input-microphone-muted-symbolic",
"cin-audio-input-microphone-low-symbolic",
"cin-audio-input-microphone-medium-symbolic",
"cin-audio-input-microphone-high-symbolic",
NULL
};
struct GvcAppletPrivate
{
GvcStreamStatusIcon *input_status_icon;
GvcStreamStatusIcon *output_status_icon;
GvcMixerControl *control;
};
static void gvc_applet_class_init (GvcAppletClass *klass);
static void gvc_applet_init (GvcApplet *applet);
static void gvc_applet_finalize (GObject *object);
G_DEFINE_TYPE (GvcApplet, gvc_applet, G_TYPE_OBJECT)
static void
maybe_show_status_icons (GvcApplet *applet)
{
gboolean show;
GvcMixerStream *stream;
GSList *source_outputs, *l;
show = TRUE;
stream = gvc_mixer_control_get_default_sink (applet->priv->control);
if (stream == NULL) {
show = FALSE;
}
gtk_status_icon_set_visible (GTK_STATUS_ICON (applet->priv->output_status_icon), show);
show = FALSE;
stream = gvc_mixer_control_get_default_source (applet->priv->control);
source_outputs = gvc_mixer_control_get_source_outputs (applet->priv->control);
if (stream != NULL && source_outputs != NULL) {
/* Check that we're not trying to add the peak detector
* as an application doing recording */
for (l = source_outputs ; l ; l = l->next) {
GvcMixerStream *s = l->data;
const char *id;
id = gvc_mixer_stream_get_application_id (s);
if (id == NULL) {
show = TRUE;
break;
}
if (!g_str_equal (id, "org.gnome.VolumeControl") &&
!g_str_equal (id, "org.PulseAudio.pavucontrol")) {
show = TRUE;
break;
}
}
}
gtk_status_icon_set_visible (GTK_STATUS_ICON (applet->priv->input_status_icon), show);
g_slist_free (source_outputs);
}
void
gvc_applet_start (GvcApplet *applet)
{
g_return_if_fail (GVC_IS_APPLET (applet));
maybe_show_status_icons (applet);
}
static void
gvc_applet_dispose (GObject *object)
{
GvcApplet *applet = GVC_APPLET (object);
if (applet->priv->control != NULL) {
g_object_unref (applet->priv->control);
applet->priv->control = NULL;
}
G_OBJECT_CLASS (gvc_applet_parent_class)->dispose (object);
}
static void
update_default_source (GvcApplet *applet)
{
GvcMixerStream *stream;
stream = gvc_mixer_control_get_default_source (applet->priv->control);
if (stream != NULL) {
gvc_stream_status_icon_set_mixer_stream (applet->priv->input_status_icon,
stream);
maybe_show_status_icons(applet);
} else {
g_debug ("Unable to get default source, or no source available");
}
}
static void
update_default_sink (GvcApplet *applet)
{
GvcMixerStream *stream;
stream = gvc_mixer_control_get_default_sink (applet->priv->control);
if (stream != NULL) {
gvc_stream_status_icon_set_mixer_stream (applet->priv->output_status_icon,
stream);
maybe_show_status_icons(applet);
} else {
g_warning ("Unable to get default sink");
}
}
static void
on_control_state_changed (GvcMixerControl *control,
GvcMixerControlState new_state,
GvcApplet *applet)
{
if (new_state == GVC_STATE_READY) {
update_default_sink (applet);
update_default_source (applet);
} else if (new_state == GVC_STATE_CONNECTING) {
g_debug ("Connecting...");
}
}
static void
on_control_default_sink_changed (GvcMixerControl *control,
guint id,
GvcApplet *applet)
{
update_default_sink (applet);
}
static void
on_control_default_source_changed (GvcMixerControl *control,
guint id,
GvcApplet *applet)
{
update_default_source (applet);
}
static void
on_control_stream_removed (GvcMixerControl *control,
guint id,
GvcApplet *applet)
{
maybe_show_status_icons (applet);
}
static void
on_control_stream_added (GvcMixerControl *control,
guint id,
GvcApplet *applet)
{
maybe_show_status_icons (applet);
}
static GObject *
gvc_applet_constructor (GType type,
guint n_construct_properties,
GObjectConstructParam *construct_params)
{
GObject *object;
GvcApplet *self;
object = G_OBJECT_CLASS (gvc_applet_parent_class)->constructor (type, n_construct_properties, construct_params);
self = GVC_APPLET (object);
self->priv->control = gvc_mixer_control_new ("Cinnamon Volume Control Applet");
g_signal_connect (self->priv->control,
"state-changed",
G_CALLBACK (on_control_state_changed),
self);
g_signal_connect (self->priv->control,
"default-sink-changed",
G_CALLBACK (on_control_default_sink_changed),
self);
g_signal_connect (self->priv->control,
"default-source-changed",
G_CALLBACK (on_control_default_source_changed),
self);
g_signal_connect (self->priv->control,
"stream-added",
G_CALLBACK (on_control_stream_added),
self);
g_signal_connect (self->priv->control,
"stream-removed",
G_CALLBACK (on_control_stream_removed),
self);
gvc_mixer_control_open (self->priv->control);
return object;
}
static void
gvc_applet_class_init (GvcAppletClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->finalize = gvc_applet_finalize;
object_class->dispose = gvc_applet_dispose;
object_class->constructor = gvc_applet_constructor;
g_type_class_add_private (klass, sizeof (GvcAppletPrivate));
}
static void
gvc_applet_init (GvcApplet *applet)
{
applet->priv = GVC_APPLET_GET_PRIVATE (applet);
applet->priv->output_status_icon = gvc_stream_status_icon_new (NULL,
output_icon_names);
gvc_stream_status_icon_set_display_name (applet->priv->output_status_icon,
_("Output"));
gtk_status_icon_set_title (GTK_STATUS_ICON (applet->priv->output_status_icon),
_("Sound Output Volume"));
applet->priv->input_status_icon = gvc_stream_status_icon_new (NULL,
input_icon_names);
gvc_stream_status_icon_set_display_name (applet->priv->input_status_icon,
_("Input"));
gtk_status_icon_set_title (GTK_STATUS_ICON (applet->priv->input_status_icon),
_("Microphone Volume"));
}
static void
gvc_applet_finalize (GObject *object)
{
GvcApplet *applet;
g_return_if_fail (object != NULL);
g_return_if_fail (GVC_IS_APPLET (object));
applet = GVC_APPLET (object);
g_return_if_fail (applet->priv != NULL);
G_OBJECT_CLASS (gvc_applet_parent_class)->finalize (object);
}
GvcApplet *
gvc_applet_new (void)
{
GObject *applet;
applet = g_object_new (GVC_TYPE_APPLET, NULL);
return GVC_APPLET (applet);
}
|
368 | ./cinnamon-control-center/panels/sound/gvc-stream-status-icon.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2008 William Jon McCann
*
* 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.
*
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <gdk/gdkkeysyms.h>
#include <gtk/gtk.h>
#include <pulse/pulseaudio.h>
#include "gvc-mixer-stream.h"
#include "gvc-channel-bar.h"
#include "gvc-stream-status-icon.h"
#define GVC_STREAM_STATUS_ICON_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GVC_TYPE_STREAM_STATUS_ICON, GvcStreamStatusIconPrivate))
struct GvcStreamStatusIconPrivate
{
char **icon_names;
GvcMixerStream *mixer_stream;
GtkWidget *dock;
GtkWidget *bar;
guint current_icon;
char *display_name;
gboolean thaw;
};
enum
{
PROP_0,
PROP_DISPLAY_NAME,
PROP_MIXER_STREAM,
PROP_ICON_NAMES,
};
static void gvc_stream_status_icon_class_init (GvcStreamStatusIconClass *klass);
static void gvc_stream_status_icon_init (GvcStreamStatusIcon *stream_status_icon);
static void gvc_stream_status_icon_finalize (GObject *object);
G_DEFINE_TYPE (GvcStreamStatusIcon, gvc_stream_status_icon, GTK_TYPE_STATUS_ICON)
static void
on_adjustment_value_changed (GtkAdjustment *adjustment,
GvcStreamStatusIcon *icon)
{
gdouble volume;
if (icon->priv->thaw)
return;
volume = gtk_adjustment_get_value (adjustment);
/* Only push the volume if it's actually changed */
if (gvc_mixer_stream_set_volume(icon->priv->mixer_stream,
(pa_volume_t) round (volume)) != FALSE) {
gvc_mixer_stream_push_volume(icon->priv->mixer_stream);
}
}
static void
update_dock (GvcStreamStatusIcon *icon)
{
GtkAdjustment *adj;
gboolean is_muted;
g_return_if_fail (icon);
adj = GTK_ADJUSTMENT (gvc_channel_bar_get_adjustment (GVC_CHANNEL_BAR (icon->priv->bar)));
icon->priv->thaw = TRUE;
gtk_adjustment_set_value (adj,
gvc_mixer_stream_get_volume (icon->priv->mixer_stream));
is_muted = gvc_mixer_stream_get_is_muted (icon->priv->mixer_stream);
gvc_channel_bar_set_is_muted (GVC_CHANNEL_BAR (icon->priv->bar), is_muted);
icon->priv->thaw = FALSE;
}
static gboolean
popup_dock (GvcStreamStatusIcon *icon,
guint time)
{
GdkRectangle area;
GtkOrientation orientation;
GdkDisplay *display;
GdkScreen *screen;
gboolean res;
int x;
int y;
int monitor_num;
GdkRectangle monitor;
GtkRequisition dock_req;
update_dock (icon);
screen = gtk_status_icon_get_screen (GTK_STATUS_ICON (icon));
res = gtk_status_icon_get_geometry (GTK_STATUS_ICON (icon),
&screen,
&area,
&orientation);
if (! res) {
g_warning ("Unable to determine geometry of status icon");
return FALSE;
}
/* position roughly */
gtk_window_set_screen (GTK_WINDOW (icon->priv->dock), screen);
gvc_channel_bar_set_orientation (GVC_CHANNEL_BAR (icon->priv->bar),
1 - orientation);
monitor_num = gdk_screen_get_monitor_at_point (screen, area.x, area.y);
gdk_screen_get_monitor_geometry (screen, monitor_num, &monitor);
gtk_container_foreach (GTK_CONTAINER (icon->priv->dock),
(GtkCallback) gtk_widget_show_all, NULL);
gtk_widget_get_preferred_size (icon->priv->dock, &dock_req, NULL);
if (orientation == GTK_ORIENTATION_VERTICAL) {
if (area.x + area.width + dock_req.width <= monitor.x + monitor.width) {
x = area.x + area.width;
} else {
x = area.x - dock_req.width;
}
if (area.y + dock_req.height <= monitor.y + monitor.height) {
y = area.y;
} else {
y = monitor.y + monitor.height - dock_req.height;
}
} else {
if (area.y + area.height + dock_req.height <= monitor.y + monitor.height) {
y = area.y + area.height;
} else {
y = area.y - dock_req.height;
}
if (area.x + dock_req.width <= monitor.x + monitor.width) {
x = area.x;
} else {
x = monitor.x + monitor.width - dock_req.width;
}
}
gtk_window_move (GTK_WINDOW (icon->priv->dock), x, y);
/* FIXME: without this, the popup window appears as a square
* after changing the orientation
*/
gtk_window_resize (GTK_WINDOW (icon->priv->dock), 1, 1);
gtk_widget_show_all (icon->priv->dock);
/* grab focus */
gtk_grab_add (icon->priv->dock);
if (gdk_pointer_grab (gtk_widget_get_window (icon->priv->dock), TRUE,
GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |
GDK_POINTER_MOTION_MASK | GDK_SCROLL_MASK, NULL, NULL,
time)
!= GDK_GRAB_SUCCESS) {
gtk_grab_remove (icon->priv->dock);
gtk_widget_hide (icon->priv->dock);
return FALSE;
}
if (gdk_keyboard_grab (gtk_widget_get_window (icon->priv->dock), TRUE, time) != GDK_GRAB_SUCCESS) {
display = gtk_widget_get_display (icon->priv->dock);
gdk_display_pointer_ungrab (display, time);
gtk_grab_remove (icon->priv->dock);
gtk_widget_hide (icon->priv->dock);
return FALSE;
}
gtk_widget_grab_focus (icon->priv->dock);
return TRUE;
}
static void
on_status_icon_activate (GtkStatusIcon *status_icon,
GvcStreamStatusIcon *icon)
{
popup_dock (icon, GDK_CURRENT_TIME);
}
static void
on_menu_mute_toggled (GtkMenuItem *item,
GvcStreamStatusIcon *icon)
{
gboolean is_muted;
is_muted = gtk_check_menu_item_get_active (GTK_CHECK_MENU_ITEM (item));
gvc_channel_bar_set_is_muted (GVC_CHANNEL_BAR (icon->priv->bar), is_muted);
}
static void
on_menu_activate_open_volume_control (GtkMenuItem *item,
GvcStreamStatusIcon *icon)
{
GAppInfo *app;
GdkAppLaunchContext *context;
GError *error;
error = NULL;
context = gdk_app_launch_context_new ();
app = g_app_info_create_from_commandline ("cinnamon-control-center cinnamon-sound", "Sound preferences", 0, &error);
if (app)
g_app_info_launch (app, NULL, G_APP_LAUNCH_CONTEXT (context), &error);
if (error != NULL) {
GtkWidget *dialog;
dialog = gtk_message_dialog_new (NULL,
0,
GTK_MESSAGE_ERROR,
GTK_BUTTONS_CLOSE,
_("Failed to start Sound Preferences: %s"),
error->message);
g_signal_connect (dialog,
"response",
G_CALLBACK (gtk_widget_destroy),
NULL);
gtk_widget_show (dialog);
g_error_free (error);
}
g_object_unref (context);
g_object_unref (app);
}
static void
on_status_icon_popup_menu (GtkStatusIcon *status_icon,
guint button,
guint activate_time,
GvcStreamStatusIcon *icon)
{
GtkWidget *menu;
GtkWidget *item;
GtkWidget *image;
menu = gtk_menu_new ();
item = gtk_check_menu_item_new_with_mnemonic (_("_Mute"));
gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (item),
gvc_mixer_stream_get_is_muted (icon->priv->mixer_stream));
g_signal_connect (item,
"toggled",
G_CALLBACK (on_menu_mute_toggled),
icon);
gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);
item = gtk_image_menu_item_new_with_mnemonic (_("_Sound Preferences"));
image = gtk_image_new_from_icon_name ("cin-multimedia-volume-control",
GTK_ICON_SIZE_MENU);
gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
g_signal_connect (item,
"activate",
G_CALLBACK (on_menu_activate_open_volume_control),
icon);
gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);
gtk_widget_show_all (menu);
gtk_menu_popup (GTK_MENU (menu),
NULL,
NULL,
gtk_status_icon_position_menu,
status_icon,
button,
activate_time);
}
static gboolean
on_status_icon_scroll_event (GtkStatusIcon *status_icon,
GdkEventScroll *event,
GvcStreamStatusIcon *icon)
{
return gvc_channel_bar_scroll (GVC_CHANNEL_BAR (icon->priv->bar), event);
}
static void
gvc_icon_release_grab (GvcStreamStatusIcon *icon,
GdkEventButton *event)
{
GdkDisplay *display;
/* ungrab focus */
display = gtk_widget_get_display (GTK_WIDGET (icon->priv->dock));
gdk_display_keyboard_ungrab (display, event->time);
gdk_display_pointer_ungrab (display, event->time);
gtk_grab_remove (icon->priv->dock);
/* hide again */
gtk_widget_hide (icon->priv->dock);
}
static gboolean
on_dock_button_press (GtkWidget *widget,
GdkEventButton *event,
GvcStreamStatusIcon *icon)
{
if (event->type == GDK_BUTTON_PRESS) {
gvc_icon_release_grab (icon, event);
return TRUE;
}
return FALSE;
}
static void
popdown_dock (GvcStreamStatusIcon *icon)
{
GdkDisplay *display;
/* ungrab focus */
display = gtk_widget_get_display (icon->priv->dock);
gdk_display_keyboard_ungrab (display, GDK_CURRENT_TIME);
gdk_display_pointer_ungrab (display, GDK_CURRENT_TIME);
gtk_grab_remove (icon->priv->dock);
/* hide again */
gtk_widget_hide (icon->priv->dock);
}
static gboolean
on_dock_key_release (GtkWidget *widget,
GdkEventKey *event,
GvcStreamStatusIcon *icon)
{
if (event->keyval == GDK_KEY_Escape) {
popdown_dock (icon);
return TRUE;
}
#if 0
if (!gtk_bindings_activate_event (GTK_OBJECT (widget), event)) {
/* The popup hasn't managed the event, pass onto the button */
gtk_bindings_activate_event (GTK_OBJECT (user_data), event);
}
#endif
return TRUE;
}
static gboolean
on_dock_scroll_event (GtkWidget *widget,
GdkEventScroll *event,
GvcStreamStatusIcon *icon)
{
/* Forward event to the status icon */
on_status_icon_scroll_event (NULL, event, icon);
return TRUE;
}
static void
update_icon (GvcStreamStatusIcon *icon)
{
guint volume;
gboolean is_muted;
guint n;
char *markup;
gboolean can_decibel;
gdouble db;
if (icon->priv->mixer_stream == NULL) {
return;
}
volume = gvc_mixer_stream_get_volume (icon->priv->mixer_stream);
is_muted = gvc_mixer_stream_get_is_muted (icon->priv->mixer_stream);
db = gvc_mixer_stream_get_decibel (icon->priv->mixer_stream);
can_decibel = gvc_mixer_stream_get_can_decibel (icon->priv->mixer_stream);
/* select image */
if (volume == 0 || is_muted) {
n = 0;
} else {
n = 3 * volume / PA_VOLUME_NORM + 1;
if (n < 1) {
n = 1;
} else if (n > 3) {
n = 3;
}
}
/* apparently status icon will reset icon even if
* if doesn't change */
if (icon->priv->current_icon != n) {
gtk_status_icon_set_from_icon_name (GTK_STATUS_ICON (icon),
icon->priv->icon_names [n]);
icon->priv->current_icon = n;
}
if (is_muted) {
markup = g_strdup_printf (
"<b>%s: %s</b>\n<small>%s</small>",
icon->priv->display_name,
_("Muted"),
gvc_mixer_stream_get_description (icon->priv->mixer_stream));
} else if (can_decibel && (db > PA_DECIBEL_MININFTY)) {
markup = g_strdup_printf (
"<b>%s: %.0f%%</b>\n<small>%0.2f dB\n%s</small>",
icon->priv->display_name,
100 * (float)volume / PA_VOLUME_NORM,
db,
gvc_mixer_stream_get_description (icon->priv->mixer_stream));
} else if (can_decibel) {
markup = g_strdup_printf (
"<b>%s: %.0f%%</b>\n<small>-∞ dB\n%s</small>",
icon->priv->display_name,
100 * (float)volume / PA_VOLUME_NORM,
gvc_mixer_stream_get_description (icon->priv->mixer_stream));
} else {
markup = g_strdup_printf (
"<b>%s: %.0f%%</b>\n<small>%s</small>",
icon->priv->display_name,
100 * (float)volume / PA_VOLUME_NORM,
gvc_mixer_stream_get_description (icon->priv->mixer_stream));
}
gtk_status_icon_set_tooltip_markup (GTK_STATUS_ICON (icon), markup);
g_free (markup);
}
void
gvc_stream_status_icon_set_icon_names (GvcStreamStatusIcon *icon,
const char **names)
{
g_return_if_fail (GVC_IS_STREAM_STATUS_ICON (icon));
g_strfreev (icon->priv->icon_names);
icon->priv->icon_names = g_strdupv ((char **)names);
update_icon (icon);
g_object_notify (G_OBJECT (icon), "icon-names");
}
static void
on_stream_volume_notify (GObject *object,
GParamSpec *pspec,
GvcStreamStatusIcon *icon)
{
update_icon (icon);
update_dock (icon);
}
static void
on_stream_is_muted_notify (GObject *object,
GParamSpec *pspec,
GvcStreamStatusIcon *icon)
{
update_icon (icon);
update_dock (icon);
}
void
gvc_stream_status_icon_set_display_name (GvcStreamStatusIcon *icon,
const char *name)
{
g_return_if_fail (GVC_STREAM_STATUS_ICON (icon));
g_free (icon->priv->display_name);
icon->priv->display_name = g_strdup (name);
update_icon (icon);
g_object_notify (G_OBJECT (icon), "display-name");
}
void
gvc_stream_status_icon_set_mixer_stream (GvcStreamStatusIcon *icon,
GvcMixerStream *stream)
{
g_return_if_fail (GVC_STREAM_STATUS_ICON (icon));
if (stream != NULL) {
g_object_ref (stream);
}
if (icon->priv->mixer_stream != NULL) {
g_signal_handlers_disconnect_by_func (icon->priv->mixer_stream,
G_CALLBACK (on_stream_volume_notify),
icon);
g_signal_handlers_disconnect_by_func (icon->priv->mixer_stream,
G_CALLBACK (on_stream_is_muted_notify),
icon);
g_object_unref (icon->priv->mixer_stream);
icon->priv->mixer_stream = NULL;
}
icon->priv->mixer_stream = stream;
if (icon->priv->mixer_stream != NULL) {
GtkAdjustment *adj;
g_object_ref (icon->priv->mixer_stream);
icon->priv->thaw = TRUE;
adj = GTK_ADJUSTMENT (gvc_channel_bar_get_adjustment (GVC_CHANNEL_BAR (icon->priv->bar)));
gtk_adjustment_set_value (adj,
gvc_mixer_stream_get_volume (icon->priv->mixer_stream));
icon->priv->thaw = FALSE;
g_signal_connect (icon->priv->mixer_stream,
"notify::volume",
G_CALLBACK (on_stream_volume_notify),
icon);
g_signal_connect (icon->priv->mixer_stream,
"notify::is-muted",
G_CALLBACK (on_stream_is_muted_notify),
icon);
}
update_icon (icon);
g_object_notify (G_OBJECT (icon), "mixer-stream");
}
static void
gvc_stream_status_icon_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GvcStreamStatusIcon *self = GVC_STREAM_STATUS_ICON (object);
switch (prop_id) {
case PROP_MIXER_STREAM:
gvc_stream_status_icon_set_mixer_stream (self, g_value_get_object (value));
break;
case PROP_DISPLAY_NAME:
gvc_stream_status_icon_set_display_name (self, g_value_get_string (value));
break;
case PROP_ICON_NAMES:
gvc_stream_status_icon_set_icon_names (self, g_value_get_boxed (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gvc_stream_status_icon_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GvcStreamStatusIcon *self = GVC_STREAM_STATUS_ICON (object);
GvcStreamStatusIconPrivate *priv = self->priv;
switch (prop_id) {
case PROP_MIXER_STREAM:
g_value_set_object (value, priv->mixer_stream);
break;
case PROP_DISPLAY_NAME:
g_value_set_string (value, priv->display_name);
break;
case PROP_ICON_NAMES:
g_value_set_boxed (value, priv->icon_names);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
on_bar_is_muted_notify (GObject *object,
GParamSpec *pspec,
GvcStreamStatusIcon *icon)
{
gboolean is_muted;
is_muted = gvc_channel_bar_get_is_muted (GVC_CHANNEL_BAR (object));
if (gvc_mixer_stream_get_is_muted (icon->priv->mixer_stream) != is_muted) {
/* Update the stream before pushing the change */
gvc_mixer_stream_set_is_muted (icon->priv->mixer_stream, is_muted);
gvc_mixer_stream_change_is_muted (icon->priv->mixer_stream,
is_muted);
}
}
static GObject *
gvc_stream_status_icon_constructor (GType type,
guint n_construct_properties,
GObjectConstructParam *construct_params)
{
GObject *object;
GvcStreamStatusIcon *icon;
GtkWidget *frame;
GtkWidget *box;
GtkAdjustment *adj;
object = G_OBJECT_CLASS (gvc_stream_status_icon_parent_class)->constructor (type, n_construct_properties, construct_params);
icon = GVC_STREAM_STATUS_ICON (object);
gtk_status_icon_set_from_icon_name (GTK_STATUS_ICON (icon),
icon->priv->icon_names[0]);
/* window */
icon->priv->dock = gtk_window_new (GTK_WINDOW_POPUP);
gtk_widget_set_name (icon->priv->dock, "gvc-stream-status-icon-popup-window");
g_signal_connect (icon->priv->dock,
"button-press-event",
G_CALLBACK (on_dock_button_press),
icon);
g_signal_connect (icon->priv->dock,
"key-release-event",
G_CALLBACK (on_dock_key_release),
icon);
g_signal_connect (icon->priv->dock,
"scroll-event",
G_CALLBACK (on_dock_scroll_event),
icon);
gtk_window_set_decorated (GTK_WINDOW (icon->priv->dock), FALSE);
frame = gtk_frame_new (NULL);
gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_OUT);
gtk_container_add (GTK_CONTAINER (icon->priv->dock), frame);
box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 6);
gtk_container_set_border_width (GTK_CONTAINER (box), 2);
gtk_container_add (GTK_CONTAINER (frame), box);
icon->priv->bar = gvc_channel_bar_new ();
gvc_channel_bar_set_orientation (GVC_CHANNEL_BAR (icon->priv->bar),
GTK_ORIENTATION_VERTICAL);
gtk_box_pack_start (GTK_BOX (box), icon->priv->bar, TRUE, FALSE, 0);
g_signal_connect (icon->priv->bar,
"notify::is-muted",
G_CALLBACK (on_bar_is_muted_notify),
icon);
adj = GTK_ADJUSTMENT (gvc_channel_bar_get_adjustment (GVC_CHANNEL_BAR (icon->priv->bar)));
g_signal_connect (adj,
"value-changed",
G_CALLBACK (on_adjustment_value_changed),
icon);
return object;
}
static void
gvc_stream_status_icon_dispose (GObject *object)
{
GvcStreamStatusIcon *icon = GVC_STREAM_STATUS_ICON (object);
if (icon->priv->dock != NULL) {
gtk_widget_destroy (icon->priv->dock);
icon->priv->dock = NULL;
}
if (icon->priv->mixer_stream != NULL) {
g_object_unref (icon->priv->mixer_stream);
icon->priv->mixer_stream = NULL;
}
G_OBJECT_CLASS (gvc_stream_status_icon_parent_class)->dispose (object);
}
static void
gvc_stream_status_icon_class_init (GvcStreamStatusIconClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->constructor = gvc_stream_status_icon_constructor;
object_class->finalize = gvc_stream_status_icon_finalize;
object_class->dispose = gvc_stream_status_icon_dispose;
object_class->set_property = gvc_stream_status_icon_set_property;
object_class->get_property = gvc_stream_status_icon_get_property;
g_object_class_install_property (object_class,
PROP_MIXER_STREAM,
g_param_spec_object ("mixer-stream",
"mixer stream",
"mixer stream",
GVC_TYPE_MIXER_STREAM,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (object_class,
PROP_DISPLAY_NAME,
g_param_spec_string ("display-name",
"Display Name",
"Name to display for this stream",
NULL,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (object_class,
PROP_ICON_NAMES,
g_param_spec_boxed ("icon-names",
"Icon Names",
"Name of icon to display for this stream",
G_TYPE_STRV,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_type_class_add_private (klass, sizeof (GvcStreamStatusIconPrivate));
}
static void
on_status_icon_visible_notify (GvcStreamStatusIcon *icon)
{
gboolean visible;
g_object_get (icon, "visible", &visible, NULL);
if (! visible) {
if (icon->priv->dock != NULL) {
gtk_widget_hide (icon->priv->dock);
}
}
}
static void
gvc_stream_status_icon_init (GvcStreamStatusIcon *icon)
{
icon->priv = GVC_STREAM_STATUS_ICON_GET_PRIVATE (icon);
g_signal_connect (icon,
"activate",
G_CALLBACK (on_status_icon_activate),
icon);
g_signal_connect (icon,
"popup-menu",
G_CALLBACK (on_status_icon_popup_menu),
icon);
g_signal_connect (icon,
"scroll-event",
G_CALLBACK (on_status_icon_scroll_event),
icon);
g_signal_connect (icon,
"notify::visible",
G_CALLBACK (on_status_icon_visible_notify),
NULL);
icon->priv->thaw = FALSE;
}
static void
gvc_stream_status_icon_finalize (GObject *object)
{
GvcStreamStatusIcon *stream_status_icon;
g_return_if_fail (object != NULL);
g_return_if_fail (GVC_IS_STREAM_STATUS_ICON (object));
stream_status_icon = GVC_STREAM_STATUS_ICON (object);
g_return_if_fail (stream_status_icon->priv != NULL);
g_strfreev (stream_status_icon->priv->icon_names);
G_OBJECT_CLASS (gvc_stream_status_icon_parent_class)->finalize (object);
}
GvcStreamStatusIcon *
gvc_stream_status_icon_new (GvcMixerStream *stream,
const char **icon_names)
{
GObject *icon;
icon = g_object_new (GVC_TYPE_STREAM_STATUS_ICON,
"mixer-stream", stream,
"icon-names", icon_names,
NULL);
return GVC_STREAM_STATUS_ICON (icon);
}
|
369 | ./cinnamon-control-center/panels/sound/gvc-level-bar.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2008 William Jon McCann <[email protected]>
*
* 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.
*
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <gtk/gtk.h>
#include "gvc-level-bar.h"
#define NUM_BOXES 24
#define GVC_LEVEL_BAR_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GVC_TYPE_LEVEL_BAR, GvcLevelBarPrivate))
#define MIN_HORIZONTAL_BAR_WIDTH 150
#define HORIZONTAL_BAR_HEIGHT 20
#define VERTICAL_BAR_WIDTH 20
#define MIN_VERTICAL_BAR_HEIGHT 400
typedef struct {
int peak_num;
int max_peak_num;
GdkRectangle area;
int delta;
int box_width;
int box_height;
int box_radius;
double bg_r;
double bg_g;
double bg_b;
double bdr_r;
double bdr_g;
double bdr_b;
double fl_r;
double fl_g;
double fl_b;
} LevelBarLayout;
struct GvcLevelBarPrivate
{
GtkOrientation orientation;
GtkAdjustment *peak_adjustment;
GtkAdjustment *rms_adjustment;
GvcLevelScale scale;
gdouble peak_fraction;
gdouble rms_fraction;
gdouble max_peak;
guint max_peak_id;
LevelBarLayout layout;
};
enum
{
PROP_0,
PROP_PEAK_ADJUSTMENT,
PROP_RMS_ADJUSTMENT,
PROP_SCALE,
PROP_ORIENTATION,
};
static void gvc_level_bar_class_init (GvcLevelBarClass *klass);
static void gvc_level_bar_init (GvcLevelBar *level_bar);
static void gvc_level_bar_finalize (GObject *object);
G_DEFINE_TYPE (GvcLevelBar, gvc_level_bar, GTK_TYPE_WIDGET)
#define check_rectangle(rectangle1, rectangle2) \
{ \
/* .x and .y are always 0 */ \
if (rectangle1.width != rectangle2.width) return TRUE; \
if (rectangle1.height != rectangle2.height) return TRUE; \
}
static gboolean
layout_changed (LevelBarLayout *layout1,
LevelBarLayout *layout2)
{
check_rectangle (layout1->area, layout2->area);
if (layout1->delta != layout2->delta) return TRUE;
if (layout1->peak_num != layout2->peak_num) return TRUE;
if (layout1->max_peak_num != layout2->max_peak_num) return TRUE;
if (layout1->bg_r != layout2->bg_r
|| layout1->bg_g != layout2->bg_g
|| layout1->bg_b != layout2->bg_b)
return TRUE;
if (layout1->bdr_r != layout2->bdr_r
|| layout1->bdr_g != layout2->bdr_g
|| layout1->bdr_b != layout2->bdr_b)
return TRUE;
if (layout1->fl_r != layout2->fl_r
|| layout1->fl_g != layout2->fl_g
|| layout1->fl_b != layout2->fl_b)
return TRUE;
return FALSE;
}
static gdouble
fraction_from_adjustment (GvcLevelBar *bar,
GtkAdjustment *adjustment)
{
gdouble level;
gdouble fraction;
gdouble min;
gdouble max;
level = gtk_adjustment_get_value (adjustment);
min = gtk_adjustment_get_lower (adjustment);
max = gtk_adjustment_get_upper (adjustment);
switch (bar->priv->scale) {
case GVC_LEVEL_SCALE_LINEAR:
fraction = (level - min) / (max - min);
break;
case GVC_LEVEL_SCALE_LOG:
fraction = log10 ((level - min + 1) / (max - min + 1));
break;
default:
g_assert_not_reached ();
}
return fraction;
}
static gboolean
reset_max_peak (GvcLevelBar *bar)
{
gdouble min;
min = gtk_adjustment_get_lower (bar->priv->peak_adjustment);
bar->priv->max_peak = min;
bar->priv->layout.max_peak_num = 0;
gtk_widget_queue_draw (GTK_WIDGET (bar));
bar->priv->max_peak_id = 0;
return FALSE;
}
static void
bar_calc_layout (GvcLevelBar *bar)
{
GdkColor color;
int peak_level;
int max_peak_level;
GtkAllocation allocation;
GtkStyle *style;
gtk_widget_get_allocation (GTK_WIDGET (bar), &allocation);
bar->priv->layout.area.width = allocation.width - 2;
bar->priv->layout.area.height = allocation.height - 2;
style = gtk_widget_get_style (GTK_WIDGET (bar));
color = style->bg [GTK_STATE_NORMAL];
bar->priv->layout.bg_r = 1.0;
bar->priv->layout.bg_g = 1.0;
bar->priv->layout.bg_b = 1.0;
color = style->dark [GTK_STATE_NORMAL];
bar->priv->layout.bdr_r = (float)color.red / 65535.0;
bar->priv->layout.bdr_g = (float)color.green / 65535.0;
bar->priv->layout.bdr_b = (float)color.blue / 65535.0;
color = style->bg [GTK_STATE_SELECTED];
bar->priv->layout.fl_r = (float)color.red / 65535.0;
bar->priv->layout.fl_g = (float)color.green / 65535.0;
bar->priv->layout.fl_b = (float)color.blue / 65535.0;
if (bar->priv->orientation == GTK_ORIENTATION_VERTICAL) {
peak_level = bar->priv->peak_fraction * bar->priv->layout.area.height;
max_peak_level = bar->priv->max_peak * bar->priv->layout.area.height;
bar->priv->layout.delta = bar->priv->layout.area.height / NUM_BOXES;
bar->priv->layout.area.x = 0;
bar->priv->layout.area.y = 0;
bar->priv->layout.box_height = bar->priv->layout.delta / 1.05;
bar->priv->layout.box_width = bar->priv->layout.area.width;
bar->priv->layout.box_radius = bar->priv->layout.box_width / 2;
} else {
peak_level = bar->priv->peak_fraction * bar->priv->layout.area.width;
max_peak_level = bar->priv->max_peak * bar->priv->layout.area.width;
bar->priv->layout.delta = bar->priv->layout.area.width / NUM_BOXES;
bar->priv->layout.area.x = 0;
bar->priv->layout.area.y = 0;
bar->priv->layout.box_width = bar->priv->layout.delta / 1.05;
bar->priv->layout.box_height = bar->priv->layout.area.height;
bar->priv->layout.box_radius = bar->priv->layout.box_height / 2;
}
/* This can happen if the level bar isn't realized */
if (bar->priv->layout.delta == 0)
return;
bar->priv->layout.peak_num = peak_level / bar->priv->layout.delta;
bar->priv->layout.max_peak_num = max_peak_level / bar->priv->layout.delta;
}
static void
update_peak_value (GvcLevelBar *bar)
{
gdouble val;
LevelBarLayout layout;
layout = bar->priv->layout;
val = fraction_from_adjustment (bar, bar->priv->peak_adjustment);
bar->priv->peak_fraction = val;
if (val > bar->priv->max_peak) {
if (bar->priv->max_peak_id > 0) {
g_source_remove (bar->priv->max_peak_id);
}
bar->priv->max_peak_id = g_timeout_add_seconds (1, (GSourceFunc)reset_max_peak, bar);
bar->priv->max_peak = val;
}
bar_calc_layout (bar);
if (layout_changed (&bar->priv->layout, &layout)) {
gtk_widget_queue_draw (GTK_WIDGET (bar));
}
}
static void
update_rms_value (GvcLevelBar *bar)
{
gdouble val;
val = fraction_from_adjustment (bar, bar->priv->rms_adjustment);
bar->priv->rms_fraction = val;
}
GtkOrientation
gvc_level_bar_get_orientation (GvcLevelBar *bar)
{
g_return_val_if_fail (GVC_IS_LEVEL_BAR (bar), 0);
return bar->priv->orientation;
}
void
gvc_level_bar_set_orientation (GvcLevelBar *bar,
GtkOrientation orientation)
{
g_return_if_fail (GVC_IS_LEVEL_BAR (bar));
if (orientation != bar->priv->orientation) {
bar->priv->orientation = orientation;
gtk_widget_queue_draw (GTK_WIDGET (bar));
g_object_notify (G_OBJECT (bar), "orientation");
}
}
static void
on_peak_adjustment_value_changed (GtkAdjustment *adjustment,
GvcLevelBar *bar)
{
update_peak_value (bar);
}
static void
on_rms_adjustment_value_changed (GtkAdjustment *adjustment,
GvcLevelBar *bar)
{
update_rms_value (bar);
}
void
gvc_level_bar_set_peak_adjustment (GvcLevelBar *bar,
GtkAdjustment *adjustment)
{
g_return_if_fail (GVC_LEVEL_BAR (bar));
g_return_if_fail (GTK_IS_ADJUSTMENT (adjustment));
if (bar->priv->peak_adjustment != NULL) {
g_signal_handlers_disconnect_by_func (bar->priv->peak_adjustment,
G_CALLBACK (on_peak_adjustment_value_changed),
bar);
g_object_unref (bar->priv->peak_adjustment);
}
bar->priv->peak_adjustment = g_object_ref_sink (adjustment);
g_signal_connect (bar->priv->peak_adjustment,
"value-changed",
G_CALLBACK (on_peak_adjustment_value_changed),
bar);
update_peak_value (bar);
g_object_notify (G_OBJECT (bar), "peak-adjustment");
}
void
gvc_level_bar_set_rms_adjustment (GvcLevelBar *bar,
GtkAdjustment *adjustment)
{
g_return_if_fail (GVC_LEVEL_BAR (bar));
g_return_if_fail (GTK_IS_ADJUSTMENT (adjustment));
if (bar->priv->rms_adjustment != NULL) {
g_signal_handlers_disconnect_by_func (bar->priv->peak_adjustment,
G_CALLBACK (on_rms_adjustment_value_changed),
bar);
g_object_unref (bar->priv->rms_adjustment);
}
bar->priv->rms_adjustment = g_object_ref_sink (adjustment);
g_signal_connect (bar->priv->peak_adjustment,
"value-changed",
G_CALLBACK (on_peak_adjustment_value_changed),
bar);
update_rms_value (bar);
g_object_notify (G_OBJECT (bar), "rms-adjustment");
}
GtkAdjustment *
gvc_level_bar_get_peak_adjustment (GvcLevelBar *bar)
{
g_return_val_if_fail (GVC_IS_LEVEL_BAR (bar), NULL);
return bar->priv->peak_adjustment;
}
GtkAdjustment *
gvc_level_bar_get_rms_adjustment (GvcLevelBar *bar)
{
g_return_val_if_fail (GVC_IS_LEVEL_BAR (bar), NULL);
return bar->priv->rms_adjustment;
}
void
gvc_level_bar_set_scale (GvcLevelBar *bar,
GvcLevelScale scale)
{
g_return_if_fail (GVC_IS_LEVEL_BAR (bar));
if (scale != bar->priv->scale) {
bar->priv->scale = scale;
update_peak_value (bar);
update_rms_value (bar);
g_object_notify (G_OBJECT (bar), "scale");
}
}
static void
gvc_level_bar_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GvcLevelBar *self = GVC_LEVEL_BAR (object);
switch (prop_id) {
case PROP_SCALE:
gvc_level_bar_set_scale (self, g_value_get_int (value));
break;
case PROP_ORIENTATION:
gvc_level_bar_set_orientation (self, g_value_get_enum (value));
break;
case PROP_PEAK_ADJUSTMENT:
gvc_level_bar_set_peak_adjustment (self, g_value_get_object (value));
break;
case PROP_RMS_ADJUSTMENT:
gvc_level_bar_set_rms_adjustment (self, g_value_get_object (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gvc_level_bar_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GvcLevelBar *self = GVC_LEVEL_BAR (object);
switch (prop_id) {
case PROP_SCALE:
g_value_set_int (value, self->priv->scale);
break;
case PROP_ORIENTATION:
g_value_set_enum (value, self->priv->orientation);
break;
case PROP_PEAK_ADJUSTMENT:
g_value_set_object (value, self->priv->peak_adjustment);
break;
case PROP_RMS_ADJUSTMENT:
g_value_set_object (value, self->priv->rms_adjustment);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static GObject *
gvc_level_bar_constructor (GType type,
guint n_construct_properties,
GObjectConstructParam *construct_params)
{
return G_OBJECT_CLASS (gvc_level_bar_parent_class)->constructor (type, n_construct_properties, construct_params);
}
static void
gvc_level_bar_size_request (GtkWidget *widget,
GtkRequisition *requisition)
{
GvcLevelBar *bar = GVC_LEVEL_BAR (widget);
switch (bar->priv->orientation) {
case GTK_ORIENTATION_VERTICAL:
requisition->width = VERTICAL_BAR_WIDTH;
requisition->height = MIN_VERTICAL_BAR_HEIGHT;
break;
case GTK_ORIENTATION_HORIZONTAL:
requisition->width = MIN_HORIZONTAL_BAR_WIDTH;
requisition->height = HORIZONTAL_BAR_HEIGHT;
break;
default:
g_assert_not_reached ();
break;
}
}
static void
gvc_level_bar_get_preferred_width (GtkWidget *widget,
gint *minimum,
gint *natural)
{
GtkRequisition requisition;
gvc_level_bar_size_request (widget, &requisition);
if (minimum != NULL) {
*minimum = requisition.width;
}
if (natural != NULL) {
*natural = requisition.width;
}
}
static void
gvc_level_bar_get_preferred_height (GtkWidget *widget,
gint *minimum,
gint *natural)
{
GtkRequisition requisition;
gvc_level_bar_size_request (widget, &requisition);
if (minimum != NULL) {
*minimum = requisition.height;
}
if (natural != NULL) {
*natural = requisition.height;
}
}
static void
gvc_level_bar_size_allocate (GtkWidget *widget,
GtkAllocation *allocation)
{
GvcLevelBar *bar;
g_return_if_fail (GVC_IS_LEVEL_BAR (widget));
g_return_if_fail (allocation != NULL);
bar = GVC_LEVEL_BAR (widget);
/* FIXME: add height property, labels, etc */
GTK_WIDGET_CLASS (gvc_level_bar_parent_class)->size_allocate (widget, allocation);
gtk_widget_set_allocation (widget, allocation);
gtk_widget_get_allocation (widget, allocation);
if (bar->priv->orientation == GTK_ORIENTATION_VERTICAL) {
allocation->height = MIN (allocation->height, MIN_VERTICAL_BAR_HEIGHT);
allocation->width = MAX (allocation->width, VERTICAL_BAR_WIDTH);
} else {
allocation->width = MIN (allocation->width, MIN_HORIZONTAL_BAR_WIDTH);
allocation->height = MAX (allocation->height, HORIZONTAL_BAR_HEIGHT);
}
bar_calc_layout (bar);
}
static void
curved_rectangle (cairo_t *cr,
double _x0,
double _y0,
double width,
double height,
double radius)
{
double x1;
double _y1;
x1 = _x0 + width;
_y1 = _y0 + height;
if (!width || !height) {
return;
}
if (width / 2 < radius) {
if (height / 2 < radius) {
cairo_move_to (cr, _x0, (_y0 + _y1) / 2);
cairo_curve_to (cr, _x0 ,_y0, _x0, _y0, (_x0 + x1) / 2, _y0);
cairo_curve_to (cr, x1, _y0, x1, _y0, x1, (_y0 + _y1) / 2);
cairo_curve_to (cr, x1, _y1, x1, _y1, (x1 + _x0) / 2, _y1);
cairo_curve_to (cr, _x0, _y1, _x0, _y1, _x0, (_y0 + _y1) / 2);
} else {
cairo_move_to (cr, _x0, _y0 + radius);
cairo_curve_to (cr, _x0, _y0, _x0, _y0, (_x0 + x1) / 2, _y0);
cairo_curve_to (cr, x1, _y0, x1, _y0, x1, _y0 + radius);
cairo_line_to (cr, x1, _y1 - radius);
cairo_curve_to (cr, x1, _y1, x1, _y1, (x1 + _x0) / 2, _y1);
cairo_curve_to (cr, _x0, _y1, _x0, _y1, _x0, _y1 - radius);
}
} else {
if (height / 2 < radius) {
cairo_move_to (cr, _x0, (_y0 + _y1) / 2);
cairo_curve_to (cr, _x0, _y0, _x0 , _y0, _x0 + radius, _y0);
cairo_line_to (cr, x1 - radius, _y0);
cairo_curve_to (cr, x1, _y0, x1, _y0, x1, (_y0 + _y1) / 2);
cairo_curve_to (cr, x1, _y1, x1, _y1, x1 - radius, _y1);
cairo_line_to (cr, _x0 + radius, _y1);
cairo_curve_to (cr, _x0, _y1, _x0, _y1, _x0, (_y0 + _y1) / 2);
} else {
cairo_move_to (cr, _x0, _y0 + radius);
cairo_curve_to (cr, _x0 , _y0, _x0 , _y0, _x0 + radius, _y0);
cairo_line_to (cr, x1 - radius, _y0);
cairo_curve_to (cr, x1, _y0, x1, _y0, x1, _y0 + radius);
cairo_line_to (cr, x1, _y1 - radius);
cairo_curve_to (cr, x1, _y1, x1, _y1, x1 - radius, _y1);
cairo_line_to (cr, _x0 + radius, _y1);
cairo_curve_to (cr, _x0, _y1, _x0, _y1, _x0, _y1 - radius);
}
}
cairo_close_path (cr);
}
static int
gvc_level_bar_draw (GtkWidget *widget,
cairo_t *cr)
{
GvcLevelBar *bar;
g_return_val_if_fail (GVC_IS_LEVEL_BAR (widget), FALSE);
bar = GVC_LEVEL_BAR (widget);
cairo_save (cr);
if (bar->priv->orientation == GTK_ORIENTATION_VERTICAL) {
int i;
int by;
for (i = 0; i < NUM_BOXES; i++) {
by = i * bar->priv->layout.delta;
curved_rectangle (cr,
bar->priv->layout.area.x + 0.5,
by + 0.5,
bar->priv->layout.box_width - 1,
bar->priv->layout.box_height - 1,
bar->priv->layout.box_radius);
if ((bar->priv->layout.max_peak_num - 1) == i) {
/* fill peak foreground */
cairo_set_source_rgb (cr, bar->priv->layout.fl_r, bar->priv->layout.fl_g, bar->priv->layout.fl_b);
cairo_fill_preserve (cr);
} else if ((bar->priv->layout.peak_num - 1) >= i) {
/* fill background */
cairo_set_source_rgb (cr, bar->priv->layout.bg_r, bar->priv->layout.bg_g, bar->priv->layout.bg_b);
cairo_fill_preserve (cr);
/* fill foreground */
cairo_set_source_rgba (cr, bar->priv->layout.fl_r, bar->priv->layout.fl_g, bar->priv->layout.fl_b, 0.7);
cairo_fill_preserve (cr);
} else {
/* fill background */
cairo_set_source_rgb (cr, bar->priv->layout.bg_r, bar->priv->layout.bg_g, bar->priv->layout.bg_b);
cairo_fill_preserve (cr);
}
/* stroke border */
cairo_set_source_rgb (cr, bar->priv->layout.bdr_r, bar->priv->layout.bdr_g, bar->priv->layout.bdr_b);
cairo_set_line_width (cr, 1);
cairo_stroke (cr);
}
} else {
int i;
int bx;
if (gtk_widget_get_direction (widget) == GTK_TEXT_DIR_RTL) {
cairo_scale (cr, -1, 1);
cairo_translate (cr, -gtk_widget_get_allocated_width (widget), 0);
}
for (i = 0; i < NUM_BOXES; i++) {
bx = i * bar->priv->layout.delta;
curved_rectangle (cr,
bx + 0.5,
bar->priv->layout.area.y + 0.5,
bar->priv->layout.box_width - 1,
bar->priv->layout.box_height - 1,
bar->priv->layout.box_radius);
if ((bar->priv->layout.max_peak_num - 1) == i) {
/* fill peak foreground */
cairo_set_source_rgb (cr, bar->priv->layout.fl_r, bar->priv->layout.fl_g, bar->priv->layout.fl_b);
cairo_fill_preserve (cr);
} else if ((bar->priv->layout.peak_num - 1) >= i) {
/* fill background */
cairo_set_source_rgb (cr, bar->priv->layout.bg_r, bar->priv->layout.bg_g, bar->priv->layout.bg_b);
cairo_fill_preserve (cr);
/* fill foreground */
cairo_set_source_rgba (cr, bar->priv->layout.fl_r, bar->priv->layout.fl_g, bar->priv->layout.fl_b, 0.7);
cairo_fill_preserve (cr);
} else {
/* fill background */
cairo_set_source_rgb (cr, bar->priv->layout.bg_r, bar->priv->layout.bg_g, bar->priv->layout.bg_b);
cairo_fill_preserve (cr);
}
/* stroke border */
cairo_set_source_rgb (cr, bar->priv->layout.bdr_r, bar->priv->layout.bdr_g, bar->priv->layout.bdr_b);
cairo_set_line_width (cr, 1);
cairo_stroke (cr);
}
}
cairo_restore (cr);
return FALSE;
}
static void
gvc_level_bar_class_init (GvcLevelBarClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);
object_class->constructor = gvc_level_bar_constructor;
object_class->finalize = gvc_level_bar_finalize;
object_class->set_property = gvc_level_bar_set_property;
object_class->get_property = gvc_level_bar_get_property;
widget_class->draw = gvc_level_bar_draw;
widget_class->get_preferred_width = gvc_level_bar_get_preferred_width;
widget_class->get_preferred_height = gvc_level_bar_get_preferred_height;
widget_class->size_allocate = gvc_level_bar_size_allocate;
g_object_class_install_property (object_class,
PROP_ORIENTATION,
g_param_spec_enum ("orientation",
"Orientation",
"The orientation of the bar",
GTK_TYPE_ORIENTATION,
GTK_ORIENTATION_HORIZONTAL,
G_PARAM_READWRITE));
g_object_class_install_property (object_class,
PROP_PEAK_ADJUSTMENT,
g_param_spec_object ("peak-adjustment",
"Peak Adjustment",
"The GtkAdjustment that contains the current peak value",
GTK_TYPE_ADJUSTMENT,
G_PARAM_READWRITE));
g_object_class_install_property (object_class,
PROP_RMS_ADJUSTMENT,
g_param_spec_object ("rms-adjustment",
"RMS Adjustment",
"The GtkAdjustment that contains the current rms value",
GTK_TYPE_ADJUSTMENT,
G_PARAM_READWRITE));
g_object_class_install_property (object_class,
PROP_SCALE,
g_param_spec_int ("scale",
"Scale",
"Scale",
0,
G_MAXINT,
GVC_LEVEL_SCALE_LINEAR,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_type_class_add_private (klass, sizeof (GvcLevelBarPrivate));
}
static void
gvc_level_bar_init (GvcLevelBar *bar)
{
bar->priv = GVC_LEVEL_BAR_GET_PRIVATE (bar);
bar->priv->peak_adjustment = GTK_ADJUSTMENT (gtk_adjustment_new (0.0,
0.0,
1.0,
0.05,
0.1,
0.1));
g_object_ref_sink (bar->priv->peak_adjustment);
g_signal_connect (bar->priv->peak_adjustment,
"value-changed",
G_CALLBACK (on_peak_adjustment_value_changed),
bar);
bar->priv->rms_adjustment = GTK_ADJUSTMENT (gtk_adjustment_new (0.0,
0.0,
1.0,
0.05,
0.1,
0.1));
g_object_ref_sink (bar->priv->rms_adjustment);
g_signal_connect (bar->priv->rms_adjustment,
"value-changed",
G_CALLBACK (on_rms_adjustment_value_changed),
bar);
gtk_widget_set_has_window (GTK_WIDGET (bar), FALSE);
}
static void
gvc_level_bar_finalize (GObject *object)
{
GvcLevelBar *bar;
g_return_if_fail (object != NULL);
g_return_if_fail (GVC_IS_LEVEL_BAR (object));
bar = GVC_LEVEL_BAR (object);
if (bar->priv->max_peak_id > 0) {
g_source_remove (bar->priv->max_peak_id);
}
g_return_if_fail (bar->priv != NULL);
G_OBJECT_CLASS (gvc_level_bar_parent_class)->finalize (object);
}
GtkWidget *
gvc_level_bar_new (void)
{
GObject *bar;
bar = g_object_new (GVC_TYPE_LEVEL_BAR,
NULL);
return GTK_WIDGET (bar);
}
|
370 | ./cinnamon-control-center/panels/sound/gvc-sound-theme-chooser.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2008 Bastien Nocera <[email protected]>
* Copyright (C) 2008 William Jon McCann
*
* 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.
*
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <utime.h>
#include <errno.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <gtk/gtk.h>
#include <canberra-gtk.h>
#include <libxml/tree.h>
#include <gsettings-desktop-schemas/gdesktop-enums.h>
#include "gvc-sound-theme-chooser.h"
#include "sound-theme-file-utils.h"
#define GVC_SOUND_THEME_CHOOSER_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GVC_TYPE_SOUND_THEME_CHOOSER, GvcSoundThemeChooserPrivate))
struct GvcSoundThemeChooserPrivate
{
GtkWidget *treeview;
GtkWidget *selection_box;
GSettings *settings;
GSettings *sound_settings;
char *current_theme;
char *current_parent;
};
static void gvc_sound_theme_chooser_class_init (GvcSoundThemeChooserClass *klass);
static void gvc_sound_theme_chooser_init (GvcSoundThemeChooser *sound_theme_chooser);
static void gvc_sound_theme_chooser_finalize (GObject *object);
G_DEFINE_TYPE (GvcSoundThemeChooser, gvc_sound_theme_chooser, GTK_TYPE_VBOX)
#define KEY_SOUNDS_SCHEMA "org.gnome.desktop.sound"
#define EVENT_SOUNDS_KEY "event-sounds"
#define INPUT_SOUNDS_KEY "input-feedback-sounds"
#define SOUND_THEME_KEY "theme-name"
#define WM_SCHEMA "org.gnome.desktop.wm.preferences"
#define AUDIO_BELL_KEY "audible-bell"
#define DEFAULT_ALERT_ID "__default"
#define CUSTOM_THEME_NAME "__custom"
#define NO_SOUNDS_THEME_NAME "__no_sounds"
#define DEFAULT_THEME "freedesktop"
enum {
THEME_DISPLAY_COL,
THEME_IDENTIFIER_COL,
THEME_PARENT_ID_COL,
THEME_NUM_COLS
};
enum {
ALERT_DISPLAY_COL,
ALERT_IDENTIFIER_COL,
ALERT_SOUND_TYPE_COL,
ALERT_NUM_COLS
};
enum {
SOUND_TYPE_UNSET,
SOUND_TYPE_OFF,
SOUND_TYPE_DEFAULT_FROM_THEME,
SOUND_TYPE_BUILTIN,
SOUND_TYPE_CUSTOM
};
#define GVC_SOUND_SOUND (xmlChar *) "sound"
#define GVC_SOUND_NAME (xmlChar *) "name"
#define GVC_SOUND_FILENAME (xmlChar *) "filename"
/* Adapted from yelp-toc-pager.c */
static xmlChar *
xml_get_and_trim_names (xmlNodePtr node)
{
xmlNodePtr cur;
xmlChar *keep_lang = NULL;
xmlChar *value;
int j, keep_pri = INT_MAX;
const gchar * const * langs = g_get_language_names ();
value = NULL;
for (cur = node->children; cur; cur = cur->next) {
if (! xmlStrcmp (cur->name, GVC_SOUND_NAME)) {
xmlChar *cur_lang = NULL;
int cur_pri = INT_MAX;
cur_lang = xmlNodeGetLang (cur);
if (cur_lang) {
for (j = 0; langs[j]; j++) {
if (g_str_equal (cur_lang, langs[j])) {
cur_pri = j;
break;
}
}
} else {
cur_pri = INT_MAX - 1;
}
if (cur_pri <= keep_pri) {
if (keep_lang)
xmlFree (keep_lang);
if (value)
xmlFree (value);
value = xmlNodeGetContent (cur);
keep_lang = cur_lang;
keep_pri = cur_pri;
} else {
if (cur_lang)
xmlFree (cur_lang);
}
}
}
/* Delete all GVC_SOUND_NAME nodes */
cur = node->children;
while (cur) {
xmlNodePtr this = cur;
cur = cur->next;
if (! xmlStrcmp (this->name, GVC_SOUND_NAME)) {
xmlUnlinkNode (this);
xmlFreeNode (this);
}
}
return value;
}
static void
populate_model_from_node (GvcSoundThemeChooser *chooser,
GtkTreeModel *model,
xmlNodePtr node)
{
xmlNodePtr child;
xmlChar *filename;
xmlChar *name;
filename = NULL;
name = xml_get_and_trim_names (node);
for (child = node->children; child; child = child->next) {
if (xmlNodeIsText (child)) {
continue;
}
if (xmlStrcmp (child->name, GVC_SOUND_FILENAME) == 0) {
filename = xmlNodeGetContent (child);
} else if (xmlStrcmp (child->name, GVC_SOUND_NAME) == 0) {
/* EH? should have been trimmed */
}
}
if (filename != NULL && name != NULL) {
gtk_list_store_insert_with_values (GTK_LIST_STORE (model),
NULL,
G_MAXINT,
ALERT_IDENTIFIER_COL, filename,
ALERT_DISPLAY_COL, name,
ALERT_SOUND_TYPE_COL, _("Built-in"),
-1);
}
xmlFree (filename);
xmlFree (name);
}
static void
populate_model_from_file (GvcSoundThemeChooser *chooser,
GtkTreeModel *model,
const char *filename)
{
xmlDocPtr doc;
xmlNodePtr root;
xmlNodePtr child;
gboolean exists;
exists = g_file_test (filename, G_FILE_TEST_EXISTS);
if (! exists) {
return;
}
doc = xmlParseFile (filename);
if (doc == NULL) {
return;
}
root = xmlDocGetRootElement (doc);
for (child = root->children; child; child = child->next) {
if (xmlNodeIsText (child)) {
continue;
}
if (xmlStrcmp (child->name, GVC_SOUND_SOUND) != 0) {
continue;
}
populate_model_from_node (chooser, model, child);
}
xmlFreeDoc (doc);
}
static void
populate_model_from_dir (GvcSoundThemeChooser *chooser,
GtkTreeModel *model,
const char *dirname)
{
GDir *d;
const char *name;
d = g_dir_open (dirname, 0, NULL);
if (d == NULL) {
return;
}
while ((name = g_dir_read_name (d)) != NULL) {
char *path;
if (! g_str_has_suffix (name, ".xml")) {
continue;
}
path = g_build_filename (dirname, name, NULL);
populate_model_from_file (chooser, model, path);
g_free (path);
}
}
static gboolean
save_alert_sounds (GvcSoundThemeChooser *chooser,
const char *id)
{
const char *sounds[3] = { "bell-terminal", "bell-window-system", NULL };
char *path;
if (strcmp (id, DEFAULT_ALERT_ID) == 0) {
delete_old_files (sounds);
delete_disabled_files (sounds);
} else {
delete_old_files (sounds);
delete_disabled_files (sounds);
add_custom_file (sounds, id);
}
/* And poke the directory so the theme gets updated */
path = custom_theme_dir_path (NULL);
if (utime (path, NULL) != 0) {
g_warning ("Failed to update mtime for directory '%s': %s",
path, g_strerror (errno));
}
g_free (path);
return FALSE;
}
static void
update_alert_model (GvcSoundThemeChooser *chooser,
const char *id)
{
GtkTreeModel *model;
GtkTreeIter iter;
model = gtk_tree_view_get_model (GTK_TREE_VIEW (chooser->priv->treeview));
gtk_tree_model_get_iter_first (model, &iter);
do {
char *this_id;
gtk_tree_model_get (model, &iter,
ALERT_IDENTIFIER_COL, &this_id,
-1);
if (strcmp (this_id, id) == 0) {
GtkTreeSelection *selection;
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (chooser->priv->treeview));
gtk_tree_selection_select_iter (selection, &iter);
}
g_free (this_id);
} while (gtk_tree_model_iter_next (model, &iter));
}
static void
save_theme_name (GvcSoundThemeChooser *chooser,
const char *theme_name)
{
/* If the name is empty, use "freedesktop" */
if (theme_name == NULL || *theme_name == '\0') {
theme_name = DEFAULT_THEME;
}
/* special case for no sounds */
if (strcmp (theme_name, NO_SOUNDS_THEME_NAME) == 0) {
g_settings_set_boolean (chooser->priv->sound_settings, EVENT_SOUNDS_KEY, FALSE);
return;
} else {
g_settings_set_boolean (chooser->priv->sound_settings, EVENT_SOUNDS_KEY, TRUE);
}
g_settings_set_string (chooser->priv->sound_settings, SOUND_THEME_KEY, theme_name);
}
static gboolean
load_theme_file (const char *path,
char **parent)
{
GKeyFile *file;
gboolean hidden;
file = g_key_file_new ();
if (g_key_file_load_from_file (file, path, G_KEY_FILE_KEEP_TRANSLATIONS, NULL) == FALSE) {
g_key_file_free (file);
return FALSE;
}
/* Don't add hidden themes to the list */
hidden = g_key_file_get_boolean (file, "Sound Theme", "Hidden", NULL);
if (!hidden) {
/* Save the parent theme, if there's one */
if (parent != NULL) {
*parent = g_key_file_get_string (file,
"Sound Theme",
"Inherits",
NULL);
}
}
g_key_file_free (file);
return TRUE;
}
static gboolean
load_theme_name (const char *name,
char **parent)
{
const char * const *data_dirs;
const char *data_dir;
char *path;
guint i;
gboolean res;
data_dir = g_get_user_data_dir ();
path = g_build_filename (data_dir, "sounds", name, "index.theme", NULL);
res = load_theme_file (path, parent);
g_free (path);
if (res)
return TRUE;
data_dirs = g_get_system_data_dirs ();
for (i = 0; data_dirs[i] != NULL; i++) {
path = g_build_filename (data_dirs[i], "sounds", name, "index.theme", NULL);
res = load_theme_file (path, parent);
g_free (path);
if (res)
return TRUE;
}
return FALSE;
}
static void
update_alert (GvcSoundThemeChooser *chooser,
const char *alert_id)
{
gboolean is_custom;
gboolean is_default;
gboolean add_custom;
gboolean remove_custom;
is_custom = strcmp (chooser->priv->current_theme, CUSTOM_THEME_NAME) == 0;
is_default = strcmp (alert_id, DEFAULT_ALERT_ID) == 0;
/* So a few possibilities:
* 1. Named theme, default alert selected: noop
* 2. Named theme, alternate alert selected: create new custom with sound
* 3. Custom theme, default alert selected: remove sound and possibly custom
* 4. Custom theme, alternate alert selected: update custom sound
*/
add_custom = FALSE;
remove_custom = FALSE;
if (! is_custom && is_default) {
/* remove custom just in case */
remove_custom = TRUE;
} else if (! is_custom && ! is_default) {
if (chooser->priv->current_parent)
create_custom_theme (chooser->priv->current_parent);
else
create_custom_theme (DEFAULT_THEME);
save_alert_sounds (chooser, alert_id);
add_custom = TRUE;
} else if (is_custom && is_default) {
save_alert_sounds (chooser, alert_id);
/* after removing files check if it is empty */
if (custom_theme_dir_is_empty ()) {
remove_custom = TRUE;
}
} else if (is_custom && ! is_default) {
save_alert_sounds (chooser, alert_id);
}
if (add_custom) {
save_theme_name (chooser, CUSTOM_THEME_NAME);
} else if (remove_custom) {
delete_custom_theme_dir ();
if (is_custom) {
save_theme_name (chooser, chooser->priv->current_parent);
}
}
update_alert_model (chooser, alert_id);
}
static void
play_preview_for_id (GvcSoundThemeChooser *chooser,
const char *id)
{
g_return_if_fail (id != NULL);
/* special case: for the default item on custom themes
* play the alert for the parent theme */
if (strcmp (id, DEFAULT_ALERT_ID) == 0) {
if (chooser->priv->current_parent != NULL) {
ca_gtk_play_for_widget (GTK_WIDGET (chooser), 0,
CA_PROP_APPLICATION_NAME, _("Sound Preferences"),
CA_PROP_EVENT_ID, "bell-window-system",
CA_PROP_CANBERRA_XDG_THEME_NAME, chooser->priv->current_parent,
CA_PROP_EVENT_DESCRIPTION, _("Testing event sound"),
CA_PROP_CANBERRA_CACHE_CONTROL, "never",
CA_PROP_APPLICATION_ID, "org.gnome.VolumeControl",
#ifdef CA_PROP_CANBERRA_ENABLE
CA_PROP_CANBERRA_ENABLE, "1",
#endif
NULL);
} else {
ca_gtk_play_for_widget (GTK_WIDGET (chooser), 0,
CA_PROP_APPLICATION_NAME, _("Sound Preferences"),
CA_PROP_EVENT_ID, "bell-window-system",
CA_PROP_EVENT_DESCRIPTION, _("Testing event sound"),
CA_PROP_CANBERRA_CACHE_CONTROL, "never",
CA_PROP_APPLICATION_ID, "org.gnome.VolumeControl",
#ifdef CA_PROP_CANBERRA_ENABLE
CA_PROP_CANBERRA_ENABLE, "1",
#endif
NULL);
}
} else {
ca_gtk_play_for_widget (GTK_WIDGET (chooser), 0,
CA_PROP_APPLICATION_NAME, _("Sound Preferences"),
CA_PROP_MEDIA_FILENAME, id,
CA_PROP_EVENT_DESCRIPTION, _("Testing event sound"),
CA_PROP_CANBERRA_CACHE_CONTROL, "never",
CA_PROP_APPLICATION_ID, "org.gnome.VolumeControl",
#ifdef CA_PROP_CANBERRA_ENABLE
CA_PROP_CANBERRA_ENABLE, "1",
#endif
NULL);
}
}
static void
on_treeview_selection_changed (GtkTreeSelection *selection,
GvcSoundThemeChooser *chooser)
{
GtkTreeModel *model;
GtkTreeIter iter;
char *id;
if (chooser->priv->treeview == NULL) {
return;
}
model = gtk_tree_view_get_model (GTK_TREE_VIEW (chooser->priv->treeview));
if (gtk_tree_selection_get_selected (selection, &model, &iter) == FALSE) {
return;
}
id = NULL;
gtk_tree_model_get (model, &iter,
ALERT_IDENTIFIER_COL, &id,
-1);
if (id == NULL) {
return;
}
play_preview_for_id (chooser, id);
update_alert (chooser, id);
g_free (id);
}
static gboolean
on_treeview_button_pressed (GtkTreeView *treeview,
GdkEventButton *event,
GvcSoundThemeChooser *chooser)
{
GtkTreeSelection *selection;
GtkTreePath *path;
selection = gtk_tree_view_get_selection (treeview);
if (gtk_tree_view_get_path_at_pos (GTK_TREE_VIEW (treeview),
event->x, event->y, &path, NULL, NULL, NULL) == FALSE) {
return FALSE;
}
if (gtk_tree_selection_path_is_selected (selection, path) == FALSE) {
gtk_tree_path_free (path);
return FALSE;
}
gtk_tree_path_free (path);
on_treeview_selection_changed (selection, chooser);
return FALSE;
}
static GtkWidget *
create_alert_treeview (GvcSoundThemeChooser *chooser)
{
GtkListStore *store;
GtkWidget *treeview;
GtkCellRenderer *renderer;
GtkTreeViewColumn *column;
GtkTreeSelection *selection;
treeview = gtk_tree_view_new ();
gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (treeview), FALSE);
g_signal_connect (treeview,
"button-press-event",
G_CALLBACK (on_treeview_button_pressed),
chooser);
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview));
gtk_tree_selection_set_mode (selection, GTK_SELECTION_SINGLE);
g_signal_connect (selection,
"changed",
G_CALLBACK (on_treeview_selection_changed),
chooser);
/* Setup the tree model, 3 columns:
* - display name
* - sound id
* - sound type
*/
store = gtk_list_store_new (ALERT_NUM_COLS,
G_TYPE_STRING,
G_TYPE_STRING,
G_TYPE_STRING);
gtk_list_store_insert_with_values (store,
NULL,
G_MAXINT,
ALERT_IDENTIFIER_COL, DEFAULT_ALERT_ID,
ALERT_DISPLAY_COL, _("Default"),
ALERT_SOUND_TYPE_COL, _("From theme"),
-1);
populate_model_from_dir (chooser, GTK_TREE_MODEL (store), SOUND_SET_DIR);
gtk_tree_view_set_model (GTK_TREE_VIEW (treeview),
GTK_TREE_MODEL (store));
renderer = gtk_cell_renderer_text_new ();
column = gtk_tree_view_column_new_with_attributes (_("Name"),
renderer,
"text", ALERT_DISPLAY_COL,
NULL);
gtk_tree_view_append_column (GTK_TREE_VIEW (treeview), column);
return treeview;
}
static int
get_file_type (const char *sound_name,
char **linked_name)
{
char *name, *filename;
*linked_name = NULL;
name = g_strdup_printf ("%s.disabled", sound_name);
filename = custom_theme_dir_path (name);
g_free (name);
if (g_file_test (filename, G_FILE_TEST_IS_REGULAR) != FALSE) {
g_free (filename);
return SOUND_TYPE_OFF;
}
g_free (filename);
/* We only check for .ogg files because those are the
* only ones we create */
name = g_strdup_printf ("%s.ogg", sound_name);
filename = custom_theme_dir_path (name);
g_free (name);
if (g_file_test (filename, G_FILE_TEST_IS_SYMLINK) != FALSE) {
*linked_name = g_file_read_link (filename, NULL);
g_free (filename);
return SOUND_TYPE_CUSTOM;
}
g_free (filename);
return SOUND_TYPE_BUILTIN;
}
static void
update_alerts_from_theme_name (GvcSoundThemeChooser *chooser,
const char *name)
{
if (strcmp (name, CUSTOM_THEME_NAME) != 0) {
/* reset alert to default */
update_alert (chooser, DEFAULT_ALERT_ID);
} else {
int sound_type;
char *linkname;
linkname = NULL;
sound_type = get_file_type ("bell-terminal", &linkname);
g_debug ("Found link: %s", linkname);
if (sound_type == SOUND_TYPE_CUSTOM) {
update_alert (chooser, linkname);
}
}
}
static void
update_theme (GvcSoundThemeChooser *chooser)
{
gboolean events_enabled;
char *last_theme;
events_enabled = g_settings_get_boolean (chooser->priv->sound_settings, EVENT_SOUNDS_KEY);
last_theme = chooser->priv->current_theme;
if (events_enabled) {
chooser->priv->current_theme = g_settings_get_string (chooser->priv->sound_settings, SOUND_THEME_KEY);
} else {
chooser->priv->current_theme = g_strdup (NO_SOUNDS_THEME_NAME);
}
if (g_strcmp0 (last_theme, chooser->priv->current_theme) != 0) {
g_free (chooser->priv->current_parent);
if (load_theme_name (chooser->priv->current_theme,
&chooser->priv->current_parent) == FALSE) {
g_free (chooser->priv->current_theme);
chooser->priv->current_theme = g_strdup (DEFAULT_THEME);
load_theme_name (DEFAULT_THEME,
&chooser->priv->current_parent);
}
}
g_free (last_theme);
gtk_widget_set_sensitive (chooser->priv->selection_box, events_enabled);
update_alerts_from_theme_name (chooser, chooser->priv->current_theme);
}
static GObject *
gvc_sound_theme_chooser_constructor (GType type,
guint n_construct_properties,
GObjectConstructParam *construct_params)
{
GObject *object;
GvcSoundThemeChooser *self;
object = G_OBJECT_CLASS (gvc_sound_theme_chooser_parent_class)->constructor (type, n_construct_properties, construct_params);
self = GVC_SOUND_THEME_CHOOSER (object);
update_theme (self);
return object;
}
static void
gvc_sound_theme_chooser_class_init (GvcSoundThemeChooserClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->constructor = gvc_sound_theme_chooser_constructor;
object_class->finalize = gvc_sound_theme_chooser_finalize;
g_type_class_add_private (klass, sizeof (GvcSoundThemeChooserPrivate));
}
static void
on_sound_settings_changed (GSettings *settings,
const char *key,
GvcSoundThemeChooser *chooser)
{
if (strcmp (key, EVENT_SOUNDS_KEY) == 0) {
update_theme (chooser);
} else if (strcmp (key, SOUND_THEME_KEY) == 0) {
update_theme (chooser);
} else if (strcmp (key, INPUT_SOUNDS_KEY) == 0) {
update_theme (chooser);
}
}
static void
on_audible_bell_changed (GSettings *settings,
const char *key,
GvcSoundThemeChooser *chooser)
{
update_theme (chooser);
}
static void
setup_list_size_constraint (GtkWidget *widget,
GtkWidget *to_size)
{
GtkRequisition req;
int max_height;
/* constrain height to be the tree height up to a max */
max_height = (gdk_screen_get_height (gtk_widget_get_screen (widget))) / 4;
gtk_widget_get_preferred_size (to_size, NULL, &req);
gtk_scrolled_window_set_min_content_height (GTK_SCROLLED_WINDOW (widget),
MIN (req.height, max_height));
}
static void
gvc_sound_theme_chooser_init (GvcSoundThemeChooser *chooser)
{
GtkWidget *box;
GtkWidget *label;
GtkWidget *scrolled_window;
GtkWidget *alignment;
char *str;
chooser->priv = GVC_SOUND_THEME_CHOOSER_GET_PRIVATE (chooser);
chooser->priv->settings = g_settings_new (WM_SCHEMA);
chooser->priv->sound_settings = g_settings_new (KEY_SOUNDS_SCHEMA);
str = g_strdup_printf ("<b>%s</b>", _("C_hoose an alert sound:"));
chooser->priv->selection_box = box = gtk_frame_new (str);
g_free (str);
label = gtk_frame_get_label_widget (GTK_FRAME (box));
gtk_label_set_use_underline (GTK_LABEL (label), TRUE);
gtk_label_set_use_markup (GTK_LABEL (label), TRUE);
gtk_frame_set_shadow_type (GTK_FRAME (box), GTK_SHADOW_NONE);
alignment = gtk_alignment_new (0, 0, 1, 1);
gtk_alignment_set_padding (GTK_ALIGNMENT (alignment), 6, 0, 0, 0);
gtk_container_add (GTK_CONTAINER (alignment), box);
gtk_box_pack_start (GTK_BOX (chooser), alignment, TRUE, TRUE, 6);
alignment = gtk_alignment_new (0, 0, 1, 1);
gtk_alignment_set_padding (GTK_ALIGNMENT (alignment), 6, 0, 0, 0);
gtk_container_add (GTK_CONTAINER (box), alignment);
chooser->priv->treeview = create_alert_treeview (chooser);
gtk_label_set_mnemonic_widget (GTK_LABEL (label), chooser->priv->treeview);
scrolled_window = gtk_scrolled_window_new (NULL, NULL);
setup_list_size_constraint (scrolled_window, chooser->priv->treeview);
gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window),
GTK_POLICY_NEVER,
GTK_POLICY_AUTOMATIC);
gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolled_window),
GTK_SHADOW_IN);
gtk_container_add (GTK_CONTAINER (scrolled_window), chooser->priv->treeview);
gtk_container_add (GTK_CONTAINER (alignment), scrolled_window);
g_signal_connect (G_OBJECT (chooser->priv->sound_settings), "changed",
G_CALLBACK (on_sound_settings_changed), chooser);
g_signal_connect (chooser->priv->settings, "changed::" AUDIO_BELL_KEY,
G_CALLBACK (on_audible_bell_changed), chooser);
}
static void
gvc_sound_theme_chooser_finalize (GObject *object)
{
GvcSoundThemeChooser *sound_theme_chooser;
g_return_if_fail (object != NULL);
g_return_if_fail (GVC_IS_SOUND_THEME_CHOOSER (object));
sound_theme_chooser = GVC_SOUND_THEME_CHOOSER (object);
if (sound_theme_chooser->priv != NULL) {
g_object_unref (sound_theme_chooser->priv->settings);
g_object_unref (sound_theme_chooser->priv->sound_settings);
}
G_OBJECT_CLASS (gvc_sound_theme_chooser_parent_class)->finalize (object);
}
GtkWidget *
gvc_sound_theme_chooser_new (void)
{
GObject *chooser;
chooser = g_object_new (GVC_TYPE_SOUND_THEME_CHOOSER,
"spacing", 6,
NULL);
return GTK_WIDGET (chooser);
}
|
371 | ./cinnamon-control-center/panels/sound/gvc-mixer-source.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2008 William Jon McCann
*
* 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.
*
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <pulse/pulseaudio.h>
#include "gvc-mixer-source.h"
#include "gvc-mixer-stream-private.h"
#include "gvc-channel-map-private.h"
#define GVC_MIXER_SOURCE_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GVC_TYPE_MIXER_SOURCE, GvcMixerSourcePrivate))
struct GvcMixerSourcePrivate
{
gpointer dummy;
};
static void gvc_mixer_source_class_init (GvcMixerSourceClass *klass);
static void gvc_mixer_source_init (GvcMixerSource *mixer_source);
static void gvc_mixer_source_finalize (GObject *object);
G_DEFINE_TYPE (GvcMixerSource, gvc_mixer_source, GVC_TYPE_MIXER_STREAM)
static gboolean
gvc_mixer_source_push_volume (GvcMixerStream *stream, gpointer *op)
{
pa_operation *o;
guint index;
const GvcChannelMap *map;
pa_context *context;
const pa_cvolume *cv;
index = gvc_mixer_stream_get_index (stream);
map = gvc_mixer_stream_get_channel_map (stream);
/* set the volume */
cv = gvc_channel_map_get_cvolume (map);
context = gvc_mixer_stream_get_pa_context (stream);
o = pa_context_set_source_volume_by_index (context,
index,
cv,
NULL,
NULL);
if (o == NULL) {
g_warning ("pa_context_set_source_volume_by_index() failed: %s", pa_strerror(pa_context_errno(context)));
return FALSE;
}
*op = o;
return TRUE;
}
static gboolean
gvc_mixer_source_change_is_muted (GvcMixerStream *stream,
gboolean is_muted)
{
pa_operation *o;
guint index;
pa_context *context;
index = gvc_mixer_stream_get_index (stream);
context = gvc_mixer_stream_get_pa_context (stream);
o = pa_context_set_source_mute_by_index (context,
index,
is_muted,
NULL,
NULL);
if (o == NULL) {
g_warning ("pa_context_set_source_mute_by_index() failed: %s", pa_strerror(pa_context_errno(context)));
return FALSE;
}
pa_operation_unref(o);
return TRUE;
}
static gboolean
gvc_mixer_source_change_port (GvcMixerStream *stream,
const char *port)
{
pa_operation *o;
guint index;
pa_context *context;
index = gvc_mixer_stream_get_index (stream);
context = gvc_mixer_stream_get_pa_context (stream);
o = pa_context_set_source_port_by_index (context,
index,
port,
NULL,
NULL);
if (o == NULL) {
g_warning ("pa_context_set_source_port_by_index() failed: %s", pa_strerror(pa_context_errno(context)));
return FALSE;
}
pa_operation_unref(o);
return TRUE;
}
static void
gvc_mixer_source_class_init (GvcMixerSourceClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
GvcMixerStreamClass *stream_class = GVC_MIXER_STREAM_CLASS (klass);
object_class->finalize = gvc_mixer_source_finalize;
stream_class->push_volume = gvc_mixer_source_push_volume;
stream_class->change_is_muted = gvc_mixer_source_change_is_muted;
stream_class->change_port = gvc_mixer_source_change_port;
g_type_class_add_private (klass, sizeof (GvcMixerSourcePrivate));
}
static void
gvc_mixer_source_init (GvcMixerSource *source)
{
source->priv = GVC_MIXER_SOURCE_GET_PRIVATE (source);
}
static void
gvc_mixer_source_finalize (GObject *object)
{
GvcMixerSource *mixer_source;
g_return_if_fail (object != NULL);
g_return_if_fail (GVC_IS_MIXER_SOURCE (object));
mixer_source = GVC_MIXER_SOURCE (object);
g_return_if_fail (mixer_source->priv != NULL);
G_OBJECT_CLASS (gvc_mixer_source_parent_class)->finalize (object);
}
/**
* gvc_mixer_source_new: (skip)
*
* @context:
* @index:
* @channel_map:
*
* Returns:
*/
GvcMixerStream *
gvc_mixer_source_new (pa_context *context,
guint index,
GvcChannelMap *channel_map)
{
GObject *object;
object = g_object_new (GVC_TYPE_MIXER_SOURCE,
"pa-context", context,
"index", index,
"channel-map", channel_map,
NULL);
return GVC_MIXER_STREAM (object);
}
|
372 | ./cinnamon-control-center/panels/sound/gvc-speaker-test.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2009 Bastien Nocera
*
* 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.
*
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <gtk/gtk.h>
#include <canberra.h>
#include <canberra-gtk.h>
#include <pulse/pulseaudio.h>
#include "gvc-speaker-test.h"
#include "gvc-mixer-stream.h"
#define GVC_SPEAKER_TEST_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GVC_TYPE_SPEAKER_TEST, GvcSpeakerTestPrivate))
struct GvcSpeakerTestPrivate
{
GtkWidget *channel_controls[PA_CHANNEL_POSITION_MAX];
ca_context *canberra;
GvcMixerStream *stream;
GvcMixerControl *control;
};
enum {
COL_NAME,
COL_HUMAN_NAME,
NUM_COLS
};
enum {
PROP_0,
PROP_STREAM,
PROP_CONTROL
};
static void gvc_speaker_test_class_init (GvcSpeakerTestClass *klass);
static void gvc_speaker_test_init (GvcSpeakerTest *speaker_test);
static void gvc_speaker_test_finalize (GObject *object);
static void update_channel_map (GvcSpeakerTest *speaker_test);
G_DEFINE_TYPE (GvcSpeakerTest, gvc_speaker_test, GTK_TYPE_TABLE)
static const int position_table[] = {
/* Position, X, Y */
PA_CHANNEL_POSITION_FRONT_LEFT, 0, 0,
PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER, 1, 0,
PA_CHANNEL_POSITION_FRONT_CENTER, 2, 0,
PA_CHANNEL_POSITION_MONO, 2, 0,
PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER, 3, 0,
PA_CHANNEL_POSITION_FRONT_RIGHT, 4, 0,
PA_CHANNEL_POSITION_SIDE_LEFT, 0, 1,
PA_CHANNEL_POSITION_SIDE_RIGHT, 4, 1,
PA_CHANNEL_POSITION_REAR_LEFT, 0, 2,
PA_CHANNEL_POSITION_REAR_CENTER, 2, 2,
PA_CHANNEL_POSITION_REAR_RIGHT, 4, 2,
PA_CHANNEL_POSITION_LFE, 3, 2
};
static void
gvc_speaker_test_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GvcSpeakerTest *self = GVC_SPEAKER_TEST (object);
switch (prop_id) {
case PROP_STREAM:
self->priv->stream = g_value_dup_object (value);
if (self->priv->control != NULL)
update_channel_map (self);
break;
case PROP_CONTROL:
self->priv->control = g_value_dup_object (value);
if (self->priv->stream != NULL)
update_channel_map (self);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gvc_speaker_test_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GvcSpeakerTest *self = GVC_SPEAKER_TEST (object);
switch (prop_id) {
case PROP_STREAM:
g_value_set_object (value, self->priv->stream);
break;
case PROP_CONTROL:
g_value_set_object (value, self->priv->control);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gvc_speaker_test_class_init (GvcSpeakerTestClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->finalize = gvc_speaker_test_finalize;
object_class->set_property = gvc_speaker_test_set_property;
object_class->get_property = gvc_speaker_test_get_property;
g_object_class_install_property (object_class,
PROP_STREAM,
g_param_spec_object ("stream",
"stream",
"The stream",
GVC_TYPE_MIXER_STREAM,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_object_class_install_property (object_class,
PROP_CONTROL,
g_param_spec_object ("control",
"control",
"The mixer controller",
GVC_TYPE_MIXER_CONTROL,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT_ONLY));
g_type_class_add_private (klass, sizeof (GvcSpeakerTestPrivate));
}
static const char *
sound_name (pa_channel_position_t position)
{
switch (position) {
case PA_CHANNEL_POSITION_FRONT_LEFT:
return "audio-channel-front-left";
case PA_CHANNEL_POSITION_FRONT_RIGHT:
return "audio-channel-front-right";
case PA_CHANNEL_POSITION_FRONT_CENTER:
return "audio-channel-front-center";
case PA_CHANNEL_POSITION_REAR_LEFT:
return "audio-channel-rear-left";
case PA_CHANNEL_POSITION_REAR_RIGHT:
return "audio-channel-rear-right";
case PA_CHANNEL_POSITION_REAR_CENTER:
return "audio-channel-rear-center";
case PA_CHANNEL_POSITION_LFE:
return "audio-channel-lfe";
case PA_CHANNEL_POSITION_SIDE_LEFT:
return "audio-channel-side-left";
case PA_CHANNEL_POSITION_SIDE_RIGHT:
return "audio-channel-side-right";
default:
return NULL;
}
}
static const char *
icon_name (pa_channel_position_t position, gboolean playing)
{
switch (position) {
case PA_CHANNEL_POSITION_FRONT_LEFT:
return playing ? "audio-speaker-left-testing" : "audio-speaker-left";
case PA_CHANNEL_POSITION_FRONT_RIGHT:
return playing ? "audio-speaker-right-testing" : "audio-speaker-right";
case PA_CHANNEL_POSITION_FRONT_CENTER:
return playing ? "audio-speaker-center-testing" : "audio-speaker-center";
case PA_CHANNEL_POSITION_REAR_LEFT:
return playing ? "audio-speaker-left-back-testing" : "audio-speaker-left-back";
case PA_CHANNEL_POSITION_REAR_RIGHT:
return playing ? "audio-speaker-right-back-testing" : "audio-speaker-right-back";
case PA_CHANNEL_POSITION_REAR_CENTER:
return playing ? "audio-speaker-center-back-testing" : "audio-speaker-center-back";
case PA_CHANNEL_POSITION_LFE:
return playing ? "audio-subwoofer-testing" : "audio-subwoofer";
case PA_CHANNEL_POSITION_SIDE_LEFT:
return playing ? "audio-speaker-left-side-testing" : "audio-speaker-left-side";
case PA_CHANNEL_POSITION_SIDE_RIGHT:
return playing ? "audio-speaker-right-side-testing" : "audio-speaker-right-side";
default:
return NULL;
}
}
static void
update_button (GtkWidget *control)
{
GtkWidget *button;
GtkWidget *image;
pa_channel_position_t position;
gboolean playing;
button = g_object_get_data (G_OBJECT (control), "button");
image = g_object_get_data (G_OBJECT (control), "image");
position = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (control), "position"));
playing = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (control), "playing"));
gtk_button_set_label (GTK_BUTTON (button), playing ? _("Stop") : _("Test"));
gtk_image_set_from_icon_name (GTK_IMAGE (image), icon_name (position, playing), GTK_ICON_SIZE_DIALOG);
}
static const char *
pretty_position (pa_channel_position_t position)
{
if (position == PA_CHANNEL_POSITION_LFE)
return N_("Subwoofer");
return pa_channel_position_to_pretty_string (position);
}
static gboolean
idle_cb (GtkWidget *control)
{
if (control == NULL)
return FALSE;
/* This is called in the background thread, hence
* forward to main thread via idle callback */
g_object_set_data (G_OBJECT (control), "playing", GINT_TO_POINTER(FALSE));
update_button (control);
return FALSE;
}
static void
finish_cb (ca_context *c, uint32_t id, int error_code, void *userdata)
{
GtkWidget *control = (GtkWidget *) userdata;
if (error_code == CA_ERROR_DESTROYED || control == NULL)
return;
g_idle_add ((GSourceFunc) idle_cb, control);
}
static void
on_test_button_clicked (GtkButton *button,
GtkWidget *control)
{
gboolean playing;
ca_context *canberra;
canberra = g_object_get_data (G_OBJECT (control), "canberra");
ca_context_cancel (canberra, 1);
playing = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (control), "playing"));
if (playing) {
g_object_set_data (G_OBJECT (control), "playing", GINT_TO_POINTER(FALSE));
} else {
pa_channel_position_t position;
const char *name;
ca_proplist *proplist;
position = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (control), "position"));
ca_proplist_create (&proplist);
ca_proplist_sets (proplist, CA_PROP_MEDIA_ROLE, "test");
ca_proplist_sets (proplist, CA_PROP_MEDIA_NAME, pretty_position (position));
ca_proplist_sets (proplist, CA_PROP_CANBERRA_FORCE_CHANNEL,
pa_channel_position_to_string (position));
ca_proplist_sets (proplist, CA_PROP_CANBERRA_ENABLE, "1");
name = sound_name (position);
if (name != NULL) {
ca_proplist_sets (proplist, CA_PROP_EVENT_ID, name);
playing = ca_context_play_full (canberra, 1, proplist, finish_cb, control) >= 0;
}
if (!playing) {
ca_proplist_sets (proplist, CA_PROP_EVENT_ID, "audio-test-signal");
playing = ca_context_play_full (canberra, 1, proplist, finish_cb, control) >= 0;
}
if (!playing) {
ca_proplist_sets(proplist, CA_PROP_EVENT_ID, "bell-window-system");
playing = ca_context_play_full (canberra, 1, proplist, finish_cb, control) >= 0;
}
g_object_set_data (G_OBJECT (control), "playing", GINT_TO_POINTER(playing));
}
update_button (control);
}
static GtkWidget *
channel_control_new (ca_context *canberra, pa_channel_position_t position)
{
GtkWidget *control;
GtkWidget *box;
GtkWidget *label;
GtkWidget *image;
GtkWidget *test_button;
const char *name;
control = gtk_box_new (GTK_ORIENTATION_VERTICAL, 6);
g_object_set_data (G_OBJECT (control), "playing", GINT_TO_POINTER(FALSE));
g_object_set_data (G_OBJECT (control), "position", GINT_TO_POINTER(position));
g_object_set_data (G_OBJECT (control), "canberra", canberra);
name = icon_name (position, FALSE);
if (name == NULL)
name = "audio-volume-medium";
image = gtk_image_new_from_icon_name (name, GTK_ICON_SIZE_DIALOG);
g_object_set_data (G_OBJECT (control), "image", image);
gtk_box_pack_start (GTK_BOX (control), image, FALSE, FALSE, 0);
label = gtk_label_new (pretty_position (position));
gtk_box_pack_start (GTK_BOX (control), label, FALSE, FALSE, 0);
test_button = gtk_button_new_with_label (_("Test"));
g_signal_connect (G_OBJECT (test_button), "clicked",
G_CALLBACK (on_test_button_clicked), control);
g_object_set_data (G_OBJECT (control), "button", test_button);
atk_object_add_relationship (gtk_widget_get_accessible (test_button),
ATK_RELATION_LABELLED_BY,
gtk_widget_get_accessible (label));
box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
gtk_box_pack_start (GTK_BOX (box), test_button, TRUE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (control), box, FALSE, FALSE, 0);
gtk_widget_show_all (control);
return control;
}
static void
create_channel_controls (GvcSpeakerTest *speaker_test)
{
guint i;
for (i = 0; i < G_N_ELEMENTS (position_table); i += 3) {
speaker_test->priv->channel_controls[position_table[i]] = channel_control_new (speaker_test->priv->canberra, (pa_channel_position_t) position_table[i]);
gtk_table_attach (GTK_TABLE (speaker_test),
speaker_test->priv->channel_controls[position_table[i]],
position_table[i+1],
position_table[i+1]+1,
position_table[i+2],
position_table[i+2]+1,
GTK_EXPAND, GTK_EXPAND, 0, 0);
}
}
static void
update_channel_map (GvcSpeakerTest *speaker_test)
{
guint i;
const GvcChannelMap *map;
g_return_if_fail (speaker_test->priv->control != NULL);
g_return_if_fail (speaker_test->priv->stream != NULL);
g_debug ("XXX update_channel_map called XXX");
map = gvc_mixer_stream_get_channel_map (speaker_test->priv->stream);
g_return_if_fail (map != NULL);
ca_context_change_device (speaker_test->priv->canberra,
gvc_mixer_stream_get_name (speaker_test->priv->stream));
for (i = 0; i < G_N_ELEMENTS (position_table); i += 3) {
gtk_widget_set_visible (speaker_test->priv->channel_controls[position_table[i]],
gvc_channel_map_has_position(map, position_table[i]));
}
}
static void
gvc_speaker_test_set_theme (ca_context *ca)
{
GtkSettings *settings;
char *theme_name;
settings = gtk_settings_get_for_screen (gdk_screen_get_default ());
g_object_get (G_OBJECT (settings),
"gtk-sound-theme-name", &theme_name,
NULL);
if (theme_name)
ca_context_change_props (ca, CA_PROP_CANBERRA_XDG_THEME_NAME, theme_name, NULL);
g_free (theme_name);
}
static void
gvc_speaker_test_init (GvcSpeakerTest *speaker_test)
{
GtkWidget *face;
speaker_test->priv = GVC_SPEAKER_TEST_GET_PRIVATE (speaker_test);
ca_context_create (&speaker_test->priv->canberra);
ca_context_set_driver (speaker_test->priv->canberra, "pulse");
ca_context_change_props (speaker_test->priv->canberra,
CA_PROP_APPLICATION_ID, "org.gnome.VolumeControl",
NULL);
gvc_speaker_test_set_theme (speaker_test->priv->canberra);
gtk_widget_set_direction (GTK_WIDGET (speaker_test), GTK_TEXT_DIR_LTR);
gtk_table_resize (GTK_TABLE (speaker_test), 3, 5);
gtk_container_set_border_width (GTK_CONTAINER (speaker_test), 12);
gtk_table_set_homogeneous (GTK_TABLE (speaker_test), TRUE);
gtk_table_set_row_spacings (GTK_TABLE (speaker_test), 12);
gtk_table_set_col_spacings (GTK_TABLE (speaker_test), 12);
create_channel_controls (speaker_test);
face = gtk_image_new_from_icon_name ("face-smile", GTK_ICON_SIZE_DIALOG);
gtk_table_attach (GTK_TABLE (speaker_test), face,
2, 3, 1, 2, GTK_EXPAND, GTK_EXPAND, 0, 0);
gtk_widget_show (face);
}
static void
gvc_speaker_test_finalize (GObject *object)
{
GvcSpeakerTest *speaker_test;
g_return_if_fail (object != NULL);
g_return_if_fail (GVC_IS_SPEAKER_TEST (object));
speaker_test = GVC_SPEAKER_TEST (object);
g_return_if_fail (speaker_test->priv != NULL);
g_object_unref (speaker_test->priv->stream);
speaker_test->priv->stream = NULL;
g_object_unref (speaker_test->priv->control);
speaker_test->priv->control = NULL;
ca_context_destroy (speaker_test->priv->canberra);
speaker_test->priv->canberra = NULL;
G_OBJECT_CLASS (gvc_speaker_test_parent_class)->finalize (object);
}
GtkWidget *
gvc_speaker_test_new (GvcMixerControl *control,
GvcMixerStream *stream)
{
GObject *speaker_test;
g_return_val_if_fail (stream != NULL, NULL);
g_return_val_if_fail (control != NULL, NULL);
speaker_test = g_object_new (GVC_TYPE_SPEAKER_TEST,
"stream", stream,
"control", control,
NULL);
return GTK_WIDGET (speaker_test);
}
|
373 | ./cinnamon-control-center/panels/sound/gvc-balance-bar.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2008 William Jon McCann
*
* 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.
*
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <gtk/gtk.h>
#include <canberra-gtk.h>
#include <pulse/pulseaudio.h>
#include "gvc-balance-bar.h"
#include "gvc-channel-map-private.h"
#define SCALE_SIZE 128
#define ADJUSTMENT_MAX_NORMAL 65536.0 /* PA_VOLUME_NORM */
#define GVC_BALANCE_BAR_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GVC_TYPE_BALANCE_BAR, GvcBalanceBarPrivate))
struct GvcBalanceBarPrivate
{
GvcChannelMap *channel_map;
GvcBalanceType btype;
GtkWidget *scale_box;
GtkWidget *start_box;
GtkWidget *end_box;
GtkWidget *label;
GtkWidget *scale;
GtkAdjustment *adjustment;
GtkSizeGroup *size_group;
gboolean symmetric;
gboolean click_lock;
};
enum
{
PROP_0,
PROP_CHANNEL_MAP,
PROP_BALANCE_TYPE,
};
static void gvc_balance_bar_class_init (GvcBalanceBarClass *klass);
static void gvc_balance_bar_init (GvcBalanceBar *balance_bar);
static void gvc_balance_bar_finalize (GObject *object);
static gboolean on_scale_button_press_event (GtkWidget *widget,
GdkEventButton *event,
GvcBalanceBar *bar);
static gboolean on_scale_button_release_event (GtkWidget *widget,
GdkEventButton *event,
GvcBalanceBar *bar);
static gboolean on_scale_scroll_event (GtkWidget *widget,
GdkEventScroll *event,
GvcBalanceBar *bar);
static void on_adjustment_value_changed (GtkAdjustment *adjustment,
GvcBalanceBar *bar);
G_DEFINE_TYPE (GvcBalanceBar, gvc_balance_bar, GTK_TYPE_HBOX)
static GtkWidget *
_scale_box_new (GvcBalanceBar *bar)
{
GvcBalanceBarPrivate *priv = bar->priv;
GtkWidget *box;
GtkWidget *sbox;
GtkWidget *ebox;
GtkAdjustment *adjustment = bar->priv->adjustment;
char *str_lower, *str_upper;
gdouble lower, upper;
bar->priv->scale_box = box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 6);
priv->scale = gtk_scale_new (GTK_ORIENTATION_HORIZONTAL, priv->adjustment);
gtk_widget_set_size_request (priv->scale, SCALE_SIZE, -1);
gtk_widget_set_name (priv->scale, "balance-bar-scale");
gtk_rc_parse_string ("style \"balance-bar-scale-style\" {\n"
" GtkScale::trough-side-details = 0\n"
"}\n"
"widget \"*.balance-bar-scale\" style : rc \"balance-bar-scale-style\"\n");
bar->priv->start_box = sbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 6);
gtk_box_pack_start (GTK_BOX (box), sbox, FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (sbox), priv->label, FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (box), priv->scale, TRUE, TRUE, 0);
switch (bar->priv->btype) {
case BALANCE_TYPE_RL:
str_lower = g_strdup_printf ("<small>%s</small>", C_("balance", "Left"));
str_upper = g_strdup_printf ("<small>%s</small>", C_("balance", "Right"));
break;
case BALANCE_TYPE_FR:
str_lower = g_strdup_printf ("<small>%s</small>", C_("balance", "Rear"));
str_upper = g_strdup_printf ("<small>%s</small>", C_("balance", "Front"));
break;
case BALANCE_TYPE_LFE:
str_lower = g_strdup_printf ("<small>%s</small>", C_("balance", "Minimum"));
str_upper = g_strdup_printf ("<small>%s</small>", C_("balance", "Maximum"));
break;
default:
g_assert_not_reached ();
}
lower = gtk_adjustment_get_lower (adjustment);
gtk_scale_add_mark (GTK_SCALE (priv->scale), lower,
GTK_POS_BOTTOM, str_lower);
g_free (str_lower);
upper = gtk_adjustment_get_upper (adjustment);
gtk_scale_add_mark (GTK_SCALE (priv->scale), upper,
GTK_POS_BOTTOM, str_upper);
g_free (str_upper);
if (bar->priv->btype != BALANCE_TYPE_LFE) {
gtk_scale_add_mark (GTK_SCALE (priv->scale),
(upper - lower)/2 + lower,
GTK_POS_BOTTOM, NULL);
}
bar->priv->end_box = ebox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 6);
gtk_box_pack_start (GTK_BOX (box), ebox, FALSE, FALSE, 0);
ca_gtk_widget_disable_sounds (bar->priv->scale, FALSE);
gtk_widget_add_events (bar->priv->scale, GDK_SCROLL_MASK);
g_signal_connect (G_OBJECT (bar->priv->scale), "button-press-event",
G_CALLBACK (on_scale_button_press_event), bar);
g_signal_connect (G_OBJECT (bar->priv->scale), "button-release-event",
G_CALLBACK (on_scale_button_release_event), bar);
g_signal_connect (G_OBJECT (bar->priv->scale), "scroll-event",
G_CALLBACK (on_scale_scroll_event), bar);
if (bar->priv->size_group != NULL) {
gtk_size_group_add_widget (bar->priv->size_group, sbox);
if (bar->priv->symmetric) {
gtk_size_group_add_widget (bar->priv->size_group, ebox);
}
}
gtk_scale_set_draw_value (GTK_SCALE (priv->scale), FALSE);
return box;
}
void
gvc_balance_bar_set_size_group (GvcBalanceBar *bar,
GtkSizeGroup *group,
gboolean symmetric)
{
g_return_if_fail (GVC_IS_BALANCE_BAR (bar));
bar->priv->size_group = group;
bar->priv->symmetric = symmetric;
if (bar->priv->size_group != NULL) {
gtk_size_group_add_widget (bar->priv->size_group,
bar->priv->start_box);
if (bar->priv->symmetric) {
gtk_size_group_add_widget (bar->priv->size_group,
bar->priv->end_box);
}
}
gtk_widget_queue_draw (GTK_WIDGET (bar));
}
static const char *
btype_to_string (guint btype)
{
switch (btype) {
case BALANCE_TYPE_RL:
return "Balance";
case BALANCE_TYPE_FR:
return "Fade";
break;
case BALANCE_TYPE_LFE:
return "LFE";
default:
g_assert_not_reached ();
}
return NULL;
}
static void
update_level_from_map (GvcBalanceBar *bar,
GvcChannelMap *map)
{
const gdouble *volumes;
gdouble val;
g_debug ("Volume changed (for %s bar)", btype_to_string (bar->priv->btype));
volumes = gvc_channel_map_get_volume (map);
switch (bar->priv->btype) {
case BALANCE_TYPE_RL:
val = volumes[BALANCE];
break;
case BALANCE_TYPE_FR:
val = volumes[FADE];
break;
case BALANCE_TYPE_LFE:
val = volumes[LFE];
break;
default:
g_assert_not_reached ();
}
gtk_adjustment_set_value (bar->priv->adjustment, val);
}
static void
on_channel_map_volume_changed (GvcChannelMap *map,
gboolean set,
GvcBalanceBar *bar)
{
update_level_from_map (bar, map);
}
static void
gvc_balance_bar_set_channel_map (GvcBalanceBar *bar,
GvcChannelMap *map)
{
g_return_if_fail (GVC_BALANCE_BAR (bar));
if (bar->priv->channel_map != NULL) {
g_signal_handlers_disconnect_by_func (G_OBJECT (bar->priv->channel_map),
on_channel_map_volume_changed, bar);
g_object_unref (bar->priv->channel_map);
}
bar->priv->channel_map = g_object_ref (map);
update_level_from_map (bar, map);
g_signal_connect (G_OBJECT (map), "volume-changed",
G_CALLBACK (on_channel_map_volume_changed), bar);
g_object_notify (G_OBJECT (bar), "channel-map");
}
static void
gvc_balance_bar_set_balance_type (GvcBalanceBar *bar,
GvcBalanceType btype)
{
GtkWidget *frame;
g_return_if_fail (GVC_BALANCE_BAR (bar));
bar->priv->btype = btype;
if (bar->priv->btype != BALANCE_TYPE_LFE) {
bar->priv->adjustment = GTK_ADJUSTMENT (gtk_adjustment_new (0.0,
-1.0,
1.0,
0.5,
0.5,
0.0));
} else {
bar->priv->adjustment = GTK_ADJUSTMENT (gtk_adjustment_new (0.0,
0.0,
ADJUSTMENT_MAX_NORMAL,
ADJUSTMENT_MAX_NORMAL/100.0,
ADJUSTMENT_MAX_NORMAL/10.0,
0.0));
}
g_object_ref_sink (bar->priv->adjustment);
g_signal_connect (bar->priv->adjustment,
"value-changed",
G_CALLBACK (on_adjustment_value_changed),
bar);
switch (btype) {
case BALANCE_TYPE_RL:
bar->priv->label = gtk_label_new_with_mnemonic (_("_Balance:"));
break;
case BALANCE_TYPE_FR:
bar->priv->label = gtk_label_new_with_mnemonic (_("_Fade:"));
break;
case BALANCE_TYPE_LFE:
bar->priv->label = gtk_label_new_with_mnemonic (_("_Subwoofer:"));
break;
default:
g_assert_not_reached ();
}
gtk_misc_set_alignment (GTK_MISC (bar->priv->label),
0.0,
0.0);
/* frame */
frame = gtk_frame_new (NULL);
gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_NONE);
gtk_container_add (GTK_CONTAINER (bar), frame);
/* box with scale */
bar->priv->scale_box = _scale_box_new (bar);
gtk_container_add (GTK_CONTAINER (frame), bar->priv->scale_box);
gtk_widget_show_all (frame);
gtk_widget_set_direction (bar->priv->scale, GTK_TEXT_DIR_LTR);
gtk_label_set_mnemonic_widget (GTK_LABEL (bar->priv->label),
bar->priv->scale);
g_object_notify (G_OBJECT (bar), "balance-type");
}
static void
gvc_balance_bar_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GvcBalanceBar *self = GVC_BALANCE_BAR (object);
switch (prop_id) {
case PROP_CHANNEL_MAP:
gvc_balance_bar_set_channel_map (self, g_value_get_object (value));
break;
case PROP_BALANCE_TYPE:
gvc_balance_bar_set_balance_type (self, g_value_get_int (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gvc_balance_bar_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GvcBalanceBar *self = GVC_BALANCE_BAR (object);
switch (prop_id) {
case PROP_CHANNEL_MAP:
g_value_set_object (value, self->priv->channel_map);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static GObject *
gvc_balance_bar_constructor (GType type,
guint n_construct_properties,
GObjectConstructParam *construct_params)
{
return G_OBJECT_CLASS (gvc_balance_bar_parent_class)->constructor (type, n_construct_properties, construct_params);
}
static void
gvc_balance_bar_class_init (GvcBalanceBarClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->constructor = gvc_balance_bar_constructor;
object_class->finalize = gvc_balance_bar_finalize;
object_class->set_property = gvc_balance_bar_set_property;
object_class->get_property = gvc_balance_bar_get_property;
g_object_class_install_property (object_class,
PROP_CHANNEL_MAP,
g_param_spec_object ("channel-map",
"channel map",
"The channel map",
GVC_TYPE_CHANNEL_MAP,
G_PARAM_READWRITE));
g_object_class_install_property (object_class,
PROP_BALANCE_TYPE,
g_param_spec_int ("balance-type",
"balance type",
"Whether the balance is right-left or front-rear",
BALANCE_TYPE_RL, NUM_BALANCE_TYPES - 1, BALANCE_TYPE_RL,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT_ONLY));
g_type_class_add_private (klass, sizeof (GvcBalanceBarPrivate));
}
static gboolean
on_scale_button_press_event (GtkWidget *widget,
GdkEventButton *event,
GvcBalanceBar *bar)
{
bar->priv->click_lock = TRUE;
return FALSE;
}
static gboolean
on_scale_button_release_event (GtkWidget *widget,
GdkEventButton *event,
GvcBalanceBar *bar)
{
bar->priv->click_lock = FALSE;
return FALSE;
}
static gboolean
on_scale_scroll_event (GtkWidget *widget,
GdkEventScroll *event,
GvcBalanceBar *bar)
{
gdouble value;
gdouble dx, dy;
value = gtk_adjustment_get_value (bar->priv->adjustment);
if (!gdk_event_get_scroll_deltas ((GdkEvent*)event, &dx, &dy)) {
dx = 0.0;
dy = 0.0;
switch (event->direction) {
case GDK_SCROLL_UP:
case GDK_SCROLL_RIGHT:
dy = 1.0;
break;
case GDK_SCROLL_DOWN:
case GDK_SCROLL_LEFT:
dy = -1.0;
break;
default:
;
}
}
if (bar->priv->btype == BALANCE_TYPE_LFE) {
if (dy > 0) {
if (value + dy * ADJUSTMENT_MAX_NORMAL/100.0 > ADJUSTMENT_MAX_NORMAL)
value = ADJUSTMENT_MAX_NORMAL;
else
value = value + dy * ADJUSTMENT_MAX_NORMAL/100.0;
} else if (dy < 0) {
if (value + dy * ADJUSTMENT_MAX_NORMAL/100.0 < 0)
value = 0.0;
else
value = value + dy * ADJUSTMENT_MAX_NORMAL/100.0;
}
} else {
if (dy > 0) {
if (value + dy * 0.01 > 1.0)
value = 1.0;
else
value = value + dy * 0.01;
} else if (dy < 0) {
if (value + dy * 0.01 < -1.0)
value = -1.0;
else
value = value + dy * 0.01;
}
}
gtk_adjustment_set_value (bar->priv->adjustment, value);
return TRUE;
}
static void
on_adjustment_value_changed (GtkAdjustment *adjustment,
GvcBalanceBar *bar)
{
gdouble val;
pa_cvolume cv;
const pa_channel_map *pa_map;
if (bar->priv->channel_map == NULL)
return;
cv = *gvc_channel_map_get_cvolume (bar->priv->channel_map);
val = gtk_adjustment_get_value (adjustment);
pa_map = gvc_channel_map_get_pa_channel_map (bar->priv->channel_map);
switch (bar->priv->btype) {
case BALANCE_TYPE_RL:
pa_cvolume_set_balance (&cv, pa_map, val);
break;
case BALANCE_TYPE_FR:
pa_cvolume_set_fade (&cv, pa_map, val);
break;
case BALANCE_TYPE_LFE:
pa_cvolume_set_position (&cv, pa_map, PA_CHANNEL_POSITION_LFE, val);
break;
}
gvc_channel_map_volume_changed (bar->priv->channel_map, &cv, TRUE);
}
static void
gvc_balance_bar_init (GvcBalanceBar *bar)
{
bar->priv = GVC_BALANCE_BAR_GET_PRIVATE (bar);
}
static void
gvc_balance_bar_finalize (GObject *object)
{
GvcBalanceBar *bar;
g_return_if_fail (object != NULL);
g_return_if_fail (GVC_IS_BALANCE_BAR (object));
bar = GVC_BALANCE_BAR (object);
g_return_if_fail (bar->priv != NULL);
if (bar->priv->channel_map != NULL) {
g_signal_handlers_disconnect_by_func (G_OBJECT (bar->priv->channel_map),
on_channel_map_volume_changed, bar);
g_object_unref (bar->priv->channel_map);
}
G_OBJECT_CLASS (gvc_balance_bar_parent_class)->finalize (object);
}
GtkWidget *
gvc_balance_bar_new (const GvcChannelMap *channel_map, GvcBalanceType btype)
{
GObject *bar;
bar = g_object_new (GVC_TYPE_BALANCE_BAR,
"channel-map", channel_map,
"balance-type", btype,
NULL);
return GTK_WIDGET (bar);
}
|
374 | ./cinnamon-control-center/panels/sound/gvc-mixer-sink.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2008 William Jon McCann
*
* 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.
*
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <pulse/pulseaudio.h>
#include "gvc-mixer-sink.h"
#include "gvc-mixer-stream-private.h"
#include "gvc-channel-map-private.h"
#define GVC_MIXER_SINK_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GVC_TYPE_MIXER_SINK, GvcMixerSinkPrivate))
struct GvcMixerSinkPrivate
{
gpointer dummy;
};
static void gvc_mixer_sink_class_init (GvcMixerSinkClass *klass);
static void gvc_mixer_sink_init (GvcMixerSink *mixer_sink);
static void gvc_mixer_sink_finalize (GObject *object);
G_DEFINE_TYPE (GvcMixerSink, gvc_mixer_sink, GVC_TYPE_MIXER_STREAM)
static gboolean
gvc_mixer_sink_push_volume (GvcMixerStream *stream, gpointer *op)
{
pa_operation *o;
guint index;
const GvcChannelMap *map;
pa_context *context;
const pa_cvolume *cv;
index = gvc_mixer_stream_get_index (stream);
map = gvc_mixer_stream_get_channel_map (stream);
/* set the volume */
cv = gvc_channel_map_get_cvolume(map);
context = gvc_mixer_stream_get_pa_context (stream);
o = pa_context_set_sink_volume_by_index (context,
index,
cv,
NULL,
NULL);
if (o == NULL) {
g_warning ("pa_context_set_sink_volume_by_index() failed: %s", pa_strerror(pa_context_errno(context)));
return FALSE;
}
*op = o;
return TRUE;
}
static gboolean
gvc_mixer_sink_change_is_muted (GvcMixerStream *stream,
gboolean is_muted)
{
pa_operation *o;
guint index;
pa_context *context;
index = gvc_mixer_stream_get_index (stream);
context = gvc_mixer_stream_get_pa_context (stream);
o = pa_context_set_sink_mute_by_index (context,
index,
is_muted,
NULL,
NULL);
if (o == NULL) {
g_warning ("pa_context_set_sink_mute_by_index() failed: %s", pa_strerror(pa_context_errno(context)));
return FALSE;
}
pa_operation_unref(o);
return TRUE;
}
static gboolean
gvc_mixer_sink_change_port (GvcMixerStream *stream,
const char *port)
{
pa_operation *o;
guint index;
pa_context *context;
index = gvc_mixer_stream_get_index (stream);
context = gvc_mixer_stream_get_pa_context (stream);
o = pa_context_set_sink_port_by_index (context,
index,
port,
NULL,
NULL);
if (o == NULL) {
g_warning ("pa_context_set_sink_port_by_index() failed: %s", pa_strerror(pa_context_errno(context)));
return FALSE;
}
pa_operation_unref(o);
return TRUE;
}
static void
gvc_mixer_sink_class_init (GvcMixerSinkClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
GvcMixerStreamClass *stream_class = GVC_MIXER_STREAM_CLASS (klass);
object_class->finalize = gvc_mixer_sink_finalize;
stream_class->push_volume = gvc_mixer_sink_push_volume;
stream_class->change_port = gvc_mixer_sink_change_port;
stream_class->change_is_muted = gvc_mixer_sink_change_is_muted;
g_type_class_add_private (klass, sizeof (GvcMixerSinkPrivate));
}
static void
gvc_mixer_sink_init (GvcMixerSink *sink)
{
sink->priv = GVC_MIXER_SINK_GET_PRIVATE (sink);
}
static void
gvc_mixer_sink_finalize (GObject *object)
{
GvcMixerSink *mixer_sink;
g_return_if_fail (object != NULL);
g_return_if_fail (GVC_IS_MIXER_SINK (object));
mixer_sink = GVC_MIXER_SINK (object);
g_return_if_fail (mixer_sink->priv != NULL);
G_OBJECT_CLASS (gvc_mixer_sink_parent_class)->finalize (object);
}
/**
* gvc_mixer_sink_new: (skip)
*
* @context:
* @index:
* @channel_map:
*
* Returns:
*/
GvcMixerStream *
gvc_mixer_sink_new (pa_context *context,
guint index,
GvcChannelMap *channel_map)
{
GObject *object;
object = g_object_new (GVC_TYPE_MIXER_SINK,
"pa-context", context,
"index", index,
"channel-map", channel_map,
NULL);
return GVC_MIXER_STREAM (object);
}
|
375 | ./cinnamon-control-center/panels/sound/gvc-mixer-dialog.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2008 William Jon McCann
*
* 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.
*
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <gdk/gdkkeysyms.h>
#include <gtk/gtk.h>
#include <pulse/pulseaudio.h>
#include "gvc-channel-bar.h"
#include "gvc-balance-bar.h"
#include "gvc-combo-box.h"
#include "gvc-mixer-control.h"
#include "gvc-mixer-card.h"
#include "gvc-mixer-sink.h"
#include "gvc-mixer-source.h"
#include "gvc-mixer-source-output.h"
#include "gvc-mixer-dialog.h"
#include "gvc-sound-theme-chooser.h"
#include "gvc-level-bar.h"
#include "gvc-speaker-test.h"
#include "gvc-mixer-control-private.h"
#define SCALE_SIZE 128
#define GVC_MIXER_DIALOG_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GVC_TYPE_MIXER_DIALOG, GvcMixerDialogPrivate))
struct GvcMixerDialogPrivate
{
GvcMixerControl *mixer_control;
GHashTable *bars; /* Application and event bars only */
GtkWidget *notebook;
GtkWidget *output_bar;
GtkWidget *input_bar;
GtkWidget *input_level_bar;
GtkWidget *effects_bar;
GtkWidget *output_stream_box;
GtkWidget *sound_effects_box;
GtkWidget *input_box;
GtkWidget *output_box;
GtkWidget *applications_box;
GtkWidget *no_apps_label;
GtkWidget *output_treeview;
GtkWidget *output_settings_box;
GtkWidget *output_balance_bar;
GtkWidget *output_fade_bar;
GtkWidget *output_lfe_bar;
GtkWidget *output_profile_combo;
GtkWidget *input_treeview;
GtkWidget *input_profile_combo;
GtkWidget *input_settings_box;
GtkWidget *sound_theme_chooser;
GtkWidget *click_feedback_button;
GtkWidget *audible_bell_button;
GtkSizeGroup *size_group;
gdouble last_input_peak;
guint num_apps;
};
enum {
NAME_COLUMN,
DEVICE_COLUMN,
ACTIVE_COLUMN,
ID_COLUMN,
ICON_COLUMN,
NUM_COLUMNS
};
enum {
HW_ID_COLUMN,
HW_ICON_COLUMN,
HW_NAME_COLUMN,
HW_STATUS_COLUMN,
HW_PROFILE_COLUMN,
HW_PROFILE_HUMAN_COLUMN,
HW_SENSITIVE_COLUMN,
HW_NUM_COLUMNS
};
enum
{
PROP_0,
PROP_MIXER_CONTROL
};
static void gvc_mixer_dialog_class_init (GvcMixerDialogClass *klass);
static void gvc_mixer_dialog_init (GvcMixerDialog *mixer_dialog);
static void gvc_mixer_dialog_finalize (GObject *object);
static void bar_set_stream (GvcMixerDialog *dialog,
GtkWidget *bar,
GvcMixerStream *stream);
static void on_adjustment_value_changed (GtkAdjustment *adjustment,
GvcMixerDialog *dialog);
static void on_control_active_output_update (GvcMixerControl *control,
guint id,
GvcMixerDialog *dialog);
static void on_control_active_input_update (GvcMixerControl *control,
guint id,
GvcMixerDialog *dialog);
static void on_test_speakers_clicked (GvcComboBox *widget,
gpointer user_data);
G_DEFINE_TYPE (GvcMixerDialog, gvc_mixer_dialog, GTK_TYPE_VBOX)
static void
profile_selection_changed (GvcComboBox *combo_box,
const char *profile,
GvcMixerDialog *dialog)
{
GvcMixerUIDevice *output;
g_debug ("profile_selection_changed() to %s", profile);
output = g_object_get_data (G_OBJECT (combo_box), "uidevice");
if (output == NULL) {
g_warning ("Could not find Output for profile combo box");
return;
}
g_debug ("on profile selection changed on output '%s' (origin: %s, id: %i)",
gvc_mixer_ui_device_get_description (output),
gvc_mixer_ui_device_get_origin (output),
gvc_mixer_ui_device_get_id (output));
if (gvc_mixer_control_change_profile_on_selected_device (dialog->priv->mixer_control, output, profile) == FALSE) {
g_warning ("Could not change profile on device %s",
gvc_mixer_ui_device_get_description (output));
}
}
static void
update_output_settings (GvcMixerDialog *dialog,
GvcMixerUIDevice *device)
{
GvcMixerStream *stream;
const GvcChannelMap *map;
const GList *profiles;
GtkAdjustment *adj;
g_debug ("Updating output settings");
if (dialog->priv->output_balance_bar != NULL) {
gtk_container_remove (GTK_CONTAINER (dialog->priv->output_settings_box),
dialog->priv->output_balance_bar);
dialog->priv->output_balance_bar = NULL;
}
if (dialog->priv->output_fade_bar != NULL) {
gtk_container_remove (GTK_CONTAINER (dialog->priv->output_settings_box),
dialog->priv->output_fade_bar);
dialog->priv->output_fade_bar = NULL;
}
if (dialog->priv->output_lfe_bar != NULL) {
gtk_container_remove (GTK_CONTAINER (dialog->priv->output_settings_box),
dialog->priv->output_lfe_bar);
dialog->priv->output_lfe_bar = NULL;
}
if (dialog->priv->output_profile_combo != NULL) {
gtk_container_remove (GTK_CONTAINER (dialog->priv->output_settings_box),
dialog->priv->output_profile_combo);
dialog->priv->output_profile_combo = NULL;
}
stream = gvc_mixer_control_get_stream_from_device (dialog->priv->mixer_control,
device);
if (stream == NULL) {
g_warning ("Default sink stream not found");
return;
}
gvc_channel_bar_set_base_volume (GVC_CHANNEL_BAR (dialog->priv->output_bar),
gvc_mixer_stream_get_base_volume (stream));
gvc_channel_bar_set_is_amplified (GVC_CHANNEL_BAR (dialog->priv->output_bar),
gvc_mixer_stream_get_can_decibel (stream));
/* Update the adjustment in case the previous bar wasn't decibel
* capable, and we clipped it */
adj = GTK_ADJUSTMENT (gvc_channel_bar_get_adjustment (GVC_CHANNEL_BAR (dialog->priv->output_bar)));
gtk_adjustment_set_value (adj,
gvc_mixer_stream_get_volume (stream));
map = gvc_mixer_stream_get_channel_map (stream);
if (map == NULL) {
g_warning ("Default sink stream has no channel map");
return;
}
dialog->priv->output_balance_bar = gvc_balance_bar_new (map, BALANCE_TYPE_RL);
if (dialog->priv->size_group != NULL) {
gvc_balance_bar_set_size_group (GVC_BALANCE_BAR (dialog->priv->output_balance_bar),
dialog->priv->size_group,
TRUE);
}
gtk_box_pack_start (GTK_BOX (dialog->priv->output_settings_box),
dialog->priv->output_balance_bar,
FALSE, FALSE, 6);
gtk_widget_show (dialog->priv->output_balance_bar);
if (gvc_channel_map_can_fade (map)) {
dialog->priv->output_fade_bar = gvc_balance_bar_new (map, BALANCE_TYPE_FR);
if (dialog->priv->size_group != NULL) {
gvc_balance_bar_set_size_group (GVC_BALANCE_BAR (dialog->priv->output_fade_bar),
dialog->priv->size_group,
TRUE);
}
gtk_box_pack_start (GTK_BOX (dialog->priv->output_settings_box),
dialog->priv->output_fade_bar,
FALSE, FALSE, 6);
gtk_widget_show (dialog->priv->output_fade_bar);
}
if (gvc_channel_map_has_lfe (map)) {
dialog->priv->output_lfe_bar = gvc_balance_bar_new (map, BALANCE_TYPE_LFE);
if (dialog->priv->size_group != NULL) {
gvc_balance_bar_set_size_group (GVC_BALANCE_BAR (dialog->priv->output_lfe_bar),
dialog->priv->size_group,
TRUE);
}
gtk_box_pack_start (GTK_BOX (dialog->priv->output_settings_box),
dialog->priv->output_lfe_bar,
FALSE, FALSE, 6);
gtk_widget_show (dialog->priv->output_lfe_bar);
}
profiles = gvc_mixer_ui_device_get_profiles (device);
/* FIXME: How do we make sure the "Test speakers" button is shown
* even when there are no profiles to choose between? */
if (TRUE /*g_list_length((GList *) profiles) >= 2 */) {
const gchar *active_profile;
dialog->priv->output_profile_combo = gvc_combo_box_new (_("_Profile:"));
g_object_set (G_OBJECT (dialog->priv->output_profile_combo), "button-label", _("_Test Speakers"), NULL);
g_object_set (G_OBJECT (dialog->priv->output_profile_combo),
"show-button", TRUE, NULL);
g_signal_connect (G_OBJECT (dialog->priv->output_profile_combo), "button-clicked",
G_CALLBACK (on_test_speakers_clicked), dialog);
if (profiles)
gvc_combo_box_set_profiles (GVC_COMBO_BOX (dialog->priv->output_profile_combo),
profiles);
gtk_box_pack_start (GTK_BOX (dialog->priv->output_settings_box),
dialog->priv->output_profile_combo,
TRUE, FALSE, 6);
if (dialog->priv->size_group != NULL) {
gvc_combo_box_set_size_group (GVC_COMBO_BOX (dialog->priv->output_profile_combo),
dialog->priv->size_group, FALSE);
}
active_profile = gvc_mixer_ui_device_get_active_profile (device);
if (active_profile)
gvc_combo_box_set_active (GVC_COMBO_BOX (dialog->priv->output_profile_combo), active_profile);
g_object_set_data (G_OBJECT (dialog->priv->output_profile_combo),
"uidevice",
device);
if (g_list_length((GList *) profiles))
g_signal_connect (G_OBJECT (dialog->priv->output_profile_combo), "changed",
G_CALLBACK (profile_selection_changed), dialog);
gtk_widget_show (dialog->priv->output_profile_combo);
}
/* FIXME: We could make this into a "No settings" label instead */
gtk_widget_set_sensitive (dialog->priv->output_balance_bar, gvc_channel_map_can_balance (map));
}
#define DECAY_STEP .15
static void
update_input_peak (GvcMixerDialog *dialog,
gdouble v)
{
GtkAdjustment *adj;
if (dialog->priv->last_input_peak >= DECAY_STEP) {
if (v < dialog->priv->last_input_peak - DECAY_STEP) {
v = dialog->priv->last_input_peak - DECAY_STEP;
}
}
dialog->priv->last_input_peak = v;
adj = gvc_level_bar_get_peak_adjustment (GVC_LEVEL_BAR (dialog->priv->input_level_bar));
if (v >= 0) {
gtk_adjustment_set_value (adj, v);
} else {
gtk_adjustment_set_value (adj, 0.0);
}
}
static void
update_input_meter (GvcMixerDialog *dialog,
uint32_t source_index,
uint32_t sink_input_idx,
double v)
{
update_input_peak (dialog, v);
}
static void
on_monitor_suspended_callback (pa_stream *s,
void *userdata)
{
GvcMixerDialog *dialog;
dialog = userdata;
if (pa_stream_is_suspended (s)) {
g_debug ("Stream suspended");
update_input_meter (dialog,
pa_stream_get_device_index (s),
PA_INVALID_INDEX,
-1);
}
}
static void
on_monitor_read_callback (pa_stream *s,
size_t length,
void *userdata)
{
GvcMixerDialog *dialog;
const void *data;
double v;
dialog = userdata;
if (pa_stream_peek (s, &data, &length) < 0) {
g_warning ("Failed to read data from stream");
return;
}
assert (length > 0);
assert (length % sizeof (float) == 0);
v = ((const float *) data)[length / sizeof (float) -1];
pa_stream_drop (s);
if (v < 0) {
v = 0;
}
if (v > 1) {
v = 1;
}
update_input_meter (dialog,
pa_stream_get_device_index (s),
pa_stream_get_monitor_stream (s),
v);
}
static void
create_monitor_stream_for_source (GvcMixerDialog *dialog,
GvcMixerStream *stream)
{
pa_stream *s;
char t[16];
pa_buffer_attr attr;
pa_sample_spec ss;
pa_context *context;
int res;
pa_proplist *proplist;
gboolean has_monitor;
if (stream == NULL) {
return;
}
has_monitor = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (stream), "has-monitor"));
if (has_monitor != FALSE) {
return;
}
g_debug ("Create monitor for %u",
gvc_mixer_stream_get_index (stream));
context = gvc_mixer_control_get_pa_context (dialog->priv->mixer_control);
if (pa_context_get_server_protocol_version (context) < 13) {
return;
}
ss.channels = 1;
ss.format = PA_SAMPLE_FLOAT32;
ss.rate = 25;
memset (&attr, 0, sizeof (attr));
attr.fragsize = sizeof (float);
attr.maxlength = (uint32_t) -1;
snprintf (t, sizeof (t), "%u", gvc_mixer_stream_get_index (stream));
proplist = pa_proplist_new ();
pa_proplist_sets (proplist, PA_PROP_APPLICATION_ID, "org.gnome.VolumeControl");
s = pa_stream_new_with_proplist (context, _("Peak detect"), &ss, NULL, proplist);
pa_proplist_free (proplist);
if (s == NULL) {
g_warning ("Failed to create monitoring stream");
return;
}
pa_stream_set_read_callback (s, on_monitor_read_callback, dialog);
pa_stream_set_suspended_callback (s, on_monitor_suspended_callback, dialog);
res = pa_stream_connect_record (s,
t,
&attr,
(pa_stream_flags_t) (PA_STREAM_DONT_MOVE
|PA_STREAM_PEAK_DETECT
|PA_STREAM_ADJUST_LATENCY));
if (res < 0) {
g_warning ("Failed to connect monitoring stream");
pa_stream_unref (s);
} else {
g_object_set_data (G_OBJECT (stream), "has-monitor", GINT_TO_POINTER (TRUE));
g_object_set_data (G_OBJECT (dialog->priv->input_level_bar), "pa_stream", s);
g_object_set_data (G_OBJECT (dialog->priv->input_level_bar), "stream", stream);
}
}
static void
stop_monitor_stream_for_source (GvcMixerDialog *dialog)
{
pa_stream *s;
pa_context *context;
int res;
GvcMixerStream *stream;
s = g_object_get_data (G_OBJECT (dialog->priv->input_level_bar), "pa_stream");
if (s == NULL)
return;
stream = g_object_get_data (G_OBJECT (dialog->priv->input_level_bar), "stream");
g_assert (stream != NULL);
g_debug ("Stopping monitor for %u", pa_stream_get_index (s));
context = gvc_mixer_control_get_pa_context (dialog->priv->mixer_control);
if (pa_context_get_server_protocol_version (context) < 13) {
return;
}
res = pa_stream_disconnect (s);
if (res == 0)
g_object_set_data (G_OBJECT (stream), "has-monitor", GINT_TO_POINTER (FALSE));
g_object_set_data (G_OBJECT (dialog->priv->input_level_bar), "pa_stream", NULL);
g_object_set_data (G_OBJECT (dialog->priv->input_level_bar), "stream", NULL);
}
static void
update_input_settings (GvcMixerDialog *dialog,
GvcMixerUIDevice *device)
{
GvcMixerStream *stream;
const GList *profiles;
GtkAdjustment *adj;
g_debug ("Updating input settings");
stop_monitor_stream_for_source (dialog);
if (dialog->priv->input_profile_combo != NULL) {
gtk_container_remove (GTK_CONTAINER (dialog->priv->input_settings_box),
dialog->priv->input_profile_combo);
dialog->priv->input_profile_combo = NULL;
}
stream = gvc_mixer_control_get_stream_from_device (dialog->priv->mixer_control,
device);
if (stream == NULL) {
g_debug ("Default source stream not found");
return;
}
gvc_channel_bar_set_base_volume (GVC_CHANNEL_BAR (dialog->priv->input_bar),
gvc_mixer_stream_get_base_volume (stream));
gvc_channel_bar_set_is_amplified (GVC_CHANNEL_BAR (dialog->priv->input_bar),
gvc_mixer_stream_get_can_decibel (stream));
/* Update the adjustment in case the previous bar wasn't decibel
* capable, and we clipped it */
adj = GTK_ADJUSTMENT (gvc_channel_bar_get_adjustment (GVC_CHANNEL_BAR (dialog->priv->input_bar)));
gtk_adjustment_set_value (adj,
gvc_mixer_stream_get_volume (stream));
profiles = gvc_mixer_ui_device_get_profiles (device);
if (g_list_length ((GList *) profiles) >= 2) {
const gchar *active_profile;
dialog->priv->input_profile_combo = gvc_combo_box_new (_("_Profile:"));
gvc_combo_box_set_profiles (GVC_COMBO_BOX (dialog->priv->input_profile_combo),
profiles);
gtk_box_pack_start (GTK_BOX (dialog->priv->input_settings_box),
dialog->priv->input_profile_combo,
TRUE, TRUE, 0);
if (dialog->priv->size_group != NULL) {
gvc_combo_box_set_size_group (GVC_COMBO_BOX (dialog->priv->input_profile_combo),
dialog->priv->size_group, FALSE);
}
active_profile = gvc_mixer_ui_device_get_active_profile (device);
if (active_profile)
gvc_combo_box_set_active (GVC_COMBO_BOX (dialog->priv->input_profile_combo), active_profile);
g_object_set_data (G_OBJECT (dialog->priv->input_profile_combo),
"uidevice",
device);
g_signal_connect (G_OBJECT (dialog->priv->input_profile_combo), "changed",
G_CALLBACK (profile_selection_changed), dialog);
gtk_widget_show (dialog->priv->input_profile_combo);
}
create_monitor_stream_for_source (dialog, stream);
}
static void
gvc_mixer_dialog_set_mixer_control (GvcMixerDialog *dialog,
GvcMixerControl *control)
{
g_return_if_fail (GVC_MIXER_DIALOG (dialog));
g_return_if_fail (GVC_IS_MIXER_CONTROL (control));
g_object_ref (control);
if (dialog->priv->mixer_control != NULL) {
g_signal_handlers_disconnect_by_func (dialog->priv->mixer_control,
G_CALLBACK (on_control_active_input_update),
dialog);
g_signal_handlers_disconnect_by_func (dialog->priv->mixer_control,
G_CALLBACK (on_control_active_output_update),
dialog);
g_object_unref (dialog->priv->mixer_control);
}
dialog->priv->mixer_control = control;
/* FIXME: Why are some mixer_control signals connected here,
* and others in the dialog constructor? (And similar for disconnect) */
g_signal_connect (dialog->priv->mixer_control,
"active-input-update",
G_CALLBACK (on_control_active_input_update),
dialog);
g_signal_connect (dialog->priv->mixer_control,
"active-output-update",
G_CALLBACK (on_control_active_output_update),
dialog);
g_object_notify (G_OBJECT (dialog), "mixer-control");
}
static GvcMixerControl *
gvc_mixer_dialog_get_mixer_control (GvcMixerDialog *dialog)
{
g_return_val_if_fail (GVC_IS_MIXER_DIALOG (dialog), NULL);
return dialog->priv->mixer_control;
}
static void
gvc_mixer_dialog_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GvcMixerDialog *self = GVC_MIXER_DIALOG (object);
switch (prop_id) {
case PROP_MIXER_CONTROL:
gvc_mixer_dialog_set_mixer_control (self, g_value_get_object (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gvc_mixer_dialog_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GvcMixerDialog *self = GVC_MIXER_DIALOG (object);
switch (prop_id) {
case PROP_MIXER_CONTROL:
g_value_set_object (value, gvc_mixer_dialog_get_mixer_control (self));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
on_adjustment_value_changed (GtkAdjustment *adjustment,
GvcMixerDialog *dialog)
{
GvcMixerStream *stream;
stream = g_object_get_data (G_OBJECT (adjustment), "gvc-mixer-dialog-stream");
if (stream != NULL) {
GObject *bar;
gdouble volume, rounded;
char *name;
volume = gtk_adjustment_get_value (adjustment);
rounded = round (volume);
bar = g_object_get_data (G_OBJECT (adjustment), "gvc-mixer-dialog-bar");
g_object_get (bar, "name", &name, NULL);
g_debug ("Setting stream volume %lf (rounded: %lf) for bar '%s'", volume, rounded, name);
g_free (name);
/* FIXME would need to do that in the balance bar really... */
/* Make sure we do not unmute muted streams, there's a button for that */
if (volume == 0.0)
gvc_mixer_stream_set_is_muted (stream, TRUE);
/* Only push the volume if it's actually changed */
if (gvc_mixer_stream_set_volume (stream, (pa_volume_t) rounded) != FALSE)
gvc_mixer_stream_push_volume (stream);
}
}
static void
on_bar_is_muted_notify (GObject *object,
GParamSpec *pspec,
GvcMixerDialog *dialog)
{
gboolean is_muted;
GvcMixerStream *stream;
is_muted = gvc_channel_bar_get_is_muted (GVC_CHANNEL_BAR (object));
stream = g_object_get_data (object, "gvc-mixer-dialog-stream");
if (stream != NULL) {
gvc_mixer_stream_change_is_muted (stream, is_muted);
} else {
char *name;
g_object_get (object, "name", &name, NULL);
g_warning ("Unable to find stream for bar '%s'", name);
g_free (name);
}
}
static GtkWidget *
lookup_bar_for_stream (GvcMixerDialog *dialog,
GvcMixerStream *stream)
{
GtkWidget *bar;
bar = g_hash_table_lookup (dialog->priv->bars, GUINT_TO_POINTER (gvc_mixer_stream_get_id (stream)));
return bar;
}
static void
on_stream_volume_notify (GObject *object,
GParamSpec *pspec,
GvcMixerDialog *dialog)
{
GvcMixerStream *stream;
GtkWidget *bar;
GtkAdjustment *adj;
stream = GVC_MIXER_STREAM (object);
bar = lookup_bar_for_stream (dialog, stream);
if (bar == NULL) {
g_warning ("Unable to find bar for stream %s in on_stream_volume_notify()",
gvc_mixer_stream_get_name (stream));
return;
}
adj = GTK_ADJUSTMENT (gvc_channel_bar_get_adjustment (GVC_CHANNEL_BAR (bar)));
g_signal_handlers_block_by_func (adj,
on_adjustment_value_changed,
dialog);
gtk_adjustment_set_value (adj,
gvc_mixer_stream_get_volume (stream));
g_signal_handlers_unblock_by_func (adj,
on_adjustment_value_changed,
dialog);
}
static void
on_stream_is_muted_notify (GObject *object,
GParamSpec *pspec,
GvcMixerDialog *dialog)
{
GvcMixerStream *stream;
GtkWidget *bar;
gboolean is_muted;
stream = GVC_MIXER_STREAM (object);
bar = lookup_bar_for_stream (dialog, stream);
if (bar == NULL) {
g_warning ("Unable to find bar for stream %s in on_stream_is_muted_notify()",
gvc_mixer_stream_get_name (stream));
return;
}
is_muted = gvc_mixer_stream_get_is_muted (stream);
gvc_channel_bar_set_is_muted (GVC_CHANNEL_BAR (bar),
is_muted);
if (stream == gvc_mixer_control_get_default_sink (dialog->priv->mixer_control)) {
gtk_widget_set_sensitive (dialog->priv->applications_box,
!is_muted);
}
}
static void
save_bar_for_stream (GvcMixerDialog *dialog,
GvcMixerStream *stream,
GtkWidget *bar)
{
g_hash_table_insert (dialog->priv->bars,
GUINT_TO_POINTER (gvc_mixer_stream_get_id (stream)),
bar);
}
static GtkWidget *
create_bar (GvcMixerDialog *dialog,
gboolean add_to_size_group,
gboolean symmetric)
{
GtkWidget *bar;
bar = gvc_channel_bar_new ();
gtk_widget_set_sensitive (bar, FALSE);
if (add_to_size_group && dialog->priv->size_group != NULL) {
gvc_channel_bar_set_size_group (GVC_CHANNEL_BAR (bar),
dialog->priv->size_group,
symmetric);
}
gvc_channel_bar_set_orientation (GVC_CHANNEL_BAR (bar),
GTK_ORIENTATION_HORIZONTAL);
gvc_channel_bar_set_show_mute (GVC_CHANNEL_BAR (bar),
TRUE);
g_signal_connect (bar,
"notify::is-muted",
G_CALLBACK (on_bar_is_muted_notify),
dialog);
return bar;
}
static GtkWidget *
create_app_bar (GvcMixerDialog *dialog,
const char *name,
const char *icon_name)
{
GtkWidget *bar;
bar = create_bar (dialog, FALSE, FALSE);
gvc_channel_bar_set_ellipsize (GVC_CHANNEL_BAR (bar), TRUE);
gvc_channel_bar_set_icon_name (GVC_CHANNEL_BAR (bar), icon_name);
if (name == NULL || strchr (name, '_') == NULL) {
gvc_channel_bar_set_name (GVC_CHANNEL_BAR (bar), name);
} else {
char **tokens, *escaped;
tokens = g_strsplit (name, "_", -1);
escaped = g_strjoinv ("__", tokens);
g_strfreev (tokens);
gvc_channel_bar_set_name (GVC_CHANNEL_BAR (bar), escaped);
g_free (escaped);
}
return bar;
}
/* active_input_update
* Handle input update change from the backend (control).
* Trust the backend whole-heartedly to deliver the correct input. */
static void
active_input_update (GvcMixerDialog *dialog,
GvcMixerUIDevice *active_input)
{
/* First make sure the correct UI device is selected. */
GtkTreeModel *model;
GtkTreeIter iter;
GvcMixerStream *stream;
g_debug ("active_input_update device id = %i",
gvc_mixer_ui_device_get_id (active_input));
model = gtk_tree_view_get_model (GTK_TREE_VIEW (dialog->priv->input_treeview));
if (gtk_tree_model_get_iter_first (model, &iter) == FALSE) {
g_warning ("No devices in the tree, so cannot set the active output");
return;
}
do {
gboolean is_selected = FALSE;
gint id;
gtk_tree_model_get (model, &iter,
ID_COLUMN, &id,
-1);
is_selected = id == gvc_mixer_ui_device_get_id (active_input);
gtk_list_store_set (GTK_LIST_STORE (model),
&iter,
ACTIVE_COLUMN, is_selected,
-1);
if (is_selected) {
GtkTreeSelection *selection;
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (dialog->priv->input_treeview));
gtk_tree_selection_select_iter (selection, &iter);
}
} while (gtk_tree_model_iter_next (model, &iter));
stream = gvc_mixer_control_get_stream_from_device (dialog->priv->mixer_control,
active_input);
if (stream == NULL) {
g_warning ("Couldn't find a stream from the active input");
gtk_widget_set_sensitive (dialog->priv->input_bar, FALSE);
return;
}
bar_set_stream (dialog, dialog->priv->input_bar, stream);
update_input_settings (dialog, active_input);
}
/* active_output_update
* Handle output update change from the backend (control).
* Trust the backend whole heartedly to deliver the correct output. */
static void
active_output_update (GvcMixerDialog *dialog,
GvcMixerUIDevice *active_output)
{
/* First make sure the correct UI device is selected. */
GvcMixerStream *stream;
GtkTreeModel *model;
GtkTreeIter iter;
g_debug ("active output update device id = %i",
gvc_mixer_ui_device_get_id (active_output));
model = gtk_tree_view_get_model (GTK_TREE_VIEW (dialog->priv->output_treeview));
if (gtk_tree_model_get_iter_first (model, &iter) == FALSE){
g_warning ("No devices in the tree, so cannot set the active output");
return;
}
do {
gboolean is_selected;
gint id;
gtk_tree_model_get (model, &iter,
ID_COLUMN, &id,
ACTIVE_COLUMN, &is_selected,
-1);
if (is_selected && id == gvc_mixer_ui_device_get_id (active_output)) {
/* XXX: profile change on the same device? */
g_debug ("Unneccessary active output update");
}
is_selected = id == gvc_mixer_ui_device_get_id (active_output);
gtk_list_store_set (GTK_LIST_STORE (model),
&iter,
ACTIVE_COLUMN, is_selected,
-1);
if (is_selected) {
GtkTreeSelection *selection;
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (dialog->priv->output_treeview));
gtk_tree_selection_select_iter (selection, &iter);
}
} while (gtk_tree_model_iter_next (model, &iter));
stream = gvc_mixer_control_get_stream_from_device (dialog->priv->mixer_control,
active_output);
if (stream == NULL) {
g_warning ("Couldn't find a stream from the active output");
return;
}
bar_set_stream (dialog, dialog->priv->output_bar, stream);
update_output_settings (dialog, active_output);
}
static void
bar_set_stream (GvcMixerDialog *dialog,
GtkWidget *bar,
GvcMixerStream *stream)
{
GtkAdjustment *adj;
GvcMixerStream *old_stream;
g_assert (bar != NULL);
old_stream = g_object_get_data (G_OBJECT (bar), "gvc-mixer-dialog-stream");
if (old_stream != NULL) {
char *name;
g_object_get (bar, "name", &name, NULL);
g_debug ("Disconnecting old stream '%s' from bar '%s'",
gvc_mixer_stream_get_name (old_stream), name);
g_free (name);
g_signal_handlers_disconnect_by_func (old_stream, on_stream_is_muted_notify, dialog);
g_signal_handlers_disconnect_by_func (old_stream, on_stream_volume_notify, dialog);
g_hash_table_remove (dialog->priv->bars, GUINT_TO_POINTER (gvc_mixer_stream_get_id (old_stream)));
}
gtk_widget_set_sensitive (bar, (stream != NULL));
adj = GTK_ADJUSTMENT (gvc_channel_bar_get_adjustment (GVC_CHANNEL_BAR (bar)));
g_signal_handlers_disconnect_by_func (adj, on_adjustment_value_changed, dialog);
g_object_set_data (G_OBJECT (bar), "gvc-mixer-dialog-stream", stream);
g_object_set_data (G_OBJECT (bar), "gvc-mixer-dialog-stream-id",
GUINT_TO_POINTER (gvc_mixer_stream_get_id (stream)));
g_object_set_data (G_OBJECT (adj), "gvc-mixer-dialog-stream", stream);
g_object_set_data (G_OBJECT (adj), "gvc-mixer-dialog-bar", bar);
if (stream != NULL) {
gboolean is_muted;
is_muted = gvc_mixer_stream_get_is_muted (stream);
gvc_channel_bar_set_is_muted (GVC_CHANNEL_BAR (bar), is_muted);
gtk_adjustment_set_value (adj,
gvc_mixer_stream_get_volume (stream));
g_signal_connect (stream,
"notify::is-muted",
G_CALLBACK (on_stream_is_muted_notify),
dialog);
g_signal_connect (stream,
"notify::volume",
G_CALLBACK (on_stream_volume_notify),
dialog);
g_signal_connect (adj,
"value-changed",
G_CALLBACK (on_adjustment_value_changed),
dialog);
}
}
static void
add_stream (GvcMixerDialog *dialog,
GvcMixerStream *stream)
{
GtkWidget *bar;
GvcMixerStream *old_stream;
bar = NULL;
if (GVC_IS_MIXER_SOURCE (stream) || GVC_IS_MIXER_SINK (stream))
return;
else if (stream == gvc_mixer_control_get_event_sink_input (dialog->priv->mixer_control)) {
bar = dialog->priv->effects_bar;
g_debug ("Adding effects stream");
} else {
/* Must be an application stream */
const char *name;
name = gvc_mixer_stream_get_name (stream);
g_debug ("Add bar for application stream : %s", name);
bar = create_app_bar (dialog, name,
gvc_mixer_stream_get_icon_name (stream));
gtk_box_pack_start (GTK_BOX (dialog->priv->applications_box), bar, FALSE, FALSE, 12);
dialog->priv->num_apps++;
gtk_widget_hide (dialog->priv->no_apps_label);
}
/* We should have a bar by now. */
g_assert (bar != NULL);
if (bar != NULL) {
old_stream = g_object_get_data (G_OBJECT (bar), "gvc-mixer-dialog-stream");
if (old_stream != NULL) {
char *name;
g_object_get (bar, "name", &name, NULL);
g_debug ("Disconnecting old stream '%s' from bar '%s'",
gvc_mixer_stream_get_name (old_stream), name);
g_free (name);
g_signal_handlers_disconnect_by_func (old_stream, on_stream_is_muted_notify, dialog);
g_signal_handlers_disconnect_by_func (old_stream, on_stream_volume_notify, dialog);
g_hash_table_remove (dialog->priv->bars, GUINT_TO_POINTER (gvc_mixer_stream_get_id (old_stream)));
}
save_bar_for_stream (dialog, stream, bar);
bar_set_stream (dialog, bar, stream);
gtk_widget_show (bar);
}
}
static void
on_control_stream_added (GvcMixerControl *control,
guint id,
GvcMixerDialog *dialog)
{
GvcMixerStream *stream;
const char *app_id;
stream = gvc_mixer_control_lookup_stream_id (control, id);
if (stream == NULL)
return;
app_id = gvc_mixer_stream_get_application_id (stream);
if (stream == gvc_mixer_control_get_event_sink_input (dialog->priv->mixer_control) ||
(GVC_IS_MIXER_SOURCE (stream) == FALSE &&
GVC_IS_MIXER_SINK (stream) == FALSE &&
gvc_mixer_stream_is_virtual (stream) == FALSE &&
g_strcmp0 (app_id, "org.gnome.VolumeControl") != 0 &&
g_strcmp0 (app_id, "org.PulseAudio.pavucontrol") != 0)) {
GtkWidget *bar;
bar = g_hash_table_lookup (dialog->priv->bars, GUINT_TO_POINTER (id));
if (bar != NULL) {
g_debug ("GvcMixerDialog: Stream %u already added", id);
return;
}
add_stream (dialog, stream);
}
}
static gboolean
find_item_by_id (GtkTreeModel *model,
guint id,
guint column,
GtkTreeIter *iter)
{
gboolean found_item;
found_item = FALSE;
if (!gtk_tree_model_get_iter_first (model, iter)) {
return FALSE;
}
do {
guint t_id;
gtk_tree_model_get (model, iter,
column, &t_id, -1);
if (id == t_id) {
found_item = TRUE;
}
} while (!found_item && gtk_tree_model_iter_next (model, iter));
return found_item;
}
static void
add_input_ui_entry (GvcMixerDialog *dialog,
GvcMixerUIDevice *input)
{
gchar *final_name;
gchar *port_name;
gchar *origin;
gchar *description;
gboolean available;
gint stream_id;
GtkTreeModel *model;
GtkTreeIter iter;
GIcon *icon;
GvcMixerCard *card;
g_debug ("Add input ui entry with id :%u",
gvc_mixer_ui_device_get_id (input));
g_object_get (G_OBJECT (input),
"stream-id", &stream_id,
"card", &card,
"origin", &origin,
"description", &description,
"port-name", &port_name,
"port-available", &available,
NULL);
if (origin && origin[0] != '\0')
final_name = g_strdup_printf ("%s - %s", description, origin);
else
final_name = g_strdup (description);
g_free (port_name);
g_free (origin);
g_free (description);
if (card == NULL) {
GvcMixerStream *stream;
g_debug ("just detected a network source");
stream = gvc_mixer_control_get_stream_from_device (dialog->priv->mixer_control, input);
if (stream == NULL) {
g_warning ("tried to add the network source but the stream was null - fail ?!");
g_free (final_name);
return;
}
icon = gvc_mixer_stream_get_gicon (stream);
} else
icon = gvc_mixer_card_get_gicon (card);
model = gtk_tree_view_get_model (GTK_TREE_VIEW (dialog->priv->input_treeview));
gtk_list_store_append (GTK_LIST_STORE (model), &iter);
gtk_list_store_set (GTK_LIST_STORE (model),
&iter,
NAME_COLUMN, final_name,
DEVICE_COLUMN, "",
ACTIVE_COLUMN, FALSE,
ICON_COLUMN, icon,
ID_COLUMN, gvc_mixer_ui_device_get_id (input),
-1);
if (icon != NULL)
g_object_unref (icon);
g_free (final_name);
}
static void
add_output_ui_entry (GvcMixerDialog *dialog,
GvcMixerUIDevice *output)
{
gchar *sink_port_name;
gchar *origin;
gchar *description;
gchar *final_name;
gboolean available;
gint sink_stream_id;
GtkTreeModel *model;
GtkTreeIter iter;
GIcon *icon;
GvcMixerCard *card;
g_debug ("Add output ui entry with id :%u",
gvc_mixer_ui_device_get_id (output));
g_object_get (G_OBJECT (output),
"stream-id", &sink_stream_id,
"card", &card,
"origin", &origin,
"description", &description,
"port-name", &sink_port_name,
"port-available", &available,
NULL);
if (origin && origin[0] != '\0')
final_name = g_strdup_printf ("%s - %s", description, origin);
else
final_name = g_strdup (description);
g_free (sink_port_name);
g_free (origin);
g_free (description);
if (card == NULL) {
GvcMixerStream *stream;
g_debug ("just detected a network sink");
stream = gvc_mixer_control_get_stream_from_device (dialog->priv->mixer_control, output);
if (stream == NULL) {
g_warning ("tried to add the network sink but the stream was null - fail ?!");
g_free (final_name);
return;
}
icon = gvc_mixer_stream_get_gicon (stream);
} else
icon = gvc_mixer_card_get_gicon (card);
model = gtk_tree_view_get_model (GTK_TREE_VIEW (dialog->priv->output_treeview));
gtk_list_store_append (GTK_LIST_STORE (model), &iter);
gtk_list_store_set (GTK_LIST_STORE (model),
&iter,
NAME_COLUMN, final_name,
DEVICE_COLUMN, "",
ACTIVE_COLUMN, FALSE,
ICON_COLUMN, icon,
ID_COLUMN, gvc_mixer_ui_device_get_id (output),
-1);
if (icon != NULL)
g_object_unref (icon);
g_free (final_name);
}
static void
on_control_active_input_update (GvcMixerControl *control,
guint id,
GvcMixerDialog *dialog)
{
GvcMixerUIDevice* in = NULL;
in = gvc_mixer_control_lookup_input_id (control, id);
if (in == NULL) {
g_warning ("on_control_active_input_update - tried to fetch an input of id %u but got nothing", id);
return;
}
active_input_update (dialog, in);
}
static void
on_control_active_output_update (GvcMixerControl *control,
guint id,
GvcMixerDialog *dialog)
{
GvcMixerUIDevice* out = NULL;
out = gvc_mixer_control_lookup_output_id (control, id);
if (out == NULL) {
g_warning ("on_control_active_output_update - tried to fetch an output of id %u but got nothing", id);
return;
}
active_output_update (dialog, out);
}
static void
on_control_input_added (GvcMixerControl *control,
guint id,
GvcMixerDialog *dialog)
{
GvcMixerUIDevice* in = NULL;
in = gvc_mixer_control_lookup_input_id (control, id);
if (in == NULL) {
g_warning ("on_control_input_added - tried to fetch an input of id %u but got nothing", id);
return;
}
add_input_ui_entry (dialog, in);
}
static void
on_control_input_removed (GvcMixerControl *control,
guint id,
GvcMixerDialog *dialog)
{
gboolean found;
GtkTreeIter iter;
GtkTreeModel *model;
gint stream_id;
GvcMixerUIDevice *in;
in = gvc_mixer_control_lookup_input_id (control, id);
g_object_get (G_OBJECT (in),
"stream-id", &stream_id,
NULL);
g_debug ("Remove input from dialog, id: %u, stream id: %i",
id,
stream_id);
/* remove from any models */
model = gtk_tree_view_get_model (GTK_TREE_VIEW (dialog->priv->input_treeview));
found = find_item_by_id (GTK_TREE_MODEL (model), id, ID_COLUMN, &iter);
if (found) {
gtk_list_store_remove (GTK_LIST_STORE (model), &iter);
}
}
static void
on_control_output_added (GvcMixerControl *control,
guint id,
GvcMixerDialog *dialog)
{
GvcMixerUIDevice* out = NULL;
out = gvc_mixer_control_lookup_output_id (control, id);
if (out == NULL) {
g_warning ("on_control_output_added - tried to fetch an output of id %u but got nothing", id);
return;
}
add_output_ui_entry (dialog, out);
}
static void
on_control_output_removed (GvcMixerControl *control,
guint id,
GvcMixerDialog *dialog)
{
gboolean found;
GtkTreeIter iter;
GtkTreeModel *model;
gint sink_stream_id;
GvcMixerUIDevice* out = NULL;
out = gvc_mixer_control_lookup_output_id (control, id);
g_object_get (G_OBJECT (out),
"stream-id", &sink_stream_id,
NULL);
g_debug ("Remove output from dialog \n id : %u \n sink stream id : %i \n",
id,
sink_stream_id);
/* remove from any models */
model = gtk_tree_view_get_model (GTK_TREE_VIEW (dialog->priv->output_treeview));
found = find_item_by_id (GTK_TREE_MODEL (model), id, ID_COLUMN, &iter);
if (found) {
gtk_list_store_remove (GTK_LIST_STORE (model), &iter);
}
}
static void
remove_stream (GvcMixerDialog *dialog,
guint id)
{
GtkWidget *bar;
guint output_id, input_id;
bar = g_hash_table_lookup (dialog->priv->bars, GUINT_TO_POINTER (id));
if (bar != NULL) {
g_hash_table_remove (dialog->priv->bars, GUINT_TO_POINTER (id));
gtk_container_remove (GTK_CONTAINER (gtk_widget_get_parent (bar)),
bar);
dialog->priv->num_apps--;
if (dialog->priv->num_apps == 0) {
gtk_widget_show (dialog->priv->no_apps_label);
}
return;
}
output_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (dialog->priv->output_bar), "gvc-mixer-dialog-stream-id"));
input_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (dialog->priv->input_bar), "gvc-mixer-dialog-stream-id"));
if (output_id == id)
bar = dialog->priv->output_bar;
else if (input_id == id)
bar = dialog->priv->input_bar;
else
return;
g_object_set_data (G_OBJECT (bar), "gvc-mixer-dialog-stream-id", NULL);
g_object_set_data (G_OBJECT (bar), "gvc-mixer-dialog-stream", NULL);
}
static void
on_control_stream_removed (GvcMixerControl *control,
guint id,
GvcMixerDialog *dialog)
{
remove_stream (dialog, id);
}
static void
_gtk_label_make_bold (GtkLabel *label)
{
PangoFontDescription *font_desc;
font_desc = pango_font_description_new ();
pango_font_description_set_weight (font_desc,
PANGO_WEIGHT_BOLD);
/* This will only affect the weight of the font, the rest is
* from the current state of the widget, which comes from the
* theme or user prefs, since the font desc only has the
* weight flag turned on.
*/
gtk_widget_modify_font (GTK_WIDGET (label), font_desc);
pango_font_description_free (font_desc);
}
static void
on_input_selection_changed (GtkTreeSelection *selection,
GvcMixerDialog *dialog)
{
GtkTreeModel *model;
GtkTreeIter iter;
gboolean active;
guint id;
GvcMixerUIDevice *input;
if (gtk_tree_selection_get_selected (selection, &model, &iter) == FALSE) {
g_debug ("Could not get default input from selection");
return;
}
gtk_tree_model_get (model, &iter,
ID_COLUMN, &id,
ACTIVE_COLUMN, &active,
-1);
input = gvc_mixer_control_lookup_input_id (dialog->priv->mixer_control, id);
if (input == NULL) {
g_warning ("on_input_selection_changed - Unable to find input with id: %u", id);
return;
}
gvc_mixer_control_change_input (dialog->priv->mixer_control, input);
}
static void
on_output_selection_changed (GtkTreeSelection *selection,
GvcMixerDialog *dialog)
{
GtkTreeModel *model;
GtkTreeIter iter;
gboolean active;
guint id;
GvcMixerUIDevice *output;
if (gtk_tree_selection_get_selected (selection, &model, &iter) == FALSE) {
g_debug ("Could not get default output from selection");
return;
}
gtk_tree_model_get (model, &iter,
ID_COLUMN, &id,
ACTIVE_COLUMN, &active,
-1);
g_debug ("on_output_selection_changed() stream id: %u, active %i", id, active);
if (active)
return;
output = gvc_mixer_control_lookup_output_id (dialog->priv->mixer_control, id);
if (output == NULL) {
g_warning ("Unable to find output with id: %u", id);
return;
}
gvc_mixer_control_change_output (dialog->priv->mixer_control, output);
}
static GtkWidget *
create_ui_device_treeview (GvcMixerDialog *dialog,
GCallback on_selection_changed)
{
GtkWidget *treeview;
GtkListStore *store;
GtkCellRenderer *renderer;
GtkTreeViewColumn *column;
GtkTreeSelection *selection;
treeview = gtk_tree_view_new ();
gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (treeview), FALSE);
store = gtk_list_store_new (NUM_COLUMNS,
G_TYPE_STRING,
G_TYPE_STRING,
G_TYPE_BOOLEAN,
G_TYPE_UINT,
G_TYPE_ICON);
gtk_tree_view_set_model (GTK_TREE_VIEW (treeview),
GTK_TREE_MODEL (store));
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview));
gtk_tree_selection_set_mode (selection, GTK_SELECTION_BROWSE);
column = gtk_tree_view_column_new ();
gtk_tree_view_column_set_title (column, _("Name"));
renderer = gtk_cell_renderer_pixbuf_new ();
gtk_tree_view_column_pack_start (column, renderer, FALSE);
g_object_set (G_OBJECT (renderer), "stock-size", GTK_ICON_SIZE_LARGE_TOOLBAR, NULL);
gtk_tree_view_column_set_attributes (column, renderer,
"gicon", ICON_COLUMN,
NULL);
renderer = gtk_cell_renderer_text_new ();
gtk_tree_view_column_pack_start (column, renderer, TRUE);
gtk_tree_view_column_set_attributes (column, renderer,
"text", NAME_COLUMN,
NULL);
gtk_tree_view_append_column (GTK_TREE_VIEW (treeview), column);
g_signal_connect (G_OBJECT (selection), "changed",
on_selection_changed, dialog);
#if 0
renderer = gtk_cell_renderer_text_new ();
column = gtk_tree_view_column_new_with_attributes (_("Device"),
renderer,
"text", DEVICE_COLUMN,
NULL);
gtk_tree_view_append_column (GTK_TREE_VIEW (treeview), column);
#endif
return treeview;
}
static void
on_test_speakers_clicked (GvcComboBox *widget,
gpointer user_data)
{
GvcMixerDialog *dialog = GVC_MIXER_DIALOG (user_data);
GtkTreeModel *model;
GtkTreeIter iter;
gint stream_id;
gint active_output = GVC_MIXER_UI_DEVICE_INVALID;
GvcMixerUIDevice *output;
GvcMixerStream *stream;
GtkWidget *d, *speaker_test, *container;
char *title;
model = gtk_tree_view_get_model (GTK_TREE_VIEW (dialog->priv->output_treeview));
if (gtk_tree_model_get_iter_first (model, &iter) == FALSE) {
g_warning ("The tree is empty => we have no device to test speakers with return");
return;
}
do {
gboolean is_selected = FALSE;
gint id;
gtk_tree_model_get (model, &iter,
ID_COLUMN, &id,
ACTIVE_COLUMN, &is_selected,
-1);
if (is_selected) {
active_output = id;
break;
}
} while (gtk_tree_model_iter_next (model, &iter));
if (active_output == GVC_MIXER_UI_DEVICE_INVALID) {
g_warning ("Can't find the active output from the UI");
return;
}
output = gvc_mixer_control_lookup_output_id (dialog->priv->mixer_control, (guint)active_output);
stream_id = gvc_mixer_ui_device_get_stream_id (output);
if (stream_id == GVC_MIXER_UI_DEVICE_INVALID)
return;
g_debug ("Test speakers on '%s'", gvc_mixer_ui_device_get_description (output));
stream = gvc_mixer_control_lookup_stream_id (dialog->priv->mixer_control, stream_id);
if (stream == NULL) {
g_debug ("Stream/sink not found");
return;
}
title = g_strdup_printf (_("Speaker Testing for %s"), gvc_mixer_ui_device_get_description (output));
d = gtk_dialog_new_with_buttons (title,
GTK_WINDOW (gtk_widget_get_toplevel (GTK_WIDGET (widget))),
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE,
NULL);
gtk_window_set_has_resize_grip (GTK_WINDOW (d), FALSE);
g_free (title);
speaker_test = gvc_speaker_test_new (dialog->priv->mixer_control,
stream);
gtk_widget_show (speaker_test);
container = gtk_dialog_get_content_area (GTK_DIALOG (d));
gtk_container_add (GTK_CONTAINER (container), speaker_test);
gtk_dialog_run (GTK_DIALOG (d));
gtk_widget_destroy (d);
}
static GObject *
gvc_mixer_dialog_constructor (GType type,
guint n_construct_properties,
GObjectConstructParam *construct_params)
{
GObject *object;
GvcMixerDialog *self;
GtkWidget *main_vbox;
GtkWidget *label;
GtkWidget *alignment;
GtkWidget *box;
GtkWidget *sbox;
GtkWidget *ebox;
GSList *streams;
GSList *l;
GvcMixerStream *stream;
object = G_OBJECT_CLASS (gvc_mixer_dialog_parent_class)->constructor (type, n_construct_properties, construct_params);
self = GVC_MIXER_DIALOG (object);
main_vbox = GTK_WIDGET (self);
gtk_box_set_spacing (GTK_BOX (main_vbox), 2);
gtk_container_set_border_width (GTK_CONTAINER (self), 6);
self->priv->output_stream_box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 12);
alignment = gtk_alignment_new (0, 0, 1, 1);
gtk_alignment_set_padding (GTK_ALIGNMENT (alignment), 12, 0, 0, 0);
gtk_container_add (GTK_CONTAINER (alignment), self->priv->output_stream_box);
gtk_box_pack_start (GTK_BOX (main_vbox),
alignment,
FALSE, FALSE, 0);
self->priv->output_bar = create_bar (self, TRUE, TRUE);
gvc_channel_bar_set_name (GVC_CHANNEL_BAR (self->priv->output_bar),
_("_Output volume:"));
gtk_widget_set_sensitive (self->priv->output_bar, FALSE);
gtk_box_pack_start (GTK_BOX (self->priv->output_stream_box),
self->priv->output_bar, TRUE, TRUE, 12);
self->priv->notebook = gtk_notebook_new ();
gtk_box_pack_start (GTK_BOX (main_vbox),
self->priv->notebook,
TRUE, TRUE, 0);
gtk_container_set_border_width (GTK_CONTAINER (self->priv->notebook), 5);
/* Output page */
self->priv->output_box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 12);
gtk_container_set_border_width (GTK_CONTAINER (self->priv->output_box), 12);
label = gtk_label_new (_("Output"));
gtk_notebook_append_page (GTK_NOTEBOOK (self->priv->notebook),
self->priv->output_box,
label);
box = gtk_frame_new (_("C_hoose a device for sound output:"));
label = gtk_frame_get_label_widget (GTK_FRAME (box));
_gtk_label_make_bold (GTK_LABEL (label));
gtk_label_set_use_underline (GTK_LABEL (label), TRUE);
gtk_frame_set_shadow_type (GTK_FRAME (box), GTK_SHADOW_NONE);
gtk_box_pack_start (GTK_BOX (self->priv->output_box), box, TRUE, TRUE, 0);
alignment = gtk_alignment_new (0, 0, 1, 1);
gtk_container_add (GTK_CONTAINER (box), alignment);
gtk_alignment_set_padding (GTK_ALIGNMENT (alignment), 6, 0, 0, 0);
self->priv->output_treeview = create_ui_device_treeview (self,
G_CALLBACK (on_output_selection_changed));
gtk_label_set_mnemonic_widget (GTK_LABEL (label), self->priv->output_treeview);
box = gtk_scrolled_window_new (NULL, NULL);
gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (box),
GTK_POLICY_NEVER,
GTK_POLICY_AUTOMATIC);
gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (box),
GTK_SHADOW_IN);
gtk_container_add (GTK_CONTAINER (box), self->priv->output_treeview);
gtk_scrolled_window_set_min_content_height (GTK_SCROLLED_WINDOW (box), 150);
gtk_container_add (GTK_CONTAINER (alignment), box);
box = gtk_frame_new (_("Settings for the selected device:"));
label = gtk_frame_get_label_widget (GTK_FRAME (box));
_gtk_label_make_bold (GTK_LABEL (label));
gtk_frame_set_shadow_type (GTK_FRAME (box), GTK_SHADOW_NONE);
gtk_box_pack_start (GTK_BOX (self->priv->output_box), box, FALSE, FALSE, 12);
self->priv->output_settings_box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0);
gtk_container_add (GTK_CONTAINER (box), self->priv->output_settings_box);
/* Input page */
self->priv->input_box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 12);
gtk_container_set_border_width (GTK_CONTAINER (self->priv->input_box), 12);
label = gtk_label_new (_("Input"));
gtk_notebook_append_page (GTK_NOTEBOOK (self->priv->notebook),
self->priv->input_box,
label);
self->priv->input_bar = create_bar (self, TRUE, TRUE);
gvc_channel_bar_set_name (GVC_CHANNEL_BAR (self->priv->input_bar),
_("_Input volume:"));
gvc_channel_bar_set_low_icon_name (GVC_CHANNEL_BAR (self->priv->input_bar),
"cin-audio-input-microphone-low-symbolic");
gvc_channel_bar_set_high_icon_name (GVC_CHANNEL_BAR (self->priv->input_bar),
"cin-audio-input-microphone-high-symbolic");
gtk_widget_set_sensitive (self->priv->input_bar, FALSE);
alignment = gtk_alignment_new (0, 0, 1, 1);
gtk_alignment_set_padding (GTK_ALIGNMENT (alignment), 6, 0, 0, 0);
gtk_container_add (GTK_CONTAINER (alignment), self->priv->input_bar);
gtk_box_pack_start (GTK_BOX (self->priv->input_box),
alignment,
FALSE, FALSE, 0);
box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 6);
gtk_box_pack_start (GTK_BOX (self->priv->input_box),
box,
FALSE, FALSE, 6);
sbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 6);
gtk_box_pack_start (GTK_BOX (box),
sbox,
FALSE, FALSE, 0);
label = gtk_label_new (_("Input level:"));
gtk_box_pack_start (GTK_BOX (sbox),
label,
FALSE, FALSE, 0);
if (self->priv->size_group != NULL)
gtk_size_group_add_widget (self->priv->size_group, sbox);
self->priv->input_level_bar = gvc_level_bar_new ();
gvc_level_bar_set_orientation (GVC_LEVEL_BAR (self->priv->input_level_bar),
GTK_ORIENTATION_HORIZONTAL);
gvc_level_bar_set_scale (GVC_LEVEL_BAR (self->priv->input_level_bar),
GVC_LEVEL_SCALE_LINEAR);
gtk_box_pack_start (GTK_BOX (box),
self->priv->input_level_bar,
TRUE, TRUE, 6);
ebox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 6);
gtk_box_pack_start (GTK_BOX (box),
ebox,
FALSE, FALSE, 0);
if (self->priv->size_group != NULL)
gtk_size_group_add_widget (self->priv->size_group, ebox);
self->priv->input_settings_box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 6);
gtk_box_pack_start (GTK_BOX (self->priv->input_box),
self->priv->input_settings_box,
FALSE, FALSE, 0);
box = gtk_frame_new (_("C_hoose a device for sound input:"));
label = gtk_frame_get_label_widget (GTK_FRAME (box));
_gtk_label_make_bold (GTK_LABEL (label));
gtk_label_set_use_underline (GTK_LABEL (label), TRUE);
gtk_frame_set_shadow_type (GTK_FRAME (box), GTK_SHADOW_NONE);
gtk_box_pack_start (GTK_BOX (self->priv->input_box), box, TRUE, TRUE, 0);
alignment = gtk_alignment_new (0, 0, 1, 1);
gtk_container_add (GTK_CONTAINER (box), alignment);
gtk_alignment_set_padding (GTK_ALIGNMENT (alignment), 6, 0, 0, 0);
self->priv->input_treeview = create_ui_device_treeview (self,
G_CALLBACK (on_input_selection_changed));
gtk_label_set_mnemonic_widget (GTK_LABEL (label), self->priv->input_treeview);
box = gtk_scrolled_window_new (NULL, NULL);
gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (box),
GTK_POLICY_NEVER,
GTK_POLICY_AUTOMATIC);
gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (box),
GTK_SHADOW_IN);
gtk_container_add (GTK_CONTAINER (box), self->priv->input_treeview);
gtk_container_add (GTK_CONTAINER (alignment), box);
/* Effects page */
self->priv->sound_effects_box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 6);
gtk_container_set_border_width (GTK_CONTAINER (self->priv->sound_effects_box), 12);
label = gtk_label_new (_("Sound Effects"));
gtk_notebook_append_page (GTK_NOTEBOOK (self->priv->notebook),
self->priv->sound_effects_box,
label);
self->priv->effects_bar = create_bar (self, TRUE, TRUE);
gvc_channel_bar_set_name (GVC_CHANNEL_BAR (self->priv->effects_bar),
_("_Alert volume:"));
gtk_widget_set_sensitive (self->priv->effects_bar, FALSE);
gtk_box_pack_start (GTK_BOX (self->priv->sound_effects_box),
self->priv->effects_bar, FALSE, FALSE, 0);
self->priv->sound_theme_chooser = gvc_sound_theme_chooser_new ();
gtk_box_pack_start (GTK_BOX (self->priv->sound_effects_box),
self->priv->sound_theme_chooser,
TRUE, TRUE, 6);
/* Applications */
self->priv->applications_box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 12);
gtk_container_set_border_width (GTK_CONTAINER (self->priv->applications_box), 12);
label = gtk_label_new (_("Applications"));
gtk_notebook_append_page (GTK_NOTEBOOK (self->priv->notebook),
self->priv->applications_box,
label);
self->priv->no_apps_label = gtk_label_new (_("No application is currently playing or recording audio."));
gtk_box_pack_start (GTK_BOX (self->priv->applications_box),
self->priv->no_apps_label,
TRUE, TRUE, 0);
g_signal_connect (self->priv->mixer_control,
"output-added",
G_CALLBACK (on_control_output_added),
self);
g_signal_connect (self->priv->mixer_control,
"output-removed",
G_CALLBACK (on_control_output_removed),
self);
g_signal_connect (self->priv->mixer_control,
"input-added",
G_CALLBACK (on_control_input_added),
self);
g_signal_connect (self->priv->mixer_control,
"input-removed",
G_CALLBACK (on_control_input_removed),
self);
g_signal_connect (self->priv->mixer_control,
"stream-added",
G_CALLBACK (on_control_stream_added),
self);
g_signal_connect (self->priv->mixer_control,
"stream-removed",
G_CALLBACK (on_control_stream_removed),
self);
gtk_widget_show_all (main_vbox);
streams = gvc_mixer_control_get_streams (self->priv->mixer_control);
for (l = streams; l != NULL; l = l->next) {
stream = l->data;
add_stream (self, stream);
}
g_slist_free (streams);
return object;
}
static void
gvc_mixer_dialog_dispose (GObject *object)
{
GvcMixerDialog *dialog = GVC_MIXER_DIALOG (object);
if (dialog->priv->mixer_control != NULL) {
g_signal_handlers_disconnect_by_func (dialog->priv->mixer_control,
on_control_output_added,
dialog);
g_signal_handlers_disconnect_by_func (dialog->priv->mixer_control,
on_control_output_removed,
dialog);
g_signal_handlers_disconnect_by_func (dialog->priv->mixer_control,
on_control_input_added,
dialog);
g_signal_handlers_disconnect_by_func (dialog->priv->mixer_control,
on_control_input_removed,
dialog);
g_signal_handlers_disconnect_by_func (dialog->priv->mixer_control,
on_control_active_input_update,
dialog);
g_signal_handlers_disconnect_by_func (dialog->priv->mixer_control,
on_control_active_output_update,
dialog);
g_signal_handlers_disconnect_by_func (dialog->priv->mixer_control,
on_control_stream_added,
dialog);
g_signal_handlers_disconnect_by_func (dialog->priv->mixer_control,
on_control_stream_removed,
dialog);
g_object_unref (dialog->priv->mixer_control);
dialog->priv->mixer_control = NULL;
}
if (dialog->priv->bars != NULL) {
g_hash_table_destroy (dialog->priv->bars);
dialog->priv->bars = NULL;
}
G_OBJECT_CLASS (gvc_mixer_dialog_parent_class)->dispose (object);
}
static void
gvc_mixer_dialog_class_init (GvcMixerDialogClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->constructor = gvc_mixer_dialog_constructor;
object_class->dispose = gvc_mixer_dialog_dispose;
object_class->finalize = gvc_mixer_dialog_finalize;
object_class->set_property = gvc_mixer_dialog_set_property;
object_class->get_property = gvc_mixer_dialog_get_property;
g_object_class_install_property (object_class,
PROP_MIXER_CONTROL,
g_param_spec_object ("mixer-control",
"mixer control",
"mixer control",
GVC_TYPE_MIXER_CONTROL,
G_PARAM_READWRITE|G_PARAM_CONSTRUCT));
g_type_class_add_private (klass, sizeof (GvcMixerDialogPrivate));
}
static void
gvc_mixer_dialog_init (GvcMixerDialog *dialog)
{
dialog->priv = GVC_MIXER_DIALOG_GET_PRIVATE (dialog);
dialog->priv->bars = g_hash_table_new (NULL, NULL);
dialog->priv->size_group = gtk_size_group_new (GTK_SIZE_GROUP_HORIZONTAL);
}
static void
gvc_mixer_dialog_finalize (GObject *object)
{
GvcMixerDialog *mixer_dialog;
g_return_if_fail (object != NULL);
g_return_if_fail (GVC_IS_MIXER_DIALOG (object));
mixer_dialog = GVC_MIXER_DIALOG (object);
g_return_if_fail (mixer_dialog->priv != NULL);
G_OBJECT_CLASS (gvc_mixer_dialog_parent_class)->finalize (object);
}
GvcMixerDialog *
gvc_mixer_dialog_new (GvcMixerControl *control)
{
GObject *dialog;
dialog = g_object_new (GVC_TYPE_MIXER_DIALOG,
"mixer-control", control,
NULL);
return GVC_MIXER_DIALOG (dialog);
}
enum {
PAGE_OUTPUT,
PAGE_INPUT,
PAGE_EVENTS,
PAGE_APPLICATIONS
};
gboolean
gvc_mixer_dialog_set_page (GvcMixerDialog *self,
const char *page)
{
guint num;
g_return_val_if_fail (self != NULL, FALSE);
num = PAGE_OUTPUT;
if (g_str_equal (page, "effects"))
num = PAGE_EVENTS;
else if (g_str_equal (page, "input"))
num = PAGE_INPUT;
else if (g_str_equal (page, "output"))
num = PAGE_OUTPUT;
else if (g_str_equal (page, "applications"))
num = PAGE_APPLICATIONS;
gtk_notebook_set_current_page (GTK_NOTEBOOK (self->priv->notebook), num);
return TRUE;
}
|
376 | ./cinnamon-control-center/panels/unused/info/gsd-disk-space-helper.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
* vim: set et sw=8 ts=8:
*
* Copyright (c) 2008, Novell, Inc.
* Copyright (c) 2012, Red Hat, Inc.
*
* Authors: Vincent Untz <[email protected]>
* Bastien Nocera <[email protected]>
*
* 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.
*
*/
#include "config.h"
#include <glib.h>
#include <gio/gio.h>
#include "gsd-disk-space-helper.h"
gboolean
gsd_should_ignore_unix_mount (GUnixMountEntry *mount)
{
const char *fs, *device;
guint i;
/* This is borrowed from GLib and used as a way to determine
* which mounts we should ignore by default. GLib doesn't
* expose this in a way that allows it to be used for this
* purpose
*/
/* We also ignore network filesystems */
const gchar *ignore_fs[] = {
"adfs",
"afs",
"auto",
"autofs",
"autofs4",
"cifs",
"cxfs",
"devfs",
"devpts",
"ecryptfs",
"fdescfs",
"gfs",
"gfs2",
"kernfs",
"linprocfs",
"linsysfs",
"lustre",
"lustre_lite",
"ncpfs",
"nfs",
"nfs4",
"nfsd",
"ocfs2",
"proc",
"procfs",
"ptyfs",
"rpc_pipefs",
"selinuxfs",
"smbfs",
"sysfs",
"tmpfs",
"usbfs",
"zfs",
NULL
};
const gchar *ignore_devices[] = {
"none",
"sunrpc",
"devpts",
"nfsd",
"/dev/loop",
"/dev/vn",
NULL
};
fs = g_unix_mount_get_fs_type (mount);
device = g_unix_mount_get_device_path (mount);
for (i = 0; ignore_fs[i] != NULL; i++)
if (g_str_equal (ignore_fs[i], fs))
return TRUE;
for (i = 0; ignore_devices[i] != NULL; i++)
if (g_str_equal (ignore_devices[i], device))
return TRUE;
return FALSE;
}
gboolean
gsd_is_removable_mount (GUnixMountEntry *mount)
{
const char *mount_path;
char *path;
mount_path = g_unix_mount_get_mount_path (mount);
if (mount_path == NULL)
return FALSE;
path = g_strdup_printf ("/run/media/%s", g_get_user_name ());
if (g_str_has_prefix (mount_path, path)) {
g_free (path);
return TRUE;
}
g_free (path);
return FALSE;
}
|
377 | ./cinnamon-control-center/panels/unused/info/test-hostname.c | #include "config.h"
#include <glib.h>
#include <glib/gi18n.h>
#include <locale.h>
#include "hostname-helper.h"
int main (int argc, char **argv)
{
char *result;
guint i;
char *contents;
char **lines;
char *locale;
/* Running in some locales will
* break the tests as "├╝" will be transliterated to
* "ue" in de_DE, and 'u"' in the C locale.
*
* Work around that by forcing en_US with UTF-8 in
* our tests
* https://bugzilla.gnome.org/show_bug.cgi?id=650342 */
locale = setlocale (LC_ALL, "en_US.UTF-8");
if (locale == NULL) {
g_debug("Missing en_US.UTF-8 locale, ignoring test.");
return 0;
}
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
if (g_file_get_contents (argv[1], &contents, NULL, NULL) == FALSE) {
g_warning ("Failed to load '%s'", argv[1]);
return 1;
}
lines = g_strsplit (contents, "\n", -1);
if (lines == NULL) {
g_warning ("Test file is empty");
return 1;
}
for (i = 0; lines[i] != NULL; i++) {
char *utf8;
char **items;
if (*lines[i] == '#')
continue;
if (*lines[i] == '\0')
break;
items = g_strsplit (lines[i], "\t", -1);
utf8 = g_locale_from_utf8 (items[0], -1, NULL, NULL, NULL);
result = pretty_hostname_to_static (items[0], FALSE);
if (g_strcmp0 (result, items[2]) != 0)
g_error ("Result for '%s' doesn't match '%s' (got: '%s')",
utf8, items[2], result);
else
g_debug ("Result for '%s' matches '%s'",
utf8, result);
g_free (result);
g_free (utf8);
result = pretty_hostname_to_static (items[0], TRUE);
utf8 = g_locale_from_utf8 (items[0], -1, NULL, NULL, NULL);
if (g_strcmp0 (result, items[1]) != 0)
g_error ("Result for '%s' doesn't match '%s' (got: '%s')",
utf8, items[1], result);
else
g_debug ("Result for '%s' matches '%s'",
utf8, result);
g_free (result);
g_free (utf8);
g_strfreev (items);
}
g_strfreev (lines);
return 0;
}
|
378 | ./cinnamon-control-center/panels/unused/info/info-module.c | /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
*
* Copyright (C) 2010 Red Hat, Inc
*
* 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.
*
*
*/
#include <config.h>
#include "cc-info-panel.h"
#include <glib/gi18n-lib.h>
void
g_io_module_load (GIOModule *module)
{
bindtextdomain (GETTEXT_PACKAGE, CINNAMONLOCALEDIR);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
/* register the panel */
cc_info_panel_register (module);
}
void
g_io_module_unload (GIOModule *module)
{
}
|
379 | ./cinnamon-control-center/panels/unused/info/hostname-helper.c | /*
* Copyright (C) 2011 Red Hat, Inc
*
* 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.
*
*/
#include <glib.h>
#include <string.h>
#include "hostname-helper.h"
static char *
allowed_chars (void)
{
GString *s;
char i;
s = g_string_new (NULL);
for (i = 'a'; i <= 'z'; i++)
g_string_append_c (s, i);
for (i = 'A'; i <= 'Z'; i++)
g_string_append_c (s, i);
for (i = '0'; i <= '9'; i++)
g_string_append_c (s, i);
g_string_append_c (s, '-');
return g_string_free (s, FALSE);
}
static char *
remove_leading_dashes (char *input)
{
char *start;
for (start = input; *start && (*start == '-'); start++)
;
g_memmove (input, start, strlen (start) + 1);
return input;
}
static gboolean
is_empty (const char *input)
{
if (input == NULL ||
*input == '\0')
return TRUE;
return FALSE;
}
static char *
remove_trailing_dashes (char *input)
{
int len;
len = strlen (input);
while (len--) {
if (input[len] == '-')
input[len] = '\0';
else
break;
}
return input;
}
static char *
remove_apostrophes (char *input)
{
char *apo;
while ((apo = strchr (input, '\'')) != NULL)
g_memmove (apo, apo + 1, strlen (apo));
return input;
}
static char *
remove_duplicate_dashes (char *input)
{
char *dashes;
while ((dashes = strstr (input, "--")) != NULL)
g_memmove (dashes, dashes + 1, strlen (dashes));
return input;
}
#define CHECK if (is_empty (result)) goto bail
char *
pretty_hostname_to_static (const char *pretty,
gboolean for_display)
{
char *result;
char *valid_chars;
g_return_val_if_fail (pretty != NULL, NULL);
g_return_val_if_fail (g_utf8_validate (pretty, -1, NULL), NULL);
g_debug ("Input: '%s'", pretty);
/* Transform the pretty hostname to ASCII */
result = g_convert (pretty,
-1,
"ASCII//TRANSLIT//IGNORE",
"UTF-8",
NULL,
NULL,
NULL);
g_debug ("\ttranslit: '%s'", result);
CHECK;
/* Remove apostrophes */
result = remove_apostrophes (result);
g_debug ("\tapostrophes: '%s'", result);
CHECK;
/* Remove all the not-allowed chars */
valid_chars = allowed_chars ();
result = g_strcanon (result, valid_chars, '-');
g_free (valid_chars);
g_debug ("\tcanon: '%s'", result);
CHECK;
/* Remove the leading dashes */
result = remove_leading_dashes (result);
g_debug ("\tleading: '%s'", result);
CHECK;
/* Remove trailing dashes */
result = remove_trailing_dashes (result);
g_debug ("\ttrailing: '%s'", result);
CHECK;
/* Remove duplicate dashes */
result = remove_duplicate_dashes (result);
g_debug ("\tduplicate: '%s'", result);
CHECK;
/* Lower case */
if (!for_display) {
char *tmp;
tmp = g_ascii_strdown (result, -1);
g_free (result);
result = tmp;
}
return result;
bail:
g_free (result);
return g_strdup ("localhost");
}
#undef CHECK
|
380 | ./cinnamon-control-center/panels/unused/info/cc-info-panel.c | /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
*
* Copyright (C) 2010 Red Hat, Inc
* Copyright (C) 2008 William Jon McCann <[email protected]>
*
* 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.
*
*/
#include <config.h>
#include "cc-info-panel.h"
#include <polkit/polkit.h>
#include <glib.h>
#include <glib/gi18n.h>
#include <gio/gio.h>
#include <gio/gunixmounts.h>
#include <gio/gdesktopappinfo.h>
#include <glibtop/fsusage.h>
#include <glibtop/mountlist.h>
#include <glibtop/mem.h>
#include <glibtop/sysinfo.h>
#include "hostname-helper.h"
#include "gsd-disk-space-helper.h"
/* Autorun options */
#define PREF_MEDIA_AUTORUN_NEVER "autorun-never"
#define PREF_MEDIA_AUTORUN_X_CONTENT_START_APP "autorun-x-content-start-app"
#define PREF_MEDIA_AUTORUN_X_CONTENT_IGNORE "autorun-x-content-ignore"
#define PREF_MEDIA_AUTORUN_X_CONTENT_OPEN_FOLDER "autorun-x-content-open-folder"
#define CUSTOM_ITEM_ASK "cc-item-ask"
#define CUSTOM_ITEM_DO_NOTHING "cc-item-do-nothing"
#define CUSTOM_ITEM_OPEN_FOLDER "cc-item-open-folder"
#define MEDIA_HANDLING_SCHEMA "org.gnome.desktop.media-handling"
/* Session */
#define GNOME_SESSION_MANAGER_SCHEMA "org.gnome.desktop.session"
#define KEY_SESSION_NAME "session-name"
#define WID(w) (GtkWidget *) gtk_builder_get_object (self->priv->builder, w)
CC_PANEL_REGISTER (CcInfoPanel, cc_info_panel)
#define INFO_PANEL_PRIVATE(o) \
(G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_INFO_PANEL, CcInfoPanelPrivate))
typedef struct {
/* Will be one of the other two below, or "Unknown" */
const char *hardware_string;
char *xorg_vesa_hardware;
char *glx_renderer;
} GraphicsData;
typedef enum {
PK_NOT_AVAILABLE,
UPDATES_AVAILABLE,
UPDATES_NOT_AVAILABLE,
CHECKING_UPDATES
} UpdatesState;
typedef struct
{
const char *content_type;
const char *label;
/* A pattern used to filter supported mime types
when changing preferred applications. NULL
means no other types should be changed */
const char *extra_type_filter;
} DefaultAppData;
struct _CcInfoPanelPrivate
{
GtkBuilder *builder;
char *gnome_version;
char *gnome_distributor;
char *gnome_date;
UpdatesState updates_state;
gboolean is_fallback;
/* Free space */
GList *primary_mounts;
guint64 total_bytes;
GCancellable *cancellable;
/* Media */
GSettings *media_settings;
GtkWidget *other_application_combo;
GDBusConnection *session_bus;
GDBusProxy *pk_proxy;
GDBusProxy *pk_transaction_proxy;
GDBusProxy *hostnamed_proxy;
GSettings *session_settings;
GraphicsData *graphics_data;
};
static void get_primary_disc_info_start (CcInfoPanel *self);
static void refresh_update_button (CcInfoPanel *self);
typedef struct
{
char *major;
char *minor;
char *micro;
char *distributor;
char *date;
char **current;
} VersionData;
static void
version_start_element_handler (GMarkupParseContext *ctx,
const char *element_name,
const char **attr_names,
const char **attr_values,
gpointer user_data,
GError **error)
{
VersionData *data = user_data;
if (g_str_equal (element_name, "platform"))
data->current = &data->major;
else if (g_str_equal (element_name, "minor"))
data->current = &data->minor;
else if (g_str_equal (element_name, "micro"))
data->current = &data->micro;
else if (g_str_equal (element_name, "distributor"))
data->current = &data->distributor;
else if (g_str_equal (element_name, "date"))
data->current = &data->date;
else
data->current = NULL;
}
static void
version_end_element_handler (GMarkupParseContext *ctx,
const char *element_name,
gpointer user_data,
GError **error)
{
VersionData *data = user_data;
data->current = NULL;
}
static void
version_text_handler (GMarkupParseContext *ctx,
const char *text,
gsize text_len,
gpointer user_data,
GError **error)
{
VersionData *data = user_data;
if (data->current != NULL)
*data->current = g_strstrip (g_strdup (text));
}
static gboolean
load_gnome_version (char **version,
char **distributor,
char **date)
{
GMarkupParser version_parser = {
version_start_element_handler,
version_end_element_handler,
version_text_handler,
NULL,
NULL,
};
GError *error;
GMarkupParseContext *ctx;
char *contents;
gsize length;
VersionData *data;
gboolean ret;
ret = FALSE;
error = NULL;
if (!g_file_get_contents (DATADIR "/cinnamon/cinnamon-version.xml",
&contents,
&length,
&error))
return FALSE;
data = g_new0 (VersionData, 1);
ctx = g_markup_parse_context_new (&version_parser, 0, data, NULL);
if (!g_markup_parse_context_parse (ctx, contents, length, &error))
{
g_warning ("Invalid version file: '%s'", error->message);
}
else
{
if (version != NULL)
*version = g_strdup_printf ("%s.%s.%s", data->major, data->minor, data->micro);
if (distributor != NULL)
*distributor = g_strdup (data->distributor);
if (date != NULL)
*date = g_strdup (data->date);
ret = TRUE;
}
g_markup_parse_context_free (ctx);
g_free (data->major);
g_free (data->minor);
g_free (data->micro);
g_free (data->distributor);
g_free (data->date);
g_free (data);
g_free (contents);
return ret;
};
typedef struct
{
char *regex;
char *replacement;
} ReplaceStrings;
static char *
prettify_info (const char *info)
{
char *pretty;
int i;
static const ReplaceStrings rs[] = {
{ "Mesa DRI ", ""},
{ "Intel[(]R[)]", "Intel<sup>\302\256</sup>"},
{ "Core[(]TM[)]", "Core<sup>\342\204\242</sup>"},
{ "Atom[(]TM[)]", "Atom<sup>\342\204\242</sup>"},
{ "Graphics Controller", "Graphics"},
};
pretty = g_markup_escape_text (info, -1);
for (i = 0; i < G_N_ELEMENTS (rs); i++)
{
GError *error;
GRegex *re;
char *new;
error = NULL;
re = g_regex_new (rs[i].regex, 0, 0, &error);
if (re == NULL)
{
g_warning ("Error building regex: %s", error->message);
g_error_free (error);
continue;
}
new = g_regex_replace_literal (re,
pretty,
-1,
0,
rs[i].replacement,
0,
&error);
g_regex_unref (re);
if (error != NULL)
{
g_warning ("Error replacing %s: %s", rs[i].regex, error->message);
g_error_free (error);
continue;
}
g_free (pretty);
pretty = new;
}
return pretty;
}
static void
graphics_data_free (GraphicsData *gdata)
{
g_free (gdata->xorg_vesa_hardware);
g_free (gdata->glx_renderer);
g_slice_free (GraphicsData, gdata);
}
static char *
get_graphics_data_glx_renderer (void)
{
GError *error;
GRegex *re;
GMatchInfo *match_info;
char *output;
char *result;
GString *info;
info = g_string_new (NULL);
error = NULL;
g_spawn_command_line_sync ("glxinfo -l", &output, NULL, NULL, &error);
if (error != NULL)
{
g_warning ("Unable to get graphics info: %s", error->message);
g_error_free (error);
return NULL;
}
re = g_regex_new ("^OpenGL renderer string: (.+)$", G_REGEX_MULTILINE, 0, &error);
if (re == NULL)
{
g_warning ("Error building regex: %s", error->message);
g_error_free (error);
goto out;
}
g_regex_match (re, output, 0, &match_info);
while (g_match_info_matches (match_info))
{
char *device;
device = g_match_info_fetch (match_info, 1);
g_string_append_printf (info, "%s ", device);
g_free (device);
g_match_info_next (match_info, NULL);
}
g_match_info_free (match_info);
g_regex_unref (re);
out:
g_free (output);
result = prettify_info (info->str);
g_string_free (info, TRUE);
return result;
}
static char *
get_graphics_data_xorg_vesa_hardware (void)
{
char *display_num;
char *log_path;
char *log_contents;
gsize log_len;
GError *error = NULL;
GRegex *re;
GMatchInfo *match;
char *result = NULL;
{
const char *display;
display = g_getenv ("DISPLAY");
if (!display)
return NULL;
re = g_regex_new ("^:([0-9]+)", 0, 0, NULL);
g_assert (re != NULL);
g_regex_match (re, display, 0, &match);
if (!g_match_info_matches (match))
{
g_regex_unref (re);
g_match_info_free (match);
return NULL;
}
display_num = g_match_info_fetch (match, 1);
g_regex_unref (re);
re = NULL;
g_match_info_free (match);
match = NULL;
}
log_path = g_strdup_printf ("/var/log/Xorg.%s.log", display_num);
g_free (display_num);
log_contents = NULL;
g_file_get_contents (log_path, &log_contents, &log_len, &error);
g_free (log_path);
if (!log_contents)
return NULL;
re = g_regex_new ("VESA VBE OEM Product: (.*)$", G_REGEX_MULTILINE, 0, NULL);
g_assert (re != NULL);
g_regex_match (re, log_contents, 0, &match);
if (g_match_info_matches (match))
{
char *tmp;
char *pretty_tmp;
tmp = g_match_info_fetch (match, 1);
pretty_tmp = prettify_info (tmp);
g_free (tmp);
/* Translators: VESA is an techncial acronym, don't translate it. */
result = g_strdup_printf (_("VESA: %s"), pretty_tmp);
g_free (pretty_tmp);
}
g_match_info_free (match);
g_regex_unref (re);
return result;
}
static GraphicsData *
get_graphics_data (void)
{
GraphicsData *result;
result = g_slice_new0 (GraphicsData);
result->glx_renderer = get_graphics_data_glx_renderer ();
result->xorg_vesa_hardware = get_graphics_data_xorg_vesa_hardware ();
if (result->xorg_vesa_hardware != NULL)
result->hardware_string = result->xorg_vesa_hardware;
else if (result->glx_renderer != NULL)
result->hardware_string = result->glx_renderer;
else
result->hardware_string = _("Unknown");
return result;
}
static gboolean
get_current_is_fallback (CcInfoPanel *self)
{
GError *error;
GVariant *reply;
GVariant *reply_str;
gboolean is_fallback;
error = NULL;
if (!(reply = g_dbus_connection_call_sync (self->priv->session_bus,
"org.gnome.SessionManager",
"/org/gnome/SessionManager",
"org.freedesktop.DBus.Properties",
"Get",
g_variant_new ("(ss)", "org.gnome.SessionManager", "session-name"),
(GVariantType*)"(v)",
0,
-1,
NULL, &error)))
{
g_warning ("Failed to get fallback mode: %s", error->message);
g_clear_error (&error);
return FALSE;
}
g_variant_get (reply, "(v)", &reply_str);
is_fallback = g_strcmp0 ("gnome-fallback", g_variant_get_string (reply_str, NULL)) == 0;
g_variant_unref (reply_str);
g_variant_unref (reply);
return is_fallback;
}
static void
cc_info_panel_get_property (GObject *object,
guint property_id,
GValue *value,
GParamSpec *pspec)
{
switch (property_id)
{
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}
}
static void
cc_info_panel_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec)
{
switch (property_id)
{
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}
}
static void
cc_info_panel_dispose (GObject *object)
{
CcInfoPanelPrivate *priv = CC_INFO_PANEL (object)->priv;
if (priv->builder != NULL)
{
g_object_unref (priv->builder);
priv->builder = NULL;
}
if (priv->pk_proxy != NULL)
{
g_object_unref (priv->pk_proxy);
priv->pk_proxy = NULL;
}
if (priv->pk_transaction_proxy != NULL)
{
g_object_unref (priv->pk_transaction_proxy);
priv->pk_transaction_proxy = NULL;
}
if (priv->graphics_data != NULL)
{
graphics_data_free (priv->graphics_data);
priv->graphics_data = NULL;
}
G_OBJECT_CLASS (cc_info_panel_parent_class)->dispose (object);
}
static void
cc_info_panel_finalize (GObject *object)
{
CcInfoPanelPrivate *priv = CC_INFO_PANEL (object)->priv;
if (priv->cancellable != NULL)
{
g_cancellable_cancel (priv->cancellable);
priv->cancellable = NULL;
}
g_free (priv->gnome_version);
g_free (priv->gnome_date);
g_free (priv->gnome_distributor);
if (priv->hostnamed_proxy != NULL)
{
g_object_unref (priv->hostnamed_proxy);
priv->hostnamed_proxy = NULL;
}
if (priv->media_settings != NULL)
{
g_object_unref (priv->media_settings);
priv->media_settings = NULL;
}
if (priv->session_settings != NULL)
{
g_object_unref (priv->session_settings);
priv->session_settings = NULL;
}
G_OBJECT_CLASS (cc_info_panel_parent_class)->finalize (object);
}
static void
cc_info_panel_class_init (CcInfoPanelClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
g_type_class_add_private (klass, sizeof (CcInfoPanelPrivate));
object_class->get_property = cc_info_panel_get_property;
object_class->set_property = cc_info_panel_set_property;
object_class->dispose = cc_info_panel_dispose;
object_class->finalize = cc_info_panel_finalize;
}
static char *
get_os_type (void)
{
int bits;
if (GLIB_SIZEOF_VOID_P == 8)
bits = 64;
else
bits = 32;
/* translators: This is the type of architecture, for example:
* "64-bit" or "32-bit" */
return g_strdup_printf (_("%d-bit"), bits);
}
static void
query_done (GFile *file,
GAsyncResult *res,
CcInfoPanel *self)
{
GFileInfo *info;
GError *error = NULL;
self->priv->cancellable = NULL;
info = g_file_query_filesystem_info_finish (file, res, &error);
if (info != NULL)
{
self->priv->total_bytes += g_file_info_get_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE);
g_object_unref (info);
}
else
{
char *path;
path = g_file_get_path (file);
g_warning ("Failed to get filesystem free space for '%s': %s", path, error->message);
g_free (path);
g_error_free (error);
}
/* And onto the next element */
get_primary_disc_info_start (self);
}
static void
get_primary_disc_info_start (CcInfoPanel *self)
{
GUnixMountEntry *mount;
GFile *file;
if (self->priv->primary_mounts == NULL)
{
char *size;
GtkWidget *widget;
size = g_format_size (self->priv->total_bytes);
widget = WID ("disk_label");
gtk_label_set_text (GTK_LABEL (widget), size);
g_free (size);
return;
}
mount = self->priv->primary_mounts->data;
self->priv->primary_mounts = g_list_remove (self->priv->primary_mounts, mount);
file = g_file_new_for_path (g_unix_mount_get_mount_path (mount));
g_unix_mount_free (mount);
self->priv->cancellable = g_cancellable_new ();
g_file_query_filesystem_info_async (file,
G_FILE_ATTRIBUTE_FILESYSTEM_SIZE,
0,
self->priv->cancellable,
(GAsyncReadyCallback) query_done,
self);
g_object_unref (file);
}
static void
get_primary_disc_info (CcInfoPanel *self)
{
GList *points;
GList *p;
points = g_unix_mount_points_get (NULL);
for (p = points; p != NULL; p = p->next)
{
GUnixMountEntry *mount = p->data;
const char *mount_path;
mount_path = g_unix_mount_get_mount_path (mount);
if (gsd_should_ignore_unix_mount (mount) ||
gsd_is_removable_mount (mount) ||
g_str_has_prefix (mount_path, "/media/") ||
g_str_has_prefix (mount_path, g_get_home_dir ()))
{
g_unix_mount_free (mount);
continue;
}
self->priv->primary_mounts = g_list_prepend (self->priv->primary_mounts, mount);
}
g_list_free (points);
get_primary_disc_info_start (self);
}
static char *
remove_duplicate_whitespace (const char *old)
{
char *new;
GRegex *re;
GError *error;
error = NULL;
re = g_regex_new ("[ \t\n\r]+", G_REGEX_MULTILINE, 0, &error);
if (re == NULL)
{
g_warning ("Error building regex: %s", error->message);
g_error_free (error);
return g_strdup (old);
}
new = g_regex_replace (re,
old,
-1,
0,
" ",
0,
&error);
g_regex_unref (re);
if (new == NULL)
{
g_warning ("Error replacing string: %s", error->message);
g_error_free (error);
return g_strdup (old);
}
return new;
}
static char *
get_cpu_info (const glibtop_sysinfo *info)
{
GHashTable *counts;
GString *cpu;
char *ret;
GHashTableIter iter;
gpointer key, value;
int i;
int j;
counts = g_hash_table_new (g_str_hash, g_str_equal);
/* count duplicates */
for (i = 0; i != info->ncpu; ++i)
{
const char * const keys[] = { "model name", "cpu" };
char *model;
int *count;
model = NULL;
for (j = 0; model == NULL && j != G_N_ELEMENTS (keys); ++j)
{
model = g_hash_table_lookup (info->cpuinfo[i].values,
keys[j]);
}
if (model == NULL)
model = _("Unknown model");
count = g_hash_table_lookup (counts, model);
if (count == NULL)
g_hash_table_insert (counts, model, GINT_TO_POINTER (1));
else
g_hash_table_replace (counts, model, GINT_TO_POINTER (GPOINTER_TO_INT (count) + 1));
}
cpu = g_string_new (NULL);
g_hash_table_iter_init (&iter, counts);
while (g_hash_table_iter_next (&iter, &key, &value))
{
char *stripped;
int count;
count = GPOINTER_TO_INT (value);
stripped = remove_duplicate_whitespace ((const char *)key);
if (count > 1)
g_string_append_printf (cpu, "%s \303\227 %d ", stripped, count);
else
g_string_append_printf (cpu, "%s ", stripped);
g_free (stripped);
}
g_hash_table_destroy (counts);
ret = prettify_info (cpu->str);
g_string_free (cpu, TRUE);
return ret;
}
static void
on_section_changed (GtkTreeSelection *selection,
gpointer data)
{
CcInfoPanel *self = CC_INFO_PANEL (data);
GtkTreeIter iter;
GtkTreeModel *model;
GtkTreePath *path;
gint *indices;
int index;
if (!gtk_tree_selection_get_selected (selection, &model, &iter))
return;
path = gtk_tree_model_get_path (model, &iter);
indices = gtk_tree_path_get_indices (path);
index = indices[0];
if (index >= 0)
{
g_object_set (G_OBJECT (WID ("notebook")),
"page", index, NULL);
}
gtk_tree_path_free (path);
}
static gboolean
switch_fallback_get_mapping (GValue *value,
GVariant *variant,
gpointer data)
{
const char *setting;
setting = g_variant_get_string (variant, NULL);
g_value_set_boolean (value, strcmp (setting, "gnome") != 0);
return TRUE;
}
static void
toggle_fallback_warning_label (CcInfoPanel *self,
gboolean visible)
{
GtkWidget *widget;
const char *text;
widget = WID ("graphics_logout_warning_label");
if (self->priv->is_fallback)
text = _("The next login will attempt to use the standard experience.");
else
text = _("The next login will use the fallback mode intended for unsupported graphics hardware.");
gtk_label_set_text (GTK_LABEL (widget), text);
if (visible)
gtk_widget_show (widget);
else
gtk_widget_hide (widget);
}
static GVariant *
switch_fallback_set_mapping (const GValue *value,
const GVariantType *expected_type,
gpointer data)
{
CcInfoPanel *self = data;
gboolean is_set;
is_set = g_value_get_boolean (value);
if (is_set != self->priv->is_fallback)
toggle_fallback_warning_label (self, TRUE);
else
toggle_fallback_warning_label (self, FALSE);
return g_variant_new_string (is_set ? "gnome-fallback" : "gnome");
}
static void
info_panel_setup_graphics (CcInfoPanel *self)
{
GtkWidget *widget;
GtkSwitch *sw;
char *text;
widget = WID ("graphics_driver_label");
gtk_label_set_markup (GTK_LABEL (widget), self->priv->graphics_data->hardware_string);
self->priv->is_fallback = get_current_is_fallback (self);
if (self->priv->is_fallback)
{
/* translators: The hardware is not able to run GNOME 3's
* shell, so we use the GNOME "Fallback" session */
text = g_strdup (C_("Experience", "Fallback"));
}
else
{
/* translators: The hardware is able to run GNOME 3's
* shell, also called "Standard" experience */
text = g_strdup (C_("Experience", "Standard"));
}
widget = WID ("graphics_experience_label");
gtk_label_set_markup (GTK_LABEL (widget), text ? text : "");
g_free (text);
widget = WID ("graphics_fallback_switch_box");
sw = GTK_SWITCH (gtk_switch_new ());
g_settings_bind_with_mapping (self->priv->session_settings, KEY_SESSION_NAME,
sw, "active", 0,
switch_fallback_get_mapping,
switch_fallback_set_mapping, self, NULL);
gtk_box_pack_start (GTK_BOX (widget), GTK_WIDGET (sw), FALSE, FALSE, 0);
gtk_widget_show_all (GTK_WIDGET (sw));
widget = WID ("fallback-label");
gtk_label_set_mnemonic_widget (GTK_LABEL (widget), GTK_WIDGET (sw));
}
static void
default_app_changed (GtkAppChooserButton *button,
CcInfoPanel *self)
{
GAppInfo *info;
GError *error = NULL;
DefaultAppData *app_data;
int i;
info = gtk_app_chooser_get_app_info (GTK_APP_CHOOSER (button));
app_data = g_object_get_data (G_OBJECT (button), "cc-default-app-data");
if (g_app_info_set_as_default_for_type (info, app_data->content_type, &error) == FALSE)
{
g_warning ("Failed to set '%s' as the default application for '%s': %s",
g_app_info_get_name (info), app_data->content_type, error->message);
g_error_free (error);
error = NULL;
}
if (g_str_equal (app_data->content_type, "x-scheme-handler/http"))
{
if (g_app_info_set_as_default_for_type (info, "x-scheme-handler/https", &error) == FALSE)
{
g_warning ("Failed to set '%s' as the default application for '%s': %s",
g_app_info_get_name (info), "x-scheme-handler/https", error->message);
g_error_free (error);
}
}
g_object_unref (info);
}
static void
info_panel_setup_default_app (CcInfoPanel *self,
DefaultAppData *data,
guint left_attach,
guint right_attach,
guint top_attach,
guint bottom_attach)
{
GtkWidget *button;
GtkWidget *table;
GtkWidget *label;
table = WID ("default_apps_table");
button = gtk_app_chooser_button_new (data->content_type);
g_object_set_data (G_OBJECT (button), "cc-default-app-data", data);
gtk_app_chooser_button_set_show_default_item (GTK_APP_CHOOSER_BUTTON (button), TRUE);
gtk_table_attach (GTK_TABLE (table), button,
left_attach, right_attach,
top_attach, bottom_attach, GTK_FILL, 0, 0, 0);
g_signal_connect (G_OBJECT (button), "changed",
G_CALLBACK (default_app_changed), self);
gtk_widget_show (button);
label = WID(data->label);
gtk_label_set_mnemonic_widget (GTK_LABEL (label), button);
}
static DefaultAppData preferred_app_infos[] = {
/* for web, we need to support text/html,
application/xhtml+xml and x-scheme-handler/https,
hence the "*" pattern
*/
{ "x-scheme-handler/http", "web-label", "*" },
{ "x-scheme-handler/mailto", "mail-label", NULL },
{ "text/calendar", "calendar-label", NULL },
{ "audio/x-vorbis+ogg", "music-label", "audio/*" },
{ "video/x-ogm+ogg", "video-label", "video/*" },
{ "image/jpeg", "photos-label", "image/*" }
};
static void
info_panel_setup_default_apps (CcInfoPanel *self)
{
int i;
for (i = 0; i < G_N_ELEMENTS(preferred_app_infos); i++)
{
info_panel_setup_default_app (self, &preferred_app_infos[i],
1, 2, i, i+1);
}
}
static char **
remove_elem_from_str_array (char **v,
const char *s)
{
GPtrArray *array;
guint idx;
array = g_ptr_array_new ();
for (idx = 0; v[idx] != NULL; idx++) {
if (g_strcmp0 (v[idx], s) == 0) {
continue;
}
g_ptr_array_add (array, v[idx]);
}
g_ptr_array_add (array, NULL);
g_free (v);
return (char **) g_ptr_array_free (array, FALSE);
}
static char **
add_elem_to_str_array (char **v,
const char *s)
{
GPtrArray *array;
guint idx;
array = g_ptr_array_new ();
for (idx = 0; v[idx] != NULL; idx++) {
g_ptr_array_add (array, v[idx]);
}
g_ptr_array_add (array, g_strdup (s));
g_ptr_array_add (array, NULL);
g_free (v);
return (char **) g_ptr_array_free (array, FALSE);
}
static int
media_panel_g_strv_find (char **strv,
const char *find_me)
{
guint index;
g_return_val_if_fail (find_me != NULL, -1);
for (index = 0; strv[index] != NULL; ++index) {
if (g_strcmp0 (strv[index], find_me) == 0) {
return index;
}
}
return -1;
}
static void
autorun_get_preferences (CcInfoPanel *self,
const char *x_content_type,
gboolean *pref_start_app,
gboolean *pref_ignore,
gboolean *pref_open_folder)
{
char **x_content_start_app;
char **x_content_ignore;
char **x_content_open_folder;
g_return_if_fail (pref_start_app != NULL);
g_return_if_fail (pref_ignore != NULL);
g_return_if_fail (pref_open_folder != NULL);
*pref_start_app = FALSE;
*pref_ignore = FALSE;
*pref_open_folder = FALSE;
x_content_start_app = g_settings_get_strv (self->priv->media_settings,
PREF_MEDIA_AUTORUN_X_CONTENT_START_APP);
x_content_ignore = g_settings_get_strv (self->priv->media_settings,
PREF_MEDIA_AUTORUN_X_CONTENT_IGNORE);
x_content_open_folder = g_settings_get_strv (self->priv->media_settings,
PREF_MEDIA_AUTORUN_X_CONTENT_OPEN_FOLDER);
if (x_content_start_app != NULL) {
*pref_start_app = media_panel_g_strv_find (x_content_start_app, x_content_type) != -1;
}
if (x_content_ignore != NULL) {
*pref_ignore = media_panel_g_strv_find (x_content_ignore, x_content_type) != -1;
}
if (x_content_open_folder != NULL) {
*pref_open_folder = media_panel_g_strv_find (x_content_open_folder, x_content_type) != -1;
}
g_strfreev (x_content_ignore);
g_strfreev (x_content_start_app);
g_strfreev (x_content_open_folder);
}
static void
autorun_set_preferences (CcInfoPanel *self,
const char *x_content_type,
gboolean pref_start_app,
gboolean pref_ignore,
gboolean pref_open_folder)
{
char **x_content_start_app;
char **x_content_ignore;
char **x_content_open_folder;
g_assert (x_content_type != NULL);
x_content_start_app = g_settings_get_strv (self->priv->media_settings,
PREF_MEDIA_AUTORUN_X_CONTENT_START_APP);
x_content_ignore = g_settings_get_strv (self->priv->media_settings,
PREF_MEDIA_AUTORUN_X_CONTENT_IGNORE);
x_content_open_folder = g_settings_get_strv (self->priv->media_settings,
PREF_MEDIA_AUTORUN_X_CONTENT_OPEN_FOLDER);
x_content_start_app = remove_elem_from_str_array (x_content_start_app, x_content_type);
if (pref_start_app) {
x_content_start_app = add_elem_to_str_array (x_content_start_app, x_content_type);
}
g_settings_set_strv (self->priv->media_settings,
PREF_MEDIA_AUTORUN_X_CONTENT_START_APP, (const gchar * const*) x_content_start_app);
x_content_ignore = remove_elem_from_str_array (x_content_ignore, x_content_type);
if (pref_ignore) {
x_content_ignore = add_elem_to_str_array (x_content_ignore, x_content_type);
}
g_settings_set_strv (self->priv->media_settings,
PREF_MEDIA_AUTORUN_X_CONTENT_IGNORE, (const gchar * const*) x_content_ignore);
x_content_open_folder = remove_elem_from_str_array (x_content_open_folder, x_content_type);
if (pref_open_folder) {
x_content_open_folder = add_elem_to_str_array (x_content_open_folder, x_content_type);
}
g_settings_set_strv (self->priv->media_settings,
PREF_MEDIA_AUTORUN_X_CONTENT_OPEN_FOLDER, (const gchar * const*) x_content_open_folder);
g_strfreev (x_content_open_folder);
g_strfreev (x_content_ignore);
g_strfreev (x_content_start_app);
}
static void
custom_item_activated_cb (GtkAppChooserButton *button,
const gchar *item,
gpointer user_data)
{
CcInfoPanel *self = user_data;
gchar *content_type;
content_type = gtk_app_chooser_get_content_type (GTK_APP_CHOOSER (button));
if (g_strcmp0 (item, CUSTOM_ITEM_ASK) == 0) {
autorun_set_preferences (self, content_type,
FALSE, FALSE, FALSE);
} else if (g_strcmp0 (item, CUSTOM_ITEM_OPEN_FOLDER) == 0) {
autorun_set_preferences (self, content_type,
FALSE, FALSE, TRUE);
} else if (g_strcmp0 (item, CUSTOM_ITEM_DO_NOTHING) == 0) {
autorun_set_preferences (self, content_type,
FALSE, TRUE, FALSE);
}
g_free (content_type);
}
static void
combo_box_changed_cb (GtkComboBox *combo_box,
gpointer user_data)
{
CcInfoPanel *self = user_data;
GAppInfo *info;
gchar *content_type;
info = gtk_app_chooser_get_app_info (GTK_APP_CHOOSER (combo_box));
if (info == NULL)
return;
content_type = gtk_app_chooser_get_content_type (GTK_APP_CHOOSER (combo_box));
autorun_set_preferences (self, content_type,
TRUE, FALSE, FALSE);
g_app_info_set_as_default_for_type (info, content_type, NULL);
g_object_unref (info);
g_free (content_type);
}
static void
prepare_combo_box (CcInfoPanel *self,
GtkWidget *combo_box,
const gchar *heading)
{
GtkAppChooserButton *app_chooser = GTK_APP_CHOOSER_BUTTON (combo_box);
gboolean pref_ask;
gboolean pref_start_app;
gboolean pref_ignore;
gboolean pref_open_folder;
GAppInfo *info;
gchar *content_type;
content_type = gtk_app_chooser_get_content_type (GTK_APP_CHOOSER (app_chooser));
/* fetch preferences for this content type */
autorun_get_preferences (self, content_type,
&pref_start_app, &pref_ignore, &pref_open_folder);
pref_ask = !pref_start_app && !pref_ignore && !pref_open_folder;
info = gtk_app_chooser_get_app_info (GTK_APP_CHOOSER (combo_box));
/* append the separator only if we have >= 1 apps in the chooser */
if (info != NULL) {
gtk_app_chooser_button_append_separator (app_chooser);
g_object_unref (info);
}
gtk_app_chooser_button_append_custom_item (app_chooser, CUSTOM_ITEM_ASK,
_("Ask what to do"),
NULL);
gtk_app_chooser_button_append_custom_item (app_chooser, CUSTOM_ITEM_DO_NOTHING,
_("Do nothing"),
NULL);
gtk_app_chooser_button_append_custom_item (app_chooser, CUSTOM_ITEM_OPEN_FOLDER,
_("Open folder"),
NULL);
gtk_app_chooser_button_set_show_dialog_item (app_chooser, TRUE);
gtk_app_chooser_button_set_heading (app_chooser, _(heading));
if (pref_ask) {
gtk_app_chooser_button_set_active_custom_item (app_chooser, CUSTOM_ITEM_ASK);
} else if (pref_ignore) {
gtk_app_chooser_button_set_active_custom_item (app_chooser, CUSTOM_ITEM_DO_NOTHING);
} else if (pref_open_folder) {
gtk_app_chooser_button_set_active_custom_item (app_chooser, CUSTOM_ITEM_OPEN_FOLDER);
}
g_signal_connect (app_chooser, "changed",
G_CALLBACK (combo_box_changed_cb), self);
g_signal_connect (app_chooser, "custom-item-activated",
G_CALLBACK (custom_item_activated_cb), self);
g_free (content_type);
}
static void
other_type_combo_box_changed (GtkComboBox *combo_box,
CcInfoPanel *self)
{
GtkTreeIter iter;
GtkTreeModel *model;
char *x_content_type;
GtkWidget *action_container;
GtkWidget *action_label;
x_content_type = NULL;
if (!gtk_combo_box_get_active_iter (combo_box, &iter)) {
return;
}
model = gtk_combo_box_get_model (combo_box);
if (model == NULL) {
return;
}
gtk_tree_model_get (model, &iter,
1, &x_content_type,
-1);
action_container = GTK_WIDGET (gtk_builder_get_object (self->priv->builder,
"media_other_action_container"));
if (self->priv->other_application_combo != NULL) {
gtk_widget_destroy (self->priv->other_application_combo);
}
self->priv->other_application_combo = gtk_app_chooser_button_new (x_content_type);
gtk_box_pack_start (GTK_BOX (action_container), self->priv->other_application_combo, TRUE, TRUE, 0);
prepare_combo_box (self, self->priv->other_application_combo, NULL);
gtk_widget_show (self->priv->other_application_combo);
action_label = GTK_WIDGET (gtk_builder_get_object (self->priv->builder,
"media_other_action_label"));
gtk_label_set_mnemonic_widget (GTK_LABEL (action_label), self->priv->other_application_combo);
g_free (x_content_type);
}
static void
on_extra_options_dialog_response (GtkWidget *dialog,
int response,
CcInfoPanel *self)
{
gtk_widget_hide (dialog);
if (self->priv->other_application_combo != NULL) {
gtk_widget_destroy (self->priv->other_application_combo);
self->priv->other_application_combo = NULL;
}
}
static void
on_extra_options_button_clicked (GtkWidget *button,
CcInfoPanel *self)
{
GtkWidget *dialog;
GtkWidget *combo_box;
dialog = GTK_WIDGET (gtk_builder_get_object (self->priv->builder, "extra_options_dialog"));
combo_box = GTK_WIDGET (gtk_builder_get_object (self->priv->builder, "media_other_type_combobox"));
gtk_window_set_transient_for (GTK_WINDOW (dialog),
GTK_WINDOW (gtk_widget_get_toplevel (GTK_WIDGET (self))));
gtk_window_set_modal (GTK_WINDOW (dialog), TRUE);
gtk_window_set_title (GTK_WINDOW (dialog), _("Other Media"));
g_signal_connect (dialog,
"response",
G_CALLBACK (on_extra_options_dialog_response),
self);
g_signal_connect (dialog,
"delete-event",
G_CALLBACK (gtk_widget_hide_on_delete),
NULL);
/* update other_application_combo */
other_type_combo_box_changed (GTK_COMBO_BOX (combo_box), self);
gtk_window_present (GTK_WINDOW (dialog));
}
static void
info_panel_setup_media (CcInfoPanel *self)
{
guint n;
GList *l, *content_types;
GtkWidget *other_type_combo_box;
GtkWidget *extras_button;
GtkListStore *other_type_list_store;
GtkCellRenderer *renderer;
GtkTreeIter iter;
GtkBuilder *builder = self->priv->builder;
struct {
const gchar *widget_name;
const gchar *content_type;
const gchar *heading;
} const defs[] = {
{ "media_audio_cdda_combobox", "x-content/audio-cdda", N_("Select an application for audio CDs") },
{ "media_video_dvd_combobox", "x-content/video-dvd", N_("Select an application for video DVDs") },
{ "media_music_player_combobox", "x-content/audio-player", N_("Select an application to run when a music player is connected") },
{ "media_dcf_combobox", "x-content/image-dcf", N_("Select an application to run when a camera is connected") },
{ "media_software_combobox", "x-content/unix-software", N_("Select an application for software CDs") },
};
struct {
const gchar *content_type;
const gchar *description;
} const other_defs[] = {
/* translators: these strings are duplicates of shared-mime-info
* strings, just here to fix capitalization of the English originals.
* If the shared-mime-info translation works for your language,
* simply leave these untranslated.
*/
{ "x-content/audio-dvd", N_("audio DVD") },
{ "x-content/blank-bd", N_("blank Blu-ray disc") },
{ "x-content/blank-cd", N_("blank CD disc") },
{ "x-content/blank-dvd", N_("blank DVD disc") },
{ "x-content/blank-hddvd", N_("blank HD DVD disc") },
{ "x-content/video-bluray", N_("Blu-ray video disc") },
{ "x-content/ebook-reader", N_("e-book reader") },
{ "x-content/video-hddvd", N_("HD DVD video disc") },
{ "x-content/image-picturecd", N_("Picture CD") },
{ "x-content/video-svcd", N_("Super Video CD") },
{ "x-content/video-vcd", N_("Video CD") },
{ "x-content/win32-software", N_("Windows software") },
{ "x-content/software", N_("Software") }
};
for (n = 0; n < G_N_ELEMENTS (defs); n++) {
prepare_combo_box (self,
GTK_WIDGET (gtk_builder_get_object (builder, defs[n].widget_name)),
defs[n].heading);
}
other_type_combo_box = GTK_WIDGET (gtk_builder_get_object (builder, "media_other_type_combobox"));
other_type_list_store = gtk_list_store_new (2,
G_TYPE_STRING,
G_TYPE_STRING);
gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (other_type_list_store),
1, GTK_SORT_ASCENDING);
content_types = g_content_types_get_registered ();
for (l = content_types; l != NULL; l = l->next) {
char *content_type = l->data;
char *description = NULL;
if (!g_str_has_prefix (content_type, "x-content/"))
continue;
for (n = 0; n < G_N_ELEMENTS (defs); n++) {
if (g_content_type_is_a (content_type, defs[n].content_type)) {
goto skip;
}
}
for (n = 0; n < G_N_ELEMENTS (other_defs); n++) {
if (strcmp (content_type, other_defs[n].content_type) == 0) {
const gchar *s = other_defs[n].description;
if (s == _(s))
description = g_content_type_get_description (content_type);
else
description = g_strdup (_(s));
break;
}
}
if (description == NULL) {
g_debug ("Content type '%s' is missing from the info panel", content_type);
description = g_content_type_get_description (content_type);
}
gtk_list_store_append (other_type_list_store, &iter);
gtk_list_store_set (other_type_list_store, &iter,
0, description,
1, content_type,
-1);
g_free (description);
skip:
;
}
g_list_free_full (content_types, g_free);
gtk_combo_box_set_model (GTK_COMBO_BOX (other_type_combo_box),
GTK_TREE_MODEL (other_type_list_store));
renderer = gtk_cell_renderer_text_new ();
gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (other_type_combo_box), renderer, TRUE);
gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (other_type_combo_box), renderer,
"text", 0,
NULL);
g_signal_connect (other_type_combo_box,
"changed",
G_CALLBACK (other_type_combo_box_changed),
self);
gtk_combo_box_set_active (GTK_COMBO_BOX (other_type_combo_box), 0);
extras_button = GTK_WIDGET (gtk_builder_get_object (builder, "extra_options_button"));
g_signal_connect (extras_button,
"clicked",
G_CALLBACK (on_extra_options_button_clicked),
self);
g_settings_bind (self->priv->media_settings,
PREF_MEDIA_AUTORUN_NEVER,
gtk_builder_get_object (self->priv->builder, "media_autorun_never_checkbutton"),
"active",
G_SETTINGS_BIND_DEFAULT);
g_settings_bind (self->priv->media_settings,
PREF_MEDIA_AUTORUN_NEVER,
GTK_WIDGET (gtk_builder_get_object (self->priv->builder, "media_handling_vbox")),
"sensitive",
G_SETTINGS_BIND_INVERT_BOOLEAN);
}
static void
info_panel_setup_selector (CcInfoPanel *self)
{
GtkTreeView *view;
GtkListStore *model;
GtkTreeSelection *selection;
GtkTreeViewColumn *column;
GtkCellRenderer *renderer;
GtkTreeIter iter;
int section_name_column = 0;
view = GTK_TREE_VIEW (WID ("overview_treeview"));
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (view));
model = gtk_list_store_new (1, G_TYPE_STRING);
gtk_tree_view_set_model (view, GTK_TREE_MODEL (model));
g_object_unref (model);
renderer = gtk_cell_renderer_text_new ();
gtk_cell_renderer_set_padding (renderer, 4, 4);
g_object_set (renderer,
"width-chars", 20,
"ellipsize", PANGO_ELLIPSIZE_END,
NULL);
column = gtk_tree_view_column_new_with_attributes (_("Section"),
renderer,
"text", section_name_column,
NULL);
gtk_tree_view_append_column (view, column);
gtk_list_store_append (model, &iter);
gtk_list_store_set (model, &iter, section_name_column,
_("Overview"),
-1);
gtk_tree_selection_select_iter (selection, &iter);
gtk_list_store_append (model, &iter);
gtk_list_store_set (model, &iter, section_name_column,
_("Default Applications"),
-1);
gtk_list_store_append (model, &iter);
gtk_list_store_set (model, &iter, section_name_column,
_("Removable Media"),
-1);
gtk_list_store_append (model, &iter);
gtk_list_store_set (model, &iter, section_name_column,
_("Graphics"),
-1);
g_signal_connect (selection, "changed",
G_CALLBACK (on_section_changed), self);
on_section_changed (selection, self);
gtk_widget_show_all (GTK_WIDGET (view));
}
static char *
get_hostname_property (CcInfoPanel *self,
const char *property)
{
GVariant *variant;
char *str;
variant = g_dbus_proxy_get_cached_property (self->priv->hostnamed_proxy,
property);
if (!variant)
{
GError *error = NULL;
GVariant *inner;
/* Work around systemd-hostname not sending us back
* the property value when changing values */
variant = g_dbus_proxy_call_sync (self->priv->hostnamed_proxy,
"org.freedesktop.DBus.Properties.Get",
g_variant_new ("(ss)", "org.freedesktop.hostname1", property),
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
&error);
if (variant == NULL)
{
g_warning ("Failed to get property '%s': %s", property, error->message);
g_error_free (error);
return NULL;
}
g_variant_get (variant, "(v)", &inner);
str = g_variant_dup_string (inner, NULL);
g_variant_unref (variant);
}
else
{
str = g_variant_dup_string (variant, NULL);
g_variant_unref (variant);
}
return str;
}
static char *
info_panel_get_hostname (CcInfoPanel *self)
{
char *str;
str = get_hostname_property (self, "PrettyHostname");
/* Empty strings means that we need to fallback */
if (str != NULL &&
*str == '\0')
{
g_free (str);
str = get_hostname_property (self, "Hostname");
}
return str;
}
static void
info_panel_set_hostname (CcInfoPanel *self,
const char *text)
{
char *hostname;
GVariant *variant;
GError *error = NULL;
g_debug ("Setting PrettyHostname to '%s'", text);
variant = g_dbus_proxy_call_sync (self->priv->hostnamed_proxy,
"SetPrettyHostname",
g_variant_new ("(sb)", text, FALSE),
G_DBUS_CALL_FLAGS_NONE,
-1, NULL, &error);
if (variant == NULL)
{
g_warning ("Could not set PrettyHostname: %s", error->message);
g_error_free (error);
error = NULL;
}
else
{
g_variant_unref (variant);
}
/* Set the static hostname */
hostname = pretty_hostname_to_static (text, FALSE);
g_assert (hostname);
g_debug ("Setting StaticHostname to '%s'", hostname);
variant = g_dbus_proxy_call_sync (self->priv->hostnamed_proxy,
"SetStaticHostname",
g_variant_new ("(sb)", hostname, FALSE),
G_DBUS_CALL_FLAGS_NONE,
-1, NULL, &error);
if (variant == NULL)
{
g_warning ("Could not set StaticHostname: %s", error->message);
g_error_free (error);
}
else
{
g_variant_unref (variant);
}
g_free (hostname);
}
static void
text_changed_cb (GtkEntry *entry,
CcInfoPanel *self)
{
const char *text;
text = gtk_entry_get_text (GTK_ENTRY (entry));
info_panel_set_hostname (self, text);
}
static void
info_panel_setup_hostname (CcInfoPanel *self,
GPermission *permission)
{
char *str;
GtkWidget *entry;
GError *error = NULL;
if (permission == NULL)
{
g_debug ("Will not show hostname, hostnamed not installed");
return;
}
entry = WID ("name_entry");
if (g_permission_get_allowed (permission) != FALSE)
{
g_debug ("Not allowed to change the hostname");
gtk_widget_set_sensitive (entry, TRUE);
}
self->priv->hostnamed_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM,
G_DBUS_PROXY_FLAGS_NONE,
NULL,
"org.freedesktop.hostname1",
"/org/freedesktop/hostname1",
"org.freedesktop.hostname1",
NULL,
&error);
/* This could only happen if the policy file was installed
* but not hostnamed, which points to a system bug */
if (self->priv->hostnamed_proxy == NULL)
{
g_debug ("Couldn't get hostnamed to start, bailing: %s", error->message);
g_error_free (error);
return;
}
gtk_widget_show (WID ("label4"));
gtk_widget_show (entry);
str = info_panel_get_hostname (self);
if (str != NULL)
gtk_entry_set_text (GTK_ENTRY (entry), str);
else
gtk_entry_set_text (GTK_ENTRY (entry), "");
g_free (str);
g_signal_connect (G_OBJECT (entry), "changed",
G_CALLBACK (text_changed_cb), self);
}
static void
info_panel_setup_overview (CcInfoPanel *self)
{
GtkWidget *widget;
glibtop_mem mem;
const glibtop_sysinfo *info;
char *text;
GPermission *permission;
permission = polkit_permission_new_sync ("org.freedesktop.hostname1.set-static-hostname", NULL, NULL, NULL);
/* Is hostnamed installed? */
info_panel_setup_hostname (self, permission);
widget = WID ("version_label");
text = g_strdup_printf (_("Version %s"), g_getenv ("CINNAMON_VERSION"));
gtk_label_set_text (GTK_LABEL (widget), text);
g_free (text);
gtk_widget_show (WID ("version_label"));
glibtop_get_mem (&mem);
text = g_format_size_full (mem.total, G_FORMAT_SIZE_IEC_UNITS);
widget = WID ("memory_label");
gtk_label_set_text (GTK_LABEL (widget), text ? text : "");
g_free (text);
info = glibtop_get_sysinfo ();
widget = WID ("processor_label");
text = get_cpu_info (info);
gtk_label_set_markup (GTK_LABEL (widget), text ? text : "");
g_free (text);
widget = WID ("os_type_label");
text = get_os_type ();
gtk_label_set_text (GTK_LABEL (widget), text ? text : "");
g_free (text);
get_primary_disc_info (self);
widget = WID ("graphics_label");
gtk_label_set_markup (GTK_LABEL (widget), self->priv->graphics_data->hardware_string);
widget = WID ("info_vbox");
gtk_widget_reparent (widget, (GtkWidget *) self);
refresh_update_button (self);
}
static void
refresh_update_button (CcInfoPanel *self)
{
GtkWidget *widget;
widget = WID ("updates_button");
if (widget == NULL)
return;
switch (self->priv->updates_state)
{
case PK_NOT_AVAILABLE:
gtk_widget_set_visible (widget, FALSE);
break;
case UPDATES_AVAILABLE:
gtk_widget_set_sensitive (widget, TRUE);
gtk_button_set_label (GTK_BUTTON (widget), _("Install Updates"));
break;
case UPDATES_NOT_AVAILABLE:
gtk_widget_set_sensitive (widget, FALSE);
gtk_button_set_label (GTK_BUTTON (widget), _("System Up-To-Date"));
break;
case CHECKING_UPDATES:
gtk_widget_set_sensitive (widget, FALSE);
gtk_button_set_label (GTK_BUTTON (widget), _("Checking for Updates"));
break;
}
}
static void
on_pk_transaction_signal (GDBusProxy *proxy,
char *sender_name,
char *signal_name,
GVariant *parameters,
CcInfoPanel *self)
{
if (g_strcmp0 (signal_name, "Package") == 0)
{
self->priv->updates_state = UPDATES_AVAILABLE;
}
else if (g_strcmp0 (signal_name, "Finished") == 0)
{
if (self->priv->updates_state == CHECKING_UPDATES)
self->priv->updates_state = UPDATES_NOT_AVAILABLE;
refresh_update_button (self);
}
else if (g_strcmp0 (signal_name, "ErrorCode") == 0)
{
self->priv->updates_state = PK_NOT_AVAILABLE;
refresh_update_button (self);
}
else if (g_strcmp0 (signal_name, "Destroy") == 0)
{
g_object_unref (self->priv->pk_transaction_proxy);
self->priv->pk_transaction_proxy = NULL;
}
}
static void
on_pk_get_updates_ready (GObject *source,
GAsyncResult *res,
CcInfoPanel *self)
{
GError *error;
GVariant *result;
error = NULL;
result = g_dbus_proxy_call_finish (G_DBUS_PROXY (source), res, &error);
if (result == NULL)
{
g_warning ("Error getting PackageKit updates list: %s", error->message);
g_error_free (error);
return;
}
}
static void
on_pk_get_tid_ready (GObject *source,
GAsyncResult *res,
CcInfoPanel *self)
{
GError *error;
GVariant *result;
char *tid;
error = NULL;
result = g_dbus_proxy_call_finish (G_DBUS_PROXY (source), res, &error);
if (result == NULL)
{
if (g_error_matches (error, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN) == FALSE)
g_warning ("Error getting PackageKit transaction ID: %s", error->message);
g_error_free (error);
return;
}
g_variant_get (result, "(o)", &tid);
self->priv->pk_transaction_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM,
G_DBUS_PROXY_FLAGS_NONE,
NULL,
"org.freedesktop.PackageKit",
tid,
"org.freedesktop.PackageKit.Transaction",
NULL,
NULL);
g_free (tid);
g_variant_unref (result);
if (self->priv->pk_transaction_proxy == NULL)
{
g_warning ("Unable to get PackageKit transaction proxy object");
return;
}
g_signal_connect (self->priv->pk_transaction_proxy,
"g-signal",
G_CALLBACK (on_pk_transaction_signal),
self);
g_dbus_proxy_call (self->priv->pk_transaction_proxy,
"GetUpdates",
g_variant_new ("(t)", 1), /* PK_FILTER_ENUM_NONE */
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
(GAsyncReadyCallback) on_pk_get_updates_ready,
self);
}
static void
refresh_updates (CcInfoPanel *self)
{
self->priv->updates_state = CHECKING_UPDATES;
refresh_update_button (self);
g_assert (self->priv->pk_proxy != NULL);
g_dbus_proxy_call (self->priv->pk_proxy,
"CreateTransaction",
NULL,
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
(GAsyncReadyCallback) on_pk_get_tid_ready,
self);
}
static void
on_pk_signal (GDBusProxy *proxy,
char *sender_name,
char *signal_name,
GVariant *parameters,
CcInfoPanel *self)
{
if (g_strcmp0 (signal_name, "UpdatesChanged") == 0)
{
refresh_updates (self);
}
}
static void
on_updates_button_clicked (GtkWidget *widget,
CcInfoPanel *self)
{
GError *error;
error = NULL;
g_spawn_command_line_async ("update-manager", &error);
if (error != NULL)
{
g_warning ("unable to launch Software Updates: %s", error->message);
g_error_free (error);
}
}
static void
cc_info_panel_init (CcInfoPanel *self)
{
GError *error = NULL;
GtkWidget *widget;
self->priv = INFO_PANEL_PRIVATE (self);
self->priv->builder = gtk_builder_new ();
self->priv->session_settings = g_settings_new (GNOME_SESSION_MANAGER_SCHEMA);
self->priv->media_settings = g_settings_new (MEDIA_HANDLING_SCHEMA);
self->priv->session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
g_assert (self->priv->session_bus);
self->priv->pk_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM,
G_DBUS_PROXY_FLAGS_NONE,
NULL,
"org.freedesktop.PackageKit",
"/org/freedesktop/PackageKit",
"org.freedesktop.PackageKit",
NULL,
NULL);
if (self->priv->pk_proxy == NULL)
{
g_warning ("Unable to get PackageKit proxy object");
self->priv->updates_state = PK_NOT_AVAILABLE;
}
else
{
GVariant *v;
guint32 major, minor, micro;
v = g_dbus_proxy_get_cached_property (self->priv->pk_proxy, "VersionMajor");
g_variant_get (v, "u", &major);
g_variant_unref (v);
v = g_dbus_proxy_get_cached_property (self->priv->pk_proxy, "VersionMinor");
g_variant_get (v, "u", &minor);
g_variant_unref (v);
v = g_dbus_proxy_get_cached_property (self->priv->pk_proxy, "VersionMicro");
g_variant_get (v, "u", µ);
g_variant_unref (v);
if (major != 0 || minor != 8)
{
g_warning ("PackageKit version %u.%u.%u not supported", major, minor, micro);
g_clear_object (&self->priv->pk_proxy);
self->priv->updates_state = PK_NOT_AVAILABLE;
}
else
{
g_signal_connect (self->priv->pk_proxy,
"g-signal",
G_CALLBACK (on_pk_signal),
self);
refresh_updates (self);
}
}
gtk_builder_add_from_file (self->priv->builder,
CINNAMONCC_UI_DIR "/info.ui",
&error);
if (error != NULL)
{
g_warning ("Could not load interface file: %s", error->message);
g_error_free (error);
return;
}
self->priv->graphics_data = get_graphics_data ();
widget = WID ("updates_button");
g_signal_connect (widget, "clicked", G_CALLBACK (on_updates_button_clicked), self);
info_panel_setup_selector (self);
info_panel_setup_overview (self);
info_panel_setup_default_apps (self);
info_panel_setup_media (self);
info_panel_setup_graphics (self);
}
void
cc_info_panel_register (GIOModule *module)
{
cc_info_panel_register_type (G_TYPE_MODULE (module));
g_io_extension_point_implement (CC_SHELL_PANEL_EXTENSION_POINT,
CC_TYPE_INFO_PANEL,
"info", 0);
}
|
381 | ./cinnamon-control-center/panels/unused/keyboard/keyboard-module.c | /*
* Copyright (C) 2010 Intel, Inc
*
* 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.
*
* Author: Thomas Wood <[email protected]>
*
*/
#include <config.h>
#include "cc-keyboard-panel.h"
#include <glib/gi18n-lib.h>
void
g_io_module_load (GIOModule *module)
{
bindtextdomain (GETTEXT_PACKAGE, CINNAMONLOCALEDIR);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
/* register the panel */
cc_keyboard_panel_register (module);
}
void
g_io_module_unload (GIOModule *module)
{
}
|
382 | ./cinnamon-control-center/panels/unused/online-accounts/cc-online-accounts-add-account-dialog.c | /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
*
* Copyright (C) 2012 Red Hat, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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.
*
* Author: Debarshi Ray <[email protected]>
*/
#include "config.h"
#include <glib/gi18n-lib.h>
#define GOA_API_IS_SUBJECT_TO_CHANGE
#define GOA_BACKEND_API_IS_SUBJECT_TO_CHANGE
#include <goabackend/goabackend.h>
#include "cc-online-accounts-add-account-dialog.h"
struct _GoaPanelAddAccountDialogPrivate
{
GError *error;
GoaClient *client;
GoaObject *object;
GtkListStore *list_store;
GtkTreePath *path;
GtkWidget *tree_view;
gboolean ignore_release;
};
#define GOA_ADD_ACCOUNT_DIALOG_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GOA_TYPE_PANEL_ADD_ACCOUNT_DIALOG, GoaPanelAddAccountDialogPrivate))
enum
{
PROP_0,
PROP_CLIENT,
};
enum
{
COLUMN_PROVIDER,
COLUMN_ICON,
COLUMN_MARKUP,
N_COLUMNS
};
G_DEFINE_TYPE (GoaPanelAddAccountDialog, goa_panel_add_account_dialog, GTK_TYPE_DIALOG)
static GoaProvider *
add_account_dialog_get_provider (GoaPanelAddAccountDialog *add_account)
{
GoaPanelAddAccountDialogPrivate *priv = add_account->priv;
GoaProvider *provider;
GtkTreeIter iter;
if (priv->path == NULL)
return NULL;
if (!gtk_tree_model_get_iter (GTK_TREE_MODEL (priv->list_store), &iter, priv->path))
return NULL;
gtk_tree_model_get (GTK_TREE_MODEL (priv->list_store), &iter, COLUMN_PROVIDER, &provider, -1);
return provider;
}
static void
add_account_dialog_add_account (GoaPanelAddAccountDialog *add_account)
{
GoaPanelAddAccountDialogPrivate *priv = add_account->priv;
GList *children;
GList *l;
GoaProvider *provider;
GtkWidget *action_area;
GtkWidget *vbox;
provider = add_account_dialog_get_provider (add_account);
g_assert (provider != NULL);
action_area = gtk_dialog_get_action_area (GTK_DIALOG (add_account));
vbox = gtk_dialog_get_content_area (GTK_DIALOG (add_account));
children = gtk_container_get_children (GTK_CONTAINER (vbox));
for (l = children; l != NULL; l = l->next)
{
GtkWidget *child = l->data;
if (child != action_area)
gtk_container_remove (GTK_CONTAINER (vbox), child);
}
g_list_free (children);
priv->object = goa_provider_add_account (provider,
priv->client,
GTK_DIALOG (add_account),
GTK_BOX (vbox),
&priv->error);
g_object_unref (provider);
}
static gboolean
tree_view_button_press_event_cb (GtkWidget *widget,
GdkEventButton *event,
gpointer *user_data)
{
GoaPanelAddAccountDialog *add_account = GOA_PANEL_ADD_ACCOUNT_DIALOG (user_data);
GoaPanelAddAccountDialogPrivate *priv = add_account->priv;
/* be sure to ignore double and triple clicks */
priv->ignore_release = (event->type != GDK_BUTTON_PRESS);
return FALSE;
}
static gboolean
tree_view_button_release_event_cb (GtkWidget *widget,
GdkEventButton *event,
gpointer *user_data)
{
GoaPanelAddAccountDialog *add_account = GOA_PANEL_ADD_ACCOUNT_DIALOG (user_data);
GoaPanelAddAccountDialogPrivate *priv = add_account->priv;
GtkTreePath *path;
GtkTreeViewColumn *column;
if (event->button != 1 || priv->ignore_release)
return TRUE;
gtk_tree_view_get_cursor (GTK_TREE_VIEW (widget), &path, &column);
if (path == NULL)
return TRUE;
gtk_tree_view_row_activated (GTK_TREE_VIEW (widget), path, column);
gtk_tree_path_free (path);
return TRUE;
}
static void
tree_view_row_activated_cb (GtkTreeView *tree_view,
GtkTreePath *path,
GtkTreeViewColumn *column,
gpointer user_data)
{
GoaPanelAddAccountDialog *add_account = GOA_PANEL_ADD_ACCOUNT_DIALOG (user_data);
GoaPanelAddAccountDialogPrivate *priv = add_account->priv;
priv->path = gtk_tree_path_copy (path);
add_account_dialog_add_account (add_account);
gtk_dialog_response (GTK_DIALOG (add_account), GTK_RESPONSE_OK);
}
static void
goa_panel_add_account_dialog_realize (GtkWidget *widget)
{
GoaPanelAddAccountDialog *add_account = GOA_PANEL_ADD_ACCOUNT_DIALOG (widget);
GoaPanelAddAccountDialogPrivate *priv = add_account->priv;
GtkWidget *button;
GtkWindow *parent;
parent = gtk_window_get_transient_for (GTK_WINDOW (add_account));
if (parent != NULL)
{
gint width;
gint height;
gtk_window_get_size (parent, &width, &height);
gtk_widget_set_size_request (GTK_WIDGET (add_account), (gint) (0.5 * width), (gint) (0.9 * height));
}
gtk_tree_view_set_model (GTK_TREE_VIEW (priv->tree_view), GTK_TREE_MODEL (priv->list_store));
GTK_WIDGET_CLASS (goa_panel_add_account_dialog_parent_class)->realize (widget);
button = gtk_dialog_get_widget_for_response (GTK_DIALOG (add_account), GTK_RESPONSE_CANCEL);
gtk_widget_grab_focus (button);
}
static void
goa_panel_add_account_dialog_dispose (GObject *object)
{
GoaPanelAddAccountDialog *add_account = GOA_PANEL_ADD_ACCOUNT_DIALOG (object);
GoaPanelAddAccountDialogPrivate *priv = add_account->priv;
if (priv->tree_view != NULL)
priv->tree_view = NULL;
g_clear_object (&priv->list_store);
g_clear_object (&priv->object);
g_clear_object (&priv->client);
G_OBJECT_CLASS (goa_panel_add_account_dialog_parent_class)->dispose (object);
}
static void
goa_panel_add_account_dialog_finalize (GObject *object)
{
GoaPanelAddAccountDialog *add_account = GOA_PANEL_ADD_ACCOUNT_DIALOG (object);
GoaPanelAddAccountDialogPrivate *priv = add_account->priv;
gtk_tree_path_free (priv->path);
if (priv->error != NULL)
g_error_free (priv->error);
G_OBJECT_CLASS (goa_panel_add_account_dialog_parent_class)->finalize (object);
}
static void
goa_panel_add_account_dialog_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec)
{
GoaPanelAddAccountDialog *add_account = GOA_PANEL_ADD_ACCOUNT_DIALOG (object);
GoaPanelAddAccountDialogPrivate *priv = add_account->priv;
switch (prop_id)
{
case PROP_CLIENT:
priv->client = GOA_CLIENT (g_value_dup_object (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
goa_panel_add_account_dialog_init (GoaPanelAddAccountDialog *add_account)
{
GoaPanelAddAccountDialogPrivate *priv;
GtkCellRenderer *renderer;
GtkTreeSelection *selection;
GtkTreeViewColumn *column;
GtkWidget *sw;
GtkWidget *vbox;
GtkWidget *grid;
add_account->priv = GOA_ADD_ACCOUNT_DIALOG_GET_PRIVATE (add_account);
priv = add_account->priv;
gtk_container_set_border_width (GTK_CONTAINER (add_account), 6);
gtk_window_set_modal (GTK_WINDOW (add_account), TRUE);
gtk_window_set_resizable (GTK_WINDOW (add_account), FALSE);
/* translators: This is the title of the "Add Account" dialog. */
gtk_window_set_title (GTK_WINDOW (add_account), _("Add Account"));
vbox = gtk_dialog_get_content_area (GTK_DIALOG (add_account));
grid = gtk_grid_new ();
gtk_container_set_border_width (GTK_CONTAINER (grid), 5);
gtk_widget_set_margin_bottom (grid, 6);
gtk_orientable_set_orientation (GTK_ORIENTABLE (grid), GTK_ORIENTATION_VERTICAL);
gtk_grid_set_row_spacing (GTK_GRID (grid), 12);
gtk_container_add (GTK_CONTAINER (vbox), grid);
priv->list_store = gtk_list_store_new (N_COLUMNS, GOA_TYPE_PROVIDER, G_TYPE_ICON, G_TYPE_STRING);
sw = gtk_scrolled_window_new (NULL, NULL);
gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (sw), GTK_SHADOW_IN);
gtk_widget_set_hexpand (sw, TRUE);
gtk_widget_set_vexpand (sw, TRUE);
gtk_container_add (GTK_CONTAINER (grid), sw);
priv->tree_view = gtk_tree_view_new ();
gtk_widget_set_hexpand (priv->tree_view, TRUE);
gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (priv->tree_view), FALSE);
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (priv->tree_view));
gtk_tree_selection_set_mode (selection, GTK_SELECTION_BROWSE);
gtk_container_add (GTK_CONTAINER (sw), priv->tree_view);
column = gtk_tree_view_column_new ();
gtk_tree_view_append_column (GTK_TREE_VIEW (priv->tree_view), column);
renderer = gtk_cell_renderer_pixbuf_new ();
gtk_tree_view_column_pack_start (column, renderer, FALSE);
g_object_set (G_OBJECT (renderer), "stock-size", GTK_ICON_SIZE_DIALOG, NULL);
gtk_tree_view_column_set_attributes (column, renderer, "gicon", COLUMN_ICON, NULL);
renderer = gtk_cell_renderer_text_new ();
gtk_tree_view_column_pack_start (column, renderer, TRUE);
gtk_tree_view_column_set_attributes (column, renderer, "markup", COLUMN_MARKUP, NULL);
gtk_dialog_add_button (GTK_DIALOG (add_account), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL);
gtk_dialog_set_default_response (GTK_DIALOG (add_account), GTK_RESPONSE_CANCEL);
g_signal_connect (priv->tree_view, "button-press-event",
G_CALLBACK (tree_view_button_press_event_cb), add_account);
g_signal_connect (priv->tree_view, "button-release-event",
G_CALLBACK (tree_view_button_release_event_cb), add_account);
g_signal_connect (priv->tree_view, "row-activated", G_CALLBACK (tree_view_row_activated_cb), add_account);
}
static void
goa_panel_add_account_dialog_class_init (GoaPanelAddAccountDialogClass *klass)
{
GObjectClass *object_class;
GtkWidgetClass *widget_class;
object_class = G_OBJECT_CLASS (klass);
object_class->dispose = goa_panel_add_account_dialog_dispose;
object_class->finalize = goa_panel_add_account_dialog_finalize;
object_class->set_property = goa_panel_add_account_dialog_set_property;
widget_class = GTK_WIDGET_CLASS (klass);
widget_class->realize = goa_panel_add_account_dialog_realize;
g_type_class_add_private (object_class, sizeof (GoaPanelAddAccountDialogPrivate));
g_object_class_install_property (object_class,
PROP_CLIENT,
g_param_spec_object ("client",
"Goa Client",
"A Goa client for talking to the Goa daemon.",
GOA_TYPE_CLIENT,
G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY));
}
GtkWidget *
goa_panel_add_account_dialog_new (GoaClient *client)
{
return g_object_new (GOA_TYPE_PANEL_ADD_ACCOUNT_DIALOG, "client", client, NULL);
}
void
goa_panel_add_account_dialog_add_provider (GoaPanelAddAccountDialog *add_account, GoaProvider *provider)
{
GoaPanelAddAccountDialogPrivate *priv = add_account->priv;
GIcon *icon;
GtkTreeIter iter;
gchar *markup;
gchar *name;
icon = goa_provider_get_provider_icon (provider, NULL);
name = goa_provider_get_provider_name (provider, NULL);
markup = g_strdup_printf ("<b>%s</b>", name);
g_free (name);
gtk_list_store_append (priv->list_store, &iter);
gtk_list_store_set (priv->list_store, &iter,
COLUMN_PROVIDER, provider,
COLUMN_ICON, icon,
COLUMN_MARKUP, markup,
-1);
g_free (markup);
g_object_unref (icon);
}
GoaObject *
goa_panel_add_account_dialog_get_account (GoaPanelAddAccountDialog *add_account, GError **error)
{
GoaPanelAddAccountDialogPrivate *priv = add_account->priv;
if (error != NULL && priv->error != NULL)
*error = g_error_copy (priv->error);
if (priv->object != NULL)
g_object_ref (priv->object);
return priv->object;
}
|
383 | ./cinnamon-control-center/panels/unused/online-accounts/cc-online-accounts-model.c | /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
*
* Copyright (C) 2008-2011 Red Hat, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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.
*
* Author: David Zeuthen <[email protected]>
*/
#include "config.h"
#include <glib/gi18n-lib.h>
#define GOA_API_IS_SUBJECT_TO_CHANGE
#define GOA_BACKEND_API_IS_SUBJECT_TO_CHANGE
#include <goabackend/goabackend.h>
#include "cc-online-accounts-model.h"
struct _GoaPanelAccountsModel
{
GtkListStore parent_instance;
GoaClient *client;
};
typedef struct
{
GtkListStoreClass parent_class;
} GoaPanelAccountsModelClass;
enum
{
PROP_0,
PROP_CLIENT,
};
static void init_model (GoaPanelAccountsModel *model);
static gboolean
find_iter_for_object (GoaPanelAccountsModel *model,
GoaObject *object,
GtkTreeIter *out_iter);
static void on_account_added (GoaClient *client,
GoaObject *object,
gpointer user_data);
static void on_account_removed (GoaClient *client,
GoaObject *object,
gpointer user_data);
static void on_account_changed (GoaClient *client,
GoaObject *object,
gpointer user_data);
G_DEFINE_TYPE (GoaPanelAccountsModel, goa_panel_accounts_model, GTK_TYPE_LIST_STORE);
static void
goa_panel_accounts_model_finalize (GObject *object)
{
GoaPanelAccountsModel *model = GOA_PANEL_ACCOUNTS_MODEL (object);
g_signal_handlers_disconnect_by_func (model->client, G_CALLBACK (on_account_added), model);
g_signal_handlers_disconnect_by_func (model->client, G_CALLBACK (on_account_removed), model);
g_signal_handlers_disconnect_by_func (model->client, G_CALLBACK (on_account_changed), model);
g_object_unref (model->client);
G_OBJECT_CLASS (goa_panel_accounts_model_parent_class)->finalize (object);
}
static void
goa_panel_accounts_model_init (GoaPanelAccountsModel *model)
{
}
static void
goa_panel_accounts_model_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GoaPanelAccountsModel *model = GOA_PANEL_ACCOUNTS_MODEL (object);
switch (prop_id)
{
case PROP_CLIENT:
g_value_set_object (value, goa_panel_accounts_model_get_client (model));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
goa_panel_accounts_model_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GoaPanelAccountsModel *model = GOA_PANEL_ACCOUNTS_MODEL (object);
switch (prop_id)
{
case PROP_CLIENT:
model->client = g_value_dup_object (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* ---------------------------------------------------------------------------------------------------- */
static void
goa_panel_accounts_model_constructed (GObject *object)
{
GoaPanelAccountsModel *model = GOA_PANEL_ACCOUNTS_MODEL (object);
GType types[GOA_PANEL_ACCOUNTS_MODEL_N_COLUMNS];
G_STATIC_ASSERT (5 == GOA_PANEL_ACCOUNTS_MODEL_N_COLUMNS);
types[0] = G_TYPE_STRING;
types[1] = GOA_TYPE_OBJECT;
types[2] = G_TYPE_BOOLEAN;
types[3] = G_TYPE_STRING;
types[4] = G_TYPE_ICON;
gtk_list_store_set_column_types (GTK_LIST_STORE (model),
GOA_PANEL_ACCOUNTS_MODEL_N_COLUMNS,
types);
gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (model),
GOA_PANEL_ACCOUNTS_MODEL_COLUMN_SORT_KEY,
GTK_SORT_ASCENDING);
g_signal_connect (model->client,
"account-added",
G_CALLBACK (on_account_added),
model);
g_signal_connect (model->client,
"account-removed",
G_CALLBACK (on_account_removed),
model);
g_signal_connect (model->client,
"account-changed",
G_CALLBACK (on_account_changed),
model);
init_model (model);
if (G_OBJECT_CLASS (goa_panel_accounts_model_parent_class)->constructed != NULL)
G_OBJECT_CLASS (goa_panel_accounts_model_parent_class)->constructed (object);
}
static void
goa_panel_accounts_model_class_init (GoaPanelAccountsModelClass *klass)
{
GObjectClass *gobject_class;
gobject_class = G_OBJECT_CLASS (klass);
gobject_class->finalize = goa_panel_accounts_model_finalize;
gobject_class->constructed = goa_panel_accounts_model_constructed;
gobject_class->get_property = goa_panel_accounts_model_get_property;
gobject_class->set_property = goa_panel_accounts_model_set_property;
/**
* GoaPanelAccountsModel:client:
*
* The #GoaClient used by the #GoaPanelAccountsModel instance.
*/
g_object_class_install_property (gobject_class,
PROP_CLIENT,
g_param_spec_object ("client",
"Client",
"The client used by the tree model",
GOA_TYPE_CLIENT,
G_PARAM_READABLE |
G_PARAM_WRITABLE |
G_PARAM_CONSTRUCT_ONLY |
G_PARAM_STATIC_STRINGS));
}
/**
* goa_panel_accounts_model_new:
* @client: A #GoaClient.
*
* Creates a new #GoaPanelAccountsModel for viewing the accounts known
* by @client.
*
* Returns: A #GoaPanelAccountsModel. Free with g_object_unref().
*/
GoaPanelAccountsModel *
goa_panel_accounts_model_new (GoaClient *client)
{
return GOA_PANEL_ACCOUNTS_MODEL (g_object_new (GOA_TYPE_PANEL_ACCOUNTS_MODEL,
"client", client,
NULL));
}
/**
* goa_panel_accounts_model_get_client:
* @model: A #GoaPanelAccountsModel.
*
* Gets the #GoaClient used by @model.
*
* Returns: (transfer none): A #GoaClient. Do not free, the object
* belongs to @model.
*/
GoaClient *
goa_panel_accounts_model_get_client (GoaPanelAccountsModel *model)
{
g_return_val_if_fail (GOA_IS_PANEL_ACCOUNTS_MODEL (model), NULL);
return model->client;
}
/**
* goa_panel_accounts_model_get_iter_for_object:
* @model: A #GoaPanelAccountsModel.
* @object: A #GoaObject.
* @iter: (out): Return location for #GtkTreeIter.
*
* Finds @model<!-- -->'s row for @object.
*
* Returns: %TRUE if @iter was set, %FALSE if @object wasn't found.
*/
gboolean
goa_panel_accounts_model_get_iter_for_object (GoaPanelAccountsModel *model,
GoaObject *object,
GtkTreeIter *iter)
{
g_return_val_if_fail (GOA_IS_PANEL_ACCOUNTS_MODEL (model), FALSE);
g_return_val_if_fail (GOA_IS_OBJECT (object), FALSE);
g_return_val_if_fail (iter != NULL, FALSE);
return find_iter_for_object (model, object, iter);
}
/* ---------------------------------------------------------------------------------------------------- */
typedef struct
{
GoaObject *object;
GtkTreeIter iter;
gboolean found;
} FindIterData;
static gboolean
find_iter_for_object_cb (GtkTreeModel *model,
GtkTreePath *path,
GtkTreeIter *iter,
gpointer user_data)
{
FindIterData *data = user_data;
GoaObject *iter_object;
iter_object = NULL;
gtk_tree_model_get (model,
iter,
GOA_PANEL_ACCOUNTS_MODEL_COLUMN_OBJECT, &iter_object,
-1);
if (iter_object == NULL)
goto out;
if (iter_object == data->object)
{
data->iter = *iter;
data->found = TRUE;
goto out;
}
out:
if (iter_object != NULL)
g_object_unref (iter_object);
return data->found;
}
static gboolean
find_iter_for_object (GoaPanelAccountsModel *model,
GoaObject *object,
GtkTreeIter *out_iter)
{
FindIterData data;
memset (&data, 0, sizeof (data));
data.object = object;
data.found = FALSE;
gtk_tree_model_foreach (GTK_TREE_MODEL (model),
find_iter_for_object_cb,
&data);
if (data.found)
{
if (out_iter != NULL)
*out_iter = data.iter;
}
return data.found;
}
/* ---------------------------------------------------------------------------------------------------- */
static void
set_values (GoaPanelAccountsModel *model,
GoaObject *object,
GtkTreeIter *iter)
{
GoaAccount *account;
GIcon *icon;
gchar *markup;
GError *error;
account = goa_object_peek_account (object);
error = NULL;
icon = g_icon_new_for_string (goa_account_get_provider_icon (account), &error);
if (icon == NULL)
{
goa_warning ("Error creating GIcon for account: %s (%s, %d)",
error->message, g_quark_to_string (error->domain), error->code);
g_error_free (error);
}
markup = g_strdup_printf ("<b>%s</b>\n<small>%s</small>",
goa_account_get_provider_name (account),
goa_account_get_presentation_identity (account));
gtk_list_store_set (GTK_LIST_STORE (model),
iter,
GOA_PANEL_ACCOUNTS_MODEL_COLUMN_SORT_KEY, goa_account_get_id (account),
GOA_PANEL_ACCOUNTS_MODEL_COLUMN_OBJECT, object,
GOA_PANEL_ACCOUNTS_MODEL_COLUMN_ATTENTION_NEEDED, goa_account_get_attention_needed (account),
GOA_PANEL_ACCOUNTS_MODEL_COLUMN_MARKUP, markup,
GOA_PANEL_ACCOUNTS_MODEL_COLUMN_ICON, icon,
-1);
g_free (markup);
g_clear_object (&icon);
}
static void
add_account (GoaPanelAccountsModel *model,
GoaObject *object)
{
GtkTreeIter iter;
gtk_list_store_insert (GTK_LIST_STORE (model),
&iter,
G_MAXINT); /* position */
set_values (model, object, &iter);
}
static void
remove_account (GoaPanelAccountsModel *model,
GoaObject *object)
{
GtkTreeIter iter;
if (!find_iter_for_object (model, object, &iter))
{
goa_warning ("Error removing object %s - not in tree", g_dbus_object_get_object_path (G_DBUS_OBJECT (object)));
}
else
{
gtk_list_store_remove (GTK_LIST_STORE (model), &iter);
}
}
static void
update_account (GoaPanelAccountsModel *model,
GoaObject *object)
{
GtkTreeIter iter;
if (!find_iter_for_object (model, object, &iter))
{
goa_warning ("Error updating object %s - not in tree", g_dbus_object_get_object_path (G_DBUS_OBJECT (object)));
}
else
{
set_values (model, object, &iter);
}
}
static void
init_model (GoaPanelAccountsModel *model)
{
GList *accounts;
GList *l;
accounts = goa_client_get_accounts (model->client);
for (l = accounts; l != NULL; l = l->next)
{
GoaObject *object = GOA_OBJECT (l->data);
add_account (model, object);
}
g_list_foreach (accounts, (GFunc) g_object_unref, NULL);
g_list_free (accounts);
}
static void
on_account_added (GoaClient *client,
GoaObject *object,
gpointer user_data)
{
GoaPanelAccountsModel *model = GOA_PANEL_ACCOUNTS_MODEL (user_data);
add_account (model, object);
}
static void
on_account_removed (GoaClient *client,
GoaObject *object,
gpointer user_data)
{
GoaPanelAccountsModel *model = GOA_PANEL_ACCOUNTS_MODEL (user_data);
remove_account (model, object);
}
static void
on_account_changed (GoaClient *client,
GoaObject *object,
gpointer user_data)
{
GoaPanelAccountsModel *model = GOA_PANEL_ACCOUNTS_MODEL (user_data);
update_account (model, object);
}
|
384 | ./cinnamon-control-center/panels/unused/online-accounts/cc-online-accounts-panel.c | /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
/*
* Copyright (C) 2011, 2012 Red Hat, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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.
*
* Author: David Zeuthen <[email protected]>
*/
#include "config.h"
#include <string.h>
#include <glib/gi18n-lib.h>
#define GOA_API_IS_SUBJECT_TO_CHANGE
#include <goa/goa.h>
#define GOA_BACKEND_API_IS_SUBJECT_TO_CHANGE
#include <goabackend/goabackend.h>
#include "cc-online-accounts-panel.h"
#include "cc-online-accounts-add-account-dialog.h"
#include "cc-online-accounts-model.h"
typedef struct _GoaPanelClass GoaPanelClass;
struct _GoaPanel
{
CcPanel parent_instance;
GtkBuilder *builder;
GoaClient *client;
GoaPanelAccountsModel *accounts_model;
GtkWidget *toolbar;
GtkWidget *toolbar_add_button;
GtkWidget *toolbar_remove_button;
GtkWidget *accounts_treeview;
GtkWidget *accounts_vbox;
};
struct _GoaPanelClass
{
CcPanelClass parent_class;
};
static void on_model_row_deleted (GtkTreeModel *tree_model,
GtkTreePath *path,
gpointer user_data);
static void on_model_row_inserted (GtkTreeModel *tree_model,
GtkTreePath *path,
GtkTreeIter *iter,
gpointer user_data);
static void on_tree_view_selection_changed (GtkTreeSelection *selection,
gpointer user_data);
static void on_toolbar_add_button_clicked (GtkToolButton *button,
gpointer user_data);
static void on_toolbar_remove_button_clicked (GtkToolButton *button,
gpointer user_data);
static void on_add_button_clicked (GtkButton *button,
gpointer user_data);
static void on_account_changed (GoaClient *client,
GoaObject *object,
gpointer user_data);
static gboolean select_account_by_id (GoaPanel *panel,
const gchar *account_id);
CC_PANEL_REGISTER (GoaPanel, goa_panel);
enum {
PROP_0,
PROP_ARGV
};
static void
goa_panel_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec)
{
switch (property_id)
{
case PROP_ARGV:
{
gchar **args;
args = g_value_get_boxed (value);
if (args != NULL && *args != '\0')
select_account_by_id (GOA_PANEL (object), args[0]);
return;
}
}
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}
static void
goa_panel_finalize (GObject *object)
{
GoaPanel *panel = GOA_PANEL (object);
if (panel->accounts_model != NULL)
g_clear_object (&panel->accounts_model);
if (panel->client != NULL)
g_object_unref (panel->client);
g_object_unref (panel->builder);
G_OBJECT_CLASS (goa_panel_parent_class)->finalize (object);
}
static void
goa_panel_init (GoaPanel *panel)
{
GtkWidget *button;
GtkWidget *w;
GError *error;
GtkStyleContext *context;
GtkTreeViewColumn *column;
GtkCellRenderer *renderer;
GtkTreeIter iter;
panel->builder = gtk_builder_new ();
error = NULL;
if (gtk_builder_add_from_file (panel->builder,
CINNAMONCC_UI_DIR "/online-accounts.ui",
&error) == 0)
{
goa_warning ("Error loading UI file: %s (%s, %d)",
error->message, g_quark_to_string (error->domain), error->code);
g_error_free (error);
goto out;
}
panel->toolbar = GTK_WIDGET (gtk_builder_get_object (panel->builder, "accounts-tree-toolbar"));
panel->toolbar_add_button = GTK_WIDGET (gtk_builder_get_object (panel->builder, "accounts-tree-toolbutton-add"));
g_signal_connect (panel->toolbar_add_button,
"clicked",
G_CALLBACK (on_toolbar_add_button_clicked),
panel);
panel->toolbar_remove_button = GTK_WIDGET (gtk_builder_get_object (panel->builder, "accounts-tree-toolbutton-remove"));
g_signal_connect (panel->toolbar_remove_button,
"clicked",
G_CALLBACK (on_toolbar_remove_button_clicked),
panel);
context = gtk_widget_get_style_context (GTK_WIDGET (gtk_builder_get_object (panel->builder, "accounts-tree-scrolledwindow")));
gtk_style_context_set_junction_sides (context, GTK_JUNCTION_BOTTOM);
context = gtk_widget_get_style_context (panel->toolbar);
gtk_style_context_set_junction_sides (context, GTK_JUNCTION_TOP);
panel->accounts_treeview = GTK_WIDGET (gtk_builder_get_object (panel->builder, "accounts-tree-treeview"));
g_signal_connect (gtk_tree_view_get_selection (GTK_TREE_VIEW (panel->accounts_treeview)),
"changed",
G_CALLBACK (on_tree_view_selection_changed),
panel);
button = GTK_WIDGET (gtk_builder_get_object (panel->builder, "accounts-button-add"));
g_signal_connect (button,
"clicked",
G_CALLBACK (on_add_button_clicked),
panel);
panel->accounts_vbox = GTK_WIDGET (gtk_builder_get_object (panel->builder, "accounts-vbox"));
/* TODO: probably want to avoid _sync() ... */
error = NULL;
panel->client = goa_client_new_sync (NULL /* GCancellable */, &error);
if (panel->client == NULL)
{
goa_warning ("Error getting a GoaClient: %s (%s, %d)",
error->message, g_quark_to_string (error->domain), error->code);
w = GTK_WIDGET (gtk_builder_get_object (panel->builder, "goa-top-widget"));
gtk_widget_set_sensitive (w, FALSE);
g_error_free (error);
goto out;
}
g_signal_connect (panel->client,
"account-changed",
G_CALLBACK (on_account_changed),
panel);
panel->accounts_model = goa_panel_accounts_model_new (panel->client);
gtk_tree_view_set_model (GTK_TREE_VIEW (panel->accounts_treeview), GTK_TREE_MODEL (panel->accounts_model));
g_signal_connect (panel->accounts_model, "row-deleted", G_CALLBACK (on_model_row_deleted), panel);
g_signal_connect (panel->accounts_model, "row-inserted", G_CALLBACK (on_model_row_inserted), panel);
column = gtk_tree_view_column_new ();
gtk_tree_view_append_column (GTK_TREE_VIEW (panel->accounts_treeview), column);
renderer = gtk_cell_renderer_pixbuf_new ();
gtk_tree_view_column_pack_start (column, renderer, FALSE);
g_object_set (G_OBJECT (renderer),
"stock-size", GTK_ICON_SIZE_DIALOG,
NULL);
gtk_tree_view_column_set_attributes (column,
renderer,
"gicon", GOA_PANEL_ACCOUNTS_MODEL_COLUMN_ICON,
NULL);
renderer = gtk_cell_renderer_text_new ();
gtk_tree_view_column_pack_start (column, renderer, FALSE);
g_object_set (G_OBJECT (renderer),
"ellipsize", PANGO_ELLIPSIZE_END,
"ellipsize-set", TRUE,
"width-chars", 30,
NULL);
gtk_tree_view_column_set_attributes (column,
renderer,
"markup", GOA_PANEL_ACCOUNTS_MODEL_COLUMN_MARKUP,
NULL);
renderer = gtk_cell_renderer_pixbuf_new ();
gtk_tree_view_column_pack_end (column, renderer, FALSE);
g_object_set (G_OBJECT (renderer),
"icon-name", "dialog-error-symbolic",
NULL);
gtk_tree_view_column_set_attributes (column,
renderer,
"visible", GOA_PANEL_ACCOUNTS_MODEL_COLUMN_ATTENTION_NEEDED,
NULL);
/* Select the first row, if any */
if (gtk_tree_model_get_iter_first (GTK_TREE_MODEL (panel->accounts_model),
&iter))
gtk_tree_selection_select_iter (gtk_tree_view_get_selection (GTK_TREE_VIEW (panel->accounts_treeview)),
&iter);
out:
w = GTK_WIDGET (gtk_builder_get_object (panel->builder, "goa-top-widget"));
gtk_widget_reparent (w, GTK_WIDGET (panel));
gtk_widget_show_all (w);
}
static const char *
goa_panel_get_help_uri (CcPanel *panel)
{
if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity"))
return "help:ubuntu-help/accounts";
else
return "help:gnome-help/accounts";
}
static void
goa_panel_class_init (GoaPanelClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
CcPanelClass *panel_class = CC_PANEL_CLASS (klass);
panel_class->get_help_uri = goa_panel_get_help_uri;
object_class->set_property = goa_panel_set_property;
object_class->finalize = goa_panel_finalize;
g_object_class_override_property (object_class, PROP_ARGV, "argv");
}
/* ---------------------------------------------------------------------------------------------------- */
static void
goa_panel_register (GIOModule *module)
{
goa_panel_register_type (G_TYPE_MODULE (module));
g_io_extension_point_implement (CC_SHELL_PANEL_EXTENSION_POINT,
GOA_TYPE_PANEL,
"online-accounts",
0);
}
void
g_io_module_load (GIOModule *module)
{
bindtextdomain (GETTEXT_PACKAGE, CINNAMONLOCALEDIR);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
goa_panel_register (module);
}
void
g_io_module_unload (GIOModule *module)
{
}
/* ---------------------------------------------------------------------------------------------------- */
static void
show_page (GoaPanel *panel,
gint page_num)
{
GtkNotebook *notebook;
notebook = GTK_NOTEBOOK (gtk_builder_get_object (panel->builder, "accounts-notebook"));
gtk_notebook_set_current_page (notebook, page_num);
}
static void
show_page_nothing_selected (GoaPanel *panel)
{
GtkWidget *box;
GtkWidget *label;
show_page (panel, 0);
box = GTK_WIDGET (gtk_builder_get_object (panel->builder, "accounts-tree-box"));
gtk_widget_set_sensitive (box, FALSE);
label = GTK_WIDGET (gtk_builder_get_object (panel->builder, "accounts-tree-label"));
gtk_widget_show (label);
}
static void
on_info_bar_response (GtkInfoBar *info_bar,
gint response_id,
gpointer user_data)
{
GoaPanel *panel = GOA_PANEL (user_data);
GtkTreeIter iter;
if (gtk_tree_selection_get_selected (gtk_tree_view_get_selection (GTK_TREE_VIEW (panel->accounts_treeview)),
NULL,
&iter))
{
GoaProvider *provider;
const gchar *provider_type;
GoaAccount *account;
GoaObject *object;
GtkWindow *parent;
GError *error;
gtk_tree_model_get (GTK_TREE_MODEL (panel->accounts_model),
&iter,
GOA_PANEL_ACCOUNTS_MODEL_COLUMN_OBJECT, &object,
-1);
account = goa_object_peek_account (object);
provider_type = goa_account_get_provider_type (account);
provider = goa_provider_get_for_provider_type (provider_type);
parent = GTK_WINDOW (cc_shell_get_toplevel (cc_panel_get_shell (CC_PANEL (panel))));
error = NULL;
if (!goa_provider_refresh_account (provider,
panel->client,
object,
parent,
&error))
{
if (!(error->domain == GOA_ERROR && error->code == GOA_ERROR_DIALOG_DISMISSED))
{
GtkWidget *dialog;
dialog = gtk_message_dialog_new (parent,
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_ERROR,
GTK_BUTTONS_CLOSE,
_("Error logging into the account"));
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
"%s",
error->message);
gtk_widget_show_all (dialog);
gtk_dialog_run (GTK_DIALOG (dialog));
gtk_widget_destroy (dialog);
}
g_error_free (error);
}
g_object_unref (provider);
g_object_unref (object);
}
}
static void
show_page_account (GoaPanel *panel,
GoaObject *object)
{
GList *children;
GList *l;
GtkWidget *box;
GtkWidget *grid;
GtkWidget *left_grid;
GtkWidget *right_grid;
GtkWidget *bar;
GtkWidget *label;
GoaProvider *provider;
GoaAccount *account;
const gchar *provider_type;
provider = NULL;
show_page (panel, 1);
box = GTK_WIDGET (gtk_builder_get_object (panel->builder, "accounts-tree-box"));
gtk_widget_set_sensitive (box, TRUE);
label = GTK_WIDGET (gtk_builder_get_object (panel->builder, "accounts-tree-label"));
gtk_widget_hide (label);
/* Out with the old */
children = gtk_container_get_children (GTK_CONTAINER (panel->accounts_vbox));
for (l = children; l != NULL; l = l->next)
gtk_container_remove (GTK_CONTAINER (panel->accounts_vbox), GTK_WIDGET (l->data));
g_list_free (children);
account = goa_object_peek_account (object);
provider_type = goa_account_get_provider_type (account);
provider = goa_provider_get_for_provider_type (provider_type);
/* And in with the new */
if (goa_account_get_attention_needed (account))
{
bar = gtk_info_bar_new ();
label = gtk_label_new (_("Expired credentials. Please log in again."));
gtk_container_add (GTK_CONTAINER (gtk_info_bar_get_content_area (GTK_INFO_BAR (bar))), label);
if (provider != NULL)
gtk_info_bar_add_button (GTK_INFO_BAR (bar), _("_Log In"), GTK_RESPONSE_OK);
gtk_box_pack_start (GTK_BOX (panel->accounts_vbox), bar, FALSE, TRUE, 0);
g_signal_connect (bar, "response", G_CALLBACK (on_info_bar_response), panel);
}
left_grid = gtk_grid_new ();
gtk_widget_set_halign (left_grid, GTK_ALIGN_END);
gtk_widget_set_hexpand (left_grid, TRUE);
gtk_orientable_set_orientation (GTK_ORIENTABLE (left_grid), GTK_ORIENTATION_VERTICAL);
gtk_grid_set_row_spacing (GTK_GRID (left_grid), 0);
right_grid = gtk_grid_new ();
gtk_widget_set_hexpand (right_grid, TRUE);
gtk_orientable_set_orientation (GTK_ORIENTABLE (right_grid), GTK_ORIENTATION_VERTICAL);
gtk_grid_set_row_spacing (GTK_GRID (right_grid), 0);
if (provider != NULL)
{
goa_provider_show_account (provider,
panel->client,
object,
GTK_BOX (panel->accounts_vbox),
GTK_GRID (left_grid),
GTK_GRID (right_grid));
}
grid = gtk_grid_new ();
gtk_orientable_set_orientation (GTK_ORIENTABLE (grid), GTK_ORIENTATION_HORIZONTAL);
gtk_grid_set_column_spacing (GTK_GRID (grid), 12);
gtk_container_add (GTK_CONTAINER (grid), left_grid);
gtk_container_add (GTK_CONTAINER (grid), right_grid);
gtk_box_pack_start (GTK_BOX (panel->accounts_vbox), grid, FALSE, TRUE, 0);
gtk_widget_show_all (panel->accounts_vbox);
if (provider != NULL)
g_object_unref (provider);
}
/* ---------------------------------------------------------------------------------------------------- */
static gboolean
select_account_by_id (GoaPanel *panel,
const gchar *account_id)
{
GoaObject *goa_object = NULL;
GtkTreeIter iter;
gboolean iter_set = FALSE;
goa_object = goa_client_lookup_by_id (panel->client, account_id);
if (goa_object != NULL)
{
iter_set = goa_panel_accounts_model_get_iter_for_object (panel->accounts_model,
goa_object,
&iter);
g_object_unref (goa_object);
}
if (iter_set)
{
GtkTreeView *tree_view;
GtkTreeSelection *selection;
tree_view = GTK_TREE_VIEW (panel->accounts_treeview);
selection = gtk_tree_view_get_selection (tree_view);
gtk_tree_selection_select_iter (selection, &iter);
}
return iter_set;
}
static void
on_tree_view_selection_changed (GtkTreeSelection *selection,
gpointer user_data)
{
GoaPanel *panel = GOA_PANEL (user_data);
GtkTreeIter iter;
if (gtk_tree_selection_get_selected (selection, NULL, &iter))
{
GoaObject *object;
gtk_tree_model_get (GTK_TREE_MODEL (panel->accounts_model),
&iter,
GOA_PANEL_ACCOUNTS_MODEL_COLUMN_OBJECT, &object,
-1);
show_page_account (panel, object);
g_object_unref (object);
}
else
{
show_page_nothing_selected (panel);
}
}
static void
on_account_changed (GoaClient *client,
GoaObject *object,
gpointer user_data)
{
GoaPanel *panel = GOA_PANEL (user_data);
GtkTreeIter iter;
if (gtk_tree_selection_get_selected (gtk_tree_view_get_selection (GTK_TREE_VIEW (panel->accounts_treeview)),
NULL,
&iter))
{
GoaObject *selected_object;
gtk_tree_model_get (GTK_TREE_MODEL (panel->accounts_model),
&iter,
GOA_PANEL_ACCOUNTS_MODEL_COLUMN_OBJECT, &selected_object,
-1);
if (selected_object == object)
show_page_account (panel, selected_object);
g_object_unref (selected_object);
}
}
/* ---------------------------------------------------------------------------------------------------- */
static void
on_model_row_changed (GtkTreeModel *tree_model,
GtkTreePath *path,
GtkTreeIter *iter,
gpointer user_data)
{
GtkTreeSelection *selection = GTK_TREE_SELECTION (user_data);
gtk_tree_selection_select_iter (selection, iter);
g_signal_handlers_disconnect_by_func (tree_model, G_CALLBACK (on_model_row_changed), user_data);
}
static void
on_model_row_deleted (GtkTreeModel *tree_model,
GtkTreePath *path,
gpointer user_data)
{
GoaPanel *panel = GOA_PANEL (user_data);
GtkTreeIter iter;
GtkTreeSelection *selection;
if (!gtk_tree_model_get_iter (tree_model, &iter, path))
{
if (!gtk_tree_path_prev (path))
return;
}
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (panel->accounts_treeview));
gtk_tree_selection_select_path (selection, path);
}
static void
on_model_row_inserted (GtkTreeModel *tree_model,
GtkTreePath *path,
GtkTreeIter *iter,
gpointer user_data)
{
GoaPanel *panel = GOA_PANEL (user_data);
GtkTreeSelection *selection;
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (panel->accounts_treeview));
if (gtk_tree_selection_get_selected (selection, NULL, NULL))
return;
/* An empty row has been inserted and is going to be filled in, so
* we expect selection to stay valid.
*/
g_signal_connect (tree_model, "row-changed", G_CALLBACK (on_model_row_changed), selection);
}
/* ---------------------------------------------------------------------------------------------------- */
static void
add_account (GoaPanel *panel)
{
GtkWindow *parent;
GtkWidget *dialog;
gint response;
GList *providers;
GList *l;
GoaObject *object;
GError *error;
providers = NULL;
parent = GTK_WINDOW (cc_shell_get_toplevel (cc_panel_get_shell (CC_PANEL (panel))));
dialog = goa_panel_add_account_dialog_new (panel->client);
gtk_window_set_transient_for (GTK_WINDOW (dialog), parent);
providers = goa_provider_get_all ();
for (l = providers; l != NULL; l = l->next)
{
GoaProvider *provider;
provider = GOA_PROVIDER (l->data);
goa_panel_add_account_dialog_add_provider (GOA_PANEL_ADD_ACCOUNT_DIALOG (dialog), provider);
}
gtk_widget_show_all (dialog);
response = gtk_dialog_run (GTK_DIALOG (dialog));
if (response != GTK_RESPONSE_OK)
{
gtk_widget_destroy (dialog);
goto out;
}
error = NULL;
object = goa_panel_add_account_dialog_get_account (GOA_PANEL_ADD_ACCOUNT_DIALOG (dialog), &error);
gtk_widget_destroy (dialog);
/* We might have an object even when error is set.
* eg., if we failed to store the credentials in the keyring.
*/
if (object != NULL)
{
GtkTreeIter iter;
/* navigate to newly created object */
if (goa_panel_accounts_model_get_iter_for_object (panel->accounts_model,
object,
&iter))
{
gtk_tree_selection_select_iter (gtk_tree_view_get_selection (GTK_TREE_VIEW (panel->accounts_treeview)),
&iter);
}
g_object_unref (object);
}
if (error != NULL)
{
if (!(error->domain == GOA_ERROR && error->code == GOA_ERROR_DIALOG_DISMISSED))
{
dialog = gtk_message_dialog_new (parent,
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_ERROR,
GTK_BUTTONS_CLOSE,
_("Error creating account"));
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
"%s",
error->message);
gtk_widget_show_all (dialog);
gtk_dialog_run (GTK_DIALOG (dialog));
gtk_widget_destroy (dialog);
}
g_error_free (error);
}
out:
g_list_foreach (providers, (GFunc) g_object_unref, NULL);
g_list_free (providers);
}
/* ---------------------------------------------------------------------------------------------------- */
static void
on_toolbar_add_button_clicked (GtkToolButton *button,
gpointer user_data)
{
GoaPanel *panel = GOA_PANEL (user_data);
add_account (panel);
}
static void
remove_account_cb (GoaAccount *account,
GAsyncResult *res,
gpointer user_data)
{
GoaPanel *panel = GOA_PANEL (user_data);
GError *error;
error = NULL;
if (!goa_account_call_remove_finish (account, res, &error))
{
GtkWidget *dialog;
dialog = gtk_message_dialog_new (GTK_WINDOW (cc_shell_get_toplevel (cc_panel_get_shell (CC_PANEL (panel)))),
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_ERROR,
GTK_BUTTONS_CLOSE,
_("Error removing account"));
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
"%s",
error->message);
gtk_widget_show_all (dialog);
gtk_dialog_run (GTK_DIALOG (dialog));
gtk_widget_destroy (dialog);
g_error_free (error);
}
g_object_unref (panel);
}
static void
on_toolbar_remove_button_clicked (GtkToolButton *button,
gpointer user_data)
{
GoaPanel *panel = GOA_PANEL (user_data);
GtkTreeIter iter;
if (gtk_tree_selection_get_selected (gtk_tree_view_get_selection (GTK_TREE_VIEW (panel->accounts_treeview)),
NULL,
&iter))
{
GoaObject *object;
GtkWidget *dialog;
gint response;
gtk_tree_model_get (GTK_TREE_MODEL (panel->accounts_model),
&iter,
GOA_PANEL_ACCOUNTS_MODEL_COLUMN_OBJECT, &object,
-1);
dialog = gtk_message_dialog_new (GTK_WINDOW (cc_shell_get_toplevel (cc_panel_get_shell (CC_PANEL (panel)))),
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_QUESTION,
GTK_BUTTONS_CANCEL,
_("Are you sure you want to remove the account?"));
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
_("This will not remove the account on the server."));
gtk_dialog_add_button (GTK_DIALOG (dialog), _("_Remove"), GTK_RESPONSE_OK);
gtk_widget_show_all (dialog);
response = gtk_dialog_run (GTK_DIALOG (dialog));
gtk_widget_destroy (dialog);
if (response == GTK_RESPONSE_OK)
{
goa_account_call_remove (goa_object_peek_account (object),
NULL, /* GCancellable */
(GAsyncReadyCallback) remove_account_cb,
g_object_ref (panel));
}
g_object_unref (object);
}
}
/* ---------------------------------------------------------------------------------------------------- */
static void
on_add_button_clicked (GtkButton *button,
gpointer user_data)
{
GoaPanel *panel = GOA_PANEL (user_data);
add_account (panel);
}
|
385 | ./cinnamon-control-center/panels/unused/wacom/cc-wacom-nav-button.c | /*
* Copyright © 2011 Red Hat, Inc.
*
* 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.
*
* Authors: Bastien Nocera <[email protected]>
*
*/
#include <config.h>
#include <glib/gi18n.h>
#include <gtk/gtk.h>
#include "cc-wacom-nav-button.h"
G_DEFINE_TYPE (CcWacomNavButton, cc_wacom_nav_button, GTK_TYPE_BOX)
#define WACOM_NAV_BUTTON_PRIVATE(o) \
(G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_WACOM_NAV_BUTTON, CcWacomNavButtonPrivate))
struct _CcWacomNavButtonPrivate
{
GtkNotebook *notebook;
GtkWidget *label;
GtkWidget *prev;
GtkWidget *next;
guint page_added_id;
guint page_removed_id;
guint page_switched_id;
gboolean ignore_first_page;
};
enum {
PROP_0,
PROP_NOTEBOOK,
PROP_IGNORE_FIRST
};
static void
cc_wacom_nav_button_update (CcWacomNavButton *nav)
{
CcWacomNavButtonPrivate *priv = nav->priv;
int num_pages;
int current_page;
char *text;
if (priv->notebook == NULL) {
gtk_widget_hide (GTK_WIDGET (nav));
return;
}
num_pages = gtk_notebook_get_n_pages (GTK_NOTEBOOK (priv->notebook));
if (num_pages == 0)
return;
if (priv->ignore_first_page && num_pages == 1)
return;
if (priv->ignore_first_page)
num_pages--;
g_assert (num_pages >= 1);
if (num_pages == 1)
gtk_widget_hide (GTK_WIDGET (nav));
else
gtk_widget_show (GTK_WIDGET (nav));
current_page = gtk_notebook_get_current_page (GTK_NOTEBOOK (priv->notebook));
if (current_page < 0)
return;
if (priv->ignore_first_page)
current_page--;
gtk_widget_set_sensitive (priv->prev, current_page == 0 ? FALSE : TRUE);
gtk_widget_set_sensitive (priv->next, current_page + 1 == num_pages ? FALSE : TRUE);
text = g_strdup_printf (_("%d of %d"),
current_page + 1,
num_pages);
gtk_label_set_text (GTK_LABEL (priv->label), text);
}
static void
pages_changed (GtkNotebook *notebook,
GtkWidget *child,
guint page_num,
CcWacomNavButton *nav)
{
cc_wacom_nav_button_update (nav);
}
static void
page_switched (GtkNotebook *notebook,
GParamSpec *pspec,
CcWacomNavButton *nav)
{
cc_wacom_nav_button_update (nav);
}
static void
next_clicked (GtkButton *button,
CcWacomNavButton *nav)
{
int current_page;
current_page = gtk_notebook_get_current_page (GTK_NOTEBOOK (nav->priv->notebook));
current_page++;
gtk_notebook_set_current_page (GTK_NOTEBOOK (nav->priv->notebook), current_page);
}
static void
prev_clicked (GtkButton *button,
CcWacomNavButton *nav)
{
int current_page;
current_page = gtk_notebook_get_current_page (GTK_NOTEBOOK (nav->priv->notebook));
current_page--;
gtk_notebook_set_current_page (GTK_NOTEBOOK (nav->priv->notebook), current_page--);
}
static void
cc_wacom_nav_button_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec)
{
CcWacomNavButton *nav = CC_WACOM_NAV_BUTTON (object);
CcWacomNavButtonPrivate *priv = nav->priv;
switch (property_id) {
case PROP_NOTEBOOK:
if (priv->notebook) {
g_signal_handler_disconnect (priv->notebook, priv->page_added_id);
g_signal_handler_disconnect (priv->notebook, priv->page_removed_id);
g_signal_handler_disconnect (priv->notebook, priv->page_switched_id);
g_object_unref (priv->notebook);
}
priv->notebook = g_value_dup_object (value);
priv->page_added_id = g_signal_connect (G_OBJECT (priv->notebook), "page-added",
G_CALLBACK (pages_changed), nav);
priv->page_removed_id = g_signal_connect (G_OBJECT (priv->notebook), "page-removed",
G_CALLBACK (pages_changed), nav);
priv->page_switched_id = g_signal_connect (G_OBJECT (priv->notebook), "notify::page",
G_CALLBACK (page_switched), nav);
cc_wacom_nav_button_update (nav);
break;
case PROP_IGNORE_FIRST:
priv->ignore_first_page = g_value_get_boolean (value);
cc_wacom_nav_button_update (nav);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}
}
static void
cc_wacom_nav_button_dispose (GObject *object)
{
CcWacomNavButtonPrivate *priv = CC_WACOM_NAV_BUTTON (object)->priv;
if (priv->notebook) {
g_signal_handler_disconnect (priv->notebook, priv->page_added_id);
priv->page_added_id = 0;
g_signal_handler_disconnect (priv->notebook, priv->page_removed_id);
priv->page_removed_id = 0;
g_signal_handler_disconnect (priv->notebook, priv->page_switched_id);
priv->page_switched_id = 0;
g_object_unref (priv->notebook);
priv->notebook = NULL;
}
G_OBJECT_CLASS (cc_wacom_nav_button_parent_class)->dispose (object);
}
static void
cc_wacom_nav_button_class_init (CcWacomNavButtonClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
g_type_class_add_private (klass, sizeof (CcWacomNavButtonPrivate));
object_class->set_property = cc_wacom_nav_button_set_property;
object_class->dispose = cc_wacom_nav_button_dispose;
g_object_class_install_property (object_class, PROP_NOTEBOOK,
g_param_spec_object ("notebook", "notebook", "notebook",
GTK_TYPE_NOTEBOOK,
G_PARAM_WRITABLE));
g_object_class_install_property (object_class, PROP_IGNORE_FIRST,
g_param_spec_boolean ("ignore-first", "ignore-first", "ignore-first",
FALSE,
G_PARAM_WRITABLE));
}
static void
cc_wacom_nav_button_init (CcWacomNavButton *self)
{
CcWacomNavButtonPrivate *priv;
GtkStyleContext *context;
GtkWidget *image, *box;
priv = self->priv = WACOM_NAV_BUTTON_PRIVATE (self);
/* Label */
priv->label = gtk_label_new (NULL);
gtk_style_context_add_class (gtk_widget_get_style_context (priv->label), "dim-label");
gtk_box_pack_start (GTK_BOX (self), priv->label,
FALSE, FALSE, 8);
box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
context = gtk_widget_get_style_context (GTK_WIDGET (box));
gtk_style_context_add_class (context, GTK_STYLE_CLASS_LINKED);
gtk_box_pack_start (GTK_BOX (self), box,
FALSE, FALSE, 0);
/* Prev button */
priv->prev = gtk_button_new ();
image = gtk_image_new_from_icon_name ("go-previous-symbolic", GTK_ICON_SIZE_MENU);
gtk_container_add (GTK_CONTAINER (priv->prev), image);
g_signal_connect (G_OBJECT (priv->prev), "clicked",
G_CALLBACK (prev_clicked), self);
gtk_widget_set_valign (priv->prev, GTK_ALIGN_CENTER);
/* Next button */
priv->next = gtk_button_new ();
image = gtk_image_new_from_icon_name ("go-next-symbolic", GTK_ICON_SIZE_MENU);
gtk_container_add (GTK_CONTAINER (priv->next), image);
g_signal_connect (G_OBJECT (priv->next), "clicked",
G_CALLBACK (next_clicked), self);
gtk_widget_set_valign (priv->next, GTK_ALIGN_CENTER);
gtk_box_pack_start (GTK_BOX (box), priv->prev,
FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (box), priv->next,
FALSE, FALSE, 0);
gtk_widget_show (priv->label);
gtk_widget_show_all (box);
}
GtkWidget *
cc_wacom_nav_button_new (void)
{
return GTK_WIDGET (g_object_new (CC_TYPE_WACOM_NAV_BUTTON, NULL));
}
|
386 | ./cinnamon-control-center/panels/unused/wacom/cc-wacom-mapping-panel.c | /*
* Copyright © 2012 Wacom.
*
* 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.
*
* Authors: Jason Gerecke <[email protected]>
*
*/
#include <config.h>
#include <gtk/gtk.h>
#include <glib/gi18n.h>
#define GNOME_DESKTOP_USE_UNSTABLE_API
#include <libgnome-desktop/gnome-rr.h>
#include <libgnome-desktop/gnome-rr-config.h>
#include <string.h>
#include "gsd-wacom-device.h"
#include "cc-wacom-mapping-panel.h"
G_DEFINE_TYPE (CcWacomMappingPanel, cc_wacom_mapping_panel, GTK_TYPE_BOX)
#define WACOM_MAPPING_PANEL_PRIVATE(o) \
(G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_WACOM_MAPPING_PANEL, CcWacomMappingPanelPrivate))
struct _CcWacomMappingPanelPrivate
{
GsdWacomDevice *device;
GtkWidget *label;
GtkWidget *combobox;
GtkWidget *checkbutton;
GtkWidget *aspectlabel;
GtkWidget *aspectswitch;
};
enum {
MONITOR_NAME_COLUMN,
MONITOR_NUM_COLUMN,
MONITOR_NUM_COLUMNS
};
static void combobox_changed_cb (GtkWidget *widget, CcWacomMappingPanel *self);
static void checkbutton_toggled_cb (GtkWidget *widget, CcWacomMappingPanel *self);
static void aspectswitch_toggled_cb (GtkWidget *widget, GParamSpec *pspec, CcWacomMappingPanel *self);
static GnomeRROutputInfo**
get_rr_outputs (void)
{
GError *error = NULL;
GnomeRRScreen *rr_screen;
GnomeRRConfig *rr_config;
/* TODO: Check the value of 'error' */
rr_screen = gnome_rr_screen_new (gdk_screen_get_default (), &error);
rr_config = gnome_rr_config_new_current (rr_screen, &error);
return gnome_rr_config_get_outputs (rr_config);
}
static void
set_combobox_sensitive (CcWacomMappingPanel *self,
gboolean sensitive)
{
gtk_widget_set_sensitive (GTK_WIDGET(self->priv->combobox), sensitive);
gtk_widget_set_sensitive (GTK_WIDGET(self->priv->label), sensitive);
gtk_widget_set_sensitive (GTK_WIDGET(self->priv->aspectswitch), sensitive);
gtk_widget_set_sensitive (GTK_WIDGET(self->priv->aspectlabel), sensitive);
}
/* Update the display of available monitors based on the latest
* information from RandR. At the moment the chooser is just a
* a combobox crudely listing available outputs. The UI mockup
* has something more akin to the Display panel, with the ability
* to do rubber-band selection of multiple outputs (note: the
* g-s-d backend can only handle a single output at the moment)
*/
static void
update_monitor_chooser (CcWacomMappingPanel *self)
{
GtkListStore *store;
GnomeRROutputInfo **outputs;
GdkRectangle geom;
GSettings *settings;
gint monitor;
gboolean single_mon;
guint i;
store = gtk_list_store_new (MONITOR_NUM_COLUMNS, G_TYPE_STRING, G_TYPE_INT);
gtk_combo_box_set_model (GTK_COMBO_BOX(self->priv->combobox), GTK_TREE_MODEL(store));
if (self->priv->device == NULL) {
set_combobox_sensitive (self, FALSE);
g_object_unref (store);
return;
}
settings = gsd_wacom_device_get_settings (self->priv->device);
monitor = gsd_wacom_device_get_display_monitor (self->priv->device);
single_mon = (monitor != GSD_WACOM_SET_ALL_MONITORS);
g_signal_handlers_block_by_func (G_OBJECT (self->priv->checkbutton), checkbutton_toggled_cb, self);
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON(self->priv->checkbutton), single_mon);
g_signal_handlers_unblock_by_func (G_OBJECT (self->priv->checkbutton), checkbutton_toggled_cb, self);
g_signal_handlers_block_by_func (G_OBJECT (self->priv->aspectswitch), aspectswitch_toggled_cb, self);
gtk_switch_set_active (GTK_SWITCH(self->priv->aspectswitch), g_settings_get_boolean (settings, "keep-aspect"));
g_signal_handlers_unblock_by_func (G_OBJECT (self->priv->aspectswitch), aspectswitch_toggled_cb, self);
/* FIXME: does this break screen tablets? What's the default
* for unconfigured tablets? */
if (monitor < 0)
monitor = 0;
gdk_screen_get_monitor_geometry (gdk_screen_get_default (), monitor, &geom);
outputs = get_rr_outputs ();
if (outputs == NULL)
goto bail;
for (i = 0; outputs[i] != NULL; i++) {
GnomeRROutputInfo *output = outputs[i];
if (gnome_rr_output_info_is_active (output)) {
GtkTreeIter iter;
gchar *name, *disp_name, *text;
int x, y, w, h;
int mon_at_point;
name = gnome_rr_output_info_get_name (output);
disp_name = gnome_rr_output_info_get_display_name (output);
text = g_strdup_printf ("%s (%s)", name, disp_name);
gnome_rr_output_info_get_geometry (output, &x, &y, &w, &h);
mon_at_point = gdk_screen_get_monitor_at_point (gdk_screen_get_default (), x, y);
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, MONITOR_NAME_COLUMN, text, MONITOR_NUM_COLUMN, mon_at_point, -1);
if (x == geom.x && y == geom.y && w == geom.width && h == geom.height) {
g_signal_handlers_block_by_func (G_OBJECT (self->priv->combobox), combobox_changed_cb, self);
gtk_combo_box_set_active_iter (GTK_COMBO_BOX(self->priv->combobox), &iter);
g_signal_handlers_unblock_by_func (G_OBJECT (self->priv->combobox), combobox_changed_cb, self);
}
g_free (text);
}
}
bail:
set_combobox_sensitive (self, single_mon);
g_object_unref (store);
}
static void
update_ui (CcWacomMappingPanel *self)
{
if (self->priv->device == NULL) {
gtk_widget_set_sensitive (GTK_WIDGET(self->priv->checkbutton), FALSE);
gtk_toggle_button_set_inconsistent (GTK_TOGGLE_BUTTON(self->priv->checkbutton), TRUE);
} else {
gboolean is_screen_tablet;
is_screen_tablet = gsd_wacom_device_is_screen_tablet (self->priv->device);
gtk_widget_set_sensitive (GTK_WIDGET(self->priv->checkbutton), !is_screen_tablet);
gtk_toggle_button_set_inconsistent (GTK_TOGGLE_BUTTON(self->priv->checkbutton), FALSE);
}
update_monitor_chooser (self);
}
static void
update_mapping (CcWacomMappingPanel *self)
{
int monitor = GSD_WACOM_SET_ALL_MONITORS;
if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (self->priv->checkbutton))) {
GtkTreeIter iter;
GtkTreeModel *model;
char *name;
model = gtk_combo_box_get_model (GTK_COMBO_BOX (self->priv->combobox));
if (!gtk_combo_box_get_active_iter (GTK_COMBO_BOX (self->priv->combobox), &iter)) {
g_warning ("Map to single monitor checked, but no screen selected.");
return;
}
gtk_tree_model_get (model, &iter, MONITOR_NAME_COLUMN, &name, MONITOR_NUM_COLUMN, &monitor, -1);
}
gsd_wacom_device_set_display (self->priv->device, monitor);
if (monitor >= 0) {
GsdWacomRotation rotation;
GSettings *settings;
rotation = gsd_wacom_device_get_display_rotation (self->priv->device);
settings = gsd_wacom_device_get_settings (self->priv->device);
g_settings_set_string (settings,
"rotation",
gsd_wacom_device_rotation_type_to_name (rotation));
}
}
void
cc_wacom_mapping_panel_set_device (CcWacomMappingPanel *self,
GsdWacomDevice *device)
{
self->priv->device = device;
update_ui (self);
}
static void
checkbutton_toggled_cb (GtkWidget *widget,
CcWacomMappingPanel *self)
{
gboolean active;
active = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget));
set_combobox_sensitive (self, active);
if (!active)
gtk_switch_set_active (GTK_SWITCH(self->priv->aspectswitch), FALSE);
update_mapping (self);
}
static void
aspectswitch_toggled_cb (GtkWidget *widget,
GParamSpec *pspec,
CcWacomMappingPanel *self)
{
GSettings *settings;
settings = gsd_wacom_device_get_settings (self->priv->device);
g_settings_set_boolean (settings,
"keep-aspect",
gtk_switch_get_active (GTK_SWITCH (widget)));
}
static void
combobox_changed_cb (GtkWidget *widget,
CcWacomMappingPanel *self)
{
update_mapping (self);
}
static void
cc_wacom_mapping_panel_init (CcWacomMappingPanel *self)
{
CcWacomMappingPanelPrivate *priv;
GtkWidget *vbox, *grid;
GtkCellRenderer *renderer;
priv = self->priv = WACOM_MAPPING_PANEL_PRIVATE (self);
vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 8);
gtk_container_add (GTK_CONTAINER (self), vbox);
gtk_container_set_border_width (GTK_CONTAINER (self), 12);
gtk_widget_set_vexpand (GTK_WIDGET (vbox), TRUE);
gtk_widget_set_hexpand (GTK_WIDGET (vbox), TRUE);
/* Output Combobox */
grid = gtk_grid_new();
gtk_grid_set_row_spacing (GTK_GRID (grid), 10);
gtk_grid_set_column_spacing (GTK_GRID (grid), 10);
priv->label = gtk_label_new (_("Output:"));
gtk_widget_set_halign (priv->label, GTK_ALIGN_END);
priv->combobox = gtk_combo_box_new ();
g_signal_connect (G_OBJECT (priv->combobox), "changed",
G_CALLBACK (combobox_changed_cb), self);
renderer = gtk_cell_renderer_text_new ();
gtk_cell_layout_pack_start (GTK_CELL_LAYOUT(priv->combobox), renderer, TRUE);
gtk_cell_layout_add_attribute (GTK_CELL_LAYOUT(priv->combobox), renderer, "text", 0);
gtk_grid_attach (GTK_GRID(grid), GTK_WIDGET(priv->label), 0, 0, 1, 1);
gtk_grid_attach (GTK_GRID(grid), GTK_WIDGET(priv->combobox), 1, 0, 1, 1);
/* Keep ratio switch */
priv->aspectlabel = gtk_label_new (_("Keep aspect ratio (letterbox):"));
gtk_widget_set_halign (priv->aspectlabel, GTK_ALIGN_END);
priv->aspectswitch = gtk_switch_new ();
gtk_widget_set_halign (priv->aspectswitch, GTK_ALIGN_START);
gtk_switch_set_active (GTK_SWITCH (priv->aspectswitch), FALSE);
g_signal_connect (GTK_SWITCH (priv->aspectswitch), "notify::active",
G_CALLBACK (aspectswitch_toggled_cb), self);
gtk_grid_attach (GTK_GRID(grid), GTK_WIDGET(priv->aspectlabel), 0, 1, 1, 1);
gtk_grid_attach (GTK_GRID(grid), GTK_WIDGET(priv->aspectswitch), 1, 1, 1, 1);
/* Whole-desktop checkbox */
priv->checkbutton = gtk_check_button_new_with_label (_("Map to single monitor"));
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (priv->checkbutton), FALSE);
g_signal_connect (G_OBJECT (priv->checkbutton), "toggled",
G_CALLBACK (checkbutton_toggled_cb), self);
gtk_box_pack_start (GTK_BOX(vbox), GTK_WIDGET(priv->checkbutton),
FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX(vbox), GTK_WIDGET(grid),
FALSE, FALSE, 8);
/* Update display */
cc_wacom_mapping_panel_set_device (self, NULL);
gtk_widget_show_all(GTK_WIDGET(self));
}
GtkWidget *
cc_wacom_mapping_panel_new (void)
{
CcWacomMappingPanel *panel;
panel = CC_WACOM_MAPPING_PANEL(g_object_new (CC_TYPE_WACOM_MAPPING_PANEL, NULL));
panel->priv->device = NULL;
return GTK_WIDGET(panel);
}
static void
cc_wacom_mapping_panel_get_property (GObject *object,
guint property_id,
GValue *value,
GParamSpec *pspec)
{
switch (property_id)
{
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}
}
static void
cc_wacom_mapping_panel_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec)
{
switch (property_id)
{
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}
}
static void
cc_wacom_mapping_panel_dispose (GObject *object)
{
G_OBJECT_CLASS (cc_wacom_mapping_panel_parent_class)->dispose (object);
}
static void
cc_wacom_mapping_panel_class_init (CcWacomMappingPanelClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
g_type_class_add_private (klass, sizeof (CcWacomMappingPanelPrivate));
object_class->get_property = cc_wacom_mapping_panel_get_property;
object_class->set_property = cc_wacom_mapping_panel_set_property;
object_class->dispose = cc_wacom_mapping_panel_dispose;
}
|
387 | ./cinnamon-control-center/panels/unused/wacom/wacom-module.c | /*
* Copyright © Red Hat, Inc.
*
* 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.
*
* Author: Peter Hutterer <[email protected]>
*
*/
#include <config.h>
#include "cc-wacom-panel.h"
#include <glib/gi18n-lib.h>
void
g_io_module_load (GIOModule *module)
{
bindtextdomain (GETTEXT_PACKAGE, CINNAMONLOCALEDIR);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
/* register the panel */
cc_wacom_panel_register (module);
}
void
g_io_module_unload (GIOModule *module)
{
}
|
388 | ./cinnamon-control-center/panels/unused/wacom/test-wacom.c |
#include "config.h"
#include <glib/gi18n.h>
#include "cc-wacom-page.h"
#include "gsd-wacom-device.h"
#define FIXED_WIDTH 675
void
cc_wacom_panel_switch_to_panel (CcWacomPanel *self, const char *panel)
{
g_message ("Should launch display preferences here");
}
static void
add_page (GList *devices,
GtkWidget *notebook)
{
GtkWidget *widget;
GsdWacomDevice *stylus, *eraser, *pad;
GList *l;
if (devices == NULL)
return;
stylus = eraser = pad = NULL;
for (l = devices; l ; l = l->next) {
switch (gsd_wacom_device_get_device_type (l->data)) {
case WACOM_TYPE_ERASER:
eraser = l->data;
break;
case WACOM_TYPE_STYLUS:
stylus = l->data;
break;
case WACOM_TYPE_PAD:
pad = l->data;
break;
default:
/* Nothing */
;
}
}
g_list_free (devices);
widget = cc_wacom_page_new (NULL, stylus, eraser, pad);
cc_wacom_page_set_navigation (CC_WACOM_PAGE (widget), GTK_NOTEBOOK (notebook), FALSE);
gtk_notebook_append_page (GTK_NOTEBOOK (notebook), widget, NULL);
gtk_widget_show (widget);
}
static gboolean
delete_event_cb (GtkWidget *widget,
GdkEvent *event,
gpointer user_data)
{
gtk_main_quit ();
return FALSE;
}
int main (int argc, char **argv)
{
GtkWidget *window, *notebook;
GList *devices;
bindtextdomain (GETTEXT_PACKAGE, CINNAMONLOCALEDIR);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
textdomain (GETTEXT_PACKAGE);
gtk_init (&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_resizable (GTK_WINDOW (window), FALSE);
gtk_widget_set_size_request (window, FIXED_WIDTH, -1);
g_signal_connect (G_OBJECT (window), "delete-event",
G_CALLBACK (delete_event_cb), NULL);
notebook = gtk_notebook_new ();
gtk_notebook_set_show_tabs (GTK_NOTEBOOK (notebook), FALSE);
gtk_widget_set_vexpand (notebook, TRUE);
gtk_container_set_border_width (GTK_CONTAINER (notebook), 24);
gtk_container_add (GTK_CONTAINER (window), notebook);
gtk_widget_show (notebook);
devices = gsd_wacom_device_create_fake_intuos4 ();
add_page (devices, notebook);
devices = gsd_wacom_device_create_fake_cintiq ();
add_page (devices, notebook);
devices = gsd_wacom_device_create_fake_bt ();
add_page (devices, notebook);
devices = gsd_wacom_device_create_fake_x201 ();
add_page (devices, notebook);
gtk_widget_show (window);
gtk_main ();
return 0;
}
|
389 | ./cinnamon-control-center/panels/unused/wacom/gsd-wacom-device.c | /*
* Copyright (C) 2011 Red Hat, Inc.
*
* 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.
*
* Author: Bastien Nocera <[email protected]>
*
*/
#include "config.h"
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <gdk/gdkx.h>
#include <X11/Xatom.h>
#define GNOME_DESKTOP_USE_UNSTABLE_API
#include <libgnome-desktop/gnome-rr.h>
#include <libwacom/libwacom.h>
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>
#include "gsd-input-helper.h"
#include "gsd-enums.h"
#include "gsd-wacom-device.h"
#define GSD_WACOM_STYLUS_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GSD_TYPE_WACOM_STYLUS, GsdWacomStylusPrivate))
#define WACOM_TABLET_SCHEMA "org.cinnamon.settings-daemon.peripherals.wacom"
#define WACOM_DEVICE_CONFIG_BASE "/org/gnome/settings-daemon/peripherals/wacom/%s-%s/"
#define WACOM_STYLUS_SCHEMA "org.cinnamon.settings-daemon.peripherals.wacom.stylus"
#define WACOM_ERASER_SCHEMA "org.cinnamon.settings-daemon.peripherals.wacom.eraser"
#define WACOM_BUTTON_SCHEMA "org.cinnamon.settings-daemon.peripherals.wacom.tablet-button"
static struct {
GnomeRRRotation rotation;
GsdWacomRotation rotation_wacom;
const gchar *rotation_string;
} rotation_table[] = {
{ GNOME_RR_ROTATION_0, GSD_WACOM_ROTATION_NONE, "none" },
{ GNOME_RR_ROTATION_90, GSD_WACOM_ROTATION_CCW, "ccw" },
{ GNOME_RR_ROTATION_180, GSD_WACOM_ROTATION_HALF, "half" },
{ GNOME_RR_ROTATION_270, GSD_WACOM_ROTATION_CW, "cw" }
};
static WacomDeviceDatabase *db = NULL;
struct GsdWacomStylusPrivate
{
GsdWacomDevice *device;
int id;
WacomStylusType type;
char *name;
const char *icon_name;
GSettings *settings;
gboolean has_eraser;
int num_buttons;
};
static void gsd_wacom_stylus_class_init (GsdWacomStylusClass *klass);
static void gsd_wacom_stylus_init (GsdWacomStylus *wacom_stylus);
static void gsd_wacom_stylus_finalize (GObject *object);
G_DEFINE_TYPE (GsdWacomStylus, gsd_wacom_stylus, G_TYPE_OBJECT)
static void
gsd_wacom_stylus_class_init (GsdWacomStylusClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->finalize = gsd_wacom_stylus_finalize;
g_type_class_add_private (klass, sizeof (GsdWacomStylusPrivate));
}
static void
gsd_wacom_stylus_init (GsdWacomStylus *stylus)
{
stylus->priv = GSD_WACOM_STYLUS_GET_PRIVATE (stylus);
}
static void
gsd_wacom_stylus_finalize (GObject *object)
{
GsdWacomStylus *stylus;
GsdWacomStylusPrivate *p;
g_return_if_fail (object != NULL);
g_return_if_fail (GSD_IS_WACOM_STYLUS (object));
stylus = GSD_WACOM_STYLUS (object);
g_return_if_fail (stylus->priv != NULL);
p = stylus->priv;
if (p->settings != NULL) {
g_object_unref (p->settings);
p->settings = NULL;
}
g_free (p->name);
p->name = NULL;
G_OBJECT_CLASS (gsd_wacom_stylus_parent_class)->finalize (object);
}
static const char *
get_icon_name_from_type (WacomStylusType type)
{
switch (type) {
case WSTYLUS_INKING:
case WSTYLUS_STROKE:
/* The stroke pen is the same as the inking pen with
* a different nib */
return "wacom-stylus-inking";
case WSTYLUS_AIRBRUSH:
return "wacom-stylus-airbrush";
case WSTYLUS_MARKER:
return "wacom-stylus-art-pen";
case WSTYLUS_CLASSIC:
return "wacom-stylus-classic";
default:
return "wacom-stylus";
}
}
static GsdWacomStylus *
gsd_wacom_stylus_new (GsdWacomDevice *device,
const WacomStylus *wstylus,
GSettings *settings)
{
GsdWacomStylus *stylus;
g_return_val_if_fail (G_IS_SETTINGS (settings), NULL);
g_return_val_if_fail (wstylus != NULL, NULL);
stylus = GSD_WACOM_STYLUS (g_object_new (GSD_TYPE_WACOM_STYLUS,
NULL));
stylus->priv->device = device;
stylus->priv->id = libwacom_stylus_get_id (wstylus);
stylus->priv->name = g_strdup (libwacom_stylus_get_name (wstylus));
stylus->priv->settings = settings;
stylus->priv->type = libwacom_stylus_get_type (wstylus);
stylus->priv->icon_name = get_icon_name_from_type (stylus->priv->type);
stylus->priv->has_eraser = libwacom_stylus_has_eraser (wstylus);
stylus->priv->num_buttons = libwacom_stylus_get_num_buttons (wstylus);
return stylus;
}
GSettings *
gsd_wacom_stylus_get_settings (GsdWacomStylus *stylus)
{
g_return_val_if_fail (GSD_IS_WACOM_STYLUS (stylus), NULL);
return stylus->priv->settings;
}
const char *
gsd_wacom_stylus_get_name (GsdWacomStylus *stylus)
{
g_return_val_if_fail (GSD_IS_WACOM_STYLUS (stylus), NULL);
return stylus->priv->name;
}
const char *
gsd_wacom_stylus_get_icon_name (GsdWacomStylus *stylus)
{
g_return_val_if_fail (GSD_IS_WACOM_STYLUS (stylus), NULL);
return stylus->priv->icon_name;
}
GsdWacomDevice *
gsd_wacom_stylus_get_device (GsdWacomStylus *stylus)
{
g_return_val_if_fail (GSD_IS_WACOM_STYLUS (stylus), NULL);
return stylus->priv->device;
}
gboolean
gsd_wacom_stylus_get_has_eraser (GsdWacomStylus *stylus)
{
g_return_val_if_fail (GSD_IS_WACOM_STYLUS (stylus), FALSE);
return stylus->priv->has_eraser;
}
guint
gsd_wacom_stylus_get_num_buttons (GsdWacomStylus *stylus)
{
g_return_val_if_fail (GSD_IS_WACOM_STYLUS (stylus), -1);
return stylus->priv->num_buttons;
}
GsdWacomStylusType
gsd_wacom_stylus_get_stylus_type (GsdWacomStylus *stylus)
{
g_return_val_if_fail (GSD_IS_WACOM_STYLUS (stylus), WACOM_STYLUS_TYPE_UNKNOWN);
switch (stylus->priv->type) {
case WSTYLUS_UNKNOWN:
return WACOM_STYLUS_TYPE_UNKNOWN;
case WSTYLUS_GENERAL:
return WACOM_STYLUS_TYPE_GENERAL;
case WSTYLUS_INKING:
return WACOM_STYLUS_TYPE_INKING;
case WSTYLUS_AIRBRUSH:
return WACOM_STYLUS_TYPE_AIRBRUSH;
case WSTYLUS_CLASSIC:
return WACOM_STYLUS_TYPE_CLASSIC;
case WSTYLUS_MARKER:
return WACOM_STYLUS_TYPE_MARKER;
case WSTYLUS_STROKE:
return WACOM_STYLUS_TYPE_STROKE;
case WSTYLUS_PUCK:
return WACOM_STYLUS_TYPE_PUCK;
default:
g_assert_not_reached ();
}
return WACOM_STYLUS_TYPE_UNKNOWN;
}
int
gsd_wacom_stylus_get_id (GsdWacomStylus *stylus)
{
g_return_val_if_fail (GSD_IS_WACOM_STYLUS (stylus), -1);
return stylus->priv->id;
}
/* Tablet buttons */
static GsdWacomTabletButton *
gsd_wacom_tablet_button_new (const char *name,
const char *id,
const char *settings_path,
GsdWacomTabletButtonType type,
int group_id,
int idx)
{
GsdWacomTabletButton *ret;
ret = g_new0 (GsdWacomTabletButton, 1);
ret->name = g_strdup (name);
ret->id = g_strdup (id);
if (type != WACOM_TABLET_BUTTON_TYPE_HARDCODED) {
char *button_settings_path;
button_settings_path = g_strdup_printf ("%s%s/", settings_path, id);
ret->settings = g_settings_new_with_path (WACOM_BUTTON_SCHEMA, button_settings_path);
g_free (button_settings_path);
}
ret->group_id = group_id;
ret->idx = idx;
ret->type = type;
return ret;
}
void
gsd_wacom_tablet_button_free (GsdWacomTabletButton *button)
{
g_return_if_fail (button != NULL);
if (button->settings != NULL)
g_object_unref (button->settings);
g_free (button->name);
g_free (button->id);
g_free (button);
}
GsdWacomTabletButton *
gsd_wacom_tablet_button_copy (GsdWacomTabletButton *button)
{
GsdWacomTabletButton *ret;
g_return_val_if_fail (button != NULL, NULL);
ret = g_new0 (GsdWacomTabletButton, 1);
ret->name = g_strdup (button->name);
if (button->settings != NULL)
ret->settings = g_object_ref (button->settings);
ret->id = button->id;
ret->type = button->type;
ret->group_id = button->group_id;
return ret;
}
#define GSD_WACOM_DEVICE_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GSD_TYPE_WACOM_DEVICE, GsdWacomDevicePrivate))
/* we support two types of settings:
* Tablet-wide settings: applied to each tool on the tablet. e.g. rotation
* Tool-specific settings: applied to one tool only.
*/
#define SETTINGS_WACOM_DIR "org.cinnamon.settings-daemon.peripherals.wacom"
#define SETTINGS_STYLUS_DIR "stylus"
#define SETTINGS_ERASER_DIR "eraser"
struct GsdWacomDevicePrivate
{
GdkDevice *gdk_device;
int device_id;
int opcode;
GsdWacomDeviceType type;
char *name;
char *path;
char *machine_id;
const char *icon_name;
char *tool_name;
gboolean reversible;
gboolean is_screen_tablet;
gboolean is_fallback;
GList *styli;
GsdWacomStylus *last_stylus;
GList *buttons;
gint num_rings;
gint num_strips;
GHashTable *modes; /* key = int (group), value = int (index) */
GHashTable *num_modes; /* key = int (group), value = int (index) */
GSettings *wacom_settings;
};
enum {
PROP_0,
PROP_GDK_DEVICE,
PROP_LAST_STYLUS
};
static void gsd_wacom_device_class_init (GsdWacomDeviceClass *klass);
static void gsd_wacom_device_init (GsdWacomDevice *wacom_device);
static void gsd_wacom_device_finalize (GObject *object);
G_DEFINE_TYPE (GsdWacomDevice, gsd_wacom_device, G_TYPE_OBJECT)
static GdkFilterReturn
filter_events (XEvent *xevent,
GdkEvent *event,
GsdWacomDevice *device)
{
XIEvent *xiev;
XIPropertyEvent *pev;
XGenericEventCookie *cookie;
char *name;
int tool_id;
/* verify we have a property event */
if (xevent->type != GenericEvent)
return GDK_FILTER_CONTINUE;
cookie = &xevent->xcookie;
if (cookie->extension != device->priv->opcode)
return GDK_FILTER_CONTINUE;
xiev = (XIEvent *) xevent->xcookie.data;
if (xiev->evtype != XI_PropertyEvent)
return GDK_FILTER_CONTINUE;
pev = (XIPropertyEvent *) xiev;
/* Is the event for us? */
if (pev->deviceid != device->priv->device_id)
return GDK_FILTER_CONTINUE;
name = XGetAtomName (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), pev->property);
if (name == NULL ||
g_strcmp0 (name, WACOM_SERIAL_IDS_PROP) != 0) {
if (name)
XFree (name);
return GDK_FILTER_CONTINUE;
}
XFree (name);
tool_id = xdevice_get_last_tool_id (device->priv->device_id);
if (tool_id == -1) {
g_warning ("Failed to get value for changed stylus ID on device '%d'", device->priv->device_id);
return GDK_FILTER_CONTINUE;
}
gsd_wacom_device_set_current_stylus (device, tool_id);
return GDK_FILTER_CONTINUE;
}
static gboolean
setup_property_notify (GsdWacomDevice *device)
{
Display *dpy;
XIEventMask evmask;
int tool_id;
evmask.deviceid = device->priv->device_id;
evmask.mask_len = XIMaskLen (XI_PropertyEvent);
evmask.mask = g_new0 (guchar, evmask.mask_len);
XISetMask (evmask.mask, XI_PropertyEvent);
dpy = GDK_DISPLAY_XDISPLAY (gdk_display_get_default ());
XISelectEvents (dpy, DefaultRootWindow (dpy), &evmask, 1);
g_free (evmask.mask);
gdk_window_add_filter (NULL,
(GdkFilterFunc) filter_events,
device);
tool_id = xdevice_get_last_tool_id (device->priv->device_id);
if (tool_id == -1) {
g_warning ("Failed to get value for changed stylus ID on device '%d", device->priv->device_id);
return TRUE;
}
gsd_wacom_device_set_current_stylus (device, tool_id);
return TRUE;
}
static GsdWacomDeviceType
get_device_type (XDeviceInfo *dev)
{
GsdWacomDeviceType ret;
static Atom stylus, cursor, eraser, pad, touch, prop;
XDevice *device;
Atom realtype;
int realformat;
unsigned long nitems, bytes_after;
unsigned char *data = NULL;
int rc;
ret = WACOM_TYPE_INVALID;
if ((dev->use == IsXPointer) || (dev->use == IsXKeyboard))
return ret;
if (!stylus)
stylus = XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), "STYLUS", False);
if (!eraser)
eraser = XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), "ERASER", False);
if (!cursor)
cursor = XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), "CURSOR", False);
if (!pad)
pad = XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), "PAD", False);
if (!touch)
touch = XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), "TOUCH", False);
if (!prop)
prop = XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), "Wacom Tool Type", False);
if (dev->type == stylus)
ret = WACOM_TYPE_STYLUS;
else if (dev->type == eraser)
ret = WACOM_TYPE_ERASER;
else if (dev->type == cursor)
ret = WACOM_TYPE_CURSOR;
else if (dev->type == pad)
ret = WACOM_TYPE_PAD;
else if (dev->type == touch)
ret = WACOM_TYPE_TOUCH;
if (ret == WACOM_TYPE_INVALID)
return ret;
/* There is currently no good way of detecting the driver for a device
* other than checking for a driver-specific property.
* Wacom Tool Type exists on all tools
*/
gdk_error_trap_push ();
device = XOpenDevice (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), dev->id);
if (gdk_error_trap_pop () || (device == NULL))
return ret;
gdk_error_trap_push ();
rc = XGetDeviceProperty (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()),
device, prop, 0, 1, False,
XA_ATOM, &realtype, &realformat, &nitems,
&bytes_after, &data);
XCloseDevice (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), device);
if (gdk_error_trap_pop () || rc != Success || realtype == None)
ret = WACOM_TYPE_INVALID;
XFree (data);
return ret;
}
/* Finds an output which matches the given EDID information. Any NULL
* parameter will be interpreted to match any value. */
static GnomeRROutput *
find_output_by_edid (GnomeRRScreen *rr_screen, const gchar *vendor, const gchar *product, const gchar *serial)
{
GnomeRROutput **rr_outputs;
GnomeRROutput *retval = NULL;
guint i;
rr_outputs = gnome_rr_screen_list_outputs (rr_screen);
for (i = 0; rr_outputs[i] != NULL; i++) {
gchar *o_vendor_s;
gchar *o_product_s;
int o_product;
gchar *o_serial_s;
int o_serial;
gboolean match;
if (!gnome_rr_output_is_connected (rr_outputs[i]))
continue;
if (!gnome_rr_output_get_ids_from_edid (rr_outputs[i],
&o_vendor_s,
&o_product,
&o_serial))
continue;
o_product_s = g_strdup_printf ("%d", o_product);
o_serial_s = g_strdup_printf ("%d", o_serial);
g_debug ("Checking for match between '%s','%s','%s' and '%s','%s','%s'", \
vendor, product, serial, o_vendor_s, o_product_s, o_serial_s);
match = (vendor == NULL || g_strcmp0 (vendor, o_vendor_s) == 0) && \
(product == NULL || g_strcmp0 (product, o_product_s) == 0) && \
(serial == NULL || g_strcmp0 (serial, o_serial_s) == 0);
g_free (o_vendor_s);
g_free (o_product_s);
g_free (o_serial_s);
if (match) {
retval = rr_outputs[i];
break;
}
}
if (retval == NULL)
g_debug ("Did not find a matching output for EDID '%s,%s,%s'",
vendor, product, serial);
return retval;
}
static GnomeRROutput*
find_builtin_output (GnomeRRScreen *rr_screen)
{
GnomeRROutput **rr_outputs;
GnomeRROutput *retval = NULL;
guint i;
rr_outputs = gnome_rr_screen_list_outputs (rr_screen);
for (i = 0; rr_outputs[i] != NULL; i++) {
if (!gnome_rr_output_is_connected (rr_outputs[i]))
continue;
if (gnome_rr_output_is_laptop(rr_outputs[i])) {
retval = rr_outputs[i];
break;
}
}
if (retval == NULL)
g_debug ("Did not find a built-in monitor");
return retval;
}
static GnomeRROutput *
find_output_by_heuristic (GnomeRRScreen *rr_screen, GsdWacomDevice *device)
{
GnomeRROutput *rr_output;
/* TODO: This heuristic will fail for non-Wacom display
* tablets and may give the wrong result if multiple Wacom
* display tablets are connected.
*/
rr_output = find_output_by_edid (rr_screen, "WAC", NULL, NULL);
if (!rr_output)
rr_output = find_builtin_output (rr_screen);
return rr_output;
}
static GnomeRROutput *
find_output_by_display (GnomeRRScreen *rr_screen, GsdWacomDevice *device)
{
gsize n;
GSettings *tablet;
GVariant *display;
const gchar **edid;
GnomeRROutput *ret;
if (device == NULL)
return NULL;
ret = NULL;
tablet = device->priv->wacom_settings;
display = g_settings_get_value (tablet, "display");
edid = g_variant_get_strv (display, &n);
if (n != 3) {
g_critical ("Expected 'display' key to store %d values; got %"G_GSIZE_FORMAT".", 3, n);
goto out;
}
if (strlen (edid[0]) == 0 || strlen (edid[1]) == 0 || strlen (edid[2]) == 0)
goto out;
ret = find_output_by_edid (rr_screen, edid[0], edid[1], edid[2]);
out:
g_free (edid);
g_variant_unref (display);
return ret;
}
static gboolean
is_on (GnomeRROutput *output)
{
GnomeRRCrtc *crtc;
crtc = gnome_rr_output_get_crtc (output);
if (!crtc)
return FALSE;
return gnome_rr_crtc_get_current_mode (crtc) != NULL;
}
static GnomeRROutput *
find_output_by_monitor (GnomeRRScreen *rr_screen,
GdkScreen *screen,
int monitor)
{
GnomeRROutput **rr_outputs;
GnomeRROutput *ret;
guint i;
ret = NULL;
rr_outputs = gnome_rr_screen_list_outputs (rr_screen);
for (i = 0; rr_outputs[i] != NULL; i++) {
GnomeRROutput *rr_output;
GnomeRRCrtc *crtc;
int x, y;
rr_output = rr_outputs[i];
if (!is_on (rr_output))
continue;
crtc = gnome_rr_output_get_crtc (rr_output);
if (!crtc)
continue;
gnome_rr_crtc_get_position (crtc, &x, &y);
if (monitor == gdk_screen_get_monitor_at_point (screen, x, y)) {
ret = rr_output;
break;
}
}
if (ret == NULL)
g_warning ("No output found for monitor %d.", monitor);
return ret;
}
static void
set_display_by_output (GsdWacomDevice *device,
GnomeRROutput *rr_output)
{
GSettings *tablet;
GVariant *c_array;
GVariant *n_array;
gsize nvalues;
gchar *o_vendor_s, *o_product_s, *o_serial_s;
int o_product, o_serial;
const gchar *values[3];
tablet = gsd_wacom_device_get_settings (device);
c_array = g_settings_get_value (tablet, "display");
g_variant_get_strv (c_array, &nvalues);
if (nvalues != 3) {
g_warning ("Unable set set display property. Got %"G_GSIZE_FORMAT" items; expected %d items.\n", nvalues, 4);
return;
}
if (rr_output == NULL ||
!gnome_rr_output_get_ids_from_edid (rr_output,
&o_vendor_s,
&o_product,
&o_serial)) {
o_vendor_s = g_strdup ("");
o_product_s = g_strdup ("");
o_serial_s = g_strdup ("");
} else {
o_product_s = g_strdup_printf ("%d", o_product);
o_serial_s = g_strdup_printf ("%d", o_serial);
}
values[0] = o_vendor_s;
values[1] = o_product_s;
values[2] = o_serial_s;
n_array = g_variant_new_strv ((const gchar * const *) &values, 3);
g_settings_set_value (tablet, "display", n_array);
g_free (o_vendor_s);
g_free (o_product_s);
g_free (o_serial_s);
}
static GsdWacomRotation
get_rotation_wacom (GnomeRRRotation rotation)
{
guint i;
for (i = 0; i < G_N_ELEMENTS (rotation_table); i++) {
if (rotation_table[i].rotation & rotation)
return (rotation_table[i].rotation_wacom);
}
g_assert_not_reached ();
}
void
gsd_wacom_device_set_display (GsdWacomDevice *device,
int monitor)
{
GError *error = NULL;
GnomeRRScreen *rr_screen;
GnomeRROutput *output = NULL;
g_return_if_fail (GSD_IS_WACOM_DEVICE (device));
rr_screen = gnome_rr_screen_new (gdk_screen_get_default (), &error);
if (rr_screen == NULL) {
g_warning ("Failed to create GnomeRRScreen: %s", error->message);
g_error_free (error);
return;
}
if (monitor > GSD_WACOM_SET_ALL_MONITORS)
output = find_output_by_monitor (rr_screen, gdk_screen_get_default (), monitor);
set_display_by_output (device, output);
g_object_unref (rr_screen);
}
static GnomeRROutput *
find_output (GnomeRRScreen *rr_screen,
GsdWacomDevice *device)
{
GnomeRROutput *rr_output;
rr_output = find_output_by_display (rr_screen, device);
if (rr_output == NULL) {
if (gsd_wacom_device_is_screen_tablet (device)) {
rr_output = find_output_by_heuristic (rr_screen, device);
if (rr_output == NULL) {
g_warning ("No fuzzy match based on heuristics was found.");
} else {
g_warning ("Automatically mapping tablet to heuristically-found display.");
set_display_by_output (device, rr_output);
}
}
}
return rr_output;
}
static void
calculate_transformation_matrix (const GdkRectangle mapped, const GdkRectangle desktop, float matrix[NUM_ELEMS_MATRIX])
{
float x_scale = (float)mapped.x / desktop.width;
float y_scale = (float)mapped.y / desktop.height;
float width_scale = (float)mapped.width / desktop.width;
float height_scale = (float)mapped.height / desktop.height;
matrix[0] = width_scale;
matrix[1] = 0.0f;
matrix[2] = x_scale;
matrix[3] = 0.0f;
matrix[4] = height_scale;
matrix[5] = y_scale;
matrix[6] = 0.0f;
matrix[7] = 0.0f;
matrix[8] = 1.0f;
g_debug ("Matrix is %f,%f,%f,%f,%f,%f,%f,%f,%f.",
matrix[0], matrix[1], matrix[2],
matrix[3], matrix[4], matrix[5],
matrix[6], matrix[7], matrix[8]);
return;
}
int
gsd_wacom_device_get_display_monitor (GsdWacomDevice *device)
{
GError *error = NULL;
GnomeRRScreen *rr_screen;
GnomeRROutput *rr_output;
GnomeRRMode *mode;
GnomeRRCrtc *crtc;
gint area[4];
g_return_val_if_fail (GSD_IS_WACOM_DEVICE (device), GSD_WACOM_SET_ALL_MONITORS);
rr_screen = gnome_rr_screen_new (gdk_screen_get_default (), &error);
if (rr_screen == NULL) {
g_warning ("Failed to create GnomeRRScreen: %s", error->message);
g_error_free (error);
return GSD_WACOM_SET_ALL_MONITORS;
}
rr_output = find_output (rr_screen, device);
if (rr_output == NULL) {
g_object_unref (rr_screen);
return GSD_WACOM_SET_ALL_MONITORS;
}
if (!is_on (rr_output)) {
g_warning ("Output is not active.");
g_object_unref (rr_screen);
return GSD_WACOM_SET_ALL_MONITORS;
}
crtc = gnome_rr_output_get_crtc (rr_output);
gnome_rr_crtc_get_position (crtc, &area[0], &area[1]);
mode = gnome_rr_crtc_get_current_mode (crtc);
area[2] = gnome_rr_mode_get_width (mode);
area[3] = gnome_rr_mode_get_height (mode);
g_object_unref (rr_screen);
if (area[2] <= 0 || area[3] <= 0) {
g_warning ("Output has non-positive area.");
return GSD_WACOM_SET_ALL_MONITORS;
}
g_debug ("Area: %d,%d %dx%d", area[0], area[1], area[2], area[3]);
return gdk_screen_get_monitor_at_point (gdk_screen_get_default (), area[0], area[1]);
}
gboolean
gsd_wacom_device_get_display_matrix (GsdWacomDevice *device, float matrix[NUM_ELEMS_MATRIX])
{
int monitor;
GdkRectangle display;
GdkRectangle desktop;
GdkScreen *screen = gdk_screen_get_default ();
matrix[0] = 1.0f;
matrix[1] = 0.0f;
matrix[2] = 0.0f;
matrix[3] = 0.0f;
matrix[4] = 1.0f;
matrix[5] = 0.0f;
matrix[6] = 0.0f;
matrix[7] = 0.0f;
matrix[8] = 1.0f;
monitor = gsd_wacom_device_get_display_monitor (device);
if (monitor < 0)
return FALSE;
desktop.x = 0;
desktop.y = 0;
desktop.width = gdk_screen_get_width (screen);
desktop.height = gdk_screen_get_height (screen);
gdk_screen_get_monitor_geometry (screen, monitor, &display);
calculate_transformation_matrix (display, desktop, matrix);
return TRUE;
}
GsdWacomRotation
gsd_wacom_device_get_display_rotation (GsdWacomDevice *device)
{
GError *error = NULL;
GnomeRRScreen *rr_screen;
GnomeRROutput *rr_output;
GnomeRRRotation rotation = GNOME_RR_ROTATION_0;
rr_screen = gnome_rr_screen_new (gdk_screen_get_default (), &error);
if (rr_screen == NULL) {
g_warning ("Failed to create GnomeRRScreen: %s", error->message);
g_error_free (error);
return GSD_WACOM_ROTATION_NONE;
}
rr_output = find_output (rr_screen, device);
if (rr_output) {
GnomeRRCrtc *crtc = gnome_rr_output_get_crtc (rr_output);
if (crtc)
rotation = gnome_rr_crtc_get_current_rotation (crtc);
}
g_object_unref (rr_screen);
return get_rotation_wacom (rotation);
}
static void
add_stylus_to_device (GsdWacomDevice *device,
const char *settings_path,
int id)
{
const WacomStylus *wstylus;
wstylus = libwacom_stylus_get_for_id (db, id);
if (wstylus) {
GsdWacomStylus *stylus;
char *stylus_settings_path;
GSettings *settings;
if (device->priv->type == WACOM_TYPE_STYLUS &&
libwacom_stylus_is_eraser (wstylus))
return;
if (device->priv->type == WACOM_TYPE_ERASER &&
libwacom_stylus_is_eraser (wstylus) == FALSE)
return;
stylus_settings_path = g_strdup_printf ("%s0x%x/", settings_path, id);
if (device->priv->type == WACOM_TYPE_STYLUS) {
settings = g_settings_new_with_path (WACOM_STYLUS_SCHEMA, stylus_settings_path);
stylus = gsd_wacom_stylus_new (device, wstylus, settings);
} else {
settings = g_settings_new_with_path (WACOM_ERASER_SCHEMA, stylus_settings_path);
stylus = gsd_wacom_stylus_new (device, wstylus, settings);
}
g_free (stylus_settings_path);
device->priv->styli = g_list_prepend (device->priv->styli, stylus);
}
}
int
gsd_wacom_device_set_next_mode (GsdWacomDevice *device,
int group_id)
{
int current_idx;
int num_modes;
g_return_val_if_fail (GSD_IS_WACOM_DEVICE (device), -1);
current_idx = GPOINTER_TO_INT (g_hash_table_lookup (device->priv->modes, GINT_TO_POINTER(group_id)));
/* That means that the mode doesn't exist, see gsd_wacom_device_add_modes() */
g_return_val_if_fail (current_idx != 0, -1);
current_idx++;
num_modes = GPOINTER_TO_INT (g_hash_table_lookup (device->priv->num_modes, GINT_TO_POINTER(group_id)));
if (current_idx > num_modes)
current_idx = 1;
g_hash_table_insert (device->priv->modes, GINT_TO_POINTER (group_id), GINT_TO_POINTER (current_idx));
return current_idx;
}
static int
flags_to_group (WacomButtonFlags flags)
{
if (flags & WACOM_BUTTON_RING_MODESWITCH)
return 1;
if (flags & WACOM_BUTTON_RING2_MODESWITCH)
return 2;
if (flags & WACOM_BUTTON_TOUCHSTRIP_MODESWITCH)
return 3;
if (flags & WACOM_BUTTON_TOUCHSTRIP2_MODESWITCH)
return 4;
return 0;
}
static GList *
gsd_wacom_device_add_ring_modes (WacomDevice *wacom_device,
const char *settings_path,
WacomButtonFlags direction)
{
GList *l;
guint num_modes;
guint i;
char *name, *id;
l = NULL;
if ((direction & WACOM_BUTTON_POSITION_LEFT) && libwacom_has_ring (wacom_device)) {
/* There is a ring so there must be at least one mode */
num_modes = MAX (1, libwacom_get_ring_num_modes (wacom_device));
for (i = 1; i <= num_modes; i++) {
name = g_strdup_printf (_("Left Ring Mode #%d"), i);
id = g_strdup_printf ("left-ring-mode-%d", i);
l = g_list_append (l, gsd_wacom_tablet_button_new (name, id, settings_path, WACOM_TABLET_BUTTON_TYPE_ELEVATOR, flags_to_group (WACOM_BUTTON_RING_MODESWITCH), i - 1));
g_free (name);
g_free (id);
}
} else if ((direction & WACOM_BUTTON_POSITION_RIGHT) && libwacom_has_ring2 (wacom_device)) {
/* There is a ring so there must be at least one mode */
num_modes = MAX (1, libwacom_get_ring2_num_modes (wacom_device));
for (i = 1; i <= num_modes; i++) {
name = g_strdup_printf (_("Right Ring Mode #%d"), i);
id = g_strdup_printf ("right-ring-mode-%d", i);
l = g_list_append (l, gsd_wacom_tablet_button_new (name, id, settings_path, WACOM_TABLET_BUTTON_TYPE_ELEVATOR, flags_to_group (WACOM_BUTTON_RING2_MODESWITCH), i - 1));
g_free (name);
g_free (id);
}
}
return l;
}
static GList *
gsd_wacom_device_add_strip_modes (WacomDevice *wacom_device,
const char *settings_path,
WacomButtonFlags direction)
{
GList *l;
guint num_modes;
guint num_strips;
guint i;
char *name, *id;
l = NULL;
num_strips = libwacom_get_num_strips (wacom_device);
if (num_strips > 2)
g_warning ("Unhandled number of touchstrips: %d", num_strips);
if ((direction & WACOM_BUTTON_POSITION_LEFT) && num_strips >= 1) {
/* There is a strip so there must be at least one mode */
num_modes = MAX (1, libwacom_get_strips_num_modes (wacom_device));
for (i = 1; i <= num_modes; i++) {
name = g_strdup_printf (_("Left Touchstrip Mode #%d"), i);
id = g_strdup_printf ("left-strip-mode-%d", i);
l = g_list_append (l, gsd_wacom_tablet_button_new (name, id, settings_path, WACOM_TABLET_BUTTON_TYPE_ELEVATOR, flags_to_group (WACOM_BUTTON_TOUCHSTRIP_MODESWITCH), i - 1));
g_free (name);
g_free (id);
}
} else if ((direction & WACOM_BUTTON_POSITION_RIGHT) && num_strips >= 2) {
/* There is a strip so there must be at least one mode */
num_modes = MAX (1, libwacom_get_strips_num_modes (wacom_device));
for (i = 1; i <= num_modes; i++) {
name = g_strdup_printf (_("Right Touchstrip Mode #%d"), i);
id = g_strdup_printf ("right-strip-mode-%d", i);
l = g_list_append (l, gsd_wacom_tablet_button_new (name, id, settings_path, WACOM_TABLET_BUTTON_TYPE_ELEVATOR, flags_to_group (WACOM_BUTTON_TOUCHSTRIP2_MODESWITCH), i - 1));
g_free (name);
g_free (id);
}
}
return l;
}
static char *
gsd_wacom_device_modeswitch_name (WacomButtonFlags flags,
guint button_num)
{
if (flags & WACOM_BUTTON_RINGS_MODESWITCH) {
if (flags & WACOM_BUTTON_POSITION_LEFT)
return g_strdup_printf (_("Left Touchring Mode Switch"));
else
return g_strdup_printf (_("Right Touchring Mode Switch"));
} else if (flags & WACOM_BUTTON_TOUCHSTRIPS_MODESWITCH) {
if (flags & WACOM_BUTTON_POSITION_LEFT)
return g_strdup_printf (_("Left Touchstrip Mode Switch"));
else
return g_strdup_printf (_("Right Touchstrip Mode Switch"));
}
g_warning ("Unhandled modeswitch and direction combination");
return g_strdup_printf (_("Mode Switch #%d"), button_num);
}
static GList *
gsd_wacom_device_add_buttons_dir (WacomDevice *wacom_device,
const char *settings_path,
WacomButtonFlags direction,
const char *button_str,
const char *button_str_id)
{
GList *l;
guint num_buttons, i, button_num;
char *name, *id;
l = NULL;
button_num = 1;
num_buttons = libwacom_get_num_buttons (wacom_device);
for (i = 'A'; i < 'A' + num_buttons; i++) {
WacomButtonFlags flags;
flags = libwacom_get_button_flag (wacom_device, i);
if (!(flags & direction))
continue;
/* Ignore mode switches */
if (flags & WACOM_BUTTON_MODESWITCH)
continue;
name = g_strdup_printf (button_str, button_num++);
id = g_strdup_printf ("%s%c", button_str_id, i);
l = g_list_append (l, gsd_wacom_tablet_button_new (name, id, settings_path, WACOM_TABLET_BUTTON_TYPE_NORMAL, flags_to_group (flags), -1));
g_free (name);
g_free (id);
}
/* Handle modeswitches */
for (i = 'A'; i < 'A' + num_buttons; i++) {
WacomButtonFlags flags;
char *name, *id;
flags = libwacom_get_button_flag (wacom_device, i);
if (!(flags & direction))
continue;
/* Ignore non-mode switches */
if (!(flags & WACOM_BUTTON_MODESWITCH))
continue;
name = gsd_wacom_device_modeswitch_name (flags, button_num++);
id = g_strdup_printf ("%s%c", button_str_id, i);
l = g_list_append (l, gsd_wacom_tablet_button_new (name, id, settings_path, WACOM_TABLET_BUTTON_TYPE_HARDCODED, flags_to_group (flags), -1));
g_free (name);
g_free (id);
}
/* Handle touch{strips,rings} */
if (libwacom_has_ring2 (wacom_device) || libwacom_has_ring (wacom_device))
l = g_list_concat (l, gsd_wacom_device_add_ring_modes (wacom_device, settings_path, direction));
if (libwacom_get_num_strips (wacom_device) > 0)
l = g_list_concat (l, gsd_wacom_device_add_strip_modes (wacom_device, settings_path, direction));
return l;
}
static void
gsd_wacom_device_add_buttons (GsdWacomDevice *device,
WacomDevice *wacom_device,
const char *settings_path)
{
GList *l, *ret;
ret = NULL;
l = gsd_wacom_device_add_buttons_dir (wacom_device, settings_path, WACOM_BUTTON_POSITION_LEFT, _("Left Button #%d"), "button");
if (l)
ret = l;
l = gsd_wacom_device_add_buttons_dir (wacom_device, settings_path, WACOM_BUTTON_POSITION_RIGHT, _("Right Button #%d"), "button");
if (l)
ret = g_list_concat (ret, l);
l = gsd_wacom_device_add_buttons_dir (wacom_device, settings_path, WACOM_BUTTON_POSITION_TOP, _("Top Button #%d"), "button");
if (l)
ret = g_list_concat (ret, l);
l = gsd_wacom_device_add_buttons_dir (wacom_device, settings_path, WACOM_BUTTON_POSITION_BOTTOM, _("Bottom Button #%d"), "button");
if (l)
ret = g_list_concat (ret, l);
device->priv->buttons = ret;
}
static void
gsd_wacom_device_get_modeswitches (WacomDevice *wacom_device,
gint *num_rings,
gint *num_strips)
{
*num_strips = libwacom_get_num_strips (wacom_device);
if (libwacom_has_ring2 (wacom_device))
*num_rings = 2;
else if (libwacom_has_ring (wacom_device))
*num_rings = 1;
else
*num_rings = 0;
}
static void
gsd_wacom_device_add_modes (GsdWacomDevice *device,
WacomDevice *wacom_device)
{
GList *l;
device->priv->modes = g_hash_table_new (g_direct_hash, g_direct_equal);
device->priv->num_modes = g_hash_table_new (g_direct_hash, g_direct_equal);
for (l = device->priv->buttons; l != NULL; l = l->next) {
GsdWacomTabletButton *button = l->data;
if (button->group_id > 0)
g_hash_table_insert (device->priv->modes, GINT_TO_POINTER (button->group_id), GINT_TO_POINTER (1));
/* See flags_to_group() for group ID/button type matches */
if (button->group_id == 1) {
g_hash_table_insert (device->priv->num_modes,
GINT_TO_POINTER (button->group_id),
GINT_TO_POINTER (libwacom_get_ring_num_modes (wacom_device)));
} else if (button->group_id == 2) {
g_hash_table_insert (device->priv->num_modes,
GINT_TO_POINTER (button->group_id),
GINT_TO_POINTER (libwacom_get_ring2_num_modes (wacom_device)));
} else if (button->group_id == 3 || button->group_id == 4) {
g_hash_table_insert (device->priv->num_modes,
GINT_TO_POINTER (button->group_id),
GINT_TO_POINTER (libwacom_get_strips_num_modes (wacom_device)));
}
}
}
static void
gsd_wacom_device_update_from_db (GsdWacomDevice *device,
WacomDevice *wacom_device,
const char *identifier)
{
char *settings_path;
settings_path = g_strdup_printf (WACOM_DEVICE_CONFIG_BASE,
device->priv->machine_id,
libwacom_get_match (wacom_device));
device->priv->wacom_settings = g_settings_new_with_path (WACOM_TABLET_SCHEMA,
settings_path);
device->priv->name = g_strdup (libwacom_get_name (wacom_device));
device->priv->reversible = libwacom_is_reversible (wacom_device);
device->priv->is_screen_tablet = libwacom_is_builtin (wacom_device);
if (device->priv->is_screen_tablet) {
if (libwacom_get_class (wacom_device) == WCLASS_CINTIQ)
device->priv->icon_name = "wacom-tablet-cintiq";
else
device->priv->icon_name = "wacom-tablet-pc";
} else {
device->priv->icon_name = "wacom-tablet";
}
if (device->priv->type == WACOM_TYPE_PAD) {
gsd_wacom_device_get_modeswitches (wacom_device,
&device->priv->num_rings,
&device->priv->num_strips);
gsd_wacom_device_add_buttons (device, wacom_device, settings_path);
gsd_wacom_device_add_modes (device, wacom_device);
}
if (device->priv->type == WACOM_TYPE_STYLUS ||
device->priv->type == WACOM_TYPE_ERASER) {
const int *ids;
int num_styli;
guint i;
ids = libwacom_get_supported_styli (wacom_device, &num_styli);
g_assert (num_styli >= 1);
for (i = 0; i < num_styli; i++)
add_stylus_to_device (device, settings_path, ids[i]);
device->priv->styli = g_list_reverse (device->priv->styli);
}
g_free (settings_path);
}
static GObject *
gsd_wacom_device_constructor (GType type,
guint n_construct_properties,
GObjectConstructParam *construct_properties)
{
GsdWacomDevice *device;
GdkDeviceManager *device_manager;
XDeviceInfo *device_info;
WacomDevice *wacom_device;
int n_devices;
guint i;
device = GSD_WACOM_DEVICE (G_OBJECT_CLASS (gsd_wacom_device_parent_class)->constructor (type,
n_construct_properties,
construct_properties));
if (device->priv->gdk_device == NULL)
return G_OBJECT (device);
device_manager = gdk_display_get_device_manager (gdk_display_get_default ());
g_object_get (device_manager, "opcode", &device->priv->opcode, NULL);
g_object_get (device->priv->gdk_device, "device-id", &device->priv->device_id, NULL);
device_info = XListInputDevices (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), &n_devices);
if (device_info == NULL) {
g_warning ("Could not list any input devices through XListInputDevices()");
goto end;
}
for (i = 0; i < n_devices; i++) {
if (device_info[i].id == device->priv->device_id) {
device->priv->type = get_device_type (&device_info[i]);
device->priv->tool_name = g_strdup (device_info[i].name);
break;
}
}
XFreeDeviceList (device_info);
if (device->priv->type == WACOM_TYPE_INVALID)
goto end;
device->priv->path = xdevice_get_device_node (device->priv->device_id);
if (device->priv->path == NULL) {
g_warning ("Could not get the device node path for ID '%d'", device->priv->device_id);
device->priv->type = WACOM_TYPE_INVALID;
goto end;
}
if (db == NULL)
db = libwacom_database_new ();
wacom_device = libwacom_new_from_path (db, device->priv->path, FALSE, NULL);
if (!wacom_device) {
WacomError *wacom_error;
g_debug ("Creating fallback driver for wacom tablet '%s' ('%s')",
gdk_device_get_name (device->priv->gdk_device),
device->priv->path);
device->priv->is_fallback = TRUE;
wacom_error = libwacom_error_new ();
wacom_device = libwacom_new_from_path (db, device->priv->path, TRUE, wacom_error);
if (wacom_device == NULL) {
g_warning ("Failed to create fallback wacom device for '%s': %s (%d)",
device->priv->path,
libwacom_error_get_message (wacom_error),
libwacom_error_get_code (wacom_error));
libwacom_error_free (&wacom_error);
device->priv->type = WACOM_TYPE_INVALID;
goto end;
}
}
gsd_wacom_device_update_from_db (device, wacom_device, device->priv->path);
libwacom_destroy (wacom_device);
if (device->priv->type == WACOM_TYPE_STYLUS ||
device->priv->type == WACOM_TYPE_ERASER) {
setup_property_notify (device);
}
end:
return G_OBJECT (device);
}
static void
gsd_wacom_device_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GsdWacomDevice *device;
device = GSD_WACOM_DEVICE (object);
switch (prop_id) {
case PROP_GDK_DEVICE:
device->priv->gdk_device = g_value_get_pointer (value);
break;
case PROP_LAST_STYLUS:
device->priv->last_stylus = g_value_get_pointer (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gsd_wacom_device_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GsdWacomDevice *device;
device = GSD_WACOM_DEVICE (object);
switch (prop_id) {
case PROP_GDK_DEVICE:
g_value_set_pointer (value, device->priv->gdk_device);
break;
case PROP_LAST_STYLUS:
g_value_set_pointer (value, device->priv->last_stylus);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gsd_wacom_device_class_init (GsdWacomDeviceClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->constructor = gsd_wacom_device_constructor;
object_class->finalize = gsd_wacom_device_finalize;
object_class->set_property = gsd_wacom_device_set_property;
object_class->get_property = gsd_wacom_device_get_property;
g_type_class_add_private (klass, sizeof (GsdWacomDevicePrivate));
g_object_class_install_property (object_class, PROP_GDK_DEVICE,
g_param_spec_pointer ("gdk-device", "gdk-device", "gdk-device",
G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
g_object_class_install_property (object_class, PROP_LAST_STYLUS,
g_param_spec_pointer ("last-stylus", "last-stylus", "last-stylus",
G_PARAM_READWRITE));
}
static void
gsd_wacom_device_init (GsdWacomDevice *device)
{
device->priv = GSD_WACOM_DEVICE_GET_PRIVATE (device);
device->priv->type = WACOM_TYPE_INVALID;
if (g_file_get_contents ("/etc/machine-id", &device->priv->machine_id, NULL, NULL) == FALSE)
if (g_file_get_contents ("/var/lib/dbus/machine-id", &device->priv->machine_id, NULL, NULL) == FALSE)
device->priv->machine_id = g_strdup ("00000000000000000000000000000000");
device->priv->machine_id = g_strstrip (device->priv->machine_id);
}
static void
gsd_wacom_device_finalize (GObject *object)
{
GsdWacomDevice *device;
GsdWacomDevicePrivate *p;
g_return_if_fail (object != NULL);
g_return_if_fail (GSD_IS_WACOM_DEVICE (object));
device = GSD_WACOM_DEVICE (object);
g_return_if_fail (device->priv != NULL);
p = device->priv;
if (p->wacom_settings != NULL) {
g_object_unref (p->wacom_settings);
p->wacom_settings = NULL;
}
g_list_foreach (p->styli, (GFunc) g_object_unref, NULL);
g_list_free (p->styli);
g_list_foreach (p->buttons, (GFunc) gsd_wacom_tablet_button_free, NULL);
g_list_free (p->buttons);
g_free (p->name);
p->name = NULL;
g_free (p->tool_name);
p->tool_name = NULL;
g_free (p->path);
p->path = NULL;
g_free (p->machine_id);
p->machine_id = NULL;
if (p->modes) {
g_hash_table_destroy (p->modes);
p->modes = NULL;
}
if (p->num_modes) {
g_hash_table_destroy (p->num_modes);
p->num_modes = NULL;
}
gdk_window_remove_filter (NULL,
(GdkFilterFunc) filter_events,
device);
G_OBJECT_CLASS (gsd_wacom_device_parent_class)->finalize (object);
}
GsdWacomDevice *
gsd_wacom_device_new (GdkDevice *device)
{
return GSD_WACOM_DEVICE (g_object_new (GSD_TYPE_WACOM_DEVICE,
"gdk-device", device,
NULL));
}
GList *
gsd_wacom_device_list_styli (GsdWacomDevice *device)
{
g_return_val_if_fail (GSD_IS_WACOM_DEVICE (device), NULL);
return g_list_copy (device->priv->styli);
}
GsdWacomStylus *
gsd_wacom_device_get_stylus_for_type (GsdWacomDevice *device,
GsdWacomStylusType type)
{
GList *l;
g_return_val_if_fail (GSD_IS_WACOM_DEVICE (device), NULL);
for (l = device->priv->styli; l != NULL; l = l->next) {
GsdWacomStylus *stylus = l->data;
if (gsd_wacom_stylus_get_stylus_type (stylus) == type)
return stylus;
}
return NULL;
}
const char *
gsd_wacom_device_get_name (GsdWacomDevice *device)
{
g_return_val_if_fail (GSD_IS_WACOM_DEVICE (device), NULL);
return device->priv->name;
}
const char *
gsd_wacom_device_get_path (GsdWacomDevice *device)
{
g_return_val_if_fail (GSD_IS_WACOM_DEVICE (device), NULL);
return device->priv->path;
}
const char *
gsd_wacom_device_get_icon_name (GsdWacomDevice *device)
{
g_return_val_if_fail (GSD_IS_WACOM_DEVICE (device), NULL);
return device->priv->icon_name;
}
const char *
gsd_wacom_device_get_tool_name (GsdWacomDevice *device)
{
g_return_val_if_fail (GSD_IS_WACOM_DEVICE (device), NULL);
return device->priv->tool_name;
}
gboolean
gsd_wacom_device_reversible (GsdWacomDevice *device)
{
g_return_val_if_fail (GSD_IS_WACOM_DEVICE (device), FALSE);
return device->priv->reversible;
}
gboolean
gsd_wacom_device_is_screen_tablet (GsdWacomDevice *device)
{
g_return_val_if_fail (GSD_IS_WACOM_DEVICE (device), FALSE);
return device->priv->is_screen_tablet;
}
gboolean
gsd_wacom_device_is_fallback (GsdWacomDevice *device)
{
g_return_val_if_fail (GSD_IS_WACOM_DEVICE (device), FALSE);
return device->priv->is_fallback;
}
gint
gsd_wacom_device_get_num_strips (GsdWacomDevice *device)
{
g_return_val_if_fail (GSD_IS_WACOM_DEVICE (device), 0);
return device->priv->num_strips;
}
gint
gsd_wacom_device_get_num_rings (GsdWacomDevice *device)
{
g_return_val_if_fail (GSD_IS_WACOM_DEVICE (device), 0);
return device->priv->num_rings;
}
GSettings *
gsd_wacom_device_get_settings (GsdWacomDevice *device)
{
g_return_val_if_fail (GSD_IS_WACOM_DEVICE (device), NULL);
return device->priv->wacom_settings;
}
void
gsd_wacom_device_set_current_stylus (GsdWacomDevice *device,
int stylus_id)
{
GList *l;
GsdWacomStylus *stylus;
g_return_if_fail (GSD_IS_WACOM_DEVICE (device));
/* Don't change anything if the stylus is already set */
if (device->priv->last_stylus != NULL) {
GsdWacomStylus *stylus = device->priv->last_stylus;
if (stylus->priv->id == stylus_id)
return;
}
for (l = device->priv->styli; l; l = l->next) {
stylus = l->data;
/* Set a nice default if 0x0 */
if (stylus_id == 0x0 &&
stylus->priv->type == WSTYLUS_GENERAL) {
g_object_set (device, "last-stylus", stylus, NULL);
return;
}
if (stylus->priv->id == stylus_id) {
g_object_set (device, "last-stylus", stylus, NULL);
return;
}
}
/* Setting the default stylus to be the generic one */
for (l = device->priv->styli; l; l = l->next) {
stylus = l->data;
/* Set a nice default if 0x0 */
if (stylus->priv->type == WSTYLUS_GENERAL) {
g_debug ("Could not find stylus ID 0x%x for tablet '%s', setting general pen ID 0x%x instead",
stylus_id, device->priv->name, stylus->priv->id);
g_object_set (device, "last-stylus", stylus, NULL);
return;
}
}
g_warning ("Could not set the current stylus ID 0x%x for tablet '%s', no general pen found",
stylus_id, device->priv->name);
/* Setting the default stylus to be the first one */
g_assert (device->priv->styli);
stylus = device->priv->styli->data;
g_object_set (device, "last-stylus", stylus, NULL);
}
GsdWacomDeviceType
gsd_wacom_device_get_device_type (GsdWacomDevice *device)
{
g_return_val_if_fail (GSD_IS_WACOM_DEVICE (device), WACOM_TYPE_INVALID);
return device->priv->type;
}
gint *
gsd_wacom_device_get_area (GsdWacomDevice *device)
{
int i, id;
XDevice *xdevice;
Atom area, realtype;
int rc, realformat;
unsigned long nitems, bytes_after;
unsigned char *data = NULL;
gint *device_area;
g_return_val_if_fail (GSD_IS_WACOM_DEVICE (device), NULL);
g_object_get (device->priv->gdk_device, "device-id", &id, NULL);
area = XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), "Wacom Tablet Area", False);
gdk_error_trap_push ();
xdevice = XOpenDevice (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), id);
if (gdk_error_trap_pop () || (device == NULL))
return NULL;
gdk_error_trap_push ();
rc = XGetDeviceProperty (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()),
xdevice, area, 0, 4, False,
XA_INTEGER, &realtype, &realformat, &nitems,
&bytes_after, &data);
if (gdk_error_trap_pop () || rc != Success || realtype == None || bytes_after != 0 || nitems != 4) {
XCloseDevice (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), xdevice);
return NULL;
}
device_area = g_new0 (int, nitems);
for (i = 0; i < nitems; i++)
device_area[i] = ((long *)data)[i];
XFree (data);
XCloseDevice (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), xdevice);
return device_area;
}
const char *
gsd_wacom_device_type_to_string (GsdWacomDeviceType type)
{
switch (type) {
case WACOM_TYPE_INVALID:
return "Invalid";
case WACOM_TYPE_STYLUS:
return "Stylus";
case WACOM_TYPE_ERASER:
return "Eraser";
case WACOM_TYPE_CURSOR:
return "Cursor";
case WACOM_TYPE_PAD:
return "Pad";
case WACOM_TYPE_TOUCH:
return "Touch";
default:
return "Unknown type";
}
}
GList *
gsd_wacom_device_get_buttons (GsdWacomDevice *device)
{
g_return_val_if_fail (GSD_IS_WACOM_DEVICE (device), NULL);
return g_list_copy (device->priv->buttons);
}
static GsdWacomTabletButton *
find_button_with_id (GsdWacomDevice *device,
const char *id)
{
GList *l;
for (l = device->priv->buttons; l != NULL; l = l->next) {
GsdWacomTabletButton *button = l->data;
if (g_strcmp0 (button->id, id) == 0)
return button;
}
return NULL;
}
static GsdWacomTabletButton *
find_button_with_index (GsdWacomDevice *device,
const char *id,
int index)
{
GsdWacomTabletButton *button;
char *str;
str = g_strdup_printf ("%s-mode-%d", id, index);
button = find_button_with_id (device, str);
g_free (str);
return button;
}
GsdWacomTabletButton *
gsd_wacom_device_get_button (GsdWacomDevice *device,
int button,
GtkDirectionType *dir)
{
int index;
if (button <= 26) {
char *id;
GsdWacomTabletButton *ret;
int physical_button;
/* mouse_button = physical_button < 4 ? physical_button : physical_button + 4 */
if (button > 4)
physical_button = button - 4;
else
physical_button = button;
id = g_strdup_printf ("button%c", 'A' + physical_button - 1);
ret = find_button_with_id (device, id);
g_free (id);
return ret;
}
switch (button) {
case 90:
case 92:
case 94:
case 96:
*dir = GTK_DIR_UP;
break;
case 91:
case 93:
case 95:
case 97:
*dir = GTK_DIR_DOWN;
break;
default:
;;
}
/* The group ID is implied by the button number */
switch (button) {
case 90:
case 91:
index = GPOINTER_TO_INT (g_hash_table_lookup (device->priv->modes, GINT_TO_POINTER (1)));
return find_button_with_index (device, "left-ring", index);
case 92:
case 93:
index = GPOINTER_TO_INT (g_hash_table_lookup (device->priv->modes, GINT_TO_POINTER (2)));
return find_button_with_index (device, "right-ring", index);
case 94:
case 95:
index = GPOINTER_TO_INT (g_hash_table_lookup (device->priv->modes, GINT_TO_POINTER (3)));
return find_button_with_index (device, "left-strip", index);
case 96:
case 97:
index = GPOINTER_TO_INT (g_hash_table_lookup (device->priv->modes, GINT_TO_POINTER (4)));
return find_button_with_index (device, "right-strip", index);
default:
return NULL;
}
}
GsdWacomRotation
gsd_wacom_device_rotation_name_to_type (const char *rotation)
{
guint i;
g_return_val_if_fail (rotation != NULL, GSD_WACOM_ROTATION_NONE);
for (i = 0; i < G_N_ELEMENTS (rotation_table); i++) {
if (strcmp (rotation_table[i].rotation_string, rotation) == 0)
return (rotation_table[i].rotation_wacom);
}
return GSD_WACOM_ROTATION_NONE;
}
const char *
gsd_wacom_device_rotation_type_to_name (GsdWacomRotation type)
{
guint i;
for (i = 0; i < G_N_ELEMENTS (rotation_table); i++) {
if (rotation_table[i].rotation_wacom == type)
return (rotation_table[i].rotation_string);
}
return "none";
}
GsdWacomDevice *
gsd_wacom_device_create_fake (GsdWacomDeviceType type,
const char *name,
const char *tool_name)
{
GsdWacomDevice *device;
GsdWacomDevicePrivate *priv;
WacomDevice *wacom_device;
device = GSD_WACOM_DEVICE (g_object_new (GSD_TYPE_WACOM_DEVICE, NULL));
if (db == NULL)
db = libwacom_database_new ();
wacom_device = libwacom_new_from_name (db, name, NULL);
if (wacom_device == NULL)
return NULL;
priv = device->priv;
priv->type = type;
priv->tool_name = g_strdup (tool_name);
gsd_wacom_device_update_from_db (device, wacom_device, name);
libwacom_destroy (wacom_device);
return device;
}
GList *
gsd_wacom_device_create_fake_cintiq (void)
{
GsdWacomDevice *device;
GList *devices;
device = gsd_wacom_device_create_fake (WACOM_TYPE_STYLUS,
"Wacom Cintiq 21UX2",
"Wacom Cintiq 21UX2 stylus");
devices = g_list_prepend (NULL, device);
device = gsd_wacom_device_create_fake (WACOM_TYPE_ERASER,
"Wacom Cintiq 21UX2",
"Wacom Cintiq 21UX2 eraser");
devices = g_list_prepend (devices, device);
device = gsd_wacom_device_create_fake (WACOM_TYPE_PAD,
"Wacom Cintiq 21UX2",
"Wacom Cintiq 21UX2 pad");
devices = g_list_prepend (devices, device);
return devices;
}
GList *
gsd_wacom_device_create_fake_bt (void)
{
GsdWacomDevice *device;
GList *devices;
device = gsd_wacom_device_create_fake (WACOM_TYPE_STYLUS,
"Wacom Graphire Wireless",
"Graphire Wireless stylus");
devices = g_list_prepend (NULL, device);
device = gsd_wacom_device_create_fake (WACOM_TYPE_ERASER,
"Wacom Graphire Wireless",
"Graphire Wireless eraser");
devices = g_list_prepend (devices, device);
device = gsd_wacom_device_create_fake (WACOM_TYPE_PAD,
"Wacom Graphire Wireless",
"Graphire Wireless pad");
devices = g_list_prepend (devices, device);
device = gsd_wacom_device_create_fake (WACOM_TYPE_CURSOR,
"Wacom Graphire Wireless",
"Graphire Wireless cursor");
devices = g_list_prepend (devices, device);
return devices;
}
GList *
gsd_wacom_device_create_fake_x201 (void)
{
GsdWacomDevice *device;
GList *devices;
device = gsd_wacom_device_create_fake (WACOM_TYPE_STYLUS,
"Wacom Serial Tablet WACf004",
"Wacom Serial Tablet WACf004 stylus");
devices = g_list_prepend (NULL, device);
device = gsd_wacom_device_create_fake (WACOM_TYPE_ERASER,
"Wacom Serial Tablet WACf004",
"Wacom Serial Tablet WACf004 eraser");
devices = g_list_prepend (devices, device);
return devices;
}
GList *
gsd_wacom_device_create_fake_intuos4 (void)
{
GsdWacomDevice *device;
GList *devices;
device = gsd_wacom_device_create_fake (WACOM_TYPE_STYLUS,
"Wacom Intuos4 6x9",
"Wacom Intuos4 6x9 stylus");
devices = g_list_prepend (NULL, device);
device = gsd_wacom_device_create_fake (WACOM_TYPE_ERASER,
"Wacom Intuos4 6x9",
"Wacom Intuos4 6x9 eraser");
devices = g_list_prepend (devices, device);
device = gsd_wacom_device_create_fake (WACOM_TYPE_PAD,
"Wacom Intuos4 6x9",
"Wacom Intuos4 6x9 pad");
devices = g_list_prepend (devices, device);
device = gsd_wacom_device_create_fake (WACOM_TYPE_CURSOR,
"Wacom Intuos4 6x9",
"Wacom Intuos4 6x9 cursor");
devices = g_list_prepend (devices, device);
return devices;
}
|
390 | ./cinnamon-control-center/panels/unused/wacom/cc-wacom-panel.c | /*
* Copyright © 2011 Red Hat, Inc.
*
* 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.
*
* Authors: Peter Hutterer <[email protected]>
* Bastien Nocera <[email protected]>
*
*/
#include <config.h>
#include <string.h>
#include <gtk/gtk.h>
#include "cc-wacom-panel.h"
#include "cc-wacom-page.h"
#include "gsd-wacom-device.h"
#define WID(x) (GtkWidget *) gtk_builder_get_object (priv->builder, x)
CC_PANEL_REGISTER (CcWacomPanel, cc_wacom_panel)
#define WACOM_PANEL_PRIVATE(o) \
(G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_WACOM_PANEL, CcWacomPanelPrivate))
struct _CcWacomPanelPrivate
{
GtkBuilder *builder;
GtkWidget *notebook;
GHashTable *devices; /* key=GdkDevice, value=GsdWacomDevice */
GHashTable *pages; /* key=device name, value=GtkWidget */
GdkDeviceManager *manager;
guint device_added_id;
guint device_removed_id;
};
typedef struct {
const char *name;
GsdWacomDevice *stylus;
GsdWacomDevice *eraser;
GsdWacomDevice *pad;
} Tablet;
enum {
WACOM_PAGE = -1,
PLUG_IN_PAGE = 0,
};
/* Boilerplate code goes below */
static void
cc_wacom_panel_get_property (GObject *object,
guint property_id,
GValue *value,
GParamSpec *pspec)
{
switch (property_id)
{
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}
}
static void
cc_wacom_panel_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec)
{
switch (property_id)
{
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}
}
static void
cc_wacom_panel_dispose (GObject *object)
{
CcWacomPanelPrivate *priv = CC_WACOM_PANEL (object)->priv;
if (priv->builder)
{
g_object_unref (priv->builder);
priv->builder = NULL;
}
if (priv->manager)
{
g_signal_handler_disconnect (priv->manager, priv->device_added_id);
g_signal_handler_disconnect (priv->manager, priv->device_removed_id);
priv->manager = NULL;
}
if (priv->devices)
{
g_hash_table_destroy (priv->devices);
priv->devices = NULL;
}
if (priv->pages)
{
g_hash_table_destroy (priv->pages);
priv->pages = NULL;
}
G_OBJECT_CLASS (cc_wacom_panel_parent_class)->dispose (object);
}
static const char *
cc_wacom_panel_get_help_uri (CcPanel *panel)
{
if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity"))
return "help:ubuntu-help/wacom";
else
return "help:gnome-help/wacom";
}
static void
cc_wacom_panel_class_init (CcWacomPanelClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
CcPanelClass *panel_class = CC_PANEL_CLASS (klass);
g_type_class_add_private (klass, sizeof (CcWacomPanelPrivate));
object_class->get_property = cc_wacom_panel_get_property;
object_class->set_property = cc_wacom_panel_set_property;
object_class->dispose = cc_wacom_panel_dispose;
panel_class->get_help_uri = cc_wacom_panel_get_help_uri;
}
static void
remove_page (GtkNotebook *notebook,
GtkWidget *widget)
{
int num_pages, i;
num_pages = gtk_notebook_get_n_pages (notebook);
g_return_if_fail (num_pages > 1);
for (i = 1; i < num_pages; i++) {
if (gtk_notebook_get_nth_page (notebook, i) == widget) {
gtk_notebook_remove_page (notebook, i);
return;
}
}
}
static void
update_current_page (CcWacomPanel *self)
{
GHashTable *ht;
GList *devices, *tablets, *l;
gboolean changed;
CcWacomPanelPrivate *priv;
priv = self->priv;
changed = FALSE;
ht = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, g_free);
devices = g_hash_table_get_values (priv->devices);
for (l = devices; l; l = l->next) {
Tablet *tablet;
GsdWacomDevice *device;
device = l->data;
tablet = g_hash_table_lookup (ht, gsd_wacom_device_get_name (device));
if (tablet == NULL) {
tablet = g_new0 (Tablet, 1);
tablet->name = gsd_wacom_device_get_name (device);
g_hash_table_insert (ht, (gpointer) tablet->name, tablet);
}
switch (gsd_wacom_device_get_device_type (device)) {
case WACOM_TYPE_STYLUS:
tablet->stylus = device;
break;
case WACOM_TYPE_ERASER:
tablet->eraser = device;
break;
case WACOM_TYPE_PAD:
tablet->pad = device;
break;
default:
/* Nothing */
;
}
}
g_list_free (devices);
/* We now have a list of Tablet structs,
* see which ones are full tablets */
tablets = g_hash_table_get_values (ht);
for (l = tablets; l; l = l->next) {
Tablet *tablet;
GtkWidget *page;
tablet = l->data;
if (tablet->stylus == NULL ||
tablet->eraser == NULL) {
page = g_hash_table_lookup (priv->pages, tablet->name);
if (page != NULL) {
remove_page (GTK_NOTEBOOK (priv->notebook), page);
g_hash_table_remove (priv->pages, tablet->name);
changed = TRUE;
}
continue;
}
/* this code is called once the stylus + eraser were set up, but the pad does not exist yet */
page = g_hash_table_lookup (priv->pages, tablet->name);
if (page == NULL) {
page = cc_wacom_page_new (self, tablet->stylus, tablet->eraser, tablet->pad);
cc_wacom_page_set_navigation (CC_WACOM_PAGE (page), GTK_NOTEBOOK (priv->notebook), TRUE);
gtk_widget_show (page);
gtk_notebook_append_page (GTK_NOTEBOOK (priv->notebook), page, NULL);
g_hash_table_insert (priv->pages, g_strdup (tablet->name), page);
changed = TRUE;
} else {
cc_wacom_page_update_tools (CC_WACOM_PAGE (page), tablet->stylus, tablet->eraser, tablet->pad);
}
}
g_list_free (tablets);
g_hash_table_destroy (ht);
if (changed == TRUE) {
int num_pages;
num_pages = gtk_notebook_get_n_pages (GTK_NOTEBOOK (priv->notebook));
if (num_pages > 1)
gtk_notebook_set_current_page (GTK_NOTEBOOK (priv->notebook), WACOM_PAGE);
}
}
static void
add_known_device (CcWacomPanel *self,
GdkDevice *gdk_device)
{
CcWacomPanelPrivate *priv;
GsdWacomDevice *device;
priv = self->priv;
device = gsd_wacom_device_new (gdk_device);
if (gsd_wacom_device_get_device_type (device) == WACOM_TYPE_INVALID) {
g_object_unref (device);
return;
}
g_debug ("Adding device '%s' (type: '%s') to known devices list",
gsd_wacom_device_get_tool_name (device),
gsd_wacom_device_type_to_string (gsd_wacom_device_get_device_type (device)));
g_hash_table_insert (priv->devices, (gpointer) gdk_device, device);
}
static void
device_removed_cb (GdkDeviceManager *manager,
GdkDevice *gdk_device,
CcWacomPanel *self)
{
g_hash_table_remove (self->priv->devices, gdk_device);
update_current_page (self);
}
static void
device_added_cb (GdkDeviceManager *manager,
GdkDevice *device,
CcWacomPanel *self)
{
add_known_device (self, device);
update_current_page (self);
}
static gboolean
link_activated (GtkLinkButton *button,
CcWacomPanel *self)
{
cc_wacom_panel_switch_to_panel (self, "bluetooth");
return TRUE;
}
void
cc_wacom_panel_switch_to_panel (CcWacomPanel *self,
const char *panel)
{
CcShell *shell;
GError *error = NULL;
g_return_if_fail (self);
shell = cc_panel_get_shell (CC_PANEL (self));
if (cc_shell_set_active_panel_from_id (shell, panel, NULL, &error) == FALSE)
{
g_warning ("Failed to activate '%s' panel: %s", panel, error->message);
g_error_free (error);
}
}
static void
enbiggen_label (GtkLabel *label)
{
const char *str;
char *new_str;
str = gtk_label_get_text (label);
new_str = g_strdup_printf ("<big>%s</big>", str);
gtk_label_set_markup (label, new_str);
g_free (new_str);
}
static void
cc_wacom_panel_init (CcWacomPanel *self)
{
CcWacomPanelPrivate *priv;
GtkNotebook *notebook;
GtkWidget *widget;
GList *devices, *l;
GError *error = NULL;
char *objects[] = {
"main-box",
NULL
};
priv = self->priv = WACOM_PANEL_PRIVATE (self);
priv->builder = gtk_builder_new ();
gtk_builder_add_objects_from_file (priv->builder,
CINNAMONCC_UI_DIR "/cinnamon-wacom-properties.ui",
objects,
&error);
if (error != NULL)
{
g_warning ("Error loading UI file: %s", error->message);
g_object_unref (priv->builder);
g_error_free (error);
return;
}
/* Notebook */
notebook = GTK_NOTEBOOK (gtk_notebook_new ());
priv->notebook = GTK_WIDGET (notebook);
gtk_notebook_set_show_tabs (notebook, FALSE);
gtk_widget_set_vexpand (GTK_WIDGET (notebook), TRUE);
gtk_container_set_border_width (GTK_CONTAINER (notebook), 0);
g_object_set (G_OBJECT (notebook),
"margin-top", 0,
"margin-right", 24,
"margin-left", 24,
"margin-bottom", 24,
NULL);
gtk_container_add (GTK_CONTAINER (self), GTK_WIDGET (notebook));
gtk_widget_show (priv->notebook);
/* No tablets page */
widget = WID ("main-box");
enbiggen_label (GTK_LABEL (WID ("advice-label1")));
gtk_notebook_append_page (notebook, widget, NULL);
g_signal_connect (G_OBJECT (WID ("linkbutton")), "activate-link",
G_CALLBACK (link_activated), self);
priv->devices = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_object_unref);
priv->pages = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
priv->manager = gdk_display_get_device_manager (gdk_display_get_default ());
priv->device_added_id = g_signal_connect (G_OBJECT (priv->manager), "device-added",
G_CALLBACK (device_added_cb), self);
priv->device_removed_id = g_signal_connect (G_OBJECT (priv->manager), "device-removed",
G_CALLBACK (device_removed_cb), self);
devices = gdk_device_manager_list_devices (priv->manager, GDK_DEVICE_TYPE_SLAVE);
for (l = devices; l ; l = l->next)
add_known_device (self, l->data);
g_list_free (devices);
update_current_page (self);
}
void
cc_wacom_panel_register (GIOModule *module)
{
cc_wacom_panel_register_type (G_TYPE_MODULE (module));
g_io_extension_point_implement (CC_SHELL_PANEL_EXTENSION_POINT,
CC_TYPE_WACOM_PANEL, "wacom", 0);
}
|
391 | ./cinnamon-control-center/panels/unused/wacom/gsd-input-helper.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2010 Bastien Nocera <[email protected]>
*
* 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.
*
*/
#include "config.h"
#include <gdk/gdk.h>
#include <gdk/gdkx.h>
#include <sys/types.h>
#include <X11/Xatom.h>
#include <X11/extensions/XInput2.h>
#include "gsd-input-helper.h"
#define INPUT_DEVICES_SCHEMA "org.cinnamon.settings-daemon.peripherals.input-devices"
#define KEY_HOTPLUG_COMMAND "hotplug-command"
typedef gboolean (* InfoIdentifyFunc) (XDeviceInfo *device_info);
typedef gboolean (* DeviceIdentifyFunc) (XDevice *xdevice);
gboolean
device_set_property (XDevice *xdevice,
const char *device_name,
PropertyHelper *property)
{
int rc, i;
Atom prop;
Atom realtype;
int realformat;
unsigned long nitems, bytes_after;
unsigned char *data;
prop = XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()),
property->name, False);
if (!prop)
return FALSE;
gdk_error_trap_push ();
rc = XGetDeviceProperty (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()),
xdevice, prop, 0, property->nitems, False,
AnyPropertyType, &realtype, &realformat, &nitems,
&bytes_after, &data);
if (rc != Success ||
realtype != property->type ||
realformat != property->format ||
nitems < property->nitems) {
gdk_error_trap_pop_ignored ();
g_warning ("Error reading property \"%s\" for \"%s\"", property->name, device_name);
return FALSE;
}
for (i = 0; i < nitems; i++) {
switch (property->format) {
case 8:
data[i] = property->data.c[i];
break;
case 32:
((long*)data)[i] = property->data.i[i];
break;
}
}
XChangeDeviceProperty (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()),
xdevice, prop, realtype, realformat,
PropModeReplace, data, nitems);
XFree (data);
if (gdk_error_trap_pop ()) {
g_warning ("Error in setting \"%s\" for \"%s\"", property->name, device_name);
return FALSE;
}
return TRUE;
}
static gboolean
supports_xinput_devices_with_opcode (int *opcode)
{
gint op_code, event, error;
gboolean retval;
retval = XQueryExtension (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()),
"XInputExtension",
&op_code,
&event,
&error);
if (opcode)
*opcode = op_code;
return retval;
}
gboolean
supports_xinput_devices (void)
{
return supports_xinput_devices_with_opcode (NULL);
}
gboolean
supports_xinput2_devices (int *opcode)
{
int major, minor;
if (supports_xinput_devices_with_opcode (opcode) == FALSE)
return FALSE;
gdk_error_trap_push ();
major = 2;
minor = 0;
if (XIQueryVersion (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), &major, &minor) != Success) {
gdk_error_trap_pop_ignored ();
/* try for 2.2, maybe gtk has already announced 2.2 support */
gdk_error_trap_push ();
major = 2;
minor = 2;
if (XIQueryVersion (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), &major, &minor) != Success) {
gdk_error_trap_pop_ignored ();
return FALSE;
}
}
gdk_error_trap_pop_ignored ();
if ((major * 1000 + minor) < (2000))
return FALSE;
return TRUE;
}
gboolean
device_is_touchpad (XDevice *xdevice)
{
Atom realtype, prop;
int realformat;
unsigned long nitems, bytes_after;
unsigned char *data;
/* we don't check on the type being XI_TOUCHPAD here,
* but having a "Synaptics Off" property should be enough */
prop = XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), "Synaptics Off", False);
if (!prop)
return FALSE;
gdk_error_trap_push ();
if ((XGetDeviceProperty (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), xdevice, prop, 0, 1, False,
XA_INTEGER, &realtype, &realformat, &nitems,
&bytes_after, &data) == Success) && (realtype != None)) {
gdk_error_trap_pop_ignored ();
XFree (data);
return TRUE;
}
gdk_error_trap_pop_ignored ();
return FALSE;
}
gboolean
device_info_is_touchpad (XDeviceInfo *device_info)
{
return (device_info->type == XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), XI_TOUCHPAD, False));
}
gboolean
device_info_is_touchscreen (XDeviceInfo *device_info)
{
return (device_info->type == XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), XI_TOUCHSCREEN, False));
}
gboolean
device_info_is_mouse (XDeviceInfo *device_info)
{
return (device_info->type == XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), XI_MOUSE, False));
}
static gboolean
device_type_is_present (InfoIdentifyFunc info_func,
DeviceIdentifyFunc device_func)
{
XDeviceInfo *device_info;
gint n_devices;
guint i;
gboolean retval;
if (supports_xinput_devices () == FALSE)
return TRUE;
retval = FALSE;
device_info = XListInputDevices (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), &n_devices);
if (device_info == NULL)
return FALSE;
for (i = 0; i < n_devices; i++) {
XDevice *device;
/* Check with the device info first */
retval = (info_func) (&device_info[i]);
if (retval == FALSE)
continue;
/* If we only have an info func, we're done checking */
if (device_func == NULL)
break;
gdk_error_trap_push ();
device = XOpenDevice (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), device_info[i].id);
if (gdk_error_trap_pop () || (device == NULL))
continue;
retval = (device_func) (device);
if (retval) {
XCloseDevice (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), device);
break;
}
XCloseDevice (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), device);
}
XFreeDeviceList (device_info);
return retval;
}
gboolean
touchscreen_is_present (void)
{
return device_type_is_present (device_info_is_touchscreen,
NULL);
}
gboolean
touchpad_is_present (void)
{
return device_type_is_present (device_info_is_touchpad,
device_is_touchpad);
}
gboolean
mouse_is_present (void)
{
return device_type_is_present (device_info_is_mouse,
NULL);
}
char *
xdevice_get_device_node (int deviceid)
{
Atom prop;
Atom act_type;
int act_format;
unsigned long nitems, bytes_after;
unsigned char *data;
char *ret;
gdk_display_sync (gdk_display_get_default ());
prop = XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), "Device Node", False);
if (!prop)
return NULL;
gdk_error_trap_push ();
if (!XIGetProperty (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()),
deviceid, prop, 0, 1000, False,
AnyPropertyType, &act_type, &act_format,
&nitems, &bytes_after, &data) == Success) {
gdk_error_trap_pop_ignored ();
return NULL;
}
if (gdk_error_trap_pop ())
goto out;
if (nitems == 0)
goto out;
if (act_type != XA_STRING)
goto out;
/* Unknown string format */
if (act_format != 8)
goto out;
ret = g_strdup ((char *) data);
XFree (data);
return ret;
out:
XFree (data);
return NULL;
}
#define TOOL_ID_FORMAT_SIZE 32
static int
get_id_for_index (guchar *data,
guint idx)
{
guchar *ptr;
int id;
ptr = data;
ptr += TOOL_ID_FORMAT_SIZE / 8 * idx;
id = *((int32_t*)ptr);
id = id & 0xfffff;
return id;
}
#define STYLUS_DEVICE_ID 0x02
#define ERASER_DEVICE_ID 0x0A
int
xdevice_get_last_tool_id (int deviceid)
{
Atom prop;
Atom act_type;
int act_format;
unsigned long nitems, bytes_after;
unsigned char *data;
int id;
id = -1;
gdk_display_sync (gdk_display_get_default ());
prop = XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), WACOM_SERIAL_IDS_PROP, False);
if (!prop)
return -1;
data = NULL;
gdk_error_trap_push ();
if (XIGetProperty (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()),
deviceid, prop, 0, 1000, False,
AnyPropertyType, &act_type, &act_format,
&nitems, &bytes_after, &data) != Success) {
gdk_error_trap_pop_ignored ();
goto out;
}
if (gdk_error_trap_pop ())
goto out;
if (nitems != 4 && nitems != 5)
goto out;
if (act_type != XA_INTEGER)
goto out;
if (act_format != TOOL_ID_FORMAT_SIZE)
goto out;
/* item 0 = tablet ID
* item 1 = old device serial number (== last tool in proximity)
* item 2 = old hardware serial number (including tool ID)
* item 3 = current serial number (0 if no tool in proximity)
* item 4 = current tool ID (since Feb 2012)
*
* Get the current tool ID first, if available, then the old one */
id = 0x0;
if (nitems == 5)
id = get_id_for_index (data, 4);
if (id == 0x0)
id = get_id_for_index (data, 2);
/* That means that no tool was set down yet */
if (id == STYLUS_DEVICE_ID ||
id == ERASER_DEVICE_ID)
id = 0x0;
out:
if (data != NULL)
XFree (data);
return id;
}
gboolean
set_device_enabled (int device_id,
gboolean enabled)
{
Atom prop;
guchar value;
prop = XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), "Device Enabled", False);
if (!prop)
return FALSE;
gdk_error_trap_push ();
value = enabled ? 1 : 0;
XIChangeProperty (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()),
device_id, prop, XA_INTEGER, 8, PropModeReplace, &value, 1);
if (gdk_error_trap_pop ())
return FALSE;
return TRUE;
}
static const char *
custom_command_to_string (CustomCommand command)
{
switch (command) {
case COMMAND_DEVICE_ADDED:
return "added";
case COMMAND_DEVICE_REMOVED:
return "removed";
case COMMAND_DEVICE_PRESENT:
return "present";
default:
g_assert_not_reached ();
}
}
/* Run a custom command on device presence events. Parameters passed into
* the custom command are:
* command -t [added|removed|present] -i <device ID> <device name>
* Type 'added' and 'removed' signal 'device added' and 'device removed',
* respectively. Type 'present' signals 'device present at
* gnome-settings-daemon init'.
*
* The script is expected to run synchronously, and an exit value
* of "1" means that no other settings will be applied to this
* particular device.
*
* More options may be added in the future.
*
* This function returns TRUE if we should not apply any more settings
* to the device.
*/
gboolean
run_custom_command (GdkDevice *device,
CustomCommand command)
{
GSettings *settings;
char *cmd;
char *argv[7];
int exit_status;
gboolean rc;
int id;
settings = g_settings_new (INPUT_DEVICES_SCHEMA);
cmd = g_settings_get_string (settings, KEY_HOTPLUG_COMMAND);
g_object_unref (settings);
if (!cmd || cmd[0] == '\0') {
g_free (cmd);
return FALSE;
}
/* Easter egg! */
g_object_get (device, "device-id", &id, NULL);
argv[0] = cmd;
argv[1] = "-t";
argv[2] = (char *) custom_command_to_string (command);
argv[3] = "-i";
argv[4] = g_strdup_printf ("%d", id);
argv[5] = g_strdup_printf ("%s", gdk_device_get_name (device));
argv[6] = NULL;
rc = g_spawn_sync (g_get_home_dir (), argv, NULL, G_SPAWN_SEARCH_PATH,
NULL, NULL, NULL, NULL, &exit_status, NULL);
if (rc == FALSE)
g_warning ("Couldn't execute command '%s', verify that this is a valid command.", cmd);
g_free (argv[0]);
g_free (argv[4]);
g_free (argv[5]);
return (exit_status == 0);
}
GList *
get_disabled_devices (GdkDeviceManager *manager)
{
XDeviceInfo *device_info;
gint n_devices;
guint i;
GList *ret;
ret = NULL;
device_info = XListInputDevices (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), &n_devices);
if (device_info == NULL)
return ret;
for (i = 0; i < n_devices; i++) {
GdkDevice *device;
/* Ignore core devices */
if (device_info[i].use == IsXKeyboard ||
device_info[i].use == IsXPointer)
continue;
/* Check whether the device is actually available */
device = gdk_x11_device_manager_lookup (manager, device_info[i].id);
if (device != NULL)
continue;
ret = g_list_prepend (ret, GINT_TO_POINTER (device_info[i].id));
}
XFreeDeviceList (device_info);
return ret;
}
|
392 | ./cinnamon-control-center/panels/unused/wacom/cc-wacom-page.c | /*
* Copyright © 2011 Red Hat, Inc.
*
* 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.
*
* Authors: Peter Hutterer <[email protected]>
* Bastien Nocera <[email protected]>
*
*/
#include <config.h>
#include <glib/gi18n-lib.h>
#include <gtk/gtk.h>
#include "cc-wacom-page.h"
#include "cc-wacom-nav-button.h"
#include "cc-wacom-mapping-panel.h"
#include "cc-wacom-stylus-page.h"
#include "gsd-enums.h"
#include "gui_gtk.h"
#include <string.h>
#define WID(x) (GtkWidget *) gtk_builder_get_object (priv->builder, x)
#define CWID(x) (GtkContainer *) gtk_builder_get_object (priv->builder, x)
#define MWID(x) (GtkWidget *) gtk_builder_get_object (priv->mapping_builder, x)
G_DEFINE_TYPE (CcWacomPage, cc_wacom_page, GTK_TYPE_BOX)
#define WACOM_PAGE_PRIVATE(o) \
(G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_WACOM_PAGE, CcWacomPagePrivate))
#define THRESHOLD_MISCLICK 15
#define THRESHOLD_DOUBLECLICK 7
#define ACTION_TYPE_KEY "action-type"
#define CUSTOM_ACTION_KEY "custom-action"
#define KEY_CUSTOM_ELEVATOR_ACTION "custom-elevator-action"
#define GSD_WACOM_ACTION_TYPE_SWITCH_MONITOR 2
enum {
MAPPING_DESCRIPTION_COLUMN,
MAPPING_TYPE_COLUMN,
MAPPING_BUTTON_COLUMN,
MAPPING_BUTTON_DIRECTION,
MAPPING_N_COLUMNS
};
enum {
ACTION_NAME_COLUMN,
ACTION_TYPE_COLUMN,
ACTION_N_COLUMNS
};
struct _CcWacomPagePrivate
{
CcWacomPanel *panel;
GsdWacomDevice *stylus, *eraser, *pad;
GtkBuilder *builder;
GtkWidget *nav;
GtkWidget *notebook;
CalibArea *area;
GSettings *wacom_settings;
/* Button mapping */
GtkBuilder *mapping_builder;
GtkWidget *button_map;
GtkListStore *action_store;
/* Display mapping */
GtkWidget *mapping;
GtkWidget *dialog;
};
/* Button combo box storage columns */
enum {
BUTTONNUMBER_COLUMN,
BUTTONNAME_COLUMN,
N_BUTTONCOLUMNS
};
/* Tablet mode combo box storage columns */
enum {
MODENUMBER_COLUMN,
MODELABEL_COLUMN,
N_MODECOLUMNS
};
/* Tablet mode options - keep in sync with .ui */
enum {
MODE_ABSOLUTE, /* stylus + eraser absolute */
MODE_RELATIVE, /* stylus + eraser relative */
};
/* Different types of layout for the tablet config */
enum {
LAYOUT_NORMAL, /* tracking mode, button mapping */
LAYOUT_REVERSIBLE, /* tracking mode, button mapping, left-hand orientation */
LAYOUT_SCREEN /* button mapping, calibration, display resolution */
};
static struct {
GsdWacomActionType action_type;
const gchar *action_name;
} action_table[] = {
{ GSD_WACOM_ACTION_TYPE_NONE, NC_("Wacom action-type", "None") },
{ GSD_WACOM_ACTION_TYPE_CUSTOM, NC_("Wacom action-type", "Send Keystroke") },
{ GSD_WACOM_ACTION_TYPE_SWITCH_MONITOR, NC_("Wacom action-type", "Switch Monitor") }
};
#define WACOM_C(x) g_dpgettext2(NULL, "Wacom action-type", x)
static void
update_tablet_ui (CcWacomPage *page,
int layout);
static int
get_layout_type (GsdWacomDevice *device)
{
int layout;
if (gsd_wacom_device_is_screen_tablet (device))
layout = LAYOUT_SCREEN;
else if (gsd_wacom_device_reversible (device))
layout = LAYOUT_REVERSIBLE;
else
layout = LAYOUT_NORMAL;
return layout;
}
static void
set_calibration (gint *cal,
gsize ncal,
GSettings *settings)
{
GVariant *current; /* current calibration */
GVariant *array; /* new calibration */
GVariant **tmp;
gsize nvalues;
int i;
current = g_settings_get_value (settings, "area");
g_variant_get_fixed_array (current, &nvalues, sizeof (gint32));
if ((ncal != 4) || (nvalues != 4)) {
g_warning("Unable set set device calibration property. Got %"G_GSIZE_FORMAT" items to put in %"G_GSIZE_FORMAT" slots; expected %d items.\n", ncal, nvalues, 4);
return;
}
tmp = g_malloc (nvalues * sizeof (GVariant*));
for (i = 0; i < ncal; i++)
tmp[i] = g_variant_new_int32 (cal[i]);
array = g_variant_new_array (G_VARIANT_TYPE_INT32, tmp, nvalues);
g_settings_set_value (settings, "area", array);
g_free (tmp);
}
static void
finish_calibration (CalibArea *area,
gpointer user_data)
{
CcWacomPage *page = (CcWacomPage *) user_data;
CcWacomPagePrivate *priv = page->priv;
XYinfo axis;
gboolean swap_xy;
int cal[4];
if (calib_area_finish (area, &axis, &swap_xy)) {
cal[0] = axis.x_min;
cal[1] = axis.y_min;
cal[2] = axis.x_max;
cal[3] = axis.y_max;
set_calibration(cal, 4, page->priv->wacom_settings);
}
calib_area_free (area);
page->priv->area = NULL;
gtk_widget_set_sensitive (WID ("button-calibrate"), TRUE);
}
static gboolean
run_calibration (CcWacomPage *page,
gint *cal,
gint monitor)
{
XYinfo old_axis;
GdkDevice *gdk_device;
CcWacomPagePrivate *priv;
int device_id;
g_assert (page->priv->area == NULL);
old_axis.x_min = cal[0];
old_axis.y_min = cal[1];
old_axis.x_max = cal[2];
old_axis.y_max = cal[3];
priv = page->priv;
g_object_get (priv->stylus, "gdk-device", &gdk_device, NULL);
if (gdk_device != NULL)
g_object_get (gdk_device, "device-id", &device_id, NULL);
else
device_id = -1;
page->priv->area = calib_area_new (NULL,
monitor,
device_id,
finish_calibration,
page,
&old_axis,
THRESHOLD_MISCLICK,
THRESHOLD_DOUBLECLICK);
return FALSE;
}
static void
calibrate_button_clicked_cb (GtkButton *button,
CcWacomPage *page)
{
int i, calibration[4];
GVariant *variant;
int *current;
gsize ncal;
gint monitor;
monitor = gsd_wacom_device_get_display_monitor (page->priv->stylus);
if (monitor < 0) {
/* The display the tablet should be mapped to could not be located.
* This shouldn't happen if the EDID data is good...
*/
g_critical("Output associated with the tablet is not connected. Unable to calibrate.");
return;
}
variant = g_settings_get_value (page->priv->wacom_settings, "area");
current = (int *) g_variant_get_fixed_array (variant, &ncal, sizeof (gint32));
if (ncal != 4) {
g_warning("Device calibration property has wrong length. Got %"G_GSIZE_FORMAT" items; expected %d.\n", ncal, 4);
g_free (current);
return;
}
for (i = 0; i < 4; i++)
calibration[i] = current[i];
if (calibration[0] == -1 &&
calibration[1] == -1 &&
calibration[2] == -1 &&
calibration[3] == -1) {
gint *device_cal;
device_cal = gsd_wacom_device_get_area (page->priv->stylus);
for (i = 0; i < 4; i++)
calibration[i] = device_cal[i];
g_free (device_cal);
}
run_calibration (page, calibration, monitor);
gtk_widget_set_sensitive (GTK_WIDGET (button), FALSE);
}
static char *
get_elevator_shortcut_string (GSettings *settings,
GtkDirectionType dir)
{
char **strv, *str;
strv = g_settings_get_strv (settings, KEY_CUSTOM_ELEVATOR_ACTION);
if (strv == NULL)
return NULL;
if (g_strv_length (strv) >= 1 && dir == GTK_DIR_UP)
str = g_strdup (strv[0]);
else if (g_strv_length (strv) >= 2 && dir == GTK_DIR_DOWN)
str = g_strdup (strv[1]);
else
str = NULL;
g_strfreev (strv);
return str;
}
static void
accel_set_func (GtkTreeViewColumn *tree_column,
GtkCellRenderer *cell,
GtkTreeModel *model,
GtkTreeIter *iter,
gpointer data)
{
GsdWacomTabletButton *button;
GsdWacomActionType type;
GtkDirectionType dir;
char *str;
guint keyval;
guint mask;
gtk_tree_model_get (model, iter,
MAPPING_BUTTON_COLUMN, &button,
MAPPING_BUTTON_DIRECTION, &dir,
-1);
if (button == NULL) {
g_object_set (cell,
"visible", FALSE,
NULL);
return;
}
if (button->type == WACOM_TABLET_BUTTON_TYPE_HARDCODED) {
/* FIXME this should list the name of the button,
* Switch Modes Touchring #1 for example */
g_object_set (cell,
"visible", TRUE,
"editable", FALSE,
"accel-key", 0,
"accel-mods", 0,
"style", PANGO_STYLE_NORMAL,
"text", "",
NULL);
return;
}
if (button->settings == NULL) {
g_warning ("Button '%s' does not have an associated GSettings", button->id);
return;
}
type = g_settings_get_enum (button->settings, ACTION_TYPE_KEY);
if (type != GSD_WACOM_ACTION_TYPE_CUSTOM) {
g_object_set (cell,
"visible", TRUE,
"editable", TRUE,
"accel-key", 0,
"accel-mods", 0,
"style", PANGO_STYLE_NORMAL,
"text", "",
NULL);
return;
}
if (button->type == WACOM_TABLET_BUTTON_TYPE_ELEVATOR)
str = get_elevator_shortcut_string (button->settings, dir);
else
str = g_settings_get_string (button->settings, CUSTOM_ACTION_KEY);
if (str == NULL || *str == '\0') {
g_object_set (cell,
"visible", TRUE,
"editable", TRUE,
"accel-key", 0,
"accel-mods", 0,
"style", PANGO_STYLE_NORMAL,
"text", C_("Wacom action-type", "None"),
NULL);
g_free (str);
return;
}
gtk_accelerator_parse (str, &keyval, &mask);
g_free (str);
g_object_set (cell,
"visible", TRUE,
"editable", TRUE,
"accel-key", keyval,
"accel-mods", mask,
"style", PANGO_STYLE_NORMAL,
NULL);
}
static gboolean
start_editing_cb (GtkTreeView *tree_view,
GdkEventButton *event,
gpointer user_data)
{
GtkTreePath *path;
GtkTreeViewColumn *column;
gboolean handled;
if (event->window != gtk_tree_view_get_bin_window (tree_view))
return FALSE;
handled = FALSE;
if (gtk_tree_view_get_path_at_pos (tree_view,
(gint) event->x,
(gint) event->y,
&path, &column,
NULL, NULL))
{
GtkTreeModel *model;
GtkTreeIter iter;
GsdWacomTabletButton *button;
GsdWacomActionType type;
if (column == gtk_tree_view_get_column (tree_view, MAPPING_TYPE_COLUMN))
goto out;
model = gtk_tree_view_get_model (tree_view);
gtk_tree_model_get_iter (model, &iter, path);
gtk_tree_model_get (model, &iter,
MAPPING_BUTTON_COLUMN, &button,
-1);
if (button == NULL)
goto out;
if (button->settings == NULL)
goto out;
type = g_settings_get_enum (button->settings, ACTION_TYPE_KEY);
if (type != GSD_WACOM_ACTION_TYPE_CUSTOM)
goto out;
gtk_widget_grab_focus (GTK_WIDGET (tree_view));
gtk_tree_view_set_cursor (tree_view,
path,
gtk_tree_view_get_column (tree_view, MAPPING_BUTTON_COLUMN),
TRUE);
g_signal_stop_emission_by_name (tree_view, "button_press_event");
handled = TRUE;
out:
gtk_tree_path_free (path);
}
return handled;
}
static void
start_editing_kb_cb (GtkTreeView *treeview,
GtkTreePath *path,
GtkTreeViewColumn *column,
gpointer user_data)
{
GtkTreeModel *model;
GtkTreeIter iter;
GsdWacomTabletButton *button;
model = gtk_tree_view_get_model (treeview);
gtk_tree_model_get_iter (model, &iter, path);
gtk_tree_model_get (model, &iter,
MAPPING_BUTTON_COLUMN, &button,
-1);
gtk_widget_grab_focus (GTK_WIDGET (treeview));
gtk_tree_view_set_cursor (treeview,
path,
gtk_tree_view_get_column (treeview, MAPPING_BUTTON_COLUMN),
TRUE);
}
static void
accel_edited_callback (GtkCellRendererText *cell,
const char *path_string,
guint keyval,
GdkModifierType mask,
guint keycode,
CcWacomPage *page)
{
GtkTreeModel *model;
GtkTreePath *path = gtk_tree_path_new_from_string (path_string);
GtkTreeView *view;
GtkTreeIter iter;
CcWacomPagePrivate *priv;
GsdWacomTabletButton *button;
GtkDirectionType dir;
char *str;
priv = page->priv;
view = GTK_TREE_VIEW (MWID("shortcut_treeview"));
model = gtk_tree_view_get_model (view);
gtk_tree_model_get_iter (model, &iter, path);
gtk_tree_path_free (path);
gtk_tree_model_get (model, &iter,
MAPPING_BUTTON_COLUMN, &button,
MAPPING_BUTTON_DIRECTION, &dir,
-1);
/* sanity check */
if (button == NULL)
return;
/* CapsLock isn't supported as a keybinding modifier, so keep it from confusing us */
mask &= ~GDK_LOCK_MASK;
str = gtk_accelerator_name (keyval, mask);
if (button->type == WACOM_TABLET_BUTTON_TYPE_ELEVATOR) {
char *strs[3];
char **strv;
strs[2] = NULL;
strs[0] = strs[1] = "";
strv = g_settings_get_strv (button->settings, KEY_CUSTOM_ELEVATOR_ACTION);
if (strv != NULL) {
if (g_strv_length (strv) >= 1)
strs[0] = strv[0];
if (g_strv_length (strv) >= 2)
strs[1] = strv[1];
}
if (dir == GTK_DIR_UP)
strs[0] = str;
else
strs[1] = str;
g_settings_set_strv (button->settings, KEY_CUSTOM_ELEVATOR_ACTION, (const gchar * const*) strs);
if (strv != NULL)
g_strfreev (strv);
} else {
g_settings_set_string (button->settings, CUSTOM_ACTION_KEY, str);
}
g_settings_set_enum (button->settings, ACTION_TYPE_KEY, GSD_WACOM_ACTION_TYPE_CUSTOM);
g_free (str);
}
static void
accel_cleared_callback (GtkCellRendererText *cell,
const char *path_string,
CcWacomPage *page)
{
GtkTreeView *view;
GtkTreePath *path = gtk_tree_path_new_from_string (path_string);
GtkTreeIter iter;
GtkTreeModel *model;
GsdWacomTabletButton *button;
CcWacomPagePrivate *priv;
GtkDirectionType dir;
priv = page->priv;
view = GTK_TREE_VIEW (MWID("shortcut_treeview"));
model = gtk_tree_view_get_model (view);
gtk_tree_model_get_iter (model, &iter, path);
gtk_tree_path_free (path);
gtk_tree_model_get (model, &iter,
MAPPING_BUTTON_COLUMN, &button,
MAPPING_BUTTON_DIRECTION, &dir,
-1);
/* sanity check */
if (button == NULL)
return;
/* Unset the key */
if (button->type == WACOM_TABLET_BUTTON_TYPE_ELEVATOR) {
char *strs[3];
char **strv;
strs[2] = NULL;
strs[0] = strs[1] = "";
strv = g_settings_get_strv (button->settings, KEY_CUSTOM_ELEVATOR_ACTION);
if (strv != NULL) {
if (g_strv_length (strv) >= 1)
strs[0] = strv[0];
if (g_strv_length (strv) >= 2)
strs[1] = strv[1];
}
if (dir == GTK_DIR_UP)
strs[0] = "";
else
strs[1] = "";
if (*strs[0] == '\0' && *strs[1] == '\0')
g_settings_set_enum (button->settings, ACTION_TYPE_KEY, GSD_WACOM_ACTION_TYPE_NONE);
g_settings_set_strv (button->settings, KEY_CUSTOM_ELEVATOR_ACTION, (const gchar * const*) strs);
if (strv != NULL)
g_strfreev (strv);
} else {
g_settings_set_enum (button->settings, ACTION_TYPE_KEY, GSD_WACOM_ACTION_TYPE_NONE);
g_settings_set_string (button->settings, CUSTOM_ACTION_KEY, "");
}
}
static void
add_button_to_store (GtkListStore *model,
GsdWacomTabletButton *button,
GtkDirectionType dir,
GsdWacomActionType type)
{
GtkTreeIter new_row;
char *dir_name;
if (dir == GTK_DIR_UP || dir == GTK_DIR_DOWN) {
dir_name = g_strdup_printf ("%s (%s)",
button->name,
dir == GTK_DIR_UP ? _("Up") : _("Down"));
} else {
dir_name = NULL;
}
gtk_list_store_append (model, &new_row);
gtk_list_store_set (model, &new_row,
MAPPING_DESCRIPTION_COLUMN, dir_name ? dir_name : button->name,
MAPPING_TYPE_COLUMN, WACOM_C(action_table[type].action_name),
MAPPING_BUTTON_COLUMN, button,
MAPPING_BUTTON_DIRECTION, dir,
-1);
g_free (dir_name);
}
static void
action_set_func (GtkTreeViewColumn *tree_column,
GtkCellRenderer *cell,
GtkTreeModel *model,
GtkTreeIter *iter,
gpointer data)
{
GsdWacomTabletButton *button;
GsdWacomActionType type;
gtk_tree_model_get (model, iter, MAPPING_BUTTON_COLUMN, &button, -1);
if (button == NULL) {
g_object_set (cell, "visible", FALSE, NULL);
return;
}
if (button->type == WACOM_TABLET_BUTTON_TYPE_HARDCODED) {
g_object_set (cell,
"visible", TRUE,
"editable", FALSE,
"style", PANGO_STYLE_NORMAL,
"text", _("Switch Modes"),
NULL);
return;
}
if (button->type == WACOM_TABLET_BUTTON_TYPE_ELEVATOR) {
g_object_set (cell,
"visible", TRUE,
"editable", FALSE,
"style", PANGO_STYLE_NORMAL,
"text", WACOM_C(action_table[GSD_WACOM_ACTION_TYPE_CUSTOM].action_name),
NULL);
return;
}
if (button->settings == NULL) {
g_warning ("Button '%s' does not have an associated GSettings", button->id);
return;
}
type = g_settings_get_enum (button->settings, ACTION_TYPE_KEY);
g_object_set (cell,
"visible", TRUE,
"editable", TRUE,
"style", PANGO_STYLE_NORMAL,
"text", WACOM_C(action_table[type].action_name),
NULL);
}
static void
combo_action_cell_changed (GtkCellRendererCombo *cell,
const gchar *path_string,
GtkTreeIter *new_iter,
CcWacomPage *page)
{
GtkTreeView *tree_view;
GtkTreePath *path;
GtkTreeModel *model;
CcWacomPagePrivate *priv;
GsdWacomActionType type;
GtkTreeIter iter;
GsdWacomTabletButton *button;
priv = page->priv;
tree_view = GTK_TREE_VIEW (MWID("shortcut_treeview"));
model = gtk_tree_view_get_model (tree_view);
path = gtk_tree_path_new_from_string (path_string);
gtk_tree_model_get (GTK_TREE_MODEL (priv->action_store), new_iter, ACTION_TYPE_COLUMN, &type, -1);
gtk_tree_model_get_iter (model, &iter, path);
gtk_list_store_set (GTK_LIST_STORE (model), &iter, MAPPING_TYPE_COLUMN, WACOM_C(action_table[type].action_name), -1);
gtk_tree_path_free (path);
gtk_tree_model_get (model, &iter, MAPPING_BUTTON_COLUMN, &button, -1);
if (button == NULL)
return;
if (button->settings == NULL)
return;
g_settings_set_enum (button->settings, ACTION_TYPE_KEY, type);
gtk_widget_grab_focus (GTK_WIDGET (tree_view));
}
static void
setup_mapping_treeview (CcWacomPage *page)
{
CcWacomPagePrivate *priv;
GtkTreeView *treeview;
GtkCellRenderer *renderer;
GtkTreeViewColumn *column;
GtkListStore *model;
GtkTreeIter iter;
GList *list, *l;
gint i;
priv = page->priv;
treeview = GTK_TREE_VIEW(MWID ("shortcut_treeview"));
g_signal_connect (treeview, "button_press_event",
G_CALLBACK (start_editing_cb), page);
g_signal_connect (treeview, "row-activated",
G_CALLBACK (start_editing_kb_cb), page);
renderer = gtk_cell_renderer_text_new ();
g_object_set (G_OBJECT (renderer), "ellipsize", PANGO_ELLIPSIZE_END, NULL);
column = gtk_tree_view_column_new_with_attributes (_("Button"),
renderer,
"text", MAPPING_DESCRIPTION_COLUMN,
NULL);
gtk_tree_view_column_set_resizable (column, FALSE);
gtk_tree_view_column_set_expand (column, TRUE);
gtk_tree_view_append_column (treeview, column);
gtk_tree_view_column_set_sort_column_id (column, MAPPING_DESCRIPTION_COLUMN);
priv->action_store = gtk_list_store_new (ACTION_N_COLUMNS, G_TYPE_STRING, G_TYPE_INT);
for (i = 0; i < G_N_ELEMENTS (action_table); i++) {
/* Screen tablets cannot switch monitors (as the monitor is the tablet) */
if (action_table[i].action_type == GSD_WACOM_ACTION_TYPE_SWITCH_MONITOR &&
gsd_wacom_device_is_screen_tablet (priv->stylus))
continue;
gtk_list_store_append (priv->action_store, &iter);
gtk_list_store_set (priv->action_store, &iter,
ACTION_NAME_COLUMN, WACOM_C(action_table[i].action_name),
ACTION_TYPE_COLUMN, action_table[i].action_type, -1);
}
renderer = gtk_cell_renderer_combo_new ();
g_object_set (renderer,
"text-column", ACTION_NAME_COLUMN,
"has-entry", FALSE,
"model", priv->action_store,
"editable", TRUE,
NULL);
g_signal_connect (renderer, "changed",
G_CALLBACK (combo_action_cell_changed), page);
column = gtk_tree_view_column_new_with_attributes (_("Type"),
renderer,
"text", MAPPING_TYPE_COLUMN,
NULL);
gtk_tree_view_column_set_cell_data_func (column, renderer, action_set_func, NULL, NULL);
gtk_tree_view_column_set_resizable (column, FALSE);
gtk_tree_view_column_set_expand (column, FALSE);
gtk_tree_view_append_column (treeview, column);
renderer = (GtkCellRenderer *) g_object_new (GTK_TYPE_CELL_RENDERER_ACCEL,
"accel-mode", GTK_CELL_RENDERER_ACCEL_MODE_OTHER,
NULL);
g_signal_connect (renderer, "accel_edited",
G_CALLBACK (accel_edited_callback),
page);
g_signal_connect (renderer, "accel_cleared",
G_CALLBACK (accel_cleared_callback),
page);
column = gtk_tree_view_column_new_with_attributes (_("Action"), renderer, NULL);
gtk_tree_view_column_set_cell_data_func (column, renderer, accel_set_func, NULL, NULL);
gtk_tree_view_column_set_resizable (column, FALSE);
gtk_tree_view_column_set_expand (column, FALSE);
gtk_tree_view_append_column (treeview, column);
model = gtk_list_store_new (MAPPING_N_COLUMNS, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_POINTER, G_TYPE_INT);
gtk_tree_view_set_model (treeview, GTK_TREE_MODEL (model));
/* Fill it up! */
list = gsd_wacom_device_get_buttons (page->priv->pad);
for (l = list; l != NULL; l = l->next) {
GsdWacomTabletButton *button = l->data;
GsdWacomActionType type = GSD_WACOM_ACTION_TYPE_NONE;
if (button->settings)
type = g_settings_get_enum (button->settings, ACTION_TYPE_KEY);
if (button->type == WACOM_TABLET_BUTTON_TYPE_ELEVATOR) {
add_button_to_store (model, button, GTK_DIR_UP, GSD_WACOM_ACTION_TYPE_CUSTOM);
add_button_to_store (model, button, GTK_DIR_DOWN, GSD_WACOM_ACTION_TYPE_CUSTOM);
} else {
add_button_to_store (model, button, 0, type);
}
}
g_list_free (list);
g_object_unref (model);
}
static void
button_mapping_dialog_closed (GtkDialog *dialog,
int response_id,
CcWacomPage *page)
{
CcWacomPagePrivate *priv;
priv = page->priv;
gtk_widget_destroy (MWID ("button-mapping-dialog"));
g_object_unref (page->priv->mapping_builder);
page->priv->mapping_builder = NULL;
}
static void
map_buttons_button_clicked_cb (GtkButton *button,
CcWacomPage *page)
{
GError *error = NULL;
GtkWidget *dialog;
CcWacomPagePrivate *priv;
GtkWidget *toplevel;
priv = page->priv;
g_assert (priv->mapping_builder == NULL);
priv->mapping_builder = gtk_builder_new ();
gtk_builder_add_from_file (priv->mapping_builder,
CINNAMONCC_UI_DIR "/button-mapping.ui",
&error);
if (error != NULL) {
g_warning ("Error loading UI file: %s", error->message);
g_object_unref (priv->mapping_builder);
priv->mapping_builder = NULL;
g_error_free (error);
return;
}
setup_mapping_treeview (page);
dialog = MWID ("button-mapping-dialog");
toplevel = gtk_widget_get_toplevel (GTK_WIDGET (page));
gtk_window_set_transient_for (GTK_WINDOW (dialog), GTK_WINDOW (toplevel));
gtk_window_set_modal (GTK_WINDOW (dialog), TRUE);
g_signal_connect (G_OBJECT (dialog), "response",
G_CALLBACK (button_mapping_dialog_closed), page);
gtk_widget_show (dialog);
priv->button_map = dialog;
g_object_add_weak_pointer (G_OBJECT (dialog), (gpointer *) &priv->button_map);
}
static void
display_mapping_dialog_closed (GtkDialog *dialog,
int response_id,
CcWacomPage *page)
{
CcWacomPagePrivate *priv;
int layout;
priv = page->priv;
gtk_widget_destroy (priv->dialog);
priv->dialog = NULL;
priv->mapping = NULL;
layout = get_layout_type (priv->stylus);
update_tablet_ui (page, layout);
}
static void
display_mapping_button_clicked_cb (GtkButton *button,
CcWacomPage *page)
{
CcWacomPagePrivate *priv;
priv = page->priv;
g_assert (priv->mapping == NULL);
priv->dialog = gtk_dialog_new_with_buttons (_("Display Mapping"),
GTK_WINDOW (gtk_widget_get_toplevel (GTK_WIDGET (page))),
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_STOCK_CLOSE,
GTK_RESPONSE_ACCEPT,
NULL);
priv->mapping = cc_wacom_mapping_panel_new ();
cc_wacom_mapping_panel_set_device (CC_WACOM_MAPPING_PANEL (priv->mapping),
priv->stylus);
gtk_container_add (GTK_CONTAINER (gtk_dialog_get_content_area (GTK_DIALOG (priv->dialog))),
priv->mapping);
g_signal_connect (G_OBJECT (priv->dialog), "response",
G_CALLBACK (display_mapping_dialog_closed), page);
gtk_widget_show_all (priv->dialog);
g_object_add_weak_pointer (G_OBJECT (priv->mapping), (gpointer *) &priv->dialog);
}
static void
tabletmode_changed_cb (GtkComboBox *combo, gpointer user_data)
{
CcWacomPagePrivate *priv = CC_WACOM_PAGE(user_data)->priv;
GtkListStore *liststore;
GtkTreeIter iter;
gint mode;
gboolean is_absolute;
if (!gtk_combo_box_get_active_iter (combo, &iter))
return;
liststore = GTK_LIST_STORE (WID ("liststore-tabletmode"));
gtk_tree_model_get (GTK_TREE_MODEL (liststore), &iter,
MODENUMBER_COLUMN, &mode,
-1);
is_absolute = (mode == MODE_ABSOLUTE);
g_settings_set_boolean (priv->wacom_settings, "is-absolute", is_absolute);
}
static const gchar*
opposite_rotation (const gchar *rotation)
{
/* Order matters here, if not found we return "none" */
static const gchar *rotations[] = { "half", "cw", "none", "ccw" };
guint i, n;
n = G_N_ELEMENTS (rotations);
for (i = 0; i < n; i++) {
if (strcmp (rotation, rotations[i]) == 0)
break;
}
return rotations[(i + n / 2) % n];
}
static void
left_handed_toggled_cb (GtkSwitch *sw, GParamSpec *pspec, gpointer *user_data)
{
CcWacomPagePrivate *priv = CC_WACOM_PAGE(user_data)->priv;
GsdWacomDevice *device = priv->stylus;
GsdWacomRotation display_rotation;
const gchar* rotation;
display_rotation = gsd_wacom_device_get_display_rotation (device);
rotation = gsd_wacom_device_rotation_type_to_name (display_rotation);
if (gtk_switch_get_active (sw))
rotation = opposite_rotation (rotation);
g_settings_set_string (priv->wacom_settings, "rotation", rotation);
}
static void
set_left_handed_from_gsettings (CcWacomPage *page)
{
CcWacomPagePrivate *priv = CC_WACOM_PAGE(page)->priv;
GsdWacomDevice *device = priv->stylus;
GsdWacomRotation display_rotation;
const gchar* rotation;
display_rotation = gsd_wacom_device_get_display_rotation (device);
rotation = g_settings_get_string (priv->wacom_settings, "rotation");
if (strcmp (rotation, gsd_wacom_device_rotation_type_to_name (display_rotation)) != 0)
gtk_switch_set_active (GTK_SWITCH (WID ("switch-left-handed")), TRUE);
}
static void
set_mode_from_gsettings (GtkComboBox *combo, CcWacomPage *page)
{
CcWacomPagePrivate *priv = page->priv;
gboolean is_absolute;
is_absolute = g_settings_get_boolean (priv->wacom_settings, "is-absolute");
/* this must be kept in sync with the .ui file */
gtk_combo_box_set_active (combo, is_absolute ? MODE_ABSOLUTE : MODE_RELATIVE);
}
static void
combobox_text_cellrenderer (GtkComboBox *combo, int name_column)
{
GtkCellRenderer *renderer;
renderer = gtk_cell_renderer_text_new ();
gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo), renderer, TRUE);
gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combo), renderer,
"text", BUTTONNAME_COLUMN, NULL);
}
static gboolean
display_clicked_cb (GtkButton *button,
CcWacomPage *page)
{
cc_wacom_panel_switch_to_panel (page->priv->panel, "display");
return TRUE;
}
/* Boilerplate code goes below */
static void
cc_wacom_page_get_property (GObject *object,
guint property_id,
GValue *value,
GParamSpec *pspec)
{
switch (property_id)
{
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}
}
static void
cc_wacom_page_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec)
{
switch (property_id)
{
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}
}
static void
cc_wacom_page_dispose (GObject *object)
{
CcWacomPagePrivate *priv = CC_WACOM_PAGE (object)->priv;
if (priv->area) {
calib_area_free (priv->area);
priv->area = NULL;
}
if (priv->button_map) {
gtk_widget_destroy (priv->button_map);
priv->button_map = NULL;
}
if (priv->dialog) {
gtk_widget_destroy (priv->dialog);
priv->dialog = NULL;
}
if (priv->builder) {
g_object_unref (priv->builder);
priv->builder = NULL;
}
priv->panel = NULL;
G_OBJECT_CLASS (cc_wacom_page_parent_class)->dispose (object);
}
static void
cc_wacom_page_class_init (CcWacomPageClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
g_type_class_add_private (klass, sizeof (CcWacomPagePrivate));
object_class->get_property = cc_wacom_page_get_property;
object_class->set_property = cc_wacom_page_set_property;
object_class->dispose = cc_wacom_page_dispose;
}
static void
cc_wacom_page_init (CcWacomPage *self)
{
CcWacomPagePrivate *priv;
GError *error = NULL;
GtkComboBox *combo;
GtkWidget *box;
GtkSwitch *sw;
char *objects[] = {
"main-grid",
"liststore-tabletmode",
"liststore-buttons",
"adjustment-tip-feel",
"adjustment-eraser-feel",
NULL
};
priv = self->priv = WACOM_PAGE_PRIVATE (self);
priv->builder = gtk_builder_new ();
gtk_builder_add_objects_from_file (priv->builder,
CINNAMONCC_UI_DIR "/cinnamon-wacom-properties.ui",
objects,
&error);
if (error != NULL) {
g_warning ("Error loading UI file: %s", error->message);
g_object_unref (priv->builder);
g_error_free (error);
return;
}
box = WID ("main-grid");
gtk_container_add (GTK_CONTAINER (self), box);
gtk_widget_set_vexpand (GTK_WIDGET (box), TRUE);
self->priv->notebook = WID ("stylus-notebook");
g_signal_connect (WID ("button-calibrate"), "clicked",
G_CALLBACK (calibrate_button_clicked_cb), self);
g_signal_connect (WID ("map-buttons-button"), "clicked",
G_CALLBACK (map_buttons_button_clicked_cb), self);
combo = GTK_COMBO_BOX (WID ("combo-tabletmode"));
combobox_text_cellrenderer (combo, MODELABEL_COLUMN);
g_signal_connect (G_OBJECT (combo), "changed",
G_CALLBACK (tabletmode_changed_cb), self);
sw = GTK_SWITCH (WID ("switch-left-handed"));
g_signal_connect (G_OBJECT (sw), "notify::active",
G_CALLBACK (left_handed_toggled_cb), self);
g_signal_connect (G_OBJECT (WID ("display-link")), "activate-link",
G_CALLBACK (display_clicked_cb), self);
g_signal_connect (G_OBJECT (WID ("display-mapping-button")), "clicked",
G_CALLBACK (display_mapping_button_clicked_cb), self);
priv->nav = cc_wacom_nav_button_new ();
gtk_widget_set_halign (priv->nav, GTK_ALIGN_END);
gtk_widget_set_margin_left (priv->nav, 10);
gtk_grid_attach (GTK_GRID (box), priv->nav, 1, 0, 1, 1);
}
static void
set_icon_name (CcWacomPage *page,
const char *widget_name,
const char *icon_name)
{
CcWacomPagePrivate *priv;
char *filename, *path;
priv = page->priv;
filename = g_strdup_printf ("%s.svg", icon_name);
path = g_build_filename (CINNAMONCC_UI_DIR, filename, NULL);
g_free (filename);
gtk_image_set_from_file (GTK_IMAGE (WID (widget_name)), path);
g_free (path);
}
typedef struct {
GsdWacomStylus *stylus;
GsdWacomStylus *eraser;
} StylusPair;
static void
add_styli (CcWacomPage *page)
{
GList *styli, *l;
CcWacomPagePrivate *priv;
priv = page->priv;
styli = gsd_wacom_device_list_styli (priv->stylus);
for (l = styli; l; l = l->next) {
GsdWacomStylus *stylus, *eraser;
GtkWidget *page;
stylus = l->data;
if (gsd_wacom_stylus_get_stylus_type (stylus) == WACOM_STYLUS_TYPE_PUCK)
continue;
if (gsd_wacom_stylus_get_has_eraser (stylus)) {
GsdWacomDeviceType type;
type = gsd_wacom_stylus_get_stylus_type (stylus);
eraser = gsd_wacom_device_get_stylus_for_type (priv->eraser, type);
} else {
eraser = NULL;
}
page = cc_wacom_stylus_page_new (stylus, eraser);
cc_wacom_stylus_page_set_navigation (CC_WACOM_STYLUS_PAGE (page), GTK_NOTEBOOK (priv->notebook));
gtk_widget_show (page);
gtk_notebook_append_page (GTK_NOTEBOOK (priv->notebook), page, NULL);
}
g_list_free (styli);
}
static void
stylus_changed (GsdWacomDevice *device,
GParamSpec *pspec,
CcWacomPage *page)
{
GsdWacomStylus *stylus;
CcWacomPagePrivate *priv;
int num_pages;
guint i;
priv = page->priv;
g_object_get (G_OBJECT (device), "last-stylus", &stylus, NULL);
if (stylus == NULL)
return;
num_pages = gtk_notebook_get_n_pages (GTK_NOTEBOOK (priv->notebook));
for (i = 0; i < num_pages; i++) {
GsdWacomStylus *s;
CcWacomStylusPage *spage;
spage = CC_WACOM_STYLUS_PAGE (gtk_notebook_get_nth_page (GTK_NOTEBOOK (priv->notebook), i));
s = cc_wacom_stylus_page_get_stylus (spage);
if (s == stylus) {
gtk_notebook_set_current_page (GTK_NOTEBOOK (priv->notebook), i);
return;
}
}
g_warning ("Failed to find the page for stylus '%s'",
gsd_wacom_stylus_get_name (stylus));
}
static void
remove_left_handed (CcWacomPagePrivate *priv)
{
gtk_widget_destroy (WID ("label-left-handed"));
gtk_widget_destroy (WID ("switch-left-handed"));
}
static void
remove_display_link (CcWacomPagePrivate *priv)
{
gtk_widget_destroy (WID ("display-link"));
gtk_container_child_set (CWID ("main-grid"),
WID ("tablet-buttons-box"),
"top_attach", 2, NULL);
}
static void
update_tablet_ui (CcWacomPage *page,
int layout)
{
CcWacomPagePrivate *priv;
gboolean has_monitor = FALSE;
priv = page->priv;
/* Hide the pad buttons if no pad is present */
gtk_widget_set_visible (WID ("map-buttons-button"), priv->pad != NULL);
switch (layout) {
case LAYOUT_NORMAL:
remove_left_handed (page->priv);
remove_display_link (page->priv);
break;
case LAYOUT_REVERSIBLE:
remove_display_link (page->priv);
break;
case LAYOUT_SCREEN:
remove_left_handed (page->priv);
gtk_widget_destroy (WID ("combo-tabletmode"));
gtk_widget_destroy (WID ("label-trackingmode"));
gtk_widget_destroy (WID ("display-mapping-button"));
gtk_widget_show (WID ("button-calibrate"));
if (gsd_wacom_device_get_display_monitor (page->priv->stylus) >= 0)
has_monitor = TRUE;
gtk_widget_set_sensitive (WID ("button-calibrate"), has_monitor);
gtk_widget_show (WID ("display-link"));
gtk_container_child_set (CWID ("main-grid"),
WID ("tablet-buttons-box"),
"top_attach", 1, NULL);
gtk_container_child_set (CWID ("main-grid"),
WID ("display-link"),
"top_attach", 2, NULL);
break;
default:
g_assert_not_reached ();
}
}
gboolean
cc_wacom_page_update_tools (CcWacomPage *page,
GsdWacomDevice *stylus,
GsdWacomDevice *eraser,
GsdWacomDevice *pad)
{
CcWacomPagePrivate *priv;
int layout;
gboolean changed;
/* Type of layout */
layout = get_layout_type (stylus);
priv = page->priv;
changed = (priv->stylus != stylus || priv->eraser != eraser || priv->pad != pad);
if (!changed)
return FALSE;
priv->stylus = stylus;
priv->eraser = eraser;
priv->pad = pad;
update_tablet_ui (CC_WACOM_PAGE (page), layout);
return TRUE;
}
GtkWidget *
cc_wacom_page_new (CcWacomPanel *panel,
GsdWacomDevice *stylus,
GsdWacomDevice *eraser,
GsdWacomDevice *pad)
{
CcWacomPage *page;
CcWacomPagePrivate *priv;
g_return_val_if_fail (GSD_IS_WACOM_DEVICE (stylus), NULL);
g_return_val_if_fail (gsd_wacom_device_get_device_type (stylus) == WACOM_TYPE_STYLUS, NULL);
g_return_val_if_fail (GSD_IS_WACOM_DEVICE (eraser), NULL);
g_return_val_if_fail (gsd_wacom_device_get_device_type (eraser) == WACOM_TYPE_ERASER, NULL);
if (pad != NULL)
g_return_val_if_fail (gsd_wacom_device_get_device_type (pad) == WACOM_TYPE_PAD, NULL);
page = g_object_new (CC_TYPE_WACOM_PAGE, NULL);
priv = page->priv;
priv->panel = panel;
cc_wacom_page_update_tools (page, stylus, eraser, pad);
/* FIXME move this to construct */
priv->wacom_settings = gsd_wacom_device_get_settings (stylus);
set_mode_from_gsettings (GTK_COMBO_BOX (WID ("combo-tabletmode")), page);
/* Tablet name */
gtk_label_set_text (GTK_LABEL (WID ("label-tabletmodel")), gsd_wacom_device_get_name (stylus));
/* Left-handedness */
if (gsd_wacom_device_reversible (stylus))
set_left_handed_from_gsettings (page);
/* Tablet icon */
set_icon_name (page, "image-tablet", gsd_wacom_device_get_icon_name (stylus));
/* Add styli */
add_styli (page);
/* Get the current stylus and switch to its page */
stylus_changed (priv->stylus, NULL, page);
g_signal_connect (G_OBJECT (priv->stylus), "notify::last-stylus",
G_CALLBACK (stylus_changed), page);
return GTK_WIDGET (page);
}
void
cc_wacom_page_set_navigation (CcWacomPage *page,
GtkNotebook *notebook,
gboolean ignore_first_page)
{
CcWacomPagePrivate *priv;
g_return_if_fail (CC_IS_WACOM_PAGE (page));
priv = page->priv;
g_object_set (G_OBJECT (priv->nav),
"notebook", notebook,
"ignore-first", ignore_first_page,
NULL);
}
|
393 | ./cinnamon-control-center/panels/unused/wacom/cc-wacom-stylus-page.c | /*
* Copyright © 2011 Red Hat, Inc.
*
* 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.
*
* Authors: Peter Hutterer <[email protected]>
* Bastien Nocera <[email protected]>
*
*/
#include <config.h>
#include <glib/gi18n.h>
#include "cc-wacom-stylus-page.h"
#include "cc-wacom-nav-button.h"
#include <gtk/gtk.h>
#include <string.h>
#define WID(x) (GtkWidget *) gtk_builder_get_object (priv->builder, x)
#define CWID(x) (GtkContainer *) gtk_builder_get_object (priv->builder, x)
G_DEFINE_TYPE (CcWacomStylusPage, cc_wacom_stylus_page, GTK_TYPE_BOX)
#define WACOM_STYLUS_PAGE_PRIVATE(o) \
(G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_WACOM_STYLUS_PAGE, CcWacomStylusPagePrivate))
struct _CcWacomStylusPagePrivate
{
GsdWacomStylus *stylus, *eraser;
GtkBuilder *builder;
GtkWidget *nav;
GSettings *stylus_settings, *eraser_settings;
};
/* Button combo box storage columns */
enum {
BUTTONNUMBER_COLUMN,
BUTTONNAME_COLUMN,
N_BUTTONCOLUMNS
};
/* GSettings stores pressurecurve as 4 values like the driver. We map slider
* scale to these values given the array below. These settings were taken from
* wacomcpl, where they've been around for years.
*/
#define N_PRESSURE_CURVES 7
static const gint32 PRESSURE_CURVES[N_PRESSURE_CURVES][4] = {
{ 0, 75, 25, 100 }, /* soft */
{ 0, 50, 50, 100 },
{ 0, 25, 75, 100 },
{ 0, 0, 100, 100 }, /* neutral */
{ 25, 0, 100, 75 },
{ 50, 0, 100, 50 },
{ 75, 0, 100, 25 } /* firm */
};
static void
set_pressurecurve (GtkRange *range, GSettings *settings)
{
gint slider_val = gtk_range_get_value (range);
GVariant *values[4],
*array;
int i;
for (i = 0; i < G_N_ELEMENTS (values); i++)
values[i] = g_variant_new_int32 (PRESSURE_CURVES[slider_val][i]);
array = g_variant_new_array (G_VARIANT_TYPE_INT32, values, G_N_ELEMENTS (values));
g_settings_set_value (settings, "pressurecurve", array);
}
static void
tip_feel_value_changed_cb (GtkRange *range, gpointer user_data)
{
set_pressurecurve (range, CC_WACOM_STYLUS_PAGE(user_data)->priv->stylus_settings);
}
static void
eraser_feel_value_changed_cb (GtkRange *range, gpointer user_data)
{
set_pressurecurve (range, CC_WACOM_STYLUS_PAGE(user_data)->priv->eraser_settings);
}
static void
set_feel_from_gsettings (GtkAdjustment *adjustment, GSettings *settings)
{
GVariant *variant;
const gint32 *values;
gsize nvalues;
int i;
variant = g_settings_get_value (settings, "pressurecurve");
values = g_variant_get_fixed_array (variant, &nvalues, sizeof (gint32));
if (nvalues != 4) {
g_warning ("Invalid pressure curve format, expected 4 values (got %"G_GSIZE_FORMAT")", nvalues);
return;
}
for (i = 0; i < N_PRESSURE_CURVES; i++) {
if (memcmp (PRESSURE_CURVES[i], values, sizeof (gint32) * 4) == 0) {
gtk_adjustment_set_value (adjustment, i);
break;
}
}
}
static void
set_button_mapping_from_gsettings (GtkComboBox *combo, GSettings* settings, gint current_button)
{
GVariant *current;
gsize nvalues;
const gint *values;
GtkTreeModel *model;
GtkTreeIter iter;
gboolean valid;
current = g_settings_get_value (settings, "buttonmapping");
values = g_variant_get_fixed_array (current, &nvalues, sizeof (gint32));
model = gtk_combo_box_get_model (combo);
valid = gtk_tree_model_get_iter_first (model, &iter);
while (valid) {
gint button;
gtk_tree_model_get (model, &iter,
BUTTONNUMBER_COLUMN, &button,
-1);
/* Currently button values match logical X buttons. If we
* introduce things like double-click, this code must
* change. Recommendation: use negative buttons numbers for
* special ones.
*/
/* 0 vs 1-indexed array/button numbers */
if (button == values[current_button - 1]) {
gtk_combo_box_set_active_iter (combo, &iter);
break;
}
valid = gtk_tree_model_iter_next (model, &iter);
}
}
static void
map_button (GSettings *settings, int button2, int button3)
{
GVariant *current; /* current mapping */
GVariant *array; /* new mapping */
GVariant **tmp;
gsize nvalues;
const gint *values;
gint i;
current = g_settings_get_value (settings, "buttonmapping");
values = g_variant_get_fixed_array (current, &nvalues, sizeof (gint32));
tmp = g_malloc (nvalues * sizeof (GVariant*));
for (i = 0; i < nvalues; i++) {
if (i == 1) /* zero indexed array vs one-indexed buttons */
tmp[i] = g_variant_new_int32 (button2);
else if (i == 2)
tmp[i] = g_variant_new_int32 (button3);
else
tmp[i] = g_variant_new_int32 (values[i]);
}
array = g_variant_new_array (G_VARIANT_TYPE_INT32, tmp, nvalues);
g_settings_set_value (settings, "buttonmapping", array);
g_free (tmp);
}
static void
button_changed_cb (GtkComboBox *combo, gpointer user_data)
{
CcWacomStylusPagePrivate *priv = CC_WACOM_STYLUS_PAGE(user_data)->priv;
GtkTreeIter iter;
GtkListStore *liststore;
gint mapping_b2,
mapping_b3;
if (!gtk_combo_box_get_active_iter (GTK_COMBO_BOX (WID ("combo-bottombutton")), &iter))
return;
liststore = GTK_LIST_STORE (WID ("liststore-buttons"));
gtk_tree_model_get (GTK_TREE_MODEL (liststore), &iter,
BUTTONNUMBER_COLUMN, &mapping_b2,
-1);
if (!gtk_combo_box_get_active_iter (GTK_COMBO_BOX (WID ("combo-topbutton")), &iter))
return;
gtk_tree_model_get (GTK_TREE_MODEL (liststore), &iter,
BUTTONNUMBER_COLUMN, &mapping_b3,
-1);
map_button (priv->stylus_settings, mapping_b2, mapping_b3);
}
static void
combobox_text_cellrenderer (GtkComboBox *combo, int name_column)
{
GtkCellRenderer *renderer;
renderer = gtk_cell_renderer_text_new ();
gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo), renderer, TRUE);
gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combo), renderer,
"text", BUTTONNAME_COLUMN, NULL);
}
/* Boilerplate code goes below */
static void
cc_wacom_stylus_page_get_property (GObject *object,
guint property_id,
GValue *value,
GParamSpec *pspec)
{
switch (property_id)
{
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}
}
static void
cc_wacom_stylus_page_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec)
{
switch (property_id)
{
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}
}
static void
cc_wacom_stylus_page_dispose (GObject *object)
{
CcWacomStylusPagePrivate *priv = CC_WACOM_STYLUS_PAGE (object)->priv;
if (priv->builder) {
g_object_unref (priv->builder);
priv->builder = NULL;
}
G_OBJECT_CLASS (cc_wacom_stylus_page_parent_class)->dispose (object);
}
static void
cc_wacom_stylus_page_class_init (CcWacomStylusPageClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
g_type_class_add_private (klass, sizeof (CcWacomStylusPagePrivate));
object_class->get_property = cc_wacom_stylus_page_get_property;
object_class->set_property = cc_wacom_stylus_page_set_property;
object_class->dispose = cc_wacom_stylus_page_dispose;
}
static void
cc_wacom_stylus_page_init (CcWacomStylusPage *self)
{
CcWacomStylusPagePrivate *priv;
GError *error = NULL;
GtkComboBox *combo;
GtkWidget *box;
char *objects[] = {
"stylus-grid",
"liststore-buttons",
"adjustment-tip-feel",
"adjustment-eraser-feel",
NULL
};
priv = self->priv = WACOM_STYLUS_PAGE_PRIVATE (self);
priv->builder = gtk_builder_new ();
gtk_builder_add_objects_from_file (priv->builder,
CINNAMONCC_UI_DIR "/wacom-stylus-page.ui",
objects,
&error);
if (error != NULL) {
g_warning ("Error loading UI file: %s", error->message);
g_object_unref (priv->builder);
g_error_free (error);
return;
}
box = WID ("stylus-grid");
gtk_container_add (GTK_CONTAINER (self), box);
gtk_widget_set_vexpand (GTK_WIDGET (box), TRUE);
g_signal_connect (WID ("scale-tip-feel"), "value-changed",
G_CALLBACK (tip_feel_value_changed_cb), self);
g_signal_connect (WID ("scale-eraser-feel"), "value-changed",
G_CALLBACK (eraser_feel_value_changed_cb), self);
combo = GTK_COMBO_BOX (WID ("combo-topbutton"));
combobox_text_cellrenderer (combo, BUTTONNAME_COLUMN);
g_signal_connect (G_OBJECT (combo), "changed",
G_CALLBACK (button_changed_cb), self);
combo = GTK_COMBO_BOX (WID ("combo-bottombutton"));
combobox_text_cellrenderer (combo, BUTTONNAME_COLUMN);
g_signal_connect (G_OBJECT (combo), "changed",
G_CALLBACK (button_changed_cb), self);
priv->nav = cc_wacom_nav_button_new ();
gtk_widget_set_halign (priv->nav, GTK_ALIGN_END);
gtk_widget_set_margin_left (priv->nav, 10);
gtk_grid_attach (GTK_GRID (box), priv->nav, 1, 0, 1, 1);
}
static void
set_icon_name (CcWacomStylusPage *page,
const char *widget_name,
const char *icon_name)
{
CcWacomStylusPagePrivate *priv;
char *filename, *path;
priv = page->priv;
filename = g_strdup_printf ("%s.svg", icon_name);
path = g_build_filename (CINNAMONCC_UI_DIR, filename, NULL);
g_free (filename);
gtk_image_set_from_file (GTK_IMAGE (WID (widget_name)), path);
g_free (path);
}
/* Different types of layout for the stylus config */
enum {
LAYOUT_NORMAL, /* eraser, 2 buttons, tip */
LAYOUT_INKING, /* tip */
LAYOUT_AIRBRUSH, /* eraser, 1 button, tip */
LAYOUT_OTHER
};
static void
remove_buttons (CcWacomStylusPagePrivate *priv)
{
gtk_widget_destroy (WID ("combo-topbutton"));
gtk_widget_destroy (WID ("combo-bottombutton"));
gtk_widget_destroy (WID ("label-top-button"));
gtk_widget_destroy (WID ("label-lower-button"));
}
static void
remove_button (CcWacomStylusPagePrivate *priv)
{
gtk_widget_destroy (WID ("combo-topbutton"));
gtk_widget_destroy (WID ("label-top-button"));
gtk_label_set_text (GTK_LABEL (WID ("label-lower-button")), _("Button"));
}
static void
remove_eraser (CcWacomStylusPagePrivate *priv)
{
gtk_widget_destroy (WID ("eraser-box"));
gtk_widget_destroy (WID ("label-eraser-feel"));
}
static void
update_stylus_ui (CcWacomStylusPage *page,
int layout)
{
CcWacomStylusPagePrivate *priv = page->priv;
switch (layout) {
case LAYOUT_NORMAL:
/* easy! */
break;
case LAYOUT_INKING:
remove_buttons (page->priv);
remove_eraser (page->priv);
gtk_container_child_set (CWID ("stylus-controls-grid"),
WID ("label-tip-feel"),
"top_attach", 0, NULL);
gtk_container_child_set (CWID ("stylus-controls-grid"),
WID ("box-tip-feel"),
"top_attach", 0, NULL);
break;
case LAYOUT_AIRBRUSH:
remove_button (page->priv);
gtk_container_child_set (CWID ("stylus-controls-grid"),
WID ("label-lower-button"),
"top_attach", 1, NULL);
gtk_container_child_set (CWID ("stylus-controls-grid"),
WID ("combo-bottombutton"),
"top_attach", 1, NULL);
gtk_container_child_set (CWID ("stylus-controls-grid"),
WID ("label-tip-feel"),
"top_attach", 2, NULL);
gtk_container_child_set (CWID ("stylus-controls-grid"),
WID ("box-tip-feel"),
"top_attach", 2, NULL);
case LAYOUT_OTHER:
/* We already warn about it in cc_wacom_stylus_page_new () */
break;
}
}
GtkWidget *
cc_wacom_stylus_page_new (GsdWacomStylus *stylus,
GsdWacomStylus *eraser)
{
CcWacomStylusPage *page;
CcWacomStylusPagePrivate *priv;
int num_buttons;
int layout;
g_return_val_if_fail (GSD_IS_WACOM_STYLUS (stylus), NULL);
page = g_object_new (CC_TYPE_WACOM_STYLUS_PAGE, NULL);
priv = page->priv;
priv->stylus = stylus;
priv->eraser = eraser;
/* Icon */
set_icon_name (page, "image-stylus", gsd_wacom_stylus_get_icon_name (stylus));
/* Settings */
priv->stylus_settings = gsd_wacom_stylus_get_settings (stylus);
if (eraser != NULL)
priv->eraser_settings = gsd_wacom_stylus_get_settings (eraser);
/* Stylus name */
gtk_label_set_text (GTK_LABEL (WID ("label-stylus")), gsd_wacom_stylus_get_name (stylus));
num_buttons = gsd_wacom_stylus_get_num_buttons (stylus);
if (num_buttons == 0 && eraser == NULL)
layout = LAYOUT_INKING;
else if (num_buttons == 2 && eraser != NULL)
layout = LAYOUT_NORMAL;
else if (num_buttons == 1 && eraser != NULL)
layout = LAYOUT_AIRBRUSH;
else {
layout = LAYOUT_OTHER;
if (num_buttons == 0)
remove_buttons (priv);
else if (num_buttons == 1)
remove_button (priv);
if (eraser == NULL)
remove_eraser (priv);
g_warning ("The layout of this page is not known, %d buttons, %s eraser",
num_buttons, eraser ? "with" : "without");
}
update_stylus_ui (page, layout);
if (num_buttons == 2)
set_button_mapping_from_gsettings (GTK_COMBO_BOX (WID ("combo-topbutton")), priv->stylus_settings, 3);
if (num_buttons >= 1)
set_button_mapping_from_gsettings (GTK_COMBO_BOX (WID ("combo-bottombutton")), priv->stylus_settings, 2);
set_feel_from_gsettings (GTK_ADJUSTMENT (WID ("adjustment-tip-feel")), priv->stylus_settings);
if (eraser != NULL)
set_feel_from_gsettings (GTK_ADJUSTMENT (WID ("adjustment-eraser-feel")), priv->eraser_settings);
g_object_set (G_OBJECT (page), "margin-top", 16, NULL);
return GTK_WIDGET (page);
}
GsdWacomStylus *
cc_wacom_stylus_page_get_stylus (CcWacomStylusPage *page)
{
return page->priv->stylus;
}
void
cc_wacom_stylus_page_set_navigation (CcWacomStylusPage *page,
GtkNotebook *notebook)
{
CcWacomStylusPagePrivate *priv;
g_return_if_fail (CC_IS_WACOM_STYLUS_PAGE (page));
priv = page->priv;
g_object_set (G_OBJECT (priv->nav),
"notebook", notebook,
NULL);
}
|
394 | ./cinnamon-control-center/panels/unused/wacom/calibrator/main.c | /*
* Copyright (c) 2009 Tias Guns
* Copyright (c) 2009 Soren Hauberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "config.h"
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <dirent.h>
#include <glib/gi18n.h>
#include <X11/extensions/XInput.h>
#include "gui_gtk.h"
#include "calibrator.h"
/**
* find a calibratable touchscreen device (using XInput)
*
* if pre_device is NULL, the last calibratable device is selected.
* retuns number of devices found,
* the data of the device is returned in the last 3 function parameters
*/
static int find_device(const char* pre_device, gboolean verbose, gboolean list_devices,
XID* device_id, const char** device_name, XYinfo* device_axis)
{
gboolean pre_device_is_id = TRUE;
int found = 0;
Display* display = XOpenDisplay(NULL);
if (display == NULL) {
fprintf(stderr, "Unable to connect to X server\n");
exit(1);
}
int xi_opcode, event, error;
if (!XQueryExtension(display, "XInputExtension", &xi_opcode, &event, &error)) {
fprintf(stderr, "X Input extension not available.\n");
exit(1);
}
/* verbose, get Xi version */
if (verbose) {
XExtensionVersion *version = XGetExtensionVersion(display, INAME);
if (version && (version != (XExtensionVersion*) NoSuchExtension)) {
printf("DEBUG: %s version is %i.%i\n",
INAME, version->major_version, version->minor_version);
XFree(version);
}
}
if (pre_device != NULL) {
/* check whether the pre_device is an ID (only digits) */
int len = strlen(pre_device);
int loop;
for (loop=0; loop<len; loop++) {
if (!isdigit(pre_device[loop])) {
pre_device_is_id = FALSE;
break;
}
}
}
if (verbose)
printf("DEBUG: Skipping virtual master devices and devices without axis valuators.\n");
int ndevices;
XDeviceInfoPtr list, slist;
slist=list=(XDeviceInfoPtr) XListInputDevices (display, &ndevices);
int i;
for (i=0; i<ndevices; i++, list++)
{
if (list->use == IsXKeyboard || list->use == IsXPointer) /* virtual master device */
continue;
/* if we are looking for a specific device */
if (pre_device != NULL) {
if ((pre_device_is_id && list->id == (XID) atoi(pre_device)) ||
(!pre_device_is_id && strcmp(list->name, pre_device) == 0)) {
/* OK, fall through */
} else {
/* skip, not this device */
continue;
}
}
XAnyClassPtr any = (XAnyClassPtr) (list->inputclassinfo);
int j;
for (j=0; j<list->num_classes; j++)
{
if (any->class == ValuatorClass)
{
XValuatorInfoPtr V = (XValuatorInfoPtr) any;
XAxisInfoPtr ax = (XAxisInfoPtr) V->axes;
if (V->mode != Absolute) {
if (verbose)
printf("DEBUG: Skipping device '%s' id=%i, does not report Absolute events.\n",
list->name, (int)list->id);
} else if (V->num_axes < 2 ||
(ax[0].min_value == -1 && ax[0].max_value == -1) ||
(ax[1].min_value == -1 && ax[1].max_value == -1)) {
if (verbose)
printf("DEBUG: Skipping device '%s' id=%i, does not have two calibratable axes.\n",
list->name, (int)list->id);
} else {
/* a calibratable device (has 2 axis valuators) */
found++;
*device_id = list->id;
*device_name = g_strdup(list->name);
device_axis->x_min = ax[0].min_value;
device_axis->x_max = ax[0].max_value;
device_axis->y_min = ax[1].min_value;
device_axis->y_max = ax[1].max_value;
if (list_devices)
printf("Device \"%s\" id=%i\n", *device_name, (int)*device_id);
}
}
/*
* Increment 'any' to point to the next item in the linked
* list. The length is in bytes, so 'any' must be cast to
* a character pointer before being incremented.
*/
any = (XAnyClassPtr) ((char *) any + any->length);
}
}
XFreeDeviceList(slist);
XCloseDisplay(display);
return found;
}
static void usage(char* cmd, unsigned thr_misclick)
{
fprintf(stderr, "Usage: %s [-h|--help] [-v|--verbose] [--list] [--device <device name or id>] [--precalib <minx> <maxx> <miny> <maxy>] [--misclick <nr of pixels>] [--output-type <auto|xorg.conf.d|hal|xinput>] [--fake]\n", cmd);
fprintf(stderr, "\t-h, --help: print this help message\n");
fprintf(stderr, "\t-v, --verbose: print debug messages during the process\n");
fprintf(stderr, "\t--list: list calibratable input devices and quit\n");
fprintf(stderr, "\t--device <device name or id>: select a specific device to calibrate\n");
fprintf(stderr, "\t--precalib: manually provide the current calibration setting (eg. the values in xorg.conf)\n");
fprintf(stderr, "\t--misclick: set the misclick threshold (0=off, default: %i pixels)\n",
thr_misclick);
fprintf(stderr, "\t--fake: emulate a fake device (for testing purposes)\n");
}
static struct Calib* CalibratorXorgPrint(const char* const device_name0, const XYinfo *axis0, const gboolean verbose0, const int thr_misclick, const int thr_doubleclick)
{
struct Calib* c = (struct Calib*)calloc(1, sizeof(struct Calib));
c->old_axis = *axis0;
c->threshold_misclick = thr_misclick;
c->threshold_doubleclick = thr_doubleclick;
printf("Calibrating standard Xorg driver \"%s\"\n", device_name0);
printf("\tcurrent calibration values: min_x=%d, max_x=%d and min_y=%d, max_y=%d\n",
c->old_axis.x_min, c->old_axis.x_max, c->old_axis.y_min, c->old_axis.y_max);
printf("\tIf these values are estimated wrong, either supply it manually with the --precalib option, or run the 'get_precalib.sh' script to automatically get it (through HAL).\n");
return c;
}
static struct Calib* main_common(int argc, char** argv)
{
gboolean verbose = FALSE;
gboolean list_devices = FALSE;
gboolean fake = FALSE;
gboolean precalib = FALSE;
XYinfo pre_axis = {-1, -1, -1, -1};
const char* pre_device = NULL;
unsigned thr_misclick = 15;
unsigned thr_doubleclick = 7;
/* parse input */
if (argc > 1) {
int i;
for (i=1; i!=argc; i++) {
/* Display help ? */
if (strcmp("-h", argv[i]) == 0 ||
strcmp("--help", argv[i]) == 0) {
fprintf(stderr, "xinput_calibratior, v%s\n\n", "0.0.0");
usage(argv[0], thr_misclick);
exit(0);
} else
/* Verbose output ? */
if (strcmp("-v", argv[i]) == 0 ||
strcmp("--verbose", argv[i]) == 0) {
verbose = TRUE;
} else
/* Just list devices ? */
if (strcmp("--list", argv[i]) == 0) {
list_devices = TRUE;
} else
/* Select specific device ? */
if (strcmp("--device", argv[i]) == 0) {
if (argc > i+1)
pre_device = argv[++i];
else {
fprintf(stderr, "Error: --device needs a device name or id as argument; use --list to list the calibratable input devices.\n\n");
usage(argv[0], thr_misclick);
exit(1);
}
} else
/* Get pre-calibration ? */
if (strcmp("--precalib", argv[i]) == 0) {
precalib = TRUE;
if (argc > i+1)
pre_axis.x_min = atoi(argv[++i]);
if (argc > i+1)
pre_axis.x_max = atoi(argv[++i]);
if (argc > i+1)
pre_axis.y_min = atoi(argv[++i]);
if (argc > i+1)
pre_axis.y_max = atoi(argv[++i]);
} else
/* Get mis-click threshold ? */
if (strcmp("--misclick", argv[i]) == 0) {
if (argc > i+1)
thr_misclick = atoi(argv[++i]);
else {
fprintf(stderr, "Error: --misclick needs a number (the pixel threshold) as argument. Set to 0 to disable mis-click detection.\n\n");
usage(argv[0], thr_misclick);
exit(1);
}
} else
/* Fake calibratable device ? */
if (strcmp("--fake", argv[i]) == 0) {
fake = TRUE;
}
/* unknown option */
else {
fprintf(stderr, "Unknown option: %s\n\n", argv[i]);
usage(argv[0], thr_misclick);
exit(0);
}
}
}
/* Choose the device to calibrate */
XID device_id = (XID) -1;
const char* device_name = NULL;
XYinfo device_axis = {-1, -1, -1, -1};
if (fake) {
/* Fake a calibratable device */
device_name = "Fake_device";
device_axis.x_min=0;
device_axis.x_max=1000;
device_axis.y_min=0;
device_axis.y_max=1000;
if (verbose) {
printf("DEBUG: Faking device: %s\n", device_name);
}
} else {
/* Find the right device */
int nr_found = find_device(pre_device, verbose, list_devices, &device_id, &device_name, &device_axis);
if (list_devices) {
/* printed the list in find_device */
if (nr_found == 0)
printf("No calibratable devices found.\n");
exit(0);
}
if (nr_found == 0) {
if (pre_device == NULL)
fprintf (stderr, "Error: No calibratable devices found.\n");
else
fprintf (stderr, "Error: Device \"%s\" not found; use --list to list the calibratable input devices.\n", pre_device);
exit(1);
} else if (nr_found > 1) {
printf ("Warning: multiple calibratable devices found, calibrating last one (%s)\n\tuse --device to select another one.\n", device_name);
}
if (verbose) {
printf("DEBUG: Selected device: %s\n", device_name);
}
}
/* override min/max XY from command line ? */
if (precalib) {
if (pre_axis.x_min != -1)
device_axis.x_min = pre_axis.x_min;
if (pre_axis.x_max != -1)
device_axis.x_max = pre_axis.x_max;
if (pre_axis.y_min != -1)
device_axis.y_min = pre_axis.y_min;
if (pre_axis.y_max != -1)
device_axis.y_max = pre_axis.y_max;
if (verbose) {
printf("DEBUG: Setting precalibration: %i, %i, %i, %i\n",
device_axis.x_min, device_axis.x_max,
device_axis.y_min, device_axis.y_max);
}
}
/* lastly, presume a standard Xorg driver (evtouch, mutouch, ...) */
return CalibratorXorgPrint(device_name, &device_axis,
verbose, thr_misclick, thr_doubleclick);
}
static gboolean output_xorgconfd(const XYinfo new_axis, int swap_xy, int new_swap_xy)
{
const char* sysfs_name = "!!Name_Of_TouchScreen!!";
/* xorg.conf.d snippet */
printf(" copy the snippet below into '/etc/X11/xorg.conf.d/99-calibration.conf'\n");
printf("Section \"InputClass\"\n");
printf(" Identifier \"calibration\"\n");
printf(" MatchProduct \"%s\"\n", sysfs_name);
printf(" Option \"MinX\" \"%d\"\n", new_axis.x_min);
printf(" Option \"MaxX\" \"%d\"\n", new_axis.x_max);
printf(" Option \"MinY\" \"%d\"\n", new_axis.y_min);
printf(" Option \"MaxY\" \"%d\"\n", new_axis.y_max);
if (swap_xy != 0)
printf(" Option \"SwapXY\" \"%d\" # unless it was already set to 1\n", new_swap_xy);
printf("EndSection\n");
return TRUE;
}
static gboolean finish_data(const XYinfo new_axis, int swap_xy)
{
gboolean success = TRUE;
/* we suppose the previous 'swap_xy' value was 0 */
/* (unfortunately there is no way to verify this (yet)) */
int new_swap_xy = swap_xy;
printf("\n\n--> Making the calibration permanent <--\n");
success &= output_xorgconfd(new_axis, swap_xy, new_swap_xy);
return success;
}
static void
calibration_finished_cb (CalibArea *area,
gpointer user_data)
{
gboolean success;
XYinfo axis;
gboolean swap_xy;
success = calib_area_finish (area, &axis, &swap_xy);
if (success)
success = finish_data (axis, swap_xy);
else
fprintf(stderr, "Error: unable to apply or save configuration values\n");
gtk_main_quit ();
}
int main(int argc, char** argv)
{
struct Calib* calibrator = main_common(argc, argv);
CalibArea *calib_area;
bindtextdomain (GETTEXT_PACKAGE, CINNAMONLOCALEDIR);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
textdomain (GETTEXT_PACKAGE);
g_setenv ("G_MESSAGES_DEBUG", "all", TRUE);
/* GTK setup */
gtk_init(&argc, &argv);
calib_area = calib_area_new (NULL,
0, /* monitor */
-1, /* -1 to ignore device ID */
calibration_finished_cb,
NULL,
&calibrator->old_axis,
calibrator->threshold_doubleclick,
calibrator->threshold_misclick);
gtk_main ();
calib_area_free (calib_area);
free(calibrator);
return 0;
}
|
395 | ./cinnamon-control-center/panels/unused/wacom/calibrator/calibrator.c | /*
* Copyright (c) 2009 Tias Guns
* Copyright (c) 2009 Soren Hauberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdlib.h>
#include "calibrator.h"
#define SWAP(x,y) do { int t; t=(x); x=(y); y=t; } while (0)
/* reset clicks */
void
reset (struct Calib *c)
{
c->num_clicks = 0;
}
/* check whether the coordinates are along the respective axis */
static gboolean
along_axis (struct Calib *c,
int xy,
int x0,
int y0)
{
return ((abs(xy - x0) <= c->threshold_misclick) ||
(abs(xy - y0) <= c->threshold_misclick));
}
/* add a click with the given coordinates */
gboolean
add_click (struct Calib *c,
int x,
int y)
{
/* Double-click detection */
if (c->threshold_doubleclick > 0 && c->num_clicks > 0)
{
int i = c->num_clicks-1;
while (i >= 0)
{
if (abs(x - c->clicked_x[i]) <= c->threshold_doubleclick &&
abs(y - c->clicked_y[i]) <= c->threshold_doubleclick)
{
return FALSE;
}
i--;
}
}
/* Mis-click detection */
if (c->threshold_misclick > 0 && c->num_clicks > 0)
{
gboolean misclick = TRUE;
if (c->num_clicks == 1)
{
/* check that along one axis of first point */
if (along_axis(c, x,c->clicked_x[0],c->clicked_y[0]) ||
along_axis(c, y,c->clicked_x[0],c->clicked_y[0]))
{
misclick = FALSE;
}
}
else if (c->num_clicks == 2)
{
/* check that along other axis of first point than second point */
if ((along_axis(c, y,c->clicked_x[0],c->clicked_y[0]) &&
along_axis(c, c->clicked_x[1],c->clicked_x[0],c->clicked_y[0])) ||
(along_axis(c, x,c->clicked_x[0],c->clicked_y[0]) &&
along_axis(c, c->clicked_y[1],c->clicked_x[0],c->clicked_y[0])))
{
misclick = FALSE;
}
}
else if (c->num_clicks == 3)
{
/* check that along both axis of second and third point */
if ((along_axis(c, x,c->clicked_x[1],c->clicked_y[1]) &&
along_axis(c, y,c->clicked_x[2],c->clicked_y[2])) ||
(along_axis(c, y,c->clicked_x[1],c->clicked_y[1]) &&
along_axis(c, x,c->clicked_x[2],c->clicked_y[2])))
{
misclick = FALSE;
}
}
if (misclick)
{
reset(c);
return FALSE;
}
}
c->clicked_x[c->num_clicks] = x;
c->clicked_y[c->num_clicks] = y;
c->num_clicks++;
return TRUE;
}
/* calculate and apply the calibration */
gboolean
finish (struct Calib *c,
XYinfo *new_axis,
gboolean *swap)
{
gboolean swap_xy;
float scale_x;
float scale_y;
int delta_x;
int delta_y;
XYinfo axis = {-1, -1, -1, -1};
if (c->num_clicks != 4)
return FALSE;
/* Should x and y be swapped? */
swap_xy = (abs (c->clicked_x [UL] - c->clicked_x [UR]) < abs (c->clicked_y [UL] - c->clicked_y [UR]));
if (swap_xy)
{
SWAP(c->clicked_x[LL], c->clicked_x[UR]);
SWAP(c->clicked_y[LL], c->clicked_y[UR]);
}
/* Compute min/max coordinates. */
/* These are scaled using the values of old_axis */
scale_x = (c->old_axis.x_max - c->old_axis.x_min)/(float)c->geometry.width;
axis.x_min = ((((c->clicked_x[UL] + c->clicked_x[LL]) / 2) - c->geometry.x) * scale_x) + c->old_axis.x_min;
axis.x_max = ((((c->clicked_x[UR] + c->clicked_x[LR]) / 2) - c->geometry.x) * scale_x) + c->old_axis.x_min;
scale_y = (c->old_axis.y_max - c->old_axis.y_min)/(float)c->geometry.height;
axis.y_min = ((((c->clicked_y[UL] + c->clicked_y[UR]) / 2) - c->geometry.y) * scale_y) + c->old_axis.y_min;
axis.y_max = ((((c->clicked_y[LL] + c->clicked_y[LR]) / 2) - c->geometry.y) * scale_y) + c->old_axis.y_min;
/* Add/subtract the offset that comes from not having the points in the
* corners (using the same coordinate system they are currently in)
*/
delta_x = (axis.x_max - axis.x_min) / (float)(NUM_BLOCKS - 2);
axis.x_min -= delta_x;
axis.x_max += delta_x;
delta_y = (axis.y_max - axis.y_min) / (float)(NUM_BLOCKS - 2);
axis.y_min -= delta_y;
axis.y_max += delta_y;
/* If x and y has to be swapped we also have to swap the parameters */
if (swap_xy)
{
SWAP(axis.x_min, axis.y_max);
SWAP(axis.y_min, axis.x_max);
}
*new_axis = axis;
*swap = swap_xy;
return TRUE;
}
|
396 | ./cinnamon-control-center/panels/unused/wacom/calibrator/gui_gtk.c | /*
* Copyright (c) 2009 Tias Guns
* Copyright (c) 2009 Soren Hauberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "config.h"
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <glib/gi18n.h>
#include <gdk/gdkx.h>
#include <gtk/gtk.h>
#include <cairo.h>
#include "calibrator.h"
#include "gui_gtk.h"
struct CalibArea
{
struct Calib calibrator;
XYinfo axis;
gboolean swap;
gboolean success;
int device_id;
double X[4], Y[4];
int display_width, display_height;
int time_elapsed;
const char* message;
guint anim_id;
GtkWidget *window;
GdkPixbuf *icon_success;
FinishCallback callback;
gpointer user_data;
};
/* Window parameters */
#define WINDOW_OPACITY 0.9
/* Timeout parameters */
#define TIME_STEP 100 /* in milliseconds */
#define MAX_TIME 15000 /* 5000 = 5 sec */
#define END_TIME 750 /* 750 = 0.75 sec */
/* Clock appereance */
#define CROSS_LINES 47
#define CROSS_CIRCLE 7
#define CROSS_CIRCLE2 27
#define CLOCK_RADIUS 50
#define CLOCK_LINE_WIDTH 10
#define CLOCK_LINE_PADDING 10
/* Text printed on screen */
#define HELP_TEXT_TITLE N_("Screen Calibration")
#define HELP_TEXT_MAIN N_("Please tap the target markers as they appear on screen to calibrate the tablet.")
#define ICON_SUCCESS "emblem-ok-symbolic"
#define ICON_SIZE 300
static void
set_display_size(CalibArea *calib_area,
int width,
int height)
{
int delta_x;
int delta_y;
calib_area->display_width = width;
calib_area->display_height = height;
/* Compute absolute circle centers */
delta_x = calib_area->display_width/NUM_BLOCKS;
delta_y = calib_area->display_height/NUM_BLOCKS;
calib_area->X[UL] = delta_x;
calib_area->Y[UL] = delta_y;
calib_area->X[UR] = calib_area->display_width - delta_x - 1;
calib_area->Y[UR] = delta_y;
calib_area->X[LL] = delta_x;
calib_area->Y[LL] = calib_area->display_height - delta_y - 1;
calib_area->X[LR] = calib_area->display_width - delta_x - 1;
calib_area->Y[LR] = calib_area->display_height - delta_y - 1;
/* reset calibration if already started */
reset(&calib_area->calibrator);
}
static void
resize_display(CalibArea *calib_area)
{
/* check that screensize did not change (if no manually specified geometry) */
GtkAllocation allocation;
gtk_widget_get_allocation(calib_area->window, &allocation);
if (calib_area->display_width != allocation.width ||
calib_area->display_height != allocation.height)
{
set_display_size(calib_area, allocation.width, allocation.height);
}
}
static void
draw_success_icon (CalibArea *area, cairo_t *cr)
{
GtkWidget *widget;
GtkStyleContext *context;
gint icon_width, icon_height;
gdouble x;
gdouble y;
widget = GTK_WIDGET (area->window);
context = gtk_widget_get_style_context (widget);
icon_width = gdk_pixbuf_get_width (area->icon_success);
icon_height = gdk_pixbuf_get_height (area->icon_success);
x = (area->display_width - icon_width) / 2;
y = (area->display_height - icon_height) / 2;
gtk_render_icon (context, cr, area->icon_success, x, y);
}
static void
draw(GtkWidget *widget, cairo_t *cr, gpointer data)
{
CalibArea *calib_area = (CalibArea*)data;
int i;
double x;
double y;
PangoLayout *layout;
PangoRectangle logical_rect;
GtkStyleContext *context;
char *markup;
resize_display(calib_area);
context = gtk_widget_get_style_context (widget);
/* Black background and reset the operator */
cairo_set_operator (cr, CAIRO_OPERATOR_CLEAR);
cairo_paint (cr);
cairo_set_operator (cr, CAIRO_OPERATOR_OVER);
/* If calibration is successful, just draw the tick */
if (calib_area->icon_success) {
draw_success_icon (calib_area, cr);
return;
}
/* Print the help lines */
layout = pango_layout_new (gtk_widget_get_pango_context (widget));
pango_layout_set_alignment (layout, PANGO_ALIGN_CENTER);
markup = g_strdup_printf ("<span foreground=\"white\"><big><b>%s</b></big>\n<big>%s</big></span>",
_(HELP_TEXT_TITLE),
_(HELP_TEXT_MAIN));
pango_layout_set_markup (layout, markup, -1);
g_free (markup);
pango_layout_get_pixel_extents (layout, NULL, &logical_rect);
x = (calib_area->display_width - logical_rect.width) / 2 + logical_rect.x;
y = (calib_area->display_height - logical_rect.height) / 2 - logical_rect.height - 40 + logical_rect.y;
gtk_render_layout (context, cr,
x + logical_rect.x,
y + logical_rect.y,
layout);
g_object_unref (layout);
/* Draw the points */
cairo_set_source_rgb(cr, 1.0, 1.0, 1.0);
i = calib_area->calibrator.num_clicks;
cairo_set_line_width(cr, 1);
cairo_move_to(cr, calib_area->X[i] - CROSS_LINES, calib_area->Y[i] - 0.5);
cairo_rel_line_to(cr, CROSS_LINES*2, 0);
cairo_move_to(cr, calib_area->X[i] - 0.5, calib_area->Y[i] - CROSS_LINES);
cairo_rel_line_to(cr, 0, CROSS_LINES*2);
cairo_stroke(cr);
cairo_set_line_width(cr, 2);
cairo_arc(cr, calib_area->X[i] - 0.5, calib_area->Y[i] - 0.5, CROSS_CIRCLE, 0.0, 2.0 * M_PI);
cairo_stroke(cr);
cairo_set_line_width(cr, 5);
cairo_arc(cr, calib_area->X[i] - 0.5, calib_area->Y[i] - 0.5, CROSS_CIRCLE2, 0.0, 2.0 * M_PI);
cairo_stroke(cr);
/* Draw the clock background */
cairo_arc(cr, calib_area->display_width/2, calib_area->display_height/2, CLOCK_RADIUS/2, 0.0, 2.0 * M_PI);
cairo_set_source_rgb(cr, 0.5, 0.5, 0.5);
cairo_fill_preserve(cr);
cairo_stroke(cr);
cairo_set_line_width(cr, CLOCK_LINE_WIDTH);
cairo_arc(cr, calib_area->display_width/2, calib_area->display_height/2, (CLOCK_RADIUS - CLOCK_LINE_WIDTH - CLOCK_LINE_PADDING)/2,
3/2.0*M_PI, (3/2.0*M_PI) + ((double)calib_area->time_elapsed/(double)MAX_TIME) * 2*M_PI);
cairo_set_source_rgb(cr, 1.0, 1.0, 1.0);
cairo_stroke(cr);
/* Draw the message (if any) */
if (calib_area->message != NULL)
{
cairo_set_source_rgb(cr, 1.0, 1.0, 1.0);
/* Frame the message */
layout = pango_layout_new (gtk_widget_get_pango_context (widget));
pango_layout_set_alignment (layout, PANGO_ALIGN_CENTER);
markup = g_strdup_printf ("<span foreground=\"white\"><big>%s</big></span>",
_(calib_area->message));
pango_layout_set_markup (layout, markup, -1);
g_free (markup);
pango_layout_get_pixel_extents (layout, NULL, &logical_rect);
x = (calib_area->display_width - logical_rect.width) / 2 + logical_rect.x;
y = (calib_area->display_height - logical_rect.height + CLOCK_RADIUS) / 2 + 60 + logical_rect.y;
cairo_set_line_width(cr, 2);
cairo_rectangle(cr, x - 10 - 0.5 , y - 10 - 0.5,
logical_rect.width + 20 + 1, logical_rect.height + 20 + 1);
cairo_stroke (cr);
/* Print the message */
gtk_render_layout (context, cr,
x + logical_rect.x,
y + logical_rect.y,
layout);
g_object_unref (layout);
}
}
static void
draw_message(CalibArea *calib_area,
const char *msg)
{
calib_area->message = msg;
}
static void
redraw(CalibArea *calib_area)
{
GdkWindow *win = gtk_widget_get_window(calib_area->window);
if (win)
{
GdkRectangle rect;
rect.x = 0;
rect.y = 0;
rect.width = calib_area->display_width;
rect.height = calib_area->display_height;
gdk_window_invalidate_rect(win, &rect, FALSE);
}
}
static gboolean
on_delete_event (GtkWidget *widget,
GdkEvent *event,
CalibArea *area)
{
if (area->anim_id > 0) {
g_source_remove (area->anim_id);
area->anim_id = 0;
}
gtk_widget_hide (area->window);
(*area->callback) (area, area->user_data);
return TRUE;
}
static gboolean
draw_success_end_wait_callback (CalibArea *area)
{
on_delete_event (NULL, NULL, area);
return FALSE;
}
static void
set_calibration_status (CalibArea *area)
{
GtkIconTheme *icon_theme;
GtkIconInfo *icon_info;
GdkRGBA white;
icon_theme = gtk_icon_theme_get_default ();
icon_info = gtk_icon_theme_lookup_icon (icon_theme,
ICON_SUCCESS,
ICON_SIZE,
GTK_ICON_LOOKUP_USE_BUILTIN);
if (icon_info == NULL) {
g_warning ("Failed to find icon \"%s\"", ICON_SUCCESS);
goto out;
}
gdk_rgba_parse (&white, "White");
area->icon_success = gtk_icon_info_load_symbolic (icon_info,
&white,
NULL,
NULL,
NULL,
NULL,
NULL);
gtk_icon_info_free (icon_info);
if (!area->icon_success)
g_warning ("Failed to load icon \"%s\"", ICON_SUCCESS);
out:
area->success = finish (&area->calibrator, &area->axis, &area->swap);
if (area->success && area->icon_success) {
redraw(area);
g_timeout_add(END_TIME, (GSourceFunc) draw_success_end_wait_callback, area);
} else {
on_delete_event (NULL, NULL, area);
}
}
static gboolean
on_button_press_event(GtkWidget *widget,
GdkEventButton *event,
CalibArea *area)
{
gboolean success;
if (area->success)
return FALSE;
/* Check matching device ID if a device ID was provided */
if (area->device_id > -1) {
GdkDevice *device;
device = gdk_event_get_source_device ((GdkEvent *) event);
if (device != NULL && gdk_x11_device_get_id (device) != area->device_id)
return FALSE;
}
/* Handle click */
area->time_elapsed = 0;
success = add_click(&area->calibrator, (int)event->x_root, (int)event->y_root);
if (!success && area->calibrator.num_clicks == 0)
draw_message(area, N_("Mis-click detected, restarting..."));
else
draw_message(area, NULL);
/* Are we done yet? */
if (area->calibrator.num_clicks >= 4)
{
set_calibration_status (area);
return FALSE;
}
/* Force a redraw */
redraw(area);
return FALSE;
}
static gboolean
on_key_release_event(GtkWidget *widget,
GdkEventKey *event,
CalibArea *area)
{
if (area->success)
return FALSE;
if (event->type != GDK_KEY_RELEASE)
return FALSE;
if (event->keyval != GDK_KEY_Escape)
return FALSE;
on_delete_event (widget, NULL, area);
return FALSE;
}
static gboolean
on_focus_out_event (GtkWidget *widget,
GdkEvent *event,
CalibArea *area)
{
if (area->success)
return FALSE;
/* If the calibrator window looses focus, simply bail out... */
on_delete_event (widget, NULL, area);
return FALSE;
}
static gboolean
on_timer_signal(CalibArea *area)
{
GdkWindow *win;
area->time_elapsed += TIME_STEP;
if (area->time_elapsed > MAX_TIME)
{
set_calibration_status (area);
return FALSE;
}
/* Update clock */
win = gtk_widget_get_window (area->window);
if (win)
{
GdkRectangle rect;
rect.x = area->display_width/2 - CLOCK_RADIUS - CLOCK_LINE_WIDTH;
rect.y = area->display_height/2 - CLOCK_RADIUS - CLOCK_LINE_WIDTH;
rect.width = 2 * CLOCK_RADIUS + 1 + 2 * CLOCK_LINE_WIDTH;
rect.height = 2 * CLOCK_RADIUS + 1 + 2 * CLOCK_LINE_WIDTH;
gdk_window_invalidate_rect(win, &rect, FALSE);
}
return TRUE;
}
/**
* Creates the windows and other objects required to do calibration
* under GTK. When the window is closed (timed out, calibration finished
* or user cancellation), callback will be called, where you should call
* calib_area_finish().
*/
CalibArea *
calib_area_new (GdkScreen *screen,
int monitor,
int device_id,
FinishCallback callback,
gpointer user_data,
XYinfo *old_axis,
int threshold_doubleclick,
int threshold_misclick)
{
CalibArea *calib_area;
GdkRectangle rect;
GdkWindow *window;
GdkRGBA black;
GdkCursor *cursor;
g_return_val_if_fail (old_axis, NULL);
g_return_val_if_fail (callback, NULL);
g_debug ("Current calibration: %d, %d, %d, %d\n",
old_axis->x_min,
old_axis->y_min,
old_axis->x_max,
old_axis->y_max);
calib_area = g_new0 (CalibArea, 1);
calib_area->callback = callback;
calib_area->user_data = user_data;
calib_area->device_id = device_id;
calib_area->calibrator.old_axis.x_min = old_axis->x_min;
calib_area->calibrator.old_axis.x_max = old_axis->x_max;
calib_area->calibrator.old_axis.y_min = old_axis->y_min;
calib_area->calibrator.old_axis.y_max = old_axis->y_max;
calib_area->calibrator.threshold_doubleclick = threshold_doubleclick;
calib_area->calibrator.threshold_misclick = threshold_misclick;
/* Set up the window */
calib_area->window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_widget_set_app_paintable (GTK_WIDGET (calib_area->window), TRUE);
/* Black background */
gdk_rgba_parse (&black, "rgb(0,0,0)");
gtk_window_set_opacity (GTK_WINDOW (calib_area->window), WINDOW_OPACITY);
gtk_widget_realize (calib_area->window);
window = gtk_widget_get_window (calib_area->window);
gdk_window_set_background_rgba (window, &black);
/* No cursor */
cursor = gdk_cursor_new (GDK_BLANK_CURSOR);
gdk_window_set_cursor (window, cursor);
g_object_unref (cursor);
/* Listen for mouse events */
gtk_widget_add_events (calib_area->window, GDK_KEY_RELEASE_MASK | GDK_BUTTON_PRESS_MASK);
gtk_widget_set_can_focus (calib_area->window, TRUE);
gtk_window_fullscreen (GTK_WINDOW (calib_area->window));
gtk_window_set_keep_above (GTK_WINDOW (calib_area->window), TRUE);
/* Connect callbacks */
g_signal_connect (calib_area->window, "draw",
G_CALLBACK(draw), calib_area);
g_signal_connect (calib_area->window, "button-press-event",
G_CALLBACK(on_button_press_event), calib_area);
g_signal_connect (calib_area->window, "key-release-event",
G_CALLBACK(on_key_release_event), calib_area);
g_signal_connect (calib_area->window, "delete-event",
G_CALLBACK(on_delete_event), calib_area);
g_signal_connect (calib_area->window, "focus-out-event",
G_CALLBACK(on_focus_out_event), calib_area);
/* Setup timer for animation */
calib_area->anim_id = g_timeout_add(TIME_STEP, (GSourceFunc)on_timer_signal, calib_area);
/* Move to correct screen */
if (screen == NULL)
screen = gdk_screen_get_default ();
gdk_screen_get_monitor_geometry (screen, monitor, &rect);
gtk_window_move (GTK_WINDOW (calib_area->window), rect.x, rect.y);
gtk_window_set_default_size (GTK_WINDOW (calib_area->window), rect.width, rect.height);
calib_area->calibrator.geometry.x = rect.x;
calib_area->calibrator.geometry.y = rect.y;
calib_area->calibrator.geometry.width = rect.width;
calib_area->calibrator.geometry.height = rect.height;
gtk_widget_show_all (calib_area->window);
return calib_area;
}
/* Finishes the calibration. Note that CalibArea
* needs to be destroyed with calib_area_free() afterwards */
gboolean
calib_area_finish (CalibArea *area,
XYinfo *new_axis,
gboolean *swap_xy)
{
g_return_val_if_fail (area != NULL, FALSE);
*new_axis = area->axis;
*swap_xy = area->swap;
if (area->success)
g_debug ("Final calibration: %d, %d, %d, %d\n",
new_axis->x_min,
new_axis->y_min,
new_axis->x_max,
new_axis->y_max);
else
g_debug ("Calibration was aborted or timed out");
return area->success;
}
void
calib_area_free (CalibArea *area)
{
g_return_if_fail (area != NULL);
if (area->anim_id > 0) {
g_source_remove (area->anim_id);
area->anim_id = 0;
}
if (area->icon_success)
g_object_unref (area->icon_success);
gtk_widget_destroy (area->window);
g_free (area);
}
|
397 | ./cinnamon-control-center/panels/unused/mouse/cinnamon-mouse-test.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*-
*
* Copyright (C) 2012 Red Hat, Inc.
*
* Written by: Ondrej Holy <[email protected]>,
*
* 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, 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.
*/
#include <config.h>
#include <glib/gi18n.h>
#include <string.h>
#include <gdk/gdk.h>
#include <gdk/gdkx.h>
#include <cinnamon-settings-daemon/gsd-enums.h>
#include <math.h>
#include "cinnamon-mouse-test.h"
#include <sys/types.h>
#include <sys/stat.h>
#define WID(x) (GtkWidget*) gtk_builder_get_object (dialog, x)
/* Click test button sizes. */
#define SHADOW_SIZE (10.0 / 180 * size)
#define SHADOW_SHIFT_Y (-1.0 / 180 * size)
#define SHADOW_OPACITY (0.15 / 180 * size)
#define OUTER_CIRCLE_SIZE (22.0 / 180 * size)
#define ANNULUS_SIZE (6.0 / 180 * size)
#define INNER_CIRCLE_SIZE (52.0 / 180 * size)
static void setup_information_label (GtkWidget *widget);
static void setup_scroll_image (GtkWidget *widget);
enum
{
DOUBLE_CLICK_TEST_OFF,
DOUBLE_CLICK_TEST_MAYBE,
DOUBLE_CLICK_TEST_ON,
DOUBLE_CLICK_TEST_STILL_ON,
DOUBLE_CLICK_TEST_ALMOST_THERE,
DOUBLE_CLICK_TEST_GEGL
};
/* State in testing the double-click speed. Global for a great deal of
* convenience
*/
static gint double_click_state = DOUBLE_CLICK_TEST_OFF;
static gint button_state = 0;
static GSettings *mouse_settings = NULL;
static gint information_label_timeout_id = 0;
static gint button_drawing_area_timeout_id = 0;
static gint scroll_image_timeout_id = 0;
/* Double Click handling */
struct test_data_t
{
gint *timeout_id;
GtkWidget *widget;
};
/* Timeout for the double click test */
static gboolean
test_maybe_timeout (struct test_data_t *data)
{
double_click_state = DOUBLE_CLICK_TEST_OFF;
gtk_widget_queue_draw (data->widget);
*data->timeout_id = 0;
return FALSE;
}
/* Timeout for the information label */
static gboolean
information_label_timeout (struct test_data_t *data)
{
setup_information_label (data->widget);
*data->timeout_id = 0;
return FALSE;
}
/* Timeout for the scroll image */
static gboolean
scroll_image_timeout (struct test_data_t *data)
{
setup_scroll_image (data->widget);
*data->timeout_id = 0;
return FALSE;
}
/* Set information label according global state variables. */
static void
setup_information_label (GtkWidget *widget)
{
static struct test_data_t data;
gchar *message = NULL;
gchar *label_text = NULL;
gboolean double_click;
if (information_label_timeout_id != 0) {
g_source_remove (information_label_timeout_id);
information_label_timeout_id = 0;
}
if (double_click_state == DOUBLE_CLICK_TEST_OFF) {
gtk_label_set_label (GTK_LABEL (widget), _("Try clicking, double clicking, scrolling"));
return;
}
if (double_click_state == DOUBLE_CLICK_TEST_GEGL) {
message = _("Five clicks, GEGL time!"), "</b>";
} else {
double_click = (double_click_state >= DOUBLE_CLICK_TEST_ON);
switch (button_state) {
case 1:
message = (double_click) ? _("Double click, primary button") : _("Single click, primary button");
break;
case 2:
message = (double_click) ? _("Double click, middle button") : _("Single click, middle button");
break;
case 3:
message = (double_click) ? _("Double click, secondary button") : _("Single click, secondary button");
break;
}
}
label_text = g_strconcat ("<b>", message, "</b>", NULL);
gtk_label_set_markup (GTK_LABEL (widget), label_text);
g_free (label_text);
data.widget = widget;
data.timeout_id = &information_label_timeout_id;
information_label_timeout_id = g_timeout_add (2500,
(GSourceFunc) information_label_timeout,
&data);
}
/* Update scroll image according to the global state variables */
static void
setup_scroll_image (GtkWidget *widget)
{
static struct test_data_t data;
char *filename;
if (scroll_image_timeout_id != 0) {
g_source_remove (scroll_image_timeout_id);
scroll_image_timeout_id = 0;
}
if (double_click_state == DOUBLE_CLICK_TEST_GEGL)
filename = CINNAMONCC_UI_DIR "/scroll-test-gegl.svg";
else
filename = CINNAMONCC_UI_DIR "/scroll-test.svg";
gtk_image_set_from_file (GTK_IMAGE (widget), filename);
if (double_click_state != DOUBLE_CLICK_TEST_GEGL)
return;
data.widget = widget;
data.timeout_id = &scroll_image_timeout_id;
scroll_image_timeout_id = g_timeout_add (5000,
(GSourceFunc) scroll_image_timeout,
&data);
}
/* Callback issued when the user clicks the double click testing area. */
static gboolean
button_drawing_area_button_press_event (GtkWidget *widget,
GdkEventButton *event,
GtkBuilder *dialog)
{
gint double_click_time;
static struct test_data_t data;
static guint32 double_click_timestamp = 0;
if (event->type != GDK_BUTTON_PRESS || event->button > 3)
return FALSE;
double_click_time = g_settings_get_int (mouse_settings, "double-click");
if (button_drawing_area_timeout_id != 0) {
g_source_remove (button_drawing_area_timeout_id);
button_drawing_area_timeout_id = 0;
}
/* Ignore fake double click using different buttons. */
if (double_click_state != DOUBLE_CLICK_TEST_OFF && button_state != event->button)
double_click_state = DOUBLE_CLICK_TEST_OFF;
switch (double_click_state) {
case DOUBLE_CLICK_TEST_OFF:
double_click_state = DOUBLE_CLICK_TEST_MAYBE;
data.widget = widget;
data.timeout_id = &button_drawing_area_timeout_id;
button_drawing_area_timeout_id = g_timeout_add (double_click_time, (GSourceFunc) test_maybe_timeout, &data);
break;
case DOUBLE_CLICK_TEST_MAYBE:
case DOUBLE_CLICK_TEST_ON:
case DOUBLE_CLICK_TEST_STILL_ON:
case DOUBLE_CLICK_TEST_ALMOST_THERE:
if (event->time - double_click_timestamp < double_click_time) {
double_click_state++;
data.widget = widget;
data.timeout_id = &button_drawing_area_timeout_id;
button_drawing_area_timeout_id = g_timeout_add (2500, (GSourceFunc) test_maybe_timeout, &data);
} else {
test_maybe_timeout (&data);
}
break;
case DOUBLE_CLICK_TEST_GEGL:
double_click_state = DOUBLE_CLICK_TEST_OFF;
break;
}
double_click_timestamp = event->time;
gtk_widget_queue_draw (widget);
button_state = event->button;
setup_information_label (WID ("information_label"));
setup_scroll_image (WID ("image"));
return TRUE;
}
static gboolean
button_drawing_area_draw_event (GtkWidget *widget,
cairo_t *cr,
GtkBuilder *dialog)
{
gdouble center_x, center_y, size;
GdkRGBA inner_color, outer_color;
cairo_pattern_t *pattern;
size = MAX (MIN (gtk_widget_get_allocated_width (widget), gtk_widget_get_allocated_height (widget)), 1);
center_x = gtk_widget_get_allocated_width (widget) / 2.0;
center_y = gtk_widget_get_allocated_height (widget) / 2.0;
switch (double_click_state) {
case DOUBLE_CLICK_TEST_ON:
case DOUBLE_CLICK_TEST_STILL_ON:
case DOUBLE_CLICK_TEST_ALMOST_THERE:
case DOUBLE_CLICK_TEST_GEGL:
gdk_rgba_parse (&outer_color, "#729fcf");
gdk_rgba_parse (&inner_color, "#729fcf");
break;
case DOUBLE_CLICK_TEST_MAYBE:
gdk_rgba_parse (&outer_color, "#729fcf");
gdk_rgba_parse (&inner_color, "#ffffff");
break;
case DOUBLE_CLICK_TEST_OFF:
gdk_rgba_parse (&outer_color, "#ffffff");
gdk_rgba_parse (&inner_color, "#ffffff");
break;
}
/* Draw shadow. */
cairo_rectangle (cr, center_x - size / 2, center_y - size / 2, size, size);
pattern = cairo_pattern_create_radial (center_x, center_y, 0, center_x, center_y, size);
cairo_pattern_add_color_stop_rgba (pattern, 0.5 - SHADOW_SIZE / size, 0, 0, 0, SHADOW_OPACITY);
cairo_pattern_add_color_stop_rgba (pattern, 0.5, 0, 0, 0, 0);
cairo_set_source (cr, pattern);
cairo_fill (cr);
/* Draw outer circle. */
cairo_set_line_width (cr, OUTER_CIRCLE_SIZE);
cairo_arc (cr, center_x, center_y + SHADOW_SHIFT_Y,
INNER_CIRCLE_SIZE + ANNULUS_SIZE + OUTER_CIRCLE_SIZE / 2,
0, 2 * G_PI);
gdk_cairo_set_source_rgba (cr, &outer_color);
cairo_stroke (cr);
/* Draw inner circle. */
cairo_set_line_width (cr, 0);
cairo_arc (cr, center_x, center_y + SHADOW_SHIFT_Y,
INNER_CIRCLE_SIZE,
0, 2 * G_PI);
gdk_cairo_set_source_rgba (cr, &inner_color);
cairo_fill (cr);
return FALSE;
}
/* Set up the property editors in the dialog. */
static void
setup_dialog (GtkBuilder *dialog)
{
GtkAdjustment *adjustment;
GdkRGBA color;
g_signal_connect (WID ("button_drawing_area"), "button_press_event",
G_CALLBACK (button_drawing_area_button_press_event),
dialog);
g_signal_connect (WID ("button_drawing_area"), "draw",
G_CALLBACK (button_drawing_area_draw_event),
dialog);
adjustment = GTK_ADJUSTMENT (WID ("scrolled_window_adjustment"));
gtk_adjustment_set_value (adjustment,
gtk_adjustment_get_upper (adjustment));
gdk_rgba_parse (&color, "#565854");
gtk_widget_override_background_color (WID ("viewport"), GTK_STATE_FLAG_NORMAL, &color);
gtk_widget_override_background_color (WID ("button_drawing_area"), GTK_STATE_FLAG_NORMAL, &color);
}
GtkWidget *
gnome_mouse_test_init (GtkBuilder *dialog)
{
mouse_settings = g_settings_new ("org.cinnamon.settings-daemon.peripherals.mouse");
setup_dialog (dialog);
return WID ("mouse_test_window");
}
void
gnome_mouse_test_dispose (GtkWidget *widget)
{
if (mouse_settings != NULL) {
g_object_unref (mouse_settings);
mouse_settings = NULL;
}
if (information_label_timeout_id != 0) {
g_source_remove (information_label_timeout_id);
information_label_timeout_id = 0;
}
if (scroll_image_timeout_id != 0) {
g_source_remove (scroll_image_timeout_id);
scroll_image_timeout_id = 0;
}
if (button_drawing_area_timeout_id != 0) {
g_source_remove (button_drawing_area_timeout_id);
button_drawing_area_timeout_id = 0;
}
}
|
398 | ./cinnamon-control-center/panels/unused/mouse/cinnamon-mouse-properties.c | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*-
*
* Copyright (C) 2001, 2012 Red Hat, Inc.
* Copyright (C) 2001 Ximian, Inc.
*
* Written by: Jonathon Blandford <[email protected]>,
* Bradford Hovinen <[email protected]>,
* Ondrej Holy <[email protected]>,
*
* 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, 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.
*/
#include <config.h>
#include <glib/gi18n.h>
#include <string.h>
#include <gdk/gdk.h>
#include <gdk/gdkx.h>
#include <cinnamon-settings-daemon/gsd-enums.h>
#include <math.h>
#include "cinnamon-mouse-properties.h"
#include "gsd-input-helper.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <X11/Xatom.h>
#include <X11/extensions/XInput.h>
#define WID(x) (GtkWidget*) gtk_builder_get_object (dialog, x)
static GSettings *mouse_settings = NULL;
static GSettings *touchpad_settings = NULL;
static GdkDeviceManager *device_manager = NULL;
static guint device_added_id = 0;
static guint device_removed_id = 0;
static gboolean changing_scroll = FALSE;
static void
orientation_radio_button_release_event (GtkWidget *widget,
GdkEventButton *event)
{
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (widget), TRUE);
}
static void
setup_scrollmethod_radios (GtkBuilder *dialog)
{
GsdTouchpadScrollMethod method;
gboolean active;
method = g_settings_get_enum (touchpad_settings, "scroll-method");
active = (method == GSD_TOUCHPAD_SCROLL_METHOD_TWO_FINGER_SCROLLING);
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (WID ("two_finger_scroll_toggle")), active);
}
static void
scrollmethod_changed_event (GtkToggleButton *button, GtkBuilder *dialog)
{
GsdTouchpadScrollMethod method;
if (changing_scroll)
return;
if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (WID ("two_finger_scroll_toggle"))))
method = GSD_TOUCHPAD_SCROLL_METHOD_TWO_FINGER_SCROLLING;
else
method = GSD_TOUCHPAD_SCROLL_METHOD_EDGE_SCROLLING;
g_settings_set_enum (touchpad_settings, "scroll-method", method);
}
static void
synaptics_check_capabilities (GtkBuilder *dialog)
{
int numdevices, i;
XDeviceInfo *devicelist;
Atom realtype, prop;
int realformat;
unsigned long nitems, bytes_after;
unsigned char *data;
prop = XInternAtom (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), "Synaptics Capabilities", True);
if (!prop)
return;
devicelist = XListInputDevices (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), &numdevices);
for (i = 0; i < numdevices; i++) {
if (devicelist[i].use != IsXExtensionPointer)
continue;
gdk_error_trap_push ();
XDevice *device = XOpenDevice (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()),
devicelist[i].id);
if (gdk_error_trap_pop ())
continue;
gdk_error_trap_push ();
if ((XGetDeviceProperty (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), device, prop, 0, 2, False,
XA_INTEGER, &realtype, &realformat, &nitems,
&bytes_after, &data) == Success) && (realtype != None)) {
/* Property data is booleans for has_left, has_middle, has_right, has_double, has_triple.
* Newer drivers (X.org/kerrnel) will also include has_pressure and has_width. */
if (!data[0]) {
gtk_widget_set_sensitive (WID ("tap_to_click_toggle"), FALSE);
}
/* Disable two finger scrolling unless the hardware supports
* double touch */
if (!(data[3]))
gtk_widget_set_sensitive (WID ("two_finger_scroll_toggle"), FALSE);
XFree (data);
}
gdk_error_trap_pop_ignored ();
XCloseDevice (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), device);
}
XFreeDeviceList (devicelist);
}
static void
pointer_speed_scale_event (GtkRange *scale, GtkBuilder *dialog)
{
gdouble value;
GSettings *settings;
GtkAdjustment *adjustment;
if (GTK_WIDGET (scale) == WID ("pointer_speed_scale"))
settings = mouse_settings;
else
settings = touchpad_settings;
g_settings_set_double (settings, "motion-acceleration", gtk_range_get_value (scale));
adjustment = gtk_range_get_adjustment (scale);
value = gtk_adjustment_get_upper (adjustment) - gtk_range_get_value (scale) + 1;
g_settings_set_int (settings, "motion-threshold", value);
}
/* Set up the property editors in the dialog. */
static void
setup_dialog (GtkBuilder *dialog)
{
GtkRadioButton *radio;
gboolean touchpad_present, mouse_present;
/* Orientation radio buttons */
radio = GTK_RADIO_BUTTON (WID ("left_handed_radio"));
g_settings_bind (mouse_settings, "left-handed", radio, "active", G_SETTINGS_BIND_DEFAULT);
/* explicitly connect to button-release so that you can change orientation with either button */
g_signal_connect (WID ("right_handed_radio"), "button_release_event",
G_CALLBACK (orientation_radio_button_release_event), NULL);
g_signal_connect (WID ("left_handed_radio"), "button_release_event",
G_CALLBACK (orientation_radio_button_release_event), NULL);
/* Double-click time */
g_settings_bind (mouse_settings, "double-click",
gtk_range_get_adjustment (GTK_RANGE (WID ("double_click_scale"))), "value",
G_SETTINGS_BIND_DEFAULT);
/* Mouse section */
mouse_present = mouse_is_present ();
gtk_widget_set_visible (WID ("mouse_vbox"), mouse_present);
g_signal_connect (WID ("pointer_speed_scale"), "value-changed",
G_CALLBACK (pointer_speed_scale_event), dialog);
/* Trackpad page */
touchpad_present = touchpad_is_present ();
gtk_widget_set_visible (WID ("touchpad_vbox"), touchpad_present);
g_settings_bind (touchpad_settings, "touchpad-enabled",
WID ("touchpad_enabled_switch"), "active",
G_SETTINGS_BIND_DEFAULT);
g_settings_bind (touchpad_settings, "touchpad-enabled",
WID ("touchpad_options_box"), "sensitive",
G_SETTINGS_BIND_GET);
g_settings_bind (touchpad_settings, "disable-while-typing",
WID ("disable_w_typing_toggle"), "active",
G_SETTINGS_BIND_DEFAULT);
g_settings_bind (touchpad_settings, "tap-to-click",
WID ("tap_to_click_toggle"), "active",
G_SETTINGS_BIND_DEFAULT);
g_settings_bind (touchpad_settings, "natural-scroll",
WID ("natural_scroll_toggle"), "active",
G_SETTINGS_BIND_DEFAULT);
g_signal_connect (WID ("touchpad_pointer_speed_scale"), "value-changed",
G_CALLBACK (pointer_speed_scale_event), dialog);
if (touchpad_present) {
synaptics_check_capabilities (dialog);
setup_scrollmethod_radios (dialog);
}
g_signal_connect (WID ("two_finger_scroll_toggle"), "toggled",
G_CALLBACK (scrollmethod_changed_event), dialog);
}
/* Construct the dialog */
static void
create_dialog (GtkBuilder *dialog)
{
GtkSizeGroup *size_group;
size_group = gtk_size_group_new (GTK_SIZE_GROUP_HORIZONTAL);
gtk_size_group_add_widget (size_group, WID ("primary_button_label"));
gtk_size_group_add_widget (size_group, WID ("pointer_speed_label"));
gtk_size_group_add_widget (size_group, WID ("double_click_label"));
gtk_size_group_add_widget (size_group, WID ("touchpad_pointer_speed_label"));
size_group = gtk_size_group_new (GTK_SIZE_GROUP_HORIZONTAL);
gtk_size_group_add_widget (size_group, WID ("pointer_speed_fast_label"));
gtk_size_group_add_widget (size_group, WID ("double_click_fast_label"));
gtk_size_group_add_widget (size_group, WID ("touchpad_pointer_speed_fast_label"));
size_group = gtk_size_group_new (GTK_SIZE_GROUP_HORIZONTAL);
gtk_size_group_add_widget (size_group, WID ("pointer_speed_slow_label"));
gtk_size_group_add_widget (size_group, WID ("double_click_slow_label"));
gtk_size_group_add_widget (size_group, WID ("touchpad_pointer_speed_slow_label"));
gtk_widget_set_direction (WID ("primary_button_box"), GTK_TEXT_DIR_LTR);
}
/* Callback issued when a button is clicked on the dialog */
static void
device_changed (GdkDeviceManager *device_manager,
GdkDevice *device,
GtkBuilder *dialog)
{
gboolean present;
present = touchpad_is_present ();
gtk_widget_set_visible (WID ("touchpad_vbox"), present);
if (present) {
changing_scroll = TRUE;
synaptics_check_capabilities (dialog);
setup_scrollmethod_radios (dialog);
changing_scroll = FALSE;
}
present = mouse_is_present ();
gtk_widget_set_visible (WID ("mouse_vbox"), present);
}
GtkWidget *
gnome_mouse_properties_init (GtkBuilder *dialog)
{
mouse_settings = g_settings_new ("org.cinnamon.settings-daemon.peripherals.mouse");
touchpad_settings = g_settings_new ("org.cinnamon.settings-daemon.peripherals.touchpad");
device_manager = gdk_display_get_device_manager (gdk_display_get_default ());
device_added_id = g_signal_connect (device_manager, "device-added",
G_CALLBACK (device_changed), dialog);
device_removed_id = g_signal_connect (device_manager, "device-removed",
G_CALLBACK (device_changed), dialog);
create_dialog (dialog);
setup_dialog (dialog);
return WID ("mouse_properties_dialog");
}
void
gnome_mouse_properties_dispose (GtkWidget *widget)
{
if (mouse_settings != NULL) {
g_object_unref (mouse_settings);
mouse_settings = NULL;
}
if (touchpad_settings != NULL) {
g_object_unref (touchpad_settings);
touchpad_settings = NULL;
}
if (device_manager != NULL) {
g_signal_handler_disconnect (device_manager, device_added_id);
device_added_id = 0;
g_signal_handler_disconnect (device_manager, device_removed_id);
device_removed_id = 0;
device_manager = NULL;
}
}
|
399 | ./cinnamon-control-center/panels/unused/mouse/mouse-module.c | /*
* Copyright (C) 2010 Intel, Inc
*
* 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.
*
* Author: Thomas Wood <[email protected]>
*
*/
#include <config.h>
#include "cc-mouse-panel.h"
#include <glib/gi18n-lib.h>
void
g_io_module_load (GIOModule *module)
{
bindtextdomain (GETTEXT_PACKAGE, CINNAMONLOCALEDIR);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
/* register the panel */
cc_mouse_panel_register (module);
}
void
g_io_module_unload (GIOModule *module)
{
}
|
400 | ./cinnamon-control-center/panels/unused/mouse/cc-mouse-panel.c | /*
* Copyright (C) 2010 Intel, Inc
* Copyright (C) 2012 Red Hat, Inc.
*
* 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.
*
* Authors: Thomas Wood <[email protected]>
* Rodrigo Moya <[email protected]>
* Ondrej Holy <[email protected]>
*
*/
#include "cc-mouse-panel.h"
#include "cinnamon-mouse-properties.h"
#include "cinnamon-mouse-test.h"
#include <gtk/gtk.h>
#include <glib/gi18n.h>
CC_PANEL_REGISTER (CcMousePanel, cc_mouse_panel)
#define MOUSE_PANEL_PRIVATE(o) \
(G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_MOUSE_PANEL, CcMousePanelPrivate))
#define WID(x) (GtkWidget*) gtk_builder_get_object (dialog, x)
struct _CcMousePanelPrivate
{
GtkBuilder *builder;
GtkWidget *widget;
GtkWidget *prefs_widget;
GtkWidget *test_widget;
GtkWidget *shell_header;
};
enum {
CC_MOUSE_PAGE_PREFS,
CC_MOUSE_PAGE_TEST
};
static void
cc_mouse_panel_get_property (GObject *object,
guint property_id,
GValue *value,
GParamSpec *pspec)
{
switch (property_id)
{
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}
}
static void
cc_mouse_panel_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec)
{
switch (property_id)
{
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}
}
static void
cc_mouse_panel_dispose (GObject *object)
{
CcMousePanelPrivate *priv = CC_MOUSE_PANEL (object)->priv;
g_clear_object (&priv->shell_header);
if (priv->prefs_widget)
{
gnome_mouse_properties_dispose (priv->prefs_widget);
priv->prefs_widget = NULL;
}
if (priv->test_widget)
{
gnome_mouse_test_dispose (priv->test_widget);
priv->test_widget = NULL;
}
if (priv->builder)
{
g_object_unref (priv->builder);
priv->builder = NULL;
}
G_OBJECT_CLASS (cc_mouse_panel_parent_class)->dispose (object);
}
static const char *
cc_mouse_panel_get_help_uri (CcPanel *panel)
{
if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity"))
return "help:ubuntu-help/mouse";
else
return "help:gnome-help/mouse";
}
static void
cc_mouse_panel_class_init (CcMousePanelClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
CcPanelClass *panel_class = CC_PANEL_CLASS (klass);
g_type_class_add_private (klass, sizeof (CcMousePanelPrivate));
panel_class->get_help_uri = cc_mouse_panel_get_help_uri;
object_class->get_property = cc_mouse_panel_get_property;
object_class->set_property = cc_mouse_panel_set_property;
object_class->dispose = cc_mouse_panel_dispose;
}
/* Toggle between mouse panel properties and testing area. */
static void
shell_test_button_toggle_event (GtkToggleButton *button, CcMousePanel *panel)
{
GtkNotebook *notebook = GTK_NOTEBOOK (panel->priv->widget);
gint page_num;
if (gtk_toggle_button_get_active (button)) {
GtkBuilder *dialog = panel->priv->builder;
GtkAdjustment *adjustment;
page_num = CC_MOUSE_PAGE_TEST;
adjustment = GTK_ADJUSTMENT (WID ("scrolled_window_adjustment"));
gtk_adjustment_set_value (adjustment,
gtk_adjustment_get_upper (adjustment));
} else {
page_num = CC_MOUSE_PAGE_PREFS;
}
gtk_notebook_set_current_page (notebook, page_num);
}
/* Add test area toggle to shell header. */
static gboolean
add_shell_test_button_cb (gpointer user_data)
{
CcMousePanel *panel = CC_MOUSE_PANEL (user_data);
GtkWidget *box, *button;
box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 2);
button = gtk_toggle_button_new_with_mnemonic (_("_Test Your Settings"));
gtk_box_pack_start (GTK_BOX (box), button, FALSE, FALSE, 0);
gtk_widget_set_visible (button, TRUE);
cc_shell_embed_widget_in_header (cc_panel_get_shell (CC_PANEL (panel)), box);
gtk_widget_set_visible (box, TRUE);
panel->priv->shell_header = g_object_ref (box);
g_signal_connect (GTK_BUTTON (button), "toggled",
G_CALLBACK (shell_test_button_toggle_event),
panel);
return FALSE;
}
static void
cc_mouse_panel_init (CcMousePanel *self)
{
CcMousePanelPrivate *priv;
GtkBuilder *dialog;
GError *error = NULL;
priv = self->priv = MOUSE_PANEL_PRIVATE (self);
priv->builder = gtk_builder_new ();
gtk_builder_add_from_file (priv->builder,
CINNAMONCC_UI_DIR "/cinnamon-mouse-properties.ui",
&error);
if (error != NULL)
{
g_warning ("Error loading UI file: %s", error->message);
return;
}
gtk_builder_add_from_file (priv->builder,
CINNAMONCC_UI_DIR "/cinnamon-mouse-test.ui",
&error);
if (error != NULL)
{
g_warning ("Error loading UI file: %s", error->message);
return;
}
dialog = priv->builder;
priv->prefs_widget = gnome_mouse_properties_init (priv->builder);
priv->test_widget = gnome_mouse_test_init (priv->builder);
priv->widget = gtk_notebook_new ();
gtk_notebook_set_show_tabs (GTK_NOTEBOOK (priv->widget), FALSE);
gtk_notebook_set_show_border (GTK_NOTEBOOK (priv->widget), FALSE);
gtk_widget_reparent (WID ("prefs_widget"), priv->widget);
gtk_widget_reparent (WID ("test_widget"), priv->widget);
gtk_container_add (GTK_CONTAINER (self), priv->widget);
gtk_widget_show (priv->widget);
g_idle_add (add_shell_test_button_cb, self);
}
void
cc_mouse_panel_register (GIOModule *module)
{
cc_mouse_panel_register_type (G_TYPE_MODULE (module));
g_io_extension_point_implement (CC_SHELL_PANEL_EXTENSION_POINT,
CC_TYPE_MOUSE_PANEL,
"mouse", 0);
}
|