./0000755000015600001650000000000012701256660011102 5ustar jenkinsjenkins./cmake/0000755000015600001650000000000012701256660012162 5ustar jenkinsjenkins./cmake/UseGSettings.cmake0000644000015600001650000000210212701256660015543 0ustar jenkinsjenkins# GSettings.cmake, CMake macros written for Marlin, feel free to re-use them. macro(add_schema SCHEMA_NAME) set(PKG_CONFIG_EXECUTABLE pkg-config) set(GSETTINGS_DIR "${CMAKE_INSTALL_FULL_DATAROOTDIR}/glib-2.0/schemas") # Run the validator and error if it fails execute_process (COMMAND ${PKG_CONFIG_EXECUTABLE} gio-2.0 --variable glib_compile_schemas OUTPUT_VARIABLE _glib_compile_schemas OUTPUT_STRIP_TRAILING_WHITESPACE) execute_process (COMMAND ${_glib_compile_schemas} --dry-run --schema-file=${SCHEMA_NAME} ERROR_VARIABLE _schemas_invalid OUTPUT_STRIP_TRAILING_WHITESPACE) if (_schemas_invalid) message (SEND_ERROR "Schema validation error: ${_schemas_invalid}") endif (_schemas_invalid) # Actually install and recomple schemas message (STATUS "${GSETTINGS_DIR} is the GSettings install dir") install (FILES ${SCHEMA_NAME} DESTINATION ${GSETTINGS_DIR} OPTIONAL) install (CODE "message (STATUS \"Compiling GSettings schemas\")") install (CODE "execute_process (COMMAND ${_glib_compile_schemas} ${GSETTINGS_DIR})") endmacro() ./cmake/Translations.cmake0000644000015600001650000000304212701256660015644 0ustar jenkinsjenkins# Translations.cmake, CMake macros written for Marlin, feel free to re-use them macro(add_translations_directory NLS_PACKAGE) add_custom_target (i18n ALL) find_program (MSGFMT_EXECUTABLE msgfmt) file (GLOB PO_FILES ${CMAKE_CURRENT_SOURCE_DIR}/*.po) foreach (PO_INPUT ${PO_FILES}) get_filename_component (PO_INPUT_BASE ${PO_INPUT} NAME_WE) set (MO_OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${PO_INPUT_BASE}.mo) add_custom_command (TARGET i18n COMMAND ${MSGFMT_EXECUTABLE} -o ${MO_OUTPUT} ${PO_INPUT}) install (FILES ${MO_OUTPUT} DESTINATION ${CMAKE_INSTALL_LOCALEDIR}/${PO_INPUT_BASE}/LC_MESSAGES RENAME ${NLS_PACKAGE}.mo) endforeach (PO_INPUT ${PO_FILES}) endmacro(add_translations_directory) macro(add_translations_catalog NLS_PACKAGE) add_custom_target (pot COMMENT “Building translation catalog.”) find_program (XGETTEXT_EXECUTABLE xgettext) # init this list, which will hold all the sources across all dirs set(SOURCES "") # add each directory's sources to the overall sources list foreach(FILES_INPUT ${ARGN}) set (DIR ${CMAKE_CURRENT_SOURCE_DIR}/${FILES_INPUT}) file (GLOB_RECURSE DIR_SOURCES ${DIR}/*.c ${DIR}/*.cc ${DIR}/*.cpp ${DIR}/*.cxx ${DIR}/*.vala) set (SOURCES ${SOURCES} ${DIR_SOURCES}) endforeach() add_custom_command (TARGET pot COMMAND ${XGETTEXT_EXECUTABLE} -d ${NLS_PACKAGE} -o ${CMAKE_CURRENT_SOURCE_DIR}/${NLS_PACKAGE}.pot ${SOURCES} --keyword="_" --keyword="N_" --from-code=UTF-8 ) endmacro() ./cmake/FindIntltool.cmake0000644000015600001650000000146112701256660015573 0ustar jenkinsjenkins# FindIntltool.cmake # # Jim Nelson # Copyright 2012 Yorba Foundation find_program (INTLTOOL_MERGE_EXECUTABLE intltool-merge) if (INTLTOOL_MERGE_EXECUTABLE) set (INTLTOOL_MERGE_FOUND TRUE) else (INTLTOOL_MERGE_EXECUTABLE) set (INTLTOOL_MERGE_FOUND FALSE) endif (INTLTOOL_MERGE_EXECUTABLE) if (INTLTOOL_MERGE_FOUND) macro (INTLTOOL_MERGE_DESKTOP desktop_id po_dir) add_custom_target (geary.desktop ALL ${INTLTOOL_MERGE_EXECUTABLE} --desktop-style ${CMAKE_SOURCE_DIR}/${po_dir} ${CMAKE_CURRENT_SOURCE_DIR}/${desktop_id}.desktop.in ${desktop_id}.desktop ) install (FILES ${CMAKE_CURRENT_BINARY_DIR}/geary.desktop DESTINATION /usr/share/applications) endmacro (INTLTOOL_MERGE_DESKTOP desktop_id po_dir) endif (INTLTOOL_MERGE_FOUND) ./cmake/GdbusCodegen.cmake0000644000015600001650000000246512701256660015524 0ustar jenkinsjenkinscmake_minimum_required(VERSION 2.6) if(POLICY CMP0011) cmake_policy(SET CMP0011 NEW) endif(POLICY CMP0011) find_program(GDBUS_CODEGEN NAMES gdbus-codegen DOC "gdbus-codegen executable") if(NOT GDBUS_CODEGEN) message(FATAL_ERROR "Excutable gdbus-codegen not found") endif() macro(add_gdbus_codegen outfiles name prefix service_xml) add_custom_command( OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${name}.h" "${CMAKE_CURRENT_BINARY_DIR}/${name}.c" COMMAND "${GDBUS_CODEGEN}" --interface-prefix "${prefix}" --generate-c-code "${name}" "${service_xml}" WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} DEPENDS ${ARGN} "${service_xml}" ) list(APPEND ${outfiles} "${CMAKE_CURRENT_BINARY_DIR}/${name}.c") endmacro(add_gdbus_codegen) macro(add_gdbus_codegen_with_namespace outfiles name prefix namespace service_xml) add_custom_command( OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${name}.h" "${CMAKE_CURRENT_BINARY_DIR}/${name}.c" COMMAND "${GDBUS_CODEGEN}" --interface-prefix "${prefix}" --generate-c-code "${name}" --c-namespace "${namespace}" "${service_xml}" WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} DEPENDS ${ARGN} "${service_xml}" ) list(APPEND ${outfiles} "${CMAKE_CURRENT_BINARY_DIR}/${name}.c") endmacro(add_gdbus_codegen_with_namespace) ./cmake/GCov.cmake0000644000015600001650000000533512701256660014030 0ustar jenkinsjenkinsif (CMAKE_BUILD_TYPE MATCHES coverage) set(GCOV_FLAGS "${GCOV_FLAGS} --coverage") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${GCOV_FLAGS}") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${GCOV_FLAGS}") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${GCOV_FLAGS}") set(GCOV_LIBS ${GCOV_LIBS} gcov) find_program(GCOVR_EXECUTABLE gcovr HINTS ${GCOVR_ROOT} "${GCOVR_ROOT}/bin") if (NOT GCOVR_EXECUTABLE) message(STATUS "Gcovr binary was not found, can not generate XML coverage info.") else () message(STATUS "Gcovr found, can generate XML coverage info.") add_custom_target (coverage-xml WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND "${GCOVR_EXECUTABLE}" --exclude="test.*" -x -r "${CMAKE_SOURCE_DIR}" --object-directory=${CMAKE_BINARY_DIR} -o coverage.xml) endif() find_program(LCOV_EXECUTABLE lcov HINTS ${LCOV_ROOT} "${GCOVR_ROOT}/bin") find_program(GENHTML_EXECUTABLE genhtml HINTS ${GENHTML_ROOT}) if (NOT LCOV_EXECUTABLE) message(STATUS "Lcov binary was not found, can not generate HTML coverage info.") else () if(NOT GENHTML_EXECUTABLE) message(STATUS "Genthml binary not found, can not generate HTML coverage info.") else() message(STATUS "Lcov and genhtml found, can generate HTML coverage info.") add_custom_target (coverage-html WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND "${CMAKE_CTEST_COMMAND}" --force-new-ctest-process --verbose COMMAND "${LCOV_EXECUTABLE}" --directory ${CMAKE_BINARY_DIR} --capture | ${CMAKE_SOURCE_DIR}/trim-lcov.py > dconf-lcov.info COMMAND "${LCOV_EXECUTABLE}" -r dconf-lcov.info /usr/include/\\* -o nosys-lcov.info COMMAND LANG=C "${GENHTML_EXECUTABLE}" --prefix ${CMAKE_BINARY_DIR} --output-directory lcov-html --legend --show-details nosys-lcov.info COMMAND ${CMAKE_COMMAND} -E echo "" COMMAND ${CMAKE_COMMAND} -E echo "file://${CMAKE_BINARY_DIR}/lcov-html/index.html" COMMAND ${CMAKE_COMMAND} -E echo "") #COMMAND "${LCOV_EXECUTABLE}" --directory ${CMAKE_BINARY_DIR} --capture --output-file coverage.info --no-checksum #COMMAND "${GENHTML_EXECUTABLE}" --prefix ${CMAKE_BINARY_DIR} --output-directory coveragereport --title "Code Coverage" --legend --show-details coverage.info #COMMAND ${CMAKE_COMMAND} -E echo "\\#define foo \\\"bar\\\"" #) endif() endif() endif() #$(MAKE) $(AM_MAKEFLAGS) check #lcov --directory $(top_builddir) --capture --test-name dconf | $(top_srcdir)/trim-lcov.py > dconf-lcov.info #LANG=C genhtml --prefix $(top_builddir) --output-directory lcov-html --legend --show-details dconf-lcov.info #@echo #@echo " file://$(abs_top_builddir)/lcov-html/index.html" #@echo ./tests/0000755000015600001650000000000012701256660012244 5ustar jenkinsjenkins./tests/test-eds-ics-tzids.cpp0000644000015600001650000000570712701256660016420 0ustar jenkinsjenkins/* * Copyright 2015 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include #include #include #include #include "glib-fixture.h" #include "print-to.h" #include "timezone-mock.h" #include "wakeup-timer-mock.h" using namespace unity::indicator::datetime; using VAlarmFixture = GlibFixture; /*** **** ***/ TEST_F(VAlarmFixture, MultipleAppointments) { // start the EDS engine auto engine = std::make_shared(); // we need a consistent timezone for the planner and our local DateTimes constexpr char const * zone_str {"Europe/Berlin"}; auto tz = std::make_shared(zone_str); auto gtz = g_time_zone_new(zone_str); // make a planner that looks at the first half of 2015 in EDS auto planner = std::make_shared(engine, tz); const DateTime range_begin {gtz, 2015,7, 1, 0, 0, 0.0}; const DateTime range_end {gtz, 2015,7,31,23,59,59.5}; planner->range().set(std::make_pair(range_begin, range_end)); // give EDS a moment to load if (planner->appointments().get().empty()) { g_message("waiting a moment for EDS to load..."); auto on_appointments_changed = [this](const std::vector& appointments){ g_message("ah, they loaded"); if (!appointments.empty()) g_main_loop_quit(loop); }; core::ScopedConnection conn(planner->appointments().changed().connect(on_appointments_changed)); constexpr int max_wait_sec = 10; wait_msec(max_wait_sec * G_TIME_SPAN_MILLISECOND); } // what we expect to get... std::array expected_appts; auto appt = &expected_appts[0]; appt->uid = "8ggc30kh89qql8vjumgtug7l14@google.com"; appt->color = "#becedd"; appt->summary = "Hello"; appt->begin = DateTime{gtz,2015,7,1,20,0,0}; appt->end = DateTime{gtz,2015,7,1,22,0,0}; // compare it to what we actually loaded... const auto appts = planner->appointments().get(); EXPECT_EQ(expected_appts.size(), appts.size()); for (size_t i=0, n=std::min(appts.size(),expected_appts.size()); i * * 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . */ #ifndef INDICATOR_DATETIME_TESTS_GLIB_FIXTURE_H #define INDICATOR_DATETIME_TESTS_GLIB_FIXTURE_H #include // std::function #include #include // std::shared_ptr #include #include #include #include #include // setlocale() class GlibFixture : public ::testing::Test { public: virtual ~GlibFixture() =default; protected: virtual void SetUp() override { setlocale(LC_ALL, "C.UTF-8"); loop = g_main_loop_new(nullptr, false); // only use local, temporary settings g_assert(g_setenv("GSETTINGS_SCHEMA_DIR", SCHEMA_DIR, true)); g_assert(g_setenv("GSETTINGS_BACKEND", "memory", true)); g_debug("SCHEMA_DIR is %s", SCHEMA_DIR); // fail on unexpected messages from this domain g_log_set_fatal_mask(G_LOG_DOMAIN, G_LOG_LEVEL_WARNING); g_unsetenv("DISPLAY"); } virtual void TearDown() override { g_test_assert_expected_messages (); g_clear_pointer(&loop, g_main_loop_unref); } void expectLogMessage (const gchar *domain, GLogLevelFlags level, const gchar *pattern) { g_test_expect_message (domain, level, pattern); } private: static gboolean wait_for_signal__timeout(gpointer name) { g_error("%s: timed out waiting for signal '%s'", G_STRLOC, (char*)name); return G_SOURCE_REMOVE; } static gboolean wait_msec__timeout(gpointer loop) { g_main_loop_quit(static_cast(loop)); return G_SOURCE_CONTINUE; } protected: /* convenience func to loop while waiting for a GObject's signal */ void wait_for_signal(gpointer o, const gchar * signal, const int timeout_seconds=5) { // wait for the signal or for timeout, whichever comes first const auto handler_id = g_signal_connect_swapped(o, signal, G_CALLBACK(g_main_loop_quit), loop); const auto timeout_id = g_timeout_add_seconds(timeout_seconds, wait_for_signal__timeout, loop); g_main_loop_run(loop); g_source_remove(timeout_id); g_signal_handler_disconnect(o, handler_id); } /* convenience func to loop for N msec */ void wait_msec(int msec=50) { const auto id = g_timeout_add(msec, wait_msec__timeout, loop); g_main_loop_run(loop); g_source_remove(id); } bool wait_for(std::function test_function, guint timeout_msec=1000) { auto timer = std::shared_ptr(g_timer_new(), [](GTimer* t){g_timer_destroy(t);}); const auto timeout_sec = timeout_msec / 1000.0; for (;;) { if (test_function()) return true; //g_message("%f ... %f", g_timer_elapsed(timer.get(), nullptr), timeout_sec); if (g_timer_elapsed(timer.get(), nullptr) >= timeout_sec) return false; wait_msec(); } } bool wait_for_name_owned(GDBusConnection* connection, const gchar* name, guint timeout_msec=1000, GBusNameWatcherFlags flags=G_BUS_NAME_WATCHER_FLAGS_AUTO_START) { struct Data { GMainLoop* loop = nullptr; bool owned = false; }; Data data; auto on_name_appeared = [](GDBusConnection* /*connection*/, const gchar* /*name_*/, const gchar* name_owner, gpointer gdata) { if (name_owner == nullptr) return; auto tmp = static_cast(gdata); tmp->owned = true; g_main_loop_quit(tmp->loop); }; const auto timeout_id = g_timeout_add(timeout_msec, wait_msec__timeout, loop); data.loop = loop; const auto watch_id = g_bus_watch_name_on_connection(connection, name, flags, on_name_appeared, nullptr, /* name_vanished */ &data, nullptr); /* user_data_free_func */ g_main_loop_run(loop); g_bus_unwatch_name(watch_id); g_source_remove(timeout_id); return data.owned; } void EXPECT_NAME_OWNED_EVENTUALLY(GDBusConnection* connection, const gchar* name, guint timeout_msec=1000, GBusNameWatcherFlags flags=G_BUS_NAME_WATCHER_FLAGS_AUTO_START) { EXPECT_TRUE(wait_for_name_owned(connection, name, timeout_msec, flags)) << "name: " << name; } void EXPECT_NAME_NOT_OWNED_EVENTUALLY(GDBusConnection* connection, const gchar* name, guint timeout_msec=1000, GBusNameWatcherFlags flags=G_BUS_NAME_WATCHER_FLAGS_AUTO_START) { EXPECT_FALSE(wait_for_name_owned(connection, name, timeout_msec, flags)) << "name: " << name; } void ASSERT_NAME_OWNED_EVENTUALLY(GDBusConnection* connection, const gchar* name, guint timeout_msec=1000, GBusNameWatcherFlags flags=G_BUS_NAME_WATCHER_FLAGS_AUTO_START) { ASSERT_TRUE(wait_for_name_owned(connection, name, timeout_msec, flags)) << "name: " << name; } void ASSERT_NAME_NOT_OWNED_EVENTUALLY(GDBusConnection* connection, const gchar* name, guint timeout_msec=1000, GBusNameWatcherFlags flags=G_BUS_NAME_WATCHER_FLAGS_AUTO_START) { ASSERT_FALSE(wait_for_name_owned(connection, name, timeout_msec, flags)) << "name: " << name; } GMainLoop * loop; }; #endif /* INDICATOR_DATETIME_TESTS_GLIB_FIXTURE_H */ ./tests/test-eds-ics-tzids-2.ics.in0000644000015600001650000000201312701256660017143 0ustar jenkinsjenkinsBEGIN:VCALENDAR CALSCALE:GREGORIAN PRODID:-//Ximian//NONSGML Evolution Calendar//EN VERSION:2.0 X-EVOLUTION-DATA-REVISION:2015-07-09T19:41:50.123217Z(3) BEGIN:VTIMEZONE TZID:Pacific Time (US & Canada) BEGIN:STANDARD DTSTART:20061105T020000 RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=11 TZOFFSETFROM:-0700 TZOFFSETTO:-0800 END:STANDARD BEGIN:DAYLIGHT DTSTART:20070311T020000 RRULE:FREQ=YEARLY;BYDAY=2SU;BYMONTH=3 TZOFFSETFROM:-0800 TZOFFSETTO:-0700 TZNAME:Daylight Savings Time END:DAYLIGHT END:VTIMEZONE BEGIN:VEVENT DTSTART;TZID=Pacific Time (US & Canada):20140121T110000 DTEND;TZID=Pacific Time (US & Canada):20140121T130000 UID:109264742 DTSTAMP:20140120T000718Z DESCRIPTION: Event description SUMMARY;ENCODING=QUOTED-PRINTABLE:National Incubator Initiative for Clean Energy (NIICE) FOA: Pre-Concept Paper Informational Webinar CREATED:20140120T000741Z LAST-MODIFIED:20140120T000741Z BEGIN:VALARM TRIGGER;VALUE=DURATION:-PT15M ACTION:DISPLAY DESCRIPTION:Reminder END:VALARM END:VEVENT END:VCALENDAR ./tests/run-eds-ics-test.sh0000755000015600001650000000407512701256660015717 0ustar jenkinsjenkins#!/bin/sh SELF=$0 # this script TEST_RUNNER=$1 # full executable path of dbus-test-runner TEST_EXEC=$2 # full executable path of test app TEST_NAME=$3 # test name CONFIG_DIR=$4 # config files ICS_FILE=$5 # ical file holding test data echo "this script: ${SELF}" echo "test-runner: ${TEST_RUNNER}" echo "test-exec: ${TEST_EXEC}" echo "test-name: ${TEST_NAME}" echo "config-dir: ${CONFIG_DIR}" echo "ics-file: ${ICS_FILE}" # set up the tmpdir export TEST_TMP_DIR=$(mktemp -p "${TMPDIR:-/tmp}" -d ${TEST_NAME}-XXXXXXXXXX) || exit 1 echo "running test '${TEST_NAME}' in ${TEST_TMP_DIR}" # set up the environment variables export QT_QPA_PLATFORM=minimal export HOME=${TEST_TMP_DIR} export XDG_RUNTIME_DIR=${TEST_TMP_DIR} export XDG_CACHE_HOME=${TEST_TMP_DIR}/.cache export XDG_CONFIG_HOME=${TEST_TMP_DIR}/.config export XDG_DATA_HOME=${TEST_TMP_DIR}/.local/share export XDG_DESKTOP_DIR=${TEST_TMP_DIR} export XDG_DOCUMENTS_DIR=${TEST_TMP_DIR} export XDG_DOWNLOAD_DIR=${TEST_TMP_DIR} export XDG_MUSIC_DIR=${TEST_TMP_DIR} export XDG_PICTURES_DIR=${TEST_TMP_DIR} export XDG_PUBLICSHARE_DIR=${TEST_TMP_DIR} export XDG_TEMPLATES_DIR=${TEST_TMP_DIR} export XDG_VIDEOS_DIR=${TEST_TMP_DIR} export QORGANIZER_EDS_DEBUG=On export GIO_USE_VFS=local # needed to ensure GVFS shuts down cleanly after the test is over export G_MESSAGES_DEBUG=all export G_DBUS_DEBUG=messages echo HOMEDIR=${HOME} rm -rf ${XDG_DATA_HOME} # if there are canned config files for this test, move them into place now if [ -d ${CONFIG_DIR} ]; then echo "copying files from ${CONFIG_DIR} to $HOME" cp --verbose --archive ${CONFIG_DIR}/. $HOME fi # if there's a specific ics file to test, copy it on top of the canned config files if [ -e ${ICS_FILE} ]; then echo "copying ${ICS_FILE} into $HOME" cp --verbose --archive ${ICS_FILE} ${XDG_DATA_HOME}/evolution/tasks/system/tasks.ics fi # run the test ${TEST_RUNNER} --keep-env --max-wait=90 --task ${TEST_EXEC} --task-name ${TEST_NAME} --wait-until-complete rv=$? # if the test passed, blow away the tmpdir if [ $rv -eq 0 ]; then rm -rf $TEST_TMP_DIR fi return $rv ./tests/test-timezones.cpp0000644000015600001650000001004312701256660015740 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include "geoclue-fixture.h" #include #include #include // std::shared_ptr #include // fopen() #include // sync() using namespace unity::indicator::datetime; typedef GeoclueFixture TimezonesFixture; #define TIMEZONE_FILE (SANDBOX "/timezone") namespace { /* convenience func to set the timezone file */ void set_file(const std::string& text) { auto fp = fopen(TIMEZONE_FILE, "w+"); fprintf(fp, "%s\n", text.c_str()); fclose(fp); sync(); } } TEST_F(TimezonesFixture, ManagerTest) { std::string timezone_file = "America/New_York"; std::string timezone_geo = "America/Denver"; set_file(timezone_file); auto settings = std::make_shared(); LiveTimezones z(settings, TIMEZONE_FILE); wait_msec(500); // wait for the bus to get set up EXPECT_EQ(timezone_file, z.timezone.get()); auto zones = z.timezones.get(); //std::set zones = z.timezones.get(); EXPECT_EQ(1, zones.size()); EXPECT_EQ(1, zones.count(timezone_file)); bool zone_changed = false; auto zone_connection = z.timezone.changed().connect([&zone_changed, this](const std::string&) { zone_changed = true; g_main_loop_quit(loop); }); // start listening for a timezone change, then change the timezone bool zones_changed = false; auto zones_connection = z.timezones.changed().connect([&zones_changed, &zones, this](const std::set& timezones) { zones_changed = true; zones = timezones; g_main_loop_quit(loop); }); g_idle_add([](gpointer s_in) { auto s = static_cast(s_in); g_message("geolocation was %d", (int)s->show_detected_location.get()); g_message("turning geolocation on"); s->show_detected_location.set(true); return G_SOURCE_REMOVE; }, settings.get()); // turn on geoclue during the idle... this should add timezone_1 to the 'timezones' property g_main_loop_run(loop); EXPECT_TRUE(zones_changed); EXPECT_EQ(timezone_file, z.timezone.get()); EXPECT_EQ(2, zones.size()); EXPECT_EQ(1, zones.count(timezone_file)); EXPECT_EQ(1, zones.count(timezone_geo)); zones_changed = false; // now tweak the geoclue value... the geoclue-detected timezone should change, // causing the 'timezones' property to change zone_changed = false; zones_changed = false; timezone_geo = "America/Chicago"; setGeoclueTimezoneOnIdle(timezone_geo); g_main_loop_run(loop); EXPECT_FALSE(zone_changed); EXPECT_TRUE(zones_changed); EXPECT_EQ(timezone_file, z.timezone.get()); EXPECT_EQ(2, zones.size()); EXPECT_EQ(1, zones.count(timezone_file)); EXPECT_EQ(1, zones.count(timezone_geo)); // now set the file value... this should change both the primary property and set property zone_changed = false; zones_changed = false; timezone_file = "America/Los_Angeles"; EXPECT_EQ(0, zones.count(timezone_file)); g_idle_add([](gpointer str) {set_file(static_cast(str)); return G_SOURCE_REMOVE;}, const_cast(timezone_file.c_str())); g_main_loop_run(loop); EXPECT_TRUE(zone_changed); EXPECT_TRUE(zones_changed); EXPECT_EQ(timezone_file, z.timezone.get()); EXPECT_EQ(2, zones.size()); EXPECT_EQ(1, zones.count(timezone_file)); EXPECT_EQ(1, zones.count(timezone_geo)); } ./tests/test-eds-ics-tzids-2.cpp0000644000015600001650000000616512701256660016556 0ustar jenkinsjenkins/* * Copyright 2015 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include #include #include #include #include "glib-fixture.h" #include "print-to.h" #include "timezone-mock.h" #include "wakeup-timer-mock.h" using namespace unity::indicator::datetime; using VAlarmFixture = GlibFixture; /*** **** ***/ TEST_F(VAlarmFixture, MultipleAppointments) { // start the EDS engine auto engine = std::make_shared(); // we need a consistent timezone for the planner and our local DateTimes constexpr char const * zone_str {"America/Los_Angeles"}; auto tz = std::make_shared(zone_str); auto gtz = g_time_zone_new(zone_str); // make a planner that looks at the first half of 2015 in EDS auto planner = std::make_shared(engine, tz); const DateTime range_begin {gtz, 2006,1, 1, 0, 0, 0.0}; const DateTime range_end {gtz, 2015,12,31,23,59,59.5}; planner->range().set(std::make_pair(range_begin, range_end)); // give EDS a moment to load if (planner->appointments().get().empty()) { g_message("waiting a moment for EDS to load..."); auto on_appointments_changed = [this](const std::vector& appointments){ g_message("ah, they loaded"); if (!appointments.empty()) g_main_loop_quit(loop); }; core::ScopedConnection conn(planner->appointments().changed().connect(on_appointments_changed)); constexpr int max_wait_sec = 10; wait_msec(max_wait_sec * G_TIME_SPAN_MILLISECOND); } // what we expect to get... std::array expected_appts; auto appt = &expected_appts[0]; appt->uid = "109264742"; appt->color = "#becedd"; appt->summary = "National Incubator Initiative for Clean Energy (NIICE) FOA: Pre-Concept Paper Informational Webinar"; appt->begin = DateTime{gtz,2014,1,21,11,0,0}; appt->end = DateTime{gtz,2014,1,21,13,0,0}; appt->alarms = std::vector{ Alarm({"Reminder", "", DateTime(gtz,2014,1,21,10,45,0)}) }; // compare it to what we actually loaded... const auto appts = planner->appointments().get(); EXPECT_EQ(expected_appts.size(), appts.size()); for (size_t i=0, n=std::min(appts.size(),expected_appts.size()); i. * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_WAKEUP_TIMER_MOCK_H #define INDICATOR_DATETIME_WAKEUP_TIMER_MOCK_H #include #include namespace unity { namespace indicator { namespace datetime { /*** **** ***/ /** * \brief A one-shot timer that emits a signal when its timeout is reached. */ class MockWakeupTimer: public WakeupTimer { public: explicit MockWakeupTimer(const std::shared_ptr& clock): m_clock(clock) { m_clock->minute_changed.connect([this](){ test_for_wakeup(); }); } virtual ~MockWakeupTimer() =default; virtual void set_wakeup_time (const DateTime& wakeup_time) override { m_wakeup_time = wakeup_time; test_for_wakeup(); } virtual core::Signal<>& timeout() override { return m_timeout; } private: void test_for_wakeup() { if (DateTime::is_same_minute(m_clock->localtime(), m_wakeup_time)) m_timeout(); } core::Signal<> m_timeout; const std::shared_ptr& m_clock; DateTime m_wakeup_time; }; /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_WAKEUP_TIMER_MOCK_H ./tests/notification-fixture.h0000644000015600001650000003261512701256660016576 0ustar jenkinsjenkins/* * Copyright 2014-2016 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #pragma once #include "libdbusmock-fixture.h" #include #include #include #include #include #include #include #include // getuid() #include // getuid() /*** **** ***/ class NotificationFixture: public LibdbusmockFixture { private: typedef LibdbusmockFixture super; protected: static constexpr char const * NOTIFY_BUSNAME {"org.freedesktop.Notifications"}; static constexpr char const * NOTIFY_INTERFACE {"org.freedesktop.Notifications"}; static constexpr char const * NOTIFY_PATH {"/org/freedesktop/Notifications"}; static constexpr char const * HAPTIC_METHOD_VIBRATE_PATTERN {"VibratePattern"}; static constexpr int SCREEN_COOKIE {8675309}; static constexpr char const * SCREEN_METHOD_KEEP_DISPLAY_ON {"keepDisplayOn"}; static constexpr char const * SCREEN_METHOD_REMOVE_DISPLAY_ON_REQUEST {"removeDisplayOnRequest"}; static constexpr int POWERD_SYS_STATE_ACTIVE = 1; static constexpr char const * POWERD_COOKIE {"567-48-8307"}; static constexpr char const * POWERD_METHOD_REQUEST_SYS_STATE {"requestSysState"}; static constexpr char const * POWERD_METHOD_CLEAR_SYS_STATE {"clearSysState"}; static constexpr int FIRST_NOTIFY_ID {1000}; static constexpr int NOTIFICATION_CLOSED_EXPIRED {1}; static constexpr int NOTIFICATION_CLOSED_DISMISSED {2}; static constexpr int NOTIFICATION_CLOSED_API {3}; static constexpr int NOTIFICATION_CLOSED_UNDEFINED {4}; static constexpr char const * METHOD_CLOSE {"CloseNotification"}; static constexpr char const * METHOD_GET_CAPS {"GetCapabilities"}; static constexpr char const * METHOD_GET_INFO {"GetServerInformation"}; static constexpr char const * METHOD_NOTIFY {"Notify"}; static constexpr char const * SIGNAL_CLOSED {"NotificationClosed"}; static constexpr char const * HINT_TIMEOUT {"x-canonical-snap-decisions-timeout"}; static constexpr char const * AS_BUSNAME {"org.freedesktop.Accounts"}; static constexpr char const * AS_INTERFACE {"com.ubuntu.touch.AccountsService.Sound"}; static constexpr char const * PROP_OTHER_VIBRATIONS {"OtherVibrate"}; static constexpr char const * PROP_SILENT_MODE {"SilentMode"}; unity::indicator::datetime::Appointment appt; unity::indicator::datetime::Appointment ualarm; DbusTestDbusMock * as_mock = nullptr; DbusTestDbusMock * notify_mock = nullptr; DbusTestDbusMock * powerd_mock = nullptr; DbusTestDbusMock * screen_mock = nullptr; DbusTestDbusMock * haptic_mock = nullptr; DbusTestDbusMockObject * as_obj = nullptr; DbusTestDbusMockObject * notify_obj = nullptr; DbusTestDbusMockObject * powerd_obj = nullptr; DbusTestDbusMockObject * screen_obj = nullptr; DbusTestDbusMockObject * haptic_obj = nullptr; void SetUp() override { GError * error = nullptr; char * str = nullptr; super::SetUp(); // init an Appointment appt.color = "green"; appt.summary = "Christmas"; appt.uid = "D4B57D50247291478ED31DED17FF0A9838DED402"; appt.type = unity::indicator::datetime::Appointment::EVENT; const auto christmas = unity::indicator::datetime::DateTime::Local(2015,12,25,0,0,0); appt.begin = christmas.start_of_day(); appt.end = christmas.end_of_day(); appt.alarms.push_back(unity::indicator::datetime::Alarm{"Ho Ho Ho!", "", appt.begin}); // init an Ubuntu Alarm ualarm.color = "red"; ualarm.summary = "Wakeup"; ualarm.uid = "E4B57D50247291478ED31DED17FF0A9838DED403"; ualarm.type = unity::indicator::datetime::Appointment::UBUNTU_ALARM; const auto tomorrow = unity::indicator::datetime::DateTime::NowLocal().add_days(1); ualarm.begin = tomorrow; ualarm.end = tomorrow; ualarm.alarms.push_back(unity::indicator::datetime::Alarm{"It's Tomorrow!", "", appt.begin}); /// /// Add the AccountsService mock /// as_mock = dbus_test_dbus_mock_new(AS_BUSNAME); auto as_path = g_strdup_printf("/org/freedesktop/Accounts/User%lu", (gulong)getuid()); as_obj = dbus_test_dbus_mock_get_object(as_mock, as_path, AS_INTERFACE, &error); g_free(as_path); g_assert_no_error(error); // PROP_SILENT_MODE dbus_test_dbus_mock_object_add_property(as_mock, as_obj, PROP_SILENT_MODE, G_VARIANT_TYPE_BOOLEAN, g_variant_new_boolean(false), &error); g_assert_no_error(error); // PROP_OTHER_VIBRATIONS dbus_test_dbus_mock_object_add_property(as_mock, as_obj, PROP_OTHER_VIBRATIONS, G_VARIANT_TYPE_BOOLEAN, g_variant_new_boolean(true), &error); g_assert_no_error(error); dbus_test_service_add_task(service, DBUS_TEST_TASK(as_mock)); /// /// Add the Notifications mock /// notify_mock = dbus_test_dbus_mock_new(NOTIFY_BUSNAME); notify_obj = dbus_test_dbus_mock_get_object(notify_mock, NOTIFY_PATH, NOTIFY_INTERFACE, &error); g_assert_no_error(error); // METHOD_GET_INFO str = g_strdup("ret = ('mock-notify', 'test vendor', '1.0', '1.1')"); dbus_test_dbus_mock_object_add_method(notify_mock, notify_obj, METHOD_GET_INFO, nullptr, G_VARIANT_TYPE("(ssss)"), str, &error); g_assert_no_error (error); g_free (str); // METHOD_NOTIFY str = g_strdup_printf("try:\n" " self.NextNotifyId\n" "except AttributeError:\n" " self.NextNotifyId = %d\n" "ret = self.NextNotifyId\n" "self.NextNotifyId += 1\n", FIRST_NOTIFY_ID); dbus_test_dbus_mock_object_add_method(notify_mock, notify_obj, METHOD_NOTIFY, G_VARIANT_TYPE("(susssasa{sv}i)"), G_VARIANT_TYPE_UINT32, str, &error); g_assert_no_error (error); g_free (str); // METHOD_CLOSE str = g_strdup_printf("self.EmitSignal('%s', '%s', 'uu', [ args[0], %d ])", NOTIFY_INTERFACE, SIGNAL_CLOSED, NOTIFICATION_CLOSED_API); dbus_test_dbus_mock_object_add_method(notify_mock, notify_obj, METHOD_CLOSE, G_VARIANT_TYPE("(u)"), nullptr, str, &error); g_assert_no_error (error); g_free (str); dbus_test_service_add_task(service, DBUS_TEST_TASK(notify_mock)); /// /// Add the powerd mock /// powerd_mock = dbus_test_dbus_mock_new(BUS_POWERD_NAME); powerd_obj = dbus_test_dbus_mock_get_object(powerd_mock, BUS_POWERD_PATH, BUS_POWERD_INTERFACE, &error); g_assert_no_error(error); str = g_strdup_printf ("ret = '%s'", POWERD_COOKIE); dbus_test_dbus_mock_object_add_method(powerd_mock, powerd_obj, POWERD_METHOD_REQUEST_SYS_STATE, G_VARIANT_TYPE("(si)"), G_VARIANT_TYPE("(s)"), str, &error); g_assert_no_error (error); g_free (str); dbus_test_dbus_mock_object_add_method(powerd_mock, powerd_obj, POWERD_METHOD_CLEAR_SYS_STATE, G_VARIANT_TYPE("(s)"), nullptr, "", &error); g_assert_no_error (error); dbus_test_service_add_task(service, DBUS_TEST_TASK(powerd_mock)); /// /// Add the Screen mock /// screen_mock = dbus_test_dbus_mock_new(BUS_SCREEN_NAME); screen_obj = dbus_test_dbus_mock_get_object(screen_mock, BUS_SCREEN_PATH, BUS_SCREEN_INTERFACE, &error); g_assert_no_error(error); str = g_strdup_printf ("ret = %d", SCREEN_COOKIE); dbus_test_dbus_mock_object_add_method(screen_mock, screen_obj, SCREEN_METHOD_KEEP_DISPLAY_ON, nullptr, G_VARIANT_TYPE("(i)"), str, &error); g_assert_no_error (error); g_free (str); dbus_test_dbus_mock_object_add_method(screen_mock, screen_obj, SCREEN_METHOD_REMOVE_DISPLAY_ON_REQUEST, G_VARIANT_TYPE("(i)"), nullptr, "", &error); g_assert_no_error (error); dbus_test_service_add_task(service, DBUS_TEST_TASK(screen_mock)); /// /// Add the haptic mock /// haptic_mock = dbus_test_dbus_mock_new(BUS_HAPTIC_NAME); haptic_obj = dbus_test_dbus_mock_get_object(haptic_mock, BUS_HAPTIC_PATH, BUS_HAPTIC_INTERFACE, &error); dbus_test_dbus_mock_object_add_method(haptic_mock, haptic_obj, HAPTIC_METHOD_VIBRATE_PATTERN, G_VARIANT_TYPE("(auu)"), nullptr, "", &error); g_assert_no_error (error); dbus_test_service_add_task(service, DBUS_TEST_TASK(haptic_mock)); startDbusMock(); } void TearDown() override { g_clear_object(&haptic_mock); g_clear_object(&screen_mock); g_clear_object(&powerd_mock); g_clear_object(¬ify_mock); g_clear_object(&as_mock); super::TearDown(); } void make_interactive() { // GetCapabilities returns an array containing 'actions', // so our snap decision will be interactive. // For this test, it means we should get a timeout Notify Hint // that matches duration_minutes GError * error = nullptr; dbus_test_dbus_mock_object_add_method(notify_mock, notify_obj, METHOD_GET_CAPS, nullptr, G_VARIANT_TYPE_STRING_ARRAY, "ret = ['actions', 'body']", &error); g_assert_no_error (error); } std::shared_ptr create_snap(const std::shared_ptr& ne, const std::shared_ptr& sb, const std::shared_ptr& settings) { auto snap = std::make_shared(ne, sb, settings); wait_msec(100); // wait a moment for the Snap to finish its async dbus bootstrapping return snap; } }; ./tests/libdbusmock-fixture.h0000644000015600001650000001230312701256660016376 0ustar jenkinsjenkins/* * Copyright 2014-2016 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #pragma once #include "glib-fixture.h" #include /*** **** ***/ class LibdbusmockFixture: public GlibFixture { private: typedef GlibFixture super; protected: GDBusConnection * system_bus {}; GDBusConnection * session_bus {}; DbusTestService * service {}; void SetUp() override { super::SetUp(); service = dbus_test_service_new(nullptr); } void startDbusMock() { // start 'em up. // make the system bus work off the mock bus too, since that's // where the upower and screen are on the system bus... dbus_test_service_start_tasks(service); g_setenv("DBUS_SYSTEM_BUS_ADDRESS", g_getenv("DBUS_SESSION_BUS_ADDRESS"), TRUE); session_bus = g_bus_get_sync(G_BUS_TYPE_SESSION, nullptr, nullptr); ASSERT_NE(nullptr, session_bus); g_dbus_connection_set_exit_on_close(session_bus, false); g_object_add_weak_pointer(G_OBJECT(session_bus), (gpointer *)&session_bus); system_bus = g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, nullptr); ASSERT_NE(nullptr, system_bus); g_dbus_connection_set_exit_on_close(system_bus, FALSE); g_object_add_weak_pointer(G_OBJECT(system_bus), (gpointer *)&system_bus); } void TearDown() override { g_clear_object(&service); g_object_unref(session_bus); g_object_unref(system_bus); // wait a little while for the scaffolding to shut down, // but don't block on it forever... unsigned int cleartry = 0; while (((system_bus != nullptr) || (session_bus != nullptr)) && (cleartry < 50)) { g_usleep(100000); while (g_main_pending()) g_main_iteration(true); cleartry++; } super::TearDown(); } bool wait_for_method_call(DbusTestDbusMock* mock, DbusTestDbusMockObject* obj, const gchar* method, GVariant* params=nullptr, guint timeout_msec=100) { if (params != nullptr) g_variant_ref_sink(params); auto test_function = [mock, obj, method, params]() { GError* error {}; const auto called = dbus_test_dbus_mock_object_check_method_call(mock, obj, method, params, &error); if (error != nullptr) { g_critical("Error looking for method call '%s': %s", method, error->message); g_clear_error(&error); } return called; }; const auto ret = wait_for(test_function, timeout_msec); g_clear_pointer(¶ms, g_variant_unref); return ret; } void EXPECT_METHOD_CALLED_EVENTUALLY(DbusTestDbusMock* mock, DbusTestDbusMockObject* obj, const gchar* method, GVariant* params=nullptr, guint timeout_msec=1000) { EXPECT_TRUE(wait_for_method_call(mock, obj, method, params, timeout_msec)) << "method: " << method; } void EXPECT_METHOD_NOT_CALLED_EVENTUALLY(DbusTestDbusMock* mock, DbusTestDbusMockObject* obj, const gchar* method, GVariant* params=nullptr, guint timeout_msec=1000) { EXPECT_FALSE(wait_for_method_call(mock, obj, method, params, timeout_msec)) << "method: " << method; } void ASSERT_METHOD_CALLED_EVENTUALLY(DbusTestDbusMock* mock, DbusTestDbusMockObject* obj, const gchar* method, GVariant* params=nullptr, guint timeout_msec=1000) { ASSERT_TRUE(wait_for_method_call(mock, obj, method, params, timeout_msec)) << "method: " << method; } void ASSERT_METHOD_NOT_CALLED_EVENTUALLY(DbusTestDbusMock* mock, DbusTestDbusMockObject* obj, const gchar* method, GVariant* params=nullptr, guint timeout_msec=1000) { ASSERT_FALSE(wait_for_method_call(mock, obj, method, params, timeout_msec)) << "method: " << method; } }; ./tests/test-dbus-fixture.h0000644000015600001650000000570012701256660016015 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_TESTS_DBUS_FIXTURE_H #define INDICATOR_DATETIME_TESTS_DBUS_FIXTURE_H #include "glib-fixture.h" /*** **** ***/ class TestDBusFixture: public GlibFixture { public: TestDBusFixture() =default; virtual ~TestDBusFixture() =default; explicit TestDBusFixture(const std::vector& service_dirs_in): service_dirs(service_dirs_in) {} private: typedef GlibFixture super; static void on_bus_opened (GObject* /*object*/, GAsyncResult * res, gpointer gself) { auto self = static_cast(gself); GError * err = 0; self->system_bus = g_bus_get_finish (res, &err); g_assert_no_error (err); g_main_loop_quit (self->loop); } static void on_bus_closed (GObject* /*object*/, GAsyncResult * res, gpointer gself) { auto self = static_cast(gself); GError * err = 0; g_dbus_connection_close_finish (self->system_bus, res, &err); g_assert_no_error (err); g_main_loop_quit (self->loop); } protected: GTestDBus * test_dbus; GDBusConnection * system_bus; const std::vector service_dirs; virtual void SetUp() override { super::SetUp (); // pull up a test dbus test_dbus = g_test_dbus_new (G_TEST_DBUS_NONE); for (const auto& dir : service_dirs) g_test_dbus_add_service_dir (test_dbus, dir.c_str()); g_test_dbus_up (test_dbus); const char * address = g_test_dbus_get_bus_address (test_dbus); g_setenv ("DBUS_SYSTEM_BUS_ADDRESS", address, true); g_setenv ("DBUS_SESSION_BUS_ADDRESS", address, true); g_debug ("test_dbus's address is %s", address); // wait for the GDBusConnection before returning g_bus_get (G_BUS_TYPE_SYSTEM, nullptr, on_bus_opened, this); g_main_loop_run (loop); } virtual void TearDown() override { wait_msec(); // close the system bus g_dbus_connection_close(system_bus, nullptr, on_bus_closed, this); g_main_loop_run(loop); g_clear_object(&system_bus); // tear down the test dbus g_test_dbus_down(test_dbus); g_clear_object(&test_dbus); super::TearDown(); } }; #endif /* INDICATOR_DATETIME_TESTS_DBUS_FIXTURE_H */ ./tests/test-alarm-queue.cpp0000644000015600001650000001242212701256660016144 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include #include "state-fixture.h" using namespace unity::indicator::datetime; class AlarmQueueFixture: public StateFixture { private: typedef StateFixture super; protected: std::vector m_triggered; std::shared_ptr m_wakeup_timer; std::unique_ptr m_watcher; std::shared_ptr m_range_planner; std::shared_ptr m_upcoming; void SetUp() { super::SetUp(); m_wakeup_timer.reset(new MainloopWakeupTimer(m_state->clock)); m_range_planner.reset(new MockRangePlanner); m_upcoming.reset(new UpcomingPlanner(m_range_planner, m_state->clock->localtime())); m_watcher.reset(new SimpleAlarmQueue(m_state->clock, m_upcoming, m_wakeup_timer)); m_watcher->alarm_reached().connect([this](const Appointment& appt, const Alarm& /*alarm*/){ m_triggered.push_back(appt.uid); }); EXPECT_TRUE(m_triggered.empty()); } void TearDown() { m_triggered.clear(); m_watcher.reset(); m_upcoming.reset(); m_range_planner.reset(); super::TearDown(); } std::vector build_some_appointments() { const auto now = m_state->clock->localtime(); const auto tomorrow_begin = now.add_days(1).start_of_day(); const auto tomorrow_end = tomorrow_begin.end_of_day(); Appointment a1; // an ubuntu alarm a1.color = "red"; a1.summary = "Alarm"; a1.summary = "http://www.example.com/"; a1.uid = "example"; a1.type = Appointment::UBUNTU_ALARM; a1.begin = tomorrow_begin; a1.end = tomorrow_end; a1.alarms.push_back(Alarm{"Alarm Text", "", a1.begin}); const auto ubermorgen_begin = now.add_days(2).start_of_day(); const auto ubermorgen_end = ubermorgen_begin.end_of_day(); Appointment a2; // something else a2.color = "green"; a2.summary = "Other Text"; a2.summary = "http://www.monkey.com/"; a2.uid = "monkey"; a2.type = Appointment::EVENT; a2.begin = ubermorgen_begin; a2.end = ubermorgen_end; a2.alarms.push_back(Alarm{"Alarm Text", "", a2.begin}); return std::vector({a1, a2}); } }; /*** **** ***/ TEST_F(AlarmQueueFixture, AppointmentsChanged) { // Add some appointments to the planner. // One of these matches our state's localtime, so that should get triggered. std::vector a = build_some_appointments(); a[0].begin = a[0].alarms.front().time = m_state->clock->localtime(); m_range_planner->appointments().set(a); // Confirm that it got fired ASSERT_EQ(1, m_triggered.size()); EXPECT_EQ(a[0].uid, m_triggered[0]); } TEST_F(AlarmQueueFixture, TimeChanged) { // Add some appointments to the planner. // Neither of these match the state's localtime, so nothing should be triggered. std::vector a = build_some_appointments(); m_range_planner->appointments().set(a); EXPECT_TRUE(m_triggered.empty()); // Set the state's clock to a time that matches one of the appointments(). // That appointment should get triggered. g_message ("%s setting clock to %s", G_STRLOC, a[1].begin.format("%F %T").c_str()); m_mock_state->mock_clock->set_localtime(a[1].begin); ASSERT_EQ(1, m_triggered.size()); EXPECT_EQ(a[1].uid, m_triggered[0]); } TEST_F(AlarmQueueFixture, MoreThanOne) { const auto now = m_state->clock->localtime(); std::vector a = build_some_appointments(); a[0].alarms.front().time = now; a[1].alarms.front().time = now; m_range_planner->appointments().set(a); ASSERT_EQ(2, m_triggered.size()); EXPECT_EQ(a[0].uid, m_triggered[0]); EXPECT_EQ(a[1].uid, m_triggered[1]); } TEST_F(AlarmQueueFixture, NoDuplicates) { // Setup: add an appointment that gets triggered. const auto now = m_state->clock->localtime(); const std::vector appointments = build_some_appointments(); std::vector a; a.push_back(appointments[0]); a[0].alarms.front().time = now; m_range_planner->appointments().set(a); ASSERT_EQ(1, m_triggered.size()); EXPECT_EQ(a[0].uid, m_triggered[0]); // Now change the appointment vector by adding one to it. // Confirm that the AlarmQueue doesn't re-trigger a[0] a.push_back(appointments[1]); m_range_planner->appointments().set(a); ASSERT_EQ(1, m_triggered.size()); EXPECT_EQ(a[0].uid, m_triggered[0]); } ./tests/test-timezone-timedated.cpp0000644000015600001650000000722012701256660017516 0ustar jenkinsjenkins /* * Copyright 2013 Canonical Ltd. * * Authors: * Charles Kerr * * 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . */ #include "timedated-fixture.h" #include using unity::indicator::datetime::TimedatedTimezone; /*** **** ***/ #define TIMEZONE_FILE (SANDBOX"/timezone") class TimezoneFixture: public TimedateFixture { private: typedef TimedateFixture super; protected: void SetUp() override { super::SetUp(); } void TearDown() override { super::TearDown(); } public: /* convenience func to set the timezone file */ void set_file(const std::string& text) { g_debug("set_file %s %s", TIMEZONE_FILE, text.c_str()); auto fp = fopen(TIMEZONE_FILE, "w+"); fprintf(fp, "%s\n", text.c_str()); fclose(fp); sync(); } }; /** * Test that timezone-timedated warns, but doesn't crash, if the timezone file doesn't exist */ TEST_F(TimezoneFixture, NoFile) { remove(TIMEZONE_FILE); ASSERT_FALSE(g_file_test(TIMEZONE_FILE, G_FILE_TEST_EXISTS)); expectLogMessage(G_LOG_DOMAIN, G_LOG_LEVEL_WARNING, "*No such file or directory*"); TimedatedTimezone tz(TIMEZONE_FILE); } /** * Test that timezone-timedated gives a default of UTC if the file doesn't exist */ TEST_F(TimezoneFixture, DefaultValueNoFile) { const std::string expected_timezone = "Etc/Utc"; remove(TIMEZONE_FILE); ASSERT_FALSE(g_file_test(TIMEZONE_FILE, G_FILE_TEST_EXISTS)); expectLogMessage(G_LOG_DOMAIN, G_LOG_LEVEL_WARNING, "*No such file or directory*"); TimedatedTimezone tz(TIMEZONE_FILE); ASSERT_EQ(expected_timezone, tz.timezone.get()); } /** * Test that timezone-timedated picks up the initial value */ TEST_F(TimezoneFixture, InitialValue) { const std::string expected_timezone = "America/Chicago"; set_file(expected_timezone); TimedatedTimezone tz(TIMEZONE_FILE); } /** * Test that changing the tz after we are running works. */ TEST_F(TimezoneFixture, ChangedValue) { const std::string initial_timezone = "America/Chicago"; const std::string changed_timezone = "America/New_York"; set_file(initial_timezone); TimedatedTimezone tz(TIMEZONE_FILE); ASSERT_EQ(initial_timezone, tz.timezone.get()); bool changed = false; tz.timezone.changed().connect( [&changed, this](const std::string& s){ g_message("timezone changed to %s", s.c_str()); changed = true; g_main_loop_quit(loop); }); g_idle_add([](gpointer gself){ static_cast(gself)->set_timezone("America/New_York"); return G_SOURCE_REMOVE; }, this); g_main_loop_run(loop); ASSERT_TRUE(changed); ASSERT_EQ(changed_timezone, tz.timezone.get()); } /** * Test that timezone-timedated picks up the initial value */ TEST_F(TimezoneFixture, IgnoreComments) { const std::string comment = "# Created by cloud-init v. 0.7.5 on Thu, 24 Apr 2014 14:03:29 +0000"; const std::string expected_timezone = "Europe/Berlin"; set_file(comment + "\n" + expected_timezone); TimedatedTimezone tz(TIMEZONE_FILE); ASSERT_EQ(expected_timezone, tz.timezone.get()); } ./tests/timedated-fixture.h0000644000015600001650000002527212701256660016051 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_TESTS_TIMEDATED_FIXTURE_H #define INDICATOR_DATETIME_TESTS_TIMEDATED_FIXTURE_H #include #include "state-mock.h" #include "glib-fixture.h" using namespace unity::indicator::datetime; class MockLiveActions: public LiveActions { public: std::string last_cmd; std::string last_url; explicit MockLiveActions(const std::shared_ptr& state_in): LiveActions(state_in) {} ~MockLiveActions() {} protected: void dispatch_url(const std::string& url) override { last_url = url; } void execute_command(const std::string& cmd) override { last_cmd = cmd; } }; /*** **** ***/ using namespace unity::indicator::datetime; class TimedateFixture: public GlibFixture { private: typedef GlibFixture super; static GVariant * timedate1_get_properties (GDBusConnection * /*connection*/ , const gchar * /*sender*/, const gchar * /*object_path*/, const gchar * /*interface_name*/, const gchar *property_name, GError ** /*error*/, gpointer gself) { auto self = static_cast(gself); g_debug("get_properties called"); if (g_strcmp0(property_name, "Timezone") == 0) { g_debug("timezone requested, giving '%s'", self->attempted_tzid.c_str()); return g_variant_new_string(self->attempted_tzid.c_str()); } return nullptr; } static void on_bus_acquired(GDBusConnection* conn, const gchar* name, gpointer gself) { auto self = static_cast(gself); g_debug("bus acquired: %s, connection is %p", name, conn); /* Set up a fake timedated which handles setting and getting the ** timezone */ static const GDBusInterfaceVTable vtable = { timedate1_handle_method_call, timedate1_get_properties, /* GetProperty */ nullptr, /* SetProperty */ }; self->connection = G_DBUS_CONNECTION(g_object_ref(G_OBJECT(conn))); GError* error = nullptr; self->object_register_id = g_dbus_connection_register_object( conn, "/org/freedesktop/timedate1", self->node_info->interfaces[0], &vtable, self, nullptr, &error); g_assert_no_error(error); } static void on_name_acquired(GDBusConnection* conn, const gchar* name, gpointer gself) { g_debug("on_name_acquired"); auto self = static_cast(gself); self->name_acquired = true; self->proxy = g_dbus_proxy_new_sync(conn, G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES, nullptr, name, "/org/freedesktop/timedate1", "org.freedesktop.timedate1", nullptr, nullptr); g_main_loop_quit(self->loop); } static void on_name_lost(GDBusConnection* /*conn*/, const gchar* /*name*/, gpointer gself) { g_debug("on_name_lost"); auto self = static_cast(gself); self->name_acquired = false; } static void on_bus_closed(GObject* /*object*/, GAsyncResult* res, gpointer gself) { g_debug("on_bus_closed"); auto self = static_cast(gself); GError* err = nullptr; g_dbus_connection_close_finish(self->connection, res, &err); g_assert_no_error(err); g_main_loop_quit(self->loop); } static void timedate1_handle_method_call(GDBusConnection * connection, const gchar * /*sender*/, const gchar * object_path, const gchar * interface_name, const gchar * method_name, GVariant * parameters, GDBusMethodInvocation * invocation, gpointer gself) { g_assert(!g_strcmp0(method_name, "SetTimezone")); g_assert(g_variant_is_of_type(parameters, G_VARIANT_TYPE_TUPLE)); g_assert(2 == g_variant_n_children(parameters)); auto child = g_variant_get_child_value(parameters, 0); g_assert(g_variant_is_of_type(child, G_VARIANT_TYPE_STRING)); auto self = static_cast(gself); self->attempted_tzid = g_variant_get_string(child, nullptr); g_debug("set tz (dbus side): '%s'", self->attempted_tzid.c_str()); g_dbus_method_invocation_return_value(invocation, nullptr); /* Send PropertiesChanged */ GError * local_error = nullptr; auto builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY); g_variant_builder_add (builder, "{sv}", "Timezone", g_variant_new_string( self->attempted_tzid.c_str())); g_dbus_connection_emit_signal (connection, NULL, object_path, "org.freedesktop.DBus.Properties", "PropertiesChanged", g_variant_new ("(sa{sv}as)", interface_name, builder, NULL), &local_error); g_assert_no_error (local_error); g_variant_unref(child); } protected: std::shared_ptr m_mock_state; std::shared_ptr m_state; std::shared_ptr m_live_actions; std::shared_ptr m_actions; bool name_acquired; std::string attempted_tzid; GTestDBus* bus; guint own_name; GDBusConnection* connection; GDBusNodeInfo* node_info; int object_register_id; GDBusProxy *proxy; void SetUp() { super::SetUp(); g_debug("SetUp"); name_acquired = false; attempted_tzid.clear(); connection = nullptr; node_info = nullptr; object_register_id = 0; own_name = 0; proxy = nullptr; // bring up the test bus bus = g_test_dbus_new(G_TEST_DBUS_NONE); g_test_dbus_up(bus); const auto address = g_test_dbus_get_bus_address(bus); g_setenv("DBUS_SYSTEM_BUS_ADDRESS", address, true); g_setenv("DBUS_SESSION_BUS_ADDRESS", address, true); g_debug("test_dbus's address is %s", address); // parse the org.freedesktop.timedate1 interface const gchar introspection_xml[] = "" " " " " " " " " " " " " " " ""; node_info = g_dbus_node_info_new_for_xml(introspection_xml, nullptr); ASSERT_TRUE(node_info != nullptr); ASSERT_TRUE(node_info->interfaces != nullptr); ASSERT_TRUE(node_info->interfaces[0] != nullptr); ASSERT_TRUE(node_info->interfaces[1] == nullptr); ASSERT_STREQ("org.freedesktop.timedate1", node_info->interfaces[0]->name); // own the bus own_name = g_bus_own_name(G_BUS_TYPE_SYSTEM, "org.freedesktop.timedate1", G_BUS_NAME_OWNER_FLAGS_NONE, on_bus_acquired, on_name_acquired, on_name_lost, this, nullptr); ASSERT_TRUE(object_register_id == 0); ASSERT_FALSE(name_acquired); ASSERT_TRUE(connection == nullptr); g_main_loop_run(loop); ASSERT_TRUE(object_register_id != 0); ASSERT_TRUE(name_acquired); ASSERT_TRUE(G_IS_DBUS_CONNECTION(connection)); // create the State and Actions m_mock_state.reset(new MockState); m_mock_state->settings.reset(new Settings); m_state = std::dynamic_pointer_cast(m_mock_state); m_live_actions.reset(new MockLiveActions(m_state)); m_actions = std::dynamic_pointer_cast(m_live_actions); } void TearDown() { g_debug("TearDown"); m_actions.reset(); m_live_actions.reset(); m_state.reset(); m_mock_state.reset(); g_dbus_connection_unregister_object(connection, object_register_id); g_object_unref(proxy); g_dbus_node_info_unref(node_info); g_bus_unown_name(own_name); g_dbus_connection_close(connection, nullptr, on_bus_closed, this); g_main_loop_run(loop); g_clear_object(&connection); g_test_dbus_down(bus); g_clear_object(&bus); super::TearDown(); } public: void set_timezone(std::string tz) { g_debug("set_timezone: '%s'", tz.c_str()); g_dbus_proxy_call_sync(proxy, "SetTimezone", g_variant_new("(sb)", tz.c_str(), FALSE), G_DBUS_CALL_FLAGS_NONE, 500, nullptr, nullptr); } }; #endif ./tests/test-eds-ics-repeating-events.cpp0000644000015600001650000000750412701256660020540 0ustar jenkinsjenkins/* * Copyright 2015 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include #include #include #include #include "glib-fixture.h" #include "print-to.h" #include "timezone-mock.h" #include "wakeup-timer-mock.h" using namespace unity::indicator::datetime; using VAlarmFixture = GlibFixture; /*** **** ***/ TEST_F(VAlarmFixture, MultipleAppointments) { // start the EDS engine auto engine = std::make_shared(); // we need a consistent timezone for the planner and our local DateTimes constexpr char const * zone_str {"America/Chicago"}; auto tz = std::make_shared(zone_str); auto gtz = g_time_zone_new(zone_str); // make a planner that looks at the first half of 2015 in EDS auto planner = std::make_shared(engine, tz); const DateTime range_begin {gtz, 2015,1, 1, 0, 0, 0.0}; const DateTime range_end {gtz, 2015,6,31,23,59,59.5}; planner->range().set(std::make_pair(range_begin, range_end)); // give EDS a moment to load if (planner->appointments().get().empty()) { g_message("waiting a moment for EDS to load..."); auto on_appointments_changed = [this](const std::vector& appointments){ g_message("ah, they loaded"); if (!appointments.empty()) g_main_loop_quit(loop); }; core::ScopedConnection conn(planner->appointments().changed().connect(on_appointments_changed)); constexpr int max_wait_sec = 10; wait_msec(max_wait_sec * G_TIME_SPAN_MILLISECOND); } // what we expect to get... Appointment expected_appt; expected_appt.uid = "20150507T211449Z-4262-32011-1418-1@ubuntu-phablet"; expected_appt.color = "#becedd"; expected_appt.summary = "Alarm"; std::array expected_alarms = { Alarm({"Alarm", "file://" ALARM_DEFAULT_SOUND, DateTime(gtz,2015,5, 8,16,40,0)}), Alarm({"Alarm", "file://" ALARM_DEFAULT_SOUND, DateTime(gtz,2015,5,15,16,40,0)}), Alarm({"Alarm", "file://" ALARM_DEFAULT_SOUND, DateTime(gtz,2015,5,22,16,40,0)}), Alarm({"Alarm", "file://" ALARM_DEFAULT_SOUND, DateTime(gtz,2015,5,29,16,40,0)}), Alarm({"Alarm", "file://" ALARM_DEFAULT_SOUND, DateTime(gtz,2015,6, 5,16,40,0)}), Alarm({"Alarm", "file://" ALARM_DEFAULT_SOUND, DateTime(gtz,2015,6,12,16,40,0)}), Alarm({"Alarm", "file://" ALARM_DEFAULT_SOUND, DateTime(gtz,2015,6,19,16,40,0)}), Alarm({"Alarm", "file://" ALARM_DEFAULT_SOUND, DateTime(gtz,2015,6,26,16,40,0)}) }; // compare it to what we actually loaded... const auto appts = planner->appointments().get(); EXPECT_EQ(expected_alarms.size(), appts.size()); for (size_t i=0, n=expected_alarms.size(); i. * * Authors: * Charles Kerr */ #include #include #include #include #include #include #include "glib-fixture.h" #include "print-to.h" #include "timezone-mock.h" #include "wakeup-timer-mock.h" using namespace unity::indicator::datetime; using VAlarmFixture = GlibFixture; /*** **** ***/ TEST_F(VAlarmFixture, UTCAppointments) { // start the EDS engine auto engine = std::make_shared(); // we need a consistent timezone for the planner and our local DateTimes constexpr char const * zone_str {"America/Recife"}; auto tz = std::make_shared(zone_str); auto gtz = g_time_zone_new(zone_str); // make a planner that looks at the first half of 2015 in EDS auto planner = std::make_shared(engine, tz); const DateTime range_begin {gtz, 2016,1, 1, 0, 0, 0.0}; const DateTime range_end {gtz, 2017,1, 1, 0, 0, 0.0}; planner->range().set(std::make_pair(range_begin, range_end)); // give EDS a moment to load if (planner->appointments().get().empty()) { g_message("waiting a moment for EDS to load..."); auto on_appointments_changed = [this](const std::vector& appointments){ g_message("ah, they loaded"); if (!appointments.empty()) g_main_loop_quit(loop); }; core::ScopedConnection conn(planner->appointments().changed().connect(on_appointments_changed)); constexpr int max_wait_sec = 10; wait_msec(max_wait_sec * G_TIME_SPAN_MILLISECOND); } // what we expect to get... std::array expected_appts; auto appt = &expected_appts[0]; appt->uid = "20160322T132738Z"; appt->color = "#becedd"; appt->summary = "UTC event"; appt->begin = DateTime{gtz,2016,3,22,15,0,0}; appt->end = DateTime{gtz,2016,3,22,16,0,0}; // compare it to what we actually loaded... const auto appts = planner->appointments().get(); EXPECT_EQ(expected_appts.size(), appts.size()); for (size_t i=0, n=std::min(appts.size(),expected_appts.size()); i. * * Authors: * Charles Kerr */ #include #include #include #include #include #include #include "glib-fixture.h" #include "print-to.h" #include "timezone-mock.h" #include "wakeup-timer-mock.h" using namespace unity::indicator::datetime; using VAlarmFixture = GlibFixture; /*** **** ***/ TEST_F(VAlarmFixture, MultipleAppointments) { // start the EDS engine auto engine = std::make_shared(); // we need a consistent timezone for the planner and our local DateTimes constexpr char const * zone_str {"America/Chicago"}; auto tz = std::make_shared(zone_str); auto gtz = g_time_zone_new(zone_str); // make a planner that looks at the first half of 2015 in EDS auto planner = std::make_shared(engine, tz); const DateTime range_begin {gtz, 2015,1, 1, 0, 0, 0.0}; const DateTime range_end {gtz, 2015,6,31,23,59,59.5}; planner->range().set(std::make_pair(range_begin, range_end)); // give EDS a moment to load if (planner->appointments().get().empty()) { g_message("waiting a moment for EDS to load..."); auto on_appointments_changed = [this](const std::vector& appointments){ g_message("ah, they loaded"); if (!appointments.empty()) g_main_loop_quit(loop); }; core::ScopedConnection conn(planner->appointments().changed().connect(on_appointments_changed)); constexpr int max_wait_sec = 10; wait_msec(max_wait_sec * G_TIME_SPAN_MILLISECOND); } // what we expect to get... Appointment expected_appt; expected_appt.uid = "20150521T111538Z-7449-1000-3572-0@ghidorah"; expected_appt.color = "#becedd"; expected_appt.summary = "Memorial Day"; expected_appt.begin = DateTime{gtz,2015,5,25,0,0,0}; expected_appt.end = DateTime{gtz,2015,5,26,0,0,0}; // compare it to what we actually loaded... const auto appts = planner->appointments().get(); ASSERT_EQ(1, appts.size()); const auto& appt = appts[0]; EXPECT_EQ(expected_appt.begin, appt.begin); EXPECT_EQ(expected_appt.end, appt.end); EXPECT_EQ(expected_appt.uid, appt.uid); EXPECT_EQ(expected_appt.color, appt.color); EXPECT_EQ(expected_appt.summary, appt.summary); EXPECT_EQ(0, appt.alarms.size()); // cleanup g_time_zone_unref(gtz); } ./tests/timezone-mock.h0000644000015600001650000000225012701256660015175 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_TIMEZONE_MOCK_H #define INDICATOR_DATETIME_TIMEZONE_MOCK_H #include namespace unity { namespace indicator { namespace datetime { class MockTimezone: public Timezone { public: MockTimezone() =default; explicit MockTimezone(const std::string& zone) {timezone.set(zone);} ~MockTimezone() =default; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_TIMEZONE_MOCK_H ./tests/test-eds-ics-missing-trigger.cpp0000644000015600001650000001000412701256660020357 0ustar jenkinsjenkins/* * Copyright 2015 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include #include #include #include #include "glib-fixture.h" #include "print-to.h" #include "timezone-mock.h" #include "wakeup-timer-mock.h" using namespace unity::indicator::datetime; using VAlarmFixture = GlibFixture; /*** **** ***/ TEST_F(VAlarmFixture, MissingTriggers) { // start the EDS engine auto engine = std::make_shared(); // we need a consistent timezone for the planner and our local DateTimes constexpr char const * zone_str {"America/Chicago"}; auto tz = std::make_shared(zone_str); auto gtz = g_time_zone_new(zone_str); // make a planner that looks at the first half of 2015 in EDS auto planner = std::make_shared(engine, tz); const DateTime range_begin {gtz, 2015,1, 1, 0, 0, 0.0}; const DateTime range_end {gtz, 2015,6,31,23,59,59.5}; planner->range().set(std::make_pair(range_begin, range_end)); // give EDS a moment to load if (planner->appointments().get().empty()) { g_message("waiting a moment for EDS to load..."); auto on_appointments_changed = [this](const std::vector& appointments){ g_message("ah, they loaded"); if (!appointments.empty()) g_main_loop_quit(loop); }; core::ScopedConnection conn(planner->appointments().changed().connect(on_appointments_changed)); constexpr int max_wait_sec = 10; wait_msec(max_wait_sec * G_TIME_SPAN_MILLISECOND); } // build expected: one-time alarm std::vector expected; Appointment a; a.type = Appointment::UBUNTU_ALARM; a.uid = "20150617T211838Z-6217-32011-2036-1@ubuntu-phablet"; a.color = "#becedd"; a.summary = "One Time Alarm"; a.begin = DateTime { gtz, 2015, 6, 18, 10, 0, 0}; a.end = a.begin; a.alarms.resize(1); a.alarms[0].audio_url = "file://" ALARM_DEFAULT_SOUND; a.alarms[0].time = a.begin; a.alarms[0].text = a.summary; expected.push_back(a); // build expected: recurring alarm a.uid = "20150617T211913Z-6217-32011-2036-5@ubuntu-phablet"; a.summary = "Recurring Alarm"; a.alarms[0].text = a.summary; std::array recurrences { DateTime{ gtz, 2015, 6, 18, 10, 1, 0 }, DateTime{ gtz, 2015, 6, 19, 10, 1, 0 }, DateTime{ gtz, 2015, 6, 20, 10, 1, 0 }, DateTime{ gtz, 2015, 6, 21, 10, 1, 0 }, DateTime{ gtz, 2015, 6, 22, 10, 1, 0 }, DateTime{ gtz, 2015, 6, 23, 10, 1, 0 }, DateTime{ gtz, 2015, 6, 24, 10, 1, 0 }, DateTime{ gtz, 2015, 6, 25, 10, 1, 0 }, DateTime{ gtz, 2015, 6, 26, 10, 1, 0 }, DateTime{ gtz, 2015, 6, 27, 10, 1, 0 }, DateTime{ gtz, 2015, 6, 28, 10, 1, 0 }, DateTime{ gtz, 2015, 6, 29, 10, 1, 0 }, DateTime{ gtz, 2015, 6, 30, 10, 1, 0 }, DateTime{ gtz, 2015, 7, 1, 10, 1, 0 } }; for (const auto& time : recurrences) { a.begin = a.end = a.alarms[0].time = time; expected.push_back(a); } // the planner should match what we've got in the calendar.ics file const auto appts = planner->appointments().get(); EXPECT_EQ(expected, appts); // cleanup g_time_zone_unref(gtz); } ./tests/test-eds-ics-repeating-events.ics.in0000644000015600001650000000144412701256660021136 0ustar jenkinsjenkinsBEGIN:VCALENDAR CALSCALE:GREGORIAN PRODID:-//Ximian//NONSGML Evolution Calendar//EN VERSION:2.0 X-EVOLUTION-DATA-REVISION:2015-05-07T21:14:49.315443Z(0) BEGIN:VTODO UID:20150507T211449Z-4262-32011-1418-1@ubuntu-phablet DTSTAMP:20150508T211449Z DTSTART:20150508T164000 RRULE:FREQ=WEEKLY;BYDAY=FR SUMMARY:Alarm CATEGORIES:x-canonical-alarm CREATED:20150507T211449Z LAST-MODIFIED:20150507T211449Z BEGIN:VALARM X-EVOLUTION-ALARM-UID:20150507T211449Z-4262-32011-1418-2@ubuntu-phablet ACTION:AUDIO ATTACH:file://@ALARM_DEFAULT_SOUND@ TRIGGER;VALUE=DURATION;RELATED=START:PT0S END:VALARM BEGIN:VALARM X-EVOLUTION-ALARM-UID:20150507T211449Z-4262-32011-1418-3@ubuntu-phablet ACTION:DISPLAY DESCRIPTION:Alarm TRIGGER;VALUE=DURATION;RELATED=START:PT0S END:VALARM END:VTODO END:VCALENDAR ./tests/test-exporter.cpp0000644000015600001650000002052112701256660015575 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include "actions-mock.h" #include "state-mock.h" #include "glib-fixture.h" #include "dbus-alarm-properties.h" #include #include #include #include #include using namespace unity::indicator::datetime; class ExporterFixture: public GlibFixture { private: typedef GlibFixture super; protected: GTestDBus* bus = nullptr; void SetUp() override { super::SetUp(); // bring up the test bus bus = g_test_dbus_new(G_TEST_DBUS_NONE); g_test_dbus_up(bus); const auto address = g_test_dbus_get_bus_address(bus); g_setenv("DBUS_SYSTEM_BUS_ADDRESS", address, true); g_setenv("DBUS_SESSION_BUS_ADDRESS", address, true); } void TearDown() override { GError * error = nullptr; GDBusConnection* connection = g_bus_get_sync(G_BUS_TYPE_SESSION, nullptr, &error); if(!g_dbus_connection_is_closed(connection)) g_dbus_connection_close_sync(connection, nullptr, &error); g_assert_no_error(error); g_clear_object(&connection); g_test_dbus_down(bus); g_clear_object(&bus); super::TearDown(); } }; TEST_F(ExporterFixture, HelloWorld) { // confirms that the Test DBus SetUp() and TearDown() works } TEST_F(ExporterFixture, Publish) { auto state = std::make_shared(); auto actions = std::make_shared(state); auto settings = std::make_shared(); std::vector> menus; MenuFactory menu_factory (actions, state); for(int i=0; i names; for(int i=0; names_strv && names_strv[i]; i++) names.insert(names_strv[i]); // confirm the actions that we expect EXPECT_EQ(1, names.count("desktop.open-alarm-app")); EXPECT_EQ(1, names.count("desktop.open-appointment")); EXPECT_EQ(1, names.count("desktop.open-calendar-app")); EXPECT_EQ(1, names.count("desktop.open-settings-app")); EXPECT_EQ(1, names.count("phone.open-alarm-app")); EXPECT_EQ(1, names.count("phone.open-appointment")); EXPECT_EQ(1, names.count("phone.open-calendar-app")); EXPECT_EQ(1, names.count("phone.open-settings-app")); EXPECT_EQ(1, names.count("calendar")); EXPECT_EQ(1, names.count("desktop_greeter-header")); EXPECT_EQ(1, names.count("desktop-header")); EXPECT_EQ(1, names.count("phone_greeter-header")); EXPECT_EQ(1, names.count("phone-header")); EXPECT_EQ(1, names.count("set-location")); // try closing the connection prematurely // to test Exporter's name-lost signal bool name_lost = false; exporter.name_lost().connect([this,&name_lost](){ name_lost = true; g_main_loop_quit(loop); }); g_dbus_connection_close_sync(connection, nullptr, nullptr); g_main_loop_run(loop); EXPECT_TRUE(name_lost); // cleanup g_strfreev(names_strv); g_clear_object(&exported); g_clear_object(&connection); } TEST_F(ExporterFixture, AlarmProperties) { /*** **** Set up the exporter ***/ std::shared_ptr state(new MockState); std::shared_ptr actions(new MockActions(state)); std::shared_ptr settings(new Settings); std::vector> menus; MenuFactory menu_factory (actions, state); for(int i=0; i(gproxy) = datetime_alarm_properties_proxy_new_for_bus_finish(res, &error); EXPECT_TRUE(error == nullptr); }; DatetimeAlarmProperties* proxy = nullptr; datetime_alarm_properties_proxy_new_for_bus(G_BUS_TYPE_SESSION, G_DBUS_PROXY_FLAGS_NONE, BUS_DATETIME_NAME, BUS_DATETIME_PATH"/AlarmProperties", nullptr, on_proxy_ready, &proxy); wait_msec(100); ASSERT_TRUE(proxy != nullptr); /*** **** Try changing the Settings -- do the DBus properties change to match it? ***/ auto expected_volume = 1; int expected_duration = 4; int expected_snooze_duration = 5; const char * expected_sound = "/tmp/foo.wav"; const char * expected_haptic = "pulse"; settings->alarm_volume.set(expected_volume); settings->alarm_duration.set(expected_duration); settings->snooze_duration.set(expected_snooze_duration); settings->alarm_sound.set(expected_sound); settings->alarm_haptic.set(expected_haptic); wait_msec(); static constexpr const char* const SOUND_PROP {"default-sound"}; static constexpr const char* const VOLUME_PROP {"default-volume"}; static constexpr const char* const DURATION_PROP {"duration"}; static constexpr const char* const HAPTIC_PROP {"haptic-feedback"}; static constexpr const char* const SNOOZE_PROP {"snooze-duration"}; char* sound = nullptr; char* haptic = nullptr; int volume = -1; int duration = -1; int snooze = -1; g_object_get(proxy, SOUND_PROP, &sound, HAPTIC_PROP, &haptic, VOLUME_PROP, &volume, DURATION_PROP, &duration, SNOOZE_PROP, &snooze, nullptr); EXPECT_STREQ(expected_sound, sound); EXPECT_STREQ(expected_haptic, haptic); EXPECT_EQ(expected_volume, volume); EXPECT_EQ(expected_duration, duration); EXPECT_EQ(expected_snooze_duration, snooze); g_clear_pointer (&sound, g_free); g_clear_pointer (&haptic, g_free); /*** **** Try changing the DBus properties -- do the Settings change to match it? ***/ expected_volume = 100; expected_duration = 30; expected_sound = "/tmp/bar.wav"; expected_haptic = "none"; expected_snooze_duration = 5; g_object_set(proxy, SOUND_PROP, expected_sound, HAPTIC_PROP, expected_haptic, VOLUME_PROP, expected_volume, DURATION_PROP, expected_duration, SNOOZE_PROP, expected_snooze_duration, nullptr); wait_msec(); EXPECT_STREQ(expected_sound, settings->alarm_sound.get().c_str()); EXPECT_STREQ(expected_haptic, settings->alarm_haptic.get().c_str()); EXPECT_EQ(expected_volume, settings->alarm_volume.get()); EXPECT_EQ(expected_duration, settings->alarm_duration.get()); EXPECT_EQ(expected_snooze_duration, settings->snooze_duration.get()); // cleanup g_clear_object(&proxy); } ./tests/test-settings.cpp0000644000015600001650000002111712701256660015567 0ustar jenkinsjenkins/* * Copyright 2013 Canonical Ltd. * * Authors: * Charles Kerr * * 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . */ #include "glib-fixture.h" #include #include using namespace unity::indicator::datetime; /*** **** ***/ class SettingsFixture: public GlibFixture { private: typedef GlibFixture super; protected: std::shared_ptr m_live; std::shared_ptr m_settings; GSettings * m_gsettings; GSettings * m_gsettings_cunh; void SetUp() override { super::SetUp(); m_gsettings = g_settings_new(SETTINGS_INTERFACE); m_gsettings_cunh = g_settings_new(SETTINGS_CUNH_SCHEMA_ID); m_live.reset(new LiveSettings); m_settings = std::dynamic_pointer_cast(m_live); } void TearDown() override { g_clear_object(&m_gsettings_cunh); g_clear_object(&m_gsettings); m_settings.reset(); m_live.reset(); super::TearDown(); } void TestBoolProperty(core::Property& property, const gchar* key) { EXPECT_EQ(g_settings_get_boolean(m_gsettings, key), property.get()); g_settings_set_boolean(m_gsettings, key, false); EXPECT_FALSE(property.get()); g_settings_set_boolean(m_gsettings, key, true); EXPECT_TRUE(property.get()); property.set(false); EXPECT_FALSE(g_settings_get_boolean(m_gsettings, key)); property.set(true); EXPECT_TRUE(g_settings_get_boolean(m_gsettings, key)); } void TestStringProperty(core::Property& property, const gchar* key) { gchar* tmp; std::string str; tmp = g_settings_get_string(m_gsettings, key); EXPECT_EQ(tmp, property.get()); g_clear_pointer(&tmp, g_free); str = "a"; g_settings_set_string(m_gsettings, key, str.c_str()); EXPECT_EQ(str, property.get()); str = "b"; g_settings_set_string(m_gsettings, key, str.c_str()); EXPECT_EQ(str, property.get()); str = "a"; property.set(str); tmp = g_settings_get_string(m_gsettings, key); EXPECT_EQ(str, tmp); g_clear_pointer(&tmp, g_free); str = "b"; property.set(str); tmp = g_settings_get_string(m_gsettings, key); EXPECT_EQ(str, tmp); g_clear_pointer(&tmp, g_free); } void TestUIntProperty(core::Property& property, const gchar* key) { EXPECT_EQ(g_settings_get_uint(m_gsettings, key), property.get()); unsigned int expected_values[] = { 1, 2, 3 }; // modify GSettings and confirm that the new value is propagated for(const auto& expected_value : expected_values) { g_settings_set_uint(m_gsettings, key, expected_value); EXPECT_EQ(expected_value, property.get()); EXPECT_EQ(expected_value, g_settings_get_uint(m_gsettings, key)); } // modify the property and confirm that the new value is propagated for(const auto& expected_value : expected_values) { property.set(expected_value); EXPECT_EQ(expected_value, property.get()); EXPECT_EQ(expected_value, g_settings_get_uint(m_gsettings, key)); } } }; /*** **** ***/ TEST_F(SettingsFixture, HelloWorld) { EXPECT_TRUE(true); } TEST_F(SettingsFixture, BoolProperties) { TestBoolProperty(m_settings->show_seconds, SETTINGS_SHOW_SECONDS_S); TestBoolProperty(m_settings->show_calendar, SETTINGS_SHOW_CALENDAR_S); TestBoolProperty(m_settings->show_clock, SETTINGS_SHOW_CLOCK_S); TestBoolProperty(m_settings->show_date, SETTINGS_SHOW_DATE_S); TestBoolProperty(m_settings->show_day, SETTINGS_SHOW_DAY_S); TestBoolProperty(m_settings->show_detected_location, SETTINGS_SHOW_DETECTED_S); TestBoolProperty(m_settings->show_events, SETTINGS_SHOW_EVENTS_S); TestBoolProperty(m_settings->show_locations, SETTINGS_SHOW_LOCATIONS_S); TestBoolProperty(m_settings->show_week_numbers, SETTINGS_SHOW_WEEK_NUMBERS_S); TestBoolProperty(m_settings->show_year, SETTINGS_SHOW_YEAR_S); } TEST_F(SettingsFixture, UIntProperties) { TestUIntProperty(m_settings->alarm_duration, SETTINGS_ALARM_DURATION_S); TestUIntProperty(m_settings->alarm_volume, SETTINGS_ALARM_VOLUME_S); TestUIntProperty(m_settings->snooze_duration, SETTINGS_SNOOZE_DURATION_S); } TEST_F(SettingsFixture, StringProperties) { TestStringProperty(m_settings->custom_time_format, SETTINGS_CUSTOM_TIME_FORMAT_S); TestStringProperty(m_settings->timezone_name, SETTINGS_TIMEZONE_NAME_S); TestStringProperty(m_settings->alarm_sound, SETTINGS_ALARM_SOUND_S); TestStringProperty(m_settings->calendar_sound, SETTINGS_CALENDAR_SOUND_S); TestStringProperty(m_settings->alarm_haptic, SETTINGS_ALARM_HAPTIC_S); } TEST_F(SettingsFixture, TimeFormatMode) { const auto key = SETTINGS_TIME_FORMAT_S; const TimeFormatMode modes[] = { TIME_FORMAT_MODE_LOCALE_DEFAULT, TIME_FORMAT_MODE_12_HOUR, TIME_FORMAT_MODE_24_HOUR, TIME_FORMAT_MODE_CUSTOM }; for(const auto& mode : modes) { g_settings_set_enum(m_gsettings, key, mode); EXPECT_EQ(mode, m_settings->time_format_mode.get()); } for(const auto& mode : modes) { m_settings->time_format_mode.set(mode); EXPECT_EQ(mode, g_settings_get_enum(m_gsettings, key)); } } namespace { std::vector strv_to_vector(const gchar** strv) { std::vector v; for(int i=0; strv && strv[i]; i++) v.push_back(strv[i]); return v; } }; TEST_F(SettingsFixture, Locations) { const auto key = SETTINGS_LOCATIONS_S; const gchar* astrv[] = {"America/Los_Angeles Oakland", "America/Chicago Oklahoma City", "Europe/London London", nullptr}; const gchar* bstrv[] = {"America/Denver", "Europe/London London", "Europe/Berlin Berlin", nullptr}; const std::vector av = strv_to_vector(astrv); const std::vector bv = strv_to_vector(bstrv); g_settings_set_strv(m_gsettings, key, astrv); EXPECT_EQ(av, m_settings->locations.get()); g_settings_set_strv(m_gsettings, key, bstrv); EXPECT_EQ(bv, m_settings->locations.get()); m_settings->locations.set(av); auto tmp = g_settings_get_strv(m_gsettings, key); auto vtmp = strv_to_vector((const gchar**)tmp); g_strfreev(tmp); EXPECT_EQ(av, vtmp); m_settings->locations.set(bv); tmp = g_settings_get_strv(m_gsettings, key); vtmp = strv_to_vector((const gchar**)tmp); g_strfreev(tmp); EXPECT_EQ(bv, vtmp); } TEST_F(SettingsFixture, MutedApps) { const auto key = SETTINGS_CUNH_BLACKLIST_S; struct { std::string pkgname; std::string appname; } apps[] = { { "", "ubuntu-system-settings" }, { "com.ubuntu.calendar", "calendar" }, { "com.ubuntu.developer.webapps.webapp-facebook", "webapp-facebook" }, { "com.ubuntu.reminders", "reminders" } }; std::set> apps_set; for (const auto& app : apps) apps_set.insert(std::make_pair(app.pkgname, app.appname)); // test that changing Settings is reflected in the schema m_settings->muted_apps.set(apps_set); auto v = g_settings_get_value(m_gsettings_cunh, key); auto str = g_variant_print(v, true); EXPECT_STREQ("[('', 'ubuntu-system-settings'), ('com.ubuntu.calendar', 'calendar'), ('com.ubuntu.developer.webapps.webapp-facebook', 'webapp-facebook'), ('com.ubuntu.reminders', 'reminders')]", str); g_clear_pointer(&str, g_free); // test that clearing the schema clears the settings g_settings_reset(m_gsettings_cunh, key); EXPECT_EQ(0, m_settings->muted_apps.get().size()); // test thst setting the schema updates the settings g_settings_set_value(m_gsettings_cunh, key, v); EXPECT_EQ(apps_set, m_settings->muted_apps.get()); // cleanup g_clear_pointer(&v, g_variant_unref); } ./tests/test-locations.cpp0000644000015600001650000001230412701256660015720 0ustar jenkinsjenkins /* * Copyright 2013 Canonical Ltd. * * Authors: * Charles Kerr * * 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . */ #include "glib-fixture.h" #include using unity::indicator::datetime::Location; using unity::indicator::datetime::Locations; using unity::indicator::datetime::Settings; using unity::indicator::datetime::SettingsLocations; using unity::indicator::datetime::Timezones; /*** **** ***/ class LocationsFixture: public GlibFixture { private: typedef GlibFixture super; protected: //GSettings * settings = nullptr; std::shared_ptr m_settings; std::shared_ptr m_timezones; const std::string nyc = "America/New_York"; const std::string chicago = "America/Chicago"; void SetUp() override { super::SetUp(); m_settings.reset(new Settings); m_settings->show_locations.set(true); m_settings->locations.set({"America/Los_Angeles Oakland", "America/Chicago Chicago", "America/Chicago Oklahoma City", "America/Toronto Toronto", "Europe/London London", "Europe/Berlin Berlin"}); m_timezones.reset(new Timezones); m_timezones->timezone.set(chicago); m_timezones->timezones.set(std::set({ nyc, chicago })); } void TearDown() override { m_timezones.reset(); m_settings.reset(); super::TearDown(); } }; TEST_F(LocationsFixture, Timezones) { m_settings->show_locations.set(false); SettingsLocations locations(m_settings, m_timezones); const auto l = locations.locations.get(); EXPECT_EQ(2, l.size()); EXPECT_STREQ("Chicago", l[0].name().c_str()); EXPECT_EQ(chicago, l[0].zone()); EXPECT_EQ("New York", l[1].name()); EXPECT_EQ(nyc, l[1].zone()); } TEST_F(LocationsFixture, SettingsLocations) { SettingsLocations locations(m_settings, m_timezones); const auto l = locations.locations.get(); EXPECT_EQ(7, l.size()); EXPECT_EQ("Chicago", l[0].name()); EXPECT_EQ(chicago, l[0].zone()); EXPECT_EQ("New York", l[1].name()); EXPECT_EQ(nyc, l[1].zone()); EXPECT_EQ("Oakland", l[2].name()); EXPECT_EQ("America/Los_Angeles", l[2].zone()); EXPECT_EQ("Oklahoma City", l[3].name()); EXPECT_EQ("America/Chicago", l[3].zone()); EXPECT_EQ("Toronto", l[4].name()); EXPECT_EQ("America/Toronto", l[4].zone()); EXPECT_EQ("London", l[5].name()); EXPECT_EQ("Europe/London", l[5].zone()); EXPECT_EQ("Berlin", l[6].name()); EXPECT_EQ("Europe/Berlin", l[6].zone()); } TEST_F(LocationsFixture, ChangeLocationStrings) { SettingsLocations locations(m_settings, m_timezones); bool locations_changed = false; locations.locations.changed().connect([&locations_changed, this](const std::vector&){ locations_changed = true; g_main_loop_quit(loop); }); g_idle_add([](gpointer settings){ static_cast(settings)->locations.set({"America/Los_Angeles Oakland", "Europe/London London", "Europe/Berlin Berlin"}); return G_SOURCE_REMOVE; }, m_settings.get()); g_main_loop_run(loop); EXPECT_TRUE(locations_changed); const auto l = locations.locations.get(); EXPECT_EQ(5, l.size()); EXPECT_EQ("Chicago", l[0].name()); EXPECT_EQ(chicago, l[0].zone()); EXPECT_EQ("New York", l[1].name()); EXPECT_EQ(nyc, l[1].zone()); EXPECT_EQ("Oakland", l[2].name()); EXPECT_EQ("America/Los_Angeles", l[2].zone()); EXPECT_EQ("London", l[3].name()); EXPECT_EQ("Europe/London", l[3].zone()); EXPECT_EQ("Berlin", l[4].name()); EXPECT_EQ("Europe/Berlin", l[4].zone()); } TEST_F(LocationsFixture, ChangeLocationVisibility) { SettingsLocations locations(m_settings, m_timezones); bool locations_changed = false; locations.locations.changed().connect([&locations_changed, this](const std::vector&){ locations_changed = true; g_main_loop_quit(loop); }); g_idle_add([](gpointer settings){ static_cast(settings)->show_locations.set(false); return G_SOURCE_REMOVE; }, m_settings.get()); g_main_loop_run(loop); EXPECT_TRUE(locations_changed); const auto l = locations.locations.get(); EXPECT_EQ(2, l.size()); EXPECT_EQ("Chicago", l[0].name()); EXPECT_EQ(chicago, l[0].zone()); EXPECT_EQ("New York", l[1].name()); EXPECT_EQ(nyc, l[1].zone()); } ./tests/test-eds-ics-config-files/0000755000015600001650000000000012701256660017113 5ustar jenkinsjenkins./tests/test-eds-ics-config-files/.config/0000755000015600001650000000000012701256660020436 5ustar jenkinsjenkins./tests/test-eds-ics-config-files/.config/evolution/0000755000015600001650000000000012701256660022462 5ustar jenkinsjenkins./tests/test-eds-ics-config-files/.config/evolution/sources/0000755000015600001650000000000012701256660024145 5ustar jenkinsjenkins./tests/test-eds-ics-config-files/.config/evolution/sources/system-proxy.source0000644000015600001650000000044012701256660030070 0ustar jenkinsjenkins [Data Source] DisplayName=Default Proxy Settings Enabled=true Parent= [Proxy] Method=default IgnoreHosts=localhost;127.0.0.0/8;::1; AutoconfigUrl= FtpHost= FtpPort=0 HttpAuthPassword= HttpAuthUser= HttpHost= HttpPort=8080 HttpUseAuth=false HttpsHost= HttpsPort=0 SocksHost= SocksPort=0 ./tests/test-eds-ics-config-files/.local/0000755000015600001650000000000012701256660020263 5ustar jenkinsjenkins./tests/test-eds-ics-config-files/.local/share/0000755000015600001650000000000012701256660021365 5ustar jenkinsjenkins./tests/test-eds-ics-config-files/.local/share/evolution/0000755000015600001650000000000012701256660023411 5ustar jenkinsjenkins./tests/test-eds-ics-config-files/.local/share/evolution/tasks/0000755000015600001650000000000012701256660024536 5ustar jenkinsjenkins./tests/test-eds-ics-config-files/.local/share/evolution/tasks/system/0000755000015600001650000000000012701256660026062 5ustar jenkinsjenkins./tests/test-eds-ics-config-files/.local/share/evolution/calendar/0000755000015600001650000000000012701256660025162 5ustar jenkinsjenkins./tests/test-eds-ics-config-files/.local/share/evolution/calendar/system/0000755000015600001650000000000012701256660026506 5ustar jenkinsjenkins./tests/test-utils.cpp0000644000015600001650000000625412701256660015074 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include TEST(UtilsTest, SplitSettingsLocation) { struct { const char* location; const char* expected_zone; const char* expected_name; } test_cases[] = { { "America/Chicago Chicago", "America/Chicago", "Chicago" }, { "America/Chicago Oklahoma City", "America/Chicago", "Oklahoma City" }, { "America/Los_Angeles", "America/Los_Angeles", "Los Angeles" }, { "America/Los_Angeles ", "America/Los_Angeles", "Los Angeles" }, { " America/Los_Angeles", "America/Los_Angeles", "Los Angeles" }, { " America/Los_Angeles ", "America/Los_Angeles", "Los Angeles" }, { "UTC UTC", "UTC", "UTC" } }; for(const auto& test_case : test_cases) { char * zone = nullptr; char * name = nullptr; split_settings_location(test_case.location, &zone, &name); ASSERT_STREQ(test_case.expected_zone, zone); ASSERT_STREQ(test_case.expected_name, name); g_free(zone); g_free(name); } } namespace { struct { const char* timezone; const char* location; const char* expected_name; } beautify_timezone_test_cases[] = { { "America/Chicago", "", "Chicago" }, { "America/Chicago", "America/Chicago", "Chicago" }, { "America/Chicago", "America/Chigago Chicago", "Chicago" }, { "America/Chicago", "America/Chicago Oklahoma City", "Oklahoma City" }, { "America/Chicago", "Europe/London London", "Chicago" } }; } TEST(UtilsTest, BeautifulTimezoneName) { for(const auto& test_case : beautify_timezone_test_cases) { auto name = get_beautified_timezone_name(test_case.timezone, test_case.location); EXPECT_STREQ(test_case.expected_name, name); g_free(name); } } TEST(UtilsTest, GetTimezonename) { // set up a local GSettings g_assert(g_setenv("GSETTINGS_SCHEMA_DIR", SCHEMA_DIR, true)); g_assert(g_setenv("GSETTINGS_BACKEND", "memory", true)); g_debug("SCHEMA_DIR is %s", SCHEMA_DIR); auto settings = g_settings_new(SETTINGS_INTERFACE); for(const auto& test_case : beautify_timezone_test_cases) { g_settings_set_string(settings, SETTINGS_TIMEZONE_NAME_S, test_case.location); auto name = get_timezone_name (test_case.timezone, settings); EXPECT_STREQ(test_case.expected_name, name); g_free(name); } g_clear_object(&settings); } ./tests/test-planner.cpp0000644000015600001650000000336312701256660015371 0ustar jenkinsjenkins/* * Copyright 2013 Canonical Ltd. * * Authors: * Charles Kerr * * 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . */ #include "glib-fixture.h" #include "timezone-mock.h" #include #include #include #include #include #include #include using namespace unity::indicator::datetime; /*** **** ***/ typedef GlibFixture PlannerFixture; TEST_F(PlannerFixture, HelloWorld) { auto halloween = DateTime::Local(2020, 10, 31, 18, 30, 59); auto christmas = DateTime::Local(2020, 12, 25, 0, 0, 0); Appointment a; a.summary = "Test"; a.begin = halloween; a.end = a.begin.add_full(0,0,0,1,0,0); const Appointment b = a; a.summary = "Foo"; EXPECT_EQ(a.summary, "Foo"); EXPECT_EQ(b.summary, "Test"); EXPECT_EQ(a.begin, b.begin); EXPECT_EQ(a.end, b.end); Appointment c; c.begin = christmas; c.end = c.begin.add_days(1); Appointment d; d = c; EXPECT_EQ(c.begin, d.begin); EXPECT_EQ(c.end, d.end); a = d; EXPECT_EQ(d.begin, a.begin); EXPECT_EQ(d.end, a.end); } ./tests/test-datetime.cpp0000644000015600001650000000725112701256660015526 0ustar jenkinsjenkins/* * Copyright 2015 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include "glib-fixture.h" using namespace unity::indicator::datetime; /*** **** ***/ class DateTimeFixture: public GlibFixture { public: DateTimeFixture() =default; virtual ~DateTimeFixture() =default; private: typedef GlibFixture super; protected: GRand * m_rand = nullptr; virtual void SetUp() override { super::SetUp(); m_rand = g_rand_new(); } virtual void TearDown() override { g_clear_pointer(&m_rand, g_rand_free); super::TearDown(); } DateTime random_day() { return DateTime::Local(g_rand_int_range(m_rand, 1970, 3000), g_rand_int_range(m_rand, 1, 13), g_rand_int_range(m_rand, 1, 29), g_rand_int_range(m_rand, 0, 24), g_rand_int_range(m_rand, 0, 60), g_rand_double_range(m_rand, 0, 60.0)); } }; /*** **** ***/ TEST_F(DateTimeFixture, StartAndEnd) { const int n_iterations{10000}; for (int i{0}; i. * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_PLANNER_MOCK_H #define INDICATOR_DATETIME_PLANNER_MOCK_H #include namespace unity { namespace indicator { namespace datetime { /** * \brief #RangePlanner which does nothing on its own. * Its controller must set its appointments property. */ class MockRangePlanner: public RangePlanner { public: MockRangePlanner(): m_range(std::pair(DateTime::NowLocal(), DateTime::NowLocal())) { } ~MockRangePlanner() =default; core::Property>& appointments() { return m_appointments; } core::Property>& range() { return m_range; } private: core::Property> m_appointments; core::Property> m_range; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_PLANNER_MOCK_H ./tests/actions-mock.h0000644000015600001650000000661212701256660015011 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_ACTIONS_MOCK_H #define INDICATOR_DATETIME_ACTIONS_MOCK_H #include #include namespace unity { namespace indicator { namespace datetime { class MockActions: public Actions { public: explicit MockActions(const std::shared_ptr& state_in): Actions(state_in) {} ~MockActions() =default; enum Action { DesktopOpenAlarmApp, DesktopOpenAppt, DesktopOpenCalendarApp, DesktopOpenSettingsApp, PhoneOpenAlarmApp, PhoneOpenAppt, PhoneOpenCalendarApp, PhoneOpenSettingsApp, SetLocation }; const std::vector& history() const { return m_history; } const DateTime& date_time() const { return m_date_time; } const std::string& zone() const { return m_zone; } const std::string& name() const { return m_name; } const Appointment& appointment() const { return m_appt; } void clear() { m_history.clear(); m_zone.clear(); m_name.clear(); } bool desktop_has_calendar_app() const { return m_desktop_has_calendar_app; } void desktop_open_alarm_app() { m_history.push_back(DesktopOpenAlarmApp); } void desktop_open_appointment(const Appointment& appt, const DateTime& dt) { m_appt = appt; m_date_time = dt; m_history.push_back(DesktopOpenAppt); } void desktop_open_calendar_app(const DateTime& dt) { m_date_time = dt; m_history.push_back(DesktopOpenCalendarApp); } void desktop_open_settings_app() { m_history.push_back(DesktopOpenSettingsApp); } void phone_open_alarm_app() { m_history.push_back(PhoneOpenAlarmApp); } void phone_open_appointment(const Appointment& appt, const DateTime& dt) { m_appt = appt; m_date_time = dt; m_history.push_back(PhoneOpenAppt); } void phone_open_calendar_app(const DateTime& dt) { m_date_time = dt; m_history.push_back(PhoneOpenCalendarApp); } void phone_open_settings_app() { m_history.push_back(PhoneOpenSettingsApp); } void set_location(const std::string& zone_, const std::string& name_) { m_history.push_back(SetLocation); m_zone = zone_; m_name = name_; } void set_desktop_has_calendar_app(bool b) { m_desktop_has_calendar_app = b; } private: bool m_desktop_has_calendar_app = true; Appointment m_appt; std::string m_zone; std::string m_name; DateTime m_date_time; std::vector m_history; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_ACTIONS_MOCK_H ./tests/test-eds-ics-nonrepeating-events.ics.in0000644000015600001650000000137512701256660021654 0ustar jenkinsjenkinsBEGIN:VCALENDAR CALSCALE:GREGORIAN PRODID:-//Ximian//NONSGML Evolution Calendar//EN VERSION:2.0 X-EVOLUTION-DATA-REVISION:2015-05-20T22:39:32.685099Z(1) BEGIN:VTODO UID:20150520T000726Z-3878-32011-1770-81@ubuntu-phablet DTSTAMP:20150520T223932Z DTSTART:20150520T200000 SUMMARY:Alarm CATEGORIES:x-canonical-alarm SEQUENCE:1 LAST-MODIFIED:20150520T223932Z BEGIN:VALARM X-EVOLUTION-ALARM-UID:20150520T223932Z-22506-32011-1771-2@ubuntu-phablet ACTION:AUDIO ATTACH:file://@ALARM_DEFAULT_SOUND@ TRIGGER;VALUE=DURATION;RELATED=START:PT0S END:VALARM BEGIN:VALARM X-EVOLUTION-ALARM-UID:20150520T223932Z-22506-32011-1771-3@ubuntu-phablet ACTION:DISPLAY DESCRIPTION:Alarm TRIGGER;VALUE=DURATION;RELATED=START:PT0S END:VALARM END:VTODO END:VCALENDAR ./tests/test-eds-ics-tzids-utc.ics.in0000644000015600001650000000055012701256660017601 0ustar jenkinsjenkinsBEGIN:VCALENDAR CALSCALE:GREGORIAN PRODID:-//Ximian//NONSGML Evolution Calendar//EN VERSION:2.0 X-EVOLUTION-DATA-REVISION:2016-03-22T16:13:53.714952Z(2) BEGIN:VEVENT UID:20160322T132738Z DTSTAMP:20160322T133534Z DTSTART:20160322T180000Z DTEND:20160322T190000Z SUMMARY:UTC event SEQUENCE:1 LAST-MODIFIED:20160322T133534Z END:VEVENT END:VCALENDAR ./tests/test-notification.cpp0000644000015600001650000001703612701256660016422 0ustar jenkinsjenkins/* * Copyright 2014-2016 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include #include "notification-fixture.h" /*** **** ***/ using namespace unity::indicator::datetime; namespace { static constexpr char const * APP_NAME {"indicator-datetime-service"}; gboolean quit_idle (gpointer gloop) { g_main_loop_quit(static_cast(gloop)); return G_SOURCE_REMOVE; } } /*** **** ***/ TEST_F(NotificationFixture,Notification) { // Feed different combinations of system settings, // indicator-datetime settings, and event types, // then see if notifications and haptic feedback behave as expected. auto settings = std::make_shared(); auto ne = std::make_shared(APP_NAME); auto sb = std::make_shared(); auto func = [this](const Appointment&, const Alarm&){g_idle_add(quit_idle, loop);}; // combinatorial factor #1: event type struct { Appointment appt; const char* icon_name; const char* prefix; bool expected_notify_called; bool expected_vibrate_called; } test_appts[] = { { appt, "reminder", "Event", true, true }, { ualarm, "alarm-clock", "Alarm", true, true } }; // combinatorial factor #2: indicator-datetime's haptic mode struct { const char* haptic_mode; bool expected_notify_called; bool expected_vibrate_called; } test_haptics[] = { { "none", true, false }, { "pulse", true, true } }; // combinatorial factor #3: system settings' "other vibrations" enabled struct { bool other_vibrations; bool expected_notify_called; bool expected_vibrate_called; } test_other_vibrations[] = { { true, true, true }, { false, true, false } }; // combinatorial factor #4: system settings' notifications app blacklist const std::set> blacklist_calendar { std::make_pair(std::string{"com.ubuntu.calendar"}, std::string{"calendar-app"}) }; const std::set> blacklist_empty; struct { std::set> muted_apps; // apps that should not trigger notifications std::set expected_notify_called; // do we expect the notification to show? std::set expected_vibrate_called; // do we expect the phone to vibrate? } test_muted_apps[] = { { blacklist_empty, std::set{ Appointment::Type::UBUNTU_ALARM, Appointment::Type::EVENT }, std::set{ Appointment::Type::UBUNTU_ALARM, Appointment::Type::EVENT } }, { blacklist_calendar, std::set{ Appointment::Type::UBUNTU_ALARM }, std::set{ Appointment::Type::UBUNTU_ALARM } } }; for (const auto& test_appt : test_appts) { for (const auto& test_haptic : test_haptics) { for (const auto& test_vibes : test_other_vibrations) { for (const auto& test_muted : test_muted_apps) { const bool expected_notify_called = test_appt.expected_notify_called && test_vibes.expected_notify_called && (test_muted.expected_notify_called.count(test_appt.appt.type) > 0) && test_haptic.expected_notify_called; const bool expected_vibrate_called = test_appt.expected_vibrate_called && test_vibes.expected_vibrate_called && (test_muted.expected_vibrate_called.count(test_appt.appt.type) > 0) && test_haptic.expected_vibrate_called; // set test case properties: blacklist settings->muted_apps.set(test_muted.muted_apps); // set test case properties: haptic mode settings->alarm_haptic.set(test_haptic.haptic_mode); // set test case properties: other-vibrations flag // (and wait for the PropertiesChanged signal so we know the dbusmock got it) GError * error {}; dbus_test_dbus_mock_object_update_property(as_mock, as_obj, PROP_OTHER_VIBRATIONS, g_variant_new_boolean(test_vibes.other_vibrations), &error); g_assert_no_error(error); // wait for previous iterations' bus noise to finish and reset the counters wait_msec(500); dbus_test_dbus_mock_object_clear_method_calls(haptic_mock, haptic_obj, &error); dbus_test_dbus_mock_object_clear_method_calls(notify_mock, notify_obj, &error); g_assert_no_error(error); // run the test auto snap = create_snap(ne, sb, settings); (*snap)(test_appt.appt, appt.alarms.front(), func, func); // confirm that the notification was as expected if (expected_notify_called) { EXPECT_METHOD_CALLED_EVENTUALLY(notify_mock, notify_obj, METHOD_NOTIFY); } else { EXPECT_METHOD_NOT_CALLED_EVENTUALLY(notify_mock, notify_obj, METHOD_NOTIFY); } // confirm that the vibration was as expected if (expected_vibrate_called) { EXPECT_METHOD_CALLED_EVENTUALLY(haptic_mock, haptic_obj, HAPTIC_METHOD_VIBRATE_PATTERN); } else { EXPECT_METHOD_NOT_CALLED_EVENTUALLY(haptic_mock, haptic_obj, HAPTIC_METHOD_VIBRATE_PATTERN); } // confirm that the notification was as expected guint num_notify_calls = 0; const auto notify_calls = dbus_test_dbus_mock_object_get_method_calls(notify_mock, notify_obj, METHOD_NOTIFY, &num_notify_calls, &error); g_assert_no_error(error); if (num_notify_calls > 0) { // test that Notify was called with the app_name const gchar* app_name {nullptr}; g_variant_get_child(notify_calls[0].params, 0, "&s", &app_name); ASSERT_STREQ(APP_NAME, app_name); // test that Notify was called with the type-appropriate icon const gchar* icon_name {nullptr}; g_variant_get_child(notify_calls[0].params, 2, "&s", &icon_name); ASSERT_STREQ(test_appt.icon_name, icon_name); // test that the Notification title has the correct prefix const gchar* title {nullptr}; g_variant_get_child(notify_calls[0].params, 3, "&s", &title); ASSERT_TRUE(g_str_has_prefix(title, test_appt.prefix)); // test that Notify was called with the appointment's body const gchar* body {nullptr}; g_variant_get_child(notify_calls[0].params, 4, "&s", &body); ASSERT_STREQ(test_appt.appt.summary.c_str(), body); } } } } } } ./tests/print-to.h0000644000015600001650000000355612701256660014202 0ustar jenkinsjenkins/* * Copyright 2015 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_TESTS_PRINT_TO #define INDICATOR_DATETIME_TESTS_PRINT_TO #include #include namespace unity { namespace indicator { namespace datetime { /*** **** PrintTo() functions for GTest to represent objects as strings ***/ void PrintTo(const DateTime& datetime, std::ostream* os) { *os << "{time:'" << datetime.format("%F %T %z") << '}'; } void PrintTo(const Alarm& alarm, std::ostream* os) { *os << '{'; *os << "{text:" << alarm.text << '}'; PrintTo(alarm.time, os); *os << '}'; } void PrintTo(const Appointment& appointment, std::ostream* os) { *os << '{'; *os << "{uid:'" << appointment.uid << "'}" << "{color:'" << appointment.color << "'}" << "{summary:'" << appointment.summary << "'}" << "{activation_url:'" << appointment.activation_url << "'}"; *os << "{begin:"; PrintTo(appointment.begin, os); *os << '}'; *os << "{end:"; PrintTo(appointment.end, os); *os << '}'; for(const auto& alarm : appointment.alarms) PrintTo(alarm, os); *os << '}'; } } // namespace datetime } // namespace indicator } // namespace unity #endif ./tests/test-live-actions.cpp0000644000015600001650000001700112701256660016321 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include "timedated-fixture.h" /*** **** ***/ TEST_F(TimedateFixture, HelloWorld) { EXPECT_TRUE(true); } TEST_F(TimedateFixture, SetLocation) { const std::string tzid = "America/Chicago"; const std::string name = "Oklahoma City"; const std::string expected = tzid + " " + name; EXPECT_NE(expected, m_state->settings->timezone_name.get()); m_actions->set_location(tzid, name); m_state->settings->timezone_name.changed().connect( [this](const std::string&){ g_main_loop_quit(loop); }); g_main_loop_run(loop); EXPECT_EQ(attempted_tzid, tzid); wait_msec(); EXPECT_EQ(expected, m_state->settings->timezone_name.get()); } /*** **** ***/ TEST_F(TimedateFixture, DesktopOpenAlarmApp) { m_actions->desktop_open_alarm_app(); const std::string expected = "evolution -c calendar"; EXPECT_EQ(expected, m_live_actions->last_cmd); } TEST_F(TimedateFixture, DesktopOpenAppointment) { Appointment a; a.uid = "some-uid"; a.begin = DateTime::NowLocal(); m_actions->desktop_open_appointment(a, a.begin); const std::string expected_substr = "evolution \"calendar:///?startdate="; EXPECT_NE(m_live_actions->last_cmd.find(expected_substr), std::string::npos); } TEST_F(TimedateFixture, DesktopOpenCalendarApp) { m_actions->desktop_open_calendar_app(DateTime::NowLocal()); const std::string expected_substr = "evolution \"calendar:///?startdate="; EXPECT_NE(m_live_actions->last_cmd.find(expected_substr), std::string::npos); } TEST_F(TimedateFixture, DesktopOpenSettingsApp) { m_actions->desktop_open_settings_app(); const std::string expected_substr = "control-center"; EXPECT_NE(m_live_actions->last_cmd.find(expected_substr), std::string::npos); } /*** **** ***/ namespace { const std::string clock_app_url = "appid://com.ubuntu.clock/clock/current-user-version"; } TEST_F(TimedateFixture, PhoneOpenAlarmApp) { m_actions->phone_open_alarm_app(); EXPECT_EQ(clock_app_url, m_live_actions->last_url); } TEST_F(TimedateFixture, PhoneOpenAppointment) { Appointment a; a.uid = "event-uid"; a.source_uid = "source-uid"; a.begin = DateTime::NowLocal(); a.type = Appointment::EVENT; auto ocurrenceDate = DateTime::Local(2014, 1, 1, 0, 0, 0); m_actions->phone_open_appointment(a, ocurrenceDate); const std::string appointment_app_url = ocurrenceDate.to_timezone("UTC").format("calendar://startdate=%Y-%m-%dT%H:%M:%S+00:00"); EXPECT_EQ(appointment_app_url, m_live_actions->last_url); a.type = Appointment::UBUNTU_ALARM; m_actions->phone_open_appointment(a, a.begin); EXPECT_EQ(clock_app_url, m_live_actions->last_url); } TEST_F(TimedateFixture, PhoneOpenCalendarApp) { auto now = DateTime::NowLocal(); m_actions->phone_open_calendar_app(now); const std::string expected = now.to_timezone("UTC").format("calendar://startdate=%Y-%m-%dT%H:%M:%S+00:00"); EXPECT_EQ(expected, m_live_actions->last_url); } TEST_F(TimedateFixture, PhoneOpenSettingsApp) { m_actions->phone_open_settings_app(); const std::string expected = "settings:///system/time-date"; EXPECT_EQ(expected, m_live_actions->last_url); } /*** **** ***/ TEST_F(TimedateFixture, CalendarState) { // init the clock auto now = DateTime::Local(2014, 1, 1, 0, 0, 0); m_mock_state->mock_clock->set_localtime (now); m_state->calendar_month->month().set(now); //m_state->planner->time.set(now); /// /// Test the default calendar state. /// auto action_group = m_actions->action_group(); auto calendar_state = g_action_group_get_action_state (action_group, "calendar"); EXPECT_TRUE (calendar_state != nullptr); EXPECT_TRUE (g_variant_is_of_type (calendar_state, G_VARIANT_TYPE_DICTIONARY)); // there's nothing in the planner yet, so appointment-days should be an empty array auto v = g_variant_lookup_value (calendar_state, "appointment-days", G_VARIANT_TYPE_ARRAY); EXPECT_TRUE (v != nullptr); EXPECT_EQ (0, g_variant_n_children (v)); g_clear_pointer (&v, g_variant_unref); // calendar-day should be in sync with m_state->calendar_day v = g_variant_lookup_value (calendar_state, "calendar-day", G_VARIANT_TYPE_INT64); EXPECT_TRUE (v != nullptr); EXPECT_EQ (m_state->calendar_month->month().get().to_unix(), g_variant_get_int64(v)); g_clear_pointer (&v, g_variant_unref); // show-week-numbers should be false because MockSettings defaults everything to 0 v = g_variant_lookup_value (calendar_state, "show-week-numbers", G_VARIANT_TYPE_BOOLEAN); EXPECT_TRUE (v != nullptr); EXPECT_FALSE (g_variant_get_boolean (v)); g_clear_pointer (&v, g_variant_unref); // cleanup this step g_clear_pointer (&calendar_state, g_variant_unref); /// /// Now add appointments to the planner and confirm that the state keeps in sync /// auto tomorrow = now.add_days(1); auto tomorrow_begin = tomorrow.start_of_day(); auto tomorrow_end = tomorrow.end_of_day(); Appointment a1; a1.color = "green"; a1.summary = "write unit tests"; a1.uid = "D4B57D50247291478ED31DED17FF0A9838DED402"; a1.begin = tomorrow_begin; a1.end = tomorrow_end; auto ubermorgen = now.add_days(2); auto ubermorgen_begin = ubermorgen.start_of_day(); auto ubermorgen_end = ubermorgen.end_of_day(); Appointment a2; a2.color = "orange"; a2.summary = "code review"; a2.uid = "2756ff7de3745bbffd65d2e4779c37c7ca60d843"; a2.begin = ubermorgen_begin; a2.end = ubermorgen_end; m_state->calendar_month->appointments().set(std::vector({a1, a2})); /// /// Now test the calendar state again. /// The this_month field should now contain the appointments we just added. /// calendar_state = g_action_group_get_action_state (action_group, "calendar"); v = g_variant_lookup_value (calendar_state, "appointment-days", G_VARIANT_TYPE_ARRAY); EXPECT_TRUE (v != nullptr); int i; g_variant_get_child (v, 0, "i", &i); EXPECT_EQ (a1.begin.day_of_month(), i); g_variant_get_child (v, 1, "i", &i); EXPECT_EQ (a2.begin.day_of_month(), i); g_clear_pointer(&v, g_variant_unref); g_clear_pointer(&calendar_state, g_variant_unref); /// /// Confirm that the action state's dictionary /// keeps in sync with settings.show_week_numbers /// auto b = m_state->settings->show_week_numbers.get(); for (i=0; i<2; i++) { b = !b; m_state->settings->show_week_numbers.set(b); calendar_state = g_action_group_get_action_state (action_group, "calendar"); v = g_variant_lookup_value (calendar_state, "show-week-numbers", G_VARIANT_TYPE_BOOLEAN); EXPECT_TRUE(v != nullptr); EXPECT_EQ(b, g_variant_get_boolean(v)); g_clear_pointer(&v, g_variant_unref); g_clear_pointer(&calendar_state, g_variant_unref); } } ./tests/test-formatter.cpp0000644000015600001650000001671012701256660015735 0ustar jenkinsjenkins /* * Copyright 2013 Canonical Ltd. * * Authors: * Charles Kerr * * 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . */ #include "glib-fixture.h" #include #include #include #include #include #include using namespace unity::indicator::datetime; /*** **** ***/ class FormatterFixture: public GlibFixture { private: typedef GlibFixture super; gchar* m_original_locale = nullptr; protected: std::shared_ptr m_settings; void SetUp() override { super::SetUp(); m_settings.reset(new Settings); m_original_locale = g_strdup(setlocale(LC_TIME, nullptr)); } void TearDown() override { m_settings.reset(); setlocale(LC_TIME, m_original_locale); g_clear_pointer(&m_original_locale, g_free); super::TearDown(); } bool SetLocale(const char* expected_locale, const char* name) { if (setlocale(LC_TIME, expected_locale) != nullptr) { return true; } else { g_warning("Unable to set locale to %s; skipping %s locale tests. (Current LC_TIME: %s)", expected_locale, name, setlocale(LC_TIME, nullptr)); return false; } } inline bool Set24hLocale() { return SetLocale("C", "24h"); } inline bool Set12hLocale() { return SetLocale("en_US.utf8", "12h"); } }; /** * Test the phone header format */ TEST_F(FormatterFixture, DISABLED_TestPhoneHeader) { auto now = DateTime::Local(2020, 10, 31, 18, 30, 59); auto clock = std::make_shared(now); // test the default value in a 24h locale if(Set24hLocale()) { PhoneFormatter formatter(clock); EXPECT_EQ(std::string("%H:%M"), formatter.header_format.get()); EXPECT_EQ(std::string("18:30"), formatter.header.get()); } // test the default value in a 12h locale if(Set12hLocale()) { PhoneFormatter formatter(clock); EXPECT_EQ(std::string("%l:%M %p"), formatter.header_format.get()); EXPECT_EQ(std::string(" 6:30 PM"), formatter.header.get()); } } #define EM_SPACE "\u2003" /** * Test the default values of the desktop header format */ TEST_F(FormatterFixture, DISABLED_TestDesktopHeader) { struct { bool is_12h; bool show_day; bool show_date; bool show_year; const char* expected_format_string; } test_cases[] = { { false, false, false, false, "%H:%M" }, { false, false, false, true, "%H:%M" }, // show_year is ignored iff show_date is false { false, false, true, false, "%b %e" EM_SPACE "%H:%M" }, { false, false, true, true, "%b %e %Y" EM_SPACE "%H:%M" }, { false, true, false, false, "%a" EM_SPACE "%H:%M" }, { false, true, false, true, "%a" EM_SPACE "%H:%M" }, // show_year is ignored iff show_date is false { false, true, true, false, "%a %b %e" EM_SPACE "%H:%M" }, { false, true, true, true, "%a %b %e %Y" EM_SPACE "%H:%M" }, { true, false, false, false, "%l:%M %p" }, { true, false, false, true, "%l:%M %p" }, // show_year is ignored iff show_date is false { true, false, true, false, "%b %e" EM_SPACE "%l:%M %p" }, { true, false, true, true, "%b %e %Y" EM_SPACE "%l:%M %p" }, { true, true, false, false, "%a" EM_SPACE "%l:%M %p" }, { true, true, false, true, "%a" EM_SPACE "%l:%M %p" }, // show_year is ignored iff show_date is false { true, true, true, false, "%a %b %e" EM_SPACE "%l:%M %p" }, { true, true, true, true, "%a %b %e %Y" EM_SPACE "%l:%M %p" } }; auto now = DateTime::Local(2020, 10, 31, 18, 30, 59); auto clock = std::make_shared(now); for(const auto& test_case : test_cases) { if (test_case.is_12h ? Set12hLocale() : Set24hLocale()) { DesktopFormatter f(clock, m_settings); m_settings->show_day.set(test_case.show_day); m_settings->show_date.set(test_case.show_date); m_settings->show_year.set(test_case.show_year); ASSERT_STREQ(test_case.expected_format_string, f.header_format.get().c_str()); } } } /** * Test the default values of the desktop header format */ TEST_F(FormatterFixture, DISABLED_TestUpcomingTimes) { auto a = DateTime::Local(2020, 10, 31, 18, 30, 59); struct { gboolean is_12h; DateTime now; DateTime then; const char* expected_format_string; } test_cases[] = { { true, a, a, "%l:%M %p" }, // identical time { true, a, a.add_full(0,0,0,1,0,0), "%l:%M %p" }, // later today { true, a, a.add_days(1), "Tomorrow" EM_SPACE "%l:%M %p" }, // tomorrow { true, a, a.add_days(2), "%a" EM_SPACE "%l:%M %p" }, { true, a, a.add_days(6), "%a" EM_SPACE "%l:%M %p" }, { true, a, a.add_days(7), "%a %d %b" EM_SPACE "%l:%M %p" }, // over one week away { false, a, a, "%H:%M" }, // identical time { false, a, a.add_full(0,0,0,1,0,0), "%H:%M" }, // later today { false, a, a.add_days(1), "Tomorrow" EM_SPACE "%H:%M" }, // tomorrow { false, a, a.add_days(2), "%a" EM_SPACE "%H:%M" }, { false, a, a.add_days(6), "%a" EM_SPACE "%H:%M" }, { false, a, a.add_days(7), "%a %d %b" EM_SPACE "%H:%M" } // over one week away }; for(const auto& test_case : test_cases) { if (test_case.is_12h ? Set12hLocale() : Set24hLocale()) { auto clock = std::make_shared(test_case.now); DesktopFormatter f(clock, m_settings); const auto fmt = f.relative_format(test_case.then.get()); ASSERT_EQ(test_case.expected_format_string, fmt); } } } /** * Test the default values of the desktop header format */ TEST_F(FormatterFixture, DISABLED_TestEventTimes) { auto day = DateTime::Local(2013, 1, 1, 13, 0, 0); auto day_begin = DateTime::Local(2013, 1, 1, 13, 0, 0); auto day_end = day_begin.add_days(1); auto tomorrow_begin = day_begin.add_days(1); auto tomorrow_end = tomorrow_begin.add_days(1); struct { bool is_12h; DateTime now; DateTime then; DateTime then_end; const char* expected_format_string; } test_cases[] = { { false, day, day_begin, day_end, _("Today") }, { true, day, day_begin, day_end, _("Today") }, { false, day, tomorrow_begin, tomorrow_end, _("Tomorrow") }, { true, day, tomorrow_begin, tomorrow_end, _("Tomorrow") } }; for(const auto& test_case : test_cases) { if (test_case.is_12h ? Set12hLocale() : Set24hLocale()) { auto clock = std::make_shared(test_case.now); DesktopFormatter f(clock, m_settings); const auto fmt = f.relative_format(test_case.then.get(), test_case.then_end.get()); ASSERT_STREQ(test_case.expected_format_string, fmt.c_str()); } } } ./tests/test-eds-ics-missing-trigger.ics.in0000644000015600001650000000235712701256660020774 0ustar jenkinsjenkinsBEGIN:VCALENDAR CALSCALE:GREGORIAN PRODID:-//Ximian//NONSGML Evolution Calendar//EN VERSION:2.0 X-EVOLUTION-DATA-REVISION:2015-06-17T21:19:13.980613Z(3) BEGIN:VTODO UID:20150617T211838Z-6217-32011-2036-1@ubuntu-phablet DTSTAMP:20150617T211838Z DTSTART:20150618T100000 SUMMARY:One Time Alarm CATEGORIES:x-canonical-alarm CREATED:20150617T211838Z LAST-MODIFIED:20150617T211838Z BEGIN:VALARM X-EVOLUTION-ALARM-UID:20150617T211838Z-6217-32011-2036-2@ubuntu-phablet ACTION:AUDIO ATTACH:file://@ALARM_DEFAULT_SOUND@ END:VALARM BEGIN:VALARM X-EVOLUTION-ALARM-UID:20150617T211838Z-6217-32011-2036-3@ubuntu-phablet ACTION:DISPLAY DESCRIPTION:One Time Alarm END:VALARM END:VTODO BEGIN:VTODO UID:20150617T211913Z-6217-32011-2036-5@ubuntu-phablet DTSTAMP:20150617T211913Z DTSTART:20150618T100100 RRULE:FREQ=DAILY SUMMARY:Recurring Alarm CATEGORIES:x-canonical-alarm CREATED:20150617T211913Z LAST-MODIFIED:20150617T211913Z BEGIN:VALARM X-EVOLUTION-ALARM-UID:20150617T211913Z-6217-32011-2036-6@ubuntu-phablet ACTION:AUDIO ATTACH:file://@ALARM_DEFAULT_SOUND@ END:VALARM BEGIN:VALARM X-EVOLUTION-ALARM-UID:20150617T211913Z-6217-32011-2036-7@ubuntu-phablet ACTION:DISPLAY DESCRIPTION:Recurring Alarm END:VALARM END:VTODO END:VCALENDAR ./tests/test-eds-ics-repeating-valarms.ics.in0000644000015600001650000000250012701256660021271 0ustar jenkinsjenkinsBEGIN:VCALENDAR CALSCALE:GREGORIAN PRODID:-//Ximian//NONSGML Evolution Calendar//EN VERSION:2.0 X-EVOLUTION-DATA-REVISION:2015-04-05T21:32:47.354433Z(2) BEGIN:VEVENT UID:20150405T213247Z-4371-32011-1698-1@ubuntu-phablet DTSTAMP:20150405T213247Z DTSTART:20150424T183500Z DTEND:20150424T193554Z X-LIC-ERROR;X-LIC-ERRORTYPE=VALUE-PARSE-ERROR:Can't parse as RECUR value in RRULE property. Removing entire property: ERROR: No Value SUMMARY:London Sprint Flight CREATED:20150405T213247Z LAST-MODIFIED:20150405T213247Z BEGIN:VALARM X-EVOLUTION-ALARM-UID:20150405T213247Z-4371-32011-1698-2@ubuntu-phablet ACTION:AUDIO TRIGGER;VALUE=DURATION;RELATED=START:-P1D REPEAT:3 DURATION:PT2M END:VALARM BEGIN:VALARM X-EVOLUTION-ALARM-UID:20150405T213247Z-4371-32011-1698-3@ubuntu-phablet ACTION:DISPLAY DESCRIPTION:Time to pack! TRIGGER;VALUE=DURATION;RELATED=START:-P1D REPEAT:3 DURATION:PT2M END:VALARM BEGIN:VALARM X-EVOLUTION-ALARM-UID:20150405T213247Z-4371-32011-1698-5@ubuntu-phablet ACTION:AUDIO TRIGGER;VALUE=DURATION;RELATED=START:-PT3H REPEAT:3 DURATION:PT2M END:VALARM BEGIN:VALARM X-EVOLUTION-ALARM-UID:20150405T213247Z-4371-32011-1698-6@ubuntu-phablet ACTION:DISPLAY DESCRIPTION:Go to the airport! TRIGGER;VALUE=DURATION;RELATED=START:-PT3H REPEAT:3 DURATION:PT2M END:VALARM END:VEVENT END:VCALENDAR ./tests/test-eds-ics-repeating-valarms.cpp0000644000015600001650000001035412701256660020676 0ustar jenkinsjenkins/* * Copyright 2015 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include #include #include #include #include "glib-fixture.h" #include "print-to.h" #include "timezone-mock.h" #include "wakeup-timer-mock.h" using namespace unity::indicator::datetime; using VAlarmFixture = GlibFixture; /*** **** ***/ TEST_F(VAlarmFixture, MultipleAppointments) { // start the EDS engine auto engine = std::make_shared(); // we need a consistent timezone for the planner and our local DateTimes constexpr char const * zone_str {"America/Chicago"}; auto tz = std::make_shared(zone_str); auto gtz = g_time_zone_new(zone_str); // make a planner that looks at the first half of 2015 in EDS auto planner = std::make_shared(engine, tz); const DateTime range_begin {gtz, 2015,1, 1, 0, 0, 0.0}; const DateTime range_end {gtz, 2015,6,31,23,59,59.5}; planner->range().set(std::make_pair(range_begin, range_end)); // give EDS a moment to load if (planner->appointments().get().empty()) { g_message("waiting a moment for EDS to load..."); auto on_appointments_changed = [this](const std::vector& appointments){ g_message("ah, they loaded"); if (!appointments.empty()) g_main_loop_quit(loop); }; core::ScopedConnection conn(planner->appointments().changed().connect(on_appointments_changed)); constexpr int max_wait_sec = 10; wait_msec(max_wait_sec * G_TIME_SPAN_MILLISECOND); } // the planner should match what we've got in the calendar.ics file const auto appts = planner->appointments().get(); ASSERT_EQ(1, appts.size()); const auto& appt = appts.front(); ASSERT_EQ(8, appt.alarms.size()); EXPECT_EQ(Alarm({"Time to pack!", "", DateTime(gtz,2015,4,23,13,35,0)}), appt.alarms[0]); EXPECT_EQ(Alarm({"Time to pack!", "", DateTime(gtz,2015,4,23,13,37,0)}), appt.alarms[1]); EXPECT_EQ(Alarm({"Time to pack!", "", DateTime(gtz,2015,4,23,13,39,0)}), appt.alarms[2]); EXPECT_EQ(Alarm({"Time to pack!", "", DateTime(gtz,2015,4,23,13,41,0)}), appt.alarms[3]); EXPECT_EQ(Alarm({"Go to the airport!", "", DateTime(gtz,2015,4,24,10,35,0)}), appt.alarms[4]); EXPECT_EQ(Alarm({"Go to the airport!", "", DateTime(gtz,2015,4,24,10,37,0)}), appt.alarms[5]); EXPECT_EQ(Alarm({"Go to the airport!", "", DateTime(gtz,2015,4,24,10,39,0)}), appt.alarms[6]); EXPECT_EQ(Alarm({"Go to the airport!", "", DateTime(gtz,2015,4,24,10,41,0)}), appt.alarms[7]); // now let's try this out with AlarmQueue... // hook the planner up to a SimpleAlarmQueue and confirm that it triggers for each of the reminders auto mock_clock = std::make_shared(range_begin); std::shared_ptr clock = mock_clock; std::shared_ptr wakeup_timer = std::make_shared(clock); auto alarm_queue = std::make_shared(clock, planner, wakeup_timer); int triggered_count = 0; alarm_queue->alarm_reached().connect([&triggered_count, appt](const Appointment&, const Alarm& active_alarm) { EXPECT_TRUE(std::find(appt.alarms.begin(), appt.alarms.end(), active_alarm) != appt.alarms.end()); ++triggered_count; }); for (auto now=range_begin; nowset_localtime(now); EXPECT_EQ(appt.alarms.size(), triggered_count); // cleanup g_time_zone_unref(gtz); } ./tests/test-menus.cpp0000644000015600001650000005057512701256660015070 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include "actions-mock.h" #include "state-fixture.h" #include #include #include #include #include using namespace unity::indicator::datetime; class MenuFixture: public StateFixture { private: typedef StateFixture super; protected: std::shared_ptr m_menu_factory; std::vector> m_menus; void SetUp() override { super::SetUp(); // build the menus on top of the actions and state m_menu_factory.reset(new MenuFactory(m_actions, m_state)); for(int i=0; ibuildMenu(Menu::Profile(i))); } void TearDown() override { m_menus.clear(); m_menu_factory.reset(); super::TearDown(); } void InspectHeader(GMenuModel* menu_model, const std::string& name) { // check that there's a header menuitem EXPECT_EQ(1,g_menu_model_get_n_items(menu_model)); gchar* str = nullptr; g_menu_model_get_item_attribute(menu_model, 0, "x-canonical-type", "s", &str); EXPECT_STREQ("com.canonical.indicator.root", str); g_clear_pointer(&str, g_free); g_menu_model_get_item_attribute(menu_model, 0, G_MENU_ATTRIBUTE_ACTION, "s", &str); const auto action_name = name + "-header"; EXPECT_EQ(std::string("indicator.")+action_name, str); g_clear_pointer(&str, g_free); // check the header auto dict = g_action_group_get_action_state(m_actions->action_group(), action_name.c_str()); EXPECT_TRUE(dict != nullptr); EXPECT_TRUE(g_variant_is_of_type(dict, G_VARIANT_TYPE_VARDICT)); auto v = g_variant_lookup_value(dict, "accessible-desc", G_VARIANT_TYPE_STRING); EXPECT_TRUE(v != nullptr); g_variant_unref(v); v = g_variant_lookup_value(dict, "label", G_VARIANT_TYPE_STRING); EXPECT_TRUE(v != nullptr); g_variant_unref(v); v = g_variant_lookup_value(dict, "title", G_VARIANT_TYPE_STRING); EXPECT_TRUE(v != nullptr); g_variant_unref(v); v = g_variant_lookup_value(dict, "visible", G_VARIANT_TYPE_BOOLEAN); EXPECT_TRUE(v != nullptr); g_variant_unref(v); g_variant_unref(dict); } void InspectCalendar(GMenuModel* menu_model, Menu::Profile profile) { gchar* str = nullptr; const char * expected_action; if (profile == Menu::Desktop) expected_action = "indicator.desktop.open-calendar-app"; else if (profile == Menu::Phone) expected_action = "indicator.phone.open-calendar-app"; else expected_action = nullptr; const auto calendar_expected = ((profile == Menu::Desktop) || (profile == Menu::DesktopGreeter)) && (m_state->settings->show_calendar.get()); // get the calendar section auto submenu = g_menu_model_get_item_link(menu_model, 0, G_MENU_LINK_SUBMENU); auto section = g_menu_model_get_item_link(submenu, Menu::Calendar, G_MENU_LINK_SECTION); // should be one or two items: a date label and maybe a calendar ASSERT_TRUE(section != nullptr); auto n_expected = calendar_expected ? 2 : 1; EXPECT_EQ(n_expected, g_menu_model_get_n_items(section)); // look at the date menuitem g_menu_model_get_item_attribute(section, 0, G_MENU_ATTRIBUTE_LABEL, "s", &str); const auto now = m_state->clock->localtime(); EXPECT_EQ(now.format("%A, %e %B %Y"), str); g_clear_pointer(&str, g_free); g_menu_model_get_item_attribute(section, 0, G_MENU_ATTRIBUTE_ACTION, "s", &str); if (expected_action != nullptr) EXPECT_STREQ(expected_action, str); else EXPECT_TRUE(str == nullptr); g_clear_pointer(&str, g_free); // look at the calendar menuitem if (calendar_expected) { g_menu_model_get_item_attribute(section, 1, "x-canonical-type", "s", &str); EXPECT_STREQ("com.canonical.indicator.calendar", str); g_clear_pointer(&str, g_free); g_menu_model_get_item_attribute(section, 1, G_MENU_ATTRIBUTE_ACTION, "s", &str); EXPECT_STREQ("indicator.calendar", str); g_clear_pointer(&str, g_free); g_menu_model_get_item_attribute(section, 1, "activation-action", "s", &str); if (expected_action != nullptr) EXPECT_STREQ(expected_action, str); else EXPECT_TRUE(str == nullptr); g_clear_pointer(&str, g_free); } g_clear_object(§ion); // now change the clock and see if the date label changes appropriately auto tomorrow = now.add_days(1).start_of_day(); m_mock_state->mock_clock->set_localtime(tomorrow); wait_msec(); section = g_menu_model_get_item_link(submenu, Menu::Calendar, G_MENU_LINK_SECTION); g_menu_model_get_item_attribute(section, 0, G_MENU_ATTRIBUTE_LABEL, "s", &str); EXPECT_EQ(tomorrow.format("%A, %e %B %Y"), str); g_clear_pointer(&str, g_free); g_clear_object(§ion); // cleanup g_object_unref(submenu); } private: void InspectEmptySection(GMenuModel* menu_model, Menu::Section section) { // get the Appointments section auto submenu = g_menu_model_get_item_link(menu_model, 0, G_MENU_LINK_SUBMENU); auto menu_section = g_menu_model_get_item_link(submenu, section, G_MENU_LINK_SECTION); EXPECT_EQ(0, g_menu_model_get_n_items(menu_section)); g_clear_object(&menu_section); g_clear_object(&submenu); } std::vector build_some_appointments() { const auto now = m_state->clock->localtime(); const auto tomorrow = now.add_days(1); Appointment a1; // an alarm clock appointment a1.color = "red"; a1.summary = "Alarm"; a1.summary = "http://www.example.com/"; a1.uid = "example"; a1.type = Appointment::UBUNTU_ALARM; a1.begin = a1.end = tomorrow; Appointment a2; // a non-alarm appointment a2.color = "green"; a2.summary = "Other Text"; a2.summary = "http://www.monkey.com/"; a2.uid = "monkey"; a1.type = Appointment::EVENT; a2.begin = a2.end = tomorrow; return std::vector({a1, a2}); } void InspectAppointmentMenuItem(GMenuModel* section, int index, const Appointment& appt) { // confirm it has the right x-canonical-type gchar * str = nullptr; g_menu_model_get_item_attribute(section, index, "x-canonical-type", "s", &str); if (appt.is_ubuntu_alarm()) EXPECT_STREQ("com.canonical.indicator.alarm", str); else EXPECT_STREQ("com.canonical.indicator.appointment", str); g_clear_pointer(&str, g_free); // confirm it has a nonempty x-canonical-time-format g_menu_model_get_item_attribute(section, index, "x-canonical-time-format", "s", &str); EXPECT_TRUE(str && *str); g_clear_pointer(&str, g_free); // confirm the color hint, if it exists, // is in the x-canonical-color attribute if (appt.color.empty()) { EXPECT_FALSE(g_menu_model_get_item_attribute(section, index, "x-canonical-color", "s", &str)); } else { EXPECT_TRUE(g_menu_model_get_item_attribute(section, index, "x-canonical-color", "s", &str)); EXPECT_EQ(appt.color, str); } g_clear_pointer(&str, g_free); // confirm that alarms have an icon if (appt.is_ubuntu_alarm()) { auto v = g_menu_model_get_item_attribute_value(section, index, G_MENU_ATTRIBUTE_ICON, nullptr); EXPECT_TRUE(v != nullptr); auto icon = g_icon_deserialize(v); EXPECT_TRUE(icon != nullptr); g_clear_object(&icon); g_clear_pointer(&v, g_variant_unref); } } void InspectAppointmentMenuItems(GMenuModel* section, int first_appt_index, const std::vector& appointments, bool can_open_planner) { // try adding a few appointments and see if the menu updates itself m_state->calendar_upcoming->appointments().set(appointments); wait_msec(); // wait a moment for the menu to update //auto submenu = g_menu_model_get_item_link(menu_model, 0, G_MENU_LINK_SUBMENU); //auto section = g_menu_model_get_item_link(submenu, Menu::Appointments, G_MENU_LINK_SECTION); const int n_add_event_buttons = can_open_planner ? 1 : 0; EXPECT_EQ(n_add_event_buttons + appointments.size(), g_menu_model_get_n_items(section)); for (int i=0, n=appointments.size(); isettings->show_events.set(false); wait_msec(); auto section = g_menu_model_get_item_link(submenu, Menu::Appointments, G_MENU_LINK_SECTION); EXPECT_EQ(0, g_menu_model_get_n_items(section)); g_clear_object(§ion); std::vector appointments; m_state->settings->show_events.set(true); m_state->calendar_upcoming->appointments().set(appointments); wait_msec(); section = g_menu_model_get_item_link(submenu, Menu::Appointments, G_MENU_LINK_SECTION); EXPECT_EQ(n_add_event_buttons, g_menu_model_get_n_items(section)); if (can_open_planner) { // when "show_events" is true, // there should be an "add event" button even if there aren't any appointments gchar* action = nullptr; EXPECT_TRUE(g_menu_model_get_item_attribute(section, 0, G_MENU_ATTRIBUTE_ACTION, "s", &action)); const char* expected_action = "desktop.open-calendar-app"; EXPECT_EQ(std::string("indicator.")+expected_action, action); EXPECT_TRUE(g_action_group_has_action(m_actions->action_group(), expected_action)); g_free(action); } g_clear_object(§ion); // try adding a few appointments and see if the menu updates itself appointments = build_some_appointments(); m_state->calendar_upcoming->appointments().set(appointments); wait_msec(); // wait a moment for the menu to update section = g_menu_model_get_item_link(submenu, Menu::Appointments, G_MENU_LINK_SECTION); EXPECT_EQ(n_add_event_buttons + 2, g_menu_model_get_n_items(section)); InspectAppointmentMenuItems(section, 0, appointments, can_open_planner); g_clear_object(§ion); // cleanup g_clear_object(&submenu); } void InspectPhoneAppointments(GMenuModel* menu_model, bool can_open_planner) { auto submenu = g_menu_model_get_item_link(menu_model, 0, G_MENU_LINK_SUBMENU); // clear all the appointments std::vector appointments; m_state->calendar_upcoming->appointments().set(appointments); wait_msec(); // wait a moment for the menu to update // check that there's a "clock app" menuitem even when there are no appointments auto section = g_menu_model_get_item_link(submenu, Menu::Appointments, G_MENU_LINK_SECTION); const char* expected_action = "phone.open-alarm-app"; EXPECT_EQ(1, g_menu_model_get_n_items(section)); gchar* action = nullptr; EXPECT_TRUE(g_menu_model_get_item_attribute(section, 0, G_MENU_ATTRIBUTE_ACTION, "s", &action)); EXPECT_EQ(std::string("indicator.")+expected_action, action); EXPECT_TRUE(g_action_group_has_action(m_actions->action_group(), expected_action)); g_free(action); g_clear_object(§ion); // add some appointments and test them appointments = build_some_appointments(); m_state->calendar_upcoming->appointments().set(appointments); wait_msec(); // wait a moment for the menu to update section = g_menu_model_get_item_link(submenu, Menu::Appointments, G_MENU_LINK_SECTION); EXPECT_EQ(3, g_menu_model_get_n_items(section)); InspectAppointmentMenuItems(section, 1, appointments, can_open_planner); g_clear_object(§ion); // cleanup g_clear_object(&submenu); } protected: void InspectAppointments(GMenuModel* menu_model, Menu::Profile profile) { const auto can_open_planner = m_actions->desktop_has_calendar_app(); switch (profile) { case Menu::Desktop: InspectDesktopAppointments(menu_model, can_open_planner); break; case Menu::DesktopGreeter: InspectEmptySection(menu_model, Menu::Appointments); break; case Menu::Phone: InspectPhoneAppointments(menu_model, can_open_planner); break; case Menu::PhoneGreeter: InspectEmptySection(menu_model, Menu::Appointments); break; default: g_warn_if_reached(); break; } } void CompareLocationsTo(GMenuModel* menu_model, const std::vector& locations) { // get the Locations section auto submenu = g_menu_model_get_item_link(menu_model, 0, G_MENU_LINK_SUBMENU); auto section = g_menu_model_get_item_link(submenu, Menu::Locations, G_MENU_LINK_SECTION); // confirm that section's menuitems mirror the "locations" vector const auto n = locations.size(); ASSERT_EQ(n, g_menu_model_get_n_items(section)); for (guint i=0; i empty; m_state->locations->locations.set(empty); wait_msec(); CompareLocationsTo(menu_model, empty); // add some locations and confirm the menu picked up our changes Location l1 ("America/Chicago", "Dallas"); Location l2 ("America/Arizona", "Phoenix"); std::vector locations({l1, l2}); m_state->locations->locations.set(locations); wait_msec(); CompareLocationsTo(menu_model, locations_expected ? locations : empty); // now remove one of the locations... locations.pop_back(); m_state->locations->locations.set(locations); wait_msec(); CompareLocationsTo(menu_model, locations_expected ? locations : empty); } void InspectSettings(GMenuModel* menu_model, Menu::Profile profile) { std::string expected_action; if (profile == Menu::Desktop) expected_action = "indicator.desktop.open-settings-app"; else if (profile == Menu::Phone) expected_action = "indicator.phone.open-settings-app"; // get the Settings section auto submenu = g_menu_model_get_item_link(menu_model, 0, G_MENU_LINK_SUBMENU); auto section = g_menu_model_get_item_link(submenu, Menu::Settings, G_MENU_LINK_SECTION); if (expected_action.empty()) { EXPECT_EQ(0, g_menu_model_get_n_items(section)); } else { EXPECT_EQ(1, g_menu_model_get_n_items(section)); gchar* str = nullptr; g_menu_model_get_item_attribute(section, 0, G_MENU_ATTRIBUTE_ACTION, "s", &str); EXPECT_EQ(expected_action, str); g_clear_pointer(&str, g_free); } g_clear_object(§ion); g_object_unref(submenu); } }; TEST_F(MenuFixture, HelloWorld) { EXPECT_EQ(Menu::NUM_PROFILES, m_menus.size()); for (int i=0; imenu_model() != nullptr); EXPECT_EQ(i, m_menus[i]->profile()); } EXPECT_EQ(m_menus[Menu::Desktop]->name(), "desktop"); } TEST_F(MenuFixture, Header) { for(auto& menu : m_menus) InspectHeader(menu->menu_model(), menu->name()); } TEST_F(MenuFixture, Sections) { for(auto& menu : m_menus) { // check that the header has a submenu auto menu_model = menu->menu_model(); auto submenu = g_menu_model_get_item_link(menu_model, 0, G_MENU_LINK_SUBMENU); EXPECT_TRUE(submenu != nullptr); EXPECT_EQ(Menu::NUM_SECTIONS, g_menu_model_get_n_items(submenu)); g_object_unref(submenu); } } TEST_F(MenuFixture, Calendar) { m_state->settings->show_calendar.set(true); for(auto& menu : m_menus) InspectCalendar(menu->menu_model(), menu->profile()); m_state->settings->show_calendar.set(false); for(auto& menu : m_menus) InspectCalendar(menu->menu_model(), menu->profile()); } TEST_F(MenuFixture, Appointments) { for(auto& menu : m_menus) InspectAppointments(menu->menu_model(), menu->profile()); // toggle can_open_planner() and test the desktop again // to confirm that the "Add Event…" menuitem appears iff // there's a calendar available user-agent m_mock_actions->set_desktop_has_calendar_app (!m_actions->desktop_has_calendar_app()); std::shared_ptr menu = m_menu_factory->buildMenu(Menu::Desktop); InspectAppointments(menu->menu_model(), menu->profile()); } TEST_F(MenuFixture, Locations) { for(auto& menu : m_menus) InspectLocations(menu->menu_model(), menu->profile()); } TEST_F(MenuFixture, Settings) { for(auto& menu : m_menus) InspectSettings(menu->menu_model(), menu->profile()); } ./tests/state-fixture.h0000644000015600001650000000360212701256660015222 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_TESTS_STATE_FIXTURE_H #define INDICATOR_DATETIME_TESTS_STATE_FIXTURE_H #include "test-dbus-fixture.h" #include "actions-mock.h" #include "state-mock.h" namespace unity { namespace indicator { namespace datetime { /*** **** ***/ class StateFixture: public TestDBusFixture { private: typedef TestDBusFixture super; public: virtual ~StateFixture() =default; protected: std::shared_ptr m_mock_state; std::shared_ptr m_state; std::shared_ptr m_mock_actions; std::shared_ptr m_actions; virtual void SetUp() { super::SetUp(); m_mock_state.reset(new MockState); m_state = std::dynamic_pointer_cast(m_mock_state); m_mock_actions.reset(new MockActions(m_state)); m_actions = std::dynamic_pointer_cast(m_mock_actions); } virtual void TearDown() { m_actions.reset(); m_mock_actions.reset(); m_state.reset(); m_mock_state.reset(); super::TearDown(); } }; /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity #endif /* INDICATOR_DATETIME_TESTS_STATE_FIXTURE_H */ ./tests/geoclue-fixture.h0000644000015600001650000001311212701256660015522 0ustar jenkinsjenkins/* * Copyright 2013 Canonical Ltd. * * Authors: * Charles Kerr * * 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . */ #ifndef INDICATOR_DATETIME_TESTS_GEOCLUE_FIXTURE_H #define INDICATOR_DATETIME_TESTS_GEOCLUE_FIXTURE_H #include "glib-fixture.h" #include class GeoclueFixture : public GlibFixture { private: typedef GlibFixture super; GDBusConnection * bus = nullptr; protected: DbusTestService * service = nullptr; DbusTestDbusMock * mock = nullptr; DbusTestDbusMockObject * obj_geo = nullptr; DbusTestDbusMockObject * obj_geo_m = nullptr; DbusTestDbusMockObject * obj_geo_mc = nullptr; DbusTestDbusMockObject * obj_geo_addr = nullptr; const std::string timezone_1 = "America/Denver"; void SetUp () override { super::SetUp(); GError * error = nullptr; const auto master_path = "/org/freedesktop/Geoclue/Master"; const auto client_path = "/org/freedesktop/Geoclue/Master/client0"; GString * gstr = g_string_new (nullptr); service = dbus_test_service_new (nullptr); mock = dbus_test_dbus_mock_new ("org.freedesktop.Geoclue.Master"); auto interface = "org.freedesktop.Geoclue.Master"; obj_geo_m = dbus_test_dbus_mock_get_object (mock, master_path, interface, nullptr); g_string_printf (gstr, "ret = '%s'", client_path); dbus_test_dbus_mock_object_add_method (mock, obj_geo_m, "Create", nullptr, G_VARIANT_TYPE_OBJECT_PATH, gstr->str, &error); interface = "org.freedesktop.Geoclue.MasterClient"; obj_geo_mc = dbus_test_dbus_mock_get_object (mock, client_path, interface, nullptr); dbus_test_dbus_mock_object_add_method (mock, obj_geo_mc, "SetRequirements", G_VARIANT_TYPE("(iibi)"), nullptr, "", &error); dbus_test_dbus_mock_object_add_method (mock, obj_geo_mc, "AddressStart", nullptr, nullptr, "", &error); interface = "org.freedesktop.Geoclue"; obj_geo = dbus_test_dbus_mock_get_object (mock, client_path, interface, nullptr); dbus_test_dbus_mock_object_add_method (mock, obj_geo, "AddReference", nullptr, nullptr, "", &error); g_string_printf (gstr, "ret = (1385238033, {'timezone': '%s'}, (3, 0.0, 0.0))", timezone_1.c_str()); interface = "org.freedesktop.Geoclue.Address"; obj_geo_addr = dbus_test_dbus_mock_get_object (mock, client_path, interface, nullptr); dbus_test_dbus_mock_object_add_method (mock, obj_geo_addr, "GetAddress", nullptr, G_VARIANT_TYPE("(ia{ss}(idd))"), gstr->str, &error); dbus_test_service_add_task(service, DBUS_TEST_TASK(mock)); dbus_test_service_start_tasks(service); bus = g_bus_get_sync (G_BUS_TYPE_SESSION, nullptr, nullptr); g_dbus_connection_set_exit_on_close (bus, FALSE); g_object_add_weak_pointer (G_OBJECT(bus), (gpointer*)&bus); g_string_free (gstr, TRUE); } void TearDown () override { g_clear_object (&mock); g_clear_object (&service); g_object_unref (bus); unsigned int cleartry = 0; while (bus != nullptr && cleartry < 10) { wait_msec (100); cleartry++; } // I've looked and can't find where this extra ref is coming from. // is there an unbalanced ref to the bus in the test harness?! while (bus != nullptr) { g_object_unref (bus); wait_msec (1000); } super::TearDown (); } private: struct EmitAddressChangedData { DbusTestDbusMock * mock = nullptr; DbusTestDbusMockObject * obj_geo_addr = nullptr; std::string timezone; EmitAddressChangedData(DbusTestDbusMock* mock_, DbusTestDbusMockObject* obj_geo_addr_, const std::string& timezone_): mock(mock_), obj_geo_addr(obj_geo_addr_), timezone(timezone_) {} }; static gboolean emit_address_changed_idle (gpointer gdata) { auto data = static_cast(gdata); auto fmt = g_strdup_printf ("(1385238033, {'timezone': '%s'}, (3, 0.0, 0.0))", data->timezone.c_str()); GError * error = nullptr; dbus_test_dbus_mock_object_emit_signal(data->mock, data->obj_geo_addr, //"org.freedesktop.Geoclue.Address", "AddressChanged", G_VARIANT_TYPE("(ia{ss}(idd))"), g_variant_new_parsed (fmt), &error); if (error) { g_warning("%s: %s", G_STRFUNC, error->message); g_error_free (error); } g_free (fmt); delete data; return G_SOURCE_REMOVE; } public: void setGeoclueTimezoneOnIdle (const std::string& newZone) { g_timeout_add (50, emit_address_changed_idle, new EmitAddressChangedData(mock, obj_geo_addr, newZone.c_str())); } }; #endif /* INDICATOR_DATETIME_TESTS_GEOCLUE_FIXTURE_H */ ./tests/test-timezone-geoclue.cpp0000644000015600001650000000305012701256660017176 0ustar jenkinsjenkins/* * Copyright 2013 Canonical Ltd. * * Authors: * Charles Kerr * * 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . */ #include "geoclue-fixture.h" #include using unity::indicator::datetime::GeoclueTimezone; // This test looks small because the interesting // work is all happening in GeoclueFixture... TEST_F(GeoclueFixture, ChangeDetected) { GeoclueTimezone tz; wait_msec(500); // wait for the bus to get set up EXPECT_EQ(timezone_1, tz.timezone.get()); // Start listening for a timezone change, then change the timezone. bool changed = false; auto connection = tz.timezone.changed().connect( [&changed, this](const std::string& s){ g_debug("timezone changed to %s", s.c_str()); changed = true; g_main_loop_quit(loop); }); const std::string timezone_2 = "America/Chicago"; setGeoclueTimezoneOnIdle(timezone_2); g_main_loop_run(loop); EXPECT_EQ(timezone_2, tz.timezone.get()); } ./tests/test-actions.cpp0000644000015600001650000002641612701256660015376 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include "state-fixture.h" using namespace unity::indicator::datetime; class ActionsFixture: public StateFixture { typedef StateFixture super; std::vector build_some_appointments() { const auto now = m_state->clock->localtime(); const auto tomorrow = now.add_days(1); Appointment a1; // an alarm clock appointment a1.color = "red"; a1.summary = "Alarm"; a1.summary = "http://www.example.com/"; a1.uid = "example"; a1.type = Appointment::UBUNTU_ALARM; a1.begin = a1.end = tomorrow; Appointment a2; // a non-alarm appointment a2.color = "green"; a2.summary = "Other Text"; a2.summary = "http://www.monkey.com/"; a2.uid = "monkey"; a1.type = Appointment::EVENT; a2.begin = a2.end = tomorrow; return std::vector({a1, a2}); } protected: void SetUp() override { super::SetUp(); } void TearDown() override { super::TearDown(); } void test_action_with_no_args(const char * action_name, MockActions::Action expected_action) { // preconditions EXPECT_TRUE(m_mock_actions->history().empty()); auto action_group = m_actions->action_group(); EXPECT_TRUE(g_action_group_has_action(action_group, action_name)); // run the test g_action_group_activate_action(action_group, action_name, nullptr); // test the results EXPECT_EQ(std::vector({expected_action}), m_mock_actions->history()); } void test_action_with_time_arg(const char * action_name, MockActions::Action expected_action) { // preconditions EXPECT_TRUE(m_mock_actions->history().empty()); auto action_group = m_actions->action_group(); EXPECT_TRUE(g_action_group_has_action(action_group, action_name)); // activate the action const auto now = DateTime::NowLocal(); auto v = g_variant_new_int64(now.to_unix()); g_action_group_activate_action(action_group, action_name, v); // test the results EXPECT_EQ(std::vector({expected_action}), m_mock_actions->history()); EXPECT_EQ(now.format("%F %T"), m_mock_actions->date_time().format("%F %T")); } void test_action_with_appt_arg(const char * action_name, MockActions::Action expected_action) { /// /// Test 1: activate an appointment that we know about /// // preconditions EXPECT_TRUE(m_mock_actions->history().empty()); auto action_group = m_actions->action_group(); EXPECT_TRUE(g_action_group_has_action(action_group, action_name)); // init some appointments to the state const auto appointments = build_some_appointments(); m_mock_state->mock_range_planner->appointments().set(appointments); // activate the action auto v = g_variant_new("(sx)", appointments[0].uid.c_str(), 0); g_action_group_activate_action(action_group, action_name, v); // test the results EXPECT_EQ(std::vector({expected_action}), m_mock_actions->history()); EXPECT_EQ(appointments[0], m_mock_actions->appointment()); /// /// Test 2: activate an appointment we *don't* know about /// // setup m_mock_actions->clear(); EXPECT_TRUE(m_mock_actions->history().empty()); // activate the action v = g_variant_new("(sx)", "this-uid-is-not-one-that-we-have", 0); g_action_group_activate_action(action_group, action_name, v); // test the results EXPECT_TRUE(m_mock_actions->history().empty()); } }; /*** **** ***/ TEST_F(ActionsFixture, ActionsExist) { EXPECT_TRUE(m_actions != nullptr); const char* names[] = { "desktop-header", "calendar", "set-location", "desktop.open-appointment", "desktop.open-alarm-app", "desktop.open-calendar-app", "desktop.open-settings-app", "phone.open-appointment", "phone.open-alarm-app", "phone.open-calendar-app", "phone.open-settings-app" }; for(const auto& name: names) { EXPECT_TRUE(g_action_group_has_action(m_actions->action_group(), name)); } } /*** **** ***/ TEST_F(ActionsFixture, DesktopOpenAlarmApp) { test_action_with_no_args("desktop.open-alarm-app", MockActions::DesktopOpenAlarmApp); } TEST_F(ActionsFixture, DesktopOpenAppointment) { test_action_with_appt_arg("desktop.open-appointment", MockActions::DesktopOpenAppt); } TEST_F(ActionsFixture, DesktopOpenCalendarApp) { test_action_with_time_arg("desktop.open-calendar-app", MockActions::DesktopOpenCalendarApp); } TEST_F(ActionsFixture, DesktopOpenSettingsApp) { test_action_with_no_args("desktop.open-settings-app", MockActions::DesktopOpenSettingsApp); } /*** **** ***/ TEST_F(ActionsFixture, PhoneOpenAlarmApp) { test_action_with_no_args("phone.open-alarm-app", MockActions::PhoneOpenAlarmApp); } TEST_F(ActionsFixture, PhoneOpenAppointment) { test_action_with_appt_arg("phone.open-appointment", MockActions::PhoneOpenAppt); } TEST_F(ActionsFixture, PhoneOpenCalendarApp) { test_action_with_time_arg("phone.open-calendar-app", MockActions::PhoneOpenCalendarApp); } TEST_F(ActionsFixture, PhoneOpenSettingsApp) { test_action_with_no_args("phone.open-settings-app", MockActions::PhoneOpenSettingsApp); } /*** **** ***/ TEST_F(ActionsFixture, SetLocation) { const auto action_name = "set-location"; auto action_group = m_actions->action_group(); EXPECT_TRUE(m_mock_actions->history().empty()); EXPECT_TRUE(g_action_group_has_action(action_group, action_name)); auto v = g_variant_new_string("America/Chicago Oklahoma City"); g_action_group_activate_action(action_group, action_name, v); const auto expected_action = MockActions::SetLocation; ASSERT_EQ(1, m_mock_actions->history().size()); EXPECT_EQ(expected_action, m_mock_actions->history()[0]); EXPECT_EQ("America/Chicago", m_mock_actions->zone()); EXPECT_EQ("Oklahoma City", m_mock_actions->name()); } TEST_F(ActionsFixture, SetCalendarDate) { // confirm that such an action exists const auto action_name = "calendar"; auto action_group = m_actions->action_group(); EXPECT_TRUE(m_mock_actions->history().empty()); EXPECT_TRUE(g_action_group_has_action(action_group, action_name)); // pick an arbitrary DateTime... auto now = DateTime::Local(2010, 1, 2, 3, 4, 5); // confirm that Planner.time gets changed to that date when we // activate the 'calendar' action with that date's time_t as the arg EXPECT_NE (now, m_state->calendar_month->month().get()); auto v = g_variant_new_int64(now.to_unix()); g_action_group_activate_action (action_group, action_name, v); EXPECT_TRUE(DateTime::is_same_day (now, m_state->calendar_month->month().get())); // DST change in US now = DateTime::Local(2015, 3, 8, 9, 0, 0); v = g_variant_new_int64(now.to_unix()); g_action_group_activate_action (action_group, action_name, v); EXPECT_TRUE(DateTime::is_same_day (now, m_state->calendar_month->month().get())); // DST change in Europe now = DateTime::Local(2015, 3, 29, 9, 0, 0); v = g_variant_new_int64(now.to_unix()); g_action_group_activate_action (action_group, action_name, v); EXPECT_TRUE(DateTime::is_same_day (now, m_state->calendar_month->month().get())); } TEST_F(ActionsFixture, ActivatingTheCalendarResetsItsDate) { // Confirm that the GActions exist auto action_group = m_actions->action_group(); EXPECT_TRUE(g_action_group_has_action(action_group, "calendar")); EXPECT_TRUE(g_action_group_has_action(action_group, "calendar-active")); /// /// Prerequisite for the test: move calendar-date away from today /// // move calendar-date a week into the future... const auto now = m_state->clock->localtime(); const auto next_week = now.add_days(7); const auto next_week_unix = next_week.to_unix(); g_action_group_activate_action (action_group, "calendar", g_variant_new_int64(next_week_unix)); // confirm the planner and calendar action state moved a week into the future // but that m_state->clock is unchanged auto expected = next_week.start_of_day(); const auto expected_unix = expected.to_unix(); EXPECT_EQ(expected_unix, m_state->calendar_month->month().get().to_unix()); EXPECT_EQ(now, m_state->clock->localtime()); auto calendar_state = g_action_group_get_action_state(action_group, "calendar"); EXPECT_TRUE(calendar_state != nullptr); EXPECT_TRUE(g_variant_is_of_type(calendar_state, G_VARIANT_TYPE_DICTIONARY)); auto v = g_variant_lookup_value(calendar_state, "calendar-day", G_VARIANT_TYPE_INT64); EXPECT_TRUE(v != nullptr); EXPECT_EQ(expected_unix, g_variant_get_int64(v)); g_clear_pointer(&v, g_variant_unref); g_clear_pointer(&calendar_state, g_variant_unref); /// /// Now the actual test. /// We set the state of 'calendar-active' to true, which should reset the calendar date. /// This is so the calendar always starts on today's date when the indicator's menu is pulled down. /// // change the state... g_action_group_change_action_state(action_group, "calendar-active", g_variant_new_boolean(true)); // confirm the planner and calendar action state were reset back to m_state->clock's time EXPECT_EQ(now.to_unix(), m_state->calendar_month->month().get().to_unix()); EXPECT_EQ(now, m_state->clock->localtime()); calendar_state = g_action_group_get_action_state(action_group, "calendar"); EXPECT_TRUE(calendar_state != nullptr); EXPECT_TRUE(g_variant_is_of_type(calendar_state, G_VARIANT_TYPE_DICTIONARY)); v = g_variant_lookup_value(calendar_state, "calendar-day", G_VARIANT_TYPE_INT64); EXPECT_TRUE(v != nullptr); EXPECT_EQ(now.to_unix(), g_variant_get_int64(v)); g_clear_pointer(&v, g_variant_unref); g_clear_pointer(&calendar_state, g_variant_unref); } ./tests/manual-test-snap.cpp0000644000015600001650000000611212701256660016141 0ustar jenkinsjenkins /* * Copyright 2013 Canonical Ltd. * * Authors: * Charles Kerr * * 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . */ #include #include #include #include #include #include using namespace unity::indicator::datetime; namespace uin = unity::indicator::notifications; /*** **** ***/ namespace { gboolean quit_idle (gpointer gloop) { g_main_loop_quit(static_cast(gloop)); return G_SOURCE_REMOVE; }; int volume = 50; GOptionEntry entries[] = { { "volume", 'v', 0, G_OPTION_ARG_INT, &volume, "Volume level [1..100]", "volume" }, { nullptr } }; } int main(int argc, const char* argv[]) { GError* error = nullptr; GOptionContext* context = g_option_context_new(nullptr); g_option_context_add_main_entries(context, entries, nullptr); if (!g_option_context_parse(context, &argc, (gchar***)&argv, &error)) { g_print("option parsing failed: %s\n", error->message); exit(1); } g_option_context_free(context); volume = CLAMP(volume, 1, 100); Appointment a; a.color = "green"; a.summary = "Alarm"; a.uid = "D4B57D50247291478ED31DED17FF0A9838DED402"; a.type = Appointment::UBUNTU_ALARM; a.begin = DateTime::Local(2014, 12, 25, 0, 0, 0); a.end = a.begin.end_of_day(); a.alarms.push_back(Alarm{"Alarm Text", "", a.begin}); auto loop = g_main_loop_new(nullptr, false); auto on_snooze = [loop](const Appointment& appt, const Alarm&){ g_message("You clicked 'Snooze' for appt url '%s'", appt.summary.c_str()); g_idle_add(quit_idle, loop); }; auto on_ok = [loop](const Appointment&, const Alarm&){ g_message("You clicked 'OK'"); g_idle_add(quit_idle, loop); }; // only use local, temporary settings g_assert(g_setenv("GSETTINGS_SCHEMA_DIR", SCHEMA_DIR, true)); g_assert(g_setenv("GSETTINGS_BACKEND", "memory", true)); g_debug("SCHEMA_DIR is %s", SCHEMA_DIR); auto settings = std::make_shared(); settings->alarm_volume.set(volume); auto notification_engine = std::make_shared("indicator-datetime-service"); auto sound_builder = std::make_shared(); Snap snap (notification_engine, sound_builder, settings); snap(a, a.alarms.front(), on_snooze, on_ok); g_main_loop_run(loop); g_main_loop_unref(loop); return 0; } ./tests/state-mock.h0000644000015600001650000000340312701256660014464 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_STATE_MOCK_H #define INDICATOR_DATETIME_STATE_MOCK_H #include "planner-mock.h" #include #include namespace unity { namespace indicator { namespace datetime { /*** **** ***/ class MockState: public State { public: std::shared_ptr mock_clock; std::shared_ptr mock_range_planner; MockState() { const DateTime now = DateTime::NowLocal(); mock_clock.reset(new MockClock(now)); clock = std::dynamic_pointer_cast(mock_clock); settings.reset(new Settings); mock_range_planner.reset(new MockRangePlanner); auto range_planner = std::dynamic_pointer_cast(mock_range_planner); calendar_month.reset(new MonthPlanner(range_planner, now)); calendar_upcoming.reset(new UpcomingPlanner(range_planner, now)); locations.reset(new Locations); } }; /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity #endif /* INDICATOR_DATETIME_STATE_MOCK_H */ ./tests/CMakeLists.txt0000644000015600001650000001171112701256660015005 0ustar jenkinsjenkins# build libgtest add_library (gtest STATIC ${GTEST_SOURCE_DIR}/gtest-all.cc ${GTEST_SOURCE_DIR}/gtest_main.cc) set_target_properties (gtest PROPERTIES INCLUDE_DIRECTORIES ${INCLUDE_DIRECTORIES} ${GTEST_INCLUDE_DIR}) set_target_properties (gtest PROPERTIES COMPILE_FLAGS ${COMPILE_FLAGS} -w) SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -g ${CC_WARNING_ARGS}") # dbustest pkg_check_modules(DBUSTEST REQUIRED dbustest-1>=14.04.0) include_directories (SYSTEM ${DBUSTEST_INCLUDE_DIRS}) # build the necessary schemas set_directory_properties (PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES gschemas.compiled) set_source_files_properties (gschemas.compiled GENERATED) # GSettings: # compile the indicator-datetime schema into a gschemas.compiled file in this directory, # and help the tests to find that file by setting -DSCHEMA_DIR set (SCHEMA_DIR ${CMAKE_CURRENT_BINARY_DIR}) add_definitions(-DSCHEMA_DIR="${SCHEMA_DIR}") execute_process (COMMAND ${PKG_CONFIG_EXECUTABLE} gio-2.0 --variable glib_compile_schemas OUTPUT_VARIABLE COMPILE_SCHEMA_EXECUTABLE OUTPUT_STRIP_TRAILING_WHITESPACE) add_custom_command (OUTPUT gschemas.compiled DEPENDS ${CMAKE_BINARY_DIR}/data/com.canonical.indicator.datetime.gschema.xml COMMAND cp -f ${CMAKE_BINARY_DIR}/data/*gschema.xml ${SCHEMA_DIR} COMMAND ${COMPILE_SCHEMA_EXECUTABLE} ${SCHEMA_DIR}) # look for headers in our src dir, and also in the directories where we autogenerate files... include_directories (${CMAKE_SOURCE_DIR}/src) include_directories (${CMAKE_BINARY_DIR}/src) include_directories (${CMAKE_CURRENT_BINARY_DIR}) include_directories (${DBUSTEST_INCLUDE_DIRS}) add_definitions (-DSANDBOX="${CMAKE_CURRENT_BINARY_DIR}") add_definitions (-DG_LOG_DOMAIN="Indicator-Datetime") function(add_test_by_name name) set (TEST_NAME ${name}) add_executable (${TEST_NAME} ${TEST_NAME}.cpp gschemas.compiled) add_test (${TEST_NAME} ${TEST_NAME}) target_link_libraries (${TEST_NAME} indicatordatetimeservice gtest ${DBUSTEST_LIBRARIES} ${SERVICE_DEPS_LIBRARIES} ${GTEST_LIBS}) endfunction() add_test_by_name(test-datetime) add_test_by_name(test-sound) add_test_by_name(test-notification) add_test_by_name(test-actions) add_test_by_name(test-alarm-queue) add_test(NAME dear-reader-the-next-test-takes-60-seconds COMMAND true) add_test_by_name(test-clock) add_test_by_name(test-exporter) add_test_by_name(test-formatter) add_test_by_name(test-live-actions) add_test_by_name(test-locations) add_test_by_name(test-menus) add_test_by_name(test-planner) add_test_by_name(test-settings) add_test_by_name(test-timezone-timedated) add_test_by_name(test-utils) set (TEST_NAME manual-test-snap) add_executable (${TEST_NAME} ${TEST_NAME}.cpp) target_link_libraries (${TEST_NAME} indicatordatetimeservice gtest ${SERVICE_DEPS_LIBRARIES} ${GTEST_LIBS}) ## ## EDS Tests ## find_program(DBUS_RUNNER dbus-test-runner) function(add_eds_ics_test_by_name name) set (TEST_NAME ${name}) configure_file("${CMAKE_CURRENT_SOURCE_DIR}/${TEST_NAME}.ics.in" "${CMAKE_CURRENT_BINARY_DIR}/${TEST_NAME}.ics") add_executable(${TEST_NAME} ${TEST_NAME}.cpp gschemas.compiled) target_link_libraries (${TEST_NAME} indicatordatetimeservice gtest ${DBUSTEST_LIBRARIES} ${SERVICE_DEPS_LIBRARIES} ${GTEST_LIBS}) add_test (${TEST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/run-eds-ics-test.sh ${DBUS_RUNNER} # arg1: dbus-test-runner exec ${CMAKE_CURRENT_BINARY_DIR}/${TEST_NAME} # arg2: test executable path ${TEST_NAME} # arg3: test name ${CMAKE_CURRENT_SOURCE_DIR}/test-eds-ics-config-files # arg4: base directory for config file template ${CMAKE_CURRENT_BINARY_DIR}/${TEST_NAME}.ics) # arg5: the ical file for this test endfunction() add_eds_ics_test_by_name(test-eds-ics-all-day-events) add_eds_ics_test_by_name(test-eds-ics-repeating-events) add_eds_ics_test_by_name(test-eds-ics-nonrepeating-events) add_eds_ics_test_by_name(test-eds-ics-repeating-valarms) add_eds_ics_test_by_name(test-eds-ics-missing-trigger) add_eds_ics_test_by_name(test-eds-ics-tzids) add_eds_ics_test_by_name(test-eds-ics-tzids-2) add_eds_ics_test_by_name(test-eds-ics-tzids-utc) # disabling the timezone unit tests because they require # https://code.launchpad.net/~ted/dbus-test-runner/multi-interface-test/+merge/199724 # which hasn't landed yet. These can be re-enabled as soon as that lands. #function(add_dbusmock_test_by_name name) # set (TEST_NAME ${name}) # add_executable (${TEST_NAME} ${TEST_NAME}.cpp gschemas.compiled) # add_test (${TEST_NAME} ${TEST_NAME}) # target_link_libraries (${TEST_NAME} indicatordatetimeservice gtest ${SERVICE_DEPS_LIBRARIES} ${DBUSTEST_LIBRARIES} ${GTEST_LIBS}) #endfunction() #add_dbusmock_test_by_name(test-timezone-geoclue) #add_dbusmock_test_by_name(test-timezones) ./tests/manual0000644000015600001650000001731112701256660013447 0ustar jenkinsjenkins Test-case indicator-datetime/unity7-items-check
Log in to a Unity 7 user session
Go to the panel and click on the DateTime indicator
Ensure there are items in the menu
Test-case indicator-datetime/unity7-greeter-items-check
Start a system and wait for the greeter or logout of the current user session
Go to the panel and click on the DateTime indicator
Ensure there are items in the menu
Test-case indicator-datetime/unity8-items-check
Login to a user session running Unity 8
Pull down the top panel until it sticks open
Navigate through the tabs until "Time & Date" is shown
Upcoming is at the top of the menu
The menu is populated with items
Test-case indicator-datetime/timestamp-wakeup
Unplug the phone from any USB connection and put it to sleep
Reawaken the device.
The indicator should be showing the correct time.
Test-case indicator-datetime/new-alarm-wakeup
Create and save an upcoming alarm in ubuntu-clock-app
Unplug the phone from any USB connection and put it to sleep
Confirm that the alarm sounds on time even if the phone is asleep. (Note: if in doubt about sleep you can see in the syslog whether the device actually suspended or whether the suspend was aborted)
Confirm that the screen comes on when the alarm is triggered.
If the device supports haptic feedback, confirm the alarm vibrates.
Test-case indicator-datetime/disabled-alarms
Create and save an upcoming alarm in ubuntu-clock-app
Confirm that the alarm icon appears next to the current time in unity's indicator display
Disable the alarm in ubuntu-clock-app
When all alarms are disabled or removed, the alarm icon should disappear.
Re-enable the alarm in ubuntu-clock-app
When the alarm is enabled, the alarm icon should reappear.
Test-case indicator-datetime/disable-one-time-alarms-after-notification
Create and save an upcoming nonrepeating alarm in ubuntu-clock-app
Confirm that the alarm icon appears next to the current time in unity's indicator display
Wait until the alarm time is reached
Confirm that the alarm notification is shown
Confirm that the alarm's sound is played while the alarm notification is present
Confirm that the one-time alarm is disabled after the notification is shown. NOTE: due to a refresh bug in clock-app you may need to refresh its alarms page (by swapping back to the main page, then the alarm page again, this is tracked in #1362341) in order to see the alarm change from enabled to disabled.
Create and save an upcoming repeating alarm in ubuntu-clock-app
Confirm that the alarm icon appears next to the current time in unity's indicator display
Wait until the alarm time is reached
Confirm that the alarm notification is shown
Confirm that the alarm's sound is played while the alarm notification is present
Confirm that the repeating alarm is not disabled after the notification is shown. NOTE: due to a refresh bug in clock-app you may need to refresh its alarms page (by swapping back to the main page, then the alarm page again, this is tracked in #1362341) in order to see the alarm change from enabled to disabled.
Test-case indicator-datetime/calendar-event-notification
In the calendar app, create and save a new upcoming calendar event that will occur in the next few minutes.
The datetime indicator's event list should update itself to show this new event.
Calendar events do not get the alarm icon, so no alarm icon should be shown in the header unless there is also an upcoming alarm set.
Wait for the event's time to be reached
The datetime indicator should pop up a non-interactive notification that plays a nonlooping sound.
The notification should disappear after a moment without requiring user intervention.
Test-case indicator-datetime/alarm-timezone
In ubuntu-system-settings, change your timezone to a zone you're not in
In ubuntu-clock-app, create and save an upcoming alarm
The indicator's menu should show the alarm to click at the specified time
In ubuntu-system-settings, change back to your correct timezone
The indicator's menu should still show the alarm to click at the specified time
Test-case indicator-datetime/snooze
Create and save an upcoming alarm in ubuntu-clock-app
When the alarm goes off, press the 'Snooze' button
The alarm should go away, then reappear N minutes later. By default the N is 5 minutes but will be configurable from ubuntu-clock-app.
When the snoozed alarm reappears, press the 'OK' button
This time when the alarm is dismissed, it should not reappear.
Test-case indicator-datetime/edited-alarm-wakeup
Edit an alarm that's already passed. (see previous test)
Unplug the phone from any USB connection and put it to sleep
Confirm that the alarm sounds on time even if the phone is asleep. (Note: if in doubt about sleep you can see in the syslog whether the device actually suspended or whether the suspend was aborted)
Confirm that the screen comes on when the alarm is triggered.
If the device supports haptic feedback, confirm the alarm vibrates.
Test-case indicator-datetime/tell-snap-decision-to-dismiss
Set an alarm and wait for it to arrive.
Alarm should go off at the specified time
Press the 'Dismiss' button in the alarm's snap decision popup before the sound stops.
Popup should disappear
Sound should stop at the same time, rather than playing til the end of the file.
Test-case indicator-datetime/change-alarm-sound
Open the clock app
Swipe up from the bottom
Click on the + symbol
Save an alarm for a few minutes time leave everything on default settings
Click on save
Click on the alarm
Change the sound of the alarm
Click on save
Let the alarm go off
The newly-selected sound should play, rather than the previous sound.
Test-case indicator-datetime/silent-mode
Set an alarm and wait for it to arrive.
From the sound indicator, turn on silent mode.
Alarm should go off at the specified time and play its sound regardless of silent mode.
From the sound indicator, turn on silent mode.
Create a calendar event from the calendar app and wait for it to arrive.
The calendar event notification should be silent.
From the sound indicator, turn off silent mode.
Create a calendar event from the calendar app and wait for it to arrive.
The calendar event notification should play a sound.
Test-case indicator-datetime/manual-time
In System Settings > Time & Date, manually change the time to an arbitrary time.
The indicator's timestamp should change right after the time manual time is set.
If all actions produce the expected results listed, please submit a 'passed' result. If an action fails, or produces an unexpected result, please submit a 'failed' result and file a bug. Please be sure to include the bug number when you submit your result. ./tests/test-sound.cpp0000644000015600001650000001201212701256660015051 0ustar jenkinsjenkins/* * Copyright 2014-2016 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include #include "notification-fixture.h" using namespace unity::indicator::datetime; namespace uin = unity::indicator::notifications; /*** **** ***/ namespace { static constexpr char const * APP_NAME {"indicator-datetime-service"}; } namespace { gboolean quit_idle (gpointer gloop) { g_main_loop_quit(static_cast(gloop)); return G_SOURCE_REMOVE; }; } /*** **** ***/ TEST_F(NotificationFixture, InteractiveDuration) { static constexpr int duration_minutes = 120; auto settings = std::make_shared(); settings->alarm_duration.set(duration_minutes); auto ne = std::make_shared(APP_NAME); auto sb = std::make_shared(); auto snap = create_snap(ne, sb, settings); make_interactive(); // call the Snap Decision auto func = [this](const Appointment&, const Alarm&){g_idle_add(quit_idle, loop);}; (*snap)(appt, appt.alarms.front(), func, func); // confirm that Notify got called once guint len = 0; GError * error = nullptr; const auto calls = dbus_test_dbus_mock_object_get_method_calls (notify_mock, notify_obj, METHOD_NOTIFY, &len, &error); g_assert_no_error(error); ASSERT_EQ(1, len); // confirm that the app_name passed to Notify was APP_NAME const auto& params = calls[0].params; ASSERT_EQ(8, g_variant_n_children(params)); const char * str = nullptr; g_variant_get_child (params, 0, "&s", &str); ASSERT_STREQ(APP_NAME, str); // confirm that the icon passed to Notify was "alarm-clock" g_variant_get_child (params, 2, "&s", &str); ASSERT_STREQ("reminder", str); // confirm that the hints passed to Notify included a timeout matching duration_minutes int32_t i32; bool b; auto hints = g_variant_get_child_value (params, 6); b = g_variant_lookup (hints, HINT_TIMEOUT, "i", &i32); EXPECT_TRUE(b); const auto duration = std::chrono::minutes(duration_minutes); EXPECT_EQ(std::chrono::duration_cast(duration).count(), i32); g_variant_unref(hints); ne.reset(); } /*** **** ***/ /** * A DefaultSoundBuilder wrapper which remembers the parameters of the last sound created. */ class TestSoundBuilder: public uin::SoundBuilder { public: TestSoundBuilder() =default; ~TestSoundBuilder() =default; virtual std::shared_ptr create(const std::string& role, const std::string& uri, unsigned int volume, bool loop) override { m_role = role; m_uri = uri; m_volume = volume; m_loop = loop; return m_impl.create(role, uri, volume, loop); } const std::string& role() { return m_role; } const std::string& uri() { return m_uri; } unsigned int volume() { return m_volume; } bool loop() { return m_loop; } private: std::string m_role; std::string m_uri; unsigned int m_volume; bool m_loop; uin::DefaultSoundBuilder m_impl; }; std::string path_to_uri(const std::string& path) { auto file = g_file_new_for_path(path.c_str()); auto uri_cstr = g_file_get_uri(file); std::string uri = uri_cstr; g_free(uri_cstr); g_clear_pointer(&file, g_object_unref); return uri; } TEST_F(NotificationFixture,DefaultSounds) { auto settings = std::make_shared(); auto ne = std::make_shared(APP_NAME); auto sb = std::make_shared(); auto func = [this](const Appointment&, const Alarm&){g_idle_add(quit_idle, loop);}; const struct { Appointment appointment; std::string expected_role; std::string expected_uri; } test_cases[] = { { ualarm, "alarm", path_to_uri(ALARM_DEFAULT_SOUND) }, { appt, "alert", path_to_uri(CALENDAR_DEFAULT_SOUND) } }; auto snap = create_snap(ne, sb, settings); for(const auto& test_case : test_cases) { (*snap)(test_case.appointment, test_case.appointment.alarms.front(), func, func); EXPECT_EQ(test_case.expected_uri, sb->uri()); EXPECT_EQ(test_case.expected_role, sb->role()); } } ./tests/test-eds-ics-nonrepeating-events.cpp0000644000015600001650000000631712701256660021254 0ustar jenkinsjenkins/* * Copyright 2015 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include #include #include #include #include "glib-fixture.h" #include "print-to.h" #include "timezone-mock.h" #include "wakeup-timer-mock.h" using namespace unity::indicator::datetime; using VAlarmFixture = GlibFixture; /*** **** ***/ TEST_F(VAlarmFixture, MultipleAppointments) { // start the EDS engine auto engine = std::make_shared(); // we need a consistent timezone for the planner and our local DateTimes constexpr char const * zone_str {"America/Chicago"}; auto tz = std::make_shared(zone_str); auto gtz = g_time_zone_new(zone_str); // make a planner that looks at the first half of 2015 in EDS auto planner = std::make_shared(engine, tz); const DateTime range_begin {gtz, 2015,1, 1, 0, 0, 0.0}; const DateTime range_end {gtz, 2015,6,31,23,59,59.5}; planner->range().set(std::make_pair(range_begin, range_end)); // give EDS a moment to load if (planner->appointments().get().empty()) { g_message("waiting a moment for EDS to load..."); auto on_appointments_changed = [this](const std::vector& appointments){ g_message("ah, they loaded"); if (!appointments.empty()) g_main_loop_quit(loop); }; core::ScopedConnection conn(planner->appointments().changed().connect(on_appointments_changed)); constexpr int max_wait_sec = 10; wait_msec(max_wait_sec * G_TIME_SPAN_MILLISECOND); } // what we expect to get... Appointment expected_appt; expected_appt.uid = "20150520T000726Z-3878-32011-1770-81@ubuntu-phablet"; expected_appt.color = "#becedd"; expected_appt.summary = "Alarm"; std::array expected_alarms = { Alarm({"Alarm", "file://" ALARM_DEFAULT_SOUND, DateTime(gtz,2015,5,20,20,00,0)}) }; // compare it to what we actually loaded... const auto appts = planner->appointments().get(); EXPECT_EQ(expected_alarms.size(), appts.size()); for (size_t i=0, n=expected_alarms.size(); i. * * Authors: * Charles Kerr */ #include #include #include #include #include "test-dbus-fixture.h" #include "timezone-mock.h" /*** **** ***/ using namespace unity::indicator::datetime; class ClockFixture: public TestDBusFixture { private: typedef TestDBusFixture super; }; TEST_F(ClockFixture, MinuteChangedSignalShouldTriggerOncePerMinute) { // start up a live clock auto timezone_ = std::make_shared(); timezone_->timezone.set("America/New_York"); LiveClock clock(timezone_); wait_msec(500); // wait for the bus to set up // count how many times clock.minute_changed() is emitted over the next minute const DateTime now = clock.localtime(); const auto gnow = now.get(); auto gthen = g_date_time_add_minutes(gnow, 1); int count = 0; clock.minute_changed.connect([&count](){count++;}); const auto msec = g_date_time_difference(gthen,gnow) / 1000; wait_msec(msec); EXPECT_EQ(1, count); g_date_time_unref(gthen); } /*** **** ***/ #define TIMEZONE_FILE (SANDBOX"/timezone") TEST_F(ClockFixture, HelloFixture) { auto timezone_ = std::make_shared(); timezone_->timezone.set("America/New_York"); LiveClock clock(timezone_); } TEST_F(ClockFixture, TimezoneChangeTriggersSkew) { auto timezone_ = std::make_shared(); timezone_->timezone.set("America/New_York"); LiveClock clock(timezone_); auto tz_nyc = g_time_zone_new("America/New_York"); auto now_nyc = g_date_time_new_now(tz_nyc); auto now = clock.localtime(); EXPECT_EQ(g_date_time_get_utc_offset(now_nyc), g_date_time_get_utc_offset(now.get())); EXPECT_LE(abs(g_date_time_difference(now_nyc,now.get())), G_USEC_PER_SEC); g_date_time_unref(now_nyc); g_time_zone_unref(tz_nyc); /// change the timezones! clock.minute_changed.connect([this](){ g_main_loop_quit(loop); }); g_idle_add([](gpointer gs){ static_cast(gs)->timezone.set("America/Los_Angeles"); return G_SOURCE_REMOVE; }, timezone_.get()); g_main_loop_run(loop); auto tz_la = g_time_zone_new("America/Los_Angeles"); auto now_la = g_date_time_new_now(tz_la); now = clock.localtime(); EXPECT_EQ(g_date_time_get_utc_offset(now_la), g_date_time_get_utc_offset(now.get())); EXPECT_LE(abs(g_date_time_difference(now_la,now.get())), G_USEC_PER_SEC); g_date_time_unref(now_la); g_time_zone_unref(tz_la); } /*** **** ***/ namespace { void on_login1_name_acquired(GDBusConnection * connection, const gchar * /*name*/, gpointer /*user_data*/) { g_dbus_connection_emit_signal(connection, nullptr, "/org/freedesktop/login1", // object path "org.freedesktop.login1.Manager", // interface "PrepareForSleep", // signal name g_variant_new("(b)", FALSE), nullptr); } } /** * Confirm that a "PrepareForSleep" event wil trigger a skew event */ TEST_F(ClockFixture, SleepTriggersSkew) { auto timezone_ = std::make_shared(); timezone_->timezone.set("America/New_York"); LiveClock clock(timezone_); wait_msec(250); // wait for the bus to set up bool skewed = false; clock.minute_changed.connect([&skewed, this](){ skewed = true; g_main_loop_quit(loop); return G_SOURCE_REMOVE; }); auto name_tag = g_bus_own_name(G_BUS_TYPE_SYSTEM, "org.freedesktop.login1", G_BUS_NAME_OWNER_FLAGS_NONE, nullptr /* bus acquired */, on_login1_name_acquired, nullptr /* name lost */, nullptr /* user_data */, nullptr /* user_data closure */); g_main_loop_run(loop); EXPECT_TRUE(skewed); g_bus_unown_name(name_tag); } namespace { void on_powerd_name_acquired(GDBusConnection * /*connection*/, const gchar * /*name*/, gpointer is_owned) { *static_cast(is_owned) = true; } } /** * Confirm that powerd's SysPowerStateChange triggers * a timestamp change */ TEST_F(ClockFixture, SysPowerStateChange) { // set up the mock clock bool minute_changed = false; auto clock = std::make_shared(DateTime::NowLocal()); clock->minute_changed.connect([&minute_changed]() { minute_changed = true; }); // control test -- minute_changed shouldn't get triggered // when the clock is silently changed gboolean is_owned = false; auto tag = g_bus_own_name_on_connection(system_bus, BUS_POWERD_NAME, G_BUS_NAME_OWNER_FLAGS_NONE, on_powerd_name_acquired, nullptr, &is_owned /* user_data */, nullptr /* user_data closure */); const DateTime not_now {DateTime::Local(1999, 12, 31, 23, 59, 59)}; clock->set_localtime_quietly(not_now); wait_msec(); ASSERT_TRUE(is_owned); ASSERT_FALSE(minute_changed); // now for the actual test, // confirm that SysPowerStateChange triggers a minute_changed() signal GError * error = nullptr; auto emitted = g_dbus_connection_emit_signal(system_bus, nullptr, BUS_POWERD_PATH, BUS_POWERD_INTERFACE, "SysPowerStateChange", g_variant_new("(i)", 1), &error); wait_msec(); EXPECT_TRUE(emitted); EXPECT_EQ(nullptr, error); EXPECT_TRUE(minute_changed); // cleanup g_bus_unown_name(tag); } ./include/0000755000015600001650000000000012701256660012525 5ustar jenkinsjenkins./include/datetime/0000755000015600001650000000000012701256671014323 5ustar jenkinsjenkins./include/datetime/actions-live.h0000644000015600001650000000403412701256671017072 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_ACTIONS_LIVE_H #define INDICATOR_DATETIME_ACTIONS_LIVE_H #include namespace unity { namespace indicator { namespace datetime { /** * \brief Production implementation of the Actions interface. * * Delegates URLs, sets the timezone via org.freedesktop.timedate1, etc. * * @see MockActions */ class LiveActions: public Actions { public: explicit LiveActions(const std::shared_ptr& state_in); virtual ~LiveActions() =default; bool desktop_has_calendar_app() const override; void desktop_open_alarm_app() override; void desktop_open_appointment(const Appointment&, const DateTime&) override; void desktop_open_calendar_app(const DateTime&) override; void desktop_open_settings_app() override; void phone_open_alarm_app() override; void phone_open_appointment(const Appointment&, const DateTime &) override; void phone_open_calendar_app(const DateTime&) override; void phone_open_settings_app() override; void set_location(const std::string& zone, const std::string& name) override; protected: static bool is_unity(); virtual void execute_command(const std::string& command); virtual void dispatch_url(const std::string& url); }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_ACTIONS_H ./include/datetime/timezones-live.h0000644000015600001650000000310412701256660017442 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_LIVE_TIMEZONES_H #define INDICATOR_DATETIME_LIVE_TIMEZONES_H #include #include #include #include #include // shared_ptr<> namespace unity { namespace indicator { namespace datetime { /** * \brief #Timezones object that uses a #TimedatedTimezone and #GeoclueTimezone * to detect what timezone we're in */ class LiveTimezones: public Timezones { public: LiveTimezones(const std::shared_ptr& settings); private: void update_geolocation(); void update_timezones(); TimedatedTimezone m_file; std::shared_ptr m_settings; std::shared_ptr m_geo; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_LIVE_TIMEZONES_H ./include/datetime/wakeup-timer-mainloop.h0000644000015600001650000000316612701256660020726 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_WAKEUP_TIMER_MAINLOOP_H #define INDICATOR_DATETIME_WAKEUP_TIMER_MAINLOOP_H #include #include #include // std::unique_ptr, std::shared_ptr namespace unity { namespace indicator { namespace datetime { /*** **** ***/ /** * \brief a WakeupTimer implemented with g_timeout_add() */ class MainloopWakeupTimer: public WakeupTimer { public: explicit MainloopWakeupTimer(const std::shared_ptr&); ~MainloopWakeupTimer(); void set_wakeup_time (const DateTime&) override; core::Signal<>& timeout() override; private: MainloopWakeupTimer(const MainloopWakeupTimer&) =delete; MainloopWakeupTimer& operator= (const MainloopWakeupTimer&) =delete; class Impl; std::unique_ptr p; }; /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_WAKEUP_TIMER_MAINLOOP_H ./include/datetime/wakeup-timer.h0000644000015600001650000000250012701256660017101 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_WAKEUP_TIMER_H #define INDICATOR_DATETIME_WAKEUP_TIMER_H #include #include namespace unity { namespace indicator { namespace datetime { /*** **** ***/ /** * \brief A one-shot timer that emits a signal when its timeout is reached. */ class WakeupTimer { public: WakeupTimer() =default; virtual ~WakeupTimer() =default; virtual void set_wakeup_time (const DateTime&) =0; virtual core::Signal<>& timeout() =0; }; /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_WAKEUP_TIMER_H ./include/datetime/exporter.h0000644000015600001650000000312612701256660016344 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_EXPORTER_H #define INDICATOR_DATETIME_EXPORTER_H #include #include #include #include #include // std::shared_ptr #include namespace unity { namespace indicator { namespace datetime { /** * \brief Exports actions and menus to DBus. */ class Exporter { public: explicit Exporter(const std::shared_ptr&); ~Exporter(); core::Signal<>& name_lost(); void publish(const std::shared_ptr& actions, const std::vector>& menus); private: class Impl; std::unique_ptr p; // disable copying Exporter(const Exporter&) =delete; Exporter& operator=(const Exporter&) =delete; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_EXPORTER_H ./include/datetime/planner-month.h0000644000015600001650000000307412701256660017260 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_PLANNER_MONTH_H #define INDICATOR_DATETIME_PLANNER_MONTH_H #include #include #include #include // std::shared_ptr namespace unity { namespace indicator { namespace datetime { /** * \brief A #Planner that contains appointments for a specified calendar month */ class MonthPlanner: public Planner { public: MonthPlanner(const std::shared_ptr& range_planner, const DateTime& month_in); ~MonthPlanner() =default; core::Property>& appointments(); core::Property& month(); private: std::shared_ptr m_range_planner; core::Property m_month; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_PLANNER_MONTH_H ./include/datetime/timezone-geoclue.h0000644000015600001650000000264612701256660017755 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_GEOCLUE_TIMEZONE_H #define INDICATOR_DATETIME_GEOCLUE_TIMEZONE_H #include // base class namespace unity { namespace indicator { namespace datetime { /** * \brief A #Timezone that gets its information from asking GeoClue */ class GeoclueTimezone: public Timezone { public: GeoclueTimezone(); ~GeoclueTimezone(); private: struct Impl; std::unique_ptr impl; // we've got pointers in here, so don't allow copying GeoclueTimezone(const GeoclueTimezone&) =delete; GeoclueTimezone& operator=(const GeoclueTimezone&) =delete; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_GEOCLUE_TIMEZONE_H ./include/datetime/settings-live.h0000644000015600001650000000450612701256660017274 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_SETTINGS_LIVE_H #define INDICATOR_DATETIME_SETTINGS_LIVE_H #include // parent class #include // GSettings namespace unity { namespace indicator { namespace datetime { /** * \brief #Settings implementation which uses GSettings. */ class LiveSettings: public Settings { public: LiveSettings(); virtual ~LiveSettings(); private: static void on_changed_ccid(GSettings*, gchar*, gpointer); static void on_changed_cunh(GSettings*, gchar*, gpointer); void update_key_ccid(const std::string& key); void update_key_cunh(const std::string& key); void update_custom_time_format(); void update_locations(); void update_show_calendar(); void update_show_clock(); void update_show_date(); void update_show_day(); void update_show_detected_locations(); void update_show_events(); void update_show_locations(); void update_show_seconds(); void update_show_week_numbers(); void update_show_year(); void update_time_format_mode(); void update_timezone_name(); void update_calendar_sound(); void update_alarm_sound(); void update_alarm_volume(); void update_alarm_duration(); void update_alarm_haptic(); void update_snooze_duration(); void update_muted_apps(); GSettings* m_settings; GSettings* m_settings_cunh; // we've got a raw pointer here, so disable copying LiveSettings(const LiveSettings&) =delete; LiveSettings& operator=(const LiveSettings&) =delete; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_SETTINGS_LIVE_H ./include/datetime/clock-mock.h0000644000015600001650000000327612701256660016524 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_CLOCK_MOCK_H #define INDICATOR_DATETIME_CLOCK_MOCK_H #include namespace unity { namespace indicator { namespace datetime { /*** **** ***/ /** * \brief A clock that uses a client-provided time instead of the system time. */ class MockClock: public Clock { public: explicit MockClock(const DateTime& dt): m_localtime(dt) {} ~MockClock() =default; DateTime localtime() const override { return m_localtime; } void set_localtime(const DateTime& dt) { const auto old = m_localtime; set_localtime_quietly(dt); if (!DateTime::is_same_minute(old, m_localtime)) minute_changed(); if (!DateTime::is_same_day(old, m_localtime)) date_changed(); } void set_localtime_quietly(const DateTime& dt) { m_localtime = dt; } private: DateTime m_localtime; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_CLOCK_MOCK_H ./include/datetime/locations.h0000644000015600001650000000360212701256660016466 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_LOCATIONS_H #define INDICATOR_DATETIME_LOCATIONS_H #include #include #include #include namespace unity { namespace indicator { namespace datetime { /** * \brief A physical place and its timezone; eg, "America/Chicago" + "Oklahoma City" * * @see Locations */ class Location { public: Location (const std::string& zone, const std::string& name); const std::string& zone() const; const std::string& name() const; bool operator== (const Location& that) const; private: /** timezone; eg, "America/Chicago" */ std::string m_zone; /* human-readable location name; eg, "Oklahoma City" */ std::string m_name; /** offset from UTC in microseconds */ int64_t m_offset = 0; }; /** * Container which holds an ordered list of Locations * * @see Location * @see State */ class Locations { public: Locations() =default; virtual ~Locations() =default; /** \brief an ordered list of Location items */ core::Property> locations; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_LOCATIONS_H ./include/datetime/appointment.h0000644000015600001650000000340212701256660017027 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_APPOINTMENT_H #define INDICATOR_DATETIME_APPOINTMENT_H #include #include #include namespace unity { namespace indicator { namespace datetime { /** * \brief Basic information required to raise a notification about some Appointment. */ struct Alarm { std::string text; std::string audio_url; DateTime time; bool operator== (const Alarm& that) const; }; /** * \brief An instance of an appointment; e.g. a calendar event or clock-app alarm * * @see Planner */ struct Appointment { public: enum Type { EVENT, UBUNTU_ALARM }; Type type = EVENT; bool is_ubuntu_alarm() const { return type == UBUNTU_ALARM; } std::string uid; std::string source_uid; std::string color; std::string summary; std::string activation_url; DateTime begin; DateTime end; std::vector alarms; bool operator== (const Appointment& that) const; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_APPOINTMENT_H ./include/datetime/clock.h0000644000015600001650000000424212701256660015567 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_CLOCK_H #define INDICATOR_DATETIME_CLOCK_H #include #include #include #include // std::shared_ptr, std::unique_ptr namespace unity { namespace indicator { namespace datetime { /** * \brief A clock. */ class Clock { public: virtual ~Clock(); virtual DateTime localtime() const =0; /** \brief A signal which fires when the clock's minute changes */ core::Signal<> minute_changed; /** \brief A signal which fires when the clock's date changes */ core::Signal<> date_changed; protected: Clock(); /** \brief Compares old and new times, emits minute_changed() or date_changed() signals if appropriate */ void maybe_emit (const DateTime& a, const DateTime& b); private: class Impl; friend class Impl; std::unique_ptr m_impl; // we've got raw pointers and GSignal tags in here, so disable copying Clock(const Clock&) =delete; Clock& operator=(const Clock&) =delete; }; /*** **** ***/ class Timezone; /** * \brief A live #Clock that provides the actual system time. */ class LiveClock: public Clock { public: LiveClock (const std::shared_ptr& zones); virtual ~LiveClock(); virtual DateTime localtime() const override; private: class Impl; std::unique_ptr p; }; /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_CLOCK_H ./include/datetime/planner-snooze.h0000644000015600001650000000276612701256660017457 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_PLANNER_SNOOZE_H #define INDICATOR_DATETIME_PLANNER_SNOOZE_H #include #include #include #include namespace unity { namespace indicator { namespace datetime { /** * A planner to hold 'Snooze' copies of other appointments */ class SnoozePlanner: public Planner { public: SnoozePlanner(const std::shared_ptr&, const std::shared_ptr&); ~SnoozePlanner(); core::Property>& appointments() override; void add(const Appointment&, const Alarm&); protected: class Impl; friend class Impl; std::unique_ptr impl; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_PLANNER_H ./include/datetime/engine-mock.h0000644000015600001650000000331012701256660016663 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_ENGINE_MOCK_H #define INDICATOR_DATETIME_ENGINE_MOCK_H #include namespace unity { namespace indicator { namespace datetime { /**** ***** ****/ /** * A no-op #Engine * * @see Engine */ class MockEngine: public Engine { public: MockEngine() =default; ~MockEngine() =default; void get_appointments(const DateTime& /*begin*/, const DateTime& /*end*/, const Timezone& /*default_timezone*/, std::function&)> appointment_func) override { appointment_func(m_appointments); } core::Signal<>& changed() override { return m_changed; } void disable_ubuntu_alarm(const Appointment&) override { } private: core::Signal<> m_changed; std::vector m_appointments; }; /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_ENGINE_MOCK_H ./include/datetime/state.h0000644000015600001650000000474212701256660015621 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_STATE_H #define INDICATOR_DATETIME_STATE_H #include #include #include #include #include #include #include #include // std::shared_ptr namespace unity { namespace indicator { namespace datetime { /** * \brief Aggregates all the classes that represent the backend state. * * This is where the app comes together. It's a model that aggregates * all of the backend appointments/alarms, locations, timezones, * system time, and so on. The "view" code (ie, the Menus) need to * respond to Signals from the State and update themselves accordingly. * * @see Menu * @see MenuFactory * @see Timezones * @see Clock * @see Planner * @see Locations * @see Settings */ struct State { /** \brief The current time. Used by the header, by the date menuitem, and by the locations for relative timestamp */ std::shared_ptr clock; /** \brief The locations to be displayed in the Locations section of the #Menu */ std::shared_ptr locations; /** \brief Appointments in the month that's being displayed in the calendar section of the #Menu */ std::shared_ptr calendar_month; /** \brief The next appointments that follow highlighed date highlighted in the calendar section of the #Menu (default date = today) */ std::shared_ptr calendar_upcoming; /** \brief Configuration options that modify the view */ std::shared_ptr settings; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_STATE_H ./include/datetime/wakeup-timer-powerd.h0000644000015600001650000000314212701256660020402 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_WAKEUP_TIMER_POWERD_H #define INDICATOR_DATETIME_WAKEUP_TIMER_POWERD_H #include #include #include // std::unique_ptr, std::shared_ptr namespace unity { namespace indicator { namespace datetime { /*** **** ***/ /** * \brief a WakeupTimer implemented with g_timeout_add() */ class PowerdWakeupTimer: public WakeupTimer { public: explicit PowerdWakeupTimer(const std::shared_ptr&); ~PowerdWakeupTimer(); void set_wakeup_time(const DateTime&) override; core::Signal<>& timeout() override; private: PowerdWakeupTimer(const PowerdWakeupTimer&) =delete; PowerdWakeupTimer& operator=(const PowerdWakeupTimer&) =delete; class Impl; std::unique_ptr p; }; /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_WAKEUP_TIMER_MAINLOOP_H ./include/datetime/planner.h0000644000015600001650000000245712701256660016141 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_PLANNER_H #define INDICATOR_DATETIME_PLANNER_H #include #include #include #include namespace unity { namespace indicator { namespace datetime { /** * \brief Simple collection of appointments */ class Planner { public: virtual ~Planner(); virtual core::Property>& appointments() =0; protected: Planner(); static void sort(std::vector&); }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_PLANNER_H ./include/datetime/utils.h0000644000015600001650000000416612701256660015641 0ustar jenkinsjenkins/* * Copyright 2010, 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Michael Terry * Charles Kerr */ #ifndef INDICATOR_DATETIME_UTILS_H #define INDICATOR_DATETIME_UTILS_H #include #include /* GSettings */ G_BEGIN_DECLS /** \brief Returns true if the current locale prefers 12h display instead of 24h */ gboolean is_locale_12h (void); void split_settings_location (const char * location, char ** zone, char ** name); gchar * get_timezone_name (const char * timezone, GSettings * settings); gchar * get_beautified_timezone_name (const char * timezone, const char * saved_location); gchar * generate_full_format_string_at_time (GDateTime * now, GDateTime * then_begin, GDateTime * then_end); /** \brief Translate the string based on LC_TIME instead of LC_MESSAGES. The intent of this is to let users set LC_TIME to override their other locale settings when generating time format string */ const char* T_ (const char * msg); G_END_DECLS #endif /* INDICATOR_DATETIME_UTILS_H */ ./include/datetime/formatter.h0000644000015600001650000001004212701256660016472 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_FORMATTER_H #define INDICATOR_DATETIME_FORMATTER_H #include #include #include #include #include // is_locale_12h() #include #include #include namespace unity { namespace indicator { namespace datetime { class Clock; class DateTime; /*** **** ***/ /** * \brief Provide the strftime() format strings * * This is a simple goal, but getting there has a lot of options and edge cases: * * - The default time format can change based on the locale. * * - The user's settings can change or completely override the format string. * * - The time formats are different on the Phone and Desktop profiles. * * - The time format string in the Locations' menuitems uses (mostly) * the same time format as the header, except for some changes. * * - The 'current time' format string in the Locations' menuitems also * prepends the string 'Yesterday' or 'Today' if it differs from the * local time, so Formatter needs to have a Clock for its state. * * So the Formatter monitors system settings, the current timezone, etc. * and upate its time format properties appropriately. */ class Formatter { public: /** \brief The time format string for the menu header */ core::Property header_format; /** \brief The time string for the menu header. (eg, the header_format + the clock's time */ core::Property header; /** \brief Signal to denote when the relativeFormat has changed. When this is emitted, clients will want to rebuild their menuitems that contain relative time strings (ie, the Appointments and Locations menuitems) */ core::Signal<> relative_format_changed; /** \brief Generate a relative time format for some time (or time range) from the current clock's value. For example, a full-day interval starting at the end of the current clock's day yields "Tomorrow" */ std::string relative_format(GDateTime* then, GDateTime* then_end=nullptr) const; protected: explicit Formatter(const std::shared_ptr&); virtual ~Formatter(); static const char* default_header_time_format(bool twelvehour, bool show_seconds); private: Formatter(const Formatter&) =delete; Formatter& operator=(const Formatter&) =delete; class Impl; std::unique_ptr p; }; /** * \brief A Formatter for the Desktop and DesktopGreeter profiles. */ class DesktopFormatter: public Formatter { public: DesktopFormatter(const std::shared_ptr&, const std::shared_ptr&); private: std::shared_ptr m_settings; void rebuildHeaderFormat(); const gchar* getFullTimeFormatString() const; std::string getHeaderLabelFormatString() const; const gchar* getDateFormat(bool show_day, bool show_date, bool show_year) const; }; /** * \brief A Formatter for Phone and PhoneGreeter profiles. */ class PhoneFormatter: public Formatter { public: explicit PhoneFormatter(const std::shared_ptr& clock): Formatter(clock) { header_format.set(default_header_time_format(is_locale_12h(), false)); } }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_CLOCK_H ./include/datetime/timezone.h0000644000015600001650000000223012701256660016321 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_TIMEZONE_H #define INDICATOR_DATETIME_TIMEZONE_H #include #include namespace unity { namespace indicator { namespace datetime { /** \brief Base a timezone, such as "America/Chicago". */ class Timezone { protected: Timezone() =default; public: core::Property timezone; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_TIMEZONE_H ./include/datetime/date-time.h0000644000015600001650000000561512701256660016352 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_DATETIME_H #define INDICATOR_DATETIME_DATETIME_H #include // GDateTime #include #include // time_t #include // std::shared_ptr namespace unity { namespace indicator { namespace datetime { /** * \brief A simple C++ wrapper for GDateTime to simplify ownership/refcounts */ class DateTime { public: static DateTime NowLocal(); static DateTime Local(time_t); static DateTime Local(int year, int month, int day, int hour, int minute, double seconds); DateTime(); DateTime(GTimeZone* tz, time_t t); DateTime(GTimeZone* tz, GDateTime* dt); DateTime(GTimeZone* tz, int year, int month, int day, int hour, int minute, double seconds); DateTime& operator=(const DateTime& in); DateTime& operator+=(const std::chrono::minutes&); DateTime& operator+=(const std::chrono::seconds&); DateTime to_timezone(const std::string& zone) const; DateTime start_of_month() const; DateTime start_of_day() const; DateTime start_of_minute() const; DateTime end_of_day() const; DateTime end_of_month() const; DateTime add_days(int days) const; DateTime add_full(int year, int month, int day, int hour, int minute, double seconds) const; GDateTime* get() const; GDateTime* operator()() const {return get();} std::string format(const std::string& fmt) const; void ymd(int& year, int& month, int& day) const; int day_of_month() const; int hour() const; int minute() const; double seconds() const; int64_t to_unix() const; bool operator<(const DateTime& that) const; bool operator<=(const DateTime& that) const; bool operator!=(const DateTime& that) const; bool operator==(const DateTime& that) const; int64_t operator- (const DateTime& that) const; static bool is_same_day(const DateTime& a, const DateTime& b); static bool is_same_minute(const DateTime& a, const DateTime& b); bool is_set() const { return m_tz && m_dt; } private: void reset(GTimeZone*, GDateTime*); std::shared_ptr m_tz; std::shared_ptr m_dt; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_DATETIME_H ./include/datetime/alarm-queue-simple.h0000644000015600001650000000314312701256660020200 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_ALARM_QUEUE_SIMPLE_H #define INDICATOR_DATETIME_ALARM_QUEUE_SIMPLE_H #include // std::shared_ptr #include #include #include #include namespace unity { namespace indicator { namespace datetime { /** * \brief A #AlarmQueue implementation */ class SimpleAlarmQueue: public AlarmQueue { public: SimpleAlarmQueue(const std::shared_ptr& clock, const std::shared_ptr& upcoming_planner, const std::shared_ptr& timer); ~SimpleAlarmQueue(); core::Signal& alarm_reached() override; private: class Impl; friend class Impl; std::unique_ptr impl; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_ALARM_QUEUE_H ./include/datetime/timezones.h0000644000015600001650000000273712701256660016520 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_TIMEZONES_H #define INDICATOR_DATETIME_TIMEZONES_H #include #include namespace unity { namespace indicator { namespace datetime { /** * \brief Helper class which aggregates one or more timezones * * @see LiveClock * @see SettingsLocations */ class Timezones { public: Timezones() =default; virtual ~Timezones() =default; /** * \brief the current timezone */ core::Property timezone; /** * \brief all the detected timezones. * The count is >1 iff the detection mechamisms disagree. */ core::Property > timezones; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_TIMEZONES_H ./include/datetime/snap.h0000644000015600001650000000340112701256660015431 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_SNAP_H #define INDICATOR_DATETIME_SNAP_H #include #include #include #include #include #include namespace unity { namespace indicator { namespace datetime { /** * \brief Pops up Snap Decisions for appointments */ class Snap { public: Snap(const std::shared_ptr& engine, const std::shared_ptr& sound_builder, const std::shared_ptr& settings); virtual ~Snap(); typedef std::function appointment_func; void operator()(const Appointment& appointment, const Alarm& alarm, appointment_func snooze, appointment_func ok); private: class Impl; std::unique_ptr impl; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_SNAP_H ./include/datetime/planner-aggregate.h0000644000015600001650000000254312701256660020061 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_PLANNER_AGGREGATE_H #define INDICATOR_DATETIME_PLANNER_AGGREGATE_H #include #include namespace unity { namespace indicator { namespace datetime { /** * \brief Aggregates one or more Planners */ class AggregatePlanner: public Planner { public: AggregatePlanner(); virtual ~AggregatePlanner(); void add(const std::shared_ptr&); core::Property>& appointments() override; protected: class Impl; std::unique_ptr impl; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_PLANNER_AGGREGATE_H ./include/datetime/planner-upcoming.h0000644000015600001650000000311512701256660017750 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_PLANNER_UPCOMING_H #define INDICATOR_DATETIME_PLANNER_UPCOMING_H #include #include #include #include // std::shared_ptr namespace unity { namespace indicator { namespace datetime { /** * \brief A collection of upcoming appointments starting from the specified date */ class UpcomingPlanner: public Planner { public: UpcomingPlanner(const std::shared_ptr& range_planner, const DateTime& date); ~UpcomingPlanner() =default; core::Property>& appointments(); core::Property& date(); private: std::shared_ptr m_range_planner; core::Property m_date; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_PLANNER_UPCOMING_H ./include/datetime/locations-settings.h0000644000015600001650000000323412701256660020325 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_SETTINGS_LOCATIONS_H #define INDICATOR_DATETIME_SETTINGS_LOCATIONS_H #include // base class #include #include namespace unity { namespace indicator { namespace datetime { /** * \brief #Locations implementation which builds its list from the #Settings. */ class SettingsLocations: public Locations { public: /** * @param[in] settings the #Settings whose locations property is to be used * @param[in] timezones the #Timezones to always show first in the list */ SettingsLocations (const std::shared_ptr& settings, const std::shared_ptr& timezones); private: std::shared_ptr m_settings; std::shared_ptr m_timezones; void reload(); }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_SETTINGS_LOCATIONS_H ./include/datetime/planner-range.h0000644000015600001650000000450412701256660017226 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_PLANNER_RANGE_H #define INDICATOR_DATETIME_PLANNER_RANGE_H #include #include #include namespace unity { namespace indicator { namespace datetime { /** * \brief A #Planner that contains appointments in a specified date range * * @see Planner */ class RangePlanner: public Planner { public: virtual ~RangePlanner() =default; virtual core::Property>& range() =0; protected: RangePlanner() =default; }; /** * \brief A #RangePlanner that uses an #Engine to generate appointments * * @see Planner */ class SimpleRangePlanner: public RangePlanner { public: SimpleRangePlanner(const std::shared_ptr& engine, const std::shared_ptr& timezone); virtual ~SimpleRangePlanner(); core::Property>& appointments(); core::Property>& range(); private: // rebuild scaffolding void rebuild_soon(); virtual void rebuild_now(); static gboolean rebuild_now_static(gpointer); guint m_rebuild_tag = 0; std::shared_ptr m_engine; std::shared_ptr m_timezone; core::Property> m_range; core::Property> m_appointments; // we've got a GSignal tag here, so disable copying explicit SimpleRangePlanner(const RangePlanner&) =delete; SimpleRangePlanner& operator=(const RangePlanner&) =delete; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_PLANNER_RANGE_H ./include/datetime/alarm-queue.h0000644000015600001650000000257312701256660016717 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_ALARM_QUEUE_H #define INDICATOR_DATETIME_ALARM_QUEUE_H #include #include #include #include #include namespace unity { namespace indicator { namespace datetime { /*** **** ***/ /** * \brief Watches the clock and appointments to notify when an * appointment's time is reached. */ class AlarmQueue { public: AlarmQueue() =default; virtual ~AlarmQueue() =default; virtual core::Signal& alarm_reached() =0; }; /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_ALARM_QUEUE_H ./include/datetime/engine-eds.h0000644000015600001650000000360612701256660016515 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_ENGINE_EDS_H #define INDICATOR_DATETIME_ENGINE_EDS_H #include #include #include #include #include #include namespace unity { namespace indicator { namespace datetime { /**** ***** ****/ /** * Class wrapper around EDS so multiple #EdsPlanners can share resources * * @see EdsPlanner */ class EdsEngine: public Engine { public: EdsEngine(); ~EdsEngine(); void get_appointments(const DateTime& begin, const DateTime& end, const Timezone& default_timezone, std::function&)> appointment_func) override; void disable_ubuntu_alarm(const Appointment&) override; core::Signal<>& changed() override; private: class Impl; std::unique_ptr p; // we've got a unique_ptr here, disable copying... EdsEngine(const EdsEngine&) =delete; EdsEngine& operator=(const EdsEngine&) =delete; }; /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_ENGINE_EDS_H ./include/datetime/CMakeLists.txt0000644000015600001650000000000212701256660017051 0ustar jenkinsjenkins ./include/datetime/menu.h0000644000015600001650000000423712701256660015444 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_MENU_H #define INDICATOR_DATETIME_MENU_H #include #include #include // std::shared_ptr #include #include // GMenuModel namespace unity { namespace indicator { namespace datetime { /** * \brief A menu for a specific profile; eg, Desktop or Phone. * * @see MenuFactory * @see Exporter */ class Menu { public: enum Profile { Desktop, DesktopGreeter, Phone, PhoneGreeter, NUM_PROFILES }; enum Section { Calendar, Appointments, Locations, Settings, NUM_SECTIONS }; const std::string& name() const; Profile profile() const; GMenuModel* menu_model(); protected: Menu (Profile profile_in, const std::string& name_in); virtual ~Menu() =default; GMenu* m_menu = nullptr; private: const Profile m_profile; const std::string m_name; // we've got raw pointers in here, so disable copying Menu(const Menu&) =delete; Menu& operator=(const Menu&) =delete; }; /** * \brief Builds a Menu for a given state and profile * * @see Menu * @see Exporter */ class MenuFactory { public: MenuFactory (const std::shared_ptr& actions, const std::shared_ptr& state); std::shared_ptr buildMenu(Menu::Profile profile); private: std::shared_ptr m_actions; std::shared_ptr m_state; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_MENU_H ./include/datetime/actions.h0000644000015600001650000000473512701256660016143 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_ACTIONS_H #define INDICATOR_DATETIME_ACTIONS_H #include #include #include // shared_ptr #include #include // GSimpleActionGroup namespace unity { namespace indicator { namespace datetime { /** * \brief Interface for all the actions that can be activated by users. * * This is a simple C++ wrapper around our GActionGroup that gets exported * onto the bus. Subclasses implement the actual code that should be run * when a particular action is triggered. */ class Actions { public: virtual bool desktop_has_calendar_app() const =0; virtual void desktop_open_alarm_app() =0; virtual void desktop_open_appointment(const Appointment&, const DateTime&) =0; virtual void desktop_open_calendar_app(const DateTime&) =0; virtual void desktop_open_settings_app() =0; virtual void phone_open_alarm_app() =0; virtual void phone_open_appointment(const Appointment&, const DateTime&) =0; virtual void phone_open_calendar_app(const DateTime&) =0; virtual void phone_open_settings_app() =0; virtual void set_location(const std::string& zone, const std::string& name)=0; void set_calendar_date(const DateTime&); GActionGroup* action_group(); const std::shared_ptr state() const; protected: explicit Actions(const std::shared_ptr& state); virtual ~Actions(); private: std::shared_ptr m_state; GSimpleActionGroup* m_actions = nullptr; void update_calendar_state(); // we've got raw pointers in here, so disable copying Actions(const Actions&) =delete; Actions& operator=(const Actions&) =delete; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_ACTIONS_H ./include/datetime/settings.h0000644000015600001650000000440012701256660016330 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_SETTINGS_H #define INDICATOR_DATETIME_SETTINGS_H #include #include #include namespace unity { namespace indicator { namespace datetime { /** * \brief Interface that represents user-configurable settings. * * See the descriptions in data/com.canonical.indicator.datetime.gschema.xml * for more information on specific properties. */ class Settings { public: Settings() =default; virtual ~Settings() =default; core::Property custom_time_format; core::Property> locations; core::Property show_calendar; core::Property show_clock; core::Property show_date; core::Property show_day; core::Property show_detected_location; core::Property show_events; core::Property show_locations; core::Property show_seconds; core::Property show_week_numbers; core::Property show_year; core::Property time_format_mode; core::Property timezone_name; core::Property calendar_sound; core::Property alarm_sound; core::Property alarm_haptic; core::Property alarm_volume; core::Property alarm_duration; core::Property snooze_duration; core::Property>> muted_apps; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_SETTINGS_H ./include/datetime/timezone-timedated.h0000644000015600001650000000311712701256660020264 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_TIMEDATED_TIMEZONE_H #define INDICATOR_DATETIME_TIMEDATED_TIMEZONE_H #define DEFAULT_FILENAME "/etc/timezone" #include // base class #include // std::string namespace unity { namespace indicator { namespace datetime { /** * \brief A #Timezone that gets its information from monitoring a file, such as /etc/timezone */ class TimedatedTimezone: public Timezone { public: TimedatedTimezone(std::string filename = DEFAULT_FILENAME); ~TimedatedTimezone(); private: class Impl; friend Impl; std::unique_ptr impl; // we have pointers in here, so disable copying TimedatedTimezone(const TimedatedTimezone&) =delete; TimedatedTimezone& operator=(const TimedatedTimezone&) =delete; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_TIMEDATED_TIMEZONE_H ./include/datetime/dbus-shared.h0000644000015600001650000000221612701256660016674 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Ted Gould * Charles Kerr */ #ifndef INDICATOR_DATETIME_DBUS_SHARED_H #define INDICATOR_DATETIME_DBUS_SHARED_H #define BUS_DATETIME_NAME "com.canonical.indicator.datetime" #define BUS_DATETIME_PATH "/com/canonical/indicator/datetime" #define BUS_POWERD_NAME "com.canonical.powerd" #define BUS_POWERD_PATH "/com/canonical/powerd" #define BUS_POWERD_INTERFACE "com.canonical.powerd" #endif /* INDICATOR_DATETIME_DBUS_SHARED_H */ ./include/datetime/settings-shared.h0000644000015600001650000000453712701256660017607 0ustar jenkinsjenkins/* * Copyright 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Ted Gould * Charles Kerr */ #ifndef INDICATOR_DATETIME_SETTINGS_SHARED #define INDICATOR_DATETIME_SETTINGS_SHARED typedef enum { TIME_FORMAT_MODE_LOCALE_DEFAULT, TIME_FORMAT_MODE_12_HOUR, TIME_FORMAT_MODE_24_HOUR, TIME_FORMAT_MODE_CUSTOM } TimeFormatMode; #define SETTINGS_INTERFACE "com.canonical.indicator.datetime" #define SETTINGS_SHOW_CLOCK_S "show-clock" #define SETTINGS_TIME_FORMAT_S "time-format" #define SETTINGS_SHOW_SECONDS_S "show-seconds" #define SETTINGS_SHOW_DAY_S "show-day" #define SETTINGS_SHOW_DATE_S "show-date" #define SETTINGS_SHOW_YEAR_S "show-year" #define SETTINGS_CUSTOM_TIME_FORMAT_S "custom-time-format" #define SETTINGS_SHOW_CALENDAR_S "show-calendar" #define SETTINGS_SHOW_WEEK_NUMBERS_S "show-week-numbers" #define SETTINGS_SHOW_EVENTS_S "show-events" #define SETTINGS_SHOW_LOCATIONS_S "show-locations" #define SETTINGS_SHOW_DETECTED_S "show-auto-detected-location" #define SETTINGS_LOCATIONS_S "locations" #define SETTINGS_TIMEZONE_NAME_S "timezone-name" #define SETTINGS_CALENDAR_SOUND_S "calendar-default-sound" #define SETTINGS_ALARM_SOUND_S "alarm-default-sound" #define SETTINGS_ALARM_VOLUME_S "alarm-default-volume" #define SETTINGS_ALARM_DURATION_S "alarm-duration-minutes" #define SETTINGS_ALARM_HAPTIC_S "alarm-haptic-feedback" #define SETTINGS_SNOOZE_DURATION_S "snooze-duration-minutes" #define SETTINGS_CUNH_SCHEMA_ID "com.ubuntu.notifications.hub" #define SETTINGS_CUNH_BLACKLIST_S "blacklist" #endif // INDICATOR_DATETIME_SETTINGS_SHARED ./include/datetime/engine.h0000644000015600001650000000330512701256660015740 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_ENGINE_H #define INDICATOR_DATETIME_ENGINE_H #include #include #include #include #include namespace unity { namespace indicator { namespace datetime { /**** ***** ****/ /** * Class wrapper around the backend that generates appointments * * @see EdsEngine * @see EdsPlanner */ class Engine { public: virtual ~Engine() =default; virtual void get_appointments(const DateTime& begin, const DateTime& end, const Timezone& default_timezone, std::function&)> appointment_func) =0; virtual void disable_ubuntu_alarm(const Appointment&) =0; virtual core::Signal<>& changed() =0; protected: Engine() =default; }; /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_ENGINE_H ./include/CMakeLists.txt0000644000015600001650000000007312701256660015265 0ustar jenkinsjenkinsadd_subdirectory(datetime) add_subdirectory(notifications) ./include/notifications/0000755000015600001650000000000012701256660015376 5ustar jenkinsjenkins./include/notifications/sound.h0000644000015600001650000000400312701256660016674 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef UNITY_INDICATOR_NOTIFICATIONS_SOUND_H #define UNITY_INDICATOR_NOTIFICATIONS_SOUND_H #include #include namespace unity { namespace indicator { namespace notifications { /*** **** ***/ /** * Plays a sound, possibly looping. * * @param uri the file to play * @param volume the volume at which to play the sound, [0..100] * @param loop if true, loop the sound for the lifespan of the object */ class Sound { public: Sound(const std::string& role, const std::string& uri, unsigned int volume, bool loop); ~Sound(); private: class Impl; std::unique_ptr impl; }; /*** **** ***/ class SoundBuilder { public: SoundBuilder() =default; virtual ~SoundBuilder() =default; virtual std::shared_ptr create(const std::string& role, const std::string& uri, unsigned int volume, bool loop) =0; }; class DefaultSoundBuilder: public SoundBuilder { public: DefaultSoundBuilder() =default; ~DefaultSoundBuilder() =default; virtual std::shared_ptr create(const std::string& role, const std::string& uri, unsigned int volume, bool loop) override { return std::make_shared(role, uri, volume, loop); } }; /*** **** ***/ } // namespace notifications } // namespace indicator } // namespace unity #endif // UNITY_INDICATOR_NOTIFICATIONS_SOUND_H ./include/notifications/notifications.h0000644000015600001650000000655612701256660020434 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef UNITY_INDICATOR_NOTIFICATIONS_NOTIFICATIONS_H #define UNITY_INDICATOR_NOTIFICATIONS_NOTIFICATIONS_H #include #include #include #include namespace unity { namespace indicator { namespace notifications { class Engine; /** * Helper class for showing notifications. * * Populate the builder, then pass it to Engine::show(). * * @see Engine::show(Builder) */ class Builder { public: Builder(); ~Builder(); void set_title (const std::string& title); void set_body (const std::string& body); void set_icon_name (const std::string& icon_name); /* Set an interval, after which the notification will automatically be closed. If not set, the notification server's default timeout is used. */ void set_timeout (const std::chrono::seconds& duration); /* Add a notification hint. These keys may be dependent on the notification server. */ void add_hint (const std::string& name); static constexpr char const * HINT_SNAP {"x-canonical-snap-decisions"}; static constexpr char const * HINT_NONSHAPED_ICON {"x-canonical-non-shaped-icon"}; static constexpr char const * HINT_AFFIRMATIVE_HINT {"x-canonical-private-affirmative-tint"}; static constexpr char const * HINT_REJECTION_TINT {"x-canonical-private-rejection-tint"}; /* Add an action button. This may fail if the Engine doesn't support actions. @see Engine::supports_actions() */ void add_action (const std::string& action, const std::string& label); /** Sets the closed callback. This will be called exactly once. */ void set_closed_callback (std::function); private: friend class Engine; class Impl; std::unique_ptr impl; }; /** * Manages Notifications and the connection to the notification server. * * When this class is destroyed, any remaining notifications it created * will be closed and their closed() callbacks will be invoked. */ class Engine { public: explicit Engine(const std::string& app_name); ~Engine(); /** @see Builder::set_action() */ bool supports_actions() const; /** Show a notification. @return zero on failure, or a key that can be passed to close() */ int show(const Builder& builder); /** Close a notification. @param key the int returned by show() */ void close(int key); /** Close all remaining notifications. */ void close_all(); const std::string& app_name() const; private: class Impl; std::unique_ptr impl; }; } // namespace notifications } // namespace indicator } // namespace unity #endif // UNITY_INDICATOR_NOTIFICATIONS_NOTIFICATIONS_H ./include/notifications/awake.h0000644000015600001650000000236312701256660016643 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef UNITY_INDICATOR_NOTIFICATIONS_AWAKE_H #define UNITY_INDICATOR_NOTIFICATIONS_AWAKE_H #include namespace unity { namespace indicator { namespace notifications { /*** **** ***/ /** * A class that forces the screen display on and inhibits sleep */ class Awake { public: explicit Awake(const std::string& app_name); ~Awake(); private: class Impl; std::unique_ptr impl; }; /*** **** ***/ } // namespace notifications } // namespace indicator } // namespace unity #endif // UNITY_INDICATOR_NOTIFICATIONS_AWAKE_H ./include/notifications/haptic.h0000644000015600001650000000245312701256660017023 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #ifndef UNITY_INDICATOR_NOTIFICATIONS_HAPTIC_H #define UNITY_INDICATOR_NOTIFICATIONS_HAPTIC_H #include namespace unity { namespace indicator { namespace notifications { /*** **** ***/ /** * Tries to emit haptic feedback to match the user-specified mode. */ class Haptic { public: enum Mode { MODE_PULSE }; explicit Haptic(const Mode& mode = MODE_PULSE); ~Haptic(); private: class Impl; std::unique_ptr impl; }; /*** **** ***/ } // namespace notifications } // namespace indicator } // namespace unity #endif // UNITY_INDICATOR_NOTIFICATIONS_HAPTIC_H ./include/notifications/CMakeLists.txt0000644000015600001650000000000012701256660020124 0ustar jenkinsjenkins./include/notifications/dbus-shared.h0000644000015600001650000000261012701256660017747 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Ted Gould * Charles Kerr */ #ifndef UNITY_INDICATOR_NOTIFICATIONS_DBUS_SHARED_H #define UNITY_INDICATOR_NOTIFICATIONS_DBUS_SHARED_H #define BUS_SCREEN_NAME "com.canonical.Unity.Screen" #define BUS_SCREEN_PATH "/com/canonical/Unity/Screen" #define BUS_SCREEN_INTERFACE "com.canonical.Unity.Screen" #define BUS_POWERD_NAME "com.canonical.powerd" #define BUS_POWERD_PATH "/com/canonical/powerd" #define BUS_POWERD_INTERFACE "com.canonical.powerd" #define BUS_HAPTIC_NAME "com.canonical.usensord" #define BUS_HAPTIC_PATH "/com/canonical/usensord/haptic" #define BUS_HAPTIC_INTERFACE "com.canonical.usensord.haptic" #endif /* INDICATOR_NOTIFICATIONS_DBUS_SHARED_H */ ./src/0000755000015600001650000000000012701256671011673 5ustar jenkinsjenkins./src/wakeup-timer-mainloop.cpp0000644000015600001650000000573512701256660016635 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include // abs() namespace unity { namespace indicator { namespace datetime { /*** **** ***/ class MainloopWakeupTimer::Impl { public: Impl(const std::shared_ptr& clock): m_clock(clock) { } ~Impl() { cancel_timer(); } void set_wakeup_time(const DateTime& d) { m_wakeup_time = d; rebuild_timer(); } core::Signal<>& timeout() { return m_timeout; } private: void rebuild_timer() { cancel_timer(); g_return_if_fail(m_wakeup_time.is_set()); const auto now = m_clock->localtime(); const auto difference_usec = g_date_time_difference(m_wakeup_time.get(), now.get()); const guint interval_msec = std::abs(difference_usec) / 1000u; g_debug("%s setting wakeup timer to kick at %s, which is in %zu seconds", G_STRFUNC, m_wakeup_time.format("%F %T").c_str(), size_t{interval_msec/1000}); m_timeout_tag = g_timeout_add_full(G_PRIORITY_HIGH, interval_msec, on_timeout, this, nullptr); } static gboolean on_timeout(gpointer gself) { g_debug("%s %s", G_STRLOC, G_STRFUNC); static_cast(gself)->on_timeout(); return G_SOURCE_REMOVE; } void on_timeout() { cancel_timer(); m_timeout(); } void cancel_timer() { if (m_timeout_tag != 0) { g_source_remove(m_timeout_tag); m_timeout_tag = 0; } } core::Signal<> m_timeout; const std::shared_ptr& m_clock; guint m_timeout_tag = 0; DateTime m_wakeup_time; }; /*** **** ***/ MainloopWakeupTimer::MainloopWakeupTimer(const std::shared_ptr& clock): p(new Impl(clock)) { } MainloopWakeupTimer::~MainloopWakeupTimer() { } void MainloopWakeupTimer::set_wakeup_time(const DateTime& d) { p->set_wakeup_time(d); } core::Signal<>& MainloopWakeupTimer::timeout() { return p->timeout(); } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/clock.cpp0000644000015600001650000002000512701256660013465 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include #include #include #include #include #include namespace unity { namespace indicator { namespace datetime { /*** **** ***/ class Clock::Impl { public: Impl(Clock& owner): m_owner(owner), m_cancellable(g_cancellable_new()) { g_bus_get(G_BUS_TYPE_SYSTEM, m_cancellable, on_bus_ready, this); } ~Impl() { g_cancellable_cancel(m_cancellable); g_object_unref(m_cancellable); for(const auto& tag : m_watched_names) g_bus_unwatch_name(tag); } private: static void on_bus_ready(GObject * /*source_object*/, GAsyncResult * res, gpointer gself) { GError * error = NULL; GDBusConnection * bus; if ((bus = g_bus_get_finish(res, &error))) { auto self = static_cast(gself); auto tag = g_bus_watch_name_on_connection(bus, "org.freedesktop.login1", G_BUS_NAME_WATCHER_FLAGS_NONE, on_login1_appeared, on_login1_vanished, gself, nullptr); self->m_watched_names.insert(tag); tag = g_bus_watch_name_on_connection(bus, BUS_POWERD_NAME, G_BUS_NAME_WATCHER_FLAGS_NONE, on_powerd_appeared, on_powerd_vanished, gself, nullptr); self->m_watched_names.insert(tag); g_object_unref(bus); } else if (error != nullptr) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) g_warning("%s Couldn't get system bus: %s", G_STRLOC, error->message); g_error_free(error); } } void remember_subscription(const std::string & name, GDBusConnection * bus, guint tag) { g_object_ref(bus); auto deleter = [tag](GDBusConnection* bus){ g_dbus_connection_signal_unsubscribe(bus, tag); g_object_unref(G_OBJECT(bus)); }; m_subscriptions[name].push_back(std::shared_ptr(bus, deleter)); } /** *** DBus Chatter: org.freedesktop.login1 *** *** Fire Clock::minute_changed() signal on login1's PrepareForSleep signal **/ static void on_login1_appeared(GDBusConnection * bus, const gchar * name, const gchar * name_owner, gpointer gself) { auto tag = g_dbus_connection_signal_subscribe(bus, name_owner, "org.freedesktop.login1.Manager", // interface "PrepareForSleep", // signal name "/org/freedesktop/login1", // object path nullptr, // arg0 G_DBUS_SIGNAL_FLAGS_NONE, on_prepare_for_sleep, gself, nullptr); static_cast(gself)->remember_subscription(name, bus, tag); } static void on_login1_vanished(GDBusConnection * /*system_bus*/, const gchar * name, gpointer gself) { static_cast(gself)->m_subscriptions[name].clear(); } static void on_prepare_for_sleep(GDBusConnection* /*connection*/, const gchar* /*sender_name*/, const gchar* /*object_path*/, const gchar* /*interface_name*/, const gchar* /*signal_name*/, GVariant* /*parameters*/, gpointer gself) { g_debug("firing clock.minute_changed() due to PrepareForSleep"); static_cast(gself)->m_owner.minute_changed(); } /** *** DBus Chatter: com.canonical.powerd *** *** Fire Clock::minute_changed() signal when powerd says the system's *** has awoken from sleep -- the old timestamp is likely out-of-date **/ static void on_powerd_appeared(GDBusConnection * bus, const gchar * name, const gchar * name_owner, gpointer gself) { auto tag = g_dbus_connection_signal_subscribe(bus, name_owner, BUS_POWERD_INTERFACE, "SysPowerStateChange", BUS_POWERD_PATH, nullptr, // arg0 G_DBUS_SIGNAL_FLAGS_NONE, on_sys_power_state_change, gself, // user_data nullptr); // user_data closure static_cast(gself)->remember_subscription(name, bus, tag); } static void on_powerd_vanished(GDBusConnection * /*bus*/, const gchar * name, gpointer gself) { static_cast(gself)->m_subscriptions[name].clear(); } static void on_sys_power_state_change(GDBusConnection* /*connection*/, const gchar* /*sender_name*/, const gchar* /*object_path*/, const gchar* /*interface_name*/, const gchar* /*signal_name*/, GVariant* /*parameters*/, gpointer gself) { g_debug("firing clock.minute_changed() due to state change"); static_cast(gself)->m_owner.minute_changed(); } /*** **** ***/ Clock& m_owner; GCancellable * m_cancellable = nullptr; std::set m_watched_names; std::map>> m_subscriptions; }; /*** **** ***/ Clock::Clock(): m_impl(new Impl{*this}) { } Clock::~Clock() { } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/locations-settings.cpp0000644000015600001650000000552012701256660016230 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include #include #include // std::find() namespace unity { namespace indicator { namespace datetime { SettingsLocations::SettingsLocations(const std::shared_ptr& settings, const std::shared_ptr& timezones): m_settings(settings), m_timezones(timezones) { m_settings->locations.changed().connect([this](const std::vector&){reload();}); m_settings->show_locations.changed().connect([this](bool){reload();}); m_timezones->timezone.changed().connect([this](const std::string&){reload();}); m_timezones->timezones.changed().connect([this](const std::set&){reload();}); reload(); } void SettingsLocations::reload() { std::vector v; const std::string timezone_name = m_settings->timezone_name.get(); // add the primary timezone first auto zone = m_timezones->timezone.get(); if (!zone.empty()) { gchar * name = get_beautified_timezone_name(zone.c_str(), timezone_name.c_str()); Location l(zone, name); v.push_back(l); g_free(name); } // add the other detected timezones for(const auto& zone : m_timezones->timezones.get()) { gchar * name = get_beautified_timezone_name(zone.c_str(), timezone_name.c_str()); Location l(zone, name); if (std::find(v.begin(), v.end(), l) == v.end()) v.push_back(l); g_free(name); } // maybe add the user-specified locations if (m_settings->show_locations.get()) { for(const auto& locstr : m_settings->locations.get()) { gchar* zone; gchar* name; split_settings_location(locstr.c_str(), &zone, &name); Location loc(zone, name); if (std::find(v.begin(), v.end(), loc) == v.end()) v.push_back(loc); g_free(name); g_free(zone); } } locations.set(v); } } // namespace datetime } // namespace indicator } // namespace unity ./src/planner-snooze.cpp0000644000015600001650000000540312701256660015351 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include // e_uid_new() namespace unity { namespace indicator { namespace datetime { /*** **** ***/ class SnoozePlanner::Impl { public: Impl(SnoozePlanner* owner, const std::shared_ptr& settings, const std::shared_ptr& clock): m_owner(owner), m_settings(settings), m_clock(clock) { } ~Impl() { } core::Property>& appointments() { return m_appointments; } void add(const Appointment& appt_in, const Alarm& alarm) { // make a copy of the appointment with only this alarm Appointment appt = appt_in; appt.alarms.clear(); appt.alarms.push_back(alarm); // reschedule the alarm to go off N minutes from now const auto offset = std::chrono::minutes(m_settings->snooze_duration.get()); appt.begin += offset; appt.end += offset; appt.alarms[0].time += offset; // give it a new ID gchar* uid = e_uid_new(); appt.uid = uid; g_free(uid); // add it to our appointment list auto tmp = appointments().get(); tmp.push_back(appt); m_owner->sort(tmp); m_appointments.set(tmp); } private: const SnoozePlanner* const m_owner; const std::shared_ptr m_settings; const std::shared_ptr m_clock; core::Property> m_appointments; }; /*** **** ***/ SnoozePlanner::SnoozePlanner(const std::shared_ptr& settings, const std::shared_ptr& clock): impl(new Impl{this, settings, clock}) { } SnoozePlanner::~SnoozePlanner() { } void SnoozePlanner::add(const Appointment& appointment, const Alarm& alarm) { impl->add(appointment, alarm); } core::Property>& SnoozePlanner::appointments() { return impl->appointments(); } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/haptic.cpp0000644000015600001650000001103712701256660013647 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include #include #include namespace unity { namespace indicator { namespace notifications { /*** **** ***/ class Haptic::Impl { public: Impl(const Mode& mode): m_mode(mode), m_cancellable(g_cancellable_new()) { g_bus_get (G_BUS_TYPE_SESSION, m_cancellable, on_bus_ready, this); } ~Impl() { if (m_tag) g_source_remove(m_tag); g_cancellable_cancel (m_cancellable); g_object_unref (m_cancellable); g_clear_object (&m_bus); } private: static void on_bus_ready (GObject*, GAsyncResult* res, gpointer gself) { GError * error; GDBusConnection * bus; error = nullptr; bus = g_bus_get_finish (res, &error); if (error != nullptr) { if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) g_warning ("Unable to get bus: %s", error->message); g_error_free (error); } else if (bus != nullptr) { auto self = static_cast(gself); self->m_bus = G_DBUS_CONNECTION (g_object_ref (bus)); self->start_vibrating(); g_object_unref (bus); } } void start_vibrating() { g_return_if_fail (m_tag == 0); switch (m_mode) { case MODE_PULSE: // the only mode currently supported... :) // one second on, one second off. m_pattern = std::vector({1000u, 1000u}); break; } // Set up a loop to keep repeating the pattern auto msec = std::accumulate(m_pattern.begin(), m_pattern.end(), 0u); m_tag = g_timeout_add(msec, call_vibrate_pattern_static, this); call_vibrate_pattern(); } static gboolean call_vibrate_pattern_static (gpointer gself) { static_cast(gself)->call_vibrate_pattern(); return G_SOURCE_CONTINUE; } void call_vibrate_pattern() { // build the vibrate pattern GVariantBuilder builder; g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY); for (const auto& msec : m_pattern) g_variant_builder_add_value (&builder, g_variant_new_uint32(msec)); auto pattern_array = g_variant_builder_end (&builder); /* Use a repeat_count of 1 here because we handle looping ourselves. NB: VibratePattern could do it for us, but doesn't let us cancel a running loop -- we could keep vibrating even after "this" was destructed */ auto repeat_count = g_variant_new_uint32 (1u); g_variant_builder_init (&builder, G_VARIANT_TYPE_TUPLE); g_variant_builder_add_value (&builder, pattern_array); g_variant_builder_add_value (&builder, repeat_count); auto vibrate_pattern_args = g_variant_builder_end (&builder); g_dbus_connection_call (m_bus, BUS_HAPTIC_NAME, BUS_HAPTIC_PATH, BUS_HAPTIC_INTERFACE, "VibratePattern", vibrate_pattern_args, nullptr, G_DBUS_CALL_FLAGS_NONE, -1, m_cancellable, nullptr, nullptr); } const Mode m_mode; GCancellable * m_cancellable = nullptr; GDBusConnection * m_bus = nullptr; std::vector m_pattern; guint m_tag = 0; }; /*** **** ***/ Haptic::Haptic(const Mode& mode): impl(new Impl (mode)) { } Haptic::~Haptic() { } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/com.ubuntu.touch.AccountsService.Sound.xml0000644000015600001650000000412512701256660022023 0ustar jenkinsjenkins ./src/settings-live.cpp0000644000015600001650000002663412701256660015205 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include namespace unity { namespace indicator { namespace datetime { /*** **** ***/ LiveSettings::~LiveSettings() { g_clear_object(&m_settings_cunh); g_clear_object(&m_settings); } LiveSettings::LiveSettings(): m_settings(g_settings_new(SETTINGS_INTERFACE)), m_settings_cunh(g_settings_new(SETTINGS_CUNH_SCHEMA_ID)) { g_signal_connect (m_settings, "changed", G_CALLBACK(on_changed_ccid), this); g_signal_connect (m_settings_cunh, "changed", G_CALLBACK(on_changed_cunh), this); // init the Properties from the GSettings backend update_custom_time_format(); update_locations(); update_show_calendar(); update_show_clock(); update_show_date(); update_show_day(); update_show_detected_locations(); update_show_events(); update_show_locations(); update_show_seconds(); update_show_week_numbers(); update_show_year(); update_time_format_mode(); update_timezone_name(); update_calendar_sound(); update_alarm_sound(); update_alarm_volume(); update_alarm_duration(); update_alarm_haptic(); update_snooze_duration(); update_muted_apps(); // now listen for clients to change the properties s.t. we can sync update GSettings custom_time_format.changed().connect([this](const std::string& value){ g_settings_set_string(m_settings, SETTINGS_CUSTOM_TIME_FORMAT_S, value.c_str()); }); muted_apps.changed().connect([this](const std::set>& value){ GVariantBuilder builder; g_variant_builder_init(&builder, G_VARIANT_TYPE("a(ss)")); for(const auto& app : value){ const std::string& pkgname {app.first}; const std::string& appname {app.second}; g_variant_builder_add(&builder, "(ss)", pkgname.c_str(), appname.c_str()); } g_settings_set_value(m_settings_cunh, SETTINGS_CUNH_BLACKLIST_S, g_variant_builder_end(&builder)); }); locations.changed().connect([this](const std::vector& value){ const int n = value.size(); gchar** strv = g_new0(gchar*, n+1); for(int i=0; i(value[i].c_str()); g_settings_set_strv(m_settings, SETTINGS_LOCATIONS_S, strv); g_free(strv); }); show_calendar.changed().connect([this](bool value){ g_settings_set_boolean(m_settings, SETTINGS_SHOW_CALENDAR_S, value); }); show_clock.changed().connect([this](bool value){ g_settings_set_boolean(m_settings, SETTINGS_SHOW_CLOCK_S, value); }); show_date.changed().connect([this](bool value){ g_settings_set_boolean(m_settings, SETTINGS_SHOW_DATE_S, value); }); show_day.changed().connect([this](bool value){ g_settings_set_boolean(m_settings, SETTINGS_SHOW_DAY_S, value); }); show_detected_location.changed().connect([this](bool value){ g_settings_set_boolean(m_settings, SETTINGS_SHOW_DETECTED_S, value); }); show_events.changed().connect([this](bool value){ g_settings_set_boolean(m_settings, SETTINGS_SHOW_EVENTS_S, value); }); show_locations.changed().connect([this](bool value){ g_settings_set_boolean(m_settings, SETTINGS_SHOW_LOCATIONS_S, value); }); show_seconds.changed().connect([this](bool value){ g_settings_set_boolean(m_settings, SETTINGS_SHOW_SECONDS_S, value); }); show_week_numbers.changed().connect([this](bool value){ g_settings_set_boolean(m_settings, SETTINGS_SHOW_WEEK_NUMBERS_S, value); }); show_year.changed().connect([this](bool value){ g_settings_set_boolean(m_settings, SETTINGS_SHOW_YEAR_S, value); }); time_format_mode.changed().connect([this](TimeFormatMode value){ g_settings_set_enum(m_settings, SETTINGS_TIME_FORMAT_S, gint(value)); }); timezone_name.changed().connect([this](const std::string& value){ g_settings_set_string(m_settings, SETTINGS_TIMEZONE_NAME_S, value.c_str()); }); calendar_sound.changed().connect([this](const std::string& value){ g_settings_set_string(m_settings, SETTINGS_CALENDAR_SOUND_S, value.c_str()); }); alarm_sound.changed().connect([this](const std::string& value){ g_settings_set_string(m_settings, SETTINGS_ALARM_SOUND_S, value.c_str()); }); alarm_volume.changed().connect([this](unsigned int value){ g_settings_set_uint(m_settings, SETTINGS_ALARM_VOLUME_S, value); }); alarm_duration.changed().connect([this](unsigned int value){ g_settings_set_uint(m_settings, SETTINGS_ALARM_DURATION_S, value); }); alarm_haptic.changed().connect([this](const std::string& value){ g_settings_set_string(m_settings, SETTINGS_ALARM_HAPTIC_S, value.c_str()); }); snooze_duration.changed().connect([this](unsigned int value){ g_settings_set_uint(m_settings, SETTINGS_SNOOZE_DURATION_S, value); }); } /*** **** ***/ void LiveSettings::update_custom_time_format() { auto val = g_settings_get_string(m_settings, SETTINGS_CUSTOM_TIME_FORMAT_S); custom_time_format.set(val); g_free(val); } void LiveSettings::update_locations() { auto strv = g_settings_get_strv(m_settings, SETTINGS_LOCATIONS_S); std::vector l; for(int i=0; strv && strv[i]; i++) l.push_back(strv[i]); g_strfreev(strv); locations.set(l); } void LiveSettings::update_muted_apps() { std::set> apps; auto blacklist = g_settings_get_value(m_settings_cunh, SETTINGS_CUNH_BLACKLIST_S); GVariantIter* iter {nullptr}; g_variant_get (blacklist, "a(ss)", &iter); gchar* pkgname; gchar* appname; while (g_variant_iter_loop (iter, "(ss)", &pkgname, &appname)) { apps.insert(std::make_pair(pkgname,appname)); } g_variant_iter_free (iter); g_clear_pointer(&blacklist, g_variant_unref); muted_apps.set(apps); } void LiveSettings::update_show_calendar() { const auto val = g_settings_get_boolean(m_settings, SETTINGS_SHOW_CALENDAR_S); show_calendar.set(val); } void LiveSettings::update_show_clock() { show_clock.set(g_settings_get_boolean(m_settings, SETTINGS_SHOW_CLOCK_S)); } void LiveSettings::update_show_date() { show_date.set(g_settings_get_boolean(m_settings, SETTINGS_SHOW_DATE_S)); } void LiveSettings::update_show_day() { show_day.set(g_settings_get_boolean(m_settings, SETTINGS_SHOW_DAY_S)); } void LiveSettings::update_show_detected_locations() { const auto val = g_settings_get_boolean(m_settings, SETTINGS_SHOW_DETECTED_S); show_detected_location.set(val); } void LiveSettings::update_show_events() { const auto val = g_settings_get_boolean(m_settings, SETTINGS_SHOW_EVENTS_S); show_events.set(val); } void LiveSettings::update_show_locations() { const auto val = g_settings_get_boolean(m_settings, SETTINGS_SHOW_LOCATIONS_S); show_locations.set(val); } void LiveSettings::update_show_seconds() { show_seconds.set(g_settings_get_boolean(m_settings, SETTINGS_SHOW_SECONDS_S)); } void LiveSettings::update_show_week_numbers() { const auto val = g_settings_get_boolean(m_settings, SETTINGS_SHOW_WEEK_NUMBERS_S); show_week_numbers.set(val); } void LiveSettings::update_show_year() { show_year.set(g_settings_get_boolean(m_settings, SETTINGS_SHOW_YEAR_S)); } void LiveSettings::update_time_format_mode() { time_format_mode.set((TimeFormatMode)g_settings_get_enum(m_settings, SETTINGS_TIME_FORMAT_S)); } void LiveSettings::update_timezone_name() { auto val = g_settings_get_string(m_settings, SETTINGS_TIMEZONE_NAME_S); timezone_name.set(val); g_free(val); } void LiveSettings::update_calendar_sound() { auto val = g_settings_get_string(m_settings, SETTINGS_CALENDAR_SOUND_S); calendar_sound.set(val); g_free(val); } void LiveSettings::update_alarm_sound() { auto val = g_settings_get_string(m_settings, SETTINGS_ALARM_SOUND_S); alarm_sound.set(val); g_free(val); } void LiveSettings::update_alarm_volume() { alarm_volume.set(g_settings_get_uint(m_settings, SETTINGS_ALARM_VOLUME_S)); } void LiveSettings::update_alarm_duration() { alarm_duration.set(g_settings_get_uint(m_settings, SETTINGS_ALARM_DURATION_S)); } void LiveSettings::update_alarm_haptic() { auto val = g_settings_get_string(m_settings, SETTINGS_ALARM_HAPTIC_S); alarm_haptic.set(val); g_free(val); } void LiveSettings::update_snooze_duration() { snooze_duration.set(g_settings_get_uint(m_settings, SETTINGS_SNOOZE_DURATION_S)); } /*** **** ***/ void LiveSettings::on_changed_cunh(GSettings* /*settings*/, gchar* key, gpointer gself) { static_cast(gself)->update_key_cunh(key); } void LiveSettings::update_key_cunh(const std::string& key) { if (key == SETTINGS_CUNH_BLACKLIST_S) update_muted_apps(); } /*** **** ***/ void LiveSettings::on_changed_ccid(GSettings* /*settings*/, gchar* key, gpointer gself) { static_cast(gself)->update_key_ccid(key); } void LiveSettings::update_key_ccid(const std::string& key) { if (key == SETTINGS_SHOW_CLOCK_S) update_show_clock(); else if (key == SETTINGS_LOCATIONS_S) update_locations(); else if (key == SETTINGS_TIME_FORMAT_S) update_time_format_mode(); else if (key == SETTINGS_SHOW_SECONDS_S) update_show_seconds(); else if (key == SETTINGS_SHOW_DAY_S) update_show_day(); else if (key == SETTINGS_SHOW_DATE_S) update_show_date(); else if (key == SETTINGS_SHOW_YEAR_S) update_show_year(); else if (key == SETTINGS_CUSTOM_TIME_FORMAT_S) update_custom_time_format(); else if (key == SETTINGS_SHOW_CALENDAR_S) update_show_calendar(); else if (key == SETTINGS_SHOW_WEEK_NUMBERS_S) update_show_week_numbers(); else if (key == SETTINGS_SHOW_EVENTS_S) update_show_events(); else if (key == SETTINGS_SHOW_LOCATIONS_S) update_show_locations(); else if (key == SETTINGS_SHOW_DETECTED_S) update_show_detected_locations(); else if (key == SETTINGS_TIMEZONE_NAME_S) update_timezone_name(); else if (key == SETTINGS_CALENDAR_SOUND_S) update_calendar_sound(); else if (key == SETTINGS_ALARM_SOUND_S) update_alarm_sound(); else if (key == SETTINGS_ALARM_VOLUME_S) update_alarm_volume(); else if (key == SETTINGS_ALARM_DURATION_S) update_alarm_duration(); else if (key == SETTINGS_ALARM_HAPTIC_S) update_alarm_haptic(); else if (key == SETTINGS_SNOOZE_DURATION_S) update_snooze_duration(); } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/timezone-timedated.cpp0000644000015600001650000001315012701256660016165 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include #include namespace unity { namespace indicator { namespace datetime { /*** **** ***/ class TimedatedTimezone::Impl { public: Impl(TimedatedTimezone& owner, std::string filename): m_owner(owner), m_filename(filename) { g_debug("Filename is '%s'", filename.c_str()); monitor_timezone_property(); } ~Impl() { clear(); } private: void clear() { if (m_connection && m_signal_subscription_id) { g_dbus_connection_signal_unsubscribe (m_connection, m_signal_subscription_id); m_signal_subscription_id = 0; } g_clear_object(&m_connection); } static void on_properties_changed (GDBusConnection *connection G_GNUC_UNUSED, const gchar *sender_name G_GNUC_UNUSED, const gchar *object_path G_GNUC_UNUSED, const gchar *interface_name G_GNUC_UNUSED, const gchar *signal_name G_GNUC_UNUSED, GVariant *parameters, gpointer gself) { auto self = static_cast(gself); const char *tz; GVariant *changed_properties; gchar **invalidated_properties; g_variant_get (parameters, "(s@a{sv}^as)", NULL, &changed_properties, &invalidated_properties); if (g_variant_lookup(changed_properties, "Timezone", "&s", &tz, NULL)) self->notify_timezone(tz); else if (g_strv_contains (invalidated_properties, "Timezone")) self->notify_timezone(self->get_timezone_from_file(self->m_filename)); g_variant_unref (changed_properties); g_strfreev (invalidated_properties); } void monitor_timezone_property() { GError *err = nullptr; /* * There is an unlikely race which happens if there is an activation * and timezone change before our match rule is added. */ notify_timezone(get_timezone_from_file(m_filename)); /* * Make sure the bus is around at least until we add the match rules, * otherwise things (tests) are sad. */ m_connection = g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, &err); if (err) { g_warning("Couldn't get bus connection: '%s'", err->message); g_error_free(err); return; } m_signal_subscription_id = g_dbus_connection_signal_subscribe(m_connection, "org.freedesktop.timedate1", "org.freedesktop.DBus.Properties", "PropertiesChanged", "/org/freedesktop/timedate1", NULL, G_DBUS_SIGNAL_FLAGS_NONE, on_properties_changed, this, nullptr); } void notify_timezone(std::string new_timezone) { g_debug("notify_timezone '%s'", new_timezone.c_str()); if (!new_timezone.empty()) m_owner.timezone.set(new_timezone); } std::string get_timezone_from_file(const std::string& filename) { GError * error; GIOChannel * io_channel; std::string ret; // read through filename line-by-line until we fine a nonempty non-comment line error = nullptr; io_channel = g_io_channel_new_file(filename.c_str(), "r", &error); if (error == nullptr) { auto line = g_string_new(nullptr); while(ret.empty()) { const auto io_status = g_io_channel_read_line_string(io_channel, line, nullptr, &error); if ((io_status == G_IO_STATUS_EOF) || (io_status == G_IO_STATUS_ERROR)) break; if (error != nullptr) break; g_strstrip(line->str); if (!line->len) // skip empty lines continue; if (*line->str=='#') // skip comments continue; ret = line->str; } g_string_free(line, true); } else /* Default to UTC */ ret = "Etc/Utc"; if (io_channel != nullptr) { g_io_channel_shutdown(io_channel, false, nullptr); g_io_channel_unref(io_channel); } if (error != nullptr) { g_warning("%s Unable to read timezone file '%s': %s", G_STRLOC, filename.c_str(), error->message); g_error_free(error); } return ret; } /*** **** ***/ TimedatedTimezone & m_owner; GDBusConnection *m_connection = nullptr; unsigned long m_signal_subscription_id = 0; std::string m_filename; }; /*** **** ***/ TimedatedTimezone::TimedatedTimezone(std::string filename): impl(new Impl{*this, filename}) { } TimedatedTimezone::~TimedatedTimezone() { } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/main.cpp0000644000015600001650000001541312701256660013325 0ustar jenkinsjenkins/* * Copyright 2013 Canonical Ltd. * * Authors: * Charles Kerr * * 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // bindtextdomain() #include #include #include // exit() namespace uin = unity::indicator::notifications; using namespace unity::indicator::datetime; namespace { std::shared_ptr create_engine() { std::shared_ptr engine; // we don't show appointments in the greeter, // so no need to connect to EDS there... if (!g_strcmp0("lightdm", g_get_user_name())) engine.reset(new MockEngine); else engine.reset(new EdsEngine); return engine; } std::shared_ptr create_state(const std::shared_ptr& engine, const std::shared_ptr& timezone_) { // create the live objects auto live_settings = std::make_shared(); auto live_timezones = std::make_shared(live_settings); auto live_clock = std::make_shared(timezone_); // create a full-month planner currently pointing to the current month const auto now = live_clock->localtime(); auto range_planner = std::make_shared(engine, timezone_); auto calendar_month = std::make_shared(range_planner, now); // create an upcoming-events planner currently pointing to the current date range_planner = std::make_shared(engine, timezone_); auto calendar_upcoming = std::make_shared(range_planner, now); // create the state auto state = std::make_shared(); state->settings = live_settings; state->clock = live_clock; state->locations = std::make_shared(live_settings, live_timezones); state->calendar_month = calendar_month; state->calendar_upcoming = calendar_upcoming; return state; } std::shared_ptr create_simple_alarm_queue(const std::shared_ptr& clock, const std::shared_ptr& snooze_planner, const std::shared_ptr& engine, const std::shared_ptr& tz) { // create an upcoming-events planner that =always= tracks the clock's date auto range_planner = std::make_shared(engine, tz); auto upcoming_planner = std::make_shared(range_planner, clock->localtime()); clock->date_changed.connect([clock,upcoming_planner](){ const auto now = clock->localtime(); g_debug("refretching appointments due to date change: %s", now.format("%F %T").c_str()); upcoming_planner->date().set(now); }); // create an aggregate planner that folds together the above // upcoming-events planner and locally-generated snooze events std::shared_ptr planner = std::make_shared(); planner->add(upcoming_planner); planner->add(snooze_planner); auto wakeup_timer = std::make_shared(clock); return std::make_shared(clock, planner, wakeup_timer); } } int main(int /*argc*/, char** /*argv*/) { // These can be removed when https://bugzilla.gnome.org/show_bug.cgi?id=674885 is fixed g_type_ensure(G_TYPE_DBUS_CONNECTION); // http://pad.lv/1239710 g_type_ensure(G_TYPE_DBUS_PROXY); // http://pad.lv/1425297 // boilerplate i18n setlocale(LC_ALL, ""); bindtextdomain(GETTEXT_PACKAGE, GNOMELOCALEDIR); textdomain(GETTEXT_PACKAGE); auto engine = create_engine(); auto timezone_ = std::make_shared(); auto state = create_state(engine, timezone_); auto actions = std::make_shared(state); MenuFactory factory(actions, state); // set up the snap decisions auto snooze_planner = std::make_shared(state->settings, state->clock); auto notification_engine = std::make_shared("indicator-datetime-service"); auto sound_builder = std::make_shared(); std::unique_ptr snap (new Snap(notification_engine, sound_builder, state->settings)); auto alarm_queue = create_simple_alarm_queue(state->clock, snooze_planner, engine, timezone_); auto on_snooze = [snooze_planner](const Appointment& appointment, const Alarm& alarm) { snooze_planner->add(appointment, alarm); }; auto on_ok = [](const Appointment&, const Alarm&){}; auto on_alarm_reached = [&engine, &snap, &on_snooze, &on_ok](const Appointment& appointment, const Alarm& alarm) { (*snap)(appointment, alarm, on_snooze, on_ok); engine->disable_ubuntu_alarm(appointment); }; alarm_queue->alarm_reached().connect(on_alarm_reached); // create the menus std::vector> menus; for(int i=0, n=Menu::NUM_PROFILES; isettings); exporter.name_lost().connect([loop](){ g_message("%s exiting; failed/lost bus ownership", GETTEXT_PACKAGE); g_main_loop_quit(loop); }); exporter.publish(actions, menus); g_main_loop_run(loop); g_main_loop_unref(loop); return 0; } ./src/notifications.cpp0000644000015600001650000002143312701256660015251 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include #include #include #include namespace unity { namespace indicator { namespace notifications { static G_DEFINE_QUARK(NotificationKey, notification_key) static G_DEFINE_QUARK(NotificationAction, notification_action) /*** **** ***/ class Builder::Impl { public: std::string m_title; std::string m_body; std::string m_icon_name; std::chrono::seconds m_duration; std::set m_string_hints; std::vector> m_actions; std::function m_closed_callback; }; Builder::Builder(): impl(new Impl()) { } Builder::~Builder() { } void Builder::set_title (const std::string& title) { impl->m_title = title; } void Builder::set_body (const std::string& body) { impl->m_body = body; } void Builder::set_icon_name (const std::string& icon_name) { impl->m_icon_name = icon_name; } void Builder::set_timeout (const std::chrono::seconds& duration) { impl->m_duration = duration; } void Builder::add_hint (const std::string& name) { impl->m_string_hints.insert (name); } void Builder::add_action (const std::string& action, const std::string& label) { impl->m_actions.push_back(std::pair(action,label)); } void Builder::set_closed_callback (std::function cb) { impl->m_closed_callback.swap (cb); } /*** **** ***/ class Engine::Impl { struct notification_data { std::shared_ptr nn; std::function closed_callback; }; public: Impl(const std::string& app_name): m_app_name(app_name) { if (!notify_init(app_name.c_str())) g_critical("Unable to initialize libnotify!"); } ~Impl() { close_all (); notify_uninit (); } const std::string& app_name() const { return m_app_name; } bool supports_actions() const { return server_caps().count("actions") != 0; } void close_all () { // call close() on all our keys std::set keys; for (const auto& it : m_notifications) keys.insert (it.first); for (const int key : keys) close (key); } void close (int key) { auto it = m_notifications.find(key); if (it != m_notifications.end()) { // tell the server to close the notification GError * error = nullptr; if (!notify_notification_close (it->second.nn.get(), &error)) { g_warning ("Unable to close notification %d: %s", key, error->message); g_error_free (error); } // call the user callback and remove it from our bookkeeping remove_closed_notification (key); } } int show (const Builder& builder) { int ret = -1; const auto& info = *builder.impl; std::shared_ptr nn ( notify_notification_new(info.m_title.c_str(), info.m_body.c_str(), info.m_icon_name.c_str()), [this](NotifyNotification * n) { g_signal_handlers_disconnect_by_data(n, this); g_object_unref (G_OBJECT(n)); } ); if (info.m_duration.count() != 0) { const auto& d= info.m_duration; auto ms = std::chrono::duration_cast(d); notify_notification_set_hint (nn.get(), HINT_TIMEOUT, g_variant_new_int32(ms.count())); } for (const auto& hint : info.m_string_hints) { notify_notification_set_hint (nn.get(), hint.c_str(), g_variant_new_string("true")); } for (const auto& action : info.m_actions) { notify_notification_add_action (nn.get(), action.first.c_str(), action.second.c_str(), on_notification_clicked, nullptr, nullptr); } static int next_key = 1; const int key = next_key++; g_object_set_qdata (G_OBJECT(nn.get()), notification_key_quark(), GINT_TO_POINTER(key)); m_notifications[key] = { nn, info.m_closed_callback }; g_signal_connect (nn.get(), "closed", G_CALLBACK(on_notification_closed), this); GError * error = nullptr; if (notify_notification_show(nn.get(), &error)) { ret = key; } else { g_critical ("Unable to show notification for '%s': %s", info.m_title.c_str(), error->message); g_error_free (error); m_notifications.erase(key); } return ret; } private: const std::set& server_caps() const { if (G_UNLIKELY(m_lazy_caps.empty())) { auto caps_gl = notify_get_server_caps(); std::string caps_str; for(auto l=caps_gl; l!=nullptr; l=l->next) { m_lazy_caps.insert((const char*)l->data); caps_str += (const char*) l->data;; if (l->next != nullptr) caps_str += ", "; } g_debug("%s notify_get_server() returned [%s]", G_STRFUNC, caps_str.c_str()); g_list_free_full(caps_gl, g_free); } return m_lazy_caps; } static void on_notification_clicked (NotifyNotification * nn, char * action, gpointer) { g_object_set_qdata_full (G_OBJECT(nn), notification_action_quark(), g_strdup(action), g_free); } static void on_notification_closed (NotifyNotification * nn, gpointer gself) { const GQuark q = notification_key_quark(); const gpointer gkey = g_object_get_qdata(G_OBJECT(nn), q); static_cast(gself)->remove_closed_notification(GPOINTER_TO_INT(gkey)); } void remove_closed_notification (int key) { auto it = m_notifications.find(key); g_return_if_fail (it != m_notifications.end()); const auto& ndata = it->second; auto nn = ndata.nn.get(); if (ndata.closed_callback) { std::string action; const GQuark q = notification_action_quark(); const gpointer p = g_object_get_qdata(G_OBJECT(nn), q); if (p != nullptr) action = static_cast(p); ndata.closed_callback (action); } m_notifications.erase(it); } /*** **** ***/ const std::string m_app_name; // key-to-data std::map m_notifications; // server capabilities. // as the name indicates, don't use this directly: use server_caps() instead mutable std::set m_lazy_caps; static constexpr char const * HINT_TIMEOUT {"x-canonical-snap-decisions-timeout"}; }; /*** **** ***/ Engine::Engine(const std::string& app_name): impl(new Impl(app_name)) { } Engine::~Engine() { } bool Engine::supports_actions() const { return impl->supports_actions(); } int Engine::show(const Builder& builder) { return impl->show(builder); } void Engine::close_all() { impl->close_all(); } void Engine::close(int key) { impl->close(key); } const std::string& Engine::app_name() const { return impl->app_name(); } /*** **** ***/ } // namespace notifications } // namespace indicator } // namespace unity ./src/menu.cpp0000644000015600001650000005020612701256660013344 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include #include #include #include namespace unity { namespace indicator { namespace datetime { /**** ***** ****/ Menu::Menu (Profile profile_in, const std::string& name_in): m_profile(profile_in), m_name(name_in) { } const std::string& Menu::name() const { return m_name; } Menu::Profile Menu::profile() const { return m_profile; } GMenuModel* Menu::menu_model() { return G_MENU_MODEL(m_menu); } /**** ***** ****/ #define ALARM_ICON_NAME "alarm-clock" #define CALENDAR_ICON_NAME "calendar" class MenuImpl: public Menu { protected: MenuImpl(const Menu::Profile profile_in, const std::string& name_in, std::shared_ptr& state, std::shared_ptr& actions, std::shared_ptr formatter): Menu(profile_in, name_in), m_state(state), m_actions(actions), m_formatter(formatter) { // initialize the menu create_gmenu(); for (int i=0; iheader.changed().connect([this](const std::string&){ update_header(); }); m_formatter->header_format.changed().connect([this](const std::string&){ update_section(Locations); // need to update x-canonical-time-format }); m_formatter->relative_format_changed.connect([this](){ update_section(Appointments); // uses formatter.relative_format() update_section(Locations); // uses formatter.relative_format() }); m_state->settings->show_clock.changed().connect([this](bool){ update_header(); // update header's label update_section(Locations); // locations' relative time may have changed }); m_state->settings->show_calendar.changed().connect([this](bool){ update_section(Calendar); }); m_state->settings->show_events.changed().connect([this](bool){ update_section(Appointments); // showing events got toggled }); m_state->calendar_upcoming->date().changed().connect([this](const DateTime&){ update_upcoming(); // our m_upcoming is planner->upcoming() filtered by time }); m_state->calendar_upcoming->appointments().changed().connect([this](const std::vector&){ update_upcoming(); // our m_upcoming is planner->upcoming() filtered by time }); m_state->clock->date_changed.connect([this](){ update_section(Calendar); // need to update the Date menuitem update_section(Locations); // locations' relative time may have changed }); m_state->clock->minute_changed.connect([this](){ update_upcoming(); // our m_upcoming is planner->upcoming() filtered by time }); m_state->locations->locations.changed().connect([this](const std::vector&) { update_section(Locations); // "locations" is the list of Locations we show }); } virtual ~MenuImpl() { g_clear_object(&m_menu); g_clear_pointer(&m_serialized_alarm_icon, g_variant_unref); g_clear_pointer(&m_serialized_calendar_icon, g_variant_unref); } virtual GVariant* create_header_state() =0; void update_header() { auto action_group = m_actions->action_group(); auto action_name = name() + "-header"; auto state = create_header_state(); g_action_group_change_action_state(action_group, action_name.c_str(), state); } void update_upcoming() { // The usual case is on desktop (and /only/ case on phone) // is that we're looking at the current date and want to see // "the next five calendar events, if any." // // However on the Desktop when the user clicks onto a different // calendar date, show the next five calendar events starting // from the beginning of that clicked day. DateTime begin; const auto now = m_state->clock->localtime(); const auto calendar_day = m_state->calendar_month->month().get(); if ((profile() == Desktop) && !DateTime::is_same_day(now, calendar_day)) begin = calendar_day.start_of_day(); else begin = now.start_of_minute(); std::vector upcoming; for(const auto& a : m_state->calendar_upcoming->appointments().get()) if (begin <= a.begin) upcoming.push_back(a); if (m_upcoming != upcoming) { m_upcoming.swap(upcoming); update_header(); // show an 'alarm' icon if there are upcoming alarms update_section(Appointments); // "upcoming" is the list of Appointments we show } } std::shared_ptr m_state; std::shared_ptr m_actions; std::shared_ptr m_formatter; GMenu* m_submenu = nullptr; GVariant* get_serialized_alarm_icon() { if (G_UNLIKELY(m_serialized_alarm_icon == nullptr)) { auto i = g_themed_icon_new_with_default_fallbacks(ALARM_ICON_NAME); m_serialized_alarm_icon = g_icon_serialize(i); g_object_unref(i); } return m_serialized_alarm_icon; } std::vector m_upcoming; private: GVariant* get_serialized_calendar_icon() { if (G_UNLIKELY(m_serialized_calendar_icon == nullptr)) { auto i = g_themed_icon_new_with_default_fallbacks(CALENDAR_ICON_NAME); m_serialized_calendar_icon = g_icon_serialize(i); g_object_unref(i); } return m_serialized_calendar_icon; } void create_gmenu() { g_assert(m_submenu == nullptr); m_submenu = g_menu_new(); // build placeholders for the sections for(int i=0; isettings->show_calendar.get() && ((profile == Desktop) || (profile == DesktopGreeter)); auto menu = g_menu_new(); const char * action_name; if (profile == Phone) action_name = "indicator.phone.open-calendar-app"; else if (profile == Desktop) action_name = "indicator.desktop.open-calendar-app"; else action_name = nullptr; /* Translators, please edit/rearrange these strftime(3) tokens to suit your locale! Format string for the day on the first menuitem in the datetime indicator. This format string gives the full weekday, date, month, and year. en_US example: "%A, %B %e %Y" --> Saturday, October 31 2020" en_GB example: "%A, %e %B %Y" --> Saturday, 31 October 2020" */ auto label = m_state->clock->localtime().format(_("%A, %e %B %Y")); auto item = g_menu_item_new (label.c_str(), nullptr); auto v = get_serialized_calendar_icon(); g_menu_item_set_attribute_value (item, G_MENU_ATTRIBUTE_ICON, v); if (action_name != nullptr) { v = g_variant_new_int64(0); g_menu_item_set_action_and_target_value (item, action_name, v); } g_menu_append_item(menu, item); g_object_unref(item); // add calendar if (show_calendar) { item = g_menu_item_new ("[calendar]", nullptr); v = g_variant_new_int64(0); g_menu_item_set_action_and_target_value (item, "indicator.calendar", v); g_menu_item_set_attribute (item, "x-canonical-type", "s", "com.canonical.indicator.calendar"); if (action_name != nullptr) g_menu_item_set_attribute (item, "activation-action", "s", action_name); g_menu_append_item (menu, item); g_object_unref (item); } return G_MENU_MODEL(menu); } void add_appointments(GMenu* menu, Profile profile) { const int MAX_APPTS = 5; std::set added; const char * action_name; if (profile == Phone) action_name = "indicator.phone.open-appointment"; else if ((profile == Desktop) && m_actions->desktop_has_calendar_app()) action_name = "indicator.desktop.open-appointment"; else action_name = nullptr; for (const auto& appt : m_upcoming) { // don't show duplicates if (added.count(appt.uid)) continue; // don't show too many if (g_menu_model_get_n_items (G_MENU_MODEL(menu)) >= MAX_APPTS) break; added.insert(appt.uid); GDateTime* begin = appt.begin(); GDateTime* end = appt.end(); auto fmt = m_formatter->relative_format(begin, end); auto unix_time = g_date_time_to_unix(begin); auto menu_item = g_menu_item_new (appt.summary.c_str(), nullptr); g_menu_item_set_attribute (menu_item, "x-canonical-time", "x", unix_time); g_menu_item_set_attribute (menu_item, "x-canonical-time-format", "s", fmt.c_str()); if (appt.is_ubuntu_alarm()) { g_menu_item_set_attribute (menu_item, "x-canonical-type", "s", "com.canonical.indicator.alarm"); g_menu_item_set_attribute_value(menu_item, G_MENU_ATTRIBUTE_ICON, get_serialized_alarm_icon()); } else { g_menu_item_set_attribute (menu_item, "x-canonical-type", "s", "com.canonical.indicator.appointment"); } if (!appt.color.empty()) g_menu_item_set_attribute (menu_item, "x-canonical-color", "s", appt.color.c_str()); if (action_name != nullptr) { g_menu_item_set_action_and_target_value (menu_item, action_name, g_variant_new ("(sx)", appt.uid.c_str(), unix_time)); } g_menu_append_item (menu, menu_item); g_object_unref (menu_item); } } GMenuModel* create_appointments_section(Profile profile) { auto menu = g_menu_new(); if ((profile==Desktop) && m_state->settings->show_events.get()) { add_appointments (menu, profile); if (m_actions->desktop_has_calendar_app()) { // add the 'Add Event…' menuitem auto menu_item = g_menu_item_new(_("Add Event…"), nullptr); const gchar* action_name = "indicator.desktop.open-calendar-app"; auto v = g_variant_new_int64(0); g_menu_item_set_action_and_target_value(menu_item, action_name, v); g_menu_append_item(menu, menu_item); g_object_unref(menu_item); } } else if (profile==Phone) { auto menu_item = g_menu_item_new (_("Clock"), "indicator.phone.open-alarm-app"); g_menu_item_set_attribute_value (menu_item, G_MENU_ATTRIBUTE_ICON, get_serialized_alarm_icon()); g_menu_append_item (menu, menu_item); g_object_unref (menu_item); add_appointments (menu, profile); } return G_MENU_MODEL(menu); } GMenuModel* create_locations_section(Profile profile) { GMenu* menu = g_menu_new(); if (profile == Desktop) { const auto now = m_state->clock->localtime(); for(const auto& location : m_state->locations->locations.get()) { const auto& zone = location.zone(); const auto& name = location.name(); const auto zone_now = now.to_timezone(zone); const auto fmt = m_formatter->relative_format(zone_now.get()); auto detailed_action = g_strdup_printf("indicator.set-location::%s %s", zone.c_str(), name.c_str()); auto i = g_menu_item_new (name.c_str(), detailed_action); g_menu_item_set_attribute(i, "x-canonical-type", "s", "com.canonical.indicator.location"); g_menu_item_set_attribute(i, "x-canonical-timezone", "s", zone.c_str()); g_menu_item_set_attribute(i, "x-canonical-time-format", "s", fmt.c_str()); g_menu_append_item (menu, i); g_object_unref(i); g_free(detailed_action); } } return G_MENU_MODEL(menu); } GMenuModel* create_settings_section(Profile profile) { auto menu = g_menu_new(); const char * action_name; if (profile == Desktop) action_name = "indicator.desktop.open-settings-app"; else if (profile == Phone) action_name = "indicator.phone.open-settings-app"; else action_name = nullptr; if (action_name != nullptr) g_menu_append (menu, _("Time & Date settings…"), action_name); return G_MENU_MODEL (menu); } void update_section(Section section) { GMenuModel * model; const auto p = profile(); switch (section) { case Calendar: model = create_calendar_section(p); break; case Appointments: model = create_appointments_section(p); break; case Locations: model = create_locations_section(p); break; case Settings: model = create_settings_section(p); break; default: model = nullptr; g_warn_if_reached(); } if (model) { g_menu_remove(m_submenu, section); g_menu_insert_section(m_submenu, section, nullptr, model); g_object_unref(model); } } //private: GVariant * m_serialized_alarm_icon = nullptr; GVariant * m_serialized_calendar_icon = nullptr; }; // class MenuImpl /*** **** ***/ class DesktopBaseMenu: public MenuImpl { protected: DesktopBaseMenu(Menu::Profile profile_, const std::string& name_, std::shared_ptr& state_, std::shared_ptr& actions_): MenuImpl(profile_, name_, state_, actions_, std::shared_ptr(new DesktopFormatter(state_->clock, state_->settings))) { update_header(); } GVariant* create_header_state() { const auto visible = m_state->settings->show_clock.get(); const auto title = _("Date and Time"); auto label = g_variant_new_string(m_formatter->header.get().c_str()); GVariantBuilder b; g_variant_builder_init(&b, G_VARIANT_TYPE_VARDICT); g_variant_builder_add(&b, "{sv}", "accessible-desc", label); g_variant_builder_add(&b, "{sv}", "label", label); g_variant_builder_add(&b, "{sv}", "title", g_variant_new_string(title)); g_variant_builder_add(&b, "{sv}", "visible", g_variant_new_boolean(visible)); return g_variant_builder_end(&b); } }; class DesktopMenu: public DesktopBaseMenu { public: DesktopMenu(std::shared_ptr& state_, std::shared_ptr& actions_): DesktopBaseMenu(Desktop,"desktop", state_, actions_) {} }; class DesktopGreeterMenu: public DesktopBaseMenu { public: DesktopGreeterMenu(std::shared_ptr& state_, std::shared_ptr& actions_): DesktopBaseMenu(DesktopGreeter,"desktop_greeter", state_, actions_) {} }; class PhoneBaseMenu: public MenuImpl { protected: PhoneBaseMenu(Menu::Profile profile_, const std::string& name_, std::shared_ptr& state_, std::shared_ptr& actions_): MenuImpl(profile_, name_, state_, actions_, std::shared_ptr(new PhoneFormatter(state_->clock))) { update_header(); } GVariant* create_header_state() { // are there alarms? bool has_ubuntu_alarms = false; for(const auto& appointment : m_upcoming) if((has_ubuntu_alarms = appointment.is_ubuntu_alarm())) break; GVariantBuilder b; g_variant_builder_init(&b, G_VARIANT_TYPE_VARDICT); g_variant_builder_add(&b, "{sv}", "title", g_variant_new_string (_("Time & Date"))); g_variant_builder_add(&b, "{sv}", "visible", g_variant_new_boolean (TRUE)); if (has_ubuntu_alarms) { auto label = m_formatter->header.get(); auto a11y = g_strdup_printf(_("%s (has alarms)"), label.c_str()); g_variant_builder_add(&b, "{sv}", "label", g_variant_new_string(label.c_str())); g_variant_builder_add(&b, "{sv}", "accessible-desc", g_variant_new_take_string(a11y)); g_variant_builder_add(&b, "{sv}", "icon", get_serialized_alarm_icon()); } else { auto v = g_variant_new_string(m_formatter->header.get().c_str()); g_variant_builder_add(&b, "{sv}", "label", v); g_variant_builder_add(&b, "{sv}", "accessible-desc", v); } return g_variant_builder_end (&b); } }; class PhoneMenu: public PhoneBaseMenu { public: PhoneMenu(std::shared_ptr& state_, std::shared_ptr& actions_): PhoneBaseMenu(Phone, "phone", state_, actions_) {} }; class PhoneGreeterMenu: public PhoneBaseMenu { public: PhoneGreeterMenu(std::shared_ptr& state_, std::shared_ptr& actions_): PhoneBaseMenu(PhoneGreeter, "phone_greeter", state_, actions_) {} }; /**** ***** ****/ MenuFactory::MenuFactory(const std::shared_ptr& actions_, const std::shared_ptr& state_): m_actions(actions_), m_state(state_) { } std::shared_ptr MenuFactory::buildMenu(Menu::Profile profile) { std::shared_ptr menu; switch (profile) { case Menu::Desktop: menu.reset(new DesktopMenu(m_state, m_actions)); break; case Menu::DesktopGreeter: menu.reset(new DesktopGreeterMenu(m_state, m_actions)); break; case Menu::Phone: menu.reset(new PhoneMenu(m_state, m_actions)); break; case Menu::PhoneGreeter: menu.reset(new PhoneGreeterMenu(m_state, m_actions)); break; default: g_warn_if_reached(); break; } return menu; } /**** ***** ****/ } // namespace datetime } // namespace indicator } // namespace unity ./src/actions-live.cpp0000644000015600001650000001621112701256671014775 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include #include namespace unity { namespace indicator { namespace datetime { /*** **** ***/ LiveActions::LiveActions(const std::shared_ptr& state_in): Actions(state_in) { } void LiveActions::execute_command(const std::string& cmdstr) { const auto cmd = cmdstr.c_str(); g_debug("Issuing command '%s'", cmd); GError* error = nullptr; if (!g_spawn_command_line_async(cmd, &error)) { g_warning("Unable to start \"%s\": %s", cmd, error->message); g_error_free(error); } } void LiveActions::dispatch_url(const std::string& url) { g_debug("Dispatching url '%s'", url.c_str()); url_dispatch_send(url.c_str(), nullptr, nullptr); } /*** **** ***/ bool LiveActions::is_unity() { static bool cached = false; static bool result; if (cached) { return result; } result = false; const gchar *xdg_current_desktop = g_getenv ("XDG_CURRENT_DESKTOP"); if (xdg_current_desktop != NULL) { gchar **desktop_names = g_strsplit (xdg_current_desktop, ":", 0); for (size_t i = 0; desktop_names[i]; ++i) { if (!g_strcmp0 (desktop_names[i], "Unity")) { result = true; break; } } g_strfreev (desktop_names); } cached = true; return result; } void LiveActions::desktop_open_settings_app() { if (g_getenv ("MIR_SOCKET") != nullptr) { dispatch_url("settings:///system/time-date"); } else if (is_unity()) { execute_command("unity-control-center datetime"); } else { execute_command("gnome-control-center datetime"); } } bool LiveActions::desktop_has_calendar_app() const { static bool inited = false; static bool have_calendar = false; if (G_UNLIKELY(!inited)) { inited = true; #if 0 auto all = g_app_info_get_all_for_type ("text/calendar"); for(auto l=all; !have_calendar && l!=nullptr; l=l->next) { auto app_info = static_cast(l->data); if (!g_strcmp0("evolution.desktop", g_app_info_get_id(app_info))) have_calendar = true; } g_list_free_full(all, (GDestroyNotify)g_object_unref); #else /* Work around http://pad.lv/1296233 for Trusty... let's revert this when the GIO bug is fixed. */ auto executable = g_find_program_in_path("evolution"); have_calendar = executable != nullptr; g_free(executable); #endif } return have_calendar; } void LiveActions::desktop_open_alarm_app() { execute_command("evolution -c calendar"); } void LiveActions::desktop_open_appointment(const Appointment&, const DateTime& date) { desktop_open_calendar_app(date); } void LiveActions::desktop_open_calendar_app(const DateTime& dt) { const auto utc = dt.start_of_day().to_timezone("UTC"); auto cmd = utc.format("evolution \"calendar:///?startdate=%Y%m%dT%H%M%SZ\""); execute_command(cmd.c_str()); } /*** **** ***/ void LiveActions::phone_open_alarm_app() { dispatch_url("appid://com.ubuntu.clock/clock/current-user-version"); } void LiveActions::phone_open_appointment(const Appointment& appt, const DateTime& date) { if (!appt.activation_url.empty()) { dispatch_url(appt.activation_url); } else switch (appt.type) { case Appointment::UBUNTU_ALARM: phone_open_alarm_app(); break; case Appointment::EVENT: default: phone_open_calendar_app(date); break; } } void LiveActions::phone_open_calendar_app(const DateTime& dt) { const auto utc = dt.to_timezone("UTC"); auto cmd = utc.format("calendar://startdate=%Y-%m-%dT%H:%M:%S+00:00"); dispatch_url(cmd); } void LiveActions::phone_open_settings_app() { dispatch_url("settings:///system/time-date"); } /*** **** ***/ namespace { struct setlocation_data { std::string tzid; std::string name; std::shared_ptr settings; }; static void on_datetime1_set_timezone_response(GObject * object, GAsyncResult * res, gpointer gdata) { GError* err = nullptr; auto response = g_dbus_proxy_call_finish(G_DBUS_PROXY(object), res, &err); auto data = static_cast(gdata); if (err != nullptr) { if (!g_error_matches(err, G_IO_ERROR, G_IO_ERROR_CANCELLED)) g_warning("Could not set new timezone: %s", err->message); g_error_free(err); } else { data->settings->timezone_name.set(data->tzid + " " + data->name); g_variant_unref(response); } delete data; } static void on_datetime1_proxy_ready (GObject * object G_GNUC_UNUSED, GAsyncResult * res, gpointer gdata) { auto data = static_cast(gdata); GError * err = nullptr; auto proxy = g_dbus_proxy_new_for_bus_finish(res, &err); if (err != nullptr) { if (!g_error_matches(err, G_IO_ERROR, G_IO_ERROR_CANCELLED)) g_warning("Could not grab DBus proxy for timedated: %s", err->message); g_error_free(err); delete data; } else { g_dbus_proxy_call(proxy, "SetTimezone", g_variant_new ("(sb)", data->tzid.c_str(), TRUE), G_DBUS_CALL_FLAGS_NONE, -1, nullptr, on_datetime1_set_timezone_response, data); g_object_unref (proxy); } } } // unnamed namespace void LiveActions::set_location(const std::string& tzid, const std::string& name) { g_return_if_fail(!tzid.empty()); g_return_if_fail(!name.empty()); auto data = new struct setlocation_data; data->tzid = tzid; data->name = name; data->settings = state()->settings; g_dbus_proxy_new_for_bus (G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, nullptr, "org.freedesktop.timedate1", "/org/freedesktop/timedate1", "org.freedesktop.timedate1", nullptr, on_datetime1_proxy_ready, data); } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/timezone-geoclue.cpp0000644000015600001650000002244212701256660015654 0ustar jenkinsjenkins/* * Copyright 2013 Canonical Ltd. * * Authors: * Charles Kerr * * 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . */ #include #include #include #include #include #define GEOCLUE_BUS_NAME "org.freedesktop.Geoclue.Master" namespace unity { namespace indicator { namespace datetime { class GeoclueTimezone::Impl { public: Impl(GeoclueTimezone& owner): m_owner(owner), m_cancellable(g_cancellable_new()) { g_bus_get(G_BUS_TYPE_SESSION, m_cancellable, on_bus_got, this); } ~Impl() { g_cancellable_cancel(m_cancellable); g_object_unref(m_cancellable); g_object_unref(m_bus); } private: void remember_subscription(GDBusConnection * bus, guint tag) { g_object_ref(bus); auto deleter = [tag](GDBusConnection* bus){ g_dbus_connection_signal_unsubscribe(bus, tag); g_object_unref(G_OBJECT(bus)); }; m_subscriptions.push_back(std::shared_ptr(bus, deleter)); } static void on_bus_got(GObject * /*source*/, GAsyncResult * res, gpointer gself) { GError * error; GDBusConnection * connection; error = nullptr; connection = g_bus_get_finish(res, &error); if (error) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) g_warning("Couldn't get bus: %s", error->message); g_error_free(error); } else { auto self = static_cast(gself); self->m_bus = connection; g_dbus_connection_call(self->m_bus, GEOCLUE_BUS_NAME, "/org/freedesktop/Geoclue/Master", "org.freedesktop.Geoclue.Master", "Create", nullptr, // parameters G_VARIANT_TYPE("(o)"), G_DBUS_CALL_FLAGS_NONE, -1, self->m_cancellable, on_client_created, self); } } static void on_client_created(GObject* source, GAsyncResult* res, gpointer gself) { GVariant * result; if ((result = call_finish(G_STRFUNC, source, res))) { auto self = static_cast(gself); GVariant * child = g_variant_get_child_value(result, 0); self->m_client_object_path = g_variant_get_string(child, nullptr); g_variant_unref(child); g_variant_unref(result); auto tag = g_dbus_connection_signal_subscribe(self->m_bus, GEOCLUE_BUS_NAME, "org.freedesktop.Geoclue.Address", // interface "AddressChanged", // signal name self->m_client_object_path.c_str(), // object path nullptr, // arg0 G_DBUS_SIGNAL_FLAGS_NONE, on_address_changed, self, nullptr); self->remember_subscription(self->m_bus, tag); g_dbus_connection_call(self->m_bus, GEOCLUE_BUS_NAME, self->m_client_object_path.c_str(), "org.freedesktop.Geoclue.MasterClient", "SetRequirements", g_variant_new("(iibi)", 2, 0, FALSE, 1023), nullptr, G_DBUS_CALL_FLAGS_NONE, -1, self->m_cancellable, on_requirements_set, self); } } static void on_address_changed(GDBusConnection* /*connection*/, const gchar* /*sender_name*/, const gchar* /*object_path*/, const gchar* /*interface_name*/, const gchar* /*signal_name*/, GVariant* parameters, gpointer gself) { static_cast(gself)->set_timezone_from_address_variant(parameters); } static void on_requirements_set(GObject* source, GAsyncResult* res, gpointer gself) { GVariant * result; if ((result = call_finish(G_STRFUNC, source, res))) { auto self = static_cast(gself); g_dbus_connection_call(self->m_bus, GEOCLUE_BUS_NAME, self->m_client_object_path.c_str(), "org.freedesktop.Geoclue.MasterClient", "AddressStart", nullptr, nullptr, G_DBUS_CALL_FLAGS_NONE, -1, self->m_cancellable, on_address_started, self); g_variant_unref(result); } } static void on_address_started(GObject* source, GAsyncResult* res, gpointer gself) { GVariant * result; if ((result = call_finish(G_STRFUNC, source, res))) { auto self = static_cast(gself); g_dbus_connection_call(self->m_bus, GEOCLUE_BUS_NAME, self->m_client_object_path.c_str(), "org.freedesktop.Geoclue.Address", "GetAddress", nullptr, G_VARIANT_TYPE("(ia{ss}(idd))"), G_DBUS_CALL_FLAGS_NONE, -1, self->m_cancellable, on_address_got, self); g_variant_unref(result); } } static void on_address_got(GObject* source, GAsyncResult* res, gpointer gself) { GVariant * result; if ((result = call_finish(G_STRFUNC, source, res))) { static_cast(gself)->set_timezone_from_address_variant(result); g_variant_unref(result); } } /*** **** ***/ void set_timezone_from_address_variant(GVariant * variant) { g_return_if_fail(g_variant_is_of_type(variant, G_VARIANT_TYPE("(ia{ss}(idd))"))); const gchar * timezone_string = nullptr; GVariant * dict = g_variant_get_child_value(variant, 1); if (dict) { if (g_variant_lookup(dict, "timezone", "&s", &timezone_string)) { g_debug("from geoclue, setting timezone to '%s'", timezone_string); m_owner.timezone.set(timezone_string); } g_variant_unref(dict); } } static GVariant* call_finish(const char * funcname, GObject * source, GAsyncResult * res) { GError * error; GVariant * result; error = nullptr; result = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), res, &error); if (error) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) g_warning("%s failed: %s", funcname, error->message); g_error_free(error); g_clear_pointer(&result, g_variant_unref); } return result; } /*** **** ***/ GeoclueTimezone & m_owner; GDBusConnection * m_bus = nullptr; GCancellable * m_cancellable = nullptr; std::string m_client_object_path; std::vector> m_subscriptions; }; /**** ***** ****/ GeoclueTimezone::GeoclueTimezone(): impl(new Impl{*this}) { } GeoclueTimezone::~GeoclueTimezone() { } /**** ***** ****/ } // namespace datetime } // namespace indicator } // namespace unity ./src/engine-eds.cpp0000644000015600001650000011463412701256660014424 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include #include #include #include // std::sort() #include #include // time() #include // strstr(), strlen() #include #include namespace unity { namespace indicator { namespace datetime { static constexpr char const * TAG_ALARM {"x-canonical-alarm"}; static constexpr char const * TAG_DISABLED {"x-canonical-disabled"}; static constexpr char const * X_PROP_ACTIVATION_URL {"X-CANONICAL-ACTIVATION-URL"}; /**** ***** ****/ class EdsEngine::Impl { public: Impl() { auto cancellable_deleter = [](GCancellable * c) { g_cancellable_cancel(c); g_clear_object(&c); }; m_cancellable = std::shared_ptr(g_cancellable_new(), cancellable_deleter); e_source_registry_new(m_cancellable.get(), on_source_registry_ready, this); } ~Impl() { m_cancellable.reset(); while(!m_sources.empty()) remove_source(*m_sources.begin()); if (m_rebuild_tag) g_source_remove(m_rebuild_tag); if (m_source_registry) g_signal_handlers_disconnect_by_data(m_source_registry, this); g_clear_object(&m_source_registry); } core::Signal<>& changed() { return m_changed; } void get_appointments(const DateTime& begin, const DateTime& end, const Timezone& timezone, std::function&)> func) { const auto b_str = begin.format("%F %T"); const auto e_str = end.format("%F %T"); g_debug("getting all appointments from [%s ... %s]", b_str.c_str(), e_str.c_str()); /** *** init the default timezone **/ icaltimezone * default_timezone = nullptr; const auto tz = timezone.timezone.get().c_str(); if (tz && *tz) { default_timezone = icaltimezone_get_builtin_timezone(tz); if (default_timezone == nullptr) // maybe str is a tzid? default_timezone = icaltimezone_get_builtin_timezone_from_tzid(tz); g_debug("default_timezone is %p", (void*)default_timezone); } /** *** walk through the sources to build the appointment list **/ auto gtz = default_timezone != nullptr ? g_time_zone_new(icaltimezone_get_location(default_timezone)) : g_time_zone_new_local(); auto main_task = std::make_shared(this, func, default_timezone, gtz, begin, end); for (auto& kv : m_clients) { auto& client = kv.second; if (default_timezone != nullptr) e_cal_client_set_default_timezone(client, default_timezone); g_debug("calling e_cal_client_generate_instances for %p", (void*)client); auto& source = kv.first; auto extension = e_source_get_extension(source, E_SOURCE_EXTENSION_CALENDAR); const auto color = e_source_selectable_get_color(E_SOURCE_SELECTABLE(extension)); auto begin_str = isodate_from_time_t(begin.to_unix()); auto end_str = isodate_from_time_t(end.to_unix()); auto sexp_fmt = g_strdup_printf("(%%s? (make-time \"%s\") (make-time \"%s\"))", begin_str, end_str); g_clear_pointer(&begin_str, g_free); g_clear_pointer(&end_str, g_free); // ask EDS about alarms that occur in this window... auto sexp = g_strdup_printf(sexp_fmt, "has-alarms-in-range"); g_debug("%s alarm sexp is %s", G_STRLOC, sexp); e_cal_client_get_object_list_as_comps( client, sexp, m_cancellable.get(), on_alarm_component_list_ready, new ClientSubtask(main_task, client, m_cancellable, color)); g_clear_pointer(&sexp, g_free); // ask EDS about events that occur in this window... sexp = g_strdup_printf(sexp_fmt, "occur-in-time-range"); g_debug("%s event sexp is %s", G_STRLOC, sexp); e_cal_client_get_object_list_as_comps( client, sexp, m_cancellable.get(), on_event_component_list_ready, new ClientSubtask(main_task, client, m_cancellable, color)); g_clear_pointer(&sexp, g_free); g_clear_pointer(&sexp_fmt, g_free); } } void disable_ubuntu_alarm(const Appointment& appointment) { if (appointment.is_ubuntu_alarm()) { for (auto& kv : m_clients) // find the matching icalcomponent { e_cal_client_get_object(kv.second, appointment.uid.c_str(), nullptr, m_cancellable.get(), on_object_ready_for_disable, this); } } } private: void set_dirty_now() { m_changed(); } static gboolean set_dirty_now_static (gpointer gself) { auto self = static_cast(gself); self->m_rebuild_tag = 0; self->m_rebuild_deadline = 0; self->set_dirty_now(); return G_SOURCE_REMOVE; } void set_dirty_soon() { static constexpr int MIN_BATCH_SEC = 1; static constexpr int MAX_BATCH_SEC = 60; static_assert(MIN_BATCH_SEC <= MAX_BATCH_SEC, "bad boundaries"); const auto now = time(nullptr); if (m_rebuild_deadline == 0) // first pass { m_rebuild_deadline = now + MAX_BATCH_SEC; m_rebuild_tag = g_timeout_add_seconds(MIN_BATCH_SEC, set_dirty_now_static, this); } else if (now < m_rebuild_deadline) { g_source_remove (m_rebuild_tag); m_rebuild_tag = g_timeout_add_seconds(MIN_BATCH_SEC, set_dirty_now_static, this); } } static void on_source_registry_ready(GObject* /*source*/, GAsyncResult* res, gpointer gself) { GError * error = nullptr; auto r = e_source_registry_new_finish(res, &error); if (error != nullptr) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) g_warning("indicator-datetime cannot show EDS appointments: %s", error->message); g_error_free(error); } else { g_signal_connect(r, "source-added", G_CALLBACK(on_source_added), gself); g_signal_connect(r, "source-removed", G_CALLBACK(on_source_removed), gself); g_signal_connect(r, "source-changed", G_CALLBACK(on_source_changed), gself); g_signal_connect(r, "source-disabled", G_CALLBACK(on_source_disabled), gself); g_signal_connect(r, "source-enabled", G_CALLBACK(on_source_enabled), gself); auto self = static_cast(gself); self->m_source_registry = r; self->add_sources_by_extension(E_SOURCE_EXTENSION_CALENDAR); self->add_sources_by_extension(E_SOURCE_EXTENSION_TASK_LIST); } } void add_sources_by_extension(const char* extension) { auto& r = m_source_registry; auto sources = e_source_registry_list_sources(r, extension); for (auto l=sources; l!=nullptr; l=l->next) on_source_added(r, E_SOURCE(l->data), this); g_list_free_full(sources, g_object_unref); } static void on_source_added(ESourceRegistry* registry, ESource* source, gpointer gself) { auto self = static_cast(gself); self->m_sources.insert(E_SOURCE(g_object_ref(source))); if (e_source_get_enabled(source)) on_source_enabled(registry, source, gself); } static void on_source_enabled(ESourceRegistry* /*registry*/, ESource* source, gpointer gself) { auto self = static_cast(gself); ECalClientSourceType source_type; bool client_wanted = false; if (e_source_has_extension(source, E_SOURCE_EXTENSION_CALENDAR)) { source_type = E_CAL_CLIENT_SOURCE_TYPE_EVENTS; client_wanted = true; } else if (e_source_has_extension(source, E_SOURCE_EXTENSION_TASK_LIST)) { source_type = E_CAL_CLIENT_SOURCE_TYPE_TASKS; client_wanted = true; } const auto source_uid = e_source_get_uid(source); if (client_wanted) { g_debug("%s connecting a client to source %s", G_STRFUNC, source_uid); e_cal_client_connect(source, source_type, #if EDS_CHECK_VERSION(3,13,90) -1, #endif self->m_cancellable.get(), on_client_connected, gself); } else { g_debug("%s not using source %s -- no tasks/calendar", G_STRFUNC, source_uid); } } static void on_client_connected(GObject* /*source*/, GAsyncResult * res, gpointer gself) { GError * error = nullptr; EClient * client = e_cal_client_connect_finish(res, &error); if (error) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) g_warning("indicator-datetime cannot connect to EDS source: %s", error->message); g_error_free(error); } else { // add the client to our collection auto self = static_cast(gself); g_debug("got a client for %s", e_cal_client_get_local_attachment_store(E_CAL_CLIENT(client))); auto source = e_client_get_source(client); auto ecc = E_CAL_CLIENT(client); self->m_clients[source] = ecc; self->ensure_client_alarms_have_triggers(ecc); // now create a view for it so that we can listen for changes e_cal_client_get_view (ecc, "#t", // match all self->m_cancellable.get(), on_client_view_ready, self); g_debug("client connected; calling set_dirty_soon()"); self->set_dirty_soon(); } } static void on_client_view_ready (GObject* client, GAsyncResult* res, gpointer gself) { GError* error = nullptr; ECalClientView* view = nullptr; if (e_cal_client_get_view_finish (E_CAL_CLIENT(client), res, &view, &error)) { // add the view to our collection e_cal_client_view_set_flags(view, E_CAL_CLIENT_VIEW_FLAGS_NONE, nullptr); e_cal_client_view_start(view, &error); g_debug("got a view for %s", e_cal_client_get_local_attachment_store(E_CAL_CLIENT(client))); auto self = static_cast(gself); self->m_views[e_client_get_source(E_CLIENT(client))] = view; g_signal_connect(view, "objects-added", G_CALLBACK(on_view_objects_added), self); g_signal_connect(view, "objects-modified", G_CALLBACK(on_view_objects_modified), self); g_signal_connect(view, "objects-removed", G_CALLBACK(on_view_objects_removed), self); g_debug("view connected; calling set_dirty_soon()"); self->set_dirty_soon(); } else if(error != nullptr) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) g_warning("indicator-datetime cannot get View to EDS client: %s", error->message); g_error_free(error); } } static void on_view_objects_added(ECalClientView* /*view*/, gpointer /*objects*/, gpointer gself) { g_debug("%s", G_STRFUNC); static_cast(gself)->set_dirty_soon(); } static void on_view_objects_modified(ECalClientView* /*view*/, gpointer /*objects*/, gpointer gself) { g_debug("%s", G_STRFUNC); static_cast(gself)->set_dirty_soon(); } static void on_view_objects_removed(ECalClientView* /*view*/, gpointer /*objects*/, gpointer gself) { g_debug("%s", G_STRFUNC); static_cast(gself)->set_dirty_soon(); } static void on_source_disabled(ESourceRegistry* /*registry*/, ESource* source, gpointer gself) { static_cast(gself)->disable_source(source); } void disable_source(ESource* source) { // if an ECalClientView is associated with this source, remove it auto vit = m_views.find(source); if (vit != m_views.end()) { auto& view = vit->second; e_cal_client_view_stop(view, nullptr); const auto n_disconnected = g_signal_handlers_disconnect_by_data(view, this); g_warn_if_fail(n_disconnected == 3); g_object_unref(view); m_views.erase(vit); set_dirty_soon(); } // if an ECalClient is associated with this source, remove it auto cit = m_clients.find(source); if (cit != m_clients.end()) { auto& client = cit->second; g_object_unref(client); m_clients.erase(cit); set_dirty_soon(); } } static void on_source_removed(ESourceRegistry* /*registry*/, ESource* source, gpointer gself) { static_cast(gself)->remove_source(source); } void remove_source(ESource* source) { disable_source(source); auto sit = m_sources.find(source); if (sit != m_sources.end()) { g_object_unref(*sit); m_sources.erase(sit); set_dirty_soon(); } } static void on_source_changed(ESourceRegistry* /*registry*/, ESource* /*source*/, gpointer gself) { g_debug("source changed; calling set_dirty_soon()"); static_cast(gself)->set_dirty_soon(); } /*** **** ***/ // old ubuntu-clock-app alarms created VTODO VALARMS without the // required 'TRIGGER' property... http://pad.lv/1465806 void ensure_client_alarms_have_triggers(ECalClient* client) { // ask the EDS server for all the ubuntu-clock-app alarms... auto sexp = g_strdup_printf("has-categories? '%s'", TAG_ALARM); e_cal_client_get_object_list_as_comps( client, sexp, m_cancellable.get(), ensure_client_alarms_have_triggers_async_cb, this); g_clear_pointer(&sexp, g_free); } static void ensure_client_alarms_have_triggers_async_cb( GObject * oclient, GAsyncResult * res, gpointer gself) { ECalClient * client = E_CAL_CLIENT(oclient); GError * error = nullptr; GSList * components = nullptr; if (e_cal_client_get_object_list_as_comps_finish(client, res, &components, &error)) { auto self = static_cast(gself); self->ensure_canonical_alarms_have_triggers(client, components); e_cal_client_free_ecalcomp_slist(components); } else if (error != nullptr) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) g_warning("can't get clock-app alarm list: %s", error->message); g_error_free(error); } } void ensure_canonical_alarms_have_triggers(ECalClient * client, GSList * components) { GSList * modify_slist = nullptr; // for each component.. for (auto l=components; l!=nullptr; l=l->next) { bool changed = false; // for each alarm... auto component = E_CAL_COMPONENT(l->data); auto auids = e_cal_component_get_alarm_uids(component); for(auto l=auids; l!=nullptr; l=l->next) { auto auid = static_cast(l->data); auto alarm = e_cal_component_get_alarm(component, auid); if (alarm == nullptr) continue; // if the alarm has no trigger, add one. ECalComponentAlarmTrigger trigger; e_cal_component_alarm_get_trigger(alarm, &trigger); if (trigger.type == E_CAL_COMPONENT_ALARM_TRIGGER_NONE) { trigger.type = E_CAL_COMPONENT_ALARM_TRIGGER_RELATIVE_START; trigger.u.rel_duration = icaldurationtype_from_int(0); e_cal_component_alarm_set_trigger (alarm, trigger); changed = true; } g_clear_pointer(&alarm, e_cal_component_alarm_free); } g_clear_pointer(&auids, cal_obj_uid_list_free); if (changed) { auto icc = e_cal_component_get_icalcomponent(component); // icc owned by ecc modify_slist = g_slist_prepend(modify_slist, icc); } } if (modify_slist != nullptr) { e_cal_client_modify_objects(client, modify_slist, E_CAL_OBJ_MOD_ALL, m_cancellable.get(), ensure_canonical_alarms_have_triggers_async_cb, this); g_clear_pointer(&modify_slist, g_slist_free); } } // log a warning if e_cal_client_modify_objects() failed static void ensure_canonical_alarms_have_triggers_async_cb( GObject * oclient, GAsyncResult * res, gpointer /*gself*/) { GError * error = nullptr; e_cal_client_modify_objects_finish (E_CAL_CLIENT(oclient), res, &error); if (error != nullptr) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) g_warning("couldn't add alarm triggers: %s", error->message); g_error_free(error); } } /*** **** ***/ typedef std::function&)> appointment_func; struct Task { Impl* p; appointment_func func; icaltimezone* default_timezone; // pointer owned by libical GTimeZone* gtz; std::vector appointments; const DateTime begin; const DateTime end; Task(Impl* p_in, appointment_func func_in, icaltimezone* tz_in, GTimeZone* gtz_in, const DateTime& begin_in, const DateTime& end_in): p{p_in}, func{func_in}, default_timezone{tz_in}, gtz{gtz_in}, begin{begin_in}, end{end_in} {} ~Task() { g_clear_pointer(>z, g_time_zone_unref); // give the caller the sorted finished product auto& a = appointments; std::sort(a.begin(), a.end(), [](const Appointment& a, const Appointment& b){return a.begin < b.begin;}); func(a); }; }; struct ClientSubtask { std::shared_ptr task; ECalClient* client; std::shared_ptr cancellable; std::string color; ClientSubtask(const std::shared_ptr& task_in, ECalClient* client_in, const std::shared_ptr& cancellable_in, const char* color_in): task(task_in), client(client_in), cancellable(cancellable_in) { if (color_in) color = color_in; } }; static std::string get_alarm_text(ECalComponentAlarm * alarm) { std::string ret; ECalComponentAlarmAction action; e_cal_component_alarm_get_action(alarm, &action); if (action == E_CAL_COMPONENT_ALARM_DISPLAY) { ECalComponentText text {}; e_cal_component_alarm_get_description(alarm, &text); if (text.value) ret = text.value; } return ret; } static std::string get_alarm_sound_url(ECalComponentAlarm * alarm) { std::string ret; ECalComponentAlarmAction action; e_cal_component_alarm_get_action(alarm, &action); if (action == E_CAL_COMPONENT_ALARM_AUDIO) { icalattach* attach = nullptr; e_cal_component_alarm_get_attach(alarm, &attach); if (attach != nullptr) { if (icalattach_get_is_url (attach)) { const char* url = icalattach_get_url(attach); if (url != nullptr) ret = url; } icalattach_unref(attach); } } return ret; } static void on_alarm_component_list_ready(GObject * oclient, GAsyncResult * res, gpointer gsubtask) { GError * error = NULL; GSList * comps_slist = NULL; auto subtask = static_cast(gsubtask); if (e_cal_client_get_object_list_as_comps_finish(E_CAL_CLIENT(oclient), res, &comps_slist, &error)) { // _generate_alarms takes a GList, so make a shallow one GList * comps_list = nullptr; for (auto l=comps_slist; l!=nullptr; l=l->next) comps_list = g_list_prepend(comps_list, l->data); constexpr std::array omit = { (ECalComponentAlarmAction)-1 }; // list of action types to omit, terminated with -1 GSList * comp_alarms = nullptr; e_cal_util_generate_alarms_for_list( comps_list, subtask->task->begin.to_unix(), subtask->task->end.to_unix(), const_cast(omit.data()), &comp_alarms, e_cal_client_resolve_tzid_cb, oclient, subtask->task->default_timezone); // walk the alarms & add them for (auto l=comp_alarms; l!=nullptr; l=l->next) add_alarms_to_subtask(static_cast(l->data), subtask, subtask->task->gtz); // cleanup e_cal_free_alarms(comp_alarms); g_list_free(comps_list); e_cal_client_free_ecalcomp_slist(comps_slist); } else if (error != nullptr) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) g_warning("can't get ecalcomponent list: %s", error->message); g_error_free(error); } delete subtask; } static void on_event_component_list_ready(GObject * oclient, GAsyncResult * res, gpointer gsubtask) { GError * error = NULL; GSList * comps_slist = NULL; auto subtask = static_cast(gsubtask); if (e_cal_client_get_object_list_as_comps_finish(E_CAL_CLIENT(oclient), res, &comps_slist, &error)) { for (auto l=comps_slist; l!=nullptr; l=l->next) add_event_to_subtask(static_cast(l->data), subtask, subtask->task->gtz); e_cal_client_free_ecalcomp_slist(comps_slist); } else if (error != nullptr) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) g_warning("can't get ecalcomponent list: %s", error->message); g_error_free(error); } delete subtask; } static DateTime datetime_from_component_date_time(ECalClient * client, std::shared_ptr & cancellable, const ECalComponentDateTime & in, GTimeZone * default_timezone) { DateTime out; g_return_val_if_fail(in.value != nullptr, out); GTimeZone * gtz {}; if (in.tzid != nullptr) { auto itz = icaltimezone_get_builtin_timezone_from_tzid(in.tzid); // usually works if (itz == nullptr) // fallback itz = icaltimezone_get_builtin_timezone(in.tzid); if (itz == nullptr) // ok we have a strange tzid... ask EDS to look it up in VTIMEZONES e_cal_client_get_timezone_sync(client, in.tzid, &itz, cancellable.get(), nullptr); const char* identifier {}; if (itz != nullptr) { identifier = icaltimezone_get_display_name(itz); if (identifier == nullptr) identifier = icaltimezone_get_location(itz); } // handle the TZID /freeassociation.sourceforge.net/Tzfile/[Location] case if (identifier != nullptr) { const char* pch; const char* key = "/freeassociation.sourceforge.net/"; if ((pch = strstr(identifier, key))) { identifier = pch + strlen(key); key = "Tzfile/"; // some don't have this, so check for it separately if ((pch = strstr(identifier, key))) identifier = pch + strlen(key); } } if (identifier == nullptr) g_warning("Unrecognized TZID: '%s'", in.tzid); gtz = g_time_zone_new(identifier); g_debug("%s eccdt.tzid -> offset is %d", G_STRLOC, in.tzid, (int)g_time_zone_get_offset(gtz,0)); } else { gtz = g_time_zone_ref(default_timezone); } out = DateTime(gtz, in.value->year, in.value->month, in.value->day, in.value->hour, in.value->minute, in.value->second); g_time_zone_unref(gtz); return out; } static bool is_component_interesting(ECalComponent * component) { // we only want calendar events and vtodos const auto vtype = e_cal_component_get_vtype(component); if ((vtype != E_CAL_COMPONENT_EVENT) && (vtype != E_CAL_COMPONENT_TODO)) return false; // we're not interested in completed or cancelled components auto status = ICAL_STATUS_NONE; e_cal_component_get_status(component, &status); if ((status == ICAL_STATUS_COMPLETED) || (status == ICAL_STATUS_CANCELLED)) return false; // we don't want disabled alarms bool disabled = false; GSList * categ_list = nullptr; e_cal_component_get_categories_list (component, &categ_list); for (GSList * l=categ_list; l!=nullptr; l=l->next) { auto tag = static_cast(l->data); if (!g_strcmp0(tag, TAG_DISABLED)) disabled = true; } e_cal_component_free_categories_list(categ_list); if (disabled) return false; return true; } static Appointment get_appointment(ECalClient * client, std::shared_ptr & cancellable, ECalComponent * component, GTimeZone * gtz) { Appointment baseline; // get appointment.uid const gchar* uid = nullptr; e_cal_component_get_uid(component, &uid); if (uid != nullptr) baseline.uid = uid; // get source uid ESource *source = nullptr; g_object_get(G_OBJECT(client), "source", &source, nullptr); if (source != nullptr) { baseline.source_uid = e_source_get_uid(source); g_object_unref(source); } // get appointment.summary ECalComponentText text {}; e_cal_component_get_summary(component, &text); if (text.value) baseline.summary = text.value; // get appointment.begin ECalComponentDateTime eccdt_tmp {}; e_cal_component_get_dtstart(component, &eccdt_tmp); baseline.begin = datetime_from_component_date_time(client, cancellable, eccdt_tmp, gtz); e_cal_component_free_datetime(&eccdt_tmp); // get appointment.end e_cal_component_get_dtend(component, &eccdt_tmp); baseline.end = eccdt_tmp.value != nullptr ? datetime_from_component_date_time(client, cancellable, eccdt_tmp, gtz) : baseline.begin; e_cal_component_free_datetime(&eccdt_tmp); // get appointment.activation_url from x-props auto icc = e_cal_component_get_icalcomponent(component); // icc owned by component auto icalprop = icalcomponent_get_first_property(icc, ICAL_X_PROPERTY); while (icalprop != nullptr) { const char * x_name = icalproperty_get_x_name(icalprop); if ((x_name != nullptr) && !g_ascii_strcasecmp(x_name, X_PROP_ACTIVATION_URL)) { const char * url = icalproperty_get_value_as_string(icalprop); if ((url != nullptr) && baseline.activation_url.empty()) baseline.activation_url = url; } icalprop = icalcomponent_get_next_property(icc, ICAL_X_PROPERTY); } // get appointment.type baseline.type = Appointment::EVENT; GSList * categ_list = nullptr; e_cal_component_get_categories_list (component, &categ_list); for (GSList * l=categ_list; l!=nullptr; l=l->next) { auto tag = static_cast(l->data); if (!g_strcmp0(tag, TAG_ALARM)) baseline.type = Appointment::UBUNTU_ALARM; } e_cal_component_free_categories_list(categ_list); g_debug("%s got appointment from %s to %s: %s", G_STRLOC, baseline.begin.format("%F %T %z").c_str(), baseline.end.format("%F %T %z").c_str(), icalcomponent_as_ical_string(icc) /* string owned by ical */); return baseline; } static void add_event_to_subtask(ECalComponent * component, ClientSubtask * subtask, GTimeZone * gtz) { // events with alarms are covered by add_alarms_to_subtask(), // so skip them here auto auids = e_cal_component_get_alarm_uids(component); const bool has_alarms = auids != nullptr; cal_obj_uid_list_free(auids); if (has_alarms) return; // add it. simple, eh? if (is_component_interesting(component)) { Appointment appointment = get_appointment(subtask->client, subtask->cancellable, component, gtz); appointment.color = subtask->color; subtask->task->appointments.push_back(appointment); } } static void add_alarms_to_subtask(ECalComponentAlarms * comp_alarms, ClientSubtask * subtask, GTimeZone * gtz) { auto& component = comp_alarms->comp; if (!is_component_interesting(component)) return; Appointment baseline = get_appointment(subtask->client, subtask->cancellable, component, gtz); baseline.color = subtask->color; /** *** Now loop through comp_alarms to get information that we need *** to build the instance appointments and their alarms. *** *** Outer map key is the instance component's start + end time. *** We build Appointment.begin and .end from that. *** *** inner map key is the alarm trigger, we build Alarm.time from that. *** *** inner map value is the Alarm. *** *** We map the alarms based on their trigger time so that we *** can fold together multiple valarms that trigger for the *** same componeng at the same time. This is commonplace; *** e.g. one valarm will have a display action and another *** will specify a sound to be played. */ std::map,std::map> alarms; for (auto l=comp_alarms->alarms; l!=nullptr; l=l->next) { auto ai = static_cast(l->data); auto a = e_cal_component_get_alarm(component, ai->auid); if (a == nullptr) continue; auto instance_time = std::make_pair(DateTime{gtz, ai->occur_start}, DateTime{gtz, ai->occur_end}); auto trigger_time = DateTime{gtz, ai->trigger}; auto& alarm = alarms[instance_time][trigger_time]; if (alarm.text.empty()) alarm.text = get_alarm_text(a); if (alarm.audio_url.empty()) alarm.audio_url = get_alarm_sound_url(a); if (!alarm.time.is_set()) alarm.time = trigger_time; e_cal_component_alarm_free(a); } for (auto& i : alarms) { Appointment appointment = baseline; appointment.begin = i.first.first; appointment.end = i.first.second; appointment.alarms.reserve(i.second.size()); for (auto& j : i.second) appointment.alarms.push_back(j.second); subtask->task->appointments.push_back(appointment); } } /*** **** ***/ static void on_object_ready_for_disable(GObject * client, GAsyncResult * result, gpointer gself) { icalcomponent * icc = nullptr; if (e_cal_client_get_object_finish (E_CAL_CLIENT(client), result, &icc, nullptr)) { auto rrule_property = icalcomponent_get_first_property (icc, ICAL_RRULE_PROPERTY); // transfer none auto rdate_property = icalcomponent_get_first_property (icc, ICAL_RDATE_PROPERTY); // transfer none const bool is_nonrepeating = (rrule_property == nullptr) && (rdate_property == nullptr); if (is_nonrepeating) { g_debug("'%s' appears to be a one-time alarm... adding 'disabled' tag.", icalcomponent_as_ical_string(icc)); auto ecc = e_cal_component_new_from_icalcomponent (icc); // takes ownership of icc icc = nullptr; if (ecc != nullptr) { // add TAG_DISABLED to the list of categories GSList * old_categories = nullptr; e_cal_component_get_categories_list(ecc, &old_categories); auto new_categories = g_slist_copy(old_categories); new_categories = g_slist_append(new_categories, const_cast(TAG_DISABLED)); e_cal_component_set_categories_list(ecc, new_categories); g_slist_free(new_categories); e_cal_component_free_categories_list(old_categories); e_cal_client_modify_object(E_CAL_CLIENT(client), e_cal_component_get_icalcomponent(ecc), E_CAL_OBJ_MOD_THIS, static_cast(gself)->m_cancellable.get(), on_disable_done, nullptr); g_clear_object(&ecc); } } g_clear_pointer(&icc, icalcomponent_free); } } static void on_disable_done (GObject* gclient, GAsyncResult *res, gpointer) { GError * error = nullptr; if (!e_cal_client_modify_object_finish (E_CAL_CLIENT(gclient), res, &error)) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) g_warning("indicator-datetime cannot mark one-time alarm as disabled: %s", error->message); g_error_free(error); } } /*** **** ***/ core::Signal<> m_changed; std::set m_sources; std::map m_clients; std::map m_views; std::shared_ptr m_cancellable; ESourceRegistry* m_source_registry {}; guint m_rebuild_tag {}; time_t m_rebuild_deadline {}; }; /*** **** ***/ EdsEngine::EdsEngine(): p(new Impl()) { } EdsEngine::~EdsEngine() =default; core::Signal<>& EdsEngine::changed() { return p->changed(); } void EdsEngine::get_appointments(const DateTime& begin, const DateTime& end, const Timezone& tz, std::function&)> func) { p->get_appointments(begin, end, tz, func); } void EdsEngine::disable_ubuntu_alarm(const Appointment& appointment) { p->disable_ubuntu_alarm(appointment); } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/date-time.cpp0000644000015600001650000001520312701256660014247 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include namespace unity { namespace indicator { namespace datetime { /*** **** ***/ DateTime::DateTime() { } DateTime::DateTime(GTimeZone* gtz, GDateTime* gdt) { g_return_if_fail(gtz!=nullptr); g_return_if_fail(gdt!=nullptr); reset(gtz, gdt); } DateTime::DateTime(GTimeZone* gtz, int year, int month, int day, int hour, int minute, double seconds) { g_return_if_fail(gtz!=nullptr); auto gdt = g_date_time_new(gtz, year, month, day, hour, minute, seconds); reset(gtz, gdt); g_date_time_unref(gdt); } DateTime& DateTime::operator=(const DateTime& that) { m_tz = that.m_tz; m_dt = that.m_dt; return *this; } DateTime& DateTime::operator+=(const std::chrono::minutes& minutes) { return (*this = add_full(0, 0, 0, 0, minutes.count(), 0)); } DateTime& DateTime::operator+=(const std::chrono::seconds& seconds) { return (*this = add_full(0, 0, 0, 0, 0, seconds.count())); } DateTime::DateTime(GTimeZone* gtz, time_t t) { auto utc = g_date_time_new_from_unix_utc(t); auto gdt = g_date_time_to_timezone (utc, gtz); reset(gtz, gdt); g_date_time_unref(gdt); g_date_time_unref(utc); } DateTime DateTime::NowLocal() { auto gtz = g_time_zone_new_local(); auto gdt = g_date_time_new_now(gtz); DateTime dt(gtz, gdt); g_time_zone_unref(gtz); g_date_time_unref(gdt); return dt; } DateTime DateTime::Local(time_t t) { auto gtz = g_time_zone_new_local(); auto gdt = g_date_time_new_from_unix_local(t); DateTime dt(gtz, gdt); g_time_zone_unref(gtz); g_date_time_unref(gdt); return dt; } DateTime DateTime::Local(int year, int month, int day, int hour, int minute, double seconds) { auto gtz = g_time_zone_new_local(); DateTime dt(gtz, year, month, day, hour, minute, seconds); g_time_zone_unref(gtz); return dt; } DateTime DateTime::to_timezone(const std::string& zone) const { auto gtz = g_time_zone_new(zone.c_str()); auto gdt = g_date_time_to_timezone(get(), gtz); DateTime dt(gtz, gdt); g_time_zone_unref(gtz); g_date_time_unref(gdt); return dt; } DateTime DateTime::end_of_day() const { g_assert(is_set()); return add_days(1).start_of_day().add_full(0,0,0,0,0,-1); } DateTime DateTime::end_of_month() const { g_assert(is_set()); return add_full(0,1,0,0,0,0).start_of_month().add_full(0,0,0,0,0,-1); } DateTime DateTime::start_of_month() const { g_assert(is_set()); int year=0, month=0, day=0; ymd(year, month, day); return DateTime(m_tz.get(), year, month, 1, 0, 0, 0); } DateTime DateTime::start_of_day() const { g_assert(is_set()); int year=0, month=0, day=0; ymd(year, month, day); return DateTime(m_tz.get(), year, month, day, 0, 0, 0); } DateTime DateTime::start_of_minute() const { g_assert(is_set()); int year=0, month=0, day=0; ymd(year, month, day); return DateTime(m_tz.get(), year, month, day, hour(), minute(), 0); } DateTime DateTime::add_full(int year, int month, int day, int hour, int minute, double seconds) const { auto gdt = g_date_time_add_full(get(), year, month, day, hour, minute, seconds); DateTime dt(m_tz.get(), gdt); g_date_time_unref(gdt); return dt; } DateTime DateTime::add_days(int days) const { return add_full(0, 0, days, 0, 0, 0); } GDateTime* DateTime::get() const { g_assert(m_dt); return m_dt.get(); } std::string DateTime::format(const std::string& fmt) const { std::string ret; gchar* str = g_date_time_format(get(), fmt.c_str()); if (str) { ret = str; g_free(str); } return ret; } void DateTime::ymd(int& year, int& month, int& day) const { g_date_time_get_ymd(get(), &year, &month, &day); } int DateTime::day_of_month() const { return g_date_time_get_day_of_month(get()); } int DateTime::hour() const { return g_date_time_get_hour(get()); } int DateTime::minute() const { return g_date_time_get_minute(get()); } double DateTime::seconds() const { return g_date_time_get_seconds(get()); } int64_t DateTime::to_unix() const { return g_date_time_to_unix(get()); } void DateTime::reset(GTimeZone* gtz, GDateTime* gdt) { g_return_if_fail (gdt!=nullptr); g_return_if_fail (gtz!=nullptr); auto tz_deleter = [](GTimeZone* tz){g_time_zone_unref(tz);}; m_tz = std::shared_ptr(g_time_zone_ref(gtz), tz_deleter); auto dt_deleter = [](GDateTime* dt){g_date_time_unref(dt);}; m_dt = std::shared_ptr(g_date_time_ref(gdt), dt_deleter); } bool DateTime::operator<(const DateTime& that) const { return g_date_time_compare(get(), that.get()) < 0; } bool DateTime::operator<=(const DateTime& that) const { return g_date_time_compare(get(), that.get()) <= 0; } bool DateTime::operator!=(const DateTime& that) const { // return true if this isn't set, or if it's not equal return (!m_dt) || !(*this == that); } bool DateTime::operator==(const DateTime& that) const { auto dt = get(); auto tdt = that.get(); if (!dt && !tdt) return true; if (!dt || !tdt) return false; return g_date_time_compare(get(), that.get()) == 0; } int64_t DateTime::operator- (const DateTime& that) const { return g_date_time_difference(get(), that.get()); } bool DateTime::is_same_day(const DateTime& a, const DateTime& b) { // it's meaningless to compare uninitialized dates if (!a.m_dt || !b.m_dt) return false; int ay, am, ad; int by, bm, bd; g_date_time_get_ymd(a.get(), &ay, &am, &ad); g_date_time_get_ymd(b.get(), &by, &bm, &bd); return (ay==by) && (am==bm) && (ad==bd); } bool DateTime::is_same_minute(const DateTime& a, const DateTime& b) { if (!is_same_day(a,b)) return false; const auto adt = a.get(); const auto bdt = b.get(); return (g_date_time_get_hour(adt) == g_date_time_get_hour(bdt)) && (g_date_time_get_minute(adt) == g_date_time_get_minute(bdt)); } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/formatter-desktop.cpp0000644000015600001650000001444112701256660016053 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include // T_() namespace unity { namespace indicator { namespace datetime { /*** **** ***/ namespace { std::string joinDateAndTimeFormatStrings(const char* date_string, const char* time_string) { std::string str; if (date_string && time_string) { str = date_string; str += "\u2003"; str += time_string; } else if (date_string) { str = date_string; } else // time_string { str = time_string; } return str; } } // unnamed namespace /*** **** ***/ DesktopFormatter::DesktopFormatter(const std::shared_ptr& clock_in, const std::shared_ptr& settings_in): Formatter(clock_in), m_settings(settings_in) { m_settings->show_day.changed().connect([this](bool){rebuildHeaderFormat();}); m_settings->show_date.changed().connect([this](bool){rebuildHeaderFormat();}); m_settings->show_year.changed().connect([this](bool){rebuildHeaderFormat();}); m_settings->show_seconds.changed().connect([this](bool){rebuildHeaderFormat();}); m_settings->time_format_mode.changed().connect([this](TimeFormatMode){rebuildHeaderFormat();}); m_settings->custom_time_format.changed().connect([this](const std::string&){rebuildHeaderFormat();}); rebuildHeaderFormat(); } void DesktopFormatter::rebuildHeaderFormat() { header_format.set(getHeaderLabelFormatString()); } std::string DesktopFormatter::getHeaderLabelFormatString() const { std::string fmt; const auto mode = m_settings->time_format_mode.get(); if (mode == TIME_FORMAT_MODE_CUSTOM) { fmt = m_settings->custom_time_format.get(); } else { const auto show_day = m_settings->show_day.get(); const auto show_date = m_settings->show_date.get(); const auto show_year = show_date && m_settings->show_year.get(); const auto date_fmt = getDateFormat(show_day, show_date, show_year); const auto time_fmt = getFullTimeFormatString(); fmt = joinDateAndTimeFormatStrings(date_fmt, time_fmt); } return fmt; } const gchar* DesktopFormatter::getFullTimeFormatString() const { const auto show_seconds = m_settings->show_seconds.get(); bool twelvehour; switch (m_settings->time_format_mode.get()) { case TIME_FORMAT_MODE_LOCALE_DEFAULT: twelvehour = is_locale_12h(); break; case TIME_FORMAT_MODE_24_HOUR: twelvehour = false; break; default: twelvehour = true; break; } return default_header_time_format(twelvehour, show_seconds); } const gchar* DesktopFormatter::getDateFormat(bool show_day, bool show_date, bool show_year) const { const char * fmt; if (show_day && show_date && show_year) /* Translators, please edit/rearrange these strftime(3) tokens to suit your locale! That will fix bug #1001595 for your locale and make the date/time in the upper-right corner of your screen look beautiful :) This format string shows the abbreviated weekday, day, abbreviated month, and year. en_US example: "%a %b %e %Y" --> "Sat Oct 31 2020" en_GB example: "%a %e %b %Y" --> "Sat 31 Oct 2020" zh_CN example(?): "%Y年%m月%d日 周%a" --> "2020年10月31日 周六" */ fmt = T_("%a %b %e %Y"); else if (show_day && show_date) /* Translators, please edit/rearrange these strftime(3) tokens to suit your locale! That will fix bug #1001595 for your locale and make the date/time in the upper-right corner of your screen look beautiful :) This format string shows the abbreviated weekday, day, and abbreviated month. en_US example: "%a %b %e" --> "Sat Oct 31" en_GB example: "%a %e %b" --> "Sat 31 Oct" zh_CN example(?): "%m月%d日 周%a" --> "03月27日 周六" */ fmt = T_("%a %b %e"); else if (show_day) /* Translators, please edit/rearrange these strftime(3) tokens to suit your locale! That will fix bug #1001595 for your locale and make the date/time in the upper-right corner of your screen look beautiful :) This format string shows the abbreviated weekday. zh_CN example(?): "周%a" --> "周六" */ fmt = T_("%a"); else if (show_date && show_year) /* Translators, please edit/rearrange these strftime(3) tokens to suit your locale! That will fix bug #1001595 for your locale and make the date/time in the upper-right corner of your screen look beautiful :) This format string shows the day, abbreviated month, and year. en_US example: "%b %e %Y" --> "Oct 31 2020" en_GB example: "%e %b %Y" --> "31 Oct 2020" zh_CN example(?): "%Y年%m月%d日" --> "2020年10月31日" */ fmt = T_("%b %e %Y"); else if (show_date) /* Translators, please edit/rearrange these strftime(3) tokens to suit your locale! That will fix bug #1001595 for your locale and make the date/time in the upper-right corner of your screen look beautiful :) This format string shows the abbreviated month and day. en_US example: "%b %e" --> "Mar 27" en_GB example: "%e %b" --> "27 Mar" zh_CN example(?): "%m月%d日" --> "03月27日" */ fmt = T_("%b %e"); else if (show_year) /* This strftime(3) format string shows the year. */ fmt = T_("%Y"); else fmt = nullptr; return fmt; } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/planner.cpp0000644000015600001650000000224712701256660014041 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include namespace unity { namespace indicator { namespace datetime { /*** **** ***/ Planner::Planner() { } Planner::~Planner() { } void Planner::sort(std::vector& appts) { std::sort(std::begin(appts), std::end(appts), [](const Appointment& a, const Appointment& b){return a.begin < b.begin;}); } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/timezones-live.cpp0000644000015600001650000000366512701256660015361 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include namespace unity { namespace indicator { namespace datetime { LiveTimezones::LiveTimezones(const std::shared_ptr& settings): m_file(), m_settings(settings) { m_file.timezone.changed().connect([this](const std::string&){update_timezones();}); m_settings->show_detected_location.changed().connect([this](bool){update_geolocation();}); update_geolocation(); update_timezones(); } void LiveTimezones::update_geolocation() { // clear the previous pointer, if any m_geo.reset(); // if location detection is enabled, turn on GeoClue if(m_settings->show_detected_location.get()) { auto geo = new GeoclueTimezone(); geo->timezone.changed().connect([this](const std::string&){update_timezones();}); m_geo.reset(geo); } } void LiveTimezones::update_timezones() { const auto a = m_file.timezone.get(); const auto b = m_geo ? m_geo->timezone.get() : ""; timezone.set(a.empty() ? b : a); std::set zones; if (!a.empty()) zones.insert(a); if (!b.empty()) zones.insert(b); timezones.set(zones); } } // namespace datetime } // namespace indicator } // namespace unity ./src/snap.cpp0000644000015600001650000002266412701256660013350 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include "dbus-accounts-sound.h" #include #include // is_locale_12h() #include #include #include #include #include #include #include #include #include // getuid() #include // getuid() namespace uin = unity::indicator::notifications; namespace unity { namespace indicator { namespace datetime { /*** **** ***/ class Snap::Impl { public: Impl(const std::shared_ptr& engine, const std::shared_ptr& sound_builder, const std::shared_ptr& settings): m_engine(engine), m_sound_builder(sound_builder), m_settings(settings), m_cancellable(g_cancellable_new()) { auto object_path = g_strdup_printf("/org/freedesktop/Accounts/User%lu", (gulong)getuid()); accounts_service_sound_proxy_new_for_bus(G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_GET_INVALIDATED_PROPERTIES, "org.freedesktop.Accounts", object_path, m_cancellable, on_sound_proxy_ready, this); g_free(object_path); } ~Impl() { g_cancellable_cancel(m_cancellable); g_clear_object(&m_cancellable); g_clear_object(&m_accounts_service_sound_proxy); for (const auto& key : m_notifications) m_engine->close (key); } void operator()(const Appointment& appointment, const Alarm& alarm, appointment_func snooze, appointment_func ok) { // If calendar notifications are muted, don't show them if (!appointment.is_ubuntu_alarm() && calendar_events_are_muted()) { g_debug("Skipping muted calendar event '%s' notification", appointment.summary.c_str()); return; } /* Alarms and calendar events are treated differently. Alarms should require manual intervention to dismiss. Calendar events are less urgent and shouldn't require manual intervention and shouldn't loop the sound. */ const bool interactive = appointment.is_ubuntu_alarm() && m_engine->supports_actions(); // force the system to stay awake auto awake = std::make_shared(m_engine->app_name()); // calendar events are muted in silent mode; alarm clocks never are std::shared_ptr sound; if (appointment.is_ubuntu_alarm() || !silent_mode()) { // create the sound. const auto role = appointment.is_ubuntu_alarm() ? "alarm" : "alert"; const auto uri = get_alarm_uri(appointment, alarm, m_settings); const auto volume = m_settings->alarm_volume.get(); const bool loop = interactive; sound = m_sound_builder->create(role, uri, volume, loop); } // create the haptic feedback... std::shared_ptr haptic; if (should_vibrate()) { const auto haptic_mode = m_settings->alarm_haptic.get(); if (haptic_mode == "pulse") haptic = std::make_shared(uin::Haptic::MODE_PULSE); } // show a notification... const auto minutes = std::chrono::minutes(m_settings->alarm_duration.get()); uin::Builder b; b.set_body (appointment.summary); b.set_icon_name (appointment.is_ubuntu_alarm() ? "alarm-clock" : "reminder"); b.add_hint (uin::Builder::HINT_NONSHAPED_ICON); const char * timefmt; if (is_locale_12h()) { /** strftime(3) format for abbreviated weekday, hours, minutes in a 12h locale; e.g. Wed, 2:00 PM */ timefmt = _("%a, %l:%M %p"); } else { /** A strftime(3) format for abbreviated weekday, hours, minutes in a 24h locale; e.g. Wed, 14:00 */ timefmt = _("%a, %H:%M"); } const auto timestr = appointment.begin.format(timefmt); const auto titlefmt = appointment.is_ubuntu_alarm() ? _("Alarm %s") : _("Event %s"); auto title = g_strdup_printf(titlefmt, timestr.c_str()); b.set_title (title); g_free (title); b.set_timeout (std::chrono::duration_cast(minutes)); if (interactive) { b.add_hint (uin::Builder::HINT_SNAP); b.add_hint (uin::Builder::HINT_AFFIRMATIVE_HINT); b.add_action ("ok", _("OK")); b.add_action ("snooze", _("Snooze")); } // add 'sound', 'haptic', and 'awake' objects to the capture so // they stay alive until the closed callback is called; i.e., // for the lifespan of the notficiation b.set_closed_callback([appointment, alarm, snooze, ok, sound, awake, haptic] (const std::string& action){ if (action == "snooze") snooze(appointment, alarm); else ok(appointment, alarm); }); const auto key = m_engine->show(b); if (key) m_notifications.insert (key); } private: bool calendar_events_are_muted() const { for(const auto& app : m_settings->muted_apps.get()) { if (app.first == "com.ubuntu.calendar") { return true; } } return false; } static void on_sound_proxy_ready(GObject* /*source_object*/, GAsyncResult* res, gpointer gself) { GError * error; error = nullptr; auto proxy = accounts_service_sound_proxy_new_for_bus_finish (res, &error); if (error != nullptr) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) g_warning("%s Couldn't find accounts service sound proxy: %s", G_STRLOC, error->message); g_clear_error(&error); } else { static_cast(gself)->m_accounts_service_sound_proxy = proxy; } } bool silent_mode() const { return (m_accounts_service_sound_proxy != nullptr) && (accounts_service_sound_get_silent_mode(m_accounts_service_sound_proxy)); } bool should_vibrate() const { return (m_accounts_service_sound_proxy != nullptr) && (accounts_service_sound_get_other_vibrate(m_accounts_service_sound_proxy)); } std::string get_alarm_uri(const Appointment& appointment, const Alarm& alarm, const std::shared_ptr& settings) const { const auto is_alarm = appointment.is_ubuntu_alarm(); const std::string candidates[] = { alarm.audio_url, is_alarm ? settings->alarm_sound.get() : settings->calendar_sound.get(), is_alarm ? ALARM_DEFAULT_SOUND : CALENDAR_DEFAULT_SOUND }; std::string uri; for(const auto& candidate : candidates) { if (gst_uri_is_valid (candidate.c_str())) { uri = candidate; break; } else if (g_file_test(candidate.c_str(), G_FILE_TEST_EXISTS)) { gchar* tmp = gst_filename_to_uri(candidate.c_str(), nullptr); if (tmp != nullptr) { uri = tmp; g_free (tmp); break; } } } return uri; } const std::shared_ptr m_engine; const std::shared_ptr m_sound_builder; const std::shared_ptr m_settings; std::set m_notifications; GCancellable * m_cancellable {nullptr}; AccountsServiceSound * m_accounts_service_sound_proxy {nullptr}; }; /*** **** ***/ Snap::Snap(const std::shared_ptr& engine, const std::shared_ptr& sound_builder, const std::shared_ptr& settings): impl(new Impl(engine, sound_builder, settings)) { } Snap::~Snap() { } void Snap::operator()(const Appointment& appointment, const Alarm& alarm, appointment_func show, appointment_func ok) { (*impl)(appointment, alarm, show, ok); } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/appointment.cpp0000644000015600001650000000250412701256660014734 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include namespace unity { namespace indicator { namespace datetime { /**** ***** ****/ bool Alarm::operator==(const Alarm& that) const { return (text==that.text) && (audio_url==that.audio_url) && (this->time==that.time); } bool Appointment::operator==(const Appointment& that) const { return (type==that.type) && (uid==that.uid) && (color==that.color) && (summary==that.summary) && (begin==that.begin) && (end==that.end) && (alarms==that.alarms); } /**** ***** ****/ } // namespace datetime } // namespace indicator } // namespace unity ./src/actions.cpp0000644000015600001650000002216412701256660014042 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include // split_settings_location() #include #include namespace unity { namespace indicator { namespace datetime { /*** **** ***/ namespace { DateTime datetime_from_timet_variant(GVariant* v) { int64_t t = 0; if (v != nullptr) if (g_variant_type_equal(G_VARIANT_TYPE_INT64,g_variant_get_type(v))) t = g_variant_get_int64(v); if (t != 0) return DateTime::Local(t); else return DateTime::NowLocal(); } bool lookup_appointment_by_uid(const std::shared_ptr& state, const gchar* uid, Appointment& setme) { for(const auto& appt : state->calendar_upcoming->appointments().get()) { if (appt.uid == uid) { setme = appt; return true; } } return false; } void on_desktop_appointment_activated (GSimpleAction*, GVariant *vdata, gpointer gself) { auto self = static_cast(gself); Appointment appt; const gchar* uid = nullptr; gint64 time = 0; g_variant_get(vdata, "(&sx)", &uid, &time); if (lookup_appointment_by_uid(self->state(), uid, appt)) self->desktop_open_appointment(appt, DateTime::Local(time)); } void on_desktop_alarm_activated (GSimpleAction*, GVariant*, gpointer gself) { static_cast(gself)->desktop_open_alarm_app(); } void on_desktop_calendar_activated (GSimpleAction*, GVariant* vt, gpointer gself) { const auto dt = datetime_from_timet_variant(vt); static_cast(gself)->desktop_open_calendar_app(dt); } void on_desktop_settings_activated (GSimpleAction*, GVariant*, gpointer gself) { static_cast(gself)->desktop_open_settings_app(); } void on_phone_appointment_activated (GSimpleAction*, GVariant *vdata, gpointer gself) { auto self = static_cast(gself); Appointment appt; const gchar* uid = nullptr; gint64 time = 0; g_variant_get(vdata, "(&sx)", &uid, &time); if (lookup_appointment_by_uid(self->state(), uid, appt)) self->phone_open_appointment(appt, DateTime::Local(time)); } void on_phone_alarm_activated (GSimpleAction*, GVariant*, gpointer gself) { static_cast(gself)->phone_open_alarm_app(); } void on_phone_calendar_activated (GSimpleAction*, GVariant* vt, gpointer gself) { const auto dt = datetime_from_timet_variant(vt); static_cast(gself)->phone_open_calendar_app(dt); } void on_phone_settings_activated (GSimpleAction*, GVariant*, gpointer gself) { static_cast(gself)->phone_open_settings_app(); } void on_set_location(GSimpleAction * /*action*/, GVariant * param, gpointer gself) { char * zone; char * name; split_settings_location(g_variant_get_string(param, nullptr), &zone, &name); static_cast(gself)->set_location(zone, name); g_free(name); g_free(zone); } void on_calendar_active_changed(GSimpleAction * /*action*/, GVariant * state, gpointer gself) { // reset the date when the menu is shown if (g_variant_get_boolean(state)) { auto self = static_cast(gself); self->set_calendar_date(self->state()->clock->localtime()); } } void on_calendar_activated(GSimpleAction * /*action*/, GVariant * state, gpointer gself) { const time_t t = g_variant_get_int64(state); g_return_if_fail(t != 0); auto dt = DateTime::Local(t).start_of_day(); static_cast(gself)->set_calendar_date(dt); } GVariant* create_default_header_state() { GVariantBuilder b; g_variant_builder_init(&b, G_VARIANT_TYPE_VARDICT); g_variant_builder_add(&b, "{sv}", "accessible-desc", g_variant_new_string("accessible-desc")); g_variant_builder_add(&b, "{sv}", "label", g_variant_new_string("label")); g_variant_builder_add(&b, "{sv}", "title", g_variant_new_string("title")); g_variant_builder_add(&b, "{sv}", "visible", g_variant_new_boolean(true)); return g_variant_builder_end(&b); } GVariant* create_calendar_state(const std::shared_ptr& state) { gboolean days[32] = { 0 }; for (const auto& appt : state->calendar_month->appointments().get()) days[appt.begin.day_of_month()] = true; GVariantBuilder day_builder; g_variant_builder_init(&day_builder, G_VARIANT_TYPE("ai")); for (guint i=0; icalendar_month->month().get().to_unix()); g_variant_builder_add(&dict_builder, "{sv}", key, v); key = "show-week-numbers"; v = g_variant_new_boolean(state->settings->show_week_numbers.get()); g_variant_builder_add(&dict_builder, "{sv}", key, v); return g_variant_builder_end(&dict_builder); } } // unnamed namespace /*** **** ***/ Actions::Actions(const std::shared_ptr& state): m_state(state), m_actions(g_simple_action_group_new()) { GActionEntry entries[] = { { "desktop.open-appointment", on_desktop_appointment_activated, "(sx)", nullptr }, { "desktop.open-alarm-app", on_desktop_alarm_activated }, { "desktop.open-calendar-app", on_desktop_calendar_activated, "x", nullptr }, { "desktop.open-settings-app", on_desktop_settings_activated }, { "phone.open-appointment", on_phone_appointment_activated, "(sx)", nullptr }, { "phone.open-alarm-app", on_phone_alarm_activated }, { "phone.open-calendar-app", on_phone_calendar_activated, "x", nullptr }, { "phone.open-settings-app", on_phone_settings_activated }, { "calendar-active", nullptr, nullptr, "false", on_calendar_active_changed }, { "set-location", on_set_location, "s" } }; g_action_map_add_action_entries(G_ACTION_MAP(m_actions), entries, G_N_ELEMENTS(entries), this); // add the header actions auto gam = G_ACTION_MAP(m_actions); auto v = create_default_header_state(); auto a = g_simple_action_new_stateful("desktop-header", nullptr, v); g_action_map_add_action(gam, G_ACTION(a)); g_object_unref(a); a = g_simple_action_new_stateful("desktop_greeter-header", nullptr, v); g_action_map_add_action(gam, G_ACTION(a)); g_object_unref(a); a = g_simple_action_new_stateful("phone-header", nullptr, v); g_action_map_add_action(gam, G_ACTION(a)); g_object_unref(a); a = g_simple_action_new_stateful("phone_greeter-header", nullptr, v); g_action_map_add_action(gam, G_ACTION(a)); g_object_unref(a); // add the calendar action v = create_calendar_state(state); a = g_simple_action_new_stateful("calendar", G_VARIANT_TYPE_INT64, v); g_action_map_add_action(gam, G_ACTION(a)); g_signal_connect(a, "activate", G_CALLBACK(on_calendar_activated), this); g_object_unref(a); /// /// Keep our GActionGroup's action's states in sync with m_state /// m_state->calendar_month->month().changed().connect([this](const DateTime&){ update_calendar_state(); }); m_state->calendar_month->appointments().changed().connect([this](const std::vector&){ update_calendar_state(); }); m_state->settings->show_week_numbers.changed().connect([this](bool){ update_calendar_state(); }); // FIXME: rebuild the calendar state when show-week-number changes } Actions::~Actions() { g_clear_object(&m_actions); } void Actions::update_calendar_state() { g_action_group_change_action_state(action_group(), "calendar", create_calendar_state(m_state)); } void Actions::set_calendar_date(const DateTime& date) { m_state->calendar_month->month().set(date); m_state->calendar_upcoming->date().set(date); } GActionGroup* Actions::action_group() { return G_ACTION_GROUP(m_actions); } const std::shared_ptr Actions::state() const { return m_state; } } // namespace datetime } // namespace indicator } // namespace unity ./src/planner-month.cpp0000644000015600001650000000325412701256660015163 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include namespace unity { namespace indicator { namespace datetime { /*** **** ***/ MonthPlanner::MonthPlanner(const std::shared_ptr& range_planner, const DateTime& month_in): m_range_planner(range_planner) { month().changed().connect([this](const DateTime& m){ auto month_begin = m.start_of_month(); auto month_end = m.end_of_month(); g_debug("PlannerMonth %p setting calendar month range: [%s..%s]", this, month_begin.format("%F %T").c_str(), month_end.format("%F %T").c_str()); m_range_planner->range().set(std::pair(month_begin,month_end)); }); month().set(month_in); } core::Property& MonthPlanner::month() { return m_month; } core::Property>& MonthPlanner::appointments() { return m_range_planner->appointments(); } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/wakeup-timer-powerd.cpp0000644000015600001650000002313412701256660016310 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include // BUS_POWERD_NAME #include #include // std::shared_ptr namespace unity { namespace indicator { namespace datetime { /*** **** ***/ class PowerdWakeupTimer::Impl { public: Impl(const std::shared_ptr& clock): m_clock(clock), m_cancellable(g_cancellable_new()) { g_bus_get(G_BUS_TYPE_SYSTEM, m_cancellable, on_bus_ready, this); } ~Impl() { clear_current_cookie(); g_cancellable_cancel(m_cancellable); g_clear_object(&m_cancellable); if (m_sub_id) g_dbus_connection_signal_unsubscribe(m_bus.get(), m_sub_id); if (m_watch_tag) g_bus_unwatch_name(m_watch_tag); } void set_wakeup_time(const DateTime& d) { m_wakeup_time = d; update_cookie(); } core::Signal<>& timeout() { return m_timeout; } private: void emit_timeout() { return m_timeout(); } static void on_bus_ready(GObject * /*unused*/, GAsyncResult * res, gpointer gself) { GError * error; GDBusConnection * bus; error = nullptr; bus = g_bus_get_finish(res, &error); if (bus == nullptr) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) g_warning("%s Couldn't get system bus: %s", G_STRLOC, error->message); } else { static_cast(gself)->init_bus(bus); } g_clear_object(&bus); g_clear_error(&error); } void init_bus(GDBusConnection* connection) { m_bus.reset(G_DBUS_CONNECTION(g_object_ref(G_OBJECT(connection))), [](GDBusConnection *c){g_object_unref(G_OBJECT(c));}); m_sub_id = g_dbus_connection_signal_subscribe(m_bus.get(), BUS_POWERD_NAME, BUS_POWERD_INTERFACE, "Wakeup", BUS_POWERD_PATH, nullptr, G_DBUS_SIGNAL_FLAGS_NONE, on_wakeup_signal, this, // userdata nullptr); // userdata free m_watch_tag = g_bus_watch_name_on_connection(m_bus.get(), BUS_POWERD_NAME, G_BUS_NAME_WATCHER_FLAGS_NONE, on_name_appeared_static, nullptr, // name-vanished, this, // userdata nullptr); // userdata free } static void on_wakeup_signal(GDBusConnection * /*connection*/, const gchar * sender_name, const gchar * /*object_path*/, const gchar * /*interface_name*/, const gchar * /*signal_name*/, GVariant * /*parameters*/, gpointer gself) { g_debug("%s %s broadcast a hw wakeup signal", G_STRLOC, sender_name); static_cast(gself)->emit_timeout(); } static void on_name_appeared_static(GDBusConnection * /*connection*/, const gchar * name, const gchar * name_owner, gpointer gself) { g_debug("%s %s owns %s now; let's ask for a new cookie", G_STRLOC, name, name_owner); static_cast(gself)->update_cookie(); } /*** **** requestWakeup ***/ void update_cookie() { if (!m_bus) return; // if we've already got a cookie, clear it clear_current_cookie(); g_warn_if_fail(m_cookie.empty()); // get a new cookie, if necessary if (m_wakeup_time.is_set()) { g_debug("%s calling %s::requestWakeup(%s)", G_STRLOC, BUS_POWERD_NAME, m_wakeup_time.format("%F %T").c_str()); auto args = g_variant_new("(st)", GETTEXT_PACKAGE, uint64_t(m_wakeup_time.to_unix())); g_dbus_connection_call(m_bus.get(), BUS_POWERD_NAME, BUS_POWERD_PATH, BUS_POWERD_INTERFACE, "requestWakeup", // method_name args, G_VARIANT_TYPE("(s)"), // reply_type G_DBUS_CALL_FLAGS_NONE, -1, // use default timeout m_cancellable, on_request_wakeup_done, this); } } static void on_request_wakeup_done(GObject * o, GAsyncResult * res, gpointer gself) { GError * error; GVariant * ret; error = nullptr; ret = g_dbus_connection_call_finish(G_DBUS_CONNECTION(o), res, &error); if (ret == nullptr) { /* powerd isn't on the desktop, but we don't need hardware wakeups there anyway... so no need to warn on SERVICE_UNKNOWN */ if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED) && !g_error_matches(error, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN)) { g_warning("%s Could not set hardware wakeup: %s", G_STRLOC, error->message); } } else { const char* s = nullptr; g_variant_get(ret, "(&s)", &s); g_debug("%s %s::requestWakeup() sent cookie %s", G_STRLOC, BUS_POWERD_NAME, s); auto& cookie = static_cast(gself)->m_cookie; if (s != nullptr) cookie = s; else cookie.clear(); } // cleanup g_clear_pointer(&ret, g_variant_unref); g_clear_error(&error); } /*** **** clearWakeup ***/ void clear_current_cookie() { if (!m_cookie.empty()) { g_debug("%s calling %s::clearWakeup(%s)", G_STRLOC, BUS_POWERD_NAME, m_cookie.c_str()); g_dbus_connection_call(m_bus.get(), BUS_POWERD_NAME, BUS_POWERD_PATH, BUS_POWERD_INTERFACE, "clearWakeup", // method_name g_variant_new("(s)", m_cookie.c_str()), nullptr, // no response type G_DBUS_CALL_FLAGS_NONE, -1, // use default timeout nullptr, // cancellable on_clear_wakeup_done, nullptr); m_cookie.clear(); } } // this is only here to log errors static void on_clear_wakeup_done(GObject * o, GAsyncResult * res, gpointer /*unused*/) { GError * error; GVariant * ret; error = nullptr; ret = g_dbus_connection_call_finish(G_DBUS_CONNECTION(o), res, &error); if (!ret && !g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) g_warning("%s Couldn't clear hardware wakeup: %s", G_STRLOC, error->message); // cleanup g_clear_pointer(&ret, g_variant_unref); g_clear_error(&error); } /*** **** ***/ core::Signal<> m_timeout; const std::shared_ptr& m_clock; DateTime m_wakeup_time; std::shared_ptr m_bus; GCancellable * m_cancellable = nullptr; std::string m_cookie; guint m_watch_tag = 0; guint m_sub_id = 0; }; /*** **** ***/ PowerdWakeupTimer::PowerdWakeupTimer(const std::shared_ptr& clock): p(new Impl(clock)) { } PowerdWakeupTimer::~PowerdWakeupTimer() { } void PowerdWakeupTimer::set_wakeup_time(const DateTime& d) { p->set_wakeup_time(d); } core::Signal<>& PowerdWakeupTimer::timeout() { return p->timeout(); } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/locations.cpp0000644000015600001650000000276412701256660014401 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include namespace unity { namespace indicator { namespace datetime { const std::string& Location::zone() const { return m_zone; } const std::string& Location::name() const { return m_name; } bool Location::operator== (const Location& that) const { return (m_name == that.m_name) && (m_zone == that.m_zone) && (m_offset == that.m_offset); } Location::Location(const std::string& zone_, const std::string& name_): m_zone(zone_), m_name(name_) { auto gzone = g_time_zone_new (zone().c_str()); auto gtime = g_date_time_new_now (gzone); m_offset = g_date_time_get_utc_offset (gtime); g_date_time_unref (gtime); g_time_zone_unref (gzone); } } // namespace datetime } // namespace indicator } // namespace unity ./src/alarm-queue-simple.cpp0000644000015600001650000001245512701256660016111 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include namespace unity { namespace indicator { namespace datetime { /*** **** ***/ class SimpleAlarmQueue::Impl { public: Impl(const std::shared_ptr& clock, const std::shared_ptr& planner, const std::shared_ptr& timer): m_clock{clock}, m_planner{planner}, m_timer{timer}, m_datetime{clock->localtime()} { m_planner->appointments().changed().connect([this](const std::vector&){ g_debug("AlarmQueue %p calling requeue() due to appointments changed", this); requeue(); }); m_clock->minute_changed.connect([this]{ const auto now = m_clock->localtime(); constexpr auto skew_threshold_usec = int64_t{90} * G_USEC_PER_SEC; const bool clock_jumped = std::abs(now - m_datetime) > skew_threshold_usec; m_datetime = now; if (clock_jumped) { g_debug("AlarmQueue %p calling requeue() due to clock skew", this); requeue(); } }); m_timer->timeout().connect([this](){ g_debug("AlarmQueue %p calling requeue() due to timeout", this); requeue(); }); requeue(); } ~Impl() { } core::Signal& alarm_reached() { return m_alarm_reached; } private: void requeue() { const auto appointments = m_planner->appointments().get(); const Alarm* alarm; // kick any current alarms for (const auto& appointment : appointments) { if ((alarm = appointment_get_current_alarm(appointment))) { m_triggered.insert(std::make_pair(appointment.uid, alarm->time)); m_alarm_reached(appointment, *alarm); } } // idle until the next alarm if ((alarm = find_next_alarm(appointments))) { g_debug ("setting timer to wake up for next appointment '%s' at %s", alarm->text.c_str(), alarm->time.format("%F %T").c_str()); m_timer->set_wakeup_time(alarm->time); } } bool already_triggered (const Appointment& appt, const Alarm& alarm) const { const std::pair key{appt.uid, alarm.time}; return m_triggered.count(key) != 0; } // return the next Alarm (if any) that will kick now or in the future const Alarm* find_next_alarm(const std::vector& appointments) const { const Alarm* best {}; const auto now = m_clock->localtime(); const auto beginning_of_minute = now.start_of_minute(); g_debug ("planner has %zu appointments in it", (size_t)appointments.size()); for(const auto& appointment : appointments) { for(const auto& alarm : appointment.alarms) { if (already_triggered(appointment, alarm)) continue; if (alarm.time < beginning_of_minute) // has this one already passed? continue; if (best && (best->time < alarm.time)) // do we already have a better match? continue; best = &alarm; } } return best; } // return the Appointment's current Alarm (if any) const Alarm* appointment_get_current_alarm(const Appointment& appointment) const { const auto now = m_clock->localtime(); for (const auto& alarm : appointment.alarms) if (!already_triggered(appointment, alarm) && DateTime::is_same_minute(now, alarm.time)) return &alarm; return nullptr; } std::set> m_triggered; const std::shared_ptr m_clock; const std::shared_ptr m_planner; const std::shared_ptr m_timer; core::Signal m_alarm_reached; DateTime m_datetime; }; /*** **** Public API ***/ SimpleAlarmQueue::SimpleAlarmQueue(const std::shared_ptr& clock, const std::shared_ptr& planner, const std::shared_ptr& timer): impl{new Impl{clock, planner, timer}} { } SimpleAlarmQueue::~SimpleAlarmQueue() { } core::Signal& SimpleAlarmQueue::alarm_reached() { return impl->alarm_reached(); } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/clock-live.cpp0000644000015600001650000001316612701256660014434 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include // g_unix_fd_add() #include #include // close() #ifndef TFD_TIMER_CANCEL_ON_SET #define TFD_TIMER_CANCEL_ON_SET (1 << 1) #endif namespace unity { namespace indicator { namespace datetime { /*** **** ***/ class LiveClock::Impl { public: Impl(LiveClock& owner, const std::shared_ptr& timezone_): m_owner(owner), m_timezone(timezone_) { if (m_timezone) { auto setter = [this](const std::string& z){setTimezone(z);}; m_timezone->timezone.changed().connect(setter); setter(m_timezone->timezone.get()); } reset_timer(); refresh(); } ~Impl() { unset_timer(); g_clear_pointer(&m_gtimezone, g_time_zone_unref); } DateTime localtime() const { g_assert(m_gtimezone != nullptr); auto gdt = g_date_time_new_now(m_gtimezone); DateTime ret(m_gtimezone, gdt); g_date_time_unref(gdt); return ret; } private: void unset_timer() { if (m_timerfd_tag != 0) { g_source_remove(m_timerfd_tag); m_timerfd_tag = 0; } if (m_timerfd != -1) { close(m_timerfd); m_timerfd = -1; } } void reset_timer() { // clear out any previous timer unset_timer(); // create a new timer m_timerfd = timerfd_create(CLOCK_REALTIME, 0); if (m_timerfd == -1) g_error("unable to create realtime timer: %s", g_strerror(errno)); // set args to fire at the beginning of the next minute... struct itimerspec timerval; int flags = TFD_TIMER_ABSTIME; auto now = g_date_time_new_now(m_gtimezone); auto next = g_date_time_add_minutes(now, 1); auto start_of_next = g_date_time_add_seconds(next, -g_date_time_get_seconds(next)); timerval.it_value.tv_sec = g_date_time_to_unix(start_of_next); timerval.it_value.tv_nsec = 0; g_date_time_unref(start_of_next); g_date_time_unref(next); g_date_time_unref(now); // ...and also to fire at the beginning of every subsequent minute... timerval.it_interval.tv_sec = 60; timerval.it_interval.tv_nsec = 0; // ...and also to fire if someone changes the time // manually (eg toggling from manual<->ntp) flags |= TFD_TIMER_CANCEL_ON_SET; if (timerfd_settime(m_timerfd, flags, &timerval, NULL) == -1) g_error("timerfd_settime failed: %s", g_strerror(errno)); // listen for the changes/timers m_timerfd_tag = g_unix_fd_add(m_timerfd, (GIOCondition)(G_IO_IN|G_IO_HUP|G_IO_ERR), on_timerfd_cond, this); } static gboolean on_timerfd_cond (gint fd, GIOCondition cond, gpointer gself) { auto self = static_cast(gself); int n_bytes = 0; uint64_t n_interrupts = 0; if (cond & G_IO_IN) n_bytes = read(fd, &n_interrupts, sizeof(uint64_t)); if ((n_interrupts==0) || (n_bytes!=sizeof(uint64_t))) { auto now = g_date_time_new_now(self->m_gtimezone); auto now_str = g_date_time_format(now, "%F %T"); g_debug("%s triggered at %s.%06d by GIOCondition %d, read %zd bytes, found %zu interrupts", G_STRFUNC, now_str, g_date_time_get_microsecond(now), (int)cond, n_bytes, n_interrupts); g_free(now_str); g_date_time_unref(now); // reset the timer in case someone changed the system clock self->reset_timer(); } self->refresh(); return G_SOURCE_CONTINUE; } /*** **** ***/ void setTimezone(const std::string& str) { g_clear_pointer(&m_gtimezone, g_time_zone_unref); m_gtimezone = g_time_zone_new(str.c_str()); m_owner.minute_changed(); } /*** **** ***/ void refresh() { const auto now = localtime(); // maybe emit change signals if (!DateTime::is_same_minute(m_prev_datetime, now)) m_owner.minute_changed(); if (!DateTime::is_same_day(m_prev_datetime, now)) m_owner.date_changed(); m_prev_datetime = now; } protected: LiveClock& m_owner; GTimeZone* m_gtimezone = nullptr; std::shared_ptr m_timezone; DateTime m_prev_datetime; int m_timerfd = -1; guint m_timerfd_tag = 0; }; LiveClock::LiveClock(const std::shared_ptr& timezone_): p(new Impl(*this, timezone_)) { } LiveClock::~LiveClock() =default; DateTime LiveClock::localtime() const { return p->localtime(); } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/planner-aggregate.cpp0000644000015600001650000000455412701256660015770 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include namespace unity { namespace indicator { namespace datetime { /*** **** ***/ class AggregatePlanner::Impl { public: Impl(AggregatePlanner* owner): m_owner(owner) { } ~Impl() =default; core::Property>& appointments() { return m_appointments; } void add(const std::shared_ptr& planner) { m_planners.push_back(planner); auto on_changed = [this](const std::vector&){rebuild();}; auto connection = planner->appointments().changed().connect(on_changed); m_connections.push_back(connection); } private: void rebuild() { // use a sorted aggregate vector of all our planners std::vector all; for (const auto& planner : m_planners) { const auto& walk = planner->appointments().get(); all.insert(std::end(all), std::begin(walk), std::end(walk)); } m_owner->sort(all); m_appointments.set(all); } const AggregatePlanner* m_owner = nullptr; core::Property> m_appointments; std::vector> m_planners; std::vector m_connections; }; /*** **** ***/ AggregatePlanner::AggregatePlanner(): impl(new Impl{this}) { } AggregatePlanner::~AggregatePlanner() { } core::Property>& AggregatePlanner::appointments() { return impl->appointments(); } void AggregatePlanner::add(const std::shared_ptr& planner) { return impl->add(planner); } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/formatter.cpp0000644000015600001650000001655712701256660014416 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include // T_() #include #include #include // setlocale() #include // nl_langinfo() #include // strstr() namespace unity { namespace indicator { namespace datetime { /*** **** ***/ namespace { void clear_timer(guint& tag) { if (tag) { g_source_remove(tag); tag = 0; } } gint calculate_milliseconds_until_next_second(const DateTime& now) { gint interval_usec; guint interval_msec; interval_usec = G_USEC_PER_SEC - g_date_time_get_microsecond(now.get()); interval_msec = (interval_usec + 999) / 1000; return interval_msec; } /* * We periodically rebuild the sections that have time format strings * that are dependent on the current time: * * 1. appointment menuitems' time format strings depend on the * current time; for example, they don't show the day of week * if the appointment is today. * * 2. location menuitems' time format strings depend on the * current time; for example, they don't show the day of the week * if the local date and location date are the same. * * 3. the "local date" menuitem in the calendar section is, * obviously, dependent on the local time. * * In short, we want to update whenever the number of days between two zone * might have changed. We do that by updating when either zone's day changes. * * Since not all UTC offsets are evenly divisible by hours * (examples: Newfoundland UTC-03:30, Nepal UTC+05:45), refreshing on the hour * is not enough. We need to refresh at HH:00, HH:15, HH:30, and HH:45. */ guint calculate_seconds_until_next_fifteen_minutes(GDateTime * now) { char * str; gint minute; guint seconds; GTimeSpan diff; GDateTime * next; GDateTime * start_of_next; minute = g_date_time_get_minute(now); minute = 15 - (minute % 15); next = g_date_time_add_minutes(now, minute); start_of_next = g_date_time_new_local(g_date_time_get_year(next), g_date_time_get_month(next), g_date_time_get_day_of_month(next), g_date_time_get_hour(next), g_date_time_get_minute(next), 0.1); str = g_date_time_format(start_of_next, "%F %T"); g_debug("%s %s the next timestamp rebuild will be at %s", G_STRLOC, G_STRFUNC, str); g_free(str); diff = g_date_time_difference(start_of_next, now); seconds = (diff + (G_TIME_SPAN_SECOND-1)) / G_TIME_SPAN_SECOND; g_date_time_unref(start_of_next); g_date_time_unref(next); return seconds; } } // unnamed namespace class Formatter::Impl { public: Impl(Formatter* owner, const std::shared_ptr& clock): m_owner(owner), m_clock(clock) { m_owner->header_format.changed().connect([this](const std::string& /*fmt*/){update_header();}); m_clock->minute_changed.connect([this](){update_header();}); update_header(); restartRelativeTimer(); } ~Impl() { clear_timer(m_header_seconds_timer); clear_timer(m_relative_timer); } private: static bool format_shows_seconds(const std::string& fmt) { return (fmt.find("%s") != std::string::npos) || (fmt.find("%S") != std::string::npos) || (fmt.find("%T") != std::string::npos) || (fmt.find("%X") != std::string::npos) || (fmt.find("%c") != std::string::npos); } void update_header() { // update the header property const auto fmt = m_owner->header_format.get(); const auto str = m_clock->localtime().format(fmt); m_owner->header.set(str); // if the header needs to show seconds, set a timer. if (format_shows_seconds(fmt)) start_header_timer(); else clear_timer(m_header_seconds_timer); } // we've got a header format that shows seconds, // so we need to update it every second void start_header_timer() { clear_timer(m_header_seconds_timer); const auto now = m_clock->localtime(); auto interval_msec = calculate_milliseconds_until_next_second(now); interval_msec += 50; // add a small margin to ensure the callback // fires /after/ next is reached m_header_seconds_timer = g_timeout_add_full(G_PRIORITY_HIGH, interval_msec, on_header_timer, this, nullptr); } static gboolean on_header_timer(gpointer gself) { static_cast(gself)->update_header(); return G_SOURCE_REMOVE; } private: void restartRelativeTimer() { clear_timer(m_relative_timer); const auto now = m_clock->localtime(); const auto seconds = calculate_seconds_until_next_fifteen_minutes(now.get()); m_relative_timer = g_timeout_add_seconds(seconds, onRelativeTimer, this); } static gboolean onRelativeTimer(gpointer gself) { auto self = static_cast(gself); self->m_owner->relative_format_changed(); self->restartRelativeTimer(); return G_SOURCE_REMOVE; } private: Formatter* const m_owner; guint m_header_seconds_timer = 0; guint m_relative_timer = 0; public: std::shared_ptr m_clock; }; /*** **** ***/ Formatter::Formatter(const std::shared_ptr& clock): p(new Formatter::Impl(this, clock)) { } Formatter::~Formatter() { } const char* Formatter::default_header_time_format(bool twelvehour, bool show_seconds) { const char* fmt; if (twelvehour && show_seconds) /* TRANSLATORS: a strftime(3) format for 12hr time w/seconds */ fmt = T_("%l:%M:%S %p"); else if (twelvehour) /* TRANSLATORS: a strftime(3) format for 12hr time */ fmt = T_("%l:%M %p"); else if (show_seconds) /* TRANSLATORS: a strftime(3) format for 24hr time w/seconds */ fmt = T_("%H:%M:%S"); else /* TRANSLATORS: a strftime(3) format for 24hr time */ fmt = T_("%H:%M"); return fmt; } /*** **** ***/ std::string Formatter::relative_format(GDateTime* then_begin, GDateTime* then_end) const { auto cstr = generate_full_format_string_at_time (p->m_clock->localtime().get(), then_begin, then_end); const std::string ret = cstr; g_free (cstr); return ret; } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/sound.cpp0000644000015600001650000001154212701256660013530 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include // std::call_once() namespace unity { namespace indicator { namespace notifications { /*** **** ***/ /** * Plays a sound, possibly looping. */ class Sound::Impl { public: Impl(const std::string& role, const std::string& uri, unsigned int volume, bool loop): m_role(role), m_uri(uri), m_volume(volume), m_loop(loop) { // init GST once static std::once_flag once; std::call_once(once, [](){ GError* error = nullptr; if (!gst_init_check (nullptr, nullptr, &error)) { g_critical("Unable to play alarm sound: %s", error->message); g_error_free(error); } }); m_play = gst_element_factory_make("playbin", "play"); auto bus = gst_pipeline_get_bus(GST_PIPELINE(m_play)); m_watch_source = gst_bus_add_watch(bus, bus_callback, this); gst_object_unref(bus); g_debug("Playing '%s'", m_uri.c_str()); g_object_set(G_OBJECT (m_play), "uri", m_uri.c_str(), "volume", get_volume(), nullptr); gst_element_set_state (m_play, GST_STATE_PLAYING); } ~Impl() { g_source_remove(m_watch_source); if (m_play != nullptr) { gst_element_set_state (m_play, GST_STATE_NULL); g_clear_pointer (&m_play, gst_object_unref); } } private: // convert settings range [1..100] to gst playbin's range is [0...1.0] gdouble get_volume() const { constexpr int in_range_lo = 1; constexpr int in_range_hi = 100; const double in = CLAMP(m_volume, in_range_lo, in_range_hi); const double pct = (in - in_range_lo) / (in_range_hi - in_range_lo); constexpr double out_range_lo = 0.0; constexpr double out_range_hi = 1.0; return out_range_lo + (pct * (out_range_hi - out_range_lo)); } static gboolean bus_callback(GstBus*, GstMessage* msg, gpointer gself) { auto self = static_cast(gself); const auto message_type = GST_MESSAGE_TYPE(msg); if ((message_type == GST_MESSAGE_EOS) && (self->m_loop)) { gst_element_seek(self->m_play, 1.0, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH, GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, (gint64)GST_CLOCK_TIME_NONE); } else if (message_type == GST_MESSAGE_STREAM_START) { /* Set the media role if audio sink is pulsesink */ GstElement *audio_sink = nullptr; g_object_get(self->m_play, "audio-sink", &audio_sink, nullptr); if (audio_sink) { GstPluginFeature *feature = nullptr; feature = GST_PLUGIN_FEATURE_CAST(GST_ELEMENT_GET_CLASS(audio_sink)->elementfactory); if (feature && g_strcmp0(gst_plugin_feature_get_name(feature), "pulsesink") == 0) { auto role_str = g_strdup_printf("props,media.role=%s", self->m_role.c_str()); GstStructure *props = gst_structure_from_string(role_str, nullptr); g_object_set(audio_sink, "stream-properties", props, nullptr); gst_structure_free(props); g_free(role_str); } gst_object_unref(audio_sink); } } return G_SOURCE_CONTINUE; // keep listening } /*** **** ***/ const std::string m_role; const std::string m_uri; const unsigned int m_volume; const bool m_loop; guint m_watch_source = 0; GstElement* m_play = nullptr; }; Sound::Sound(const std::string& role, const std::string& uri, unsigned int volume, bool loop): impl (new Impl(role, uri, volume, loop)) { } Sound::~Sound() { } /*** **** ***/ } // namespace notifications } // namespace indicator } // namespace unity ./src/CMakeLists.txt0000644000015600001650000000463312701256660014437 0ustar jenkinsjenkinsset (SERVICE_LIB "indicatordatetimeservice") set (SERVICE_EXEC "indicator-datetime-service") add_definitions (-DG_LOG_DOMAIN="Indicator-Datetime") # handwritten sources set (SERVICE_C_SOURCES utils.c) set (SERVICE_CXX_SOURCES actions.cpp actions-live.cpp alarm-queue-simple.cpp awake.cpp appointment.cpp clock.cpp clock-live.cpp date-time.cpp engine-eds.cpp exporter.cpp formatter.cpp formatter-desktop.cpp haptic.cpp locations.cpp locations-settings.cpp menu.cpp notifications.cpp planner.cpp planner-aggregate.cpp planner-snooze.cpp planner-month.cpp planner-range.cpp planner-upcoming.cpp settings-live.cpp snap.cpp sound.cpp timezone-geoclue.cpp timezones-live.cpp timezone-timedated.cpp utils.c wakeup-timer-mainloop.cpp wakeup-timer-powerd.cpp) # generated sources include (GdbusCodegen) set(SERVICE_GENERATED_SOURCES) add_gdbus_codegen(SERVICE_GENERATED_SOURCES dbus-alarm-properties com.canonical.indicator ${CMAKE_SOURCE_DIR}/data/com.canonical.indicator.datetime.AlarmProperties.xml) add_gdbus_codegen(SERVICE_GENERATED_SOURCES dbus-accounts-sound com.ubuntu.touch ${CMAKE_SOURCE_DIR}/src/com.ubuntu.touch.AccountsService.Sound.xml) # add warnings/coverage info on handwritten files # but not the autogenerated ones... set_source_files_properties(${SERVICE_CXX_SOURCES} PROPERTIES COMPILE_FLAGS "${CXX_WARNING_ARGS} ${GCOV_FLAGS} -g -std=c++11") set_source_files_properties(${SERVICE_C_SOURCES} PROPERTIES COMPILE_FLAGS "${CXX_WARNING_ARGS} ${GCOV_FLAGS} -g -std=c99") # add the bin dir to our include path so our code can find the generated header files include_directories (${CMAKE_CURRENT_BINARY_DIR}) add_library (${SERVICE_LIB} STATIC ${SERVICE_C_SOURCES} ${SERVICE_CXX_SOURCES} ${SERVICE_GENERATED_SOURCES}) include_directories (${CMAKE_SOURCE_DIR}) link_directories (${SERVICE_DEPS_LIBRARY_DIRS}) add_executable (${SERVICE_EXEC} main.cpp) set_source_files_properties(${SERVICE_SOURCES} main.cpp PROPERTIES COMPILE_FLAGS "${CXX_WARNING_ARGS} -g -std=c++11") target_link_libraries (${SERVICE_EXEC} ${SERVICE_LIB} ${SERVICE_DEPS_LIBRARIES} ${GCOV_LIBS}) install (TARGETS ${SERVICE_EXEC} RUNTIME DESTINATION ${CMAKE_INSTALL_FULL_PKGLIBEXECDIR}) ./src/planner-upcoming.cpp0000644000015600001650000000330312701256660015652 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include namespace unity { namespace indicator { namespace datetime { /*** **** ***/ UpcomingPlanner::UpcomingPlanner(const std::shared_ptr& range_planner, const DateTime& date_in): m_range_planner(range_planner) { date().changed().connect([this](const DateTime& dt){ // set the range to the upcoming month const auto b = dt.add_days(-1).start_of_day(); const auto e = b.add_full(0, 1, 0, 0, 0, 0); g_debug("%p setting date range to [%s..%s]", this, b.format("%F %T").c_str(), e.format("%F %T").c_str()); m_range_planner->range().set(std::pair(b,e)); }); date().set(date_in); } core::Property& UpcomingPlanner::date() { return m_date; } core::Property>& UpcomingPlanner::appointments() { return m_range_planner->appointments(); } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/utils.c0000644000015600001650000003477512701256660013215 0ustar jenkinsjenkins/* * Copyright 2010, 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Michael Terry * Charles Kerr */ #include #include #include #include #include #include #include /* Check the system locale setting to see if the format is 24-hour time or 12-hour time */ gboolean is_locale_12h(void) { int i; static const char *formats_24h[] = {"%H", "%R", "%T", "%OH", "%k", NULL}; const char* t_fmt = nl_langinfo(T_FMT); for (i=0; formats_24h[i]!=NULL; i++) if (strstr(t_fmt, formats_24h[i]) != NULL) return FALSE; return TRUE; } void split_settings_location(const gchar* location, gchar** zone, gchar** name) { gchar* location_dup = g_strdup(location); if(location_dup != NULL) g_strstrip(location_dup); gchar* first = NULL; if(location_dup && (first = strchr(location_dup, ' '))) *first = '\0'; if(zone) *zone = location_dup; if(name != NULL) { gchar* after = first ? g_strstrip(first + 1) : NULL; if(after && *after) { *name = g_strdup(after); } else if (location_dup) // make the name from zone { gchar * chr = strrchr(location_dup, '/'); after = g_strdup(chr ? chr + 1 : location_dup); // replace underscores with spaces for(chr=after; chr && *chr; chr++) if(*chr == '_') *chr = ' '; *name = after; } else { *name = NULL; } } } /** * Our Locations come from two places: (1) direct user input and (2) ones * guessed by the system, such as from geoclue or timedate1. * * Since the latter only have a timezone (eg, "America/Chicago") and the * former have a descriptive name provided by the end user (eg, * "America/Chicago Oklahoma City"), this function tries to make a * more human-readable name by using the user-provided name if the guessed * timezone matches the last one the user manually clicked on. * * In the example above, this allows the menuitem for the system-guessed * timezone ("America/Chicago") to read "Oklahoma City" after the user clicks * on the "Oklahoma City" menuitem. */ gchar* get_beautified_timezone_name(const char* timezone_, const char* saved_location) { gchar* zone; gchar* name; split_settings_location(timezone_, &zone, &name); gchar* saved_zone; gchar* saved_name; split_settings_location(saved_location, &saved_zone, &saved_name); gchar* rv; if (g_strcmp0(zone, saved_zone) == 0) { rv = saved_name; saved_name = NULL; } else { rv = name; name = NULL; } g_free(zone); g_free(name); g_free(saved_zone); g_free(saved_name); return rv; } gchar* get_timezone_name(const gchar* timezone_, GSettings* settings) { gchar* saved_location = g_settings_get_string(settings, SETTINGS_TIMEZONE_NAME_S); gchar* rv = get_beautified_timezone_name(timezone_, saved_location); g_free(saved_location); return rv; } /*** **** ***/ typedef enum { DATE_PROXIMITY_TODAY, DATE_PROXIMITY_TOMORROW, DATE_PROXIMITY_WEEK, DATE_PROXIMITY_FAR } date_proximity_t; static date_proximity_t getDateProximity(GDateTime* now, GDateTime* time) { date_proximity_t prox = DATE_PROXIMITY_FAR; gint now_year, now_month, now_day; gint time_year, time_month, time_day; // did it already happen? if (g_date_time_difference(time, now) < -G_USEC_PER_SEC) return DATE_PROXIMITY_FAR; // does it happen today? g_date_time_get_ymd(now, &now_year, &now_month, &now_day); g_date_time_get_ymd(time, &time_year, &time_month, &time_day); if ((now_year == time_year) && (now_month == time_month) && (now_day == time_day)) prox = DATE_PROXIMITY_TODAY; // does it happen tomorrow? if (prox == DATE_PROXIMITY_FAR) { GDateTime* tomorrow = g_date_time_add_days(now, 1); gint tom_year, tom_month, tom_day; g_date_time_get_ymd(tomorrow, &tom_year, &tom_month, &tom_day); if ((tom_year == time_year) && (tom_month == time_month) && (tom_day == time_day)) prox = DATE_PROXIMITY_TOMORROW; g_date_time_unref(tomorrow); } // does it happen this week? if (prox == DATE_PROXIMITY_FAR) { GDateTime* week = g_date_time_add_days(now, 6); GDateTime* week_bound = g_date_time_new_local(g_date_time_get_year(week), g_date_time_get_month(week), g_date_time_get_day_of_month(week), 23, 59, 59.9); if (g_date_time_compare(time, week_bound) <= 0) prox = DATE_PROXIMITY_WEEK; g_date_time_unref(week_bound); g_date_time_unref(week); } return prox; } const char* T_(const char *msg) { /* General strategy here is to make sure LANGUAGE is empty (since that trumps all LC_* vars) and then to temporarily swap LC_TIME and LC_MESSAGES. Then have gettext translate msg. We strdup the strings because the setlocale & *env functions do not guarantee anything about the storage used for the string, and thus the string may not be portably safe after multiple calls. Note that while you might think g_dcgettext would do the trick here, that actually looks in /usr/share/locale/XX/LC_TIME, not the LC_MESSAGES directory, so we won't find any translation there. */ gchar* message_locale = g_strdup(setlocale(LC_MESSAGES, NULL)); const char* time_locale = setlocale(LC_TIME, NULL); gchar* language = g_strdup(g_getenv("LANGUAGE")); if (language) g_unsetenv("LANGUAGE"); setlocale(LC_MESSAGES, time_locale); /* Get the LC_TIME version */ const char* rv = _(msg); /* Put everything back the way it was */ setlocale(LC_MESSAGES, message_locale); if (language) g_setenv("LANGUAGE", language, TRUE); g_free(message_locale); g_free(language); return rv; } /** * _ a time today should be shown as just the time (e.g. “3:55 PM”) * _ a full-day event today should be shown as “Today” * _ a time any other day this week should be shown as the short version of the * day and time (e.g. “Wed 3:55 PM”) * _ a full-day event tomorrow should be shown as “Tomorrow” * _ a full-day event another day this week should be shown as the * weekday (e.g. “Friday”) * _ a time after this week should be shown as the short version of the day, * date, and time (e.g. “Wed 21 Apr 3:55 PM”) * _ a full-day event after this week should be shown as the short version of * the day and date (e.g. “Wed 21 Apr”). * _ in addition, when presenting the times of upcoming events, the time should * be followed by the timezone if it is different from the one the computer * is currently set to. For example, “Wed 3:55 PM UTC−5”. */ char* generate_full_format_string_at_time (GDateTime* now, GDateTime* then, GDateTime* then_end) { GString* ret = g_string_new (NULL); if (then != NULL) { const gboolean full_day = then_end && (g_date_time_difference(then_end, then) >= G_TIME_SPAN_DAY); const date_proximity_t prox = getDateProximity(now, then); if (full_day) { switch (prox) { case DATE_PROXIMITY_TODAY: g_string_assign (ret, T_("Today")); break; case DATE_PROXIMITY_TOMORROW: g_string_assign (ret, T_("Tomorrow")); break; case DATE_PROXIMITY_WEEK: /* This is a strftime(3) format string indicating the unabbreviated weekday. */ g_string_assign (ret, T_("%A")); break; case DATE_PROXIMITY_FAR: /* Translators, please edit/rearrange these strftime(3) tokens to suit your locale! This format string is used for showing full-day events that are over a week away. en_US example: "%a %b %d" --> "Sat Oct 31" en_GB example: "%a %d %b" --> "Sat 31 Oct" zh_CN example(?): "%m月%d日 周%a" --> "10月31日 周六" */ g_string_assign (ret, T_("%a %d %b")); break; } } else if (is_locale_12h()) { switch (prox) { case DATE_PROXIMITY_TODAY: /* Translators, please edit/rearrange these strftime(3) tokens to suit your locale! This format string is used for showing, on a 12-hour clock, events/appointments that happen today. en_US example: "%l:%M %p" --> "1:00 PM" */ g_string_assign (ret, T_("%l:%M %p")); break; case DATE_PROXIMITY_TOMORROW: /* Translators, please edit/rearrange these strftime(3) tokens to suit your locale! This format string is used for showing, on a 12-hour clock, events/appointments that happen tomorrow. (Note: the space between the day and the time is an em space (unicode character 2003), which is slightly wider than a normal space.) en_US example: "Tomorrow %l:%M %p" --> "Tomorrow 1:00 PM" */ g_string_assign (ret, T_("Tomorrow %l:%M %p")); break; case DATE_PROXIMITY_WEEK: /* Translators, please edit/rearrange these strftime(3) tokens to suit your locale! This format string is used for showing, on a 12-hour clock, events/appointments that happen this week. (Note: the space between the day and the time is an em space (unicode character 2003), which is slightly wider than a normal space.) en_US example: "Tomorrow %l:%M %p" --> "Fri 1:00 PM" */ g_string_assign (ret, T_("%a %l:%M %p")); break; case DATE_PROXIMITY_FAR: /* Translators, please edit/rearrange these strftime(3) tokens to suit your locale! This format string is used for showing, on a 12-hour clock, events/appointments that happen over a week from now. (Note: the space between the day and the time is an em space (unicode character 2003), which is slightly wider than a normal space.) en_US example: "%a %b %d %l:%M %p" --> "Fri Oct 31 1:00 PM" en_GB example: "%a %d %b %l:%M %p" --> "Fri 31 Oct 1:00 PM" */ g_string_assign (ret, T_("%a %d %b %l:%M %p")); break; } } else { switch (prox) { case DATE_PROXIMITY_TODAY: /* Translators, please edit/rearrange these strftime(3) tokens to suit your locale! This format string is used for showing, on a 24-hour clock, events/appointments that happen today. en_US example: "%H:%M" --> "13:00" */ g_string_assign (ret, T_("%H:%M")); break; case DATE_PROXIMITY_TOMORROW: /* Translators, please edit/rearrange these strftime(3) tokens to suit your locale! This format string is used for showing, on a 24-hour clock, events/appointments that happen tomorrow. (Note: the space between the day and the time is an em space (unicode character 2003), which is slightly wider than a normal space.) en_US example: "Tomorrow %l:%M %p" --> "Tomorrow 13:00" */ g_string_assign (ret, T_("Tomorrow %H:%M")); break; case DATE_PROXIMITY_WEEK: /* Translators, please edit/rearrange these strftime(3) tokens to suit your locale! This format string is used for showing, on a 24-hour clock, events/appointments that happen this week. (Note: the space between the day and the time is an em space (unicode character 2003), which is slightly wider than a normal space.) en_US example: "%a %H:%M" --> "Fri 13:00" */ g_string_assign (ret, T_("%a %H:%M")); break; case DATE_PROXIMITY_FAR: /* Translators, please edit/rearrange these strftime(3) tokens to suit your locale! This format string is used for showing, on a 24-hour clock, events/appointments that happen over a week from now. (Note: the space between the day and the time is an em space (unicode character 2003), which is slightly wider than a normal space.) en_US example: "%a %b %d %H:%M" --> "Fri Oct 31 13:00" en_GB example: "%a %d %b %H:%M" --> "Fri 31 Oct 13:00" */ g_string_assign (ret, T_("%a %d %b %H:%M")); break; } } /* if it's an appointment in a different timezone (and doesn't run for a full day) then the time should be followed by its timezone. */ if ((then_end != NULL) && (!full_day) && ((g_date_time_get_utc_offset(now) != g_date_time_get_utc_offset(then)))) { g_string_append_printf (ret, " %s", g_date_time_get_timezone_abbreviation(then)); } } return g_string_free (ret, FALSE); } ./src/planner-range.cpp0000644000015600001650000000554612701256660015140 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include namespace unity { namespace indicator { namespace datetime { /*** **** ***/ SimpleRangePlanner::SimpleRangePlanner(const std::shared_ptr& engine, const std::shared_ptr& timezone): m_engine(engine), m_timezone(timezone), m_range(std::pair(DateTime::NowLocal(), DateTime::NowLocal())) { engine->changed().connect([this](){ g_debug("RangePlanner %p rebuilding soon because Engine %p emitted 'changed' signal", this, m_engine.get()); rebuild_soon(); }); m_timezone->timezone.changed().connect([this](const std::string& s){ g_debug("RangePlanner %p rebuilding soon because the timezone changed to '%s'", this, s.c_str()); rebuild_soon(); }); range().changed().connect([this](const std::pair&){ g_debug("rebuilding because the date range changed"); rebuild_soon(); }); } SimpleRangePlanner::~SimpleRangePlanner() { if (m_rebuild_tag) g_source_remove(m_rebuild_tag); } /*** **** ***/ void SimpleRangePlanner::rebuild_now() { const auto& r = range().get(); auto on_appointments_fetched = [this](const std::vector& a){ g_debug("RangePlanner %p got %zu appointments", this, a.size()); appointments().set(a); }; m_engine->get_appointments(r.first, r.second, *m_timezone.get(), on_appointments_fetched); } void SimpleRangePlanner::rebuild_soon() { static const int ARBITRARY_BATCH_MSEC = 200; if (m_rebuild_tag == 0) m_rebuild_tag = g_timeout_add(ARBITRARY_BATCH_MSEC, rebuild_now_static, this); } gboolean SimpleRangePlanner::rebuild_now_static(gpointer gself) { auto self = static_cast(gself); self->m_rebuild_tag = 0; self->rebuild_now(); return G_SOURCE_REMOVE; } /*** **** ***/ core::Property>& SimpleRangePlanner::appointments() { return m_appointments; } core::Property>& SimpleRangePlanner::range() { return m_range; } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/exporter.cpp0000644000015600001650000001716512701256660014257 0ustar jenkinsjenkins/* * Copyright 2013 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include "dbus-alarm-properties.h" #include #include namespace unity { namespace indicator { namespace datetime { /*** **** ***/ class Exporter::Impl { public: Impl(const std::shared_ptr& settings): m_settings(settings), m_alarm_props(datetime_alarm_properties_skeleton_new()) { alarm_properties_init(); } ~Impl() { if (m_bus != nullptr) { for(auto& id : m_exported_menu_ids) g_dbus_connection_unexport_menu_model(m_bus, id); if (m_exported_actions_id) g_dbus_connection_unexport_action_group(m_bus, m_exported_actions_id); } g_dbus_interface_skeleton_unexport(G_DBUS_INTERFACE_SKELETON(m_alarm_props)); g_clear_object(&m_alarm_props); if (m_own_id) g_bus_unown_name(m_own_id); g_clear_object(&m_bus); } core::Signal<> name_lost; void publish(const std::shared_ptr& actions, const std::vector>& menus) { m_actions = actions; m_menus = menus; m_own_id = g_bus_own_name(G_BUS_TYPE_SESSION, BUS_DATETIME_NAME, G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT, on_bus_acquired, nullptr, on_name_lost, this, nullptr); } private: /*** **** ***/ static void on_gobject_notify_string(GObject* o, GParamSpec* pspec, gpointer p) { gchar* val = nullptr; g_object_get (o, pspec->name, &val, nullptr); static_cast*>(p)->set(val); g_free(val); } void bind_string_property(gpointer o, const char* propname, core::Property& p) { // initialize the GObject property from the Settings g_object_set(o, propname, p.get().c_str(), nullptr); // when the GObject changes, update the Settings const std::string notify_propname = std::string("notify::") + propname; g_signal_connect(o, notify_propname.c_str(), G_CALLBACK(on_gobject_notify_string), &p); // when the Settings changes, update the GObject p.changed().connect([o, propname](const std::string& val){ g_object_set(o, propname, val.c_str(), nullptr); }); } static void on_gobject_notify_uint(GObject* o, GParamSpec* pspec, gpointer p) { uint val = 0; g_object_get (o, pspec->name, &val, nullptr); static_cast*>(p)->set(val); } void bind_uint_property(gpointer o, const char* propname, core::Property& p) { // initialize the GObject property from the Settings g_object_set(o, propname, p.get(), nullptr); // when the GObject changes, update the Settings const std::string notify_propname = std::string("notify::") + propname; g_signal_connect(o, notify_propname.c_str(), G_CALLBACK(on_gobject_notify_uint), &p); // when the Settings changes, update the GObject p.changed().connect([o, propname](unsigned int val){ g_object_set(o, propname, val, nullptr); }); } void alarm_properties_init() { bind_uint_property(m_alarm_props, "duration", m_settings->alarm_duration); bind_uint_property(m_alarm_props, "default-volume", m_settings->alarm_volume); bind_string_property(m_alarm_props, "default-sound", m_settings->alarm_sound); bind_string_property(m_alarm_props, "haptic-feedback", m_settings->alarm_haptic); bind_uint_property(m_alarm_props, "snooze-duration", m_settings->snooze_duration); } /*** **** ***/ static void on_bus_acquired(GDBusConnection* connection, const gchar* name, gpointer gthis) { g_debug("bus acquired: %s", name); static_cast(gthis)->on_bus_acquired(connection, name); } void on_bus_acquired(GDBusConnection* bus, const gchar* /*name*/) { m_bus = static_cast(g_object_ref(G_OBJECT(bus))); // export the alarm properties GError * error = nullptr; g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(m_alarm_props), m_bus, BUS_DATETIME_PATH"/AlarmProperties", &error); // export the actions const auto id = g_dbus_connection_export_action_group(m_bus, BUS_DATETIME_PATH, m_actions->action_group(), &error); if (id) { m_exported_actions_id = id; } else { g_warning("cannot export action group: %s", error->message); g_clear_error(&error); } // export the menus for(auto& menu : m_menus) { const auto path = std::string(BUS_DATETIME_PATH) + "/" + menu->name(); const auto id = g_dbus_connection_export_menu_model(m_bus, path.c_str(), menu->menu_model(), &error); if (id) { m_exported_menu_ids.insert(id); } else { if (error != nullptr) g_warning("cannot export %s menu: %s", menu->name().c_str(), error->message); g_clear_error(&error); } } } /*** **** ***/ static void on_name_lost(GDBusConnection*, const gchar* name, gpointer gthis) { g_debug("name lost: %s", name); static_cast(gthis)->name_lost(); } /*** **** ***/ std::shared_ptr m_settings; std::set m_exported_menu_ids; guint m_own_id = 0; guint m_exported_actions_id = 0; GDBusConnection* m_bus = nullptr; std::shared_ptr m_actions; std::vector> m_menus; DatetimeAlarmProperties* m_alarm_props = nullptr; }; /*** **** ***/ Exporter::Exporter(const std::shared_ptr& settings): p(new Impl(settings)) { } Exporter::~Exporter() { } core::Signal<>& Exporter::name_lost() { return p->name_lost; } void Exporter::publish(const std::shared_ptr& actions, const std::vector>& menus) { p->publish(actions, menus); } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/awake.cpp0000644000015600001650000002235412701256660013473 0ustar jenkinsjenkins/* * Copyright 2014 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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 . * * Authors: * Charles Kerr */ #include #include #include #include namespace unity { namespace indicator { namespace notifications { /*** **** ***/ class Awake::Impl { public: Impl(const std::string& app_name): m_app_name(app_name), m_cancellable(g_cancellable_new()) { g_bus_get(G_BUS_TYPE_SYSTEM, m_cancellable, on_system_bus_ready, this); } ~Impl() { g_cancellable_cancel (m_cancellable); g_object_unref (m_cancellable); if (m_display_on_timer) { g_source_remove (m_display_on_timer); m_display_on_timer = 0; } if (m_system_bus != nullptr) { unforce_awake (); remove_display_on_request (); g_object_unref (m_system_bus); } } private: static void on_system_bus_ready (GObject *, GAsyncResult *res, gpointer gself) { GError * error; GDBusConnection * system_bus; error = nullptr; system_bus = g_bus_get_finish (res, &error); if (error != nullptr) { if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) g_warning ("Unable to get bus: %s", error->message); g_error_free (error); } else if (system_bus != nullptr) { auto self = static_cast(gself); self->m_system_bus = G_DBUS_CONNECTION (g_object_ref (system_bus)); // ask powerd to keep the system awake static constexpr int32_t POWERD_SYS_STATE_ACTIVE = 1; g_dbus_connection_call (system_bus, BUS_POWERD_NAME, BUS_POWERD_PATH, BUS_POWERD_INTERFACE, "requestSysState", g_variant_new("(si)", self->m_app_name.c_str(), POWERD_SYS_STATE_ACTIVE), G_VARIANT_TYPE("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, self->m_cancellable, on_force_awake_response, self); // ask unity-system-compositor to turn on the screen g_dbus_connection_call (system_bus, BUS_SCREEN_NAME, BUS_SCREEN_PATH, BUS_SCREEN_INTERFACE, "keepDisplayOn", nullptr, G_VARIANT_TYPE("(i)"), G_DBUS_CALL_FLAGS_NONE, -1, self->m_cancellable, on_keep_display_on_response, self); g_object_unref (system_bus); } } static void on_force_awake_response (GObject * connection, GAsyncResult * res, gpointer gself) { GError * error; GVariant * args; error = nullptr; args = g_dbus_connection_call_finish (G_DBUS_CONNECTION(connection), res, &error); if (error != nullptr) { if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED) && !g_error_matches (error, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN)) { g_warning ("Unable to inhibit sleep: %s", error->message); } g_error_free (error); } else { auto self = static_cast(gself); g_clear_pointer (&self->m_awake_cookie, g_free); g_variant_get (args, "(s)", &self->m_awake_cookie); g_debug ("m_awake_cookie is now '%s'", self->m_awake_cookie); g_variant_unref (args); } } static void on_keep_display_on_response (GObject * connection, GAsyncResult * res, gpointer gself) { GError * error; GVariant * args; error = nullptr; args = g_dbus_connection_call_finish (G_DBUS_CONNECTION(connection), res, &error); if (error != nullptr) { if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED) && !g_error_matches (error, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN)) { g_warning ("Unable to turn on the screen: %s", error->message); } g_error_free (error); } else { auto self = static_cast(gself); self->m_display_on_cookie = NO_DISPLAY_ON_COOKIE; g_variant_get (args, "(i)", &self->m_display_on_cookie); g_debug ("m_display_on_cookie is now '%d'", self->m_display_on_cookie); self->m_display_on_timer = g_timeout_add_seconds (self->m_display_on_seconds, on_display_on_timer, gself); g_variant_unref (args); } } static gboolean on_display_on_timer (gpointer gself) { auto self = static_cast(gself); self->m_display_on_timer = 0; self->remove_display_on_request(); return G_SOURCE_REMOVE; } void unforce_awake () { g_return_if_fail (G_IS_DBUS_CONNECTION(m_system_bus)); if (m_awake_cookie != nullptr) { g_dbus_connection_call (m_system_bus, BUS_POWERD_NAME, BUS_POWERD_PATH, BUS_POWERD_INTERFACE, "clearSysState", g_variant_new("(s)", m_awake_cookie), nullptr, G_DBUS_CALL_FLAGS_NONE, -1, nullptr, nullptr, nullptr); g_clear_pointer (&m_awake_cookie, g_free); } } void remove_display_on_request () { g_return_if_fail (G_IS_DBUS_CONNECTION(m_system_bus)); if (m_display_on_cookie != NO_DISPLAY_ON_COOKIE) { g_dbus_connection_call (m_system_bus, BUS_SCREEN_NAME, BUS_SCREEN_PATH, BUS_SCREEN_INTERFACE, "removeDisplayOnRequest", g_variant_new("(i)", m_display_on_cookie), nullptr, G_DBUS_CALL_FLAGS_NONE, -1, nullptr, nullptr, nullptr); m_display_on_cookie = NO_DISPLAY_ON_COOKIE; } } const std::string m_app_name; GCancellable * m_cancellable = nullptr; GDBusConnection * m_system_bus = nullptr; char * m_awake_cookie = nullptr; /** * As described by bug #1434637, alarms should have the display turn on, * dim, and turn off "just like it would if you'd woken it up yourself". * USC may be adding an intent-based bus API to handle this use case, * e.g. turnDisplayOnTemporarily(intent), but there's no timeframe for it. * * Until that's avaialble, we can get close to Design's specs by * requesting a display-on cookie and then releasing the cookie * a moment later. */ const guint m_display_on_seconds = 1; guint m_display_on_timer = 0; int32_t m_display_on_cookie = NO_DISPLAY_ON_COOKIE; static constexpr int32_t NO_DISPLAY_ON_COOKIE { std::numeric_limits::min() }; }; /*** **** ***/ Awake::Awake(const std::string& app_name): impl(new Impl(app_name)) { } Awake::~Awake() { } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./README0000644000015600001650000001147712701256660011774 0ustar jenkinsjenkinsACTIONS ======= * "desktop.open-settings-app" * "phone.open-settings-app" Description: open the settings application. State: None Parameter: None * "desktop.open-alarm-app" * "phone.open-alarm-app" Description: open the application for creating new alarms. State: None Parameter: None * "desktop.open-calendar-app" * "phone.open-calendar-app" State: None Parameter: int64, a time_t hinting which day/time to show in the planner, or 0 for the current day * "desktop.open-appointment" * "phone.open-appointment" Description: opens an appointment editor to the specified appointment. State: None Parameter: string, an opaque uid to specify which appointment to use. This uid comes from the menuitems' target values. * "set-location" Description: Set the current location. This will try to set the current timezone to the new location's timezone. State: None Parameter: a timezone id string followed by a space and location name. Example: "America/Chicago Oklahoma City" * "calendar" Description: set which month/day should be given focus in the indicator's calendar. The planner will look for appointments from this day to the end of the same month. Client code implementing the calendar view should call this when the user clicks on a new day, month, or year. State: a dictionary containing these key value/pairs: "appointment-days": an array of day-of-month ints. Used by the calendar menuitem to mark appointment days. "calendar-day": int64, a time_t. Used by the calendar menuitem to know which year/month should be visible and which day should have the cursor. "show-week-numbers": if true, show week numbers in the calendar. Parameter: int64, a time_t specifying which year/month should be visible and which day should have the cursor. CUSTOM MENUITEMS ================ * Calendar - x-canonical-type s "com.canonical.indicator.calendar" * Alarm - label s short summary of the appointment - x-canonical-type s "com.canonical.indicator.alarm" - x-canonical-time x the date of the appointment - x-canonical-time-format s strftime format string * Appointment - label s short summary of the appointment - x-canonical-type s "com.canonical.indicator.appointment" - x-canonical-color s color of the appt's type, to give a visual cue - x-canonical-time x the date of the appointment - x-canonical-time-format s strftime format string * Location - label s the location's name, eg "Oklahoma City" - x-canonical-type s "com.canonical.indicator.location" - x-canonical-timezone s timezone that the location is in - x-canonical-time-format s strftime format string CODE ==== Model The app's model is represented by the "State" class, and "Menu" objects are the corresponding views. "State" is a simple container for various properties, and menus connect to those properties' changed() signals to know when the view needs to be refreshed. As one can see in main.c, the app's very simple flow is to instantiate a state and its properties, build menus that correspond to the state, and export the menus on DBus. Because State is a simple aggregate of its components (such as a "Clock" or "Planner" object to get the current time and upcoming appointments, respectively), one can plug in live components for production and mock components for unit tests. The entire backend can be mix-and-matched by adding the desired test-or-production components. Start with: include/datetime/state.h include/datetime/clock.h include/datetime/locations.h include/datetime/planner.h include/datetime/settings.h include/datetime/timezones.h Implementations: include/datetime/settings-live.h include/datetime/locations-settings.h include/datetime/planner-eds.h include/datetime/timezones-live.h View Menu is a mostly-opaque class to wrap GMenu code. Its subclasses contain the per-profile logic of which sections/menuitems to show and which to hide. Menus are instantiated via the MenuFactory, which takes a state and profile. Actions is a mostly-opaque class to wrap our GActionGroup. Its subclasses contain the code that actually executed when an action is triggered (ie, LiveActions for production and MockActions for testing). Exporter exports the Actions and Menus onto the DBus, and also emits a signal if/when the busname is lost so indicator-datetime-service knows when to exit. include/datetime/menu.h include/datetime/actions.h include/datetime/exporter.h ./po/0000755000015600001650000000000012701256660011520 5ustar jenkinsjenkins./po/pl.po0000644000015600001650000000260112701256660012472 0ustar jenkinsjenkins# Polish translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Polish\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 " "|| n%100>=20) ? 1 : 2);\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Wystąpił błąd pobierania godziny" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d AM" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d PM" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Otwórz kalendarz" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Ustaw godzinę i datę..." ./po/nl.po0000644000015600001650000000246212701256660012475 0ustar jenkinsjenkins# Dutch translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Dutch\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Fout bij lezen van tijd" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d%d%d VM" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d%d%d NM" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Kalender openen" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Datum en tijd instellen..." ./po/zh_TW.po0000644000015600001650000000243612701256660013120 0ustar jenkinsjenkins# Chinese translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Chinese (traditional)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "獲得時間發生錯誤" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d 上午" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d 下午" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "開啟行事曆" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "設定時間和日期..." ./po/hi.po0000644000015600001650000000263012701256660012461 0ustar jenkinsjenkins# Hindi translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Hindi\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "समय प्राप्त करने में त्रुटि" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "प्रातः %d%d:%d%d बजे" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "सायं %d%d:%d%d बजे" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "कैलेंडर खोलें" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "समय और तिथि सेट करें..." ./po/nb.po0000644000015600001650000000252412701256660012462 0ustar jenkinsjenkins# Norwegian Bokmal translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Norwegian Bokmal\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Feil under henting av klokkeslett" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d AM" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d PM" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Åpne kalender" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Angi dato og klokkeslett..." ./po/cs.po0000644000015600001650000000252512701256660012471 0ustar jenkinsjenkins# Czech translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Czech\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Chyba získání času" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d dop." #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d odp." #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Otevřít kalendář" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Nastavit čas a datum..." ./po/pt.po0000644000015600001650000000250112701256660012501 0ustar jenkinsjenkins# Portuguese translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Portuguese\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Erro na obtenção das horas" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d AM" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d PM" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Abrir Calendário" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Acertar Hora e Data..." ./po/pt_BR.po0000644000015600001650000000250212701256660013065 0ustar jenkinsjenkins# Portuguese translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Brazilian Portuguese\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Erro ao obter hora" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d AM" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d PM" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Abrir o calendário" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Ajustar data e hora..." ./po/sk.po0000644000015600001650000000252012701256660012474 0ustar jenkinsjenkins# Slovak translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Slovak\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Čas zistenia chyby" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d AM" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d PM" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Otvoriť kalendár" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Nastaviť čas a dátum..." ./po/sv.po0000644000015600001650000000247512701256660012520 0ustar jenkinsjenkins# Swedish translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Swedish\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Ett fel uppstod då tid hämtades" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d FM" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d EM" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Öppna kalender" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Ange tid och datum..." ./po/ar.po0000644000015600001650000000252112701256660012462 0ustar jenkinsjenkins# Arabic translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:05-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Arabic\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "خطأ في الحصول على الوقت" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d صباحا" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d مساء" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "التقويم المفتوح (Open Calendar)" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "ضبط الوقت والتاريخ..." ./po/th.po0000644000015600001650000000254212701256660012476 0ustar jenkinsjenkins# Thai translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Thai\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "ข้อผิดพลาดการขอข้อมูลเวลา" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d AM" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d PM" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "เปิดปฏิทิน" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "ตั้งเวลาและวันที่..." ./po/ko.po0000644000015600001650000000247112701256660012475 0ustar jenkinsjenkins# Korean translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Korean\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "시간 가져오기 오류" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "오전 %d%d:%d%d" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "오후 %d%d:%d%d" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "일정 열기" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "시간 및 날짜 설정..." ./po/hu.po0000644000015600001650000000251312701256660012475 0ustar jenkinsjenkins# Hungarian translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Hungarian\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Hiba az idő lekérésekor" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d de." #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d du." #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Naptár megnyitása" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Idő és dátum beállítása..." ./po/sl.po0000644000015600001650000000260012701256660012474 0ustar jenkinsjenkins# Slovenian translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Slovenian\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=4; plural=(n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n" "%100==4 ? 2 : 3);\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Napaka pri pridobivanju podatka o času" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d AM" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d PM" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Odpri koledar" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Nastavi čas in datum ..." ./po/it.po0000644000015600001650000000250012701256660012471 0ustar jenkinsjenkins# Italian translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Italian\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Errore nell'acquisizione dell'orario" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d AM" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d PM" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Apri calendario" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Imposta data e ora..." ./po/bg.po0000644000015600001650000000253512701256660012455 0ustar jenkinsjenkins# Bulgarian translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:05-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Bulgarian\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Грешка при проверка на време" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d преди обяд" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d следобед" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Отвори календар" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Свери час и дата..." ./po/el.po0000644000015600001650000000262012701256660012460 0ustar jenkinsjenkins# Greek translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Greek\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Σφάλμα κατά τη λήψη του χρόνου" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d π.μ." #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d μ.μ." #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Άνοιγμα ημερολογίου" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Ορισμός ώρας και ημερομηνίας..." ./po/sr.po0000644000015600001650000000261312701256660012506 0ustar jenkinsjenkins# Serbian translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Serbian\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%" "10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Greška u prikazu vremena" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d%d%d pre podne" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d%d%d popodne" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Otvori kalendar" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Podesi vreme i datum" ./po/da.po0000644000015600001650000000250112701256660012442 0ustar jenkinsjenkins# Danish translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Danish\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Fejl ved hentning af klokkeslæt" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d.%d%d AM" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d.%d%d PM" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Åbn Kalender" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Indstil klokkeslæt og dato..." ./po/tr.po0000644000015600001650000000250312701256660012505 0ustar jenkinsjenkins# Turkish translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Turkish\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Saati alma hatâsı" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "Öğleden Önce %d%d:%d%d" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "Öğleden Sonra %d%d:%d%d" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Takvimi Aç" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Saati ve Târihi Ayarla..." ./po/hr.po0000644000015600001650000000261512701256660012475 0ustar jenkinsjenkins# Croatian translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Croatian\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%" "10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Greška pri dohvaćanju vremena" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d%d%d AM" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d%d%d PM" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Otvori kalendar" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Postavi vrijeme i datum..." ./po/fi.po0000644000015600001650000000250612701256660012461 0ustar jenkinsjenkins# Finnish translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Finnish\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Virheen noudettaessa aikaa" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d AP" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d IP" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Avaa kalenteri" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Aseta kellonaika ja päivämäärä..." ./po/ru.po0000644000015600001650000000270212701256660012507 0ustar jenkinsjenkins# Russian translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Russian\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%" "10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Ошибка получения времени" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d AM" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d PM" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Открыть календарь" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Установить время и дату..." ./po/ro.po0000644000015600001650000000255712701256660012511 0ustar jenkinsjenkins# Romanian translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Romanian\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=n==1 ? 0 : (n==0 || (n%100 > 0 && n%100 < " "20)) ? 1 : 2;\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Eroare la obținerea orei" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d AM" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d PM" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Deschide calendarul" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Setare oră și dată..." ./po/LINGUAS0000644000015600001650000000014612701256660012546 0ustar jenkinsjenkinsar bg cs da de el es fi fr he hi hr hu it ja ko nb nl pl pt pt_BR ro ru sk sl sr sv th tr zh_CN zh_TW ./po/he.po0000644000015600001650000000251112701256660012453 0ustar jenkinsjenkins# Hebrew translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Hebrew\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "שגיאה בקבלת השעה" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d AM" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d PM" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "פתח לוח שנה" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "הגדרת שעה ותאריך..." ./po/es.po0000644000015600001650000000246712701256660012500 0ustar jenkinsjenkins# Spanish translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Spanish\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Error al obtener la hora" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d AM" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d PM" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Abrir calendario" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Ajustar fecha y hora..." ./po/CMakeLists.txt0000644000015600001650000000020112701256660014251 0ustar jenkinsjenkinsinclude (Translations) add_translations_directory ("${GETTEXT_PACKAGE}") add_translations_catalog ("${GETTEXT_PACKAGE}" ../src/) ./po/fr.po0000644000015600001650000000251312701256660012470 0ustar jenkinsjenkins# French translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: French\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Erreur lors de l'obtention de l'heure" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d AM" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d PM" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Ouvrir le calendrier" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Régler la date et l'heure..." ./po/POTFILES.in0000644000015600001650000000012212701256660013270 0ustar jenkinsjenkinssrc/formatter.cpp src/formatter-desktop.cpp src/menu.cpp src/snap.cpp src/utils.c ./po/ja.po0000644000015600001650000000251412701256660012454 0ustar jenkinsjenkins# Japanese translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Japanese\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "時刻を取得できません" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "午前 %d%d:%d%d" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "午後 %d%d:%d%d" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "カレンダーを開く" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "時刻と日付の設定..." ./po/Makevars0000644000015600001650000000036212701256660013215 0ustar jenkinsjenkinsDOMAIN = $(PACKAGE) subdir = po top_builddir = .. XGETTEXT_OPTIONS = --keyword=_ --keyword=N_ --keyword=C_:1c,2 --keyword=T_ --from-code=UTF-8 COPYRIGHT_HOLDER = Canonical Ltd. MSGID_BUGS_ADDRESS = ted@canonical.com EXTRA_LOCALE_CATEGORIES = ./po/de.po0000644000015600001650000000247712701256660012462 0ustar jenkinsjenkins# German translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: German\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "Fehler beim Abrufen der Zeit" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d AM" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d PM" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "Kalender öffnen" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "Datum und Uhrzeit einstellen." ./po/zh_CN.po0000644000015600001650000000242412701256660013063 0ustar jenkinsjenkins# Chinese translations for PACKAGE package. # Copyright (C) 2010 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # Canonical OEM, 2010. # msgid "" msgstr "" "Project-Id-Version: indicator-datetime\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-03-10 15:20-0500\n" "PO-Revision-Date: 2010-03-03 10:06-0500\n" "Last-Translator: Canonical OEM\n" "Language-Team: Chinese (simplified)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: ../src/indicator-datetime.c:177 msgid "Error getting time" msgstr "获取时间出错" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:259 #, c-format msgid "%d%d:%d%d AM" msgstr "%d%d:%d%d 上午" #. TRANSLATORS: This string is used for measuring the size of #. the font used for showing the time and is not shown to the #. user anywhere. #: ../src/indicator-datetime.c:266 #, c-format msgid "%d%d:%d%d PM" msgstr "%d%d:%d%d 下午" #: ../src/indicator-datetime.c:351 msgid "Open Calendar" msgstr "打开日历" #: ../src/indicator-datetime.c:361 msgid "Set Time and Date..." msgstr "设置时间和日期..." ./COPYING0000644000015600001650000010451312701256660012141 0ustar jenkinsjenkins 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 . ./trim-lcov.py0000755000015600001650000000267012701256660013400 0ustar jenkinsjenkins#!/usr/bin/python # This script removes branch and/or line coverage data for lines that # contain a particular substring. # # In the interest of "fairness" it removes all branch or coverage data # when a match is found -- not just negative data. It is therefore # likely that running this script will actually reduce the total number # of lines and branches that are marked as covered (in absolute terms). # # This script intentionally avoids checking for errors. Any exceptions # will trigger make to fail. # # Author: Ryan Lortie import sys line_suppress = ['g_assert_not_reached'] branch_suppress = ['g_assert', 'g_return_if_fail', 'g_clear_object', 'g_clear_pointer', 'g_return_val_if_fail', 'G_DEFINE_TYPE'] def check_suppress(suppressions, source, data): line, _, rest = data.partition(',') line = int(line) - 1 assert line < len(source) for suppression in suppressions: if suppression in source[line]: return True return False source = [] for line in sys.stdin: line = line[:-1] keyword, _, rest = line.partition(':') # Source file if keyword == 'SF': source = file(rest).readlines() # Branch coverage data elif keyword == 'BRDA': if check_suppress(branch_suppress, source, rest): continue # Line coverage data elif keyword == 'DA': if check_suppress(line_suppress, source, rest): continue print line ./AUTHORS0000644000015600001650000000003112701256660012144 0ustar jenkinsjenkins# Generated by Makefile ./m4/0000755000015600001650000000000012701256660011422 5ustar jenkinsjenkins./m4/gtest.m40000644000015600001650000000477112701256660013023 0ustar jenkinsjenkins# Copyright (C) 2012 Canonical, Ltd. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice (including the next # paragraph) shall be included in all copies or substantial portions of the # Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # Checks whether the gtest source is available on the system. Allows for # adjusting the include and source path. Sets have_gtest=yes if the source is # present. Sets GTEST_CPPFLAGS and GTEST_SOURCE to the preprocessor flags and # source location respectively. AC_DEFUN([CHECK_GTEST], [ AC_ARG_WITH([gtest-include-path], [AS_HELP_STRING([--with-gtest-include-path], [location of the Google test headers])], [GTEST_CPPFLAGS="-I$withval"]) AC_ARG_WITH([gtest-source-path], [AS_HELP_STRING([--with-gtest-source-path], [location of the Google test sources, defaults to /usr/src/gtest])], [GTEST_SOURCE="$withval"], [GTEST_SOURCE="/usr/src/gtest"]) GTEST_CPPFLAGS="$GTEST_CPPFLAGS -I$GTEST_SOURCE" AC_LANG_PUSH([C++]) tmp_CPPFLAGS="$CPPFLAGS" CPPFLAGS="$CPPFLAGS $GTEST_CPPFLAGS" AC_CHECK_HEADER([gtest/gtest.h]) CPPFLAGS="$tmp_CPPFLAGS" AC_LANG_POP AC_CHECK_FILES([$GTEST_SOURCE/src/gtest-all.cc] [$GTEST_SOURCE/src/gtest_main.cc], [have_gtest_source=yes], [have_gtest_source=no]) AS_IF([test "x$ac_cv_header_gtest_gtest_h" = xyes -a \ "x$have_gtest_source" = xyes], [have_gtest=yes] [AC_SUBST(GTEST_CPPFLAGS)] [AC_SUBST(GTEST_SOURCE)], [have_gtest=no]) ]) # CHECK_GTEST ./m4/gcov.m40000644000015600001650000000470512701256660012630 0ustar jenkinsjenkins# Checks for existence of coverage tools: # * gcov # * lcov # * genhtml # * gcovr # # Sets ac_cv_check_gcov to yes if tooling is present # and reports the executables to the variables LCOV, GCOVR and GENHTML. AC_DEFUN([AC_TDD_GCOV], [ AC_ARG_ENABLE(gcov, AS_HELP_STRING([--enable-gcov], [enable coverage testing with gcov]), [use_gcov=$enableval], [use_gcov=no]) if test "x$use_gcov" = "xyes"; then # we need gcc: if test "$GCC" != "yes"; then AC_MSG_ERROR([GCC is required for --enable-gcov]) fi # Check if ccache is being used AC_CHECK_PROG(SHTOOL, shtool, shtool) case `$SHTOOL path $CC` in *ccache*[)] gcc_ccache=yes;; *[)] gcc_ccache=no;; esac if test "$gcc_ccache" = "yes" && (test -z "$CCACHE_DISABLE" || test "$CCACHE_DISABLE" != "1"); then AC_MSG_ERROR([ccache must be disabled when --enable-gcov option is used. You can disable ccache by setting environment variable CCACHE_DISABLE=1.]) fi lcov_version_list="1.6 1.7 1.8 1.9" AC_CHECK_PROG(LCOV, lcov, lcov) AC_CHECK_PROG(GENHTML, genhtml, genhtml) if test "$LCOV"; then AC_CACHE_CHECK([for lcov version], glib_cv_lcov_version, [ glib_cv_lcov_version=invalid lcov_version=`$LCOV -v 2>/dev/null | $SED -e 's/^.* //'` for lcov_check_version in $lcov_version_list; do if test "$lcov_version" = "$lcov_check_version"; then glib_cv_lcov_version="$lcov_check_version (ok)" fi done ]) else lcov_msg="To enable code coverage reporting you must have one of the following lcov versions installed: $lcov_version_list" AC_MSG_ERROR([$lcov_msg]) fi case $glib_cv_lcov_version in ""|invalid[)] lcov_msg="You must have one of the following versions of lcov: $lcov_version_list (found: $lcov_version)." AC_MSG_ERROR([$lcov_msg]) LCOV="exit 0;" ;; esac if test -z "$GENHTML"; then AC_MSG_ERROR([Could not find genhtml from the lcov package]) fi ac_cv_check_gcov=yes ac_cv_check_lcov=yes # Remove all optimization flags from CFLAGS changequote({,}) CFLAGS=`echo "$CFLAGS" | $SED -e 's/-O[0-9]*//g'` changequote([,]) # Add the special gcc flags COVERAGE_CFLAGS="-O0 -fprofile-arcs -ftest-coverage" COVERAGE_CXXFLAGS="-O0 -fprofile-arcs -ftest-coverage" COVERAGE_LDFLAGS="-lgcov" # Check availability of gcovr AC_CHECK_PROG(GCOVR, gcovr, gcovr) if test -z "$GCOVR"; then ac_cv_check_gcovr=no else ac_cv_check_gcovr=yes fi fi ]) # AC_TDD_GCOV ./data/0000755000015600001650000000000012701256660012013 5ustar jenkinsjenkins./data/com.canonical.indicator.datetime.gschema.xml.in.in0000644000015600001650000001550512701256660023435 0ustar jenkinsjenkins true <_summary>Show the clock in the panel <_description> Controls whether the clock indicator appears in the panel or not. 'locale-default' <_summary>What the time format should be <_description> Controls the time format that is displayed in the indicator. For almost all users this should be the default for their locale. If you think the setting is wrong for your locale please join or talk to the translation team for your language. If you just want something different you can adjust this to be either 12 or 24 time. Or, you can use a custom format string and set the custom-time-format setting. "%l:%M %p" <_summary>The format string passed to strftime <_description> The format of the time and/or date that is visible on the panel when using the indicator. For most users this will be a set of predefined values as determined by the configuration utility, but advanced users can change it to anything strftime can accept. Look at the man page on strftime for more information. false <_summary>Show the number of seconds in the indicator <_description> Makes the datetime indicator show the number of seconds in the indicator. It's important to note that this will cause additional battery drain as the time will update 60 times as often, so it is not recommended. Also, this setting will be ignored if the time-format value is set to custom. false <_summary>Show the day of the week in the indicator <_description> Puts the day of the week on the panel along with the time and/or date depending on settings. This setting will be ignored if the time-format value is set to custom. false <_summary>Show the month and date in the indicator <_description> Puts the month and the date in the panel along with the time and/or day of the week depending on settings. This setting will be ignored if the time-format value is set to custom. false <_summary>Show the year in the indicator <_description> Puts the year in the panel along with the month and the date. This setting will be ignored if either the time-format value is set to custom or if show-date is set to false. true <_summary>Show the monthly calendar in the indicator <_description> Puts the monthly calendar in indicator-datetime's menu. false <_summary>Show week numbers in calendar <_description> Shows the week numbers in the monthly calendar in indicator-datetime's menu. true <_summary>Show events in the indicator <_description> Shows events from Evolution in indicator-datetime's menu. false <_summary>Show the auto-detected location in the indicator <_description> Shows your current location (determined from geoclue and /etc/timezone) in indicator-datetime's menu. false <_summary>Show locations in the indicator <_description> Shows custom defined locations in indicator-datetime's menu. ['UTC'] <_summary>A List of locations <_description> Adds the list of locations the user has configured to display in the indicator-datetime menu. '' <_summary>The name of the current timezone <_description> Some timezones can be known by many different cities or names. This setting describes how the current zone prefers to be named. Format is "TIMEZONE NAME" (e.g. "America/New_York Boston" to name the New_York zone Boston). 'pulse' <_summary>What kind of haptic feedback, if any, to trigger with an alarm. <_description> What kind of haptic feedback, if any, to trigger with an alarm. Two modes are currently supported: 'pulse', 'none'. '@CALENDAR_DEFAULT_SOUND@' <_summary>The calendar's default sound file. <_description> If a calendar or reminder event doesn't specify its own sound file, this file will be used as the fallback sound. '@ALARM_DEFAULT_SOUND@' <_summary>The alarm's default sound file. <_description> If an alarm doesn't specify its own sound file, this file will be used as the fallback sound. 50 <_summary>The alarm's default volume level. <_description> The volume at which alarms will be played. 10 <_summary>The alarm's duration. <_description> How long the alarm's sound will be looped if its snap decision is not dismissed by the user. 5 <_summary>The snooze duration. <_description> How long to wait when the user hits the Snooze button. ./data/com.canonical.indicator.datetime.AlarmProperties.xml0000644000015600001650000000321312701256660024116 0ustar jenkinsjenkins The default alarm sound's filename. What kind of haptic feedback, if any, to trigger with an alarm. Two modes are currently supported: 'pulse', 'none'. How loudly to play alarm sounds. [Range: 1-100] How long an alarm's sound should be looped. How many minutes to wait when the Snooze button is pressed. [Range: 1-15] ./data/indicator-datetime.upstart.desktop.in0000644000015600001650000000027412701256660021265 0ustar jenkinsjenkins[Desktop Entry] Type=Application Name=Indicator Date & Time Exec=@pkglibexecdir@/indicator-datetime-service OnlyShowIn=Unity; NoDisplay=true StartupNotify=false Terminal=false Hidden=true ./data/indicator-datetime.desktop.in0000644000015600001650000000035612701256660017565 0ustar jenkinsjenkins[Desktop Entry] Type=Application Name=Indicator Date & Time Exec=@pkglibexecdir@/indicator-datetime-service OnlyShowIn=Unity;GNOME;Pantheon; NoDisplay=true StartupNotify=false Terminal=false AutostartCondition=GNOME3 unless-session gnome ./data/CMakeLists.txt0000644000015600001650000000620012701256660014551 0ustar jenkinsjenkins## ## GSettings schema ## include (UseGSettings) set (SCHEMA_NAME "com.canonical.indicator.datetime.gschema.xml") set (SCHEMA_FILE_IN_IN "${CMAKE_CURRENT_SOURCE_DIR}/${SCHEMA_NAME}.in.in") set (SCHEMA_FILE_IN "${CMAKE_CURRENT_BINARY_DIR}/${SCHEMA_NAME}.in") set (SCHEMA_FILE "${CMAKE_CURRENT_BINARY_DIR}/${SCHEMA_NAME}") # generate the .xml.in file so cmake constants are included configure_file(${SCHEMA_FILE_IN_IN} ${SCHEMA_FILE_IN}) # generate the .xml file using intltool set (ENV{LC_ALL} "C") execute_process (COMMAND intltool-merge -quiet --xml-style --utf8 --no-translations "${SCHEMA_FILE_IN}" "${SCHEMA_FILE}") # let UseGSettings do the rest add_schema (${SCHEMA_FILE}) ## ## Upstart Job File ## # where to install set (UPSTART_JOB_DIR "${CMAKE_INSTALL_FULL_DATADIR}/upstart/sessions") message (STATUS "${UPSTART_JOB_DIR} is the Upstart Job File install dir") set (UPSTART_JOB_NAME "${CMAKE_PROJECT_NAME}.conf") set (UPSTART_JOB_FILE "${CMAKE_CURRENT_BINARY_DIR}/${UPSTART_JOB_NAME}") set (UPSTART_JOB_FILE_IN "${CMAKE_CURRENT_SOURCE_DIR}/${UPSTART_JOB_NAME}.in") # build it set (pkglibexecdir "${CMAKE_INSTALL_FULL_PKGLIBEXECDIR}") configure_file ("${UPSTART_JOB_FILE_IN}" "${UPSTART_JOB_FILE}") # install it install (FILES "${UPSTART_JOB_FILE}" DESTINATION "${UPSTART_JOB_DIR}") ## ## XDG Autostart File ## # where to install set (XDG_AUTOSTART_DIR "/etc/xdg/autostart") message (STATUS "${XDG_AUTOSTART_DIR} is the DBus Service File install dir") set (XDG_AUTOSTART_NAME "${CMAKE_PROJECT_NAME}.desktop") set (XDG_AUTOSTART_FILE "${CMAKE_CURRENT_BINARY_DIR}/${XDG_AUTOSTART_NAME}") set (XDG_AUTOSTART_FILE_IN "${CMAKE_CURRENT_SOURCE_DIR}/${XDG_AUTOSTART_NAME}.in") # build it set (pkglibexecdir "${CMAKE_INSTALL_FULL_PKGLIBEXECDIR}") configure_file ("${XDG_AUTOSTART_FILE_IN}" "${XDG_AUTOSTART_FILE}") # install it install (FILES "${XDG_AUTOSTART_FILE}" DESTINATION "${XDG_AUTOSTART_DIR}") ## ## Upstart XDG Autostart Override ## # where to install set (UPSTART_XDG_AUTOSTART_DIR "${CMAKE_INSTALL_FULL_DATAROOTDIR}/upstart/xdg/autostart") message (STATUS "${UPSTART_XDG_AUTOSTART_DIR} is the Upstart XDG autostart override dir") set (UPSTART_XDG_AUTOSTART_NAME "${CMAKE_PROJECT_NAME}.upstart.desktop") set (UPSTART_XDG_AUTOSTART_FILE "${CMAKE_CURRENT_BINARY_DIR}/${UPSTART_XDG_AUTOSTART_NAME}") set (UPSTART_XDG_AUTOSTART_FILE_IN "${CMAKE_CURRENT_SOURCE_DIR}/${UPSTART_XDG_AUTOSTART_NAME}.in") # build it set (pkglibexecdir "${CMAKE_INSTALL_FULL_PKGLIBEXECDIR}") configure_file ("${UPSTART_XDG_AUTOSTART_FILE_IN}" "${UPSTART_XDG_AUTOSTART_FILE}") # install it install (FILES "${UPSTART_XDG_AUTOSTART_FILE}" DESTINATION "${UPSTART_XDG_AUTOSTART_DIR}" RENAME "${XDG_AUTOSTART_NAME}") ## ## Unity Indicator File ## # where to install set (UNITY_INDICATOR_DIR "${CMAKE_INSTALL_FULL_DATAROOTDIR}/unity/indicators") message (STATUS "${UNITY_INDICATOR_DIR} is the Unity Indicator install dir") set (UNITY_INDICATOR_NAME "com.canonical.indicator.datetime") set (UNITY_INDICATOR_FILE "${CMAKE_CURRENT_SOURCE_DIR}/${UNITY_INDICATOR_NAME}") install (FILES "${UNITY_INDICATOR_FILE}" DESTINATION "${UNITY_INDICATOR_DIR}") ./data/indicator-datetime.conf.in0000644000015600001650000000031212701256660017031 0ustar jenkinsjenkinsdescription "Indicator Date & Time Backend" start on indicator-services-start stop on desktop-end or indicator-services-end respawn respawn limit 2 10 exec @pkglibexecdir@/indicator-datetime-service ./data/com.canonical.indicator.datetime0000644000015600001650000000072112701256660020210 0ustar jenkinsjenkins[Indicator Service] Name=indicator-datetime ObjectPath=/com/canonical/indicator/datetime Position=20 [desktop] ObjectPath=/com/canonical/indicator/datetime/desktop [desktop_greeter] ObjectPath=/com/canonical/indicator/datetime/desktop_greeter [desktop_lockscreen] ObjectPath=/com/canonical/indicator/datetime/desktop_greeter [phone] ObjectPath=/com/canonical/indicator/datetime/phone [phone_greeter] ObjectPath=/com/canonical/indicator/datetime/phone_greeter ./MERGE-REVIEW0000644000015600001650000000346012701256660012666 0ustar jenkinsjenkins* '''Checklist for component''': indicator-datetime * '''Component Test Plan''': https://wiki.ubuntu.com/Process/Merges/TestPlan/indicator-datetime * '''Trunk URL''': lp:indicator-datetime * '''Ubuntu Package URL (LP)''': http://launchpad.net/ubuntu/+source/indicator-datetime This documents the expections that the project has on what both submitters and reviewers should ensure that they've done for a merge into the project. == MP Submission Checklist Template == '''Note: Please ensure you include the following form filled out and submitted along side your code to the MP ticket.''' * Are there any related MPs required for this MP to build/function as expected? Please list. * Is your branch in sync with latest trunk? (e.g. bzr pull lp:trunk -> no changes) * Did the code build without warnings? * Did the tests run successfully? * Did you perform an exploratory manual test run of your code change and any related functionality? * If you changed the packaging (debian), did you subscribe the ubuntu-unity team to this MP? * Has your component test plan been executed successfully on emulator, N4? * Please list which manual tests are germane for the reviewer in this MR. == MP Review Checklist Template == '''Note: Please ensure you include the following form filled out and submitted along side your code to the MP ticket.''' * Have you checked that the submitter has accurately filled out the submitter checklist and has taken no shortcuts? * Did you run the manual tests listed by the submitter? * Did you do exploratory testing related to the component you own with the MP changeset included? * If new features have been added, are the manual tests sufficient to cover them? == MP Landing Checklist Template == * Ensure that the checklists have been properly filled out by submitter and all reviewers ./INSTALL0000644000015600001650000000351112701256660012133 0ustar jenkinsjenkins# # Copyright (C) 2013 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 . # BUILD DEPENDENCIES ================== build dependencies for indicator-datetime-service * glib-2.0 >= 2.36 * gio-unix-2.0 >= 2.36 * geoclue >= 0.12 * libical >= 0.48 * libecal-1.2 >= 3.5 * libedataserver-1.2 >= 3.5 * libnotify >= 0.7.6 * url-dispatcher-1 >= 1 * json-glib-1.0 >= 0.16.2 Additional build dependencies for the gnome-control-center panel: * gtk+-3.0>=3.1.4 * timezonemap * libgnome-control-center * polkit-gobject-1 Build dependencies for testing / code coverage: * gcovr (gcovr, 2.4 or later) * lcov (lcov, 1.9 or later) * google test (libgtest-dev, 1.6.0 or later) * cppcheck (cppcheck) Building the code ----------------- 1. $ cd indicator-datetime-X.Y.Z 2. $ mkdir build 3. $ cd build 4. $ cmake .. or $ cmake -DCMAKE_INSTALL_PREFIX=/your/install/prefix/here .. or $ cmake -GNinja .. 5. $ make Running the tests ----------------- 1. $ cd indicator-datetime-X.Y.Z 2. $ mkdir build 3. $ cd build 4. $ cmake .. 5. $ make 6. $ make test 7. $ make cppcheck Generating Test Coverage Reports -------------------------------- 1. $ cd indicator-datetime-X.Y.Z 2. $ mkdir build-coverage 3. $ cd build-coverage 4. $ cmake -DCMAKE_BUILD_TYPE=coverage .. 5. $ make 6. $ make coverage-html ./NEWS0000644000015600001650000000141012701256660011575 0ustar jenkinsjenkins12.10.2 - Fix 12.10.0 appointment calendar regression. (LP: #1060263) 12.10.1 - Gracefully handle clock skew (LP: #917236) - Raise the version number of our EDS dependency (LP: #1024437) - Fix X-Ubuntu-Gettext-Domain entries in the .desktop file (LP: #1048834) - Remove unnecessary watching for geoclue address provider changes 12.10.0 - Support EDS 3.6's API (cyphermox) - Apply an 'en space' between the date and time strings. (LP #749847) lp:~bobowen/indicator-datetime/fix-for-749847 - Sort locations as spec'ed by https://wiki.ubuntu.com/TimeAndDate (LP #833325) lp:~charlesk/indicator-datetime/lp-833325 - Fix a bug that caused location settings to be re-saved each 2 seconds lp:~charlesk/indicator-datetime/unnecessary-saves - Drop GTK+ 2 support ./CMakeLists.txt0000644000015600001650000000620112701256660013641 0ustar jenkinsjenkinsproject (indicator-datetime C CXX) cmake_minimum_required (VERSION 2.8.9) list (APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake) set (PROJECT_VERSION "14.04.0") set (PACKAGE ${CMAKE_PROJECT_NAME}) set (GETTEXT_PACKAGE "indicator-datetime") add_definitions (-DGETTEXT_PACKAGE="${GETTEXT_PACKAGE}" -DGNOMELOCALEDIR="${CMAKE_INSTALL_FULL_LOCALEDIR}") set(ALARM_DEFAULT_SOUND "/usr/share/sounds/ubuntu/ringtones/Alarm clock.ogg") set(CALENDAR_DEFAULT_SOUND "/usr/share/sounds/ubuntu/ringtones/Marimbach.ogg") add_definitions(-DALARM_DEFAULT_SOUND="${ALARM_DEFAULT_SOUND}" -DCALENDAR_DEFAULT_SOUND="${CALENDAR_DEFAULT_SOUND}") option (enable_tests "Build the package's automatic tests." ON) option (enable_lcov "Generate lcov code coverage reports." ON) ## ## GNU standard installation directories ## include (GNUInstallDirs) if (EXISTS "/etc/debian_version") # Workaround for libexecdir on debian set (CMAKE_INSTALL_LIBEXECDIR "${CMAKE_INSTALL_LIBDIR}") set (CMAKE_INSTALL_FULL_LIBEXECDIR "${CMAKE_INSTALL_FULL_LIBDIR}") endif () set (CMAKE_INSTALL_PKGLIBEXECDIR "${CMAKE_INSTALL_LIBEXECDIR}/${CMAKE_PROJECT_NAME}") set (CMAKE_INSTALL_FULL_PKGLIBEXECDIR "${CMAKE_INSTALL_FULL_LIBEXECDIR}/${CMAKE_PROJECT_NAME}") ## ## Check for prerequisites ## find_package (PkgConfig REQUIRED) include (CheckIncludeFile) include (FindPkgConfig) pkg_check_modules (SERVICE_DEPS REQUIRED glib-2.0>=2.36 gio-unix-2.0>=2.36 libical>=0.48 libecal-1.2>=3.5 libedataserver-1.2>=3.5 gstreamer-1.0>=1.2 libnotify>=0.7.6 url-dispatcher-1>=1 properties-cpp>=0.0.1) include_directories (SYSTEM ${SERVICE_DEPS_INCLUDE_DIRS}) ## ## custom targets ## set (ARCHIVE_NAME ${CMAKE_PROJECT_NAME}-${PROJECT_VERSION}) add_custom_target (dist COMMAND bzr export --root=${ARCHIVE_NAME} ${CMAKE_BINARY_DIR}/${ARCHIVE_NAME}.tar.gz WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}) add_custom_target (clean-coverage COMMAND find ${CMAKE_BINARY_DIR} -name '*.gcda' | xargs rm -f) add_custom_target (cppcheck COMMAND cppcheck --enable=all -q --error-exitcode=2 --inline-suppr ${CMAKE_SOURCE_DIR}/src ${CMAKE_SOURCE_DIR}/tests) ## ## Actual building ## set (CC_WARNING_ARGS " -Wall -Wshadow -Wextra -Wunused -Wformat=2 -Wno-missing-field-initializers") set (CXX_WARNING_ARGS " -Wall -Wextra -pedantic -Wno-missing-field-initializers") include_directories (${CMAKE_CURRENT_SOURCE_DIR}/include) include_directories (${CMAKE_CURRENT_BINARY_DIR}/include) # testing & coverage if (${enable_tests}) pkg_check_modules (DBUSTEST REQUIRED dbustest-1>=14.04.0) set (GTEST_SOURCE_DIR /usr/src/gtest/src) set (GTEST_INCLUDE_DIR ${GTEST_SOURCE_DIR}/..) set (GTEST_LIBS -lpthread) enable_testing () if (${enable_lcov}) include(GCov) endif () endif () # actually build things add_subdirectory(include) add_subdirectory(src) add_subdirectory(data) add_subdirectory(po) if (${enable_tests}) add_subdirectory(tests) endif () ./ChangeLog0000644000015600001650000000003112701256660012646 0ustar jenkinsjenkins# Generated by Makefile