./0000755000004100000410000000000013151304763011246 5ustar www-datawww-data./CMakeLists.txt0000644000004100000410000000565713151304762014022 0ustar www-datawww-dataproject (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}") ## ## Always Be Testing ## enable_testing() ## ## 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 libaccounts-glib>=1.18 messaging-menu>=12.10 uuid>=2.25) 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 (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) # actually build things add_subdirectory(include) add_subdirectory(src) add_subdirectory(data) add_subdirectory(po) add_subdirectory(tests) # testing & coverage find_package(CoverageReport) ENABLE_COVERAGE_REPORT( TARGETS indicatordatetimeservice indicator-datetime-service TESTS ${COVERAGE_TEST_TARGETS} FILTER /usr/include ${CMAKE_BINARY_DIR}/* ) ./NEWS0000644000004100000410000000141013151304754011741 0ustar www-datawww-data12.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 ./INSTALL0000644000004100000410000000351113151304754012277 0ustar www-datawww-data# # 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 ./README0000644000004100000410000001147713151304754012140 0ustar www-datawww-dataACTIONS ======= * "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 ./include/0000755000004100000410000000000013151304754012671 5ustar www-datawww-data./include/datetime/0000755000004100000410000000000013151304754014465 5ustar www-datawww-data./include/datetime/planner-aggregate.h0000644000004100000410000000254313151304754020225 0ustar www-datawww-data/* * 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/date-time.h0000644000004100000410000000575613151304754016524 0ustar www-datawww-data/* * 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; 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/CMakeLists.txt0000644000004100000410000000000213151304754017215 0ustar www-datawww-data ./include/datetime/actions.h0000644000004100000410000000432313151304754016300 0ustar www-datawww-data/* * 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 open_alarm_app() =0; virtual void open_appointment(const Appointment&, const DateTime&) =0; virtual void open_calendar_app(const DateTime&) =0; virtual void 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/wakeup-timer.h0000644000004100000410000000250013151304754017245 0ustar www-datawww-data/* * 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/timezone-geoclue.h0000644000004100000410000000264613151304754020121 0ustar www-datawww-data/* * 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.h0000644000004100000410000000473713151304754016511 0ustar www-datawww-data/* * 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 cal_notification_enabled; core::Property cal_notification_sounds; core::Property cal_notification_vibrations; core::Property cal_notification_bubbles; core::Property cal_notification_list; core::Property vibrate_silent_mode; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_SETTINGS_H ./include/datetime/clock.h0000644000004100000410000000424213151304754015733 0ustar www-datawww-data/* * 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-upcoming.h0000644000004100000410000000311513151304754020114 0ustar www-datawww-data/* * 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/dbus-shared.h0000644000004100000410000000376113151304754017046 0ustar www-datawww-data/* * 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" namespace Bus { namespace Timedate1 { static constexpr char const * BUSNAME {"org.freedesktop.timedate1"}; static constexpr char const * ADDR {"/org/freedesktop/timedate1"}; static constexpr char const * IFACE {"org.freedesktop.timedate1"}; namespace Properties { static constexpr char const * TIMEZONE {"Timezone"}; } namespace Methods { static constexpr char const * SET_TIMEZONE {"SetTimezone"}; } } namespace Properties { static constexpr char const * IFACE {"org.freedesktop.DBus.Properties"}; namespace Methods { static constexpr char const * GET {"Get"}; } namespace Signals { static constexpr char const * PROPERTIES_CHANGED {"PropertiesChanged"}; } } } #endif /* INDICATOR_DATETIME_DBUS_SHARED_H */ ./include/datetime/snap.h0000644000004100000410000000355213151304754015604 0ustar www-datawww-data/* * 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 // GDBusConnection #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, GDBusConnection* system_bus); virtual ~Snap(); enum class Response { None, Snooze, ShowApp }; typedef std::function response_func; void operator()(const Appointment& appointment, const Alarm& alarm, response_func on_response); private: class Impl; std::unique_ptr impl; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_SNAP_H ./include/datetime/timezones-live.h0000644000004100000410000000314213151304754017610 0ustar www-datawww-data/* * 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 // 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, const std::shared_ptr& primary_timezone); private: void update_geolocation(); void update_timezones(); std::shared_ptr m_primary_timezone; std::shared_ptr m_settings; std::shared_ptr m_geo; }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_LIVE_TIMEZONES_H ./include/datetime/settings-live.h0000644000004100000410000000541713151304754017442 0ustar www-datawww-data/* * 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_cal_notification(GSettings*, gchar*, gpointer); static void on_changed_general_notification(GSettings*, gchar*, gpointer); void update_key_ccid(const std::string& key); void update_key_cal_notification(const std::string& key); void update_key_general_notification(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_cal_notification_enabled(); void update_cal_notification_sounds(); void update_cal_notification_vibrations(); void update_cal_notification_bubbles(); void update_cal_notification_list(); void update_vibrate_silent_mode(); GSettings* m_settings; GSettings* m_settings_cal_notification; GSettings* m_settings_general_notification; // 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/appointment.h0000644000004100000410000000347113151304754017201 0ustar www-datawww-data/* * 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; bool has_sound() const; bool has_text() 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/formatter.h0000644000004100000410000001004213151304754016636 0ustar www-datawww-data/* * 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/engine-mock.h0000644000004100000410000000331013151304754017027 0ustar www-datawww-data/* * 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/timezone-timedated.h0000644000004100000410000000306413151304754020431 0ustar www-datawww-data/* * 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 #include // base class #include // GDBusConnection* #include // std::string namespace unity { namespace indicator { namespace datetime { /** * \brief A #Timezone that gets its information from org.freedesktop.timedate1 */ class TimedatedTimezone: public Timezone { public: TimedatedTimezone(GDBusConnection* connection); ~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/engine-eds.h0000644000004100000410000000367013151304754016662 0ustar www-datawww-data/* * 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 Myself; /** * Class wrapper around EDS so multiple #EdsPlanners can share resources * * @see EdsPlanner */ class EdsEngine: public Engine { public: EdsEngine(const std::shared_ptr &myself); ~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/wakeup-timer-mainloop.h0000644000004100000410000000316613151304754021072 0ustar www-datawww-data/* * 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/menu.h0000644000004100000410000000455313151304754015611 0ustar www-datawww-data/* * 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 #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(); static std::vector get_display_appointments( const std::vector&, const DateTime& start, unsigned int max_items=5); 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/utils.h0000644000004100000410000000416613151304754016005 0ustar www-datawww-data/* * 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/locations-settings.h0000644000004100000410000000323413151304754020471 0ustar www-datawww-data/* * 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/locations.h0000644000004100000410000000360213151304754016632 0ustar www-datawww-data/* * 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/state.h0000644000004100000410000000474213151304754015765 0ustar www-datawww-data/* * 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/timezones.h0000644000004100000410000000273713151304754016664 0ustar www-datawww-data/* * 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/wakeup-timer-powerd.h0000644000004100000410000000314213151304754020546 0ustar www-datawww-data/* * 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/settings-shared.h0000644000004100000410000000557613151304754017757 0ustar www-datawww-data/* * 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_NOTIFY_APPS_SCHEMA_ID "com.ubuntu.notifications.settings.applications" #define SETTINGS_VIBRATE_SILENT_KEY "vibrate-silent-mode" #define SETTINGS_NOTIFY_SCHEMA_ID "com.ubuntu.notifications.settings" #define SETTINGS_NOTIFY_CALENDAR_PATH "/com/ubuntu/NotificationSettings/com.ubuntu.calendar/calendar/" #define SETTINGS_NOTIFY_ENABLED_KEY "enable-notifications" #define SETTINGS_NOTIFY_SOUNDS_KEY "use-sounds-notifications" #define SETTINGS_NOTIFY_VIBRATIONS_KEY "use-vibrations-notifications" #define SETTINGS_NOTIFY_BUBBLES_KEY "use-bubbles-notifications" #define SETTINGS_NOTIFY_LIST_KEY "use-list-notifications" #endif // INDICATOR_DATETIME_SETTINGS_SHARED ./include/datetime/actions-live.h0000644000004100000410000000367713151304754017250 0ustar www-datawww-data/* * 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: enum Desktop { OTHER = 0, UNITY7, UNITY8, }; explicit LiveActions(const std::shared_ptr& state_in); virtual ~LiveActions() =default; bool desktop_has_calendar_app() const override; void open_alarm_app() override; void open_appointment(const Appointment&, const DateTime&) override; void open_calendar_app(const DateTime&) override; void open_settings_app() override; void set_location(const std::string& zone, const std::string& name) override; protected: virtual Desktop get_desktop(); virtual void execute_command(const std::string& command); virtual void dispatch_url(const std::string& url); void unity8_open_appointment(const Appointment& appt, const DateTime& date); }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_ACTIONS_H ./include/datetime/timezone.h0000644000004100000410000000223013151304754016465 0ustar www-datawww-data/* * 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/planner-range.h0000644000004100000410000000450413151304754017372 0ustar www-datawww-data/* * 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/planner-month.h0000644000004100000410000000307413151304754017424 0ustar www-datawww-data/* * 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/planner.h0000644000004100000410000000245713151304754016305 0ustar www-datawww-data/* * 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/myself.h0000644000004100000410000000275013151304754016141 0ustar www-datawww-data/* * Copyright 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: * Renato Araujo Oliveira Filho */ #ifndef INDICATOR_DATETIME_MYSELF_H #define INDICATOR_DATETIME_MYSELF_H #include #include #include #include #include typedef struct _AgManager AgManager; namespace unity { namespace indicator { namespace datetime { class Myself { public: Myself(); const core::Property>& emails() { return m_emails; } bool isMyEmail(const std::string &email); private: std::shared_ptr m_accounts_manager; core::Property > m_emails; static void on_accounts_changed(AgManager*, guint, Myself*); void reloadEmails(); }; } // namespace datetime } // namespace indicator } // namespace unity #endif // INDICATOR_DATETIME_MYSELF_H ./include/datetime/alarm-queue-simple.h0000644000004100000410000000314313151304754020344 0ustar www-datawww-data/* * 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/exporter.h0000644000004100000410000000312613151304754016510 0ustar www-datawww-data/* * 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/engine.h0000644000004100000410000000330513151304754016104 0ustar www-datawww-data/* * 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/datetime/alarm-queue.h0000644000004100000410000000257313151304754017063 0ustar www-datawww-data/* * 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/planner-snooze.h0000644000004100000410000000276613151304754017623 0ustar www-datawww-data/* * 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/clock-mock.h0000644000004100000410000000327613151304754016670 0ustar www-datawww-data/* * 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/CMakeLists.txt0000644000004100000410000000007313151304754015431 0ustar www-datawww-dataadd_subdirectory(datetime) add_subdirectory(notifications) ./include/notifications/0000755000004100000410000000000013151304754015542 5ustar www-datawww-data./include/notifications/CMakeLists.txt0000644000004100000410000000000013151304754020270 0ustar www-datawww-data./include/notifications/dbus-shared.h0000644000004100000410000000261013151304754020113 0ustar www-datawww-data/* * 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 */ ./include/notifications/haptic.h0000644000004100000410000000250013151304754017160 0ustar www-datawww-data/* * 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, bool repeat = false); ~Haptic(); private: class Impl; std::unique_ptr impl; }; /*** **** ***/ } // namespace notifications } // namespace indicator } // namespace unity #endif // UNITY_INDICATOR_NOTIFICATIONS_HAPTIC_H ./include/notifications/notifications.h0000644000004100000410000000761313151304754020573 0ustar www-datawww-data/* * 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); void set_start_time(uint64_t time); /* 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"}; static constexpr char const * HINT_INTERACTIVE {"x-canonical-switch-to-application"}; /* 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. After notification dissapear */ void set_closed_callback (std::function); /** Sets the time-out callback. This will be called exactly once. */ void set_timeout_callback (std::function); /** Sets if a notification bubble should be displayed. */ void set_show_notification_bubble (bool show); /** Sets if notification should be posted to messaging menu after it is closed. */ void set_post_to_messaging_menu (bool post); 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.h0000644000004100000410000000244613151304754017011 0ustar www-datawww-data/* * 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 #include namespace unity { namespace indicator { namespace notifications { /*** **** ***/ /** * A class that forces the screen display on and inhibits sleep */ class Awake { public: explicit Awake(GDBusConnection* system_bus, 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/sound.h0000644000004100000410000000400313151304754017040 0ustar www-datawww-data/* * 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 ./COPYING0000644000004100000410000010451313151304754012305 0ustar www-datawww-data 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 . ./src/0000755000004100000410000000000013151304763012035 5ustar www-datawww-data./src/planner-aggregate.cpp0000644000004100000410000000455413151304754016134 0ustar www-datawww-data/* * 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/CMakeLists.txt0000644000004100000410000000457113151304754014604 0ustar www-datawww-dataset (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 myself.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} -std=c++11") set_source_files_properties(${SERVICE_C_SOURCES} PROPERTIES COMPILE_FLAGS "${CXX_WARNING_ARGS} -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} -std=c++11") target_link_libraries (${SERVICE_EXEC} ${SERVICE_LIB} ${SERVICE_DEPS_LIBRARIES}) install (TARGETS ${SERVICE_EXEC} RUNTIME DESTINATION ${CMAKE_INSTALL_FULL_PKGLIBEXECDIR}) ./src/timezone-timedated.cpp0000644000004100000410000001441713151304754016340 0ustar www-datawww-data/* * 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 namespace unity { namespace indicator { namespace datetime { /*** **** ***/ class TimedatedTimezone::Impl { public: Impl(TimedatedTimezone& owner, GDBusConnection* connection): m_owner{owner}, m_connection{G_DBUS_CONNECTION(g_object_ref(G_OBJECT(connection)))}, m_cancellable{g_cancellable_new()} { // set the fallback value m_owner.timezone.set("Etc/Utc"); // watch for timedate1 on the bus m_watcher_id = g_bus_watch_name_on_connection( m_connection, Bus::Timedate1::BUSNAME, G_BUS_NAME_WATCHER_FLAGS_AUTO_START, on_timedate1_appeared, on_timedate1_vanished, this, nullptr); // listen for changed properties m_signal_subscription_id = g_dbus_connection_signal_subscribe( m_connection, Bus::Timedate1::IFACE, Bus::Properties::IFACE, Bus::Properties::Signals::PROPERTIES_CHANGED, Bus::Timedate1::ADDR, nullptr, G_DBUS_SIGNAL_FLAGS_NONE, on_properties_changed, this, nullptr); } ~Impl() { g_cancellable_cancel(m_cancellable); g_clear_object(&m_cancellable); g_bus_unwatch_name(m_watcher_id); g_dbus_connection_signal_unsubscribe(m_connection, m_signal_subscription_id); g_clear_object(&m_connection); } private: static void on_timedate1_appeared(GDBusConnection * /*connection*/, const gchar * name, const gchar * /*name_owner*/, gpointer gself) { g_debug("%s appeared on bus", name); static_cast(gself)->ask_for_timezone(); } static void on_timedate1_vanished(GDBusConnection * /*connection*/, const gchar * name, gpointer /*gself*/) { g_debug("%s not present on bus", name); } static void on_properties_changed(GDBusConnection * /*connection*/, const gchar * /*sender_name*/, const gchar * /*object_path*/, const gchar * /*interface_name*/, const gchar * /*signal_name*/, GVariant * parameters, gpointer gself) { auto self = static_cast(gself); GVariant* changed_properties {}; gchar** invalidated_properties {}; g_variant_get(parameters, "(s@a{sv}^as)", NULL, &changed_properties, &invalidated_properties); const char* tz {}; if (g_variant_lookup(changed_properties, Bus::Timedate1::Properties::TIMEZONE, "&s", &tz, NULL)) { if (tz != nullptr) self->set_timezone(tz); else g_warning("%s no timezone found", G_STRLOC); } else if (g_strv_contains(invalidated_properties, Bus::Timedate1::Properties::TIMEZONE)) { self->ask_for_timezone(); } g_variant_unref(changed_properties); g_strfreev(invalidated_properties); } void ask_for_timezone() { g_dbus_connection_call( m_connection, Bus::Timedate1::BUSNAME, Bus::Timedate1::ADDR, Bus::Properties::IFACE, Bus::Properties::Methods::GET, g_variant_new("(ss)", Bus::Timedate1::IFACE, Bus::Timedate1::Properties::TIMEZONE), G_VARIANT_TYPE("(v)"), G_DBUS_CALL_FLAGS_NONE, -1, m_cancellable, on_get_timezone_ready, this); } static void on_get_timezone_ready(GObject * connection, GAsyncResult * res, gpointer gself) { GError* error {}; GVariant* v = 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_warning("%s Couldn't get timezone: %s", G_STRLOC, error->message); } else if (v != nullptr) { GVariant* tzv {}; g_variant_get(v, "(v)", &tzv); const char* tz = g_variant_get_string(tzv, nullptr); if (tz != nullptr) static_cast(gself)->set_timezone(tz); else g_warning("%s no timezone found", G_STRLOC); g_clear_pointer(&tzv, g_variant_unref); g_clear_pointer(&v, g_variant_unref); } } void set_timezone(const std::string& tz) { g_return_if_fail(!tz.empty()); g_debug("set timezone: '%s'", tz.c_str()); m_owner.timezone.set(tz); } /*** **** ***/ TimedatedTimezone& m_owner; GDBusConnection* m_connection {}; GCancellable* m_cancellable {}; unsigned long m_signal_subscription_id {}; unsigned int m_watcher_id {}; }; /*** **** ***/ TimedatedTimezone::TimedatedTimezone(GDBusConnection* connection): impl{new Impl{*this, connection}} { } TimedatedTimezone::~TimedatedTimezone() { } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/timezones-live.cpp0000644000004100000410000000405013151304754015512 0ustar www-datawww-data/* * 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, const std::shared_ptr& primary_timezone ): m_primary_timezone(primary_timezone), m_settings(settings) { m_primary_timezone->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_primary_timezone->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/awake.cpp0000644000004100000410000001045713151304754013640 0ustar www-datawww-data/* * 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(GDBusConnection* bus, const std::string& app_name): m_app_name(app_name), m_cancellable(g_cancellable_new()), m_system_bus{G_DBUS_CONNECTION(g_object_ref(bus))} { // ask repowerd to keep the system awake static constexpr int32_t POWERD_SYS_STATE_ACTIVE = 1; g_dbus_connection_call (m_system_bus, BUS_POWERD_NAME, BUS_POWERD_PATH, BUS_POWERD_INTERFACE, "requestSysState", g_variant_new("(si)", m_app_name.c_str(), POWERD_SYS_STATE_ACTIVE), G_VARIANT_TYPE("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, m_cancellable, on_force_awake_response, this); } ~Impl() { g_cancellable_cancel (m_cancellable); g_object_unref (m_cancellable); unforce_awake (); g_clear_object (&m_system_bus); } private: 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_variant_unref (args); } } 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, m_cancellable, nullptr, nullptr); g_clear_pointer (&m_awake_cookie, g_free); } } const std::string m_app_name; GCancellable * m_cancellable = nullptr; GDBusConnection * m_system_bus = nullptr; char * m_awake_cookie = nullptr; }; /*** **** ***/ Awake::Awake(GDBusConnection* system_bus, const std::string& app_name): impl{new Impl{system_bus, app_name}} { } Awake::~Awake() { } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/planner.cpp0000644000004100000410000000224713151304754014205 0ustar www-datawww-data/* * 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/planner-month.cpp0000644000004100000410000000325413151304754015327 0ustar www-datawww-data/* * 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.cpp0000644000004100000410000002313413151304754016454 0ustar www-datawww-data/* * 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/com.ubuntu.touch.AccountsService.Sound.xml0000644000004100000410000000412513151304754022167 0ustar www-datawww-data ./src/menu.cpp0000644000004100000410000005612313151304754013514 0ustar www-datawww-data/* * 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 { /**** ***** ****/ 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); } /** * To avoid a giant menu on the PC, and to avoid pushing lower menu items * off-screen on the phone, the menu should the * next five calendar events, if any. * * The list might include multiple occurrences of the same event (bug 1515821). */ std::vector Menu::get_display_appointments(const std::vector& appointments_in, const DateTime& now, unsigned int max_items) { std::vector appointments; std::copy_if(appointments_in.begin(), appointments_in.end(), std::back_inserter(appointments), [now](const Appointment& a){return a.end >= now;}); if (appointments.size() > max_items) { const auto next_minute = now.add_full(0,0,0,0,1,-now.seconds()); const auto start_of_day = now.start_of_day(); const auto end_of_day = now.end_of_day(); /* * If there are more than five, the events shown should be, in order of priority: * 1. any events that start or end (bug 1329048) after the current minute today; * 2. any full-day events that span all of today (bug 1302004); * 3. any events that start or end tomorrow; * 4. any events that start or end the day after tomorrow; and so on. */ auto compare = [next_minute, start_of_day, end_of_day]( const Appointment& a, const Appointment& b) { const bool a_later_today = (a.begin >= next_minute) || (a.end <= end_of_day); const bool b_later_today = (b.begin >= next_minute) || (b.end <= end_of_day); if (a_later_today != b_later_today) return a_later_today; const bool a_full_day_today = (a.begin <= start_of_day) && (end_of_day <= a.end); const bool b_full_day_today = (b.begin <= start_of_day) && (end_of_day <= b.end); if (a_full_day_today != b_full_day_today) return a_full_day_today; const bool a_after_today = (a.begin > end_of_day) || (a.end > end_of_day); const bool b_after_today = (a.begin > end_of_day) || (a.end > end_of_day); if (a_after_today != b_after_today) return a_after_today; if (a.begin != b.begin) return a.begin < b.begin; if (b.end != b.end) return a.end < b.end; return false; }; std::sort(appointments.begin(), appointments.end(), compare); appointments.resize(max_items); } /* * However, the display order should be the reverse: full-day events * first (since they start first), part-day events afterward in * chronological order. If multiple events have exactly the same start+end * time, they should be sorted alphabetically. */ auto compare = [](const Appointment& a, const Appointment& b) { if (a.begin != b.begin) return a.begin < b.begin; if (a.end != b.end) return a.end < b.end; return a.summary < b.summary; }; std::sort(appointments.begin(), appointments.end(), compare); return appointments; } /**** ***** ****/ #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 to show events germane to the current time. // However when the user clicks onto a different calendar date, // we pick events starting from the beginning of that clicked day. const auto now = m_state->clock->localtime(); const auto calendar_day = m_state->calendar_month->month().get(); const auto begin = DateTime::is_same_day(now, calendar_day) ? now.start_of_minute() : calendar_day.start_of_day(); auto upcoming = get_display_appointments( m_state->calendar_upcoming->appointments().get(), begin ); 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) || (profile == Phone)); 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 || profile == Phone) { 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/wakeup-timer-mainloop.cpp0000644000004100000410000000573513151304754017001 0ustar www-datawww-data/* * 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-live.cpp0000644000004100000410000001316613151304754014600 0ustar www-datawww-data/* * 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/date-time.cpp0000644000004100000410000001554713151304754014426 0ustar www-datawww-data/* * 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 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/locations-settings.cpp0000644000004100000410000000552013151304754016374 0ustar www-datawww-data/* * 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/notifications.cpp0000644000004100000410000003517513151304762015424 0ustar www-datawww-data/* * 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 #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; gint64 m_start_time {}; std::set m_string_hints; std::vector> m_actions; std::function m_closed_callback; std::function m_timeout_callback; bool m_show_notification_bubble; bool m_post_to_messaging_menu; }; 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); } void Builder::set_timeout_callback (std::function cb) { impl->m_timeout_callback.swap (cb); } void Builder::set_start_time (uint64_t time) { impl->m_start_time = time; } void Builder::set_show_notification_bubble (bool show) { impl->m_show_notification_bubble = show; } void Builder::set_post_to_messaging_menu (bool post) { impl->m_post_to_messaging_menu = post; } /*** **** ***/ class Engine::Impl { struct notification_data { std::shared_ptr nn; Builder::Impl data; }; struct messaging_menu_data { std::string msg_id; std::function callback; Engine::Impl *self; }; 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!"); // messaging menu auto app_id = calendar_app_id(); if (!app_id.empty()) { m_messaging_app.reset(messaging_menu_app_new(app_id.c_str()), g_object_unref); messaging_menu_app_register(m_messaging_app.get()); } } ~Impl() { close_all (); remove_all (); notify_uninit (); if (m_messaging_app) messaging_menu_app_unregister (m_messaging_app.get()); } 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 }; g_signal_connect (nn.get(), "closed", G_CALLBACK(on_notification_closed), this); if (!info.m_show_notification_bubble) { post(info); return ret; } 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; } std::string post(const Builder::Impl& data) { if (!data.m_post_to_messaging_menu) { return ""; } if (!m_messaging_app) { return std::string(); } uuid_t message_uuid; uuid_generate(message_uuid); char uuid_buf[37]; uuid_unparse(message_uuid, uuid_buf); const std::string message_id(uuid_buf); // use full icon path name, "calendar-app" does not work with themed icons auto icon_file = g_file_new_for_path(calendar_app_icon().c_str()); // messaging_menu_message_new: will take control of icon object GIcon *icon = g_file_icon_new(icon_file); g_object_unref(icon_file); // check if source exists if (!messaging_menu_app_has_source(m_messaging_app.get(), m_app_name.c_str())) messaging_menu_app_append_source(m_messaging_app.get(), m_app_name.c_str(), nullptr, "Calendar"); auto msg = messaging_menu_message_new(message_id.c_str(), icon, data.m_title.c_str(), nullptr, data.m_body.c_str(), data.m_start_time * G_USEC_PER_SEC); // secs -> microsecs if (msg) { std::shared_ptr msg_data(new messaging_menu_data{message_id, data.m_timeout_callback, this}); m_messaging_messages[message_id] = msg_data; g_signal_connect(G_OBJECT(msg), "activate", G_CALLBACK(on_message_activated), msg_data.get()); messaging_menu_app_append_message(m_messaging_app.get(), msg, m_app_name.c_str(), false); // we use that to keep track of messaging, in case of message get cleared from menu g_object_set_data_full(G_OBJECT(msg), "destroy-notify", msg_data.get(), on_message_destroyed); // keep the message control with message_menu g_object_unref(msg); return message_id; } else { g_warning("Fail to create messaging menu message"); } return ""; } void remove (const std::string &key) { auto it = m_messaging_messages.find(key); if (it != m_messaging_messages.end()) { // tell the server to remove message messaging_menu_app_remove_message_by_id(m_messaging_app.get(), it->second->msg_id.c_str()); // message will be remove by on_message_destroyed cb. } } void remove_all () { // call remove() on all our keys while (!m_messaging_messages.empty()) remove(m_messaging_messages.begin()->first); } 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)); } static void on_message_activated (MessagingMenuMessage *, const char *, GVariant *, gpointer data) { auto msg_data = static_cast(data); auto it = msg_data->self->m_messaging_messages.find(msg_data->msg_id); g_return_if_fail (it != msg_data->self->m_messaging_messages.end()); const auto& ndata = it->second; if (ndata->callback) ndata->callback(); } static void on_message_destroyed(gpointer data) { auto msg_data = static_cast(data); auto it = msg_data->self->m_messaging_messages.find(msg_data->msg_id); if (it != msg_data->self->m_messaging_messages.end()) msg_data->self->m_messaging_messages.erase(it); } 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.data.m_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.data.m_closed_callback (action); // empty action means that the notification got timeout // post a message on messaging menu if (action.empty()) post(ndata.data); } m_notifications.erase(it); } static std::string calendar_app_id() { return "org.gnome.Calendar.desktop"; } static std::string calendar_app_icon() { auto app_desktop = g_desktop_app_info_new(calendar_app_id().c_str()); if (app_desktop != nullptr) { auto icon_name = g_desktop_app_info_get_string(app_desktop, "Icon"); g_object_unref(app_desktop); if (icon_name) { std::string result(icon_name); g_free(icon_name); return result; } } g_warning("Fail to get calendar icon"); return std::string(); } /*** **** ***/ // messaging menu std::shared_ptr m_messaging_app; std::map > m_messaging_messages; 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/myself.cpp0000644000004100000410000000415613151304754014046 0ustar www-datawww-data/* * Copyright 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: * Renato Araujo Oliveira Filho */ #include "datetime/myself.h" #include #include #include namespace unity { namespace indicator { namespace datetime { Myself::Myself() : m_accounts_manager(ag_manager_new(), g_object_unref) { reloadEmails(); g_object_connect(m_accounts_manager.get(), "signal::account-created", on_accounts_changed, this, "signal::account-deleted", on_accounts_changed, this, "signal::account-updated", on_accounts_changed, this, nullptr); } bool Myself::isMyEmail(const std::string &email) { return m_emails.get().count(email) > 0; } void Myself::on_accounts_changed(AgManager *, guint, Myself *self) { self->reloadEmails(); } void Myself::reloadEmails() { std::set emails; auto manager = m_accounts_manager.get(); auto ids = ag_manager_list(manager); for (auto l=ids; l!=nullptr; l=l->next) { auto acc = ag_manager_get_account(manager, GPOINTER_TO_UINT(l->data)); if (acc) { auto account_name = ag_account_get_display_name(acc); if (account_name != nullptr) emails.insert(account_name); g_object_unref(acc); } } ag_manager_list_free(ids); m_emails.set(emails); } } // namespace datetime } // namespace indicator } // namespace unity ./src/exporter.cpp0000644000004100000410000001716513151304754014423 0ustar www-datawww-data/* * 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/locations.cpp0000644000004100000410000000276413151304754014545 0ustar www-datawww-data/* * 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/sound.cpp0000644000004100000410000001154213151304754013674 0ustar www-datawww-data/* * 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/snap.cpp0000644000004100000410000002676413151304754013521 0ustar www-datawww-data/* * 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, GDBusConnection* system_bus): m_engine(engine), m_sound_builder(sound_builder), m_settings(settings), m_cancellable(g_cancellable_new()), m_system_bus{G_DBUS_CONNECTION(g_object_ref(system_bus))} { auto object_path = g_strdup_printf("/org/freedesktop/Accounts/User%lu", (gulong)getuid()); accounts_service_sound_proxy_new(m_system_bus, 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); g_clear_object(&m_system_bus); for (const auto& key : m_notifications) m_engine->close (key); } void operator()(const Appointment& appointment, const Alarm& alarm, response_func on_response) { // If calendar notifications are disabled, don't show them if (!appointment.is_ubuntu_alarm() && !calendar_notifications_are_enabled()) { g_debug("Skipping disabled 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 std::shared_ptr awake; if (appointment.is_ubuntu_alarm() || calendar_bubbles_enabled() || calendar_list_enabled()) { awake = std::make_shared(m_system_bus, m_engine->app_name()); } // calendar events are muted in silent mode; alarm clocks never are std::shared_ptr sound; if (appointment.is_ubuntu_alarm() || (calendar_sounds_enabled() && !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() && (appointment.is_ubuntu_alarm() || calendar_vibrations_enabled())) { // when in silent mode should only vibrate if user defined so if (!silent_mode() || vibrate_in_silent_mode_enabled()) { const auto haptic_mode = m_settings->alarm_haptic.get(); if (haptic_mode == "pulse") haptic = std::make_shared(uin::Haptic::MODE_PULSE, appointment.is_ubuntu_alarm()); } } // 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" : "calendar-app"); b.add_hint (uin::Builder::HINT_NONSHAPED_ICON); b.set_start_time (appointment.begin.to_unix()); 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 (ACTION_NONE, _("OK")); b.add_action (ACTION_SNOOZE, _("Snooze")); } else { b.add_hint (uin::Builder::HINT_INTERACTIVE); b.add_action (ACTION_SHOW_APP, _("OK")); } // 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, on_response, sound, awake, haptic] (const std::string& action){ Snap::Response response; if (action == ACTION_SNOOZE) response = Snap::Response::Snooze; else if (action == ACTION_SHOW_APP) response = Snap::Response::ShowApp; else response = Snap::Response::None; on_response(appointment, alarm, response); }); //TODO: we need to extend it to support alarms appointments if (!appointment.is_ubuntu_alarm()) { b.set_timeout_callback([appointment, alarm, on_response](){ on_response(appointment, alarm, Snap::Response::ShowApp); }); } b.set_show_notification_bubble(appointment.is_ubuntu_alarm() || calendar_bubbles_enabled()); b.set_post_to_messaging_menu(appointment.is_ubuntu_alarm() || calendar_list_enabled()); const auto key = m_engine->show(b); if (key) m_notifications.insert (key); } private: bool calendar_notifications_are_enabled() const { return m_settings->cal_notification_enabled.get(); } bool calendar_sounds_enabled() const { return m_settings->cal_notification_sounds.get(); } bool calendar_vibrations_enabled() const { return m_settings->cal_notification_vibrations.get(); } bool calendar_bubbles_enabled() const { return m_settings->cal_notification_bubbles.get(); } bool calendar_list_enabled() const { return m_settings->cal_notification_list.get(); } bool vibrate_in_silent_mode_enabled() const { return m_settings->vibrate_silent_mode.get(); } static void on_sound_proxy_ready(GObject* /*source_object*/, GAsyncResult* res, gpointer gself) { GError * error; error = nullptr; auto proxy = accounts_service_sound_proxy_new_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}; GDBusConnection * m_system_bus {nullptr}; static constexpr char const * ACTION_NONE {"none"}; static constexpr char const * ACTION_SNOOZE {"snooze"}; static constexpr char const * ACTION_SHOW_APP {"show-app"}; }; /*** **** ***/ Snap::Snap(const std::shared_ptr& engine, const std::shared_ptr& sound_builder, const std::shared_ptr& settings, GDBusConnection* system_bus): impl(new Impl(engine, sound_builder, settings, system_bus)) { } Snap::~Snap() { } void Snap::operator()(const Appointment& appointment, const Alarm& alarm, response_func on_response) { (*impl)(appointment, alarm, on_response); } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/timezone-geoclue.cpp0000644000004100000410000002244213151304754016020 0ustar www-datawww-data/* * 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/alarm-queue-simple.cpp0000644000004100000410000001245513151304754016255 0ustar www-datawww-data/* * 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/main.cpp0000644000004100000410000001667713151304754013506 0ustar www-datawww-data/* * 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 #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(std::shared_ptr(new Myself))); 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, timezone_); 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); // get the system bus GError* error {}; auto system_bus = g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, &error); if (error != nullptr) { g_critical("Unable to get system bus: %s", error->message); g_clear_error(&error); return 0; } auto engine = create_engine(); auto timezone_ = std::make_shared(system_bus); 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, system_bus)); auto alarm_queue = create_simple_alarm_queue(state->clock, snooze_planner, engine, timezone_); auto on_response = [snooze_planner, actions](const Appointment& appointment, const Alarm& alarm, const Snap::Response& response) { switch(response) { case Snap::Response::Snooze: snooze_planner->add(appointment, alarm); break; case Snap::Response::ShowApp: actions->open_appointment(appointment, appointment.begin); break; case Snap::Response::None: break; } }; auto on_alarm_reached = [&engine, &snap, &on_response](const Appointment& appointment, const Alarm& alarm) { (*snap)(appointment, alarm, on_response); 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); g_clear_object(&system_bus); return 0; } ./src/planner-range.cpp0000644000004100000410000000554613151304754015304 0ustar www-datawww-data/* * 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/planner-snooze.cpp0000644000004100000410000000540313151304754015515 0ustar www-datawww-data/* * 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/engine-eds.cpp0000644000004100000410000012603213151304754014563 0ustar www-datawww-data/* * 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 #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(const std::shared_ptr &myself) : m_myself(myself) { 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); m_myself->emails().changed().connect([this](const std::set &) { set_dirty_soon(); }); } ~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(); auto gtz = timezone_from_name(tz, nullptr, nullptr, &default_timezone); if (gtz == nullptr) { gtz = g_time_zone_new_local(); } g_debug("default_timezone is %s", default_timezone ? icaltimezone_get_display_name(default_timezone) : "null"); /** *** walk through the sources to build the appointment list **/ 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); // check source is selected if (!e_source_selectable_get_selected(E_SOURCE_SELECTABLE(extension))) { g_debug("Soure is not selected, ignore it: %s", e_source_get_display_name(source)); continue; } const auto color = e_source_selectable_get_color(E_SOURCE_SELECTABLE(extension)); e_cal_client_generate_instances( client, begin.to_unix(), end.to_unix(), m_cancellable.get(), on_event_generated, new ClientSubtask(main_task, client, m_cancellable, color), on_event_generated_list_ready); } } 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; GList *components; GList *instance_components; std::set parent_components; 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), components(nullptr), instance_components(nullptr) { 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, const std::string & default_sound) { 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); } if (ret.empty()) ret = default_sound; } return ret; } static gboolean on_event_generated(ECalComponent *comp, time_t, time_t, gpointer gsubtask) { auto subtask = static_cast(gsubtask); const gchar *uid = nullptr; e_cal_component_get_uid (comp, &uid); g_object_ref(comp); if (e_cal_component_is_instance(comp) && (uid != nullptr)) { subtask->parent_components.insert(std::string(uid)); subtask->instance_components = g_list_append(subtask->instance_components, comp); } else { subtask->components = g_list_append(subtask->components, comp); } return TRUE; } static void merge_detached_instances(ClientSubtask *subtask, GSList *instances) { for (GSList *i=instances; i!=nullptr; i=i->next) { auto instance = static_cast(i->data); auto instance_id = e_cal_component_get_id(instance); for (GList *c=subtask->instance_components ; c!= nullptr; c=c->next) { auto component = static_cast(c->data); auto component_id = e_cal_component_get_id(component); bool found = false; if (e_cal_component_id_equal(instance_id, component_id)) { // replaces virtual instance with the real one g_object_unref(component); c->data = g_object_ref(instance); found = true; } e_cal_component_free_id(component_id); if (found) break; } e_cal_component_free_id (instance_id); } } static void fetch_detached_instances(GObject *, GAsyncResult *res, gpointer gsubtask) { auto subtask = static_cast(gsubtask); if (res) { GError *error = nullptr; GSList *comps = nullptr; e_cal_client_get_objects_for_uid_finish(subtask->client, res, &comps, &error); if (error) { g_warning("Fail to retrieve detached instances: %s", error->message); g_error_free(error); } else { merge_detached_instances(subtask, comps); e_cal_client_free_ecalcomp_slist(comps); } } if (subtask->parent_components.empty()) { on_event_fetch_list_done(gsubtask); return; } // continue fetch detached instances auto i_begin = subtask->parent_components.begin(); std::string id = *i_begin; subtask->parent_components.erase(i_begin); e_cal_client_get_objects_for_uid(subtask->client, id.c_str(), subtask->cancellable.get(), (GAsyncReadyCallback) fetch_detached_instances, gsubtask); } static void on_event_generated_list_ready(gpointer gsubtask) { fetch_detached_instances(nullptr, nullptr, gsubtask); } static gint sort_events_by_start_date(ECalComponent *eventA, ECalComponent *eventB) { ECalComponentDateTime start_date_a; ECalComponentDateTime start_date_b; e_cal_component_get_dtstart(eventA, &start_date_a); e_cal_component_get_dtstart(eventB, &start_date_b); auto time_a = icaltime_as_timet(*start_date_a.value); auto time_b = icaltime_as_timet(*start_date_b.value); if (time_a == time_b) return 0; if (time_a < time_b) return -1; return 1; } static bool is_alarm_interesting(ECalComponentAlarm *alarm) { if (alarm) { ECalComponentAlarmAction action; e_cal_component_alarm_get_action(alarm, &action); if ((action == E_CAL_COMPONENT_ALARM_AUDIO) || (action == E_CAL_COMPONENT_ALARM_DISPLAY)) { return true; } } return false; } // we only care about AUDIO or DISPLAY alarms, other kind of alarm will not generate a notification static bool event_has_valid_alarms(ECalComponent *event) { if (!e_cal_component_has_alarms(event)) return false; // check alarms bool valid = false; auto uids = e_cal_component_get_alarm_uids(event); for (auto l=uids; l!=nullptr; l=uids->next) { auto auid = static_cast(l->data); auto alarm = e_cal_component_get_alarm(event, auid); valid = is_alarm_interesting(alarm); if (valid) { break; } } cal_obj_uid_list_free(uids); return valid; } static void on_event_fetch_list_done(gpointer gsubtask) { auto subtask = static_cast(gsubtask); // generate alarms constexpr std::array omit = { (ECalComponentAlarmAction)-1 }; // list of action types to omit, terminated with -1 GSList * comp_alarms = nullptr; // we do not need translate tz for instance events, // they are aredy in the correct time e_cal_util_generate_alarms_for_list( subtask->instance_components, subtask->task->begin.to_unix(), subtask->task->end.to_unix(), const_cast(omit.data()), &comp_alarms, e_cal_client_resolve_tzid_cb, subtask->client, nullptr); // convert timezone for non-instance events e_cal_util_generate_alarms_for_list( subtask->components, subtask->task->begin.to_unix(), subtask->task->end.to_unix(), const_cast(omit.data()), &comp_alarms, e_cal_client_resolve_tzid_cb, subtask->client, 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); subtask->components = g_list_concat(subtask->components, subtask->instance_components); subtask->components = g_list_sort(subtask->components, (GCompareFunc) sort_events_by_start_date); // add events without alarm for (auto l=subtask->components; l!=nullptr; l=l->next) { auto component = static_cast(l->data); if (!event_has_valid_alarms(component)) add_event_to_subtask(component, subtask, subtask->task->gtz); } g_list_free_full(subtask->components, g_object_unref); e_cal_free_alarms(comp_alarms); delete subtask; } static GTimeZone * timezone_from_name (const char * tzid, ECalClient * client, GCancellable * cancellable, icaltimezone **itimezone) { if (tzid == nullptr) return nullptr; auto itz = icaltimezone_get_builtin_timezone_from_tzid(tzid); // usually works if (itz == nullptr) // fallback itz = icaltimezone_get_builtin_timezone(tzid); if (client && (itz == nullptr)) // ok we have a strange tzid... ask EDS to look it up in VTIMEZONES e_cal_client_get_timezone_sync(client, tzid, &itz, cancellable, nullptr); const char* identifier {}; if (itimezone) *itimezone = itz; 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'", tzid); else return g_time_zone_new(identifier); return nullptr; } 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 = timezone_from_name(in.tzid, client, cancellable.get(), nullptr); if (gtz == nullptr) 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; } 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) { // we don't want not attending alarms // check if the user is part of attendee list if we found it check the status GSList *attendeeList = nullptr; e_cal_component_get_attendee_list(component, &attendeeList); for (GSList *attendeeIter=attendeeList; attendeeIter != nullptr; attendeeIter = attendeeIter->next) { ECalComponentAttendee *attendee = static_cast(attendeeIter->data); if (attendee->value) { if (strncmp(attendee->value, "mailto:", 7) == 0) { if (m_myself->isMyEmail(attendee->value+7)) { disabled = (attendee->status == ICAL_PARTSTAT_DECLINED); break; } } } } if (attendeeList) e_cal_component_free_attendee_list(attendeeList); } 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_alarms_to_subtask(ECalComponentAlarms * comp_alarms, ClientSubtask * subtask, GTimeZone * gtz) { auto& component = comp_alarms->comp; if (!subtask->task->p->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 (!is_alarm_interesting(a)) { 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, (baseline.is_ubuntu_alarm() ? "file://" ALARM_DEFAULT_SOUND : "file://" CALENDAR_DEFAULT_SOUND)); 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) { if (j.second.has_text() || j.second.has_sound()) appointment.alarms.push_back(j.second); } subtask->task->appointments.push_back(appointment); } } static void add_event_to_subtask(ECalComponent * component, ClientSubtask * subtask, GTimeZone * gtz) { // add it. simple, eh? if (subtask->task->p->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 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 {}; std::shared_ptr m_myself; }; /*** **** ***/ EdsEngine::EdsEngine(const std::shared_ptr &myself): p(new Impl(myself)) { } 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/formatter-desktop.cpp0000644000004100000410000001444113151304754016217 0ustar www-datawww-data/* * 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-upcoming.cpp0000644000004100000410000000326613151304754016026 0ustar www-datawww-data/* * 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.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/actions.cpp0000644000004100000410000002025613151304754014206 0ustar www-datawww-data/* * 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_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->open_appointment(appt, DateTime::Local(time)); } void on_alarm_activated (GSimpleAction*, GVariant*, gpointer gself) { static_cast(gself)->open_alarm_app(); } void on_calendar_activated (GSimpleAction*, GVariant* vt, gpointer gself) { const auto dt = datetime_from_timet_variant(vt); static_cast(gself)->open_calendar_app(dt); } void on_settings_activated (GSimpleAction*, GVariant*, gpointer gself) { static_cast(gself)->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_date_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_appointment_activated, "(sx)", nullptr }, { "desktop.open-alarm-app", on_alarm_activated }, { "desktop.open-calendar-app", on_calendar_activated, "x", nullptr }, { "desktop.open-settings-app", on_settings_activated }, { "phone.open-appointment", on_appointment_activated, "(sx)", nullptr }, { "phone.open-alarm-app", on_alarm_activated }, { "phone.open-calendar-app", on_calendar_activated, "x", nullptr }, { "phone.open-settings-app", on_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_date_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/utils.c0000644000004100000410000003477513151304754013361 0ustar www-datawww-data/* * 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/settings-live.cpp0000644000004100000410000003345713151304754015352 0ustar www-datawww-data/* * 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_general_notification); g_clear_object(&m_settings_cal_notification); g_clear_object(&m_settings); } LiveSettings::LiveSettings(): m_settings(g_settings_new(SETTINGS_INTERFACE)), m_settings_cal_notification(g_settings_new_with_path(SETTINGS_NOTIFY_SCHEMA_ID, SETTINGS_NOTIFY_CALENDAR_PATH)), m_settings_general_notification(g_settings_new(SETTINGS_NOTIFY_APPS_SCHEMA_ID)) { g_signal_connect (m_settings, "changed", G_CALLBACK(on_changed_ccid), this); g_signal_connect (m_settings_cal_notification, "changed", G_CALLBACK(on_changed_cal_notification), this); g_signal_connect (m_settings_general_notification, "changed", G_CALLBACK(on_changed_general_notification), 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_cal_notification_enabled(); update_cal_notification_sounds(); update_cal_notification_vibrations(); update_cal_notification_bubbles(); update_cal_notification_list(); update_vibrate_silent_mode(); // 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()); }); 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); }); cal_notification_enabled.changed().connect([this](bool value){ g_settings_set_boolean(m_settings_cal_notification, SETTINGS_NOTIFY_ENABLED_KEY, value); }); cal_notification_sounds.changed().connect([this](bool value){ g_settings_set_boolean(m_settings_cal_notification, SETTINGS_NOTIFY_SOUNDS_KEY, value); }); cal_notification_vibrations.changed().connect([this](bool value){ g_settings_set_boolean(m_settings_cal_notification, SETTINGS_NOTIFY_VIBRATIONS_KEY, value); }); cal_notification_bubbles.changed().connect([this](bool value){ g_settings_set_boolean(m_settings_cal_notification, SETTINGS_NOTIFY_BUBBLES_KEY, value); }); cal_notification_list.changed().connect([this](bool value){ g_settings_set_boolean(m_settings_cal_notification, SETTINGS_NOTIFY_LIST_KEY, value); }); vibrate_silent_mode.changed().connect([this](bool value){ g_settings_set_boolean(m_settings_general_notification, SETTINGS_VIBRATE_SILENT_KEY, 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_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::update_cal_notification_enabled() { cal_notification_enabled.set(g_settings_get_boolean(m_settings_cal_notification, SETTINGS_NOTIFY_ENABLED_KEY)); } void LiveSettings::update_cal_notification_sounds() { cal_notification_sounds.set(g_settings_get_boolean(m_settings_cal_notification, SETTINGS_NOTIFY_SOUNDS_KEY)); } void LiveSettings::update_cal_notification_vibrations() { cal_notification_vibrations.set(g_settings_get_boolean(m_settings_cal_notification, SETTINGS_NOTIFY_VIBRATIONS_KEY)); } void LiveSettings::update_cal_notification_bubbles() { cal_notification_bubbles.set(g_settings_get_boolean(m_settings_cal_notification, SETTINGS_NOTIFY_BUBBLES_KEY)); } void LiveSettings::update_cal_notification_list() { cal_notification_list.set(g_settings_get_boolean(m_settings_cal_notification, SETTINGS_NOTIFY_LIST_KEY)); } void LiveSettings::update_vibrate_silent_mode() { vibrate_silent_mode.set(g_settings_get_boolean(m_settings_general_notification, SETTINGS_VIBRATE_SILENT_KEY)); } /*** **** ***/ void LiveSettings::on_changed_cal_notification(GSettings* /*settings*/, gchar* key, gpointer gself) { static_cast(gself)->update_key_cal_notification(key); } void LiveSettings::update_key_cal_notification(const std::string& key) { if (key == SETTINGS_NOTIFY_ENABLED_KEY) update_cal_notification_enabled(); else if (key == SETTINGS_NOTIFY_SOUNDS_KEY) update_cal_notification_sounds(); else if (key == SETTINGS_NOTIFY_VIBRATIONS_KEY) update_cal_notification_vibrations(); else if (key == SETTINGS_NOTIFY_BUBBLES_KEY) update_cal_notification_bubbles(); else if (key == SETTINGS_NOTIFY_LIST_KEY) update_cal_notification_list(); } /*** **** ***/ void LiveSettings::on_changed_general_notification(GSettings* /*settings*/, gchar* key, gpointer gself) { static_cast(gself)->update_key_general_notification(key); } void LiveSettings::update_key_general_notification(const std::string& key) { if (key == SETTINGS_VIBRATE_SILENT_KEY) update_vibrate_silent_mode(); } /*** **** ***/ 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/actions-live.cpp0000644000004100000410000001733713151304754015151 0ustar www-datawww-data/* * 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 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); } /*** **** ***/ LiveActions::Desktop LiveActions::get_desktop() { static bool cached = false; static LiveActions::Desktop result = LiveActions::OTHER; if (cached) { return result; } // check for unity8 if (g_getenv ("MIR_SOCKET") != nullptr) { result = LiveActions::UNITY8; } else { 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 = LiveActions::UNITY7; break; } } g_strfreev (desktop_names); } } cached = true; return result; } void LiveActions::open_alarm_app() { switch(get_desktop()) { case LiveActions::UNITY8: dispatch_url("appid://ubuntu-clock-app/ubuntu-clock-app/current-user-version"); break; case LiveActions::UNITY7: default: execute_command("evolution -c calendar"); } } void LiveActions::open_appointment(const Appointment& appt, const DateTime& date) { switch(get_desktop()) { case LiveActions::UNITY8: unity8_open_appointment(appt, date); break; case LiveActions::UNITY7: default: open_calendar_app(date); } } void LiveActions::open_calendar_app(const DateTime& dt) { switch(get_desktop()) { case LiveActions::UNITY8: { const auto utc = dt.to_timezone("UTC"); auto cmd = utc.format("calendar://startdate=%Y-%m-%dT%H:%M:%S+00:00"); dispatch_url(cmd); break; } case LiveActions::UNITY7: default: { 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::open_settings_app() { switch(get_desktop()) { case LiveActions::UNITY8: dispatch_url("settings:///system/time-date"); break; case LiveActions::UNITY7: execute_command("unity-control-center datetime"); break; default: 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::unity8_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: open_alarm_app(); break; case Appointment::EVENT: default: open_calendar_app(date); break; } } /*** **** ***/ 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, Bus::Timedate1::Methods::SET_TIMEZONE, 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, Bus::Timedate1::BUSNAME, Bus::Timedate1::ADDR, Bus::Timedate1::IFACE, nullptr, on_datetime1_proxy_ready, data); } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/formatter.cpp0000644000004100000410000001655713151304754014562 0ustar www-datawww-data/* * 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/haptic.cpp0000644000004100000410000001125513151304754014015 0ustar www-datawww-data/* * 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, bool repeat): m_mode(mode), m_cancellable(g_cancellable_new()), m_repeat(repeat) { 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; } if (m_repeat) { // 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; bool m_repeat = false; }; /*** **** ***/ Haptic::Haptic(const Mode& mode, bool repeat): impl(new Impl (mode, repeat)) { } Haptic::~Haptic() { } /*** **** ***/ } // namespace datetime } // namespace indicator } // namespace unity ./src/appointment.cpp0000644000004100000410000000270613151304754015104 0ustar www-datawww-data/* * 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 Alarm::has_sound() const { return !audio_url.empty(); } bool Alarm::has_text() const { return !text.empty(); } 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/clock.cpp0000644000004100000410000002000513151304754013631 0ustar www-datawww-data/* * 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 ./cmake/0000755000004100000410000000000013151304754012326 5ustar www-datawww-data./cmake/UseGSettings.cmake0000644000004100000410000000210213151304754015707 0ustar www-datawww-data# 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/GdbusCodegen.cmake0000644000004100000410000000246513151304754015670 0ustar www-datawww-datacmake_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) ./ChangeLog0000644000004100000410000000003113151304754013012 0ustar www-datawww-data# Generated by Makefile ./MERGE-REVIEW0000644000004100000410000000346013151304754013032 0ustar www-datawww-data* '''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 ./tests/0000755000004100000410000000000013151305012012374 5ustar www-datawww-data./tests/test-datetime.cpp0000644000004100000410000000725113151304754015672 0ustar www-datawww-data/* * 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_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-settings.cpp0000644000004100000410000002040613151304754015733 0ustar www-datawww-data/* * 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_cal_notification {}; void SetUp() override { super::SetUp(); m_gsettings = g_settings_new(SETTINGS_INTERFACE); m_gsettings_cal_notification = g_settings_new_with_path(SETTINGS_NOTIFY_SCHEMA_ID, SETTINGS_NOTIFY_CALENDAR_PATH); m_live.reset(new LiveSettings); m_settings = std::dynamic_pointer_cast(m_live); } void TearDown() override { g_clear_object(&m_gsettings_cal_notification); g_clear_object(&m_gsettings); m_settings.reset(); m_live.reset(); super::TearDown(); } void TestBoolProperty(GSettings* gsettings, core::Property& property, const gchar* key) { EXPECT_EQ(g_settings_get_boolean(gsettings, key), property.get()); g_settings_set_boolean(gsettings, key, false); EXPECT_FALSE(property.get()); g_settings_set_boolean(gsettings, key, true); EXPECT_TRUE(property.get()); property.set(false); EXPECT_FALSE(g_settings_get_boolean(gsettings, key)); property.set(true); EXPECT_TRUE(g_settings_get_boolean(gsettings, key)); } void TestStringProperty(GSettings* gsettings, core::Property& property, const gchar* key) { gchar* tmp; std::string str; tmp = g_settings_get_string(gsettings, key); EXPECT_EQ(tmp, property.get()); g_clear_pointer(&tmp, g_free); str = "a"; g_settings_set_string(gsettings, key, str.c_str()); EXPECT_EQ(str, property.get()); str = "b"; g_settings_set_string(gsettings, key, str.c_str()); EXPECT_EQ(str, property.get()); str = "a"; property.set(str); tmp = g_settings_get_string(gsettings, key); EXPECT_EQ(str, tmp); g_clear_pointer(&tmp, g_free); str = "b"; property.set(str); tmp = g_settings_get_string(gsettings, key); EXPECT_EQ(str, tmp); g_clear_pointer(&tmp, g_free); } void TestUIntProperty(GSettings* gsettings, core::Property& property, const gchar* key) { EXPECT_EQ(g_settings_get_uint(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(gsettings, key, expected_value); EXPECT_EQ(expected_value, property.get()); EXPECT_EQ(expected_value, g_settings_get_uint(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(gsettings, key)); } } }; /*** **** ***/ TEST_F(SettingsFixture, HelloWorld) { EXPECT_TRUE(true); } TEST_F(SettingsFixture, BoolProperties) { TestBoolProperty(m_gsettings, m_settings->show_seconds, SETTINGS_SHOW_SECONDS_S); TestBoolProperty(m_gsettings, m_settings->show_calendar, SETTINGS_SHOW_CALENDAR_S); TestBoolProperty(m_gsettings, m_settings->show_clock, SETTINGS_SHOW_CLOCK_S); TestBoolProperty(m_gsettings, m_settings->show_date, SETTINGS_SHOW_DATE_S); TestBoolProperty(m_gsettings, m_settings->show_day, SETTINGS_SHOW_DAY_S); TestBoolProperty(m_gsettings, m_settings->show_detected_location, SETTINGS_SHOW_DETECTED_S); TestBoolProperty(m_gsettings, m_settings->show_events, SETTINGS_SHOW_EVENTS_S); TestBoolProperty(m_gsettings, m_settings->show_locations, SETTINGS_SHOW_LOCATIONS_S); TestBoolProperty(m_gsettings, m_settings->show_week_numbers, SETTINGS_SHOW_WEEK_NUMBERS_S); TestBoolProperty(m_gsettings, m_settings->show_year, SETTINGS_SHOW_YEAR_S); } TEST_F(SettingsFixture, UIntProperties) { TestUIntProperty(m_gsettings, m_settings->alarm_duration, SETTINGS_ALARM_DURATION_S); TestUIntProperty(m_gsettings, m_settings->alarm_volume, SETTINGS_ALARM_VOLUME_S); TestUIntProperty(m_gsettings, m_settings->snooze_duration, SETTINGS_SNOOZE_DURATION_S); } TEST_F(SettingsFixture, StringProperties) { TestStringProperty(m_gsettings, m_settings->custom_time_format, SETTINGS_CUSTOM_TIME_FORMAT_S); TestStringProperty(m_gsettings, m_settings->timezone_name, SETTINGS_TIMEZONE_NAME_S); TestStringProperty(m_gsettings, m_settings->alarm_sound, SETTINGS_ALARM_SOUND_S); TestStringProperty(m_gsettings, m_settings->calendar_sound, SETTINGS_CALENDAR_SOUND_S); TestStringProperty(m_gsettings, 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) { if (!m_gsettings_cal_notification) { return; } TestBoolProperty(m_gsettings_cal_notification, m_settings->cal_notification_enabled, SETTINGS_NOTIFY_ENABLED_KEY); TestBoolProperty(m_gsettings_cal_notification, m_settings->cal_notification_sounds, SETTINGS_NOTIFY_SOUNDS_KEY); TestBoolProperty(m_gsettings_cal_notification, m_settings->cal_notification_vibrations, SETTINGS_NOTIFY_VIBRATIONS_KEY); TestBoolProperty(m_gsettings_cal_notification, m_settings->cal_notification_bubbles, SETTINGS_NOTIFY_BUBBLES_KEY); TestBoolProperty(m_gsettings_cal_notification, m_settings->cal_notification_list, SETTINGS_NOTIFY_LIST_KEY); } ./tests/CMakeLists.txt0000644000004100000410000001317713151305000015142 0ustar www-datawww-datafind_package(GMock REQUIRED) SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 ${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}) set (COVERAGE_TEST_TARGETS ${COVERAGE_TEST_TARGETS} ${TEST_NAME} PARENT_SCOPE) add_executable (${TEST_NAME} ${TEST_NAME}.cpp gschemas.compiled) add_test (${TEST_NAME} ${TEST_NAME}) set_tests_properties(${TEST_NAME} PROPERTIES ENVIRONMENT "XDG_DATA_DIRS=${CMAKE_CURRENT_SOURCE_DIR}/data:/usr/share") target_link_libraries (${TEST_NAME} indicatordatetimeservice ${DBUSTEST_LIBRARIES} ${SERVICE_DEPS_LIBRARIES} ${GTEST_LIBRARIES} ${GMOCK_LIBRARIES}) endfunction() add_test_by_name(test-datetime) add_test_by_name(test-sound) add_test_by_name(test-notification) add_test_by_name(test-notification-response) 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-menu-appointments) 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) set (COVERAGE_TEST_TARGETS ${COVERAGE_TEST_TARGETS} ${TEST_NAME}) add_executable (${TEST_NAME} ${TEST_NAME}.cpp) target_link_libraries (${TEST_NAME} indicatordatetimeservice ${SERVICE_DEPS_LIBRARIES} ${GTEST_LIBRARIES} ${GMOCK_LIBRARIES}) ## ## EDS Tests ## find_program(DBUS_RUNNER dbus-test-runner) function(add_eds_ics_test_by_name name) set (TEST_NAME ${name}) set (COVERAGE_TEST_TARGETS ${COVERAGE_TEST_TARGETS} ${TEST_NAME} PARENT_SCOPE) 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 ${DBUSTEST_LIBRARIES} ${SERVICE_DEPS_LIBRARIES} ${GTEST_LIBRARIES} ${GMOCK_LIBRARIES}) 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 ${CMAKE_CURRENT_SOURCE_DIR}/accounts.db # arg6: online accounts database ${CMAKE_CURRENT_SOURCE_DIR}/data) # arg7: data dir 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) add_eds_ics_test_by_name(test-eds-ics-non-attending-alarms) add_eds_ics_test_by_name(test-eds-ics-repeating-events-with-individual-change) # 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}) # set (COVERAGE_TEST_TARGETS ${COVERAGE_TEST_TARGETS} ${TEST_NAME} PARENT_SCOPE) # add_executable (${TEST_NAME} ${TEST_NAME}.cpp gschemas.compiled) # add_test (${TEST_NAME} ${TEST_NAME}) # target_link_libraries (${TEST_NAME} indicatordatetimeservice ${SERVICE_DEPS_LIBRARIES} ${DBUSTEST_LIBRARIES} ${GTEST_LIBRARIES} ${GMOCK_LIBRARIES}) #endfunction() #add_dbusmock_test_by_name(test-timezone-geoclue) #add_dbusmock_test_by_name(test-timezones) set( COVERAGE_TEST_TARGETS ${COVERAGE_TEST_TARGETS} PARENT_SCOPE ) ./tests/test-eds-ics-tzids-utc.ics.in0000644000004100000410000000055013151304754017745 0ustar www-datawww-dataBEGIN: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-eds-ics-tzids-2.ics.in0000644000004100000410000000201313151304754017307 0ustar www-datawww-dataBEGIN: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/test-menu-appointments.cpp0000644000004100000410000002036213151304754017557 0ustar www-datawww-data/* * Copyright 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 "glib-fixture.h" #include "print-to.h" #include #include #include using MenuAppointmentFixture = GlibFixture; using namespace unity::indicator::datetime; namespace { Appointment create_appointment( const Appointment::Type& type, const std::string& uid, const std::string& summary, const DateTime& begin, const DateTime& end) { Appointment a; a.type = type; a.uid = uid; a.summary = summary; a.begin = begin; a.end = end; return a; } } TEST_F(MenuAppointmentFixture, DisplayEvents) { const auto airport = create_appointment( Appointment::UBUNTU_ALARM, "uid-airport", "Pick Aunt Mabel up at the airport", DateTime::Local(2016,12,24,10,0,0), DateTime::Local(2016,12,24,10,0,0) ); const auto christmas_eve_candle_service = create_appointment( Appointment::EVENT, "uid-christmas-eve-candle-service", "Christmas Eve Candle Service", DateTime::Local(2016,12,24,22,0,0), DateTime::Local(2016,12,24,23,0,0) ); const auto christmas = create_appointment( Appointment::EVENT, "uid-christmas", "Christmas", DateTime::Local(2016,12,25,0,0,0), DateTime::Local(2016,12,26,0,0,0) ); const auto santa = create_appointment( Appointment::UBUNTU_ALARM, "uid-santa", "Time to set out cookies and milk for Santa", DateTime::Local(2016,12,25,1,0,0), DateTime::Local(2016,12,25,1,0,0) ); const auto bike = create_appointment( Appointment::UBUNTU_ALARM, "uid-bike", "Remember to put out the bike, it's in the garage", DateTime::Local(2016,12,25,1,0,0), DateTime::Local(2016,12,25,1,0,0) ); const auto christmas_lunch = create_appointment( Appointment::EVENT, "uid-christmas-lunch", "Christmas Lunch at Grandma's", DateTime::Local(2016,12,25,12,0,0), DateTime::Local(2016,12,25,14,0,0) ); const auto boxing_day = create_appointment( Appointment::EVENT, "uid-boxing-day", "Boxing Day", DateTime::Local(2016,12,26,0,0,0), DateTime::Local(2016,12,27,0,0,0) ); const auto new_years_eve = create_appointment( Appointment::EVENT, "uid-new-years-eve", "New Years' Eve", DateTime::Local(2016,12,31,0,0,0), DateTime::Local(2017,1,1,0,0,0) ); const auto nye_party = create_appointment( Appointment::EVENT, "uid-new-years-party", "New Year Party at Ted's", DateTime::Local(2016,12,31,19,0,0), DateTime::Local(2017, 1, 1, 2,0,0) ); const auto new_years_day = create_appointment( Appointment::EVENT, "uid-new-years-day", "New Years' Day", DateTime::Local(2017,1,1,0,0,0), DateTime::Local(2017,1,2,0,0,0) ); const auto weekday_wakeup_alarm = create_appointment( Appointment::UBUNTU_ALARM, "wakeup-alarm", "Wake Up", DateTime::Local(2017,1,3,6,0,0), DateTime::Local(2017,1,3,6,0,0) ); const auto dentist_appointment = create_appointment( Appointment::EVENT, "dentist", "Dentist", DateTime::Local(2017,1,5,14,0,0), DateTime::Local(2017,1,5,15,0,0) ); const auto marcus_birthday = create_appointment( Appointment::EVENT, "uid-mlk", "Marcus' Birthday", DateTime::Local(2017,1,8,0,0,0), DateTime::Local(2017,1,9,0,0,0) ); const auto mlk_day = create_appointment( Appointment::EVENT, "uid-mlk", "Martin Luther King Day", DateTime::Local(2017,1,16,0,0,0), DateTime::Local(2017,1,17,0,0,0) ); const auto rodney_party = create_appointment( Appointment::EVENT, "uid-rodney", "Rodney's Party", DateTime::Local(2017,1,30,19,0,0), DateTime::Local(2017,1,30,23,0,0) ); const auto pub_with_pawel = create_appointment( Appointment::UBUNTU_ALARM, "uid-pawel", "Meet Pawel at the Pub", DateTime::Local(2017,2,4,19,0,0), DateTime::Local(2017,2,4,19,0,0) ); const struct { const char* const description; DateTime start; std::vector appointments; std::vector expected_display_appointments; int max_items; } tests[] = { { "test presentation order: full-day events come before part-day events", DateTime::Local(2016,12,25,6,0,0), std::vector({christmas, christmas_lunch, boxing_day, new_years_eve}), std::vector({christmas, christmas_lunch, boxing_day, new_years_eve}), 5 }, { "test presentation order: part-day events in chronological order", DateTime::Local(2016,12,24,0,0,0), std::vector({airport, christmas_eve_candle_service, christmas, santa, christmas_lunch}), std::vector({airport, christmas_eve_candle_service, christmas, santa, christmas_lunch}), 5 }, { "test presentation order: multiple events with the same start+end sorted alphabetically", DateTime::Local(2016,12,25,0,0,0), std::vector({christmas, bike, santa, christmas_lunch}), std::vector({christmas, bike, santa, christmas_lunch}), 5 }, { "test culling priority: today's part-day events outrank today's full-day events", DateTime::Local(2016,12,25,1,0,0), std::vector({christmas, santa, christmas_lunch}), std::vector({santa, christmas_lunch}), 2 }, { "test culling priority: events later today outrank both tomorrow's full-day and part-day events", DateTime::Local(2016,12,24,0,0,0), std::vector({christmas_eve_candle_service, christmas, santa}), std::vector({christmas_eve_candle_service}), 1 }, { "test edge cases: confirm ({christmas, christmas_lunch}), std::vector({christmas, christmas_lunch}), 5 }, { "test edge cases: confirm 0 events works ok", DateTime::Local(2016,12,24,0,0,0), std::vector({}), std::vector({}), 5 }, { "test edge cases: confirm max-events of 0 doesn't crash", DateTime::Local(2016,12,24,0,0,0), std::vector({christmas, bike, santa, christmas_lunch}), std::vector({}), 0 } }; for (const auto& test : tests) { g_debug("running test: %s", test.description); // run the test... ASSERT_EQ(test.expected_display_appointments, Menu::get_display_appointments(test.appointments, test.start, test.max_items)); // ...and again with a reversed vector to confirm input order doesn't matter auto reversed = test.appointments; std::reverse(reversed.begin(), reversed.end()); ASSERT_EQ(test.expected_display_appointments, Menu::get_display_appointments(reversed, test.start, test.max_items)); } } ./tests/geoclue-fixture.h0000644000004100000410000001311213151304754015666 0ustar www-datawww-data/* * 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/glib-fixture.h0000644000004100000410000001625313151304754015171 0ustar www-datawww-data/* * Copyright 2013-2016 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 . */ #pragma once #include #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; } using source_func = std::function; guint idle_add(source_func&& func) { return g_idle_add_full( G_PRIORITY_DEFAULT_IDLE, [](gpointer gf){return (*static_cast(gf))();}, new std::function(func), [](gpointer gf){delete static_cast(gf);} ); } guint timeout_add(source_func&& func, std::chrono::milliseconds msec) { return g_timeout_add_full( G_PRIORITY_DEFAULT, msec.count(), [](gpointer gf){return (*static_cast(gf))();}, new std::function(func), [](gpointer gf){delete static_cast(gf);} ); } GMainLoop* loop {}; }; ./tests/test-eds-ics-non-selected-source.cpp0000644000004100000410000000635213151305012021266 0ustar www-datawww-data/* * 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: * Renato Araujo Oliveira Filh */ #include #include #include #include #include #include #include "glib-fixture.h" #include "timezone-mock.h" using namespace unity::indicator::datetime; using VAlarmFixture = GlibFixture; /*** **** ***/ TEST_F(VAlarmFixture, NonSelectedSources) { // start the EDS engine auto engine = std::make_shared(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,30,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); } // appointmes are visible auto appts = planner->appointments().get(); EXPECT_TRUE(appts.size() > 0); // Unselect all sources auto registry = e_source_registry_new_sync(NULL, NULL); auto sources = e_source_registry_list_sources(registry, E_SOURCE_EXTENSION_TASK_LIST); for (auto l=sources; l!=nullptr; l=l->next) { auto source = static_cast(l->data); auto extension = e_source_get_extension(source, E_SOURCE_EXTENSION_CALENDAR); e_source_selectable_set_selected(E_SOURCE_SELECTABLE(extension), FALSE); e_source_write_sync(source, NULL, NULL); } g_list_free_full(sources, g_object_unref); g_object_unref(registry); // give some time to planner update wait_msec(5 * G_TIME_SPAN_MILLISECOND); // the planner should be empty at this point appts = planner->appointments().get(); EXPECT_TRUE(appts.size() == 0); // cleanup g_time_zone_unref(gtz); } ./tests/test-eds-ics-tzids.cpp0000644000004100000410000000577613151304754016572 0ustar www-datawww-data/* * 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 #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(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. * * 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... wait_for([this](){return system_bus==nullptr && session_bus==nullptr;}, 5000); 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-sound.cpp0000644000004100000410000001306013151304754015221 0ustar www-datawww-data/* * 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); settings->cal_notification_enabled.set(true); settings->cal_notification_sounds.set(true); settings->cal_notification_vibrations.set(true); settings->cal_notification_bubbles.set(true); settings->cal_notification_list.set(true); make_interactive(); // call the Snap Decision auto func = [this](const Appointment&, const Alarm&, const Snap::Response&){g_idle_add(quit_idle, loop);}; (*snap)(appt, appt.alarms.front(), 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("calendar-app", 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&, const Snap::Response&){g_idle_add(quit_idle, loop);}; settings->cal_notification_enabled.set(true); settings->cal_notification_sounds.set(true); settings->cal_notification_vibrations.set(true); settings->cal_notification_bubbles.set(true); settings->cal_notification_list.set(true); const struct { Appointment appointment; std::string expected_role; std::string expected_uri; } test_cases[] = { { ualarm, "alarm", path_to_uri(ALARM_DEFAULT_SOUND) } // No sound for appointments // { 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); EXPECT_EQ(test_case.expected_uri, sb->uri()); EXPECT_EQ(test_case.expected_role, sb->role()); } } ./tests/test-timezone-timedated.cpp0000644000004100000410000000433113151304754017662 0ustar www-datawww-data/* * 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 * Ted Gould */ #include "timedated-fixture.h" #include using namespace unity::indicator::datetime; using TestTimedatedFixture = TimedatedFixture; /*** **** ***/ TEST_F(TestTimedatedFixture, HelloWorld) { } /** * Test that the tzid is right if timedated isn't available */ TEST_F(TestTimedatedFixture, DefaultTimezone) { const std::string expected_tzid{"Etc/Utc"}; TimedatedTimezone tmp {m_bus}; EXPECT_TZID(expected_tzid, tmp); } /** * Test that the tzid is right if timedated shows BEFORE we start */ TEST_F(TestTimedatedFixture, Timedate1First) { const std::string expected_tzid{"America/Chicago"}; start_timedate1(expected_tzid); TimedatedTimezone tmp {m_bus}; EXPECT_TZID(expected_tzid, tmp); } /** * Test that the tzid is right if timedated shows AFTER we start */ TEST_F(TestTimedatedFixture, Timedate1Last) { const std::string expected_tzid("America/Los_Angeles"); TimedatedTimezone tmp {m_bus}; start_timedate1(expected_tzid); EXPECT_TZID(expected_tzid, tmp); } /** * Test that the tzid is right if timedated's property changes */ TEST_F(TestTimedatedFixture, TimezoneChange) { const std::vector expected_tzids{"America/Los_Angeles", "America/Chicago", "Etc/Utc"}; TimedatedTimezone tmp {m_bus}; start_timedate1("America/New_York"); for(const auto& expected_tzid : expected_tzids) { set_timedate1_timezone(expected_tzid); EXPECT_TZID(expected_tzid, tmp); } } ./tests/test-timezones.cpp0000644000004100000410000001004313151304754016104 0ustar www-datawww-data/* * 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-utc.cpp0000644000004100000410000000575313151304754017356 0ustar www-datawww-data/* * 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 #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(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 #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, NonAttendingEvent) { // start the EDS engine auto engine = std::make_shared(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 2016 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, 2016,6,30,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(); EXPECT_EQ(2, appts.size()); EXPECT_EQ(appts[0].begin, DateTime(gtz, 2016, 4, 4, 16, 0, 0)); EXPECT_EQ(appts[1].begin, DateTime(gtz, 2016, 4, 6, 16, 0, 0)); // cleanup g_time_zone_unref(gtz); } ./tests/test-eds-ics-repeating-events.ics.in0000644000004100000410000000144413151304754021302 0ustar www-datawww-dataBEGIN: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-eds-ics-non-attending-alarms.ics.in0000644000004100000410000000324513151304754022045 0ustar www-datawww-dataBEGIN: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 STATUS:CONFIRMED DTSTAMP:20160405T152128Z CREATED:20160405T152128Z UID:ddtvl069dn2cquo8dhg3j9c360@google.com SEQUENCE:1 TRANSP:OPAQUE SUMMARY:Every day at 4PM DTSTART;TZID=/freeassociation.sourceforge.net/Tzfile/America/Recife: 20160404T160000 RRULE:FREQ=DAILY;UNTIL=20160406T190000Z DTEND;TZID=/freeassociation.sourceforge.net/Tzfile/America/Recife: 20160404T170000 ATTENDEE;CN=Uphablet;PARTSTAT=NEEDS-ACTION;ROLE=REQ-PARTICIPANT; CUTYPE=INDIVIDUAL:mailto:uphablet@ubuntu.com LAST-MODIFIED:20160405T152128Z BEGIN:VALARM TRIGGER;VALUE=DURATION:-PT30M ACTION:EMAIL DESCRIPTION:This is an event reminder X-EVOLUTION-ALARM-UID:20160405T152128Z-2848-32011-1844-65@ubuntu-phablet END:VALARM END:VEVENT BEGIN:VEVENT STATUS:CONFIRMED DTSTAMP:20160405T152128Z CREATED:20160405T151054Z UID:ddtvl069dn2cquo8dhg3j9c360@google.com SEQUENCE:1 TRANSP:OPAQUE SUMMARY::Every day at 4PM DTSTART;TZID=/freeassociation.sourceforge.net/Tzfile/America/Fortaleza: 20160405T160000 RECURRENCE-ID;TZID=/freeassociation.sourceforge.net/Tzfile/America/Recife: 20160405T160000 DTEND;TZID=/freeassociation.sourceforge.net/Tzfile/America/Fortaleza: 20160405T170000 ATTENDEE;CN=Uphablet;PARTSTAT=DECLINED;ROLE=REQ-PARTICIPANT; CUTYPE=INDIVIDUAL:mailto:uphablet@ubuntu.com LAST-MODIFIED:20160405T152128Z BEGIN:VALARM TRIGGER;VALUE=DURATION:-PT30M ACTION:EMAIL DESCRIPTION:This is an event reminder X-EVOLUTION-ALARM-UID:20160405T152128Z-2848-32011-1844-66@ubuntu-phablet END:VALARM END:VEVENT END:VCALENDAR ./tests/test-eds-ics-tzids.ics.in0000644000004100000410000000256113151304754017160 0ustar www-datawww-dataBEGIN:VCALENDAR CALSCALE:GREGORIAN PRODID:-//Ximian//NONSGML Evolution Calendar//EN VERSION:2.0 X-EVOLUTION-DATA-REVISION:2015-07-09T17:27:58.908570Z(0) BEGIN:VTIMEZONE TZID:/freeassociation.sourceforge.net/Tzfile/America/Sao_Paulo X-LIC-LOCATION:America/Sao_Paulo BEGIN:STANDARD TZNAME:BRT DTSTART:19700222T000000 RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=2 TZOFFSETFROM:-0200 TZOFFSETTO:-0300 END:STANDARD BEGIN:DAYLIGHT TZNAME:BRST DTSTART:19701018T000000 RRULE:FREQ=YEARLY;BYDAY=3SU;BYMONTH=10 TZOFFSETFROM:-0300 TZOFFSETTO:-0200 END:DAYLIGHT END:VTIMEZONE BEGIN:VTIMEZONE TZID:/freeassociation.sourceforge.net/Tzfile/Europe/Berlin X-LIC-LOCATION:Europe/Berlin BEGIN:STANDARD TZNAME:CET DTSTART:19701025T030000 RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10 TZOFFSETFROM:+0200 TZOFFSETTO:+0100 END:STANDARD BEGIN:DAYLIGHT TZNAME:CEST DTSTART:19700329T020000 RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=3 TZOFFSETFROM:+0100 TZOFFSETTO:+0200 END:DAYLIGHT END:VTIMEZONE BEGIN:VEVENT STATUS:CONFIRMED DTSTAMP:20150708T095820Z CREATED:20150708T095820Z UID:8ggc30kh89qql8vjumgtug7l14@google.com SEQUENCE:0 TRANSP:OPAQUE SUMMARY:Hello DTSTART;TZID=/freeassociation.sourceforge.net/Tzfile/Europe/Berlin: 20150701T200000 DTEND;TZID=/freeassociation.sourceforge.net/Tzfile/Europe/Berlin: 20150701T220000 LAST-MODIFIED:20150708T095820Z END:VEVENT END:VCALENDAR ./tests/test-utils.cpp0000644000004100000410000000625413151304754015240 0ustar www-datawww-data/* * 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-eds-ics-nonrepeating-events.ics.in0000644000004100000410000000137513151304754022020 0ustar www-datawww-dataBEGIN: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/state-mock.h0000644000004100000410000000340313151304754014630 0ustar www-datawww-data/* * 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/test-eds-ics-repeating-events-with-individual-change.ics.in0000644000004100000410000004224413151304754025627 0ustar www-datawww-dataBEGIN:VCALENDAR CALSCALE:GREGORIAN PRODID:-//Ximian//NONSGML Evolution Calendar//EN VERSION:2.0 X-EVOLUTION-DATA-REVISION:2016-06-21T21:42:08.507434Z(7) BEGIN:VTIMEZONE TZID:/freeassociation.sourceforge.net/Tzfile/America/Recife X-LIC-LOCATION:America/Recife BEGIN:STANDARD TZNAME:BRT DTSTART:19680301T000000 TZOFFSETFROM:-0200 TZOFFSETTO:-0300 END:STANDARD BEGIN:DAYLIGHT TZNAME:BRST DTSTART:19851102T000000 TZOFFSETFROM:-0300 TZOFFSETTO:-0200 END:DAYLIGHT BEGIN:STANDARD TZNAME:BRT DTSTART:19860315T000000 TZOFFSETFROM:-0200 TZOFFSETTO:-0300 END:STANDARD BEGIN:DAYLIGHT TZNAME:BRST DTSTART:19861025T000000 TZOFFSETFROM:-0300 TZOFFSETTO:-0200 END:DAYLIGHT BEGIN:STANDARD TZNAME:BRT DTSTART:19870214T000000 TZOFFSETFROM:-0200 TZOFFSETTO:-0300 END:STANDARD BEGIN:DAYLIGHT TZNAME:BRST DTSTART:19871025T000000 TZOFFSETFROM:-0300 TZOFFSETTO:-0200 END:DAYLIGHT BEGIN:STANDARD TZNAME:BRT DTSTART:19880207T000000 TZOFFSETFROM:-0200 TZOFFSETTO:-0300 END:STANDARD BEGIN:DAYLIGHT TZNAME:BRST DTSTART:19881016T000000 TZOFFSETFROM:-0300 TZOFFSETTO:-0200 END:DAYLIGHT BEGIN:STANDARD TZNAME:BRT DTSTART:19890129T000000 TZOFFSETFROM:-0200 TZOFFSETTO:-0300 END:STANDARD BEGIN:DAYLIGHT TZNAME:BRST DTSTART:19891015T000000 TZOFFSETFROM:-0300 TZOFFSETTO:-0200 END:DAYLIGHT BEGIN:STANDARD TZNAME:BRT DTSTART:19900211T000000 TZOFFSETFROM:-0200 TZOFFSETTO:-0300 END:STANDARD BEGIN:DAYLIGHT TZNAME:BRST DTSTART:19991003T000000 TZOFFSETFROM:-0300 TZOFFSETTO:-0200 END:DAYLIGHT BEGIN:STANDARD TZNAME:BRT DTSTART:20000227T000000 TZOFFSETFROM:-0200 TZOFFSETTO:-0300 END:STANDARD BEGIN:DAYLIGHT TZNAME:BRST DTSTART:20001008T000000 TZOFFSETFROM:-0300 TZOFFSETTO:-0200 END:DAYLIGHT BEGIN:STANDARD TZNAME:BRT DTSTART:20001015T000000 TZOFFSETFROM:-0200 TZOFFSETTO:-0300 END:STANDARD BEGIN:DAYLIGHT TZNAME:BRST DTSTART:20011014T000000 TZOFFSETFROM:-0300 TZOFFSETTO:-0200 END:DAYLIGHT BEGIN:STANDARD TZNAME:BRT DTSTART:20020217T000000 TZOFFSETFROM:-0200 TZOFFSETTO:-0300 END:STANDARD END:VTIMEZONE BEGIN:VTIMEZONE TZID:/freeassociation.sourceforge.net/Tzfile/America/New_York X-LIC-LOCATION:America/New_York BEGIN:STANDARD TZNAME:EST DTSTART:19691026T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19700426T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19701025T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19710425T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19711031T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19720430T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19721029T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19730429T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19731028T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19740106T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19741027T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19750223T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19751026T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19760425T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19761031T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19770424T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19771030T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19780430T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19781029T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19790429T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19791028T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19800427T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19801026T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19810426T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19811025T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19820425T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19821031T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19830424T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19831030T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19840429T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19841028T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19850428T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19851027T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19860427T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19861026T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19870405T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19871025T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19880403T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19881030T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19890402T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19891029T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19900401T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19901028T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19910407T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19911027T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19920405T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19921025T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19930404T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19931031T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19940403T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19941030T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19950402T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19951029T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19960407T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19961027T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19970406T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19971026T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19980405T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19981025T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:19990404T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:19991031T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20000402T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20001029T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20010401T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20011028T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20020407T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20021027T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20030406T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20031026T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20040404T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20041031T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20050403T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20051030T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20060402T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20061029T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20070311T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20071104T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20080309T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20081102T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20090308T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20091101T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20100314T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20101107T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20110313T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20111106T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20120311T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20121104T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20130310T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20131103T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20140309T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20141102T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20150308T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20151101T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20160313T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20161106T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20170312T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20171105T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20180311T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20181104T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20190310T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20191103T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20200308T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20201101T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20210314T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20211107T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20220313T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20221106T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20230312T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20231105T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20240310T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20241103T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20250309T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20251102T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20260308T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20261101T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20270314T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20271107T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20280312T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20281105T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20290311T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20291104T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20300310T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20301103T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20310309T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20311102T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20320314T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20321107T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20330313T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20331106T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20340312T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20341105T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20350311T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20351104T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20360309T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20361102T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD BEGIN:DAYLIGHT TZNAME:EDT DTSTART:20370308T020000 TZOFFSETFROM:-0500 TZOFFSETTO:-0400 END:DAYLIGHT BEGIN:STANDARD TZNAME:EST DTSTART:20371101T020000 TZOFFSETFROM:-0400 TZOFFSETTO:-0500 END:STANDARD END:VTIMEZONE BEGIN:VEVENT UID:20160621T214054Z-31488-1000-4151-27@rento-ubuntu DTSTAMP:20160621T123718Z DTSTART;TZID=/freeassociation.sourceforge.net/Tzfile/America/Recife: 20160620T100000 DTEND;TZID=/freeassociation.sourceforge.net/Tzfile/America/Recife: 20160620T103000 TRANSP:OPAQUE SEQUENCE:2 SUMMARY:Every day and every night CLASS:PUBLIC RRULE;X-EVOLUTION-ENDDATE=20160629T130000Z:FREQ=DAILY;COUNT=10 CREATED:20160621T214124Z LAST-MODIFIED:20160621T214124Z END:VEVENT BEGIN:VEVENT UID:20160621T214054Z-31488-1000-4151-27@rento-ubuntu DTSTAMP:20160621T123718Z DTSTART;TZID=/freeassociation.sourceforge.net/Tzfile/America/Recife: 20160624T200000 DTEND;TZID=/freeassociation.sourceforge.net/Tzfile/America/Recife: 20160624T203000 TRANSP:OPAQUE SEQUENCE:3 SUMMARY:At night CLASS:PUBLIC CREATED:20160621T214124Z LAST-MODIFIED:20160621T214208Z RECURRENCE-ID;TZID=/freeassociation.sourceforge.net/Tzfile/America/Recife: 20160624T100000 END:VEVENT END:VCALENDAR ./tests/timedated-fixture.h0000644000004100000410000001117413151304754016211 0ustar www-datawww-data/* * 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 */ #pragma once #include #include "glib-fixture.h" #include #include /*** **** ***/ struct TimedatedFixture: public GlibFixture { private: using super = GlibFixture; protected: GDBusConnection* m_bus {}; GTestDBus* m_test_bus {}; virtual void SetUp() override { super::SetUp(); // use a fake bus m_test_bus = g_test_dbus_new(G_TEST_DBUS_NONE); g_test_dbus_up(m_test_bus); const char * address = g_test_dbus_get_bus_address(m_test_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); // get the bus m_bus = g_bus_get_sync(G_BUS_TYPE_SESSION, nullptr, nullptr); g_dbus_connection_set_exit_on_close(m_bus, FALSE); g_object_add_weak_pointer(G_OBJECT(m_bus), (gpointer*)&m_bus); } virtual void TearDown() override { // take down the bus bool bus_finished = false; g_object_weak_ref( G_OBJECT(m_bus), [](gpointer gbus_finished, GObject*){*static_cast(gbus_finished) = true;}, &bus_finished ); g_clear_object(&m_bus); EXPECT_TRUE(wait_for([&bus_finished](){return bus_finished;})); // take down the GTestBus g_clear_object(&m_test_bus); super::TearDown(); } void start_timedate1(const std::string& tzid) { // start dbusmock with the timedated template auto json_parameters = g_strdup_printf("{\"Timezone\": \"%s\"}", tzid.c_str()); const gchar* child_argv[] = { "python3", "-m", "dbusmock", "--template", "timedated", "--parameters", json_parameters, nullptr }; GError* error = nullptr; g_spawn_async(nullptr, (gchar**)child_argv, nullptr, G_SPAWN_SEARCH_PATH, nullptr, nullptr, nullptr, &error); g_assert_no_error(error); g_free(json_parameters); // wait for it to appear on the bus wait_for_name_owned(m_bus, Bus::Timedate1::BUSNAME); } bool wait_for_tzid(const std::string& tzid, unity::indicator::datetime::Timezone& tz) { return wait_for([&tzid, &tz](){return tzid == tz.timezone.get();}); } void set_timedate1_timezone(const std::string& tzid) { GError* error {}; auto v = g_dbus_connection_call_sync( m_bus, Bus::Timedate1::BUSNAME, Bus::Timedate1::ADDR, Bus::Timedate1::IFACE, Bus::Timedate1::Methods::SET_TIMEZONE, g_variant_new("(sb)", tzid.c_str(), FALSE), nullptr, G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &error); g_assert_no_error(error); g_clear_pointer(&v, g_variant_unref); } std::string get_timedate1_timezone() { GError* error {}; auto v = g_dbus_connection_call_sync( m_bus, Bus::Timedate1::BUSNAME, Bus::Timedate1::ADDR, Bus::Properties::IFACE, Bus::Properties::Methods::GET, g_variant_new("(ss)", Bus::Timedate1::IFACE, Bus::Timedate1::Properties::TIMEZONE), G_VARIANT_TYPE("(v)"), G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &error); g_assert_no_error(error); GVariant* tzv {}; g_variant_get(v, "(v)", &tzv); std::string tzid; const char* tz = g_variant_get_string(tzv, nullptr); if (tz != nullptr) tzid = tz; g_clear_pointer(&tzv, g_variant_unref); g_clear_pointer(&v, g_variant_unref); return tzid; } }; #define EXPECT_TZID(expected_tzid, tmp) \ EXPECT_TRUE(wait_for_tzid(expected_tzid, tmp)) \ << "expected " << expected_tzid \ << " got " << tmp.timezone.get(); ./tests/test-alarm-queue.cpp0000644000004100000410000001242213151304754016310 0ustar www-datawww-data/* * 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-eds-ics-all-day-events.cpp0000644000004100000410000000624113151305012020232 0ustar www-datawww-data/* * 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 #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(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,30,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/test-eds-ics-nonrepeating-events.cpp0000644000004100000410000000640313151305012021400 0ustar www-datawww-data/* * 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 #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(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,30,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 */ #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!", CALENDAR_DEFAULT_SOUND, 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, system_bus); wait_msec(100); // wait a moment for the Snap to finish its async dbus bootstrapping return snap; } }; ./tests/test-live-actions.cpp0000644000004100000410000002317513151304754016476 0ustar www-datawww-data/* * 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 "state-mock.h" #include "timedated-fixture.h" #include 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() {} void set_desktop(LiveActions::Desktop desktop) { m_desktop = desktop; } protected: LiveActions::Desktop m_desktop; LiveActions::Desktop get_desktop() override { return m_desktop; } void dispatch_url(const std::string& url) override { last_url = url; } void execute_command(const std::string& cmd) override { last_cmd = cmd; } }; class TestLiveActionsFixture: public TimedatedFixture { private: using super = TimedatedFixture; protected: std::shared_ptr m_mock_state; std::shared_ptr m_state; std::shared_ptr m_live_actions; std::shared_ptr m_actions; void SetUp() override { super::SetUp(); // 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); // start the timedate1 dbusmock start_timedate1("Etc/Utc"); } void TearDown() override { m_actions.reset(); m_live_actions.reset(); m_state.reset(); m_mock_state.reset(); super::TearDown(); } }; /*** **** ***/ TEST_F(TestLiveActionsFixture, HelloWorld) { EXPECT_TRUE(true); } TEST_F(TestLiveActionsFixture, 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()); std::string new_name; m_state->settings->timezone_name.changed().connect( [&new_name](const std::string& n){new_name = n;} ); m_actions->set_location(tzid, name); EXPECT_TRUE(wait_for([&new_name](){return !new_name.empty();})); EXPECT_EQ(expected, new_name); EXPECT_EQ(expected, m_state->settings->timezone_name.get()); EXPECT_EQ(tzid, get_timedate1_timezone()); } /*** **** ***/ TEST_F(TestLiveActionsFixture, DesktopOpenAlarmApp) { m_live_actions->set_desktop(LiveActions::UNITY7); m_actions->open_alarm_app(); const std::string expected = "evolution -c calendar"; EXPECT_EQ(expected, m_live_actions->last_cmd); } TEST_F(TestLiveActionsFixture, DesktopOpenAppointment) { m_live_actions->set_desktop(LiveActions::UNITY7); Appointment a; a.uid = "some-uid"; a.begin = DateTime::NowLocal(); m_actions->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(TestLiveActionsFixture, DesktopOpenCalendarApp) { m_live_actions->set_desktop(LiveActions::UNITY7); m_actions->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(TestLiveActionsFixture, DesktopOpenSettingsApp) { m_live_actions->set_desktop(LiveActions::UNITY7); m_actions->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://ubuntu-clock-app/ubuntu-clock-app/current-user-version"; } TEST_F(TestLiveActionsFixture, PhoneOpenAlarmApp) { m_live_actions->set_desktop(LiveActions::UNITY8); m_actions->open_alarm_app(); EXPECT_EQ(clock_app_url, m_live_actions->last_url); } TEST_F(TestLiveActionsFixture, PhoneOpenAppointment) { m_live_actions->set_desktop(LiveActions::UNITY8); 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->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->open_appointment(a, a.begin); EXPECT_EQ(clock_app_url, m_live_actions->last_url); } TEST_F(TestLiveActionsFixture, PhoneOpenCalendarApp) { m_live_actions->set_desktop(LiveActions::UNITY8); auto now = DateTime::NowLocal(); m_actions->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(TestLiveActionsFixture, PhoneOpenSettingsApp) { m_live_actions->set_desktop(LiveActions::UNITY8); m_actions->open_settings_app(); const std::string expected = "settings:///system/time-date"; EXPECT_EQ(expected, m_live_actions->last_url); } /*** **** ***/ TEST_F(TestLiveActionsFixture, 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-exporter.cpp0000644000004100000410000002052113151304754015741 0ustar www-datawww-data/* * 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-locations.cpp0000644000004100000410000001230413151304754016064 0ustar www-datawww-data /* * 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-formatter.cpp0000644000004100000410000001671013151304754016101 0ustar www-datawww-data /* * 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-notification-response.cpp0000644000004100000410000001142713151304754020420 0ustar www-datawww-data/* * 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,Response) { // create the world make_interactive(); auto ne = std::make_shared(APP_NAME); auto sb = std::make_shared(); auto settings = std::make_shared(); int next_notification_id {FIRST_NOTIFY_ID}; // set a response callback that remembers what response we got bool on_response_called {}; Snap::Response response {}; auto on_response = [this, &on_response_called, &response] (const Appointment&, const Alarm&, const Snap::Response& r){ on_response_called = true; response = r; g_idle_add(quit_idle, loop); }; // our tests! const struct { Appointment appt; std::vector expected_actions; std::string action; Snap::Response expected_response; } tests[] = { { appt, {"show-app"}, "show-app", Snap::Response::ShowApp }, { ualarm, {"none", "snooze"}, "snooze", Snap::Response::Snooze }, { ualarm, {"none", "snooze"}, "none", Snap::Response::None } }; settings->cal_notification_enabled.set(true); settings->cal_notification_sounds.set(true); settings->cal_notification_vibrations.set(true); settings->cal_notification_bubbles.set(true); settings->cal_notification_list.set(true); // walk through the tests for (const auto& test : tests) { // wait for previous iterations' bus noise to finish and reset the counters GError* error {}; wait_msec(500); dbus_test_dbus_mock_object_clear_method_calls(notify_mock, notify_obj, &error); g_assert_no_error(error); on_response_called = false; // create a snap decision auto snap = create_snap(ne, sb, settings); (*snap)(test.appt, test.appt.alarms.front(), on_response); // wait for the notification to show up EXPECT_METHOD_CALLED_EVENTUALLY(notify_mock, notify_obj, METHOD_NOTIFY); // test that Notify was called the right number of times static constexpr int expected_num_notify_calls {1}; guint num_notify_calls {}; 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); EXPECT_EQ(expected_num_notify_calls, num_notify_calls); // test that Notify was called with the correct list of actions if (num_notify_calls > 0) { std::vector actions; const gchar** as {nullptr}; g_variant_get_child(notify_calls[0].params, 5, "^a&s", &as); for (int i=0; as && as[i]; i+=2) // actions are in pairs of (name, i18n), skip the i18n actions.push_back(as[i]); EXPECT_EQ(test.expected_actions, actions); } // make the notification mock tell the world that the user invoked an action const auto notification_id = next_notification_id++; idle_add([this, notification_id, test](){ GError* err {}; dbus_test_dbus_mock_object_emit_signal(notify_mock, notify_obj, "ActionInvoked", G_VARIANT_TYPE("(us)"), g_variant_new("(us)", guint(notification_id), test.action.c_str()), &err); dbus_test_dbus_mock_object_emit_signal(notify_mock, notify_obj, "NotificationClosed", G_VARIANT_TYPE("(uu)"), g_variant_new("(uu)", guint(notification_id), guint(NOTIFICATION_CLOSED_DISMISSED)), &err); g_assert_no_error(err); return G_SOURCE_REMOVE; }); // confirm that the response callback got the right response EXPECT_TRUE(wait_for([&on_response_called](){return on_response_called;})); EXPECT_EQ(int(test.expected_response), int(response)) << "notification_id " << notification_id; } } ./tests/state-fixture.h0000644000004100000410000000360213151304754015366 0ustar www-datawww-data/* * 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/test-eds-ics-config-files/0000755000004100000410000000000013151304754017257 5ustar www-datawww-data./tests/test-eds-ics-config-files/.config/0000755000004100000410000000000013151304754020602 5ustar www-datawww-data./tests/test-eds-ics-config-files/.config/evolution/0000755000004100000410000000000013151304754022626 5ustar www-datawww-data./tests/test-eds-ics-config-files/.config/evolution/sources/0000755000004100000410000000000013151304754024311 5ustar www-datawww-data./tests/test-eds-ics-config-files/.config/evolution/sources/system-proxy.source0000644000004100000410000000044013151304754030234 0ustar www-datawww-data [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/0000755000004100000410000000000013151304754020427 5ustar www-datawww-data./tests/test-eds-ics-config-files/.local/share/0000755000004100000410000000000013151304754021531 5ustar www-datawww-data./tests/test-eds-ics-config-files/.local/share/evolution/0000755000004100000410000000000013151304754023555 5ustar www-datawww-data./tests/test-eds-ics-config-files/.local/share/evolution/tasks/0000755000004100000410000000000013151304754024702 5ustar www-datawww-data./tests/test-eds-ics-config-files/.local/share/evolution/tasks/system/0000755000004100000410000000000013151304754026226 5ustar www-datawww-data./tests/test-eds-ics-config-files/.local/share/evolution/calendar/0000755000004100000410000000000013151304754025326 5ustar www-datawww-data./tests/test-eds-ics-config-files/.local/share/evolution/calendar/system/0000755000004100000410000000000013151304754026652 5ustar www-datawww-data./tests/actions-mock.h0000644000004100000410000000525113151304754015153 0ustar www-datawww-data/* * 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 { OpenAlarmApp, OpenAppt, OpenCalendarApp, OpenSettingsApp, 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 open_alarm_app() { m_history.push_back(OpenAlarmApp); } void open_appointment(const Appointment& appt, const DateTime& dt) { m_appt = appt; m_date_time = dt; m_history.push_back(OpenAppt); } void open_calendar_app(const DateTime& dt) { m_date_time = dt; m_history.push_back(OpenCalendarApp); } void open_settings_app() { m_history.push_back(OpenSettingsApp); } 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/manual-test-snap.cpp0000644000004100000410000000653213151304754016313 0ustar www-datawww-data /* * 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_response = [loop](const Appointment& appt, const Alarm&, const Snap::Response& response){ const char* str {""}; switch(response) { case Snap::Response::ShowApp: str = "show-app"; break; case Snap::Response::Snooze: str = "snooze"; break; case Snap::Response::None: str = "no-action"; break; }; g_message("You clicked '%s' for appt url '%s'", str, appt.summary.c_str()); 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(); auto system_bus = g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, nullptr); Snap snap (notification_engine, sound_builder, settings, system_bus); snap(a, a.alarms.front(), on_response); g_main_loop_run(loop); g_main_loop_unref(loop); g_clear_object(&system_bus); return 0; } ./tests/timezone-mock.h0000644000004100000410000000225013151304754015341 0ustar www-datawww-data/* * 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.ics.in0000644000004100000410000000235713151304754021140 0ustar www-datawww-dataBEGIN: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-missing-trigger.cpp0000644000004100000410000001001413151305012020510 0ustar www-datawww-data/* * 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 #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(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,30,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 }, }; 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/planner-mock.h0000644000004100000410000000316513151304754015154 0ustar www-datawww-data/* * 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_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/test-planner.cpp0000644000004100000410000000336313151304754015535 0ustar www-datawww-data/* * 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-eds-ics-tzids-2.cpp0000644000004100000410000000625413151304754016721 0ustar www-datawww-data/* * 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 #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(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 */ #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&, const Snap::Response&){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, "calendar-app", "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 disabled struct { bool cal_notification_enabled; // calendar app can 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_cal_disabled[] = { { true, std::set{ Appointment::Type::UBUNTU_ALARM, Appointment::Type::EVENT }, std::set{ Appointment::Type::UBUNTU_ALARM, Appointment::Type::EVENT } }, { false, 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_disabled : test_cal_disabled) { const bool expected_notify_called = test_appt.expected_notify_called && test_vibes.expected_notify_called && (test_disabled.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_disabled.expected_vibrate_called.count(test_appt.appt.type) > 0) && test_haptic.expected_vibrate_called; // set test case properties: cal_notification_enabled settings->cal_notification_enabled.set(test_disabled.cal_notification_enabled); settings->cal_notification_sounds.set(test_disabled.cal_notification_enabled); settings->cal_notification_vibrations.set(test_disabled.cal_notification_enabled); settings->cal_notification_bubbles.set(test_disabled.cal_notification_enabled); settings->cal_notification_list.set(test_disabled.cal_notification_enabled); // 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); // 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/test-eds-ics-non-selected-source.ics.in0000644000004100000410000000144413151304754021700 0ustar www-datawww-dataBEGIN: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/manual0000644000004100000410000001731113151304754013613 0ustar www-datawww-data 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-actions.cpp0000644000004100000410000002633613151304754015543 0ustar www-datawww-data/* * 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::OpenAlarmApp); } TEST_F(ActionsFixture, DesktopOpenAppointment) { test_action_with_appt_arg("desktop.open-appointment", MockActions::OpenAppt); } TEST_F(ActionsFixture, DesktopOpenCalendarApp) { test_action_with_time_arg("desktop.open-calendar-app", MockActions::OpenCalendarApp); } TEST_F(ActionsFixture, DesktopOpenSettingsApp) { test_action_with_no_args("desktop.open-settings-app", MockActions::OpenSettingsApp); } /*** **** ***/ TEST_F(ActionsFixture, PhoneOpenAlarmApp) { test_action_with_no_args("phone.open-alarm-app", MockActions::OpenAlarmApp); } TEST_F(ActionsFixture, PhoneOpenAppointment) { test_action_with_appt_arg("phone.open-appointment", MockActions::OpenAppt); } TEST_F(ActionsFixture, PhoneOpenCalendarApp) { test_action_with_time_arg("phone.open-calendar-app", MockActions::OpenCalendarApp); } TEST_F(ActionsFixture, PhoneOpenSettingsApp) { test_action_with_no_args("phone.open-settings-app", MockActions::OpenSettingsApp); } /*** **** ***/ 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/test-timezone-geoclue.cpp0000644000004100000410000000305013151304754017342 0ustar www-datawww-data/* * 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-eds-ics-all-day-events.ics.in0000644000004100000410000000075213151304754020650 0ustar www-datawww-dataBEGIN:VCALENDAR CALSCALE:GREGORIAN PRODID:-//Ximian//NONSGML Evolution Calendar//EN VERSION:2.0 X-EVOLUTION-DATA-REVISION:2015-05-07T21:14:49.315443Z(0) BEGIN:VEVENT UID:20150521T111538Z-7449-1000-3572-0@ghidorah DTSTAMP:20150521T001128Z DTSTART;VALUE=DATE:20150525 DTEND;VALUE=DATE:20150526 TRANSP:TRANSPARENT SEQUENCE:2 SUMMARY:Memorial Day DESCRIPTION:Today is Memorial Day CLASS:PUBLIC CREATED:20150521T111638Z LAST-MODIFIED:20150521T111638Z END:VEVENT END:VCALENDAR ./tests/accounts.db0000644000004100000410000004600013151304754014536 0ustar www-datawww-dataSQLite format 3@ -   cB+ user@ubuntu.comUbuntu3 uphablet@ubuntu.comUbuntu  Accounts Services&    <<<<<<<<<<<<<MMMMMMMMDY[llYlMMrM\MAM*MmO hhh`H`#" 4#`[cH[HNH>H(HHjXF5#`N=0 zzP%pUtableAccountsAccountsCREATE TABLE Accounts (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,provider TEXT,enabled INTEGER)P++Ytablesqlite_sequencesqlite_sequenceCREATE TABLE sqlite_sequence(name,seq)!tableServicesServicesCREATE TABLE Services (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NOT NULL UNIQUE,display TEXT NOT NULL,provider TEXT,type TEXT)/Cindexsqlite_autoindex_Services_1ServicesI#aindexidx_serviceServicesCREATE INDEX idx_service ON Services(name) mtableSettingsSettingsCREATE TABLE Settings (account INTEGER NOT NULL,service INTEGER,key TEXT NOT NULL,type TEXT NOT NULL,value BLOB)  O\m )!indexidx_signaturesSignatures CREATE UNIQUE INDEX idx_signatures ON Signatures (account, service, key)c#indexidx_settingSettingsCREATE UNIQUE INDEX idx_setting ON Settings (account, service, key)%/ triggertg_delete_accountAccountsCREATE TRIGGER tg_delete_account BEFORE DELETE ON Accounts FOR EACH ROW BEGIN DELETE FROM Settings WHERE account = OLD.id; END! !! tableSignaturesSignatures CREATE TABLE Signatures (account INTEGER NOT NULL,service INTEGER,key TEXT NOT NULL,signature TEXT NOT NULL,token TEXT NOT NULL)  ./tests/test-eds-ics-repeating-events-with-individual-change.cpp0000644000004100000410000000667513151304754025236 0ustar www-datawww-data/* * Copyright 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: * Renato Araujo Oliveira Filho */ #include #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, RepeatingEventsWithIndividualChange) { // start the EDS engine auto engine = std::make_shared(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 year of 2016 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, 2016,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... Appointment expected_appt; expected_appt.summary = "Alarm"; std::array expected_times = { DateTime(gtz,2016,6, 20,10,00,0), DateTime(gtz,2016,6, 21,10,00,0), DateTime(gtz,2016,6, 22,10,00,0), DateTime(gtz,2016,6, 23,10,00,0), DateTime(gtz,2016,6, 24,20,00,0), DateTime(gtz,2016,6, 25,10,00,0), DateTime(gtz,2016,6, 26,10,00,0), DateTime(gtz,2016,6, 27,10,00,0), DateTime(gtz,2016,6, 28,10,00,0), DateTime(gtz,2016,6, 29,10,00,0) }; // compare it to what we actually loaded... const auto appts = planner->appointments().get(); EXPECT_EQ(expected_times.size(), appts.size()); for (size_t i=0, n=expected_times.size(); i. * * Authors: * Charles Kerr */ #ifndef INDICATOR_DATETIME_TESTS_PRINT_TO #define INDICATOR_DATETIME_TESTS_PRINT_TO #include #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 << '}'; } void PrintTo(const std::vector& appointments, std::ostream* os) { *os << '{'; for (const auto& appointment : appointments) PrintTo(appointment, os); *os << '}'; } } // namespace datetime } // namespace indicator } // namespace unity #endif ./tests/wakeup-timer-mock.h0000644000004100000410000000361213151304754016124 0ustar www-datawww-data/* * 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_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/test-eds-ics-repeating-valarms.cpp0000644000004100000410000001102313151305012021020 0ustar www-datawww-data/* * 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 #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(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,30,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!", "file://" CALENDAR_DEFAULT_SOUND, DateTime(gtz,2015,4,23,13,35,0)}), appt.alarms[0]); EXPECT_EQ(Alarm({"Time to pack!", "file://" CALENDAR_DEFAULT_SOUND, DateTime(gtz,2015,4,23,13,37,0)}), appt.alarms[1]); EXPECT_EQ(Alarm({"Time to pack!", "file://" CALENDAR_DEFAULT_SOUND, DateTime(gtz,2015,4,23,13,39,0)}), appt.alarms[2]); EXPECT_EQ(Alarm({"Time to pack!", "file://" CALENDAR_DEFAULT_SOUND, DateTime(gtz,2015,4,23,13,41,0)}), appt.alarms[3]); EXPECT_EQ(Alarm({"Go to the airport!", "file://" CALENDAR_DEFAULT_SOUND, DateTime(gtz,2015,4,24,10,35,0)}), appt.alarms[4]); EXPECT_EQ(Alarm({"Go to the airport!", "file://" CALENDAR_DEFAULT_SOUND, DateTime(gtz,2015,4,24,10,37,0)}), appt.alarms[5]); EXPECT_EQ(Alarm({"Go to the airport!", "file://" CALENDAR_DEFAULT_SOUND, DateTime(gtz,2015,4,24,10,39,0)}), appt.alarms[6]); EXPECT_EQ(Alarm({"Go to the airport!", "file://" CALENDAR_DEFAULT_SOUND, 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-clock.cpp0000644000004100000410000001572513151304754015176 0ustar www-datawww-data/* * 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 "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); } ./tests/test-eds-ics-repeating-events.cpp0000644000004100000410000000757013151305012020673 0ustar www-datawww-data/* * 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 #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(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,30,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(); ixrjO,mBrXt)֬Y @AA!̙3GWڠ`x t }o-B疭k 0 #x̚5 ZZLe˖AW6rs󐑑)ϟ50\A"o~뵽~tڇdgg%Srrr"z->|xZ >%=ݭ۷:_־w {_ WWW$&$HXp!x<޴Ls8mxT8>7;E>o#.1dgd`_dpP/Q@hpD>", uW;`x:'G6~ިCd7Y3]FBl,\H*&b--bc {7BǶ~sV(/_s5h*  F`w&NN ^!Rk ;pYa؆uI2=.rDOu_8qBhihޠFhonZoe.j }7$oéKvx´  mDAlt4SD֦&F)<*B9?Ӵ΀.Ǵam0L^ h~Z,Ng{;#` vhXg܉ ̓W6:琋M8U8;:btpPfuw3g9a M|"`OBCebhx2$S]u&h;CQݤF(X^~ͳkqDP04#&r2(wʩ Wj9pT' R 9ΐP`2{o NVU%Yrf֕p`+X)ll\Qaup|2vh+_iNdݭyP= p?Dhv'4Owsq:"uJ2Hū,뱭ߴ , |hIy2SlYtw~̢kD? ?t`J D;OY%E @BXMӾS7. * * 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) || (profile == Menu::Phone)) && (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()); } ./po/0000755000004100000410000000000013151304754011664 5ustar www-datawww-data./po/fi.po0000644000004100000410000000250613151304754012625 0ustar www-datawww-data# 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/CMakeLists.txt0000644000004100000410000000042513151304754014425 0ustar www-datawww-datafind_package(Intltool REQUIRED) intltool_update_potfile( KEYWORDS "_" "_:1,2" "N_" "N_:1,2" GETTEXT_PACKAGE ${GETTEXT_PACKAGE} COPYRIGHT_HOLDER "Canonical Ltd." FILTER "test/*" ) intltool_install_translations( ALL GETTEXT_PACKAGE ${GETTEXT_PACKAGE} ) ./po/tr.po0000644000004100000410000000250313151304754012651 0ustar www-datawww-data# 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/el.po0000644000004100000410000000262013151304754012624 0ustar www-datawww-data# 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/pl.po0000644000004100000410000000260113151304754012636 0ustar www-datawww-data# 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/bg.po0000644000004100000410000000253513151304754012621 0ustar www-datawww-data# 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/fr.po0000644000004100000410000000251313151304754012634 0ustar www-datawww-data# 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/sl.po0000644000004100000410000000260013151304754012640 0ustar www-datawww-data# 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/de.po0000644000004100000410000000247713151304754012626 0ustar www-datawww-data# 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/sv.po0000644000004100000410000000247513151304754012664 0ustar www-datawww-data# 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/pt.po0000644000004100000410000000250113151304754012645 0ustar www-datawww-data# 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/nl.po0000644000004100000410000000246213151304754012641 0ustar www-datawww-data# 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_CN.po0000644000004100000410000000242413151304754013227 0ustar www-datawww-data# 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 "设置时间和日期..." ./po/ro.po0000644000004100000410000000255713151304754012655 0ustar www-datawww-data# 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/hu.po0000644000004100000410000000251313151304754012641 0ustar www-datawww-data# 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/es.po0000644000004100000410000000246713151304754012644 0ustar www-datawww-data# 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/hr.po0000644000004100000410000000261513151304754012641 0ustar www-datawww-data# 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/sk.po0000644000004100000410000000252013151304754012640 0ustar www-datawww-data# 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/sr.po0000644000004100000410000000261313151304754012652 0ustar www-datawww-data# 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/ru.po0000644000004100000410000000270213151304754012653 0ustar www-datawww-data# 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/he.po0000644000004100000410000000251113151304754012617 0ustar www-datawww-data# 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/hi.po0000644000004100000410000000263013151304754012625 0ustar www-datawww-data# 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/da.po0000644000004100000410000000250113151304754012606 0ustar www-datawww-data# 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/pt_BR.po0000644000004100000410000000250213151304754013231 0ustar www-datawww-data# 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/ja.po0000644000004100000410000000251413151304754012620 0ustar www-datawww-data# 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/indicator-datetime.pot0000644000004100000410000000357113151304754016164 0ustar www-datawww-data# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR Canonical Ltd. # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR , YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2017-02-09 12:28-0500\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #. 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" #: ../src/menu.cpp:329 msgid "%A, %e %B %Y" msgstr "" #. add the 'Add Event…' menuitem #: ../src/menu.cpp:429 msgid "Add Event…" msgstr "" #: ../src/menu.cpp:439 msgid "Clock" msgstr "" #: ../src/menu.cpp:491 msgid "Time & Date Settings…" msgstr "" #: ../src/menu.cpp:546 msgid "Date and Time" msgstr "" #: ../src/menu.cpp:596 msgid "Time & Date" msgstr "" #: ../src/menu.cpp:601 #, c-format msgid "%s (has alarms)" msgstr "" #. * strftime(3) format for abbreviated weekday, #. hours, minutes in a 12h locale; e.g. Wed, 2:00 PM #: ../src/snap.cpp:144 msgid "%a, %l:%M %p" msgstr "" #. * A strftime(3) format for abbreviated weekday, #. hours, minutes in a 24h locale; e.g. Wed, 14:00 #: ../src/snap.cpp:148 msgid "%a, %H:%M" msgstr "" #: ../src/snap.cpp:153 #, c-format msgid "Alarm %s" msgstr "" #: ../src/snap.cpp:154 #, c-format msgid "Event %s" msgstr "" #: ../src/snap.cpp:162 ../src/snap.cpp:166 msgid "OK" msgstr "" #: ../src/snap.cpp:163 msgid "Snooze" msgstr "" ./po/cs.po0000644000004100000410000000252513151304754012635 0ustar www-datawww-data# 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/th.po0000644000004100000410000000254213151304754012642 0ustar www-datawww-data# 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/ar.po0000644000004100000410000000252113151304754012626 0ustar www-datawww-data# 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/ko.po0000644000004100000410000000247113151304754012641 0ustar www-datawww-data# 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/zh_TW.po0000644000004100000410000000243613151304754013264 0ustar www-datawww-data# 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/it.po0000644000004100000410000000250013151304754012635 0ustar www-datawww-data# 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/nb.po0000644000004100000410000000252413151304754012626 0ustar www-datawww-data# 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..." ./AUTHORS0000644000004100000410000000003113151304754012310 0ustar www-datawww-data# Generated by Makefile ./data/0000755000004100000410000000000013151304754012157 5ustar www-datawww-data./data/indicator-datetime.service.in0000644000004100000410000000030013151304754017705 0ustar www-datawww-data[Unit] Description=Indicator Date & Time Backend PartOf=graphical-session.target After=indicators-pre.target [Service] ExecStart=@pkglibexecdir@/indicator-datetime-service Restart=on-failure ./data/CMakeLists.txt0000644000004100000410000000544513151304754014727 0ustar www-datawww-data## ## 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}) ## ## Systemd Unit File ## # where to install # Uncomment when we drop Vivid # pkg_get_variable(SYSTEMD_USER_DIR systemd systemduserunitdir) set (SYSTEMD_USER_DIR "/usr/lib/systemd/user") message (STATUS "${SYSTEMD_USER_DIR} is the systemd user unit file install dir") set (SYSTEMD_USER_NAME "${CMAKE_PROJECT_NAME}.service") set (SYSTEMD_USER_FILE "${CMAKE_CURRENT_BINARY_DIR}/${SYSTEMD_USER_NAME}") set (SYSTEMD_USER_FILE_IN "${CMAKE_CURRENT_SOURCE_DIR}/${SYSTEMD_USER_NAME}.in") # build it set (pkglibexecdir "${CMAKE_INSTALL_FULL_PKGLIBEXECDIR}") configure_file ("${SYSTEMD_USER_FILE_IN}" "${SYSTEMD_USER_FILE}") # install it install (FILES "${SYSTEMD_USER_FILE}" DESTINATION "${SYSTEMD_USER_DIR}") ## ## Upstart systemd override Job File ## set (UPSTART_SYSTEMD_OVERRIDE_DIR "${CMAKE_INSTALL_FULL_DATADIR}/upstart/systemd-session/upstart") message (STATUS "${UPSTART_SYSTEMD_OVERRIDE_DIR} is the Upstart override Job File for systemd dir") install (FILES "${CMAKE_CURRENT_SOURCE_DIR}/${CMAKE_PROJECT_NAME}.override" DESTINATION "${UPSTART_SYSTEMD_OVERRIDE_DIR}") ## ## 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}") ## ## 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.override0000644000004100000410000000000713151304754017463 0ustar www-datawww-datamanual ./data/com.canonical.indicator.datetime0000644000004100000410000000072113151304754020354 0ustar www-datawww-data[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 ./data/indicator-datetime.conf.in0000644000004100000410000000031713151304754017202 0ustar www-datawww-datadescription "Indicator Date & Time Backend" start on indicator-services-start stop on desktop-end or indicator-services-end respawn respawn limit 2 10 exec $SNAP@pkglibexecdir@/indicator-datetime-service ./data/com.canonical.indicator.datetime.gschema.xml.in.in0000644000004100000410000001550513151304754023601 0ustar www-datawww-data 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.xml0000644000004100000410000000321313151304754024262 0ustar www-datawww-data 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]