libunity-7.1.4+15.10.20151002/ 0000755 0000153 0000161 00000000000 12603351405 015701 5 ustar pbuser pbgroup 0000000 0000000 libunity-7.1.4+15.10.20151002/Makefile.am 0000644 0000153 0000161 00000000676 12603350222 017742 0 ustar pbuser pbgroup 0000000 0000000 SUBDIRS = \
data \
protocol \
src \
extras \
loader \
bindings \
tools \
doc \
examples \
test \
vapi \
po
pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = unity.pc unity-protocol-private.pc unity-extras.pc
EXTRA_DIST = \
autogen.sh \
unity.pc.in \
unity-extras.pc.in \
unity-protocol-private.pc.in
DISTCLEANFILES =
DISTCHECK_CONFIGURE_FLAGS = --enable-introspection
include $(top_srcdir)/Makefile.am.coverage
libunity-7.1.4+15.10.20151002/protocol/ 0000755 0000153 0000161 00000000000 12603351405 017542 5 ustar pbuser pbgroup 0000000 0000000 libunity-7.1.4+15.10.20151002/protocol/Makefile.am 0000644 0000153 0000161 00000004272 12603350222 021577 0 ustar pbuser pbgroup 0000000 0000000 NULL =
BUILT_SOURCES =
CLEANFILES =
EXTRA_DIST =
EXTRA_FLAGS = -g
protolibdir = $(libdir)/libunity
protolib_LTLIBRARIES = \
libunity-protocol-private.la
##
# Headers, vapi, and gir
##
unityincludedir = $(includedir)/unity/unity
nodist_unityinclude_HEADERS = unity-protocol.h
unityvapidir = $(datadir)/vala/vapi
nodist_unityvapi_DATA = \
unity-protocol.vapi \
$(NULL)
if !ENABLE_C_WARNINGS
EXTRA_FLAGS += -w
endif
if ENABLE_TRACE_LOG
EXTRA_FLAGS += -DENABLE_UNITY_TRACE_LOG
endif
#libunity-protocol
libunity_protocol_private_la_CPPFLAGS = \
-DG_LOG_DOMAIN=\"libunity-protocol-private\" \
-DPKGDATADIR=\"$(PKGDATADIR)\" \
-DGETTEXT_PACKAGE=\"$(GETTEXT_PACKAGE)\" \
-DDATADIR=\"$(DATADIR)\" \
-I$(srcdir) \
$(EXTRA_FLAGS) \
$(LIBUNITY_CFLAGS) \
$(COVERAGE_CFLAGS) \
$(NULL)
libunity_protocol_private_la_LIBADD = \
$(LIBUNITY_LIBS) -lm
libunity_protocol_private_la_LDFLAGS = \
$(LIBPROTOCOL_LT_LDFLAGS) \
$(COVERAGE_LDFLAGS) \
$(NULL)
libunity_protocol_private_la_VALAFLAGS = \
-C \
-H unity-protocol.h -d . \
--library unity-protocol \
--vapi unity-protocol.vapi \
--thread \
--vapidir $(top_srcdir)/vapi \
--pkg config \
$(LIBUNITY_PACKAGES) \
$(MAINTAINER_VALAFLAGS)
nodist_libunity_protocol_private_la_SOURCES = \
$(libunity_protocol_private_la_VALASOURCES:.vala=.c) \
$(NULL)
libunity_protocol_private_la_VALASOURCES = \
protocol-icon.vala \
protocol-scope-interface.vala \
protocol-previews.vala \
protocol-scope-discovery.vala \
protocol-preview-player.vala \
unity-scope-proxy.vala \
unity-scope-proxy-remote.vala \
$(NULL)
libunity_protocol_private_la_GENERATED = \
unity-protocol.h \
unity-protocol.vapi \
$(NULL)
$(libunity_protocol_private_la_GENERATED): libunity_protocol_private_la_vala.stamp
libunity_protocol_private_la_vala.stamp: $(libunity_protocol_private_la_VALASOURCES)
$(AM_V_GEN) $(VALAC) $(libunity_protocol_private_la_VALAFLAGS) $^
@touch $@
BUILT_SOURCES += libunity_protocol_private_la_vala.stamp
EXTRA_DIST += \
$(libunity_protocol_private_la_VALASOURCES) \
$(NULL)
CLEANFILES += \
*.stamp \
$(libunity_protocol_private_la_GENERATED) \
$(libunity_protocol_private_la_VALASOURCES:.vala=.c) \
$(NULL)
libunity-7.1.4+15.10.20151002/protocol/protocol-icon.vala 0000644 0000153 0000161 00000012100 12603350222 023164 0 ustar pbuser pbgroup 0000000 0000000 /*
* Copyright (C) 2012 Canonical, Ltd.
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* version 3.0 as published by the Free Software Foundation.
*
* 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 version 3.0 for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see
* .
*
* Authored by Michal Hruby
*
*/
namespace Unity.Protocol {
public enum CategoryType
{
NONE,
APPLICATION,
BOOK,
MUSIC,
MOVIE,
GAMES,
ELECTRONICS,
COMPUTERS,
OFFICE,
HOME,
GARDEN,
PETS,
TOYS,
CHILDREN,
BABY,
CLOTHES,
SHOES,
WATCHES,
SPORTS,
OUTDOORS,
GROCERY,
HEALTH,
BEAUTY,
DIY,
TOOLS,
CAR,
N_CATEGORIES
}
public class AnnotatedIcon : Object, GLib.Icon
{
public Icon icon { get; set; }
public string ribbon { get; set; }
public CategoryType category { get; set; default = CategoryType.NONE; }
public bool use_small_icon { get; set; }
public uint32 colorize_value { get; set; }
public AnnotatedIcon (Icon? base_icon)
{
Object (icon: base_icon);
}
construct
{
_hints = new HashTable (str_hash, str_equal);
}
private HashTable _hints;
public void add_hint (string name, Variant value)
{
_hints[name] = value;
}
public unowned Variant? get_hint (string name)
{
return _hints[name];
}
public void set_colorize_rgba (double r, double g, double b, double a)
{
const uint MAX_VAL = 255;
const double MAX_VAL_DBL = 255.0;
uint32 color = 0;
color += uint.min (MAX_VAL, (uint) Math.round (r * MAX_VAL_DBL));
color <<= 8;
color += uint.min (MAX_VAL, (uint) Math.round (g * MAX_VAL_DBL));
color <<= 8;
color += uint.min (MAX_VAL, (uint) Math.round (b * MAX_VAL_DBL));
color <<= 8;
color += uint.min (MAX_VAL, (uint) Math.round (a * MAX_VAL_DBL));
colorize_value = color;
}
private bool equal (Icon? icon2)
{
return (this.to_string () == icon2.to_string ());
}
private uint hash ()
{
return str_hash (to_string ());
}
/* FIXME: hack, vala thinks this is instance method, while it actually
* is not one - it's suppossed to create a new instance, kind of
* `static virtual` (access "this" and the process will die a swift,
* yet painful death with the famous last words of SIGSEGV) */
[CCode (instance_pos = -0.9)]
private Icon? from_tokens (string[] tokens, int version) throws Error
{
if (tokens.length != 1)
{
throw new IOError.INVALID_ARGUMENT (
"Unable to construct AnnotatedIcon: wrong number of tokens");
}
var dict = Variant.parse (null, tokens[0]);
var icon = Object.new (typeof (AnnotatedIcon)) as AnnotatedIcon;
icon._hints = (HashTable) dict;
unowned Variant icon_variant = icon.get_hint ("base-icon");
if (icon_variant != null && icon_variant.get_string () != null)
{
icon.icon = Icon.new_for_string (icon_variant.get_string ());
icon._hints.remove ("base-icon");
}
unowned Variant category_variant = icon.get_hint ("category");
if (category_variant != null)
{
icon.category = (CategoryType) category_variant.get_uint32 ();
icon._hints.remove ("category");
}
unowned Variant ribbon_variant = icon.get_hint ("ribbon");
if (ribbon_variant != null && ribbon_variant.get_string () != null)
{
icon.ribbon = ribbon_variant.get_string ();
icon._hints.remove ("ribbon");
}
unowned Variant small_icon_variant = icon.get_hint ("use-small-icon");
if (small_icon_variant != null)
{
icon.use_small_icon = small_icon_variant.get_boolean ();
icon._hints.remove ("use-small-icon");
}
unowned Variant colorize_variant = icon.get_hint ("colorize-value");
if (colorize_variant != null)
{
icon.colorize_value = colorize_variant.get_uint32 ();
icon._hints.remove ("colorize-value");
}
return icon;
}
private bool to_tokens (GenericArray tokens, out int version)
requires (icon != null)
{
version = 0;
var base_icon_string = icon.to_string ();
add_hint ("base-icon", base_icon_string);
if (category != CategoryType.NONE && category < CategoryType.N_CATEGORIES)
add_hint ("category", new Variant.uint32 (category));
if (ribbon != null && ribbon[0] != '\0')
add_hint ("ribbon", ribbon);
if (use_small_icon)
add_hint ("use-small-icon", new Variant.boolean (true));
if (colorize_value > 0)
add_hint ("colorize-value", new Variant.uint32 (colorize_value));
Variant dict = _hints;
tokens.add (dict.print (true));
return true;
}
/* Added to GIcon interface in 2.37 */
private Variant serialize ()
{
Variant? ret = null;
return ret;
}
}
} /* namespace unity */
libunity-7.1.4+15.10.20151002/protocol/protocol-preview-player.vala 0000644 0000153 0000161 00000007047 12603350222 025225 0 ustar pbuser pbgroup 0000000 0000000 /*
* Copyright (C) 2012 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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, see .
*
* Authored by Pawel Stolowski
*/
namespace Unity.Protocol
{
[DBus (name = "com.canonical.Unity.Lens.Music.PreviewPlayer")]
internal interface PreviewPlayerService: GLib.Object
{
public signal void progress (string uri, uint32 state, double progress);
public abstract async void play (string uri) throws Error;
public abstract async void pause () throws Error;
public abstract async void pause_resume () throws Error;
public abstract async void resume () throws Error;
public abstract async void stop () throws Error;
public abstract async void close () throws Error;
public abstract async HashTable video_properties (string uri) throws Error;
}
/**
* Client class for preview player DBus interface (com.canonical.Unity.Lens.Music.PreviewPlayer).
*/
public class PreviewPlayer: GLib.Object
{
static const string PREVIEW_PLAYER_DBUS_NAME = "com.canonical.Unity.Lens.Music.PreviewPlayer";
static const string PREVIEW_PLAYER_DBUS_PATH = "/com/canonical/Unity/Lens/Music/PreviewPlayer";
/**
* Reports progress of playback for given track uri.
*/
public signal void progress (string uri, PlayState state, double progress);
private async void connect_to () throws Error
{
_preview_player_service = yield Bus.get_proxy (BusType.SESSION, PREVIEW_PLAYER_DBUS_NAME, PREVIEW_PLAYER_DBUS_PATH);
_preview_player_service.progress.connect (on_progress_signal);
}
public async void play (string uri) throws Error
{
if (_preview_player_service == null)
{
yield connect_to ();
}
yield _preview_player_service.play (uri);
}
public async void pause () throws Error
{
if (_preview_player_service == null)
{
yield connect_to ();
}
yield _preview_player_service.pause ();
}
public async void pause_resume () throws Error
{
if (_preview_player_service == null)
{
yield connect_to ();
}
yield _preview_player_service.pause_resume ();
}
public async void resume () throws Error
{
if (_preview_player_service == null)
{
yield connect_to ();
}
yield _preview_player_service.resume ();
}
public async void stop () throws Error
{
if (_preview_player_service == null)
{
yield connect_to ();
}
yield _preview_player_service.stop ();
}
public async void close () throws Error
{
if (_preview_player_service == null)
{
yield connect_to ();
}
yield _preview_player_service.close ();
}
public async HashTable video_properties (string uri) throws Error
{
if (_preview_player_service == null)
{
yield connect_to ();
}
var props = yield _preview_player_service.video_properties (uri);
return props;
}
internal void on_progress_signal (string uri, uint32 state, double progress_value)
{
progress (uri, (PlayState) state, progress_value);
}
private PreviewPlayerService _preview_player_service;
}
}
libunity-7.1.4+15.10.20151002/protocol/protocol-scope-discovery.vala 0000644 0000153 0000161 00000074151 12603350222 025370 0 ustar pbuser pbgroup 0000000 0000000 /*
* Copyright (C) 2012-2013 Canonical, Ltd.
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* version 3.0 as published by the Free Software Foundation.
*
* 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 version 3.0 for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see
* .
*
* Authored by Pawel Stolowski
*
*/
namespace Unity.Protocol
{
private static const string SCOPES_DIR = "unity/scopes";
errordomain ParseError
{
INVALID_METADATA,
FILE_NOT_FOUND,
INVALID_PATH,
UNKNOWN_FILE
}
public class MetaDataColumnInfo
{
public string name { get; internal set; }
public string type_id { get; internal set; }
/**
* Creates MetaDataColumnInfo from a string in format "name[t]", where 't' is GVariant type.
*/
public MetaDataColumnInfo (string v) throws Error
{
int idx = v.index_of ("[");
if (idx > 0 && v.index_of ("]") == v.length - 1) //there must be at least 1 character preceding [, thus > 0
{
name = v.substring (0, idx);
type_id = v.slice (idx + 1, v.length - 1);
}
else
{
throw new ParseError.INVALID_METADATA ("Invalid format of meta data string");
}
}
public virtual bool equals (MetaDataColumnInfo m)
{
return name == m.name && type_id == m.type_id;
}
}
public class MetaDataSchemaInfo
{
public GLib.GenericArray columns;
/**
* Creates a list of MetaDataColumnInfo objects from a semicolon-separated strings, e.g. "name1[type];name2[type2]...".
*
* @param mdinfo_str semicolon-separated name[type] entries
* @return list of MetaDataColumnInfo objects
*/
public static MetaDataSchemaInfo from_string (string mdinfo_str) throws Error
{
var schema_info = new MetaDataSchemaInfo ();
schema_info.columns = new GLib.GenericArray ();
foreach (var m in mdinfo_str.split (";"))
{
if (m.length > 0)
{
var info = new MetaDataColumnInfo (m);
schema_info.columns.add (info);
}
}
return schema_info;
}
public HashTable as_hash_table ()
{
HashTable ret = new HashTable (str_hash, str_equal);
for (int i = 0; i < columns.length; i++)
{
unowned MetaDataColumnInfo info = columns[i];
ret[info.name] = info.type_id;
}
return ret;
}
public bool equals (MetaDataSchemaInfo s)
{
if (columns.length != s.columns.length)
return false;
for (int i = 0; i < columns.length; i++)
{
if (!columns[i].equals (s.columns[i]))
return false;
}
return true;
}
}
public class CategoryDefinition
{
public string id { get; private set; }
public string name { get; private set; }
public string icon { get; private set; }
public string? renderer { get; private set; }
public string? content_type { get; private set; }
public string? dedup_field { get; private set; }
public string? sort_field { get; private set; }
public string? renderer_hint { get; set; }
internal static CategoryDefinition create (string id, string name,
string icon,
string? renderer = null,
string? content_type = null,
string? dedup_field = null,
string? sort_field = null)
requires (id[0] != '\0')
{
var def = new CategoryDefinition ();
def.id = id;
def.name = name;
def.icon = icon;
def.renderer = renderer;
def.content_type = content_type;
def.dedup_field = dedup_field;
def.sort_field = sort_field;
return def;
}
}
public class FilterDefinition
{
public string id { get; private set; }
public string filter_type { get; private set; }
public string name { get; private set; }
public string? sort_type { get; private set; }
private string[] option_ids;
private string[] option_names;
public unowned string[] get_option_ids ()
{
return option_ids;
}
public unowned string[] get_option_names ()
{
return option_names;
}
public void add_option (string id, string name)
requires (id[0] != '\0')
{
option_ids += id;
option_names += name;
}
internal static FilterDefinition create (string id, string filter_type,
string name,
string? sort_type = null)
requires (id[0] != '\0')
{
var def = new FilterDefinition ();
def.id = id;
def.filter_type = filter_type;
def.name = name;
def.sort_type = sort_type;
return def;
}
}
public class ScopeRegistry
{
private static const string SCOPE_GROUP = "Scope";
private static const string DESKTOP_GROUP = "Desktop Entry";
private static string[] scope_directories = null;
private static string[] scope_file_prefixes = null;
private static bool overrides_scope_dirs = false;
private static string extract_scope_id (string path)
{
string? real_path = null;
if (!Path.is_absolute (path))
{
var f = File.new_for_path (path);
real_path = f.get_path ();
path = real_path;
}
if (scope_file_prefixes == null) init_scope_file_prefixes ();
string normalized_path = path.replace ("//", "/");
foreach (unowned string prefix in scope_file_prefixes)
{
if (normalized_path.has_prefix (prefix))
{
string without_prefix = normalized_path.substring (prefix.length);
if (Path.DIR_SEPARATOR_S in without_prefix)
return without_prefix.replace (Path.DIR_SEPARATOR_S, "-");
return without_prefix;
}
}
return Path.get_basename (path);
}
internal static void init_scope_file_prefixes ()
{
if (scope_directories == null) init_scope_directories ();
scope_file_prefixes = {};
foreach (unowned string scope_dir in scope_directories)
{
var f = File.new_for_path (scope_dir);
// this will resolve relative paths
scope_file_prefixes += "%s/".printf (f.get_path ());
}
}
internal static void init_scope_directories ()
{
var overriden_dirs = Environment.get_variable ("LIBUNITY_SCOPE_DIRECTORIES");
overrides_scope_dirs = overriden_dirs != null;
if (overriden_dirs == null)
{
scope_directories = {};
var data_dirs = Environment.get_system_data_dirs ();
foreach (unowned string data_dir in data_dirs)
{
scope_directories += Path.build_filename (data_dir, SCOPES_DIR);
}
}
else
{
scope_directories = overriden_dirs.split (":");
}
}
public class ScopeMetadata
{
private static string[] hidden_scope_ids;
private const string SCOPE_SCHEMA = "com.canonical.Unity.Lenses";
static construct
{
// the hidden scopes are not supposed to be changed, so no need
// to monitor for dynamic changes
update_hidden_scope_ids ();
}
internal static void update_hidden_scope_ids ()
{
var schema_src = SettingsSchemaSource.get_default().lookup (SCOPE_SCHEMA, false);
if (schema_src != null)
{
var settings = new Settings.full (schema_src, null, null);
hidden_scope_ids = settings.get_strv ("hidden-scopes");
}
else
{
hidden_scope_ids = {};
}
}
/* careful here, although it's a private lib, keeping it
* ABI compatible is a good idea (unity-core uses it) */
public string id;
public string domain;
public string full_path;
public string name;
public string dbus_path;
public string dbus_name;
public string icon;
public string category_icon;
public MetaDataSchemaInfo? required_metadata;
public MetaDataSchemaInfo? optional_metadata;
public GLib.SList keywords;
public string type;
public string description;
public string search_hint;
public bool is_master;
public bool global_searches;
public bool visible;
public bool remote_content;
public string query_binary;
public string query_pattern;
public string shortcut;
public string no_content_hint;
public bool no_export;
public string module;
public string module_type;
public int timeout;
private CategoryDefinition[] categories;
private FilterDefinition[] filters;
private string[] subscope_ids;
private bool overrides_subscopes;
public unowned CategoryDefinition[] get_categories ()
{
return categories;
}
public unowned FilterDefinition[] get_filters ()
{
return filters;
}
public unowned string[] get_subscope_ids ()
{
return subscope_ids;
}
internal bool get_overrides_subscopes ()
{
return overrides_subscopes;
}
public void load_from_key_file (KeyFile file) throws Error
{
this.domain = null;
// Get the Gettext-Domain first, if it exists
if (file.has_group (DESKTOP_GROUP) && file.has_key (DESKTOP_GROUP, "X-Ubuntu-Gettext-Domain"))
this.domain = file.get_string (DESKTOP_GROUP, "X-Ubuntu-Gettext-Domain");
// required fields
this.name = dgettext(this.domain, file.get_string (SCOPE_GROUP, "Name"));
// support deprecated DBusName / DBusPath, but require the new
// GroupName & UniqueName
if (file.has_key (SCOPE_GROUP, "DBusName"))
{
this.dbus_name = file.get_string (SCOPE_GROUP, "DBusName");
}
else
{
this.dbus_name = file.get_string (SCOPE_GROUP, "GroupName");
}
if (file.has_key (SCOPE_GROUP, "DBusPath"))
{
this.dbus_path = file.get_string (SCOPE_GROUP, "DBusPath");
}
else
{
this.dbus_path = file.get_string (SCOPE_GROUP, "UniqueName");
}
this.icon = file.get_string (SCOPE_GROUP, "Icon");
this.type = file.get_string (SCOPE_GROUP, "Type");
// optional fields
if (file.has_key (SCOPE_GROUP, "IsMaster"))
this.is_master = file.get_boolean (SCOPE_GROUP, "IsMaster");
else
this.is_master = false;
if (file.has_key (SCOPE_GROUP, "Module"))
this.module = file.get_string (SCOPE_GROUP, "Module");
else
this.module = null;
if (file.has_key (SCOPE_GROUP, "ModuleType"))
this.module_type = file.get_string (SCOPE_GROUP, "ModuleType");
else
this.module_type = null;
if (file.has_key (SCOPE_GROUP, "Visible"))
this.visible = file.get_boolean (SCOPE_GROUP, "Visible");
else
this.visible = true;
if (file.has_key (SCOPE_GROUP, "GlobalSearches"))
this.global_searches = file.get_boolean (SCOPE_GROUP, "GlobalSearches");
else
this.global_searches = true;
if (file.has_key (SCOPE_GROUP, "RemoteContent"))
this.remote_content = file.get_boolean (SCOPE_GROUP, "RemoteContent");
else
this.remote_content = false;
if (file.has_key (SCOPE_GROUP, "QueryBinary"))
this.query_binary = file.get_string (SCOPE_GROUP, "QueryBinary");
if (file.has_key (SCOPE_GROUP, "CategoryIcon"))
this.category_icon = file.get_string (SCOPE_GROUP, "CategoryIcon");
if (file.has_key (SCOPE_GROUP, "QueryPattern"))
this.query_pattern = file.get_string (SCOPE_GROUP, "QueryPattern");
if (file.has_key (SCOPE_GROUP, "Description"))
this.description = file.get_string (SCOPE_GROUP, "Description");
if (file.has_key (SCOPE_GROUP, "SearchHint"))
this.search_hint = dgettext (this.domain, file.get_string (SCOPE_GROUP, "SearchHint"));
if (file.has_key (SCOPE_GROUP, "RequiredMetadata"))
this.required_metadata = MetaDataSchemaInfo.from_string (file.get_string (SCOPE_GROUP, "RequiredMetadata"));
if (file.has_key (SCOPE_GROUP, "OptionalMetadata"))
this.optional_metadata = MetaDataSchemaInfo.from_string (file.get_string (SCOPE_GROUP, "OptionalMetadata"));
if (file.has_key (SCOPE_GROUP, "Keywords"))
{
// split keywords
this.keywords = new GLib.SList ();
foreach (var k in file.get_string (SCOPE_GROUP, "Keywords").split (";"))
{
if (k.length > 0)
this.keywords.append (k);
}
}
if (file.has_key (SCOPE_GROUP, "Shortcut"))
{
this.shortcut = file.get_string (SCOPE_GROUP, "Shortcut");
}
if (file.has_key (SCOPE_GROUP, "Timeout"))
{
this.timeout = file.get_integer (SCOPE_GROUP, "Timeout");
}
if (file.has_key (SCOPE_GROUP, "NoExport"))
{
this.no_export = file.get_boolean (SCOPE_GROUP, "NoExport");
}
else
{
this.no_export = false;
}
// key to specify subscope ids, so no discovery is needed
if (file.has_key (SCOPE_GROUP, "NoContentHint"))
{
this.no_content_hint = dgettext (this.domain, file.get_string (SCOPE_GROUP, "NoContentHint"));
}
if (file.has_key (SCOPE_GROUP, "Subscopes"))
{
this.subscope_ids = file.get_string_list (SCOPE_GROUP, "Subscopes");
this.overrides_subscopes = true;
}
const string FILTER_PREFIX = "Filter ";
const string CATEGORY_PREFIX = "Category ";
// parse categories and filters
foreach (unowned string group_name in file.get_groups ())
{
var stripped = group_name.strip ();
if (group_name.has_prefix (CATEGORY_PREFIX)
&& stripped.length >= CATEGORY_PREFIX.length + 1)
{
var id = stripped.substring (CATEGORY_PREFIX.length).strip ();
var name = dgettext (this.domain, file.get_string (group_name, "Name"));
var icon = file.get_string (group_name, "Icon");
string? dedup_field = null;
if (file.has_key (group_name, "DedupField"))
{
dedup_field = file.get_string (group_name, "DedupField");
}
string? sort_field = null;
if (file.has_key (group_name, "SortField"))
{
sort_field = file.get_string (group_name, "SortField");
}
string? renderer = null;
if (file.has_key (group_name, "Renderer"))
{
renderer = file.get_string (group_name, "Renderer");
}
string? cat_content_type = null;
if (file.has_key (group_name, "ContentType"))
{
cat_content_type = file.get_string (group_name, "ContentType");
}
string? renderer_hint = null;
if (file.has_key (group_name, "RendererHint"))
{
renderer_hint = file.get_string (group_name, "RendererHint");
}
var category_definition = CategoryDefinition.create (id, name, icon,
renderer,
cat_content_type,
dedup_field,
sort_field);
if (category_definition != null)
{
category_definition.renderer_hint = renderer_hint;
categories += category_definition;
}
}
else if (group_name.has_prefix (FILTER_PREFIX)
&& stripped.length >= FILTER_PREFIX.length + 1)
{
var id = stripped.substring (FILTER_PREFIX.length).strip ();
var type = file.get_string (group_name, "Type");
var name = dgettext (this.domain, file.get_string (group_name, "Name"));
string? sort_type = null;
if (file.has_key (group_name, "SortType"))
{
sort_type = file.get_string (group_name, "SortType");
}
var filter_definition = FilterDefinition.create (id, type, name,
sort_type);
// parse the options
var option_ids = file.get_string_list (group_name, "OptionIDs");
var option_names_str = dgettext (this.domain, file.get_string (group_name, "OptionNames"));
// trailing ';' will cause extra split argument containing empty string, get rid of that
if (option_names_str[option_names_str.length-1] == ';')
{
option_names_str.data[option_names_str.length-1] = 0;
}
var option_names = option_names_str.split (";");
if (option_ids.length != option_names.length)
{
warning ("Number of elements of OptionIDs doesn't match OptionNames (%d vs %d)", option_ids.length, option_names.length);
}
for (int i = 0; i < option_ids.length && i < option_names.length; i++)
{
filter_definition.add_option (option_ids[i], option_names[i]);
}
if (filter_definition != null)
{
filters += filter_definition;
}
}
}
}
/* Private method cause ScopeMetadata.full_path and .id are null */
private static ScopeMetadata for_keyfile (KeyFile file) throws Error
{
ScopeMetadata data = new ScopeMetadata ();
data.load_from_key_file (file);
return data;
}
public static ScopeMetadata for_id (string scope_id) throws Error
{
debug ("for_id: %s", scope_id);
if (scope_id in hidden_scope_ids)
throw new ParseError.FILE_NOT_FOUND ("Scope is disabled: %s", scope_id);
string full_path;
var file = new KeyFile ();
bool loaded;
if (overrides_scope_dirs)
{
loaded = file.load_from_dirs (scope_id, scope_directories,
out full_path, KeyFileFlags.NONE);
}
else
{
var path = "%s/%s".printf (SCOPES_DIR, scope_id);
loaded = file.load_from_data_dirs (path, out full_path,
KeyFileFlags.NONE);
}
if (!loaded)
throw new ParseError.FILE_NOT_FOUND ("Scope not found: %s", scope_id);
var data = ScopeMetadata.for_keyfile (file);
data.id = scope_id;
data.full_path = full_path;
return data;
}
public static ScopeMetadata for_path (string path) throws Error
{
debug ("for_path: %s", path);
bool loaded = true;
string full_path;
var keyfile = new KeyFile ();
if (GLib.Path.is_absolute (path))
{
loaded = keyfile.load_from_file (path, KeyFileFlags.NONE);
full_path = path;
}
else
{
loaded = keyfile.load_from_data_dirs (path, out full_path, KeyFileFlags.NONE);
}
if (!loaded)
throw new ParseError.FILE_NOT_FOUND ("File not found: %s", path);
ScopeMetadata data = ScopeMetadata.for_keyfile (keyfile);
data.full_path = full_path;
data.id = extract_scope_id (full_path);
if (data.id in hidden_scope_ids)
throw new ParseError.FILE_NOT_FOUND ("Scope is disabled: %s", data.id);
return data;
}
}
// node representing single scope, with optional sub-scopes (if master scope)
public class ScopeRegistryNode
{
public ScopeMetadata scope_info;
public GLib.SList? sub_scopes;
}
// list of top-level scopes
private SList scopes_ = new SList ();
public GLib.SList? scopes
{
get { return scopes_; }
}
private ScopeRegistry ()
{
}
static construct
{
init_scope_directories ();
}
/**
* Build registry of all scopes in start_path.
* start_path can be a directory, a .scope file path or just scope id (.scope file name, including extenstion).
*
* @param start_path starting directory or specific .scope file
* @return registry of all scopes (if start_path is a dir) or just one scope and its subscopes.
*/
public static async ScopeRegistry find_scopes (string? start_path) throws Error
{
var registry = new ScopeRegistry ();
Node root_node = new Node (null);
if (start_path == null)
{
foreach (unowned string scope_dir in scope_directories)
{
if (!FileUtils.test (scope_dir, FileTest.IS_DIR)) continue;
try
{
yield build_scope_node_tree (root_node, scope_dir);
}
catch (Error e)
{
// we'll ignore errors from here
warning ("Unable to process scope directory %s: %s",
scope_dir, e.message);
}
}
}
else
{
yield build_scope_node_tree (root_node, start_path);
}
registry.from_tree (root_node);
return registry;
}
private static bool node_has_child_with_id (Node node,
string scope_id,
out unowned Node child)
{
bool scope_id_present = false;
unowned Node found_child = null;
node.children_foreach (TraverseFlags.ALL, (child_) =>
{
unowned Node child_node = child_;
if (child_node.data.id == scope_id)
{
scope_id_present = true;
found_child = child_node;
}
});
child = found_child;
return scope_id_present;
}
private static async void build_scope_node_tree (Node root_node,
string start_path)
throws Error
{
debug ("build_scope_node_tree [level: %u]: %s", root_node.depth (), start_path);
if (FileUtils.test (start_path, FileTest.IS_DIR))
{
var dir = GLib.Dir.open (start_path);
string name;
while ((name = dir.read_name ()) != null)
{
string filename = Path.build_filename (start_path, name);
if (!filename.has_suffix (".scope")) continue;
// failure of single scope shouldn't break processing of others scopes
try
{
yield build_scope_node_tree (root_node, filename);
}
catch (Error e)
{
warning ("Failed to process '%s': %s", filename, e.message);
}
}
}
else
{
if (!start_path.has_suffix (".scope"))
{
throw new ParseError.UNKNOWN_FILE ("Unknown file type: \"%s\"", start_path);
}
debug ("Found scope file: %s", start_path);
// this may throw, in such case don't process this scope
// (and possibly its subscopes if it was master scope)
ScopeMetadata? scope_data = ScopeMetadata.for_path (start_path);
if (scope_data == null) return;
// do we already have this scope in the tree?
unowned Node child_node = null;
bool scope_id_present = node_has_child_with_id (root_node,
scope_data.id,
out child_node);
if (!scope_id_present)
{
// save the node in the tree
child_node = root_node.append_data (scope_data);
}
assert (child_node != null);
if (child_node.data.is_master)
{
// if master scope specifies its subscopes, don't try to merge
// the children from multiple locations
if (child_node.data.get_overrides_subscopes () &&
child_node.n_children () == 0)
{
debug ("Scope %s overrides its children", child_node.data.id);
unowned string[] subscopes = child_node.data.get_subscope_ids ();
foreach (unowned string subscope_id in subscopes)
{
try
{
ScopeMetadata subscope_data = ScopeMetadata.for_id (subscope_id);
if (subscope_data != null &&
!node_has_child_with_id (child_node, subscope_data.id, null))
{
// FIXME: we're not building the complete tree here,
// but right now it's not needed
child_node.append_data (subscope_data);
}
}
catch (Error e)
{
warning ("Failed to process '%s': %s", subscope_id, e.message);
}
}
}
else
{
/* This is a master scope, find its children in subdirectory */
var scopefile = GLib.File.new_for_path (scope_data.full_path);
var parent = scopefile.get_parent ();
if (parent == null) return;
string scope_name = remove_scope_extension (scope_data.id);
string check_path = Path.build_filename (parent.get_path (), scope_name);
if (!FileUtils.test (check_path, FileTest.IS_DIR)) return;
yield build_scope_node_tree (child_node, check_path);
}
}
}
}
private void from_tree (Node root_node)
{
// only 2 level traverse, anything deeper will be discarded
root_node.children_foreach (TraverseFlags.ALL, (top_child_) =>
{
unowned Node top_child = top_child_;
var scope_node = new ScopeRegistryNode ()
{
scope_info = top_child.data,
sub_scopes = new GLib.SList ()
};
top_child.children_foreach (TraverseFlags.ALL, (child_) =>
{
unowned Node child = child_;
scope_node.sub_scopes.append (child.data);
});
this.scopes_.append (scope_node);
});
}
internal static string remove_scope_extension (string scope_id)
{
if (scope_id.has_suffix (".scope"))
return scope_id.substring (0, scope_id.last_index_of ("."));
return scope_id;
}
/**
* Find sub-scopes for given master scope id in unity/scopes subdirectory
* of XDG_DATA_DIRS dirs or in root_path.
* @param scope_id id of a master scope (with .scope suffix)
* @param root_path base directory of scopes, defaults to XDG_DATA_DIRS paths + "/unity/scopes"
* @return scope registry with scopes property populated with all sub-scopes of the master scope.
*/
public static async ScopeRegistry find_scopes_for_id (string scope_id, string? root_path = null) throws Error
{
var registry = new ScopeRegistry ();
debug ("find_scopes_for_id: %s", scope_id);
var root_node = new Node (null);
// try to find the master scope file
try
{
var scope_metadata = ScopeMetadata.for_id (scope_id);
yield build_scope_node_tree (root_node, scope_metadata.full_path);
if (scope_file_prefixes == null) init_scope_file_prefixes ();
}
catch (Error err)
{
// silently ignore
}
/* if the scope was found, we need to check also the other
* scope_directories, and merge sub-scopes from all of them, if it wasn't
* this wasn't a valid scope_id, perhaps we can find a dir? */
string[]? dirs = root_path == null ?
scope_directories : new string [1] { root_path };
if (dirs == null || dirs.length == 0)
{
throw new ParseError.INVALID_PATH ("Invalid scopes path");
}
unowned Node node = root_node.n_children () > 0 ?
root_node.first_child () : root_node;
var suffix = remove_scope_extension (scope_id);
foreach (var path in dirs)
{
var check_path = Path.build_filename (path, suffix);
if (!FileUtils.test (check_path, FileTest.IS_DIR)) continue;
yield build_scope_node_tree (node, check_path);
}
// the registry from this method is not expected to contain the scope
// itself, so don't use the root directly
registry.from_tree (node);
return registry;
}
}
public struct ScopeGroupScopeInfo
{
public string scope_id;
public string dbus_name;
public string dbus_path;
public string module;
public string module_type;
}
public class ScopeGroupConfig
{
private static const string SCOPE_GROUP_GROUP = "Scope Group";
public List scopes;
public int timeout;
public ScopeGroupConfig (string file_name) throws Error
{
var file = new KeyFile ();
if (!file.load_from_file (file_name, KeyFileFlags.NONE))
{
throw new IOError.NOT_FOUND (@"Scope group not found: $file_name");
}
if (file.has_key (SCOPE_GROUP_GROUP, "Timeout"))
this.timeout = file.get_integer (SCOPE_GROUP_GROUP, "Timeout");
else
this.timeout = 0;
this.scopes = null;
foreach (var scope_id in file.get_string (SCOPE_GROUP_GROUP, "Scopes").split(";"))
{
// Read additional metadata from groups named by the scope IDs.
var metadata = Unity.Protocol.ScopeRegistry.ScopeMetadata.for_id (scope_id);
this.scopes.append (
{scope_id,
metadata.dbus_name, metadata.dbus_path,
metadata.module, metadata.module_type});
}
}
}
} /* namespace unity */
libunity-7.1.4+15.10.20151002/protocol/unity-scope-proxy.vala 0000644 0000153 0000161 00000007241 12603350222 024045 0 ustar pbuser pbgroup 0000000 0000000 /*
* Copyright (C) 2012 Canonical, Ltd.
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* version 3.0 as published by the Free Software Foundation.
*
* 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 version 3.0 for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see
* .
*
* Authored by Michal Hruby
*
*/
using GLib;
using Unity.Protocol;
namespace Unity.Protocol {
/*
* Proxies a Scope from DBus
*/
public abstract interface ScopeProxy : GLib.Object
{
public abstract bool visible { get; }
public abstract bool is_master { get; }
public abstract bool connected { get; }
public abstract string search_hint { get; }
public abstract ViewType view_type { get; set; }
public abstract Dee.SerializableModel filters_model { get; }
public abstract Dee.SerializableModel categories_model { get; }
/* no access to Filter class in proto lib */
public abstract Variant sources { get; }
public abstract HashTable metadata { get; }
public abstract HashTable optional_metadata { get; }
public signal void category_order_changed (
string channel_id, uint32[] new_order);
public signal void filter_settings_changed (
string channel_id, Variant filter_rows);
public signal void results_invalidated (ChannelType channel_type);
public abstract async ActivationReplyRaw activate (
string channel_id,
Variant[] result_arr,
ActionType action_type,
HashTable hints,
Cancellable? cancellable = null) throws Error;
public abstract async HashTable search (
string channel_id,
string search_string,
HashTable hints,
Cancellable? cancellable = null) throws Error;
public abstract async string open_channel (
ChannelType channel_type,
ChannelFlags channel_flags,
Cancellable? cancellable = null,
out Dee.SerializableModel results_model) throws Error;
public abstract async void close_channel (
string channel_id,
Cancellable? cancellable = null) throws Error;
public signal void channels_invalidated ();
public abstract async void set_active_sources (
string channel_id,
string[] sources,
Cancellable? cancellable = null) throws Error;
public abstract async HashTable push_results (
string channel_id,
string search_string,
string source_scope_id,
Dee.SerializableModel model,
string[] categories,
GLib.Cancellable? cancellable = null) throws Error;
public static async ScopeProxy new_for_id (
string id, Cancellable? cancellable = null) throws Error
{
throw new IOError.FAILED ("Unimplemented!");
}
public static async ScopeProxy new_from_dbus (
string dbus_name, string dbus_path,
Cancellable? cancellable = null) throws Error
{
var proxy = yield ScopeProxyRemote.create (dbus_name, dbus_path, cancellable);
return proxy;
}
public static async ScopeProxy new_from_metadata (
ScopeRegistry.ScopeMetadata metadata,
Cancellable? cancellable = null) throws Error
{
// FIXME: this is a place where we could use local proxies too
var proxy = yield ScopeProxyRemote.create (metadata.dbus_name, metadata.dbus_path, cancellable);
return proxy;
}
}
} /* namespace */
libunity-7.1.4+15.10.20151002/protocol/protocol-previews.vala 0000644 0000153 0000161 00000056034 12603350222 024116 0 ustar pbuser pbgroup 0000000 0000000 /*
* Copyright (C) 2012 Canonical, Ltd.
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* version 3.0 as published by the Free Software Foundation.
*
* 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 version 3.0 for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see
* .
*
* Authored by Michal Hruby
*
*/
using GLib;
using Dee;
namespace Unity.Protocol {
/* The raw type that get's passed over DBus to Unity */
private struct PreviewRaw
{
// make sure this matches the real signature
internal const string SIGNATURE = "(ssssssa(sssua{sv})a(sssv)a{sv})";
public string renderer_name;
public string title;
public string subtitle;
public string description;
public string image_source_uri;
public string image_hint;
public PreviewActionRaw[] actions;
public InfoHintRaw[] info_hints;
public HashTable hints;
public PreviewRaw ()
{
hints = new HashTable (str_hash, str_equal);
}
public static PreviewRaw? from_variant (Variant v)
{
return (PreviewRaw) v;
}
public Variant to_variant ()
{
return this;
}
}
public enum LayoutHint
{
NONE,
LEFT,
RIGHT,
TOP,
BOTTOM
}
public struct InfoHintRaw
{
public string id;
public string display_name;
public string icon_hint;
public Variant value;
}
public struct PreviewActionRaw
{
public string id;
public string display_name;
public string icon_hint;
public uint layout_hint;
public HashTable hints;
public PreviewActionRaw ()
{
hints = new HashTable (str_hash, str_equal);
}
public static PreviewActionRaw? from_variant (Variant v)
{
return (PreviewActionRaw) v;
}
public Variant to_variant ()
{
return this;
}
}
public abstract class Preview : Object, Dee.Serializable
{
public string title { get; set; }
public string subtitle { get; set; }
public string description { get; set; }
public string image_source_uri { get; set; }
public Icon? image { get; set; }
private PreviewRaw _raw = PreviewRaw ();
private PreviewActionRaw[] _actions_raw = null;
private InfoHintRaw[] _info_hints = null;
private HashTable? _updates = null;
private bool _no_details = false;
public virtual void begin_updates()
{
if (_updates != null)
{
warning ("Called begin_updates without end_updates");
}
else
{
_updates = new HashTable (str_hash, str_equal);
}
}
public virtual HashTable? end_updates_as_hashtable ()
{
if (_updates == null)
{
warning ("Called end_updates without begin_updates");
}
var result = _updates;
_updates = null;
return result;
}
public virtual Variant? end_updates ()
{
HashTable result = end_updates_as_hashtable ();
return result;
}
public void add_action (string id, string display_name,
Icon? icon, uint layout_hint)
{
var hints = new HashTable (null, null);
add_action_with_hints (id, display_name, icon, layout_hint, (owned) hints);
}
public void add_action_with_hints (string id, string display_name,
Icon? icon, uint layout_hint,
owned HashTable hints)
{
PreviewActionRaw? action_raw = PreviewActionRaw ();
action_raw.id = id;
action_raw.display_name = display_name;
action_raw.icon_hint = icon != null ? icon.to_string () : "";
action_raw.layout_hint = layout_hint;
action_raw.hints = (owned) hints;
_actions_raw += (owned) action_raw;
}
public unowned PreviewActionRaw[] get_actions ()
{
return _actions_raw;
}
public void add_info_hint (string id,
string display_name,
Icon? icon_hint,
Variant value)
{
InfoHintRaw? info = InfoHintRaw ();
info.id = id;
info.display_name = display_name;
info.icon_hint = icon_hint != null ? icon_hint.to_string () : "";
info.value = value;
_info_hints += (owned) info;
}
public abstract unowned string get_renderer_name ();
public unowned InfoHintRaw[] get_info_hints ()
{
return _info_hints;
}
public void set_no_details (bool val)
{
_no_details = val;
}
public bool get_no_details ()
{
return _no_details;
}
/**
* Called by Dash when preview has been closed
*/
public void preview_closed ()
{
add_update ("base-preview-action", "closed");
}
public virtual void update_property (HashTable properties)
{
}
internal virtual void add_properties (HashTable properties)
{
if (_no_details)
properties["no-details"] = new Variant.boolean (true);
}
internal void add_update(string property, Variant value)
{
if (_updates != null)
{
_updates[property] = value;
}
}
internal HashTable get_properties ()
{
var properties = new HashTable (str_hash, str_equal);
add_properties (properties);
return properties;
}
private Variant serialize ()
{
_raw.renderer_name = get_renderer_name ();
_raw.title = title != null ? title : "";
_raw.subtitle = subtitle != null ? subtitle : "";
_raw.description = description != null ? description : "";
_raw.image_source_uri = image_source_uri != null ? image_source_uri : "";
_raw.image_hint = image != null ? image.to_string () : "";
_raw.actions = _actions_raw;
_raw.info_hints = _info_hints;
_raw.hints = get_properties ();
return _raw.to_variant ();
}
internal static Icon? string_to_icon (string s)
{
if (s[0] != '\0')
{
try
{
return Icon.new_for_string (s);
}
catch (Error err)
{
warning ("Failed to deserialize GIcon: %s", err.message);
return null;
}
}
return null;
}
internal static Icon? variant_to_icon (Variant? v)
{
return v != null ? string_to_icon (v.get_string ()) : null;
}
private static bool parsers_registered = false;
private static void register_parsers ()
{
typeof (GenericPreview).class_ref ();
typeof (ApplicationPreview).class_ref ();
typeof (MusicPreview).class_ref ();
typeof (PaymentPreview).class_ref ();
typeof (MoviePreview).class_ref ();
typeof (SocialPreview).class_ref ();
typeof (SeriesPreview).class_ref ();
}
public static Preview? parse (Variant data)
{
if (!parsers_registered)
{
register_parsers ();
parsers_registered = true;
}
Object? result_obj = null;
unowned string renderer = data.get_child_value (0).get_string ();
switch (renderer)
{
case GenericPreview.RENDERER_NAME:
result_obj = Dee.Serializable.parse (data, typeof (GenericPreview));
break;
case ApplicationPreview.RENDERER_NAME:
result_obj = Dee.Serializable.parse (data, typeof (ApplicationPreview));
break;
case MusicPreview.RENDERER_NAME:
result_obj = Dee.Serializable.parse (data, typeof (MusicPreview));
break;
case PaymentPreview.RENDERER_NAME:
result_obj = Dee.Serializable.parse (data, typeof (PaymentPreview));
break;
case MoviePreview.RENDERER_NAME:
result_obj = Dee.Serializable.parse (data, typeof (MoviePreview));
break;
case SocialPreview.RENDERER_NAME:
result_obj = Dee.Serializable.parse (data, typeof (SocialPreview));
break;
case SeriesPreview.RENDERER_NAME:
result_obj = Dee.Serializable.parse (data, typeof (SeriesPreview));
break;
default:
warning ("Unknown preview renderer: %s", renderer);
break;
}
return result_obj as Preview;
}
internal static T deserialize (
Variant data, out HashTable out_properties = null)
requires (typeof (T).is_a (typeof (Preview)))
{
Preview result = Object.new (typeof (T)) as Preview;
var raw = PreviewRaw.from_variant (data);
out_properties = raw.hints;
// set base properties
result.title = raw.title;
result.subtitle = raw.subtitle;
result.description = raw.description;
result.image_source_uri = raw.image_source_uri;
result.image = Preview.string_to_icon (raw.image_hint);
result._actions_raw = (owned) raw.actions;
result._info_hints = (owned) raw.info_hints;
unowned Variant no_det_var = raw.hints.lookup ("no-details");
if (no_det_var != null)
result._no_details = no_det_var.get_boolean ();
return (T) result;
}
internal static void checked_set (Variant? v, Func f)
{
if (v != null) f (v);
}
}
public class GenericPreview : Preview
{
internal const string RENDERER_NAME = "preview-generic";
public GenericPreview ()
{
Object ();
}
internal override unowned string get_renderer_name ()
{
return RENDERER_NAME;
}
static construct
{
Dee.Serializable.register_parser (typeof (GenericPreview),
new VariantType (PreviewRaw.SIGNATURE),
(data) =>
{
unowned string renderer = data.get_child_value (0).get_string ();
warn_if_fail (renderer == RENDERER_NAME);
GenericPreview result;
result = Preview.deserialize (data);
return result;
});
}
}
public class ApplicationPreview : Preview
{
internal const string RENDERER_NAME = "preview-application";
public Icon app_icon { get; set; }
public string license { get; set; }
public string copyright { get; set; }
public string last_update { get; set; }
public float rating { get; set; }
public uint num_ratings { get; set; }
public ApplicationPreview ()
{
Object ();
}
internal override unowned string get_renderer_name ()
{
return RENDERER_NAME;
}
internal override void add_properties (HashTable properties)
{
base.add_properties (properties);
if (app_icon != null)
properties["application-icon"] = app_icon.to_string ();
if (license != null)
properties["license"] = license;
if (copyright != null)
properties["copyright"] = copyright;
if (last_update != null)
properties["last-update"] = last_update;
if (rating >= -1.0f)
properties["rating"] = (double) rating;
if (num_ratings > 0)
properties["num-ratings"] = num_ratings;
}
static construct
{
Dee.Serializable.register_parser (typeof (ApplicationPreview),
new VariantType (PreviewRaw.SIGNATURE),
(data) =>
{
unowned string renderer = data.get_child_value (0).get_string ();
warn_if_fail (renderer == RENDERER_NAME);
HashTable properties;
ApplicationPreview result = Preview.deserialize (
data, out properties);
Preview.checked_set (properties["application-icon"],
(v) => { result.app_icon = Preview.variant_to_icon (v); });
Preview.checked_set (properties["license"],
(v) => { result.license = v.get_string (); });
Preview.checked_set (properties["copyright"],
(v) => { result.copyright = v.get_string (); });
Preview.checked_set (properties["last-update"],
(v) => { result.last_update = v.get_string (); });
Preview.checked_set (properties["rating"],
(v) => { result.rating = (float) v.get_double (); });
Preview.checked_set (properties["num-ratings"],
(v) => { result.num_ratings = v.get_uint32 (); });
return result;
});
}
}
public enum PlayState
{
STOPPED,
PLAYING,
PAUSED
}
public class MusicPreview : Preview
{
internal const string RENDERER_NAME = "preview-music";
public string track_data_swarm_name { get; set; }
public string track_data_address { get; set; }
public Dee.SerializableModel track_model { get; set; }
public MusicPreview ()
{
Object ();
}
internal override unowned string get_renderer_name ()
{
return RENDERER_NAME;
}
internal override void add_properties (HashTable properties)
{
base.add_properties (properties);
if (track_data_swarm_name != null)
properties["track-data-swarm-name"] = track_data_swarm_name;
if (track_data_address != null)
properties["track-data-address"] = track_data_address;
if (track_model != null)
properties["track-model"] = track_model.serialize ();
}
static construct
{
Dee.Serializable.register_parser (typeof (MusicPreview),
new VariantType (PreviewRaw.SIGNATURE),
(data) =>
{
unowned string renderer = data.get_child_value (0).get_string ();
warn_if_fail (renderer == RENDERER_NAME);
HashTable properties;
MusicPreview result = Preview.deserialize (
data, out properties);
Preview.checked_set (properties["track-data-swarm-name"],
(v) => { result.track_data_swarm_name = v.get_string (); });
Preview.checked_set (properties["track-data-address"],
(v) => { result.track_data_address= v.get_string (); });
Preview.checked_set (properties["track-model"], (v) =>
{
var model = Dee.Serializable.parse (v, typeof (Dee.SequenceModel));
result.track_model = model as Dee.SerializableModel;
});
return result;
});
}
}
public enum PreviewPaymentType {
APPLICATION,
MUSIC,
ERROR,
}
public class PaymentPreview : Preview
{
internal const string RENDERER_NAME = "preview-payment";
public string header { get; set; }
public string email { get; set; }
public string payment_method { get; set; }
public string purchase_prize { get; set; }
public string purchase_type { get; set; }
public PreviewPaymentType preview_type { get; set; default = PreviewPaymentType.MUSIC; }
public PaymentPreview ()
{
Object ();
}
internal override unowned string get_renderer_name ()
{
return RENDERER_NAME;
}
internal override void add_properties (HashTable properties)
{
base.add_properties (properties);
if (header != null)
properties["header"] = header;
if (email != null)
properties["email"] = email;
if (payment_method != null)
properties["payment-method"] = payment_method;
if (purchase_prize != null)
properties["purchase-prize"] = purchase_prize;
if (purchase_type != null)
properties["purchase-type"] = purchase_type;
properties["preview-type"] = preview_type;
}
static construct
{
Dee.Serializable.register_parser (typeof (PaymentPreview),
new VariantType (PreviewRaw.SIGNATURE),
(data) =>
{
unowned string renderer = data.get_child_value (0).get_string ();
warn_if_fail (renderer == RENDERER_NAME);
HashTable properties;
PaymentPreview result = Preview.deserialize (
data, out properties);
Preview.checked_set (properties["title"],
(v) => { result.title = v.get_string (); });
Preview.checked_set (properties["subtitle"],
(v) => { result.subtitle = v.get_string (); });
Preview.checked_set (properties["header"],
(v) => { result.header = v.get_string (); });
Preview.checked_set (properties["email"],
(v) => { result.email = v.get_string (); });
Preview.checked_set (properties["payment-method"],
(v) => { result.payment_method = v.get_string (); });
Preview.checked_set (properties["purchase-prize"],
(v) => { result.purchase_prize = v.get_string (); });
Preview.checked_set (properties["purchase-type"],
(v) => { result.purchase_type = v.get_string (); });
Preview.checked_set (properties["preview-type"],
(v) => { result.preview_type = (PreviewPaymentType) v.get_int32 (); });
return result;
});
}
}
public class MoviePreview : Preview
{
internal const string RENDERER_NAME = "preview-movie";
public string year { get; set; }
public float rating { get; set; }
public uint num_ratings { get; set; }
public MoviePreview ()
{
Object ();
}
internal override unowned string get_renderer_name ()
{
return RENDERER_NAME;
}
internal override void add_properties (HashTable properties)
{
base.add_properties (properties);
if (rating >= -1.0f)
properties["rating"] = (double) rating;
if (num_ratings > 0)
properties["num-ratings"] = num_ratings;
if (year != null)
properties["year"] = year;
}
static construct
{
Dee.Serializable.register_parser (typeof (MoviePreview),
new VariantType (PreviewRaw.SIGNATURE),
(data) =>
{
unowned string renderer = data.get_child_value (0).get_string ();
warn_if_fail (renderer == RENDERER_NAME);
HashTable properties;
MoviePreview result = Preview.deserialize (
data, out properties);
Preview.checked_set (properties["rating"],
(v) => { result.rating = (float) v.get_double (); });
Preview.checked_set (properties["num-ratings"],
(v) => { result.num_ratings = v.get_uint32 (); });
Preview.checked_set (properties["year"],
(v) => { result.year = v.get_string (); });
return result;
});
}
}
public class SocialPreview : Preview
{
internal const string RENDERER_NAME = "preview-social";
public Icon avatar { get; set; }
public string content { get; set; }
public string sender { get; set; }
public CommentRaw[] comments;
private CommentRaw[] _comments = null;
public struct CommentRaw
{
public string id;
public string display_name;
public string content;
public string time;
}
public SocialPreview ()
{
Object ();
}
internal override unowned string get_renderer_name ()
{
return RENDERER_NAME;
}
internal override void add_properties (HashTable properties)
{
base.add_properties (properties);
if (_comments.length > 0)
properties["comments"] = _comments;
if (avatar != null)
properties["avatar"] = avatar.to_string ();
if (content != null)
properties["content"] = content;
if (sender != null)
properties["sender"] = sender;
}
static construct
{
Dee.Serializable.register_parser (typeof (SocialPreview),
new VariantType (PreviewRaw.SIGNATURE),
(data) =>
{
unowned string renderer = data.get_child_value (0).get_string ();
warn_if_fail (renderer == RENDERER_NAME);
HashTable properties;
SocialPreview result = Preview.deserialize (
data, out properties);
Preview.checked_set (properties["avatar"],
(v) => { result.avatar = Preview.variant_to_icon (v); });
Preview.checked_set (properties["content"],
(v) => { result.content = v.get_string (); });
Preview.checked_set (properties["sender"],
(v) => { result.sender = v.get_string (); });
Preview.checked_set (properties["comments"], (v) =>
{
CommentRaw[] comments = (CommentRaw[]) v;
result._comments = (owned) comments;
});
return result;
});
}
public void add_comment (string id,
string display_name,
string content,
string time)
{
CommentRaw? comment = CommentRaw ();
comment.id = id;
comment.display_name = display_name;
comment.content = content;
comment.time = time;
_comments += (owned) comment;
}
public unowned CommentRaw[] get_comments ()
{
return _comments;
}
}
public struct SeriesItemRaw
{
public string uri;
public string title;
public string icon_hint;
}
public class SeriesPreview : Preview
{
internal const string RENDERER_NAME = "preview-series";
public int selected_item { get; set; }
public Preview child_preview { get; set; }
private SeriesItemRaw[] _items = null;
private ulong _selected_item_sig_id = 0;
public SeriesPreview ()
{
Object ();
}
public override void begin_updates ()
{
base.begin_updates();
if (_selected_item_sig_id == 0)
{
_selected_item_sig_id = notify["selected-item"].connect (() =>
{
add_update("series-active-index", selected_item);
});
}
}
public override HashTable? end_updates_as_hashtable ()
{
if (_selected_item_sig_id > 0)
{
SignalHandler.disconnect(this, _selected_item_sig_id);
_selected_item_sig_id = 0;
}
return base.end_updates_as_hashtable();
}
public void add_series_item (string title, string uri, Icon? icon)
{
SeriesItemRaw? item = SeriesItemRaw ();
item.uri = uri;
item.title = title;
item.icon_hint = icon != null ? icon.to_string () : "";
_items += (owned) item;
}
public unowned SeriesItemRaw[] get_items ()
{
return _items;
}
internal override unowned string get_renderer_name ()
{
return RENDERER_NAME;
}
public override void update_property (HashTable properties)
{
base.update_property (properties);
if (properties.contains("series-active-index"))
{
selected_item = properties["series-active-index"].get_int32();
}
}
internal override void add_properties (HashTable properties)
{
base.add_properties (properties);
if (_items.length > 0)
properties["series-items"] = _items;
if (child_preview != null)
properties["current-preview"] = child_preview.serialize ();
if (selected_item >= 0)
properties["series-active-index"] = selected_item;
}
static construct
{
Dee.Serializable.register_parser (typeof (SeriesPreview),
new VariantType (PreviewRaw.SIGNATURE),
(data) =>
{
unowned string renderer = data.get_child_value (0).get_string ();
warn_if_fail (renderer == RENDERER_NAME);
HashTable properties;
SeriesPreview result = Preview.deserialize (
data, out properties);
Preview.checked_set (properties["series-items"], (v) =>
{
SeriesItemRaw[] items = (SeriesItemRaw[]) v;
result._items = (owned) items;
});
Preview.checked_set (properties["series-active-index"],
(v) => { result.selected_item = v.get_int32 (); });
Preview.checked_set (properties["current-preview"], (v) =>
{
result.child_preview = Preview.parse (v);
});
return result;
});
}
}
} /* namespace unity */
libunity-7.1.4+15.10.20151002/protocol/unity-scope-proxy-remote.vala 0000644 0000153 0000161 00000032747 12603350222 025347 0 ustar pbuser pbgroup 0000000 0000000 /*
* Copyright (C) 2011 Canonical, Ltd.
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* version 3.0 as published by the Free Software Foundation.
*
* 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 version 3.0 for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see
* .
*
* Authored by Neil Jagdish Patel
*
*/
using GLib;
using Dee;
namespace Unity.Protocol {
private class ScopeProxyRemote : GLib.Object, ScopeProxy
{
const int REQUIRED_PROTOCOL_VERSION = 1;
public string dbus_name { get; construct; }
public string dbus_path { get; construct; }
public bool auto_reconnect { get; set; default = true; }
// really Vala? no "private set;" when inheriting from interface?
public bool visible { get { return _visible; } }
public bool is_master { get { return _is_master; } }
public bool connected { get { return _is_connected; } }
public Variant sources { get { return _sources; } }
public string search_hint { get { return _search_hint; } }
public Dee.SerializableModel filters_model { get { return _filters_model; } }
public Dee.SerializableModel categories_model { get { return _categories_model; } }
public HashTable metadata { get { return _metadata; } }
public HashTable optional_metadata { get { return _optional_metadata; } }
public ViewType view_type {
// FIXME: ehm?!
get { return _view_type; }
// make sure we do dbus calls only on changes
set { if (_view_type != value) set_view_type.begin (value); }
}
private bool _visible;
private bool _is_master;
private bool _is_connected;
private Variant _sources;
private string _search_hint;
private Dee.SerializableModel _filters_model;
private Dee.SerializableModel _categories_model;
private HashTable _metadata;
private HashTable _optional_metadata;
private ViewType _view_type;
private DBusConnection _bus;
private ScopeService _service;
private bool _connecting_to_proxy;
private uint _reconnection_id = 0;
private int64 _last_scope_crash = 0;
private uint _scope_crashes = 0;
private ulong _cat_sig_id = 0;
private ulong _filters_sig_id = 0;
private ulong _results_invalidated_sig_id = 0;
private ScopeProxyRemote (string dbus_name_, string dbus_path_)
{
Object (dbus_name:dbus_name_, dbus_path:dbus_path_);
}
/* Vala increments reference count on objects that are associated with
* the callbacks in watch_name, therefore this object serves as a proxy, so
* that the ScopeProxyRemote instance can be safely reference counted */
private class NameWatcher
{
private uint watch_id;
unowned ScopeProxyRemote owner;
public NameWatcher (DBusConnection bus, string dbus_name,
ScopeProxyRemote parent, bool auto_start)
{
owner = parent;
var flags = auto_start ?
BusNameWatcherFlags.AUTO_START : BusNameWatcherFlags.NONE;
watch_id =
Bus.watch_name_on_connection (bus, dbus_name, flags,
() => { owner.on_scope_appeared (); },
() => { owner.on_scope_vanished (); });
}
public void unwatch ()
{
if (watch_id != 0)
{
Bus.unwatch_name (watch_id);
watch_id = 0;
}
}
}
private NameWatcher _watcher;
construct
{
try {
_bus = Bus.get_sync (BusType.SESSION);
// auto starting the service here
_watcher = new NameWatcher (_bus, dbus_name, this, true);
} catch (Error e) {
critical ("Unable to connect to session bus: %s", e.message);
}
}
~ScopeProxyRemote ()
{
_watcher.unwatch ();
}
// poor man's AsyncInitable
public static async ScopeProxyRemote create (
string dbus_name, string dbus_path,
Cancellable? cancellable = null) throws Error
{
// this will always return a valid object, even if the proxy is invalid
// (well unless you cancel the request)
var proxy = new ScopeProxyRemote (dbus_name, dbus_path);
yield proxy.wait_for_proxy ();
if (cancellable != null) cancellable.set_error_if_cancelled ();
return proxy;
}
private signal void proxy_initialized ();
private async void wait_for_proxy ()
{
if (_service == null)
{
var sig_id = this.proxy_initialized.connect (() =>
{
wait_for_proxy.callback ();
});
yield;
SignalHandler.disconnect (this, sig_id);
}
}
private async void connect_to_scope ()
{
if (_connecting_to_proxy) return; // can't call this multiple times
try
{
_connecting_to_proxy = true;
_service = yield _bus.get_proxy (dbus_name, dbus_path);
// FIXME: do we need to connect to any property changes?
DBusProxy proxy = _service as DBusProxy;
_is_connected = proxy.g_name_owner != null;
if (_is_connected)
{
if (_service.protocol_version < REQUIRED_PROTOCOL_VERSION)
throw new ScopeError.UNKNOWN ("Unsupported scope proxy");
_is_master = _service.is_master;
_visible = _service.visible;
_search_hint = _service.search_hint;
_metadata = _service.metadata;
_optional_metadata = _service.optional_metadata;
_categories_model = Dee.Serializable.parse (_service.categories, typeof (Dee.SequenceModel)) as Dee.SerializableModel;
_filters_model = Dee.Serializable.parse (_service.filters, typeof (Dee.SequenceModel)) as Dee.SerializableModel;
_cat_sig_id = _service.category_order_changed.connect (on_category_order_changed);
_filters_sig_id = _service.filter_settings_changed.connect (on_filter_settings_changed);
_results_invalidated_sig_id = _service.results_invalidated.connect (on_results_invalidated);
// do we need hints?
}
proxy.g_properties_changed.connect (properties_changed);
} catch (Error e) {
_is_connected = false;
warning ("Unable to connect to Scope (%s @ %s): %s",
dbus_path, dbus_name, e.message);
}
_connecting_to_proxy = false;
notify_property ("connected");
proxy_initialized ();
}
private void properties_changed (DBusProxy proxy,
Variant changed_properties,
[CCode (array_length = false, array_null_terminated = true)] string[] invalidated_properties)
{
var iter = new VariantIter (changed_properties);
unowned string prop_name;
Variant prop_value;
while (iter.next ("{&sv}", out prop_name, out prop_value))
{
if (prop_name == "Filters")
{
_filters_model = Dee.Serializable.parse (_service.filters, typeof (Dee.SequenceModel)) as Dee.SerializableModel;
this.notify_property ("filters-model");
}
else if (prop_name == "Categories")
{
_categories_model = Dee.Serializable.parse (_service.categories, typeof (Dee.SequenceModel)) as Dee.SerializableModel;
this.notify_property ("categories-model");
}
}
}
private void on_category_order_changed (string channel_id, uint32[] new_order)
{
category_order_changed (channel_id, new_order);
}
private void on_filter_settings_changed (string channel_id, Variant filter_rows)
{
filter_settings_changed (channel_id, filter_rows);
}
private void on_results_invalidated (uint channel_type)
{
results_invalidated ((ChannelType) channel_type);
}
public void on_scope_appeared ()
{
if (_reconnection_id != 0)
Source.remove (_reconnection_id);
connect_to_scope.begin ();
}
public void on_scope_vanished ()
{
//sources = new CheckOptionFilter ("sources", "Sources", null, true);
/* No need to clear the filters model, it's read-only for the scope and
* it would just cause warnings from filters synchronizer */
_filters_model = null;
if (_service != null)
{
if (_cat_sig_id > 0)
{
SignalHandler.disconnect (_service, _cat_sig_id);
_cat_sig_id = 0;
}
if (_filters_sig_id > 0)
{
SignalHandler.disconnect (_service, _filters_sig_id);
_filters_sig_id = 0;
}
if (_results_invalidated_sig_id > 0)
{
SignalHandler.disconnect (_service, _results_invalidated_sig_id);
_results_invalidated_sig_id = 0;
}
/* Here comes the protected-restarting logic - the scope will be
* restarted unless it crashed more than 10 times during the past
* 15 minutes */
_scope_crashes++;
var cur_time = get_monotonic_time ();
var time_since_last_crash = cur_time - _last_scope_crash;
if (time_since_last_crash >= 15*60000000) // 15 minutes
{
_last_scope_crash = cur_time;
// reset crash counter, it's not that bad
_scope_crashes = 1;
}
else if (_scope_crashes >= 10)
{
// more than 10 crashes in the past 15 minutes
warning ("Scope %s is crashing too often, disabling it", dbus_name);
return;
}
start_reconnection_timeout ();
}
else
{
start_reconnection_timeout ();
}
_is_connected = false;
// notify users that all associated channels are no longer valid
channels_invalidated ();
notify_property ("connected");
}
private void start_reconnection_timeout ()
{
if (_reconnection_id != 0)
Source.remove (_reconnection_id);
if (!auto_reconnect) return;
_reconnection_id = Timeout.add_seconds (2, () =>
{
if (_service == null)
connect_to_scope.begin ();
else if ((_service as DBusProxy).g_name_owner == null)
close_channel.begin (""); // ping the service to autostart it
_reconnection_id = 0;
return false;
});
}
private void check_proxy () throws Error
{
// we have NameWatcher and will try to reconnect once the name appears
if (_service == null)
throw new DBusError.SERVICE_UNKNOWN ("Unable to connect to service");
}
/*
* Implementation of the ScopeService interface
*/
public async ActivationReplyRaw activate (
string channel_id,
Variant[] result_arr, ActionType action_type,
HashTable hints,
Cancellable? cancellable) throws Error
{
check_proxy ();
var raw = yield _service.activate (channel_id, result_arr,
(uint) action_type, hints,
cancellable);
return raw;
}
public async HashTable search (
string channel_id, string search_string,
HashTable hints,
Cancellable? cancellable) throws Error
{
check_proxy ();
var ht = yield _service.search (channel_id, search_string, hints,
cancellable);
return ht;
}
public async string open_channel (
ChannelType channel_type,
ChannelFlags channel_flags,
Cancellable? cancellable,
out Dee.SerializableModel results_model) throws Error
{
check_proxy ();
var hints = new HashTable (str_hash, str_equal);
bool private_channel = ChannelFlags.PRIVATE in channel_flags;
bool diff_model = ChannelFlags.DIFF_CHANGES in channel_flags;
if (private_channel)
hints[CHANNEL_PRIVATE_HINT] = new Variant.boolean (true);
if (diff_model)
hints[CHANNEL_DIFF_MODEL_HINT] = new Variant.boolean (true);
HashTable out_hints;
var channel_id = yield _service.open_channel ((uint) channel_type, hints,
cancellable,
out out_hints);
Dee.Peer peer = private_channel ?
new Dee.Client (out_hints[CHANNEL_SWARM_NAME_HINT].get_string ()) :
new Dee.Peer (out_hints[CHANNEL_SWARM_NAME_HINT].get_string ());
var model = new Dee.SharedModel.for_peer (peer);
results_model = model;
return channel_id;
}
public async void close_channel (
string channel_id,
Cancellable? cancellable) throws Error
{
check_proxy ();
var hints = new HashTable (str_hash, str_equal);
yield _service.close_channel (channel_id, hints, cancellable);
}
public async void set_view_type (ViewType view_type)
{
_view_type = view_type;
try {
check_proxy ();
// FIXME: no need to set HOME_VIEW if !search_in_global
yield _service.set_view_type (view_type);
} catch (Error e) {
warning (@"Unable to set_active ($dbus_path): $(e.message)");
}
}
public async void set_active_sources (
string channel_id,
string[] sources,
Cancellable? cancellable) throws Error
{
check_proxy ();
// FIXME: remove from ScopeProxy?
if (cancellable != null) cancellable.set_error_if_cancelled ();
}
public async HashTable push_results (
string channel_id,
string search_string,
string source_scope_id,
Dee.SerializableModel model,
string[] categories,
GLib.Cancellable? cancellable = null) throws Error
{
check_proxy ();
return yield _service.push_results (channel_id, search_string,
source_scope_id, model.serialize (),
categories, cancellable);
}
}
} /* Namespace */
libunity-7.1.4+15.10.20151002/protocol/protocol-scope-interface.vala 0000644 0000153 0000161 00000011130 12603350222 025305 0 ustar pbuser pbgroup 0000000 0000000 /*
* Copyright (C) 2011-2012 Canonical, Ltd.
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* version 3.0 as published by the Free Software Foundation.
*
* 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 version 3.0 for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see
* .
*
* Authored by Neil Jagdish Patel
* Michal Hruby
*/
using GLib;
using Dee;
namespace Unity.Protocol {
/* The raw structs that get's passed over DBus to/from the parent Lens */
public struct ActivationReplyRaw
{
public string uri;
public uint handled;
public HashTable hints;
}
public enum HandledType
{
NOT_HANDLED,
SHOW_DASH,
HIDE_DASH,
GOTO_DASH_URI,
SHOW_PREVIEW,
PERFORM_SEARCH
}
public enum ActionType
{
ACTIVATE_RESULT,
PREVIEW_RESULT,
PREVIEW_ACTION,
PREVIEW_BUILTIN_ACTION
}
public enum ViewType
{
HIDDEN,
HOME_VIEW,
LENS_VIEW
}
public enum ChannelType
{
DEFAULT,
GLOBAL
}
[Flags]
public enum ChannelFlags
{
NONE = 0,
PRIVATE,
NO_FILTERING,
DIFF_CHANGES;
public static ChannelFlags from_hints (HashTable hints)
{
ChannelFlags flags = 0;
if (CHANNEL_PRIVATE_HINT in hints &&
hints[CHANNEL_PRIVATE_HINT].get_boolean ())
{
flags |= ChannelFlags.PRIVATE;
}
if (CHANNEL_DIFF_MODEL_HINT in hints &&
hints[CHANNEL_DIFF_MODEL_HINT].get_boolean ())
{
flags |= ChannelFlags.DIFF_CHANGES;
}
return flags;
}
}
/* The error types that can be thrown from DBus methods */
[DBus (name = "com.canonical.Unity.ScopeError")]
public errordomain ScopeError
{
REQUEST_FAILED,
DATA_MISMATCH,
INVALID_CHANNEL,
SEARCH_CANCELLED,
DISABLED_CONTENT,
UNKNOWN
}
public const string CHANNEL_PRIVATE_HINT = "private-channel";
public const string CHANNEL_DIFF_MODEL_HINT = "diff-model";
public const string CHANNEL_SWARM_NAME_HINT = "model-swarm-name";
/**
* ScopeService:
*
* The Scope interface exported on DBus
*/
[DBus (name = "com.canonical.Unity.Scope")]
public interface ScopeService : GLib.Object
{
public const string INTERFACE_NAME = "com.canonical.Unity.Scope";
/* Methods */
public abstract async ActivationReplyRaw activate (
string channel_id,
Variant[] result_arr,
uint action_type,
HashTable hints,
Cancellable? cancellable = null) throws IOError, ScopeError;
public abstract async HashTable search (
string channel_id,
string search_string,
HashTable hints,
Cancellable? cancellable = null) throws IOError, ScopeError;
public abstract async string open_channel (
uint channel_type,
HashTable hints,
Cancellable? cancellable = null,
out HashTable out_hints,
BusName? sender = null) throws IOError;
public abstract async void close_channel (
string channel_id,
HashTable hints,
Cancellable? cancellable = null) throws IOError, ScopeError;
public abstract async HashTable push_results (
string channel_id,
string search_string,
string source_scope_id,
Variant result_variant,
string[] categories,
Cancellable? cancellable = null) throws IOError, ScopeError;
/* do we still need this? */
public abstract async void set_view_type (uint view_type) throws IOError;
/* Signals */
public signal void category_order_changed (
string channel_id, uint32[] new_order);
public signal void filter_settings_changed (
string channel_id,
[DBus (signature = "a(ssssa{sv}bbb)")] Variant filter_rows);
public signal void results_invalidated (uint channel_type);
/* Properties */
public abstract int protocol_version { get; }
public abstract bool visible { get; }
public abstract bool is_master { get; }
public abstract string search_hint { owned get; }
public abstract HashTable metadata { owned get; }
public abstract HashTable optional_metadata { owned get; }
public abstract Variant categories { owned get; }
public abstract Variant filters { owned get; }
public abstract HashTable hints { owned get; }
}
} /* namespace unity */
libunity-7.1.4+15.10.20151002/doc/ 0000755 0000153 0000161 00000000000 12603351405 016446 5 ustar pbuser pbgroup 0000000 0000000 libunity-7.1.4+15.10.20151002/doc/Makefile.am 0000644 0000153 0000161 00000000025 12603350222 020473 0 ustar pbuser pbgroup 0000000 0000000 SUBDIRS = reference
libunity-7.1.4+15.10.20151002/doc/reference/ 0000755 0000153 0000161 00000000000 12603351405 020404 5 ustar pbuser pbgroup 0000000 0000000 libunity-7.1.4+15.10.20151002/doc/reference/Makefile.am 0000644 0000153 0000161 00000003543 12603350222 022441 0 ustar pbuser pbgroup 0000000 0000000 NULL =
if ENABLE_DOCS
FILES = \
$(wildcard $(top_srcdir)/src/*.vala) \
$(wildcard $(top_srcdir)/extras/*.vala) \
$(NULL)
# earlier versions of valadoc 0.3.2 don't support the valac --version properly
# (yes valadoc 0.3.2 was 0.3.2 for far too long)
DRIVER_VERSION = $(VALADOC_DRIVER)
VALADOC_FLAGS = \
--force \
--target-glib=2.32 \
--driver "$(DRIVER_VERSION)" \
$(LIBUNITY_PACKAGES) \
--vapidir $(top_builddir)/protocol \
--vapidir $(top_srcdir)/vapi \
--vapidir $(top_srcdir)/src \
--vapidir $(top_srcdir)/extras \
--pkg unity-protocol \
--pkg config \
--pkg unity-trace \
--basedir $(top_srcdir)/src \
--package-name unity \
--package-version $(PACKAGE_VERSION) \
$(FILES) \
$(NULL)
LIBUNITY_SO_FILE = $(top_builddir)/src/.libs/libunity.so
LIBUNITY_EXTRAS_SO_FILE = $(top_builddir)/extras/.libs/libunity-extras.so
# the so isn't really a dep, but it's good for making sure the docs are fresh
valadoc: Makefile $(LIBUNITY_SO_FILE) $(LIBUNITY_EXTRAS_SO_FILE)
$(VALADOC) \
-o valadoc \
$(VALADOC_FLAGS) \
$(NULL)
# valadoc doesn't support multiple -l flags; needs to be fixed upstream.
gtkdoc: Makefile $(LIBUNITY_SO_FILE) $(LIBUNITY_EXTRAS_SO_FILE)
$(VALADOC) \
-X $(top_builddir)/src/unity.h \
-X $(top_builddir)/extras/unity-extras.h \
-X -l -X $(LIBUNITY_EXTRAS_SO_FILE) \
-X -l -X $(LIBUNITY_SO_FILE) \
-o gtkdoc \
--doclet gtkdoc \
$(VALADOC_FLAGS) \
$(NULL)
clean-local:
rm -rf valadoc gtkdoc
uninstall-hook:
rm -rf $(DESTDIR)$(datadir)/gtk-doc/html/libunity
# The chmod corrects the directory permissions so that distcheck can remove the installed files.
install-data-hook: gtkdoc
$(MKDIR_P) $(DESTDIR)$(datadir)/gtk-doc/html/libunity
cp -d -R $(builddir)/gtkdoc/html $(DESTDIR)$(datadir)/gtk-doc/html/libunity
chmod -R u+w $(DESTDIR)$(datadir)/gtk-doc/html/libunity
all: valadoc gtkdoc
EXTRA_DIST = gtkdoc valadoc
endif
libunity-7.1.4+15.10.20151002/COPYING.GPL-3 0000644 0000153 0000161 00000104374 12603350222 017522 0 ustar pbuser pbgroup 0000000 0000000
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 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, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
libunity-7.1.4+15.10.20151002/Makefile.decl 0000644 0000153 0000161 00000005562 12603350222 020253 0 ustar pbuser pbgroup 0000000 0000000 # GLIB - Library of useful C routines
#
# This file is copied almost verbatim from the GLib-2.0 distribution
#
GTESTER = gtester
GTESTER_REPORT = gtester-report
# initialize variables for unconditional += appending
EXTRA_DIST =
TEST_PROGS =
### testing rules
# test: run all tests in cwd and subdirs
test: test-nonrecursive
@ for subdir in $(SUBDIRS) . ; do \
test "$$subdir" = "." -o "$$subdir" = "po" || \
( cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $@ ) || exit $? ; \
done
# test-nonrecursive: run tests only in cwd
test-nonrecursive: ${TEST_PROGS}
@test -z "${TEST_PROGS}" || G_DEBUG=gc-friendly MALLOC_CHECK_=2 MALLOC_PERTURB_=$$(($${RANDOM:-256} % 256)) ${GTESTER} --verbose ${TEST_PROGS}
# test-report: run tests in subdirs and generate report
# perf-report: run tests in subdirs with -m perf and generate report
# full-report: like test-report: with -m perf and -m slow
test-report perf-report full-report: ${TEST_PROGS}
@test -z "${TEST_PROGS}" || { \
case $@ in \
test-report) test_options="-k";; \
perf-report) test_options="-k -m=perf";; \
full-report) test_options="-k -m=perf -m=slow";; \
esac ; \
if test -z "$$GTESTER_LOGDIR" ; then \
${GTESTER} --verbose $$test_options -o test-report.xml ${TEST_PROGS} ; \
elif test -n "${TEST_PROGS}" ; then \
${GTESTER} --verbose $$test_options -o `mktemp "$$GTESTER_LOGDIR/log-XXXXXX"` ${TEST_PROGS} ; \
fi ; \
}
@ ignore_logdir=true ; \
if test -z "$$GTESTER_LOGDIR" ; then \
GTESTER_LOGDIR=`mktemp -d "\`pwd\`/.testlogs-XXXXXX"`; export GTESTER_LOGDIR ; \
ignore_logdir=false ; \
fi ; \
REVISION=$(VERSION) ; \
for subdir in $(SUBDIRS) . ; do \
test "$$subdir" = "." -o "$$subdir" = "po" || \
( cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $@ ) || exit $? ; \
done ; \
$$ignore_logdir || { \
echo '' > $@.xml ; \
echo '' >> $@.xml ; \
echo '' >> $@.xml ; \
echo ' $(PACKAGE)' >> $@.xml ; \
echo ' $(VERSION)' >> $@.xml ; \
echo " $$REVISION" >> $@.xml ; \
echo '' >> $@.xml ; \
for lf in `ls -L "$$GTESTER_LOGDIR"/.` ; do \
sed '1,1s/^?]*?>//' <"$$GTESTER_LOGDIR"/"$$lf" >> $@.xml ; \
done ; \
echo >> $@.xml ; \
echo '' >> $@.xml ; \
rm -rf "$$GTESTER_LOGDIR"/ ; \
${GTESTER_REPORT} --version 2>/dev/null 1>&2 ; test "$$?" != 0 || ${GTESTER_REPORT} $@.xml >$@.html ; \
}
.PHONY: test test-report perf-report full-report test-nonrecursive
# run tests in cwd as part of make check
if ENABLE_HEADLESS_TESTS
check-local: test-headless
LOG_PATH = headless-logs
test-headless:
set -e; \
$(XVFB) -a make test-nonrecursive; \
sleep 1;
else
check-local: test-nonrecursive
endif
libunity-7.1.4+15.10.20151002/tools/ 0000755 0000153 0000161 00000000000 12603351405 017041 5 ustar pbuser pbgroup 0000000 0000000 libunity-7.1.4+15.10.20151002/tools/unity-tool-res.gresource.xml 0000644 0000153 0000161 00000000362 12603350222 024467 0 ustar pbuser pbgroup 0000000 0000000
unity-tool.uidbus-scope-connect.ui
libunity-7.1.4+15.10.20151002/tools/Makefile.am 0000644 0000153 0000161 00000003352 12603350222 021074 0 ustar pbuser pbgroup 0000000 0000000 NULL =
BUILT_SOURCES =
CLEANFILES =
EXTRA_DIST =
bin_PROGRAMS = \
libunity-tool
libunity_tool_CPPFLAGS = \
-DG_LOG_DOMAIN=\"libunity-tool\" \
-I$(srcdir) \
-I$(top_builddir)/src \
-I$(top_builddir)/protocol \
$(LIBUNITY_CFLAGS) \
$(UNITYTOOL_CFLAGS)
if !ENABLE_C_WARNINGS
libunity_tool_CPPFLAGS += -w
endif
if ENABLE_TRACE_LOG
libunity_tool_CPPFLAGS += -DENABLE_UNITY_TRACE_LOG
endif
libunity_tool_LDADD = \
$(top_builddir)/src/libunity.la \
$(top_builddir)/protocol/libunity-protocol-private.la \
$(LIBUNITY_LIBS) \
$(UNITYTOOL_LIBS)
libunity_tool_VALAFLAGS = \
-C \
--vapidir $(top_srcdir)/vapi \
--vapidir=$(top_builddir)/protocol \
--vapidir=$(top_builddir)/src \
--pkg config \
--pkg gtk+-3.0 \
--pkg gmodule-2.0 \
--pkg unity-internal \
--pkg unity-protocol \
$(LIBUNITY_PACKAGES) \
$(MAINTAINER_VALAFLAGS)
libunity_tool_VALASOURCES = \
unity-tool.vala \
unity-tool-dbus-util.vala \
unity-tool-ui.vala \
preview-renderer.vala \
music-track-model-renderer.vala \
$(NULL)
libunity_tool_UISOURCES = unity-tool-res.gresource.xml unity-tool.ui dbus-scope-connect.ui
unity-tool-res.c: $(libunity_tool_UISOURCES)
$(AM_V_GEN)$(GLIB_RESCOMPILE) --sourcedir $(srcdir) --target=$@ --generate-source $(filter %.xml,$^)
nodist_libunity_tool_SOURCES = \
$(libunity_tool_VALASOURCES:.vala=.c) \
unity-tool-res.c \
$(NULL)
BUILT_SOURCES += unity-tool-res.c unity_tool_vala.stamp
EXTRA_DIST += \
$(libunity_tool_VALASOURCES) \
$(libunity_tool_UISOURCES) \
$(NULL)
unity_tool_vala.stamp: $(libunity_tool_VALASOURCES)
$(AM_V_GEN) $(VALAC) $(libunity_tool_VALAFLAGS) $^
@touch $@
CLEANFILES += \
unity_tool_vala.stamp \
unity-tool-res.c \
$(libunity_tool_VALASOURCES:.vala=.c) \
$(NULL)
libunity-7.1.4+15.10.20151002/tools/preview-renderer.vala 0000644 0000153 0000161 00000043736 12603350222 023204 0 ustar pbuser pbgroup 0000000 0000000 /*
* Copyright (C) 2012 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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, see .
*
* Authored by Pawel Stolowski
*
*/
using Gtk;
namespace Unity.Tester {
public abstract class PreviewRenderer: Object
{
public signal void preview_action_clicked(string action_id);
public signal void preview_closed_clicked();
public abstract Gtk.Widget get_widget();
public abstract Gtk.Widget get_buttons();
public abstract Gtk.Widget get_extra_buttons();
internal abstract void render_buttons();
internal abstract void render_extra_buttons();
internal abstract void render();
public static PreviewRenderer? create(Unity.Protocol.Preview preview, string scope_uri)
{
if (preview is Unity.Protocol.GenericPreview) {
return new GenericPreviewRenderer(preview as Unity.Protocol.GenericPreview, scope_uri);
}
if (preview is Unity.Protocol.ApplicationPreview) {
return new ApplicationPreviewRenderer(preview as Unity.Protocol.ApplicationPreview, scope_uri);
}
if (preview is Unity.Protocol.MusicPreview) {
return new MusicPreviewRenderer(preview as Unity.Protocol.MusicPreview, scope_uri);
}
if (preview is Unity.Protocol.MoviePreview) {
return new MoviePreviewRenderer(preview as Unity.Protocol.MoviePreview, scope_uri);
}
if (preview is Unity.Protocol.SeriesPreview) {
return new SeriesPreviewRenderer(preview as Unity.Protocol.SeriesPreview, scope_uri);
}
/* fallback - a generic preview renderer */
return new GenericPreviewRenderer(preview, scope_uri);
}
public Unity.Protocol.Preview preview { get; construct; }
public string scope_uri { get; construct; }
}
/**
* Render preview in Gtk.Grid with 2 columns (name and value).
*/
public abstract class GridRenderer: PreviewRenderer
{
public GridRenderer()
{
Object();
}
internal void add_standard_attributes(Unity.Protocol.Preview preview)
{
add_text_row("Title", preview.title);
add_text_row("Subtitle", preview.subtitle);
add_text_row("Description", preview.description);
add_text_row("Image source", preview.image_source_uri);
add_text_icon_row("Image", preview.image, preview.image.to_string(), 512);
}
internal void add_info_hints(Unity.Protocol.Preview preview)
{
Unity.Protocol.InfoHintRaw[] hints = preview.get_info_hints();
add_headline("Info Hint");
foreach (Unity.Protocol.InfoHintRaw hint in hints) {
add_text_row("Id", hint.id);
add_text_row("Display Name", hint.display_name);
add_text_row("Icon hint", hint.icon_hint);
add_text_row("Value", hint.value.print(true));
}
}
/**
* Renders name and value in two adjacent cells of grid row
*/
public void add_text_row(string name, string? value)
{
var name_label = new Gtk.Label(null);
name_label.set_markup(name);
grid.attach(name_label, 0, row, 1, 1);
var value_label = new Gtk.Label(value);
value_label.selectable = true;
grid.attach(value_label, 1, row, 1, 1);
++row;
}
/**
* Renders text in two joined cells of grid row
*/
public void add_headline(string text)
{
var label = new Gtk.Label(null);
label.set_markup(text);
grid.attach(label, 0, row, 2, 1);
++row;
}
/**
* Renders name and arbitrary widget in two adjacent cells of grid row
*/
public void add_widget(string name, Gtk.Widget widget)
{
var name_label = new Gtk.Label(null);
name_label.set_markup(name);
grid.attach(name_label, 0, row, 1, 1);
grid.attach(widget, 1, row, 1, 1);
++row;
}
public void on_preview_action_clicked(Gtk.Button button)
{
string id = preview_actions.get(button);
preview_action_clicked(id);
}
public void on_preview_closed_clicked(Gtk.Button button)
{
preview_closed_clicked();
}
/**
* Renders name and icon in two adjacent cells of grid row
*/
public void add_text_icon_row(string name, GLib.Icon? icon, string? tooltip, int size=32)
{
var icon_label = new Gtk.Label(null);
icon_label.set_markup(name);
grid.attach(icon_label, 0, row, 1, 1);
var themed_icon = Gtk.IconTheme.get_default().lookup_by_gicon(icon, size, 0);
try {
var pixbuf = themed_icon.load_icon();
Gtk.Image image = new Gtk.Image.from_pixbuf(pixbuf);
if (tooltip != null) {
image.set_tooltip_text(tooltip);
}
grid.attach(image, 1, row, 1, 1);
}
catch (GLib.Error e) {
warning(@"Got error while loading pixmap: $(e.message)");
}
++row;
}
public override Gtk.Widget get_widget()
{
render();
grid.foreach((obj) => { obj.set_halign(Gtk.Align.START); });
return grid;
}
public override Gtk.Widget get_buttons()
{
render_buttons();
return preview_actions_box;
}
public override Gtk.Widget get_extra_buttons()
{
render_extra_buttons();
return preview_extra_buttons_box;
}
public override void render_buttons()
{
preview_actions = new GLib.HashTable(null, null);
Unity.Protocol.PreviewActionRaw[] actions = preview.get_actions();
for (int i=0; i preview_actions = null;
}
public class GenericPreviewRenderer: GridRenderer
{
public GenericPreviewRenderer(Unity.Protocol.Preview preview, string scope_uri)
{
Object(preview: preview, scope_uri: scope_uri);
}
internal override void render()
{
assert(preview != null);
base.add_standard_attributes(preview as Unity.Protocol.Preview);
base.add_info_hints(preview as Unity.Protocol.Preview);
}
}
public class ApplicationPreviewRenderer: GridRenderer
{
public ApplicationPreviewRenderer(Unity.Protocol.ApplicationPreview preview, string scope_uri)
{
Object(preview: preview, scope_uri: scope_uri);
}
internal override void render()
{
assert(preview != null);
var app_preview = preview as Unity.Protocol.ApplicationPreview;
base.add_standard_attributes(preview);
base.add_text_row("License", app_preview.license);
base.add_text_row("Copyright", app_preview.copyright);
base.add_text_row("Last update", app_preview.last_update);
base.add_text_row("Rating", "%.2f".printf(app_preview.rating));
base.add_text_row("Number of ratings", "%u".printf(app_preview.num_ratings));
base.add_text_icon_row("Application icon", app_preview.app_icon, app_preview.app_icon.to_string());
base.add_info_hints(app_preview);
}
}
public class MusicPreviewRenderer: GridRenderer
{
private MusicTrackModelRenderer track_model_renderer;
private Gtk.TreeView track_view;
private Gtk.Menu track_view_popup_menu;
public signal void play_music_track_clicked(string uri);
public signal void pause_music_track_clicked(string uri);
public MusicPreviewRenderer(Unity.Protocol.MusicPreview preview, string scope_uri)
{
Object(preview: preview, scope_uri: scope_uri);
}
internal override void render()
{
assert(preview != null);
var music_preview = preview as Unity.Protocol.MusicPreview;
base.add_standard_attributes(preview);
base.add_text_row("Track data swarm name", music_preview.track_model != null ? "<>" : music_preview.track_data_swarm_name);
base.add_text_row("Track data address", music_preview.track_data_address);
base.add_info_hints(music_preview);
if (music_preview.track_model != null)
{
track_model_renderer = new MusicTrackModelRenderer(music_preview.track_model);
track_view = new TreeView();
var track_view_viewport = new Viewport(null, null);
track_view.set_model(track_model_renderer.track_view_model);
track_view.insert_column_with_attributes(-1, "uri", new CellRendererText (), "text", 0);
track_view.insert_column_with_attributes(-1, "track no", new CellRendererText (), "text", 1);
track_view.insert_column_with_attributes(-1, "title", new CellRendererText (), "text", 2);
track_view.insert_column_with_attributes(-1, "length", new CellRendererText (), "text", 3);
track_view.insert_column_with_attributes(-1, "playing", new CellRendererText (), "text", 4);
track_view.insert_column_with_attributes(-1, "progress", new CellRendererText (), "text", 5);
track_view_viewport.add_with_properties(track_view);
add_widget("Track model", track_view_viewport);
track_view_popup_menu = new Gtk.Menu();
var play_item = new Gtk.MenuItem.with_label("Play");
play_item.activate.connect(on_play_item_clicked);
track_view_popup_menu.append(play_item);
play_item.show();
var pause_item = new Gtk.MenuItem.with_label("Pause");
pause_item.activate.connect(on_pause_item_clicked);
track_view_popup_menu.append(pause_item);
pause_item.show();
track_view.button_press_event.connect(on_track_view_right_click);
track_model_renderer.sync();
}
}
public bool on_track_view_right_click(Gtk.Widget widget, Gdk.EventButton event)
{
if (event.type == Gdk.EventType.BUTTON_PRESS && event.button == 3 /* right mouse button */) {
track_view_popup_menu.popup(null, null, null, event.button, event.time);
}
return false;
}
internal string get_selected_track_uri()
{
TreeModel model;
TreeIter iter;
var selection = track_view.get_selection();
if (selection.get_selected(out model, out iter)) {
Value val;
// get uri column
model.get_value(iter, 0, out val);
return val.get_string();
}
return "";
}
internal void on_play_item_clicked(Gtk.MenuItem item)
{
string uri = get_selected_track_uri();
if (uri != "")
{
play_music_track_clicked(uri);
}
}
internal void on_pause_item_clicked(Gtk.MenuItem item)
{
string uri = get_selected_track_uri();
if (uri != "")
{
pause_music_track_clicked(uri);
}
}
}
public class MoviePreviewRenderer: GridRenderer
{
public MoviePreviewRenderer(Unity.Protocol.MoviePreview preview, string scope_uri)
{
Object(preview: preview, scope_uri: scope_uri);
}
internal override void render()
{
assert(preview != null);
var movie_preview= preview as Unity.Protocol.MoviePreview;
base.add_standard_attributes(preview);
base.add_text_row("Rating", "%.2f".printf(movie_preview.rating));
base.add_text_row("Number of ratings", "%u".printf(movie_preview.num_ratings));
base.add_info_hints(movie_preview);
}
}
public class SeriesPreviewRenderer: GridRenderer
{
public signal void change_selected_series_item_clicked(string uri, int index);
public SeriesPreviewRenderer(Unity.Protocol.SeriesPreview preview, string scope_uri)
{
Object(preview: preview, scope_uri: scope_uri);
}
public void update_child_preview(Unity.Protocol.Preview child_preview)
{
(preview as Unity.Protocol.SeriesPreview).child_preview = child_preview;
}
private void on_change_selected_item_clicked(Gtk.ComboBox combo)
{
int index = int.parse(combo.active_id);
var series_preview = preview as Unity.Protocol.SeriesPreview;
if (index != series_preview.selected_item) {
change_selected_series_item_clicked(scope_uri, index);
}
}
internal override void render_extra_buttons()
{
var series_preview = preview as Unity.Protocol.SeriesPreview;
Gtk.Box box = new Gtk.Box(Gtk.Orientation.HORIZONTAL, 5);
Gtk.ComboBoxText items_combo = new Gtk.ComboBoxText();
items_combo.changed.connect(on_change_selected_item_clicked);
Protocol.SeriesItemRaw[] items = series_preview.get_items();
for (int i=0; iSelected item", "%d".printf(series_preview.selected_item));
Protocol.SeriesItemRaw[] items = series_preview.get_items();
PreviewRenderer? child_preview = PreviewRenderer.create(series_preview.child_preview, scope_uri);
if (child_preview != null) {
base.add_widget("Child preview", child_preview.get_widget());
}
for (int i=0; iSeries item #%u".printf(i));
base.add_text_row("Title", items[i].title);
base.add_text_row("Uri", items[i].uri);
if (items[i].icon_hint != null) {
try {
var icon = GLib.Icon.new_for_string(items[i].icon_hint);
base.add_text_icon_row("Icon", icon, items[i].icon_hint.to_string());
}
catch (GLib.Error e) {
stderr.printf("Series Item icon couldn't be loaded: %s\n", e.message);
}
}
}
base.add_info_hints(series_preview);
}
}
}
libunity-7.1.4+15.10.20151002/tools/unity-tool-dbus-util.vala 0000644 0000153 0000161 00000015272 12603350222 023742 0 ustar pbuser pbgroup 0000000 0000000 namespace Unity.Tester {
public class DBusLensUtil
{
const MarkupParser parser = {
start,
null, /* end */
null, /* text */
null, /* comment */
null /* error */
};
public struct DBusObjectAddress {
string dbus_name;
string dbus_path;
}
public DBusLensUtil()
{
try {
scope_dbusname_regex = new Regex("^.+[.]Scope[.][a-zA-Z.]+$");
}
catch (Error e) {
stderr.printf("Error parsing scope_dbusname_regex");
}
}
/**
* Discover available DBus services
*/
private List getServices() throws GLib.Error
{
List services = new List();
var vt = new VariantType ("(as)");
var bus = Bus.get_sync (BusType.SESSION);
Variant v = bus.call_sync("org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
"ListNames",
null,
vt,
0,
-1,
null);
string *[]names = v.get_child_value(0).get_strv();
foreach (string *s in names) {
services.append(s);
}
return services;
}
private void start(MarkupParseContext context, string name, string[] attr_names, string[] attr_values) throws MarkupError {
if (name == "node") {
for (int i=0; i {
return a.dbus_name == b.dbus_name && a.dbus_path == b.dbus_path ? 0 : 1; })
.length() == 0) {
lenses.append(obj);
}
}
}
}
}
/**
* Find objects implementing com.canonical.Unity.Lens interface
*/
public async unowned List findLenses() throws GLib.Error
{
if (scope_dbusname_regex == null) {
stderr.printf("Invalid scope_dbusname_regex");
return lenses;
}
var bus = Bus.get_sync (BusType.SESSION);
var vt = new VariantType ("(s)");
//
// Service filtering - potential lenses must match this regexp;
// e.g. com.canonical.Unity.Lens.applications.T1338793992370.Results
foreach (string srv in getServices()) {
if (scope_dbusname_regex.match(srv)) {
try {
var vb = new VariantBuilder(new VariantType("(s)"));
vb.add_value(srv);
Variant v = bus.call_sync(
"org.freedesktop.DBus",
"/",
"org.freedesktop.DBus",
"GetNameOwner",
vb.end(),
vt,
0,
10,
null);
if (v != null) {
string owner = v.get_child_value(0).get_string();
if (owner != null) {
DBusObjectAddress obj = DBusObjectAddress() {
dbus_name = owner,
dbus_path = "/"
};
nodes.push_tail(obj);
}
}
}
catch (Error e) {
// silently ignore
}
}
}
//
// introspect all dbus paths from nodes queue.
// queue may grow as new paths are discovered.
while (nodes.length > 0) {
DBusObjectAddress node = nodes.pop_head();
current_dbus_name = node.dbus_name;
current_dbus_path = node.dbus_path;
try {
Variant v = bus.call_sync(current_dbus_name,
current_dbus_path,
"org.freedesktop.DBus.Introspectable",
"Introspect",
null,
vt,
0,
10,
null);
if (v != null) {
string xmldata = v.get_child_value(0).get_string();
var context = new MarkupParseContext (parser, MarkupParseFlags.TREAT_CDATA_AS_TEXT, this, null);
context.parse (xmldata, xmldata.length);
}
}
catch (Error e) {
// silently ignore
}
Idle.add(findLenses.callback);
yield;
}
return lenses;
}
private Regex scope_dbusname_regex;
private string current_dbus_name;
private string current_dbus_path;
private Queue nodes = new Queue();
private List lenses = new List();
}
}
libunity-7.1.4+15.10.20151002/tools/unity-tool.ui 0000644 0000153 0000161 00000136167 12603350222 021535 0 ustar pbuser pbgroup 0000000 0000000
FalseLibunity Toolcenter640380TrueFalseverticalTrueFalseTrueFalse_FileTrueTrueFalsegtk-newTrueFalseTrueTrueTrueFalsegtk-quitTrueFalseTrueTrueTrueFalse_EditTrueTrueFalseTrueFalseClear LogTrueFalseTrue0TrueFalse6TrueFalse5TrueFalseScope queryFalseTrue50TrueTrue•TrueTrueTrue1TrueTrue0TrueFalse5TrueFalseTypeFalseTrue0LocalTrueTrueFalse00.55000001192092896TrueTrueFalseTrue1GlobalTrueTrueFalse0Truesearch_type_localFalseTrue2FalseTrue52TrueFalseResultsTrueTrueTrueRead current results without issuing searchFalseTrue0SearchTrueTrueTrueTrueTrueRun Scope search query and read results10.52999997138977051rightFalseTrue1FalseTrue3False44FalseFalseend4FalseTrue1TrueTrue66TrueFalseinTrueTrueresults_modelFalseFalse0FalseTrue510uri0Trueicon-hint1Truecategory-index2result-type3Truemimetype4Truename5Truecommentdescending6Truednd-uri7True510metadata8TrueFalseResults modelFalseTrueTrueinTrueTruefilters_modelFalseFalse0FalsehorizontalTrue510id0Truename1Trueicon_hint2Truerenderer name3Trueautosizerenderer state4Truevisibledescending5Truecollapsed6Truefiltering71TrueFalseFilters model1FalseTrueTrueinTrueTruecategories_modelid0True32name1True32icon_hint2True32renderer3True32hints42TrueFalseCategories model2FalseTrueFalse<<TrueFalseTrueTrueFalseTrue0TrueFalseTruevertical10TrueFalse0noneTrueFalse12TrueFalse<b>Preview actions</b>TrueFalseTrue0TrueFalseFalseTrue1TrueFalse0noneTrueFalse12TrueFalse<b>Preview signals</b>TrueFalseTrue2FalseTrue1TrueTrueTrueTruebottomTrueTrueinTrueFalseTrueFalseRenderedFalseTrueTrueneverinTrueTrueFalsecharpreview_raw_data1TrueFalseRaw data1FalseFalseTrue2>>TrueFalseTrueTrueFalseTrue33TrueFalsePreview3FalseTrueTrueinTrueTrueFalseFalselog_buffer4TrueFalseLog4FalseTrueTrue2TrueFalsevertical2FalseTrue3
libunity-7.1.4+15.10.20151002/tools/unity-tool-ui.vala 0000644 0000153 0000161 00000101154 12603350222 022442 0 ustar pbuser pbgroup 0000000 0000000 /*
* Copyright (C) 2012 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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, see .
*
* Authored by Pawel Stolowski
*
*/
using Gtk;
namespace Unity.Tester {
public class UnityToolUi: GLib.Object
{
public UnityToolUi()
{
}
public bool init_gui()
{
var builder = new Builder ();
try {
builder.add_from_resource("/com/canonical/Unity/unity-tool/unity-tool.ui");
builder.connect_signals(this);
spinner = builder.get_object ("spinner") as Spinner;
var window = builder.get_object ("window") as Window;
window.destroy.connect(Gtk.main_quit);
window.show_all();
uimodel = builder.get_object("results_model") as Gtk.ListStore;
ui_filter_model = builder.get_object("filters_model") as Gtk.ListStore;
ui_cat_model = builder.get_object("categories_model") as Gtk.ListStore;
notebook = builder.get_object("notebook") as Notebook;
search_entry = builder.get_object("search_entry") as Entry;
search_type_global_rbutton = builder.get_object("search_type_global") as RadioButton;
search_button = builder.get_object("search_button") as Button;
results_button = builder.get_object("results_button") as Button;
prev_preview_button = builder.get_object("prev_preview_btn") as Button;
next_preview_button = builder.get_object("next_preview_btn") as Button;
statusbar = builder.get_object("statusbar") as Statusbar;
log_buffer = builder.get_object("log_buffer") as TextBuffer;
preview_raw_data = builder.get_object("preview_raw_data") as TextBuffer;
preview_buttons_container = builder.get_object("preview_buttons_container") as Alignment;
preview_extra_buttons_container = builder.get_object("preview_extra_buttons_container") as Alignment;
preview_viewport = builder.get_object("preview_viewport") as Viewport;
assert(preview_viewport != null);
results_view = builder.get_object("results_view") as TreeView;
results_view_selection = builder.get_object("results_view_selection") as TreeSelection;
results_popup_menu = builder.get_object("results_popup_menu") as Gtk.Menu;
statusbar_info_ctx = statusbar.get_context_id("Info");
statusbar_error_ctx = statusbar.get_context_id("Error");
show_no_preview();
show_connect_dialog();
}
catch (GLib.Error e) {
ui_load_error(e.message);
return false;
}
return true;
}
private void ui_load_error(string message)
{
Gtk.Dialog dlg = new Gtk.MessageDialog(null,
Gtk.DialogFlags.DESTROY_WITH_PARENT | Gtk.DialogFlags.MODAL,
Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE,
"Error loading UI file:\n%s".printf(message));
dlg.title = "Error creating UI";
dlg.run();
dlg.destroy();
}
private void discover_scope()
{
scope_discovery_spinner.start();
TreeIter iter;
scope_list_model.append(out iter);
scope_list_model.set(iter, 0,"", 1, "", -1); //add empty combobox entry
DBusLensUtil c = new DBusLensUtil();
c.findLenses.begin((obj, res) => {
try {
unowned List results = c.findLenses.end(res);
foreach (DBusLensUtil.DBusObjectAddress addr in results) {
scope_list_model.append(out iter);
scope_list_model.set(iter, 0, addr.dbus_name, 1, addr.dbus_path, -1);
}
scope_discovery_spinner.stop();
}
catch (Error e) {
stderr.printf("DBus Lens auto-discovery failed %s\n", e.message);
scope_discovery_spinner.stop();
}
});
}
[CCode (instance_pos = -1)]
public void on_scope_combobox_clicked(Gtk.MenuItem item)
{
TreeIter iter;
if (scope_list_combobox.get_active() > 0) { // ignore first empty item
if (scope_list_combobox.get_active_iter(out iter)) {
Value val;
scope_list_model.get_value(iter, 0, out val);
dbus_name_entry.text = val.get_string();
scope_list_model.get_value(iter, 1, out val);
dbus_path_entry.text = val.get_string();
}
}
}
//
// Handler for File > New menu item.
[CCode (instance_pos = -1)]
public void on_connect_clicked(Gtk.MenuItem item)
{
show_connect_dialog();
}
/**
* Handler for Edit > Clear Log menu item.
*/
[CCode (instance_pos = -1)]
public void on_clear_log_clicked(Gtk.MenuItem item)
{
Gtk.TextIter start;
Gtk.TextIter end;
log_buffer.get_start_iter(out start);
log_buffer.get_end_iter(out end);
log_buffer.delete(ref start, ref end);
}
private void show_connect_dialog()
{
var builder = new Builder ();
try {
builder.add_from_resource("/com/canonical/Unity/unity-tool/dbus-scope-connect.ui");
builder.connect_signals(this);
scope_discovery_spinner = builder.get_object("scope_discovery_spinner") as Spinner;
scope_list_model = builder.get_object("scope_list_model") as Gtk.ListStore;
scope_list_combobox = builder.get_object("scope_list_combobox") as ComboBox;
dbus_name_entry = builder.get_object("dbus_name_entry") as Entry;
dbus_path_entry = builder.get_object("dbus_path_entry") as Entry;
scope_connect_dlg = builder.get_object("scope_connect_dialog") as Dialog;
discover_scope();
if (Options.scope_dbus_path != null && Options.scope_dbus_path != "" && Options.scope_dbus_name != null && Options.scope_dbus_name != "") {
dbus_name_entry.text = Options.scope_dbus_name;
dbus_path_entry.text = Options.scope_dbus_path;
}
scope_connect_dlg.show_all();
}
catch (GLib.Error e) {
ui_load_error(e.message);
}
}
private void results_row_added_cb(Dee.Model model, Dee.ModelIter iter)
{
var row = model.get_row(iter);
TreeIter uiiter;
uimodel.append(out uiiter);
uimodel.set(uiiter, 0, row[0].get_string(),
1, row[1].get_string(),
2, row[2].get_uint32(),
3, row[3].get_uint32(),
4, row[4].get_string(),
5, row[5].get_string(),
6, row[6].get_string(),
7, row[7].get_string(),
8, row[8].print (true),
-1);
}
private void filters_row_added_cb(Dee.Model model, Dee.ModelIter iter)
{
var row = model.get_row(iter);
TreeIter uiiter;
ui_filter_model.append(out uiiter);
ui_filter_model.set(uiiter, 0, row[0].get_string (),
1, row[1].get_string (),
2, row[2].get_string (),
3, row[3].get_string (),
4, row[4].print (true),
5, row[5].get_boolean (),
6, row[6].get_boolean (),
7, row[7].get_boolean (), -1);
}
private void categories_row_added_cb(Dee.Model model, Dee.ModelIter iter)
{
var row = model.get_row(iter);
TreeIter uiiter;
ui_cat_model.append(out uiiter);
ui_cat_model.set(uiiter, 0, row[0].get_string (),
1, row[1].get_string (),
2, row[2].get_string (),
3, row[3].get_string (),
4, row[4].print (true), -1);
}
private void update_status()
{
statusbar.pop(statusbar_info_ctx);
statusbar.push(statusbar_info_ctx, "%u records".printf(dee_results_model.get_n_rows()) + ", DBus name: " + Options.scope_dbus_name + " path: " +
Options.scope_dbus_path);
}
private void model_synchronized_cb()
{
spinner.stop();
update_status();
append_log_message("Search returned %u records\n".printf(dee_results_model.get_n_rows()));
dee_results_model = null;
}
private void filter_model_synchronized_cb()
{
dee_filters_model = null;
}
private void categories_model_synchronized_cb()
{
dee_categories_model = null;
}
private void on_scope_service_vanished(GLib.DBusConnection connection, string name)
{
handle_error("Disconnected from %s".printf(name));
GLib.Bus.unwatch_name(dbus_watcher_id);
dbus_watcher_id = 0;
scope_proxy = null;
clear_data();
clear_categories_and_filters();
remove_preview();
show_no_preview();
disable_ui_actions_on_error_condition();
}
private void disable_ui_actions_on_error_condition()
{
if (scope_proxy == null || Options.scope_dbus_path == null || Options.scope_dbus_path.length == 0 || Options.scope_dbus_name == null || Options.scope_dbus_name.length == 0) {
search_entry.sensitive = false;
results_button.sensitive = false;
search_button.sensitive = false;
} else {
search_entry.sensitive = true;
results_button.sensitive = true;
search_button.sensitive = true;
}
}
/**
* Triggered by clicking 'Ok' in the connection dialog.
*/
[CCode (instance_pos = -1)]
public void on_scope_connect(Gtk.Dialog dlg, int response)
{
//
// user clicked 'Ok' in the Lens Connect dialog
if (response == 1) {
clear_data();
clear_categories_and_filters();
remove_preview();
show_no_preview();
Options.scope_dbus_name = dbus_name_entry.text;
Options.scope_dbus_path = dbus_path_entry.text;
scope_proxy = null;
DBusConnection? bus = null;
try
{
bus = Bus.get_sync(BusType.SESSION);
scope_proxy = bus.get_proxy_sync(Options.scope_dbus_name, Options.scope_dbus_path);
if (dbus_watcher_id > 0) {
GLib.Bus.unwatch_name(dbus_watcher_id);
}
dbus_watcher_id = GLib.Bus.watch_name(GLib.BusType.SESSION, Options.scope_dbus_name, GLib.BusNameWatcherFlags.AUTO_START, null, on_scope_service_vanished);
/* read global models */
dee_filters_model = Dee.Serializable.parse(scope_proxy.filters, typeof(Dee.SequenceModel)) as Dee.SerializableModel;
for (var iter = dee_filters_model.get_first_iter();
iter != dee_filters_model.get_last_iter();
iter = dee_filters_model.next(iter))
filters_row_added_cb(dee_filters_model, iter);
dee_categories_model = Dee.Serializable.parse(scope_proxy.categories, typeof(Dee.SequenceModel)) as Dee.SerializableModel;
for (var iter = dee_categories_model.get_first_iter();
iter != dee_categories_model.get_last_iter();
iter = dee_categories_model.next(iter))
categories_row_added_cb(dee_categories_model, iter);
var is_global = search_type_global_rbutton.get_active();
scope_proxy.open_channel.begin(is_global ? 1 : 0, new HashTable(null, null), null, null, (obj, res) =>
{
var proxy = obj as Protocol.ScopeService;
HashTable hints;
current_channel_id = proxy.open_channel.end(res, out hints);
string model_name = hints["model-swarm-name"].get_string();
current_swarm_name = model_name;
});
append_log_message("Connected to: %s, %s\n".printf(Options.scope_dbus_name, Options.scope_dbus_path));
}
catch (GLib.IOError e) {
handle_error(e.message);
}
}
disable_ui_actions_on_error_condition();
dlg.destroy();
}
/**
* Triggered by clicking 'From scope file' button in the connection dialog.
* Opens file browser letting the user pick a .scope file.
*/
[CCode (instance_pos = -1)]
public void on_from_scope_clicked(Gtk.Button btn)
{
var filter = new FileFilter();
filter.set_name("Scope files");
filter.add_pattern("*.scope");
var file_chooser = new FileChooserDialog("Open Lens file", null, Gtk.FileChooserAction.OPEN, Gtk.Stock.CANCEL, 0, Gtk.Stock.OPEN, 1);
file_chooser.set_filter(filter);
if (file_chooser.run() == 1) {
try {
get_scope_params_from_file(file_chooser.get_filename());
dbus_name_entry.text = Options.scope_dbus_name;
dbus_path_entry.text = Options.scope_dbus_path;
}
catch (Error e) {
Gtk.Dialog dlg = new Gtk.MessageDialog(null,
Gtk.DialogFlags.DESTROY_WITH_PARENT | Gtk.DialogFlags.MODAL,
Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE,
"Error loading scope parameters from file:\n%s".printf(e.message));
dlg.title = "Error loading scope file";
dlg.run();
dlg.destroy();
}
}
file_chooser.destroy();
}
/**
* Appends log message to 'Log' tab.
*/
private void append_log_message(string message)
{
TextIter iter;
log_buffer.get_end_iter(out iter);
log_buffer.insert(ref iter, message, -1);
}
/**
* Clears all models, removing all search results.
*/
private void clear_data()
{
if (dee_results_model != null) {
dee_results_model = null;
}
uimodel.clear();
}
private void clear_categories_and_filters()
{
if (dee_filters_model != null) {
dee_filters_model = null;
}
if (dee_categories_model != null) {
dee_categories_model = null;
}
ui_filter_model.clear();
ui_cat_model.clear();
}
[CCode (instance_pos = -1)]
public void on_results_button_clicked(Gtk.Button btn)
{
clear_data();
remove_preview();
}
/**
* Triggered by clicking 'Search' button. Starts scope search over dbus.
*/
[CCode (instance_pos = -1)]
public void on_search_button_clicked(Gtk.Button btn)
{
string text = search_entry.text;
spinner.start();
if (DBus.is_name(Options.scope_dbus_name) && GLib.Variant.is_object_path(Options.scope_dbus_path)) {
append_log_message("Query: '%s' (%s), DBus name: %s, DBus path: %s\n".printf(
text,
search_type_global_rbutton.get_active() ? "global" : "local",
Options.scope_dbus_name,
Options.scope_dbus_path));
remove_preview();
show_no_preview();
clear_data();
var is_global_search = search_type_global_rbutton.get_active();
scope_proxy.search.begin(current_channel_id, text,
new HashTable(null, null),
null, (obj, res) =>
{
try {
var proxy = obj as Protocol.ScopeService;
var result = proxy.search.end(res);
dee_results_model = new Dee.SharedModel(current_swarm_name);
model_sync_sig_id = dee_results_model.notify["synchronized"].connect(model_synchronized_cb);
dee_results_model.row_added.connect(results_row_added_cb);
var msg = "Search reply: %s\n".printf (dump_ht_reply(result));
append_log_message(msg);
}
catch (Error e) {
handle_error(e.message);
}
});
} else {
handle_error("Invalid DBus name/path");
}
}
private static string dump_ht_reply(HashTable reply)
{
var bld = new StringBuilder("{\n");
reply.foreach((k, v) => {
bld.append_printf("\t%s = %s", k, v.print(true));
});
bld.append("\n}");
return bld.str;
}
private static string dump_activation_reply(Unity.Protocol.ActivationReplyRaw reply)
{
var bld = new StringBuilder();
string handled_str = ((EnumClass) typeof (Unity.HandledType).class_ref()).get_value((int)reply.handled).value_name;
bld.append_printf("ActivationReplyRaw: {\n\turi=%s,\n\thandled=%s,\n\thints={\n\t", reply.uri, handled_str);
reply.hints.foreach((k, v) => {
bld.append_printf("\t\t%s = %s", k, v.print(true));
});
bld.append("\n\t}\n}");
return bld.str;
}
/**
* Helper method that stops spinner and puts error message on statusbar.
*/
private void handle_error(string message)
{
spinner.stop();
statusbar.pop(statusbar_error_ctx);
statusbar.push(statusbar_error_ctx, message);
append_log_message(message + "\n");
}
/**
* Helper method to workaround vala-0.16 & vala-0.17 bug -
* fix is coming to vala - see http://git.gnome.org/browse/vala/commit/?id=79925e1174d62d740ca8f360f489dd1660ea5881
*/
private async void send_activate (string channel_id, Variant[] result_arr, uint action_type, HashTable? hints_, out Unity.Protocol.ActivationReplyRaw reply) throws GLib.IOError
{
var hints = hints_;
if (hints == null) {
hints = new HashTable (null, null);
}
reply = yield scope_proxy.activate (channel_id, result_arr,
action_type, hints);
}
private async void send_update (string channel_id, string uri, HashTable props, out HashTable reply) throws GLib.IOError
{
// TODO: handle locally, same way the dash does
warning ("Unimplemented preview update for %s", uri);
}
private void activate_preview(string channel_id, Variant[] result_arr)
{
// call scope activate over dbus
Unity.Protocol.ActivationReplyRaw? reply_struct = null;
send_activate.begin(channel_id, result_arr,
Unity.Protocol.ActionType.PREVIEW_RESULT, null,
(obj, res) => {
try {
send_activate.end(res, out reply_struct);
preview_scope_uri = reply_struct.uri;
handle_activation_reply(reply_struct);
notebook.set_current_page(3); //activate 'Preview' tab
}
catch (GLib.IOError e) {
handle_error(e.message);
}
});
}
private void update_next_prev_buttons(TreeModel model, TreeIter cur_iter)
{
TreeIter iter;
iter = cur_iter;
prev_preview_button.sensitive = model.iter_previous(ref iter);
iter = cur_iter;
next_preview_button.sensitive = model.iter_next(ref iter);
}
/**
* Handler for 'Request preview' context menu item.
*/
[CCode (instance_pos = -1)]
public void on_request_preview(Gtk.MenuItem item)
{
TreeModel model;
TreeIter iter;
if (results_view_selection.get_selected(out model, out iter)) {
last_active_model = model;
last_active_iter = iter;
activate_preview(current_channel_id,
get_selected_result_variant (results_view_selection));
update_next_prev_buttons(model, iter);
}
}
/**
* Handler for 'Request preview' context menu item.
*/
[CCode (instance_pos = -1)]
public void on_prev_preview_clicked(Gtk.Button button)
requires (last_active_model != null)
{
TreeModel model = last_active_model;
TreeIter iter = last_active_iter;
if (last_active_model.iter_previous (ref iter)) {
last_active_iter = iter;
results_view_selection.select_iter (iter);
var result_arr = get_selected_result_variant (results_view_selection);
activate_preview(current_channel_id, result_arr);
update_next_prev_buttons(model, iter);
}
}
/**
* Handler for 'Request preview' context menu item.
*/
[CCode (instance_pos = -1)]
public void on_next_preview_clicked(Gtk.MenuItem item)
requires (last_active_model != null)
{
TreeModel model = last_active_model;
TreeIter iter = last_active_iter;
if (last_active_model.iter_next (ref iter)) {
last_active_iter = iter;
results_view_selection.select_iter (iter);
var result_arr = get_selected_result_variant (results_view_selection);
activate_preview(current_channel_id, result_arr);
update_next_prev_buttons(model, iter);
}
}
/**
* Handler for 'Activate result' context menu item.
*/
[CCode (instance_pos = -1)]
public void on_activate_result(Gtk.MenuItem item)
{
var result_arr = get_selected_result_variant (results_view_selection);
//
// call scope activate over dbus
//
Unity.Protocol.ActivationReplyRaw? reply_struct = null;
send_activate.begin(current_channel_id, result_arr, Unity.Protocol.ActionType.ACTIVATE_RESULT, null, (obj, res) => {
try {
send_activate.end(res, out reply_struct);
handle_activation_reply(reply_struct);
}
catch (GLib.IOError e) {
handle_error(e.message);
}
});
}
private Variant[] get_selected_result_variant (Gtk.TreeSelection selection)
{
Variant[] result_props = new Variant[9];
TreeModel model;
TreeIter iter;
if (selection.get_selected(out model, out iter)) {
Value value;
// Convert model row to variant array
model.get_value(iter, 0, out value);
result_props[0] = value.get_string ();
model.get_value(iter, 1, out value);
result_props[1] = value.get_string ();
model.get_value(iter, 2, out value);
result_props[2] = value.get_uint ();
model.get_value(iter, 3, out value);
result_props[3] = value.get_uint ();
model.get_value(iter, 4, out value);
result_props[4] = value.get_string ();
model.get_value(iter, 5, out value);
result_props[5] = value.get_string ();
model.get_value(iter, 6, out value);
result_props[6] = value.get_string ();
model.get_value(iter, 7, out value);
result_props[7] = value.get_string ();
model.get_value(iter, 8, out value);
result_props[8] = Variant.parse (null, value.get_string ());
}
return result_props;
}
/**
* Render preview and action buttons depending on preview type (if applicable); log reply.
*/
private void handle_activation_reply(Unity.Protocol.ActivationReplyRaw reply_struct)
{
append_log_message("Activate reply: " + dump_activation_reply(reply_struct) + "\n");
if (reply_struct.handled == Unity.HandledType.SHOW_PREVIEW) {
if (reply_struct.hints.contains("preview")) {
handle_preview(reply_struct.hints["preview"]);
} else {
handle_error("Reply hints don't contain preview element");
}
} else {
remove_preview();
show_no_preview();
}
}
private void handle_preview(Variant preview_var)
{
Unity.Protocol.Preview? reconstructed = Unity.Protocol.Preview.parse(preview_var);
preview_raw_data.set_text(preview_var.print(true));
preview_renderer = PreviewRenderer.create(reconstructed, preview_scope_uri);
update_preview();
}
private void update_preview()
{
remove_preview();
if (preview_renderer != null) {
preview_renderer.preview_action_clicked.connect(on_preview_action_clicked);
preview_renderer.preview_closed_clicked.connect(on_preview_closed_clicked);
if (preview_renderer is SeriesPreviewRenderer) {
((SeriesPreviewRenderer)preview_renderer).change_selected_series_item_clicked.connect(on_change_selected_series_item_clicked);
}
else if (preview_renderer is MusicPreviewRenderer) {
var renderer = preview_renderer as MusicPreviewRenderer;
renderer.play_music_track_clicked.connect(on_play_music_track_clicked);
renderer.pause_music_track_clicked.connect(on_pause_music_track_clicked);
}
preview_viewport.add_with_properties(preview_renderer.get_widget());
preview_viewport.show_all();
preview_buttons_container.add_with_properties(preview_renderer.get_buttons());
preview_buttons_container.show_all();
preview_extra_buttons_container.add_with_properties(preview_renderer.get_extra_buttons());
preview_extra_buttons_container.show_all();
} else {
handle_error("Unknown preview type");
show_no_preview();
}
}
private void show_no_preview()
{
preview_renderer = null;
preview_raw_data.set_text("");
var box = new Gtk.Box(Gtk.Orientation.HORIZONTAL, 0);
var label = new Gtk.Label("No preview");
box.pack_start(label);
preview_viewport.add_with_properties(box);
box.show_all();
}
/**
* Destroys all preview objects in the 'Render' tab.
*/
private void remove_preview()
{
preview_viewport.foreach((obj) => { obj.destroy(); });
// remove preview buttons
preview_buttons_container.foreach((btn) => { btn.destroy(); });
preview_extra_buttons_container.foreach((btn) => { btn.destroy(); });
}
private void on_preview_closed_clicked(PreviewRenderer renderer)
{
renderer.preview.begin_updates();
renderer.preview.preview_closed();
handle_preview_signals(renderer.preview.end_updates_as_hashtable());
remove_preview();
}
private void on_preview_action_clicked(PreviewRenderer renderer, string action_id)
{
Unity.Protocol.ActivationReplyRaw? reply_struct = null;
var hints = new HashTable(null, null);
hints.insert("preview-action-id", action_id);
send_activate.begin(current_channel_id, get_selected_result_variant (results_view_selection), Unity.Protocol.ActionType.PREVIEW_ACTION, hints, (obj, res) => {
try {
send_activate.end(res, out reply_struct);
handle_activation_reply(reply_struct);
}
catch (GLib.IOError e) {
handle_error(e.message);
}
});
}
private void on_play_music_track_clicked(MusicPreviewRenderer renderer, string uri)
{
var player = new Protocol.PreviewPlayer ();
player.play.begin (uri);
}
private void on_pause_music_track_clicked(MusicPreviewRenderer renderer, string uri)
{
var player = new Protocol.PreviewPlayer ();
player.pause.begin ();
}
private void handle_preview_signals(HashTable props)
{
HashTable? ht = null;
send_update.begin(current_channel_id, preview_scope_uri, props, (obj, res) => {
try {
send_update.end(res, out ht);
if (ht != null) {
append_log_message("UpdatePreviewProperty reply: " + dump_ht_reply(ht) + "\n"); //TODO: do we expect any reply?
}
}
catch (GLib.IOError e) {
handle_error(e.message);
}
});
}
private void on_change_selected_series_item_clicked(SeriesPreviewRenderer renderer, string uri, int index)
{
var props = new HashTable(str_hash, str_equal);
props["series-active-index"] = new Variant.int32(index);
HashTable? ht = null;
send_update.begin(current_channel_id, uri, props, (obj, res) => {
try {
send_update.end(res, out ht);
if (ht != null) {
append_log_message("UpdatePreviewProperty reply: " + dump_ht_reply(ht) + "\n");
if (ht.contains("preview")) {
if (preview_renderer is SeriesPreviewRenderer) {
(preview_renderer as SeriesPreviewRenderer).update_child_preview(Unity.Protocol.Preview.parse(ht["preview"]));
update_preview();
}
}
}
}
catch (GLib.IOError e) {
handle_error(e.message);
}
});
}
/**
* Handle 'Request preview' context menu action.
*/
[CCode (instance_pos = -1)]
public void on_results_popup_request(Gtk.Widget widget)
{
}
/**
* Handles right mouse button click event in 'Results' tab.
*/
[CCode (instance_pos = -1)]
public bool on_results_right_click(Gtk.Widget widget, Gdk.EventButton event)
{
if (event.type == Gdk.EventType.BUTTON_PRESS && event.button == 3 /* right mouse button */) {
results_popup_menu.popup(null, null, null, event.button, event.time);
}
return false;
}
private PreviewRenderer preview_renderer = null;
private Protocol.ScopeService scope_proxy = null;
private uint dbus_watcher_id = 0;
private string preview_scope_uri;
private Gtk.Notebook notebook = null;
private Gtk.Viewport preview_viewport = null;
private Gtk.TreeSelection results_view_selection = null;
private Gtk.Alignment preview_buttons_container = null;
private Gtk.Alignment preview_extra_buttons_container = null;
private Gtk.TextBuffer preview_raw_data = null;
private Gtk.Menu results_popup_menu = null;
private Gtk.TreeView results_view = null;
private Gtk.RadioButton search_type_global_rbutton = null;
private Gtk.Dialog scope_connect_dlg = null;
private Gtk.Spinner spinner = null;
private Gtk.Spinner scope_discovery_spinner = null;
private Gtk.Button search_button = null;
private Gtk.Button results_button = null;
private Gtk.Button prev_preview_button = null;
private Gtk.Button next_preview_button = null;
private Gtk.Statusbar statusbar = null;
private Gtk.TextBuffer log_buffer = null;
private uint statusbar_info_ctx;
private uint statusbar_error_ctx;
private Gtk.Entry search_entry = null;
private Gtk.Entry dbus_name_entry = null;
private Gtk.Entry dbus_path_entry = null;
private Gtk.ComboBox scope_list_combobox = null;
private Gtk.ListStore uimodel = null;
private Gtk.ListStore ui_filter_model = null;
private Gtk.ListStore scope_list_model = null;
private Gtk.ListStore ui_cat_model = null;
private ulong model_sync_sig_id;
private Dee.SharedModel? dee_results_model = null;
private string current_channel_id = "";
private string current_swarm_name = "";
private Dee.SerializableModel? dee_filters_model = null;
private Dee.SerializableModel? dee_categories_model = null;
private TreeModel? last_active_model = null;
private TreeIter? last_active_iter = null;
}
}
libunity-7.1.4+15.10.20151002/tools/capture-trace.py 0000755 0000153 0000161 00000017263 12603350222 022162 0 ustar pbuser pbgroup 0000000 0000000 #!/usr/bin/env python
import os, sys
import subprocess
import re
"""
# This script has two modes of operation:
#
# 1) Capture a trace and generate a html visualization.
# To use this mode just run `./capture_trace.py`. This will setup a lttng
# session, enable all userspace trace events and spawns a subshell where
# you can for example run libunity-tool to perform a search on a scope.
# When the subshell exits, tracing is stopped and visualization is generated.
#
# 2) Only generate a html visualization of a previously captured trace.
# Use `./capture_trace.py /path/to/lttng/trace_dir`.
#
# Note that use use the first mode you need to have lttng installed
# and libunity compiled with --enable-lttng option.
# Required packages (besides requirements for libunity's --enable-lttng):
# sudo apt-get install lttng-tools babeltrace
"""
"""
# --- Manually capturing a trace
# lttng create session_name
# lttng enable-event -u -a
# lttng start
# --- start home scope with lttng-enabled branch of libunity, perform a search
# lttng stop
# lttng destroy
# --- view the trace in cli
# babeltrace ~/lttng_traces/
"""
def capture_lttng_trace():
session = subprocess.check_output(["lttng", "create", "libunity-trace"], stdin=subprocess.PIPE)
trace_started = False
try:
subprocess.check_output(["lttng", "enable-event", "-u", "-a"], stdin=subprocess.PIPE)
subprocess.check_output(["lttng", "start"], stdin=subprocess.PIPE)
trace_started = True
sys.stderr.write("Trace running... Close this sub-shell with Ctrl+D to finish\n")
subprocess.check_call(["bash"]) # let this inherit our stdin
except subprocess.CalledProcessError as cpe:
if trace_started:
# bash will return non-zero exit code if you for example Ctrl+C
# a program within it, let's just ignore those errors
msg = "Warning: subshell returned error: " + str(cpe.returncode)
sys.stderr.write(msg + "\n")
else: raise
finally:
if trace_started:
subprocess.check_output(["lttng", "stop"], stdin=subprocess.PIPE)
subprocess.check_output(["lttng", "destroy", "libunity-trace"], stdin=subprocess.PIPE)
match = re.findall(r'Traces will be written in (.+)', session)
if len(match) > 0: return match[0]
return None
# trace event example
"""
[20:00:30.697493680] (+0.000014138) miso-ThinkPad:unity-scope-hom:26439 libunity:message: { cpu_id = 0 }, { message = "flush::com.canonical.Unity.Master.Scope.home.T296521243842038" }
"""
def parse_trace_line(line):
pattern = re.compile(r'^\[(?P[0-9:\.]+)\].+?{ message = "(?P[^"]+)"')
match = pattern.match(line)
timestamp = match.group("timestamp")
msg = match.group("msg")
msg_parts = msg.split("::", 2)
if len(msg_parts) > 1:
msg_type = msg_parts[0]
msg = {}
for kv in msg_parts[1].split(";"):
items = kv.split("=", 2)
if len(items) > 1:
msg[items[0]] = items[1]
else:
msg['content'] = items[0]
else:
msg_type = "other"
msg = {'content': msg}
return (timestamp, msg_type, msg)
def find_end_event(events, searched_event, event_type):
for i in range(len(events)):
event = events[i]
if event[1] == event_type and event[2] == searched_event[2]:
return i
return -1
def pair_events(events):
paired = []
i = 0
while i < len(events):
event = events[i]
event_type = event[1]
if event_type.endswith(":start"):
group = event[1].split(":", 2)[0]
j = find_end_event(events[i+1:], event, group + ":end")
if j >= 0:
end_event = events.pop(i+j+1)
paired.append((event, end_event))
i = i+1
continue
paired.append((event, None))
i = i+1
return paired
COLOR_FOR_EVENT = {
'search': "'#394a6b'",
'subsearch': "'#109618'",
'changeset': "'#990099'",
'diff': "'#e57357'",
'flush': "'#ff9900'",
'push': "'#0099c6'"
}
def produce_html(trace_name, pairs):
base = """%s
"""
rows = []
colors = []
for pair in pairs:
(start_event, end_event) = pair
(timestamp, event_type, metadata) = start_event
has_end_ts = end_event is not None
group = event_type if not event_type.endswith(":start") else event_type.split(":", 2)[0]
color = COLOR_FOR_EVENT[group] if group in COLOR_FOR_EVENT else "'#c60000'"
has_scope_id = 'scope' in metadata
scope_id = metadata['scope'] if has_scope_id else metadata['content']
if has_scope_id: del metadata['scope']
else:
if group in ['changeset', 'flush', 'diff']:
match = re.match(r'com.canonical.Unity\.Master\.Scope\.(\w+)\.T', scope_id)
if match: scope_id = "%s.scope" % match.group(1)
data = str(metadata).replace("'", "\\'")
# we're loosing our lovely nanosecond precision :(
map_to_int = lambda x: int(x[0:3])
start_date = map(map_to_int, re.findall(r'\d+', timestamp))
end_date = start_date
if has_end_ts:
end_date = map(map_to_int, re.findall(r'\d+', end_event[0]))
event_name = "%s - %s" % (group, metadata['target']) if 'target' in metadata else group
data_tuple = (scope_id, group, data, ",".join(map(str,start_date)), ",".join(map(str, end_date)))
data_format = "[ '%s', '%s', '%s', new Date(0,0,0,%s), new Date(0,0,0,%s) ]"
data_row = data_format % data_tuple
rows.append(data_row)
colors.append(color)
return base % ("Analysis of %s" % trace_name, ",\n".join(rows))
def get_events_from_babeltrace(trace_dir):
events = []
all_events = subprocess.check_output(["babeltrace", trace_dir])
lines = filter(None, all_events.split("\n"))
for line in lines:
event = parse_trace_line(line)
events.append(event)
return events
def main(args):
output_name = None
if len(args) > 1:
trace_dir = args[1]
else:
trace_dir = capture_lttng_trace()
if trace_dir:
basename = os.path.basename(trace_dir)
if not basename:
basename = os.path.basename(os.path.dirname(trace_dir))
output_name = "%s.html" % basename
events = get_events_from_babeltrace(trace_dir)
if len(events) == 0:
raise RuntimeError("There are 0 events in the trace")
pairs = pair_events(events)
html = produce_html(trace_dir, pairs)
if output_name:
sys.stderr.write("Writing output to '%s'\n" % output_name)
f = open(output_name, 'w')
f.write(html)
f.close()
else:
print html
if __name__ == "__main__":
main (sys.argv)
libunity-7.1.4+15.10.20151002/tools/music-track-model-renderer.vala 0000644 0000153 0000161 00000006451 12603350222 025034 0 ustar pbuser pbgroup 0000000 0000000 /*
* Copyright (C) 2012 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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, see .
*
* Authored by Pawel Stolowski
*
*/
namespace Unity.Tester {
public class MusicTrackModelRenderer: Object
{
public Dee.Model track_model { get; construct; }
private Dee.ModelTag track_model_tag;
private int row_counter = 0;
private ulong model_sync_sig_id = 0;
public Gtk.ListStore track_view_model { get; construct; }
public signal void track_list_synchronized();
construct
{
track_view_model = new Gtk.ListStore(6, typeof(string), typeof(int), typeof(string), typeof(uint), typeof(uint), typeof(double));
}
public MusicTrackModelRenderer(Dee.Model track_model)
{
Object(track_model: track_model);
}
public void sync()
{
track_model_tag = new Dee.ModelTag(track_model);
track_model.row_added.connect(track_added_cb);
track_model.row_changed.connect(track_changed_cb);
var iter = track_model.get_first_iter ();
var end_iter = track_model.get_last_iter ();
while (iter != end_iter)
{
track_added_cb (track_model, iter);
iter = track_model.next (iter);
}
if (track_model is Dee.SharedModel)
{
model_sync_sig_id = track_model.notify["synchronized"].connect(track_model_synchronized_cb);
}
}
private void track_added_cb(Dee.Model model, Dee.ModelIter iter)
{
var row = model.get_row(iter);
track_model_tag.set(track_model, iter, row_counter++);
Gtk.TreeIter tm_iter;
track_view_model.append(out tm_iter);
track_view_model.set(tm_iter, 0, row[0].get_string(), 1, row[1].get_int32(), 2, row[2].get_string(), 3, row[3].get_uint32(), 4, row[4].get_uint32(), 5, row[5].get_double(), -1);
}
private void track_changed_cb(Dee.Model model, Dee.ModelIter iter)
{
int index = track_model_tag.get(track_model, iter);
Gtk.TreeIter tm_iter;
if (track_view_model.get_iter_first(out tm_iter)) {
while (index > 0)
{
if (!track_view_model.iter_next(ref tm_iter)) {
break;
}
--index;
}
if (index == 0) {
var row = model.get_row(iter);
track_view_model.set(tm_iter, 0, row[0].get_string(), 1, row[1].get_int32(), 2, row[2].get_string(), 3, row[3].get_uint32(), 4, row[4].get_uint32(), 5, row[5].get_double(), -1);
} else {
stderr.printf("can't update row");
}
}
}
private void track_model_synchronized_cb()
{
SignalHandler.disconnect (track_model, model_sync_sig_id);
track_list_synchronized();
}
}
}
libunity-7.1.4+15.10.20151002/tools/dbus-scope-connect.ui 0000644 0000153 0000161 00000033423 12603350222 023074 0 ustar pbuser pbgroup 0000000 0000000
False5Connect to LensTruecenter-on-parent510160TruedialogFalsevertical2Falseendgtk-cancelFalseTrueTrueTrueFalseTruerightFalseTrue0gtk-okFalseTrueTrueTrueTrueTrueFalseTrueFalseTrue1FalseTrueend0TrueFalsestart6vertical5TrueFalseTrue5TrueFalsestart17DBus Name0011TrueFalsestart27DBus Path0111TrueTrueTrue•True1011TrueTrueTrue•True1111TrueTrue0TrueFalsestartTrue5BrowseFalseTrueTrueTrueTrueFill in DBus Name and Path from a Lens fileFill in DBus Name and Path from a Lens filestartstart1Falsebottom1011TrueFalsestartFrom Lens file0011TrueFalsestartDiscovered from DBus0111TrueFalseTrueTrueFalsestartTruescope_list_model01FalseTrue0TrueFalseFalseTrue11111FalseTrue2FalseTrue1button3button2
libunity-7.1.4+15.10.20151002/tools/unity-tool.vala 0000644 0000153 0000161 00000043031 12603350222 022026 0 ustar pbuser pbgroup 0000000 0000000 /*
* Copyright (C) 2012 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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, see .
*
* Authored by Michal Hruby
*
*/
using Gtk;
using Unity.Protocol;
namespace Unity.Tester
{
namespace Options
{
public static bool gui;
public static bool benchmark;
public static string scope_dbus_name;
public static string scope_dbus_path;
public static string scope_file;
public static string search_string;
public static int search_type;
public static bool private_channel;
public static bool common_tests;
public static bool print_search_reply;
public static bool dump_results;
public static bool dump_filters;
public static bool diff_changes;
public static bool test_server_mode;
public static string[] test_cases;
}
namespace TestRunner
{
public static string[] test_cases;
public static int test_index;
}
public errordomain TesterError
{
INVALID_ARGS
}
private UnityToolUi ui;
const OptionEntry[] options =
{
{
"gui", 'g', 0, OptionArg.NONE, out Options.gui,
"Run GUI", null
},
{
"benchmark", 'b', 0, OptionArg.NONE, out Options.benchmark,
"Benchmark searches", null
},
{
"dbus-name", 'n', 0, OptionArg.STRING, out Options.scope_dbus_name,
"Unique dbus name of the tested scope", null
},
{
"dbus-path", 'p', 0, OptionArg.STRING, out Options.scope_dbus_path,
"Object path of the scope", null
},
{
"scope-file", 's', 0, OptionArg.STRING, out Options.scope_file,
"Path to the scope file (to read out dbus name and path)", null
},
{
"common-tests", 'c', 0, OptionArg.NONE, out Options.common_tests,
"Perform common tests each scope should conform to", null
},
{
"search", 'q', 0, OptionArg.STRING, out Options.search_string,
"Search string to send to the scope", null
},
{
"search-type", 't', 0, OptionArg.INT, out Options.search_type,
"Type of the search (value from Unity.SearchType enum)", null
},
{
"dump-results", 'r', 0, OptionArg.NONE, out Options.dump_results,
"Output the results model on stdout", null
},
{
"dump-filters", 'f', 0, OptionArg.NONE, out Options.dump_filters,
"Output the filter model on stdout", null
},
{
"print-search-reply", 0, 0, OptionArg.NONE, out Options.print_search_reply,
"Output reply of the search call in its raw form", null
},
{
"private-channel", 0, 0, OptionArg.NONE, out Options.private_channel,
"Use private channel for results transfer", null
},
{
"diff-changes", 'd', 0, OptionArg.NONE, out Options.diff_changes,
"Use diff channel", null
},
{
"test-server-mode", 0, 0, OptionArg.NONE, out Options.test_server_mode,
"Run a collection of test scripts", null
},
{
"", 0, 0, OptionArg.FILENAME_ARRAY, out Options.test_cases,
"Invididual test cases", ""
},
{
null
}
};
public static void get_scope_params_from_file(string filename) throws Error
{
Unity.Protocol.ScopeRegistry.ScopeMetadata metadata;
if (Path.is_absolute (filename))
{
metadata = Unity.Protocol.ScopeRegistry.ScopeMetadata.for_path (filename);
}
else
{
metadata = Unity.Protocol.ScopeRegistry.ScopeMetadata.for_id (filename);
}
Options.scope_dbus_name = metadata.dbus_name;
Options.scope_dbus_path = metadata.dbus_path;
}
public static void warn (string format, ...)
{
var args = va_list ();
logv ("libunity-tool", LogLevelFlags.LEVEL_WARNING, format, args);
}
public static int main (string[] args)
{
Environment.set_prgname ("libunity-tool");
var opt_context = new OptionContext (" - libunity tool");
opt_context.add_main_entries (options, null);
try
{
if (args.length <= 1)
{
print ("%s\n", opt_context.get_help (true, null));
return 0;
}
opt_context.parse (ref args);
if (Options.test_server_mode)
{
if (Options.test_cases == null ||
(Options.test_cases.length=(int)strv_length(Options.test_cases)) == 0)
{
throw new TesterError.INVALID_ARGS ("No test cases specified");
}
// special mode where we just run test scripts inside a directory
string[] test_scripts = get_test_cases ();
TestRunner.test_cases = test_scripts;
Test.init (ref args);
foreach (unowned string test_case in test_scripts)
{
Test.add_data_func ("/Integration/ScopeTest/" +
Path.get_basename (test_case),
() =>
{
string test = TestRunner.test_cases[TestRunner.test_index++];
int status;
try
{
Process.spawn_command_line_sync (test,
null,
null,
out status);
}
catch (Error e)
{
warn ("%s", e.message);
status = -1;
}
assert (status == 0);
});
}
return Test.run ();
}
else
{
// read dbus name and path from the scope file
if (Options.scope_file != null)
{
get_scope_params_from_file(Options.scope_file);
}
if (Options.gui)
{
Gtk.init(ref args);
ui = new UnityToolUi();
if (ui.init_gui()) {
Gtk.main();
}
return 0;
}
// check that we have dbus names
if (Options.scope_dbus_name == null || Options.scope_dbus_path == null)
{
throw new TesterError.INVALID_ARGS ("Scope DBus name and path not specified!");
}
if (Options.common_tests)
{
int status = run_common_tests ();
assert (status == 0);
}
if (Options.benchmark)
{
// libunity uses an envvar to add time information, tell dbus
// to use that envvar for newly spawned services
var conn = Bus.get_sync (BusType.SESSION, null);
var env = new HashTable (str_hash, str_equal);
env["LIBUNITY_TIME_SEARCHES"] = "1";
conn.call_sync ("org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
"UpdateActivationEnvironment",
new Variant.tuple ({env}),
null, 0, -1, null);
}
// Get proxy
string channel_id;
Dee.SerializableModel results_model;
var proxy = get_scope_proxy (Options.scope_dbus_name,
Options.scope_dbus_path,
(ChannelType) Options.search_type,
get_global_channel_flags (),
out channel_id, out results_model);
// Performing search
if (Options.search_string != null)
{
var ml = new MainLoop ();
int64 start_time = get_monotonic_time ();
int64 first_result = 0;
uint64 model_seqnum = 0;
results_model.row_added.connect (() =>
{
if (first_result == 0) first_result = get_monotonic_time ();
});
proxy.search.begin (channel_id, Options.search_string,
new HashTable (null, null),
null,
(obj, res) =>
{
try
{
var reply_dict = proxy.search.end (res);
if ("model-seqnum" in reply_dict)
model_seqnum = reply_dict["model-seqnum"].get_uint64 ();
if (Options.print_search_reply)
{
Variant v = reply_dict;
print ("%s\n", v.print (true)); // so much easier
}
}
catch (Error err)
{
warning ("%s", err.message);
}
ml.quit ();
});
assert (run_with_timeout (ml, 15000));
wait_for_seqnum (results_model as Dee.SharedModel, model_seqnum);
if (Options.benchmark)
{
int64 end_time = get_monotonic_time ();
int64 delta = end_time - start_time;
double elapsed = delta;
print ("Search took: %g seconds\n", elapsed / 1000000.0);
if (first_result > 0)
{
delta = first_result - start_time;
elapsed = delta;
print ("First result after: %g seconds\n", elapsed / 1000000.0);
}
}
}
// Dumping models
if (Options.dump_results || Options.dump_filters)
{
if (Options.dump_results)
{
dump_results_model (results_model);
}
if (Options.dump_filters)
{
dump_filters_model (proxy.filters_model);
}
}
close_channel (proxy, channel_id);
}
}
catch (Error err)
{
warn ("%s", err.message);
return 1;
}
return 0;
}
private ScopeProxy get_scope_proxy (string dbus_name, string dbus_path,
ChannelType channel_type,
ChannelFlags channel_flags,
out string channel_id,
out Dee.SerializableModel model)
throws Error
{
ScopeProxy? proxy = null;
var ml = new MainLoop ();
ScopeProxy.new_from_dbus.begin (dbus_name, dbus_path, null, (obj, res) =>
{
try
{
proxy = ScopeProxy.new_from_dbus.end (res);
}
catch (Error err)
{
warning ("%s", err.message);
}
ml.quit ();
});
run_with_timeout (ml, 15000);
if (proxy == null)
{
throw new IOError.TIMED_OUT ("Timed out waiting for proxy");
}
ml = new MainLoop ();
string? chan_id = null;
Error? outer_error = null;
Dee.SerializableModel? results_model = null;
proxy.open_channel.begin (channel_type, channel_flags, null, (obj, res) =>
{
try
{
chan_id = proxy.open_channel.end (res, out results_model);
}
catch (Error err)
{
warning ("%s", err.message);
outer_error = err;
}
ml.quit ();
});
run_with_timeout (ml, 15000);
if (outer_error != null) throw outer_error;
channel_id = chan_id;
model = results_model;
return proxy;
}
private void close_channel (ScopeProxy proxy, string channel_id)
{
var ml = new MainLoop ();
proxy.close_channel.begin (channel_id, null, (obj, res) =>
{
try
{
proxy.close_channel.end (res);
}
catch (Error err)
{
warning ("%s", err.message);
}
ml.quit ();
});
run_with_timeout (ml, 15000);
}
private static void wait_for_seqnum (Dee.SharedModel model, uint64 seqnum)
{
if (model.get_seqnum () >= seqnum) return;
var ml = new MainLoop ();
var update_sig_id = model.end_transaction.connect ((m, begin_seqnum, end_seqnum) =>
{
if (end_seqnum < seqnum) return;
/* disconnect from within the signal handler... awesome, right? */
ml.quit ();
});
run_with_timeout (ml, 15000);
SignalHandler.disconnect (model, update_sig_id);
}
public static string[] get_test_cases ()
{
string[] results = {};
foreach (string path in Options.test_cases)
{
if (FileUtils.test (path, FileTest.IS_REGULAR) &&
FileUtils.test (path, FileTest.IS_EXECUTABLE))
{
results += path;
}
else if (FileUtils.test (path, FileTest.IS_DIR))
{
try
{
var dir = Dir.open (path);
unowned string name = dir.read_name ();
while (name != null)
{
var child_path = Path.build_filename (path, name, null);
if (FileUtils.test (child_path, FileTest.IS_REGULAR) &&
FileUtils.test (child_path, FileTest.IS_EXECUTABLE))
{
results += child_path;
}
name = dir.read_name ();
}
} catch (Error e) { warn ("%s", e.message); }
}
}
return results;
}
public static bool run_with_timeout (MainLoop ml, uint timeout_ms)
{
bool timeout_reached = false;
var t_id = Timeout.add (timeout_ms, () =>
{
timeout_reached = true;
debug ("Timeout reached");
ml.quit ();
return false;
});
ml.run ();
if (!timeout_reached) Source.remove (t_id);
return !timeout_reached;
}
private static int run_common_tests ()
{
string[] args = { "./libunity-tool" };
unowned string[] dummy = args;
Test.init (ref dummy);
// checks that scope emits finished signal for every search type
// (and both empty and non-empty searches)
Test.add_data_func ("/Integration/ScopeTest/DefaultSearch/Empty", () =>
{
call_scope_search ("", ChannelType.DEFAULT);
});
Test.add_data_func ("/Integration/ScopeTest/DefaultSearch/NonEmpty", () =>
{
call_scope_search ("a", ChannelType.DEFAULT);
});
// check also non-empty -> empty search
Test.add_data_func ("/Integration/ScopeTest/DefaultSearch/Empty2", () =>
{
call_scope_search ("", ChannelType.DEFAULT);
});
Test.add_data_func ("/Integration/ScopeTest/GlobalSearch/Empty", () =>
{
call_scope_search ("", ChannelType.GLOBAL);
});
Test.add_data_func ("/Integration/ScopeTest/GlobalSearch/NonEmpty", () =>
{
call_scope_search ("a", ChannelType.GLOBAL);
});
// check also non-empty -> empty search
Test.add_data_func ("/Integration/ScopeTest/GlobalSearch/Empty2", () =>
{
call_scope_search ("", ChannelType.GLOBAL);
});
return Test.run ();
}
private static ChannelFlags get_global_channel_flags ()
{
var flags = ChannelFlags.NONE;
if (Options.private_channel) flags |= ChannelFlags.PRIVATE;
if (Options.diff_changes) flags |= ChannelFlags.DIFF_CHANGES;
return flags;
}
private static void call_scope_search (string search_string,
int search_type)
{
string channel_id;
Dee.SerializableModel results_model;
var proxy = get_scope_proxy (Options.scope_dbus_name,
Options.scope_dbus_path,
(ChannelType) search_type,
get_global_channel_flags (),
out channel_id, out results_model);
var ml = new MainLoop ();
uint64 model_seqnum = 0;
HashTable? reply_dict = null;
proxy.search.begin (channel_id, search_string,
new HashTable (null, null),
null,
(obj, res) =>
{
try
{
reply_dict = proxy.search.end (res);
if ("model-seqnum" in reply_dict)
model_seqnum = reply_dict["model-seqnum"].get_uint64 ();
}
catch (Error err)
{
warning ("%s", err.message);
}
ml.quit ();
});
assert (run_with_timeout (ml, 15000));
wait_for_seqnum (results_model as Dee.SharedModel, model_seqnum);
close_channel (proxy, channel_id);
}
private void dump_results_model (Dee.Model model)
{
var iter = model.get_first_iter ();
var last_iter = model.get_last_iter ();
while (iter != last_iter)
{
var row = model.get_row (iter);
print ("%s\t%s\t%u\t%u\t%s\t%s\t%s\t%s\t%s\n",
row[0].get_string (),
row[1].get_string (),
row[2].get_uint32 (),
row[3].get_uint32 (),
row[4].get_string (),
row[5].get_string (),
row[6].get_string (),
row[7].get_string (),
row[8].print (true)
);
iter = model.next (iter);
}
}
private void dump_filters_model (Dee.Model model)
{
var iter = model.get_first_iter ();
var last_iter = model.get_last_iter ();
while (iter != last_iter)
{
var row = model.get_row (iter);
print ("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
row[0].get_string (),
row[1].get_string (),
row[2].get_string (),
row[3].get_string (),
row[4].print (true),
row[5].get_boolean ().to_string (),
row[6].get_boolean ().to_string (),
row[7].get_boolean ().to_string ()
);
iter = model.next (iter);
}
}
}
libunity-7.1.4+15.10.20151002/MAINTAINERS 0000644 0000153 0000161 00000000000 12603350222 017360 0 ustar pbuser pbgroup 0000000 0000000 libunity-7.1.4+15.10.20151002/test/ 0000755 0000153 0000161 00000000000 12603351405 016660 5 ustar pbuser pbgroup 0000000 0000000 libunity-7.1.4+15.10.20151002/test/Makefile.am 0000644 0000153 0000161 00000000355 12603350222 020713 0 ustar pbuser pbgroup 0000000 0000000 include $(top_srcdir)/Makefile.decl
SUBDIRS = vala C python
EXTRA_DIST += \
data/applications/ubuntu-about.desktop \
data/applications/asdasdasd.desktop \
data/scope0.scope \
data/test_desktop_file.desktop
libunity-7.1.4+15.10.20151002/test/C/ 0000755 0000153 0000161 00000000000 12603351405 017042 5 ustar pbuser pbgroup 0000000 0000000 libunity-7.1.4+15.10.20151002/test/C/Makefile.am 0000644 0000153 0000161 00000000045 12603350222 021071 0 ustar pbuser pbgroup 0000000 0000000 include $(top_srcdir)/Makefile.decl
libunity-7.1.4+15.10.20151002/test/python/ 0000755 0000153 0000161 00000000000 12603351405 020201 5 ustar pbuser pbgroup 0000000 0000000 libunity-7.1.4+15.10.20151002/test/python/Makefile.am 0000644 0000153 0000161 00000001022 12603350222 022224 0 ustar pbuser pbgroup 0000000 0000000 include $(top_srcdir)/Makefile.decl
TESTS = bug-1062331.py extras.py container-ownership.py scope-result.py
TEST_EXTENSIONS = .py
# gtester doesn't care about our TESTS_ENVIRONMENT, so can't use it
#TEST_PROGS = $(TESTS)
TESTS_ENVIRONMENT = \
GI_TYPELIB_PATH=$(top_builddir)/src:$(top_builddir)/extras:$$GI_TYPELIB_PATH; \
export GI_TYPELIB_PATH; \
LD_LIBRARY_PATH=$(top_builddir)/src/.libs:$(top_builddir)/extras/.libs:$$LD_LIBRARY_PATH; \
export LD_LIBRARY_PATH; \
$(NULL)
PY_LOG_COMPILER = $(PYTHON)
AM_PY_LOG_FLAGS =
libunity-7.1.4+15.10.20151002/test/python/bug-1062331.py 0000755 0000153 0000161 00000000307 12603350222 022144 0 ustar pbuser pbgroup 0000000 0000000 #!/usr/bin/python
# no longer testing the bug from the filename
from gi.repository import Unity
generic_preview = Unity.GenericPreview.new("Title", "Description", None)
generic_preview.serialize()
libunity-7.1.4+15.10.20151002/test/python/scope-result.py 0000755 0000153 0000161 00000002040 12603350222 023173 0 ustar pbuser pbgroup 0000000 0000000 #!/usr/bin/python
from gi.repository import Unity, GLib
class TestResultSet(Unity.ResultSet):
def __init__(self):
Unity.ResultSet.__init__(self)
self.results = []
def do_add_result(self, result):
assert(result.uri == "file:///foo")
assert(result.title == "Title")
assert(len(result.metadata) > 0)
assert("whatever" in result.metadata)
# bug in pygi? copy() shouldn't be needed
self.results.append(result.copy())
rs = TestResultSet()
# overrides are not installed when running tests, so don't use add_result
variant = GLib.Variant('(ssuussssa{sv})', ("file:///foo", "file:///", 0, 0,
"text/plain", "Title", "",
"file:///foo", {'whatever': GLib.Variant("s", "foo")}))
rs.add_result_from_variant(variant)
saved_result = rs.results[0]
assert(saved_result.uri == "file:///foo")
assert(saved_result.title == "Title")
assert(len(saved_result.metadata) > 0)
assert("whatever" in saved_result.metadata)
libunity-7.1.4+15.10.20151002/test/python/container-ownership.py 0000755 0000153 0000161 00000000727 12603350222 024556 0 ustar pbuser pbgroup 0000000 0000000 #!/usr/bin/python
from gi.repository import Unity, Gio
category_set = Unity.CategorySet.new()
cat = Unity.Category.new("example", "Example", Gio.ThemedIcon.new("test"), Unity.CategoryRenderer.DEFAULT)
category_set.add(cat)
cat = Unity.Category.new("another", "Another", Gio.ThemedIcon.new("test"), Unity.CategoryRenderer.GRID)
category_set.add(cat)
cat_list = category_set.get_categories()
#if the binding is broken there'll be double free
del cat_list
del category_set
libunity-7.1.4+15.10.20151002/test/python/extras.py 0000755 0000153 0000161 00000000144 12603350222 022057 0 ustar pbuser pbgroup 0000000 0000000 #!/usr/bin/python
from gi.repository import UnityExtras
player = UnityExtras.PreviewPlayer.new ()
libunity-7.1.4+15.10.20151002/test/vala/ 0000755 0000153 0000161 00000000000 12603351405 017603 5 ustar pbuser pbgroup 0000000 0000000 libunity-7.1.4+15.10.20151002/test/vala/Makefile.am 0000644 0000153 0000161 00000006753 12603350222 021646 0 ustar pbuser pbgroup 0000000 0000000 include $(top_srcdir)/Makefile.decl
DISTCHECK_CONFIGURE_FLAGS = --enable-integration-tests=no
check_PROGRAMS = test-vala test-scope test-blacklist-crash test-extras
AM_CPPFLAGS = \
-I$(top_srcdir) \
-I$(top_builddir)/protocol \
-I$(top_builddir)/extras \
-I$(top_builddir)/src \
-DBUILDDIR=\"$(top_builddir)\" \
-DTESTDIR=\"$(top_srcdir)/test\" \
-DTESTVALADIR=\"$(top_srcdir)/test/vala\" \
-DG_SETTINGS_ENABLE_BACKEND \
-ggdb \
$(LIBUNITY_CFLAGS) \
$(LIBUNITY_LIBS)
if !ENABLE_C_WARNINGS
AM_CPPFLAGS += -w
endif
if ENABLE_TRACE_LOG
AM_CPPFLAGS += -DENABLE_UNITY_TRACE_LOG
endif
AM_VALAFLAGS = \
--vapidir=$(top_builddir)/src \
--vapidir=$(top_builddir)/protocol \
--vapidir=$(top_builddir)/extras \
--vapidir=$(top_srcdir)/test/vala \
--pkg unity-protocol \
--pkg unity-internal \
--pkg config \
$(LIBUNITY_PACKAGES) \
$(MAINTAINER_VALAFLAGS) \
$(NULL)
test_extras_AM_VALAFLAGS = \
--vapidir=$(top_builddir)/src \
--vapidir=$(top_builddir)/extras \
--vapidir=$(top_srcdir)/test/vala \
--pkg unity \
--pkg unity-extras-internal \
--pkg config \
$(LIBUNITY_PACKAGES) \
$(MAINTAINER_VALAFLAGS) \
$(NULL)
test_libs = \
$(top_builddir)/src/libunity.la \
$(top_builddir)/protocol/libunity-protocol-private.la \
$(top_builddir)/extras/libunity-extras.la \
$(LIBUNITY_LIBS) \
$(NULL)
if ENABLE_LTTNG
test_libs += -lurcu-bp
endif
TEST_PROGS += test-vala test-scope test-blacklist-crash test-extras
test_vala_LDADD = $(test_libs)
test_vala_LDFLAGS = -static
test_vala_VALASOURCES = \
common.vala \
test-appinfo-manager.vala \
test-diff.vala \
test-filters.vala \
test-io.vala \
test-launcher.vala \
test-preferences.vala \
test-previews.vala \
test-scope-base.vala \
test-scope-discovery.vala \
test-scope-group.vala \
test-vala.vala \
test-results-synchronizer.vala \
$(NULL)
nodist_test_vala_SOURCES = $(test_vala_VALASOURCES:.vala=.c)
test_scope_LDADD = $(test_libs)
test_scope_LDFLAGS = -static
test_scope_VALASOURCES = common.vala test-scope.vala
nodist_test_scope_SOURCES = $(test_scope_VALASOURCES:.vala=.c)
test_blacklist_crash_LDADD = $(test_libs)
test_blacklist_crash_VALASOURCES = blacklist-crash-1029949-test-case.vala
nodist_test_blacklist_crash_SOURCES = $(test_blacklist_crash_VALASOURCES:.vala=.c)
test_extras_LDADD = $(test_libs)
test_extras_LDFLAGS = -static
test_extras_VALASOURCES = \
test-preview-player-iface.vala \
test-utils.vala \
common.vala \
test-extras.vala \
$(NULL)
nodist_test_extras_SOURCES = $(test_extras_VALASOURCES:.vala=.c)
BUILT_SOURCES = \
test-vala.vala.stamp \
test-scope.vala.stamp \
test-blacklist-crash.vala.stamp \
test-extras.vala.stamp \
$(NULL)
test-vala.vala.stamp: $(test_vala_VALASOURCES)
$(AM_V_GEN)$(VALAC) -C $(AM_VALAFLAGS) $(VALAFLAGS) $^
@touch $@
test-scope.vala.stamp: $(test_scope_VALASOURCES)
$(AM_V_GEN)$(VALAC) -C $(AM_VALAFLAGS) $(VALAFLAGS) $^
@touch $@
test-blacklist-crash.vala.stamp: $(test_blacklist_crash_VALASOURCES)
$(AM_V_GEN)$(VALAC) -C $(AM_VALAFLAGS) $(VALAFLAGS) $^
@touch $@
test-extras.vala.stamp: $(test_extras_VALASOURCES)
$(AM_V_GEN)$(VALAC) -C $(test_extras_AM_VALAFLAGS) $(VALAFLAGS) $^
@touch $@
include Makefile.integration_tests
EXTRA_DIST += \
$(test_vala_VALASOURCES) \
$(test_scope_VALASOURCES) \
$(test_blacklist_crash_VALASOURCES) \
$(test_extras_VALASOURCES) \
config.vapi \
$(NULL)
CLEANFILES = \
*.stamp \
$(test_vala_VALASOURCES:.vala=.c) \
$(test_scope_VALASOURCES:.vala=.c) \
$(test_blacklist_crash_VALASOURCES:.vala=.c) \
$(test_extras_VALASOURCES:.vala=.c) \
$(NULL)
libunity-7.1.4+15.10.20151002/test/vala/test-diff.vala 0000644 0000153 0000161 00000040610 12603350222 022332 0 ustar pbuser pbgroup 0000000 0000000 /* -*- Mode: vala; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*- */
/*
* Copyright (C) 2011 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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, see .
*
* Authored by Michal Hruby
*
*/
using Unity.Internal;
using Unity.Internal.Utils.Diff;
namespace Unity.Test
{
public class DiffSuite
{
public DiffSuite ()
{
GLib.Test.add_data_func ("/Unit/Diff/Empty",
Fixture.create (DiffTester.test_empty_diff));
GLib.Test.add_data_func ("/Unit/Diff/Populate",
Fixture.create (DiffTester.test_populate));
GLib.Test.add_data_func ("/Unit/Diff/Identical",
Fixture.create (DiffTester.test_identical));
GLib.Test.add_data_func ("/Unit/Diff/Appends",
Fixture.create (DiffTester.test_appends));
GLib.Test.add_data_func ("/Unit/Diff/Prepends",
Fixture.create (DiffTester.test_prepends));
GLib.Test.add_data_func ("/Unit/Diff/Inserts",
Fixture.create (DiffTester.test_inserts));
GLib.Test.add_data_func ("/Unit/Diff/MoveToMiddle",
Fixture.create (DiffTester.test_move_to_middle));
GLib.Test.add_data_func ("/Unit/Diff/RemoveBegin",
Fixture.create (DiffTester.test_remove_begin));
GLib.Test.add_data_func ("/Unit/Diff/RemoveEnd",
Fixture.create (DiffTester.test_remove_end));
GLib.Test.add_data_func ("/Unit/Diff/RemoveMid",
Fixture.create (DiffTester.test_remove_mid));
GLib.Test.add_data_func ("/Unit/Diff/Mixed",
Fixture.create (DiffTester.test_mixed));
GLib.Test.add_data_func ("/Unit/DiffModel/Populate",
Fixture.create (DiffModelTester.test_populate));
GLib.Test.add_data_func ("/Unit/DiffModel/Clear",
Fixture.create (DiffModelTester.test_clear));
GLib.Test.add_data_func ("/Unit/DiffModel/Mixed",
Fixture.create (DiffModelTester.test_mixed));
GLib.Test.add_data_func ("/Unit/DiffModel/ChangedMetadata",
Fixture.create (DiffModelTester.test_metadata));
}
class DiffTester: Object, Fixture
{
private void setup ()
{
}
private void teardown ()
{
}
private SList run_diff (string[] x, string[] y)
{
var script = run (x.length, y.length, (a, b) =>
{
return x[a] == y[b];
});
script.reverse ();
return script;
}
public void test_empty_diff ()
{
string[] x_results = {};
string[] y_results = {};
var script = run_diff (x_results, y_results);
assert (script.length () == 0);
}
public void test_populate ()
{
string[] x_results = {};
string[] y_results = {};
y_results += "Line #1";
y_results += "Line #2";
y_results += "Line #3";
y_results += "Line #4";
var script = run_diff (x_results, y_results);
assert (script.length () == 1);
var change = script.nth_data (0);
assert (change.x_offset == 0);
assert (change.y_offset == 0);
assert (change.inserted == 4);
assert (change.deleted == 0);
}
public void test_identical ()
{
string[] x_results = {};
x_results += "Line #1";
x_results += "Line #2";
x_results += "Line #3";
x_results += "Line #4";
string[] y_results = {};
y_results += "Line #1";
y_results += "Line #2";
y_results += "Line #3";
y_results += "Line #4";
var script = run_diff (x_results, y_results);
assert (script.length () == 0);
}
public void test_appends ()
{
string[] x_results = {};
x_results += "Line #1";
x_results += "Line #2";
x_results += "Line #3";
x_results += "Line #4";
string[] y_results = {};
y_results += "Line #1";
y_results += "Line #2";
y_results += "Line #3";
y_results += "Line #4";
y_results += "Line #5";
y_results += "Line #6";
y_results += "Line #7";
var script = run_diff (x_results, y_results);
assert (script.length () == 1);
var change = script.nth_data (0);
assert (change.x_offset == 4);
assert (change.y_offset == 4);
assert (change.inserted == 3);
assert (change.deleted == 0);
}
public void test_prepends ()
{
string[] x_results = {};
x_results += "Line #1";
x_results += "Line #2";
x_results += "Line #3";
x_results += "Line #4";
string[] y_results = {};
y_results += "Line #5";
y_results += "Line #6";
y_results += "Line #7";
y_results += "Line #1";
y_results += "Line #2";
y_results += "Line #3";
y_results += "Line #4";
var script = run_diff (x_results, y_results);
assert (script.length () == 1);
var change = script.nth_data (0);
assert (change.x_offset == 0);
assert (change.y_offset == 0);
assert (change.inserted == 3);
assert (change.deleted == 0);
}
public void test_inserts ()
{
string[] x_results = {};
x_results += "Line #2";
x_results += "Line #4";
string[] y_results = {};
y_results += "Line #1";
y_results += "Line #2";
y_results += "Line #3";
y_results += "Line #4";
y_results += "Line #5";
var script = run_diff (x_results, y_results);
assert (script.length () == 3);
var change = script.nth_data (0);
assert (change.x_offset == 0);
assert (change.y_offset == 0);
assert (change.inserted == 1);
assert (change.deleted == 0);
change = script.nth_data (1);
assert (change.x_offset == 1);
assert (change.y_offset == 2);
assert (change.inserted == 1);
assert (change.deleted == 0);
change = script.nth_data (2);
assert (change.x_offset == 2);
assert (change.y_offset == 4);
assert (change.inserted == 1);
assert (change.deleted == 0);
}
public void test_move_to_middle ()
{
string[] x_results = {};
x_results += "Original";
string[] y_results = {};
for (int i = 0; i < 86; i++)
{
if (i == 40) y_results += "Original";
else y_results += "Line #%d".printf (i);
}
var script = run_diff (x_results, y_results);
assert (script.length () == 2);
var change = script.nth_data (0);
assert (change.inserted == 40);
change = script.nth_data (1);
assert (change.inserted == 45);
}
public void test_remove_begin ()
{
string[] x_results = {};
x_results += "Line #1";
x_results += "Line #2";
x_results += "Line #3";
x_results += "Line #4";
string[] y_results = {};
y_results += "Line #3";
y_results += "Line #4";
var script = run_diff (x_results, y_results);
assert (script.length () == 1);
var change = script.nth_data (0);
assert (change.x_offset == 0);
assert (change.y_offset == 0);
assert (change.inserted == 0);
assert (change.deleted == 2);
}
public void test_remove_end ()
{
string[] x_results = {};
x_results += "Line #1";
x_results += "Line #2";
x_results += "Line #3";
x_results += "Line #4";
string[] y_results = {};
y_results += "Line #1";
y_results += "Line #2";
var script = run_diff (x_results, y_results);
assert (script.length () == 1);
var change = script.nth_data (0);
assert (change.x_offset == 2);
assert (change.y_offset == 2);
assert (change.inserted == 0);
assert (change.deleted == 2);
}
public void test_remove_mid ()
{
string[] x_results = {};
x_results += "Line #1";
x_results += "Line #2";
x_results += "Line #3";
x_results += "Line #4";
string[] y_results = {};
y_results += "Line #1";
y_results += "Line #4";
var script = run_diff (x_results, y_results);
assert (script.length () == 1);
var change = script.nth_data (0);
assert (change.x_offset == 1);
assert (change.y_offset == 1);
assert (change.inserted == 0);
assert (change.deleted == 2);
}
public void test_mixed ()
{
string[] x_results = {};
x_results += "Line #1";
x_results += "Line #2";
x_results += "Line #3";
x_results += "Line #4";
x_results += "Line #5";
x_results += "Line #6";
x_results += "Line #7";
x_results += "Line #8";
x_results += "Line #9";
x_results += "Line #10";
string[] y_results = {};
y_results += "Line #3";
y_results += "Line #4";
y_results += "Line #5";
y_results += "Line #6";
y_results += "Line #7";
y_results += "Added #1";
y_results += "Added #2";
y_results += "Line #8";
y_results += "Line #9";
y_results += "Line #12";
y_results += "Line #14";
var script = run_diff (x_results, y_results);
assert (script.length () == 3);
var change = script.nth_data (0);
assert (change.x_offset == 0);
assert (change.y_offset == 0);
assert (change.inserted == 0);
assert (change.deleted == 2);
change = script.nth_data (1);
assert (change.x_offset == 7);
assert (change.y_offset == 5);
assert (change.inserted == 2);
assert (change.deleted == 0);
change = script.nth_data (2);
assert (change.x_offset == 9);
assert (change.y_offset == 9);
assert (change.inserted == 2);
assert (change.deleted == 1);
}
}
class DiffModelTester: Object, Fixture
{
private Unity.Internal.DiffModel? model;
private Dee.SequenceModel? backend_model;
private uint rows_added;
private uint rows_removed;
private void setup ()
{
backend_model = new Dee.SequenceModel ();
backend_model.set_schema_full (RESULTS_SCHEMA);
backend_model.set_column_names_full (RESULTS_COLUMN_NAMES);
var peer = new Dee.Server ("com.canonical.Libunity.Test");
model = new Unity.Internal.DiffModel (peer, backend_model);
model.set_schema_full (RESULTS_SCHEMA);
model.set_column_names_full (RESULTS_COLUMN_NAMES);
model.row_added.connect (() => { rows_added++; });
model.row_removed.connect (() => { rows_removed++; });
var ml = new MainLoop ();
Utils.wait_for_model_synchronization (model, (obj, res) =>
{
ml.quit ();
});
assert (run_with_timeout (ml));
}
private void teardown ()
{
model = null;
backend_model = null;
}
private void add_sample_result (
string uri,
uint category,
HashTable? metadata = null)
{
Variant metadata_v = metadata != null ?
metadata : new Variant.array (VariantType.VARDICT.element (), {});
backend_model.append (uri, "icon", category, 0, "text/plain",
Path.get_basename (uri), "", uri, metadata_v);
}
public void test_populate ()
{
assert (backend_model.get_n_rows () == 0);
assert (model.get_n_rows () == 0);
assert (model.target_model.get_n_rows () == 0);
add_sample_result ("file:///test1", 0);
add_sample_result ("file:///test2", 0);
add_sample_result ("file:///test9", 1);
add_sample_result ("file:///test2", 1);
assert (backend_model.get_n_rows () == 4);
assert (model.target_model.get_n_rows () == 4);
assert (model.get_n_rows () == 0);
assert (rows_added == 0);
assert (rows_removed == 0);
model.commit_changes ();
assert (model.get_n_rows () == 4);
assert (rows_added == 4);
assert (rows_removed == 0);
}
public void test_clear ()
{
add_sample_result ("file:///test1", 0);
add_sample_result ("file:///test2", 0);
add_sample_result ("file:///test3", 0);
add_sample_result ("file:///test9", 1);
add_sample_result ("file:///test2", 1);
add_sample_result ("file:///test5", 4);
model.commit_changes ();
assert (model.get_n_rows () == backend_model.get_n_rows ());
assert (rows_added == backend_model.get_n_rows ());
assert (rows_removed == 0);
backend_model.clear ();
rows_added = 0;
rows_removed = 0;
model.commit_changes ();
assert (model.get_n_rows () == backend_model.get_n_rows ());
assert (rows_added == 0);
assert (rows_removed == 6);
}
public void test_mixed ()
{
add_sample_result ("file:///test1", 0);
add_sample_result ("file:///test2", 0);
add_sample_result ("file:///test3", 0);
add_sample_result ("file:///test9", 1);
add_sample_result ("file:///test2", 1);
add_sample_result ("file:///test5", 4);
model.commit_changes ();
assert (model.get_n_rows () == backend_model.get_n_rows ());
assert (rows_added == backend_model.get_n_rows ());
assert (rows_removed == 0);
backend_model.clear ();
add_sample_result ("file:///test1", 0);
add_sample_result ("file:///test3", 0);
add_sample_result ("file:///test9", 1);
add_sample_result ("file:///test2", 1);
add_sample_result ("file:///test5", 4);
add_sample_result ("file:///test2", 4);
add_sample_result ("file:///test1", 4);
rows_added = 0;
rows_removed = 0;
model.commit_changes ();
assert (model.get_n_rows () == backend_model.get_n_rows ());
assert (rows_added == 2);
assert (rows_removed == 1);
// compare the actual values and their ordering
for (uint i = 0; i < model.get_n_rows (); i++)
{
var row = model.get_row (model.get_iter_at_row (i));
var orig_row = backend_model.get_row (backend_model.get_iter_at_row (i));
assert (row[ResultColumn.URI].equal (orig_row[ResultColumn.URI]));
assert (row[ResultColumn.CATEGORY].equal (orig_row[ResultColumn.CATEGORY]));
}
}
public void test_metadata ()
{
var metadata = new HashTable (str_hash, str_equal);
add_sample_result ("file:///test1", 0, metadata);
model.commit_changes ();
assert (model.get_n_rows () == backend_model.get_n_rows ());
assert (rows_added == backend_model.get_n_rows ());
assert (rows_removed == 0);
backend_model.clear ();
// change in metadata will count as completely different result
metadata["test"] = new Variant.int32 (43);
add_sample_result ("file:///test1", 0, metadata);
rows_added = 0;
rows_removed = 0;
model.commit_changes ();
assert (model.get_n_rows () == backend_model.get_n_rows ());
assert (rows_added == 1);
assert (rows_removed == 1);
// compare the actual values and their ordering
for (uint i = 0; i < model.get_n_rows (); i++)
{
var row = model.get_row (model.get_iter_at_row (i));
var orig_row = backend_model.get_row (backend_model.get_iter_at_row (i));
assert (row[ResultColumn.URI].equal (orig_row[ResultColumn.URI]));
assert (row[ResultColumn.CATEGORY].equal (orig_row[ResultColumn.CATEGORY]));
assert (row[ResultColumn.METADATA].equal (orig_row[ResultColumn.METADATA]));
}
}
}
}
}
libunity-7.1.4+15.10.20151002/test/vala/test-launcher.vala 0000644 0000153 0000161 00000006000 12603350222 023216 0 ustar pbuser pbgroup 0000000 0000000 /* -*- Mode: vala; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*- */
/*
* Copyright (C) 2010 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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, see .
*
* Authored by Mikkel Kamstrup Erlandsen
*
*/
using Unity;
namespace Unity.Test
{
public class LauncherSuite
{
public LauncherSuite ()
{
GLib.Test.add_data_func ("/Unit/Launcher/EmptyEntry",
LauncherSuite.test_empty_launcher_entry);
GLib.Test.add_data_func ("/Unit/Launcher/SingletonEntry",
LauncherSuite.test_singleton_entry);
GLib.Test.add_data_func ("/Unit/Launcher/Serializable",
LauncherSuite.test_serializable_entry);
}
internal static void test_empty_launcher_entry ()
{
var l = Unity.LauncherEntry.get_for_desktop_id ("foo.desktop");
assert (l is LauncherEntry);
assert (l.app_uri == "application://foo.desktop");
assert (l.count == 0);
assert (l.count_visible == false);
assert (l.progress == 0.0);
assert (l.progress_visible == false);
assert (l.urgent == false);
assert (l.quicklist == null);
}
internal static void test_singleton_entry ()
{
var l1 = Unity.LauncherEntry.get_for_desktop_id ("foo.desktop");
var l2 = Unity.LauncherEntry.get_for_desktop_id ("foo.desktop");
var l3 = Unity.LauncherEntry.get_for_app_uri ("application://foo.desktop");
var l4 = Unity.LauncherEntry.get_for_desktop_file ("/usr/share/applications/foo.desktop");
assert (l1 == l2);
assert (l2 == l3);
assert (l3 == l4);
}
internal static void test_serializable_entry ()
{
var orig = Unity.LauncherEntry.get_for_desktop_id ("foo.desktop");
orig.count = 27;
orig.count_visible = true;
orig.progress = 1.0;
orig.progress_visible = true;
orig.urgent = true;
Variant data = orig.externalize ();
var copy = Dee.Serializable.parse_external (data) as Unity.LauncherEntry;
assert (orig.count == copy.count);
assert (orig.count_visible == copy.count_visible);
assert (orig.progress > copy.progress - 0.01 &&
orig.progress < copy.progress + 0.01);
assert (orig.progress_visible == copy.progress_visible);
assert (orig.urgent == copy.urgent);
// FIXME: We're not testing the quicklist here, that's a bit tricky
}
}
}
libunity-7.1.4+15.10.20151002/test/vala/test-mpris-backend-prop-updates-client.vala 0000644 0000153 0000161 00000032442 12603350222 030042 0 ustar pbuser pbgroup 0000000 0000000 using Unity;
using Gee;
const string MPRIS_PREFIX = "org.mpris.MediaPlayer2.";
const string MPRIS_MEDIA_PLAYER_PATH = "/org/mpris/MediaPlayer2";
const string FREEDESKTOP_SERVICE = "org.freedesktop.DBus";
const string FREEDESKTOP_OBJECT = "/org/freedesktop/DBus";
[DBus (name = "org.freedesktop.DBus")]
public interface FreeDesktopObject: Object {
public abstract async string[] list_names() throws IOError;
public abstract signal void name_owner_changed ( string name,
string old_owner,
string new_owner );
}
[DBus (name = "org.mpris.MediaPlayer2")]
public interface MprisRoot : Object {
// properties
public abstract bool HasTracklist{owned get; set;}
public abstract bool CanQuit{owned get; set;}
public abstract bool CanRaise{owned get; set;}
public abstract string Identity{owned get; set;}
public abstract string DesktopEntry{owned get; set;}
// methods
public abstract async void Quit() throws IOError;
public abstract async void Raise() throws IOError;
}
[DBus (name = "org.mpris.MediaPlayer2.Player")]
public interface MprisPlayer : Object {
// properties
public abstract HashTable Metadata{owned get; set;}
public abstract int32 Position{owned get; set;}
public abstract string PlaybackStatus{owned get; set;}
// methods
public abstract async void PlayPause() throws IOError;
public abstract async void Next() throws IOError;
public abstract async void Previous() throws IOError;
public abstract async void Seek(int64 offset) throws IOError;
// signals
public signal void Seeked(int64 new_position);
}
// Playlist container
public struct PlaylistDetails{
public ObjectPath path;
public string name;
public string icon_name;
}
// Active playlist property container
public struct ActivePlaylistContainer{
public bool valid;
public PlaylistDetails details;
}
[DBus (name = "org.mpris.MediaPlayer2.Playlists")]
public interface MprisPlaylists : Object {
//properties
public abstract string[] Orderings{owned get; set;}
public abstract uint32 PlaylistCount{owned get; set;}
public abstract ActivePlaylistContainer ActivePlaylist {owned get; set;}
//methods
public abstract async void ActivatePlaylist(ObjectPath playlist_id) throws IOError;
public abstract async PlaylistDetails[] GetPlaylists ( uint32 index,
uint32 max_count,
string order,
bool reverse_order ) throws IOError;
//signals
public signal void PlaylistChanged (PlaylistDetails details);
}
[DBus (name = "org.freedesktop.DBus.Properties")]
public interface FreeDesktopProperties : Object{
public signal void PropertiesChanged (string source, HashTable changed_properties,
string[] invalid );
}
public errordomain XmlError {
FILE_NOT_FOUND,
XML_DOCUMENT_EMPTY
}
public class Mpris2Watcher : GLib.Object
{
FreeDesktopObject fdesktop_obj;
public signal void client_appeared ();
public signal void client_disappeared ();
public Mpris2Watcher ()
{
}
construct
{
try {
this.fdesktop_obj = Bus.get_proxy_sync ( BusType.SESSION,
FREEDESKTOP_SERVICE,
FREEDESKTOP_OBJECT,
DBusProxyFlags.DO_NOT_LOAD_PROPERTIES );
this.fdesktop_obj.name_owner_changed.connect (this.name_changes_detected);
}
catch ( IOError e ){
warning( "Mpris2watcher could not set up a watch for mpris clients appearing on the bus: %s",
e.message );
}
}
// At startup check to see if there are clients up that we are interested in
public async void check_for_active_clients()
{
string[] interfaces;
try{
interfaces = yield this.fdesktop_obj.list_names();
}
catch ( IOError e) {
warning( "Mpris2watcher could fetch active interfaces at startup: %s",
e.message );
return;
}
foreach (var address in interfaces) {
if (address.has_prefix (MPRIS_PREFIX)){
MprisRoot? mpris2_root = this.create_mpris_root(address);
if (mpris2_root == null) return;
client_appeared ();
}
}
}
private void name_changes_detected ( FreeDesktopObject dbus_obj,
string name,
string previous_owner,
string current_owner )
{
MprisRoot? mpris2_root = this.create_mpris_root(name);
if (mpris2_root == null) return;
if (previous_owner == "" && current_owner != "") {
debug ("Client '%s' has appeared", name);
client_appeared ();
}
}
private MprisRoot? create_mpris_root ( string name ){
MprisRoot mpris2_root = null;
if ( name.has_prefix (MPRIS_PREFIX) ){
try {
mpris2_root = Bus.get_proxy_sync ( BusType.SESSION,
name,
MPRIS_MEDIA_PLAYER_PATH );
}
catch (IOError e){
warning( "Mpris2watcher could not create a root interface: %s",
e.message );
}
}
return mpris2_root;
}
}
public class Mpris2Controller : GLib.Object
{
public string dbus_name {get; construct;}
public MprisRoot mpris2_root;
public MprisPlayer player;
public MprisPlaylists playlists;
public FreeDesktopProperties properties_interface;
public ArrayList received_prop_updates_for_playback_status;
public ArrayList> received_prop_updates_for_metadata_change;
public ArrayList received_prop_updates_for_active_playlists;
public Mpris2Controller(string name)
{
GLib.Object (dbus_name : name);
}
construct{
try {
this.received_prop_updates_for_playback_status = new ArrayList();
this.received_prop_updates_for_metadata_change = new ArrayList>();
this.received_prop_updates_for_active_playlists = new ArrayList();
this.mpris2_root = Bus.get_proxy_sync ( BusType.SESSION,
dbus_name,
"/org/mpris/MediaPlayer2" );
this.player = Bus.get_proxy_sync ( BusType.SESSION,
dbus_name,
"/org/mpris/MediaPlayer2" );
this.properties_interface = Bus.get_proxy_sync ( BusType.SESSION,
"org.freedesktop.Properties.PropertiesChanged",
"/org/mpris/MediaPlayer2" );
this.properties_interface.PropertiesChanged.connect ( property_changed_cb );
this.playlists = Bus.get_proxy_sync ( BusType.SESSION,
dbus_name,
"/org/mpris/MediaPlayer2" );
}
catch (IOError e) {
critical("Can't create our DBus interfaces - %s", e.message);
}
}
public void property_changed_cb ( string interface_source,
HashTable changed_properties,
string[] invalid )
{
if (changed_properties.lookup ("PlaybackStatus") != null){
this.received_prop_updates_for_playback_status.add (changed_properties.lookup ("PlaybackStatus").get_string());
}
else if (changed_properties.lookup ("Metadata") != null){
this.received_prop_updates_for_metadata_change.add ((GLib.HashTable)changed_properties.lookup ("Metadata"));
}
else if (changed_properties.lookup ("ActivePlaylist") != null){
// interesting I can reproduce the race condition which I was seeing with the clients
Timeout.add (500, update_active_playlist_array);
}
}
private bool update_active_playlist_array()
{
this.received_prop_updates_for_active_playlists.add (this.playlists.ActivePlaylist);
return false;
}
}
public class MprisClient : GLib.Object
{
public MainLoop mainloop {get; construct;}
public Mpris2Watcher watcher;
public MprisClient (MainLoop loop)
{
GLib.Object (mainloop : loop);
}
construct{
this.watcher = new Mpris2Watcher();
watcher.client_appeared.connect (on_client_appeared);
watcher.check_for_active_clients();
}
public void on_client_appeared ()
{
Timeout.add_seconds (5, () =>{
run_tests();
return escape();
});
}
public bool escape()
{
this.mainloop.quit();
return false;
}
public static int main (string[] args)
{
Environment.set_variable ("XDG_DATA_HOME", Config.TESTDIR+"/data", true);
MainLoop mainloop = new MainLoop (MainContext.default(), false);
Test.init (ref args);
GLib.Test.add_data_func ("/Integration/SoundMenu/Mpris/Backend/Player/PlaybackStatusPropertyUpdates",
player_property_updates_playback_status);
GLib.Test.add_data_func ("/Integration/SoundMenu/Mpris/Backend/Player/MetadataPropertyUpdates",
player_property_updates_metadata);
GLib.Test.add_data_func ("/Integration/SoundMenu/Mpris/Backend/Playlists/ActivePlaylistPropertyUpdates",
playlists_property_update_test_activate_playlist);
MprisClient client = new MprisClient (mainloop);
/* Make sure we flush and sync all needed state */
while (mainloop.get_context().pending() == true){
mainloop.get_context().iteration (true);
}
Idle.add (run_tests);
mainloop.run();
return 0;
}
public static bool run_tests()
{
Test.run ();
return false;
}
// No legitimate way of testing, tested manually and it seemed fine
/*internal static void root_property_updates_identity()
{
}*/
private const string RB_NAME = "org.mpris.MediaPlayer2.rhythmbox";
internal static void player_property_updates_playback_status ()
{
Mpris2Controller controller = new Mpris2Controller (RB_NAME);
controller.player.PlayPause();
Timeout.add_seconds (2, () => {
// note the client will miss the initial playbackstatus update hence the first entry is
// 'playing' from our playpause instruction just above.
assert (controller.received_prop_updates_for_playback_status[0] == "Playing");
//debug ("pbs = %s", controller.received_prop_updates_for_playback_status[0]);
return false;
});
}
internal static void player_property_updates_metadata()
{
Mpris2Controller controller = new Mpris2Controller (RB_NAME);
controller.player.Next();
Timeout.add_seconds (2, () => {
assert (controller.received_prop_updates_for_metadata_change.size == 1);
Variant? artist_v = controller.received_prop_updates_for_metadata_change[0].lookup("xesam:artist");
assert (artist_v.get_string() == "Sonnamble");
Variant? album_v = controller.received_prop_updates_for_metadata_change[0].lookup("xesam:album");
assert (album_v.get_string() == "Seven months in E minor");
//debug ("album = %s", album_v.get_string());
Variant? title_v = controller.received_prop_updates_for_metadata_change[0].lookup("xesam:title");
assert (title_v.get_string() == "Sehnsucht");
//debug ("title = %s", title_v.get_string());
Variant? art_v = controller.received_prop_updates_for_metadata_change[0].lookup("mpris:artUrl");
assert (art_v.get_string() == "file:///home/user/download/sonnamble.jpg");
//debug ("art = %s", art_v.get_string());
return false;
});
}
internal static void playlists_property_update_test_activate_playlist()
{
MainLoop loop = new MainLoop();
do_test_async_property_update_activate_playlist (loop);
loop.run();
}
internal static async void do_test_async_property_update_activate_playlist (MainLoop loop)
{
Mpris2Controller contr = new Mpris2Controller (RB_NAME);
try{
PlaylistDetails[] pls = yield contr.playlists.GetPlaylists (0,
10,
"alphabetical",
false);
contr.playlists.ActivatePlaylist.begin(pls[1].path);
// debug ("new playlist name %s", pls[1].name);
// Give it a sec
Timeout.add_seconds (3, () => {
assert (contr.received_prop_updates_for_active_playlists.size == 1);
assert (contr.received_prop_updates_for_active_playlists[0].valid == true);
assert (contr.received_prop_updates_for_active_playlists[0].details.path == "/fake/pl2/id");
assert (contr.received_prop_updates_for_active_playlists[0].details.name == "another playlist");
assert (contr.received_prop_updates_for_active_playlists[0].details.icon_name == "audio-volume-high");
return false;
});
}
catch (IOError e){
warning ("do_test_async_property_update_activate_playlist: Failed to activate playlist asynchronously");
}
loop.quit();
}
}
libunity-7.1.4+15.10.20151002/test/vala/test-mpris-backend-client.vala 0000644 0000153 0000161 00000036220 12603350222 025417 0 ustar pbuser pbgroup 0000000 0000000 using Unity;
using Gee;
const string MPRIS_PREFIX = "org.mpris.MediaPlayer2.";
const string MPRIS_MEDIA_PLAYER_PATH = "/org/mpris/MediaPlayer2";
const string FREEDESKTOP_SERVICE = "org.freedesktop.DBus";
const string FREEDESKTOP_OBJECT = "/org/freedesktop/DBus";
[DBus (name = "org.freedesktop.DBus")]
public interface FreeDesktopObject: Object {
public abstract async string[] list_names() throws IOError;
public abstract signal void name_owner_changed ( string name,
string old_owner,
string new_owner );
}
[DBus (name = "org.mpris.MediaPlayer2")]
public interface MprisRoot : Object {
// properties
public abstract bool HasTracklist{owned get; set;}
public abstract bool CanQuit{owned get; set;}
public abstract bool CanRaise{owned get; set;}
public abstract string Identity{owned get; set;}
public abstract string DesktopEntry{owned get; set;}
// methods
public abstract async void Quit() throws IOError;
public abstract async void Raise() throws IOError;
}
[DBus (name = "org.mpris.MediaPlayer2.Player")]
public interface MprisPlayer : Object {
// properties
public abstract HashTable Metadata{owned get; set;}
public abstract int32 Position{owned get; set;}
public abstract string PlaybackStatus{owned get; set;}
// methods
public abstract async void PlayPause() throws IOError;
public abstract async void Next() throws IOError;
public abstract async void Previous() throws IOError;
public abstract async void Seek(int64 offset) throws IOError;
// signals
public signal void Seeked(int64 new_position);
}
// Playlist container
public struct PlaylistDetails{
public ObjectPath path;
public string name;
public string icon_name;
}
// Active playlist property container
public struct ActivePlaylistContainer{
public bool valid;
public PlaylistDetails details;
}
[DBus (name = "org.mpris.MediaPlayer2.Playlists")]
public interface MprisPlaylists : Object {
//properties
public abstract string[] Orderings{owned get; set;}
public abstract uint32 PlaylistCount{owned get; set;}
public abstract ActivePlaylistContainer ActivePlaylist {owned get; set;}
//methods
public abstract async void ActivatePlaylist(ObjectPath playlist_id) throws IOError;
public abstract async PlaylistDetails[] GetPlaylists ( uint32 index,
uint32 max_count,
string order,
bool reverse_order ) throws IOError;
//signals
public signal void PlaylistChanged (PlaylistDetails details);
}
public class Mpris2Watcher : GLib.Object
{
FreeDesktopObject fdesktop_obj;
public signal void client_appeared ();
public signal void client_disappeared ();
public Mpris2Watcher ()
{
}
construct
{
try {
this.fdesktop_obj = Bus.get_proxy_sync ( BusType.SESSION,
FREEDESKTOP_SERVICE,
FREEDESKTOP_OBJECT,
DBusProxyFlags.DO_NOT_LOAD_PROPERTIES );
this.fdesktop_obj.name_owner_changed.connect (this.name_changes_detected);
}
catch ( IOError e ){
warning( "Mpris2watcher could not set up a watch for mpris clients appearing on the bus: %s",
e.message );
}
}
// At startup check to see if there are clients up that we are interested in
public async void check_for_active_clients()
{
string[] interfaces;
try{
interfaces = yield this.fdesktop_obj.list_names();
}
catch ( IOError e) {
warning( "Mpris2watcher could fetch active interfaces at startup: %s",
e.message );
return;
}
foreach (var address in interfaces) {
if (address.has_prefix (MPRIS_PREFIX)){
MprisRoot? mpris2_root = this.create_mpris_root(address);
if (mpris2_root == null) return;
client_appeared ();
}
}
}
private void name_changes_detected ( FreeDesktopObject dbus_obj,
string name,
string previous_owner,
string current_owner )
{
MprisRoot? mpris2_root = this.create_mpris_root(name);
if (mpris2_root == null) return;
if (previous_owner == "" && current_owner != "") {
debug ("Client '%s' has appeared", name);
client_appeared ();
}
}
private MprisRoot? create_mpris_root ( string name ){
MprisRoot mpris2_root = null;
if ( name.has_prefix (MPRIS_PREFIX) ){
try {
mpris2_root = Bus.get_proxy_sync ( BusType.SESSION,
name,
MPRIS_MEDIA_PLAYER_PATH );
}
catch (IOError e){
warning( "Mpris2watcher could not create a root interface: %s",
e.message );
}
}
return mpris2_root;
}
}
public class Mpris2Controller : GLib.Object
{
public string dbus_name {get; construct;}
public MprisRoot mpris2_root;
public MprisPlayer player;
public MprisPlaylists playlists;
public HashMap name_changed_playlistdetails{get; construct;}
public Mpris2Controller(string name)
{
GLib.Object (dbus_name : name);
}
construct{
try {
this.name_changed_playlistdetails = new HashMap();
this.mpris2_root = Bus.get_proxy_sync ( BusType.SESSION,
dbus_name,
"/org/mpris/MediaPlayer2" );
this.player = Bus.get_proxy_sync ( BusType.SESSION,
dbus_name,
"/org/mpris/MediaPlayer2" );
this.playlists = Bus.get_proxy_sync ( BusType.SESSION,
dbus_name,
"/org/mpris/MediaPlayer2" );
this.playlists.PlaylistChanged.connect (on_playlistdetails_changed);
}
catch (IOError e) {
critical("Can't create our DBus interfaces - %s", e.message);
}
}
private void on_playlistdetails_changed (PlaylistDetails details)
{
this.name_changed_playlistdetails.set (details.name, details);
}
}
public class MprisClient : GLib.Object
{
public MainLoop mainloop {get; construct;}
public Mpris2Watcher watcher;
public MprisClient (MainLoop loop)
{
GLib.Object (mainloop : loop);
}
construct{
this.watcher = new Mpris2Watcher();
watcher.client_appeared.connect (on_client_appeared);
watcher.check_for_active_clients();
}
public void on_client_appeared ()
{
Timeout.add_seconds (5, () =>{
run_tests();
return escape();
});
}
public bool escape()
{
this.mainloop.quit();
return false;
}
public static int main (string[] args)
{
Environment.set_variable ("XDG_DATA_HOME", Config.TESTDIR+"/data", true);
MainLoop mainloop = new MainLoop (MainContext.default(), false);
Test.init (ref args);
GLib.Test.add_data_func ("/Integration/SoundMenu/Mpris/Backend/Root/Identity",
root_identity);
GLib.Test.add_data_func ("/Integration/SoundMenu/Mpris/Backend/Root/DesktopEntry",
root_desktop_entry);
GLib.Test.add_data_func ("/Integration/SoundMenu/Mpris/Backend/Root/CanRaise",
root_can_raise);
GLib.Test.add_data_func ("/Integration/SoundMenu/Mpris/Backend/Player/CurrentTrack",
player_current_metadata);
GLib.Test.add_data_func ("/Integration/SoundMenu/Mpris/Backend/Player/PlaybackStatus",
player_current_playback_status);
GLib.Test.add_data_func ("/Integration/SoundMenu/Mpris/Backend/Blacklisting",
test_blacklist_check);
GLib.Test.add_data_func ("/Integration/SoundMenu/Mpris/Backend/Playlist/CurrentPlaylist",
playlists_current_playlist);
GLib.Test.add_data_func ("/Integration/SoundMenu/Mpris/Backend/Playlist/GetPlaylists",
playlists_test_get_playlists);
GLib.Test.add_data_func ("/Integration/SoundMenu/Mpris/Backend/Playlist/PlaylistCount",
playlists_test_playlist_count);
GLib.Test.add_data_func ("/Integration/SoundMenu/Mpris/Backend/Playlist/Orderings",
playlists_test_playlist_orderings);
GLib.Test.add_data_func ("/Integration/SoundMenu/Mpris/Backend/Playlist/ActivatePlaylist",
playlists_test_activate_playlist);
MprisClient client = new MprisClient (mainloop);
/* Make sure we flush and sync all needed state */
while (mainloop.get_context().pending() == true){
mainloop.get_context().iteration (true);
}
mainloop.run();
return 0;
}
public static bool run_tests()
{
Test.run ();
return false;
}
internal static void root_identity ()
{
var controller = new Mpris2Controller ("org.mpris.MediaPlayer2.rhythmbox");
if (controller.mpris2_root.Identity != "Rhythmbox")
{
critical ("Expected 'Rhythmbox', but found '%s'",
controller.mpris2_root.Identity);
assert (controller.mpris2_root.Identity == "Rhythmbox");
}
}
internal static void root_desktop_entry ()
{
var controller = new Mpris2Controller ("org.mpris.MediaPlayer2.rhythmbox");
assert (controller.mpris2_root.DesktopEntry == "rhythmbox");
}
internal static void root_can_raise ()
{
var controller = new Mpris2Controller ("org.mpris.MediaPlayer2.rhythmbox");
assert (controller.mpris2_root.CanRaise == true);
}
internal static void player_current_metadata ()
{
var controller = new Mpris2Controller ("org.mpris.MediaPlayer2.rhythmbox");
Variant? v_artist = controller.player.Metadata.lookup ("xesam:artist");
Variant? v_album = controller.player.Metadata.lookup ("xesam:album");
Variant? v_title = controller.player.Metadata.lookup ("xesam:title");
Variant? v_art = controller.player.Metadata.lookup ("mpris:artUrl");
assert (v_artist.get_string() == "Autechre");
assert (v_album.get_string() == "LP5");
assert (v_title.get_string() == "Rae");
assert (v_art.get_string() == "file:///home/user/download/ae_lp5.jpg");
}
internal static void player_current_playback_status ()
{
var controller = new Mpris2Controller ("org.mpris.MediaPlayer2.rhythmbox");
assert (controller.player.PlaybackStatus == "Paused");
controller.player.PlayPause();
Timeout.add (2, test_playbackstatus_change);
}
internal static bool test_playbackstatus_change ()
{
var controller = new Mpris2Controller ("org.mpris.MediaPlayer2.rhythmbox");
assert (controller.player.PlaybackStatus == "Playing");
controller.player.PlayPause();
Timeout.add (2, test_second_playbackstatus_change);
return false;
}
internal static bool test_second_playbackstatus_change ()
{
var controller = new Mpris2Controller ("org.mpris.MediaPlayer2.rhythmbox");
assert (controller.player.PlaybackStatus == "Paused");
return false;
}
// This test is flaky, I'm unsure why ...
internal static void test_blacklist_check()
{
var controller = new Mpris2Controller ("org.mpris.MediaPlayer2.rhythmbox");
// TODO - timeout needed ?
var settings = new Settings ("com.canonical.indicator.sound");
var blacklist = settings.get_strv ("blacklisted-media-players");
bool present = false;
foreach (var s in blacklist){
//debug("%s is blacklisted", s);
if (s == controller.mpris2_root.DesktopEntry){
present = true;
}
}
assert (present == false);
}
internal static void playlists_current_playlist()
{
var controller = new Mpris2Controller ("org.mpris.MediaPlayer2.rhythmbox");
assert (controller.playlists.ActivePlaylist.valid == true);
assert (controller.playlists.ActivePlaylist.details.path == "/fake/pl/id");
assert (controller.playlists.ActivePlaylist.details.name == "yellow swans like");
assert (controller.playlists.ActivePlaylist.details.icon_name == "audio-volume-high");
}
internal static void playlists_test_playlist_count()
{
var controller = new Mpris2Controller ("org.mpris.MediaPlayer2.rhythmbox");
assert(controller.playlists.PlaylistCount == 2);
}
internal static void playlists_test_playlist_orderings()
{
var controller = new Mpris2Controller ("org.mpris.MediaPlayer2.rhythmbox");
assert(controller.playlists.Orderings.length == 1);
assert(controller.playlists.Orderings[0] == "alphabetical");
}
internal static void playlists_test_get_playlists()
{
MainLoop loop = new MainLoop();
do_test_async_get_playlists (loop);
loop.run();
}
internal static async void do_test_async_get_playlists (MainLoop loop)
{
var controller = new Mpris2Controller ("org.mpris.MediaPlayer2.rhythmbox");
try{
PlaylistDetails[] pls = yield controller.playlists.GetPlaylists (0,
10,
"alphabetical",
false);
assert (pls.length == 2);
assert((string)pls[0].path == "/fake/pl/id");
assert((string)pls[1].path == "/fake/pl2/id");
assert (pls[0].name == "yellow swans like");
assert (pls[1].name == "another playlist");
assert (pls[0].icon_name == "audio-volume-high");
assert (pls[1].icon_name == "audio-volume-high");
}
catch (IOError e){
warning ("do_test_async_get_playlists: Failed to get the playlists asynchronously");
}
loop.quit();
}
internal static void playlists_test_activate_playlist()
{
MainLoop loop = new MainLoop();
do_test_async_activate_playlist (loop);
loop.run();
}
internal static async void do_test_async_activate_playlist (MainLoop loop)
{
var contr = new Mpris2Controller ("org.mpris.MediaPlayer2.rhythmbox");
try{
PlaylistDetails[] pls = yield contr.playlists.GetPlaylists (0,
10,
"alphabetical",
false);
contr.playlists.ActivatePlaylist.begin(pls[1].path);
// Give it a sec
Timeout.add_seconds (2, () => {
assert (contr.playlists.ActivePlaylist.valid == true);
assert (contr.playlists.ActivePlaylist.details.path == "/fake/pl2/id");
assert (contr.playlists.ActivePlaylist.details.name == "another playlist");
assert (contr.playlists.ActivePlaylist.details.icon_name == "audio-volume-high");
return false;
});
}
catch (IOError e){
warning ("do_test_async_activate_playlist: Failed to activate playlist asynchronously");
}
loop.quit();
}
}
libunity-7.1.4+15.10.20151002/test/vala/test-preferences.vala 0000644 0000153 0000161 00000004365 12603350222 023732 0 ustar pbuser pbgroup 0000000 0000000 /* -*- Mode: vala; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*- */
/*
* Copyright (C) 2012 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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, see .
*
* Authored by Didier Roche
*
*/
using Unity;
namespace Unity.Test
{
public class PreferencesSuite
{
public PreferencesSuite ()
{
GLib.Test.add_data_func ("/Unit/Preferences/GsettingsLoad",
test_loading_remote_search_preference);
GLib.Test.add_data_func ("/Unit/Preferences/AlwaysSearch",
test_always_search_preference);
GLib.Test.add_data_func ("/Unit/Preferences/Singleton",
test_singleton);
}
internal static void test_loading_remote_search_preference ()
{
var p = Unity.PreferencesManager.get_default ();
assert (p.remote_content_search == Unity.PreferencesManager.RemoteContent.ALL);
var gp_settings = new Settings ("com.canonical.Unity.Lenses");
gp_settings.set_string ("remote-content-search", "none");
assert (p.remote_content_search == Unity.PreferencesManager.RemoteContent.NONE);
}
internal static void test_always_search_preference ()
{
var p = Unity.PreferencesManager.get_default ();
assert (p.always_search.length == 4);
string reference [4] = new string [] {"applications.scope","music.scope","videos.scope","files.scope"};
for (int i=0; i