code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/****************************************************************************** * Icinga 2 * * Copyright (C) 2012-2015 Icinga Development Team (http://www.icinga.org) * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software Foundation * * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * ******************************************************************************/ #include "icinga/compatutility.hpp" #include "icinga/checkcommand.hpp" #include "icinga/eventcommand.hpp" #include "icinga/pluginutility.hpp" #include "icinga/service.hpp" #include "base/utility.hpp" #include "base/configtype.hpp" #include "base/objectlock.hpp" #include "base/convert.hpp" #include <boost/foreach.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/algorithm/string/join.hpp> using namespace icinga; /* command */ String CompatUtility::GetCommandLine(const Command::Ptr& command) { Value commandLine = command->GetCommandLine(); String result; if (commandLine.IsObjectType<Array>()) { Array::Ptr args = commandLine; ObjectLock olock(args); String arg; BOOST_FOREACH(arg, args) { // This is obviously incorrect for non-trivial cases. result += " \"" + EscapeString(arg) + "\""; } } else if (!commandLine.IsEmpty()) { result = EscapeString(Convert::ToString(commandLine)); } else { result = "<internal>"; } return result; } String CompatUtility::GetCommandNamePrefix(const Command::Ptr command) { if (!command) return Empty; String prefix; if (command->GetType() == ConfigType::GetByName("CheckCommand")) prefix = "check_"; else if (command->GetType() == ConfigType::GetByName("NotificationCommand")) prefix = "notification_"; else if (command->GetType() == ConfigType::GetByName("EventCommand")) prefix = "event_"; return prefix; } String CompatUtility::GetCommandName(const Command::Ptr command) { if (!command) return Empty; return GetCommandNamePrefix(command) + command->GetName(); } /* host */ int CompatUtility::GetHostCurrentState(const Host::Ptr& host) { if (host->GetState() != HostUp && !host->IsReachable()) return 2; /* hardcoded compat state */ return host->GetState(); } String CompatUtility::GetHostStateString(const Host::Ptr& host) { if (host->GetState() != HostUp && !host->IsReachable()) return "UNREACHABLE"; /* hardcoded compat state */ return Host::StateToString(host->GetState()); } String CompatUtility::GetHostAlias(const Host::Ptr& host) { if (!host->GetDisplayName().IsEmpty()) return host->GetName(); else return host->GetDisplayName(); } int CompatUtility::GetHostNotifyOnDown(const Host::Ptr& host) { unsigned long notification_state_filter = GetCheckableNotificationStateFilter(host); if (notification_state_filter & (1<<ServiceCritical) || notification_state_filter & (1<<ServiceWarning)) return 1; return 0; } int CompatUtility::GetHostNotifyOnUnreachable(const Host::Ptr& host) { unsigned long notification_state_filter = GetCheckableNotificationStateFilter(host); if (notification_state_filter & (1<<ServiceUnknown)) return 1; return 0; } /* service */ String CompatUtility::GetCheckableCommandArgs(const Checkable::Ptr& checkable) { CheckCommand::Ptr command = checkable->GetCheckCommand(); Dictionary::Ptr args = new Dictionary(); if (command) { Host::Ptr host; Service::Ptr service; tie(host, service) = GetHostService(checkable); String command_line = GetCommandLine(command); Dictionary::Ptr command_vars = command->GetVars(); if (command_vars) { ObjectLock olock(command_vars); BOOST_FOREACH(const Dictionary::Pair& kv, command_vars) { String macro = "$" + kv.first + "$"; // this is too simple if (command_line.Contains(macro)) args->Set(kv.first, kv.second); } } Dictionary::Ptr host_vars = host->GetVars(); if (host_vars) { ObjectLock olock(host_vars); BOOST_FOREACH(const Dictionary::Pair& kv, host_vars) { String macro = "$" + kv.first + "$"; // this is too simple if (command_line.Contains(macro)) args->Set(kv.first, kv.second); macro = "$host.vars." + kv.first + "$"; if (command_line.Contains(macro)) args->Set(kv.first, kv.second); } } if (service) { Dictionary::Ptr service_vars = service->GetVars(); if (service_vars) { ObjectLock olock(service_vars); BOOST_FOREACH(const Dictionary::Pair& kv, service_vars) { String macro = "$" + kv.first + "$"; // this is too simple if (command_line.Contains(macro)) args->Set(kv.first, kv.second); macro = "$service.vars." + kv.first + "$"; if (command_line.Contains(macro)) args->Set(kv.first, kv.second); } } } String arg_string; ObjectLock olock(args); BOOST_FOREACH(const Dictionary::Pair& kv, args) { arg_string += Convert::ToString(kv.first) + "=" + Convert::ToString(kv.second) + "!"; } return arg_string; } return Empty; } int CompatUtility::GetCheckableCheckType(const Checkable::Ptr& checkable) { return (checkable->GetEnableActiveChecks() ? 0 : 1); } double CompatUtility::GetCheckableCheckInterval(const Checkable::Ptr& checkable) { return checkable->GetCheckInterval() / 60.0; } double CompatUtility::GetCheckableRetryInterval(const Checkable::Ptr& checkable) { return checkable->GetRetryInterval() / 60.0; } String CompatUtility::GetCheckableCheckPeriod(const Checkable::Ptr& checkable) { TimePeriod::Ptr check_period = checkable->GetCheckPeriod(); if (check_period) return check_period->GetName(); else return "24x7"; } int CompatUtility::GetCheckableHasBeenChecked(const Checkable::Ptr& checkable) { return (checkable->GetLastCheckResult() ? 1 : 0); } int CompatUtility::GetCheckableProblemHasBeenAcknowledged(const Checkable::Ptr& checkable) { return (checkable->GetAcknowledgement() != AcknowledgementNone ? 1 : 0); } int CompatUtility::GetCheckableAcknowledgementType(const Checkable::Ptr& checkable) { return static_cast<int>(checkable->GetAcknowledgement()); } int CompatUtility::GetCheckablePassiveChecksEnabled(const Checkable::Ptr& checkable) { return (checkable->GetEnablePassiveChecks() ? 1 : 0); } int CompatUtility::GetCheckableActiveChecksEnabled(const Checkable::Ptr& checkable) { return (checkable->GetEnableActiveChecks() ? 1 : 0); } int CompatUtility::GetCheckableEventHandlerEnabled(const Checkable::Ptr& checkable) { return (checkable->GetEnableEventHandler() ? 1 : 0); } int CompatUtility::GetCheckableFlapDetectionEnabled(const Checkable::Ptr& checkable) { return (checkable->GetEnableFlapping() ? 1 : 0); } int CompatUtility::GetCheckableIsFlapping(const Checkable::Ptr& checkable) { return (checkable->IsFlapping() ? 1 : 0); } int CompatUtility::GetCheckableIsReachable(const Checkable::Ptr& checkable) { return (checkable->IsReachable() ? 1 : 0); } double CompatUtility::GetCheckablePercentStateChange(const Checkable::Ptr& checkable) { return checkable->GetFlappingCurrent(); } int CompatUtility::GetCheckableProcessPerformanceData(const Checkable::Ptr& checkable) { return (checkable->GetEnablePerfdata() ? 1 : 0); } String CompatUtility::GetCheckableEventHandler(const Checkable::Ptr& checkable) { String event_command_str; EventCommand::Ptr eventcommand = checkable->GetEventCommand(); if (eventcommand) event_command_str = eventcommand->GetName(); return event_command_str; } String CompatUtility::GetCheckableCheckCommand(const Checkable::Ptr& checkable) { String check_command_str; CheckCommand::Ptr checkcommand = checkable->GetCheckCommand(); if (checkcommand) check_command_str = checkcommand->GetName(); return check_command_str; } int CompatUtility::GetCheckableIsVolatile(const Checkable::Ptr& checkable) { return (checkable->GetVolatile() ? 1 : 0); } double CompatUtility::GetCheckableLowFlapThreshold(const Checkable::Ptr& checkable) { return checkable->GetFlappingThreshold(); } double CompatUtility::GetCheckableHighFlapThreshold(const Checkable::Ptr& checkable) { return checkable->GetFlappingThreshold(); } int CompatUtility::GetCheckableFreshnessChecksEnabled(const Checkable::Ptr& checkable) { return (checkable->GetCheckInterval() > 0 ? 1 : 0); } int CompatUtility::GetCheckableFreshnessThreshold(const Checkable::Ptr& checkable) { return static_cast<int>(checkable->GetCheckInterval()); } double CompatUtility::GetCheckableStaleness(const Checkable::Ptr& checkable) { if (checkable->HasBeenChecked() && checkable->GetLastCheck() > 0) return (Utility::GetTime() - checkable->GetLastCheck()) / (checkable->GetCheckInterval() * 3600); return 0.0; } int CompatUtility::GetCheckableIsAcknowledged(const Checkable::Ptr& checkable) { return (checkable->IsAcknowledged() ? 1 : 0); } int CompatUtility::GetCheckableNoMoreNotifications(const Checkable::Ptr& checkable) { if (CompatUtility::GetCheckableNotificationNotificationInterval(checkable) == 0 && !checkable->GetVolatile()) return 1; return 0; } int CompatUtility::GetCheckableInCheckPeriod(const Checkable::Ptr& checkable) { TimePeriod::Ptr timeperiod = checkable->GetCheckPeriod(); /* none set means always checked */ if (!timeperiod) return 1; return (timeperiod->IsInside(Utility::GetTime()) ? 1 : 0); } int CompatUtility::GetCheckableInNotificationPeriod(const Checkable::Ptr& checkable) { BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) { ObjectLock olock(notification); TimePeriod::Ptr timeperiod = notification->GetPeriod(); /* first notification wins */ if (timeperiod) return (timeperiod->IsInside(Utility::GetTime()) ? 1 : 0); } /* none set means always notified */ return 1; } /* vars attr */ Dictionary::Ptr CompatUtility::GetCustomAttributeConfig(const CustomVarObject::Ptr& object) { Dictionary::Ptr vars = object->GetVars(); if (!vars) return Dictionary::Ptr(); return vars; } String CompatUtility::GetCustomAttributeConfig(const CustomVarObject::Ptr& object, const String& name) { Dictionary::Ptr vars = object->GetVars(); if (!vars) return Empty; return vars->Get(name); } Array::Ptr CompatUtility::GetModifiedAttributesList(const CustomVarObject::Ptr& object) { Array::Ptr mod_attr_list = new Array(); if (object->GetType() != ConfigType::GetByName("Host") && object->GetType() != ConfigType::GetByName("Service") && object->GetType() != ConfigType::GetByName("User") && object->GetType() != ConfigType::GetByName("CheckCommand") && object->GetType() != ConfigType::GetByName("EventCommand") && object->GetType() != ConfigType::GetByName("NotificationCommand")) return mod_attr_list; int flags = object->GetModifiedAttributes(); if ((flags & ModAttrNotificationsEnabled)) mod_attr_list->Add("notifications_enabled"); if ((flags & ModAttrActiveChecksEnabled)) mod_attr_list->Add("active_checks_enabled"); if ((flags & ModAttrPassiveChecksEnabled)) mod_attr_list->Add("passive_checks_enabled"); if ((flags & ModAttrFlapDetectionEnabled)) mod_attr_list->Add("flap_detection_enabled"); if ((flags & ModAttrEventHandlerEnabled)) mod_attr_list->Add("event_handler_enabled"); if ((flags & ModAttrPerformanceDataEnabled)) mod_attr_list->Add("performance_data_enabled"); if ((flags & ModAttrNormalCheckInterval)) mod_attr_list->Add("check_interval"); if ((flags & ModAttrRetryCheckInterval)) mod_attr_list->Add("retry_interval"); if ((flags & ModAttrEventHandlerCommand)) mod_attr_list->Add("event_handler_command"); if ((flags & ModAttrCheckCommand)) mod_attr_list->Add("check_command"); if ((flags & ModAttrMaxCheckAttempts)) mod_attr_list->Add("max_check_attemps"); if ((flags & ModAttrCheckTimeperiod)) mod_attr_list->Add("check_timeperiod"); if ((flags & ModAttrCustomVariable)) mod_attr_list->Add("custom_variable"); return mod_attr_list; } /* notifications */ int CompatUtility::GetCheckableNotificationsEnabled(const Checkable::Ptr& checkable) { return (checkable->GetEnableNotifications() ? 1 : 0); } int CompatUtility::GetCheckableNotificationLastNotification(const Checkable::Ptr& checkable) { double last_notification = 0.0; BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) { if (notification->GetLastNotification() > last_notification) last_notification = notification->GetLastNotification(); } return static_cast<int>(last_notification); } int CompatUtility::GetCheckableNotificationNextNotification(const Checkable::Ptr& checkable) { double next_notification = 0.0; BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) { if (next_notification == 0 || notification->GetNextNotification() < next_notification) next_notification = notification->GetNextNotification(); } return static_cast<int>(next_notification); } int CompatUtility::GetCheckableNotificationNotificationNumber(const Checkable::Ptr& checkable) { int notification_number = 0; BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) { if (notification->GetNotificationNumber() > notification_number) notification_number = notification->GetNotificationNumber(); } return notification_number; } double CompatUtility::GetCheckableNotificationNotificationInterval(const Checkable::Ptr& checkable) { double notification_interval = -1; BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) { if (notification_interval == -1 || notification->GetInterval() < notification_interval) notification_interval = notification->GetInterval(); } if (notification_interval == -1) notification_interval = 60; return notification_interval / 60.0; } String CompatUtility::GetCheckableNotificationNotificationPeriod(const Checkable::Ptr& checkable) { TimePeriod::Ptr notification_period; BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) { if (notification->GetPeriod()) notification_period = notification->GetPeriod(); } if (!notification_period) return Empty; return notification_period->GetName(); } String CompatUtility::GetCheckableNotificationNotificationOptions(const Checkable::Ptr& checkable) { Host::Ptr host; Service::Ptr service; tie(host, service) = GetHostService(checkable); unsigned long notification_type_filter = 0; unsigned long notification_state_filter = 0; BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) { notification_type_filter = notification->GetTypeFilter(); notification_state_filter = notification->GetStateFilter(); } std::vector<String> notification_options; /* notification state filters */ if (service) { if (notification_state_filter & (1<<ServiceWarning)) { notification_options.push_back("w"); } if (notification_state_filter & (1<<ServiceUnknown)) { notification_options.push_back("u"); } if (notification_state_filter & (1<<ServiceCritical)) { notification_options.push_back("c"); } } else { if (notification_state_filter & (1<<HostDown)) { notification_options.push_back("d"); } } /* notification type filters */ if (notification_type_filter & (1<<NotificationRecovery)) { notification_options.push_back("r"); } if (notification_type_filter & (1<<NotificationFlappingStart) || notification_type_filter & (1<<NotificationFlappingEnd)) { notification_options.push_back("f"); } if (notification_type_filter & (1<<NotificationDowntimeStart) || notification_type_filter & (1<<NotificationDowntimeEnd) || notification_type_filter & (1<<NotificationDowntimeRemoved)) { notification_options.push_back("s"); } return boost::algorithm::join(notification_options, ","); } int CompatUtility::GetCheckableNotificationTypeFilter(const Checkable::Ptr& checkable) { unsigned long notification_type_filter = 0; BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) { ObjectLock olock(notification); notification_type_filter = notification->GetTypeFilter(); } return notification_type_filter; } int CompatUtility::GetCheckableNotificationStateFilter(const Checkable::Ptr& checkable) { unsigned long notification_state_filter = 0; BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) { ObjectLock olock(notification); notification_state_filter = notification->GetStateFilter(); } return notification_state_filter; } int CompatUtility::GetCheckableNotifyOnWarning(const Checkable::Ptr& checkable) { if (GetCheckableNotificationStateFilter(checkable) & (1<<ServiceWarning)) return 1; return 0; } int CompatUtility::GetCheckableNotifyOnCritical(const Checkable::Ptr& checkable) { if (GetCheckableNotificationStateFilter(checkable) & (1<<ServiceCritical)) return 1; return 0; } int CompatUtility::GetCheckableNotifyOnUnknown(const Checkable::Ptr& checkable) { if (GetCheckableNotificationStateFilter(checkable) & (1<<ServiceUnknown)) return 1; return 0; } int CompatUtility::GetCheckableNotifyOnRecovery(const Checkable::Ptr& checkable) { if (GetCheckableNotificationTypeFilter(checkable) & (1<<NotificationRecovery)) return 1; return 0; } int CompatUtility::GetCheckableNotifyOnFlapping(const Checkable::Ptr& checkable) { unsigned long notification_type_filter = GetCheckableNotificationTypeFilter(checkable); if (notification_type_filter & (1<<NotificationFlappingStart) || notification_type_filter & (1<<NotificationFlappingEnd)) return 1; return 0; } int CompatUtility::GetCheckableNotifyOnDowntime(const Checkable::Ptr& checkable) { unsigned long notification_type_filter = GetCheckableNotificationTypeFilter(checkable); if (notification_type_filter & (1<<NotificationDowntimeStart) || notification_type_filter & (1<<NotificationDowntimeEnd) || notification_type_filter & (1<<NotificationDowntimeRemoved)) return 1; return 0; } std::set<User::Ptr> CompatUtility::GetCheckableNotificationUsers(const Checkable::Ptr& checkable) { /* Service -> Notifications -> (Users + UserGroups -> Users) */ std::set<User::Ptr> allUsers; std::set<User::Ptr> users; BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) { ObjectLock olock(notification); users = notification->GetUsers(); std::copy(users.begin(), users.end(), std::inserter(allUsers, allUsers.begin())); BOOST_FOREACH(const UserGroup::Ptr& ug, notification->GetUserGroups()) { std::set<User::Ptr> members = ug->GetMembers(); std::copy(members.begin(), members.end(), std::inserter(allUsers, allUsers.begin())); } } return allUsers; } std::set<UserGroup::Ptr> CompatUtility::GetCheckableNotificationUserGroups(const Checkable::Ptr& checkable) { std::set<UserGroup::Ptr> usergroups; /* Service -> Notifications -> UserGroups */ BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) { ObjectLock olock(notification); BOOST_FOREACH(const UserGroup::Ptr& ug, notification->GetUserGroups()) { usergroups.insert(ug); } } return usergroups; } String CompatUtility::GetCheckResultOutput(const CheckResult::Ptr& cr) { if (!cr) return Empty; String output; String raw_output = cr->GetOutput(); /* * replace semi-colons with colons in output * semi-colon is used as delimiter in various interfaces */ boost::algorithm::replace_all(raw_output, ";", ":"); size_t line_end = raw_output.Find("\n"); return raw_output.SubStr(0, line_end); } String CompatUtility::GetCheckResultLongOutput(const CheckResult::Ptr& cr) { if (!cr) return Empty; String long_output; String output; String raw_output = cr->GetOutput(); /* * replace semi-colons with colons in output * semi-colon is used as delimiter in various interfaces */ boost::algorithm::replace_all(raw_output, ";", ":"); size_t line_end = raw_output.Find("\n"); if (line_end > 0 && line_end != String::NPos) { long_output = raw_output.SubStr(line_end+1, raw_output.GetLength()); return EscapeString(long_output); } return Empty; } String CompatUtility::GetCheckResultPerfdata(const CheckResult::Ptr& cr) { if (!cr) return String(); return PluginUtility::FormatPerfdata(cr->GetPerformanceData()); } String CompatUtility::EscapeString(const String& str) { String result = str; boost::algorithm::replace_all(result, "\n", "\\n"); return result; } String CompatUtility::UnEscapeString(const String& str) { String result = str; boost::algorithm::replace_all(result, "\\n", "\n"); return result; } std::pair<unsigned long, unsigned long> CompatUtility::ConvertTimestamp(double time) { unsigned long time_sec = static_cast<long>(time); unsigned long time_usec = (time - time_sec) * 1000 * 1000; return std::make_pair(time_sec, time_usec); } int CompatUtility::MapNotificationReasonType(NotificationType type) { switch (type) { case NotificationDowntimeStart: return 5; case NotificationDowntimeEnd: return 6; case NotificationDowntimeRemoved: return 7; case NotificationCustom: return 8; case NotificationAcknowledgement: return 1; case NotificationProblem: return 0; case NotificationRecovery: return 0; case NotificationFlappingStart: return 2; case NotificationFlappingEnd: return 3; default: return 0; } } int CompatUtility::MapExternalCommandType(const String& name) { if (name == "NONE") return 0; if (name == "ADD_HOST_COMMENT") return 1; if (name == "DEL_HOST_COMMENT") return 2; if (name == "ADD_SVC_COMMENT") return 3; if (name == "DEL_SVC_COMMENT") return 4; if (name == "ENABLE_SVC_CHECK") return 5; if (name == "DISABLE_SVC_CHECK") return 6; if (name == "SCHEDULE_SVC_CHECK") return 7; if (name == "DELAY_SVC_NOTIFICATION") return 9; if (name == "DELAY_HOST_NOTIFICATION") return 10; if (name == "DISABLE_NOTIFICATIONS") return 11; if (name == "ENABLE_NOTIFICATIONS") return 12; if (name == "RESTART_PROCESS") return 13; if (name == "SHUTDOWN_PROCESS") return 14; if (name == "ENABLE_HOST_SVC_CHECKS") return 15; if (name == "DISABLE_HOST_SVC_CHECKS") return 16; if (name == "SCHEDULE_HOST_SVC_CHECKS") return 17; if (name == "DELAY_HOST_SVC_NOTIFICATIONS") return 19; if (name == "DEL_ALL_HOST_COMMENTS") return 20; if (name == "DEL_ALL_SVC_COMMENTS") return 21; if (name == "ENABLE_SVC_NOTIFICATIONS") return 22; if (name == "DISABLE_SVC_NOTIFICATIONS") return 23; if (name == "ENABLE_HOST_NOTIFICATIONS") return 24; if (name == "DISABLE_HOST_NOTIFICATIONS") return 25; if (name == "ENABLE_ALL_NOTIFICATIONS_BEYOND_HOST") return 26; if (name == "DISABLE_ALL_NOTIFICATIONS_BEYOND_HOST") return 27; if (name == "ENABLE_HOST_SVC_NOTIFICATIONS") return 28; if (name == "DISABLE_HOST_SVC_NOTIFICATIONS") return 29; if (name == "PROCESS_SERVICE_CHECK_RESULT") return 30; if (name == "SAVE_STATE_INFORMATION") return 31; if (name == "READ_STATE_INFORMATION") return 32; if (name == "ACKNOWLEDGE_HOST_PROBLEM") return 33; if (name == "ACKNOWLEDGE_SVC_PROBLEM") return 34; if (name == "START_EXECUTING_SVC_CHECKS") return 35; if (name == "STOP_EXECUTING_SVC_CHECKS") return 36; if (name == "START_ACCEPTING_PASSIVE_SVC_CHECKS") return 37; if (name == "STOP_ACCEPTING_PASSIVE_SVC_CHECKS") return 38; if (name == "ENABLE_PASSIVE_SVC_CHECKS") return 39; if (name == "DISABLE_PASSIVE_SVC_CHECKS") return 40; if (name == "ENABLE_EVENT_HANDLERS") return 41; if (name == "DISABLE_EVENT_HANDLERS") return 42; if (name == "ENABLE_HOST_EVENT_HANDLER") return 43; if (name == "DISABLE_HOST_EVENT_HANDLER") return 44; if (name == "ENABLE_SVC_EVENT_HANDLER") return 45; if (name == "DISABLE_SVC_EVENT_HANDLER") return 46; if (name == "ENABLE_HOST_CHECK") return 47; if (name == "DISABLE_HOST_CHECK") return 48; if (name == "START_OBSESSING_OVER_SVC_CHECKS") return 49; if (name == "STOP_OBSESSING_OVER_SVC_CHECKS") return 50; if (name == "REMOVE_HOST_ACKNOWLEDGEMENT") return 51; if (name == "REMOVE_SVC_ACKNOWLEDGEMENT") return 52; if (name == "SCHEDULE_FORCED_HOST_SVC_CHECKS") return 53; if (name == "SCHEDULE_FORCED_SVC_CHECK") return 54; if (name == "SCHEDULE_HOST_DOWNTIME") return 55; if (name == "SCHEDULE_SVC_DOWNTIME") return 56; if (name == "ENABLE_HOST_FLAP_DETECTION") return 57; if (name == "DISABLE_HOST_FLAP_DETECTION") return 58; if (name == "ENABLE_SVC_FLAP_DETECTION") return 59; if (name == "DISABLE_SVC_FLAP_DETECTION") return 60; if (name == "ENABLE_FLAP_DETECTION") return 61; if (name == "DISABLE_FLAP_DETECTION") return 62; if (name == "ENABLE_HOSTGROUP_SVC_NOTIFICATIONS") return 63; if (name == "DISABLE_HOSTGROUP_SVC_NOTIFICATIONS") return 64; if (name == "ENABLE_HOSTGROUP_HOST_NOTIFICATIONS") return 65; if (name == "DISABLE_HOSTGROUP_HOST_NOTIFICATIONS") return 66; if (name == "ENABLE_HOSTGROUP_SVC_CHECKS") return 67; if (name == "DISABLE_HOSTGROUP_SVC_CHECKS") return 68; if (name == "CANCEL_HOST_DOWNTIME") return 69; if (name == "CANCEL_SVC_DOWNTIME") return 70; if (name == "CANCEL_ACTIVE_HOST_DOWNTIME") return 71; if (name == "CANCEL_PENDING_HOST_DOWNTIME") return 72; if (name == "CANCEL_ACTIVE_SVC_DOWNTIME") return 73; if (name == "CANCEL_PENDING_SVC_DOWNTIME") return 74; if (name == "CANCEL_ACTIVE_HOST_SVC_DOWNTIME") return 75; if (name == "CANCEL_PENDING_HOST_SVC_DOWNTIME") return 76; if (name == "FLUSH_PENDING_COMMANDS") return 77; if (name == "DEL_HOST_DOWNTIME") return 78; if (name == "DEL_SVC_DOWNTIME") return 79; if (name == "ENABLE_FAILURE_PREDICTION") return 80; if (name == "DISABLE_FAILURE_PREDICTION") return 81; if (name == "ENABLE_PERFORMANCE_DATA") return 82; if (name == "DISABLE_PERFORMANCE_DATA") return 83; if (name == "SCHEDULE_HOSTGROUP_HOST_DOWNTIME") return 84; if (name == "SCHEDULE_HOSTGROUP_SVC_DOWNTIME") return 85; if (name == "SCHEDULE_HOST_SVC_DOWNTIME") return 86; if (name == "PROCESS_HOST_CHECK_RESULT") return 87; if (name == "START_EXECUTING_HOST_CHECKS") return 88; if (name == "STOP_EXECUTING_HOST_CHECKS") return 89; if (name == "START_ACCEPTING_PASSIVE_HOST_CHECKS") return 90; if (name == "STOP_ACCEPTING_PASSIVE_HOST_CHECKS") return 91; if (name == "ENABLE_PASSIVE_HOST_CHECKS") return 92; if (name == "DISABLE_PASSIVE_HOST_CHECKS") return 93; if (name == "START_OBSESSING_OVER_HOST_CHECKS") return 94; if (name == "STOP_OBSESSING_OVER_HOST_CHECKS") return 95; if (name == "SCHEDULE_HOST_CHECK") return 96; if (name == "SCHEDULE_FORCED_HOST_CHECK") return 98; if (name == "START_OBSESSING_OVER_SVC") return 99; if (name == "STOP_OBSESSING_OVER_SVC") return 100; if (name == "START_OBSESSING_OVER_HOST") return 101; if (name == "STOP_OBSESSING_OVER_HOST") return 102; if (name == "ENABLE_HOSTGROUP_HOST_CHECKS") return 103; if (name == "DISABLE_HOSTGROUP_HOST_CHECKS") return 104; if (name == "ENABLE_HOSTGROUP_PASSIVE_SVC_CHECKS") return 105; if (name == "DISABLE_HOSTGROUP_PASSIVE_SVC_CHECKS") return 106; if (name == "ENABLE_HOSTGROUP_PASSIVE_HOST_CHECKS") return 107; if (name == "DISABLE_HOSTGROUP_PASSIVE_HOST_CHECKS") return 108; if (name == "ENABLE_SERVICEGROUP_SVC_NOTIFICATIONS") return 109; if (name == "DISABLE_SERVICEGROUP_SVC_NOTIFICATIONS") return 110; if (name == "ENABLE_SERVICEGROUP_HOST_NOTIFICATIONS") return 111; if (name == "DISABLE_SERVICEGROUP_HOST_NOTIFICATIONS") return 112; if (name == "ENABLE_SERVICEGROUP_SVC_CHECKS") return 113; if (name == "DISABLE_SERVICEGROUP_SVC_CHECKS") return 114; if (name == "ENABLE_SERVICEGROUP_HOST_CHECKS") return 115; if (name == "DISABLE_SERVICEGROUP_HOST_CHECKS") return 116; if (name == "ENABLE_SERVICEGROUP_PASSIVE_SVC_CHECKS") return 117; if (name == "DISABLE_SERVICEGROUP_PASSIVE_SVC_CHECKS") return 118; if (name == "ENABLE_SERVICEGROUP_PASSIVE_HOST_CHECKS") return 119; if (name == "DISABLE_SERVICEGROUP_PASSIVE_HOST_CHECKS") return 120; if (name == "SCHEDULE_SERVICEGROUP_HOST_DOWNTIME") return 121; if (name == "SCHEDULE_SERVICEGROUP_SVC_DOWNTIME") return 122; if (name == "CHANGE_GLOBAL_HOST_EVENT_HANDLER") return 123; if (name == "CHANGE_GLOBAL_SVC_EVENT_HANDLER") return 124; if (name == "CHANGE_HOST_EVENT_HANDLER") return 125; if (name == "CHANGE_SVC_EVENT_HANDLER") return 126; if (name == "CHANGE_HOST_CHECK_COMMAND") return 127; if (name == "CHANGE_SVC_CHECK_COMMAND") return 128; if (name == "CHANGE_NORMAL_HOST_CHECK_INTERVAL") return 129; if (name == "CHANGE_NORMAL_SVC_CHECK_INTERVAL") return 130; if (name == "CHANGE_RETRY_SVC_CHECK_INTERVAL") return 131; if (name == "CHANGE_MAX_HOST_CHECK_ATTEMPTS") return 132; if (name == "CHANGE_MAX_SVC_CHECK_ATTEMPTS") return 133; if (name == "SCHEDULE_AND_PROPAGATE_TRIGGERED_HOST_DOWNTIME") return 134; if (name == "ENABLE_HOST_AND_CHILD_NOTIFICATIONS") return 135; if (name == "DISABLE_HOST_AND_CHILD_NOTIFICATIONS") return 136; if (name == "SCHEDULE_AND_PROPAGATE_HOST_DOWNTIME") return 137; if (name == "ENABLE_SERVICE_FRESHNESS_CHECKS") return 138; if (name == "DISABLE_SERVICE_FRESHNESS_CHECKS") return 139; if (name == "ENABLE_HOST_FRESHNESS_CHECKS") return 140; if (name == "DISABLE_HOST_FRESHNESS_CHECKS") return 141; if (name == "SET_HOST_NOTIFICATION_NUMBER") return 142; if (name == "SET_SVC_NOTIFICATION_NUMBER") return 143; if (name == "CHANGE_HOST_CHECK_TIMEPERIOD") return 144; if (name == "CHANGE_SVC_CHECK_TIMEPERIOD") return 145; if (name == "PROCESS_FILE") return 146; if (name == "CHANGE_CUSTOM_HOST_VAR") return 147; if (name == "CHANGE_CUSTOM_SVC_VAR") return 148; if (name == "CHANGE_CUSTOM_CONTACT_VAR") return 149; if (name == "ENABLE_CONTACT_HOST_NOTIFICATIONS") return 150; if (name == "DISABLE_CONTACT_HOST_NOTIFICATIONS") return 151; if (name == "ENABLE_CONTACT_SVC_NOTIFICATIONS") return 152; if (name == "DISABLE_CONTACT_SVC_NOTIFICATIONS") return 153; if (name == "ENABLE_CONTACTGROUP_HOST_NOTIFICATIONS") return 154; if (name == "DISABLE_CONTACTGROUP_HOST_NOTIFICATIONS") return 155; if (name == "ENABLE_CONTACTGROUP_SVC_NOTIFICATIONS") return 156; if (name == "DISABLE_CONTACTGROUP_SVC_NOTIFICATIONS") return 157; if (name == "CHANGE_RETRY_HOST_CHECK_INTERVAL") return 158; if (name == "SEND_CUSTOM_HOST_NOTIFICATION") return 159; if (name == "SEND_CUSTOM_SVC_NOTIFICATION") return 160; if (name == "CHANGE_HOST_NOTIFICATION_TIMEPERIOD") return 161; if (name == "CHANGE_SVC_NOTIFICATION_TIMEPERIOD") return 162; if (name == "CHANGE_CONTACT_HOST_NOTIFICATION_TIMEPERIOD") return 163; if (name == "CHANGE_CONTACT_SVC_NOTIFICATION_TIMEPERIOD") return 164; if (name == "CHANGE_HOST_MODATTR") return 165; if (name == "CHANGE_SVC_MODATTR") return 166; if (name == "CHANGE_CONTACT_MODATTR") return 167; if (name == "CHANGE_CONTACT_MODHATTR") return 168; if (name == "CHANGE_CONTACT_MODSATTR") return 169; if (name == "SYNC_STATE_INFORMATION") return 170; if (name == "DEL_DOWNTIME_BY_HOST_NAME") return 171; if (name == "DEL_DOWNTIME_BY_HOSTGROUP_NAME") return 172; if (name == "DEL_DOWNTIME_BY_START_TIME_COMMENT") return 173; if (name == "ACKNOWLEDGE_HOST_PROBLEM_EXPIRE") return 174; if (name == "ACKNOWLEDGE_SVC_PROBLEM_EXPIRE") return 175; if (name == "DISABLE_NOTIFICATIONS_EXPIRE_TIME") return 176; if (name == "CUSTOM_COMMAND") return 999; return 0; }
ogg1980/icinga2
lib/icinga/compatutility.cpp
C++
gpl-2.0
32,466
<?php /** * Shop System Plugins - Terms of Use * * The plugins offered are provided free of charge by Qenta Payment CEE GmbH * (abbreviated to Qenta CEE) and are explicitly not part of the Qenta CEE range of * products and services. * * They have been tested and approved for full functionality in the standard configuration * (status on delivery) of the corresponding shop system. They are under General Public * License Version 2 (GPLv2) and can be used, developed and passed on to third parties under * the same terms. * * However, Qenta CEE does not provide any guarantee or accept any liability for any errors * occurring when used in an enhanced, customized shop system configuration. * * Operation in an enhanced, customized configuration is at your own risk and requires a * comprehensive test phase by the user of the plugin. * * Customers use the plugins at their own risk. Qenta CEE does not guarantee their full * functionality neither does Qenta CEE assume liability for any disadvantages related to * the use of the plugins. Additionally, Qenta CEE does not guarantee the full functionality * for customized shop systems or installed plugins of other vendors of plugins within the same * shop system. * * Customers are responsible for testing the plugin's functionality before starting productive * operation. * * By installing the plugin into the shop system the customer agrees to these terms of use. * Please do not use the plugin if you do not agree to these terms of use! */ /** * Config class * * Handles configuration settings, basketcreation and addressinformation * * @since 1.3.0 */ class WC_Gateway_WCP_Config { /** * Payment gateway settings * * @since 1.3.0 * @access protected * @var array */ protected $_settings; /** * Test/Demo configurations * * @since 1.3.0 * @access protected * @var array */ protected $_presets = array( 'demo' => array( 'customer_id' => 'D200001', 'shop_id' => '', 'secret' => 'B8AKTPWBRMNBV455FG6M2DANE99WU2', 'backendpw' => 'jcv45z' ), 'test' => array( 'customer_id' => 'D200411', 'shop_id' => '', 'secret' => 'CHCSH7UGHVVX2P7EHDHSY4T2S4CGYK4QBE4M5YUUG2ND5BEZWNRZW5EJYVJQ', 'backendpw' => '2g4f9q2m' ), 'test3d' => array( 'customer_id' => 'D200411', 'shop_id' => '3D', 'secret' => 'DP4TMTPQQWFJW34647RM798E9A5X7E8ATP462Z4VGZK53YEJ3JWXS98B9P4F', 'backendpw' => '2g4f9q2m' ) ); /** * WC_Gateway_WCP_Config constructor. * * @since 1.3.0 * * @param $gateway_settings */ public function __construct( $gateway_settings ) { $this->_settings = $gateway_settings; } /** * Handles configuration modes and returns config array for FrontendClient * * @since 1.3.0 * * @return array * */ public function get_client_config() { $config_mode = $this->_settings['configuration']; if ( array_key_exists( $config_mode, $this->_presets ) ) { return Array( 'CUSTOMER_ID' => $this->_presets[ $config_mode ]['customer_id'], 'SHOP_ID' => $this->_presets[ $config_mode ]['shop_id'], 'SECRET' => $this->_presets[ $config_mode ]['secret'], 'LANGUAGE' => $this->get_language_code(), ); } else { return Array( 'CUSTOMER_ID' => trim( $this->_settings['customer_id'] ), 'SHOP_ID' => trim( $this->_settings['shop_id'] ), 'SECRET' => trim( $this->_settings['secret'] ), 'LANGUAGE' => $this->get_language_code(), ); } } /** * Getter for customer id * * @since 1.3.2 * * @return string */ public function get_customer_id() { $config_mode = $this->_settings['configuration']; if ( array_key_exists( $config_mode, $this->_presets ) ) { return $this->_presets[ $config_mode ]['customer_id']; } else { return trim( $this->_settings['customer_id'] ); } } /** * Extract language code from locale settings * * @since 1.3.0 * @return mixed */ public function get_language_code() { $locale = get_locale(); $parts = explode( '_', $locale ); return $parts[0]; } /** * Return configured secret * * @return string */ public function get_secret() { $config = $this->get_client_config(); return $config['SECRET']; } /** * Checks is ratepay enabled * * @since 1.3.8 * @param $payment_provider * @return boolean */ public function is_ratepay_enabled($payment_provider) { return $this->_settings[$payment_provider] == 'ratepay'; } }
wirecard/woocommerce-wcp
woocommerce-qenta-checkout-page/classes/class-woocommerce-wcp-config.php
PHP
gpl-2.0
4,522
#ifndef _LINUX_MMZONE_H #define _LINUX_MMZONE_H #ifndef __ASSEMBLY__ #ifndef __GENERATING_BOUNDS_H #include <linux/spinlock.h> #include <linux/list.h> #include <linux/wait.h> #include <linux/bitops.h> #include <linux/cache.h> #include <linux/threads.h> #include <linux/numa.h> #include <linux/init.h> #include <linux/seqlock.h> #include <linux/nodemask.h> #include <linux/pageblock-flags.h> #include <generated/bounds.h> #include <linux/atomic.h> #include <asm/page.h> /* Free memory management - zoned buddy allocator. */ #ifndef CONFIG_FORCE_MAX_ZONEORDER #define MAX_ORDER 11 #else #define MAX_ORDER CONFIG_FORCE_MAX_ZONEORDER #endif #define MAX_ORDER_NR_PAGES (1 << (MAX_ORDER - 1)) /* * PAGE_ALLOC_COSTLY_ORDER is the order at which allocations are deemed * costly to service. That is between allocation orders which should * coelesce naturally under reasonable reclaim pressure and those which * will not. */ #define PAGE_ALLOC_COSTLY_ORDER 3 enum { MIGRATE_UNMOVABLE, MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_PCPTYPES, /* the number of types on the pcp lists */ MIGRATE_RESERVE = MIGRATE_PCPTYPES, #ifdef CONFIG_CMA /* * MIGRATE_CMA migration type is designed to mimic the way * ZONE_MOVABLE works. Only movable pages can be allocated * from MIGRATE_CMA pageblocks and page allocator never * implicitly change migration type of MIGRATE_CMA pageblock. * * The way to use it is to change migratetype of a range of * pageblocks to MIGRATE_CMA which can be done by * __free_pageblock_cma() function. What is important though * is that a range of pageblocks must be aligned to * MAX_ORDER_NR_PAGES should biggest page be bigger then * a single pageblock. */ MIGRATE_CMA, #endif MIGRATE_ISOLATE, /* can't allocate from here */ MIGRATE_TYPES }; /* * Returns a list which contains the migrate types on to which * an allocation falls back when the free list for the migrate * type mtype is depleted. * The end of the list is delimited by the type MIGRATE_RESERVE. */ extern int *get_migratetype_fallbacks(int mtype); #ifdef CONFIG_CMA bool is_cma_pageblock(struct page *page); # define is_migrate_cma(migratetype) unlikely((migratetype) == MIGRATE_CMA) #else # define is_cma_pageblock(page) false # define is_migrate_cma(migratetype) false #endif #define for_each_migratetype_order(order, type) \ for (order = 0; order < MAX_ORDER; order++) \ for (type = 0; type < MIGRATE_TYPES; type++) extern int page_group_by_mobility_disabled; static inline int get_pageblock_migratetype(struct page *page) { return get_pageblock_flags_group(page, PB_migrate, PB_migrate_end); } struct free_area { struct list_head free_list[MIGRATE_TYPES]; unsigned long nr_free; }; struct pglist_data; /* * zone->lock and zone->lru_lock are two of the hottest locks in the kernel. * So add a wild amount of padding here to ensure that they fall into separate * cachelines. There are very few zone structures in the machine, so space * consumption is not a concern here. */ #if defined(CONFIG_SMP) struct zone_padding { char x[0]; } ____cacheline_internodealigned_in_smp; #define ZONE_PADDING(name) struct zone_padding name; #else #define ZONE_PADDING(name) #endif enum zone_stat_item { /* First 128 byte cacheline (assuming 64 bit words) */ NR_FREE_PAGES, NR_LRU_BASE, NR_INACTIVE_ANON = NR_LRU_BASE, /* must match order of LRU_[IN]ACTIVE */ NR_ACTIVE_ANON, /* " " " " " */ NR_INACTIVE_FILE, /* " " " " " */ NR_ACTIVE_FILE, /* " " " " " */ NR_UNEVICTABLE, /* " " " " " */ NR_MLOCK, /* mlock()ed pages found and moved off LRU */ NR_ANON_PAGES, /* Mapped anonymous pages */ NR_FILE_MAPPED, /* pagecache pages mapped into pagetables. only modified from process context */ NR_FILE_PAGES, NR_FILE_DIRTY, NR_WRITEBACK, NR_SLAB_RECLAIMABLE, NR_SLAB_UNRECLAIMABLE, NR_PAGETABLE, /* used for pagetables */ NR_KERNEL_STACK, /* Second 128 byte cacheline */ NR_UNSTABLE_NFS, /* NFS unstable pages */ NR_BOUNCE, NR_VMSCAN_WRITE, NR_VMSCAN_IMMEDIATE, /* Prioritise for reclaim when writeback ends */ NR_WRITEBACK_TEMP, /* Writeback using temporary buffers */ NR_ISOLATED_ANON, /* Temporary isolated pages from anon lru */ NR_ISOLATED_FILE, /* Temporary isolated pages from file lru */ NR_SHMEM, /* shmem pages (included tmpfs/GEM pages) */ NR_DIRTIED, /* page dirtyings since bootup */ NR_WRITTEN, /* page writings since bootup */ #ifdef CONFIG_NUMA NUMA_HIT, /* allocated in intended node */ NUMA_MISS, /* allocated in non intended node */ NUMA_FOREIGN, /* was intended here, hit elsewhere */ NUMA_INTERLEAVE_HIT, /* interleaver preferred this zone */ NUMA_LOCAL, /* allocation from local node */ NUMA_OTHER, /* allocation from other node */ #endif NR_ANON_TRANSPARENT_HUGEPAGES, NR_FREE_CMA_PAGES, NR_VM_ZONE_STAT_ITEMS }; /* * We do arithmetic on the LRU lists in various places in the code, * so it is important to keep the active lists LRU_ACTIVE higher in * the array than the corresponding inactive lists, and to keep * the *_FILE lists LRU_FILE higher than the corresponding _ANON lists. * * This has to be kept in sync with the statistics in zone_stat_item * above and the descriptions in vmstat_text in mm/vmstat.c */ #define LRU_BASE 0 #define LRU_ACTIVE 1 #define LRU_FILE 2 enum lru_list { LRU_INACTIVE_ANON = LRU_BASE, LRU_ACTIVE_ANON = LRU_BASE + LRU_ACTIVE, LRU_INACTIVE_FILE = LRU_BASE + LRU_FILE, LRU_ACTIVE_FILE = LRU_BASE + LRU_FILE + LRU_ACTIVE, LRU_UNEVICTABLE, NR_LRU_LISTS }; #define for_each_lru(lru) for (lru = 0; lru < NR_LRU_LISTS; lru++) #define for_each_evictable_lru(lru) for (lru = 0; lru <= LRU_ACTIVE_FILE; lru++) static inline int is_file_lru(enum lru_list lru) { return (lru == LRU_INACTIVE_FILE || lru == LRU_ACTIVE_FILE); } static inline int is_active_lru(enum lru_list lru) { return (lru == LRU_ACTIVE_ANON || lru == LRU_ACTIVE_FILE); } static inline int is_unevictable_lru(enum lru_list lru) { return (lru == LRU_UNEVICTABLE); } struct lruvec { struct list_head lists[NR_LRU_LISTS]; }; /* Mask used at gathering information at once (see memcontrol.c) */ #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE)) #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON)) #define LRU_ALL_EVICTABLE (LRU_ALL_FILE | LRU_ALL_ANON) #define LRU_ALL ((1 << NR_LRU_LISTS) - 1) /* Isolate inactive pages */ #define ISOLATE_INACTIVE ((__force isolate_mode_t)0x1) /* Isolate active pages */ #define ISOLATE_ACTIVE ((__force isolate_mode_t)0x2) /* Isolate clean file */ #define ISOLATE_CLEAN ((__force isolate_mode_t)0x4) /* Isolate unmapped file */ #define ISOLATE_UNMAPPED ((__force isolate_mode_t)0x8) /* Isolate for asynchronous migration */ #define ISOLATE_ASYNC_MIGRATE ((__force isolate_mode_t)0x10) /* LRU Isolation modes. */ typedef unsigned __bitwise__ isolate_mode_t; enum zone_watermarks { WMARK_MIN, WMARK_LOW, WMARK_HIGH, NR_WMARK }; #define min_wmark_pages(z) (z->watermark[WMARK_MIN]) #define low_wmark_pages(z) (z->watermark[WMARK_LOW]) #define high_wmark_pages(z) (z->watermark[WMARK_HIGH]) struct per_cpu_pages { int count; /* number of pages in the list */ int high; /* high watermark, emptying needed */ int batch; /* chunk size for buddy add/remove */ /* Lists of pages, one per migrate type stored on the pcp-lists */ struct list_head lists[MIGRATE_PCPTYPES]; }; struct per_cpu_pageset { struct per_cpu_pages pcp; #ifdef CONFIG_NUMA s8 expire; #endif #ifdef CONFIG_SMP s8 stat_threshold; s8 vm_stat_diff[NR_VM_ZONE_STAT_ITEMS]; #endif }; #endif /* !__GENERATING_BOUNDS.H */ enum zone_type { #ifdef CONFIG_ZONE_DMA /* * ZONE_DMA is used when there are devices that are not able * to do DMA to all of addressable memory (ZONE_NORMAL). Then we * carve out the portion of memory that is needed for these devices. * The range is arch specific. * * Some examples * * Architecture Limit * --------------------------- * parisc, ia64, sparc <4G * s390 <2G * arm Various * alpha Unlimited or 0-16MB. * * i386, x86_64 and multiple other arches * <16M. */ ZONE_DMA, #endif #ifdef CONFIG_ZONE_DMA32 /* * x86_64 needs two ZONE_DMAs because it supports devices that are * only able to do DMA to the lower 16M but also 32 bit devices that * can only do DMA areas below 4G. */ ZONE_DMA32, #endif /* * Normal addressable memory is in ZONE_NORMAL. DMA operations can be * performed on pages in ZONE_NORMAL if the DMA devices support * transfers to all addressable memory. */ ZONE_NORMAL, #ifdef CONFIG_HIGHMEM /* * A memory area that is only addressable by the kernel through * mapping portions into its own address space. This is for example * used by i386 to allow the kernel to address the memory beyond * 900MB. The kernel will set up special mappings (page * table entries on i386) for each page that the kernel needs to * access. */ ZONE_HIGHMEM, #endif ZONE_MOVABLE, __MAX_NR_ZONES }; #ifndef __GENERATING_BOUNDS_H /* * When a memory allocation must conform to specific limitations (such * as being suitable for DMA) the caller will pass in hints to the * allocator in the gfp_mask, in the zone modifier bits. These bits * are used to select a priority ordered list of memory zones which * match the requested limits. See gfp_zone() in include/linux/gfp.h */ #if MAX_NR_ZONES < 2 #define ZONES_SHIFT 0 #elif MAX_NR_ZONES <= 2 #define ZONES_SHIFT 1 #elif MAX_NR_ZONES <= 4 #define ZONES_SHIFT 2 #else #error ZONES_SHIFT -- too many zones configured adjust calculation #endif struct zone_reclaim_stat { /* * The pageout code in vmscan.c keeps track of how many of the * mem/swap backed and file backed pages are refeferenced. * The higher the rotated/scanned ratio, the more valuable * that cache is. * * The anon LRU stats live in [0], file LRU stats in [1] */ unsigned long recent_rotated[2]; unsigned long recent_scanned[2]; }; struct zone { /* Fields commonly accessed by the page allocator */ /* zone watermarks, access with *_wmark_pages(zone) macros */ unsigned long watermark[NR_WMARK]; /* * When free pages are below this point, additional steps are taken * when reading the number of free pages to avoid per-cpu counter * drift allowing watermarks to be breached */ unsigned long percpu_drift_mark; /* * We don't know if the memory that we're going to allocate will be freeable * or/and it will be released eventually, so to avoid totally wasting several * GB of ram we must reserve some of the lower zone memory (otherwise we risk * to run OOM on the lower zones despite there's tons of freeable ram * on the higher zones). This array is recalculated at runtime if the * sysctl_lowmem_reserve_ratio sysctl changes. */ unsigned long lowmem_reserve[MAX_NR_ZONES]; /* * This is a per-zone reserve of pages that should not be * considered dirtyable memory. */ unsigned long dirty_balance_reserve; #ifdef CONFIG_NUMA int node; /* * zone reclaim becomes active if more unmapped pages exist. */ unsigned long min_unmapped_pages; unsigned long min_slab_pages; #endif struct per_cpu_pageset __percpu *pageset; /* * free areas of different sizes */ spinlock_t lock; #if defined CONFIG_COMPACTION || defined CONFIG_CMA /* Set to true when the PG_migrate_skip bits should be cleared */ bool compact_blockskip_flush; /* pfns where compaction scanners should start */ unsigned long compact_cached_free_pfn; unsigned long compact_cached_migrate_pfn; #endif #ifdef CONFIG_MEMORY_HOTPLUG /* see spanned/present_pages for more description */ seqlock_t span_seqlock; #endif #ifdef CONFIG_CMA bool cma_alloc; #endif struct free_area free_area[MAX_ORDER]; #ifndef CONFIG_SPARSEMEM /* * Flags for a pageblock_nr_pages block. See pageblock-flags.h. * In SPARSEMEM, this map is stored in struct mem_section */ unsigned long *pageblock_flags; #endif /* CONFIG_SPARSEMEM */ #ifdef CONFIG_COMPACTION /* * On compaction failure, 1<<compact_defer_shift compactions * are skipped before trying again. The number attempted since * last failure is tracked with compact_considered. */ unsigned int compact_considered; unsigned int compact_defer_shift; int compact_order_failed; #endif ZONE_PADDING(_pad1_) /* Fields commonly accessed by the page reclaim scanner */ spinlock_t lru_lock; struct lruvec lruvec; struct zone_reclaim_stat reclaim_stat; unsigned long pages_scanned; /* since last reclaim */ unsigned long flags; /* zone flags, see below */ /* Zone statistics */ atomic_long_t vm_stat[NR_VM_ZONE_STAT_ITEMS]; /* * The target ratio of ACTIVE_ANON to INACTIVE_ANON pages on * this zone's LRU. Maintained by the pageout code. */ unsigned int inactive_ratio; ZONE_PADDING(_pad2_) /* Rarely used or read-mostly fields */ /* * wait_table -- the array holding the hash table * wait_table_hash_nr_entries -- the size of the hash table array * wait_table_bits -- wait_table_size == (1 << wait_table_bits) * * The purpose of all these is to keep track of the people * waiting for a page to become available and make them * runnable again when possible. The trouble is that this * consumes a lot of space, especially when so few things * wait on pages at a given time. So instead of using * per-page waitqueues, we use a waitqueue hash table. * * The bucket discipline is to sleep on the same queue when * colliding and wake all in that wait queue when removing. * When something wakes, it must check to be sure its page is * truly available, a la thundering herd. The cost of a * collision is great, but given the expected load of the * table, they should be so rare as to be outweighed by the * benefits from the saved space. * * __wait_on_page_locked() and unlock_page() in mm/filemap.c, are the * primary users of these fields, and in mm/page_alloc.c * free_area_init_core() performs the initialization of them. */ wait_queue_head_t * wait_table; unsigned long wait_table_hash_nr_entries; unsigned long wait_table_bits; /* * Discontig memory support fields. */ struct pglist_data *zone_pgdat; /* zone_start_pfn == zone_start_paddr >> PAGE_SHIFT */ unsigned long zone_start_pfn; /* * zone_start_pfn, spanned_pages and present_pages are all * protected by span_seqlock. It is a seqlock because it has * to be read outside of zone->lock, and it is done in the main * allocator path. But, it is written quite infrequently. * * The lock is declared along with zone->lock because it is * frequently read in proximity to zone->lock. It's good to * give them a chance of being in the same cacheline. */ unsigned long spanned_pages; /* total size, including holes */ unsigned long present_pages; /* amount of memory (excluding holes) */ /* * rarely used fields: */ const char *name; } ____cacheline_internodealigned_in_smp; typedef enum { ZONE_RECLAIM_LOCKED, /* prevents concurrent reclaim */ ZONE_OOM_LOCKED, /* zone is in OOM killer zonelist */ ZONE_CONGESTED, /* zone has many dirty pages backed by * a congested BDI */ } zone_flags_t; static inline void zone_set_flag(struct zone *zone, zone_flags_t flag) { set_bit(flag, &zone->flags); } static inline int zone_test_and_set_flag(struct zone *zone, zone_flags_t flag) { return test_and_set_bit(flag, &zone->flags); } static inline void zone_clear_flag(struct zone *zone, zone_flags_t flag) { clear_bit(flag, &zone->flags); } static inline int zone_is_reclaim_congested(const struct zone *zone) { return test_bit(ZONE_CONGESTED, &zone->flags); } static inline int zone_is_reclaim_locked(const struct zone *zone) { return test_bit(ZONE_RECLAIM_LOCKED, &zone->flags); } static inline int zone_is_oom_locked(const struct zone *zone) { return test_bit(ZONE_OOM_LOCKED, &zone->flags); } /* * The "priority" of VM scanning is how much of the queues we will scan in one * go. A value of 12 for DEF_PRIORITY implies that we will scan 1/4096th of the * queues ("queue_length >> 12") during an aging round. */ #define DEF_PRIORITY 12 /* Maximum number of zones on a zonelist */ #define MAX_ZONES_PER_ZONELIST (MAX_NUMNODES * MAX_NR_ZONES) #ifdef CONFIG_NUMA /* * The NUMA zonelists are doubled because we need zonelists that restrict the * allocations to a single node for GFP_THISNODE. * * [0] : Zonelist with fallback * [1] : No fallback (GFP_THISNODE) */ #define MAX_ZONELISTS 2 /* * We cache key information from each zonelist for smaller cache * footprint when scanning for free pages in get_page_from_freelist(). * * 1) The BITMAP fullzones tracks which zones in a zonelist have come * up short of free memory since the last time (last_fullzone_zap) * we zero'd fullzones. * 2) The array z_to_n[] maps each zone in the zonelist to its node * id, so that we can efficiently evaluate whether that node is * set in the current tasks mems_allowed. * * Both fullzones and z_to_n[] are one-to-one with the zonelist, * indexed by a zones offset in the zonelist zones[] array. * * The get_page_from_freelist() routine does two scans. During the * first scan, we skip zones whose corresponding bit in 'fullzones' * is set or whose corresponding node in current->mems_allowed (which * comes from cpusets) is not set. During the second scan, we bypass * this zonelist_cache, to ensure we look methodically at each zone. * * Once per second, we zero out (zap) fullzones, forcing us to * reconsider nodes that might have regained more free memory. * The field last_full_zap is the time we last zapped fullzones. * * This mechanism reduces the amount of time we waste repeatedly * reexaming zones for free memory when they just came up low on * memory momentarilly ago. * * The zonelist_cache struct members logically belong in struct * zonelist. However, the mempolicy zonelists constructed for * MPOL_BIND are intentionally variable length (and usually much * shorter). A general purpose mechanism for handling structs with * multiple variable length members is more mechanism than we want * here. We resort to some special case hackery instead. * * The MPOL_BIND zonelists don't need this zonelist_cache (in good * part because they are shorter), so we put the fixed length stuff * at the front of the zonelist struct, ending in a variable length * zones[], as is needed by MPOL_BIND. * * Then we put the optional zonelist cache on the end of the zonelist * struct. This optional stuff is found by a 'zlcache_ptr' pointer in * the fixed length portion at the front of the struct. This pointer * both enables us to find the zonelist cache, and in the case of * MPOL_BIND zonelists, (which will just set the zlcache_ptr to NULL) * to know that the zonelist cache is not there. * * The end result is that struct zonelists come in two flavors: * 1) The full, fixed length version, shown below, and * 2) The custom zonelists for MPOL_BIND. * The custom MPOL_BIND zonelists have a NULL zlcache_ptr and no zlcache. * * Even though there may be multiple CPU cores on a node modifying * fullzones or last_full_zap in the same zonelist_cache at the same * time, we don't lock it. This is just hint data - if it is wrong now * and then, the allocator will still function, perhaps a bit slower. */ struct zonelist_cache { unsigned short z_to_n[MAX_ZONES_PER_ZONELIST]; /* zone->nid */ DECLARE_BITMAP(fullzones, MAX_ZONES_PER_ZONELIST); /* zone full? */ unsigned long last_full_zap; /* when last zap'd (jiffies) */ }; #else #define MAX_ZONELISTS 1 struct zonelist_cache; #endif /* * This struct contains information about a zone in a zonelist. It is stored * here to avoid dereferences into large structures and lookups of tables */ struct zoneref { struct zone *zone; /* Pointer to actual zone */ int zone_idx; /* zone_idx(zoneref->zone) */ }; /* * One allocation request operates on a zonelist. A zonelist * is a list of zones, the first one is the 'goal' of the * allocation, the other zones are fallback zones, in decreasing * priority. * * If zlcache_ptr is not NULL, then it is just the address of zlcache, * as explained above. If zlcache_ptr is NULL, there is no zlcache. * * * To speed the reading of the zonelist, the zonerefs contain the zone index * of the entry being read. Helper functions to access information given * a struct zoneref are * * zonelist_zone() - Return the struct zone * for an entry in _zonerefs * zonelist_zone_idx() - Return the index of the zone for an entry * zonelist_node_idx() - Return the index of the node for an entry */ struct zonelist { struct zonelist_cache *zlcache_ptr; // NULL or &zlcache struct zoneref _zonerefs[MAX_ZONES_PER_ZONELIST + 1]; #ifdef CONFIG_NUMA struct zonelist_cache zlcache; // optional ... #endif }; #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP struct node_active_region { unsigned long start_pfn; unsigned long end_pfn; int nid; }; #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */ #ifndef CONFIG_DISCONTIGMEM /* The array of struct pages - for discontigmem use pgdat->lmem_map */ extern struct page *mem_map; #endif /* * The pg_data_t structure is used in machines with CONFIG_DISCONTIGMEM * (mostly NUMA machines?) to denote a higher-level memory zone than the * zone denotes. * * On NUMA machines, each NUMA node would have a pg_data_t to describe * it's memory layout. * * Memory statistics and page replacement data structures are maintained on a * per-zone basis. */ struct bootmem_data; typedef struct pglist_data { struct zone node_zones[MAX_NR_ZONES]; struct zonelist node_zonelists[MAX_ZONELISTS]; int nr_zones; #ifdef CONFIG_FLAT_NODE_MEM_MAP /* means !SPARSEMEM */ struct page *node_mem_map; #ifdef CONFIG_CGROUP_MEM_RES_CTLR struct page_cgroup *node_page_cgroup; #endif #endif #ifndef CONFIG_NO_BOOTMEM struct bootmem_data *bdata; #endif #ifdef CONFIG_MEMORY_HOTPLUG /* * Must be held any time you expect node_start_pfn, node_present_pages * or node_spanned_pages stay constant. Holding this will also * guarantee that any pfn_valid() stays that way. * * Nests above zone->lock and zone->size_seqlock. */ spinlock_t node_size_lock; #endif unsigned long node_start_pfn; unsigned long node_present_pages; /* total number of physical pages */ unsigned long node_spanned_pages; /* total size of physical page range, including holes */ int node_id; wait_queue_head_t kswapd_wait; struct task_struct *kswapd; /* Protected by lock_memory_hotplug() */ int kswapd_max_order; enum zone_type classzone_idx; } pg_data_t; #define node_present_pages(nid) (NODE_DATA(nid)->node_present_pages) #define node_spanned_pages(nid) (NODE_DATA(nid)->node_spanned_pages) #ifdef CONFIG_FLAT_NODE_MEM_MAP #define pgdat_page_nr(pgdat, pagenr) ((pgdat)->node_mem_map + (pagenr)) #else #define pgdat_page_nr(pgdat, pagenr) pfn_to_page((pgdat)->node_start_pfn + (pagenr)) #endif #define nid_page_nr(nid, pagenr) pgdat_page_nr(NODE_DATA(nid),(pagenr)) #define node_start_pfn(nid) (NODE_DATA(nid)->node_start_pfn) #define node_end_pfn(nid) ({\ pg_data_t *__pgdat = NODE_DATA(nid);\ __pgdat->node_start_pfn + __pgdat->node_spanned_pages;\ }) #include <linux/memory_hotplug.h> extern struct mutex zonelists_mutex; void build_all_zonelists(void *data); void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx); bool zone_watermark_ok(struct zone *z, int order, unsigned long mark, int classzone_idx, int alloc_flags); bool zone_watermark_ok_safe(struct zone *z, int order, unsigned long mark, int classzone_idx, int alloc_flags); enum memmap_context { MEMMAP_EARLY, MEMMAP_HOTPLUG, }; extern int init_currently_empty_zone(struct zone *zone, unsigned long start_pfn, unsigned long size, enum memmap_context context); #ifdef CONFIG_HAVE_MEMORY_PRESENT void memory_present(int nid, unsigned long start, unsigned long end); #else static inline void memory_present(int nid, unsigned long start, unsigned long end) {} #endif #ifdef CONFIG_HAVE_MEMORYLESS_NODES int local_memory_node(int node_id); #else static inline int local_memory_node(int node_id) { return node_id; }; #endif #ifdef CONFIG_NEED_NODE_MEMMAP_SIZE unsigned long __init node_memmap_size_bytes(int, unsigned long, unsigned long); #endif /* * zone_idx() returns 0 for the ZONE_DMA zone, 1 for the ZONE_NORMAL zone, etc. */ #define zone_idx(zone) ((zone) - (zone)->zone_pgdat->node_zones) static inline int populated_zone(struct zone *zone) { return (!!zone->present_pages); } extern int movable_zone; static inline int zone_movable_is_highmem(void) { #if defined(CONFIG_HIGHMEM) && defined(CONFIG_HAVE_MEMBLOCK_NODE) return movable_zone == ZONE_HIGHMEM; #else return 0; #endif } static inline int is_highmem_idx(enum zone_type idx) { #ifdef CONFIG_HIGHMEM return (idx == ZONE_HIGHMEM || (idx == ZONE_MOVABLE && zone_movable_is_highmem())); #else return 0; #endif } static inline int is_normal_idx(enum zone_type idx) { return (idx == ZONE_NORMAL); } /** * is_highmem - helper function to quickly check if a struct zone is a * highmem zone or not. This is an attempt to keep references * to ZONE_{DMA/NORMAL/HIGHMEM/etc} in general code to a minimum. * @zone - pointer to struct zone variable */ static inline int is_highmem(struct zone *zone) { #ifdef CONFIG_HIGHMEM int zone_off = (char *)zone - (char *)zone->zone_pgdat->node_zones; return zone_off == ZONE_HIGHMEM * sizeof(*zone) || (zone_off == ZONE_MOVABLE * sizeof(*zone) && zone_movable_is_highmem()); #else return 0; #endif } static inline int is_normal(struct zone *zone) { return zone == zone->zone_pgdat->node_zones + ZONE_NORMAL; } static inline int is_dma32(struct zone *zone) { #ifdef CONFIG_ZONE_DMA32 return zone == zone->zone_pgdat->node_zones + ZONE_DMA32; #else return 0; #endif } static inline int is_dma(struct zone *zone) { #ifdef CONFIG_ZONE_DMA return zone == zone->zone_pgdat->node_zones + ZONE_DMA; #else return 0; #endif } /* These two functions are used to setup the per zone pages min values */ struct ctl_table; int min_free_kbytes_sysctl_handler(struct ctl_table *, int, void __user *, size_t *, loff_t *); extern int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1]; int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *, int, void __user *, size_t *, loff_t *); int percpu_pagelist_fraction_sysctl_handler(struct ctl_table *, int, void __user *, size_t *, loff_t *); int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table *, int, void __user *, size_t *, loff_t *); int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *, int, void __user *, size_t *, loff_t *); extern int numa_zonelist_order_handler(struct ctl_table *, int, void __user *, size_t *, loff_t *); extern char numa_zonelist_order[]; #define NUMA_ZONELIST_ORDER_LEN 16 /* string buffer size */ #ifndef CONFIG_NEED_MULTIPLE_NODES extern struct pglist_data contig_page_data; #define NODE_DATA(nid) (&contig_page_data) #define NODE_MEM_MAP(nid) mem_map #else /* CONFIG_NEED_MULTIPLE_NODES */ #include <asm/mmzone.h> #endif /* !CONFIG_NEED_MULTIPLE_NODES */ extern struct pglist_data *first_online_pgdat(void); extern struct pglist_data *next_online_pgdat(struct pglist_data *pgdat); extern struct zone *next_zone(struct zone *zone); /** * for_each_online_pgdat - helper macro to iterate over all online nodes * @pgdat - pointer to a pg_data_t variable */ #define for_each_online_pgdat(pgdat) \ for (pgdat = first_online_pgdat(); \ pgdat; \ pgdat = next_online_pgdat(pgdat)) /** * for_each_zone - helper macro to iterate over all memory zones * @zone - pointer to struct zone variable * * The user only needs to declare the zone variable, for_each_zone * fills it in. */ #define for_each_zone(zone) \ for (zone = (first_online_pgdat())->node_zones; \ zone; \ zone = next_zone(zone)) #define for_each_populated_zone(zone) \ for (zone = (first_online_pgdat())->node_zones; \ zone; \ zone = next_zone(zone)) \ if (!populated_zone(zone)) \ ; /* do nothing */ \ else static inline struct zone *zonelist_zone(struct zoneref *zoneref) { return zoneref->zone; } static inline int zonelist_zone_idx(struct zoneref *zoneref) { return zoneref->zone_idx; } static inline int zonelist_node_idx(struct zoneref *zoneref) { #ifdef CONFIG_NUMA /* zone_to_nid not available in this context */ return zoneref->zone->node; #else return 0; #endif /* CONFIG_NUMA */ } /** * next_zones_zonelist - Returns the next zone at or below highest_zoneidx within the allowed nodemask using a cursor within a zonelist as a starting point * @z - The cursor used as a starting point for the search * @highest_zoneidx - The zone index of the highest zone to return * @nodes - An optional nodemask to filter the zonelist with * @zone - The first suitable zone found is returned via this parameter * * This function returns the next zone at or below a given zone index that is * within the allowed nodemask using a cursor as the starting point for the * search. The zoneref returned is a cursor that represents the current zone * being examined. It should be advanced by one before calling * next_zones_zonelist again. */ struct zoneref *next_zones_zonelist(struct zoneref *z, enum zone_type highest_zoneidx, nodemask_t *nodes, struct zone **zone); /** * first_zones_zonelist - Returns the first zone at or below highest_zoneidx within the allowed nodemask in a zonelist * @zonelist - The zonelist to search for a suitable zone * @highest_zoneidx - The zone index of the highest zone to return * @nodes - An optional nodemask to filter the zonelist with * @zone - The first suitable zone found is returned via this parameter * * This function returns the first zone at or below a given zone index that is * within the allowed nodemask. The zoneref returned is a cursor that can be * used to iterate the zonelist with next_zones_zonelist by advancing it by * one before calling. */ static inline struct zoneref *first_zones_zonelist(struct zonelist *zonelist, enum zone_type highest_zoneidx, nodemask_t *nodes, struct zone **zone) { return next_zones_zonelist(zonelist->_zonerefs, highest_zoneidx, nodes, zone); } /** * for_each_zone_zonelist_nodemask - helper macro to iterate over valid zones in a zonelist at or below a given zone index and within a nodemask * @zone - The current zone in the iterator * @z - The current pointer within zonelist->zones being iterated * @zlist - The zonelist being iterated * @highidx - The zone index of the highest zone to return * @nodemask - Nodemask allowed by the allocator * * This iterator iterates though all zones at or below a given zone index and * within a given nodemask */ #define for_each_zone_zonelist_nodemask(zone, z, zlist, highidx, nodemask) \ for (z = first_zones_zonelist(zlist, highidx, nodemask, &zone); \ zone; \ z = next_zones_zonelist(++z, highidx, nodemask, &zone)) \ /** * for_each_zone_zonelist - helper macro to iterate over valid zones in a zonelist at or below a given zone index * @zone - The current zone in the iterator * @z - The current pointer within zonelist->zones being iterated * @zlist - The zonelist being iterated * @highidx - The zone index of the highest zone to return * * This iterator iterates though all zones at or below a given zone index. */ #define for_each_zone_zonelist(zone, z, zlist, highidx) \ for_each_zone_zonelist_nodemask(zone, z, zlist, highidx, NULL) #ifdef CONFIG_SPARSEMEM #include <asm/sparsemem.h> #endif #if !defined(CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID) && \ !defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP) static inline unsigned long early_pfn_to_nid(unsigned long pfn) { return 0; } #endif #ifdef CONFIG_FLATMEM #define pfn_to_nid(pfn) (0) #endif #ifdef CONFIG_SPARSEMEM /* * SECTION_SHIFT #bits space required to store a section # * * PA_SECTION_SHIFT physical address to/from section number * PFN_SECTION_SHIFT pfn to/from section number */ #define SECTIONS_SHIFT (MAX_PHYSMEM_BITS - SECTION_SIZE_BITS) #define PA_SECTION_SHIFT (SECTION_SIZE_BITS) #define PFN_SECTION_SHIFT (SECTION_SIZE_BITS - PAGE_SHIFT) #define NR_MEM_SECTIONS (1UL << SECTIONS_SHIFT) #define PAGES_PER_SECTION (1UL << PFN_SECTION_SHIFT) #define PAGE_SECTION_MASK (~(PAGES_PER_SECTION-1)) #define SECTION_BLOCKFLAGS_BITS \ ((1UL << (PFN_SECTION_SHIFT - pageblock_order)) * NR_PAGEBLOCK_BITS) #if (MAX_ORDER - 1 + PAGE_SHIFT) > SECTION_SIZE_BITS #error Allocator MAX_ORDER exceeds SECTION_SIZE #endif #define pfn_to_section_nr(pfn) ((pfn) >> PFN_SECTION_SHIFT) #define section_nr_to_pfn(sec) ((sec) << PFN_SECTION_SHIFT) #define SECTION_ALIGN_UP(pfn) (((pfn) + PAGES_PER_SECTION - 1) & PAGE_SECTION_MASK) #define SECTION_ALIGN_DOWN(pfn) ((pfn) & PAGE_SECTION_MASK) struct page; struct page_cgroup; struct mem_section { /* * This is, logically, a pointer to an array of struct * pages. However, it is stored with some other magic. * (see sparse.c::sparse_init_one_section()) * * Additionally during early boot we encode node id of * the location of the section here to guide allocation. * (see sparse.c::memory_present()) * * Making it a UL at least makes someone do a cast * before using it wrong. */ unsigned long section_mem_map; /* See declaration of similar field in struct zone */ unsigned long *pageblock_flags; #ifdef CONFIG_CGROUP_MEM_RES_CTLR /* * If !SPARSEMEM, pgdat doesn't have page_cgroup pointer. We use * section. (see memcontrol.h/page_cgroup.h about this.) */ struct page_cgroup *page_cgroup; unsigned long pad; #endif }; #ifdef CONFIG_SPARSEMEM_EXTREME #define SECTIONS_PER_ROOT (PAGE_SIZE / sizeof (struct mem_section)) #else #define SECTIONS_PER_ROOT 1 #endif #define SECTION_NR_TO_ROOT(sec) ((sec) / SECTIONS_PER_ROOT) #define NR_SECTION_ROOTS DIV_ROUND_UP(NR_MEM_SECTIONS, SECTIONS_PER_ROOT) #define SECTION_ROOT_MASK (SECTIONS_PER_ROOT - 1) #ifdef CONFIG_SPARSEMEM_EXTREME extern struct mem_section *mem_section[NR_SECTION_ROOTS]; #else extern struct mem_section mem_section[NR_SECTION_ROOTS][SECTIONS_PER_ROOT]; #endif static inline struct mem_section *__nr_to_section(unsigned long nr) { if (!mem_section[SECTION_NR_TO_ROOT(nr)]) return NULL; return &mem_section[SECTION_NR_TO_ROOT(nr)][nr & SECTION_ROOT_MASK]; } extern int __section_nr(struct mem_section* ms); extern unsigned long usemap_size(void); /* * We use the lower bits of the mem_map pointer to store * a little bit of information. There should be at least * 3 bits here due to 32-bit alignment. */ #define SECTION_MARKED_PRESENT (1UL<<0) #define SECTION_HAS_MEM_MAP (1UL<<1) #define SECTION_MAP_LAST_BIT (1UL<<2) #define SECTION_MAP_MASK (~(SECTION_MAP_LAST_BIT-1)) #define SECTION_NID_SHIFT 2 static inline struct page *__section_mem_map_addr(struct mem_section *section) { unsigned long map = section->section_mem_map; map &= SECTION_MAP_MASK; return (struct page *)map; } static inline int present_section(struct mem_section *section) { return (section && (section->section_mem_map & SECTION_MARKED_PRESENT)); } static inline int present_section_nr(unsigned long nr) { return present_section(__nr_to_section(nr)); } static inline int valid_section(struct mem_section *section) { return (section && (section->section_mem_map & SECTION_HAS_MEM_MAP)); } static inline int valid_section_nr(unsigned long nr) { return valid_section(__nr_to_section(nr)); } static inline struct mem_section *__pfn_to_section(unsigned long pfn) { return __nr_to_section(pfn_to_section_nr(pfn)); } #ifndef CONFIG_HAVE_ARCH_PFN_VALID static inline int pfn_valid(unsigned long pfn) { if (pfn_to_section_nr(pfn) >= NR_MEM_SECTIONS) return 0; return valid_section(__nr_to_section(pfn_to_section_nr(pfn))); } #endif static inline int pfn_present(unsigned long pfn) { if (pfn_to_section_nr(pfn) >= NR_MEM_SECTIONS) return 0; return present_section(__nr_to_section(pfn_to_section_nr(pfn))); } /* * These are _only_ used during initialisation, therefore they * can use __initdata ... They could have names to indicate * this restriction. */ #ifdef CONFIG_NUMA #define pfn_to_nid(pfn) \ ({ \ unsigned long __pfn_to_nid_pfn = (pfn); \ page_to_nid(pfn_to_page(__pfn_to_nid_pfn)); \ }) #else #define pfn_to_nid(pfn) (0) #endif #define early_pfn_valid(pfn) pfn_valid(pfn) void sparse_init(void); #else #define sparse_init() do {} while (0) #define sparse_index_init(_sec, _nid) do {} while (0) #endif /* CONFIG_SPARSEMEM */ #ifdef CONFIG_NODES_SPAN_OTHER_NODES bool early_pfn_in_nid(unsigned long pfn, int nid); #else #define early_pfn_in_nid(pfn, nid) (1) #endif #ifndef early_pfn_valid #define early_pfn_valid(pfn) (1) #endif void memory_present(int nid, unsigned long start, unsigned long end); unsigned long __init node_memmap_size_bytes(int, unsigned long, unsigned long); /* * If it is possible to have holes within a MAX_ORDER_NR_PAGES, then we * need to check pfn validility within that MAX_ORDER_NR_PAGES block. * pfn_valid_within() should be used in this case; we optimise this away * when we have no holes within a MAX_ORDER_NR_PAGES block. */ #ifdef CONFIG_HOLES_IN_ZONE #define pfn_valid_within(pfn) pfn_valid(pfn) #else #define pfn_valid_within(pfn) (1) #endif #ifdef CONFIG_ARCH_HAS_HOLES_MEMORYMODEL /* * pfn_valid() is meant to be able to tell if a given PFN has valid memmap * associated with it or not. In FLATMEM, it is expected that holes always * have valid memmap as long as there is valid PFNs either side of the hole. * In SPARSEMEM, it is assumed that a valid section has a memmap for the * entire section. * * However, an ARM, and maybe other embedded architectures in the future * free memmap backing holes to save memory on the assumption the memmap is * never used. The page_zone linkages are then broken even though pfn_valid() * returns true. A walker of the full memmap must then do this additional * check to ensure the memmap they are looking at is sane by making sure * the zone and PFN linkages are still valid. This is expensive, but walkers * of the full memmap are extremely rare. */ int memmap_valid_within(unsigned long pfn, struct page *page, struct zone *zone); #else static inline int memmap_valid_within(unsigned long pfn, struct page *page, struct zone *zone) { return 1; } #endif /* CONFIG_ARCH_HAS_HOLES_MEMORYMODEL */ #endif /* !__GENERATING_BOUNDS.H */ #endif /* !__ASSEMBLY__ */ #endif /* _LINUX_MMZONE_H */
Unlegacy-Android/android_kernel_omap4_common
include/linux/mmzone.h
C
gpl-2.0
38,834
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ /** * Sales order view items block * * @author Magento Core Team <core@magentocommerce.com> */ namespace Magento\Shipping\Block; /** * @api * @since 100.0.2 */ class Items extends \Magento\Sales\Block\Items\AbstractItems { /** * Core registry * * @var \Magento\Framework\Registry */ protected $_coreRegistry = null; /** * @param \Magento\Framework\View\Element\Template\Context $context * @param \Magento\Framework\Registry $registry * @param array $data */ public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Framework\Registry $registry, array $data = [] ) { $this->_coreRegistry = $registry; parent::__construct($context, $data); } /** * Retrieve current order model instance * * @return \Magento\Sales\Model\Order */ public function getOrder() { return $this->_coreRegistry->registry('current_order'); } /** * @param object $shipment * @return string */ public function getPrintShipmentUrl($shipment) { return $this->getUrl('*/*/printShipment', ['shipment_id' => $shipment->getId()]); } /** * @param object $order * @return string */ public function getPrintAllShipmentsUrl($order) { return $this->getUrl('*/*/printShipment', ['order_id' => $order->getId()]); } /** * Get html of shipment comments block * * @param \Magento\Sales\Model\Order\Shipment $shipment * @return string */ public function getCommentsHtml($shipment) { $html = ''; $comments = $this->getChildBlock('shipment_comments'); if ($comments) { $comments->setEntity($shipment)->setTitle(__('About Your Shipment')); $html = $comments->toHtml(); } return $html; } }
kunj1988/Magento2
app/code/Magento/Shipping/Block/Items.php
PHP
gpl-2.0
2,035
<?php /** * @file * Provides hook documentation for PGAPI module. */ function hook_pgapi_callback($transaction) { } function hook_pgapi_format_price($type, $price, $symbol) { } function hook_pgapi_transaction($status, $transaction) { } function hook_pgapi_transaction_all($status, $transaction) { } function hook_pgapi_gw($op, $a3 = NULL, $a4 = NULL) { } function hook_pgapi_transaction_status(&$status) { } function hook_pgapi_transaction_workflow(&$workflow) { }
usabilidoido/corais
sites/all/modules/pgapi/pgapi.api.php
PHP
gpl-2.0
489
/* ** Copyright (C) 2010-2013 Sourcefire, Inc. ** Author: Michael R. Altizer <maltizer@sourcefire.com> ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License Version 2 as ** published by the Free Software Foundation. You may not use, modify or ** distribute this program under any other version of the GNU General ** Public License. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef _DAQ_COMMON_H #define _DAQ_COMMON_H #include <stdint.h> #include <unistd.h> #include <netinet/in.h> #ifndef WIN32 #include <sys/time.h> #else /* for struct timeavl */ #include <winsock2.h> #include <windows.h> #endif #ifndef DAQ_SO_PUBLIC #if defined _WIN32 || defined __CYGWIN__ # if defined DAQ_DLL # ifdef __GNUC__ # define DAQ_SO_PUBLIC __attribute__((dllexport)) # else # define DAQ_SO_PUBLIC __declspec(dllexport) # endif # else # ifdef __GNUC__ # define DAQ_SO_PUBLIC __attribute__((dllimport)) # else # define DAQ_SO_PUBLIC __declspec(dllimport) # endif # endif # define DLL_LOCAL #else # ifdef HAVE_VISIBILITY # define DAQ_SO_PUBLIC __attribute__ ((visibility("default"))) # define DAQ_SO_PRIVATE __attribute__ ((visibility("hidden"))) # else # define DAQ_SO_PUBLIC # define DAQ_SO_PRIVATE # endif #endif #endif #ifdef _WIN32 # ifdef DAQ_DLL # define DAQ_LINKAGE DAQ_SO_PUBLIC # else # define DAQ_LINKAGE # endif #else # define DAQ_LINKAGE DAQ_SO_PUBLIC #endif #define DAQ_PKTCNT_OP_SET 5 /* User liked return value */ #define DAQ_PKTCNT_OP_DATA 4 /* User liked return value */ #define DAQ_PKTCNT_OP_NONE 3 /* User liked return value */ #define DAQ_USER_INT_EXIT 2 /* Daq interrupted by user */ #define DAQ_HALF_EXIT 1 /* Daq Initialize interrupted by user */ #define DAQ_SUCCESS 0 /* Success! */ #define DAQ_ERROR -1 /* Generic error */ #define DAQ_ERROR_NOMEM -2 /* Out of memory error */ #define DAQ_ERROR_NODEV -3 /* No such device error */ #define DAQ_ERROR_NOTSUP -4 /* Functionality is unsupported error */ #define DAQ_ERROR_NOMOD -5 /* No module specified error */ #define DAQ_ERROR_NOCTX -6 /* No context specified error */ #define DAQ_ERROR_INVAL -7 /* Invalid argument/request error */ #define DAQ_ERROR_EXISTS -8 /* Argument or device already exists */ #define DAQ_ERROR_AGAIN -9 /* Try again */ #define DAQ_READFILE_EOF -42 /* Hit the end of the file being read! */ #define DAQ_PKT_FLAG_HW_TCP_CS_GOOD 0x1 /* The DAQ module reports that the checksum for this packet is good. */ #define DAQ_PKT_FLAG_OPAQUE_IS_VALID 0x2 /* The DAQ module actively set the opaque value in the DAQ packet header. */ #define DAQ_PKT_FLAG_NOT_FORWARDING 0x4 /* The DAQ module will not be actively forwarding this packet regardless of the verdict (e.g, Passive or Inline Tap interfaces). */ #define DAQ_PKT_FLAG_PRE_ROUTING 0x8 /* The packet is being routed via us but packet modifications (MAC and TTL) have not yet been made. */ #define DAQ_PKT_FLAG_SSL_DETECTED 0x10 /* Packet is ssl client hello */ #define DAQ_PKT_FLAG_SSL_SHELLO 0x20 /* Packet is ssl server hello */ #define DAQ_PKT_FLAG_SSL_SERVER_KEYX 0x40 /* Packet is ssl server keyx */ #define DAQ_PKT_FLAG_SSL_CLIENT_KEYX 0x80 /* Packet is ssl client keyx */ /* The DAQ packet header structure passed to DAQ Analysis Functions. * This should NEVER be modified by user applications. */ #define DAQ_PKTHDR_UNKNOWN -1 /* Ingress or Egress not known */ #define DAQ_PKTHDR_FLOOD -2 /* Egress is flooding */ typedef struct _daq_pkthdr { struct timeval ts; /* Timestamp */ time_t cts; uint32_t caplen; /* Length of the portion present */ uint32_t pktlen; /* Length of this packet (off wire) */ int32_t ingress_index; /* Index of the inbound interface. */ int32_t egress_index; /* Index of the outbound interface. */ int32_t ingress_group; /* Index of the inbound group. */ int32_t egress_group; /* Index of the outbound group. */ uint32_t flags; /* Flags for the packet (DAQ_PKT_FLAG_*) */ uint32_t opaque; /* Opaque context value from the DAQ module or underlying hardware. Directly related to the opaque value in FlowStats. */ void *priv_ptr; /* Private data pointer */ uint32_t flow_id; uint16_t address_space_id; /* Unique ID of the address space */ } DAQ_PktHdr_t; #define DAQ_METAHDR_TYPE_SOF 0 #define DAQ_METAHDR_TYPE_EOF 1 #define DAQ_METAHDR_TYPE_VPN_LOGIN 2 #define DAQ_METAHDR_TYPE_VPN_LOGOUT 3 typedef struct _daq_metahdr { int type; /* Type */ } DAQ_MetaHdr_t; typedef struct _daq_modflow { uint32_t opaque; /* */ } DAQ_ModFlow_t; #define DAQ_FLOWSTATS_IPV4 0 #define DAQ_FLOWSTATS_IPV6 1 typedef struct _flow_stats { int32_t ingressZone; int32_t egressZone; int32_t ingressIntf; int32_t egressIntf; uint8_t initiatorIp[16]; uint8_t responderIp[16]; uint16_t initiatorPort; uint16_t responderPort; uint8_t protocol; uint8_t version; uint64_t initiatorPkts; uint64_t responderPkts; uint64_t initiatorBytes; uint64_t responderBytes; uint32_t opaque; uint16_t vlan_tag; struct timeval sof_timestamp; struct timeval eof_timestamp; uint16_t address_space_id; } Flow_Stats_t, *Flow_Stats_p; typedef enum { NP_IDFW_VPN_SESSION_TYPE_UNKNOWN = 0, NP_IDFW_VPN_SESSION_TYPE_RA_IKEV1 = 1, NP_IDFW_VPN_SESSION_TYPE_RA_IKEV2 = 2, NP_IDFW_VPN_SESSION_TYPE_RA_SSLVPN = 3, NP_IDFW_VPN_SESSION_TYPE_RA_SSLVPN_CLIENTLESS = 4, NP_IDFW_VPN_SESSION_TYPE_LAN2LAN_IKEV1 = 5, NP_IDFW_VPN_SESSION_TYPE_LAN2LAN_IKEV2 = 6, NP_IDFW_VPN_SESSION_TYPE_MAX, } np_idfw_vpn_session_type_t; #define DAQ_VPN_INFO_MAX_USER_NAME_LEN 256 typedef struct _daq_vpn_info { uint8_t ip[16]; uint32_t id; } DAQ_VPN_Info_t, *DAQ_VPN_Info_p; typedef struct _daq_vpn_login_info { DAQ_VPN_Info_t info; uint32_t os; uint32_t type; char user[DAQ_VPN_INFO_MAX_USER_NAME_LEN + 1]; } DAQ_VPN_Login_Info_t, *DAQ_VPN_Login_Info_p; typedef enum { DAQ_VERDICT_PASS, /* Pass the packet. */ DAQ_VERDICT_BLOCK, /* Block the packet. */ DAQ_VERDICT_REPLACE, /* Pass a packet that has been modified in-place. (No resizing allowed!) */ DAQ_VERDICT_WHITELIST, /* Pass the packet and fastpath all future packets in the same flow systemwide. */ DAQ_VERDICT_BLACKLIST, /* Block the packet and block all future packets in the same flow systemwide. */ DAQ_VERDICT_IGNORE, /* Pass the packet and fastpath all future packets in the same flow for this application. */ DAQ_VERDICT_RETRY, /* Hold the packet briefly and resend it to Snort while Snort waits for external response. Drop any new packets received on that flow while holding before sending them to Snort. */ MAX_DAQ_VERDICT } DAQ_Verdict; typedef DAQ_Verdict (*DAQ_Analysis_Func_t)(void *user, const DAQ_PktHdr_t *hdr, const uint8_t *data); typedef int (*DAQ_Meta_Func_t)(void *user, const DAQ_MetaHdr_t *hdr, const uint8_t *data); typedef int (*DAQ_Set_PktCnt_Filter)(void *args); typedef enum __daq_pc_filter_req_type { DAQ_PC_GET_DATA, DAQ_PC_GET_DATA_RTN, DAQ_PC_SET_FILTER, DAQ_PC_SET_FILTER_RTN, DAQ_PC_FILTER_INVALID, DAQ_PC_FILTER_INVALID_RTN }daq_pc_filter_req_type; typedef enum { DAQ_MODE_PASSIVE, DAQ_MODE_INLINE, DAQ_MODE_READ_FILE, MAX_DAQ_MODE } DAQ_Mode; #define DAQ_FILTER_CONFIG_DATA_SIZE 128 typedef struct __DAQ_Filter_Config { uint32_t uOperation; //Operation as defined in module.h uint32_t config_size; char content[DAQ_FILTER_CONFIG_DATA_SIZE]; }DAQ_Filter_Config; #define DAQ_CFG_PROMISC 0x01 #define DAQ_CFG_DAEMON 0x02 #define DAQ_CFG_SYSLOG 0x04 typedef struct _daq_dict_entry DAQ_Dict; typedef struct _daq_config { char *name; /* Name of the interface(s) or file to be opened */ int snaplen; /* Maximum packet capture length */ unsigned timeout; /* Read timeout for acquire loop in milliseconds (0 = unlimited) */ DAQ_Mode mode; /* Module mode (DAQ_MODE_*) */ uint32_t flags; /* Other configuration flags (DAQ_CFG_*) */ DAQ_Dict *values; /* Dictionary of arbitrary key[:value] string pairs. */ char *extra; /* Miscellaneous configuration data to be passed to the DAQ module */ } DAQ_Config_t; typedef enum { DAQ_STATE_UNINITIALIZED, DAQ_STATE_INITIALIZED, DAQ_STATE_STARTED, DAQ_STATE_STOPPED, DAQ_STATE_UNKNOWN, MAX_DAQ_STATE } DAQ_State; typedef struct _daq_stats { uint64_t hw_packets_received; /* Packets received by the hardware */ uint64_t hw_packets_dropped; /* Packets dropped by the hardware */ uint64_t packets_received; /* Packets received by this instance */ uint64_t packets_filtered; /* Packets filtered by this instance's BPF */ uint64_t packets_injected; /* Packets injected by this instance */ uint64_t verdicts[MAX_DAQ_VERDICT]; /* Counters of packets handled per-verdict. */ } DAQ_Stats_t; #define DAQ_DP_TUNNEL_TYPE_NON_TUNNEL 0 #define DAQ_DP_TUNNEL_TYPE_GTP_TUNNEL 1 #define DAQ_DP_TUNNEL_TYPE_OTHER_TUNNEL 2 typedef struct _DAQ_DP_key_t { uint32_t af; /* AF_INET or AF_INET6 */ union { struct in_addr src_ip4; struct in6_addr src_ip6; } sa; union { struct in_addr dst_ip4; struct in6_addr dst_ip6; } da; uint8_t protocol; /* TCP or UDP (IPPROTO_TCP or IPPROTO_UDP )*/ uint16_t src_port; /* TCP/UDP source port */ uint16_t dst_port; /* TCP/UDP destination port */ uint16_t address_space_id; /* Address Space ID */ uint16_t tunnel_type; /* Tunnel type */ uint16_t vlan_id; /* VLAN ID */ uint16_t vlan_cnots; } DAQ_DP_key_t; /* DAQ module type flags */ #define DAQ_TYPE_FILE_CAPABLE 0x01 /* can read from a file */ #define DAQ_TYPE_INTF_CAPABLE 0x02 /* can open live interfaces */ #define DAQ_TYPE_INLINE_CAPABLE 0x04 /* can form an inline bridge */ #define DAQ_TYPE_MULTI_INSTANCE 0x08 /* can be instantiated multiple times */ #define DAQ_TYPE_NO_UNPRIV 0x10 /* can not run unprivileged */ /* DAQ module capability flags */ #define DAQ_CAPA_NONE 0x000 /* no capabilities */ #define DAQ_CAPA_BLOCK 0x001 /* can block packets */ #define DAQ_CAPA_REPLACE 0x002 /* can replace/modify packet data (up to the original data size) */ #define DAQ_CAPA_INJECT 0x004 /* can inject packets */ #define DAQ_CAPA_WHITELIST 0x008 /* can whitelist flows */ #define DAQ_CAPA_BLACKLIST 0x010 /* can blacklist flows */ #define DAQ_CAPA_UNPRIV_START 0x020 /* can call start() without root privileges */ #define DAQ_CAPA_BREAKLOOP 0x040 /* can call breakloop() to break acquisition loop */ #define DAQ_CAPA_BPF 0x080 /* can call set_filter() to establish a BPF */ #define DAQ_CAPA_DEVICE_INDEX 0x100 /* can consistently fill the device_index field in DAQ_PktHdr */ #define DAQ_CAPA_INJECT_RAW 0x200 /* injection of raw packets (no layer-2 headers) */ #define DAQ_CAPA_RETRY 0x400 /* resend packet to Snort after brief delay. */ typedef struct _daq_module DAQ_Module_t; #endif /* _DAQ_COMMON_H */
phyorat/Pktgen-user-payload
examples/daq-2.0.6-dpdk/api/daq_common.h
C
gpl-2.0
12,016
/* * Copyright 2010, Intel Corporation * * This file is part of PowerTOP * * This program file 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; version 2 of the License. * * 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 in a file named COPYING; if not, write to the * Free Software Foundation, Inc, * 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * or just google for it. * * Authors: * Arjan van de Ven <arjan@linux.intel.com> */ #ifndef __INCLUDE_GUARD_REPORT_H_ #define __INCLUDE_GUARD_REPORT_H_ #include <string> #include <stdio.h> using namespace std; struct reportstream { FILE *http_report; FILE *csv_report; char filename[256]; }; void http_header_output(void); extern bool reporttype; extern struct reportstream reportout; extern void init_report_output(char *filename_str); extern void finish_report_output(void); #endif
AllenDou/powertop
src/report.h
C
gpl-2.0
1,278
class Ruby_highline < PACKMAN::Package url PACKMAN.gem_url('highline-1.7.2.gem') sha1 'd7114ed98c5651b928cc7195aded7b0000e09689' version '1.7.2' label :try_system_package_first def install PACKMAN.gem "install highline-#{version}.gem" end def remove PACKMAN.gem 'uninstall -x highline' end def installed? PACKMAN.is_gem_installed? 'highline', version end end
dongli/packman
packages/ruby_highline.rb
Ruby
gpl-2.0
395
spellEffects[ 'FlagFlap' ] = function( args ) { var self = this, _ccd = Component.bugcraft.currentCharacterObject.characterData, _moveFrames = {}, _tc = args.targetCharacter, _tcd = _tc.characterData, _changeFrameFunctionPointer = null, _currentIndex = 1, _maxFrames = 1, _backgroundSound = null; this.ID = spellEffects.layer[0].push( this ) - 1; this.characterSpellEffectID = _tc._internal.spellEffects.push( this ) - 1; this.offsetX = 20; this.offsetY = 20; this.rotation = _tcd.character_rotation; this.deleteRange = 40; this.previousX = _tcd.character_zone_x - this.offsetX; this.previousY = _tcd.character_zone_y - this.offsetY; // initialize var _soundLoop = function() { _backgroundSound = Application.sound.playExclusive({ url: '/components/bugcraft/resources/public/component.bugcraft.spellEffects/sounds/FlagFlap/FlagFlap.mp3', volume: spellEffects.volumeByRangeVoice( _ccd.character_zone_x, _ccd.character_zone_y, _tcd.character_zone_x, _tcd.character_zone_y, spellEffects.volumeRangeLong ), onFinish: function() { _soundLoop(); } }); } // for(var i=1;i<=_maxFrames;i++) // { // _moveFrames[ i ] = { image: new Image(), alpha: 0 }; // _moveFrames[ i ].image.src = '/components/bugcraft/resources/public/component.bugcraft.spellEffects/images/FlagFlap/FlagFlap' + i + '.png'; // } //draw the bombardierBeetleDeath spatter this.draw = function() { // Map.ctx.save(); // Map.ctx.translate( self.previousX + self.offsetX + Map.viewPortX, self.previousY + self.offsetY + Map.viewPortY ); // Map.ctx.rotate( ( self.rotation - 90 ) * Math.PI / 180 ); // Map.ctx.shadowColor = 'rgba(0, 0, 0, 0.7)'; // Map.ctx.shadowOffsetX = 3; // Map.ctx.shadowOffsetY = 3; // Map.ctx.drawImage( // _moveFrames[ _currentIndex ].image, // - self.offsetX, // - self.offsetY // ); // Map.ctx.restore(); // Map.ctx.globalAlpha = 1; } //remove the deathDecay this.remove = function() { clearTimeout( _changeFrameFunctionPointer ); if( _backgroundSound ) { _backgroundSound.stop(); } spellEffects.layerCleaner.push( this ); spellEffects.layer[0][ this.ID ] = null; delete _tc._internal.spellEffects[ this.characterSpellEffectID ]; } var _changeFrameFunction = function() { _currentIndex++; if( _currentIndex > _maxFrames ) { _currentIndex = 1; setTimeout( _changeFrameFunction, 2000 + Math.random() * 5000 ); return; } _changeFrameFunctionPointer = setTimeout( _changeFrameFunction, 100 ); } _soundLoop(); // _changeFrameFunction(); } //end bombardierBeetleDeath
victoralex/gameleon
public_web/components/bugcraft/resources/public/component.bugcraft.spellEffects/class.spellEffects.FlagFlap.js
JavaScript
gpl-2.0
3,039
/* ** Copyright (C) 1997, Peter McCluskey (pcm@rahul.net) ** ** This program and library is free software; you can redistribute it and/or ** modify it under the terms of the GNU (Library) General Public License ** as published by the Free Software Foundation; either version 2 ** of the License, or 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 (Library) General Public License for more details. ** ** You should have received a copy of the GNU (Library) General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #include "hypermail.h" #include "finelink.h" #include "print.h" #include "struct.h" #include "search.h" #include "setup.h" #include "proto.h" #include <string.h> #include <ctype.h> static int str_similar_str(const char *str1, const char *str2); static char *stripwhitespace(const char *line); static int new_reply_to = -1; static int found_quote = 0; static char *get_path(struct emailinfo *ep, struct emailinfo *ep2) { char *path = ""; if (ep2->subdir && ep2->subdir != ep->subdir) trio_asprintf(&path, "%s%s", ep2->subdir->rel_path_to_top, ep2->subdir->subdir); return path; } static struct body *place_anchor(const String_Match * match_info, struct body *bp, char *buffer, FILE *fp2, char **ptr, const char *anchor) { if (match_info) { int index; char token[MAXLINE]; char *tptr; char *ptr1 = buffer; char *last_ptr0 = *ptr; char *penultimate_ptr0 = last_ptr0; char *last_ptr = ptr1; char *penultimate_ptr = ptr1; if (!bp) return FALSE; while ((bp = tokenize_body(bp, token, ptr, &index, TRUE)) != NULL) { if (*ptr == match_info->start_match) { strcpy(token, last_ptr); *last_ptr = 0; fprintf(fp2, "%s<a name=\"%s\">", buffer, anchor); strcpy(buffer, token); *ptr = last_ptr0; return bp; } penultimate_ptr = ptr1; last_ptr = penultimate_ptr; last_ptr0 = penultimate_ptr0; penultimate_ptr0 = *ptr; if (!(tptr = strstr(ptr1, *ptr))) { int len = (4 * strlen(*ptr)) / 5; char *temp1 = (char *)emalloc(len + 1); strncpy(temp1, *ptr, len); temp1[len] = 0; tptr = strstr(ptr1, temp1); free(temp1); if (!tptr) break; } ptr1 = tptr; while (ispunct(*ptr1) && *ptr1 != '<') ++ptr1; } if (0) printf("No match found %s; %s", anchor, buffer); } fprintf(fp2, "<a name=\"%s\">", anchor); return bp; } static int place_a_end(const String_Match * match_info, struct body **bp, char *buffer, FILE *fp2, char **ptr) { int index; char token[MAXLINE]; char *ptr1 = buffer; char *last_ptr = ptr1; char *tptr; if (!*bp) return FALSE; while ((*bp = tokenize_body(*bp, token, ptr, &index, TRUE)) != NULL) { if (*ptr == match_info->stop_match) { strcpy(token, ptr1); *ptr1 = 0; fprintf(fp2, "%s</a>%s", buffer, token); return TRUE; } last_ptr = ptr1; if (!(tptr = strstr(ptr1, *ptr))) { int len = (4 * strlen(*ptr)) / 5; char *temp1 = (char *)emalloc(len + 1); strncpy(temp1, *ptr, len); temp1[len] = 0; tptr = strstr(ptr1, temp1); free(temp1); if (!tptr) return FALSE; } ptr1 = tptr; while (ispunct(*ptr1) && *ptr1 != '<') ++ptr1; } return FALSE; } /* ** Alter the message being quoted to add an anchor specifying the quoted text */ static int add_anchor(int msgnum, int quoting_msgnum, int quote_num, const char *anchor, char *line, int find_substr, int count_quoted_lines, const String_Match * match_info) { char *filename; char *tmpfilename; char buffer[MAXLINE]; FILE *fp1, *fp2; int matches = 0; int in_body = FALSE; int cmp_len = strlen(line); struct emailinfo *ep; struct body *bp = hashnumlookup(msgnum, &ep); char *ptr; char *tmpptr; while (bp && (!strncmp(bp->line, "Date:", 5) || !strncmp(bp->line, "From:", 5) || !strncmp(bp->line, "From:", 5) || !strncasecmp(bp->line, "Message-Id:", 11) || !strncmp(bp->line, "Subject:", 8) || !strncasecmp(bp->line, "In-Reply-To:", 12) || !strncasecmp(bp->line, "References:", 11) || !strncmp(bp->line, "To:", 3))) bp = bp->next; /* skip over header info */ ptr = bp ? bp->line : NULL; while (ptr && !*ptr) { bp = bp->next; if (!bp) break; ptr = bp->line; } filename = articlehtmlfilename(ep); if ((fp1 = fopen(filename, "r")) == NULL) { free(filename); if (msgnum > quoting_msgnum) return 0; /* just a forward ref */ if (set_showprogress) fprintf(stderr, "Couldn't read message number %d (linked from %d). " "May mean message deleted with delete_level = 0.\n", msgnum, quoting_msgnum); return -1; } tmpfilename = htmlfilename("tmp", ep, "tmp"); /* AUDIT biege: where is the tmp-file created? cwd? what about checking the return-value */ if ((fp2 = fopen(tmpfilename, "w")) == NULL) { snprintf(errmsg, sizeof(errmsg), "Couldn't write \"%s\".", tmpfilename); progerr(errmsg); } while (fgets(buffer, sizeof(buffer), fp1)) { if ((find_substr && str_similar_str(buffer, line)) || (!find_substr && !strncmp(buffer, line, cmp_len))) { int wrote_a_end = FALSE; ++matches; bp = place_anchor(match_info, bp, buffer, fp2, &ptr, anchor); if (set_link_to_replies) { struct emailinfo *ep2; if (hashnumlookup(quoting_msgnum, &ep2)) { char *path = get_path(ep, ep2); fprintf(fp2, "<a href=\"%s%.4d.%s#qlink%d\">%s</a>", path, quoting_msgnum, set_htmlsuffix, quote_num, set_link_to_replies); if (*path) free(path); } } /* Now find end of quoted text: */ do { if (!strcmp(buffer, "<!-- body=\"end\" -->\n")) { count_quoted_lines = -1; break; /* reply quoted more lines than exist? */ } if (match_info && place_a_end(match_info, &bp, buffer, fp2, &ptr)) { wrote_a_end = TRUE; count_quoted_lines = 0; if (bp) bp = bp->next; if (bp) ptr = bp->line; break; } fputs(buffer, fp2); /* suppress decrement for lines inserted by html conversion: */ if (!strcasecmp(buffer, "<p>\n")) ++count_quoted_lines; else { char *tptr = remove_hypermail_tags(buffer); if (tptr) free(tptr); else ++count_quoted_lines; } } while (--count_quoted_lines > 0 && fgets(buffer, sizeof(buffer), fp1)); if (!wrote_a_end) fputs("</a>", fp2); if (count_quoted_lines > 0) /* got eof? */ break; /* avoid last fputs */ else if (count_quoted_lines == 0 && !fgets(buffer, sizeof(buffer), fp1)) break; } else if (in_body && bp && (tmpptr = remove_hypermail_tags(buffer))) { char *tmpptr2 = unconvchars(tmpptr); if (tmpptr2 && str_similar_str(tmpptr, bp->line)) bp = bp->next; if (bp) ptr = bp->line; if (tmpptr2) free(tmpptr2); free(tmpptr); } else if (!in_body && !strcmp(buffer, "<!-- body=\"start\" -->\n")) in_body = TRUE; fputs(buffer, fp2); } fclose(fp1); fclose(fp2); if (matches != 1) remove(tmpfilename); else { if (rename(tmpfilename, filename) == -1) { snprintf(errmsg, sizeof(errmsg), "Couldn't rename \"%s\" to %s.", tmpfilename, filename); progerr(errmsg); } if (chmod(filename, set_filemode) == -1) { snprintf(errmsg, sizeof(errmsg), "Couldn't chmod \"%s\" to %o.", filename, set_filemode); progerr(errmsg); } } free(filename); free(tmpfilename); return matches == 1; } static char *unquote_and_strip(char *line) { char *p = unquote(line); char *p2; char *cvtd_line; while (*p && isspace(*p)) ++p; cvtd_line = (char *)emalloc(strlen(p) + 1); strcpy(cvtd_line, p); p2 = cvtd_line + strlen(cvtd_line); if (p2 > cvtd_line && p2[-1] == '\n') *--p2 = 0; if (p2 > cvtd_line && *--p2 == '-') *p2 = 0; /* don't demand trailing '-' in searches; may have been unhyphenated */ return cvtd_line; } /* ** Find URL of the message this line of quoted text was taken from */ static char *url_replying_to(struct emailinfo *email, char *line1, /* first line of quoted text, with html */ const char *line2, /* first line of quoted text, w/o html */ const struct body *bp, int quote_num, int *quoting_msgnum, int count_quoted_lines, int maybe_reply) { String_Match match_info; char *p; int subjmatch = 0; char *anchor; struct emailinfo *ep; int statusnum = hashreplynumlookup(*quoting_msgnum, email->inreplyto, email->subject, &subjmatch); hashnumlookup(*quoting_msgnum, &ep); trio_asprintf(&anchor, "%.4dqlink%d", *quoting_msgnum, quote_num); if (statusnum != -1) { struct emailinfo *ep2; hashnumlookup(statusnum, &ep2); if (add_anchor(statusnum, *quoting_msgnum, quote_num, anchor, line1, 0, count_quoted_lines, NULL)) { char *path = get_path(ep, ep2); char *buf; trio_asprintf(&buf, "%s%.4d.%s#%s", path, statusnum, set_htmlsuffix, anchor); if (maybe_reply) set_new_reply_to(statusnum, strlen(line2)); if (*path) free(path); free(anchor); return buf; } if (strlen(line2) > 6 && (p = strstr(line2, "..."))) { char *parsed; char *tptr = (char *)emalloc(p - line2 + 1 + strlen(p + 3)); /* AUDIT biege: IOF unlikely */ strncpy(tptr, line2, p - line2); strcpy(tptr + (p - line2), p + 3); parsed = ConvURLsString(tptr, email->msgid, email->subject, email->charset); free(tptr); tptr = stripwhitespace(parsed ? parsed : ""); if (parsed) free(parsed); if (add_anchor(statusnum, *quoting_msgnum, quote_num, anchor, tptr, 1, count_quoted_lines, NULL)) { char *path = get_path(ep, ep2); char *buf; trio_asprintf(&buf, "%s%.4d.%s#%s", path, statusnum, set_htmlsuffix, anchor); free(tptr); if (maybe_reply) set_new_reply_to(statusnum, strlen(buf)); if (*path) free(path); free(anchor); return buf; } free(tptr); } } { int i; struct Push full_line; struct Push exact_line; INIT_PUSH(full_line); INIT_PUSH(exact_line); PushString(&full_line, p = stripwhitespace(line2)); free(p); PushString(&exact_line, line2); for (i = 1; i < count_quoted_lines && (bp = bp->next); ++i) { char *stripped = unquote_and_strip(bp->line); PushByte(&full_line, '\n'); PushString(&full_line, p = stripwhitespace(stripped)); free(p); free(stripped); PushString(&exact_line, unquote(bp->line)); } search_for_quote(PUSH_STRING(full_line), PUSH_STRING(exact_line), *quoting_msgnum, &match_info); free(PUSH_STRING(full_line)); free(PUSH_STRING(exact_line)); } if (match_info.msgnum >= 0) { char *parsed = ConvURLsString(match_info.last_matched_string, email->msgid, email->subject, email->charset); if (parsed) { char *parsed2 = stripwhitespace(parsed); free(parsed); if (add_anchor(match_info.msgnum, *quoting_msgnum, quote_num, anchor, parsed2, 1, count_quoted_lines, &match_info)) { struct emailinfo *ep2; char *path; char *buf; hashnumlookup(match_info.msgnum, &ep2); path = get_path(ep, ep2); trio_asprintf(&buf, "%s%.4d.%s#%s", path, match_info.msgnum, set_htmlsuffix, anchor); set_new_reply_to(match_info.msgnum, match_info.match_len_bytes); free(parsed2); if (*path) free(path); free(anchor); return buf; } free(parsed2); } if (match_info.last_matched_string) free(match_info.last_matched_string); } if (count_quoted_lines < 3 && strcmp(get_quote_prefix(), ">") && strcmp(get_quote_prefix(), " >")) /* was quote_prefix guess shaky? */ *quoting_msgnum = -1; /* msg probably doesn't have any quotes */ free(anchor); return NULL; } /* ** handles everything we do for a single line that is a quote ** of another message */ int handle_quoted_text(FILE *fp, struct emailinfo *email, const struct body *bp, char *line, int inquote, int quote_num, bool replace_quoted, int maybe_reply) { char *url1; int quoting_msgnum = email->msgnum; const struct body *last_quoted_line = bp; int count_quoted_lines = 0; char *fmt2; char *cvtd_line = ConvURLsString(unquote(line), email->msgid, email->subject, email->charset); char *buffer1; trio_asprintf(&fmt2, set_iquotes ? "<em class=\"%s\">%%s</em><br>" : "<span class=\"%s\">%%s</span><br>", find_quote_class(line)); trio_asprintf(&buffer1, fmt2, cvtd_line ? cvtd_line : ""); if (cvtd_line) free(cvtd_line); found_quote = (quote_num > 0); while (last_quoted_line && isquote(last_quoted_line->line)) { ++count_quoted_lines; last_quoted_line = last_quoted_line->next; } cvtd_line = unquote_and_strip(line); if (strlen(cvtd_line) < 5 && (!replace_quoted || !inquote)) { char *parsed = ConvURLsString(line, email->msgid, email->subject, email->charset); if (parsed) { fprintf(fp, fmt2, parsed); free(parsed); } } else if ((!inquote || !found_quote) && (url1 = url_replying_to(email, buffer1, cvtd_line, bp, ++quote_num, &quoting_msgnum, count_quoted_lines, maybe_reply))) { static const char *fmt1 = "<a href=\"%s\">%s</a>%s<br>\n"; char *tmpline; char *p2; bool replacing = replace_quoted && set_quote_link_string && set_quote_link_string[0]; char *part2 = strcasestr(line, "<a href="); if (!part2) { part2 = ""; tmpline = strsav(line); } else { tmpline = (char *)emalloc(part2 - line + 1); strncpy(tmpline, line, part2 - line); tmpline[part2 - line] = 0; } if (set_link_to_replies) fprintf(fp, "<a name=\"qlink%d\"></a>", quote_num); p2 = ConvURLsString(part2, email->msgid, email->subject, email->charset); if (replacing) fprintf(fp, fmt1, url1, set_quote_link_string, p2 ? p2 : ""); else { char *tmpptr = convchars(tmpline, email->charset); if (tmpptr) { fprintf(fp, fmt1, url1, tmpptr, p2 ? p2 : ""); free(tmpptr); } } free(url1); free(tmpline); if (p2) free(p2); free(cvtd_line); free(buffer1); free(fmt2); return 1; } else if (!replace_quoted || !inquote) { char *parsed = ConvURLsString(bp->line, email->msgid, email->subject, email->charset); if (parsed) { fprintf(fp, quoting_msgnum >= 0 ? fmt2 : "%s<br>\n", parsed); free(parsed); } } free(cvtd_line); free(buffer1); free(fmt2); return 0; } /* ** Update guess about which message the current message is replying to; ** do nothing if set_new_reply_to has been called more for another msgnum since ** starting this message or if another msgnum had longer match_len. */ void set_new_reply_to(int msgnum, int match_len) { static int alt_msgnum = -1; static int count_alt = 0; static int count_last = 0; static int best_match_len = -1; if (new_reply_to == -1 || msgnum == -1) { new_reply_to = msgnum; count_last = 1; count_alt = 0; alt_msgnum = -1; best_match_len = match_len; } else if (msgnum == new_reply_to) { ++count_last; } else { if (msgnum == alt_msgnum || alt_msgnum == -1) { if (++count_alt > count_last || (count_alt == count_last && match_len > best_match_len)) { count_last = count_alt; new_reply_to = msgnum; if (match_len > best_match_len) best_match_len = match_len; } } else count_alt = 0; alt_msgnum = msgnum; } } int get_new_reply_to() { return new_reply_to; } /* * Update a message to change "maybe in reply to"'s to a single definite * "In reply to" */ void replace_maybe_replies(const char *filename, struct emailinfo *ep, int new_reply_to) { char tmpfilename[MAXFILELEN]; char buffer[MAXLINE]; FILE *fp1, *fp2; struct emailinfo *ep2; int in_body = 0; char *ptr; static const char *prev_patt0 = ".html\">[ Previous ]</a>"; if (!hashnumlookup(new_reply_to, &ep2)) return; snprintf(tmpfilename, sizeof(tmpfilename), "%s/aaaa.tmp", set_dir); /* AUDIT biege: poss. BOF. */ if ((fp1 = fopen(filename, "r")) == NULL) { snprintf(errmsg, sizeof(errmsg), "Couldn't read \"%s\".", filename); progerr(errmsg); } if ((fp2 = fopen(tmpfilename, "w")) == NULL) { snprintf(errmsg, sizeof(errmsg), "Couldn't write \"%s\".", tmpfilename); progerr(errmsg); } while (fgets(buffer, sizeof(buffer), fp1)) { if (strstr(buffer, "<!-- body=\"end\" -->\n")) in_body = 0; if (!strcmp(buffer, "<!-- body=\"start\" -->\n")) in_body = 1; if (!in_body) { if (!strcmp(buffer, "<!-- unextthread=\"start\" -->\n")) { char *tmpptr = convchars(ep2->subject, ep2->charset); if (tmpptr) { char *path = get_path(ep, ep2); fprintf(fp2,"[ <a href=\"%s%.4d.%s\" title=\"%s: &quot;%s&quot;\">%s</a> ]\n", path, new_reply_to, set_htmlsuffix, lang[MSG_LTITLE_IN_REPLY_TO], ep2->name, tmpptr ? tmpptr : ""); free(tmpptr); } } else if (!strcmp(buffer, "<!-- lnextthread=\"start\" -->\n")) { char *tmpptr = convchars(ep2->subject, ep2->charset); if (tmpptr) { char *path = get_path(ep, ep2); fprintf(fp2, "<li><dfn>%s</dfn> " "<a href=\"%s%.4d.%s\" title=\"%s\">%s: \"%s\"</a></li>\n", lang[MSG_IN_REPLY_TO], path, new_reply_to, set_htmlsuffix, lang[MSG_LTITLE_IN_REPLY_TO], ep2->name, tmpptr ? tmpptr : ""); free(tmpptr); } } else if (!strcmp(buffer, "<!-- nextthread=\"start\" -->\n")) { char *tmpptr = convchars(ep2->subject, ep2->charset); if (tmpptr) { char *path = get_path(ep, ep2); fprintf(fp2, "<li> <strong>%s:</strong> " "<a href=\"%s%.4d.%s\">%s: \"%s\"</a>\n", lang[MSG_IN_REPLY_TO], path, new_reply_to, set_htmlsuffix, ep2->name, tmpptr ? tmpptr : ""); free(tmpptr); } } else { static const char *patts[] = { "<b>Maybe in reply to:</b>", "<strong>%s:</strong>", "<b>In reply to:</b>", "<strong>%s:</strong>", "<li> <b>Previous message:</b> <a href=\"", "<li> <strong>%s:</strong> <a href=\"", "<li><dfn>%s</dfn>: <a href=\"", "<li><dfn>%s</dfn>: <a href=\"", "<li><dfn>%s</dfn>: <a href=\"", NULL }; static const int indices[] = { MSG_MAYBE_IN_REPLY_TO, MSG_MAYBE_IN_REPLY_TO, MSG_IN_REPLY_TO, MSG_IN_REPLY_TO, MSG_PREVIOUS_MESSAGE, MSG_PREVIOUS_MESSAGE, MSG_MAYBE_IN_REPLY_TO, MSG_IN_REPLY_TO, MSG_PREVIOUS_MESSAGE }; int i; int suppress = 0; for (i = 0; patts[i]; ++i) { char temp[256]; snprintf(temp,sizeof(temp), patts[i], lang[indices[i]]); if ((ptr = strcasestr(buffer, temp)) && (i < 4 || new_reply_to == atoi(ptr + strlen(temp)))) { suppress = 1; break; } } if (suppress) continue; } /* check for old critmail format */ if ((ptr = strstr(buffer, prev_patt0)) && new_reply_to == atoi(ptr - 4) && !strncasecmp(ptr - 13, "<a href", 7)) { ptr[-13] = 0; } } fputs(buffer, fp2); } fclose(fp1); fclose(fp2); if (rename(tmpfilename, filename) == -1) { snprintf(errmsg, sizeof(errmsg), "Couldn't rename \"%s\" to %s.", tmpfilename, filename); progerr(errmsg); } } /* * a fuzzy version of strstr() */ static int str_similar_str(const char *str1, const char *str2) { int len; char *s; char *temp1; if (strstr(str1, str2)) return TRUE; len = strlen(str2); if (strstr(str1, str2 + len / 5)) return TRUE; len = (4 * len) / 5; temp1 = (char *)emalloc(len + 1); strncpy(temp1, str2, len); temp1[len] = 0; s = strstr(str1, temp1); free(temp1); if (s) return TRUE; return FALSE; } /* ** remove whitespace from begin and end of a string */ static char *stripwhitespace(const char *line) { char *buffer = (char *)emalloc(strlen(line) + 1); int i = 0; while (*line && isspace(*line)) ++line; while (*line) buffer[i++] = *line++; buffer[i] = 0; while (i >= 0 && isspace(buffer[--i])) buffer[i] = '\0'; return buffer; }
hypermail-project/hypermail
src/finelink.c
C
gpl-2.0
20,260
/* Copyright (c) 2008 Volker Krause <vkrause@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "entitydisplayattribute.h" #include "imapparser_p.h" #include <KIcon> using namespace Akonadi; class EntityDisplayAttribute::Private { public: Private() : hidden(false) { } QString name; QString icon; QString activeIcon; QColor backgroundColor; bool hidden; }; EntityDisplayAttribute::EntityDisplayAttribute() : d(new Private) { } EntityDisplayAttribute::~ EntityDisplayAttribute() { delete d; } QString EntityDisplayAttribute::displayName() const { return d->name; } void EntityDisplayAttribute::setDisplayName(const QString &name) { d->name = name; } KIcon EntityDisplayAttribute::icon() const { return KIcon(d->icon); } QString EntityDisplayAttribute::iconName() const { return d->icon; } void EntityDisplayAttribute::setIconName(const QString &icon) { d->icon = icon; } QByteArray Akonadi::EntityDisplayAttribute::type() const { return "ENTITYDISPLAY"; } EntityDisplayAttribute *EntityDisplayAttribute::clone() const { EntityDisplayAttribute *attr = new EntityDisplayAttribute(); attr->d->name = d->name; attr->d->icon = d->icon; attr->d->activeIcon = d->activeIcon; attr->d->backgroundColor = d->backgroundColor; return attr; } QByteArray EntityDisplayAttribute::serialized() const { QList<QByteArray> l; l << ImapParser::quote(d->name.toUtf8()); l << ImapParser::quote(d->icon.toUtf8()); l << ImapParser::quote(d->activeIcon.toUtf8()); QList<QByteArray> components; if (d->backgroundColor.isValid()) { components = QList<QByteArray>() << QByteArray::number(d->backgroundColor.red()) << QByteArray::number(d->backgroundColor.green()) << QByteArray::number(d->backgroundColor.blue()) << QByteArray::number(d->backgroundColor.alpha()); } l << '(' + ImapParser::join(components, " ") + ')'; return '(' + ImapParser::join(l, " ") + ')'; } void EntityDisplayAttribute::deserialize(const QByteArray &data) { QList<QByteArray> l; ImapParser::parseParenthesizedList(data, l); int size = l.size(); Q_ASSERT(size >= 2); d->name = QString::fromUtf8(l[0]); d->icon = QString::fromUtf8(l[1]); if (size >= 3) { d->activeIcon = QString::fromUtf8(l[2]); } if (size >= 4) { if (!l[3].isEmpty()) { QList<QByteArray> componentData; ImapParser::parseParenthesizedList(l[3], componentData); if (componentData.size() != 4) { return; } QList<int> components; bool ok; for (int i = 0; i <= 3; ++i) { components << componentData.at(i).toInt(&ok); if (!ok) { return; } } d->backgroundColor = QColor(components.at(0), components.at(1), components.at(2), components.at(3)); } } } void EntityDisplayAttribute::setActiveIconName(const QString &name) { d->activeIcon = name; } KIcon EntityDisplayAttribute::activeIcon() const { return KIcon(d->activeIcon); } QString EntityDisplayAttribute::activeIconName() const { return d->activeIcon; } QColor EntityDisplayAttribute::backgroundColor() const { return d->backgroundColor; } void EntityDisplayAttribute::setBackgroundColor(const QColor &color) { d->backgroundColor = color; }
kolab-groupware/kdepimlibs
akonadi/entitydisplayattribute.cpp
C++
gpl-2.0
4,253
/* * Turbo Sliders++ * Copyright (C) 2013-2014 Martin Newhouse * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #ifndef GUI_INPUT_INTERFACE_HPP #define GUI_INPUT_INTERFACE_HPP #include <SFML/Window.hpp> #include "mouse.hpp" namespace ts { namespace gui { struct Key_modifiers { static const unsigned int None = 0; static const unsigned int Shift = 1; static const unsigned int Ctrl = 2; static const unsigned int Alt = 4; }; struct SFML_Input_interface { public: void handle_event(const sf::Event& event); protected: ~SFML_Input_interface() = default; private: virtual void process_mouse_move(Vector2i new_position, unsigned int key_modifiers) = 0; virtual void process_mouse_button_down(mouse::Button button, unsigned int key_modifiers) = 0; virtual void process_mouse_button_up(mouse::Button button, unsigned int key_modifiers) = 0; virtual void process_mouse_wheel(int wheel_delta, unsigned int key_modifiers) = 0; virtual void process_key_up(sf::Keyboard::Key key_code, unsigned int key_modifiers) = 0; virtual void process_key_down(sf::Keyboard::Key key_code, unsigned int key_modifiers) = 0; virtual void process_text_input(utf8::uint32_t code_point) = 0; }; } } #endif
mnewhouse/tspp
src/user_interface/input_interface.hpp
C++
gpl-2.0
2,178
#!/usr/bin/perl use strict; use warnings; use CGI; use C4::Auth; use C4::Serials; use C4::Acquisition; use C4::Output; use C4::Bookseller; use C4::Context; use C4::Letters; my $input = new CGI; my $serialid = $input->param('serialid'); my $op = $input->param('op'); my $claimletter = $input->param('claimletter'); my $supplierid = $input->param('supplierid'); my $order = $input->param('order'); my %supplierlist = GetSuppliersWithLateIssues; my @select_supplier; # open template first (security & userenv set here) my ($template, $loggedinuser, $cookie) = get_template_and_user({template_name => "serials/claims.tmpl", query => $input, type => "intranet", authnotrequired => 0, flagsrequired => {serials => 1}, debug => 1, }); foreach my $supplierid (sort {$supplierlist{$a} cmp $supplierlist{$b} } keys %supplierlist){ my ($count, @dummy) = GetLateOrMissingIssues($supplierid,"",$order); my $counting = $count; $supplierlist{$supplierid} = $supplierlist{$supplierid}." ($counting)"; push @select_supplier, $supplierid } my $letters = GetLetters("claimissues"); my @letters; foreach (keys %$letters){ push @letters ,{code=>$_,name=> $letters->{$_}}; } my $letter=((scalar(@letters)>1) || ($letters[0]->{name}||$letters[0]->{code})); my ($count2, @missingissues); if ($supplierid) { ($count2, @missingissues) = GetLateOrMissingIssues($supplierid,$serialid,$order); } my $CGIsupplier=CGI::scrolling_list( -name => 'supplierid', -id => 'supplierid', -values => \@select_supplier, -default => $supplierid, -labels => \%supplierlist, -size => 1, -multiple => 0 ); my ($singlesupplier,@supplierinfo); if($supplierid){ (@supplierinfo)=GetBookSeller($supplierid); } else { # set up supplierid for the claim links out of main table if all suppliers is chosen for my $mi (@missingissues){ $mi->{supplierid} = getsupplierbyserialid($mi->{serialid}); } } my $preview=0; if($op && $op eq 'preview'){ $preview = 1; } else { my @serialnums=$input->param('serialid'); if (@serialnums) { # i.e. they have been flagged to generate claims SendAlerts('claimissues',\@serialnums,$input->param("letter_code")); my $cntupdate=UpdateClaimdateIssues(\@serialnums); ### $cntupdate SHOULD be equal to scalar(@$serialnums) TODO so what do we do about it?? } } $template->param('letters'=>\@letters,'letter'=>$letter); $template->param( order =>$order, CGIsupplier => $CGIsupplier, phone => $supplierinfo[0]->{phone}, booksellerfax => $supplierinfo[0]->{booksellerfax}, bookselleremail => $supplierinfo[0]->{bookselleremail}, preview => $preview, missingissues => \@missingissues, supplierid => $supplierid, claimletter => $claimletter, singlesupplier => $singlesupplier, supplierloop => \@supplierinfo, dateformat => C4::Context->preference("dateformat"), ); output_html_with_http_headers $input, $cookie, $template->output;
buitenzorg812/Koha-PTFS
serials/claims.pl
Perl
gpl-2.0
3,116
<HTML><HEAD><TITLE>Xilinx System Settings Report</TITLE></HEAD> <BODY TEXT='#000000' BGCOLOR='#FFFFFF' LINK='#0000EE' VLINK='#551A8B' ALINK='#FF0000'> <center><big><big><b>System Settings</b></big></big></center><br> <A NAME="Environment Settings"></A> &nbsp;<BR><TABLE BORDER CELLSPACING=0 CELLPADDING=3 WIDTH='100%'> <TR ALIGN=CENTER BGCOLOR='#99CCFF'> <TD ALIGN=CENTER COLSPAN='5'><B> Environment Settings </B></TD> </tr> <tr bgcolor='#ffff99'> <td><b>Environment Variable</b></td> <td><b>xst</b></td> <td><b>ngdbuild</b></td> <td><b>map</b></td> <td><b>par</b></td> </tr> <tr> <td>LD_LIBRARY_PATH</td> <td>/opt/Xilinx/14.7/ISE_DS/ISE//lib/lin64:<br>/opt/Xilinx/14.7/ISE_DS/ISE/lib/lin64:<br>/opt/Xilinx/14.7/ISE_DS/ISE/smartmodel/lin64/installed_lin64/lib:<br>/opt/Xilinx/14.7/ISE_DS/ISE/sysgen/lib:<br>/opt/Xilinx/14.7/ISE_DS/EDK/lib/lin64:<br>/opt/Xilinx/14.7/ISE_DS/common/lib/lin64</td> <td>/opt/Xilinx/14.7/ISE_DS/ISE//lib/lin64:<br>/opt/Xilinx/14.7/ISE_DS/ISE/lib/lin64:<br>/opt/Xilinx/14.7/ISE_DS/ISE/smartmodel/lin64/installed_lin64/lib:<br>/opt/Xilinx/14.7/ISE_DS/ISE/sysgen/lib:<br>/opt/Xilinx/14.7/ISE_DS/EDK/lib/lin64:<br>/opt/Xilinx/14.7/ISE_DS/common/lib/lin64</td> <td><font color=gray>&lt;&nbsp;data not available&nbsp;&gt;</font></td> <td><font color=gray>&lt;&nbsp;data not available&nbsp;&gt;</font></td> </tr> <tr> <td>LMC_HOME</td> <td>/opt/Xilinx/14.7/ISE_DS/ISE/smartmodel/lin64/installed_lin64</td> <td>/opt/Xilinx/14.7/ISE_DS/ISE/smartmodel/lin64/installed_lin64</td> <td><font color=gray>&lt;&nbsp;data not available&nbsp;&gt;</font></td> <td><font color=gray>&lt;&nbsp;data not available&nbsp;&gt;</font></td> </tr> <tr> <td>PATH</td> <td>/opt/Xilinx/14.7/ISE_DS/ISE//bin/lin64:<br>/opt/Xilinx/14.7/ISE_DS/ISE/bin/lin64:<br>/opt/Xilinx/14.7/ISE_DS/ISE/sysgen/util:<br>/opt/Xilinx/14.7/ISE_DS/ISE/sysgen/bin:<br>/opt/Xilinx/14.7/ISE_DS/ISE/../../../DocNav:<br>/opt/Xilinx/14.7/ISE_DS/PlanAhead/bin:<br>/opt/Xilinx/14.7/ISE_DS/EDK/bin/lin64:<br>/opt/Xilinx/14.7/ISE_DS/EDK/gnu/microblaze/lin/bin:<br>/opt/Xilinx/14.7/ISE_DS/EDK/gnu/powerpc-eabi/lin/bin:<br>/opt/Xilinx/14.7/ISE_DS/EDK/gnu/arm/lin/bin:<br>/opt/Xilinx/14.7/ISE_DS/EDK/gnu/microblaze/linux_toolchain/lin64_be/bin:<br>/opt/Xilinx/14.7/ISE_DS/EDK/gnu/microblaze/linux_toolchain/lin64_le/bin:<br>/opt/Xilinx/14.7/ISE_DS/common/bin/lin64:<br>/usr/local/sbin:<br>/usr/local/bin:<br>/usr/sbin:<br>/usr/bin:<br>/sbin:<br>/bin:<br>/usr/games:<br>/usr/local/games</td> <td>/opt/Xilinx/14.7/ISE_DS/ISE//bin/lin64:<br>/opt/Xilinx/14.7/ISE_DS/ISE/bin/lin64:<br>/opt/Xilinx/14.7/ISE_DS/ISE/sysgen/util:<br>/opt/Xilinx/14.7/ISE_DS/ISE/sysgen/bin:<br>/opt/Xilinx/14.7/ISE_DS/ISE/../../../DocNav:<br>/opt/Xilinx/14.7/ISE_DS/PlanAhead/bin:<br>/opt/Xilinx/14.7/ISE_DS/EDK/bin/lin64:<br>/opt/Xilinx/14.7/ISE_DS/EDK/gnu/microblaze/lin/bin:<br>/opt/Xilinx/14.7/ISE_DS/EDK/gnu/powerpc-eabi/lin/bin:<br>/opt/Xilinx/14.7/ISE_DS/EDK/gnu/arm/lin/bin:<br>/opt/Xilinx/14.7/ISE_DS/EDK/gnu/microblaze/linux_toolchain/lin64_be/bin:<br>/opt/Xilinx/14.7/ISE_DS/EDK/gnu/microblaze/linux_toolchain/lin64_le/bin:<br>/opt/Xilinx/14.7/ISE_DS/common/bin/lin64:<br>/usr/local/sbin:<br>/usr/local/bin:<br>/usr/sbin:<br>/usr/bin:<br>/sbin:<br>/bin:<br>/usr/games:<br>/usr/local/games</td> <td><font color=gray>&lt;&nbsp;data not available&nbsp;&gt;</font></td> <td><font color=gray>&lt;&nbsp;data not available&nbsp;&gt;</font></td> </tr> <tr> <td>XILINX</td> <td>/opt/Xilinx/14.7/ISE_DS/ISE/</td> <td>/opt/Xilinx/14.7/ISE_DS/ISE/</td> <td><font color=gray>&lt;&nbsp;data not available&nbsp;&gt;</font></td> <td><font color=gray>&lt;&nbsp;data not available&nbsp;&gt;</font></td> </tr> <tr> <td>XILINX_DSP</td> <td>/opt/Xilinx/14.7/ISE_DS/ISE</td> <td>/opt/Xilinx/14.7/ISE_DS/ISE</td> <td><font color=gray>&lt;&nbsp;data not available&nbsp;&gt;</font></td> <td><font color=gray>&lt;&nbsp;data not available&nbsp;&gt;</font></td> </tr> <tr> <td>XILINX_EDK</td> <td>/opt/Xilinx/14.7/ISE_DS/EDK</td> <td>/opt/Xilinx/14.7/ISE_DS/EDK</td> <td><font color=gray>&lt;&nbsp;data not available&nbsp;&gt;</font></td> <td><font color=gray>&lt;&nbsp;data not available&nbsp;&gt;</font></td> </tr> <tr> <td>XILINX_PLANAHEAD</td> <td>/opt/Xilinx/14.7/ISE_DS/PlanAhead</td> <td>/opt/Xilinx/14.7/ISE_DS/PlanAhead</td> <td><font color=gray>&lt;&nbsp;data not available&nbsp;&gt;</font></td> <td><font color=gray>&lt;&nbsp;data not available&nbsp;&gt;</font></td> </tr> </TABLE> <A NAME="Synthesis Property Settings"></A> &nbsp;<BR><TABLE BORDER CELLSPACING=0 CELLPADDING=3 WIDTH='100%'> <TR ALIGN=CENTER BGCOLOR='#99CCFF'> <TD ALIGN=CENTER COLSPAN='4'><B>Synthesis Property Settings </B></TD> </tr> <tr bgcolor='#ffff99'> <td><b>Switch Name</b></td> <td><b>Property Name</b></td> <td><b>Value</b></td> <td><b>Default Value</b></td> </tr> <tr> <td>-ifn</td> <td>&nbsp;</td> <td>tb_addop.prj</td> <td>&nbsp;</td> </tr> <tr> <td>-ifmt</td> <td>&nbsp;</td> <td>mixed</td> <td>MIXED</td> </tr> <tr> <td>-ofn</td> <td>&nbsp;</td> <td>tb_addop</td> <td>&nbsp;</td> </tr> <tr> <td>-ofmt</td> <td>&nbsp;</td> <td>NGC</td> <td>NGC</td> </tr> <tr> <td>-p</td> <td>&nbsp;</td> <td>xc3s500e-4-fg320</td> <td>&nbsp;</td> </tr> <tr> <td>-top</td> <td>&nbsp;</td> <td>tb_addop</td> <td>&nbsp;</td> </tr> <tr> <td>-opt_mode</td> <td>Optimization Goal</td> <td>Speed</td> <td>SPEED</td> </tr> <tr> <td>-opt_level</td> <td>Optimization Effort</td> <td>1</td> <td>1</td> </tr> <tr> <td>-iuc</td> <td>Use synthesis Constraints File</td> <td>NO</td> <td>NO</td> </tr> <tr> <td>-keep_hierarchy</td> <td>Keep Hierarchy</td> <td>No</td> <td>NO</td> </tr> <tr> <td>-netlist_hierarchy</td> <td>Netlist Hierarchy</td> <td>As_Optimized</td> <td>as_optimized</td> </tr> <tr> <td>-rtlview</td> <td>Generate RTL Schematic</td> <td>Yes</td> <td>NO</td> </tr> <tr> <td>-glob_opt</td> <td>Global Optimization Goal</td> <td>AllClockNets</td> <td>ALLCLOCKNETS</td> </tr> <tr> <td>-read_cores</td> <td>Read Cores</td> <td>YES</td> <td>YES</td> </tr> <tr> <td>-write_timing_constraints</td> <td>Write Timing Constraints</td> <td>NO</td> <td>NO</td> </tr> <tr> <td>-cross_clock_analysis</td> <td>Cross Clock Analysis</td> <td>NO</td> <td>NO</td> </tr> <tr> <td>-bus_delimiter</td> <td>Bus Delimiter</td> <td>&lt;&gt;</td> <td>&lt;&gt;</td> </tr> <tr> <td>-slice_utilization_ratio</td> <td>Slice Utilization Ratio</td> <td>100</td> <td>100%</td> </tr> <tr> <td>-bram_utilization_ratio</td> <td>BRAM Utilization Ratio</td> <td>100</td> <td>100%</td> </tr> <tr> <td>-verilog2001</td> <td>Verilog 2001</td> <td>YES</td> <td>YES</td> </tr> <tr> <td>-fsm_extract</td> <td>&nbsp;</td> <td>YES</td> <td>YES</td> </tr> <tr> <td>-fsm_encoding</td> <td>&nbsp;</td> <td>Auto</td> <td>AUTO</td> </tr> <tr> <td>-safe_implementation</td> <td>&nbsp;</td> <td>No</td> <td>NO</td> </tr> <tr> <td>-fsm_style</td> <td>&nbsp;</td> <td>LUT</td> <td>LUT</td> </tr> <tr> <td>-ram_extract</td> <td>&nbsp;</td> <td>Yes</td> <td>YES</td> </tr> <tr> <td>-ram_style</td> <td>&nbsp;</td> <td>Auto</td> <td>AUTO</td> </tr> <tr> <td>-rom_extract</td> <td>&nbsp;</td> <td>Yes</td> <td>YES</td> </tr> <tr> <td>-shreg_extract</td> <td>&nbsp;</td> <td>YES</td> <td>YES</td> </tr> <tr> <td>-rom_style</td> <td>&nbsp;</td> <td>Auto</td> <td>AUTO</td> </tr> <tr> <td>-auto_bram_packing</td> <td>&nbsp;</td> <td>NO</td> <td>NO</td> </tr> <tr> <td>-resource_sharing</td> <td>&nbsp;</td> <td>YES</td> <td>YES</td> </tr> <tr> <td>-async_to_sync</td> <td>&nbsp;</td> <td>NO</td> <td>NO</td> </tr> <tr> <td>-mult_style</td> <td>&nbsp;</td> <td>Auto</td> <td>AUTO</td> </tr> <tr> <td>-iobuf</td> <td>&nbsp;</td> <td>YES</td> <td>YES</td> </tr> <tr> <td>-max_fanout</td> <td>&nbsp;</td> <td>100000</td> <td>500</td> </tr> <tr> <td>-bufg</td> <td>&nbsp;</td> <td>24</td> <td>24</td> </tr> <tr> <td>-register_duplication</td> <td>&nbsp;</td> <td>YES</td> <td>YES</td> </tr> <tr> <td>-register_balancing</td> <td>&nbsp;</td> <td>No</td> <td>NO</td> </tr> <tr> <td>-optimize_primitives</td> <td>&nbsp;</td> <td>NO</td> <td>NO</td> </tr> <tr> <td>-use_clock_enable</td> <td>&nbsp;</td> <td>Yes</td> <td>YES</td> </tr> <tr> <td>-use_sync_set</td> <td>&nbsp;</td> <td>Yes</td> <td>YES</td> </tr> <tr> <td>-use_sync_reset</td> <td>&nbsp;</td> <td>Yes</td> <td>YES</td> </tr> <tr> <td>-iob</td> <td>&nbsp;</td> <td>Auto</td> <td>AUTO</td> </tr> <tr> <td>-equivalent_register_removal</td> <td>&nbsp;</td> <td>YES</td> <td>YES</td> </tr> <tr> <td>-slice_utilization_ratio_maxmargin</td> <td>&nbsp;</td> <td>5</td> <td>0%</td> </tr> </TABLE> <A NAME="Translation Property Settings"></A> &nbsp;<BR><TABLE BORDER CELLSPACING=0 CELLPADDING=3 WIDTH='100%'> <TR ALIGN=CENTER BGCOLOR='#99CCFF'> <TD ALIGN=CENTER COLSPAN='4'><B>Translation Property Settings </B></TD> </tr> <tr bgcolor='#ffff99'> <td><b>Switch Name</b></td> <td><b>Property Name</b></td> <td><b>Value</b></td> <td><b>Default Value</b></td> </tr> <tr> <td>-intstyle</td> <td>&nbsp;</td> <td>ise</td> <td>None</td> </tr> <tr> <td>-dd</td> <td>&nbsp;</td> <td>_ngo</td> <td>None</td> </tr> <tr> <td>-p</td> <td>&nbsp;</td> <td>xc3s500e-fg320-4</td> <td>None</td> </tr> <tr> <td>-uc</td> <td>&nbsp;</td> <td>idea_hw.ucf</td> <td>None</td> </tr> </TABLE> <A NAME="Operating System Information"></A> &nbsp;<BR><TABLE BORDER CELLSPACING=0 CELLPADDING=3 WIDTH='100%'> <TR ALIGN=CENTER BGCOLOR='#99CCFF'> <TD ALIGN=CENTER COLSPAN='5'><B> Operating System Information </B></TD> </tr> <tr bgcolor='#ffff99'> <td><b>Operating System Information</b></td> <td><b>xst</b></td> <td><b>ngdbuild</b></td> <td><b>map</b></td> <td><b>par</b></td> </tr> <tr> <td>CPU Architecture/Speed</td> <td>AMD Athlon Dual-Core QL-60/1900.000 MHz</td> <td>AMD Athlon Dual-Core QL-60/1900.000 MHz</td> <td><font color=gray>&lt;&nbsp; data not available &nbsp;&gt;</font></td> <td><font color=gray>&lt;&nbsp; data not available &nbsp;&gt;</font></td> </tr> <tr> <td>Host</td> <td>compq</td> <td>compq</td> <td><font color=gray>&lt;&nbsp; data not available &nbsp;&gt;</font></td> <td><font color=gray>&lt;&nbsp; data not available &nbsp;&gt;</font></td> </tr> <tr> <td>OS Name</td> <td>Ubuntu</td> <td>Ubuntu</td> <td><font color=gray>&lt;&nbsp; data not available &nbsp;&gt;</font></td> <td><font color=gray>&lt;&nbsp; data not available &nbsp;&gt;</font></td> </tr> <tr> <td>OS Release</td> <td>Ubuntu 15.10</td> <td>Ubuntu 15.10</td> <td><font color=gray>&lt;&nbsp; data not available &nbsp;&gt;</font></td> <td><font color=gray>&lt;&nbsp; data not available &nbsp;&gt;</font></td> </tr> </TABLE> </BODY> </HTML>
tolgasel/vhdl_system_design
workspace/idea_rcs1/idea_rcs1/tb_addop_envsettings.html
HTML
gpl-2.0
10,474
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>List of All Members for QImageDocumentSelectorDialog</title> <link href="classic.css" rel="stylesheet" type="text/css" /> </head> <body> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td align="left" valign="top" width="32"><img src="images/qpelogo.png" align="left" width="32" height="32" border="0" /></td> <td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">All&nbsp;Classes</font></a>&nbsp;&middot; <a href="groups.html"><font color="#004faf">Grouped Classes</font></a>&nbsp;&middot; <a href="annotated.html"><font color="#004faf">Annotated</font></a>&nbsp;&middot; <a href="functions.html"><font color="#004faf">Functions</font></a></td> <td align="right" valign="top"><img src="images/codeless.png" align="right" border="0" /></td></tr></table><h1 class="title">List of All Members for QImageDocumentSelectorDialog</h1> <p>This is the complete list of members for <a href="qimagedocumentselectordialog.html">QImageDocumentSelectorDialog</a>, including inherited members.</p> <p><table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr><td width="45%" valign="top"><ul> <li><div class="fn"/>enum <a href="qdialog.html#DialogCode-enum">DialogCode</a></li> <li><div class="fn"/>enum <a href="qpaintdevice.html#PaintDeviceMetric-enum">PaintDeviceMetric</a></li> <li><div class="fn"/>enum <a href="qwidget.html#RenderFlag-enum">RenderFlag</a></li> <li><div class="fn"/>typedef <a href="qwidget.html#RenderFlags-typedef">RenderFlags</a></li> <li><div class="fn"/><a href="qimagedocumentselectordialog.html#QImageDocumentSelectorDialog">QImageDocumentSelectorDialog</a> ( QWidget * )</li> <li><div class="fn"/><a href="qimagedocumentselectordialog.html#dtor.QImageDocumentSelectorDialog">~QImageDocumentSelectorDialog</a> ()</li> <li><div class="fn"/><a href="qdialog.html#accept">accept</a> ()</li> <li><div class="fn"/><a href="qwidget.html#acceptDrops-prop">acceptDrops</a> () const</li> <li><div class="fn"/><a href="qdialog.html#accepted">accepted</a> ()</li> <li><div class="fn"/><a href="qwidget.html#accessibleDescription-prop">accessibleDescription</a> () const</li> <li><div class="fn"/><a href="qwidget.html#accessibleName-prop">accessibleName</a> () const</li> <li><div class="fn"/><a href="qwidget.html#actionEvent">actionEvent</a> ( QActionEvent * )</li> <li><div class="fn"/><a href="qwidget.html#actions">actions</a> () const</li> <li><div class="fn"/><a href="qwidget.html#activateWindow">activateWindow</a> ()</li> <li><div class="fn"/><a href="qwidget.html#addAction">addAction</a> ( QAction * )</li> <li><div class="fn"/><a href="qwidget.html#addActions">addActions</a> ( QList&lt;QAction *&gt; )</li> <li><div class="fn"/><a href="qwidget.html#adjustSize">adjustSize</a> ()</li> <li><div class="fn"/><a href="qwidget.html#autoFillBackground-prop">autoFillBackground</a> () const</li> <li><div class="fn"/><a href="qwidget.html#backgroundRole">backgroundRole</a> () const</li> <li><div class="fn"/><a href="qwidget.html#baseSize-prop">baseSize</a> () const</li> <li><div class="fn"/><a href="qobject.html#blockSignals">blockSignals</a> ( bool )</li> <li><div class="fn"/><a href="qwidget.html#changeEvent">changeEvent</a> ( QEvent * )</li> <li><div class="fn"/><a href="qwidget.html#childAt">childAt</a> ( int, int ) const</li> <li><div class="fn"/><a href="qwidget.html#childAt-4">childAt</a> ( const QPoint &amp; ) const</li> <li><div class="fn"/><a href="qobject.html#childEvent">childEvent</a> ( QChildEvent * )</li> <li><div class="fn"/><a href="qobject.html#children">children</a> () const</li> <li><div class="fn"/><a href="qwidget.html#childrenRect-prop">childrenRect</a> () const</li> <li><div class="fn"/><a href="qwidget.html#childrenRegion-prop">childrenRegion</a> () const</li> <li><div class="fn"/><a href="qwidget.html#clearFocus">clearFocus</a> ()</li> <li><div class="fn"/><a href="qwidget.html#clearMask">clearMask</a> ()</li> <li><div class="fn"/><a href="qwidget.html#close">close</a> ()</li> <li><div class="fn"/><a href="qwidget.html#closeEvent">closeEvent</a> ( QCloseEvent * )</li> <li><div class="fn"/><a href="qobject.html#connect">connect</a> ( const QObject *, const char *, const QObject *, const char *, Qt::ConnectionType )</li> <li><div class="fn"/><a href="qobject.html#connect-2">connect</a> ( const QObject *, const char *, const char *, Qt::ConnectionType ) const</li> <li><div class="fn"/><a href="qobject.html#connectNotify">connectNotify</a> ( const char * )</li> <li><div class="fn"/><a href="qwidget.html#contentsRect">contentsRect</a> () const</li> <li><div class="fn"/><a href="qwidget.html#contextMenuEvent">contextMenuEvent</a> ( QContextMenuEvent * )</li> <li><div class="fn"/><a href="qwidget.html#contextMenuPolicy-prop">contextMenuPolicy</a> () const</li> <li><div class="fn"/><a href="qwidget.html#create">create</a> ( WId, bool, bool )</li> <li><div class="fn"/><a href="qwidget.html#cursor-prop">cursor</a> () const</li> <li><div class="fn"/><a href="qwidget.html#customContextMenuRequested">customContextMenuRequested</a> ( const QPoint &amp; )</li> <li><div class="fn"/><a href="qobject.html#customEvent">customEvent</a> ( QEvent * )</li> <li><div class="fn"/><a href="qobject.html#d_ptr-var">d_ptr</a> : </li> <li><div class="fn"/><a href="qimagedocumentselectordialog.html#defaultCategories">defaultCategories</a> () const : QStringList</li> <li><div class="fn"/><a href="qobject.html#deleteLater">deleteLater</a> ()</li> <li><div class="fn"/><a href="qpaintdevice.html#depth">depth</a> () const</li> <li><div class="fn"/><a href="qwidget.html#destroy">destroy</a> ( bool, bool )</li> <li><div class="fn"/><a href="qobject.html#destroyed">destroyed</a> ( QObject * )</li> <li><div class="fn"/><a href="qobject.html#disconnect">disconnect</a> ( const QObject *, const char *, const QObject *, const char * )</li> <li><div class="fn"/><a href="qobject.html#disconnect-2">disconnect</a> ( const char *, const QObject *, const char * )</li> <li><div class="fn"/><a href="qobject.html#disconnect-3">disconnect</a> ( const QObject *, const char * )</li> <li><div class="fn"/><a href="qobject.html#disconnectNotify">disconnectNotify</a> ( const char * )</li> <li><div class="fn"/><a href="qimagedocumentselectordialog.html#documents">documents</a> () const : const QContentSet &amp;</li> <li><div class="fn"/><a href="qdialog.html#done">done</a> ( int )</li> <li><div class="fn"/><a href="qwidget.html#dragEnterEvent">dragEnterEvent</a> ( QDragEnterEvent * )</li> <li><div class="fn"/><a href="qwidget.html#dragLeaveEvent">dragLeaveEvent</a> ( QDragLeaveEvent * )</li> <li><div class="fn"/><a href="qwidget.html#dragMoveEvent">dragMoveEvent</a> ( QDragMoveEvent * )</li> <li><div class="fn"/><a href="qwidget.html#dropEvent">dropEvent</a> ( QDropEvent * )</li> <li><div class="fn"/><a href="qobject.html#dumpObjectInfo">dumpObjectInfo</a> ()</li> <li><div class="fn"/><a href="qobject.html#dumpObjectTree">dumpObjectTree</a> ()</li> <li><div class="fn"/><a href="qobject.html#dynamicPropertyNames">dynamicPropertyNames</a> () const</li> <li><div class="fn"/><a href="qwidget.html#ensurePolished">ensurePolished</a> () const</li> <li><div class="fn"/><a href="qwidget.html#enterEvent">enterEvent</a> ( QEvent * )</li> <li><div class="fn"/><a href="qwidget.html#event">event</a> ( QEvent * )</li> <li><div class="fn"/><a href="qobject.html#eventFilter">eventFilter</a> ( QObject *, QEvent * )</li> <li><div class="fn"/><a href="qdialog.html#exec">exec</a> ()</li> <li><div class="fn"/><a href="qimagedocumentselectordialog.html#filter">filter</a> () const : QContentFilter</li> <li><div class="fn"/><a href="qwidget.html#find">find</a> ( WId )</li> <li><div class="fn"/><a href="qobject.html#findChild">findChild</a> ( const QString &amp; ) const</li> <li><div class="fn"/><a href="qobject.html#findChildren">findChildren</a> ( const QString &amp; ) const</li> <li><div class="fn"/><a href="qobject.html#findChildren-2">findChildren</a> ( const QRegExp &amp; ) const</li> <li><div class="fn"/><a href="qdialog.html#finished">finished</a> ( int )</li> <li><div class="fn"/><a href="qwidget.html#focusInEvent">focusInEvent</a> ( QFocusEvent * )</li> <li><div class="fn"/><a href="qwidget.html#focusNextChild">focusNextChild</a> ()</li> <li><div class="fn"/><a href="qwidget.html#focusNextPrevChild">focusNextPrevChild</a> ( bool )</li> <li><div class="fn"/><a href="qwidget.html#focusOutEvent">focusOutEvent</a> ( QFocusEvent * )</li> <li><div class="fn"/><a href="qwidget.html#focusPolicy-prop">focusPolicy</a> () const</li> <li><div class="fn"/><a href="qwidget.html#focusPreviousChild">focusPreviousChild</a> ()</li> <li><div class="fn"/><a href="qwidget.html#focusProxy">focusProxy</a> () const</li> <li><div class="fn"/><a href="qwidget.html#focusWidget">focusWidget</a> () const</li> <li><div class="fn"/><a href="qwidget.html#font-prop">font</a> () const</li> <li><div class="fn"/><a href="qwidget.html#fontInfo">fontInfo</a> () const</li> <li><div class="fn"/><a href="qwidget.html#fontMetrics">fontMetrics</a> () const</li> <li><div class="fn"/><a href="qwidget.html#foregroundRole">foregroundRole</a> () const</li> <li><div class="fn"/><a href="qwidget.html#frameGeometry-prop">frameGeometry</a> () const</li> <li><div class="fn"/><a href="qwidget.html#frameSize-prop">frameSize</a> () const</li> <li><div class="fn"/><a href="qwidget.html#geometry-prop">geometry</a> () const</li> <li><div class="fn"/><a href="qwidget.html#getContentsMargins">getContentsMargins</a> ( int *, int *, int *, int * ) const</li> <li><div class="fn"/><a href="qwidget.html#getDC">getDC</a> () const</li> <li><div class="fn"/><a href="qwidget.html#grabKeyboard">grabKeyboard</a> ()</li> <li><div class="fn"/><a href="qwidget.html#grabMouse">grabMouse</a> ()</li> <li><div class="fn"/><a href="qwidget.html#grabMouse-2">grabMouse</a> ( const QCursor &amp; )</li> <li><div class="fn"/><a href="qwidget.html#grabShortcut">grabShortcut</a> ( const QKeySequence &amp;, Qt::ShortcutContext )</li> <li><div class="fn"/><a href="qwidget.html#hasEditFocus">hasEditFocus</a> () const</li> <li><div class="fn"/><a href="qwidget.html#focus-prop">hasFocus</a> () const</li> <li><div class="fn"/><a href="qwidget.html#mouseTracking-prop">hasMouseTracking</a> () const</li> <li><div class="fn"/><a href="qwidget.html#height-prop">height</a> () const</li> <li><div class="fn"/><a href="qwidget.html#heightForWidth">heightForWidth</a> ( int ) const</li> <li><div class="fn"/><a href="qpaintdevice.html#heightMM">heightMM</a> () const</li> <li><div class="fn"/><a href="qwidget.html#hide">hide</a> ()</li> <li><div class="fn"/><a href="qwidget.html#hideEvent">hideEvent</a> ( QHideEvent * )</li> <li><div class="fn"/><a href="qobject.html#inherits">inherits</a> ( const char * ) const</li> <li><div class="fn"/><a href="qwidget.html#inputContext">inputContext</a> ()</li> <li><div class="fn"/><a href="qwidget.html#inputMethodEvent">inputMethodEvent</a> ( QInputMethodEvent * )</li> <li><div class="fn"/><a href="qwidget.html#inputMethodQuery">inputMethodQuery</a> ( Qt::InputMethodQuery ) const</li> <li><div class="fn"/><a href="qwidget.html#insertAction">insertAction</a> ( QAction *, QAction * )</li> <li><div class="fn"/><a href="qwidget.html#insertActions">insertActions</a> ( QAction *, QList&lt;QAction *&gt; )</li> <li><div class="fn"/><a href="qobject.html#installEventFilter">installEventFilter</a> ( QObject * )</li> <li><div class="fn"/><a href="qwidget.html#isActiveWindow-prop">isActiveWindow</a> () const</li> <li><div class="fn"/><a href="qwidget.html#isAncestorOf">isAncestorOf</a> ( const QWidget * ) const</li> <li><div class="fn"/><a href="qwidget.html#enabled-prop">isEnabled</a> () const</li> <li><div class="fn"/><a href="qwidget.html#isEnabledTo">isEnabledTo</a> ( QWidget * ) const</li> <li><div class="fn"/><a href="qwidget.html#fullScreen-prop">isFullScreen</a> () const</li> <li><div class="fn"/><a href="qwidget.html#isHidden">isHidden</a> () const</li> <li><div class="fn"/><a href="qwidget.html#maximized-prop">isMaximized</a> () const</li> <li><div class="fn"/><a href="qwidget.html#minimized-prop">isMinimized</a> () const</li> <li><div class="fn"/><a href="qwidget.html#modal-prop">isModal</a> () const</li> <li><div class="fn"/><a href="qdialog.html#sizeGripEnabled-prop">isSizeGripEnabled</a> () const</li> <li><div class="fn"/><a href="qwidget.html#visible-prop">isVisible</a> () const</li> <li><div class="fn"/><a href="qwidget.html#isVisibleTo">isVisibleTo</a> ( QWidget * ) const</li> <li><div class="fn"/><a href="qobject.html#isWidgetType">isWidgetType</a> () const</li> <li><div class="fn"/><a href="qwidget.html#isWindow">isWindow</a> () const</li> <li><div class="fn"/><a href="qwidget.html#windowModified-prop">isWindowModified</a> () const</li> <li><div class="fn"/><a href="qwidget.html#keyPressEvent">keyPressEvent</a> ( QKeyEvent * )</li> <li><div class="fn"/><a href="qwidget.html#keyReleaseEvent">keyReleaseEvent</a> ( QKeyEvent * )</li> <li><div class="fn"/><a href="qwidget.html#keyboardGrabber">keyboardGrabber</a> ()</li> <li><div class="fn"/><a href="qobject.html#killTimer">killTimer</a> ( int )</li> <li><div class="fn"/><a href="qwidget.html#layout">layout</a> () const</li> <li><div class="fn"/><a href="qwidget.html#layoutDirection-prop">layoutDirection</a> () const</li> <li><div class="fn"/><a href="qwidget.html#leaveEvent">leaveEvent</a> ( QEvent * )</li> <li><div class="fn"/><a href="qwidget.html#locale-prop">locale</a> () const</li> <li><div class="fn"/><a href="qpaintdevice.html#logicalDpiX">logicalDpiX</a> () const</li> <li><div class="fn"/><a href="qpaintdevice.html#logicalDpiY">logicalDpiY</a> () const</li> <li><div class="fn"/><a href="qwidget.html#lower">lower</a> ()</li> <li><div class="fn"/><a href="qwidget.html#macCGHandle">macCGHandle</a> () const</li> <li><div class="fn"/><a href="qwidget.html#macEvent">macEvent</a> ( EventHandlerCallRef, EventRef )</li> <li><div class="fn"/><a href="qwidget.html#macQDHandle">macQDHandle</a> () const</li> <li><div class="fn"/><a href="qimagedocumentselectordialog.html#mandatoryPermissions">mandatoryPermissions</a> () const : QDrmRights::Permissions</li> <li><div class="fn"/><a href="qwidget.html#mapFrom">mapFrom</a> ( QWidget *, const QPoint &amp; ) const</li> <li><div class="fn"/><a href="qwidget.html#mapFromGlobal">mapFromGlobal</a> ( const QPoint &amp; ) const</li> <li><div class="fn"/><a href="qwidget.html#mapFromParent">mapFromParent</a> ( const QPoint &amp; ) const</li> <li><div class="fn"/><a href="qwidget.html#mapTo">mapTo</a> ( QWidget *, const QPoint &amp; ) const</li> <li><div class="fn"/><a href="qwidget.html#mapToGlobal">mapToGlobal</a> ( const QPoint &amp; ) const</li> <li><div class="fn"/><a href="qwidget.html#mapToParent">mapToParent</a> ( const QPoint &amp; ) const</li> <li><div class="fn"/><a href="qwidget.html#mask">mask</a> () const</li> <li><div class="fn"/><a href="qwidget.html#maximumHeight-prop">maximumHeight</a> () const</li> <li><div class="fn"/><a href="qwidget.html#maximumSize-prop">maximumSize</a> () const</li> <li><div class="fn"/><a href="qwidget.html#maximumWidth-prop">maximumWidth</a> () const</li> <li><div class="fn"/><a href="qobject.html#metaObject">metaObject</a> () const</li> <li><div class="fn"/><a href="qwidget.html#metric">metric</a> ( PaintDeviceMetric ) const</li> <li><div class="fn"/><a href="qwidget.html#minimumHeight-prop">minimumHeight</a> () const</li> <li><div class="fn"/><a href="qwidget.html#minimumSize-prop">minimumSize</a> () const</li> <li><div class="fn"/><a href="qwidget.html#minimumSizeHint-prop">minimumSizeHint</a> () const</li> <li><div class="fn"/><a href="qwidget.html#minimumWidth-prop">minimumWidth</a> () const</li> <li><div class="fn"/><a href="qwidget.html#mouseDoubleClickEvent">mouseDoubleClickEvent</a> ( QMouseEvent * )</li> <li><div class="fn"/><a href="qwidget.html#mouseGrabber">mouseGrabber</a> ()</li> <li><div class="fn"/><a href="qwidget.html#mouseMoveEvent">mouseMoveEvent</a> ( QMouseEvent * )</li> <li><div class="fn"/><a href="qwidget.html#mousePressEvent">mousePressEvent</a> ( QMouseEvent * )</li> <li><div class="fn"/><a href="qwidget.html#mouseReleaseEvent">mouseReleaseEvent</a> ( QMouseEvent * )</li> <li><div class="fn"/><a href="qwidget.html#pos-prop">move</a> ( const QPoint &amp; )</li> <li><div class="fn"/><a href="qwidget.html#pos-prop">move</a> ( int, int )</li> <li><div class="fn"/><a href="qwidget.html#moveEvent">moveEvent</a> ( QMoveEvent * )</li> <li><div class="fn"/><a href="qobject.html#moveToThread">moveToThread</a> ( QThread * )</li> <li><div class="fn"/><a href="qwidget.html#nextInFocusChain">nextInFocusChain</a> () const</li> <li><div class="fn"/><a href="qwidget.html#normalGeometry-prop">normalGeometry</a> () const</li> <li><div class="fn"/><a href="qpaintdevice.html#numColors">numColors</a> () const</li> <li><div class="fn"/><a href="qobject.html#objectName-prop">objectName</a> () const</li> <li><div class="fn"/><a href="qwidget.html#overrideWindowFlags">overrideWindowFlags</a> ( QFlags&lt;Qt::WindowType&gt; )</li> <li><div class="fn"/><a href="qwidget.html#paintEngine">paintEngine</a> () const</li> <li><div class="fn"/><a href="qwidget.html#paintEvent">paintEvent</a> ( QPaintEvent * )</li> <li><div class="fn"/><a href="qpaintdevice.html#painters-var">painters</a> : </li> <li><div class="fn"/><a href="qpaintdevice.html#paintingActive">paintingActive</a> () const</li> <li><div class="fn"/><a href="qwidget.html#palette-prop">palette</a> () const</li> <li><div class="fn"/><a href="qobject.html#parent">parent</a> () const</li> <li><div class="fn"/><a href="qwidget.html#parentWidget">parentWidget</a> () const</li> <li><div class="fn"/><a href="qpaintdevice.html#physicalDpiX">physicalDpiX</a> () const</li> </ul></td><td valign="top"><ul> <li><div class="fn"/><a href="qpaintdevice.html#physicalDpiY">physicalDpiY</a> () const</li> <li><div class="fn"/><a href="qwidget.html#pos-prop">pos</a> () const</li> <li><div class="fn"/><a href="qobject.html#property">property</a> ( const char * ) const</li> <li><div class="fn"/><a href="qwidget.html#qwsEvent">qwsEvent</a> ( QWSEvent * )</li> <li><div class="fn"/><a href="qwidget.html#raise">raise</a> ()</li> <li><div class="fn"/><a href="qobject.html#receivers">receivers</a> ( const char * ) const</li> <li><div class="fn"/><a href="qwidget.html#rect-prop">rect</a> () const</li> <li><div class="fn"/><a href="qdialog.html#reject">reject</a> ()</li> <li><div class="fn"/><a href="qdialog.html#rejected">rejected</a> ()</li> <li><div class="fn"/><a href="qwidget.html#releaseDC">releaseDC</a> ( HDC ) const</li> <li><div class="fn"/><a href="qwidget.html#releaseKeyboard">releaseKeyboard</a> ()</li> <li><div class="fn"/><a href="qwidget.html#releaseMouse">releaseMouse</a> ()</li> <li><div class="fn"/><a href="qwidget.html#releaseShortcut">releaseShortcut</a> ( int )</li> <li><div class="fn"/><a href="qwidget.html#removeAction">removeAction</a> ( QAction * )</li> <li><div class="fn"/><a href="qobject.html#removeEventFilter">removeEventFilter</a> ( QObject * )</li> <li><div class="fn"/><a href="qwidget.html#render">render</a> ( QPaintDevice *, const QPoint &amp;, const QRegion &amp;, QFlags&lt;QWidget::RenderFlag&gt; )</li> <li><div class="fn"/><a href="qwidget.html#repaint">repaint</a> ()</li> <li><div class="fn"/><a href="qwidget.html#repaint-6">repaint</a> ( int, int, int, int )</li> <li><div class="fn"/><a href="qwidget.html#repaint-7">repaint</a> ( const QRect &amp; )</li> <li><div class="fn"/><a href="qwidget.html#repaint-8">repaint</a> ( const QRegion &amp; )</li> <li><div class="fn"/><a href="qwidget.html#resetInputContext">resetInputContext</a> ()</li> <li><div class="fn"/><a href="qwidget.html#size-prop">resize</a> ( const QSize &amp; )</li> <li><div class="fn"/><a href="qwidget.html#size-prop">resize</a> ( int, int )</li> <li><div class="fn"/><a href="qwidget.html#resizeEvent">resizeEvent</a> ( QResizeEvent * )</li> <li><div class="fn"/><a href="qwidget.html#restoreGeometry">restoreGeometry</a> ( const QByteArray &amp; )</li> <li><div class="fn"/><a href="qdialog.html#result">result</a> () const</li> <li><div class="fn"/><a href="qwidget.html#saveGeometry">saveGeometry</a> () const</li> <li><div class="fn"/><a href="qwidget.html#scroll">scroll</a> ( int, int )</li> <li><div class="fn"/><a href="qwidget.html#scroll-2">scroll</a> ( int, int, const QRect &amp; )</li> <li><div class="fn"/><a href="qimagedocumentselectordialog.html#selectPermission">selectPermission</a> () const : QDrmRights::Permission</li> <li><div class="fn"/><a href="qimagedocumentselectordialog.html#selectedDocument">selectedDocument</a> () const : QContent</li> <li><div class="fn"/><a href="qobject.html#sender">sender</a> () const</li> <li><div class="fn"/><a href="qwidget.html#acceptDrops-prop">setAcceptDrops</a> ( bool )</li> <li><div class="fn"/><a href="qwidget.html#accessibleDescription-prop">setAccessibleDescription</a> ( const QString &amp; )</li> <li><div class="fn"/><a href="qwidget.html#accessibleName-prop">setAccessibleName</a> ( const QString &amp; )</li> <li><div class="fn"/><a href="qwidget.html#setAttribute">setAttribute</a> ( Qt::WidgetAttribute, bool )</li> <li><div class="fn"/><a href="qwidget.html#autoFillBackground-prop">setAutoFillBackground</a> ( bool )</li> <li><div class="fn"/><a href="qwidget.html#setBackgroundRole">setBackgroundRole</a> ( QPalette::ColorRole )</li> <li><div class="fn"/><a href="qwidget.html#baseSize-prop">setBaseSize</a> ( const QSize &amp; )</li> <li><div class="fn"/><a href="qwidget.html#baseSize-prop">setBaseSize</a> ( int, int )</li> <li><div class="fn"/><a href="qwidget.html#setContentsMargins">setContentsMargins</a> ( int, int, int, int )</li> <li><div class="fn"/><a href="qwidget.html#contextMenuPolicy-prop">setContextMenuPolicy</a> ( Qt::ContextMenuPolicy )</li> <li><div class="fn"/><a href="qwidget.html#cursor-prop">setCursor</a> ( const QCursor &amp; )</li> <li><div class="fn"/><a href="qimagedocumentselectordialog.html#setDefaultCategories">setDefaultCategories</a> ( const QStringList &amp; )</li> <li><div class="fn"/><a href="qwidget.html#setDisabled">setDisabled</a> ( bool )</li> <li><div class="fn"/><a href="qwidget.html#setEditFocus">setEditFocus</a> ( bool )</li> <li><div class="fn"/><a href="qwidget.html#enabled-prop">setEnabled</a> ( bool )</li> <li><div class="fn"/><a href="qimagedocumentselectordialog.html#setFilter">setFilter</a> ( const QContentFilter &amp; )</li> <li><div class="fn"/><a href="qwidget.html#setFixedHeight">setFixedHeight</a> ( int )</li> <li><div class="fn"/><a href="qwidget.html#setFixedSize">setFixedSize</a> ( const QSize &amp; )</li> <li><div class="fn"/><a href="qwidget.html#setFixedSize-2">setFixedSize</a> ( int, int )</li> <li><div class="fn"/><a href="qwidget.html#setFixedWidth">setFixedWidth</a> ( int )</li> <li><div class="fn"/><a href="qwidget.html#setFocus">setFocus</a> ( Qt::FocusReason )</li> <li><div class="fn"/><a href="qwidget.html#setFocus-2">setFocus</a> ()</li> <li><div class="fn"/><a href="qwidget.html#focusPolicy-prop">setFocusPolicy</a> ( Qt::FocusPolicy )</li> <li><div class="fn"/><a href="qwidget.html#setFocusProxy">setFocusProxy</a> ( QWidget * )</li> <li><div class="fn"/><a href="qwidget.html#font-prop">setFont</a> ( const QFont &amp; )</li> <li><div class="fn"/><a href="qwidget.html#setForegroundRole">setForegroundRole</a> ( QPalette::ColorRole )</li> <li><div class="fn"/><a href="qwidget.html#geometry-prop">setGeometry</a> ( const QRect &amp; )</li> <li><div class="fn"/><a href="qwidget.html#geometry-prop">setGeometry</a> ( int, int, int, int )</li> <li><div class="fn"/><a href="qwidget.html#setHidden">setHidden</a> ( bool )</li> <li><div class="fn"/><a href="qwidget.html#setInputContext">setInputContext</a> ( QInputContext * )</li> <li><div class="fn"/><a href="qwidget.html#setLayout">setLayout</a> ( QLayout * )</li> <li><div class="fn"/><a href="qwidget.html#layoutDirection-prop">setLayoutDirection</a> ( Qt::LayoutDirection )</li> <li><div class="fn"/><a href="qwidget.html#locale-prop">setLocale</a> ( const QLocale &amp; )</li> <li><div class="fn"/><a href="qimagedocumentselectordialog.html#setMandatoryPermissions">setMandatoryPermissions</a> ( QDrmRights::Permissions )</li> <li><div class="fn"/><a href="qwidget.html#setMask">setMask</a> ( const QBitmap &amp; )</li> <li><div class="fn"/><a href="qwidget.html#setMask-2">setMask</a> ( const QRegion &amp; )</li> <li><div class="fn"/><a href="qwidget.html#maximumHeight-prop">setMaximumHeight</a> ( int )</li> <li><div class="fn"/><a href="qwidget.html#maximumSize-prop">setMaximumSize</a> ( const QSize &amp; )</li> <li><div class="fn"/><a href="qwidget.html#maximumSize-prop">setMaximumSize</a> ( int, int )</li> <li><div class="fn"/><a href="qwidget.html#maximumWidth-prop">setMaximumWidth</a> ( int )</li> <li><div class="fn"/><a href="qwidget.html#minimumHeight-prop">setMinimumHeight</a> ( int )</li> <li><div class="fn"/><a href="qwidget.html#minimumSize-prop">setMinimumSize</a> ( const QSize &amp; )</li> <li><div class="fn"/><a href="qwidget.html#minimumSize-prop">setMinimumSize</a> ( int, int )</li> <li><div class="fn"/><a href="qwidget.html#minimumWidth-prop">setMinimumWidth</a> ( int )</li> <li><div class="fn"/><a href="qdialog.html#modal-prop">setModal</a> ( bool )</li> <li><div class="fn"/><a href="qwidget.html#mouseTracking-prop">setMouseTracking</a> ( bool )</li> <li><div class="fn"/><a href="qobject.html#objectName-prop">setObjectName</a> ( const QString &amp; )</li> <li><div class="fn"/><a href="qwidget.html#palette-prop">setPalette</a> ( const QPalette &amp; )</li> <li><div class="fn"/><a href="qwidget.html#setParent">setParent</a> ( QWidget * )</li> <li><div class="fn"/><a href="qwidget.html#setParent-2">setParent</a> ( QWidget *, QFlags&lt;Qt::WindowType&gt; )</li> <li><div class="fn"/><a href="qobject.html#setProperty">setProperty</a> ( const char *, const QVariant &amp; )</li> <li><div class="fn"/><a href="qdialog.html#setResult">setResult</a> ( int )</li> <li><div class="fn"/><a href="qimagedocumentselectordialog.html#setSelectPermission">setSelectPermission</a> ( QDrmRights::Permission )</li> <li><div class="fn"/><a href="qwidget.html#setShortcutAutoRepeat">setShortcutAutoRepeat</a> ( int, bool )</li> <li><div class="fn"/><a href="qwidget.html#setShortcutEnabled">setShortcutEnabled</a> ( int, bool )</li> <li><div class="fn"/><a href="qdialog.html#sizeGripEnabled-prop">setSizeGripEnabled</a> ( bool )</li> <li><div class="fn"/><a href="qwidget.html#sizeIncrement-prop">setSizeIncrement</a> ( const QSize &amp; )</li> <li><div class="fn"/><a href="qwidget.html#sizeIncrement-prop">setSizeIncrement</a> ( int, int )</li> <li><div class="fn"/><a href="qwidget.html#sizePolicy-prop">setSizePolicy</a> ( QSizePolicy )</li> <li><div class="fn"/><a href="qwidget.html#sizePolicy-prop">setSizePolicy</a> ( QSizePolicy::Policy, QSizePolicy::Policy )</li> <li><div class="fn"/><a href="qimagedocumentselectordialog.html#setSortCriteria">setSortCriteria</a> ( const QContentSortCriteria &amp; )</li> <li><div class="fn"/><a href="qimagedocumentselectordialog.html#setSortMode">setSortMode</a> ( QDocumentSelector::SortMode )</li> <li><div class="fn"/><a href="qwidget.html#statusTip-prop">setStatusTip</a> ( const QString &amp; )</li> <li><div class="fn"/><a href="qwidget.html#setStyle">setStyle</a> ( QStyle * )</li> <li><div class="fn"/><a href="qwidget.html#styleSheet-prop">setStyleSheet</a> ( const QString &amp; )</li> <li><div class="fn"/><a href="qwidget.html#setTabOrder">setTabOrder</a> ( QWidget *, QWidget * )</li> <li><div class="fn"/><a href="qimagedocumentselectordialog.html#setThumbnailSize">setThumbnailSize</a> ( const QSize &amp; )</li> <li><div class="fn"/><a href="qwidget.html#toolTip-prop">setToolTip</a> ( const QString &amp; )</li> <li><div class="fn"/><a href="qwidget.html#updatesEnabled-prop">setUpdatesEnabled</a> ( bool )</li> <li><div class="fn"/><a href="qwidget.html#visible-prop">setVisible</a> ( bool )</li> <li><div class="fn"/><a href="qwidget.html#whatsThis-prop">setWhatsThis</a> ( const QString &amp; )</li> <li><div class="fn"/><a href="qwidget.html#windowFlags-prop">setWindowFlags</a> ( QFlags&lt;Qt::WindowType&gt; )</li> <li><div class="fn"/><a href="qwidget.html#windowIcon-prop">setWindowIcon</a> ( const QIcon &amp; )</li> <li><div class="fn"/><a href="qwidget.html#windowIconText-prop">setWindowIconText</a> ( const QString &amp; )</li> <li><div class="fn"/><a href="qwidget.html#windowModality-prop">setWindowModality</a> ( Qt::WindowModality )</li> <li><div class="fn"/><a href="qwidget.html#windowModified-prop">setWindowModified</a> ( bool )</li> <li><div class="fn"/><a href="qwidget.html#windowOpacity-prop">setWindowOpacity</a> ( qreal )</li> <li><div class="fn"/><a href="qwidget.html#setWindowRole">setWindowRole</a> ( const QString &amp; )</li> <li><div class="fn"/><a href="qwidget.html#setWindowState">setWindowState</a> ( QFlags&lt;Qt::WindowState&gt; )</li> <li><div class="fn"/><a href="qwidget.html#setWindowSurface">setWindowSurface</a> ( QWindowSurface * )</li> <li><div class="fn"/><a href="qwidget.html#windowTitle-prop">setWindowTitle</a> ( const QString &amp; )</li> <li><div class="fn"/><a href="qwidget.html#show">show</a> ()</li> <li><div class="fn"/><a href="qwidget.html#showEvent">showEvent</a> ( QShowEvent * )</li> <li><div class="fn"/><a href="qwidget.html#showFullScreen">showFullScreen</a> ()</li> <li><div class="fn"/><a href="qwidget.html#showMaximized">showMaximized</a> ()</li> <li><div class="fn"/><a href="qwidget.html#showMinimized">showMinimized</a> ()</li> <li><div class="fn"/><a href="qwidget.html#showNormal">showNormal</a> ()</li> <li><div class="fn"/><a href="qobject.html#signalsBlocked">signalsBlocked</a> () const</li> <li><div class="fn"/><a href="qwidget.html#size-prop">size</a> () const</li> <li><div class="fn"/><a href="qwidget.html#sizeHint-prop">sizeHint</a> () const</li> <li><div class="fn"/><a href="qwidget.html#sizeIncrement-prop">sizeIncrement</a> () const</li> <li><div class="fn"/><a href="qwidget.html#sizePolicy-prop">sizePolicy</a> () const</li> <li><div class="fn"/><a href="qimagedocumentselectordialog.html#sortCriteria">sortCriteria</a> () const : QContentSortCriteria</li> <li><div class="fn"/><a href="qimagedocumentselectordialog.html#sortMode">sortMode</a> () const : QDocumentSelector::SortMode</li> <li><div class="fn"/><a href="qwidget.html#stackUnder">stackUnder</a> ( QWidget * )</li> <li><div class="fn"/><a href="qobject.html#startTimer">startTimer</a> ( int )</li> <li><div class="fn"/><a href="qobject.html#staticMetaObject-var">staticMetaObject</a> : </li> <li><div class="fn"/><a href="qobject.html#staticQtMetaObject-var">staticQtMetaObject</a> : </li> <li><div class="fn"/><a href="qwidget.html#statusTip-prop">statusTip</a> () const</li> <li><div class="fn"/><a href="qwidget.html#style">style</a> () const</li> <li><div class="fn"/><a href="qwidget.html#styleSheet-prop">styleSheet</a> () const</li> <li><div class="fn"/><a href="qwidget.html#tabletEvent">tabletEvent</a> ( QTabletEvent * )</li> <li><div class="fn"/><a href="qwidget.html#testAttribute">testAttribute</a> ( Qt::WidgetAttribute ) const</li> <li><div class="fn"/><a href="qobject.html#thread">thread</a> () const</li> <li><div class="fn"/><a href="qimagedocumentselectordialog.html#thumbnailSize">thumbnailSize</a> () const : QSize</li> <li><div class="fn"/><a href="qobject.html#timerEvent">timerEvent</a> ( QTimerEvent * )</li> <li><div class="fn"/><a href="qwidget.html#toolTip-prop">toolTip</a> () const</li> <li><div class="fn"/><a href="qobject.html#tr">tr</a> ( const char *, const char *, int )</li> <li><div class="fn"/><a href="qobject.html#trUtf8">trUtf8</a> ( const char *, const char *, int )</li> <li><div class="fn"/><a href="qwidget.html#underMouse">underMouse</a> () const</li> <li><div class="fn"/><a href="qwidget.html#cursor-prop">unsetCursor</a> ()</li> <li><div class="fn"/><a href="qwidget.html#layoutDirection-prop">unsetLayoutDirection</a> ()</li> <li><div class="fn"/><a href="qwidget.html#locale-prop">unsetLocale</a> ()</li> <li><div class="fn"/><a href="qwidget.html#update">update</a> ()</li> <li><div class="fn"/><a href="qwidget.html#update-2">update</a> ( int, int, int, int )</li> <li><div class="fn"/><a href="qwidget.html#update-3">update</a> ( const QRect &amp; )</li> <li><div class="fn"/><a href="qwidget.html#update-4">update</a> ( const QRegion &amp; )</li> <li><div class="fn"/><a href="qwidget.html#updateGeometry">updateGeometry</a> ()</li> <li><div class="fn"/><a href="qwidget.html#updateMicroFocus">updateMicroFocus</a> ()</li> <li><div class="fn"/><a href="qwidget.html#updatesEnabled-prop">updatesEnabled</a> () const</li> <li><div class="fn"/><a href="qwidget.html#visibleRegion">visibleRegion</a> () const</li> <li><div class="fn"/><a href="qwidget.html#whatsThis-prop">whatsThis</a> () const</li> <li><div class="fn"/><a href="qwidget.html#wheelEvent">wheelEvent</a> ( QWheelEvent * )</li> <li><div class="fn"/><a href="qwidget.html#width-prop">width</a> () const</li> <li><div class="fn"/><a href="qpaintdevice.html#widthMM">widthMM</a> () const</li> <li><div class="fn"/><a href="qwidget.html#winEvent">winEvent</a> ( MSG *, long * )</li> <li><div class="fn"/><a href="qwidget.html#winId">winId</a> () const</li> <li><div class="fn"/><a href="qwidget.html#window">window</a> () const</li> <li><div class="fn"/><a href="qwidget.html#windowFlags-prop">windowFlags</a> () const</li> <li><div class="fn"/><a href="qwidget.html#windowIcon-prop">windowIcon</a> () const</li> <li><div class="fn"/><a href="qwidget.html#windowIconText-prop">windowIconText</a> () const</li> <li><div class="fn"/><a href="qwidget.html#windowModality-prop">windowModality</a> () const</li> <li><div class="fn"/><a href="qwidget.html#windowOpacity-prop">windowOpacity</a> () const</li> <li><div class="fn"/><a href="qwidget.html#windowRole">windowRole</a> () const</li> <li><div class="fn"/><a href="qwidget.html#windowState">windowState</a> () const</li> <li><div class="fn"/><a href="qwidget.html#windowSurface">windowSurface</a> () const</li> <li><div class="fn"/><a href="qwidget.html#windowTitle-prop">windowTitle</a> () const</li> <li><div class="fn"/><a href="qwidget.html#windowType">windowType</a> () const</li> <li><div class="fn"/><a href="qwidget.html#x-prop">x</a> () const</li> <li><div class="fn"/><a href="qwidget.html#x11Event">x11Event</a> ( XEvent * )</li> <li><div class="fn"/><a href="qwidget.html#x11Info">x11Info</a> () const</li> <li><div class="fn"/><a href="qwidget.html#x11PictureHandle">x11PictureHandle</a> () const</li> <li><div class="fn"/><a href="qwidget.html#y-prop">y</a> () const</li> </ul> </td></tr> </table></p> <p /><address><hr /><div align="center"> <table width="100%" cellspacing="0" border="0"><tr class="address"> <td align="left">Copyright &copy; 2008 Trolltech</td> <td align="center"><a href="trademarks.html">Trademarks</a></td> <td align="right"><div align="right">Qtopia 4.3.4</div></td> </tr></table></div></address></body> </html>
muromec/qtopia-ezx
doc/html/qimagedocumentselectordialog-members.html
HTML
gpl-2.0
35,457
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>phamerator.alignmentDatabase.blastWorkUnit</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="phamerator-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar" width="100%"></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> <a href="phamerator-module.html">Package&nbsp;phamerator</a> :: <a href="phamerator.alignmentDatabase-module.html">Module&nbsp;alignmentDatabase</a> :: Class&nbsp;blastWorkUnit </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="phamerator.alignmentDatabase.blastWorkUnit-class.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <!-- ==================== CLASS DESCRIPTION ==================== --> <h1 class="epydoc">Class blastWorkUnit</h1><p class="nomargin-top"><span class="codelink"><a href="phamerator.alignmentDatabase-pysrc.html#blastWorkUnit">source&nbsp;code</a></span></p> <pre class="base-tree"> <a href="phamerator.errorHandler.errorHandler-class.html">errorHandler.errorHandler</a> --+ | <strong class="uidshort">blastWorkUnit</strong> </pre> <hr /> <!-- ==================== INSTANCE METHODS ==================== --> <a name="section-InstanceMethods"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Instance Methods</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-InstanceMethods" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="phamerator.alignmentDatabase.blastWorkUnit-class.html#__init__" class="summary-sig-name">__init__</a>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">c</span>, <span class="summary-sig-arg">query_id</span>=<span class="summary-sig-default">None</span>)</span></td> <td align="right" valign="top"> <span class="codelink"><a href="phamerator.alignmentDatabase-pysrc.html#blastWorkUnit.__init__">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="_mark_pending"></a><span class="summary-sig-name">_mark_pending</span>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">c</span>)</span></td> <td align="right" valign="top"> <span class="codelink"><a href="phamerator.alignmentDatabase-pysrc.html#blastWorkUnit._mark_pending">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="create_database"></a><span class="summary-sig-name">create_database</span>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">c</span>)</span></td> <td align="right" valign="top"> <span class="codelink"><a href="phamerator.alignmentDatabase-pysrc.html#blastWorkUnit.create_database">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="get_as_fasta"></a><span class="summary-sig-name">get_as_fasta</span>(<span class="summary-sig-arg">self</span>)</span></td> <td align="right" valign="top"> <span class="codelink"><a href="phamerator.alignmentDatabase-pysrc.html#blastWorkUnit.get_as_fasta">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="add_matches"></a><span class="summary-sig-name">add_matches</span>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">matches</span>, <span class="summary-sig-arg">c</span>)</span><br /> called by a compute node to keep track of a good BLASTp alignment</td> <td align="right" valign="top"> <span class="codelink"><a href="phamerator.alignmentDatabase-pysrc.html#blastWorkUnit.add_matches">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="_add_match"></a><span class="summary-sig-name">_add_match</span>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">qid</span>, <span class="summary-sig-arg">sid</span>, <span class="summary-sig-arg">e</span>, <span class="summary-sig-arg">bits</span>, <span class="summary-sig-arg">c</span>)</span><br /> called by a compute node to keep track of a good BLAST alignment</td> <td align="right" valign="top"> <span class="codelink"><a href="phamerator.alignmentDatabase-pysrc.html#blastWorkUnit._add_match">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="get_matches"></a><span class="summary-sig-name">get_matches</span>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">qid</span>)</span><br /> called by server when adding good BLAST alignment(s) to MySQL db</td> <td align="right" valign="top"> <span class="codelink"><a href="phamerator.alignmentDatabase-pysrc.html#blastWorkUnit.get_matches">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="phamerator.errorHandler.errorHandler-class.html">errorHandler.errorHandler</a></code></b>: <code><a href="phamerator.errorHandler.errorHandler-class.html#show_sql_errors">show_sql_errors</a></code> </p> </td> </tr> </table> <!-- ==================== METHOD DETAILS ==================== --> <a name="section-MethodDetails"></a> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Method Details</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-MethodDetails" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> </table> <a name="__init__"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">__init__</span>(<span class="sig-arg">self</span>, <span class="sig-arg">c</span>, <span class="sig-arg">query_id</span>=<span class="sig-default">None</span>)</span> <br /><em class="fname">(Constructor)</em> </h3> </td><td align="right" valign="top" ><span class="codelink"><a href="phamerator.alignmentDatabase-pysrc.html#blastWorkUnit.__init__">source&nbsp;code</a></span>&nbsp; </td> </tr></table> <dl class="fields"> <dt>Overrides: <a href="phamerator.errorHandler.errorHandler-class.html#__init__">errorHandler.errorHandler.__init__</a> </dt> </dl> </td></tr></table> </div> <br /> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="phamerator-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar" width="100%"></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Thu Nov 1 08:13:40 2012 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
byuphamerator/phamerator-dev
doc/phamerator.alignmentDatabase.blastWorkUnit-class.html
HTML
gpl-2.0
12,371
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Virvar.Net; using Microsoft.Xna.Framework; using GameObjects.DrawableClasses; using GameObjects; using GameObjects.ProtoClasses; namespace GameProcess.Actors.Client { class HitsActor : IActor, IClientPacketHandler { private GameStateClient _gameState; public HitsActor(GameStateClient gameState) { this._gameState = gameState; } public void Update(GameTime gameTime) { ushort sequence = _gameState.NetPlayer.ClientPacket.Sequence; lock (_gameState.NetPlayer.ClientPacket.Shoots) { lock (_gameState.Player) { _gameState.NetPlayer.ClientPacket.Shoots[sequence] = _gameState.Player.ShootingTime; _gameState.Player.ShootingTime = 0; } } } public void Receive(ServerPacket msg) { // анимация выстрела foreach (var player in _gameState.Players.Values) { player.IsShooting = false; } lock (msg.ShootingPlayers) { foreach (var player in msg.ShootingPlayers) { _gameState.Players[player].IsShooting = true; } } // удаляем из пакета выстрелы игрока, которые уже были обработаны сервером HashSet<ushort> keysToRemove = new HashSet<ushort>(); foreach (var shootSeq in _gameState.NetPlayer.ClientPacket.Shoots.Keys) { if (msg.Ack > shootSeq) { keysToRemove.Add(shootSeq); } } float deletedValue; foreach (var key in keysToRemove) { _gameState.NetPlayer.ClientPacket.Shoots.TryRemove(key, out deletedValue); } } } }
virvar/StillAlive
StillAlive/GameProcess/Actors/Client/HitsActor.cs
C#
gpl-2.0
2,078
# Overview Firstly this repository serves as a single point of entry for all language-variants of the Syscoin API. All variants can be found in the [`/server` directory](/server). The variant officially supported by Blockchain Foundry, the primary developers of Syscoin is the NodeJS variant located in [`/server/nodejs`](server/nodejs). Deployment specifics can be found in the [README](server/nodejs/README.md) file relative to the desired variant (ie: `/server/nodejs/README`). Secondly this repository allows users to generate various Syscoin-API server *and* client stubs based on the provided OpenAPI spec in swagger.yaml. They can then complete the implementation of the business logic (if working on the server side) within that variant and issue a pull request- for more information see the [Contributing](#contributing) section. # Generating API To generate the API first download [swagger-codegen](https://github.com/swagger-api/swagger-codegen) and build it. After its built, create an alias: ``` alias swagger-codegen='java -jar [/path/to/built/swagger-codegen]/swagger-codegen/modules/swagger-codegen-cli/target/swagger-codegen-cli.jar' ``` ##Generating the JSON Spec Anytime the root swagger.yaml is modified the JSON spec should be updated and copied into `swagger-ui/dist/swagger-spec.js` as the value for the `swaggerSpec` var. Currently this is a manual process. To regenerate the JSON API spec due to YAML changes (required for docs UI to be accurate): ``` swagger-codegen generate -i swagger.yaml -o ./generated-json -l swagger ``` The generated JSON can be deleted after its been copied to `swagger-spec.js`. ##Generating Server Stubs You can contribute to the syscoin-api project by writing connectors for Syscoin in different languages. Swagger-codegen can greatly reduce the time it takes to write connectors in other languages by generating a server-api stub in the desired language. To generate the Server stub use the command below replacing LANGUAGE with one of the [supported SwaggerJS server values](https://github.com/swagger-api/swagger-codegen/wiki/Server-stub-generator-HOWTO). ``` swagger-codegen generate -i swagger.yaml -o ./server/generated-server -l LANGUAGE ``` We encourage anyone who does this to submit a pull request to have their server API added to the official repo. Package your server API using folder names mirroring the swagger language name, ie: 'nodejs-server'. Client API's can also be submitted using the same format. ##Generating the Client SDK To quickly start communicating with an instance of the Syscoin API server simply generate a client-side SDK in your preferred language. To generate the Client SDK use the command below replacing LANGUAGE with one of the [supported SwaggerJS client values](https://generator.swagger.io/#!/clients/clientOptions). ``` swagger-codegen generate -i swagger.yaml -o ./client/generated-client -l LANGUAGE ``` # Contributing This project is fully open source and welcomes pull requests at all levels. Simply fork the repository, apply your changes to the fork and then issue a pull request. Once reviewed the pull request will be integrated into master and (if warranted) released as a new official Syscoin API version. # Credits This project leverages the mega-awesome [swagger-tools](https://github.com/apigee-127/swagger-tools) middleware which does most all the work.
syscoin/syscoin-api-server
README.md
Markdown
gpl-2.0
3,396
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.3.1"/> <title>Taobao Cpp/Qt SDK: SimbaInsightWordscatsGetResponse Class Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Taobao Cpp/Qt SDK </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.3.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Pages</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="#pri-attribs">Private Attributes</a> &#124; <a href="classSimbaInsightWordscatsGetResponse-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">SimbaInsightWordscatsGetResponse Class Reference</div> </div> </div><!--header--> <div class="contents"> <p>TOP RESPONSE API: 词和类目查询 <a href="classSimbaInsightWordscatsGetResponse.html#details">More...</a></p> <p><code>#include &lt;<a class="el" href="SimbaInsightWordscatsGetResponse_8h_source.html">SimbaInsightWordscatsGetResponse.h</a>&gt;</code></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:aefdbce0ee7a0c514c83fb5980e7d5f9e"><td class="memItemLeft" align="right" valign="top">virtual&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classSimbaInsightWordscatsGetResponse.html#aefdbce0ee7a0c514c83fb5980e7d5f9e">~SimbaInsightWordscatsGetResponse</a> ()</td></tr> <tr class="separator:aefdbce0ee7a0c514c83fb5980e7d5f9e"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a49ebe465b7b04e2eab003ea3bf79641c"><td class="memItemLeft" align="right" valign="top">QList&lt; <a class="el" href="classINWordCategory.html">INWordCategory</a> &gt;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classSimbaInsightWordscatsGetResponse.html#a49ebe465b7b04e2eab003ea3bf79641c">getInWordCategories</a> () const </td></tr> <tr class="separator:a49ebe465b7b04e2eab003ea3bf79641c"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ad068f500ada5ecd5b9402c67c9145ec3"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classSimbaInsightWordscatsGetResponse.html#ad068f500ada5ecd5b9402c67c9145ec3">setInWordCategories</a> (QList&lt; <a class="el" href="classINWordCategory.html">INWordCategory</a> &gt; <a class="el" href="classSimbaInsightWordscatsGetResponse.html#a0544d92dc334185c3a57d1947ff6dc82">inWordCategories</a>)</td></tr> <tr class="separator:ad068f500ada5ecd5b9402c67c9145ec3"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ab7c8500a489691ca739714eff575d237"><td class="memItemLeft" align="right" valign="top">virtual void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classSimbaInsightWordscatsGetResponse.html#ab7c8500a489691ca739714eff575d237">parseNormalResponse</a> ()</td></tr> <tr class="separator:ab7c8500a489691ca739714eff575d237"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="inherit_header pub_methods_classTaoResponse"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_classTaoResponse')"><img src="closed.png" alt="-"/>&#160;Public Member Functions inherited from <a class="el" href="classTaoResponse.html">TaoResponse</a></td></tr> <tr class="memitem:a2e4420f5671664de8a1360866977d28b inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a2e4420f5671664de8a1360866977d28b">TaoResponse</a> ()</td></tr> <tr class="separator:a2e4420f5671664de8a1360866977d28b inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a32ef9c53545a593316521cb1daab3e1a inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">virtual&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a32ef9c53545a593316521cb1daab3e1a">~TaoResponse</a> ()</td></tr> <tr class="separator:a32ef9c53545a593316521cb1daab3e1a inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:af5a077aab153edf6247200587ee855ee inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#af5a077aab153edf6247200587ee855ee">parseResponse</a> ()</td></tr> <tr class="separator:af5a077aab153edf6247200587ee855ee inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a174dc083a44795514cfe7a9f14a3731a inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a174dc083a44795514cfe7a9f14a3731a">setParser</a> (<a class="el" href="classParser.html">Parser</a> *parser)</td></tr> <tr class="separator:a174dc083a44795514cfe7a9f14a3731a inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a854c6fdaef0abbeab21b5a43f65233ea inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a854c6fdaef0abbeab21b5a43f65233ea">parseError</a> ()</td></tr> <tr class="separator:a854c6fdaef0abbeab21b5a43f65233ea inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ae8f183ea55d76bf813f038aae7022db4 inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">QString&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#ae8f183ea55d76bf813f038aae7022db4">getErrorCode</a> () const </td></tr> <tr class="separator:ae8f183ea55d76bf813f038aae7022db4 inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a2468d6e3ad0939ba2f4b12efd1b00413 inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a2468d6e3ad0939ba2f4b12efd1b00413">setErrorCode</a> (const QString &amp;<a class="el" href="classTaoResponse.html#ac54f11b3b22a4f93c8587c1f4c3899d7">errorCode</a>)</td></tr> <tr class="separator:a2468d6e3ad0939ba2f4b12efd1b00413 inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:adf75dc6bcbb550c8edb64d33939345ed inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">QString&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#adf75dc6bcbb550c8edb64d33939345ed">getMsg</a> () const </td></tr> <tr class="separator:adf75dc6bcbb550c8edb64d33939345ed inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a76b9304897ecfc563d8f706d32c01b59 inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a76b9304897ecfc563d8f706d32c01b59">setMsg</a> (const QString &amp;<a class="el" href="classTaoResponse.html#adc5e9252ac61126ac2936ab2f6b9a0c6">msg</a>)</td></tr> <tr class="separator:a76b9304897ecfc563d8f706d32c01b59 inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a35fd73600c578a0d5fe9cbe1e1750689 inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">QString&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a35fd73600c578a0d5fe9cbe1e1750689">getSubCode</a> () const </td></tr> <tr class="separator:a35fd73600c578a0d5fe9cbe1e1750689 inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a3c6346680f5209b3b9cd7fa0277222e6 inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a3c6346680f5209b3b9cd7fa0277222e6">setSubCode</a> (const QString &amp;<a class="el" href="classTaoResponse.html#a5c6f8d740932e6453e7e3a2590fd3e6f">subCode</a>)</td></tr> <tr class="separator:a3c6346680f5209b3b9cd7fa0277222e6 inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a7a0c8be833060f35437f741af784dd69 inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">QString&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a7a0c8be833060f35437f741af784dd69">getSubMsg</a> () const </td></tr> <tr class="separator:a7a0c8be833060f35437f741af784dd69 inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a4eac44413ea5445d5cee1e8aac077194 inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a4eac44413ea5445d5cee1e8aac077194">setSubMsg</a> (const QString &amp;<a class="el" href="classTaoResponse.html#a13f08fbbfd176df1e06c9dbf579d06f4">subMsg</a>)</td></tr> <tr class="separator:a4eac44413ea5445d5cee1e8aac077194 inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aff41254c8d0cf4454d663876569379d2 inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#aff41254c8d0cf4454d663876569379d2">isSuccess</a> ()</td></tr> <tr class="separator:aff41254c8d0cf4454d663876569379d2 inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a92f81ae42b484c9b2258b508e4023068 inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">QString&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a92f81ae42b484c9b2258b508e4023068">getTopForbiddenFields</a> () const </td></tr> <tr class="separator:a92f81ae42b484c9b2258b508e4023068 inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a475fb70a1c5657f8a947c3d1e3f5262d inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a475fb70a1c5657f8a947c3d1e3f5262d">setTopForbiddenFields</a> (const QString &amp;<a class="el" href="classTaoResponse.html#a4ff01826fe5b531e2427c7df23d4cc18">topForbiddenFields</a>)</td></tr> <tr class="separator:a475fb70a1c5657f8a947c3d1e3f5262d inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pri-attribs"></a> Private Attributes</h2></td></tr> <tr class="memitem:a0544d92dc334185c3a57d1947ff6dc82"><td class="memItemLeft" align="right" valign="top">QList&lt; <a class="el" href="classINWordCategory.html">INWordCategory</a> &gt;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classSimbaInsightWordscatsGetResponse.html#a0544d92dc334185c3a57d1947ff6dc82">inWordCategories</a></td></tr> <tr class="memdesc:a0544d92dc334185c3a57d1947ff6dc82"><td class="mdescLeft">&#160;</td><td class="mdescRight">词和类目基础信息对象列表 <a href="#a0544d92dc334185c3a57d1947ff6dc82">More...</a><br/></td></tr> <tr class="separator:a0544d92dc334185c3a57d1947ff6dc82"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="inherited"></a> Additional Inherited Members</h2></td></tr> <tr class="inherit_header pub_attribs_classTaoResponse"><td colspan="2" onclick="javascript:toggleInherit('pub_attribs_classTaoResponse')"><img src="closed.png" alt="-"/>&#160;Public Attributes inherited from <a class="el" href="classTaoResponse.html">TaoResponse</a></td></tr> <tr class="memitem:a49272f40b67d4bbb9c63f3f7b1ae7386 inherit pub_attribs_classTaoResponse"><td class="memItemLeft" align="right" valign="top"><a class="el" href="classParser.html">Parser</a> *&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a49272f40b67d4bbb9c63f3f7b1ae7386">responseParser</a></td></tr> <tr class="separator:a49272f40b67d4bbb9c63f3f7b1ae7386 inherit pub_attribs_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>TOP RESPONSE API: 词和类目查询 </p> <dl class="section author"><dt>Author</dt><dd>sd44 <a href="#" onclick="location.href='mai'+'lto:'+'sd4'+'4s'+'dd4'+'4@'+'yea'+'h.'+'net'; return false;">sd44s<span style="display: none;">.nosp@m.</span>dd44<span style="display: none;">.nosp@m.</span>@yeah<span style="display: none;">.nosp@m.</span>.net</a> </dd></dl> </div><h2 class="groupheader">Constructor &amp; Destructor Documentation</h2> <a class="anchor" id="aefdbce0ee7a0c514c83fb5980e7d5f9e"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">virtual SimbaInsightWordscatsGetResponse::~SimbaInsightWordscatsGetResponse </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <h2 class="groupheader">Member Function Documentation</h2> <a class="anchor" id="a49ebe465b7b04e2eab003ea3bf79641c"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">QList&lt; <a class="el" href="classINWordCategory.html">INWordCategory</a> &gt; SimbaInsightWordscatsGetResponse::getInWordCategories </td> <td>(</td> <td class="paramname"></td><td>)</td> <td> const</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a class="anchor" id="ab7c8500a489691ca739714eff575d237"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">void SimbaInsightWordscatsGetResponse::parseNormalResponse </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Implements <a class="el" href="classTaoResponse.html#a726f09ea73fc5f7e1560c097d03b9838">TaoResponse</a>.</p> </div> </div> <a class="anchor" id="ad068f500ada5ecd5b9402c67c9145ec3"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void SimbaInsightWordscatsGetResponse::setInWordCategories </td> <td>(</td> <td class="paramtype">QList&lt; <a class="el" href="classINWordCategory.html">INWordCategory</a> &gt;&#160;</td> <td class="paramname"><em>inWordCategories</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> </div> </div> <h2 class="groupheader">Member Data Documentation</h2> <a class="anchor" id="a0544d92dc334185c3a57d1947ff6dc82"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">QList&lt;<a class="el" href="classINWordCategory.html">INWordCategory</a>&gt; SimbaInsightWordscatsGetResponse::inWordCategories</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">private</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>词和类目基础信息对象列表 </p> </div> </div> <hr/>The documentation for this class was generated from the following files:<ul> <li>TaoApiCpp/response/<a class="el" href="SimbaInsightWordscatsGetResponse_8h_source.html">SimbaInsightWordscatsGetResponse.h</a></li> <li>TaoApiCpp/response/<a class="el" href="SimbaInsightWordscatsGetResponse_8cpp.html">SimbaInsightWordscatsGetResponse.cpp</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Sun Apr 14 2013 16:25:40 for Taobao Cpp/Qt SDK by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.3.1 </small></address> </body> </html>
sd44/TaobaoCppQtSDK
doc/classSimbaInsightWordscatsGetResponse.html
HTML
gpl-2.0
21,281
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ /* * Nemo * * Copyright (C) 1999, 2000 Eazel, Inc. * * Nemo is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * Nemo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. * * Authors: John Sullivan <sullivan@eazel.com> */ /* nemo-bookmark-list.h - interface for centralized list of bookmarks. */ #ifndef NEMO_BOOKMARK_LIST_H #define NEMO_BOOKMARK_LIST_H #include <libnemo-private/nemo-bookmark.h> #include <gio/gio.h> typedef struct NemoBookmarkList NemoBookmarkList; typedef struct NemoBookmarkListClass NemoBookmarkListClass; #define NEMO_TYPE_BOOKMARK_LIST nemo_bookmark_list_get_type() #define NEMO_BOOKMARK_LIST(obj) \ (G_TYPE_CHECK_INSTANCE_CAST ((obj), NEMO_TYPE_BOOKMARK_LIST, NemoBookmarkList)) #define NEMO_BOOKMARK_LIST_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST ((klass), NEMO_TYPE_BOOKMARK_LIST, NemoBookmarkListClass)) #define NEMO_IS_BOOKMARK_LIST(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE ((obj), NEMO_TYPE_BOOKMARK_LIST)) #define NEMO_IS_BOOKMARK_LIST_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE ((klass), NEMO_TYPE_BOOKMARK_LIST)) #define NEMO_BOOKMARK_LIST_GET_CLASS(obj) \ (G_TYPE_INSTANCE_GET_CLASS ((obj), NEMO_TYPE_BOOKMARK_LIST, NemoBookmarkListClass)) struct NemoBookmarkList { GObject object; GList *list; GFileMonitor *monitor; GQueue *pending_ops; GVolumeMonitor *volume_monitor; }; struct NemoBookmarkListClass { GObjectClass parent_class; void (* changed) (NemoBookmarkList *bookmarks); }; GType nemo_bookmark_list_get_type (void); NemoBookmarkList * nemo_bookmark_list_new (void); void nemo_bookmark_list_append (NemoBookmarkList *bookmarks, NemoBookmark *bookmark); void nemo_bookmark_list_delete_item_at (NemoBookmarkList *bookmarks, guint index); void nemo_bookmark_list_delete_items_with_uri (NemoBookmarkList *bookmarks, const char *uri); void nemo_bookmark_list_insert_item (NemoBookmarkList *bookmarks, NemoBookmark *bookmark, guint index); GList * nemo_bookmark_list_get_for_uri (NemoBookmarkList *bookmarks, const char *uri); guint nemo_bookmark_list_length (NemoBookmarkList *bookmarks); NemoBookmark * nemo_bookmark_list_item_at (NemoBookmarkList *bookmarks, guint index); NemoBookmark * nemo_bookmark_list_item_with_location (NemoBookmarkList *bookmarks, GFile *location, guint *index); void nemo_bookmark_list_move_item (NemoBookmarkList *bookmarks, guint index, guint destination); void nemo_bookmark_list_sort_ascending (NemoBookmarkList *bookmarks); gboolean nemo_bookmark_list_can_bookmark_location (NemoBookmarkList *list, GFile *location); #endif /* NEMO_BOOKMARK_LIST_H */
Eloston/nemo-gnome
src/nemo-bookmark-list.h
C
gpl-2.0
3,781
<?php /** * @package RedSHOP.Backend * @subpackage Table * * @copyright Copyright (C) 2008 - 2015 redCOMPONENT.com. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ defined('_JEXEC') or die; class Tablesample_detail extends JTable { public $sample_id = null; public $sample_name = null; public $published = null; public function __construct(&$db) { $this->_table_prefix = '#__redshop_'; parent::__construct($this->_table_prefix . 'catalog_sample', 'sample_id', $db); } public function bind($array, $ignore = '') { if (array_key_exists('params', $array) && is_array($array['params'])) { $registry = new JRegistry; $registry->loadArray($array['params']); $array['params'] = $registry->toString(); } return parent::bind($array, $ignore); } }
RCoomes/reynard-rs-v1.5.0.4
component/admin/tables/sample_detail.php
PHP
gpl-2.0
839
package com.jhr.jarvis.commands; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.shell.core.CommandMarker; import org.springframework.shell.core.annotation.CliCommand; import org.springframework.shell.core.annotation.CliOption; import org.springframework.shell.support.util.OsUtils; import org.springframework.shell.support.util.StringUtils; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.google.common.collect.ImmutableList; import com.jhr.jarvis.exceptions.SystemNotFoundException; import com.jhr.jarvis.model.Ship; import com.jhr.jarvis.model.StarSystem; import com.jhr.jarvis.model.Station; import com.jhr.jarvis.service.ShipService; import com.jhr.jarvis.service.StarSystemService; import com.jhr.jarvis.service.StationService; import com.jhr.jarvis.table.TableRenderer; import com.jhr.jarvis.util.DrawUtils; @Component public class SystemCommands implements CommandMarker { @Autowired private ShipService shipService; @Autowired private StarSystemService starSystemService; @Autowired private StationService stationService; @Autowired private DrawUtils drawUtils; @CliCommand(value = { "system" }, help = "usage: system <exact or starts with>") public String osystem( @CliOption(key = { "", "command" }, optionContext = "disable-string-converter availableCommands", help = "usage: system <regex>") String buffer) { String out = ""; String usage = "Usage: sys <regex>"; StarSystem starSystem; Date start = new Date(); if (StringUtils.isEmpty(buffer)) { out += drawUtils.messageBox(3, "Error: No systems matching '" + buffer + "' could be found.", usage, "Jarvis won't store a system until you've been close to it."); return out; } try { starSystem = starSystemService.findExactSystemOrientDb(buffer); } catch (SystemNotFoundException e) { List<StarSystem> systems = starSystemService.findSystemsOrientDb(buffer); if (systems.size() == 0) { out += drawUtils.messageBox(3, "Error: No systems matching '" + buffer + "' could be found.", "Jarvis won't load a system until you've been close to it."); return out; } else if (systems.size() == 1) { starSystem = systems.get(0); } else { List<Map<String, Object>> tableData = systems.stream().map(sys->{ Map<String, Object> tableRow = new HashMap<>(); tableRow.put("SYSTEM", sys.getName()); tableRow.put("X", sys.getX()); tableRow.put("Y", sys.getY()); tableRow.put("Z", sys.getZ()); return tableRow; }).collect(Collectors.toList()); out += "Systems matching '" + buffer + "'" + OsUtils.LINE_SEPARATOR; out += OsUtils.LINE_SEPARATOR + TableRenderer.renderMapDataAsTable(tableData, ImmutableList.of("SYSTEM", "X", "Y", "Z")); out += OsUtils.LINE_SEPARATOR + "executed in " + (new Date().getTime() - start.getTime())/1000.0 + " seconds."; return out; } } out += starSystemService.printStarSystemTable(starSystem); return out; } @CliCommand(value = { "path" }, help = "usage: path --from 'System Name' --to 'System Name'") public String path( @CliOption(key = { "from" }, mandatory = false, help = "Starting System") final String from, @CliOption(key = { "to" }, mandatory = false, help = "End System") final String to ) throws JsonParseException, JsonMappingException, IOException { String out = ""; String usage = "Usage: path --from 'System Name' --to 'System Name'"; Ship ship; try { ship = shipService.loadShip(); } catch (IOException e) { out += drawUtils.messageBox(3, "Error: There was an error loading your ship.", "Check your write permissions in the ../data dir."); return out; } StarSystem foundFrom = null; if (StringUtils.isEmpty(from)) { String storedSystem = starSystemService.getUserLastStoredSystem(); if (StringUtils.isEmpty(storedSystem)) { out += drawUtils.messageBox(3, "Error: Could not find 'from' system matching '" + from + "'", usage, "Example: path --from igala --to pemede", "If you have stored a station with a 'find' or 'station' command, it will default to 'from'."); return out; } try { foundFrom = starSystemService.findExactSystemOrientDb(storedSystem); } catch (SystemNotFoundException e) { out += drawUtils.messageBox(3, "Error: Could not find 'from' system matching '" + from + "'", usage, "Example: path --from igala --to pemede", "If you have stored a station with a 'find' or 'station' command, it will default to 'from'."); return out; } } else { try { foundFrom = starSystemService.findUniqueSystemOrientDb(from); } catch (SystemNotFoundException e) { out += drawUtils.messageBox(3, "Error: Could not find 'from' system matching '" + from + "'", usage, "Example: path --from igala --to pemede"); return out; } } StarSystem foundTo = null; if (StringUtils.isEmpty(to)) { out += drawUtils.messageBox(3, "Error: Could not find 'to' system matching '" + to + "'", usage, "Example: path --from igala --to pemede"); return out; } try { foundTo = starSystemService.findUniqueSystemOrientDb(to); } catch (SystemNotFoundException e) { out += drawUtils.messageBox(3, "Error: Could not find 'to' system matching '" + to + "'", usage, "Example: path --from igala --to pemede"); return out; } return starSystemService.calculateShortestPathBetweenSystems(ship, foundFrom.getName(), foundTo.getName()); } }
jrosocha/jarvisCli
src/main/java/com/jhr/jarvis/commands/SystemCommands.java
Java
gpl-2.0
7,281
module Katello class ProductsController < Katello::ApplicationController respond_to :html, :js before_action :find_product, :only => [:available_repositories, :toggle_repository] before_action :find_provider, :only => [:available_repositories, :toggle_repository] before_action :find_content, :only => [:toggle_repository] include ForemanTasks::Triggers def section_id 'contents' end def available_repositories if @product.custom? render_bad_parameters _('Repository sets are not available for custom products.') else task = sync_task(::Actions::Katello::RepositorySet::ScanCdn, @product, params[:content_id]) repos = task.output[:results] repos = exclude_rolling_kickstart_repos(repos) repos = available_synced_repos(repos, params[:content_id]) locals = {:scan_cdn => task, :repos => repos, :error_message => nil} locals[:error_message => task_error(task)] if task.result == 'warning' render :partial => 'katello/providers/redhat/repos', :locals => locals end end def toggle_repository action_class = if params[:repo] == '1' ::Actions::Katello::RepositorySet::EnableRepository else ::Actions::Katello::RepositorySet::DisableRepository end task = sync_task(action_class, @product, @content, substitutions) render :json => { :task_id => task.id } rescue => e render :partial => 'katello/providers/redhat/enable_errors', :locals => { :error_message => e.message}, :status => 500 end private def find_provider @provider = @product.provider if @product #don't trust the provider_id coming in if we don't need it @provider ||= Provider.find(params[:provider_id]) end def find_product @product = Product.find(params[:id]) end def find_content if (product_content = @product.product_content_by_id(params[:content_id])) @content = product_content.content else fail HttpErrors::NotFound, _("Couldn't find content '%s'") % params[:content_id] end end def substitutions params.permit(:basearch, :releasever, :registry_name).to_h end def task_error(task) task.failed_steps.first.action(task.execution_plan).steps.map { |s| s.try(:error).try(:message) }.reject(&:blank?).join(', ') end def exclude_rolling_kickstart_repos(repos) repos.select do |repo| if repo[:path].include?('kickstart') variants = ['Server', 'Client', 'ComputeNode', 'Workstation'] has_variant = variants.any? { |v| repo[:substitutions][:releasever].try(:include?, v) } has_variant ? repo[:enabled] : true else true end end end def available_synced_repos(repos, content_id) @product.repositories.in_default_view.where(:content_id => content_id).find_each do |product_repo| found = repos.detect do |repo| product_repo.id == repo[:repository_id] end unless found repos << { :repo_name => product_repo.name, :path => product_repo.url, :pulp_id => product_repo.pulp_id, :content_id => product_repo.content_id, :substitutions => { :basearch => product_repo.arch, :releasever => product_repo.minor }, :enabled => true, :promoted => product_repo.promoted?, :registry_name => product_repo.docker_upstream_name } end end repos end end end
stbenjam/katello
app/controllers/katello/products_controller.rb
Ruby
gpl-2.0
3,669
<?php /* +--------------------------------------------------------------------+ | CiviCRM version 1.8 | +--------------------------------------------------------------------+ | Copyright CiviCRM LLC (c) 2004-2007 | +--------------------------------------------------------------------+ | This file is a part of CiviCRM. | | | | CiviCRM is free software; you can copy, modify, and distribute it | | under the terms of the Affero General Public License Version 1, | | March 2002. | | | | CiviCRM 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 Affero General Public License for more details. | | | | You should have received a copy of the Affero General Public | | License along with this program; if not, contact CiviCRM LLC | | at info[AT]civicrm[DOT]org. If you have questions about the | | Affero General Public License or the licensing of CiviCRM, | | see the CiviCRM license FAQ at http://civicrm.org/licensing | +--------------------------------------------------------------------+ */ /** * * * @package CRM * @copyright CiviCRM LLC (c) 2004-2007 * $Id$ * */ class CRM_Core_BAO_CustomQuery { const PREFIX = 'custom_value_'; /** * the set of custom field ids * * @var array */ protected $_ids; /** * the select clause * * @var array */ public $_select; /** * the name of the elements that are in the select clause * used to extract the values * * @var array */ public $_element; /** * the tables involved in the query * * @var array */ public $_tables; public $_whereTables; /** * the where clause * * @var array */ public $_where; /** * The english language version of the query * * @var array */ public $_qill; /** * The cache to translate the option values into labels * * @var array */ public $_options; /** * The custom fields information * * @var array */ protected $_fields; /** * This stores custom data group types and tables that it extends * * @var array * @static */ static $extendsMap = array( 'Contact' => 'civicrm_contact', 'Individual' => 'civicrm_contact', 'Household' => 'civicrm_contact', 'Organization' => 'civicrm_contact', 'Contribution' => 'civicrm_contribution', 'Membership' => 'civicrm_membership', 'Participant' => 'civicrm_participant', 'Group' => 'civicrm_group', 'Relationship' => 'civicrm_relationship', 'Event' => 'civicrm_event', 'Activity' => 'civicrm_activity', 'Meeting' => 'civicrm_meeting', 'Phonecall' => 'civicrm_phonecall' ); /** * class constructor * * Takes in a set of custom field ids andsets up the data structures to * generate a query * * @param array $ids the set of custom field ids * * @access public */ function __construct( $ids ) { $this->_ids =& $ids; $this->_select = array( ); $this->_element = array( ); $this->_tables = array( ); $this->_whereTables = array( ); $this->_where = array( ); $this->_qill = array( ); $this->_options = array( ); $this->_fields = array( ); if ( empty( $this->_ids ) ) { return; } // initialize the field array $tmpArray = array_keys( $this->_ids ); $query = 'select * from civicrm_custom_field where is_active = 1 AND id IN ( ' . implode( ',', $tmpArray ) . ' ) '; $dao =& CRM_Core_DAO::executeQuery( $query, CRM_Core_DAO::$_nullArray ); $optionIds = array( ); while ( $dao->fetch( ) ) { // get the group dao to figure which class this custom field extends $extends =& CRM_Core_DAO::getFieldValue( 'CRM_Core_DAO_CustomGroup', $dao->custom_group_id, 'extends' ); $extendsTable = self::$extendsMap[$extends]; $this->_fields[$dao->id] = array( 'id' => $dao->id, 'label' => $dao->label, 'extends' => $extendsTable, 'data_type' => $dao->data_type, 'html_type' => $dao->html_type, 'is_search_range' => $dao->is_search_range, 'db_field' => CRM_Core_BAO_CustomValue::typeToField( $dao->data_type ) ); // store it in the options cache to make things easier // during option lookup $this->_options[$dao->id] = array( ); $this->_options[$dao->id]['attributes'] = array( 'label' => $dao->label, 'data_type' => $dao->data_type, 'html_type' => $dao->html_type ); if ( $dao->html_type == 'CheckBox' || $dao->html_type == 'Radio' || $dao->html_type == 'Select' || $dao->html_type == 'Multi-Select' ) { $optionIds[] = $dao->id; } } // build the cache for custom values with options (label => value) if ( ! empty( $optionIds ) ) { $optionIdString = implode( ',', $optionIds ); $query = " SELECT entity_id, label, value FROM civicrm_custom_option WHERE entity_id IN ( $optionIdString ) AND entity_table = 'civicrm_custom_field' "; $dao =& CRM_Core_DAO::executeQuery( $query, CRM_Core_DAO::$_nullArray ); while ( $dao->fetch( ) ) { $dataType = $this->_fields[$dao->entity_id]['data_type']; if ( $dataType == 'Int' || $dataType == 'Float' ) { $num = round($dao->value, 2); $this->_options[$dao->entity_id]["$num"] = $dao->label; } else { $this->_options[$dao->entity_id][$dao->value] = $dao->label; } } } } /** * generate the select clause and the associated tables * for the from clause * * @param NULL * @return void * @access public */ function select( ) { if ( empty( $this->_fields ) ) { return; } foreach ( $this->_fields as $id => $field ) { $name = self::PREFIX . $field['id']; $fieldName = 'custom_' . $field['id']; $this->_select["{$name}_id"] = "{$name}.id as {$name}_id"; $this->_element["{$name}_id"] = 1; $this->_select[$fieldName] = $name . '.' . $field['db_field'] . " as $fieldName"; $this->_element[$fieldName] = 1; if ( $field['extends'] == 'civicrm_contact' ) { $this->_tables[$name] = "\nLEFT JOIN civicrm_custom_value $name ON $name.custom_field_id = " . $field['id'] . " AND $name.entity_table = 'civicrm_contact' AND $name.entity_id = contact_a.id "; if ( $this->_ids[$id] ) { $this->_whereTables[$name] = $this->_tables[$name]; } } else if ( $field['extends'] == 'civicrm_contribution' ) { $this->_tables[$name] = "\nLEFT JOIN civicrm_custom_value $name ON $name.custom_field_id = " . $field['id'] . " AND $name.entity_table = 'civicrm_contribution' AND $name.entity_id = civicrm_contribution.id "; $this->_whereTables['civicrm_contribution'] = $this->_tables['civicrm_contribution'] = 1; if ( $this->_ids[$id] ) { $this->_whereTables[$name] = $this->_tables[$name]; } } else if ( $field['extends'] == 'civicrm_participant' ) { $this->_tables[$name] = "\nLEFT JOIN civicrm_custom_value $name ON $name.custom_field_id = " . $field['id'] . " AND $name.entity_table = 'civicrm_participant' AND $name.entity_id = civicrm_participant.id "; $this->_whereTables['civicrm_participant'] = $this->_tables['civicrm_participant'] = 1; if ( $this->_ids[$id] ) { $this->_whereTables[$name] = $this->_tables[$name]; } } else if ( $field['extends'] == 'civicrm_membership' ) { $this->_tables[$name] = "\nLEFT JOIN civicrm_custom_value $name ON $name.custom_field_id = " . $field['id'] . " AND $name.entity_table = 'civicrm_membership' AND $name.entity_id = civicrm_membership.id "; $this->_whereTables['civicrm_membership'] = $this->_tables['civicrm_membership'] = 1; if ( $this->_ids[$id] ) { $this->_whereTables[$name] = $this->_tables[$name]; } } } } /** * generate the where clause and also the english language * equivalent * * @param NULL * * @return void * * @access public */ function where( ) { //CRM_Core_Error::debug( 'fld', $this->_fields ); //CRM_Core_Error::debug( 'ids', $this->_ids ); foreach ( $this->_ids as $id => $values ) { // Fixed for Isuue CRM 607 if ( CRM_Utils_Array::value( $id, $this->_fields ) === null || ! $values ) { continue; } foreach ( $values as $tuple ) { list( $name, $op, $value, $grouping, $wildcard ) = $tuple; // fix $value here to escape sql injection attacks $field = $this->_fields[$id]; $qillValue = CRM_Core_BAO_CustomField::getDisplayValue( $value, $id, $this->_options ); if ( ! is_array( $value ) ) { $value = addslashes(trim($value)); } switch ( $field['data_type'] ) { case 'String': $sql = 'LOWER(' . self::PREFIX . $field['id'] . '.char_data) '; // if we are coming in from listings, for checkboxes the value is already in the right format and is NOT an array if ( is_array( $value ) ) { require_once 'CRM/Core/BAO/CustomOption.php'; //ignoring $op value for checkbox and multi select $sqlValue = array( ); if ($field['html_type'] == 'CheckBox') { foreach ( $value as $k => $v ) { $sqlValue[] = "( $sql like '%" . CRM_Core_BAO_CustomOption::VALUE_SEPERATOR . $k . CRM_Core_BAO_CustomOption::VALUE_SEPERATOR . "%' ) "; } $this->_where[$grouping][] = implode( ' AND ', $sqlValue ); $this->_qill[$grouping][] = "$field[label] $op $qillValue"; } else { // for multi select foreach ( $value as $k => $v ) { $sqlValue[] = "( $sql like '%" . CRM_Core_BAO_CustomOption::VALUE_SEPERATOR . $v . CRM_Core_BAO_CustomOption::VALUE_SEPERATOR . "%' ) "; } $this->_where[$grouping][] = implode( ' AND ', $sqlValue ); $this->_qill[$grouping][] = "$field[label] $op $qillValue"; } } else { if ( $field['is_search_range'] && is_array( $value ) ) { $this->searchRange( $field['id'], $field['label'], 'char_data', $value, $grouping ); } else { $val = CRM_Utils_Type::escape( strtolower(trim($value)), 'String' ); $this->_where[$grouping][] = "{$sql} {$op} '{$val}'"; $this->_qill[$grouping][] = "$field[label] $op $qillValue"; } } continue; case 'Int': if ( $field['is_search_range'] && is_array( $value ) ) { $this->searchRange( $field['id'], $field['label'], 'int_data', $value, $grouping ); } else { $this->_where[$grouping][] = self::PREFIX . $field['id'] . ".int_data {$op} " . CRM_Utils_Type::escape( $value, 'Integer' ); $this->_qill[$grouping][] = $field['label'] . " $op $value"; } continue; case 'Boolean': $value = (int ) $value; $value = ( $value == 1 ) ? 1 : 0; $this->_where[$grouping][] = self::PREFIX . $field['id'] . ".int_data {$op} " . CRM_Utils_Type::escape( $value, 'Integer' ); $value = $value ? ts('Yes') : ts('No'); $this->_qill[$grouping][] = $field['label'] . " {$op} {$value}"; continue; case 'Float': if ( $field['is_search_range'] && is_array( $value ) ) { $this->searchRange( $field['id'], $field['label'], 'float_data', $value, $grouping ); } else { $this->_where[$grouping][] = self::PREFIX . $field['id'] . ".float_data {$op} " . CRM_Utils_Type::escape( $value, 'Float' ); $this->_qill[$grouping][] = $field['label'] . " {$op} {$value}"; } continue; case 'Money': if ( $field['is_search_range'] && is_array( $value ) ) { foreach( $value as $key => $val ) { require_once "CRM/Utils/Rule.php"; $moneyFormat = CRM_Utils_Rule::cleanMoney($value[$key]); $value[$key] = $moneyFormat; } $this->searchRange( $field['id'], $field['label'], 'decimal_data', $value, $grouping ); } else { $moneyFormat = CRM_Utils_Rule::cleanMoney($value); $value = $moneyFormat; $this->_where[$grouping][] = self::PREFIX . $field['id'] . ".decimal_data {$op} " . CRM_Utils_Type::escape( $value, 'Float' ); $this->_qill[$grouping][] = $field['label'] . " {$op} {$value}"; } continue; case 'Memo': $val = CRM_Utils_Type::escape( strtolower(trim($value)), 'String' ); $this->_where[$grouping][] = self::PREFIX . $field['id'] . ".memo_data {$op} '{$val}'"; $this->_qill[$grouping][] = "$field[label] $op $value"; continue; case 'Date': $fromValue = CRM_Utils_Array::value( 'from', $value ); $toValue = CRM_Utils_Array::value( 'to' , $value ); if ( ! $fromValue && ! $toValue ) { $date = CRM_Utils_Date::format( $value ); if ( ! $date ) { continue; } $this->_where[$grouping][] = self::PREFIX . $field['id'] . ".date_data {$op} {$date}"; $date = CRM_Utils_Date::format( $value, '-' ); $this->_qill[$grouping][] = $field['label'] . " {$op} " . CRM_Utils_Date::customFormat( $date ); } else { $fromDate = CRM_Utils_Date::format( $fromValue ); $toDate = CRM_Utils_Date::format( $toValue ); if ( ! $fromDate && ! $toDate ) { continue; } if ( $fromDate ) { $this->_where[$grouping][] = self::PREFIX . $field['id'] . ".date_data >= $fromDate"; $fromDate = CRM_Utils_Date::format( $fromValue, '-' ); $this->_qill[$grouping][] = $field['label'] . ' >= ' . CRM_Utils_Date::customFormat( $fromDate ); } if ( $toDate ) { $this->_where[$grouping][] = self::PREFIX . $field['id'] . ".date_data <= $toDate"; $toDate = CRM_Utils_Date::format( $toValue, '-' ); $this->_qill[$grouping][] = $field['label'] . ' <= ' . CRM_Utils_Date::customFormat( $toDate ); } } continue; case 'StateProvince': $states =& CRM_Core_PseudoConstant::stateProvince(); if ( ! is_numeric( $value ) ) { $value = array_search( $value, $states ); } if ( $value ) { $this->_where[$grouping][] = self::PREFIX . $field['id'] . ".int_data {$op} " . CRM_Utils_Type::escape( $value, 'Int' ); $this->_qill[$grouping][] = $field['label'] . " {$op} {$states[$value]}"; } continue; case 'Country': $countries =& CRM_Core_PseudoConstant::country(); if ( ! is_numeric( $value ) ) { $value = array_search( $value, $countries ); } if ( $value ) { $this->_where[$grouping][] = self::PREFIX . $field['id'] . ".int_data {$op} " . CRM_Utils_Type::escape( $value, 'Int' ); $this->_qill[$grouping][] = $field['label'] . " {$op} {$countries[$value]}"; } continue; } } //CRM_Core_Error::debug( 'w', $this->_where ); } } /** * function that does the actual query generation * basically ties all the above functions together * * @param NULL * @return array array of strings * @access public */ function query( ) { $this->select( ); $this->where( ); $whereStr = null; if ( ! empty( $this->_where ) ) { $clauses = array( ); foreach ( $this->_where as $grouping => $values ) { if ( ! empty( $values ) ) { $clauses[] = implode( ' AND ', $values ); } } if ( ! empty( $clauses ) ) { $whereStr = implode( ' OR ', $clauses ); } } return array( implode( ' , ' , $this->_select ), implode( ' ' , $this->_tables ), $whereStr ); } function searchRange( &$id, &$label, $type, &$value, &$grouping ) { $qill = array( ); $crmType = CRM_Core_BAO_CustomValue::fieldToType( $type ); if ( isset( $value['from'] ) ) { $val = CRM_Utils_Type::escape( $value['from'], $crmType ); if ( $type == 'char_data' ) { $this->_where[$grouping][] = self::PREFIX . "$id.$type >= '$val'"; } else { $this->_where[$grouping][] = self::PREFIX . "$id.$type >= $val"; } $qill[] = ts( 'greater than or equal to "%1"', array( 1 => $value['from'] ) ); } if ( isset( $value['to'] ) ) { $val = CRM_Utils_Type::escape( $value['to'], $crmType ); if ( $type == 'char_data' ) { $this->_where[$grouping][] = self::PREFIX . "$id.$type <= '$val'"; } else { $this->_where[$grouping][] = self::PREFIX . "$id.$type <= $val"; } $qill[] = ts( 'less than or equal to "%1"', array( 1 => $value['to'] ) ); } if ( ! empty( $qill ) ) { $this->_qill[$grouping][] = $label . ' - ' . implode( ' ' . ts('and') . ' ', $qill ); } } } ?>
zakiya/Peoples-History
sites/all/modules/civicrm/CRM/Core/BAO/CustomQuery.php
PHP
gpl-2.0
21,723
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Authors : David Castellanos <dcastellanos@indra.es> # # Copyright (c) 2012, Telefonica Móviles España S.A.U. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. # """ TGCM Logging is a daemon designed to gather TGCM logs """ __version__ = '0.1' __author__ = 'David Castellanos <dcastellanos@indra.es>'
tgcmteam/tgcmlinux
src/tgcm/contrib/tgcm-logging/src/tgcmlogging/__init__.py
Python
gpl-2.0
1,034
<include file="Public:header" /> <div id="main" class="main" > <div class="content"> <div class="title">{$Think.lang._EDIT_GROUP_} [ <a href="__URL__">{$Think.lang._BACK_TO_LIST_}</a> ]</div> <form method='post' id="form1" > <table cellpadding=3 cellspacing=3> <tr> <td class="tRight" >{$Think.lang._EDIT_NAME_}</td> <td class="tLeft" ><input type="text" class="medium bLeftRequire" check='^\S+$' warning="{$Think.lang._NAME_NOT_EMPTY_}" name="name" value="{$vo.name}"></td> </tr> <tr> <td class="tRight tTop">{$Think.lang._EDIT_TITLE_}</td> <td class="tLeft"><input type="text" class="medium bLeftRequire" name="title" value="{$vo.title}"></td> </tr> <tr> <td class="tRight">{$Think.lang._EDIT_SHOW_}</td> <td class="tLeft"><SELECT class="small bLeft" name="show"> <option <eq name="vo.status" value="1" >selected</eq> value="1">{$Think.lang._YES_}</option> <option <eq name="vo.status" value="0" >selected</eq> value="0">{$Think.lang._NO_}</option> </SELECT></td> </tr> <tr> <td class="tRight">{$Think.lang._EDIT_STATUS_}</td> <td class="tLeft"><SELECT class="small bLeft" name="status"> <option <eq name="vo.status" value="1" >selected</eq> value="1">{$Think.lang._STATUS_ON_}</option> <option <eq name="vo.status" value="0" >selected</eq> value="0">{$Think.lang._STATUS_OFF_}</option> </SELECT></td> </tr> <tr> <td></td> <td class="center"><div style="width:100%;margin:5px"> <input type="hidden" name="id" value="{$vo.id}"> <input type="hidden" name="ajax" value="1"> <div class="impBtn fLeft"><input type="button" value="{$Think.lang._SAVE_}" onclick="ThinkAjax.sendForm('form1','__URL__/update/','tips')" class="save imgButton"></div> <div class="impBtn fRig"><input type="reset" class="reset imgButton" value="{$Think.lang._CANCEL_}" ></div> </div></td> </tr> </table> </form> </div> </div>
zhenghaiyong/BioInfo_CAHEC-VRL-ISM
cahec/VRL/Tpl/Group/edit.html
HTML
gpl-2.0
1,827
Grailbird.data.tweets_2010_03 = [ { "source" : "\u003Ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003ETwitter Web Client\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "10548776482", "text" : "Published a new blog post: Of Themes and Winnings http:\/\/bit.ly\/cr7moP", "id" : 10548776482, "created_at" : "2010-03-16 00:00:00 +0000", "user" : { "name" : "Jamie Harrell", "screen_name" : "peoii", "protected" : false, "id_str" : "38397135", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/567774981887508480\/kEDNPXn7_normal.jpeg", "id" : 38397135, "verified" : false } }, { "source" : "\u003Ca href=\"http:\/\/www.google.com\/\" rel=\"nofollow\"\u003EGoogle\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "10304534365", "text" : "I favorited a YouTube video -- Academy Award Winning Movie Trailer http:\/\/youtu.be\/nFicqklGuB0?a", "id" : 10304534365, "created_at" : "2010-03-11 00:00:00 +0000", "user" : { "name" : "Jamie Harrell", "screen_name" : "peoii", "protected" : false, "id_str" : "38397135", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/567774981887508480\/kEDNPXn7_normal.jpeg", "id" : 38397135, "verified" : false } }, { "source" : "\u003Ca href=\"http:\/\/www.google.com\/\" rel=\"nofollow\"\u003EGoogle\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "10000863331", "text" : "I favorited a YouTube video -- Rise Against - Audience Of One http:\/\/youtu.be\/4MjLKjPc7q8?a", "id" : 10000863331, "created_at" : "2010-03-05 00:00:00 +0000", "user" : { "name" : "Jamie Harrell", "screen_name" : "peoii", "protected" : false, "id_str" : "38397135", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/567774981887508480\/kEDNPXn7_normal.jpeg", "id" : 38397135, "verified" : false } }, { "source" : "\u003Ca href=\"http:\/\/www.google.com\/\" rel=\"nofollow\"\u003EGoogle\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "9992930940", "text" : "I favorited a YouTube video -- Capercaillie - Heart of the Highland http:\/\/youtu.be\/PZEIKnKLfVM?a", "id" : 9992930940, "created_at" : "2010-03-04 00:00:00 +0000", "user" : { "name" : "Jamie Harrell", "screen_name" : "peoii", "protected" : false, "id_str" : "38397135", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/567774981887508480\/kEDNPXn7_normal.jpeg", "id" : 38397135, "verified" : false } }, { "source" : "\u003Ca href=\"http:\/\/www.google.com\/\" rel=\"nofollow\"\u003EGoogle\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "9992981333", "text" : "I favorited a YouTube video -- Regina Spektor - \"Us\" [OFFICIAL VIDEO] http:\/\/youtu.be\/x_13MYoqULM?a", "id" : 9992981333, "created_at" : "2010-03-04 00:00:00 +0000", "user" : { "name" : "Jamie Harrell", "screen_name" : "peoii", "protected" : false, "id_str" : "38397135", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/567774981887508480\/kEDNPXn7_normal.jpeg", "id" : 38397135, "verified" : false } } ]
peoii/twit_archive
data/js/tweets/2010_03.js
JavaScript
gpl-2.0
3,659
<?php /** * fvcn-admin-dashboard.php * * Admin Dashboard * * @package FV Community News * @subpackage Admin Dashboard * @author Frank Verhoeven <info@frank-verhoeven.com> */ if (!defined('ABSPATH')) { exit; } /** * FvCommunityNews_Admin_Dashboard * */ class FvCommunityNews_Admin_Dashboard { /** * __construct() * * @version 20120729 * @return void */ public function __construct() { $this->registerWidgets(); } /** * registerWidgets() * * @version 20120719 * @return FvCommunityNews_Admin_Dashboard */ public function registerWidgets() { add_action('wp_dashboard_setup', array(new FvCommunityNews_Admin_Dashboard_Widget_RecentPosts(), 'register')); do_action('fvcn_register_dashboard_widgets'); return $this; } } /** * FvCommunityNews_Admin_Dashboard_Widget_RecentPosts_Interface * */ interface FvCommunityNews_Admin_Dashboard_Widget_RecentPosts_Interface { /** * register() * * @return FvCommunityNews_Admin_Dashboard_Widget_RecentPosts_Interface */ public function register(); /** * widget() * * @return void */ public function widget(); } /** * FvCommunityNews_Admin_Dashboard_Widget_RecentPosts * */ class FvCommunityNews_Admin_Dashboard_Widget_RecentPosts implements FvCommunityNews_Admin_Dashboard_Widget_RecentPosts_Interface { /** * __construct() * * @version 20120729 * @return void */ public function __construct() { add_action('fvcn_admin_enqueue_scripts', array($this, 'enqueueScripts')); add_action('fvcn_admin_head', array($this, 'dashboardHead')); add_action('wp_ajax_fvcn-dashboard-widget-rp-ajax', array($this, 'ajaxResponse')); $this->response(); } /** * enqueueScripts() * * @version 20120729 * @return void */ public function enqueueScripts() { wp_enqueue_script( 'fvcn-dashboard-widget-rp-js', FvCommunityNews_Registry::get('adminUrl') . 'js/dashboard.js', array('jquery'), '20120721' ); wp_localize_script( 'fvcn-dashboard-widget-rp-js', 'FvCommunityNewsAdminDashboardOptions', array( 'ajaxurl' => esc_url( admin_url('admin-ajax.php') ), 'action' => 'fvcn-dashboard-widget-rp-ajax', 'nonce' => wp_create_nonce('fvcn-dashboard') ) ); do_action('fvcn_enqueue_dashboard_widget_recent_posts_scripts'); } /** * dashboardHead() * * @version 20120729 * @return void */ public function dashboardHead() { ?> <style type="text/css"> #fvcn-dashboard-recent-posts .inside { margin: 0 auto; padding: 0; } #fvcn-dashboard-recent-posts .inside .dashboard-widget-control-form { padding: 0 10px 10px; } #fvcn-dashboard-recent-posts-list .fvcn-post { clear: both; padding: 10px; border-top: 1px solid #dfdfdf; } #fvcn-dashboard-recent-posts-list .fvcn-post:first-child { border-top: none; } #fvcn-dashboard-recent-posts-list .fvcn-post.pending { background-color: #ffffe0; } #fvcn-dashboard-recent-posts-list .fvcn-post .avatar, #fvcn-dashboard-recent-posts-list .fvcn-post .wp-post-image { float: left; margin: 0 10px 10px 0; } #fvcn-dashboard-recent-posts-list .fvcn-post .fvcn-dashboard-post-wrap blockquote { margin: 0 auto; } #fvcn-dashboard-recent-posts-list .fvcn-post .fvcn-row-actions { visibility: hidden; margin: 3px 0 0; } #fvcn-dashboard-recent-posts-list .fvcn-post:hover .fvcn-row-actions { visibility: visible; } #fvcn-dashboard-recent-posts-list .fvcn-post .fvcn-row-actions .publish a { color: #006505; } #fvcn-dashboard-recent-posts-list .fvcn-post .fvcn-row-actions .unpublish a { color: #d98500; } #fvcn-dashboard-recent-posts-list .fvcn-post .fvcn-row-actions .spam a { color: #bc0b0b; } #fvcn-dashboard-recent-posts-list .fvcn-post .fvcn-row-actions .trash a { color: #bc0b0b; } #fvcn-dashboard-recent-posts-list .fvcn-post .fvcn-row-actions .trash a:hover, #fvcn-dashboard-recent-posts-list .fvcn-post .fvcn-row-actions .spam a:hover, #fvcn-dashboard-recent-posts-list .fvcn-post .fvcn-row-actions .unpublish a:hover, #fvcn-dashboard-recent-posts-list .fvcn-post .fvcn-row-actions .publish a:hover { color: #d54e21; } #fvcn-dashboard-recent-posts-list .fvcn-post.approved .fvcn-row-actions .publish, #fvcn-dashboard-recent-posts-list .fvcn-post.pending .fvcn-row-actions .unpublish { display: none; } #fvcn-dashboard-view-links { margin: 10px 10px; } </style> <?php do_action('fvcn_dashboard_widget_recent_posts_styles'); } /** * response() * * @version 20120729 * @return void */ public function response() { if (!isset($_GET['action'], $_GET['post_id']) || false === strpos($_GET['action'], 'fvcn')) { return; } $this->_updatePostStatus($_GET['post_id'], $_GET['action']); } /** * ajaxResponse() * * @version 20120729 * @return void */ public function ajaxResponse() { $success = false; $message = false; if (!isset($_POST['nonce'], $_POST['post_id'], $_POST['fvcn_action']) || !wp_verify_nonce($_POST['nonce'], 'fvcn-dashboard') || !is_numeric($_POST['post_id']) || !fvcn_get_post($_POST['post_id']) || !current_user_can('edit_posts', $_POST['post_id'])) { $message = __('Are you sure?', 'fvcn'); } if (false === $message) { $success = $this->_updatePostStatus($_POST['post_id'], $_POST['fvcn_action']); if (false === $success) { $message = __('Invallid action', 'fvcn'); } } if (false === $success) { $response = array( 'success' => false, 'message' => $message ); } else { $response = array( 'success' => true ); } echo json_encode( $response ); exit; } /** * _updatePostStatus() * * @version 20120729 * @param string $action * @return bool */ protected function _updatePostStatus($postId, $action) { switch ($action) { case 'fvcn_toggle_post_spam_status' : check_admin_referer('fvcn-spam-post_' . $postId); return fvcn_is_post_spam($postId) ? fvcn_publish_post($postId) : fvcn_spam_post($postId); break; case 'fvcn_toggle_post_publish_status' : check_admin_referer('fvcn-publish-post_' . $postId); return fvcn_is_post_published($postId) ? fvcn_unpublish_post($postId) : fvcn_publish_post($postId); break; default: return false; } } /** * register() * * @version 20120719 * @return FvCommunityNews_Admin_Dashboard_Widget_RecentPosts */ public function register() { if (current_user_can('edit_posts')) { wp_add_dashboard_widget( 'fvcn-dashboard-recent-posts', __('Recent Community News', 'fvcn'), array($this, 'widget'), array($this, 'control') ); } return $this; } /** * widget() * * @version 20120721 * @return void */ public function widget() { $options = array( 'posts_per_page' => fvcn_get_option('_fvcn_dashboard_rp_num'), 'post_status' => fvcn_get_public_post_status() . ',' . fvcn_get_pending_post_status() ); if (fvcn_has_posts($options)) : $alt = 'odd alt'; ?> <div id="fvcn-dashboard-recent-posts-list"> <?php while (fvcn_posts()) : fvcn_the_post(); ?> <?php $class = 'fvcn-post '; if (fvcn_get_pending_post_status() == fvcn_get_post_status()) { $class .= 'pending '; } else { $class .= 'approved '; } $class .= $alt; ?> <div id="fvcn-post-<?php fvcn_post_id(); ?>" class="<?php echo $class; ?>"> <?php if (fvcn_has_post_thumbnail()) { fvcn_post_thumbnail(0, array(50, 50)); } else { fvcn_post_author_avatar(0, 50); } ?> <div class="fvcn-dashboard-post-wrap"> <h4 class="fvcn-post-title"> <?php if (fvcn_has_post_link()) : ?> <a href="<?php fvcn_post_link(); ?>"><?php fvcn_post_title(); ?></a> <?php else : ?> <?php fvcn_post_title(); ?> <?php endif; ?> <a href="<?php fvcn_post_permalink(); ?>">#</a> </h4> <blockquote><?php fvcn_post_excerpt(); ?></blockquote> <p class="fvcn-row-actions"> <?php $publish_uri = esc_url( wp_nonce_url( add_query_arg(array( 'post_id' => fvcn_get_post_id(), 'action' => 'fvcn_toggle_post_publish_status' ), 'index.php'), 'fvcn-publish-post_' . fvcn_get_post_id())); $edit_uri = esc_url( add_query_arg(array( 'post' => fvcn_get_post_id(), 'action' => 'edit' ), 'post.php')); $spam_uri = esc_url( wp_nonce_url( add_query_arg(array( 'post_id' => fvcn_get_post_id(), 'action' => 'fvcn_toggle_post_spam_status' ), 'index.php'), 'fvcn-spam-post_' . fvcn_get_post_id())); $trash_uri = esc_url( wp_nonce_url( add_query_arg(array( 'post' => fvcn_get_post_id(), 'action' => 'trash' ), 'post.php'), 'trash-' . fvcn_get_post_type() . '_' . fvcn_get_post_id())); ?> <span class="publish"><a href="<?php echo $publish_uri; ?>"><?php _e('Publish', 'fvcn'); ?></a></span> <span class="unpublish"><a href="<?php echo $publish_uri; ?>"><?php _e('Unpublish', 'fvcn'); ?></a></span> <span class="edit"> | <a href="<?php echo $edit_uri; ?>"><?php _e('Edit', 'fvcn'); ?></a></span> <span class="spam"> | <a href="<?php echo $spam_uri; ?>"><?php _e('Spam', 'fvcn'); ?></a></span> <span class="trash"> | <a href="<?php echo $trash_uri; ?>"><?php _e('Trash', 'fvcn'); ?></a></span> </p> </div> </div> <?php $alt = ($alt == 'even' ? 'odd alt' : 'even'); endwhile; ?> </div> <p id="fvcn-dashboard-view-links"> <a href="edit.php?post_type=<?php fvcn_post_type(); ?>"><?php _e('View All', 'fvcn'); ?></a> </p> <?php else : ?> <p><?php _e('No posts found, yet.', 'fvcn'); ?></p> <?php endif; } /** * control() * * @version 20120729 * @return void */ public function control() { if ('post' == strtolower($_SERVER['REQUEST_METHOD']) && isset($_POST['_fvcn_dashboard_rp'])) { update_option('_fvcn_dashboard_rp_num', min( max((int) $_POST['_fvcn_dashboard_rp_num'], 1), 30)); } ?> <p> <label for="_fvcn_dashboard_rp_num"><?php _e('Number of posts to show:', 'fvcn'); ?></label> <input type="text" name="_fvcn_dashboard_rp_num" id="_fvcn_dashboard_rp_num" value="<?php echo fvcn_form_option('_fvcn_dashboard_rp_num'); ?>" size="3" /> <small><?php _e('(1 - 30)', 'fvcn'); ?></small> </p> <input type="hidden" name="_fvcn_dashboard_rp" id="_fvcn_dashboard_rp" value="1" /> <?php } }
tresemece/AndesMills
wp-content/plugins/fv-community-news/fvcn-admin/fvcn-admin-dashboard.php
PHP
gpl-2.0
10,681
/* * ngIRCd -- The Next Generation IRC Daemon * Copyright (c)2001-2019 Alexander Barton (alex@barton.de) and Contributors. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * Please read the file COPYING, README and AUTHORS for more information. */ #include "portab.h" /** * @file * Logging functions */ #include <assert.h> #ifdef PROTOTYPES # include <stdarg.h> #else # include <varargs.h> #endif #include <stdio.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #ifdef SYSLOG # include <syslog.h> #endif #include "ngircd.h" #include "conn.h" #include "channel.h" #include "irc-write.h" #include "conf.h" #include "log.h" static bool Is_Daemon; static void Log_Message(int Level, const char *msg) { if (!Is_Daemon) { /* log to console */ fprintf(stdout, "[%ld:%d %4ld] %s\n", (long)getpid(), Level, (long)(time(NULL) - NGIRCd_Start), msg); fflush(stdout); } #ifdef SYSLOG else { syslog(Level, "%s", msg); } #endif } /** * Initialitze logging. * This function is called before the configuration file is read in. * * @param Daemon_Mode Set to true if ngIRCd is running as daemon. */ GLOBAL void Log_Init(bool Daemon_Mode) { Is_Daemon = Daemon_Mode; #ifdef SYSLOG #ifndef LOG_CONS /* Kludge: mips-dec-ultrix4.5 has no LOG_CONS */ #define LOG_CONS 0 #endif #ifdef LOG_DAEMON openlog(PACKAGE, LOG_CONS|LOG_PID, LOG_DAEMON); #else openlog(PACKAGE, LOG_CONS|LOG_PID, 0); #endif #endif Log(LOG_NOTICE, "%s starting ...", NGIRCd_Version); } /* Log_Init */ /** * Re-init logging after reading the configuration file. */ GLOBAL void Log_ReInit(void) { #ifdef SYSLOG #ifndef LOG_CONS /* Kludge: mips-dec-ultrix4.5 has no LOG_CONS */ #define LOG_CONS 0 #endif closelog(); openlog(PACKAGE, LOG_CONS|LOG_PID, Conf_SyslogFacility); #endif } GLOBAL void Log_Exit( void ) { Log(LOG_NOTICE, "%s done%s, served %lu connection%s.", PACKAGE_NAME, NGIRCd_SignalRestart ? " (restarting)" : "", Conn_CountAccepted(), Conn_CountAccepted() == 1 ? "" : "s"); #ifdef SYSLOG closelog(); #endif } /* Log_Exit */ /** * Log function for debug messages. * This function is only functional when the program is compiled with debug * code enabled; otherwise it is an empty function which the compiler will * hopefully mangle down to "nothing" (see log.h). Therefore you should use * LogDebug(...) in favor to Log(LOG_DEBUG, ...). * @param Format Format string like printf(). * @param ... Further arguments. */ #ifdef DEBUG # ifdef PROTOTYPES GLOBAL void LogDebug( const char *Format, ... ) # else GLOBAL void LogDebug( Format, va_alist ) const char *Format; va_dcl # endif /* PROTOTYPES */ { char msg[MAX_LOG_MSG_LEN]; va_list ap; if (!NGIRCd_Debug) return; #ifdef PROTOTYPES va_start( ap, Format ); #else va_start( ap ); #endif vsnprintf( msg, MAX_LOG_MSG_LEN, Format, ap ); va_end( ap ); Log(LOG_DEBUG, "%s", msg); } #endif /* DEBUG */ /** * Logging function of ngIRCd. * This function logs messages to the console and/or syslog, whichever is * suitable for the mode ngIRCd is running in (daemon vs. non-daemon). * If LOG_snotice is set, the log messages goes to all user with the mode +s * set and the local &SERVER channel, too. * Please note: you should use LogDebug(...) for debug messages! * @param Level syslog level (LOG_xxx) * @param Format Format string like printf(). * @param ... Further arguments. */ #ifdef PROTOTYPES GLOBAL void Log( int Level, const char *Format, ... ) #else GLOBAL void Log( Level, Format, va_alist ) int Level; const char *Format; va_dcl #endif { char msg[MAX_LOG_MSG_LEN]; bool snotice; va_list ap; assert( Format != NULL ); if( Level & LOG_snotice ) { /* Notice an User mit "s" Mode */ snotice = true; Level &= ~LOG_snotice; } else snotice = false; #ifdef DEBUG if(( Level == LOG_DEBUG ) && ( ! NGIRCd_Debug )) return; #else if( Level == LOG_DEBUG ) return; #endif #ifdef PROTOTYPES va_start( ap, Format ); #else va_start( ap ); #endif vsnprintf( msg, MAX_LOG_MSG_LEN, Format, ap ); va_end( ap ); Log_Message(Level, msg); if (snotice) { /* Send NOTICE to all local users with mode +s and to the * local &SERVER channel */ Log_ServerNotice('s', "%s", msg); Channel_LogServer(msg); } } /* Log */ GLOBAL void Log_Init_Subprocess(char UNUSED *Name) { #ifdef SYSLOG openlog(PACKAGE, LOG_CONS|LOG_PID, Conf_SyslogFacility); #endif #ifdef DEBUG Log_Subprocess(LOG_DEBUG, "%s sub-process starting, PID %ld.", Name, (long)getpid()); #endif } GLOBAL void Log_Exit_Subprocess(char UNUSED *Name) { #ifdef DEBUG Log_Subprocess(LOG_DEBUG, "%s sub-process %ld done.", Name, (long)getpid()); #endif #ifdef SYSLOG closelog( ); #endif } #ifdef PROTOTYPES GLOBAL void Log_Subprocess(const int Level, const char *Format, ...) #else GLOBAL void Log_Subprocess(Level, Format, va_alist) const int Level; const char *Format; va_dcl #endif { char msg[MAX_LOG_MSG_LEN]; va_list ap; assert(Format != NULL); #ifdef DEBUG if ((Level == LOG_DEBUG) && (!NGIRCd_Debug)) return; #else if (Level == LOG_DEBUG) return; #endif #ifdef PROTOTYPES va_start(ap, Format); #else va_start(ap); #endif vsnprintf(msg, MAX_LOG_MSG_LEN, Format, ap); va_end(ap); Log_Message(Level, msg); } /** * Send a log message to all local users flagged with the given user mode. * @param UserMode User mode which the target user must have set, * @param Format The format string. */ #ifdef PROTOTYPES GLOBAL void Log_ServerNotice(const char UserMode, const char *Format, ... ) #else GLOBAL void Log_ServerNotice(UserMode, Format, va_alist) const char UserMode; const char *Format; va_dcl #endif { CLIENT *c; char msg[MAX_LOG_MSG_LEN]; va_list ap; assert(Format != NULL); #ifdef PROTOTYPES va_start(ap, Format); #else va_start(ap); #endif vsnprintf(msg, MAX_LOG_MSG_LEN, Format, ap); va_end(ap); for(c=Client_First(); c != NULL; c=Client_Next(c)) { if (Client_Conn(c) > NONE && Client_HasMode(c, UserMode)) IRC_WriteStrClient(c, "NOTICE %s :%s%s", Client_ID(c), NOTICE_TXTPREFIX, msg); } } /* Log_ServerNotice */ /* -eof- */
ngircd/ngircd
src/ngircd/log.c
C
gpl-2.0
6,301
$(function () { var max_upload = parseInt($('#max_upload').val()); var temid = parseInt($('#temid').val()); var albumid = parseInt($('#albumid').val()); var limit = max_upload - temid; $('#file_upload').uploadify({ 'swf': swf_link, 'uploader': upload_link, 'cancelImg': cancel_link, 'buttonText': 'CHỌN ẢNH...', 'removeTimeout': 5, 'uploadLimit': limit, 'queueSizeLimit': limit, 'fileSizeLimit': '5221908 byte', 'fileTypeExts': '*.jpg;*.jpeg;*.png;*.gif', 'fileDesc': '.jpg, .jpeg, .png, .gif', 'removeCompleted': true, 'formData': { 'uploadfile': '1', 'modname': nv_module_name, 'siteroot': nv_siteroot, 'module_logo': module_logo, 'folder': folder, 'albumid': albumid, 'limit': temid }, 'onUploadSuccess': function (file, data, response) { var tem = parseInt($('#temid').val()) + 1; $('#temid').val(tem); var info = data.split('[NV3]'); if (info[0] == "OK") { var status= "status_" + tem + ""; var a = ''; a += '<div id="row_' + tem + '">'; a += '<div class="loopc">'; a += ' <div class="img">'; a += ' <input class="rid" rel="' + tem + '" type="hidden" value="' + info[3] + '" name="rid_' + tem + '" id="rid_' + tem + '" />'; a += ' <input type="hidden" value="' + info[1] + '" name="thumb_' + tem + '" id="thumb_' + tem + '" />'; a += ' <span id="del_' + tem + '" onclick="delete_image(' + tem + ', 0, ' +albumid+ ', ' + admin_site + ');" title="Xóa ảnh này" class="delete"></span>'; a += '<span title="Trạng thái" class="status">'; a += ' <input id="status_' + tem + '" name="status_' + tem + '" onclick="status_image(\'status_' + tem + '\',' + info[3] + ',' + albumid + ');" value="1" checked type="checkbox">'; a += '</span>'; a += '<span title="Chọn làm ảnh mặc định album" class="default">'; a += '<input id="fileimg_' + tem + '" name="fileimg_' + tem + '" value="' + info[2] + '" type="hidden">'; a += '<input id="default_' + tem + '" name="default_' + tem + '" onclick="get_image(\'' + tem + '\',\'' + info[3] + '\', \'' +albumid+ '\', \'' + info[4] + '\', \'' + info[5] + '\', \'' + info[6] + '\');" value="1" type="radio">'; a += '</span>'; a += ' <a class="duan-thumb" rel="' + info[2] + '" href="' + info[2] + '">'; a += ' <img width="100px" src="' + info[1] + '" />'; a += ' </a>'; a += ' </div>'; a += '</div>'; a += '</div>'; $("#showimage").append(a); $('.duan-thumb').lightBox(); } else { $('#file_upload').uploadify('settings', 'queueSizeLimit', tem); $('#file_upload').uploadify('settings', 'queueSizeLimit', tem); //alert(info[1]); } } }); }); function delete_image(delrow, rid, albumid) { if (confirm('Bạn có chắc chắn xóa ảnh này')) { $.ajax({ async: false, type: 'POST', url: admin_site + 'index.php?' + nv_name_variable + '=' + nv_module_name + '&' + nv_fc_variable + '=uploads&del=1', data: 'rid=' + rid + '&albumid=' + albumid, success: function (a) { var b = a.split("[NV3]"); if (b[0] == 'OK') { $('#row_' + delrow).remove(); var i=1; $.each($('.rid'), function () { $('#row_' + $(this).attr('rel')).attr('id', 'row_' + i); tmp = $(this).attr('rel'); $('#del_' + tmp).attr('onclick', "delete_image(" + i + ", " + $('#rid_' + tmp).val() + ", " + albumid + ")"); $('#del_' + tmp).attr('id', 'del_' + i); $('#picture_' + tmp).attr('name', 'picture_' + i); $('#picture_' + tmp).attr('id', 'picture_' + i); $('#thumb_' + tmp).attr('name', 'thumb_' + i); $('#thumb_' + tmp).attr('id', 'thumb_' + i); $(this).attr('name', 'rid_' + i); $(this).attr('id', 'rid_' + i); $(this).attr('rel', i); ++i; }); var tem = parseInt($('#temid').val()) - 1; $('#temid').val(tem); } else if (b[0] == 'ERR') { alert(b[1]); } } }); } return false; } function status_image(checkbox_id, rid, albumid ) { if (confirm(nv_is_change_act_confirm[0])) { var nv_timer = nv_settimeout_disable(checkbox_id, 5000); nv_ajax("post", script_name, nv_name_variable + '=' + nv_module_name + '&' + nv_fc_variable + '=uploads&act=1&rid=' + rid + '&albumid=' + albumid + '&loop=' + checkbox_id + '&num=' + nv_randomPassword(8), '', 'status_image_res'); } else { var sl = document.getElementById(checkbox_id); if (sl.checked == true) sl.checked = false; else sl.checked = true; } return; } // --------------------------------------- function status_image_res(res) { var r_split = res.split("|"); if (r_split[0] != 'OK') { alert(nv_is_change_act_confirm[2]); var sl = document.getElementById(r_split[1]); if (sl.checked == true) sl.checked = false; else sl.checked = true; clearTimeout(nv_timer); sl.disabled = true; } return false; } function reset_content() { $('#crop-img').hide(); return false; }; function updateCoords(c) { $('#x').val(c.x); $('#y').val(c.y); $('#w').val(c.w); $('#h').val(c.h); }; function checkCoords() { if (parseInt($('#w').val())) { var x = $('#x').val(); var y = $('#y').val(); var w = $('#w').val(); var h = $('#h').val(); var targ_w = 402; var targ_h = 254; var imgw = $('#imgw').val(); var imgh = $('#imgh').val(); var imgfile = $('#imgfile').val(); var alias_ab = $('#alias_ab').val(); var rid = $('#rid').val(); var albumid = $('#albumid').val(); var tems = $('#tems').val(); $.ajax({ url: admin_site + 'index.php?' + nv_lang_variable + '=' + nv_sitelang + '&' + nv_name_variable + '=' + nv_module_name + '&' + nv_fc_variable + '=uploads&upload=1&nocache=' + new Date().getTime(), type: "POST", data: 'leftX=' + x + '&leftY=' + y + '&newwidth=' + w + '&newheight=' + h + '&imgw=' + imgw + '&imgh=' + imgh + '&tems=' + tems + '&imgfile=' + imgfile+ '&alias_ab=' + alias_ab+ '&rid=' + rid+ '&albumid=' + albumid, success: function (res) { var r_split = res.split("[NV3]"); if (r_split[0] == 'OK') { document.getElementById("contentimg1").innerHTML = '<img src="' + r_split[1] + '" width="220" height="139" >'; $('#frontimg').val(r_split[1]); }else { alert(r_split[1]); } $('#crop-img').hide(); $('#response').hide(); } }); } else { alert('Hãy chọn vùng ảnh trước khi bấm lưu vùng ảnh đã chọn'); } return false; }; function get_image(i,rid,albumid,w,h,tems) { var img = document.getElementById('fileimg_'+i).value; $('#imgfile').val(img); $('#rid').val(rid); $('#imgw').val(w); $('#imgh').val(h); $('#tems').val(tems); $('#albumid').val(albumid); document.getElementById("response").innerHTML = '<img id="cropbox" src="' + img + '" width="' + w + '" height="' + h + '">'; $('#cropbox').Jcrop({ //aspectRatio: 1, bgFade: true, bgOpacity: .2, minSize: [402, 254], maxSize: [630, 380], aspectRatio: 630 / 380, onSelect: updateCoords }); $('#crop-img').show(); }
dangdinhtu2014/nukeviet_photo
modules/photo/js/New folder/uploads.js
JavaScript
gpl-2.0
7,904
public class DragAction : System.Enum, System.IComparable, System.IFormattable, System.IConvertible { // Methods public virtual bool Equals(object obj) {} public virtual int GetHashCode() {} public virtual string ToString() {} public virtual string ToString(string format, System.IFormatProvider provider) {} public virtual int CompareTo(object target) {} public virtual string ToString(System.IFormatProvider provider) {} public virtual System.TypeCode GetTypeCode() {} public string ToString(string format) {} public Type GetType() {} // Fields public int value__; public DragAction Continue; public DragAction Drop; public DragAction Cancel; }
Pengfei-Gao/source-Insight-3-for-centos7
SourceInsight3/NetFramework/DragAction.cs
C#
gpl-2.0
665
//事件兼容pc $.each("String Boolean RegExp Number Date Object Null Undefined".split(" "), function( i, name ){ var fn; if( 'is' + name in $ ) return;//already defined then ignore. switch (name) { case 'Null': fn = function(obj){ return obj === null; }; break; case 'Undefined': fn = function(obj){ return obj === undefined; }; break; default: fn = function(obj){ return new RegExp(name + ']', 'i').test( toString(obj) )}; } $['is'+name] = fn; }); (function () { var $onFn = $.fn.on, $offFn = $.fn.off, transEvent = { touchstart: 'mousedown', touchend: 'mouseup', touchmove: 'mousemove', tap: 'click' }, reversalEvent= { mousedown: 'touchstart', mouseup: 'touchend', mousemove: 'touchmove', click: 'tap' }, transFn = function(e) { var events, org, event; if($.isObject(e)){ org = e; $.each(e, function(key){ event = parse(key); !$.support.touch && transEvent[event.e] && (org[transEvent[event.e]+event.ns] = this); }); return org; }else { events = []; $.each((e || '').split(' '), function(i, type) { event = parse(type); events.push(!$.support.touch && transEvent[event.e] ? transEvent[event.e]+event.ns : type); }); return events.join(' '); } }, parse = function(event) { var idx = event.indexOf('.'), e, ns; if(idx>-1) { e = event.substr(0, idx); ns = event.substr(idx); } else { e = event; ns = ''; } return {e:e, ns:ns}; }, callbackStack = []; $.extend($.fn, { on: function(event, selector, callback) { if( Object.prototype.toString.call(selector) === '[object Function]' ) { callback = selector; selector = null; } $.proxy(callback); var targetActived = false; var transedEvent = transFn(event); var _callback = function(e){ var options = e || {}; options.changedTouches = options.changedTouches || []; var bubbles = typeof options.bubbles != 'undefined' ? options.bubbles : true ; var cancelable = typeof options.cancelable != 'undefined' ? options.cancelable : (event != "touchcancel"); var view = typeof options.view != 'undefined' ? options.view : window; var detail = typeof options.detail != 'undefined' ? options.detail : 0; var clientX = typeof options.pageX != 'undefined' ? options.pageX : 0; var clientY = typeof options.pageY != 'undefined' ? options.pageY : 0; var ctrlKey = typeof options.ctrlKey != 'undefined' ? options.ctrlKey : false; var altKey = typeof options.altKey != 'undefined' ? options.altKey : false; var shiftKey = typeof options.shiftKey != 'undefined' ? options.shiftKey : false; var metaKey = typeof options.metaKey != 'undefined' ? options.metaKey : false; var scale = typeof options.scale != 'undefined' ? options.scale : 1.0; var rotation = typeof options.rotation != 'undefined' ? options.rotation : 0.0; var relatedTarget = typeof options.relatedTarget != 'undefined' ? options.relatedTarget : null; var touches = []; var targetTouches = []; var changedTouches = []; var _event = document.createEvent('MouseEvents'); _event.initMouseEvent(reversalEvent[e.type] || e.type, bubbles, cancelable, view, 1, 0, 0, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, touches, targetTouches, changedTouches, scale, rotation, relatedTarget); _event.touches = [e]; switch( e.type ){ case 'mousedown': targetActived = true; callback.call(null, _event); break; case 'mousemove': if( !targetActived ) { // 如果touchstart没触发,touchmove(mousemove)应该不响应 return; } else { callback.call(null, _event); break; } case 'mouseup': targetActived = false; callback.call(null, _event); break; } }; callbackStack.push({ 'target': this, 'event': transedEvent, 'selector': selector, 'callback': callback, '_callback': _callback }); _callback._zid = callback._zid; return $onFn.call(this, transedEvent, selector, _callback); }, off: function(event, selector, callback) { return $offFn.call(this, transFn(event), selector, callback); } }); })();
elppac/moment
demo/GMU-master/examples/assets/mobileevent2pc.js
JavaScript
gpl-2.0
5,558
# We borrow heavily from the kernel build setup, though we are simpler since # we don't have Kconfig tweaking settings on us. # The implicit make rules have it looking for RCS files, among other things. # We instead explicitly write all the rules we care about. # It's even quicker (saves ~200ms) to pass -r on the command line. MAKEFLAGS=-r # The source directory tree. srcdir := .. abs_srcdir := $(abspath $(srcdir)) # The name of the builddir. builddir_name ?= . # The V=1 flag on command line makes us verbosely print command lines. ifdef V quiet= else quiet=quiet_ endif # Specify BUILDTYPE=Release on the command line for a release build. BUILDTYPE ?= Release # Directory all our build output goes into. # Note that this must be two directories beneath src/ for unit tests to pass, # as they reach into the src/ directory for data with relative paths. builddir ?= $(builddir_name)/$(BUILDTYPE) abs_builddir := $(abspath $(builddir)) depsdir := $(builddir)/.deps # Object output directory. obj := $(builddir)/obj abs_obj := $(abspath $(obj)) # We build up a list of every single one of the targets so we can slurp in the # generated dependency rule Makefiles in one pass. all_deps := # C++ apps need to be linked with g++. # # Note: flock is used to seralize linking. Linking is a memory-intensive # process so running parallel links can often lead to thrashing. To disable # the serialization, override LINK via an envrionment variable as follows: # # export LINK=g++ # # This will allow make to invoke N linker processes as specified in -jN. LINK ?= ./gyp-mac-tool flock $(builddir)/linker.lock $(CXX.target) CC.target ?= $(CC) CFLAGS.target ?= $(CFLAGS) CXX.target ?= $(CXX) CXXFLAGS.target ?= $(CXXFLAGS) LINK.target ?= $(LINK) LDFLAGS.target ?= $(LDFLAGS) AR.target ?= $(AR) # TODO(evan): move all cross-compilation logic to gyp-time so we don't need # to replicate this environment fallback in make as well. CC.host ?= gcc CFLAGS.host ?= CXX.host ?= g++ CXXFLAGS.host ?= LINK.host ?= g++ LDFLAGS.host ?= AR.host ?= ar # Define a dir function that can handle spaces. # http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions # "leading spaces cannot appear in the text of the first argument as written. # These characters can be put into the argument value by variable substitution." empty := space := $(empty) $(empty) # http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces replace_spaces = $(subst $(space),?,$1) unreplace_spaces = $(subst ?,$(space),$1) dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) # Flags to make gcc output dependency info. Note that you need to be # careful here to use the flags that ccache and distcc can understand. # We write to a dep file on the side first and then rename at the end # so we can't end up with a broken dep file. depfile = $(depsdir)/$(call replace_spaces,$@).d DEPFLAGS = -MMD -MF $(depfile).raw # We have to fixup the deps output in a few ways. # (1) the file output should mention the proper .o file. # ccache or distcc lose the path to the target, so we convert a rule of # the form: # foobar.o: DEP1 DEP2 # into # path/to/foobar.o: DEP1 DEP2 # (2) we want missing files not to cause us to fail to build. # We want to rewrite # foobar.o: DEP1 DEP2 \ # DEP3 # to # DEP1: # DEP2: # DEP3: # so if the files are missing, they're just considered phony rules. # We have to do some pretty insane escaping to get those backslashes # and dollar signs past make, the shell, and sed at the same time. # Doesn't work with spaces, but that's fine: .d files have spaces in # their names replaced with other characters. define fixup_dep # The depfile may not exist if the input file didn't have any #includes. touch $(depfile).raw # Fixup path as in (1). sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) # Add extra rules as in (2). # We remove slashes and replace spaces with new lines; # remove blank lines; # delete the first line and append a colon to the remaining lines. sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ grep -v '^$$' |\ sed -e 1d -e 's|$$|:|' \ >> $(depfile) rm $(depfile).raw endef # Command definitions: # - cmd_foo is the actual command to run; # - quiet_cmd_foo is the brief-output summary of the command. quiet_cmd_cc = CC($(TOOLSET)) $@ cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_cxx = CXX($(TOOLSET)) $@ cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_objc = CXX($(TOOLSET)) $@ cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< quiet_cmd_objcxx = CXX($(TOOLSET)) $@ cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< # Commands for precompiled header files. quiet_cmd_pch_c = CXX($(TOOLSET)) $@ cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_pch_cc = CXX($(TOOLSET)) $@ cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_pch_m = CXX($(TOOLSET)) $@ cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< quiet_cmd_pch_mm = CXX($(TOOLSET)) $@ cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< # gyp-mac-tool is written next to the root Makefile by gyp. # Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd # already. quiet_cmd_mac_tool = MACTOOL $(4) $< cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@" quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@ cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) quiet_cmd_infoplist = INFOPLIST $@ cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@" quiet_cmd_touch = TOUCH $@ cmd_touch = touch $@ quiet_cmd_copy = COPY $@ # send stderr to /dev/null to ignore messages when linking directories. cmd_copy = rm -rf "$@" && cp -af "$<" "$@" quiet_cmd_alink = LIBTOOL-STATIC $@ cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^) quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) # TODO(thakis): Find out and document the difference between shared_library and # loadable_module on mac. quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) # TODO(thakis): The solink_module rule is likely wrong. Xcode seems to pass # -bundle -single_module here (for osmesa.so). quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) # Define an escape_quotes function to escape single quotes. # This allows us to handle quotes properly as long as we always use # use single quotes and escape_quotes. escape_quotes = $(subst ','\'',$(1)) # This comment is here just to include a ' to unconfuse syntax highlighting. # Define an escape_vars function to escape '$' variable syntax. # This allows us to read/write command lines with shell variables (e.g. # $LD_LIBRARY_PATH), without triggering make substitution. escape_vars = $(subst $$,$$$$,$(1)) # Helper that expands to a shell command to echo a string exactly as it is in # make. This uses printf instead of echo because printf's behaviour with respect # to escape sequences is more portable than echo's across different shells # (e.g., dash, bash). exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' # Helper to compare the command we're about to run against the command # we logged the last time we ran the command. Produces an empty # string (false) when the commands match. # Tricky point: Make has no string-equality test function. # The kernel uses the following, but it seems like it would have false # positives, where one string reordered its arguments. # arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ # $(filter-out $(cmd_$@), $(cmd_$(1)))) # We instead substitute each for the empty string into the other, and # say they're equal if both substitutions produce the empty string. # .d files contain ? instead of spaces, take that into account. command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) # Helper that is non-empty when a prerequisite changes. # Normally make does this implicitly, but we force rules to always run # so we can check their command lines. # $? -- new prerequisites # $| -- order-only dependencies prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) # Helper that executes all postbuilds until one fails. define do_postbuilds @E=0;\ for p in $(POSTBUILDS); do\ eval $$p;\ E=$$?;\ if [ $$E -ne 0 ]; then\ break;\ fi;\ done;\ if [ $$E -ne 0 ]; then\ rm -rf "$@";\ exit $$E;\ fi endef # do_cmd: run a command via the above cmd_foo names, if necessary. # Should always run for a given target to handle command-line changes. # Second argument, if non-zero, makes it do asm/C/C++ dependency munging. # Third argument, if non-zero, makes it do POSTBUILDS processing. # Note: We intentionally do NOT call dirx for depfile, since it contains ? for # spaces already and dirx strips the ? characters. define do_cmd $(if $(or $(command_changed),$(prereq_changed)), @$(call exact_echo, $($(quiet)cmd_$(1))) @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" $(if $(findstring flock,$(word 2,$(cmd_$1))), @$(cmd_$(1)) @echo " $(quiet_cmd_$(1)): Finished", @$(cmd_$(1)) ) @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) @$(if $(2),$(fixup_dep)) $(if $(and $(3), $(POSTBUILDS)), $(call do_postbuilds) ) ) endef # Declare the "all" target first so it is the default, # even though we don't have the deps yet. .PHONY: all all: # make looks for ways to re-generate included makefiles, but in our case, we # don't have a direct way. Explicitly telling make that it has nothing to do # for them makes it go faster. %.d: ; # Use FORCE_DO_CMD to force a target to run. Should be coupled with # do_cmd. .PHONY: FORCE_DO_CMD FORCE_DO_CMD: TOOLSET := target # Suffix rules, putting all outputs into $(obj). $(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.m FORCE_DO_CMD @$(call do_cmd,objc,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.mm FORCE_DO_CMD @$(call do_cmd,objcxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD @$(call do_cmd,cc,1) # Try building from generated source, too. $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.m FORCE_DO_CMD @$(call do_cmd,objc,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.mm FORCE_DO_CMD @$(call do_cmd,objcxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.m FORCE_DO_CMD @$(call do_cmd,objc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.mm FORCE_DO_CMD @$(call do_cmd,objcxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD @$(call do_cmd,cc,1) ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ $(findstring $(join ^,$(prefix)),\ $(join ^,kerberos.target.mk)))),) include kerberos.target.mk endif quiet_cmd_regen_makefile = ACTION Regenerating $@ cmd_regen_makefile = /usr/local/Cellar/node/0.8.14/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp -fmake --ignore-environment "--toplevel-dir=." -I/Users/toulon/load_tapes/node_modules/mongoskin/node_modules/mongodb/node_modules/kerberos/build/config.gypi -I/usr/local/Cellar/node/0.8.14/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/Users/toulon/.node-gyp/0.10.22/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/Users/toulon/.node-gyp/0.10.22" "-Dmodule_root_dir=/Users/toulon/load_tapes/node_modules/mongoskin/node_modules/mongodb/node_modules/kerberos" binding.gyp Makefile: $(srcdir)/../../../../../../../../../usr/local/Cellar/node/0.8.14/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../../../.node-gyp/0.10.22/common.gypi $(call do_cmd,regen_makefile) # "all" is a concatenation of the "all" targets from all the included # sub-makefiles. This is just here to clarify. all: # Add in dependency-tracking rules. $(all_deps) is the list of every single # target in our tree. Only consider the ones with .d (dependency) info: d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) ifneq ($(d_files),) include $(d_files) endif
toulon/load_tapes
node_modules/mongoskin/node_modules/mongodb/node_modules/kerberos/build/Makefile
Makefile
gpl-2.0
13,917
# -*- coding: utf-8 -*- __author__ = 'frank' from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy.dialects import mysql from datetime import datetime db = SQLAlchemy() # 时间都存为utcnow,具体显示根据不同的本地环境进行相应转换 # 如分析数据,或者在本地显示(采用moment插件前端显示) class Application(db.Model): """twitter application""" __tablename__ = 'applications' id = db.Column(db.Integer, primary_key=True) consumer_token = db.Column(db.String(30)) consumer_secret = db.Column(db.String(60)) created_at = db.Column(db.DateTime, default=datetime.utcnow) is_valid = db.Column(db.Boolean, default=True) access_tokens = db.relationship('AccessToken', backref='application', lazy='dynamic', order_by='desc(AccessToken.created_at)') class User(db.Model): """用户信息表""" __tablename__ = 'users' # 其中id用于外键链接,user_id与api交互 # 针对于mysql数据库 id = db.Column(mysql.INTEGER(30), primary_key=True) # id_str user_id = db.Column(db.String(30)) name = db.Column(db.String(50)) screen_name = db.Column(db.String(50)) location = db.Column(db.String(30)) statuses_count = db.Column(db.Integer) followers_count = db.Column(db.Integer) # 关注人员数, following friends_count = db.Column(db.Integer) created_at = db.Column(db.DateTime) # 下次待抓取消息id下限 since_id = db.Column(db.String(30), default='0') # 是否为待监控用户 is_target = db.Column(db.Boolean, default=False) # 关注者id,表明该待同步用户被monitor_user_id关注 monitor_user_id = db.Column(mysql.INTEGER(30)) # 图像地址 profile_image_url = db.Column(db.String(150)) # url 主页地址 url = db.Column(db.String(150)) access_tokens = db.relationship( 'AccessToken', backref='user', lazy='dynamic', order_by='desc(AccessToken.created_at)') statuses = db.relationship( 'Status', backref='user', lazy='dynamic', order_by='desc(Status.created_at)') def __repr__(self): return 'User %s' % self.screen_name class AccessToken(db.Model): """access_token信息表""" __tablename__ = 'accesstokens' id = db.Column(db.Integer, primary_key=True) access_token = db.Column(db.String(50)) access_token_secret = db.Column(db.String(45)) is_valid = db.Column(db.Boolean, default=True) created_at = db.Column(db.DateTime, default=datetime.utcnow) user_id = db.Column(mysql.INTEGER(30), db.ForeignKey('users.id')) applcation_id = db.Column(db.Integer, db.ForeignKey('applications.id')) def __repr__(self): return "AccessToken userid %d" % self.user_id class Status(db.Model): """状态信息表""" __tablename__ = 'statuses' # 针对于mysql数据库 id = db.Column(mysql.INTEGER(30), primary_key=True) # twitter_status_id status_id = db.Column(db.String(30)) text = db.Column(db.String(150)) created_at = db.Column(db.DateTime) # 图片地址 media_url = db.Column(db.String(150)) # 被关注者id,表明该tweet是user_id发出的 user_id = db.Column(mysql.INTEGER(30), db.ForeignKey('users.id')) # 关注者id,表明该tweet是id关注待同步用户之后产生的 monitor_user_id = db.Column(mysql.INTEGER(30)) def __repr__(self): print "Status %s" % self.status_id
Fansion/crawltwitter
crawltwitter/models.py
Python
gpl-2.0
3,522
/**************************************************************************** Copyright (c) 2010 Ricardo Quesada Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef __CCCONFIGURATION_H__ #define __CCCONFIGURATION_H__ #include <string> #include "base/CCRef.h" #include "base/CCValue.h" #include "platform/CCGL.h" NS_CC_BEGIN /** * @addtogroup global * @{ */ /** @brief Configuration contains some openGL variables @since v0.99.0 */ class CC_DLL Configuration : public Ref { public: /** returns a shared instance of Configuration */ static Configuration *getInstance(); /** purge the shared instance of Configuration */ static void destroyInstance(); /** @deprecated Use getInstance() instead */ CC_DEPRECATED_ATTRIBUTE static Configuration *sharedConfiguration(); /** @deprecated Use destroyInstance() instead */ CC_DEPRECATED_ATTRIBUTE static void purgeConfiguration(); public: /** * @js NA * @lua NA */ virtual ~Configuration(); /** OpenGL Max texture size. */ int getMaxTextureSize() const; /** OpenGL Max Modelview Stack Depth. */ int getMaxModelviewStackDepth() const; /** returns the maximum texture units @since v2.0.0 */ int getMaxTextureUnits() const; /** Whether or not the GPU supports NPOT (Non Power Of Two) textures. OpenGL ES 2.0 already supports NPOT (iOS). @since v0.99.2 */ bool supportsNPOT() const; /** Whether or not PVR Texture Compressed is supported */ bool supportsPVRTC() const; /** Whether or not ETC Texture Compressed is supported */ bool supportsETC() const; /** Whether or not S3TC Texture Compressed is supported */ bool supportsS3TC() const; /** Whether or not ATITC Texture Compressed is supported */ bool supportsATITC() const; /** Whether or not BGRA8888 textures are supported. @since v0.99.2 */ bool supportsBGRA8888() const; /** Whether or not glDiscardFramebufferEXT is supported @since v0.99.2 */ bool supportsDiscardFramebuffer() const; /** Whether or not shareable VAOs are supported. @since v2.0.0 */ bool supportsShareableVAO() const; /** returns whether or not an OpenGL is supported */ bool checkForGLExtension(const std::string &searchName) const; bool init(); /** returns the value of a given key as a double */ const Value& getValue(const std::string& key, const Value& defaultValue = Value::Null) const; /** sets a new key/value pair in the configuration dictionary */ void setValue(const std::string& key, const Value& value); /** returns the Configuration info */ std::string getInfo() const; /** gathers OpenGL / GPU information */ void gatherGPUInfo(); /** Loads a config file. If the keys are already present, then they are going to be replaced. Otherwise the new keys are added. */ void loadConfigFile(const std::string& filename); private: Configuration(void); static Configuration *s_sharedConfiguration; static std::string s_configfile; protected: GLint _maxTextureSize; GLint _maxModelviewStackDepth; bool _supportsPVRTC; bool _supportsETC1; bool _supportsS3TC; bool _supportsATITC; bool _supportsNPOT; bool _supportsBGRA8888; bool _supportsDiscardFramebuffer; bool _supportsShareableVAO; GLint _maxSamplesAllowed; GLint _maxTextureUnits; char * _glExtensions; ValueMap _valueDict; }; // end of global group /// @} NS_CC_END #endif // __CCCONFIGURATION_H__
SubwayRocketTeam/Prototype
cocos2d/cocos/base/CCConfiguration.h
C
gpl-2.0
4,878
<?php include "testerLib.inc.php"; require_once("interfaces.inc.php"); //set exception handler set_error_handler("exception_error_handler"); $test = false; if (isset ($_GET['test'])){ $test = $_GET['test']; } $grade = 0; $test_1 = new TestSequence ("Test 1 - File existance Tests"); $test_1->add( new FileExistanceTest("includes.inc.php file existence ",0,true,"includes.inc.php") ); $test_1->add( new FileExistanceTest("constants.inc.php file existence ",0,true,"constants.inc.php") ); //$test_1->debuggingOn(); if (!$test || $test == 'init') { $test_1->run(); $grade += $test_1->getGrade(); } require_once("includes.inc.php"); $test_2 = new TestSequence ("Test 2 - Database access tests"); $test_2->add (new ConstantsDefinedTest("Database constants are defined",0,true) ); $test_2->add (new DBAccessTest("Writing tests to database",0,true) ); //$test_2->debuggingOn(); if (!$test || $test == 'init') { $test_2->run(); $grade += $test_2->getGrade(); } /***************** end of initial tests **************************/ $ts_sgt = new TestSequence ("Test 3 - Singleton tests"); $ts_sgt->add( new ClassExistanceTest("Singleton class definition", 0, true, "SingletonDB") ); $ts_sgt->add( new ClassImplementsInterfaceTest("SingletonDB implements Singleton interface", 0, true, "SingletonDB", "Singleton") ); class MysqlWarning extends Test { public function run () {$con = SingletonDB::connect(); return true;} } $ts_sgt->add( new NoExceptionDecorator( new MysqlWarning ("Test if connection has no MYSQL warnings", 1, true) ) ); $ts_sgt->add( new NotInstantiableTest("Do not allow direct instantiation ", 3, false, "SingletonDB") ); $ts_sgt->add( new GoodSingletonTest("Multiple 'connect' calls return same reference ", 3, false) ); $ts_sgt->add( new SingletonIsConnectionTest("Test if SingletonDB::connect returns a connection ", 3, false) ); if (!$test || $test == 'bonus') { $ts_sgt->run(); $grade += $ts_sgt->getGrade(); } /******************* end of bonus tests *************************/ $test_4 = new TestSequence("Test 4 - Item tests"); $test_4->add( new ClassExistanceTest("ItemFactory class definition", 0, true, "ItemFactory") ); $test_4->add( new ClassImplementsInterfaceTest("ItemFactory implements IItemFactory interface", 0, true, "ItemFactory", "IItemFactory") ); $test_4->add( new ContextNEDecorator ( new ItemFactoryTest("ItemFactory::getItem() simple call test", 3, true) ) ); $test_4->add( new ContextEDecorator (new ReadItemTest("InvalidIndexException test",3, false, 9999, "pw_users"), "InvalidIndexException")); $test_4->add( new ContextEDecorator (new ReadItemTest("InvalidTableException test 1",3, false, 1, "pw_user"), "InvalidTableException")); $test_4->add( new ContextEDecorator (new ReadItemTest("InvalidTableException test 2",3, false, 1, ""), "InvalidTableException")); /* for $object = ItemFactory::getItem(2, ... ); checks if '$object->property' equals with column value 'property' on row 2 from a given table */ $test_4->add( new ContextNEDecorator (new ReadItemTest("Test if we can read properties of items ",4, false, 2, "pw_users") ) ) ; $test_4->add( new ContextEDecorator (new GetInvalidPropertyTest("Get value of invalid property (should throw an exception)",3, false), "NoSuchPropertyException")); $test_4->add( new ContextEDecorator (new SetInvalidPropertyTest("Set value invalid property (should throw an exception)",3, false), "NoSuchPropertyException")); $test_4->add( new ContextNEDecorator (new ModifyItemTest("Modify existent property ",4, false, 2, "pw_users") ) ); $test_4->add( new ContextNEDecorator (new CreateItemTest("Create new item ",4, false,"pw_users",array("firstName","lastName")) ) ); $itemST = new ItemStressTest("Stress test: random table, multiple accesses", 10, false); $test_4->add($itemST); //$test_4->debuggingOn(); /* stress test has huge debugging Output, better turned off */ $itemST->debuggingOff(); if (!$test || $test == 'item') { $test_4->run(); $grade += $test_4->getGrade(); } $test_5 = new TestSequence ("Test 5 - Collection tests"); $test_5->add( new ClassExistanceTest("CollectionFactory class definition", 0, true, "CollectionFactory" ) ); $test_5->add( new ClassImplementsInterfaceTest("CollectionFactory implements ICollectionFactory interface", 0, true, "CollectionFactory", "ICollectionFactory") ); $test_5->add( new ContextNEDecorator( new CollectionFactoryTest("CollectionFactory::getCollection() simple call test", 1, true) ) ); $test_5->add( new ContextNEDecorator( new HasNextSimpleTest("HasNext simple test", 1, false) ) ); $test_5->add( new ContextNEDecorator( new NextSimpleTest("Next simple test (must return an object of type Item)", 1, false) ) ); /* Test for an empty collection */ $cTest_0 = new CollectionTest("Empty collection",1,false); $cTest_0->initParams("pw_empty",array(),array(),array(),array(),array(),null,null); $cTest_0->initQuery("SELECT * from pw_empty"); $test_5->add(new ContextNEDecorator($cTest_0)); /* Exception tests */ //invalid table name: $exTest_1 = new CollectionTest("Testing if exception is thrown for invalid table",1,false); $exTest_1->initParams("pw_invalid",array(),array(),array(),array(),array(),null,null); $test_5->add(new ContextEDecorator($exTest_1,"MySQLException")); //invalid restrictions: $exTest_2 = new CollectionTest("Testing if exception is thrown for invalid restrictions",1,false); $exTest_2->initParams("pw_users",array("invalid" => "invalid"),array("invalid" => "invalid"),array("invalid" => "invalid"),array("invalid" => "invalid"),array("invalid" => array("invalid")),null,null); $test_5->add(new ContextEDecorator($exTest_2,"MySQLException")); //invalid restrictions: $exTest_3 = new CollectionTest("Testing if exception is thrown for invalid sorting",1,false); $exTest_3->initParams("pw_users",array(),array(),array(),array(),array(),"invalid","invalid"); $test_5->add(new ContextEDecorator($exTest_3,"MySQLException")); /* simple collection test */ $cTest_4 = new CollectionTest("Collection test 1 (simple list)",1, false); //$tableName, $equalPairs, $likePairs, $lessThanPairs, $greaterThanPairs, $inPairs, $orderBy, $orderType $cTest_4->initParams("pw_users",array(),array(),array(),array(),array(),null,null); $cTest_4->initQuery("SELECT * from pw_users "); $test_5->add(new ContextNEDecorator($cTest_4)); /* equal test */ $cTest_5 = new CollectionTest("Collection test 2 (some restrictions)",4, false); $cTest_5->initParams("pw_users",array("lastName" => "Popovici"), //$equalPairs, array(), //$likePairs, array(), //$lessThanPairs, array(), //$greaterThanPairs, array("id" => array("1","2")), //$inPairs, null, //$orderBy, null); //$orderType $cTest_5->initQuery("SELECT * from pw_users WHERE lastName = 'Popovici' AND id IN (1,2) "); $test_5->add(new ContextNEDecorator($cTest_5)); $cTest_6 = new CollectionTest("Collection test 3 (restrictions & sorting)",4, false); $cTest_6->initParams("pw_products",array("productAvailability" => "Yes"), //$equalPairs, array(), //$likePairs, array(), //$lessThanPairs, array(), //$greaterThanPairs, array(), //$inPairs, "id", //$orderBy, "ASC"); //$orderType $cTest_6->initQuery("SELECT * from pw_products WHERE productAvailability = 'Yes' ORDER BY id ASC "); $test_5->add(new ContextNEDecorator($cTest_6)); $cTest_7 = new CollectionTest("Collection test 4 (displaying only first page)",4, false); $cTest_7->initParams("pw_products",array("productAvailability" => "Yes"), //$equalPairs, array(), //$likePairs, array(), //$lessThanPairs, array(), //$greaterThanPairs, array(), //$inPairs, "id", //$orderBy, "ASC", //$orderType 3, //items per page 1); //current page to display $cTest_7->initQuery("SELECT * from pw_products WHERE productAvailability = 'Yes' ORDER BY id ASC LIMIT 0,3"); //$cTest_7->debuggingOn(); $test_5->add(new ContextNEDecorator($cTest_7)); $cTest_8 = new CollectionTest("Collection test 5 (displaying only some page)",4, false); $cTest_8->initParams("pw_products",array("productAvailability" => "No"), //$equalPairs, array(), //$likePairs, array(), //$lessThanPairs, array(), //$greaterThanPairs, array(), //$inPairs, "id", //$orderBy, "ASC", //$orderType 4, //items per page 2); //current page to display $cTest_8->initQuery("SELECT * from pw_products WHERE productAvailability = 'No' ORDER BY id ASC LIMIT 4,4"); //$cTest_8->debuggingOn(); $test_5->add(new ContextNEDecorator($cTest_8)); $cTest_9 = new CollectionTest("Collection test 6 (testing like)",4, false); $cTest_9->initParams("pw_users",array("lastName" => "Popovici"), //$equalPairs, array("firstName" => "M"), //$likePairs, array(), //$lessThanPairs, array(), //$greaterThanPairs, array(), //$inPairs, "id", //$orderBy, "ASC"); //$orderType $cTest_9->initQuery("SELECT * from pw_users WHERE lastName ='Popovici' AND firstName LIKE 'M' order by id ASC"); $test_5->add(new ContextNEDecorator($cTest_9)); $cTest_10 = new CollectionTest("Collection test 7 (testing > and <)",4, false); $cTest_10->initParams("pw_products",array(), //$equalPairs, array(), //$likePairs, array("id" => '110'), //$lessThanPairs, array("id" => '104'), //$greaterThanPairs, array(), //$inPairs, "id", //$orderBy, "ASC"); //$orderType $cTest_10->initQuery("SELECT * from pw_products WHERE id > 104 AND id < 110 order by id ASC"); $test_5->add(new ContextNEDecorator($cTest_10)); $cTest_11 = new CollectionTest("Collection test 8 (combined test)",4, false); $cTest_11->initParams("pw_products",array("productAvailability" => "Yes"), //$equalPairs, array("productDescription" => "script"), //$likePairs, array("id" => '110'), //$lessThanPairs, array("id" => '104'), //$greaterThanPairs, array("id" => array("105","107"), "productName" => array("Prod_5")), //$inPairs, "productName", //$orderBy, "DESC"); //$orderType $cTest_11->initQuery("SELECT * from pw_products WHERE productAvailability = 'Yes' AND productDescription LIKE 'script' AND id < 110 AND id > 104 AND id IN (105,107) AND productName IN ('Prod_5') order by productName DESC"); $test_5->add(new ContextNEDecorator($cTest_11)); $cTest_12 = new CollectionTest("Collection test 9 (combined test returning empty collection)",4, false); $cTest_12->initParams("pw_products",array("productAvailability" => "Yes", "productAvailability" => "No"), //$equalPairs, array("productDescription" => "script"), //$likePairs, array("id" => '110'), //$lessThanPairs, array("id" => '104'), //$greaterThanPairs, array("id" => array("105","107"), "productName" => array("Prod_5"))); //$inPairs, $cTest_12->initQuery("SELECT * from pw_products WHERE productAvailability = 'Yes' AND productAvailability = 'No' AND productDescription LIKE 'script' AND id < 110 AND id > 104 AND id IN (105,107) AND productName IN ('Prod_5')"); $test_5->add(new ContextNEDecorator($cTest_12)); //$test_5->debuggingOn(); if (!$test || $test == 'collection') { $test_5->run(); $grade += $test_5->getGrade(); } $test_6 = new TestSequence ("Test 6 - Script file existance"); $test_6->add(new FileExistanceTest("file index.php exists",0,true,"index.php") ); if (!$test) { $test_6->run(); $grade += $test_6->getGrade(); } space(); space(); displayGrade($grade); ?>
danadorneanu/portofolio
web-programming/webprog-assign1/tester.php
PHP
gpl-2.0
11,931
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ /* * GThumb * * Copyright (C) 2009 The Free Software Foundation, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA. */ #ifndef DLG_CATALOG_PROPERTIES_H #define DLG_CATALOG_PROPERTIES_H #include <gthumb.h> void dlg_catalog_properties (GthBrowser *browser, GthFileData *file_data); #endif /* DLG_CATALOG_PROPERTIES_H */
novas0x2a/gthumb
extensions/catalogs/dlg-catalog-properties.h
C
gpl-2.0
1,090
#pragma once // Google test includes #include "gtest/gtest.h" //---------------------------------------------------------------------------- // SimulationTest //---------------------------------------------------------------------------- class SimulationTest : public ::testing::Test { protected: //-------------------------------------------------------------------------- // test virtuals //-------------------------------------------------------------------------- virtual void SetUp() { // Perform GeNN initialization allocateMem(); PreInit(); initialize(); Init(); initializeSparse(); copyStateFromDevice(); } virtual void TearDown() { freeMem(); } //-------------------------------------------------------------------------- // Declared virtuals //-------------------------------------------------------------------------- virtual void PreInit(){} virtual void Init(){} //-------------------------------------------------------------------------- // Protected methods //-------------------------------------------------------------------------- void StepGeNN() { stepTime(); copyStateFromDevice(); } };
genn-team/genn
tests/utils/simulation_test.h
C
gpl-2.0
1,294
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/YouTube.framework/YouTube */ #import <YouTube/YTFeedRequest.h> #import <YouTube/YouTube-Structs.h> @interface YTAccountFeedRequest : YTFeedRequest { } - (void)didParseData; // 0x1620d - (void)failWithError:(id)error; // 0x165cd - (void)addVideosToFavorites:(id)favorites withBatchURL:(id)batchURL; // 0x16421 - (void)addVideo:(id)video toPlaylist:(id)playlist; // 0x162bd @end
kokoabim/iOSOpenDev-Framework-Header-Files
YouTube.framework/Headers/YTAccountFeedRequest.h
C
gpl-2.0
483
<!doctype html> <html class="theme-next mist use-motion" lang="zh-Hans"> <head> <meta charset="UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/> <meta http-equiv="Cache-Control" content="no-transform" /> <meta http-equiv="Cache-Control" content="no-siteapp" /> <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" /> <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css"> <link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" /> <link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" /> <meta name="keywords" content="Hexo, Zing" /> <link rel="alternate" href="/atom.xml" title="Zing" type="application/atom+xml" /> <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" /> <meta name="description" content="光荣在于平淡艰巨在于漫长无论我多早迎接这清晨在路上都会有人在我以为别人还在梦乡但无论什么时候这个世界都比我快一步"> <meta property="og:type" content="website"> <meta property="og:title" content="Zing"> <meta property="og:url" content="http://micorochio.github.io/tags/运维/index.html"> <meta property="og:site_name" content="Zing"> <meta property="og:description" content="光荣在于平淡艰巨在于漫长无论我多早迎接这清晨在路上都会有人在我以为别人还在梦乡但无论什么时候这个世界都比我快一步"> <meta name="twitter:card" content="summary"> <meta name="twitter:title" content="Zing"> <meta name="twitter:description" content="光荣在于平淡艰巨在于漫长无论我多早迎接这清晨在路上都会有人在我以为别人还在梦乡但无论什么时候这个世界都比我快一步"> <script type="text/javascript" id="hexo.configurations"> var NexT = window.NexT || {}; var CONFIG = { root: '/', scheme: 'Mist', sidebar: {"position":"right","display":"always","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false}, fancybox: true, motion: true, duoshuo: { userId: '0', author: '博主' }, algolia: { applicationID: '67GQC0CBTX', apiKey: 'c7cbdee3fb9a4a84e4e16302861d6ede', indexName: 'zing', hits: {"per_page":10}, labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"} } }; </script> <link rel="canonical" href="http://micorochio.github.io/tags/运维/"/> <title>标签: 运维 | Zing</title> </head> <body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans"> <div class="container sidebar-position-right "> <div class="headband"></div> <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader"> <div class="header-inner"><div class="site-brand-wrapper"> <div class="site-meta "> <div class="custom-logo-site-title"> <a href="/" class="brand" rel="start"> <span class="logo-line-before"><i></i></span> <span class="site-title">Zing</span> <span class="logo-line-after"><i></i></span> </a> </div> <p class="site-subtitle">不忘初心,方得始终</p> </div> <div class="site-nav-toggle"> <button> <span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span> </button> </div> </div> <nav class="site-nav"> <ul id="menu" class="menu"> <li class="menu-item menu-item-home"> <a href="/" rel="section"> <i class="menu-item-icon fa fa-fw fa-home"></i> <br /> 首页 </a> </li> <li class="menu-item menu-item-archives"> <a href="/archives" rel="section"> <i class="menu-item-icon fa fa-fw fa-archive"></i> <br /> 归档 </a> </li> <li class="menu-item menu-item-tags"> <a href="/tags" rel="section"> <i class="menu-item-icon fa fa-fw fa-tags"></i> <br /> 标签 </a> </li> <li class="menu-item menu-item-about"> <a href="/about" rel="section"> <i class="menu-item-icon fa fa-fw fa-user"></i> <br /> 关于 </a> </li> <li class="menu-item menu-item-全栈计划"> <a href="/fs-plan" rel="section"> <i class="menu-item-icon fa fa-fw fa-plane"></i> <br /> menu.全栈计划 </a> </li> <li class="menu-item menu-item-commonweal"> <a href="/404.htm" rel="section"> <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br /> 公益404 </a> </li> <li class="menu-item menu-item-search"> <a href="javascript:;" class="popup-trigger"> <i class="menu-item-icon fa fa-search fa-fw"></i> <br /> 搜索 </a> </li> </ul> <div class="site-search"> <div class="algolia-popup popup search-popup"> <div class="algolia-search"> <div class="algolia-search-input-icon"> <i class="fa fa-search"></i> </div> <div class="algolia-search-input" id="algolia-search-input"></div> </div> <div class="algolia-results"> <div id="algolia-stats"></div> <div id="algolia-hits"></div> <div id="algolia-pagination" class="algolia-pagination"></div> </div> <span class="popup-btn-close"> <i class="fa fa-times-circle"></i> </span> </div> </div> </nav> </div> </header> <main id="main" class="main"> <div class="main-inner"> <div class="content-wrap"> <div id="content" class="content"> <div id="posts" class="posts-collapse"> <div class="collection-title"> <h1>运维<small>标签</small> </h1> </div> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2017/06/19/ansible-learning-03/" itemprop="url"> <span itemprop="name">Ansible自动化部署从入门到弃坑</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2017-06-19T01:48:58+08:00" content="2017-06-19" > 06-19 </time> </div> </header> </article> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2017/06/05/ansible-learning-02/" itemprop="url"> <span itemprop="name">Ansible自动化部署入门</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2017-06-05T01:48:58+08:00" content="2017-06-05" > 06-05 </time> </div> </header> </article> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2017/05/31/ansible-learning-01/" itemprop="url"> <span itemprop="name">自动化部署工具 Ansible填坑记录</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2017-05-31T01:48:58+08:00" content="2017-05-31" > 05-31 </time> </div> </header> </article> </div> </div> </div> <div class="sidebar-toggle"> <div class="sidebar-toggle-line-wrap"> <span class="sidebar-toggle-line sidebar-toggle-line-first"></span> <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span> <span class="sidebar-toggle-line sidebar-toggle-line-last"></span> </div> </div> <aside id="sidebar" class="sidebar"> <div class="sidebar-inner"> <section class="site-overview sidebar-panel sidebar-panel-active"> <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"> <img class="site-author-image" itemprop="image" src="/image/head_3.png" alt="zing" /> <p class="site-author-name" itemprop="name">zing</p> <p class="site-description motion-element" itemprop="description"><br/>光荣在于平淡<br/>艰巨在于漫长<br/><br/><br/>无论我多早迎接这清晨<br/>在路上<br/>都会有人在<br/>我以为别人还在梦乡<br/>但无论什么时候<br/>这个世界都比我快一步</p> </div> <nav class="site-state motion-element"> <div class="site-state-item site-state-posts"> <a href="/archives"> <span class="site-state-item-count">46</span> <span class="site-state-item-name">日志</span> </a> </div> <div class="site-state-item site-state-tags"> <a href="/tags/index.html"> <span class="site-state-item-count">70</span> <span class="site-state-item-name">标签</span> </a> </div> </nav> <div class="feed-link motion-element"> <a href="/atom.xml" rel="alternate"> <i class="fa fa-rss"></i> RSS </a> </div> <div class="links-of-author motion-element"> </div> </section> </div> </aside> </div> </main> <footer id="footer" class="footer"> <div class="footer-inner"> <div class="copyright" > &copy; <span itemprop="copyrightYear">2018</span> <span class="with-love"> <i class="fa fa-heart"></i> </span> <span class="author" itemprop="copyrightHolder">zing</span> </div> <div class="powered-by"> 由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动 </div> <div class="theme-info"> 主题 - <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next"> NexT.Mist </a> </div> </div> </footer> <div class="back-to-top"> <i class="fa fa-arrow-up"></i> </div> </div> <script type="text/javascript"> if (Object.prototype.toString.call(window.Promise) !== '[object Function]') { window.Promise = null; } </script> <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script> <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script> <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script> <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script> <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script> <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script> <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script> <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script> <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script> <script type="text/javascript"> (function(){ var appid = 'cysYXx7FA'; var conf = 'e2355a388f5561a2ed245ad3c1a5d48c'; var width = window.innerWidth || document.documentElement.clientWidth; if (width < 960) { window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){ window.changyan.api.config({appid:appid,conf:conf})}); } })(); </script> <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script> <link rel="stylesheet" href="/lib/algolia-instant-search/instantsearch.min.css"> <script src="/lib/algolia-instant-search/instantsearch.min.js"></script> <script src="/js/src/algolia-search.js?v=5.1.1"></script> <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script> <script>AV.initialize("075L7uHacQltb04SleGNHG3G-gzGzoHsz", "s8bu3ivhYQbULV5pwlVel70f");</script> <script> function showTime(Counter) { var query = new AV.Query(Counter); var entries = []; var $visitors = $(".leancloud_visitors"); $visitors.each(function () { entries.push( $(this).attr("id").trim() ); }); query.containedIn('url', entries); query.find() .done(function (results) { var COUNT_CONTAINER_REF = '.leancloud-visitors-count'; if (results.length === 0) { $visitors.find(COUNT_CONTAINER_REF).text(0); return; } for (var i = 0; i < results.length; i++) { var item = results[i]; var url = item.get('url'); var time = item.get('time'); var element = document.getElementById(url); $(element).find(COUNT_CONTAINER_REF).text(time); } for(var i = 0; i < entries.length; i++) { var url = entries[i]; var element = document.getElementById(url); var countSpan = $(element).find(COUNT_CONTAINER_REF); if( countSpan.text() == '') { countSpan.text(0); } } }) .fail(function (object, error) { console.log("Error: " + error.code + " " + error.message); }); } function addCount(Counter) { var $visitors = $(".leancloud_visitors"); var url = $visitors.attr('id').trim(); var title = $visitors.attr('data-flag-title').trim(); var query = new AV.Query(Counter); query.equalTo("url", url); query.find({ success: function(results) { if (results.length > 0) { var counter = results[0]; counter.fetchWhenSave(true); counter.increment("time"); counter.save(null, { success: function(counter) { var $element = $(document.getElementById(url)); $element.find('.leancloud-visitors-count').text(counter.get('time')); }, error: function(counter, error) { console.log('Failed to save Visitor num, with error message: ' + error.message); } }); } else { var newcounter = new Counter(); /* Set ACL */ var acl = new AV.ACL(); acl.setPublicReadAccess(true); acl.setPublicWriteAccess(true); newcounter.setACL(acl); /* End Set ACL */ newcounter.set("title", title); newcounter.set("url", url); newcounter.set("time", 1); newcounter.save(null, { success: function(newcounter) { var $element = $(document.getElementById(url)); $element.find('.leancloud-visitors-count').text(newcounter.get('time')); }, error: function(newcounter, error) { console.log('Failed to create'); } }); } }, error: function(error) { console.log('Error:' + error.code + " " + error.message); } }); } $(function() { var Counter = AV.Object.extend("Counter"); if ($('.leancloud_visitors').length == 1) { addCount(Counter); } else if ($('.post-title-link').length > 1) { showTime(Counter); } }); </script> </body> </html>
micorochio/micorochio.github.io
tags/运维/index.html
HTML
gpl-2.0
17,795
/* * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2013-2014 Phoenixia Productions <phoenixia-gaming.no-ip.biz> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "mana_tombs.h" enum Yells { SAY_INTRO = 0, SAY_AGGRO = 1, SAY_SLAY = 2, SAY_SUMMON = 3, SAY_DEAD = 4 }; enum Spells { SPELL_BLINK = 34605, SPELL_FROSTBOLT = 32364, SPELL_FIREBALL = 32363, SPELL_FROSTNOVA = 32365, SPELL_ETHEREAL_BEACON = 32371, SPELL_ETHEREAL_BEACON_VISUAL = 32368, SPELL_ARCANE_BOLT = 15254, SPELL_ETHEREAL_APPRENTICE = 32372 }; enum Creatures { NPC_BEACON = 18431, NPC_SHAFFAR = 18344 }; enum EtherealApprentice { SPELL_ETHEREAL_APPRENTICE_FIREBOLT = 32369, SPELL_ETHEREAL_APPRENTICE_FROSTBOLT = 32370, EVENT_ETHEREAL_APPRENTICE_FIREBOLT = 1, EVENT_ETHEREAL_APPRENTICE_FROSTBOLT }; enum EtherealBeacon { EVENT_APPRENTICE = 1, EVENT_ARCANE_BOLT }; enum Misc { NR_INITIAL_BEACONS = 3 }; enum Events { EVENT_BLINK = 1, EVENT_BEACON, EVENT_FIREBALL, EVENT_FROSTBOLT, EVENT_FROST_NOVA }; enum Yor { SPELL_DOUBLE_BREATH = 38361, EVENT_DOUBLE_BREATH = 1 }; /*************** Boss : Nexus' Prince Shaffar ***************/ class boss_nexusprince_shaffar : public CreatureScript { public: boss_nexusprince_shaffar() : CreatureScript("boss_nexusprince_shaffar") {} struct boss_nexusprince_shaffarAI : public BossAI { boss_nexusprince_shaffarAI(Creature* creature) : BossAI(creature, DATA_NEXUSPRINCE_SHAFFAR) { _hasTaunted = false; } void Reset() override { _Reset(); float dist = 8.0f; float posX, posY, posZ, angle; me->GetHomePosition(posX, posY, posZ, angle); me->SummonCreature(NPC_BEACON, posX - dist, posY - dist, posZ, angle, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 7200000); me->SummonCreature(NPC_BEACON, posX - dist, posY + dist, posZ, angle, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 7200000); me->SummonCreature(NPC_BEACON, posX + dist, posY, posZ, angle, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 7200000); } void MoveInLineOfSight(Unit* who) override { if (!_hasTaunted && who->GetTypeId() == TYPEID_PLAYER && me->IsWithinDistInMap(who, 100.0f)) { Talk(SAY_INTRO); _hasTaunted = true; } } void EnterCombat(Unit* /*who*/) override { Talk(SAY_AGGRO); _EnterCombat(); events.ScheduleEvent(EVENT_BEACON, 10000); events.ScheduleEvent(EVENT_FIREBALL, 8000); events.ScheduleEvent(EVENT_FROSTBOLT, 4000); events.ScheduleEvent(EVENT_FROST_NOVA, 15000); } void JustSummoned(Creature* summoned) override { if (summoned->GetEntry() == NPC_BEACON) { summoned->CastSpell(summoned, SPELL_ETHEREAL_BEACON_VISUAL, false); if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) summoned->AI()->AttackStart(target); } summons.Summon(summoned); } void KilledUnit(Unit* victim) override { if (victim->GetTypeId() == TYPEID_PLAYER) Talk(SAY_SLAY); } void JustDied(Unit* /*killer*/) override { Talk(SAY_DEAD); _JustDied(); } void ExecuteEvent(uint32 eventId) override { switch (eventId) { case EVENT_BLINK: if (me->IsNonMeleeSpellCast(false)) me->InterruptNonMeleeSpells(true); if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == CHASE_MOTION_TYPE) me->GetMotionMaster()->MovementExpired(); DoCast(me, SPELL_BLINK); break; case EVENT_BEACON: if (!urand(0, 3)) Talk(SAY_SUMMON); DoCast(me, SPELL_ETHEREAL_BEACON, true); events.ScheduleEvent(EVENT_BEACON, 10000); break; case EVENT_FIREBALL: DoCastVictim(SPELL_FROSTBOLT); events.ScheduleEvent(EVENT_FIREBALL, urand(4500, 6000)); break; case EVENT_FROSTBOLT: DoCastVictim(SPELL_FROSTBOLT); events.ScheduleEvent(EVENT_FROSTBOLT, urand(4500, 6000)); break; case EVENT_FROST_NOVA: DoCast(me, SPELL_FROSTNOVA); events.ScheduleEvent(EVENT_FROST_NOVA, urand(17500, 25000)); events.ScheduleEvent(EVENT_BLINK, 1500); break; default: break; } } private: bool _hasTaunted; }; CreatureAI* GetAI(Creature* creature) const override { return GetManaTombsAI<boss_nexusprince_shaffarAI>(creature); } }; /*************** Creature : Ethereal Apprentice ***************/ class npc_ethereal_apprentice : public CreatureScript { public: npc_ethereal_apprentice() : CreatureScript("npc_ethereal_apprentice") {} struct npc_ethereal_apprenticeAI : public ScriptedAI { npc_ethereal_apprenticeAI(Creature* creature) : ScriptedAI(creature) {} void Reset() override { _events.Reset(); } void EnterCombat(Unit* /*who*/) override { _events.ScheduleEvent(EVENT_ETHEREAL_APPRENTICE_FIREBOLT, 3000); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case EVENT_ETHEREAL_APPRENTICE_FIREBOLT: DoCastVictim(SPELL_ETHEREAL_APPRENTICE_FIREBOLT, true); _events.ScheduleEvent(EVENT_ETHEREAL_APPRENTICE_FROSTBOLT, 3000); break; case EVENT_ETHEREAL_APPRENTICE_FROSTBOLT: DoCastVictim(SPELL_ETHEREAL_APPRENTICE_FROSTBOLT, true); _events.ScheduleEvent(EVENT_ETHEREAL_APPRENTICE_FIREBOLT, 3000); break; default: break; } } } private: EventMap _events; }; CreatureAI* GetAI(Creature* creature) const override { return new npc_ethereal_apprenticeAI(creature); } }; /*************** Creature : Ethereal Beacon ***************/ class npc_ethereal_beacon : public CreatureScript { public: npc_ethereal_beacon() : CreatureScript("npc_ethereal_beacon") {} struct npc_ethereal_beaconAI : public ScriptedAI { npc_ethereal_beaconAI(Creature* creature) : ScriptedAI(creature) {} void Reset() override { _events.Reset(); } void EnterCombat(Unit* who) override { if (Creature* shaffar = me->FindNearestCreature(NPC_SHAFFAR, 100.0f)) if (!shaffar->IsInCombat()) shaffar->AI()->AttackStart(who); _events.ScheduleEvent(EVENT_APPRENTICE, DUNGEON_MODE(20000, 10000)); _events.ScheduleEvent(EVENT_ARCANE_BOLT, 1000); } void JustSummoned(Creature* summoned) override { summoned->AI()->AttackStart(me->GetVictim()); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case EVENT_APPRENTICE: DoCast(me, SPELL_ETHEREAL_APPRENTICE, true); me->DespawnOrUnsummon(); break; case EVENT_ARCANE_BOLT: DoCastVictim(SPELL_ARCANE_BOLT); _events.ScheduleEvent(EVENT_ARCANE_BOLT, urand(2000, 4500)); break; default: break; } } } private: EventMap _events; }; CreatureAI* GetAI(Creature* creature) const override { return new npc_ethereal_beaconAI(creature); } }; /*************** Creature : Yor ***************/ class npc_yor : public CreatureScript { public: npc_yor() : CreatureScript("npc_yor") {} struct npc_yorAI : public ScriptedAI { npc_yorAI(Creature* creature) : ScriptedAI(creature) {} void Reset() override {} void EnterCombat(Unit* /*who*/) override { _events.ScheduleEvent(EVENT_DOUBLE_BREATH, urand(6000,9000)); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; _events.Update(diff); while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case EVENT_DOUBLE_BREATH: if (me->IsWithinDist(me->GetVictim(), ATTACK_DISTANCE)) DoCastVictim(SPELL_DOUBLE_BREATH); _events.ScheduleEvent(EVENT_DOUBLE_BREATH, urand(6000,9000)); break; default: break; } } DoMeleeAttackIfReady(); } private: EventMap _events; }; CreatureAI* GetAI(Creature* creature) const override { return new npc_yorAI(creature); } }; /*************** Add Scripts ***************/ void AddSC_boss_nexusprince_shaffar() { new boss_nexusprince_shaffar; new npc_ethereal_beacon; new npc_ethereal_apprentice; new npc_yor; }
PhoenixiaGaming/WoP-v4
src/server/scripts/Outland/Auchindoun/ManaTombs/boss_nexusprince_shaffar.cpp
C++
gpl-2.0
12,485
/** * @license AngularJS v1.3.11 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, document, undefined) {'use strict'; /** * @description * * This object provides a utility for producing rich Error messages within * Angular. It can be called as follows: * * var exampleMinErr = minErr('example'); * throw exampleMinErr('one', 'This {0} is {1}', foo, bar); * * The above creates an instance of minErr in the example namespace. The * resulting error will have a namespaced error code of example.one. The * resulting error will replace {0} with the value of foo, and {1} with the * value of bar. The object is not restricted in the number of arguments it can * take. * * If fewer arguments are specified than necessary for interpolation, the extra * interpolation markers will be preserved in the final string. * * Since data will be parsed statically during a build step, some restrictions * are applied with respect to how minErr instances are created and called. * Instances should have names of the form namespaceMinErr for a minErr created * using minErr('namespace') . Error codes, namespaces and template strings * should all be static strings, not variables or general expressions. * * @param {string} module The namespace to use for the new minErr instance. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning * error from returned function, for cases when a particular type of error is useful. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance */ function minErr(module, ErrorConstructor) { ErrorConstructor = ErrorConstructor || Error; return function() { var code = arguments[0], prefix = '[' + (module ? module + ':' : '') + code + '] ', template = arguments[1], templateArgs = arguments, message, i; message = prefix + template.replace(/\{\d+\}/g, function(match) { var index = +match.slice(1, -1), arg; if (index + 2 < templateArgs.length) { return toDebugString(templateArgs[index + 2]); } return match; }); message = message + '\nhttp://errors.angularjs.org/1.3.11/' + (module ? module + '/' : '') + code; for (i = 2; i < arguments.length; i++) { message = message + (i == 2 ? '?' : '&') + 'p' + (i - 2) + '=' + encodeURIComponent(toDebugString(arguments[i])); } return new ErrorConstructor(message); }; } /* We need to tell jshint what variables are being exported */ /* global angular: true, msie: true, jqLite: true, jQuery: true, slice: true, splice: true, push: true, toString: true, ngMinErr: true, angularModule: true, uid: true, REGEX_STRING_REGEXP: true, VALIDITY_STATE_PROPERTY: true, lowercase: true, uppercase: true, manualLowercase: true, manualUppercase: true, nodeName_: true, isArrayLike: true, forEach: true, sortedKeys: true, forEachSorted: true, reverseParams: true, nextUid: true, setHashKey: true, extend: true, int: true, inherit: true, noop: true, identity: true, valueFn: true, isUndefined: true, isDefined: true, isObject: true, isString: true, isNumber: true, isDate: true, isArray: true, isFunction: true, isRegExp: true, isWindow: true, isScope: true, isFile: true, isFormData: true, isBlob: true, isBoolean: true, isPromiseLike: true, trim: true, escapeForRegexp: true, isElement: true, makeMap: true, includes: true, arrayRemove: true, copy: true, shallowCopy: true, equals: true, csp: true, concat: true, sliceArgs: true, bind: true, toJsonReplacer: true, toJson: true, fromJson: true, startingTag: true, tryDecodeURIComponent: true, parseKeyValue: true, toKeyValue: true, encodeUriSegment: true, encodeUriQuery: true, angularInit: true, bootstrap: true, getTestability: true, snake_case: true, bindJQuery: true, assertArg: true, assertArgFn: true, assertNotHasOwnProperty: true, getter: true, getBlockNodes: true, hasOwnProperty: true, createMap: true, NODE_TYPE_ELEMENT: true, NODE_TYPE_TEXT: true, NODE_TYPE_COMMENT: true, NODE_TYPE_DOCUMENT: true, NODE_TYPE_DOCUMENT_FRAGMENT: true, */ //////////////////////////////////// /** * @ngdoc module * @name ng * @module ng * @description * * # ng (core module) * The ng module is loaded by default when an AngularJS application is started. The module itself * contains the essential components for an AngularJS application to function. The table below * lists a high level breakdown of each of the services/factories, filters, directives and testing * components available within this core module. * * <div doc-module-components="ng"></div> */ var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/; // The name of a form control's ValidityState property. // This is used so that it's possible for internal tests to create mock ValidityStates. var VALIDITY_STATE_PROPERTY = 'validity'; /** * @ngdoc function * @name angular.lowercase * @module ng * @kind function * * @description Converts the specified string to lowercase. * @param {string} string String to be converted to lowercase. * @returns {string} Lowercased string. */ var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;}; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * @ngdoc function * @name angular.uppercase * @module ng * @kind function * * @description Converts the specified string to uppercase. * @param {string} string String to be converted to uppercase. * @returns {string} Uppercased string. */ var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;}; var manualLowercase = function(s) { /* jshint bitwise: false */ return isString(s) ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);}) : s; }; var manualUppercase = function(s) { /* jshint bitwise: false */ return isString(s) ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);}) : s; }; // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods // with correct but slower alternatives. if ('i' !== 'I'.toLowerCase()) { lowercase = manualLowercase; uppercase = manualUppercase; } var msie, // holds major version number for IE, or NaN if UA is not IE. jqLite, // delay binding since jQuery could be loaded after us. jQuery, // delay binding slice = [].slice, splice = [].splice, push = [].push, toString = Object.prototype.toString, ngMinErr = minErr('ng'), /** @name angular */ angular = window.angular || (window.angular = {}), angularModule, uid = 0; /** * documentMode is an IE-only property * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx */ msie = document.documentMode; /** * @private * @param {*} obj * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments, * String ...) */ function isArrayLike(obj) { if (obj == null || isWindow(obj)) { return false; } var length = obj.length; if (obj.nodeType === NODE_TYPE_ELEMENT && length) { return true; } return isString(obj) || isArray(obj) || length === 0 || typeof length === 'number' && length > 0 && (length - 1) in obj; } /** * @ngdoc function * @name angular.forEach * @module ng * @kind function * * @description * Invokes the `iterator` function once for each item in `obj` collection, which can be either an * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value` * is the value of an object property or an array element, `key` is the object property key or * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional. * * It is worth noting that `.forEach` does not iterate over inherited properties because it filters * using the `hasOwnProperty` method. * * Unlike ES262's * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18), * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just * return the value provided. * ```js var values = {name: 'misko', gender: 'male'}; var log = []; angular.forEach(values, function(value, key) { this.push(key + ': ' + value); }, log); expect(log).toEqual(['name: misko', 'gender: male']); ``` * * @param {Object|Array} obj Object to iterate over. * @param {Function} iterator Iterator function. * @param {Object=} context Object to become context (`this`) for the iterator function. * @returns {Object|Array} Reference to `obj`. */ function forEach(obj, iterator, context) { var key, length; if (obj) { if (isFunction(obj)) { for (key in obj) { // Need to check if hasOwnProperty exists, // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) { iterator.call(context, obj[key], key, obj); } } } else if (isArray(obj) || isArrayLike(obj)) { var isPrimitive = typeof obj !== 'object'; for (key = 0, length = obj.length; key < length; key++) { if (isPrimitive || key in obj) { iterator.call(context, obj[key], key, obj); } } } else if (obj.forEach && obj.forEach !== forEach) { obj.forEach(iterator, context, obj); } else { for (key in obj) { if (obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key, obj); } } } } return obj; } function sortedKeys(obj) { return Object.keys(obj).sort(); } function forEachSorted(obj, iterator, context) { var keys = sortedKeys(obj); for (var i = 0; i < keys.length; i++) { iterator.call(context, obj[keys[i]], keys[i]); } return keys; } /** * when using forEach the params are value, key, but it is often useful to have key, value. * @param {function(string, *)} iteratorFn * @returns {function(*, string)} */ function reverseParams(iteratorFn) { return function(value, key) { iteratorFn(key, value); }; } /** * A consistent way of creating unique IDs in angular. * * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before * we hit number precision issues in JavaScript. * * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M * * @returns {number} an unique alpha-numeric string */ function nextUid() { return ++uid; } /** * Set or clear the hashkey for an object. * @param obj object * @param h the hashkey (!truthy to delete the hashkey) */ function setHashKey(obj, h) { if (h) { obj.$$hashKey = h; } else { delete obj.$$hashKey; } } /** * @ngdoc function * @name angular.extend * @module ng * @kind function * * @description * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s) * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`. * Note: Keep in mind that `angular.extend` does not support recursive merge (deep copy). * * @param {Object} dst Destination object. * @param {...Object} src Source object(s). * @returns {Object} Reference to `dst`. */ function extend(dst) { var h = dst.$$hashKey; for (var i = 1, ii = arguments.length; i < ii; i++) { var obj = arguments[i]; if (obj) { var keys = Object.keys(obj); for (var j = 0, jj = keys.length; j < jj; j++) { var key = keys[j]; dst[key] = obj[key]; } } } setHashKey(dst, h); return dst; } function int(str) { return parseInt(str, 10); } function inherit(parent, extra) { return extend(Object.create(parent), extra); } /** * @ngdoc function * @name angular.noop * @module ng * @kind function * * @description * A function that performs no operations. This function can be useful when writing code in the * functional style. ```js function foo(callback) { var result = calculateResult(); (callback || angular.noop)(result); } ``` */ function noop() {} noop.$inject = []; /** * @ngdoc function * @name angular.identity * @module ng * @kind function * * @description * A function that returns its first argument. This function is useful when writing code in the * functional style. * ```js function transformer(transformationFn, value) { return (transformationFn || angular.identity)(value); }; ``` * @param {*} value to be returned. * @returns {*} the value passed in. */ function identity($) {return $;} identity.$inject = []; function valueFn(value) {return function() {return value;};} /** * @ngdoc function * @name angular.isUndefined * @module ng * @kind function * * @description * Determines if a reference is undefined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is undefined. */ function isUndefined(value) {return typeof value === 'undefined';} /** * @ngdoc function * @name angular.isDefined * @module ng * @kind function * * @description * Determines if a reference is defined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is defined. */ function isDefined(value) {return typeof value !== 'undefined';} /** * @ngdoc function * @name angular.isObject * @module ng * @kind function * * @description * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not * considered to be objects. Note that JavaScript arrays are objects. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Object` but not `null`. */ function isObject(value) { // http://jsperf.com/isobject4 return value !== null && typeof value === 'object'; } /** * @ngdoc function * @name angular.isString * @module ng * @kind function * * @description * Determines if a reference is a `String`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `String`. */ function isString(value) {return typeof value === 'string';} /** * @ngdoc function * @name angular.isNumber * @module ng * @kind function * * @description * Determines if a reference is a `Number`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Number`. */ function isNumber(value) {return typeof value === 'number';} /** * @ngdoc function * @name angular.isDate * @module ng * @kind function * * @description * Determines if a value is a date. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Date`. */ function isDate(value) { return toString.call(value) === '[object Date]'; } /** * @ngdoc function * @name angular.isArray * @module ng * @kind function * * @description * Determines if a reference is an `Array`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Array`. */ var isArray = Array.isArray; /** * @ngdoc function * @name angular.isFunction * @module ng * @kind function * * @description * Determines if a reference is a `Function`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Function`. */ function isFunction(value) {return typeof value === 'function';} /** * Determines if a value is a regular expression object. * * @private * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `RegExp`. */ function isRegExp(value) { return toString.call(value) === '[object RegExp]'; } /** * Checks if `obj` is a window object. * * @private * @param {*} obj Object to check * @returns {boolean} True if `obj` is a window obj. */ function isWindow(obj) { return obj && obj.window === obj; } function isScope(obj) { return obj && obj.$evalAsync && obj.$watch; } function isFile(obj) { return toString.call(obj) === '[object File]'; } function isFormData(obj) { return toString.call(obj) === '[object FormData]'; } function isBlob(obj) { return toString.call(obj) === '[object Blob]'; } function isBoolean(value) { return typeof value === 'boolean'; } function isPromiseLike(obj) { return obj && isFunction(obj.then); } var trim = function(value) { return isString(value) ? value.trim() : value; }; // Copied from: // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021 // Prereq: s is a string. var escapeForRegexp = function(s) { return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1'). replace(/\x08/g, '\\x08'); }; /** * @ngdoc function * @name angular.isElement * @module ng * @kind function * * @description * Determines if a reference is a DOM element (or wrapped jQuery element). * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element). */ function isElement(node) { return !!(node && (node.nodeName // we are a direct element || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API } /** * @param str 'key1,key2,...' * @returns {object} in the form of {key1:true, key2:true, ...} */ function makeMap(str) { var obj = {}, items = str.split(","), i; for (i = 0; i < items.length; i++) obj[ items[i] ] = true; return obj; } function nodeName_(element) { return lowercase(element.nodeName || (element[0] && element[0].nodeName)); } function includes(array, obj) { return Array.prototype.indexOf.call(array, obj) != -1; } function arrayRemove(array, value) { var index = array.indexOf(value); if (index >= 0) array.splice(index, 1); return value; } /** * @ngdoc function * @name angular.copy * @module ng * @kind function * * @description * Creates a deep copy of `source`, which should be an object or an array. * * * If no destination is supplied, a copy of the object or array is created. * * If a destination is provided, all of its elements (for arrays) or properties (for objects) * are deleted and then all elements/properties from the source are copied to it. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned. * * If `source` is identical to 'destination' an exception will be thrown. * * @param {*} source The source that will be used to make a copy. * Can be any type, including primitives, `null`, and `undefined`. * @param {(Object|Array)=} destination Destination into which the source is copied. If * provided, must be of the same type as `source`. * @returns {*} The copy or updated `destination`, if `destination` was specified. * * @example <example module="copyExample"> <file name="index.html"> <div ng-controller="ExampleController"> <form novalidate class="simple-form"> Name: <input type="text" ng-model="user.name" /><br /> E-mail: <input type="email" ng-model="user.email" /><br /> Gender: <input type="radio" ng-model="user.gender" value="male" />male <input type="radio" ng-model="user.gender" value="female" />female<br /> <button ng-click="reset()">RESET</button> <button ng-click="update(user)">SAVE</button> </form> <pre>form = {{user | json}}</pre> <pre>master = {{master | json}}</pre> </div> <script> angular.module('copyExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.master= {}; $scope.update = function(user) { // Example with 1 argument $scope.master= angular.copy(user); }; $scope.reset = function() { // Example with 2 arguments angular.copy($scope.master, $scope.user); }; $scope.reset(); }]); </script> </file> </example> */ function copy(source, destination, stackSource, stackDest) { if (isWindow(source) || isScope(source)) { throw ngMinErr('cpws', "Can't copy! Making copies of Window or Scope instances is not supported."); } if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, [], stackSource, stackDest); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isRegExp(source)) { destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]); destination.lastIndex = source.lastIndex; } else if (isObject(source)) { var emptyObject = Object.create(Object.getPrototypeOf(source)); destination = copy(source, emptyObject, stackSource, stackDest); } } } else { if (source === destination) throw ngMinErr('cpi', "Can't copy! Source and destination are identical."); stackSource = stackSource || []; stackDest = stackDest || []; if (isObject(source)) { var index = stackSource.indexOf(source); if (index !== -1) return stackDest[index]; stackSource.push(source); stackDest.push(destination); } var result; if (isArray(source)) { destination.length = 0; for (var i = 0; i < source.length; i++) { result = copy(source[i], null, stackSource, stackDest); if (isObject(source[i])) { stackSource.push(source[i]); stackDest.push(result); } destination.push(result); } } else { var h = destination.$$hashKey; if (isArray(destination)) { destination.length = 0; } else { forEach(destination, function(value, key) { delete destination[key]; }); } for (var key in source) { if (source.hasOwnProperty(key)) { result = copy(source[key], null, stackSource, stackDest); if (isObject(source[key])) { stackSource.push(source[key]); stackDest.push(result); } destination[key] = result; } } setHashKey(destination,h); } } return destination; } /** * Creates a shallow copy of an object, an array or a primitive. * * Assumes that there are no proto properties for objects. */ function shallowCopy(src, dst) { if (isArray(src)) { dst = dst || []; for (var i = 0, ii = src.length; i < ii; i++) { dst[i] = src[i]; } } else if (isObject(src)) { dst = dst || {}; for (var key in src) { if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) { dst[key] = src[key]; } } } return dst || src; } /** * @ngdoc function * @name angular.equals * @module ng * @kind function * * @description * Determines if two objects or two values are equivalent. Supports value types, regular * expressions, arrays and objects. * * Two objects or values are considered equivalent if at least one of the following is true: * * * Both objects or values pass `===` comparison. * * Both objects or values are of the same type and all of their properties are equal by * comparing them with `angular.equals`. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal) * * Both values represent the same regular expression (In JavaScript, * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual * representation matches). * * During a property comparison, properties of `function` type and properties with names * that begin with `$` are ignored. * * Scope and DOMWindow objects are being compared only by identify (`===`). * * @param {*} o1 Object or value to compare. * @param {*} o2 Object or value to compare. * @returns {boolean} True if arguments are equal. */ function equals(o1, o2) { if (o1 === o2) return true; if (o1 === null || o2 === null) return false; if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2) { if (t1 == 'object') { if (isArray(o1)) { if (!isArray(o2)) return false; if ((length = o1.length) == o2.length) { for (key = 0; key < length; key++) { if (!equals(o1[key], o2[key])) return false; } return true; } } else if (isDate(o1)) { if (!isDate(o2)) return false; return equals(o1.getTime(), o2.getTime()); } else if (isRegExp(o1) && isRegExp(o2)) { return o1.toString() == o2.toString(); } else { if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false; keySet = {}; for (key in o1) { if (key.charAt(0) === '$' || isFunction(o1[key])) continue; if (!equals(o1[key], o2[key])) return false; keySet[key] = true; } for (key in o2) { if (!keySet.hasOwnProperty(key) && key.charAt(0) !== '$' && o2[key] !== undefined && !isFunction(o2[key])) return false; } return true; } } } return false; } var csp = function() { if (isDefined(csp.isActive_)) return csp.isActive_; var active = !!(document.querySelector('[ng-csp]') || document.querySelector('[data-ng-csp]')); if (!active) { try { /* jshint -W031, -W054 */ new Function(''); /* jshint +W031, +W054 */ } catch (e) { active = true; } } return (csp.isActive_ = active); }; function concat(array1, array2, index) { return array1.concat(slice.call(array2, index)); } function sliceArgs(args, startIndex) { return slice.call(args, startIndex || 0); } /* jshint -W101 */ /** * @ngdoc function * @name angular.bind * @module ng * @kind function * * @description * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for * `fn`). You can supply optional `args` that are prebound to the function. This feature is also * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application). * * @param {Object} self Context which `fn` should be evaluated in. * @param {function()} fn Function to be bound. * @param {...*} args Optional arguments to be prebound to the `fn` function call. * @returns {function()} Function that wraps the `fn` with all the specified bindings. */ /* jshint +W101 */ function bind(self, fn) { var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : []; if (isFunction(fn) && !(fn instanceof RegExp)) { return curryArgs.length ? function() { return arguments.length ? fn.apply(self, concat(curryArgs, arguments, 0)) : fn.apply(self, curryArgs); } : function() { return arguments.length ? fn.apply(self, arguments) : fn.call(self); }; } else { // in IE, native methods are not functions so they cannot be bound (note: they don't need to be) return fn; } } function toJsonReplacer(key, value) { var val = value; if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') { val = undefined; } else if (isWindow(value)) { val = '$WINDOW'; } else if (value && document === value) { val = '$DOCUMENT'; } else if (isScope(value)) { val = '$SCOPE'; } return val; } /** * @ngdoc function * @name angular.toJson * @module ng * @kind function * * @description * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be * stripped since angular uses this notation internally. * * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. * @param {boolean|number=} pretty If set to true, the JSON output will contain newlines and whitespace. * If set to an integer, the JSON output will contain that many spaces per indentation (the default is 2). * @returns {string|undefined} JSON-ified string representing `obj`. */ function toJson(obj, pretty) { if (typeof obj === 'undefined') return undefined; if (!isNumber(pretty)) { pretty = pretty ? 2 : null; } return JSON.stringify(obj, toJsonReplacer, pretty); } /** * @ngdoc function * @name angular.fromJson * @module ng * @kind function * * @description * Deserializes a JSON string. * * @param {string} json JSON string to deserialize. * @returns {Object|Array|string|number} Deserialized JSON string. */ function fromJson(json) { return isString(json) ? JSON.parse(json) : json; } /** * @returns {string} Returns the string representation of the element. */ function startingTag(element) { element = jqLite(element).clone(); try { // turns out IE does not let you set .html() on elements which // are not allowed to have children. So we just ignore it. element.empty(); } catch (e) {} var elemHtml = jqLite('<div>').append(element).html(); try { return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) : elemHtml. match(/^(<[^>]+>)/)[1]. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); }); } catch (e) { return lowercase(elemHtml); } } ///////////////////////////////////////////////// /** * Tries to decode the URI component without throwing an exception. * * @private * @param str value potential URI component to check. * @returns {boolean} True if `value` can be decoded * with the decodeURIComponent function. */ function tryDecodeURIComponent(value) { try { return decodeURIComponent(value); } catch (e) { // Ignore any invalid uri component } } /** * Parses an escaped url query string into key-value pairs. * @returns {Object.<string,boolean|Array>} */ function parseKeyValue(/**string*/keyValue) { var obj = {}, key_value, key; forEach((keyValue || "").split('&'), function(keyValue) { if (keyValue) { key_value = keyValue.replace(/\+/g,'%20').split('='); key = tryDecodeURIComponent(key_value[0]); if (isDefined(key)) { var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true; if (!hasOwnProperty.call(obj, key)) { obj[key] = val; } else if (isArray(obj[key])) { obj[key].push(val); } else { obj[key] = [obj[key],val]; } } } }); return obj; } function toKeyValue(obj) { var parts = []; forEach(obj, function(value, key) { if (isArray(value)) { forEach(value, function(arrayValue) { parts.push(encodeUriQuery(key, true) + (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true))); }); } else { parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true))); } }); return parts.length ? parts.join('&') : ''; } /** * We need our custom method because encodeURIComponent is too aggressive and doesn't follow * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path * segments: * segment = *pchar * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * pct-encoded = "%" HEXDIG HEXDIG * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriSegment(val) { return encodeUriQuery(val, true). replace(/%26/gi, '&'). replace(/%3D/gi, '='). replace(/%2B/gi, '+'); } /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriQuery(val, pctEncodeSpaces) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace(/%3B/gi, ';'). replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); } var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-']; function getNgAttribute(element, ngAttr) { var attr, i, ii = ngAttrPrefixes.length; element = jqLite(element); for (i = 0; i < ii; ++i) { attr = ngAttrPrefixes[i] + ngAttr; if (isString(attr = element.attr(attr))) { return attr; } } return null; } /** * @ngdoc directive * @name ngApp * @module ng * * @element ANY * @param {angular.Module} ngApp an optional application * {@link angular.module module} name to load. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be * created in "strict-di" mode. This means that the application will fail to invoke functions which * do not use explicit function annotation (and are thus unsuitable for minification), as described * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in * tracking down the root of these bugs. * * @description * * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive * designates the **root element** of the application and is typically placed near the root element * of the page - e.g. on the `<body>` or `<html>` tags. * * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp` * found in the document will be used to define the root element to auto-bootstrap as an * application. To run multiple applications in an HTML document you must manually bootstrap them using * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other. * * You can specify an **AngularJS module** to be used as the root module for the application. This * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It * should contain the application code needed or have dependencies on other modules that will * contain the code. See {@link angular.module} for more information. * * In the example below if the `ngApp` directive were not placed on the `html` element then the * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}` * would not be resolved to `3`. * * `ngApp` is the easiest, and most common way to bootstrap an application. * <example module="ngAppDemo"> <file name="index.html"> <div ng-controller="ngAppDemoController"> I can add: {{a}} + {{b}} = {{ a+b }} </div> </file> <file name="script.js"> angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) { $scope.a = 1; $scope.b = 2; }); </file> </example> * * Using `ngStrictDi`, you would see something like this: * <example ng-app-included="true"> <file name="index.html"> <div ng-app="ngAppStrictDemo" ng-strict-di> <div ng-controller="GoodController1"> I can add: {{a}} + {{b}} = {{ a+b }} <p>This renders because the controller does not fail to instantiate, by using explicit annotation style (see script.js for details) </p> </div> <div ng-controller="GoodController2"> Name: <input ng-model="name"><br /> Hello, {{name}}! <p>This renders because the controller does not fail to instantiate, by using explicit annotation style (see script.js for details) </p> </div> <div ng-controller="BadController"> I can add: {{a}} + {{b}} = {{ a+b }} <p>The controller could not be instantiated, due to relying on automatic function annotations (which are disabled in strict mode). As such, the content of this section is not interpolated, and there should be an error in your web console. </p> </div> </div> </file> <file name="script.js"> angular.module('ngAppStrictDemo', []) // BadController will fail to instantiate, due to relying on automatic function annotation, // rather than an explicit annotation .controller('BadController', function($scope) { $scope.a = 1; $scope.b = 2; }) // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated, // due to using explicit annotations using the array style and $inject property, respectively. .controller('GoodController1', ['$scope', function($scope) { $scope.a = 1; $scope.b = 2; }]) .controller('GoodController2', GoodController2); function GoodController2($scope) { $scope.name = "World"; } GoodController2.$inject = ['$scope']; </file> <file name="style.css"> div[ng-controller] { margin-bottom: 1em; -webkit-border-radius: 4px; border-radius: 4px; border: 1px solid; padding: .5em; } div[ng-controller^=Good] { border-color: #d6e9c6; background-color: #dff0d8; color: #3c763d; } div[ng-controller^=Bad] { border-color: #ebccd1; background-color: #f2dede; color: #a94442; margin-bottom: 0; } </file> </example> */ function angularInit(element, bootstrap) { var appElement, module, config = {}; // The element `element` has priority over any other element forEach(ngAttrPrefixes, function(prefix) { var name = prefix + 'app'; if (!appElement && element.hasAttribute && element.hasAttribute(name)) { appElement = element; module = element.getAttribute(name); } }); forEach(ngAttrPrefixes, function(prefix) { var name = prefix + 'app'; var candidate; if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) { appElement = candidate; module = candidate.getAttribute(name); } }); if (appElement) { config.strictDi = getNgAttribute(appElement, "strict-di") !== null; bootstrap(appElement, module ? [module] : [], config); } } /** * @ngdoc function * @name angular.bootstrap * @module ng * @description * Use this function to manually start up angular application. * * See: {@link guide/bootstrap Bootstrap} * * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually. * They must use {@link ng.directive:ngApp ngApp}. * * Angular will detect if it has been loaded into the browser more than once and only allow the * first loaded script to be bootstrapped and will report a warning to the browser console for * each of the subsequent scripts. This prevents strange results in applications, where otherwise * multiple instances of Angular try to work on the DOM. * * ```html * <!doctype html> * <html> * <body> * <div ng-controller="WelcomeController"> * {{greeting}} * </div> * * <script src="angular.js"></script> * <script> * var app = angular.module('demo', []) * .controller('WelcomeController', function($scope) { * $scope.greeting = 'Welcome!'; * }); * angular.bootstrap(document, ['demo']); * </script> * </body> * </html> * ``` * * @param {DOMElement} element DOM element which is the root of angular application. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application. * Each item in the array should be the name of a predefined module or a (DI annotated) * function that will be invoked by the injector as a `config` block. * See: {@link angular.module modules} * @param {Object=} config an object for defining configuration options for the application. The * following keys are supported: * * * `strictDi` - disable automatic function annotation for the application. This is meant to * assist in finding bugs which break minified code. Defaults to `false`. * * @returns {auto.$injector} Returns the newly created injector for this app. */ function bootstrap(element, modules, config) { if (!isObject(config)) config = {}; var defaultConfig = { strictDi: false }; config = extend(defaultConfig, config); var doBootstrap = function() { element = jqLite(element); if (element.injector()) { var tag = (element[0] === document) ? 'document' : startingTag(element); //Encode angle brackets to prevent input from being sanitized to empty string #8683 throw ngMinErr( 'btstrpd', "App Already Bootstrapped with this Element '{0}'", tag.replace(/</,'&lt;').replace(/>/,'&gt;')); } modules = modules || []; modules.unshift(['$provide', function($provide) { $provide.value('$rootElement', element); }]); if (config.debugInfoEnabled) { // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`. modules.push(['$compileProvider', function($compileProvider) { $compileProvider.debugInfoEnabled(true); }]); } modules.unshift('ng'); var injector = createInjector(modules, config.strictDi); injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', function bootstrapApply(scope, element, compile, injector) { scope.$apply(function() { element.data('$injector', injector); compile(element)(scope); }); }] ); return injector; }; var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/; var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/; if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) { config.debugInfoEnabled = true; window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, ''); } if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) { return doBootstrap(); } window.name = window.name.replace(NG_DEFER_BOOTSTRAP, ''); angular.resumeBootstrap = function(extraModules) { forEach(extraModules, function(module) { modules.push(module); }); doBootstrap(); }; } /** * @ngdoc function * @name angular.reloadWithDebugInfo * @module ng * @description * Use this function to reload the current application with debug information turned on. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`. * * See {@link ng.$compileProvider#debugInfoEnabled} for more. */ function reloadWithDebugInfo() { window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name; window.location.reload(); } /** * @name angular.getTestability * @module ng * @description * Get the testability service for the instance of Angular on the given * element. * @param {DOMElement} element DOM element which is the root of angular application. */ function getTestability(rootElement) { var injector = angular.element(rootElement).injector(); if (!injector) { throw ngMinErr('test', 'no injector found for element argument to getTestability'); } return injector.get('$$testability'); } var SNAKE_CASE_REGEXP = /[A-Z]/g; function snake_case(name, separator) { separator = separator || '_'; return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); } var bindJQueryFired = false; var skipDestroyOnNextJQueryCleanData; function bindJQuery() { var originalCleanData; if (bindJQueryFired) { return; } // bind to jQuery if present; jQuery = window.jQuery; // Use jQuery if it exists with proper functionality, otherwise default to us. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older // versions. It will not work for sure with jQuery <1.7, though. if (jQuery && jQuery.fn.on) { jqLite = jQuery; extend(jQuery.fn, { scope: JQLitePrototype.scope, isolateScope: JQLitePrototype.isolateScope, controller: JQLitePrototype.controller, injector: JQLitePrototype.injector, inheritedData: JQLitePrototype.inheritedData }); // All nodes removed from the DOM via various jQuery APIs like .remove() // are passed through jQuery.cleanData. Monkey-patch this method to fire // the $destroy event on all removed nodes. originalCleanData = jQuery.cleanData; jQuery.cleanData = function(elems) { var events; if (!skipDestroyOnNextJQueryCleanData) { for (var i = 0, elem; (elem = elems[i]) != null; i++) { events = jQuery._data(elem, "events"); if (events && events.$destroy) { jQuery(elem).triggerHandler('$destroy'); } } } else { skipDestroyOnNextJQueryCleanData = false; } originalCleanData(elems); }; } else { jqLite = JQLite; } angular.element = jqLite; // Prevent double-proxying. bindJQueryFired = true; } /** * throw error if the argument is falsy. */ function assertArg(arg, name, reason) { if (!arg) { throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required")); } return arg; } function assertArgFn(arg, name, acceptArrayAnnotation) { if (acceptArrayAnnotation && isArray(arg)) { arg = arg[arg.length - 1]; } assertArg(isFunction(arg), name, 'not a function, got ' + (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg)); return arg; } /** * throw error if the name given is hasOwnProperty * @param {String} name the name to test * @param {String} context the context in which the name is used, such as module or directive */ function assertNotHasOwnProperty(name, context) { if (name === 'hasOwnProperty') { throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context); } } /** * Return the value accessible from the object by path. Any undefined traversals are ignored * @param {Object} obj starting object * @param {String} path path to traverse * @param {boolean} [bindFnToScope=true] * @returns {Object} value as accessible by path */ //TODO(misko): this function needs to be removed function getter(obj, path, bindFnToScope) { if (!path) return obj; var keys = path.split('.'); var key; var lastInstance = obj; var len = keys.length; for (var i = 0; i < len; i++) { key = keys[i]; if (obj) { obj = (lastInstance = obj)[key]; } } if (!bindFnToScope && isFunction(obj)) { return bind(lastInstance, obj); } return obj; } /** * Return the DOM siblings between the first and last node in the given array. * @param {Array} array like object * @returns {jqLite} jqLite collection containing the nodes */ function getBlockNodes(nodes) { // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original // collection, otherwise update the original collection. var node = nodes[0]; var endNode = nodes[nodes.length - 1]; var blockNodes = [node]; do { node = node.nextSibling; if (!node) break; blockNodes.push(node); } while (node !== endNode); return jqLite(blockNodes); } /** * Creates a new object without a prototype. This object is useful for lookup without having to * guard against prototypically inherited properties via hasOwnProperty. * * Related micro-benchmarks: * - http://jsperf.com/object-create2 * - http://jsperf.com/proto-map-lookup/2 * - http://jsperf.com/for-in-vs-object-keys2 * * @returns {Object} */ function createMap() { return Object.create(null); } var NODE_TYPE_ELEMENT = 1; var NODE_TYPE_TEXT = 3; var NODE_TYPE_COMMENT = 8; var NODE_TYPE_DOCUMENT = 9; var NODE_TYPE_DOCUMENT_FRAGMENT = 11; /** * @ngdoc type * @name angular.Module * @module ng * @description * * Interface for configuring angular {@link angular.module modules}. */ function setupModuleLoader(window) { var $injectorMinErr = minErr('$injector'); var ngMinErr = minErr('ng'); function ensure(obj, name, factory) { return obj[name] || (obj[name] = factory()); } var angular = ensure(window, 'angular', Object); // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap angular.$$minErr = angular.$$minErr || minErr; return ensure(angular, 'module', function() { /** @type {Object.<string, angular.Module>} */ var modules = {}; /** * @ngdoc function * @name angular.module * @module ng * @description * * The `angular.module` is a global place for creating, registering and retrieving Angular * modules. * All modules (angular core or 3rd party) that should be available to an application must be * registered using this mechanism. * * When passed two or more arguments, a new module is created. If passed only one argument, an * existing module (the name passed as the first argument to `module`) is retrieved. * * * # Module * * A module is a collection of services, directives, controllers, filters, and configuration information. * `angular.module` is used to configure the {@link auto.$injector $injector}. * * ```js * // Create a new module * var myModule = angular.module('myModule', []); * * // register a new service * myModule.value('appName', 'MyCoolApp'); * * // configure existing services inside initialization blocks. * myModule.config(['$locationProvider', function($locationProvider) { * // Configure existing providers * $locationProvider.hashPrefix('!'); * }]); * ``` * * Then you can create an injector and load your modules like this: * * ```js * var injector = angular.injector(['ng', 'myModule']) * ``` * * However it's more likely that you'll just use * {@link ng.directive:ngApp ngApp} or * {@link angular.bootstrap} to simplify this process for you. * * @param {!string} name The name of the module to create or retrieve. * @param {!Array.<string>=} requires If specified then new module is being created. If * unspecified then the module is being retrieved for further configuration. * @param {Function=} configFn Optional configuration function for the module. Same as * {@link angular.Module#config Module#config()}. * @returns {module} new module with the {@link angular.Module} api. */ return function module(name, requires, configFn) { var assertNotHasOwnProperty = function(name, context) { if (name === 'hasOwnProperty') { throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); } }; assertNotHasOwnProperty(name, 'module'); if (requires && modules.hasOwnProperty(name)) { modules[name] = null; } return ensure(modules, name, function() { if (!requires) { throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " + "the module name or forgot to load it. If registering a module ensure that you " + "specify the dependencies as the second argument.", name); } /** @type {!Array.<Array.<*>>} */ var invokeQueue = []; /** @type {!Array.<Function>} */ var configBlocks = []; /** @type {!Array.<Function>} */ var runBlocks = []; var config = invokeLater('$injector', 'invoke', 'push', configBlocks); /** @type {angular.Module} */ var moduleInstance = { // Private state _invokeQueue: invokeQueue, _configBlocks: configBlocks, _runBlocks: runBlocks, /** * @ngdoc property * @name angular.Module#requires * @module ng * * @description * Holds the list of modules which the injector will load before the current module is * loaded. */ requires: requires, /** * @ngdoc property * @name angular.Module#name * @module ng * * @description * Name of the module. */ name: name, /** * @ngdoc method * @name angular.Module#provider * @module ng * @param {string} name service name * @param {Function} providerType Construction function for creating new instance of the * service. * @description * See {@link auto.$provide#provider $provide.provider()}. */ provider: invokeLater('$provide', 'provider'), /** * @ngdoc method * @name angular.Module#factory * @module ng * @param {string} name service name * @param {Function} providerFunction Function for creating new instance of the service. * @description * See {@link auto.$provide#factory $provide.factory()}. */ factory: invokeLater('$provide', 'factory'), /** * @ngdoc method * @name angular.Module#service * @module ng * @param {string} name service name * @param {Function} constructor A constructor function that will be instantiated. * @description * See {@link auto.$provide#service $provide.service()}. */ service: invokeLater('$provide', 'service'), /** * @ngdoc method * @name angular.Module#value * @module ng * @param {string} name service name * @param {*} object Service instance object. * @description * See {@link auto.$provide#value $provide.value()}. */ value: invokeLater('$provide', 'value'), /** * @ngdoc method * @name angular.Module#constant * @module ng * @param {string} name constant name * @param {*} object Constant value. * @description * Because the constant are fixed, they get applied before other provide methods. * See {@link auto.$provide#constant $provide.constant()}. */ constant: invokeLater('$provide', 'constant', 'unshift'), /** * @ngdoc method * @name angular.Module#animation * @module ng * @param {string} name animation name * @param {Function} animationFactory Factory function for creating new instance of an * animation. * @description * * **NOTE**: animations take effect only if the **ngAnimate** module is loaded. * * * Defines an animation hook that can be later used with * {@link ngAnimate.$animate $animate} service and directives that use this service. * * ```js * module.animation('.animation-name', function($inject1, $inject2) { * return { * eventName : function(element, done) { * //code to run the animation * //once complete, then run done() * return function cancellationFunction(element) { * //code to cancel the animation * } * } * } * }) * ``` * * See {@link ng.$animateProvider#register $animateProvider.register()} and * {@link ngAnimate ngAnimate module} for more information. */ animation: invokeLater('$animateProvider', 'register'), /** * @ngdoc method * @name angular.Module#filter * @module ng * @param {string} name Filter name. * @param {Function} filterFactory Factory function for creating new instance of filter. * @description * See {@link ng.$filterProvider#register $filterProvider.register()}. */ filter: invokeLater('$filterProvider', 'register'), /** * @ngdoc method * @name angular.Module#controller * @module ng * @param {string|Object} name Controller name, or an object map of controllers where the * keys are the names and the values are the constructors. * @param {Function} constructor Controller constructor function. * @description * See {@link ng.$controllerProvider#register $controllerProvider.register()}. */ controller: invokeLater('$controllerProvider', 'register'), /** * @ngdoc method * @name angular.Module#directive * @module ng * @param {string|Object} name Directive name, or an object map of directives where the * keys are the names and the values are the factories. * @param {Function} directiveFactory Factory function for creating new instance of * directives. * @description * See {@link ng.$compileProvider#directive $compileProvider.directive()}. */ directive: invokeLater('$compileProvider', 'directive'), /** * @ngdoc method * @name angular.Module#config * @module ng * @param {Function} configFn Execute this function on module load. Useful for service * configuration. * @description * Use this method to register work which needs to be performed on module loading. * For more about how to configure services, see * {@link providers#provider-recipe Provider Recipe}. */ config: config, /** * @ngdoc method * @name angular.Module#run * @module ng * @param {Function} initializationFn Execute this function after injector creation. * Useful for application initialization. * @description * Use this method to register work which should be performed when the injector is done * loading all modules. */ run: function(block) { runBlocks.push(block); return this; } }; if (configFn) { config(configFn); } return moduleInstance; /** * @param {string} provider * @param {string} method * @param {String=} insertMethod * @returns {angular.Module} */ function invokeLater(provider, method, insertMethod, queue) { if (!queue) queue = invokeQueue; return function() { queue[insertMethod || 'push']([provider, method, arguments]); return moduleInstance; }; } }); }; }); } /* global: toDebugString: true */ function serializeObject(obj) { var seen = []; return JSON.stringify(obj, function(key, val) { val = toJsonReplacer(key, val); if (isObject(val)) { if (seen.indexOf(val) >= 0) return '<<already seen>>'; seen.push(val); } return val; }); } function toDebugString(obj) { if (typeof obj === 'function') { return obj.toString().replace(/ \{[\s\S]*$/, ''); } else if (typeof obj === 'undefined') { return 'undefined'; } else if (typeof obj !== 'string') { return serializeObject(obj); } return obj; } /* global angularModule: true, version: true, $LocaleProvider, $CompileProvider, htmlAnchorDirective, inputDirective, inputDirective, formDirective, scriptDirective, selectDirective, styleDirective, optionDirective, ngBindDirective, ngBindHtmlDirective, ngBindTemplateDirective, ngClassDirective, ngClassEvenDirective, ngClassOddDirective, ngCspDirective, ngCloakDirective, ngControllerDirective, ngFormDirective, ngHideDirective, ngIfDirective, ngIncludeDirective, ngIncludeFillContentDirective, ngInitDirective, ngNonBindableDirective, ngPluralizeDirective, ngRepeatDirective, ngShowDirective, ngStyleDirective, ngSwitchDirective, ngSwitchWhenDirective, ngSwitchDefaultDirective, ngOptionsDirective, ngTranscludeDirective, ngModelDirective, ngListDirective, ngChangeDirective, patternDirective, patternDirective, requiredDirective, requiredDirective, minlengthDirective, minlengthDirective, maxlengthDirective, maxlengthDirective, ngValueDirective, ngModelOptionsDirective, ngAttributeAliasDirectives, ngEventDirectives, $AnchorScrollProvider, $AnimateProvider, $BrowserProvider, $CacheFactoryProvider, $ControllerProvider, $DocumentProvider, $ExceptionHandlerProvider, $FilterProvider, $InterpolateProvider, $IntervalProvider, $HttpProvider, $HttpBackendProvider, $LocationProvider, $LogProvider, $ParseProvider, $RootScopeProvider, $QProvider, $$QProvider, $$SanitizeUriProvider, $SceProvider, $SceDelegateProvider, $SnifferProvider, $TemplateCacheProvider, $TemplateRequestProvider, $$TestabilityProvider, $TimeoutProvider, $$RAFProvider, $$AsyncCallbackProvider, $WindowProvider, $$jqLiteProvider */ /** * @ngdoc object * @name angular.version * @module ng * @description * An object that contains information about the current AngularJS version. This object has the * following properties: * * - `full` – `{string}` – Full version string, such as "0.9.18". * - `major` – `{number}` – Major version number, such as "0". * - `minor` – `{number}` – Minor version number, such as "9". * - `dot` – `{number}` – Dot version number, such as "18". * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". */ var version = { full: '1.3.11', // all of these placeholder strings will be replaced by grunt's major: 1, // package task minor: 3, dot: 11, codeName: 'spiffy-manatee' }; function publishExternalAPI(angular) { extend(angular, { 'bootstrap': bootstrap, 'copy': copy, 'extend': extend, 'equals': equals, 'element': jqLite, 'forEach': forEach, 'injector': createInjector, 'noop': noop, 'bind': bind, 'toJson': toJson, 'fromJson': fromJson, 'identity': identity, 'isUndefined': isUndefined, 'isDefined': isDefined, 'isString': isString, 'isFunction': isFunction, 'isObject': isObject, 'isNumber': isNumber, 'isElement': isElement, 'isArray': isArray, 'version': version, 'isDate': isDate, 'lowercase': lowercase, 'uppercase': uppercase, 'callbacks': {counter: 0}, 'getTestability': getTestability, '$$minErr': minErr, '$$csp': csp, 'reloadWithDebugInfo': reloadWithDebugInfo }); angularModule = setupModuleLoader(window); try { angularModule('ngLocale'); } catch (e) { angularModule('ngLocale', []).provider('$locale', $LocaleProvider); } angularModule('ng', ['ngLocale'], ['$provide', function ngModule($provide) { // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it. $provide.provider({ $$sanitizeUri: $$SanitizeUriProvider }); $provide.provider('$compile', $CompileProvider). directive({ a: htmlAnchorDirective, input: inputDirective, textarea: inputDirective, form: formDirective, script: scriptDirective, select: selectDirective, style: styleDirective, option: optionDirective, ngBind: ngBindDirective, ngBindHtml: ngBindHtmlDirective, ngBindTemplate: ngBindTemplateDirective, ngClass: ngClassDirective, ngClassEven: ngClassEvenDirective, ngClassOdd: ngClassOddDirective, ngCloak: ngCloakDirective, ngController: ngControllerDirective, ngForm: ngFormDirective, ngHide: ngHideDirective, ngIf: ngIfDirective, ngInclude: ngIncludeDirective, ngInit: ngInitDirective, ngNonBindable: ngNonBindableDirective, ngPluralize: ngPluralizeDirective, ngRepeat: ngRepeatDirective, ngShow: ngShowDirective, ngStyle: ngStyleDirective, ngSwitch: ngSwitchDirective, ngSwitchWhen: ngSwitchWhenDirective, ngSwitchDefault: ngSwitchDefaultDirective, ngOptions: ngOptionsDirective, ngTransclude: ngTranscludeDirective, ngModel: ngModelDirective, ngList: ngListDirective, ngChange: ngChangeDirective, pattern: patternDirective, ngPattern: patternDirective, required: requiredDirective, ngRequired: requiredDirective, minlength: minlengthDirective, ngMinlength: minlengthDirective, maxlength: maxlengthDirective, ngMaxlength: maxlengthDirective, ngValue: ngValueDirective, ngModelOptions: ngModelOptionsDirective }). directive({ ngInclude: ngIncludeFillContentDirective }). directive(ngAttributeAliasDirectives). directive(ngEventDirectives); $provide.provider({ $anchorScroll: $AnchorScrollProvider, $animate: $AnimateProvider, $browser: $BrowserProvider, $cacheFactory: $CacheFactoryProvider, $controller: $ControllerProvider, $document: $DocumentProvider, $exceptionHandler: $ExceptionHandlerProvider, $filter: $FilterProvider, $interpolate: $InterpolateProvider, $interval: $IntervalProvider, $http: $HttpProvider, $httpBackend: $HttpBackendProvider, $location: $LocationProvider, $log: $LogProvider, $parse: $ParseProvider, $rootScope: $RootScopeProvider, $q: $QProvider, $$q: $$QProvider, $sce: $SceProvider, $sceDelegate: $SceDelegateProvider, $sniffer: $SnifferProvider, $templateCache: $TemplateCacheProvider, $templateRequest: $TemplateRequestProvider, $$testability: $$TestabilityProvider, $timeout: $TimeoutProvider, $window: $WindowProvider, $$rAF: $$RAFProvider, $$asyncCallback: $$AsyncCallbackProvider, $$jqLite: $$jqLiteProvider }); } ]); } /* global JQLitePrototype: true, addEventListenerFn: true, removeEventListenerFn: true, BOOLEAN_ATTR: true, ALIASED_ATTR: true, */ ////////////////////////////////// //JQLite ////////////////////////////////// /** * @ngdoc function * @name angular.element * @module ng * @kind function * * @description * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. * * If jQuery is available, `angular.element` is an alias for the * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element` * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite." * * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most * commonly needed functionality with the goal of having a very small footprint.</div> * * To use jQuery, simply load it before `DOMContentLoaded` event fired. * * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or * jqLite; they are never raw DOM references.</div> * * ## Angular's jqLite * jqLite provides only the following jQuery methods: * * - [`addClass()`](http://api.jquery.com/addClass/) * - [`after()`](http://api.jquery.com/after/) * - [`append()`](http://api.jquery.com/append/) * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData * - [`children()`](http://api.jquery.com/children/) - Does not support selectors * - [`clone()`](http://api.jquery.com/clone/) * - [`contents()`](http://api.jquery.com/contents/) * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()` * - [`data()`](http://api.jquery.com/data/) * - [`detach()`](http://api.jquery.com/detach/) * - [`empty()`](http://api.jquery.com/empty/) * - [`eq()`](http://api.jquery.com/eq/) * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name * - [`hasClass()`](http://api.jquery.com/hasClass/) * - [`html()`](http://api.jquery.com/html/) * - [`next()`](http://api.jquery.com/next/) - Does not support selectors * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors * - [`prepend()`](http://api.jquery.com/prepend/) * - [`prop()`](http://api.jquery.com/prop/) * - [`ready()`](http://api.jquery.com/ready/) * - [`remove()`](http://api.jquery.com/remove/) * - [`removeAttr()`](http://api.jquery.com/removeAttr/) * - [`removeClass()`](http://api.jquery.com/removeClass/) * - [`removeData()`](http://api.jquery.com/removeData/) * - [`replaceWith()`](http://api.jquery.com/replaceWith/) * - [`text()`](http://api.jquery.com/text/) * - [`toggleClass()`](http://api.jquery.com/toggleClass/) * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces * - [`val()`](http://api.jquery.com/val/) * - [`wrap()`](http://api.jquery.com/wrap/) * * ## jQuery/jqLite Extras * Angular also provides the following additional methods and events to both jQuery and jqLite: * * ### Events * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM * element before it is removed. * * ### Methods * - `controller(name)` - retrieves the controller of the current element or its parent. By default * retrieves controller associated with the `ngController` directive. If `name` is provided as * camelCase directive name, then the controller for this directive will be retrieved (e.g. * `'ngModel'`). * - `injector()` - retrieves the injector of the current element or its parent. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to * be enabled. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the * current element. This getter should be used only on elements that contain a directive which starts a new isolate * scope. Calling `scope()` on this element always returns the original non-isolate scope. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top * parent element is reached. * * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. * @returns {Object} jQuery object. */ JQLite.expando = 'ng339'; var jqCache = JQLite.cache = {}, jqId = 1, addEventListenerFn = function(element, type, fn) { element.addEventListener(type, fn, false); }, removeEventListenerFn = function(element, type, fn) { element.removeEventListener(type, fn, false); }; /* * !!! This is an undocumented "private" function !!! */ JQLite._data = function(node) { //jQuery always returns an object on cache miss return this.cache[node[this.expando]] || {}; }; function jqNextId() { return ++jqId; } var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g; var MOZ_HACK_REGEXP = /^moz([A-Z])/; var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"}; var jqLiteMinErr = minErr('jqLite'); /** * Converts snake_case to camelCase. * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */ function camelCase(name) { return name. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) { return offset ? letter.toUpperCase() : letter; }). replace(MOZ_HACK_REGEXP, 'Moz$1'); } var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/; var HTML_REGEXP = /<|&#?\w+;/; var TAG_NAME_REGEXP = /<([\w:]+)/; var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi; var wrapMap = { 'option': [1, '<select multiple="multiple">', '</select>'], 'thead': [1, '<table>', '</table>'], 'col': [2, '<table><colgroup>', '</colgroup></table>'], 'tr': [2, '<table><tbody>', '</tbody></table>'], 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'], '_default': [0, "", ""] }; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function jqLiteIsTextNode(html) { return !HTML_REGEXP.test(html); } function jqLiteAcceptsData(node) { // The window object can accept data but has no nodeType // Otherwise we are only interested in elements (1) and documents (9) var nodeType = node.nodeType; return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT; } function jqLiteBuildFragment(html, context) { var tmp, tag, wrap, fragment = context.createDocumentFragment(), nodes = [], i; if (jqLiteIsTextNode(html)) { // Convert non-html into a text node nodes.push(context.createTextNode(html)); } else { // Convert html into DOM nodes tmp = tmp || fragment.appendChild(context.createElement("div")); tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase(); wrap = wrapMap[tag] || wrapMap._default; tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2]; // Descend through wrappers to the right content i = wrap[0]; while (i--) { tmp = tmp.lastChild; } nodes = concat(nodes, tmp.childNodes); tmp = fragment.firstChild; tmp.textContent = ""; } // Remove wrapper from fragment fragment.textContent = ""; fragment.innerHTML = ""; // Clear inner HTML forEach(nodes, function(node) { fragment.appendChild(node); }); return fragment; } function jqLiteParseHTML(html, context) { context = context || document; var parsed; if ((parsed = SINGLE_TAG_REGEXP.exec(html))) { return [context.createElement(parsed[1])]; } if ((parsed = jqLiteBuildFragment(html, context))) { return parsed.childNodes; } return []; } ///////////////////////////////////////////// function JQLite(element) { if (element instanceof JQLite) { return element; } var argIsString; if (isString(element)) { element = trim(element); argIsString = true; } if (!(this instanceof JQLite)) { if (argIsString && element.charAt(0) != '<') { throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element'); } return new JQLite(element); } if (argIsString) { jqLiteAddNodes(this, jqLiteParseHTML(element)); } else { jqLiteAddNodes(this, element); } } function jqLiteClone(element) { return element.cloneNode(true); } function jqLiteDealoc(element, onlyDescendants) { if (!onlyDescendants) jqLiteRemoveData(element); if (element.querySelectorAll) { var descendants = element.querySelectorAll('*'); for (var i = 0, l = descendants.length; i < l; i++) { jqLiteRemoveData(descendants[i]); } } } function jqLiteOff(element, type, fn, unsupported) { if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument'); var expandoStore = jqLiteExpandoStore(element); var events = expandoStore && expandoStore.events; var handle = expandoStore && expandoStore.handle; if (!handle) return; //no listeners registered if (!type) { for (type in events) { if (type !== '$destroy') { removeEventListenerFn(element, type, handle); } delete events[type]; } } else { forEach(type.split(' '), function(type) { if (isDefined(fn)) { var listenerFns = events[type]; arrayRemove(listenerFns || [], fn); if (listenerFns && listenerFns.length > 0) { return; } } removeEventListenerFn(element, type, handle); delete events[type]; }); } } function jqLiteRemoveData(element, name) { var expandoId = element.ng339; var expandoStore = expandoId && jqCache[expandoId]; if (expandoStore) { if (name) { delete expandoStore.data[name]; return; } if (expandoStore.handle) { if (expandoStore.events.$destroy) { expandoStore.handle({}, '$destroy'); } jqLiteOff(element); } delete jqCache[expandoId]; element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it } } function jqLiteExpandoStore(element, createIfNecessary) { var expandoId = element.ng339, expandoStore = expandoId && jqCache[expandoId]; if (createIfNecessary && !expandoStore) { element.ng339 = expandoId = jqNextId(); expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined}; } return expandoStore; } function jqLiteData(element, key, value) { if (jqLiteAcceptsData(element)) { var isSimpleSetter = isDefined(value); var isSimpleGetter = !isSimpleSetter && key && !isObject(key); var massGetter = !key; var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter); var data = expandoStore && expandoStore.data; if (isSimpleSetter) { // data('key', value) data[key] = value; } else { if (massGetter) { // data() return data; } else { if (isSimpleGetter) { // data('key') // don't force creation of expandoStore if it doesn't exist yet return data && data[key]; } else { // mass-setter: data({key1: val1, key2: val2}) extend(data, key); } } } } } function jqLiteHasClass(element, selector) { if (!element.getAttribute) return false; return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " "). indexOf(" " + selector + " ") > -1); } function jqLiteRemoveClass(element, cssClasses) { if (cssClasses && element.setAttribute) { forEach(cssClasses.split(' '), function(cssClass) { element.setAttribute('class', trim( (" " + (element.getAttribute('class') || '') + " ") .replace(/[\n\t]/g, " ") .replace(" " + trim(cssClass) + " ", " ")) ); }); } } function jqLiteAddClass(element, cssClasses) { if (cssClasses && element.setAttribute) { var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ') .replace(/[\n\t]/g, " "); forEach(cssClasses.split(' '), function(cssClass) { cssClass = trim(cssClass); if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) { existingClasses += cssClass + ' '; } }); element.setAttribute('class', trim(existingClasses)); } } function jqLiteAddNodes(root, elements) { // THIS CODE IS VERY HOT. Don't make changes without benchmarking. if (elements) { // if a Node (the most common case) if (elements.nodeType) { root[root.length++] = elements; } else { var length = elements.length; // if an Array or NodeList and not a Window if (typeof length === 'number' && elements.window !== elements) { if (length) { for (var i = 0; i < length; i++) { root[root.length++] = elements[i]; } } } else { root[root.length++] = elements; } } } } function jqLiteController(element, name) { return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller'); } function jqLiteInheritedData(element, name, value) { // if element is the document object work with the html element instead // this makes $(document).scope() possible if (element.nodeType == NODE_TYPE_DOCUMENT) { element = element.documentElement; } var names = isArray(name) ? name : [name]; while (element) { for (var i = 0, ii = names.length; i < ii; i++) { if ((value = jqLite.data(element, names[i])) !== undefined) return value; } // If dealing with a document fragment node with a host element, and no parent, use the host // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM // to lookup parent controllers. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host); } } function jqLiteEmpty(element) { jqLiteDealoc(element, true); while (element.firstChild) { element.removeChild(element.firstChild); } } function jqLiteRemove(element, keepData) { if (!keepData) jqLiteDealoc(element); var parent = element.parentNode; if (parent) parent.removeChild(element); } function jqLiteDocumentLoaded(action, win) { win = win || window; if (win.document.readyState === 'complete') { // Force the action to be run async for consistent behaviour // from the action's point of view // i.e. it will definitely not be in a $apply win.setTimeout(action); } else { // No need to unbind this handler as load is only ever called once jqLite(win).on('load', action); } } ////////////////////////////////////////// // Functions which are declared directly. ////////////////////////////////////////// var JQLitePrototype = JQLite.prototype = { ready: function(fn) { var fired = false; function trigger() { if (fired) return; fired = true; fn(); } // check if document is already loaded if (document.readyState === 'complete') { setTimeout(trigger); } else { this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9 // we can not use jqLite since we are not done loading and jQuery could be loaded later. // jshint -W064 JQLite(window).on('load', trigger); // fallback to window.onload for others // jshint +W064 } }, toString: function() { var value = []; forEach(this, function(e) { value.push('' + e);}); return '[' + value.join(', ') + ']'; }, eq: function(index) { return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]); }, length: 0, push: push, sort: [].sort, splice: [].splice }; ////////////////////////////////////////// // Functions iterating getter/setters. // these functions return self on setter and // value on get. ////////////////////////////////////////// var BOOLEAN_ATTR = {}; forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) { BOOLEAN_ATTR[lowercase(value)] = value; }); var BOOLEAN_ELEMENTS = {}; forEach('input,select,option,textarea,button,form,details'.split(','), function(value) { BOOLEAN_ELEMENTS[value] = true; }); var ALIASED_ATTR = { 'ngMinlength': 'minlength', 'ngMaxlength': 'maxlength', 'ngMin': 'min', 'ngMax': 'max', 'ngPattern': 'pattern' }; function getBooleanAttrName(element, name) { // check dom last since we will most likely fail on name var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()]; // booleanAttr is here twice to minimize DOM access return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr; } function getAliasedAttrName(element, name) { var nodeName = element.nodeName; return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name]; } forEach({ data: jqLiteData, removeData: jqLiteRemoveData }, function(fn, name) { JQLite[name] = fn; }); forEach({ data: jqLiteData, inheritedData: jqLiteInheritedData, scope: function(element) { // Can't use jqLiteData here directly so we stay compatible with jQuery! return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']); }, isolateScope: function(element) { // Can't use jqLiteData here directly so we stay compatible with jQuery! return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate'); }, controller: jqLiteController, injector: function(element) { return jqLiteInheritedData(element, '$injector'); }, removeAttr: function(element, name) { element.removeAttribute(name); }, hasClass: jqLiteHasClass, css: function(element, name, value) { name = camelCase(name); if (isDefined(value)) { element.style[name] = value; } else { return element.style[name]; } }, attr: function(element, name, value) { var lowercasedName = lowercase(name); if (BOOLEAN_ATTR[lowercasedName]) { if (isDefined(value)) { if (!!value) { element[name] = true; element.setAttribute(name, lowercasedName); } else { element[name] = false; element.removeAttribute(lowercasedName); } } else { return (element[name] || (element.attributes.getNamedItem(name) || noop).specified) ? lowercasedName : undefined; } } else if (isDefined(value)) { element.setAttribute(name, value); } else if (element.getAttribute) { // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code // some elements (e.g. Document) don't have get attribute, so return undefined var ret = element.getAttribute(name, 2); // normalize non-existing attributes to undefined (as jQuery) return ret === null ? undefined : ret; } }, prop: function(element, name, value) { if (isDefined(value)) { element[name] = value; } else { return element[name]; } }, text: (function() { getText.$dv = ''; return getText; function getText(element, value) { if (isUndefined(value)) { var nodeType = element.nodeType; return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : ''; } element.textContent = value; } })(), val: function(element, value) { if (isUndefined(value)) { if (element.multiple && nodeName_(element) === 'select') { var result = []; forEach(element.options, function(option) { if (option.selected) { result.push(option.value || option.text); } }); return result.length === 0 ? null : result; } return element.value; } element.value = value; }, html: function(element, value) { if (isUndefined(value)) { return element.innerHTML; } jqLiteDealoc(element, true); element.innerHTML = value; }, empty: jqLiteEmpty }, function(fn, name) { /** * Properties: writes return selection, reads return first value */ JQLite.prototype[name] = function(arg1, arg2) { var i, key; var nodeCount = this.length; // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it // in a way that survives minification. // jqLiteEmpty takes no arguments but is a setter. if (fn !== jqLiteEmpty && (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) { if (isObject(arg1)) { // we are a write, but the object properties are the key/values for (i = 0; i < nodeCount; i++) { if (fn === jqLiteData) { // data() takes the whole object in jQuery fn(this[i], arg1); } else { for (key in arg1) { fn(this[i], key, arg1[key]); } } } // return self for chaining return this; } else { // we are a read, so read the first child. // TODO: do we still need this? var value = fn.$dv; // Only if we have $dv do we iterate over all, otherwise it is just the first element. var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount; for (var j = 0; j < jj; j++) { var nodeValue = fn(this[j], arg1, arg2); value = value ? value + nodeValue : nodeValue; } return value; } } else { // we are a write, so apply to all children for (i = 0; i < nodeCount; i++) { fn(this[i], arg1, arg2); } // return self for chaining return this; } }; }); function createEventHandler(element, events) { var eventHandler = function(event, type) { // jQuery specific api event.isDefaultPrevented = function() { return event.defaultPrevented; }; var eventFns = events[type || event.type]; var eventFnsLength = eventFns ? eventFns.length : 0; if (!eventFnsLength) return; if (isUndefined(event.immediatePropagationStopped)) { var originalStopImmediatePropagation = event.stopImmediatePropagation; event.stopImmediatePropagation = function() { event.immediatePropagationStopped = true; if (event.stopPropagation) { event.stopPropagation(); } if (originalStopImmediatePropagation) { originalStopImmediatePropagation.call(event); } }; } event.isImmediatePropagationStopped = function() { return event.immediatePropagationStopped === true; }; // Copy event handlers in case event handlers array is modified during execution. if ((eventFnsLength > 1)) { eventFns = shallowCopy(eventFns); } for (var i = 0; i < eventFnsLength; i++) { if (!event.isImmediatePropagationStopped()) { eventFns[i].call(element, event); } } }; // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all // events on `element` eventHandler.elem = element; return eventHandler; } ////////////////////////////////////////// // Functions iterating traversal. // These functions chain results into a single // selector. ////////////////////////////////////////// forEach({ removeData: jqLiteRemoveData, on: function jqLiteOn(element, type, fn, unsupported) { if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters'); // Do not add event handlers to non-elements because they will not be cleaned up. if (!jqLiteAcceptsData(element)) { return; } var expandoStore = jqLiteExpandoStore(element, true); var events = expandoStore.events; var handle = expandoStore.handle; if (!handle) { handle = expandoStore.handle = createEventHandler(element, events); } // http://jsperf.com/string-indexof-vs-split var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type]; var i = types.length; while (i--) { type = types[i]; var eventFns = events[type]; if (!eventFns) { events[type] = []; if (type === 'mouseenter' || type === 'mouseleave') { // Refer to jQuery's implementation of mouseenter & mouseleave // Read about mouseenter and mouseleave: // http://www.quirksmode.org/js/events_mouse.html#link8 jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) { var target = this, related = event.relatedTarget; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if (!related || (related !== target && !target.contains(related))) { handle(event, type); } }); } else { if (type !== '$destroy') { addEventListenerFn(element, type, handle); } } eventFns = events[type]; } eventFns.push(fn); } }, off: jqLiteOff, one: function(element, type, fn) { element = jqLite(element); //add the listener twice so that when it is called //you can remove the original function and still be //able to call element.off(ev, fn) normally element.on(type, function onFn() { element.off(type, fn); element.off(type, onFn); }); element.on(type, fn); }, replaceWith: function(element, replaceNode) { var index, parent = element.parentNode; jqLiteDealoc(element); forEach(new JQLite(replaceNode), function(node) { if (index) { parent.insertBefore(node, index.nextSibling); } else { parent.replaceChild(node, element); } index = node; }); }, children: function(element) { var children = []; forEach(element.childNodes, function(element) { if (element.nodeType === NODE_TYPE_ELEMENT) children.push(element); }); return children; }, contents: function(element) { return element.contentDocument || element.childNodes || []; }, append: function(element, node) { var nodeType = element.nodeType; if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return; node = new JQLite(node); for (var i = 0, ii = node.length; i < ii; i++) { var child = node[i]; element.appendChild(child); } }, prepend: function(element, node) { if (element.nodeType === NODE_TYPE_ELEMENT) { var index = element.firstChild; forEach(new JQLite(node), function(child) { element.insertBefore(child, index); }); } }, wrap: function(element, wrapNode) { wrapNode = jqLite(wrapNode).eq(0).clone()[0]; var parent = element.parentNode; if (parent) { parent.replaceChild(wrapNode, element); } wrapNode.appendChild(element); }, remove: jqLiteRemove, detach: function(element) { jqLiteRemove(element, true); }, after: function(element, newElement) { var index = element, parent = element.parentNode; newElement = new JQLite(newElement); for (var i = 0, ii = newElement.length; i < ii; i++) { var node = newElement[i]; parent.insertBefore(node, index.nextSibling); index = node; } }, addClass: jqLiteAddClass, removeClass: jqLiteRemoveClass, toggleClass: function(element, selector, condition) { if (selector) { forEach(selector.split(' '), function(className) { var classCondition = condition; if (isUndefined(classCondition)) { classCondition = !jqLiteHasClass(element, className); } (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className); }); } }, parent: function(element) { var parent = element.parentNode; return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null; }, next: function(element) { return element.nextElementSibling; }, find: function(element, selector) { if (element.getElementsByTagName) { return element.getElementsByTagName(selector); } else { return []; } }, clone: jqLiteClone, triggerHandler: function(element, event, extraParameters) { var dummyEvent, eventFnsCopy, handlerArgs; var eventName = event.type || event; var expandoStore = jqLiteExpandoStore(element); var events = expandoStore && expandoStore.events; var eventFns = events && events[eventName]; if (eventFns) { // Create a dummy event to pass to the handlers dummyEvent = { preventDefault: function() { this.defaultPrevented = true; }, isDefaultPrevented: function() { return this.defaultPrevented === true; }, stopImmediatePropagation: function() { this.immediatePropagationStopped = true; }, isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; }, stopPropagation: noop, type: eventName, target: element }; // If a custom event was provided then extend our dummy event with it if (event.type) { dummyEvent = extend(dummyEvent, event); } // Copy event handlers in case event handlers array is modified during execution. eventFnsCopy = shallowCopy(eventFns); handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent]; forEach(eventFnsCopy, function(fn) { if (!dummyEvent.isImmediatePropagationStopped()) { fn.apply(element, handlerArgs); } }); } } }, function(fn, name) { /** * chaining functions */ JQLite.prototype[name] = function(arg1, arg2, arg3) { var value; for (var i = 0, ii = this.length; i < ii; i++) { if (isUndefined(value)) { value = fn(this[i], arg1, arg2, arg3); if (isDefined(value)) { // any function which returns a value needs to be wrapped value = jqLite(value); } } else { jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3)); } } return isDefined(value) ? value : this; }; // bind legacy bind/unbind to on/off JQLite.prototype.bind = JQLite.prototype.on; JQLite.prototype.unbind = JQLite.prototype.off; }); // Provider for private $$jqLite service function $$jqLiteProvider() { this.$get = function $$jqLite() { return extend(JQLite, { hasClass: function(node, classes) { if (node.attr) node = node[0]; return jqLiteHasClass(node, classes); }, addClass: function(node, classes) { if (node.attr) node = node[0]; return jqLiteAddClass(node, classes); }, removeClass: function(node, classes) { if (node.attr) node = node[0]; return jqLiteRemoveClass(node, classes); } }); }; } /** * Computes a hash of an 'obj'. * Hash of a: * string is string * number is number as string * object is either result of calling $$hashKey function on the object or uniquely generated id, * that is also assigned to the $$hashKey property of the object. * * @param obj * @returns {string} hash string such that the same input will have the same hash string. * The resulting string key is in 'type:hashKey' format. */ function hashKey(obj, nextUidFn) { var key = obj && obj.$$hashKey; if (key) { if (typeof key === 'function') { key = obj.$$hashKey(); } return key; } var objType = typeof obj; if (objType == 'function' || (objType == 'object' && obj !== null)) { key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)(); } else { key = objType + ':' + obj; } return key; } /** * HashMap which can use objects as keys */ function HashMap(array, isolatedUid) { if (isolatedUid) { var uid = 0; this.nextUid = function() { return ++uid; }; } forEach(array, this.put, this); } HashMap.prototype = { /** * Store key value pair * @param key key to store can be any type * @param value value to store can be any type */ put: function(key, value) { this[hashKey(key, this.nextUid)] = value; }, /** * @param key * @returns {Object} the value for the key */ get: function(key) { return this[hashKey(key, this.nextUid)]; }, /** * Remove the key/value pair * @param key */ remove: function(key) { var value = this[key = hashKey(key, this.nextUid)]; delete this[key]; return value; } }; /** * @ngdoc function * @module ng * @name angular.injector * @kind function * * @description * Creates an injector object that can be used for retrieving services as well as for * dependency injection (see {@link guide/di dependency injection}). * * @param {Array.<string|Function>} modules A list of module functions or their aliases. See * {@link angular.module}. The `ng` module must be explicitly added. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which * disallows argument name annotation inference. * @returns {injector} Injector object. See {@link auto.$injector $injector}. * * @example * Typical usage * ```js * // create an injector * var $injector = angular.injector(['ng']); * * // use the injector to kick off your application * // use the type inference to auto inject arguments, or use implicit injection * $injector.invoke(function($rootScope, $compile, $document) { * $compile($document)($rootScope); * $rootScope.$digest(); * }); * ``` * * Sometimes you want to get access to the injector of a currently running Angular app * from outside Angular. Perhaps, you want to inject and compile some markup after the * application has been bootstrapped. You can do this using the extra `injector()` added * to JQuery/jqLite elements. See {@link angular.element}. * * *This is fairly rare but could be the case if a third party library is injecting the * markup.* * * In the following example a new block of HTML containing a `ng-controller` * directive is added to the end of the document body by JQuery. We then compile and link * it into the current AngularJS scope. * * ```js * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>'); * $(document.body).append($div); * * angular.element(document).injector().invoke(function($compile) { * var scope = angular.element($div).scope(); * $compile($div)(scope); * }); * ``` */ /** * @ngdoc module * @name auto * @description * * Implicit module which gets automatically added to each {@link auto.$injector $injector}. */ var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; var $injectorMinErr = minErr('$injector'); function anonFn(fn) { // For anonymous functions, showing at the very least the function signature can help in // debugging. var fnText = fn.toString().replace(STRIP_COMMENTS, ''), args = fnText.match(FN_ARGS); if (args) { return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')'; } return 'fn'; } function annotate(fn, strictDi, name) { var $inject, fnText, argDecl, last; if (typeof fn === 'function') { if (!($inject = fn.$inject)) { $inject = []; if (fn.length) { if (strictDi) { if (!isString(name) || !name) { name = fn.name || anonFn(fn); } throw $injectorMinErr('strictdi', '{0} is not using explicit annotation and cannot be invoked in strict mode', name); } fnText = fn.toString().replace(STRIP_COMMENTS, ''); argDecl = fnText.match(FN_ARGS); forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) { arg.replace(FN_ARG, function(all, underscore, name) { $inject.push(name); }); }); } fn.$inject = $inject; } } else if (isArray(fn)) { last = fn.length - 1; assertArgFn(fn[last], 'fn'); $inject = fn.slice(0, last); } else { assertArgFn(fn, 'fn', true); } return $inject; } /////////////////////////////////////// /** * @ngdoc service * @name $injector * * @description * * `$injector` is used to retrieve object instances as defined by * {@link auto.$provide provider}, instantiate types, invoke methods, * and load modules. * * The following always holds true: * * ```js * var $injector = angular.injector(); * expect($injector.get('$injector')).toBe($injector); * expect($injector.invoke(function($injector) { * return $injector; * })).toBe($injector); * ``` * * # Injection Function Annotation * * JavaScript does not have annotations, and annotations are needed for dependency injection. The * following are all valid ways of annotating function with injection arguments and are equivalent. * * ```js * // inferred (only works if code not minified/obfuscated) * $injector.invoke(function(serviceA){}); * * // annotated * function explicit(serviceA) {}; * explicit.$inject = ['serviceA']; * $injector.invoke(explicit); * * // inline * $injector.invoke(['serviceA', function(serviceA){}]); * ``` * * ## Inference * * In JavaScript calling `toString()` on a function returns the function definition. The definition * can then be parsed and the function arguments can be extracted. This method of discovering * annotations is disallowed when the injector is in strict mode. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the * argument names. * * ## `$inject` Annotation * By adding an `$inject` property onto a function the injection parameters can be specified. * * ## Inline * As an array of injection names, where the last item in the array is the function to call. */ /** * @ngdoc method * @name $injector#get * * @description * Return an instance of the service. * * @param {string} name The name of the instance to retrieve. * @param {string} caller An optional string to provide the origin of the function call for error messages. * @return {*} The instance. */ /** * @ngdoc method * @name $injector#invoke * * @description * Invoke the method and supply the method arguments from the `$injector`. * * @param {!Function} fn The function to invoke. Function parameters are injected according to the * {@link guide/di $inject Annotation} rules. * @param {Object=} self The `this` for the invoked method. * @param {Object=} locals Optional object. If preset then any argument names are read from this * object first, before the `$injector` is consulted. * @returns {*} the value returned by the invoked `fn` function. */ /** * @ngdoc method * @name $injector#has * * @description * Allows the user to query if the particular service exists. * * @param {string} name Name of the service to query. * @returns {boolean} `true` if injector has given service. */ /** * @ngdoc method * @name $injector#instantiate * @description * Create a new instance of JS type. The method takes a constructor function, invokes the new * operator, and supplies all of the arguments to the constructor function as specified by the * constructor annotation. * * @param {Function} Type Annotated constructor function. * @param {Object=} locals Optional object. If preset then any argument names are read from this * object first, before the `$injector` is consulted. * @returns {Object} new instance of `Type`. */ /** * @ngdoc method * @name $injector#annotate * * @description * Returns an array of service names which the function is requesting for injection. This API is * used by the injector to determine which services need to be injected into the function when the * function is invoked. There are three ways in which the function can be annotated with the needed * dependencies. * * # Argument names * * The simplest form is to extract the dependencies from the arguments of the function. This is done * by converting the function into a string using `toString()` method and extracting the argument * names. * ```js * // Given * function MyController($scope, $route) { * // ... * } * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * ``` * * You can disallow this method by using strict injection mode. * * This method does not work with code minification / obfuscation. For this reason the following * annotation strategies are supported. * * # The `$inject` property * * If a function has an `$inject` property and its value is an array of strings, then the strings * represent names of services to be injected into the function. * ```js * // Given * var MyController = function(obfuscatedScope, obfuscatedRoute) { * // ... * } * // Define function dependencies * MyController['$inject'] = ['$scope', '$route']; * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * ``` * * # The array notation * * It is often desirable to inline Injected functions and that's when setting the `$inject` property * is very inconvenient. In these situations using the array notation to specify the dependencies in * a way that survives minification is a better choice: * * ```js * // We wish to write this (not minification / obfuscation safe) * injector.invoke(function($compile, $rootScope) { * // ... * }); * * // We are forced to write break inlining * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) { * // ... * }; * tmpFn.$inject = ['$compile', '$rootScope']; * injector.invoke(tmpFn); * * // To better support inline function the inline annotation is supported * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) { * // ... * }]); * * // Therefore * expect(injector.annotate( * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}]) * ).toEqual(['$compile', '$rootScope']); * ``` * * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to * be retrieved as described above. * * @param {boolean=} [strictDi=false] Disallow argument name annotation inference. * * @returns {Array.<string>} The names of the services which the function requires. */ /** * @ngdoc service * @name $provide * * @description * * The {@link auto.$provide $provide} service has a number of methods for registering components * with the {@link auto.$injector $injector}. Many of these functions are also exposed on * {@link angular.Module}. * * An Angular **service** is a singleton object created by a **service factory**. These **service * factories** are functions which, in turn, are created by a **service provider**. * The **service providers** are constructor functions. When instantiated they must contain a * property called `$get`, which holds the **service factory** function. * * When you request a service, the {@link auto.$injector $injector} is responsible for finding the * correct **service provider**, instantiating it and then calling its `$get` **service factory** * function to get the instance of the **service**. * * Often services have no configuration options and there is no need to add methods to the service * provider. The provider will be no more than a constructor function with a `$get` property. For * these cases the {@link auto.$provide $provide} service has additional helper methods to register * services without specifying a provider. * * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the * {@link auto.$injector $injector} * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by * providers and services. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by * services, not providers. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`, * that will be wrapped in a **service provider** object, whose `$get` property will contain the * given factory function. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class` * that will be wrapped in a **service provider** object, whose `$get` property will instantiate * a new object using the given constructor function. * * See the individual methods for more information and examples. */ /** * @ngdoc method * @name $provide#provider * @description * * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions * are constructor functions, whose instances are responsible for "providing" a factory for a * service. * * Service provider names start with the name of the service they provide followed by `Provider`. * For example, the {@link ng.$log $log} service has a provider called * {@link ng.$logProvider $logProvider}. * * Service provider objects can have additional methods which allow configuration of the provider * and its service. Importantly, you can configure what kind of service is created by the `$get` * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a * method {@link ng.$logProvider#debugEnabled debugEnabled} * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the * console or not. * * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key. * @param {(Object|function())} provider If the provider is: * * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created. * - `Constructor`: a new instance of the provider will be created using * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`. * * @returns {Object} registered provider instance * @example * * The following example shows how to create a simple event tracking service and register it using * {@link auto.$provide#provider $provide.provider()}. * * ```js * // Define the eventTracker provider * function EventTrackerProvider() { * var trackingUrl = '/track'; * * // A provider method for configuring where the tracked events should been saved * this.setTrackingUrl = function(url) { * trackingUrl = url; * }; * * // The service factory function * this.$get = ['$http', function($http) { * var trackedEvents = {}; * return { * // Call this to track an event * event: function(event) { * var count = trackedEvents[event] || 0; * count += 1; * trackedEvents[event] = count; * return count; * }, * // Call this to save the tracked events to the trackingUrl * save: function() { * $http.post(trackingUrl, trackedEvents); * } * }; * }]; * } * * describe('eventTracker', function() { * var postSpy; * * beforeEach(module(function($provide) { * // Register the eventTracker provider * $provide.provider('eventTracker', EventTrackerProvider); * })); * * beforeEach(module(function(eventTrackerProvider) { * // Configure eventTracker provider * eventTrackerProvider.setTrackingUrl('/custom-track'); * })); * * it('tracks events', inject(function(eventTracker) { * expect(eventTracker.event('login')).toEqual(1); * expect(eventTracker.event('login')).toEqual(2); * })); * * it('saves to the tracking url', inject(function(eventTracker, $http) { * postSpy = spyOn($http, 'post'); * eventTracker.event('login'); * eventTracker.save(); * expect(postSpy).toHaveBeenCalled(); * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track'); * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track'); * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 }); * })); * }); * ``` */ /** * @ngdoc method * @name $provide#factory * @description * * Register a **service factory**, which will be called to return the service instance. * This is short for registering a service where its provider consists of only a `$get` property, * which is the given service factory function. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to * configure your service in a provider. * * @param {string} name The name of the instance. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand * for `$provide.provider(name, {$get: $getFn})`. * @returns {Object} registered provider instance * * @example * Here is an example of registering a service * ```js * $provide.factory('ping', ['$http', function($http) { * return function ping() { * return $http.send('/ping'); * }; * }]); * ``` * You would then inject and use this service like this: * ```js * someModule.controller('Ctrl', ['ping', function(ping) { * ping(); * }]); * ``` */ /** * @ngdoc method * @name $provide#service * @description * * Register a **service constructor**, which will be invoked with `new` to create the service * instance. * This is short for registering a service where its provider's `$get` property is the service * constructor function that will be used to instantiate the service instance. * * You should use {@link auto.$provide#service $provide.service(class)} if you define your service * as a type/class. * * @param {string} name The name of the instance. * @param {Function} constructor A class (constructor function) that will be instantiated. * @returns {Object} registered provider instance * * @example * Here is an example of registering a service using * {@link auto.$provide#service $provide.service(class)}. * ```js * var Ping = function($http) { * this.$http = $http; * }; * * Ping.$inject = ['$http']; * * Ping.prototype.send = function() { * return this.$http.get('/ping'); * }; * $provide.service('ping', Ping); * ``` * You would then inject and use this service like this: * ```js * someModule.controller('Ctrl', ['ping', function(ping) { * ping.send(); * }]); * ``` */ /** * @ngdoc method * @name $provide#value * @description * * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a * number, an array, an object or a function. This is short for registering a service where its * provider's `$get` property is a factory function that takes no arguments and returns the **value * service**. * * Value services are similar to constant services, except that they cannot be injected into a * module configuration function (see {@link angular.Module#config}) but they can be overridden by * an Angular * {@link auto.$provide#decorator decorator}. * * @param {string} name The name of the instance. * @param {*} value The value. * @returns {Object} registered provider instance * * @example * Here are some examples of creating value services. * ```js * $provide.value('ADMIN_USER', 'admin'); * * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 }); * * $provide.value('halfOf', function(value) { * return value / 2; * }); * ``` */ /** * @ngdoc method * @name $provide#constant * @description * * Register a **constant service**, such as a string, a number, an array, an object or a function, * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be * injected into a module configuration function (see {@link angular.Module#config}) and it cannot * be overridden by an Angular {@link auto.$provide#decorator decorator}. * * @param {string} name The name of the constant. * @param {*} value The constant value. * @returns {Object} registered instance * * @example * Here a some examples of creating constants: * ```js * $provide.constant('SHARD_HEIGHT', 306); * * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']); * * $provide.constant('double', function(value) { * return value * 2; * }); * ``` */ /** * @ngdoc method * @name $provide#decorator * @description * * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator * intercepts the creation of a service, allowing it to override or modify the behaviour of the * service. The object returned by the decorator may be the original service, or a new service * object which replaces or wraps and delegates to the original service. * * @param {string} name The name of the service to decorate. * @param {function()} decorator This function will be invoked when the service needs to be * instantiated and should return the decorated service instance. The function is called using * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable. * Local injection arguments: * * * `$delegate` - The original service instance, which can be monkey patched, configured, * decorated or delegated to. * * @example * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting * calls to {@link ng.$log#error $log.warn()}. * ```js * $provide.decorator('$log', ['$delegate', function($delegate) { * $delegate.warn = $delegate.error; * return $delegate; * }]); * ``` */ function createInjector(modulesToLoad, strictDi) { strictDi = (strictDi === true); var INSTANTIATING = {}, providerSuffix = 'Provider', path = [], loadedModules = new HashMap([], true), providerCache = { $provide: { provider: supportObject(provider), factory: supportObject(factory), service: supportObject(service), value: supportObject(value), constant: supportObject(constant), decorator: decorator } }, providerInjector = (providerCache.$injector = createInternalInjector(providerCache, function(serviceName, caller) { if (angular.isString(caller)) { path.push(caller); } throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- ')); })), instanceCache = {}, instanceInjector = (instanceCache.$injector = createInternalInjector(instanceCache, function(serviceName, caller) { var provider = providerInjector.get(serviceName + providerSuffix, caller); return instanceInjector.invoke(provider.$get, provider, undefined, serviceName); })); forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); }); return instanceInjector; //////////////////////////////////// // $provider //////////////////////////////////// function supportObject(delegate) { return function(key, value) { if (isObject(key)) { forEach(key, reverseParams(delegate)); } else { return delegate(key, value); } }; } function provider(name, provider_) { assertNotHasOwnProperty(name, 'service'); if (isFunction(provider_) || isArray(provider_)) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) { throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name); } return providerCache[name + providerSuffix] = provider_; } function enforceReturnValue(name, factory) { return function enforcedReturnValue() { var result = instanceInjector.invoke(factory, this); if (isUndefined(result)) { throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name); } return result; }; } function factory(name, factoryFn, enforce) { return provider(name, { $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn }); } function service(name, constructor) { return factory(name, ['$injector', function($injector) { return $injector.instantiate(constructor); }]); } function value(name, val) { return factory(name, valueFn(val), false); } function constant(name, value) { assertNotHasOwnProperty(name, 'constant'); providerCache[name] = value; instanceCache[name] = value; } function decorator(serviceName, decorFn) { var origProvider = providerInjector.get(serviceName + providerSuffix), orig$get = origProvider.$get; origProvider.$get = function() { var origInstance = instanceInjector.invoke(orig$get, origProvider); return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); }; } //////////////////////////////////// // Module Loading //////////////////////////////////// function loadModules(modulesToLoad) { var runBlocks = [], moduleFn; forEach(modulesToLoad, function(module) { if (loadedModules.get(module)) return; loadedModules.put(module, true); function runInvokeQueue(queue) { var i, ii; for (i = 0, ii = queue.length; i < ii; i++) { var invokeArgs = queue[i], provider = providerInjector.get(invokeArgs[0]); provider[invokeArgs[1]].apply(provider, invokeArgs[2]); } } try { if (isString(module)) { moduleFn = angularModule(module); runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); runInvokeQueue(moduleFn._invokeQueue); runInvokeQueue(moduleFn._configBlocks); } else if (isFunction(module)) { runBlocks.push(providerInjector.invoke(module)); } else if (isArray(module)) { runBlocks.push(providerInjector.invoke(module)); } else { assertArgFn(module, 'module'); } } catch (e) { if (isArray(module)) { module = module[module.length - 1]; } if (e.message && e.stack && e.stack.indexOf(e.message) == -1) { // Safari & FF's stack traces don't contain error.message content // unlike those of Chrome and IE // So if stack doesn't contain message, we create a new string that contains both. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here. /* jshint -W022 */ e = e.message + '\n' + e.stack; } throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}", module, e.stack || e.message || e); } }); return runBlocks; } //////////////////////////////////// // internal Injector //////////////////////////////////// function createInternalInjector(cache, factory) { function getService(serviceName, caller) { if (cache.hasOwnProperty(serviceName)) { if (cache[serviceName] === INSTANTIATING) { throw $injectorMinErr('cdep', 'Circular dependency found: {0}', serviceName + ' <- ' + path.join(' <- ')); } return cache[serviceName]; } else { try { path.unshift(serviceName); cache[serviceName] = INSTANTIATING; return cache[serviceName] = factory(serviceName, caller); } catch (err) { if (cache[serviceName] === INSTANTIATING) { delete cache[serviceName]; } throw err; } finally { path.shift(); } } } function invoke(fn, self, locals, serviceName) { if (typeof locals === 'string') { serviceName = locals; locals = null; } var args = [], $inject = annotate(fn, strictDi, serviceName), length, i, key; for (i = 0, length = $inject.length; i < length; i++) { key = $inject[i]; if (typeof key !== 'string') { throw $injectorMinErr('itkn', 'Incorrect injection token! Expected service name as string, got {0}', key); } args.push( locals && locals.hasOwnProperty(key) ? locals[key] : getService(key, serviceName) ); } if (isArray(fn)) { fn = fn[length]; } // http://jsperf.com/angularjs-invoke-apply-vs-switch // #5388 return fn.apply(self, args); } function instantiate(Type, locals, serviceName) { // Check if Type is annotated and use just the given function at n-1 as parameter // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]); // Object creation: http://jsperf.com/create-constructor/2 var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null); var returnedValue = invoke(Type, instance, locals, serviceName); return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance; } return { invoke: invoke, instantiate: instantiate, get: getService, annotate: annotate, has: function(name) { return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); } }; } } createInjector.$$annotate = annotate; /** * @ngdoc provider * @name $anchorScrollProvider * * @description * Use `$anchorScrollProvider` to disable automatic scrolling whenever * {@link ng.$location#hash $location.hash()} changes. */ function $AnchorScrollProvider() { var autoScrollingEnabled = true; /** * @ngdoc method * @name $anchorScrollProvider#disableAutoScrolling * * @description * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br /> * Use this method to disable automatic scrolling. * * If automatic scrolling is disabled, one must explicitly call * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the * current hash. */ this.disableAutoScrolling = function() { autoScrollingEnabled = false; }; /** * @ngdoc service * @name $anchorScroll * @kind function * @requires $window * @requires $location * @requires $rootScope * * @description * When called, it checks the current value of {@link ng.$location#hash $location.hash()} and * scrolls to the related element, according to the rules specified in the * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document). * * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to * match any anchor whenever it changes. This can be disabled by calling * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}. * * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a * vertical scroll-offset (either fixed or dynamic). * * @property {(number|function|jqLite)} yOffset * If set, specifies a vertical scroll-offset. This is often useful when there are fixed * positioned elements at the top of the page, such as navbars, headers etc. * * `yOffset` can be specified in various ways: * - **number**: A fixed number of pixels to be used as offset.<br /><br /> * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return * a number representing the offset (in pixels).<br /><br /> * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from * the top of the page to the element's bottom will be used as offset.<br /> * **Note**: The element will be taken into account only as long as its `position` is set to * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust * their height and/or positioning according to the viewport's size. * * <br /> * <div class="alert alert-warning"> * In order for `yOffset` to work properly, scrolling should take place on the document's root and * not some child element. * </div> * * @example <example module="anchorScrollExample"> <file name="index.html"> <div id="scrollArea" ng-controller="ScrollController"> <a ng-click="gotoBottom()">Go to bottom</a> <a id="bottom"></a> You're at the bottom! </div> </file> <file name="script.js"> angular.module('anchorScrollExample', []) .controller('ScrollController', ['$scope', '$location', '$anchorScroll', function ($scope, $location, $anchorScroll) { $scope.gotoBottom = function() { // set the location.hash to the id of // the element you wish to scroll to. $location.hash('bottom'); // call $anchorScroll() $anchorScroll(); }; }]); </file> <file name="style.css"> #scrollArea { height: 280px; overflow: auto; } #bottom { display: block; margin-top: 2000px; } </file> </example> * * <hr /> * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value). * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details. * * @example <example module="anchorScrollOffsetExample"> <file name="index.html"> <div class="fixed-header" ng-controller="headerCtrl"> <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]"> Go to anchor {{x}} </a> </div> <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]"> Anchor {{x}} of 5 </div> </file> <file name="script.js"> angular.module('anchorScrollOffsetExample', []) .run(['$anchorScroll', function($anchorScroll) { $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels }]) .controller('headerCtrl', ['$anchorScroll', '$location', '$scope', function ($anchorScroll, $location, $scope) { $scope.gotoAnchor = function(x) { var newHash = 'anchor' + x; if ($location.hash() !== newHash) { // set the $location.hash to `newHash` and // $anchorScroll will automatically scroll to it $location.hash('anchor' + x); } else { // call $anchorScroll() explicitly, // since $location.hash hasn't changed $anchorScroll(); } }; } ]); </file> <file name="style.css"> body { padding-top: 50px; } .anchor { border: 2px dashed DarkOrchid; padding: 10px 10px 200px 10px; } .fixed-header { background-color: rgba(0, 0, 0, 0.2); height: 50px; position: fixed; top: 0; left: 0; right: 0; } .fixed-header > a { display: inline-block; margin: 5px 15px; } </file> </example> */ this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) { var document = $window.document; // Helper function to get first anchor from a NodeList // (using `Array#some()` instead of `angular#forEach()` since it's more performant // and working in all supported browsers.) function getFirstAnchor(list) { var result = null; Array.prototype.some.call(list, function(element) { if (nodeName_(element) === 'a') { result = element; return true; } }); return result; } function getYOffset() { var offset = scroll.yOffset; if (isFunction(offset)) { offset = offset(); } else if (isElement(offset)) { var elem = offset[0]; var style = $window.getComputedStyle(elem); if (style.position !== 'fixed') { offset = 0; } else { offset = elem.getBoundingClientRect().bottom; } } else if (!isNumber(offset)) { offset = 0; } return offset; } function scrollTo(elem) { if (elem) { elem.scrollIntoView(); var offset = getYOffset(); if (offset) { // `offset` is the number of pixels we should scroll UP in order to align `elem` properly. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the // top of the viewport. // // IF the number of pixels from the top of `elem` to the end of the page's content is less // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some // way down the page. // // This is often the case for elements near the bottom of the page. // // In such cases we do not need to scroll the whole `offset` up, just the difference between // the top of the element and the offset, which is enough to align the top of `elem` at the // desired position. var elemTop = elem.getBoundingClientRect().top; $window.scrollBy(0, elemTop - offset); } } else { $window.scrollTo(0, 0); } } function scroll() { var hash = $location.hash(), elm; // empty hash, scroll to the top of the page if (!hash) scrollTo(null); // element with given id else if ((elm = document.getElementById(hash))) scrollTo(elm); // first anchor with given name :-D else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm); // no element and hash == 'top', scroll to the top of the page else if (hash === 'top') scrollTo(null); } // does not scroll when user clicks on anchor link that is currently on // (no url change, no $location.hash() change), browser native does scroll if (autoScrollingEnabled) { $rootScope.$watch(function autoScrollWatch() {return $location.hash();}, function autoScrollWatchAction(newVal, oldVal) { // skip the initial scroll if $location.hash is empty if (newVal === oldVal && newVal === '') return; jqLiteDocumentLoaded(function() { $rootScope.$evalAsync(scroll); }); }); } return scroll; }]; } var $animateMinErr = minErr('$animate'); /** * @ngdoc provider * @name $animateProvider * * @description * Default implementation of $animate that doesn't perform any animations, instead just * synchronously performs DOM * updates and calls done() callbacks. * * In order to enable animations the ngAnimate module has to be loaded. * * To see the functional implementation check out src/ngAnimate/animate.js */ var $AnimateProvider = ['$provide', function($provide) { this.$$selectors = {}; /** * @ngdoc method * @name $animateProvider#register * * @description * Registers a new injectable animation factory function. The factory function produces the * animation object which contains callback functions for each event that is expected to be * animated. * * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction` * must be called once the element animation is complete. If a function is returned then the * animation service will use this function to cancel the animation whenever a cancel event is * triggered. * * * ```js * return { * eventFn : function(element, done) { * //code to run the animation * //once complete, then run done() * return function cancellationFunction() { * //code to cancel the animation * } * } * } * ``` * * @param {string} name The name of the animation. * @param {Function} factory The factory function that will be executed to return the animation * object. */ this.register = function(name, factory) { var key = name + '-animation'; if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name); this.$$selectors[name.substr(1)] = key; $provide.factory(key, factory); }; /** * @ngdoc method * @name $animateProvider#classNameFilter * * @description * Sets and/or returns the CSS class regular expression that is checked when performing * an animation. Upon bootstrap the classNameFilter value is not set at all and will * therefore enable $animate to attempt to perform an animation on any element. * When setting the classNameFilter value, animations will only be performed on elements * that successfully match the filter expression. This in turn can boost performance * for low-powered devices as well as applications containing a lot of structural operations. * @param {RegExp=} expression The className expression which will be checked against all animations * @return {RegExp} The current CSS className expression value. If null then there is no expression value */ this.classNameFilter = function(expression) { if (arguments.length === 1) { this.$$classNameFilter = (expression instanceof RegExp) ? expression : null; } return this.$$classNameFilter; }; this.$get = ['$$q', '$$asyncCallback', '$rootScope', function($$q, $$asyncCallback, $rootScope) { var currentDefer; function runAnimationPostDigest(fn) { var cancelFn, defer = $$q.defer(); defer.promise.$$cancelFn = function ngAnimateMaybeCancel() { cancelFn && cancelFn(); }; $rootScope.$$postDigest(function ngAnimatePostDigest() { cancelFn = fn(function ngAnimateNotifyComplete() { defer.resolve(); }); }); return defer.promise; } function resolveElementClasses(element, classes) { var toAdd = [], toRemove = []; var hasClasses = createMap(); forEach((element.attr('class') || '').split(/\s+/), function(className) { hasClasses[className] = true; }); forEach(classes, function(status, className) { var hasClass = hasClasses[className]; // If the most recent class manipulation (via $animate) was to remove the class, and the // element currently has the class, the class is scheduled for removal. Otherwise, if // the most recent class manipulation (via $animate) was to add the class, and the // element does not currently have the class, the class is scheduled to be added. if (status === false && hasClass) { toRemove.push(className); } else if (status === true && !hasClass) { toAdd.push(className); } }); return (toAdd.length + toRemove.length) > 0 && [toAdd.length ? toAdd : null, toRemove.length ? toRemove : null]; } function cachedClassManipulation(cache, classes, op) { for (var i=0, ii = classes.length; i < ii; ++i) { var className = classes[i]; cache[className] = op; } } function asyncPromise() { // only serve one instance of a promise in order to save CPU cycles if (!currentDefer) { currentDefer = $$q.defer(); $$asyncCallback(function() { currentDefer.resolve(); currentDefer = null; }); } return currentDefer.promise; } function applyStyles(element, options) { if (angular.isObject(options)) { var styles = extend(options.from || {}, options.to || {}); element.css(styles); } } /** * * @ngdoc service * @name $animate * @description The $animate service provides rudimentary DOM manipulation functions to * insert, remove and move elements within the DOM, as well as adding and removing classes. * This service is the core service used by the ngAnimate $animator service which provides * high-level animation hooks for CSS and JavaScript. * * $animate is available in the AngularJS core, however, the ngAnimate module must be included * to enable full out animation support. Otherwise, $animate will only perform simple DOM * manipulation operations. * * To learn more about enabling animation support, click here to visit the {@link ngAnimate * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service * page}. */ return { animate: function(element, from, to) { applyStyles(element, { from: from, to: to }); return asyncPromise(); }, /** * * @ngdoc method * @name $animate#enter * @kind function * @description Inserts the element into the DOM either after the `after` element or * as the first child within the `parent` element. When the function is called a promise * is returned that will be resolved at a later time. * @param {DOMElement} element the element which will be inserted into the DOM * @param {DOMElement} parent the parent element which will append the element as * a child (if the after element is not present) * @param {DOMElement} after the sibling element which will append the element * after itself * @param {object=} options an optional collection of styles that will be applied to the element. * @return {Promise} the animation callback promise */ enter: function(element, parent, after, options) { applyStyles(element, options); after ? after.after(element) : parent.prepend(element); return asyncPromise(); }, /** * * @ngdoc method * @name $animate#leave * @kind function * @description Removes the element from the DOM. When the function is called a promise * is returned that will be resolved at a later time. * @param {DOMElement} element the element which will be removed from the DOM * @param {object=} options an optional collection of options that will be applied to the element. * @return {Promise} the animation callback promise */ leave: function(element, options) { element.remove(); return asyncPromise(); }, /** * * @ngdoc method * @name $animate#move * @kind function * @description Moves the position of the provided element within the DOM to be placed * either after the `after` element or inside of the `parent` element. When the function * is called a promise is returned that will be resolved at a later time. * * @param {DOMElement} element the element which will be moved around within the * DOM * @param {DOMElement} parent the parent element where the element will be * inserted into (if the after element is not present) * @param {DOMElement} after the sibling element where the element will be * positioned next to * @param {object=} options an optional collection of options that will be applied to the element. * @return {Promise} the animation callback promise */ move: function(element, parent, after, options) { // Do not remove element before insert. Removing will cause data associated with the // element to be dropped. Insert will implicitly do the remove. return this.enter(element, parent, after, options); }, /** * * @ngdoc method * @name $animate#addClass * @kind function * @description Adds the provided className CSS class value to the provided element. * When the function is called a promise is returned that will be resolved at a later time. * @param {DOMElement} element the element which will have the className value * added to it * @param {string} className the CSS class which will be added to the element * @param {object=} options an optional collection of options that will be applied to the element. * @return {Promise} the animation callback promise */ addClass: function(element, className, options) { return this.setClass(element, className, [], options); }, $$addClassImmediately: function(element, className, options) { element = jqLite(element); className = !isString(className) ? (isArray(className) ? className.join(' ') : '') : className; forEach(element, function(element) { jqLiteAddClass(element, className); }); applyStyles(element, options); return asyncPromise(); }, /** * * @ngdoc method * @name $animate#removeClass * @kind function * @description Removes the provided className CSS class value from the provided element. * When the function is called a promise is returned that will be resolved at a later time. * @param {DOMElement} element the element which will have the className value * removed from it * @param {string} className the CSS class which will be removed from the element * @param {object=} options an optional collection of options that will be applied to the element. * @return {Promise} the animation callback promise */ removeClass: function(element, className, options) { return this.setClass(element, [], className, options); }, $$removeClassImmediately: function(element, className, options) { element = jqLite(element); className = !isString(className) ? (isArray(className) ? className.join(' ') : '') : className; forEach(element, function(element) { jqLiteRemoveClass(element, className); }); applyStyles(element, options); return asyncPromise(); }, /** * * @ngdoc method * @name $animate#setClass * @kind function * @description Adds and/or removes the given CSS classes to and from the element. * When the function is called a promise is returned that will be resolved at a later time. * @param {DOMElement} element the element which will have its CSS classes changed * removed from it * @param {string} add the CSS classes which will be added to the element * @param {string} remove the CSS class which will be removed from the element * @param {object=} options an optional collection of options that will be applied to the element. * @return {Promise} the animation callback promise */ setClass: function(element, add, remove, options) { var self = this; var STORAGE_KEY = '$$animateClasses'; var createdCache = false; element = jqLite(element); var cache = element.data(STORAGE_KEY); if (!cache) { cache = { classes: {}, options: options }; createdCache = true; } else if (options && cache.options) { cache.options = angular.extend(cache.options || {}, options); } var classes = cache.classes; add = isArray(add) ? add : add.split(' '); remove = isArray(remove) ? remove : remove.split(' '); cachedClassManipulation(classes, add, true); cachedClassManipulation(classes, remove, false); if (createdCache) { cache.promise = runAnimationPostDigest(function(done) { var cache = element.data(STORAGE_KEY); element.removeData(STORAGE_KEY); // in the event that the element is removed before postDigest // is run then the cache will be undefined and there will be // no need anymore to add or remove and of the element classes if (cache) { var classes = resolveElementClasses(element, cache.classes); if (classes) { self.$$setClassImmediately(element, classes[0], classes[1], cache.options); } } done(); }); element.data(STORAGE_KEY, cache); } return cache.promise; }, $$setClassImmediately: function(element, add, remove, options) { add && this.$$addClassImmediately(element, add); remove && this.$$removeClassImmediately(element, remove); applyStyles(element, options); return asyncPromise(); }, enabled: noop, cancel: noop }; }]; }]; function $$AsyncCallbackProvider() { this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) { return $$rAF.supported ? function(fn) { return $$rAF(fn); } : function(fn) { return $timeout(fn, 0, false); }; }]; } /* global stripHash: true */ /** * ! This is a private undocumented service ! * * @name $browser * @requires $log * @description * This object has two goals: * * - hide all the global state in the browser caused by the window object * - abstract away all the browser specific features and inconsistencies * * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` * service, which can be used for convenient testing of the application without the interaction with * the real browser apis. */ /** * @param {object} window The global window object. * @param {object} document jQuery wrapped document. * @param {object} $log window.console or an object with the same interface. * @param {object} $sniffer $sniffer service */ function Browser(window, document, $log, $sniffer) { var self = this, rawDocument = document[0], location = window.location, history = window.history, setTimeout = window.setTimeout, clearTimeout = window.clearTimeout, pendingDeferIds = {}; self.isMock = false; var outstandingRequestCount = 0; var outstandingRequestCallbacks = []; // TODO(vojta): remove this temporary api self.$$completeOutstandingRequest = completeOutstandingRequest; self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; }; /** * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. */ function completeOutstandingRequest(fn) { try { fn.apply(null, sliceArgs(arguments, 1)); } finally { outstandingRequestCount--; if (outstandingRequestCount === 0) { while (outstandingRequestCallbacks.length) { try { outstandingRequestCallbacks.pop()(); } catch (e) { $log.error(e); } } } } } function getHash(url) { var index = url.indexOf('#'); return index === -1 ? '' : url.substr(index + 1); } /** * @private * Note: this method is used only by scenario runner * TODO(vojta): prefix this method with $$ ? * @param {function()} callback Function that will be called when no outstanding request */ self.notifyWhenNoOutstandingRequests = function(callback) { // force browser to execute all pollFns - this is needed so that cookies and other pollers fire // at some deterministic time in respect to the test runner's actions. Leaving things up to the // regular poller would result in flaky tests. forEach(pollFns, function(pollFn) { pollFn(); }); if (outstandingRequestCount === 0) { callback(); } else { outstandingRequestCallbacks.push(callback); } }; ////////////////////////////////////////////////////////////// // Poll Watcher API ////////////////////////////////////////////////////////////// var pollFns = [], pollTimeout; /** * @name $browser#addPollFn * * @param {function()} fn Poll function to add * * @description * Adds a function to the list of functions that poller periodically executes, * and starts polling if not started yet. * * @returns {function()} the added function */ self.addPollFn = function(fn) { if (isUndefined(pollTimeout)) startPoller(100, setTimeout); pollFns.push(fn); return fn; }; /** * @param {number} interval How often should browser call poll functions (ms) * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. * * @description * Configures the poller to run in the specified intervals, using the specified * setTimeout fn and kicks it off. */ function startPoller(interval, setTimeout) { (function check() { forEach(pollFns, function(pollFn) { pollFn(); }); pollTimeout = setTimeout(check, interval); })(); } ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// var cachedState, lastHistoryState, lastBrowserUrl = location.href, baseElement = document.find('base'), reloadLocation = null; cacheState(); lastHistoryState = cachedState; /** * @name $browser#url * * @description * GETTER: * Without any argument, this method just returns current value of location.href. * * SETTER: * With at least one argument, this method sets url to new value. * If html5 history api supported, pushState/replaceState is used, otherwise * location.href/location.replace is used. * Returns its own instance to allow chaining * * NOTE: this api is intended for use only by the $location service. Please use the * {@link ng.$location $location service} to change url. * * @param {string} url New url (when used as setter) * @param {boolean=} replace Should new url replace current history record? * @param {object=} state object to use with pushState/replaceState */ self.url = function(url, replace, state) { // In modern browsers `history.state` is `null` by default; treating it separately // from `undefined` would cause `$browser.url('/foo')` to change `history.state` // to undefined via `pushState`. Instead, let's change `undefined` to `null` here. if (isUndefined(state)) { state = null; } // Android Browser BFCache causes location, history reference to become stale. if (location !== window.location) location = window.location; if (history !== window.history) history = window.history; // setter if (url) { var sameState = lastHistoryState === state; // Don't change anything if previous and current URLs and states match. This also prevents // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode. // See https://github.com/angular/angular.js/commit/ffb2701 if (lastBrowserUrl === url && (!$sniffer.history || sameState)) { return self; } var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url); lastBrowserUrl = url; lastHistoryState = state; // Don't use history API if only the hash changed // due to a bug in IE10/IE11 which leads // to not firing a `hashchange` nor `popstate` event // in some cases (see #9143). if ($sniffer.history && (!sameBase || !sameState)) { history[replace ? 'replaceState' : 'pushState'](state, '', url); cacheState(); // Do the assignment again so that those two variables are referentially identical. lastHistoryState = cachedState; } else { if (!sameBase) { reloadLocation = url; } if (replace) { location.replace(url); } else if (!sameBase) { location.href = url; } else { location.hash = getHash(url); } } return self; // getter } else { // - reloadLocation is needed as browsers don't allow to read out // the new location.href if a reload happened. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 return reloadLocation || location.href.replace(/%27/g,"'"); } }; /** * @name $browser#state * * @description * This method is a getter. * * Return history.state or null if history.state is undefined. * * @returns {object} state */ self.state = function() { return cachedState; }; var urlChangeListeners = [], urlChangeInit = false; function cacheStateAndFireUrlChange() { cacheState(); fireUrlChange(); } // This variable should be used *only* inside the cacheState function. var lastCachedState = null; function cacheState() { // This should be the only place in $browser where `history.state` is read. cachedState = window.history.state; cachedState = isUndefined(cachedState) ? null : cachedState; // Prevent callbacks fo fire twice if both hashchange & popstate were fired. if (equals(cachedState, lastCachedState)) { cachedState = lastCachedState; } lastCachedState = cachedState; } function fireUrlChange() { if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) { return; } lastBrowserUrl = self.url(); lastHistoryState = cachedState; forEach(urlChangeListeners, function(listener) { listener(self.url(), cachedState); }); } /** * @name $browser#onUrlChange * * @description * Register callback function that will be called, when url changes. * * It's only called when the url is changed from outside of angular: * - user types different url into address bar * - user clicks on history (forward/back) button * - user clicks on a link * * It's not called when url is changed by $browser.url() method * * The listener gets called with new url as parameter. * * NOTE: this api is intended for use only by the $location service. Please use the * {@link ng.$location $location service} to monitor url changes in angular apps. * * @param {function(string)} listener Listener function to be called when url changes. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. */ self.onUrlChange = function(callback) { // TODO(vojta): refactor to use node's syntax for events if (!urlChangeInit) { // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) // don't fire popstate when user change the address bar and don't fire hashchange when url // changed by push/replaceState // html5 history api - popstate event if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange); // hashchange event jqLite(window).on('hashchange', cacheStateAndFireUrlChange); urlChangeInit = true; } urlChangeListeners.push(callback); return callback; }; /** * Checks whether the url has changed outside of Angular. * Needs to be exported to be able to check for changes that have been done in sync, * as hashchange/popstate events fire in async. */ self.$$checkUrlChange = fireUrlChange; ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// /** * @name $browser#baseHref * * @description * Returns current <base href> * (always relative - without domain) * * @returns {string} The current base href */ self.baseHref = function() { var href = baseElement.attr('href'); return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : ''; }; ////////////////////////////////////////////////////////////// // Cookies API ////////////////////////////////////////////////////////////// var lastCookies = {}; var lastCookieString = ''; var cookiePath = self.baseHref(); function safeDecodeURIComponent(str) { try { return decodeURIComponent(str); } catch (e) { return str; } } /** * @name $browser#cookies * * @param {string=} name Cookie name * @param {string=} value Cookie value * * @description * The cookies method provides a 'private' low level access to browser cookies. * It is not meant to be used directly, use the $cookie service instead. * * The return values vary depending on the arguments that the method was called with as follows: * * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify * it * - cookies(name, value) -> set name to value, if value is undefined delete the cookie * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that * way) * * @returns {Object} Hash of all cookies (if called without any parameter) */ self.cookies = function(name, value) { var cookieLength, cookieArray, cookie, i, index; if (name) { if (value === undefined) { rawDocument.cookie = encodeURIComponent(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT"; } else { if (isString(value)) { cookieLength = (rawDocument.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) + ';path=' + cookiePath).length + 1; // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: // - 300 cookies // - 20 cookies per unique domain // - 4096 bytes per cookie if (cookieLength > 4096) { $log.warn("Cookie '" + name + "' possibly not set or overflowed because it was too large (" + cookieLength + " > 4096 bytes)!"); } } } } else { if (rawDocument.cookie !== lastCookieString) { lastCookieString = rawDocument.cookie; cookieArray = lastCookieString.split("; "); lastCookies = {}; for (i = 0; i < cookieArray.length; i++) { cookie = cookieArray[i]; index = cookie.indexOf('='); if (index > 0) { //ignore nameless cookies name = safeDecodeURIComponent(cookie.substring(0, index)); // the first value that is seen for a cookie is the most // specific one. values for the same cookie name that // follow are for less specific paths. if (lastCookies[name] === undefined) { lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1)); } } } } return lastCookies; } }; /** * @name $browser#defer * @param {function()} fn A function, who's execution should be deferred. * @param {number=} [delay=0] of milliseconds to defer the function execution. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. * * @description * Executes a fn asynchronously via `setTimeout(fn, delay)`. * * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed * via `$browser.defer.flush()`. * */ self.defer = function(fn, delay) { var timeoutId; outstandingRequestCount++; timeoutId = setTimeout(function() { delete pendingDeferIds[timeoutId]; completeOutstandingRequest(fn); }, delay || 0); pendingDeferIds[timeoutId] = true; return timeoutId; }; /** * @name $browser#defer.cancel * * @description * Cancels a deferred task identified with `deferId`. * * @param {*} deferId Token returned by the `$browser.defer` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully * canceled. */ self.defer.cancel = function(deferId) { if (pendingDeferIds[deferId]) { delete pendingDeferIds[deferId]; clearTimeout(deferId); completeOutstandingRequest(noop); return true; } return false; }; } function $BrowserProvider() { this.$get = ['$window', '$log', '$sniffer', '$document', function($window, $log, $sniffer, $document) { return new Browser($window, $document, $log, $sniffer); }]; } /** * @ngdoc service * @name $cacheFactory * * @description * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to * them. * * ```js * * var cache = $cacheFactory('cacheId'); * expect($cacheFactory.get('cacheId')).toBe(cache); * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined(); * * cache.put("key", "value"); * cache.put("another key", "another value"); * * // We've specified no options on creation * expect(cache.info()).toEqual({id: 'cacheId', size: 2}); * * ``` * * * @param {string} cacheId Name or id of the newly created cache. * @param {object=} options Options object that specifies the cache behavior. Properties: * * - `{number=}` `capacity` — turns the cache into LRU cache. * * @returns {object} Newly created cache object with the following set of methods: * * - `{object}` `info()` — Returns id, size, and options of cache. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns * it. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache. * - `{void}` `removeAll()` — Removes all cached values. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory. * * @example <example module="cacheExampleApp"> <file name="index.html"> <div ng-controller="CacheController"> <input ng-model="newCacheKey" placeholder="Key"> <input ng-model="newCacheValue" placeholder="Value"> <button ng-click="put(newCacheKey, newCacheValue)">Cache</button> <p ng-if="keys.length">Cached Values</p> <div ng-repeat="key in keys"> <span ng-bind="key"></span> <span>: </span> <b ng-bind="cache.get(key)"></b> </div> <p>Cache Info</p> <div ng-repeat="(key, value) in cache.info()"> <span ng-bind="key"></span> <span>: </span> <b ng-bind="value"></b> </div> </div> </file> <file name="script.js"> angular.module('cacheExampleApp', []). controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) { $scope.keys = []; $scope.cache = $cacheFactory('cacheId'); $scope.put = function(key, value) { if ($scope.cache.get(key) === undefined) { $scope.keys.push(key); } $scope.cache.put(key, value === undefined ? null : value); }; }]); </file> <file name="style.css"> p { margin: 10px 0 3px; } </file> </example> */ function $CacheFactoryProvider() { this.$get = function() { var caches = {}; function cacheFactory(cacheId, options) { if (cacheId in caches) { throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId); } var size = 0, stats = extend({}, options, {id: cacheId}), data = {}, capacity = (options && options.capacity) || Number.MAX_VALUE, lruHash = {}, freshEnd = null, staleEnd = null; /** * @ngdoc type * @name $cacheFactory.Cache * * @description * A cache object used to store and retrieve data, primarily used by * {@link $http $http} and the {@link ng.directive:script script} directive to cache * templates and other data. * * ```js * angular.module('superCache') * .factory('superCache', ['$cacheFactory', function($cacheFactory) { * return $cacheFactory('super-cache'); * }]); * ``` * * Example test: * * ```js * it('should behave like a cache', inject(function(superCache) { * superCache.put('key', 'value'); * superCache.put('another key', 'another value'); * * expect(superCache.info()).toEqual({ * id: 'super-cache', * size: 2 * }); * * superCache.remove('another key'); * expect(superCache.get('another key')).toBeUndefined(); * * superCache.removeAll(); * expect(superCache.info()).toEqual({ * id: 'super-cache', * size: 0 * }); * })); * ``` */ return caches[cacheId] = { /** * @ngdoc method * @name $cacheFactory.Cache#put * @kind function * * @description * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be * retrieved later, and incrementing the size of the cache if the key was not already * present in the cache. If behaving like an LRU cache, it will also remove stale * entries from the set. * * It will not insert undefined values into the cache. * * @param {string} key the key under which the cached data is stored. * @param {*} value the value to store alongside the key. If it is undefined, the key * will not be stored. * @returns {*} the value stored. */ put: function(key, value) { if (capacity < Number.MAX_VALUE) { var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); refresh(lruEntry); } if (isUndefined(value)) return; if (!(key in data)) size++; data[key] = value; if (size > capacity) { this.remove(staleEnd.key); } return value; }, /** * @ngdoc method * @name $cacheFactory.Cache#get * @kind function * * @description * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object. * * @param {string} key the key of the data to be retrieved * @returns {*} the value stored. */ get: function(key) { if (capacity < Number.MAX_VALUE) { var lruEntry = lruHash[key]; if (!lruEntry) return; refresh(lruEntry); } return data[key]; }, /** * @ngdoc method * @name $cacheFactory.Cache#remove * @kind function * * @description * Removes an entry from the {@link $cacheFactory.Cache Cache} object. * * @param {string} key the key of the entry to be removed */ remove: function(key) { if (capacity < Number.MAX_VALUE) { var lruEntry = lruHash[key]; if (!lruEntry) return; if (lruEntry == freshEnd) freshEnd = lruEntry.p; if (lruEntry == staleEnd) staleEnd = lruEntry.n; link(lruEntry.n,lruEntry.p); delete lruHash[key]; } delete data[key]; size--; }, /** * @ngdoc method * @name $cacheFactory.Cache#removeAll * @kind function * * @description * Clears the cache object of any entries. */ removeAll: function() { data = {}; size = 0; lruHash = {}; freshEnd = staleEnd = null; }, /** * @ngdoc method * @name $cacheFactory.Cache#destroy * @kind function * * @description * Destroys the {@link $cacheFactory.Cache Cache} object entirely, * removing it from the {@link $cacheFactory $cacheFactory} set. */ destroy: function() { data = null; stats = null; lruHash = null; delete caches[cacheId]; }, /** * @ngdoc method * @name $cacheFactory.Cache#info * @kind function * * @description * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}. * * @returns {object} an object with the following properties: * <ul> * <li>**id**: the id of the cache instance</li> * <li>**size**: the number of entries kept in the cache instance</li> * <li>**...**: any additional properties from the options object when creating the * cache.</li> * </ul> */ info: function() { return extend({}, stats, {size: size}); } }; /** * makes the `entry` the freshEnd of the LRU linked list */ function refresh(entry) { if (entry != freshEnd) { if (!staleEnd) { staleEnd = entry; } else if (staleEnd == entry) { staleEnd = entry.n; } link(entry.n, entry.p); link(entry, freshEnd); freshEnd = entry; freshEnd.n = null; } } /** * bidirectionally links two entries of the LRU linked list */ function link(nextEntry, prevEntry) { if (nextEntry != prevEntry) { if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify } } } /** * @ngdoc method * @name $cacheFactory#info * * @description * Get information about all the caches that have been created * * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info` */ cacheFactory.info = function() { var info = {}; forEach(caches, function(cache, cacheId) { info[cacheId] = cache.info(); }); return info; }; /** * @ngdoc method * @name $cacheFactory#get * * @description * Get access to a cache object by the `cacheId` used when it was created. * * @param {string} cacheId Name or id of a cache to access. * @returns {object} Cache object identified by the cacheId or undefined if no such cache. */ cacheFactory.get = function(cacheId) { return caches[cacheId]; }; return cacheFactory; }; } /** * @ngdoc service * @name $templateCache * * @description * The first time a template is used, it is loaded in the template cache for quick retrieval. You * can load templates directly into the cache in a `script` tag, or by consuming the * `$templateCache` service directly. * * Adding via the `script` tag: * * ```html * <script type="text/ng-template" id="templateId.html"> * <p>This is the content of the template</p> * </script> * ``` * * **Note:** the `script` tag containing the template does not need to be included in the `head` of * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE, * element with ng-app attribute), otherwise the template will be ignored. * * Adding via the $templateCache service: * * ```js * var myApp = angular.module('myApp', []); * myApp.run(function($templateCache) { * $templateCache.put('templateId.html', 'This is the content of the template'); * }); * ``` * * To retrieve the template later, simply use it in your HTML: * ```html * <div ng-include=" 'templateId.html' "></div> * ``` * * or get it via Javascript: * ```js * $templateCache.get('templateId.html') * ``` * * See {@link ng.$cacheFactory $cacheFactory}. * */ function $TemplateCacheProvider() { this.$get = ['$cacheFactory', function($cacheFactory) { return $cacheFactory('templates'); }]; } /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE! * * DOM-related variables: * * - "node" - DOM Node * - "element" - DOM Element or Node * - "$node" or "$element" - jqLite-wrapped node or element * * * Compiler related stuff: * * - "linkFn" - linking fn of a single directive * - "nodeLinkFn" - function that aggregates all linking fns for a particular node * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList) */ /** * @ngdoc service * @name $compile * @kind function * * @description * Compiles an HTML string or DOM into a template and produces a template function, which * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together. * * The compilation is a process of walking the DOM tree and matching DOM elements to * {@link ng.$compileProvider#directive directives}. * * <div class="alert alert-warning"> * **Note:** This document is an in-depth reference of all directive options. * For a gentle introduction to directives with examples of common use cases, * see the {@link guide/directive directive guide}. * </div> * * ## Comprehensive Directive API * * There are many different options for a directive. * * The difference resides in the return value of the factory function. * You can either return a "Directive Definition Object" (see below) that defines the directive properties, * or just the `postLink` function (all other properties will have the default values). * * <div class="alert alert-success"> * **Best Practice:** It's recommended to use the "directive definition object" form. * </div> * * Here's an example directive declared with a Directive Definition Object: * * ```js * var myModule = angular.module(...); * * myModule.directive('directiveName', function factory(injectables) { * var directiveDefinitionObject = { * priority: 0, * template: '<div></div>', // or // function(tElement, tAttrs) { ... }, * // or * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... }, * transclude: false, * restrict: 'A', * templateNamespace: 'html', * scope: false, * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... }, * controllerAs: 'stringAlias', * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'], * compile: function compile(tElement, tAttrs, transclude) { * return { * pre: function preLink(scope, iElement, iAttrs, controller) { ... }, * post: function postLink(scope, iElement, iAttrs, controller) { ... } * } * // or * // return function postLink( ... ) { ... } * }, * // or * // link: { * // pre: function preLink(scope, iElement, iAttrs, controller) { ... }, * // post: function postLink(scope, iElement, iAttrs, controller) { ... } * // } * // or * // link: function postLink( ... ) { ... } * }; * return directiveDefinitionObject; * }); * ``` * * <div class="alert alert-warning"> * **Note:** Any unspecified options will use the default value. You can see the default values below. * </div> * * Therefore the above can be simplified as: * * ```js * var myModule = angular.module(...); * * myModule.directive('directiveName', function factory(injectables) { * var directiveDefinitionObject = { * link: function postLink(scope, iElement, iAttrs) { ... } * }; * return directiveDefinitionObject; * // or * // return function postLink(scope, iElement, iAttrs) { ... } * }); * ``` * * * * ### Directive Definition Object * * The directive definition object provides instructions to the {@link ng.$compile * compiler}. The attributes are: * * #### `multiElement` * When this property is set to true, the HTML compiler will collect DOM nodes between * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them * together as the directive elements. It is recommended that this feature be used on directives * which are not strictly behavioural (such as {@link ngClick}), and which * do not manipulate or replace child nodes (such as {@link ngInclude}). * * #### `priority` * When there are multiple directives defined on a single DOM element, sometimes it * is necessary to specify the order in which the directives are applied. The `priority` is used * to sort the directives before their `compile` functions get called. Priority is defined as a * number. Directives with greater numerical `priority` are compiled first. Pre-link functions * are also run in priority order, but post-link functions are run in reverse order. The order * of directives with the same priority is undefined. The default priority is `0`. * * #### `terminal` * If set to true then the current `priority` will be the last set of directives * which will execute (any directives at the current priority will still execute * as the order of execution on same `priority` is undefined). Note that expressions * and other directives used in the directive's template will also be excluded from execution. * * #### `scope` * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the * same element request a new scope, only one new scope is created. The new scope rule does not * apply for the root of the template since the root of the template always gets a new scope. * * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from * normal scope in that it does not prototypically inherit from the parent scope. This is useful * when creating reusable components, which should not accidentally read or modify data in the * parent scope. * * The 'isolate' scope takes an object hash which defines a set of local scope properties * derived from the parent scope. These local properties are useful for aliasing values for * templates. Locals definition is a hash of local scope property to its source: * * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is * always a string since DOM attributes are strings. If no `attr` name is specified then the * attribute name is assumed to be the same as the local name. * Given `<widget my-attr="hello {{name}}">` and widget definition * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the * `localName` property on the widget scope. The `name` is read from the parent scope (not * component scope). * * * `=` or `=attr` - set up bi-directional binding between a local scope property and the * parent scope property of name defined via the value of the `attr` attribute. If no `attr` * name is specified then the attribute name is assumed to be the same as the local name. * Given `<widget my-attr="parentModel">` and widget definition of * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If * you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use * `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional). * * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. * If no `attr` name is specified then the attribute name is assumed to be the same as the * local name. Given `<widget my-attr="count = count + value">` and widget definition of * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to * a function wrapper for the `count = count + value` expression. Often it's desirable to * pass data from the isolated scope via an expression to the parent scope, this can be * done by passing a map of local variable names and values into the expression wrapper fn. * For example, if the expression is `increment(amount)` then we can specify the amount value * by calling the `localFn` as `localFn({amount: 22})`. * * * #### `bindToController` * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will * allow a component to have its properties bound to the controller, rather than to scope. When the controller * is instantiated, the initial values of the isolate scope bindings are already available. * * #### `controller` * Controller constructor function. The controller is instantiated before the * pre-linking phase and it is shared with other directives (see * `require` attribute). This allows the directives to communicate with each other and augment * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals: * * * `$scope` - Current scope associated with the element * * `$element` - Current element * * `$attrs` - Current attributes object for the element * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope: * `function([scope], cloneLinkingFn, futureParentElement)`. * * `scope`: optional argument to override the scope. * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content. * * `futureParentElement`: * * defines the parent to which the `cloneLinkingFn` will add the cloned elements. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements) * and when the `cloneLinkinFn` is passed, * as those elements need to created and cloned in a special way when they are defined outside their * usual containers (e.g. like `<svg>`). * * See also the `directive.templateNamespace` property. * * * #### `require` * Require another directive and inject its controller as the fourth argument to the linking function. The * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the * injected argument will be an array in corresponding order. If no such directive can be * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with: * * * (no prefix) - Locate the required controller on the current element. Throw an error if not found. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass * `null` to the `link` fn if not found. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass * `null` to the `link` fn if not found. * * * #### `controllerAs` * Controller alias at the directive scope. An alias for the controller so it * can be referenced at the directive template. The directive needs to define a scope for this * configuration to be used. Useful in the case when directive is used as component. * * * #### `restrict` * String of subset of `EACM` which restricts the directive to a specific directive * declaration style. If omitted, the defaults (elements and attributes) are used. * * * `E` - Element name (default): `<my-directive></my-directive>` * * `A` - Attribute (default): `<div my-directive="exp"></div>` * * `C` - Class: `<div class="my-directive: exp;"></div>` * * `M` - Comment: `<!-- directive: my-directive exp -->` * * * #### `templateNamespace` * String representing the document type used by the markup in the template. * AngularJS needs this information as those elements need to be created and cloned * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`. * * * `html` - All root nodes in the template are HTML. Root nodes may also be * top-level elements such as `<svg>` or `<math>`. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`). * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`). * * If no `templateNamespace` is specified, then the namespace is considered to be `html`. * * #### `template` * HTML markup that may: * * Replace the contents of the directive's element (default). * * Replace the directive's element itself (if `replace` is true - DEPRECATED). * * Wrap the contents of the directive's element (if `transclude` is true). * * Value may be: * * * A string. For example `<div red-on-hover>{{delete_str}}</div>`. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile` * function api below) and returns a string value. * * * #### `templateUrl` * This is similar to `template` but the template is loaded from the specified URL, asynchronously. * * Because template loading is asynchronous the compiler will suspend compilation of directives on that element * for later when the template has been resolved. In the meantime it will continue to compile and link * sibling and parent elements as though this element had not contained any directives. * * The compiler does not suspend the entire compilation to wait for templates to be loaded because this * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the * case when only one deeply nested directive has `templateUrl`. * * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache} * * You can specify `templateUrl` as a string representing the URL or as a function which takes two * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns * a string value representing the url. In either case, the template URL is passed through {@link * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}. * * * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0) * specify what the template should replace. Defaults to `false`. * * * `true` - the template will replace the directive's element. * * `false` - the template will replace the contents of the directive's element. * * The replacement process migrates all of the attributes / classes from the old element to the new * one. See the {@link guide/directive#template-expanding-directive * Directives Guide} for an example. * * There are very few scenarios where element replacement is required for the application function, * the main one being reusable custom components that are used within SVG contexts * (because SVG doesn't work with custom elements in the DOM tree). * * #### `transclude` * Extract the contents of the element where the directive appears and make it available to the directive. * The contents are compiled and provided to the directive as a **transclusion function**. See the * {@link $compile#transclusion Transclusion} section below. * * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the * directive's element or the entire element: * * * `true` - transclude the content (i.e. the child nodes) of the directive's element. * * `'element'` - transclude the whole of the directive's element including any directives on this * element that defined at a lower priority than this directive. When used, the `template` * property is ignored. * * * #### `compile` * * ```js * function compile(tElement, tAttrs, transclude) { ... } * ``` * * The compile function deals with transforming the template DOM. Since most directives do not do * template transformation, it is not used often. The compile function takes the following arguments: * * * `tElement` - template element - The element where the directive has been declared. It is * safe to do template transformation on the element and child elements only. * * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared * between all directive compile functions. * * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)` * * <div class="alert alert-warning"> * **Note:** The template instance and the link instance may be different objects if the template has * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration * should be done in a linking function rather than in a compile function. * </div> * <div class="alert alert-warning"> * **Note:** The compile function cannot handle directives that recursively use themselves in their * own templates or compile functions. Compiling these directives results in an infinite loop and a * stack overflow errors. * * This can be avoided by manually using $compile in the postLink function to imperatively compile * a directive's template instead of relying on automatic template compilation via `template` or * `templateUrl` declaration or manual compilation inside the compile function. * </div> * * <div class="alert alert-error"> * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it * e.g. does not know about the right outer scope. Please use the transclude function that is passed * to the link function instead. * </div> * A compile function can have a return value which can be either a function or an object. * * * returning a (post-link) function - is equivalent to registering the linking function via the * `link` property of the config object when the compile function is empty. * * * returning an object with function(s) registered via `pre` and `post` properties - allows you to * control when a linking function should be called during the linking phase. See info about * pre-linking and post-linking functions below. * * * #### `link` * This property is used only if the `compile` property is not defined. * * ```js * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... } * ``` * * The link function is responsible for registering DOM listeners as well as updating the DOM. It is * executed after the template has been cloned. This is where most of the directive logic will be * put. * * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the * directive for registering {@link ng.$rootScope.Scope#$watch watches}. * * * `iElement` - instance element - The element where the directive is to be used. It is safe to * manipulate the children of the element only in `postLink` function since the children have * already been linked. * * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared * between all directive linking functions. * * * `controller` - a controller instance - A controller instance if at least one directive on the * element defines a controller. The controller is shared among all the directives, which allows * the directives to use the controllers as a communication channel. * * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope. * This is the same as the `$transclude` * parameter of directive controllers, see there for details. * `function([scope], cloneLinkingFn, futureParentElement)`. * * #### Pre-linking function * * Executed before the child elements are linked. Not safe to do DOM transformation since the * compiler linking function will fail to locate the correct elements for linking. * * #### Post-linking function * * Executed after the child elements are linked. * * Note that child elements that contain `templateUrl` directives will not have been compiled * and linked since they are waiting for their template to load asynchronously and their own * compilation and linking has been suspended until that occurs. * * It is safe to do DOM transformation in the post-linking function on elements that are not waiting * for their async templates to be resolved. * * * ### Transclusion * * Transclusion is the process of extracting a collection of DOM element from one part of the DOM and * copying them to another part of the DOM, while maintaining their connection to the original AngularJS * scope from where they were taken. * * Transclusion is used (often with {@link ngTransclude}) to insert the * original contents of a directive's element into a specified place in the template of the directive. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded * content has access to the properties on the scope from which it was taken, even if the directive * has isolated scope. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}. * * This makes it possible for the widget to have private state for its template, while the transcluded * content has access to its originating scope. * * <div class="alert alert-warning"> * **Note:** When testing an element transclude directive you must not place the directive at the root of the * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives * Testing Transclusion Directives}. * </div> * * #### Transclusion Functions * * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion * function** to the directive's `link` function and `controller`. This transclusion function is a special * **linking function** that will return the compiled contents linked to a new transclusion scope. * * <div class="alert alert-info"> * If you are just using {@link ngTransclude} then you don't need to worry about this function, since * ngTransclude will deal with it for us. * </div> * * If you want to manually control the insertion and removal of the transcluded content in your directive * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery * object that contains the compiled DOM, which is linked to the correct transclusion scope. * * When you call a transclusion function you can pass in a **clone attach function**. This function accepts * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded * content and the `scope` is the newly created transclusion scope, to which the clone is bound. * * <div class="alert alert-info"> * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope. * </div> * * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone * attach function**: * * ```js * var transcludedContent, transclusionScope; * * $transclude(function(clone, scope) { * element.append(clone); * transcludedContent = clone; * transclusionScope = scope; * }); * ``` * * Later, if you want to remove the transcluded content from your DOM then you should also destroy the * associated transclusion scope: * * ```js * transcludedContent.remove(); * transclusionScope.$destroy(); * ``` * * <div class="alert alert-info"> * **Best Practice**: if you intend to add and remove transcluded content manually in your directive * (by calling the transclude function to get the DOM and and calling `element.remove()` to remove it), * then you are also responsible for calling `$destroy` on the transclusion scope. * </div> * * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat} * automatically destroy their transluded clones as necessary so you do not need to worry about this if * you are simply using {@link ngTransclude} to inject the transclusion into your directive. * * * #### Transclusion Scopes * * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it * was taken. * * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look * like this: * * ```html * <div ng-app> * <div isolate> * <div transclusion> * </div> * </div> * </div> * ``` * * The `$parent` scope hierarchy will look like this: * * ``` * - $rootScope * - isolate * - transclusion * ``` * * but the scopes will inherit prototypically from different scopes to their `$parent`. * * ``` * - $rootScope * - transclusion * - isolate * ``` * * * ### Attributes * * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the * `link()` or `compile()` functions. It has a variety of uses. * * accessing *Normalized attribute names:* * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. * the attributes object allows for normalized access to * the attributes. * * * *Directive inter-communication:* All directives share the same instance of the attributes * object which allows the directives to use the attributes object as inter directive * communication. * * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object * allowing other directives to read the interpolated value. * * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also * the only way to easily get the actual value because during the linking phase the interpolation * hasn't been evaluated yet and so the value is at this time set to `undefined`. * * ```js * function linkingFn(scope, elm, attrs, ctrl) { * // get the attribute value * console.log(attrs.ngModel); * * // change the attribute * attrs.$set('ngModel', 'new value'); * * // observe changes to interpolated attribute * attrs.$observe('ngModel', function(value) { * console.log('ngModel has changed value to ' + value); * }); * } * ``` * * ## Example * * <div class="alert alert-warning"> * **Note**: Typically directives are registered with `module.directive`. The example below is * to illustrate how `$compile` works. * </div> * <example module="compileExample"> <file name="index.html"> <script> angular.module('compileExample', [], function($compileProvider) { // configure new 'compile' directive by passing a directive // factory function. The factory function injects the '$compile' $compileProvider.directive('compile', function($compile) { // directive factory creates a link function return function(scope, element, attrs) { scope.$watch( function(scope) { // watch the 'compile' expression for changes return scope.$eval(attrs.compile); }, function(value) { // when the 'compile' expression changes // assign it into the current DOM element.html(value); // compile the new DOM and link it to the current // scope. // NOTE: we only compile .childNodes so that // we don't get into infinite loop compiling ourselves $compile(element.contents())(scope); } ); }; }); }) .controller('GreeterController', ['$scope', function($scope) { $scope.name = 'Angular'; $scope.html = 'Hello {{name}}'; }]); </script> <div ng-controller="GreeterController"> <input ng-model="name"> <br> <textarea ng-model="html"></textarea> <br> <div compile="html"></div> </div> </file> <file name="protractor.js" type="protractor"> it('should auto compile', function() { var textarea = $('textarea'); var output = $('div[compile]'); // The initial state reads 'Hello Angular'. expect(output.getText()).toBe('Hello Angular'); textarea.clear(); textarea.sendKeys('{{name}}!'); expect(output.getText()).toBe('Angular!'); }); </file> </example> * * * @param {string|DOMElement} element Element or HTML string to compile into a template function. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED. * * <div class="alert alert-error"> * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it * e.g. will not use the right outer scope. Please pass the transclude function as a * `parentBoundTranscludeFn` to the link function instead. * </div> * * @param {number} maxPriority only apply directives lower than given priority (Only effects the * root element(s), not their children) * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template * (a DOM element/tree) to a scope. Where: * * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the * `template` and call the `cloneAttachFn` function allowing the caller to attach the * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is * called as: <br> `cloneAttachFn(clonedElement, scope)` where: * * * `clonedElement` - is a clone of the original `element` passed into the compiler. * * `scope` - is the current scope with which the linking function is working with. * * * `options` - An optional object hash with linking options. If `options` is provided, then the following * keys may be used to control linking behavior: * * * `parentBoundTranscludeFn` - the transclude function made available to * directives; if given, it will be passed through to the link functions of * directives found in `element` during compilation. * * `transcludeControllers` - an object hash with keys that map controller names * to controller instances; if given, it will make the controllers * available to directives. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add * the cloned elements; only needed for transcludes that are allowed to contain non html * elements (e.g. SVG elements). See also the directive.controller property. * * Calling the linking function returns the element of the template. It is either the original * element passed in, or the clone of the element if the `cloneAttachFn` is provided. * * After linking the view is not updated until after a call to $digest which typically is done by * Angular automatically. * * If you need access to the bound view, there are two ways to do it: * * - If you are not asking the linking function to clone the template, create the DOM element(s) * before you send them to the compiler and keep this reference around. * ```js * var element = $compile('<p>{{total}}</p>')(scope); * ``` * * - if on the other hand, you need the element to be cloned, the view reference from the original * example would not point to the clone, but rather to the original template that was cloned. In * this case, you can access the clone via the cloneAttachFn: * ```js * var templateElement = angular.element('<p>{{total}}</p>'), * scope = ....; * * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) { * //attach the clone to DOM document at the right place * }); * * //now we have reference to the cloned DOM via `clonedElement` * ``` * * * For information on how the compiler works, see the * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide. */ var $compileMinErr = minErr('$compile'); /** * @ngdoc provider * @name $compileProvider * * @description */ $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider']; function $CompileProvider($provide, $$sanitizeUriProvider) { var hasDirectives = {}, Suffix = 'Directive', COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/, CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/, ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'), REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/; // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes // The assumption is that future DOM event attribute names will begin with // 'on' and be composed of only English letters. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/; function parseIsolateBindings(scope, directiveName) { var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/; var bindings = {}; forEach(scope, function(definition, scopeName) { var match = definition.match(LOCAL_REGEXP); if (!match) { throw $compileMinErr('iscp', "Invalid isolate scope definition for directive '{0}'." + " Definition: {... {1}: '{2}' ...}", directiveName, scopeName, definition); } bindings[scopeName] = { mode: match[1][0], collection: match[2] === '*', optional: match[3] === '?', attrName: match[4] || scopeName }; }); return bindings; } /** * @ngdoc method * @name $compileProvider#directive * @kind function * * @description * Register a new directive with the compiler. * * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which * will match as <code>ng-bind</code>), or an object map of directives where the keys are the * names and the values are the factories. * @param {Function|Array} directiveFactory An injectable directive factory function. See * {@link guide/directive} for more info. * @returns {ng.$compileProvider} Self for chaining. */ this.directive = function registerDirective(name, directiveFactory) { assertNotHasOwnProperty(name, 'directive'); if (isString(name)) { assertArg(directiveFactory, 'directiveFactory'); if (!hasDirectives.hasOwnProperty(name)) { hasDirectives[name] = []; $provide.factory(name + Suffix, ['$injector', '$exceptionHandler', function($injector, $exceptionHandler) { var directives = []; forEach(hasDirectives[name], function(directiveFactory, index) { try { var directive = $injector.invoke(directiveFactory); if (isFunction(directive)) { directive = { compile: valueFn(directive) }; } else if (!directive.compile && directive.link) { directive.compile = valueFn(directive.link); } directive.priority = directive.priority || 0; directive.index = index; directive.name = directive.name || name; directive.require = directive.require || (directive.controller && directive.name); directive.restrict = directive.restrict || 'EA'; if (isObject(directive.scope)) { directive.$$isolateBindings = parseIsolateBindings(directive.scope, directive.name); } directives.push(directive); } catch (e) { $exceptionHandler(e); } }); return directives; }]); } hasDirectives[name].push(directiveFactory); } else { forEach(name, reverseParams(registerDirective)); } return this; }; /** * @ngdoc method * @name $compileProvider#aHrefSanitizationWhitelist * @kind function * * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during a[href] sanitization. * * The sanitization is a security measure aimed at preventing XSS attacks via html links. * * Any url about to be assigned to a[href] via data-binding is first normalized and turned into * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` * regular expression. If a match is found, the original url is written into the dom. Otherwise, * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.aHrefSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp); return this; } else { return $$sanitizeUriProvider.aHrefSanitizationWhitelist(); } }; /** * @ngdoc method * @name $compileProvider#imgSrcSanitizationWhitelist * @kind function * * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during img[src] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * * Any url about to be assigned to img[src] via data-binding is first normalized and turned into * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` * regular expression. If a match is found, the original url is written into the dom. Otherwise, * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.imgSrcSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp); return this; } else { return $$sanitizeUriProvider.imgSrcSanitizationWhitelist(); } }; /** * @ngdoc method * @name $compileProvider#debugInfoEnabled * * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the * current debugInfoEnabled state * @returns {*} current value if used as getter or itself (chaining) if used as setter * * @kind function * * @description * Call this method to enable/disable various debug runtime information in the compiler such as adding * binding information and a reference to the current scope on to DOM elements. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope * * `ng-binding` CSS class * * `$binding` data property containing an array of the binding expressions * * You may want to disable this in production for a significant performance boost. See * {@link guide/production#disabling-debug-data Disabling Debug Data} for more. * * The default value is true. */ var debugInfoEnabled = true; this.debugInfoEnabled = function(enabled) { if (isDefined(enabled)) { debugInfoEnabled = enabled; return this; } return debugInfoEnabled; }; this.$get = [ '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse', '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri', function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse, $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) { var Attributes = function(element, attributesToCopy) { if (attributesToCopy) { var keys = Object.keys(attributesToCopy); var i, l, key; for (i = 0, l = keys.length; i < l; i++) { key = keys[i]; this[key] = attributesToCopy[key]; } } else { this.$attr = {}; } this.$$element = element; }; Attributes.prototype = { /** * @ngdoc method * @name $compile.directive.Attributes#$normalize * @kind function * * @description * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or * `data-`) to its normalized, camelCase form. * * Also there is special case for Moz prefix starting with upper case letter. * * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives} * * @param {string} name Name to normalize */ $normalize: directiveNormalize, /** * @ngdoc method * @name $compile.directive.Attributes#$addClass * @kind function * * @description * Adds the CSS class value specified by the classVal parameter to the element. If animations * are enabled then an animation will be triggered for the class addition. * * @param {string} classVal The className value that will be added to the element */ $addClass: function(classVal) { if (classVal && classVal.length > 0) { $animate.addClass(this.$$element, classVal); } }, /** * @ngdoc method * @name $compile.directive.Attributes#$removeClass * @kind function * * @description * Removes the CSS class value specified by the classVal parameter from the element. If * animations are enabled then an animation will be triggered for the class removal. * * @param {string} classVal The className value that will be removed from the element */ $removeClass: function(classVal) { if (classVal && classVal.length > 0) { $animate.removeClass(this.$$element, classVal); } }, /** * @ngdoc method * @name $compile.directive.Attributes#$updateClass * @kind function * * @description * Adds and removes the appropriate CSS class values to the element based on the difference * between the new and old CSS class values (specified as newClasses and oldClasses). * * @param {string} newClasses The current CSS className value * @param {string} oldClasses The former CSS className value */ $updateClass: function(newClasses, oldClasses) { var toAdd = tokenDifference(newClasses, oldClasses); if (toAdd && toAdd.length) { $animate.addClass(this.$$element, toAdd); } var toRemove = tokenDifference(oldClasses, newClasses); if (toRemove && toRemove.length) { $animate.removeClass(this.$$element, toRemove); } }, /** * Set a normalized attribute on the element in a way such that all directives * can share the attribute. This function properly handles boolean attributes. * @param {string} key Normalized key. (ie ngAttribute) * @param {string|boolean} value The value to set. If `null` attribute will be deleted. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute. * Defaults to true. * @param {string=} attrName Optional none normalized name. Defaults to key. */ $set: function(key, value, writeAttr, attrName) { // TODO: decide whether or not to throw an error if "class" //is set through this function since it may cause $updateClass to //become unstable. var node = this.$$element[0], booleanKey = getBooleanAttrName(node, key), aliasedKey = getAliasedAttrName(node, key), observer = key, nodeName; if (booleanKey) { this.$$element.prop(key, value); attrName = booleanKey; } else if (aliasedKey) { this[aliasedKey] = value; observer = aliasedKey; } this[key] = value; // translate normalized key to actual key if (attrName) { this.$attr[key] = attrName; } else { attrName = this.$attr[key]; if (!attrName) { this.$attr[key] = attrName = snake_case(key, '-'); } } nodeName = nodeName_(this.$$element); if ((nodeName === 'a' && key === 'href') || (nodeName === 'img' && key === 'src')) { // sanitize a[href] and img[src] values this[key] = value = $$sanitizeUri(value, key === 'src'); } else if (nodeName === 'img' && key === 'srcset') { // sanitize img[srcset] values var result = ""; // first check if there are spaces because it's not the same pattern var trimmedSrcset = trim(value); // ( 999x ,| 999w ,| ,|, ) var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/; var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/; // split srcset into tuple of uri and descriptor except for the last item var rawUris = trimmedSrcset.split(pattern); // for each tuples var nbrUrisWith2parts = Math.floor(rawUris.length / 2); for (var i = 0; i < nbrUrisWith2parts; i++) { var innerIdx = i * 2; // sanitize the uri result += $$sanitizeUri(trim(rawUris[innerIdx]), true); // add the descriptor result += (" " + trim(rawUris[innerIdx + 1])); } // split the last item into uri and descriptor var lastTuple = trim(rawUris[i * 2]).split(/\s/); // sanitize the last uri result += $$sanitizeUri(trim(lastTuple[0]), true); // and add the last descriptor if any if (lastTuple.length === 2) { result += (" " + trim(lastTuple[1])); } this[key] = value = result; } if (writeAttr !== false) { if (value === null || value === undefined) { this.$$element.removeAttr(attrName); } else { this.$$element.attr(attrName, value); } } // fire observers var $$observers = this.$$observers; $$observers && forEach($$observers[observer], function(fn) { try { fn(value); } catch (e) { $exceptionHandler(e); } }); }, /** * @ngdoc method * @name $compile.directive.Attributes#$observe * @kind function * * @description * Observes an interpolated attribute. * * The observer function will be invoked once during the next `$digest` following * compilation. The observer is then invoked whenever the interpolated value * changes. * * @param {string} key Normalized key. (ie ngAttribute) . * @param {function(interpolatedValue)} fn Function that will be called whenever the interpolated value of the attribute changes. * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info. * @returns {function()} Returns a deregistration function for this observer. */ $observe: function(key, fn) { var attrs = this, $$observers = (attrs.$$observers || (attrs.$$observers = createMap())), listeners = ($$observers[key] || ($$observers[key] = [])); listeners.push(fn); $rootScope.$evalAsync(function() { if (!listeners.$$inter && attrs.hasOwnProperty(key)) { // no one registered attribute interpolation function, so lets call it manually fn(attrs[key]); } }); return function() { arrayRemove(listeners, fn); }; } }; function safeAddClass($element, className) { try { $element.addClass(className); } catch (e) { // ignore, since it means that we are trying to set class on // SVG element, where class name is read-only. } } var startSymbol = $interpolate.startSymbol(), endSymbol = $interpolate.endSymbol(), denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}') ? identity : function denormalizeTemplate(template) { return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol); }, NG_ATTR_BINDING = /^ngAttr[A-Z]/; compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) { var bindings = $element.data('$binding') || []; if (isArray(binding)) { bindings = bindings.concat(binding); } else { bindings.push(binding); } $element.data('$binding', bindings); } : noop; compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) { safeAddClass($element, 'ng-binding'); } : noop; compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) { var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope'; $element.data(dataName, scope); } : noop; compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) { safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope'); } : noop; return compile; //================================ function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) { if (!($compileNodes instanceof jqLite)) { // jquery always rewraps, whereas we need to preserve the original selector so that we can // modify it. $compileNodes = jqLite($compileNodes); } // We can not compile top level text elements since text nodes can be merged and we will // not be able to attach scope data to them, so we will wrap them in <span> forEach($compileNodes, function(node, index) { if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) { $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0]; } }); var compositeLinkFn = compileNodes($compileNodes, transcludeFn, $compileNodes, maxPriority, ignoreDirective, previousCompileContext); compile.$$addScopeClass($compileNodes); var namespace = null; return function publicLinkFn(scope, cloneConnectFn, options) { assertArg(scope, 'scope'); options = options || {}; var parentBoundTranscludeFn = options.parentBoundTranscludeFn, transcludeControllers = options.transcludeControllers, futureParentElement = options.futureParentElement; // When `parentBoundTranscludeFn` is passed, it is a // `controllersBoundTransclude` function (it was previously passed // as `transclude` to directive.link) so we must unwrap it to get // its `boundTranscludeFn` if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) { parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude; } if (!namespace) { namespace = detectNamespaceForChildElements(futureParentElement); } var $linkNode; if (namespace !== 'html') { // When using a directive with replace:true and templateUrl the $compileNodes // (or a child element inside of them) // might change, so we need to recreate the namespace adapted compileNodes // for call to the link function. // Note: This will already clone the nodes... $linkNode = jqLite( wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html()) ); } else if (cloneConnectFn) { // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart // and sometimes changes the structure of the DOM. $linkNode = JQLitePrototype.clone.call($compileNodes); } else { $linkNode = $compileNodes; } if (transcludeControllers) { for (var controllerName in transcludeControllers) { $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance); } } compile.$$addScopeInfo($linkNode, scope); if (cloneConnectFn) cloneConnectFn($linkNode, scope); if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn); return $linkNode; }; } function detectNamespaceForChildElements(parentElement) { // TODO: Make this detect MathML as well... var node = parentElement && parentElement[0]; if (!node) { return 'html'; } else { return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html'; } } /** * Compile function matches each node in nodeList against the directives. Once all directives * for a particular node are collected their compile functions are executed. The compile * functions return values - the linking functions - are combined into a composite linking * function, which is the a linking function for the node. * * @param {NodeList} nodeList an array of nodes or NodeList to compile * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the * scope argument is auto-generated to the new child of the transcluded parent scope. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then * the rootElement must be set the jqLite collection of the compile root. This is * needed so that the jqLite collection items can be replaced with widgets. * @param {number=} maxPriority Max directive priority. * @returns {Function} A composite linking function of all of the matched directives or null. */ function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective, previousCompileContext) { var linkFns = [], attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound; for (var i = 0; i < nodeList.length; i++) { attrs = new Attributes(); // we must always refer to nodeList[i] since the nodes can be replaced underneath us. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined, ignoreDirective); nodeLinkFn = (directives.length) ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement, null, [], [], previousCompileContext) : null; if (nodeLinkFn && nodeLinkFn.scope) { compile.$$addScopeClass(attrs.$$element); } childLinkFn = (nodeLinkFn && nodeLinkFn.terminal || !(childNodes = nodeList[i].childNodes) || !childNodes.length) ? null : compileNodes(childNodes, nodeLinkFn ? ( (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement) && nodeLinkFn.transclude) : transcludeFn); if (nodeLinkFn || childLinkFn) { linkFns.push(i, nodeLinkFn, childLinkFn); linkFnFound = true; nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn; } //use the previous context only for the first element in the virtual group previousCompileContext = null; } // return a linking function if we have found anything, null otherwise return linkFnFound ? compositeLinkFn : null; function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) { var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn; var stableNodeList; if (nodeLinkFnFound) { // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our // offsets don't get screwed up var nodeListLength = nodeList.length; stableNodeList = new Array(nodeListLength); // create a sparse array by only copying the elements which have a linkFn for (i = 0; i < linkFns.length; i+=3) { idx = linkFns[i]; stableNodeList[idx] = nodeList[idx]; } } else { stableNodeList = nodeList; } for (i = 0, ii = linkFns.length; i < ii;) { node = stableNodeList[linkFns[i++]]; nodeLinkFn = linkFns[i++]; childLinkFn = linkFns[i++]; if (nodeLinkFn) { if (nodeLinkFn.scope) { childScope = scope.$new(); compile.$$addScopeInfo(jqLite(node), childScope); } else { childScope = scope; } if (nodeLinkFn.transcludeOnThisElement) { childBoundTranscludeFn = createBoundTranscludeFn( scope, nodeLinkFn.transclude, parentBoundTranscludeFn, nodeLinkFn.elementTranscludeOnThisElement); } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) { childBoundTranscludeFn = parentBoundTranscludeFn; } else if (!parentBoundTranscludeFn && transcludeFn) { childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn); } else { childBoundTranscludeFn = null; } nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn); } else if (childLinkFn) { childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn); } } } } function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn, elementTransclusion) { var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) { if (!transcludedScope) { transcludedScope = scope.$new(false, containingScope); transcludedScope.$$transcluded = true; } return transcludeFn(transcludedScope, cloneFn, { parentBoundTranscludeFn: previousBoundTranscludeFn, transcludeControllers: controllers, futureParentElement: futureParentElement }); }; return boundTranscludeFn; } /** * Looks for directives on the given node and adds them to the directive collection which is * sorted. * * @param node Node to search. * @param directives An array to which the directives are added to. This array is sorted before * the function returns. * @param attrs The shared attrs object which is used to populate the normalized attributes. * @param {number=} maxPriority Max directive priority. */ function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) { var nodeType = node.nodeType, attrsMap = attrs.$attr, match, className; switch (nodeType) { case NODE_TYPE_ELEMENT: /* Element */ // use the node name: <directive> addDirective(directives, directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective); // iterate over the attributes for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes, j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { var attrStartName = false; var attrEndName = false; attr = nAttrs[j]; name = attr.name; value = trim(attr.value); // support ngAttr attribute binding ngAttrName = directiveNormalize(name); if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) { name = name.replace(PREFIX_REGEXP, '') .substr(8).replace(/_(.)/g, function(match, letter) { return letter.toUpperCase(); }); } var directiveNName = ngAttrName.replace(/(Start|End)$/, ''); if (directiveIsMultiElement(directiveNName)) { if (ngAttrName === directiveNName + 'Start') { attrStartName = name; attrEndName = name.substr(0, name.length - 5) + 'end'; name = name.substr(0, name.length - 6); } } nName = directiveNormalize(name.toLowerCase()); attrsMap[nName] = name; if (isNgAttr || !attrs.hasOwnProperty(nName)) { attrs[nName] = value; if (getBooleanAttrName(node, nName)) { attrs[nName] = true; // presence means true } } addAttrInterpolateDirective(node, directives, value, nName, isNgAttr); addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName, attrEndName); } // use class as directive className = node.className; if (isObject(className)) { // Maybe SVGAnimatedString className = className.animVal; } if (isString(className) && className !== '') { while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) { nName = directiveNormalize(match[2]); if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) { attrs[nName] = trim(match[3]); } className = className.substr(match.index + match[0].length); } } break; case NODE_TYPE_TEXT: /* Text Node */ addTextInterpolateDirective(directives, node.nodeValue); break; case NODE_TYPE_COMMENT: /* Comment */ try { match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); if (match) { nName = directiveNormalize(match[1]); if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) { attrs[nName] = trim(match[2]); } } } catch (e) { // turns out that under some circumstances IE9 throws errors when one attempts to read // comment's node value. // Just ignore it and continue. (Can't seem to reproduce in test case.) } break; } directives.sort(byPriority); return directives; } /** * Given a node with an directive-start it collects all of the siblings until it finds * directive-end. * @param node * @param attrStart * @param attrEnd * @returns {*} */ function groupScan(node, attrStart, attrEnd) { var nodes = []; var depth = 0; if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) { do { if (!node) { throw $compileMinErr('uterdir', "Unterminated attribute, found '{0}' but no matching '{1}' found.", attrStart, attrEnd); } if (node.nodeType == NODE_TYPE_ELEMENT) { if (node.hasAttribute(attrStart)) depth++; if (node.hasAttribute(attrEnd)) depth--; } nodes.push(node); node = node.nextSibling; } while (depth > 0); } else { nodes.push(node); } return jqLite(nodes); } /** * Wrapper for linking function which converts normal linking function into a grouped * linking function. * @param linkFn * @param attrStart * @param attrEnd * @returns {Function} */ function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) { return function(scope, element, attrs, controllers, transcludeFn) { element = groupScan(element[0], attrStart, attrEnd); return linkFn(scope, element, attrs, controllers, transcludeFn); }; } /** * Once the directives have been collected, their compile functions are executed. This method * is responsible for inlining directive templates as well as terminating the application * of the directives if the terminal directive has been reached. * * @param {Array} directives Array of collected directives to execute their compile function. * this needs to be pre-sorted by priority order. * @param {Node} compileNode The raw DOM node to apply the compile functions to * @param {Object} templateAttrs The shared attribute function * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the * scope argument is auto-generated to the new * child of the transcluded parent scope. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this * argument has the root jqLite array so that we can replace nodes * on it. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when * compiling the transclusion. * @param {Array.<Function>} preLinkFns * @param {Array.<Function>} postLinkFns * @param {Object} previousCompileContext Context used for previous compilation of the current * node * @returns {Function} linkFn */ function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, jqCollection, originalReplaceDirective, preLinkFns, postLinkFns, previousCompileContext) { previousCompileContext = previousCompileContext || {}; var terminalPriority = -Number.MAX_VALUE, newScopeDirective, controllerDirectives = previousCompileContext.controllerDirectives, controllers, newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective, templateDirective = previousCompileContext.templateDirective, nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective, hasTranscludeDirective = false, hasTemplate = false, hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective, $compileNode = templateAttrs.$$element = jqLite(compileNode), directive, directiveName, $template, replaceDirective = originalReplaceDirective, childTranscludeFn = transcludeFn, linkFn, directiveValue; // executes all directives on the current element for (var i = 0, ii = directives.length; i < ii; i++) { directive = directives[i]; var attrStart = directive.$$start; var attrEnd = directive.$$end; // collect multiblock sections if (attrStart) { $compileNode = groupScan(compileNode, attrStart, attrEnd); } $template = undefined; if (terminalPriority > directive.priority) { break; // prevent further processing of directives } if (directiveValue = directive.scope) { // skip the check for directives with async templates, we'll check the derived sync // directive when the template arrives if (!directive.templateUrl) { if (isObject(directiveValue)) { // This directive is trying to add an isolated scope. // Check that there is no scope of any kind already assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective, directive, $compileNode); newIsolateScopeDirective = directive; } else { // This directive is trying to add a child scope. // Check that there is no isolated scope already assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive, $compileNode); } } newScopeDirective = newScopeDirective || directive; } directiveName = directive.name; if (!directive.templateUrl && directive.controller) { directiveValue = directive.controller; controllerDirectives = controllerDirectives || {}; assertNoDuplicate("'" + directiveName + "' controller", controllerDirectives[directiveName], directive, $compileNode); controllerDirectives[directiveName] = directive; } if (directiveValue = directive.transclude) { hasTranscludeDirective = true; // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion. // This option should only be used by directives that know how to safely handle element transclusion, // where the transcluded nodes are added or replaced after linking. if (!directive.$$tlb) { assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode); nonTlbTranscludeDirective = directive; } if (directiveValue == 'element') { hasElementTranscludeDirective = true; terminalPriority = directive.priority; $template = $compileNode; $compileNode = templateAttrs.$$element = jqLite(document.createComment(' ' + directiveName + ': ' + templateAttrs[directiveName] + ' ')); compileNode = $compileNode[0]; replaceWith(jqCollection, sliceArgs($template), compileNode); childTranscludeFn = compile($template, transcludeFn, terminalPriority, replaceDirective && replaceDirective.name, { // Don't pass in: // - controllerDirectives - otherwise we'll create duplicates controllers // - newIsolateScopeDirective or templateDirective - combining templates with // element transclusion doesn't make sense. // // We need only nonTlbTranscludeDirective so that we prevent putting transclusion // on the same element more than once. nonTlbTranscludeDirective: nonTlbTranscludeDirective }); } else { $template = jqLite(jqLiteClone(compileNode)).contents(); $compileNode.empty(); // clear contents childTranscludeFn = compile($template, transcludeFn); } } if (directive.template) { hasTemplate = true; assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; directiveValue = (isFunction(directive.template)) ? directive.template($compileNode, templateAttrs) : directive.template; directiveValue = denormalizeTemplate(directiveValue); if (directive.replace) { replaceDirective = directive; if (jqLiteIsTextNode(directiveValue)) { $template = []; } else { $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue))); } compileNode = $template[0]; if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) { throw $compileMinErr('tplrt', "Template for directive '{0}' must have exactly one root element. {1}", directiveName, ''); } replaceWith(jqCollection, $compileNode, compileNode); var newTemplateAttrs = {$attr: {}}; // combine directives from the original node and from the template: // - take the array of directives for this element // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed) // - collect directives from the template and sort them by priority // - combine directives as: processed + template + unprocessed var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs); var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1)); if (newIsolateScopeDirective) { markDirectivesAsIsolate(templateDirectives); } directives = directives.concat(templateDirectives).concat(unprocessedDirectives); mergeTemplateAttributes(templateAttrs, newTemplateAttrs); ii = directives.length; } else { $compileNode.html(directiveValue); } } if (directive.templateUrl) { hasTemplate = true; assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; if (directive.replace) { replaceDirective = directive; } nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode, templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, { controllerDirectives: controllerDirectives, newIsolateScopeDirective: newIsolateScopeDirective, templateDirective: templateDirective, nonTlbTranscludeDirective: nonTlbTranscludeDirective }); ii = directives.length; } else if (directive.compile) { try { linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); if (isFunction(linkFn)) { addLinkFns(null, linkFn, attrStart, attrEnd); } else if (linkFn) { addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd); } } catch (e) { $exceptionHandler(e, startingTag($compileNode)); } } if (directive.terminal) { nodeLinkFn.terminal = true; terminalPriority = Math.max(terminalPriority, directive.priority); } } nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true; nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective; nodeLinkFn.elementTranscludeOnThisElement = hasElementTranscludeDirective; nodeLinkFn.templateOnThisElement = hasTemplate; nodeLinkFn.transclude = childTranscludeFn; previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective; // might be normal or delayed nodeLinkFn depending on if templateUrl is present return nodeLinkFn; //////////////////// function addLinkFns(pre, post, attrStart, attrEnd) { if (pre) { if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd); pre.require = directive.require; pre.directiveName = directiveName; if (newIsolateScopeDirective === directive || directive.$$isolateScope) { pre = cloneAndAnnotateFn(pre, {isolateScope: true}); } preLinkFns.push(pre); } if (post) { if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd); post.require = directive.require; post.directiveName = directiveName; if (newIsolateScopeDirective === directive || directive.$$isolateScope) { post = cloneAndAnnotateFn(post, {isolateScope: true}); } postLinkFns.push(post); } } function getControllers(directiveName, require, $element, elementControllers) { var value, retrievalMethod = 'data', optional = false; var $searchElement = $element; var match; if (isString(require)) { match = require.match(REQUIRE_PREFIX_REGEXP); require = require.substring(match[0].length); if (match[3]) { if (match[1]) match[3] = null; else match[1] = match[3]; } if (match[1] === '^') { retrievalMethod = 'inheritedData'; } else if (match[1] === '^^') { retrievalMethod = 'inheritedData'; $searchElement = $element.parent(); } if (match[2] === '?') { optional = true; } value = null; if (elementControllers && retrievalMethod === 'data') { if (value = elementControllers[require]) { value = value.instance; } } value = value || $searchElement[retrievalMethod]('$' + require + 'Controller'); if (!value && !optional) { throw $compileMinErr('ctreq', "Controller '{0}', required by directive '{1}', can't be found!", require, directiveName); } return value || null; } else if (isArray(require)) { value = []; forEach(require, function(require) { value.push(getControllers(directiveName, require, $element, elementControllers)); }); } return value; } function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element, attrs; if (compileNode === linkNode) { attrs = templateAttrs; $element = templateAttrs.$$element; } else { $element = jqLite(linkNode); attrs = new Attributes($element, templateAttrs); } if (newIsolateScopeDirective) { isolateScope = scope.$new(true); } if (boundTranscludeFn) { // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn` // is later passed as `parentBoundTranscludeFn` to `publicLinkFn` transcludeFn = controllersBoundTransclude; transcludeFn.$$boundTransclude = boundTranscludeFn; } if (controllerDirectives) { // TODO: merge `controllers` and `elementControllers` into single object. controllers = {}; elementControllers = {}; forEach(controllerDirectives, function(directive) { var locals = { $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope, $element: $element, $attrs: attrs, $transclude: transcludeFn }, controllerInstance; controller = directive.controller; if (controller == '@') { controller = attrs[directive.name]; } controllerInstance = $controller(controller, locals, true, directive.controllerAs); // For directives with element transclusion the element is a comment, // but jQuery .data doesn't support attaching data to comment nodes as it's hard to // clean up (http://bugs.jquery.com/ticket/8335). // Instead, we save the controllers for the element in a local hash and attach to .data // later, once we have the actual element. elementControllers[directive.name] = controllerInstance; if (!hasElementTranscludeDirective) { $element.data('$' + directive.name + 'Controller', controllerInstance.instance); } controllers[directive.name] = controllerInstance; }); } if (newIsolateScopeDirective) { compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective || templateDirective === newIsolateScopeDirective.$$originalDirective))); compile.$$addScopeClass($element, true); var isolateScopeController = controllers && controllers[newIsolateScopeDirective.name]; var isolateBindingContext = isolateScope; if (isolateScopeController && isolateScopeController.identifier && newIsolateScopeDirective.bindToController === true) { isolateBindingContext = isolateScopeController.instance; } forEach(isolateScope.$$isolateBindings = newIsolateScopeDirective.$$isolateBindings, function(definition, scopeName) { var attrName = definition.attrName, optional = definition.optional, mode = definition.mode, // @, =, or & lastValue, parentGet, parentSet, compare; switch (mode) { case '@': attrs.$observe(attrName, function(value) { isolateBindingContext[scopeName] = value; }); attrs.$$observers[attrName].$$scope = scope; if (attrs[attrName]) { // If the attribute has been provided then we trigger an interpolation to ensure // the value is there for use in the link fn isolateBindingContext[scopeName] = $interpolate(attrs[attrName])(scope); } break; case '=': if (optional && !attrs[attrName]) { return; } parentGet = $parse(attrs[attrName]); if (parentGet.literal) { compare = equals; } else { compare = function(a, b) { return a === b || (a !== a && b !== b); }; } parentSet = parentGet.assign || function() { // reset the change, or we will throw this exception on every $digest lastValue = isolateBindingContext[scopeName] = parentGet(scope); throw $compileMinErr('nonassign', "Expression '{0}' used with directive '{1}' is non-assignable!", attrs[attrName], newIsolateScopeDirective.name); }; lastValue = isolateBindingContext[scopeName] = parentGet(scope); var parentValueWatch = function parentValueWatch(parentValue) { if (!compare(parentValue, isolateBindingContext[scopeName])) { // we are out of sync and need to copy if (!compare(parentValue, lastValue)) { // parent changed and it has precedence isolateBindingContext[scopeName] = parentValue; } else { // if the parent can be assigned then do so parentSet(scope, parentValue = isolateBindingContext[scopeName]); } } return lastValue = parentValue; }; parentValueWatch.$stateful = true; var unwatch; if (definition.collection) { unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch); } else { unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal); } isolateScope.$on('$destroy', unwatch); break; case '&': parentGet = $parse(attrs[attrName]); isolateBindingContext[scopeName] = function(locals) { return parentGet(scope, locals); }; break; } }); } if (controllers) { forEach(controllers, function(controller) { controller(); }); controllers = null; } // PRELINKING for (i = 0, ii = preLinkFns.length; i < ii; i++) { linkFn = preLinkFns[i]; invokeLinkFn(linkFn, linkFn.isolateScope ? isolateScope : scope, $element, attrs, linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn ); } // RECURSION // We only pass the isolate scope, if the isolate directive has a template, // otherwise the child elements do not belong to the isolate directive. var scopeToChild = scope; if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) { scopeToChild = isolateScope; } childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn); // POSTLINKING for (i = postLinkFns.length - 1; i >= 0; i--) { linkFn = postLinkFns[i]; invokeLinkFn(linkFn, linkFn.isolateScope ? isolateScope : scope, $element, attrs, linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn ); } // This is the function that is injected as `$transclude`. // Note: all arguments are optional! function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) { var transcludeControllers; // No scope passed in: if (!isScope(scope)) { futureParentElement = cloneAttachFn; cloneAttachFn = scope; scope = undefined; } if (hasElementTranscludeDirective) { transcludeControllers = elementControllers; } if (!futureParentElement) { futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element; } return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild); } } } function markDirectivesAsIsolate(directives) { // mark all directives as needing isolate scope. for (var j = 0, jj = directives.length; j < jj; j++) { directives[j] = inherit(directives[j], {$$isolateScope: true}); } } /** * looks up the directive and decorates it with exception handling and proper parameters. We * call this the boundDirective. * * @param {string} name name of the directive to look up. * @param {string} location The directive must be found in specific format. * String containing any of theses characters: * * * `E`: element name * * `A': attribute * * `C`: class * * `M`: comment * @returns {boolean} true if directive was added. */ function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName, endAttrName) { if (name === ignoreDirective) return null; var match = null; if (hasDirectives.hasOwnProperty(name)) { for (var directive, directives = $injector.get(name + Suffix), i = 0, ii = directives.length; i < ii; i++) { try { directive = directives[i]; if ((maxPriority === undefined || maxPriority > directive.priority) && directive.restrict.indexOf(location) != -1) { if (startAttrName) { directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName}); } tDirectives.push(directive); match = directive; } } catch (e) { $exceptionHandler(e); } } } return match; } /** * looks up the directive and returns true if it is a multi-element directive, * and therefore requires DOM nodes between -start and -end markers to be grouped * together. * * @param {string} name name of the directive to look up. * @returns true if directive was registered as multi-element. */ function directiveIsMultiElement(name) { if (hasDirectives.hasOwnProperty(name)) { for (var directive, directives = $injector.get(name + Suffix), i = 0, ii = directives.length; i < ii; i++) { directive = directives[i]; if (directive.multiElement) { return true; } } } return false; } /** * When the element is replaced with HTML template then the new attributes * on the template need to be merged with the existing attributes in the DOM. * The desired effect is to have both of the attributes present. * * @param {object} dst destination attributes (original DOM) * @param {object} src source attributes (from the directive template) */ function mergeTemplateAttributes(dst, src) { var srcAttr = src.$attr, dstAttr = dst.$attr, $element = dst.$$element; // reapply the old attributes to the new element forEach(dst, function(value, key) { if (key.charAt(0) != '$') { if (src[key] && src[key] !== value) { value += (key === 'style' ? ';' : ' ') + src[key]; } dst.$set(key, value, true, srcAttr[key]); } }); // copy the new attributes on the old attrs object forEach(src, function(value, key) { if (key == 'class') { safeAddClass($element, value); dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value; } else if (key == 'style') { $element.attr('style', $element.attr('style') + ';' + value); dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value; // `dst` will never contain hasOwnProperty as DOM parser won't let it. // You will get an "InvalidCharacterError: DOM Exception 5" error if you // have an attribute like "has-own-property" or "data-has-own-property", etc. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { dst[key] = value; dstAttr[key] = srcAttr[key]; } }); } function compileTemplateUrl(directives, $compileNode, tAttrs, $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) { var linkQueue = [], afterTemplateNodeLinkFn, afterTemplateChildLinkFn, beforeTemplateCompileNode = $compileNode[0], origAsyncDirective = directives.shift(), // The fact that we have to copy and patch the directive seems wrong! derivedSyncDirective = extend({}, origAsyncDirective, { templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective }), templateUrl = (isFunction(origAsyncDirective.templateUrl)) ? origAsyncDirective.templateUrl($compileNode, tAttrs) : origAsyncDirective.templateUrl, templateNamespace = origAsyncDirective.templateNamespace; $compileNode.empty(); $templateRequest($sce.getTrustedResourceUrl(templateUrl)) .then(function(content) { var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn; content = denormalizeTemplate(content); if (origAsyncDirective.replace) { if (jqLiteIsTextNode(content)) { $template = []; } else { $template = removeComments(wrapTemplate(templateNamespace, trim(content))); } compileNode = $template[0]; if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) { throw $compileMinErr('tplrt', "Template for directive '{0}' must have exactly one root element. {1}", origAsyncDirective.name, templateUrl); } tempTemplateAttrs = {$attr: {}}; replaceWith($rootElement, $compileNode, compileNode); var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs); if (isObject(origAsyncDirective.scope)) { markDirectivesAsIsolate(templateDirectives); } directives = templateDirectives.concat(directives); mergeTemplateAttributes(tAttrs, tempTemplateAttrs); } else { compileNode = beforeTemplateCompileNode; $compileNode.html(content); } directives.unshift(derivedSyncDirective); afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns, previousCompileContext); forEach($rootElement, function(node, i) { if (node == compileNode) { $rootElement[i] = $compileNode[0]; } }); afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn); while (linkQueue.length) { var scope = linkQueue.shift(), beforeTemplateLinkNode = linkQueue.shift(), linkRootElement = linkQueue.shift(), boundTranscludeFn = linkQueue.shift(), linkNode = $compileNode[0]; if (scope.$$destroyed) continue; if (beforeTemplateLinkNode !== beforeTemplateCompileNode) { var oldClasses = beforeTemplateLinkNode.className; if (!(previousCompileContext.hasElementTranscludeDirective && origAsyncDirective.replace)) { // it was cloned therefore we have to clone as well. linkNode = jqLiteClone(compileNode); } replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode); // Copy in CSS classes from original node safeAddClass(jqLite(linkNode), oldClasses); } if (afterTemplateNodeLinkFn.transcludeOnThisElement) { childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn); } else { childBoundTranscludeFn = boundTranscludeFn; } afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, childBoundTranscludeFn); } linkQueue = null; }); return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) { var childBoundTranscludeFn = boundTranscludeFn; if (scope.$$destroyed) return; if (linkQueue) { linkQueue.push(scope, node, rootElement, childBoundTranscludeFn); } else { if (afterTemplateNodeLinkFn.transcludeOnThisElement) { childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn); } afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn); } }; } /** * Sorting function for bound directives. */ function byPriority(a, b) { var diff = b.priority - a.priority; if (diff !== 0) return diff; if (a.name !== b.name) return (a.name < b.name) ? -1 : 1; return a.index - b.index; } function assertNoDuplicate(what, previousDirective, directive, element) { if (previousDirective) { throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}', previousDirective.name, directive.name, what, startingTag(element)); } } function addTextInterpolateDirective(directives, text) { var interpolateFn = $interpolate(text, true); if (interpolateFn) { directives.push({ priority: 0, compile: function textInterpolateCompileFn(templateNode) { var templateNodeParent = templateNode.parent(), hasCompileParent = !!templateNodeParent.length; // When transcluding a template that has bindings in the root // we don't have a parent and thus need to add the class during linking fn. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent); return function textInterpolateLinkFn(scope, node) { var parent = node.parent(); if (!hasCompileParent) compile.$$addBindingClass(parent); compile.$$addBindingInfo(parent, interpolateFn.expressions); scope.$watch(interpolateFn, function interpolateFnWatchAction(value) { node[0].nodeValue = value; }); }; } }); } } function wrapTemplate(type, template) { type = lowercase(type || 'html'); switch (type) { case 'svg': case 'math': var wrapper = document.createElement('div'); wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>'; return wrapper.childNodes[0].childNodes; default: return template; } } function getTrustedContext(node, attrNormalizedName) { if (attrNormalizedName == "srcdoc") { return $sce.HTML; } var tag = nodeName_(node); // maction[xlink:href] can source SVG. It's not limited to <maction>. if (attrNormalizedName == "xlinkHref" || (tag == "form" && attrNormalizedName == "action") || (tag != "img" && (attrNormalizedName == "src" || attrNormalizedName == "ngSrc"))) { return $sce.RESOURCE_URL; } } function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) { var trustedContext = getTrustedContext(node, name); allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing; var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing); // no interpolation found -> ignore if (!interpolateFn) return; if (name === "multiple" && nodeName_(node) === "select") { throw $compileMinErr("selmulti", "Binding to the 'multiple' attribute is not supported. Element: {0}", startingTag(node)); } directives.push({ priority: 100, compile: function() { return { pre: function attrInterpolatePreLinkFn(scope, element, attr) { var $$observers = (attr.$$observers || (attr.$$observers = {})); if (EVENT_HANDLER_ATTR_REGEXP.test(name)) { throw $compileMinErr('nodomevents', "Interpolations for HTML DOM event attributes are disallowed. Please use the " + "ng- versions (such as ng-click instead of onclick) instead."); } // If the attribute has changed since last $interpolate()ed var newValue = attr[name]; if (newValue !== value) { // we need to interpolate again since the attribute value has been updated // (e.g. by another directive's compile function) // ensure unset/empty values make interpolateFn falsy interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing); value = newValue; } // if attribute was updated so that there is no interpolation going on we don't want to // register any observers if (!interpolateFn) return; // initialize attr object so that it's ready in case we need the value for isolate // scope initialization, otherwise the value would not be available from isolate // directive's linking fn during linking phase attr[name] = interpolateFn(scope); ($$observers[name] || ($$observers[name] = [])).$$inter = true; (attr.$$observers && attr.$$observers[name].$$scope || scope). $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) { //special case for class attribute addition + removal //so that class changes can tap into the animation //hooks provided by the $animate service. Be sure to //skip animations when the first digest occurs (when //both the new and the old values are the same) since //the CSS classes are the non-interpolated values if (name === 'class' && newValue != oldValue) { attr.$updateClass(newValue, oldValue); } else { attr.$set(name, newValue); } }); } }; } }); } /** * This is a special jqLite.replaceWith, which can replace items which * have no parents, provided that the containing jqLite collection is provided. * * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes * in the root of the tree. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep * the shell, but replace its DOM node reference. * @param {Node} newNode The new DOM node. */ function replaceWith($rootElement, elementsToRemove, newNode) { var firstElementToRemove = elementsToRemove[0], removeCount = elementsToRemove.length, parent = firstElementToRemove.parentNode, i, ii; if ($rootElement) { for (i = 0, ii = $rootElement.length; i < ii; i++) { if ($rootElement[i] == firstElementToRemove) { $rootElement[i++] = newNode; for (var j = i, j2 = j + removeCount - 1, jj = $rootElement.length; j < jj; j++, j2++) { if (j2 < jj) { $rootElement[j] = $rootElement[j2]; } else { delete $rootElement[j]; } } $rootElement.length -= removeCount - 1; // If the replaced element is also the jQuery .context then replace it // .context is a deprecated jQuery api, so we should set it only when jQuery set it // http://api.jquery.com/context/ if ($rootElement.context === firstElementToRemove) { $rootElement.context = newNode; } break; } } } if (parent) { parent.replaceChild(newNode, firstElementToRemove); } // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it? var fragment = document.createDocumentFragment(); fragment.appendChild(firstElementToRemove); // Copy over user data (that includes Angular's $scope etc.). Don't copy private // data here because there's no public interface in jQuery to do that and copying over // event listeners (which is the main use of private data) wouldn't work anyway. jqLite(newNode).data(jqLite(firstElementToRemove).data()); // Remove data of the replaced element. We cannot just call .remove() // on the element it since that would deallocate scope that is needed // for the new node. Instead, remove the data "manually". if (!jQuery) { delete jqLite.cache[firstElementToRemove[jqLite.expando]]; } else { // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after // the replaced element. The cleanData version monkey-patched by Angular would cause // the scope to be trashed and we do need the very same scope to work with the new // element. However, we cannot just cache the non-patched version and use it here as // that would break if another library patches the method after Angular does (one // example is jQuery UI). Instead, set a flag indicating scope destroying should be // skipped this one time. skipDestroyOnNextJQueryCleanData = true; jQuery.cleanData([firstElementToRemove]); } for (var k = 1, kk = elementsToRemove.length; k < kk; k++) { var element = elementsToRemove[k]; jqLite(element).remove(); // must do this way to clean up expando fragment.appendChild(element); delete elementsToRemove[k]; } elementsToRemove[0] = newNode; elementsToRemove.length = 1; } function cloneAndAnnotateFn(fn, annotation) { return extend(function() { return fn.apply(null, arguments); }, fn, annotation); } function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) { try { linkFn(scope, $element, attrs, controllers, transcludeFn); } catch (e) { $exceptionHandler(e, startingTag($element)); } } }]; } var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i; /** * Converts all accepted directives format into proper directive name. * @param name Name to normalize */ function directiveNormalize(name) { return camelCase(name.replace(PREFIX_REGEXP, '')); } /** * @ngdoc type * @name $compile.directive.Attributes * * @description * A shared object between directive compile / linking functions which contains normalized DOM * element attributes. The values reflect current binding state `{{ }}`. The normalization is * needed since all of these are treated as equivalent in Angular: * * ``` * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a"> * ``` */ /** * @ngdoc property * @name $compile.directive.Attributes#$attr * * @description * A map of DOM element attribute names to the normalized name. This is * needed to do reverse lookup from normalized name back to actual name. */ /** * @ngdoc method * @name $compile.directive.Attributes#$set * @kind function * * @description * Set DOM element attribute value. * * * @param {string} name Normalized element attribute name of the property to modify. The name is * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr} * property to the original name. * @param {string} value Value to set the attribute to. The value can be an interpolated string. */ /** * Closure compiler type information */ function nodesetLinkingFn( /* angular.Scope */ scope, /* NodeList */ nodeList, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn ) {} function directiveLinkingFn( /* nodesetLinkingFn */ nodesetLinkingFn, /* angular.Scope */ scope, /* Node */ node, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn ) {} function tokenDifference(str1, str2) { var values = '', tokens1 = str1.split(/\s+/), tokens2 = str2.split(/\s+/); outer: for (var i = 0; i < tokens1.length; i++) { var token = tokens1[i]; for (var j = 0; j < tokens2.length; j++) { if (token == tokens2[j]) continue outer; } values += (values.length > 0 ? ' ' : '') + token; } return values; } function removeComments(jqNodes) { jqNodes = jqLite(jqNodes); var i = jqNodes.length; if (i <= 1) { return jqNodes; } while (i--) { var node = jqNodes[i]; if (node.nodeType === NODE_TYPE_COMMENT) { splice.call(jqNodes, i, 1); } } return jqNodes; } /** * @ngdoc provider * @name $controllerProvider * @description * The {@link ng.$controller $controller service} is used by Angular to create new * controllers. * * This provider allows controller registration via the * {@link ng.$controllerProvider#register register} method. */ function $ControllerProvider() { var controllers = {}, globals = false, CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/; /** * @ngdoc method * @name $controllerProvider#register * @param {string|Object} name Controller name, or an object map of controllers where the keys are * the names and the values are the constructors. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI * annotations in the array notation). */ this.register = function(name, constructor) { assertNotHasOwnProperty(name, 'controller'); if (isObject(name)) { extend(controllers, name); } else { controllers[name] = constructor; } }; /** * @ngdoc method * @name $controllerProvider#allowGlobals * @description If called, allows `$controller` to find controller constructors on `window` */ this.allowGlobals = function() { globals = true; }; this.$get = ['$injector', '$window', function($injector, $window) { /** * @ngdoc service * @name $controller * @requires $injector * * @param {Function|string} constructor If called with a function then it's considered to be the * controller constructor function. Otherwise it's considered to be a string which is used * to retrieve the controller constructor using the following steps: * * * check if a controller with given name is registered via `$controllerProvider` * * check if evaluating the string on the current scope returns a constructor * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global * `window` object (not recommended) * * The string can use the `controller as property` syntax, where the controller instance is published * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this * to work correctly. * * @param {Object} locals Injection locals for Controller. * @return {Object} Instance of given controller. * * @description * `$controller` service is responsible for instantiating controllers. * * It's just a simple call to {@link auto.$injector $injector}, but extracted into * a service, so that one can override this service with [BC version](https://gist.github.com/1649788). */ return function(expression, locals, later, ident) { // PRIVATE API: // param `later` --- indicates that the controller's constructor is invoked at a later time. // If true, $controller will allocate the object with the correct // prototype chain, but will not invoke the controller until a returned // callback is invoked. // param `ident` --- An optional label which overrides the label parsed from the controller // expression, if any. var instance, match, constructor, identifier; later = later === true; if (ident && isString(ident)) { identifier = ident; } if (isString(expression)) { match = expression.match(CNTRL_REG), constructor = match[1], identifier = identifier || match[3]; expression = controllers.hasOwnProperty(constructor) ? controllers[constructor] : getter(locals.$scope, constructor, true) || (globals ? getter($window, constructor, true) : undefined); assertArgFn(expression, constructor, true); } if (later) { // Instantiate controller later: // This machinery is used to create an instance of the object before calling the // controller's constructor itself. // // This allows properties to be added to the controller before the constructor is // invoked. Primarily, this is used for isolate scope bindings in $compile. // // This feature is not intended for use by applications, and is thus not documented // publicly. // Object creation: http://jsperf.com/create-constructor/2 var controllerPrototype = (isArray(expression) ? expression[expression.length - 1] : expression).prototype; instance = Object.create(controllerPrototype || null); if (identifier) { addIdentifier(locals, identifier, instance, constructor || expression.name); } return extend(function() { $injector.invoke(expression, instance, locals, constructor); return instance; }, { instance: instance, identifier: identifier }); } instance = $injector.instantiate(expression, locals, constructor); if (identifier) { addIdentifier(locals, identifier, instance, constructor || expression.name); } return instance; }; function addIdentifier(locals, identifier, instance, name) { if (!(locals && isObject(locals.$scope))) { throw minErr('$controller')('noscp', "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.", name, identifier); } locals.$scope[identifier] = instance; } }]; } /** * @ngdoc service * @name $document * @requires $window * * @description * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object. * * @example <example module="documentExample"> <file name="index.html"> <div ng-controller="ExampleController"> <p>$document title: <b ng-bind="title"></b></p> <p>window.document title: <b ng-bind="windowTitle"></b></p> </div> </file> <file name="script.js"> angular.module('documentExample', []) .controller('ExampleController', ['$scope', '$document', function($scope, $document) { $scope.title = $document[0].title; $scope.windowTitle = angular.element(window.document)[0].title; }]); </file> </example> */ function $DocumentProvider() { this.$get = ['$window', function(window) { return jqLite(window.document); }]; } /** * @ngdoc service * @name $exceptionHandler * @requires ng.$log * * @description * Any uncaught exception in angular expressions is delegated to this service. * The default implementation simply delegates to `$log.error` which logs it into * the browser console. * * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing. * * ## Example: * * ```js * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() { * return function(exception, cause) { * exception.message += ' (caused by "' + cause + '")'; * throw exception; * }; * }); * ``` * * This example will override the normal action of `$exceptionHandler`, to make angular * exceptions fail hard when they happen, instead of just logging to the console. * * <hr /> * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind` * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler} * (unless executed during a digest). * * If you wish, you can manually delegate exceptions, e.g. * `try { ... } catch(e) { $exceptionHandler(e); }` * * @param {Error} exception Exception associated with the error. * @param {string=} cause optional information about the context in which * the error was thrown. * */ function $ExceptionHandlerProvider() { this.$get = ['$log', function($log) { return function(exception, cause) { $log.error.apply($log, arguments); }; }]; } var APPLICATION_JSON = 'application/json'; var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'}; var JSON_START = /^\[|^\{(?!\{)/; var JSON_ENDS = { '[': /]$/, '{': /}$/ }; var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/; function defaultHttpResponseTransform(data, headers) { if (isString(data)) { // Strip json vulnerability protection prefix and trim whitespace var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim(); if (tempData) { var contentType = headers('Content-Type'); if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) { data = fromJson(tempData); } } } return data; } function isJsonLike(str) { var jsonStart = str.match(JSON_START); return jsonStart && JSON_ENDS[jsonStart[0]].test(str); } /** * Parse headers into key value object * * @param {string} headers Raw headers as a string * @returns {Object} Parsed headers as key value object */ function parseHeaders(headers) { var parsed = createMap(), key, val, i; if (!headers) return parsed; forEach(headers.split('\n'), function(line) { i = line.indexOf(':'); key = lowercase(trim(line.substr(0, i))); val = trim(line.substr(i + 1)); if (key) { parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } }); return parsed; } /** * Returns a function that provides access to parsed headers. * * Headers are lazy parsed when first requested. * @see parseHeaders * * @param {(string|Object)} headers Headers to provide access to. * @returns {function(string=)} Returns a getter function which if called with: * * - if called with single an argument returns a single header value or null * - if called with no arguments returns an object containing all headers. */ function headersGetter(headers) { var headersObj = isObject(headers) ? headers : undefined; return function(name) { if (!headersObj) headersObj = parseHeaders(headers); if (name) { var value = headersObj[lowercase(name)]; if (value === void 0) { value = null; } return value; } return headersObj; }; } /** * Chain all given functions * * This function is used for both request and response transforming * * @param {*} data Data to transform. * @param {function(string=)} headers HTTP headers getter fn. * @param {number} status HTTP status code of the response. * @param {(Function|Array.<Function>)} fns Function or an array of functions. * @returns {*} Transformed data. */ function transformData(data, headers, status, fns) { if (isFunction(fns)) return fns(data, headers, status); forEach(fns, function(fn) { data = fn(data, headers, status); }); return data; } function isSuccess(status) { return 200 <= status && status < 300; } /** * @ngdoc provider * @name $httpProvider * @description * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service. * */ function $HttpProvider() { /** * @ngdoc property * @name $httpProvider#defaults * @description * * Object containing default values for all {@link ng.$http $http} requests. * * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`} * that will provide the cache for all requests who set their `cache` property to `true`. * If you set the `default.cache = false` then only requests that specify their own custom * cache object will be cached. See {@link $http#caching $http Caching} for more information. * * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token. * Defaults value is `'XSRF-TOKEN'`. * * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the * XSRF token. Defaults value is `'X-XSRF-TOKEN'`. * * - **`defaults.headers`** - {Object} - Default headers for all $http requests. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on * setting default headers. * - **`defaults.headers.common`** * - **`defaults.headers.post`** * - **`defaults.headers.put`** * - **`defaults.headers.patch`** * **/ var defaults = this.defaults = { // transform incoming response data transformResponse: [defaultHttpResponseTransform], // transform outgoing request data transformRequest: [function(d) { return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d; }], // default headers headers: { common: { 'Accept': 'application/json, text/plain, */*' }, post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON) }, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN' }; var useApplyAsync = false; /** * @ngdoc method * @name $httpProvider#useApplyAsync * @description * * Configure $http service to combine processing of multiple http responses received at around * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in * significant performance improvement for bigger applications that make many HTTP requests * concurrently (common during application bootstrap). * * Defaults to false. If no value is specifed, returns the current configured value. * * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window * to load and share the same digest cycle. * * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining. * otherwise, returns the current configured value. **/ this.useApplyAsync = function(value) { if (isDefined(value)) { useApplyAsync = !!value; return this; } return useApplyAsync; }; /** * @ngdoc property * @name $httpProvider#interceptors * @description * * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http} * pre-processing of request or postprocessing of responses. * * These service factories are ordered by request, i.e. they are applied in the same order as the * array, on request, but reverse order, on response. * * {@link ng.$http#interceptors Interceptors detailed info} **/ var interceptorFactories = this.interceptors = []; this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) { var defaultCache = $cacheFactory('$http'); /** * Interceptors stored in reverse order. Inner interceptors before outer interceptors. * The reversal is needed so that we can build up the interception chain around the * server request. */ var reversedInterceptors = []; forEach(interceptorFactories, function(interceptorFactory) { reversedInterceptors.unshift(isString(interceptorFactory) ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory)); }); /** * @ngdoc service * @kind function * @name $http * @requires ng.$httpBackend * @requires $cacheFactory * @requires $rootScope * @requires $q * @requires $injector * * @description * The `$http` service is a core Angular service that facilitates communication with the remote * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest) * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP). * * For unit testing applications that use `$http` service, see * {@link ngMock.$httpBackend $httpBackend mock}. * * For a higher level of abstraction, please check out the {@link ngResource.$resource * $resource} service. * * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage * it is important to familiarize yourself with these APIs and the guarantees they provide. * * * ## General usage * The `$http` service is a function which takes a single argument — a configuration object — * that is used to generate an HTTP request and returns a {@link ng.$q promise} * with two $http specific methods: `success` and `error`. * * ```js * // Simple GET request example : * $http.get('/someUrl'). * success(function(data, status, headers, config) { * // this callback will be called asynchronously * // when the response is available * }). * error(function(data, status, headers, config) { * // called asynchronously if an error occurs * // or server returns response with an error status. * }); * ``` * * ```js * // Simple POST request example (passing data) : * $http.post('/someUrl', {msg:'hello word!'}). * success(function(data, status, headers, config) { * // this callback will be called asynchronously * // when the response is available * }). * error(function(data, status, headers, config) { * // called asynchronously if an error occurs * // or server returns response with an error status. * }); * ``` * * * Since the returned value of calling the $http function is a `promise`, you can also use * the `then` method to register callbacks, and these callbacks will receive a single argument – * an object representing the response. See the API signature and type info below for more * details. * * A response status code between 200 and 299 is considered a success status and * will result in the success callback being called. Note that if the response is a redirect, * XMLHttpRequest will transparently follow it, meaning that the error callback will not be * called for such responses. * * ## Writing Unit Tests that use $http * When unit testing (using {@link ngMock ngMock}), it is necessary to call * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending * request using trained responses. * * ``` * $httpBackend.expectGET(...); * $http.get(...); * $httpBackend.flush(); * ``` * * ## Shortcut methods * * Shortcut methods are also available. All shortcut methods require passing in the URL, and * request data must be passed in for POST/PUT requests. * * ```js * $http.get('/someUrl').success(successCallback); * $http.post('/someUrl', data).success(successCallback); * ``` * * Complete list of shortcut methods: * * - {@link ng.$http#get $http.get} * - {@link ng.$http#head $http.head} * - {@link ng.$http#post $http.post} * - {@link ng.$http#put $http.put} * - {@link ng.$http#delete $http.delete} * - {@link ng.$http#jsonp $http.jsonp} * - {@link ng.$http#patch $http.patch} * * * ## Setting HTTP Headers * * The $http service will automatically add certain HTTP headers to all requests. These defaults * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration * object, which currently contains this default configuration: * * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): * - `Accept: application/json, text/plain, * / *` * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) * - `Content-Type: application/json` * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests) * - `Content-Type: application/json` * * To add or overwrite these defaults, simply add or remove a property from these configuration * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object * with the lowercased HTTP method name as the key, e.g. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }. * * The defaults can also be set at runtime via the `$http.defaults` object in the same * fashion. For example: * * ``` * module.run(function($http) { * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w' * }); * ``` * * In addition, you can supply a `headers` property in the config object passed when * calling `$http(config)`, which overrides the defaults without changing them globally. * * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis, * Use the `headers` property, setting the desired header to `undefined`. For example: * * ```js * var req = { * method: 'POST', * url: 'http://example.com', * headers: { * 'Content-Type': undefined * }, * data: { test: 'test' }, * } * * $http(req).success(function(){...}).error(function(){...}); * ``` * * ## Transforming Requests and Responses * * Both requests and responses can be transformed using transformation functions: `transformRequest` * and `transformResponse`. These properties can be a single function that returns * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions, * which allows you to `push` or `unshift` a new transformation function into the transformation chain. * * ### Default Transformations * * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and * `defaults.transformResponse` properties. If a request does not provide its own transformations * then these will be applied. * * You can augment or replace the default transformations by modifying these properties by adding to or * replacing the array. * * Angular provides the following default transformations: * * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`): * * - If the `data` property of the request configuration object contains an object, serialize it * into JSON format. * * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`): * * - If XSRF prefix is detected, strip it (see Security Considerations section below). * - If JSON response is detected, deserialize it using a JSON parser. * * * ### Overriding the Default Transformations Per Request * * If you wish override the request/response transformations only for a single request then provide * `transformRequest` and/or `transformResponse` properties on the configuration object passed * into `$http`. * * Note that if you provide these properties on the config object the default transformations will be * overwritten. If you wish to augment the default transformations then you must include them in your * local transformation array. * * The following code demonstrates adding a new response transformation to be run after the default response * transformations have been run. * * ```js * function appendTransform(defaults, transform) { * * // We can't guarantee that the default transformation is an array * defaults = angular.isArray(defaults) ? defaults : [defaults]; * * // Append the new transformation to the defaults * return defaults.concat(transform); * } * * $http({ * url: '...', * method: 'GET', * transformResponse: appendTransform($http.defaults.transformResponse, function(value) { * return doTransform(value); * }) * }); * ``` * * * ## Caching * * To enable caching, set the request configuration `cache` property to `true` (to use default * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}). * When the cache is enabled, `$http` stores the response from the server in the specified * cache. The next time the same request is made, the response is served from the cache without * sending a request to the server. * * Note that even if the response is served from cache, delivery of the data is asynchronous in * the same way that real requests are. * * If there are multiple GET requests for the same URL that should be cached using the same * cache, but the cache is not populated yet, only one request to the server will be made and * the remaining requests will be fulfilled using the response from the first request. * * You can change the default cache to a new object (built with * {@link ng.$cacheFactory `$cacheFactory`}) by updating the * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set * their `cache` property to `true` will now use this cache object. * * If you set the default cache to `false` then only requests that specify their own custom * cache object will be cached. * * ## Interceptors * * Before you start creating interceptors, be sure to understand the * {@link ng.$q $q and deferred/promise APIs}. * * For purposes of global error handling, authentication, or any kind of synchronous or * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be * able to intercept requests before they are handed to the server and * responses before they are handed over to the application code that * initiated these requests. The interceptors leverage the {@link ng.$q * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing. * * The interceptors are service factories that are registered with the `$httpProvider` by * adding them to the `$httpProvider.interceptors` array. The factory is called and * injected with dependencies (if specified) and returns the interceptor. * * There are two kinds of interceptors (and two kinds of rejection interceptors): * * * `request`: interceptors get called with a http `config` object. The function is free to * modify the `config` object or create a new one. The function needs to return the `config` * object directly, or a promise containing the `config` or a new `config` object. * * `requestError`: interceptor gets called when a previous interceptor threw an error or * resolved with a rejection. * * `response`: interceptors get called with http `response` object. The function is free to * modify the `response` object or create a new one. The function needs to return the `response` * object directly, or as a promise containing the `response` or a new `response` object. * * `responseError`: interceptor gets called when a previous interceptor threw an error or * resolved with a rejection. * * * ```js * // register the interceptor as a service * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { * return { * // optional method * 'request': function(config) { * // do something on success * return config; * }, * * // optional method * 'requestError': function(rejection) { * // do something on error * if (canRecover(rejection)) { * return responseOrNewPromise * } * return $q.reject(rejection); * }, * * * * // optional method * 'response': function(response) { * // do something on success * return response; * }, * * // optional method * 'responseError': function(rejection) { * // do something on error * if (canRecover(rejection)) { * return responseOrNewPromise * } * return $q.reject(rejection); * } * }; * }); * * $httpProvider.interceptors.push('myHttpInterceptor'); * * * // alternatively, register the interceptor via an anonymous factory * $httpProvider.interceptors.push(function($q, dependency1, dependency2) { * return { * 'request': function(config) { * // same as above * }, * * 'response': function(response) { * // same as above * } * }; * }); * ``` * * ## Security Considerations * * When designing web applications, consider security threats from: * * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) * * Both server and the client must cooperate in order to eliminate these threats. Angular comes * pre-configured with strategies that address these issues, but for this to work backend server * cooperation is required. * * ### JSON Vulnerability Protection * * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) * allows third party website to turn your JSON resource URL into * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To * counter this your server can prefix all JSON requests with following string `")]}',\n"`. * Angular will automatically strip the prefix before processing it as JSON. * * For example if your server needs to return: * ```js * ['one','two'] * ``` * * which is vulnerable to attack, your server can return: * ```js * )]}', * ['one','two'] * ``` * * Angular will strip the prefix, before processing the JSON. * * * ### Cross Site Request Forgery (XSRF) Protection * * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which * an unauthorized site can gain your user's private data. Angular provides a mechanism * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only * JavaScript that runs on your domain could read the cookie, your server can be assured that * the XHR came from JavaScript running on your domain. The header will not be set for * cross-domain requests. * * To take advantage of this, your server needs to set a token in a JavaScript readable session * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure * that only JavaScript running on your domain could have sent the request. The token must be * unique for each user and must be verifiable by the server (to prevent the JavaScript from * making up its own tokens). We recommend that the token is a digest of your site's * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;) * for added security. * * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time, * or the per-request config object. * * * @param {object} config Object describing the request to be made and how it should be * processed. The object has following properties: * * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be * JSONified. * - **data** – `{string|Object}` – Data to be sent as the request message data. * - **headers** – `{Object}` – Map of strings or functions which return strings representing * HTTP headers to send to the server. If the return value of a function is null, the * header will not be sent. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. * - **transformRequest** – * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * request body and headers and returns its transformed (typically serialized) version. * See {@link ng.$http#overriding-the-default-transformations-per-request * Overriding the Default Transformations} * - **transformResponse** – * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` – * transform function or an array of such functions. The transform function takes the http * response body, headers and status and returns its transformed (typically deserialized) version. * See {@link ng.$http#overriding-the-default-transformations-per-request * Overriding the Default Transformations} * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the * GET request, otherwise if a cache instance built with * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for * caching. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} * that should abort the request when resolved. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials) * for more information. * - **responseType** - `{string}` - see * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType). * * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the * standard `then` method and two http specific methods: `success` and `error`. The `then` * method takes two arguments a success and an error callback which will be called with a * response object. The `success` and `error` methods take a single argument - a function that * will be called when the request succeeds or fails respectively. The arguments passed into * these functions are destructured representation of the response object passed into the * `then` method. The response object has these properties: * * - **data** – `{string|Object}` – The response body transformed with the transform * functions. * - **status** – `{number}` – HTTP status code of the response. * - **headers** – `{function([headerName])}` – Header getter function. * - **config** – `{Object}` – The configuration object that was used to generate the request. * - **statusText** – `{string}` – HTTP status text of the response. * * @property {Array.<Object>} pendingRequests Array of config objects for currently pending * requests. This is primarily meant to be used for debugging purposes. * * * @example <example module="httpExample"> <file name="index.html"> <div ng-controller="FetchController"> <select ng-model="method"> <option>GET</option> <option>JSONP</option> </select> <input type="text" ng-model="url" size="80"/> <button id="fetchbtn" ng-click="fetch()">fetch</button><br> <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button> <button id="samplejsonpbtn" ng-click="updateModel('JSONP', 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')"> Sample JSONP </button> <button id="invalidjsonpbtn" ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')"> Invalid JSONP </button> <pre>http status code: {{status}}</pre> <pre>http response data: {{data}}</pre> </div> </file> <file name="script.js"> angular.module('httpExample', []) .controller('FetchController', ['$scope', '$http', '$templateCache', function($scope, $http, $templateCache) { $scope.method = 'GET'; $scope.url = 'http-hello.html'; $scope.fetch = function() { $scope.code = null; $scope.response = null; $http({method: $scope.method, url: $scope.url, cache: $templateCache}). success(function(data, status) { $scope.status = status; $scope.data = data; }). error(function(data, status) { $scope.data = data || "Request failed"; $scope.status = status; }); }; $scope.updateModel = function(method, url) { $scope.method = method; $scope.url = url; }; }]); </file> <file name="http-hello.html"> Hello, $http! </file> <file name="protractor.js" type="protractor"> var status = element(by.binding('status')); var data = element(by.binding('data')); var fetchBtn = element(by.id('fetchbtn')); var sampleGetBtn = element(by.id('samplegetbtn')); var sampleJsonpBtn = element(by.id('samplejsonpbtn')); var invalidJsonpBtn = element(by.id('invalidjsonpbtn')); it('should make an xhr GET request', function() { sampleGetBtn.click(); fetchBtn.click(); expect(status.getText()).toMatch('200'); expect(data.getText()).toMatch(/Hello, \$http!/); }); // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185 // it('should make a JSONP request to angularjs.org', function() { // sampleJsonpBtn.click(); // fetchBtn.click(); // expect(status.getText()).toMatch('200'); // expect(data.getText()).toMatch(/Super Hero!/); // }); it('should make JSONP request to invalid URL and invoke the error handler', function() { invalidJsonpBtn.click(); fetchBtn.click(); expect(status.getText()).toMatch('0'); expect(data.getText()).toMatch('Request failed'); }); </file> </example> */ function $http(requestConfig) { if (!angular.isObject(requestConfig)) { throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig); } var config = extend({ method: 'get', transformRequest: defaults.transformRequest, transformResponse: defaults.transformResponse }, requestConfig); config.headers = mergeHeaders(requestConfig); config.method = uppercase(config.method); var serverRequest = function(config) { var headers = config.headers; var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest); // strip content-type if data is undefined if (isUndefined(reqData)) { forEach(headers, function(value, header) { if (lowercase(header) === 'content-type') { delete headers[header]; } }); } if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { config.withCredentials = defaults.withCredentials; } // send request return sendReq(config, reqData).then(transformResponse, transformResponse); }; var chain = [serverRequest, undefined]; var promise = $q.when(config); // apply interceptors forEach(reversedInterceptors, function(interceptor) { if (interceptor.request || interceptor.requestError) { chain.unshift(interceptor.request, interceptor.requestError); } if (interceptor.response || interceptor.responseError) { chain.push(interceptor.response, interceptor.responseError); } }); while (chain.length) { var thenFn = chain.shift(); var rejectFn = chain.shift(); promise = promise.then(thenFn, rejectFn); } promise.success = function(fn) { promise.then(function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.error = function(fn) { promise.then(null, function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; return promise; function transformResponse(response) { // make a copy since the response must be cacheable var resp = extend({}, response); if (!response.data) { resp.data = response.data; } else { resp.data = transformData(response.data, response.headers, response.status, config.transformResponse); } return (isSuccess(response.status)) ? resp : $q.reject(resp); } function executeHeaderFns(headers) { var headerContent, processedHeaders = {}; forEach(headers, function(headerFn, header) { if (isFunction(headerFn)) { headerContent = headerFn(); if (headerContent != null) { processedHeaders[header] = headerContent; } } else { processedHeaders[header] = headerFn; } }); return processedHeaders; } function mergeHeaders(config) { var defHeaders = defaults.headers, reqHeaders = extend({}, config.headers), defHeaderName, lowercaseDefHeaderName, reqHeaderName; defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]); // using for-in instead of forEach to avoid unecessary iteration after header has been found defaultHeadersIteration: for (defHeaderName in defHeaders) { lowercaseDefHeaderName = lowercase(defHeaderName); for (reqHeaderName in reqHeaders) { if (lowercase(reqHeaderName) === lowercaseDefHeaderName) { continue defaultHeadersIteration; } } reqHeaders[defHeaderName] = defHeaders[defHeaderName]; } // execute if header value is a function for merged headers return executeHeaderFns(reqHeaders); } } $http.pendingRequests = []; /** * @ngdoc method * @name $http#get * * @description * Shortcut method to perform `GET` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#delete * * @description * Shortcut method to perform `DELETE` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#head * * @description * Shortcut method to perform `HEAD` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#jsonp * * @description * Shortcut method to perform `JSONP` request. * * @param {string} url Relative or absolute URL specifying the destination of the request. * The name of the callback should be the string `JSON_CALLBACK`. * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethods('get', 'delete', 'head', 'jsonp'); /** * @ngdoc method * @name $http#post * * @description * Shortcut method to perform `POST` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#put * * @description * Shortcut method to perform `PUT` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#patch * * @description * Shortcut method to perform `PATCH` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethodsWithData('post', 'put', 'patch'); /** * @ngdoc property * @name $http#defaults * * @description * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of * default headers, withCredentials as well as request and response transformations. * * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. */ $http.defaults = defaults; return $http; function createShortMethods(names) { forEach(arguments, function(name) { $http[name] = function(url, config) { return $http(extend(config || {}, { method: name, url: url })); }; }); } function createShortMethodsWithData(name) { forEach(arguments, function(name) { $http[name] = function(url, data, config) { return $http(extend(config || {}, { method: name, url: url, data: data })); }; }); } /** * Makes the request. * * !!! ACCESSES CLOSURE VARS: * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests */ function sendReq(config, reqData) { var deferred = $q.defer(), promise = deferred.promise, cache, cachedResp, reqHeaders = config.headers, url = buildUrl(config.url, config.params); $http.pendingRequests.push(config); promise.then(removePendingReq, removePendingReq); if ((config.cache || defaults.cache) && config.cache !== false && (config.method === 'GET' || config.method === 'JSONP')) { cache = isObject(config.cache) ? config.cache : isObject(defaults.cache) ? defaults.cache : defaultCache; } if (cache) { cachedResp = cache.get(url); if (isDefined(cachedResp)) { if (isPromiseLike(cachedResp)) { // cached request has already been sent, but there is no response yet cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult); } else { // serving from cache if (isArray(cachedResp)) { resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]); } else { resolvePromise(cachedResp, 200, {}, 'OK'); } } } else { // put the promise for the non-transformed response into cache as a placeholder cache.put(url, promise); } } // if we won't have the response in cache, set the xsrf headers and // send the request to the backend if (isUndefined(cachedResp)) { var xsrfValue = urlIsSameOrigin(config.url) ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName] : undefined; if (xsrfValue) { reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; } $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, config.withCredentials, config.responseType); } return promise; /** * Callback registered to $httpBackend(): * - caches the response if desired * - resolves the raw $http promise * - calls $apply */ function done(status, response, headersString, statusText) { if (cache) { if (isSuccess(status)) { cache.put(url, [status, response, parseHeaders(headersString), statusText]); } else { // remove promise from the cache cache.remove(url); } } function resolveHttpPromise() { resolvePromise(response, status, headersString, statusText); } if (useApplyAsync) { $rootScope.$applyAsync(resolveHttpPromise); } else { resolveHttpPromise(); if (!$rootScope.$$phase) $rootScope.$apply(); } } /** * Resolves the raw $http promise. */ function resolvePromise(response, status, headers, statusText) { // normalize internal statuses to 0 status = Math.max(status, 0); (isSuccess(status) ? deferred.resolve : deferred.reject)({ data: response, status: status, headers: headersGetter(headers), config: config, statusText: statusText }); } function resolvePromiseWithResult(result) { resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText); } function removePendingReq() { var idx = $http.pendingRequests.indexOf(config); if (idx !== -1) $http.pendingRequests.splice(idx, 1); } } function buildUrl(url, params) { if (!params) return url; var parts = []; forEachSorted(params, function(value, key) { if (value === null || isUndefined(value)) return; if (!isArray(value)) value = [value]; forEach(value, function(v) { if (isObject(v)) { if (isDate(v)) { v = v.toISOString(); } else { v = toJson(v); } } parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(v)); }); }); if (parts.length > 0) { url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); } return url; } }]; } function createXhr() { return new window.XMLHttpRequest(); } /** * @ngdoc service * @name $httpBackend * @requires $window * @requires $document * * @description * HTTP backend used by the {@link ng.$http service} that delegates to * XMLHttpRequest object or JSONP and deals with browser incompatibilities. * * You should never need to use this service directly, instead use the higher-level abstractions: * {@link ng.$http $http} or {@link ngResource.$resource $resource}. * * During testing this implementation is swapped with {@link ngMock.$httpBackend mock * $httpBackend} which can be trained with responses. */ function $HttpBackendProvider() { this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) { return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]); }]; } function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) { // TODO(vojta): fix the signature return function(method, url, post, callback, headers, timeout, withCredentials, responseType) { $browser.$$incOutstandingRequestCount(); url = url || $browser.url(); if (lowercase(method) == 'jsonp') { var callbackId = '_' + (callbacks.counter++).toString(36); callbacks[callbackId] = function(data) { callbacks[callbackId].data = data; callbacks[callbackId].called = true; }; var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), callbackId, function(status, text) { completeRequest(callback, status, callbacks[callbackId].data, "", text); callbacks[callbackId] = noop; }); } else { var xhr = createXhr(); xhr.open(method, url, true); forEach(headers, function(value, key) { if (isDefined(value)) { xhr.setRequestHeader(key, value); } }); xhr.onload = function requestLoaded() { var statusText = xhr.statusText || ''; // responseText is the old-school way of retrieving response (supported by IE8 & 9) // response/responseType properties were introduced in XHR Level2 spec (supported by IE10) var response = ('response' in xhr) ? xhr.response : xhr.responseText; // normalize IE9 bug (http://bugs.jquery.com/ticket/1450) var status = xhr.status === 1223 ? 204 : xhr.status; // fix status code when it is 0 (0 status is undocumented). // Occurs when accessing file resources or on Android 4.1 stock browser // while retrieving files from application cache. if (status === 0) { status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0; } completeRequest(callback, status, response, xhr.getAllResponseHeaders(), statusText); }; var requestError = function() { // The response is always empty // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error completeRequest(callback, -1, null, null, ''); }; xhr.onerror = requestError; xhr.onabort = requestError; if (withCredentials) { xhr.withCredentials = true; } if (responseType) { try { xhr.responseType = responseType; } catch (e) { // WebKit added support for the json responseType value on 09/03/2013 // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are // known to throw when setting the value "json" as the response type. Other older // browsers implementing the responseType // // The json response type can be ignored if not supported, because JSON payloads are // parsed on the client-side regardless. if (responseType !== 'json') { throw e; } } } xhr.send(post || null); } if (timeout > 0) { var timeoutId = $browserDefer(timeoutRequest, timeout); } else if (isPromiseLike(timeout)) { timeout.then(timeoutRequest); } function timeoutRequest() { jsonpDone && jsonpDone(); xhr && xhr.abort(); } function completeRequest(callback, status, response, headersString, statusText) { // cancel timeout and subsequent timeout promise resolution if (timeoutId !== undefined) { $browserDefer.cancel(timeoutId); } jsonpDone = xhr = null; callback(status, response, headersString, statusText); $browser.$$completeOutstandingRequest(noop); } }; function jsonpReq(url, callbackId, done) { // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: // - fetches local scripts via XHR and evals them // - adds and immediately removes script elements from the document var script = rawDocument.createElement('script'), callback = null; script.type = "text/javascript"; script.src = url; script.async = true; callback = function(event) { removeEventListenerFn(script, "load", callback); removeEventListenerFn(script, "error", callback); rawDocument.body.removeChild(script); script = null; var status = -1; var text = "unknown"; if (event) { if (event.type === "load" && !callbacks[callbackId].called) { event = { type: "error" }; } text = event.type; status = event.type === "error" ? 404 : 200; } if (done) { done(status, text); } }; addEventListenerFn(script, "load", callback); addEventListenerFn(script, "error", callback); rawDocument.body.appendChild(script); return callback; } } var $interpolateMinErr = minErr('$interpolate'); /** * @ngdoc provider * @name $interpolateProvider * * @description * * Used for configuring the interpolation markup. Defaults to `{{` and `}}`. * * @example <example module="customInterpolationApp"> <file name="index.html"> <script> var customInterpolationApp = angular.module('customInterpolationApp', []); customInterpolationApp.config(function($interpolateProvider) { $interpolateProvider.startSymbol('//'); $interpolateProvider.endSymbol('//'); }); customInterpolationApp.controller('DemoController', function() { this.label = "This binding is brought you by // interpolation symbols."; }); </script> <div ng-app="App" ng-controller="DemoController as demo"> //demo.label// </div> </file> <file name="protractor.js" type="protractor"> it('should interpolate binding with custom symbols', function() { expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.'); }); </file> </example> */ function $InterpolateProvider() { var startSymbol = '{{'; var endSymbol = '}}'; /** * @ngdoc method * @name $interpolateProvider#startSymbol * @description * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. * * @param {string=} value new value to set the starting symbol to. * @returns {string|self} Returns the symbol when used as getter and self if used as setter. */ this.startSymbol = function(value) { if (value) { startSymbol = value; return this; } else { return startSymbol; } }; /** * @ngdoc method * @name $interpolateProvider#endSymbol * @description * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. * * @param {string=} value new value to set the ending symbol to. * @returns {string|self} Returns the symbol when used as getter and self if used as setter. */ this.endSymbol = function(value) { if (value) { endSymbol = value; return this; } else { return endSymbol; } }; this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) { var startSymbolLength = startSymbol.length, endSymbolLength = endSymbol.length, escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'), escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g'); function escape(ch) { return '\\\\\\' + ch; } /** * @ngdoc service * @name $interpolate * @kind function * * @requires $parse * @requires $sce * * @description * * Compiles a string with markup into an interpolation function. This service is used by the * HTML {@link ng.$compile $compile} service for data binding. See * {@link ng.$interpolateProvider $interpolateProvider} for configuring the * interpolation markup. * * * ```js * var $interpolate = ...; // injected * var exp = $interpolate('Hello {{name | uppercase}}!'); * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!'); * ``` * * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is * `true`, the interpolation function will return `undefined` unless all embedded expressions * evaluate to a value other than `undefined`. * * ```js * var $interpolate = ...; // injected * var context = {greeting: 'Hello', name: undefined }; * * // default "forgiving" mode * var exp = $interpolate('{{greeting}} {{name}}!'); * expect(exp(context)).toEqual('Hello !'); * * // "allOrNothing" mode * exp = $interpolate('{{greeting}} {{name}}!', false, null, true); * expect(exp(context)).toBeUndefined(); * context.name = 'Angular'; * expect(exp(context)).toEqual('Hello Angular!'); * ``` * * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior. * * ####Escaped Interpolation * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash). * It will be rendered as a regular start/end marker, and will not be interpreted as an expression * or binding. * * This enables web-servers to prevent script injection attacks and defacing attacks, to some * degree, while also enabling code examples to work without relying on the * {@link ng.directive:ngNonBindable ngNonBindable} directive. * * **For security purposes, it is strongly encouraged that web servers escape user-supplied data, * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all * interpolation start/end markers with their escaped counterparts.** * * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered * output when the $interpolate service processes the text. So, for HTML elements interpolated * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such, * this is typically useful only when user-data is used in rendering a template from the server, or * when otherwise untrusted data is used by a directive. * * <example> * <file name="index.html"> * <div ng-init="username='A user'"> * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\} * </p> * <p><strong>{{username}}</strong> attempts to inject code which will deface the * application, but fails to accomplish their task, because the server has correctly * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash) * characters.</p> * <p>Instead, the result of the attempted script injection is visible, and can be removed * from the database by an administrator.</p> * </div> * </file> * </example> * * @param {string} text The text with markup to interpolate. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have * embedded expression in order to return an interpolation function. Strings with no * embedded expression will return null for the interpolation function. * @param {string=} trustedContext when provided, the returned function passes the interpolated * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult, * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that * provides Strict Contextual Escaping for details. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined * unless all embedded expressions evaluate to a value other than `undefined`. * @returns {function(context)} an interpolation function which is used to compute the * interpolated string. The function has these parameters: * * - `context`: evaluation context for all expressions embedded in the interpolated text */ function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) { allOrNothing = !!allOrNothing; var startIndex, endIndex, index = 0, expressions = [], parseFns = [], textLength = text.length, exp, concat = [], expressionPositions = []; while (index < textLength) { if (((startIndex = text.indexOf(startSymbol, index)) != -1) && ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) { if (index !== startIndex) { concat.push(unescapeText(text.substring(index, startIndex))); } exp = text.substring(startIndex + startSymbolLength, endIndex); expressions.push(exp); parseFns.push($parse(exp, parseStringifyInterceptor)); index = endIndex + endSymbolLength; expressionPositions.push(concat.length); concat.push(''); } else { // we did not find an interpolation, so we have to add the remainder to the separators array if (index !== textLength) { concat.push(unescapeText(text.substring(index))); } break; } } // Concatenating expressions makes it hard to reason about whether some combination of // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a // single expression be used for iframe[src], object[src], etc., we ensure that the value // that's used is assigned or constructed by some JS code somewhere that is more testable or // make it obvious that you bound the value to some user controlled value. This helps reduce // the load when auditing for XSS issues. if (trustedContext && concat.length > 1) { throw $interpolateMinErr('noconcat', "Error while interpolating: {0}\nStrict Contextual Escaping disallows " + "interpolations that concatenate multiple expressions when a trusted value is " + "required. See http://docs.angularjs.org/api/ng.$sce", text); } if (!mustHaveExpression || expressions.length) { var compute = function(values) { for (var i = 0, ii = expressions.length; i < ii; i++) { if (allOrNothing && isUndefined(values[i])) return; concat[expressionPositions[i]] = values[i]; } return concat.join(''); }; var getValue = function(value) { return trustedContext ? $sce.getTrusted(trustedContext, value) : $sce.valueOf(value); }; var stringify = function(value) { if (value == null) { // null || undefined return ''; } switch (typeof value) { case 'string': break; case 'number': value = '' + value; break; default: value = toJson(value); } return value; }; return extend(function interpolationFn(context) { var i = 0; var ii = expressions.length; var values = new Array(ii); try { for (; i < ii; i++) { values[i] = parseFns[i](context); } return compute(values); } catch (err) { var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString()); $exceptionHandler(newErr); } }, { // all of these properties are undocumented for now exp: text, //just for compatibility with regular watchers created via $watch expressions: expressions, $$watchDelegate: function(scope, listener, objectEquality) { var lastValue; return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) { var currValue = compute(values); if (isFunction(listener)) { listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope); } lastValue = currValue; }, objectEquality); } }); } function unescapeText(text) { return text.replace(escapedStartRegexp, startSymbol). replace(escapedEndRegexp, endSymbol); } function parseStringifyInterceptor(value) { try { value = getValue(value); return allOrNothing && !isDefined(value) ? value : stringify(value); } catch (err) { var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString()); $exceptionHandler(newErr); } } } /** * @ngdoc method * @name $interpolate#startSymbol * @description * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`. * * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change * the symbol. * * @returns {string} start symbol. */ $interpolate.startSymbol = function() { return startSymbol; }; /** * @ngdoc method * @name $interpolate#endSymbol * @description * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. * * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change * the symbol. * * @returns {string} end symbol. */ $interpolate.endSymbol = function() { return endSymbol; }; return $interpolate; }]; } function $IntervalProvider() { this.$get = ['$rootScope', '$window', '$q', '$$q', function($rootScope, $window, $q, $$q) { var intervals = {}; /** * @ngdoc service * @name $interval * * @description * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay` * milliseconds. * * The return value of registering an interval function is a promise. This promise will be * notified upon each tick of the interval, and will be resolved after `count` iterations, or * run indefinitely if `count` is not defined. The value of the notification will be the * number of iterations that have run. * To cancel an interval, call `$interval.cancel(promise)`. * * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to * move forward by `millis` milliseconds and trigger any functions scheduled to run in that * time. * * <div class="alert alert-warning"> * **Note**: Intervals created by this service must be explicitly destroyed when you are finished * with them. In particular they are not automatically destroyed when a controller's scope or a * directive's element are destroyed. * You should take this into consideration and make sure to always cancel the interval at the * appropriate moment. See the example below for more details on how and when to do this. * </div> * * @param {function()} fn A function that should be called repeatedly. * @param {number} delay Number of milliseconds between each function call. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat * indefinitely. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. * @returns {promise} A promise which will be notified on each iteration. * * @example * <example module="intervalExample"> * <file name="index.html"> * <script> * angular.module('intervalExample', []) * .controller('ExampleController', ['$scope', '$interval', * function($scope, $interval) { * $scope.format = 'M/d/yy h:mm:ss a'; * $scope.blood_1 = 100; * $scope.blood_2 = 120; * * var stop; * $scope.fight = function() { * // Don't start a new fight if we are already fighting * if ( angular.isDefined(stop) ) return; * * stop = $interval(function() { * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) { * $scope.blood_1 = $scope.blood_1 - 3; * $scope.blood_2 = $scope.blood_2 - 4; * } else { * $scope.stopFight(); * } * }, 100); * }; * * $scope.stopFight = function() { * if (angular.isDefined(stop)) { * $interval.cancel(stop); * stop = undefined; * } * }; * * $scope.resetFight = function() { * $scope.blood_1 = 100; * $scope.blood_2 = 120; * }; * * $scope.$on('$destroy', function() { * // Make sure that the interval is destroyed too * $scope.stopFight(); * }); * }]) * // Register the 'myCurrentTime' directive factory method. * // We inject $interval and dateFilter service since the factory method is DI. * .directive('myCurrentTime', ['$interval', 'dateFilter', * function($interval, dateFilter) { * // return the directive link function. (compile function not needed) * return function(scope, element, attrs) { * var format, // date format * stopTime; // so that we can cancel the time updates * * // used to update the UI * function updateTime() { * element.text(dateFilter(new Date(), format)); * } * * // watch the expression, and update the UI on change. * scope.$watch(attrs.myCurrentTime, function(value) { * format = value; * updateTime(); * }); * * stopTime = $interval(updateTime, 1000); * * // listen on DOM destroy (removal) event, and cancel the next UI update * // to prevent updating time after the DOM element was removed. * element.on('$destroy', function() { * $interval.cancel(stopTime); * }); * } * }]); * </script> * * <div> * <div ng-controller="ExampleController"> * Date format: <input ng-model="format"> <hr/> * Current time is: <span my-current-time="format"></span> * <hr/> * Blood 1 : <font color='red'>{{blood_1}}</font> * Blood 2 : <font color='red'>{{blood_2}}</font> * <button type="button" data-ng-click="fight()">Fight</button> * <button type="button" data-ng-click="stopFight()">StopFight</button> * <button type="button" data-ng-click="resetFight()">resetFight</button> * </div> * </div> * * </file> * </example> */ function interval(fn, delay, count, invokeApply) { var setInterval = $window.setInterval, clearInterval = $window.clearInterval, iteration = 0, skipApply = (isDefined(invokeApply) && !invokeApply), deferred = (skipApply ? $$q : $q).defer(), promise = deferred.promise; count = isDefined(count) ? count : 0; promise.then(null, null, fn); promise.$$intervalId = setInterval(function tick() { deferred.notify(iteration++); if (count > 0 && iteration >= count) { deferred.resolve(iteration); clearInterval(promise.$$intervalId); delete intervals[promise.$$intervalId]; } if (!skipApply) $rootScope.$apply(); }, delay); intervals[promise.$$intervalId] = deferred; return promise; } /** * @ngdoc method * @name $interval#cancel * * @description * Cancels a task associated with the `promise`. * * @param {promise} promise returned by the `$interval` function. * @returns {boolean} Returns `true` if the task was successfully canceled. */ interval.cancel = function(promise) { if (promise && promise.$$intervalId in intervals) { intervals[promise.$$intervalId].reject('canceled'); $window.clearInterval(promise.$$intervalId); delete intervals[promise.$$intervalId]; return true; } return false; }; return interval; }]; } /** * @ngdoc service * @name $locale * * @description * $locale service provides localization rules for various Angular components. As of right now the * only public api is: * * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) */ function $LocaleProvider() { this.$get = function() { return { id: 'en-us', NUMBER_FORMATS: { DECIMAL_SEP: '.', GROUP_SEP: ',', PATTERNS: [ { // Decimal Pattern minInt: 1, minFrac: 0, maxFrac: 3, posPre: '', posSuf: '', negPre: '-', negSuf: '', gSize: 3, lgSize: 3 },{ //Currency Pattern minInt: 1, minFrac: 2, maxFrac: 2, posPre: '\u00A4', posSuf: '', negPre: '(\u00A4', negSuf: ')', gSize: 3, lgSize: 3 } ], CURRENCY_SYM: '$' }, DATETIME_FORMATS: { MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December' .split(','), SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), AMPMS: ['AM','PM'], medium: 'MMM d, y h:mm:ss a', 'short': 'M/d/yy h:mm a', fullDate: 'EEEE, MMMM d, y', longDate: 'MMMM d, y', mediumDate: 'MMM d, y', shortDate: 'M/d/yy', mediumTime: 'h:mm:ss a', shortTime: 'h:mm a' }, pluralCat: function(num) { if (num === 1) { return 'one'; } return 'other'; } }; }; } var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/, DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; var $locationMinErr = minErr('$location'); /** * Encode path using encodeUriSegment, ignoring forward slashes * * @param {string} path Path to encode * @returns {string} */ function encodePath(path) { var segments = path.split('/'), i = segments.length; while (i--) { segments[i] = encodeUriSegment(segments[i]); } return segments.join('/'); } function parseAbsoluteUrl(absoluteUrl, locationObj) { var parsedUrl = urlResolve(absoluteUrl); locationObj.$$protocol = parsedUrl.protocol; locationObj.$$host = parsedUrl.hostname; locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null; } function parseAppUrl(relativeUrl, locationObj) { var prefixed = (relativeUrl.charAt(0) !== '/'); if (prefixed) { relativeUrl = '/' + relativeUrl; } var match = urlResolve(relativeUrl); locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ? match.pathname.substring(1) : match.pathname); locationObj.$$search = parseKeyValue(match.search); locationObj.$$hash = decodeURIComponent(match.hash); // make sure path starts with '/'; if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') { locationObj.$$path = '/' + locationObj.$$path; } } /** * * @param {string} begin * @param {string} whole * @returns {string} returns text from whole after begin or undefined if it does not begin with * expected string. */ function beginsWith(begin, whole) { if (whole.indexOf(begin) === 0) { return whole.substr(begin.length); } } function stripHash(url) { var index = url.indexOf('#'); return index == -1 ? url : url.substr(0, index); } function trimEmptyHash(url) { return url.replace(/(#.+)|#$/, '$1'); } function stripFile(url) { return url.substr(0, stripHash(url).lastIndexOf('/') + 1); } /* return the server only (scheme://host:port) */ function serverBase(url) { return url.substring(0, url.indexOf('/', url.indexOf('//') + 2)); } /** * LocationHtml5Url represents an url * This object is exposed as $location service when HTML5 mode is enabled and supported * * @constructor * @param {string} appBase application base URL * @param {string} basePrefix url path prefix */ function LocationHtml5Url(appBase, basePrefix) { this.$$html5 = true; basePrefix = basePrefix || ''; var appBaseNoFile = stripFile(appBase); parseAbsoluteUrl(appBase, this); /** * Parse given html5 (regular) url string into properties * @param {string} url HTML5 url * @private */ this.$$parse = function(url) { var pathUrl = beginsWith(appBaseNoFile, url); if (!isString(pathUrl)) { throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url, appBaseNoFile); } parseAppUrl(pathUrl, this); if (!this.$$path) { this.$$path = '/'; } this.$$compose(); }; /** * Compose url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/' }; this.$$parseLinkUrl = function(url, relHref) { if (relHref && relHref[0] === '#') { // special case for links to hash fragments: // keep the old url and only replace the hash fragment this.hash(relHref.slice(1)); return true; } var appUrl, prevAppUrl; var rewrittenUrl; if ((appUrl = beginsWith(appBase, url)) !== undefined) { prevAppUrl = appUrl; if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) { rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl); } else { rewrittenUrl = appBase + prevAppUrl; } } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) { rewrittenUrl = appBaseNoFile + appUrl; } else if (appBaseNoFile == url + '/') { rewrittenUrl = appBaseNoFile; } if (rewrittenUrl) { this.$$parse(rewrittenUrl); } return !!rewrittenUrl; }; } /** * LocationHashbangUrl represents url * This object is exposed as $location service when developer doesn't opt into html5 mode. * It also serves as the base class for html5 mode fallback on legacy browsers. * * @constructor * @param {string} appBase application base URL * @param {string} hashPrefix hashbang prefix */ function LocationHashbangUrl(appBase, hashPrefix) { var appBaseNoFile = stripFile(appBase); parseAbsoluteUrl(appBase, this); /** * Parse given hashbang url into properties * @param {string} url Hashbang url * @private */ this.$$parse = function(url) { var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url); var withoutHashUrl; if (withoutBaseUrl.charAt(0) === '#') { // The rest of the url starts with a hash so we have // got either a hashbang path or a plain hash fragment withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl); if (isUndefined(withoutHashUrl)) { // There was no hashbang prefix so we just have a hash fragment withoutHashUrl = withoutBaseUrl; } } else { // There was no hashbang path nor hash fragment: // If we are in HTML5 mode we use what is left as the path; // Otherwise we ignore what is left withoutHashUrl = this.$$html5 ? withoutBaseUrl : ''; } parseAppUrl(withoutHashUrl, this); this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase); this.$$compose(); /* * In Windows, on an anchor node on documents loaded from * the filesystem, the browser will return a pathname * prefixed with the drive name ('/C:/path') when a * pathname without a drive is set: * * a.setAttribute('href', '/foo') * * a.pathname === '/C:/foo' //true * * Inside of Angular, we're always using pathnames that * do not include drive names for routing. */ function removeWindowsDriveName(path, url, base) { /* Matches paths for file protocol on windows, such as /C:/foo/bar, and captures only /foo/bar. */ var windowsFilePathExp = /^\/[A-Z]:(\/.*)/; var firstPathSegmentMatch; //Get the relative path from the input URL. if (url.indexOf(base) === 0) { url = url.replace(base, ''); } // The input URL intentionally contains a first path segment that ends with a colon. if (windowsFilePathExp.exec(url)) { return path; } firstPathSegmentMatch = windowsFilePathExp.exec(path); return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path; } }; /** * Compose hashbang url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : ''); }; this.$$parseLinkUrl = function(url, relHref) { if (stripHash(appBase) == stripHash(url)) { this.$$parse(url); return true; } return false; }; } /** * LocationHashbangUrl represents url * This object is exposed as $location service when html5 history api is enabled but the browser * does not support it. * * @constructor * @param {string} appBase application base URL * @param {string} hashPrefix hashbang prefix */ function LocationHashbangInHtml5Url(appBase, hashPrefix) { this.$$html5 = true; LocationHashbangUrl.apply(this, arguments); var appBaseNoFile = stripFile(appBase); this.$$parseLinkUrl = function(url, relHref) { if (relHref && relHref[0] === '#') { // special case for links to hash fragments: // keep the old url and only replace the hash fragment this.hash(relHref.slice(1)); return true; } var rewrittenUrl; var appUrl; if (appBase == stripHash(url)) { rewrittenUrl = url; } else if ((appUrl = beginsWith(appBaseNoFile, url))) { rewrittenUrl = appBase + hashPrefix + appUrl; } else if (appBaseNoFile === url + '/') { rewrittenUrl = appBaseNoFile; } if (rewrittenUrl) { this.$$parse(rewrittenUrl); } return !!rewrittenUrl; }; this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#' this.$$absUrl = appBase + hashPrefix + this.$$url; }; } var locationPrototype = { /** * Are we in html5 mode? * @private */ $$html5: false, /** * Has any change been replacing? * @private */ $$replace: false, /** * @ngdoc method * @name $location#absUrl * * @description * This method is getter only. * * Return full url representation with all segments encoded according to rules specified in * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt). * * * ```js * // given url http://example.com/#/some/path?foo=bar&baz=xoxo * var absUrl = $location.absUrl(); * // => "http://example.com/#/some/path?foo=bar&baz=xoxo" * ``` * * @return {string} full url */ absUrl: locationGetter('$$absUrl'), /** * @ngdoc method * @name $location#url * * @description * This method is getter / setter. * * Return url (e.g. `/path?a=b#hash`) when called without any parameter. * * Change path, search and hash, when called with parameter and return `$location`. * * * ```js * // given url http://example.com/#/some/path?foo=bar&baz=xoxo * var url = $location.url(); * // => "/some/path?foo=bar&baz=xoxo" * ``` * * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) * @return {string} url */ url: function(url) { if (isUndefined(url)) return this.$$url; var match = PATH_MATCH.exec(url); if (match[1] || url === '') this.path(decodeURIComponent(match[1])); if (match[2] || match[1] || url === '') this.search(match[3] || ''); this.hash(match[5] || ''); return this; }, /** * @ngdoc method * @name $location#protocol * * @description * This method is getter only. * * Return protocol of current url. * * * ```js * // given url http://example.com/#/some/path?foo=bar&baz=xoxo * var protocol = $location.protocol(); * // => "http" * ``` * * @return {string} protocol of current url */ protocol: locationGetter('$$protocol'), /** * @ngdoc method * @name $location#host * * @description * This method is getter only. * * Return host of current url. * * * ```js * // given url http://example.com/#/some/path?foo=bar&baz=xoxo * var host = $location.host(); * // => "example.com" * ``` * * @return {string} host of current url. */ host: locationGetter('$$host'), /** * @ngdoc method * @name $location#port * * @description * This method is getter only. * * Return port of current url. * * * ```js * // given url http://example.com/#/some/path?foo=bar&baz=xoxo * var port = $location.port(); * // => 80 * ``` * * @return {Number} port */ port: locationGetter('$$port'), /** * @ngdoc method * @name $location#path * * @description * This method is getter / setter. * * Return path of current url when called without any parameter. * * Change path when called with parameter and return `$location`. * * Note: Path should always begin with forward slash (/), this method will add the forward slash * if it is missing. * * * ```js * // given url http://example.com/#/some/path?foo=bar&baz=xoxo * var path = $location.path(); * // => "/some/path" * ``` * * @param {(string|number)=} path New path * @return {string} path */ path: locationGetterSetter('$$path', function(path) { path = path !== null ? path.toString() : ''; return path.charAt(0) == '/' ? path : '/' + path; }), /** * @ngdoc method * @name $location#search * * @description * This method is getter / setter. * * Return search part (as object) of current url when called without any parameter. * * Change search part when called with parameter and return `$location`. * * * ```js * // given url http://example.com/#/some/path?foo=bar&baz=xoxo * var searchObject = $location.search(); * // => {foo: 'bar', baz: 'xoxo'} * * // set foo to 'yipee' * $location.search('foo', 'yipee'); * // $location.search() => {foo: 'yipee', baz: 'xoxo'} * ``` * * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or * hash object. * * When called with a single argument the method acts as a setter, setting the `search` component * of `$location` to the specified value. * * If the argument is a hash object containing an array of values, these values will be encoded * as duplicate search parameters in the url. * * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue` * will override only a single search property. * * If `paramValue` is an array, it will override the property of the `search` component of * `$location` specified via the first argument. * * If `paramValue` is `null`, the property specified via the first argument will be deleted. * * If `paramValue` is `true`, the property specified via the first argument will be added with no * value nor trailing equal sign. * * @return {Object} If called with no arguments returns the parsed `search` object. If called with * one or more arguments returns `$location` object itself. */ search: function(search, paramValue) { switch (arguments.length) { case 0: return this.$$search; case 1: if (isString(search) || isNumber(search)) { search = search.toString(); this.$$search = parseKeyValue(search); } else if (isObject(search)) { search = copy(search, {}); // remove object undefined or null properties forEach(search, function(value, key) { if (value == null) delete search[key]; }); this.$$search = search; } else { throw $locationMinErr('isrcharg', 'The first argument of the `$location#search()` call must be a string or an object.'); } break; default: if (isUndefined(paramValue) || paramValue === null) { delete this.$$search[search]; } else { this.$$search[search] = paramValue; } } this.$$compose(); return this; }, /** * @ngdoc method * @name $location#hash * * @description * This method is getter / setter. * * Return hash fragment when called without any parameter. * * Change hash fragment when called with parameter and return `$location`. * * * ```js * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue * var hash = $location.hash(); * // => "hashValue" * ``` * * @param {(string|number)=} hash New hash fragment * @return {string} hash */ hash: locationGetterSetter('$$hash', function(hash) { return hash !== null ? hash.toString() : ''; }), /** * @ngdoc method * @name $location#replace * * @description * If called, all changes to $location during current `$digest` will be replacing current history * record, instead of adding new one. */ replace: function() { this.$$replace = true; return this; } }; forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) { Location.prototype = Object.create(locationPrototype); /** * @ngdoc method * @name $location#state * * @description * This method is getter / setter. * * Return the history state object when called without any parameter. * * Change the history state object when called with one parameter and return `$location`. * The state object is later passed to `pushState` or `replaceState`. * * NOTE: This method is supported only in HTML5 mode and only in browsers supporting * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support * older browsers (like IE9 or Android < 4.0), don't use this method. * * @param {object=} state State object for pushState or replaceState * @return {object} state */ Location.prototype.state = function(state) { if (!arguments.length) return this.$$state; if (Location !== LocationHtml5Url || !this.$$html5) { throw $locationMinErr('nostate', 'History API state support is available only ' + 'in HTML5 mode and only in browsers supporting HTML5 History API'); } // The user might modify `stateObject` after invoking `$location.state(stateObject)` // but we're changing the $$state reference to $browser.state() during the $digest // so the modification window is narrow. this.$$state = isUndefined(state) ? null : state; return this; }; }); function locationGetter(property) { return function() { return this[property]; }; } function locationGetterSetter(property, preprocess) { return function(value) { if (isUndefined(value)) return this[property]; this[property] = preprocess(value); this.$$compose(); return this; }; } /** * @ngdoc service * @name $location * * @requires $rootElement * * @description * The $location service parses the URL in the browser address bar (based on the * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL * available to your application. Changes to the URL in the address bar are reflected into * $location service and changes to $location are reflected into the browser address bar. * * **The $location service:** * * - Exposes the current URL in the browser address bar, so you can * - Watch and observe the URL. * - Change the URL. * - Synchronizes the URL with the browser when the user * - Changes the address bar. * - Clicks the back or forward button (or clicks a History link). * - Clicks on a link. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). * * For more information see {@link guide/$location Developer Guide: Using $location} */ /** * @ngdoc provider * @name $locationProvider * @description * Use the `$locationProvider` to configure how the application deep linking paths are stored. */ function $LocationProvider() { var hashPrefix = '', html5Mode = { enabled: false, requireBase: true, rewriteLinks: true }; /** * @ngdoc method * @name $locationProvider#hashPrefix * @description * @param {string=} prefix Prefix for hash part (containing path and search) * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.hashPrefix = function(prefix) { if (isDefined(prefix)) { hashPrefix = prefix; return this; } else { return hashPrefix; } }; /** * @ngdoc method * @name $locationProvider#html5Mode * @description * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported * properties: * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not * support `pushState`. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are * true, and a base tag is not present, an error will be thrown when `$location` is injected. * See the {@link guide/$location $location guide for more information} * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled, * enables/disables url rewriting for relative links. * * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter */ this.html5Mode = function(mode) { if (isBoolean(mode)) { html5Mode.enabled = mode; return this; } else if (isObject(mode)) { if (isBoolean(mode.enabled)) { html5Mode.enabled = mode.enabled; } if (isBoolean(mode.requireBase)) { html5Mode.requireBase = mode.requireBase; } if (isBoolean(mode.rewriteLinks)) { html5Mode.rewriteLinks = mode.rewriteLinks; } return this; } else { return html5Mode; } }; /** * @ngdoc event * @name $location#$locationChangeStart * @eventType broadcast on root scope * @description * Broadcasted before a URL will change. * * This change can be prevented by calling * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more * details about event object. Upon successful change * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired. * * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when * the browser supports the HTML5 History API. * * @param {Object} angularEvent Synthetic event object. * @param {string} newUrl New URL * @param {string=} oldUrl URL that was before it was changed. * @param {string=} newState New history state object * @param {string=} oldState History state object that was before it was changed. */ /** * @ngdoc event * @name $location#$locationChangeSuccess * @eventType broadcast on root scope * @description * Broadcasted after a URL was changed. * * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when * the browser supports the HTML5 History API. * * @param {Object} angularEvent Synthetic event object. * @param {string} newUrl New URL * @param {string=} oldUrl URL that was before it was changed. * @param {string=} newState New history state object * @param {string=} oldState History state object that was before it was changed. */ this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window', function($rootScope, $browser, $sniffer, $rootElement, $window) { var $location, LocationMode, baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to '' initialUrl = $browser.url(), appBase; if (html5Mode.enabled) { if (!baseHref && html5Mode.requireBase) { throw $locationMinErr('nobase', "$location in HTML5 mode requires a <base> tag to be present!"); } appBase = serverBase(initialUrl) + (baseHref || '/'); LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url; } else { appBase = stripHash(initialUrl); LocationMode = LocationHashbangUrl; } $location = new LocationMode(appBase, '#' + hashPrefix); $location.$$parseLinkUrl(initialUrl, initialUrl); debugger; if($browser && $browser.state){ console.log(999999999999999999999999999999999999999999999999999999999); $location.$$state = $browser.state(); } var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i; function setBrowserUrlWithFallback(url, replace, state) { var oldUrl = $location.url(); var oldState = $location.$$state; try { $browser.url(url, replace, state); // Make sure $location.state() returns referentially identical (not just deeply equal) // state object; this makes possible quick checking if the state changed in the digest // loop. Checking deep equality would be too expensive. $location.$$state = $browser.state(); } catch (e) { // Restore old values if pushState fails $location.url(oldUrl); $location.$$state = oldState; throw e; } } $rootElement.on('click', function(event) { // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) // currently we open nice url link and redirect then if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return; var elm = jqLite(event.target); // traverse the DOM up to find first A tag while (nodeName_(elm[0]) !== 'a') { // ignore rewriting if no A tag (reached root element, or no parent - removed from document) if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return; } var absHref = elm.prop('href'); // get the actual href attribute - see // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx var relHref = elm.attr('href') || elm.attr('xlink:href'); if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') { // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during // an animation. absHref = urlResolve(absHref.animVal).href; } // Ignore when url is started with javascript: or mailto: if (IGNORE_URI_REGEXP.test(absHref)) return; if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) { if ($location.$$parseLinkUrl(absHref, relHref)) { // We do a preventDefault for all urls that are part of the angular application, // in html5mode and also without, so that we are able to abort navigation without // getting double entries in the location history. event.preventDefault(); // update location manually if ($location.absUrl() != $browser.url()) { $rootScope.$apply(); // hack to work around FF6 bug 684208 when scenario runner clicks on links $window.angular['ff-684208-preventDefault'] = true; } } } }); // rewrite hashbang url <> html5 url if ($location.absUrl() != initialUrl) { $browser.url($location.absUrl(), true); } var initializing = true; // update $location when $browser url changes $browser.onUrlChange(function(newUrl, newState) { $rootScope.$evalAsync(function() { var oldUrl = $location.absUrl(); var oldState = $location.$$state; var defaultPrevented; $location.$$parse(newUrl); $location.$$state = newState; defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, newState, oldState).defaultPrevented; // if the location was changed by a `$locationChangeStart` handler then stop // processing this location change if ($location.absUrl() !== newUrl) return; if (defaultPrevented) { $location.$$parse(oldUrl); $location.$$state = oldState; setBrowserUrlWithFallback(oldUrl, false, oldState); } else { initializing = false; afterLocationChange(oldUrl, oldState); } }); if (!$rootScope.$$phase) $rootScope.$digest(); }); // update browser $rootScope.$watch(function $locationWatch() { var oldUrl = trimEmptyHash($browser.url()); var newUrl = trimEmptyHash($location.absUrl()); var oldState = $browser.state(); var currentReplace = $location.$$replace; var urlOrStateChanged = oldUrl !== newUrl || ($location.$$html5 && $sniffer.history && oldState !== $location.$$state); if (initializing || urlOrStateChanged) { initializing = false; $rootScope.$evalAsync(function() { var newUrl = $location.absUrl(); var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, $location.$$state, oldState).defaultPrevented; // if the location was changed by a `$locationChangeStart` handler then stop // processing this location change if ($location.absUrl() !== newUrl) return; if (defaultPrevented) { $location.$$parse(oldUrl); $location.$$state = oldState; } else { if (urlOrStateChanged) { setBrowserUrlWithFallback(newUrl, currentReplace, oldState === $location.$$state ? null : $location.$$state); } afterLocationChange(oldUrl, oldState); } }); } $location.$$replace = false; // we don't need to return anything because $evalAsync will make the digest loop dirty when // there is a change }); return $location; function afterLocationChange(oldUrl, oldState) { $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl, $location.$$state, oldState); } }]; } /** * @ngdoc service * @name $log * @requires $window * * @description * Simple service for logging. Default implementation safely writes the message * into the browser's console (if present). * * The main purpose of this service is to simplify debugging and troubleshooting. * * The default is to log `debug` messages. You can use * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this. * * @example <example module="logExample"> <file name="script.js"> angular.module('logExample', []) .controller('LogController', ['$scope', '$log', function($scope, $log) { $scope.$log = $log; $scope.message = 'Hello World!'; }]); </file> <file name="index.html"> <div ng-controller="LogController"> <p>Reload this page with open console, enter text and hit the log button...</p> Message: <input type="text" ng-model="message"/> <button ng-click="$log.log(message)">log</button> <button ng-click="$log.warn(message)">warn</button> <button ng-click="$log.info(message)">info</button> <button ng-click="$log.error(message)">error</button> </div> </file> </example> */ /** * @ngdoc provider * @name $logProvider * @description * Use the `$logProvider` to configure how the application logs messages */ function $LogProvider() { var debug = true, self = this; /** * @ngdoc method * @name $logProvider#debugEnabled * @description * @param {boolean=} flag enable or disable debug level messages * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.debugEnabled = function(flag) { if (isDefined(flag)) { debug = flag; return this; } else { return debug; } }; this.$get = ['$window', function($window) { return { /** * @ngdoc method * @name $log#log * * @description * Write a log message */ log: consoleLog('log'), /** * @ngdoc method * @name $log#info * * @description * Write an information message */ info: consoleLog('info'), /** * @ngdoc method * @name $log#warn * * @description * Write a warning message */ warn: consoleLog('warn'), /** * @ngdoc method * @name $log#error * * @description * Write an error message */ error: consoleLog('error'), /** * @ngdoc method * @name $log#debug * * @description * Write a debug message */ debug: (function() { var fn = consoleLog('debug'); return function() { if (debug) { fn.apply(self, arguments); } }; }()) }; function formatError(arg) { if (arg instanceof Error) { if (arg.stack) { arg = (arg.message && arg.stack.indexOf(arg.message) === -1) ? 'Error: ' + arg.message + '\n' + arg.stack : arg.stack; } else if (arg.sourceURL) { arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; } } return arg; } function consoleLog(type) { var console = $window.console || {}, logFn = console[type] || console.log || noop, hasApply = false; // Note: reading logFn.apply throws an error in IE11 in IE8 document mode. // The reason behind this is that console.log has type "object" in IE8... try { hasApply = !!logFn.apply; } catch (e) {} if (hasApply) { return function() { var args = []; forEach(arguments, function(arg) { args.push(formatError(arg)); }); return logFn.apply(console, args); }; } // we are IE which either doesn't have window.console => this is noop and we do nothing, // or we are IE where console.log doesn't have apply so we log at least first 2 args return function(arg1, arg2) { logFn(arg1, arg2 == null ? '' : arg2); }; } }]; } var $parseMinErr = minErr('$parse'); // Sandboxing Angular Expressions // ------------------------------ // Angular expressions are generally considered safe because these expressions only have direct // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by // obtaining a reference to native JS functions such as the Function constructor. // // As an example, consider the following Angular expression: // // {}.toString.constructor('alert("evil JS code")') // // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits // against the expression language, but not to prevent exploits that were enabled by exposing // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good // practice and therefore we are not even trying to protect against interaction with an object // explicitly exposed in this way. // // In general, it is not possible to access a Window object from an angular expression unless a // window or some DOM object that has a reference to window is published onto a Scope. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to // native objects. // // See https://docs.angularjs.org/guide/security function ensureSafeMemberName(name, fullExpression) { if (name === "__defineGetter__" || name === "__defineSetter__" || name === "__lookupGetter__" || name === "__lookupSetter__" || name === "__proto__") { throw $parseMinErr('isecfld', 'Attempting to access a disallowed field in Angular expressions! ' + 'Expression: {0}', fullExpression); } return name; } function ensureSafeObject(obj, fullExpression) { // nifty check if obj is Function that is fast and works across iframes and other contexts if (obj) { if (obj.constructor === obj) { throw $parseMinErr('isecfn', 'Referencing Function in Angular expressions is disallowed! Expression: {0}', fullExpression); } else if (// isWindow(obj) obj.window === obj) { throw $parseMinErr('isecwindow', 'Referencing the Window in Angular expressions is disallowed! Expression: {0}', fullExpression); } else if (// isElement(obj) obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) { throw $parseMinErr('isecdom', 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}', fullExpression); } else if (// block Object so that we can't get hold of dangerous Object.* methods obj === Object) { throw $parseMinErr('isecobj', 'Referencing Object in Angular expressions is disallowed! Expression: {0}', fullExpression); } } return obj; } var CALL = Function.prototype.call; var APPLY = Function.prototype.apply; var BIND = Function.prototype.bind; function ensureSafeFunction(obj, fullExpression) { if (obj) { if (obj.constructor === obj) { throw $parseMinErr('isecfn', 'Referencing Function in Angular expressions is disallowed! Expression: {0}', fullExpression); } else if (obj === CALL || obj === APPLY || obj === BIND) { throw $parseMinErr('isecff', 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}', fullExpression); } } } //Keyword constants var CONSTANTS = createMap(); forEach({ 'null': function() { return null; }, 'true': function() { return true; }, 'false': function() { return false; }, 'undefined': function() {} }, function(constantGetter, name) { constantGetter.constant = constantGetter.literal = constantGetter.sharedGetter = true; CONSTANTS[name] = constantGetter; }); //Not quite a constant, but can be lex/parsed the same CONSTANTS['this'] = function(self) { return self; }; CONSTANTS['this'].sharedGetter = true; //Operators - will be wrapped by binaryFn/unaryFn/assignment/filter var OPERATORS = extend(createMap(), { '+':function(self, locals, a, b) { a=a(self, locals); b=b(self, locals); if (isDefined(a)) { if (isDefined(b)) { return a + b; } return a; } return isDefined(b) ? b : undefined;}, '-':function(self, locals, a, b) { a=a(self, locals); b=b(self, locals); return (isDefined(a) ? a : 0) - (isDefined(b) ? b : 0); }, '*':function(self, locals, a, b) {return a(self, locals) * b(self, locals);}, '/':function(self, locals, a, b) {return a(self, locals) / b(self, locals);}, '%':function(self, locals, a, b) {return a(self, locals) % b(self, locals);}, '===':function(self, locals, a, b) {return a(self, locals) === b(self, locals);}, '!==':function(self, locals, a, b) {return a(self, locals) !== b(self, locals);}, '==':function(self, locals, a, b) {return a(self, locals) == b(self, locals);}, '!=':function(self, locals, a, b) {return a(self, locals) != b(self, locals);}, '<':function(self, locals, a, b) {return a(self, locals) < b(self, locals);}, '>':function(self, locals, a, b) {return a(self, locals) > b(self, locals);}, '<=':function(self, locals, a, b) {return a(self, locals) <= b(self, locals);}, '>=':function(self, locals, a, b) {return a(self, locals) >= b(self, locals);}, '&&':function(self, locals, a, b) {return a(self, locals) && b(self, locals);}, '||':function(self, locals, a, b) {return a(self, locals) || b(self, locals);}, '!':function(self, locals, a) {return !a(self, locals);}, //Tokenized as operators but parsed as assignment/filters '=':true, '|':true }); var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; ///////////////////////////////////////// /** * @constructor */ var Lexer = function(options) { this.options = options; }; Lexer.prototype = { constructor: Lexer, lex: function(text) { this.text = text; this.index = 0; this.tokens = []; while (this.index < this.text.length) { var ch = this.text.charAt(this.index); if (ch === '"' || ch === "'") { this.readString(ch); } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) { this.readNumber(); } else if (this.isIdent(ch)) { this.readIdent(); } else if (this.is(ch, '(){}[].,;:?')) { this.tokens.push({index: this.index, text: ch}); this.index++; } else if (this.isWhitespace(ch)) { this.index++; } else { var ch2 = ch + this.peek(); var ch3 = ch2 + this.peek(2); var op1 = OPERATORS[ch]; var op2 = OPERATORS[ch2]; var op3 = OPERATORS[ch3]; if (op1 || op2 || op3) { var token = op3 ? ch3 : (op2 ? ch2 : ch); this.tokens.push({index: this.index, text: token, operator: true}); this.index += token.length; } else { this.throwError('Unexpected next character ', this.index, this.index + 1); } } } return this.tokens; }, is: function(ch, chars) { return chars.indexOf(ch) !== -1; }, peek: function(i) { var num = i || 1; return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false; }, isNumber: function(ch) { return ('0' <= ch && ch <= '9') && typeof ch === "string"; }, isWhitespace: function(ch) { // IE treats non-breaking space as \u00A0 return (ch === ' ' || ch === '\r' || ch === '\t' || ch === '\n' || ch === '\v' || ch === '\u00A0'); }, isIdent: function(ch) { return ('a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '_' === ch || ch === '$'); }, isExpOperator: function(ch) { return (ch === '-' || ch === '+' || this.isNumber(ch)); }, throwError: function(error, start, end) { end = end || this.index; var colStr = (isDefined(start) ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']' : ' ' + end); throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].', error, colStr, this.text); }, readNumber: function() { var number = ''; var start = this.index; while (this.index < this.text.length) { var ch = lowercase(this.text.charAt(this.index)); if (ch == '.' || this.isNumber(ch)) { number += ch; } else { var peekCh = this.peek(); if (ch == 'e' && this.isExpOperator(peekCh)) { number += ch; } else if (this.isExpOperator(ch) && peekCh && this.isNumber(peekCh) && number.charAt(number.length - 1) == 'e') { number += ch; } else if (this.isExpOperator(ch) && (!peekCh || !this.isNumber(peekCh)) && number.charAt(number.length - 1) == 'e') { this.throwError('Invalid exponent'); } else { break; } } this.index++; } this.tokens.push({ index: start, text: number, constant: true, value: Number(number) }); }, readIdent: function() { var start = this.index; while (this.index < this.text.length) { var ch = this.text.charAt(this.index); if (!(this.isIdent(ch) || this.isNumber(ch))) { break; } this.index++; } this.tokens.push({ index: start, text: this.text.slice(start, this.index), identifier: true }); }, readString: function(quote) { var start = this.index; this.index++; var string = ''; var rawString = quote; var escape = false; while (this.index < this.text.length) { var ch = this.text.charAt(this.index); rawString += ch; if (escape) { if (ch === 'u') { var hex = this.text.substring(this.index + 1, this.index + 5); if (!hex.match(/[\da-f]{4}/i)) this.throwError('Invalid unicode escape [\\u' + hex + ']'); this.index += 4; string += String.fromCharCode(parseInt(hex, 16)); } else { var rep = ESCAPE[ch]; string = string + (rep || ch); } escape = false; } else if (ch === '\\') { escape = true; } else if (ch === quote) { this.index++; this.tokens.push({ index: start, text: rawString, constant: true, value: string }); return; } else { string += ch; } this.index++; } this.throwError('Unterminated quote', start); } }; function isConstant(exp) { return exp.constant; } /** * @constructor */ var Parser = function(lexer, $filter, options) { this.lexer = lexer; this.$filter = $filter; this.options = options; }; Parser.ZERO = extend(function() { return 0; }, { sharedGetter: true, constant: true }); Parser.prototype = { constructor: Parser, parse: function(text) { this.text = text; this.tokens = this.lexer.lex(text); var value = this.statements(); if (this.tokens.length !== 0) { this.throwError('is an unexpected token', this.tokens[0]); } value.literal = !!value.literal; value.constant = !!value.constant; return value; }, primary: function() { var primary; if (this.expect('(')) { primary = this.filterChain(); this.consume(')'); } else if (this.expect('[')) { primary = this.arrayDeclaration(); } else if (this.expect('{')) { primary = this.object(); } else if (this.peek().identifier && this.peek().text in CONSTANTS) { primary = CONSTANTS[this.consume().text]; } else if (this.peek().identifier) { primary = this.identifier(); } else if (this.peek().constant) { primary = this.constant(); } else { this.throwError('not a primary expression', this.peek()); } var next, context; while ((next = this.expect('(', '[', '.'))) { if (next.text === '(') { primary = this.functionCall(primary, context); context = null; } else if (next.text === '[') { context = primary; primary = this.objectIndex(primary); } else if (next.text === '.') { context = primary; primary = this.fieldAccess(primary); } else { this.throwError('IMPOSSIBLE'); } } return primary; }, throwError: function(msg, token) { throw $parseMinErr('syntax', 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].', token.text, msg, (token.index + 1), this.text, this.text.substring(token.index)); }, peekToken: function() { if (this.tokens.length === 0) throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); return this.tokens[0]; }, peek: function(e1, e2, e3, e4) { return this.peekAhead(0, e1, e2, e3, e4); }, peekAhead: function(i, e1, e2, e3, e4) { if (this.tokens.length > i) { var token = this.tokens[i]; var t = token.text; if (t === e1 || t === e2 || t === e3 || t === e4 || (!e1 && !e2 && !e3 && !e4)) { return token; } } return false; }, expect: function(e1, e2, e3, e4) { var token = this.peek(e1, e2, e3, e4); if (token) { this.tokens.shift(); return token; } return false; }, consume: function(e1) { if (this.tokens.length === 0) { throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); } var token = this.expect(e1); if (!token) { this.throwError('is unexpected, expecting [' + e1 + ']', this.peek()); } return token; }, unaryFn: function(op, right) { var fn = OPERATORS[op]; return extend(function $parseUnaryFn(self, locals) { return fn(self, locals, right); }, { constant:right.constant, inputs: [right] }); }, binaryFn: function(left, op, right, isBranching) { var fn = OPERATORS[op]; return extend(function $parseBinaryFn(self, locals) { return fn(self, locals, left, right); }, { constant: left.constant && right.constant, inputs: !isBranching && [left, right] }); }, identifier: function() { var id = this.consume().text; //Continue reading each `.identifier` unless it is a method invocation while (this.peek('.') && this.peekAhead(1).identifier && !this.peekAhead(2, '(')) { id += this.consume().text + this.consume().text; } return getterFn(id, this.options, this.text); }, constant: function() { var value = this.consume().value; return extend(function $parseConstant() { return value; }, { constant: true, literal: true }); }, statements: function() { var statements = []; while (true) { if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']')) statements.push(this.filterChain()); if (!this.expect(';')) { // optimize for the common case where there is only one statement. // TODO(size): maybe we should not support multiple statements? return (statements.length === 1) ? statements[0] : function $parseStatements(self, locals) { var value; for (var i = 0, ii = statements.length; i < ii; i++) { value = statements[i](self, locals); } return value; }; } } }, filterChain: function() { var left = this.expression(); var token; while ((token = this.expect('|'))) { left = this.filter(left); } return left; }, filter: function(inputFn) { var fn = this.$filter(this.consume().text); var argsFn; var args; if (this.peek(':')) { argsFn = []; args = []; // we can safely reuse the array while (this.expect(':')) { argsFn.push(this.expression()); } } var inputs = [inputFn].concat(argsFn || []); return extend(function $parseFilter(self, locals) { var input = inputFn(self, locals); if (args) { args[0] = input; var i = argsFn.length; while (i--) { args[i + 1] = argsFn[i](self, locals); } return fn.apply(undefined, args); } return fn(input); }, { constant: !fn.$stateful && inputs.every(isConstant), inputs: !fn.$stateful && inputs }); }, expression: function() { return this.assignment(); }, assignment: function() { var left = this.ternary(); var right; var token; if ((token = this.expect('='))) { if (!left.assign) { this.throwError('implies assignment but [' + this.text.substring(0, token.index) + '] can not be assigned to', token); } right = this.ternary(); return extend(function $parseAssignment(scope, locals) { return left.assign(scope, right(scope, locals), locals); }, { inputs: [left, right] }); } return left; }, ternary: function() { var left = this.logicalOR(); var middle; var token; if ((token = this.expect('?'))) { middle = this.assignment(); if (this.consume(':')) { var right = this.assignment(); return extend(function $parseTernary(self, locals) { return left(self, locals) ? middle(self, locals) : right(self, locals); }, { constant: left.constant && middle.constant && right.constant }); } } return left; }, logicalOR: function() { var left = this.logicalAND(); var token; while ((token = this.expect('||'))) { left = this.binaryFn(left, token.text, this.logicalAND(), true); } return left; }, logicalAND: function() { var left = this.equality(); var token; while ((token = this.expect('&&'))) { left = this.binaryFn(left, token.text, this.equality(), true); } return left; }, equality: function() { var left = this.relational(); var token; while ((token = this.expect('==','!=','===','!=='))) { left = this.binaryFn(left, token.text, this.relational()); } return left; }, relational: function() { var left = this.additive(); var token; while ((token = this.expect('<', '>', '<=', '>='))) { left = this.binaryFn(left, token.text, this.additive()); } return left; }, additive: function() { var left = this.multiplicative(); var token; while ((token = this.expect('+','-'))) { left = this.binaryFn(left, token.text, this.multiplicative()); } return left; }, multiplicative: function() { var left = this.unary(); var token; while ((token = this.expect('*','/','%'))) { left = this.binaryFn(left, token.text, this.unary()); } return left; }, unary: function() { var token; if (this.expect('+')) { return this.primary(); } else if ((token = this.expect('-'))) { return this.binaryFn(Parser.ZERO, token.text, this.unary()); } else if ((token = this.expect('!'))) { return this.unaryFn(token.text, this.unary()); } else { return this.primary(); } }, fieldAccess: function(object) { var getter = this.identifier(); return extend(function $parseFieldAccess(scope, locals, self) { var o = self || object(scope, locals); return (o == null) ? undefined : getter(o); }, { assign: function(scope, value, locals) { var o = object(scope, locals); if (!o) object.assign(scope, o = {}, locals); return getter.assign(o, value); } }); }, objectIndex: function(obj) { var expression = this.text; var indexFn = this.expression(); this.consume(']'); return extend(function $parseObjectIndex(self, locals) { var o = obj(self, locals), i = indexFn(self, locals), v; ensureSafeMemberName(i, expression); if (!o) return undefined; v = ensureSafeObject(o[i], expression); return v; }, { assign: function(self, value, locals) { var key = ensureSafeMemberName(indexFn(self, locals), expression); // prevent overwriting of Function.constructor which would break ensureSafeObject check var o = ensureSafeObject(obj(self, locals), expression); if (!o) obj.assign(self, o = {}, locals); return o[key] = value; } }); }, functionCall: function(fnGetter, contextGetter) { var argsFn = []; if (this.peekToken().text !== ')') { do { argsFn.push(this.expression()); } while (this.expect(',')); } this.consume(')'); var expressionText = this.text; // we can safely reuse the array across invocations var args = argsFn.length ? [] : null; return function $parseFunctionCall(scope, locals) { var context = contextGetter ? contextGetter(scope, locals) : isDefined(contextGetter) ? undefined : scope; var fn = fnGetter(scope, locals, context) || noop; if (args) { var i = argsFn.length; while (i--) { args[i] = ensureSafeObject(argsFn[i](scope, locals), expressionText); } } ensureSafeObject(context, expressionText); ensureSafeFunction(fn, expressionText); // IE doesn't have apply for some native functions var v = fn.apply ? fn.apply(context, args) : fn(args[0], args[1], args[2], args[3], args[4]); return ensureSafeObject(v, expressionText); }; }, // This is used with json array declaration arrayDeclaration: function() { var elementFns = []; if (this.peekToken().text !== ']') { do { if (this.peek(']')) { // Support trailing commas per ES5.1. break; } elementFns.push(this.expression()); } while (this.expect(',')); } this.consume(']'); return extend(function $parseArrayLiteral(self, locals) { var array = []; for (var i = 0, ii = elementFns.length; i < ii; i++) { array.push(elementFns[i](self, locals)); } return array; }, { literal: true, constant: elementFns.every(isConstant), inputs: elementFns }); }, object: function() { var keys = [], valueFns = []; if (this.peekToken().text !== '}') { do { if (this.peek('}')) { // Support trailing commas per ES5.1. break; } var token = this.consume(); if (token.constant) { keys.push(token.value); } else if (token.identifier) { keys.push(token.text); } else { this.throwError("invalid key", token); } this.consume(':'); valueFns.push(this.expression()); } while (this.expect(',')); } this.consume('}'); return extend(function $parseObjectLiteral(self, locals) { var object = {}; for (var i = 0, ii = valueFns.length; i < ii; i++) { object[keys[i]] = valueFns[i](self, locals); } return object; }, { literal: true, constant: valueFns.every(isConstant), inputs: valueFns }); } }; ////////////////////////////////////////////////// // Parser helper functions ////////////////////////////////////////////////// function setter(obj, locals, path, setValue, fullExp) { ensureSafeObject(obj, fullExp); ensureSafeObject(locals, fullExp); var element = path.split('.'), key; for (var i = 0; element.length > 1; i++) { key = ensureSafeMemberName(element.shift(), fullExp); var propertyObj = (i === 0 && locals && locals[key]) || obj[key]; if (!propertyObj) { propertyObj = {}; obj[key] = propertyObj; } obj = ensureSafeObject(propertyObj, fullExp); } key = ensureSafeMemberName(element.shift(), fullExp); ensureSafeObject(obj[key], fullExp); obj[key] = setValue; return setValue; } var getterFnCacheDefault = createMap(); var getterFnCacheExpensive = createMap(); function isPossiblyDangerousMemberName(name) { return name == 'constructor'; } /** * Implementation of the "Black Hole" variant from: * - http://jsperf.com/angularjs-parse-getter/4 * - http://jsperf.com/path-evaluation-simplified/7 */ function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, expensiveChecks) { ensureSafeMemberName(key0, fullExp); ensureSafeMemberName(key1, fullExp); ensureSafeMemberName(key2, fullExp); ensureSafeMemberName(key3, fullExp); ensureSafeMemberName(key4, fullExp); var eso = function(o) { return ensureSafeObject(o, fullExp); }; var eso0 = (expensiveChecks || isPossiblyDangerousMemberName(key0)) ? eso : identity; var eso1 = (expensiveChecks || isPossiblyDangerousMemberName(key1)) ? eso : identity; var eso2 = (expensiveChecks || isPossiblyDangerousMemberName(key2)) ? eso : identity; var eso3 = (expensiveChecks || isPossiblyDangerousMemberName(key3)) ? eso : identity; var eso4 = (expensiveChecks || isPossiblyDangerousMemberName(key4)) ? eso : identity; return function cspSafeGetter(scope, locals) { var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope; if (pathVal == null) return pathVal; pathVal = eso0(pathVal[key0]); if (!key1) return pathVal; if (pathVal == null) return undefined; pathVal = eso1(pathVal[key1]); if (!key2) return pathVal; if (pathVal == null) return undefined; pathVal = eso2(pathVal[key2]); if (!key3) return pathVal; if (pathVal == null) return undefined; pathVal = eso3(pathVal[key3]); if (!key4) return pathVal; if (pathVal == null) return undefined; pathVal = eso4(pathVal[key4]); return pathVal; }; } function getterFnWithEnsureSafeObject(fn, fullExpression) { return function(s, l) { return fn(s, l, ensureSafeObject, fullExpression); }; } function getterFn(path, options, fullExp) { var expensiveChecks = options.expensiveChecks; var getterFnCache = (expensiveChecks ? getterFnCacheExpensive : getterFnCacheDefault); var fn = getterFnCache[path]; if (fn) return fn; var pathKeys = path.split('.'), pathKeysLength = pathKeys.length; // http://jsperf.com/angularjs-parse-getter/6 if (options.csp) { if (pathKeysLength < 6) { fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp, expensiveChecks); } else { fn = function cspSafeGetter(scope, locals) { var i = 0, val; do { val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], fullExp, expensiveChecks)(scope, locals); locals = undefined; // clear after first iteration scope = val; } while (i < pathKeysLength); return val; }; } } else { var code = ''; if (expensiveChecks) { code += 's = eso(s, fe);\nl = eso(l, fe);\n'; } var needsEnsureSafeObject = expensiveChecks; forEach(pathKeys, function(key, index) { ensureSafeMemberName(key, fullExp); var lookupJs = (index // we simply dereference 's' on any .dot notation ? 's' // but if we are first then we check locals first, and if so read it first : '((l&&l.hasOwnProperty("' + key + '"))?l:s)') + '.' + key; if (expensiveChecks || isPossiblyDangerousMemberName(key)) { lookupJs = 'eso(' + lookupJs + ', fe)'; needsEnsureSafeObject = true; } code += 'if(s == null) return undefined;\n' + 's=' + lookupJs + ';\n'; }); code += 'return s;'; /* jshint -W054 */ var evaledFnGetter = new Function('s', 'l', 'eso', 'fe', code); // s=scope, l=locals, eso=ensureSafeObject /* jshint +W054 */ evaledFnGetter.toString = valueFn(code); if (needsEnsureSafeObject) { evaledFnGetter = getterFnWithEnsureSafeObject(evaledFnGetter, fullExp); } fn = evaledFnGetter; } fn.sharedGetter = true; fn.assign = function(self, value, locals) { return setter(self, locals, path, value, path); }; getterFnCache[path] = fn; return fn; } var objectValueOf = Object.prototype.valueOf; function getValueOf(value) { return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value); } /////////////////////////////////// /** * @ngdoc service * @name $parse * @kind function * * @description * * Converts Angular {@link guide/expression expression} into a function. * * ```js * var getter = $parse('user.name'); * var setter = getter.assign; * var context = {user:{name:'angular'}}; * var locals = {user:{name:'local'}}; * * expect(getter(context)).toEqual('angular'); * setter(context, 'newValue'); * expect(context.user.name).toEqual('newValue'); * expect(getter(context, locals)).toEqual('local'); * ``` * * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. * * The returned function also has the following properties: * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript * literal. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript * constant literals. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be * set to a function to change its value on the given context. * */ /** * @ngdoc provider * @name $parseProvider * * @description * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse} * service. */ function $ParseProvider() { var cacheDefault = createMap(); var cacheExpensive = createMap(); this.$get = ['$filter', '$sniffer', function($filter, $sniffer) { var $parseOptions = { csp: $sniffer.csp, expensiveChecks: false }, $parseOptionsExpensive = { csp: $sniffer.csp, expensiveChecks: true }; function wrapSharedExpression(exp) { var wrapped = exp; if (exp.sharedGetter) { wrapped = function $parseWrapper(self, locals) { return exp(self, locals); }; wrapped.literal = exp.literal; wrapped.constant = exp.constant; wrapped.assign = exp.assign; } return wrapped; } return function $parse(exp, interceptorFn, expensiveChecks) { var parsedExpression, oneTime, cacheKey; switch (typeof exp) { case 'string': cacheKey = exp = exp.trim(); var cache = (expensiveChecks ? cacheExpensive : cacheDefault); parsedExpression = cache[cacheKey]; if (!parsedExpression) { if (exp.charAt(0) === ':' && exp.charAt(1) === ':') { oneTime = true; exp = exp.substring(2); } var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions; var lexer = new Lexer(parseOptions); var parser = new Parser(lexer, $filter, parseOptions); parsedExpression = parser.parse(exp); if (parsedExpression.constant) { parsedExpression.$$watchDelegate = constantWatchDelegate; } else if (oneTime) { //oneTime is not part of the exp passed to the Parser so we may have to //wrap the parsedExpression before adding a $$watchDelegate parsedExpression = wrapSharedExpression(parsedExpression); parsedExpression.$$watchDelegate = parsedExpression.literal ? oneTimeLiteralWatchDelegate : oneTimeWatchDelegate; } else if (parsedExpression.inputs) { parsedExpression.$$watchDelegate = inputsWatchDelegate; } cache[cacheKey] = parsedExpression; } return addInterceptor(parsedExpression, interceptorFn); case 'function': return addInterceptor(exp, interceptorFn); default: return addInterceptor(noop, interceptorFn); } }; function collectExpressionInputs(inputs, list) { for (var i = 0, ii = inputs.length; i < ii; i++) { var input = inputs[i]; if (!input.constant) { if (input.inputs) { collectExpressionInputs(input.inputs, list); } else if (list.indexOf(input) === -1) { // TODO(perf) can we do better? list.push(input); } } } return list; } function expressionInputDirtyCheck(newValue, oldValueOfValue) { if (newValue == null || oldValueOfValue == null) { // null/undefined return newValue === oldValueOfValue; } if (typeof newValue === 'object') { // attempt to convert the value to a primitive type // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can // be cheaply dirty-checked newValue = getValueOf(newValue); if (typeof newValue === 'object') { // objects/arrays are not supported - deep-watching them would be too expensive return false; } // fall-through to the primitive equality check } //Primitive or NaN return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue); } function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression) { var inputExpressions = parsedExpression.$$inputs || (parsedExpression.$$inputs = collectExpressionInputs(parsedExpression.inputs, [])); var lastResult; if (inputExpressions.length === 1) { var oldInputValue = expressionInputDirtyCheck; // init to something unique so that equals check fails inputExpressions = inputExpressions[0]; return scope.$watch(function expressionInputWatch(scope) { var newInputValue = inputExpressions(scope); if (!expressionInputDirtyCheck(newInputValue, oldInputValue)) { lastResult = parsedExpression(scope); oldInputValue = newInputValue && getValueOf(newInputValue); } return lastResult; }, listener, objectEquality); } var oldInputValueOfValues = []; for (var i = 0, ii = inputExpressions.length; i < ii; i++) { oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails } return scope.$watch(function expressionInputsWatch(scope) { var changed = false; for (var i = 0, ii = inputExpressions.length; i < ii; i++) { var newInputValue = inputExpressions[i](scope); if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) { oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue); } } if (changed) { lastResult = parsedExpression(scope); } return lastResult; }, listener, objectEquality); } function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) { var unwatch, lastValue; return unwatch = scope.$watch(function oneTimeWatch(scope) { return parsedExpression(scope); }, function oneTimeListener(value, old, scope) { lastValue = value; if (isFunction(listener)) { listener.apply(this, arguments); } if (isDefined(value)) { scope.$$postDigest(function() { if (isDefined(lastValue)) { unwatch(); } }); } }, objectEquality); } function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) { var unwatch, lastValue; return unwatch = scope.$watch(function oneTimeWatch(scope) { return parsedExpression(scope); }, function oneTimeListener(value, old, scope) { lastValue = value; if (isFunction(listener)) { listener.call(this, value, old, scope); } if (isAllDefined(value)) { scope.$$postDigest(function() { if (isAllDefined(lastValue)) unwatch(); }); } }, objectEquality); function isAllDefined(value) { var allDefined = true; forEach(value, function(val) { if (!isDefined(val)) allDefined = false; }); return allDefined; } } function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) { var unwatch; return unwatch = scope.$watch(function constantWatch(scope) { return parsedExpression(scope); }, function constantListener(value, old, scope) { if (isFunction(listener)) { listener.apply(this, arguments); } unwatch(); }, objectEquality); } function addInterceptor(parsedExpression, interceptorFn) { if (!interceptorFn) return parsedExpression; var watchDelegate = parsedExpression.$$watchDelegate; var regularWatch = watchDelegate !== oneTimeLiteralWatchDelegate && watchDelegate !== oneTimeWatchDelegate; var fn = regularWatch ? function regularInterceptedExpression(scope, locals) { var value = parsedExpression(scope, locals); return interceptorFn(value, scope, locals); } : function oneTimeInterceptedExpression(scope, locals) { var value = parsedExpression(scope, locals); var result = interceptorFn(value, scope, locals); // we only return the interceptor's result if the // initial value is defined (for bind-once) return isDefined(value) ? result : value; }; // Propagate $$watchDelegates other then inputsWatchDelegate if (parsedExpression.$$watchDelegate && parsedExpression.$$watchDelegate !== inputsWatchDelegate) { fn.$$watchDelegate = parsedExpression.$$watchDelegate; } else if (!interceptorFn.$stateful) { // If there is an interceptor, but no watchDelegate then treat the interceptor like // we treat filters - it is assumed to be a pure function unless flagged with $stateful fn.$$watchDelegate = inputsWatchDelegate; fn.inputs = [parsedExpression]; } return fn; } }]; } /** * @ngdoc service * @name $q * @requires $rootScope * * @description * A service that helps you run functions asynchronously, and use their return values (or exceptions) * when they are done processing. * * This is an implementation of promises/deferred objects inspired by * [Kris Kowal's Q](https://github.com/kriskowal/q). * * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred * implementations, and the other which resembles ES6 promises to some degree. * * # $q constructor * * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver` * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony, * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). * * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are * available yet. * * It can be used like so: * * ```js * // for the purpose of this example let's assume that variables `$q` and `okToGreet` * // are available in the current lexical scope (they could have been injected or passed in). * * function asyncGreet(name) { * // perform some asynchronous operation, resolve or reject the promise when appropriate. * return $q(function(resolve, reject) { * setTimeout(function() { * if (okToGreet(name)) { * resolve('Hello, ' + name + '!'); * } else { * reject('Greeting ' + name + ' is not allowed.'); * } * }, 1000); * }); * } * * var promise = asyncGreet('Robin Hood'); * promise.then(function(greeting) { * alert('Success: ' + greeting); * }, function(reason) { * alert('Failed: ' + reason); * }); * ``` * * Note: progress/notify callbacks are not currently supported via the ES6-style interface. * * However, the more traditional CommonJS-style usage is still available, and documented below. * * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an * interface for interacting with an object that represents the result of an action that is * performed asynchronously, and may or may not be finished at any given point in time. * * From the perspective of dealing with error handling, deferred and promise APIs are to * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming. * * ```js * // for the purpose of this example let's assume that variables `$q` and `okToGreet` * // are available in the current lexical scope (they could have been injected or passed in). * * function asyncGreet(name) { * var deferred = $q.defer(); * * setTimeout(function() { * deferred.notify('About to greet ' + name + '.'); * * if (okToGreet(name)) { * deferred.resolve('Hello, ' + name + '!'); * } else { * deferred.reject('Greeting ' + name + ' is not allowed.'); * } * }, 1000); * * return deferred.promise; * } * * var promise = asyncGreet('Robin Hood'); * promise.then(function(greeting) { * alert('Success: ' + greeting); * }, function(reason) { * alert('Failed: ' + reason); * }, function(update) { * alert('Got notification: ' + update); * }); * ``` * * At first it might not be obvious why this extra complexity is worth the trouble. The payoff * comes in the way of guarantees that promise and deferred APIs make, see * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md. * * Additionally the promise api allows for composition that is very hard to do with the * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the * section on serial or parallel joining of promises. * * # The Deferred API * * A new instance of deferred is constructed by calling `$q.defer()`. * * The purpose of the deferred object is to expose the associated Promise instance as well as APIs * that can be used for signaling the successful or unsuccessful completion, as well as the status * of the task. * * **Methods** * * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection * constructed via `$q.reject`, the promise will be rejected instead. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to * resolving it with a rejection constructed via `$q.reject`. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called * multiple times before the promise is either resolved or rejected. * * **Properties** * * - promise – `{Promise}` – promise object associated with this deferred. * * * # The Promise API * * A new promise instance is created when a deferred instance is created and can be retrieved by * calling `deferred.promise`. * * The purpose of the promise object is to allow for interested parties to get access to the result * of the deferred task when it completes. * * **Methods** * * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously * as soon as the result is available. The callbacks are called with a single argument: the result * or rejection reason. Additionally, the notify callback may be called zero or more times to * provide a progress indication, before the promise is resolved or rejected. * * This method *returns a new promise* which is resolved or rejected via the return value of the * `successCallback`, `errorCallback`. It also notifies via the return value of the * `notifyCallback` method. The promise cannot be resolved or rejected from the notifyCallback * method. * * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)` * * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise, * but to do so without modifying the final value. This is useful to release resources or do some * clean-up that needs to be done whether the promise was rejected or resolved. See the [full * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for * more information. * * # Chaining promises * * Because calling the `then` method of a promise returns a new derived promise, it is easily * possible to create a chain of promises: * * ```js * promiseB = promiseA.then(function(result) { * return result + 1; * }); * * // promiseB will be resolved immediately after promiseA is resolved and its value * // will be the result of promiseA incremented by 1 * ``` * * It is possible to create chains of any length and since a promise can be resolved with another * promise (which will defer its resolution further), it is possible to pause/defer resolution of * the promises at any point in the chain. This makes it possible to implement powerful APIs like * $http's response interceptors. * * * # Differences between Kris Kowal's Q and $q * * There are two main differences: * * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation * mechanism in angular, which means faster propagation of resolution or rejection into your * models and avoiding unnecessary browser repaints, which would result in flickering UI. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains * all the important functionality needed for common async tasks. * * # Testing * * ```js * it('should simulate promise', inject(function($q, $rootScope) { * var deferred = $q.defer(); * var promise = deferred.promise; * var resolvedValue; * * promise.then(function(value) { resolvedValue = value; }); * expect(resolvedValue).toBeUndefined(); * * // Simulate resolving of promise * deferred.resolve(123); * // Note that the 'then' function does not get called synchronously. * // This is because we want the promise API to always be async, whether or not * // it got called synchronously or asynchronously. * expect(resolvedValue).toBeUndefined(); * * // Propagate promise resolution to 'then' functions using $apply(). * $rootScope.$apply(); * expect(resolvedValue).toEqual(123); * })); * ``` * * @param {function(function, function)} resolver Function which is responsible for resolving or * rejecting the newly created promise. The first parameter is a function which resolves the * promise, the second parameter is a function which rejects the promise. * * @returns {Promise} The newly created promise. */ function $QProvider() { this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { return qFactory(function(callback) { $rootScope.$evalAsync(callback); }, $exceptionHandler); }]; } function $$QProvider() { this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) { return qFactory(function(callback) { $browser.defer(callback); }, $exceptionHandler); }]; } /** * Constructs a promise manager. * * @param {function(function)} nextTick Function for executing functions in the next turn. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for * debugging purposes. * @returns {object} Promise manager. */ function qFactory(nextTick, exceptionHandler) { var $qMinErr = minErr('$q', TypeError); function callOnce(self, resolveFn, rejectFn) { var called = false; function wrap(fn) { return function(value) { if (called) return; called = true; fn.call(self, value); }; } return [wrap(resolveFn), wrap(rejectFn)]; } /** * @ngdoc method * @name ng.$q#defer * @kind function * * @description * Creates a `Deferred` object which represents a task which will finish in the future. * * @returns {Deferred} Returns a new instance of deferred. */ var defer = function() { return new Deferred(); }; function Promise() { this.$$state = { status: 0 }; } Promise.prototype = { then: function(onFulfilled, onRejected, progressBack) { var result = new Deferred(); this.$$state.pending = this.$$state.pending || []; this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]); if (this.$$state.status > 0) scheduleProcessQueue(this.$$state); return result.promise; }, "catch": function(callback) { return this.then(null, callback); }, "finally": function(callback, progressBack) { return this.then(function(value) { return handleCallback(value, true, callback); }, function(error) { return handleCallback(error, false, callback); }, progressBack); } }; //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native function simpleBind(context, fn) { return function(value) { fn.call(context, value); }; } function processQueue(state) { var fn, promise, pending; pending = state.pending; state.processScheduled = false; state.pending = undefined; for (var i = 0, ii = pending.length; i < ii; ++i) { promise = pending[i][0]; fn = pending[i][state.status]; try { if (isFunction(fn)) { promise.resolve(fn(state.value)); } else if (state.status === 1) { promise.resolve(state.value); } else { promise.reject(state.value); } } catch (e) { promise.reject(e); exceptionHandler(e); } } } function scheduleProcessQueue(state) { if (state.processScheduled || !state.pending) return; state.processScheduled = true; nextTick(function() { processQueue(state); }); } function Deferred() { this.promise = new Promise(); //Necessary to support unbound execution :/ this.resolve = simpleBind(this, this.resolve); this.reject = simpleBind(this, this.reject); this.notify = simpleBind(this, this.notify); } Deferred.prototype = { resolve: function(val) { if (this.promise.$$state.status) return; if (val === this.promise) { this.$$reject($qMinErr( 'qcycle', "Expected promise to be resolved with value other than itself '{0}'", val)); } else { this.$$resolve(val); } }, $$resolve: function(val) { var then, fns; fns = callOnce(this, this.$$resolve, this.$$reject); try { if ((isObject(val) || isFunction(val))) then = val && val.then; if (isFunction(then)) { this.promise.$$state.status = -1; then.call(val, fns[0], fns[1], this.notify); } else { this.promise.$$state.value = val; this.promise.$$state.status = 1; scheduleProcessQueue(this.promise.$$state); } } catch (e) { fns[1](e); exceptionHandler(e); } }, reject: function(reason) { if (this.promise.$$state.status) return; this.$$reject(reason); }, $$reject: function(reason) { this.promise.$$state.value = reason; this.promise.$$state.status = 2; scheduleProcessQueue(this.promise.$$state); }, notify: function(progress) { var callbacks = this.promise.$$state.pending; if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) { nextTick(function() { var callback, result; for (var i = 0, ii = callbacks.length; i < ii; i++) { result = callbacks[i][0]; callback = callbacks[i][3]; try { result.notify(isFunction(callback) ? callback(progress) : progress); } catch (e) { exceptionHandler(e); } } }); } } }; /** * @ngdoc method * @name $q#reject * @kind function * * @description * Creates a promise that is resolved as rejected with the specified `reason`. This api should be * used to forward rejection in a chain of promises. If you are dealing with the last promise in * a promise chain, you don't need to worry about it. * * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via * a promise error callback and you want to forward the error to the promise derived from the * current promise, you have to "rethrow" the error by returning a rejection constructed via * `reject`. * * ```js * promiseB = promiseA.then(function(result) { * // success: do something and resolve promiseB * // with the old or a new result * return result; * }, function(reason) { * // error: handle the error if possible and * // resolve promiseB with newPromiseOrValue, * // otherwise forward the rejection to promiseB * if (canHandle(reason)) { * // handle the error and recover * return newPromiseOrValue; * } * return $q.reject(reason); * }); * ``` * * @param {*} reason Constant, message, exception or an object representing the rejection reason. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. */ var reject = function(reason) { var result = new Deferred(); result.reject(reason); return result.promise; }; var makePromise = function makePromise(value, resolved) { var result = new Deferred(); if (resolved) { result.resolve(value); } else { result.reject(value); } return result.promise; }; var handleCallback = function handleCallback(value, isResolved, callback) { var callbackOutput = null; try { if (isFunction(callback)) callbackOutput = callback(); } catch (e) { return makePromise(e, false); } if (isPromiseLike(callbackOutput)) { return callbackOutput.then(function() { return makePromise(value, isResolved); }, function(error) { return makePromise(error, false); }); } else { return makePromise(value, isResolved); } }; /** * @ngdoc method * @name $q#when * @kind function * * @description * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. * This is useful when you are dealing with an object that might or might not be a promise, or if * the promise comes from a source that can't be trusted. * * @param {*} value Value or a promise * @returns {Promise} Returns a promise of the passed value or promise */ var when = function(value, callback, errback, progressBack) { var result = new Deferred(); result.resolve(value); return result.promise.then(callback, errback, progressBack); }; /** * @ngdoc method * @name $q#all * @kind function * * @description * Combines multiple promises into a single promise that is resolved when all of the input * promises are resolved. * * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values, * each value corresponding to the promise at the same index/key in the `promises` array/hash. * If any of the promises is resolved with a rejection, this resulting promise will be rejected * with the same rejection value. */ function all(promises) { var deferred = new Deferred(), counter = 0, results = isArray(promises) ? [] : {}; forEach(promises, function(promise, key) { counter++; when(promise).then(function(value) { if (results.hasOwnProperty(key)) return; results[key] = value; if (!(--counter)) deferred.resolve(results); }, function(reason) { if (results.hasOwnProperty(key)) return; deferred.reject(reason); }); }); if (counter === 0) { deferred.resolve(results); } return deferred.promise; } var $Q = function Q(resolver) { if (!isFunction(resolver)) { throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver); } if (!(this instanceof Q)) { // More useful when $Q is the Promise itself. return new Q(resolver); } var deferred = new Deferred(); function resolveFn(value) { deferred.resolve(value); } function rejectFn(reason) { deferred.reject(reason); } resolver(resolveFn, rejectFn); return deferred.promise; }; $Q.defer = defer; $Q.reject = reject; $Q.when = when; $Q.all = all; return $Q; } function $$RAFProvider() { //rAF this.$get = ['$window', '$timeout', function($window, $timeout) { var requestAnimationFrame = $window.requestAnimationFrame || $window.webkitRequestAnimationFrame; var cancelAnimationFrame = $window.cancelAnimationFrame || $window.webkitCancelAnimationFrame || $window.webkitCancelRequestAnimationFrame; var rafSupported = !!requestAnimationFrame; var raf = rafSupported ? function(fn) { var id = requestAnimationFrame(fn); return function() { cancelAnimationFrame(id); }; } : function(fn) { var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666 return function() { $timeout.cancel(timer); }; }; raf.supported = rafSupported; return raf; }]; } /** * DESIGN NOTES * * The design decisions behind the scope are heavily favored for speed and memory consumption. * * The typical use of scope is to watch the expressions, which most of the time return the same * value as last time so we optimize the operation. * * Closures construction is expensive in terms of speed as well as memory: * - No closures, instead use prototypical inheritance for API * - Internal state needs to be stored on scope directly, which means that private state is * exposed as $$____ properties * * Loop operations are optimized by using while(count--) { ... } * - this means that in order to keep the same order of execution as addition we have to add * items to the array at the beginning (unshift) instead of at the end (push) * * Child scopes are created and removed often * - Using an array would be slow since inserts in middle are expensive so we use linked list * * There are few watches then a lot of observers. This is why you don't want the observer to be * implemented in the same way as watch. Watch requires return of initialization function which * are expensive to construct. */ /** * @ngdoc provider * @name $rootScopeProvider * @description * * Provider for the $rootScope service. */ /** * @ngdoc method * @name $rootScopeProvider#digestTtl * @description * * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and * assuming that the model is unstable. * * The current default is 10 iterations. * * In complex applications it's possible that the dependencies between `$watch`s will result in * several digest iterations. However if an application needs more than the default 10 digest * iterations for its model to stabilize then you should investigate what is causing the model to * continuously change during the digest. * * Increasing the TTL could have performance implications, so you should not change it without * proper justification. * * @param {number} limit The number of digest iterations. */ /** * @ngdoc service * @name $rootScope * @description * * Every application has a single root {@link ng.$rootScope.Scope scope}. * All other scopes are descendant scopes of the root scope. Scopes provide separation * between the model and the view, via a mechanism for watching the model for changes. * They also provide an event emission/broadcast and subscription facility. See the * {@link guide/scope developer guide on scopes}. */ function $RootScopeProvider() { var TTL = 10; var $rootScopeMinErr = minErr('$rootScope'); var lastDirtyWatch = null; var applyAsyncId = null; this.digestTtl = function(value) { if (arguments.length) { TTL = value; } return TTL; }; this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser', function($injector, $exceptionHandler, $parse, $browser) { /** * @ngdoc type * @name $rootScope.Scope * * @description * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the * {@link auto.$injector $injector}. Child scopes are created using the * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when * compiled HTML template is executed.) * * Here is a simple scope snippet to show how you can interact with the scope. * ```html * <file src="./test/ng/rootScopeSpec.js" tag="docs1" /> * ``` * * # Inheritance * A scope can inherit from a parent scope, as in this example: * ```js var parent = $rootScope; var child = parent.$new(); parent.salutation = "Hello"; expect(child.salutation).toEqual('Hello'); child.salutation = "Welcome"; expect(child.salutation).toEqual('Welcome'); expect(parent.salutation).toEqual('Hello'); * ``` * * When interacting with `Scope` in tests, additional helper methods are available on the * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional * details. * * * @param {Object.<string, function()>=} providers Map of service factory which need to be * provided for the current scope. Defaults to {@link ng}. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should * append/override services provided by `providers`. This is handy * when unit-testing and having the need to override a default * service. * @returns {Object} Newly created scope. * */ function Scope() { this.$id = nextUid(); this.$$phase = this.$parent = this.$$watchers = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = null; this.$root = this; this.$$destroyed = false; this.$$listeners = {}; this.$$listenerCount = {}; this.$$isolateBindings = null; } /** * @ngdoc property * @name $rootScope.Scope#$id * * @description * Unique scope ID (monotonically increasing) useful for debugging. */ /** * @ngdoc property * @name $rootScope.Scope#$parent * * @description * Reference to the parent scope. */ /** * @ngdoc property * @name $rootScope.Scope#$root * * @description * Reference to the root scope. */ Scope.prototype = { constructor: Scope, /** * @ngdoc method * @name $rootScope.Scope#$new * @kind function * * @description * Creates a new child {@link ng.$rootScope.Scope scope}. * * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. * * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is * desired for the scope and its child scopes to be permanently detached from the parent and * thus stop participating in model change detection and listener notification by invoking. * * @param {boolean} isolate If true, then the scope does not prototypically inherit from the * parent scope. The scope is isolated, as it can not see parent scope properties. * When creating widgets, it is useful for the widget to not accidentally read parent * state. * * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent` * of the newly created scope. Defaults to `this` scope if not provided. * This is used when creating a transclude scope to correctly place it * in the scope hierarchy while maintaining the correct prototypical * inheritance. * * @returns {Object} The newly created child scope. * */ $new: function(isolate, parent) { var child; parent = parent || this; if (isolate) { child = new Scope(); child.$root = this.$root; } else { // Only create a child scope class if somebody asks for one, // but cache it to allow the VM to optimize lookups. if (!this.$$ChildScope) { this.$$ChildScope = function ChildScope() { this.$$watchers = this.$$nextSibling = this.$$childHead = this.$$childTail = null; this.$$listeners = {}; this.$$listenerCount = {}; this.$id = nextUid(); this.$$ChildScope = null; }; this.$$ChildScope.prototype = this; } child = new this.$$ChildScope(); } child.$parent = parent; child.$$prevSibling = parent.$$childTail; if (parent.$$childHead) { parent.$$childTail.$$nextSibling = child; parent.$$childTail = child; } else { parent.$$childHead = parent.$$childTail = child; } // When the new scope is not isolated or we inherit from `this`, and // the parent scope is destroyed, the property `$$destroyed` is inherited // prototypically. In all other cases, this property needs to be set // when the parent scope is destroyed. // The listener needs to be added after the parent is set if (isolate || parent != this) child.$on('$destroy', destroyChild); return child; function destroyChild() { child.$$destroyed = true; } }, /** * @ngdoc method * @name $rootScope.Scope#$watch * @kind function * * @description * Registers a `listener` callback to be executed whenever the `watchExpression` changes. * * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest * $digest()} and should return the value that will be watched. (Since * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the * `watchExpression` can execute multiple times per * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.) * - The `listener` is called only when the value from the current `watchExpression` and the * previous call to `watchExpression` are not equal (with the exception of the initial run, * see below). Inequality is determined according to reference inequality, * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators) * via the `!==` Javascript operator, unless `objectEquality == true` * (see next point) * - When `objectEquality == true`, inequality of the `watchExpression` is determined * according to the {@link angular.equals} function. To save the value of the object for * later comparison, the {@link angular.copy} function is used. This therefore means that * watching complex objects will have adverse memory and performance implications. * - The watch `listener` may change the model, which may trigger other `listener`s to fire. * This is achieved by rerunning the watchers until no changes are detected. The rerun * iteration limit is 10 to prevent an infinite loop deadlock. * * * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, * you can register a `watchExpression` function with no `listener`. (Since `watchExpression` * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a * change is detected, be prepared for multiple calls to your listener.) * * After a watcher is registered with the scope, the `listener` fn is called asynchronously * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the * watcher. In rare cases, this is undesirable because the listener is called when the result * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the * listener was called due to initialization. * * * * # Example * ```js // let's assume that scope was dependency injected as the $rootScope var scope = $rootScope; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // the listener is always called during the first $digest loop after it was registered expect(scope.counter).toEqual(1); scope.$digest(); // but now it will not be called unless the value changes expect(scope.counter).toEqual(1); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(2); // Using a function as a watchExpression var food; scope.foodCounter = 0; expect(scope.foodCounter).toEqual(0); scope.$watch( // This function returns the value being watched. It is called for each turn of the $digest loop function() { return food; }, // This is the change listener, called when the value returned from the above function changes function(newValue, oldValue) { if ( newValue !== oldValue ) { // Only increment the counter if the value changed scope.foodCounter = scope.foodCounter + 1; } } ); // No digest has been run so the counter will be zero expect(scope.foodCounter).toEqual(0); // Run the digest but since food has not changed count will still be zero scope.$digest(); expect(scope.foodCounter).toEqual(0); // Update food and run digest. Now the counter will increment food = 'cheeseburger'; scope.$digest(); expect(scope.foodCounter).toEqual(1); * ``` * * * * @param {(function()|string)} watchExpression Expression that is evaluated on each * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers * a call to the `listener`. * * - `string`: Evaluated as {@link guide/expression expression} * - `function(scope)`: called with current `scope` as a parameter. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value * of `watchExpression` changes. * * - `newVal` contains the current value of the `watchExpression` * - `oldVal` contains the previous value of the `watchExpression` * - `scope` refers to the current scope * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of * comparing for reference equality. * @returns {function()} Returns a deregistration function for this listener. */ $watch: function(watchExp, listener, objectEquality) { var get = $parse(watchExp); if (get.$$watchDelegate) { return get.$$watchDelegate(this, listener, objectEquality, get); } var scope = this, array = scope.$$watchers, watcher = { fn: listener, last: initWatchVal, get: get, exp: watchExp, eq: !!objectEquality }; lastDirtyWatch = null; if (!isFunction(listener)) { watcher.fn = noop; } if (!array) { array = scope.$$watchers = []; } // we use unshift since we use a while loop in $digest for speed. // the while loop reads in reverse order. array.unshift(watcher); return function deregisterWatch() { arrayRemove(array, watcher); lastDirtyWatch = null; }; }, /** * @ngdoc method * @name $rootScope.Scope#$watchGroup * @kind function * * @description * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`. * If any one expression in the collection changes the `listener` is executed. * * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every * call to $digest() to see if any items changes. * - The `listener` is called whenever any expression in the `watchExpressions` array changes. * * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually * watched using {@link ng.$rootScope.Scope#$watch $watch()} * * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any * expression in `watchExpressions` changes * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching * those of `watchExpression` * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching * those of `watchExpression` * The `scope` refers to the current scope. * @returns {function()} Returns a de-registration function for all listeners. */ $watchGroup: function(watchExpressions, listener) { var oldValues = new Array(watchExpressions.length); var newValues = new Array(watchExpressions.length); var deregisterFns = []; var self = this; var changeReactionScheduled = false; var firstRun = true; if (!watchExpressions.length) { // No expressions means we call the listener ASAP var shouldCall = true; self.$evalAsync(function() { if (shouldCall) listener(newValues, newValues, self); }); return function deregisterWatchGroup() { shouldCall = false; }; } if (watchExpressions.length === 1) { // Special case size of one return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) { newValues[0] = value; oldValues[0] = oldValue; listener(newValues, (value === oldValue) ? newValues : oldValues, scope); }); } forEach(watchExpressions, function(expr, i) { var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) { newValues[i] = value; oldValues[i] = oldValue; if (!changeReactionScheduled) { changeReactionScheduled = true; self.$evalAsync(watchGroupAction); } }); deregisterFns.push(unwatchFn); }); function watchGroupAction() { changeReactionScheduled = false; if (firstRun) { firstRun = false; listener(newValues, newValues, self); } else { listener(newValues, oldValues, self); } } return function deregisterWatchGroup() { while (deregisterFns.length) { deregisterFns.shift()(); } }; }, /** * @ngdoc method * @name $rootScope.Scope#$watchCollection * @kind function * * @description * Shallow watches the properties of an object and fires whenever any of the properties change * (for arrays, this implies watching the array items; for object maps, this implies watching * the properties). If a change is detected, the `listener` callback is fired. * * - The `obj` collection is observed via standard $watch operation and is examined on every * call to $digest() to see if any items have been added, removed, or moved. * - The `listener` is called whenever anything within the `obj` has changed. Examples include * adding, removing, and moving items belonging to an object or array. * * * # Example * ```js $scope.names = ['igor', 'matias', 'misko', 'james']; $scope.dataCount = 4; $scope.$watchCollection('names', function(newNames, oldNames) { $scope.dataCount = newNames.length; }); expect($scope.dataCount).toEqual(4); $scope.$digest(); //still at 4 ... no changes expect($scope.dataCount).toEqual(4); $scope.names.pop(); $scope.$digest(); //now there's been a change expect($scope.dataCount).toEqual(3); * ``` * * * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The * expression value should evaluate to an object or an array which is observed on each * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the * collection will trigger a call to the `listener`. * * @param {function(newCollection, oldCollection, scope)} listener a callback function called * when a change is detected. * - The `newCollection` object is the newly modified data obtained from the `obj` expression * - The `oldCollection` object is a copy of the former collection data. * Due to performance considerations, the`oldCollection` value is computed only if the * `listener` function declares two or more arguments. * - The `scope` argument refers to the current scope. * * @returns {function()} Returns a de-registration function for this listener. When the * de-registration function is executed, the internal watch operation is terminated. */ $watchCollection: function(obj, listener) { $watchCollectionInterceptor.$stateful = true; var self = this; // the current value, updated on each dirty-check run var newValue; // a shallow copy of the newValue from the last dirty-check run, // updated to match newValue during dirty-check run var oldValue; // a shallow copy of the newValue from when the last change happened var veryOldValue; // only track veryOldValue if the listener is asking for it var trackVeryOldValue = (listener.length > 1); var changeDetected = 0; var changeDetector = $parse(obj, $watchCollectionInterceptor); var internalArray = []; var internalObject = {}; var initRun = true; var oldLength = 0; function $watchCollectionInterceptor(_value) { newValue = _value; var newLength, key, bothNaN, newItem, oldItem; // If the new value is undefined, then return undefined as the watch may be a one-time watch if (isUndefined(newValue)) return; if (!isObject(newValue)) { // if primitive if (oldValue !== newValue) { oldValue = newValue; changeDetected++; } } else if (isArrayLike(newValue)) { if (oldValue !== internalArray) { // we are transitioning from something which was not an array into array. oldValue = internalArray; oldLength = oldValue.length = 0; changeDetected++; } newLength = newValue.length; if (oldLength !== newLength) { // if lengths do not match we need to trigger change notification changeDetected++; oldValue.length = oldLength = newLength; } // copy the items to oldValue and look for changes. for (var i = 0; i < newLength; i++) { oldItem = oldValue[i]; newItem = newValue[i]; bothNaN = (oldItem !== oldItem) && (newItem !== newItem); if (!bothNaN && (oldItem !== newItem)) { changeDetected++; oldValue[i] = newItem; } } } else { if (oldValue !== internalObject) { // we are transitioning from something which was not an object into object. oldValue = internalObject = {}; oldLength = 0; changeDetected++; } // copy the items to oldValue and look for changes. newLength = 0; for (key in newValue) { if (newValue.hasOwnProperty(key)) { newLength++; newItem = newValue[key]; oldItem = oldValue[key]; if (key in oldValue) { bothNaN = (oldItem !== oldItem) && (newItem !== newItem); if (!bothNaN && (oldItem !== newItem)) { changeDetected++; oldValue[key] = newItem; } } else { oldLength++; oldValue[key] = newItem; changeDetected++; } } } if (oldLength > newLength) { // we used to have more keys, need to find them and destroy them. changeDetected++; for (key in oldValue) { if (!newValue.hasOwnProperty(key)) { oldLength--; delete oldValue[key]; } } } } return changeDetected; } function $watchCollectionAction() { if (initRun) { initRun = false; listener(newValue, newValue, self); } else { listener(newValue, veryOldValue, self); } // make a copy for the next time a collection is changed if (trackVeryOldValue) { if (!isObject(newValue)) { //primitive veryOldValue = newValue; } else if (isArrayLike(newValue)) { veryOldValue = new Array(newValue.length); for (var i = 0; i < newValue.length; i++) { veryOldValue[i] = newValue[i]; } } else { // if object veryOldValue = {}; for (var key in newValue) { if (hasOwnProperty.call(newValue, key)) { veryOldValue[key] = newValue[key]; } } } } } return this.$watch(changeDetector, $watchCollectionAction); }, /** * @ngdoc method * @name $rootScope.Scope#$digest * @kind function * * @description * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} * until no more listeners are firing. This means that it is possible to get into an infinite * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of * iterations exceeds 10. * * Usually, you don't call `$digest()` directly in * {@link ng.directive:ngController controllers} or in * {@link ng.$compileProvider#directive directives}. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`. * * If you want to be notified whenever `$digest()` is called, * you can register a `watchExpression` function with * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`. * * In unit tests, you may need to call `$digest()` to simulate the scope life cycle. * * # Example * ```js var scope = ...; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // the listener is always called during the first $digest loop after it was registered expect(scope.counter).toEqual(1); scope.$digest(); // but now it will not be called unless the value changes expect(scope.counter).toEqual(1); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(2); * ``` * */ $digest: function() { var watch, value, last, watchers, length, dirty, ttl = TTL, next, current, target = this, watchLog = [], logIdx, logMsg, asyncTask; beginPhase('$digest'); // Check for changes to browser url that happened in sync before the call to $digest $browser.$$checkUrlChange(); if (this === $rootScope && applyAsyncId !== null) { // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then // cancel the scheduled $apply and flush the queue of expressions to be evaluated. $browser.defer.cancel(applyAsyncId); flushApplyAsync(); } lastDirtyWatch = null; do { // "while dirty" loop dirty = false; current = target; while (asyncQueue.length) { try { asyncTask = asyncQueue.shift(); asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals); } catch (e) { $exceptionHandler(e); } lastDirtyWatch = null; } traverseScopesLoop: do { // "traverse the scopes" loop if ((watchers = current.$$watchers)) { // process our watches length = watchers.length; while (length--) { try { watch = watchers[length]; // Most common watches are on primitives, in which case we can short // circuit it with === operator, only when === fails do we use .equals if (watch) { if ((value = watch.get(current)) !== (last = watch.last) && !(watch.eq ? equals(value, last) : (typeof value === 'number' && typeof last === 'number' && isNaN(value) && isNaN(last)))) { dirty = true; lastDirtyWatch = watch; watch.last = watch.eq ? copy(value, null) : value; watch.fn(value, ((last === initWatchVal) ? value : last), current); if (ttl < 5) { logIdx = 4 - ttl; if (!watchLog[logIdx]) watchLog[logIdx] = []; watchLog[logIdx].push({ msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp, newVal: value, oldVal: last }); } } else if (watch === lastDirtyWatch) { // If the most recently dirty watcher is now clean, short circuit since the remaining watchers // have already been tested. dirty = false; break traverseScopesLoop; } } } catch (e) { $exceptionHandler(e); } } } // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $broadcast if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while (current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); // `break traverseScopesLoop;` takes us to here if ((dirty || asyncQueue.length) && !(ttl--)) { clearPhase(); throw $rootScopeMinErr('infdig', '{0} $digest() iterations reached. Aborting!\n' + 'Watchers fired in the last 5 iterations: {1}', TTL, watchLog); } } while (dirty || asyncQueue.length); clearPhase(); while (postDigestQueue.length) { try { postDigestQueue.shift()(); } catch (e) { $exceptionHandler(e); } } }, /** * @ngdoc event * @name $rootScope.Scope#$destroy * @eventType broadcast on scope being destroyed * * @description * Broadcasted when a scope and its children are being destroyed. * * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to * clean up DOM bindings before an element is removed from the DOM. */ /** * @ngdoc method * @name $rootScope.Scope#$destroy * @kind function * * @description * Removes the current scope (and all of its children) from the parent scope. Removal implies * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer * propagate to the current scope and its children. Removal also implies that the current * scope is eligible for garbage collection. * * The `$destroy()` is usually used by directives such as * {@link ng.directive:ngRepeat ngRepeat} for managing the * unrolling of the loop. * * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope. * Application code can register a `$destroy` event handler that will give it a chance to * perform any necessary cleanup. * * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to * clean up DOM bindings before an element is removed from the DOM. */ $destroy: function() { // we can't destroy the root scope or a scope that has been already destroyed if (this.$$destroyed) return; var parent = this.$parent; this.$broadcast('$destroy'); this.$$destroyed = true; if (this === $rootScope) return; for (var eventName in this.$$listenerCount) { decrementListenerCount(this, this.$$listenerCount[eventName], eventName); } // sever all the references to parent scopes (after this cleanup, the current scope should // not be retained by any of our references and should be eligible for garbage collection) if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; // Disable listeners, watchers and apply/digest methods this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop; this.$on = this.$watch = this.$watchGroup = function() { return noop; }; this.$$listeners = {}; // All of the code below is bogus code that works around V8's memory leak via optimized code // and inline caches. // // see: // - https://code.google.com/p/v8/issues/detail?id=2073#c26 // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909 // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = this.$root = this.$$watchers = null; }, /** * @ngdoc method * @name $rootScope.Scope#$eval * @kind function * * @description * Executes the `expression` on the current scope and returns the result. Any exceptions in * the expression are propagated (uncaught). This is useful when evaluating Angular * expressions. * * # Example * ```js var scope = ng.$rootScope.Scope(); scope.a = 1; scope.b = 2; expect(scope.$eval('a+b')).toEqual(3); expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); * ``` * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * * @param {(object)=} locals Local variables object, useful for overriding values in scope. * @returns {*} The result of evaluating the expression. */ $eval: function(expr, locals) { return $parse(expr)(this, locals); }, /** * @ngdoc method * @name $rootScope.Scope#$evalAsync * @kind function * * @description * Executes the expression on the current scope at a later point in time. * * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only * that: * * - it will execute after the function that scheduled the evaluation (preferably before DOM * rendering). * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after * `expression` execution. * * Any exceptions from the execution of the expression are forwarded to the * {@link ng.$exceptionHandler $exceptionHandler} service. * * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle * will be scheduled. However, it is encouraged to always call code that changes the model * from within an `$apply` call. That includes code evaluated via `$evalAsync`. * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * * @param {(object)=} locals Local variables object, useful for overriding values in scope. */ $evalAsync: function(expr, locals) { // if we are outside of an $digest loop and this is the first time we are scheduling async // task also schedule async auto-flush if (!$rootScope.$$phase && !asyncQueue.length) { $browser.defer(function() { if (asyncQueue.length) { $rootScope.$digest(); } }); } asyncQueue.push({scope: this, expression: expr, locals: locals}); }, $$postDigest: function(fn) { postDigestQueue.push(fn); }, /** * @ngdoc method * @name $rootScope.Scope#$apply * @kind function * * @description * `$apply()` is used to execute an expression in angular from outside of the angular * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). * Because we are calling into the angular framework we need to perform proper scope life * cycle of {@link ng.$exceptionHandler exception handling}, * {@link ng.$rootScope.Scope#$digest executing watches}. * * ## Life cycle * * # Pseudo-Code of `$apply()` * ```js function $apply(expr) { try { return $eval(expr); } catch (e) { $exceptionHandler(e); } finally { $root.$digest(); } } * ``` * * * Scope's `$apply()` method transitions through the following stages: * * 1. The {@link guide/expression expression} is executed using the * {@link ng.$rootScope.Scope#$eval $eval()} method. * 2. Any exceptions from the execution of the expression are forwarded to the * {@link ng.$exceptionHandler $exceptionHandler} service. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. * * * @param {(string|function())=} exp An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with current `scope` parameter. * * @returns {*} The result of evaluating the expression. */ $apply: function(expr) { try { beginPhase('$apply'); return this.$eval(expr); } catch (e) { $exceptionHandler(e); } finally { clearPhase(); try { $rootScope.$digest(); } catch (e) { $exceptionHandler(e); throw e; } } }, /** * @ngdoc method * @name $rootScope.Scope#$applyAsync * @kind function * * @description * Schedule the invocation of $apply to occur at a later time. The actual time difference * varies across browsers, but is typically around ~10 milliseconds. * * This can be used to queue up multiple expressions which need to be evaluated in the same * digest. * * @param {(string|function())=} exp An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with current `scope` parameter. */ $applyAsync: function(expr) { var scope = this; expr && applyAsyncQueue.push($applyAsyncExpression); scheduleApplyAsync(); function $applyAsyncExpression() { scope.$eval(expr); } }, /** * @ngdoc method * @name $rootScope.Scope#$on * @kind function * * @description * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for * discussion of event life cycle. * * The event listener function format is: `function(event, args...)`. The `event` object * passed into the listener has the following attributes: * * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or * `$broadcast`-ed. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the * event propagates through the scope hierarchy, this property is set to null. * - `name` - `{string}`: name of the event. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel * further event propagation (available only for events that were `$emit`-ed). * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag * to true. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. * * @param {string} name Event name to listen on. * @param {function(event, ...args)} listener Function to call when the event is emitted. * @returns {function()} Returns a deregistration function for this listener. */ $on: function(name, listener) { var namedListeners = this.$$listeners[name]; if (!namedListeners) { this.$$listeners[name] = namedListeners = []; } namedListeners.push(listener); var current = this; do { if (!current.$$listenerCount[name]) { current.$$listenerCount[name] = 0; } current.$$listenerCount[name]++; } while ((current = current.$parent)); var self = this; return function() { var indexOfListener = namedListeners.indexOf(listener); if (indexOfListener !== -1) { namedListeners[indexOfListener] = null; decrementListenerCount(self, 1, name); } }; }, /** * @ngdoc method * @name $rootScope.Scope#$emit * @kind function * * @description * Dispatches an event `name` upwards through the scope hierarchy notifying the * registered {@link ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$emit` was called. All * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get * notified. Afterwards, the event traverses upwards toward the root scope and calls all * registered listeners along the way. The event will stop propagating if one of the listeners * cancels it. * * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}). */ $emit: function(name, args) { var empty = [], namedListeners, scope = this, stopPropagation = false, event = { name: name, targetScope: scope, stopPropagation: function() {stopPropagation = true;}, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }, listenerArgs = concat([event], arguments, 1), i, length; do { namedListeners = scope.$$listeners[name] || empty; event.currentScope = scope; for (i = 0, length = namedListeners.length; i < length; i++) { // if listeners were deregistered, defragment the array if (!namedListeners[i]) { namedListeners.splice(i, 1); i--; length--; continue; } try { //allow all listeners attached to the current scope to run namedListeners[i].apply(null, listenerArgs); } catch (e) { $exceptionHandler(e); } } //if any listener on the current scope stops propagation, prevent bubbling if (stopPropagation) { event.currentScope = null; return event; } //traverse upwards scope = scope.$parent; } while (scope); event.currentScope = null; return event; }, /** * @ngdoc method * @name $rootScope.Scope#$broadcast * @kind function * * @description * Dispatches an event `name` downwards to all child scopes (and their children) notifying the * registered {@link ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$broadcast` was called. All * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get * notified. Afterwards, the event propagates to all direct and indirect scopes of the current * scope and calls all registered listeners along the way. The event cannot be canceled. * * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to broadcast. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} */ $broadcast: function(name, args) { var target = this, current = target, next = target, event = { name: name, targetScope: target, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }; if (!target.$$listenerCount[name]) return event; var listenerArgs = concat([event], arguments, 1), listeners, i, length; //down while you can, then up and next sibling or up and next sibling until back at root while ((current = next)) { event.currentScope = current; listeners = current.$$listeners[name] || []; for (i = 0, length = listeners.length; i < length; i++) { // if listeners were deregistered, defragment the array if (!listeners[i]) { listeners.splice(i, 1); i--; length--; continue; } try { listeners[i].apply(null, listenerArgs); } catch (e) { $exceptionHandler(e); } } // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $digest // (though it differs due to having the extra check for $$listenerCount) if (!(next = ((current.$$listenerCount[name] && current.$$childHead) || (current !== target && current.$$nextSibling)))) { while (current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } event.currentScope = null; return event; } }; var $rootScope = new Scope(); //The internal queues. Expose them on the $rootScope for debugging/testing purposes. var asyncQueue = $rootScope.$$asyncQueue = []; var postDigestQueue = $rootScope.$$postDigestQueue = []; var applyAsyncQueue = $rootScope.$$applyAsyncQueue = []; return $rootScope; function beginPhase(phase) { if ($rootScope.$$phase) { throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase); } $rootScope.$$phase = phase; } function clearPhase() { $rootScope.$$phase = null; } function decrementListenerCount(current, count, name) { do { current.$$listenerCount[name] -= count; if (current.$$listenerCount[name] === 0) { delete current.$$listenerCount[name]; } } while ((current = current.$parent)); } /** * function used as an initial value for watchers. * because it's unique we can easily tell it apart from other values */ function initWatchVal() {} function flushApplyAsync() { while (applyAsyncQueue.length) { try { applyAsyncQueue.shift()(); } catch (e) { $exceptionHandler(e); } } applyAsyncId = null; } function scheduleApplyAsync() { if (applyAsyncId === null) { applyAsyncId = $browser.defer(function() { $rootScope.$apply(flushApplyAsync); }); } } }]; } /** * @description * Private service to sanitize uris for links and images. Used by $compile and $sanitize. */ function $$SanitizeUriProvider() { var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/, imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/; /** * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during a[href] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * * Any url about to be assigned to a[href] via data-binding is first normalized and turned into * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` * regular expression. If a match is found, the original url is written into the dom. Otherwise, * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.aHrefSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { aHrefSanitizationWhitelist = regexp; return this; } return aHrefSanitizationWhitelist; }; /** * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during img[src] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * * Any url about to be assigned to img[src] via data-binding is first normalized and turned into * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` * regular expression. If a match is found, the original url is written into the dom. Otherwise, * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.imgSrcSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { imgSrcSanitizationWhitelist = regexp; return this; } return imgSrcSanitizationWhitelist; }; this.$get = function() { return function sanitizeUri(uri, isImage) { var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist; var normalizedVal; normalizedVal = urlResolve(uri).href; if (normalizedVal !== '' && !normalizedVal.match(regex)) { return 'unsafe:' + normalizedVal; } return uri; }; }; } var $sceMinErr = minErr('$sce'); var SCE_CONTEXTS = { HTML: 'html', CSS: 'css', URL: 'url', // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a // url. (e.g. ng-include, script src, templateUrl) RESOURCE_URL: 'resourceUrl', JS: 'js' }; // Helper functions follow. function adjustMatcher(matcher) { if (matcher === 'self') { return matcher; } else if (isString(matcher)) { // Strings match exactly except for 2 wildcards - '*' and '**'. // '*' matches any character except those from the set ':/.?&'. // '**' matches any character (like .* in a RegExp). // More than 2 *'s raises an error as it's ill defined. if (matcher.indexOf('***') > -1) { throw $sceMinErr('iwcard', 'Illegal sequence *** in string matcher. String: {0}', matcher); } matcher = escapeForRegexp(matcher). replace('\\*\\*', '.*'). replace('\\*', '[^:/.?&;]*'); return new RegExp('^' + matcher + '$'); } else if (isRegExp(matcher)) { // The only other type of matcher allowed is a Regexp. // Match entire URL / disallow partial matches. // Flags are reset (i.e. no global, ignoreCase or multiline) return new RegExp('^' + matcher.source + '$'); } else { throw $sceMinErr('imatcher', 'Matchers may only be "self", string patterns or RegExp objects'); } } function adjustMatchers(matchers) { var adjustedMatchers = []; if (isDefined(matchers)) { forEach(matchers, function(matcher) { adjustedMatchers.push(adjustMatcher(matcher)); }); } return adjustedMatchers; } /** * @ngdoc service * @name $sceDelegate * @kind function * * @description * * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict * Contextual Escaping (SCE)} services to AngularJS. * * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things * work because `$sce` delegates to `$sceDelegate` for these operations. * * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service. * * The default instance of `$sceDelegate` should work out of the box with little pain. While you * can override it completely to change the behavior of `$sce`, the common case would * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist * $sceDelegateProvider.resourceUrlWhitelist} and {@link * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} */ /** * @ngdoc provider * @name $sceDelegateProvider * @description * * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure * that the URLs used for sourcing Angular templates are safe. Refer {@link * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} * * For the general details about this service in Angular, read the main page for {@link ng.$sce * Strict Contextual Escaping (SCE)}. * * **Example**: Consider the following case. <a name="example"></a> * * - your app is hosted at url `http://myapp.example.com/` * - but some of your templates are hosted on other domains you control such as * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`. * * Here is what a secure configuration for this scenario might look like: * * ``` * angular.module('myApp', []).config(function($sceDelegateProvider) { * $sceDelegateProvider.resourceUrlWhitelist([ * // Allow same origin resource loads. * 'self', * // Allow loading from our assets domain. Notice the difference between * and **. * 'http://srv*.assets.example.com/**' * ]); * * // The blacklist overrides the whitelist so the open redirect here is blocked. * $sceDelegateProvider.resourceUrlBlacklist([ * 'http://myapp.example.com/clickThru**' * ]); * }); * ``` */ function $SceDelegateProvider() { this.SCE_CONTEXTS = SCE_CONTEXTS; // Resource URLs can also be trusted by policy. var resourceUrlWhitelist = ['self'], resourceUrlBlacklist = []; /** * @ngdoc method * @name $sceDelegateProvider#resourceUrlWhitelist * @kind function * * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value * provided. This must be an array or null. A snapshot of this array is used so further * changes to the array are ignored. * * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items * allowed in this array. * * Note: **an empty whitelist array will block all URLs**! * * @return {Array} the currently set whitelist array. * * The **default value** when no whitelist has been explicitly set is `['self']` allowing only * same origin resource requests. * * @description * Sets/Gets the whitelist of trusted resource URLs. */ this.resourceUrlWhitelist = function(value) { if (arguments.length) { resourceUrlWhitelist = adjustMatchers(value); } return resourceUrlWhitelist; }; /** * @ngdoc method * @name $sceDelegateProvider#resourceUrlBlacklist * @kind function * * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value * provided. This must be an array or null. A snapshot of this array is used so further * changes to the array are ignored. * * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items * allowed in this array. * * The typical usage for the blacklist is to **block * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as * these would otherwise be trusted but actually return content from the redirected domain. * * Finally, **the blacklist overrides the whitelist** and has the final say. * * @return {Array} the currently set blacklist array. * * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there * is no blacklist.) * * @description * Sets/Gets the blacklist of trusted resource URLs. */ this.resourceUrlBlacklist = function(value) { if (arguments.length) { resourceUrlBlacklist = adjustMatchers(value); } return resourceUrlBlacklist; }; this.$get = ['$injector', function($injector) { var htmlSanitizer = function htmlSanitizer(html) { throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); }; if ($injector.has('$sanitize')) { htmlSanitizer = $injector.get('$sanitize'); } function matchUrl(matcher, parsedUrl) { if (matcher === 'self') { return urlIsSameOrigin(parsedUrl); } else { // definitely a regex. See adjustMatchers() return !!matcher.exec(parsedUrl.href); } } function isResourceUrlAllowedByPolicy(url) { var parsedUrl = urlResolve(url.toString()); var i, n, allowed = false; // Ensure that at least one item from the whitelist allows this url. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) { if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) { allowed = true; break; } } if (allowed) { // Ensure that no item from the blacklist blocked this url. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) { if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) { allowed = false; break; } } } return allowed; } function generateHolderType(Base) { var holderType = function TrustedValueHolderType(trustedValue) { this.$$unwrapTrustedValue = function() { return trustedValue; }; }; if (Base) { holderType.prototype = new Base(); } holderType.prototype.valueOf = function sceValueOf() { return this.$$unwrapTrustedValue(); }; holderType.prototype.toString = function sceToString() { return this.$$unwrapTrustedValue().toString(); }; return holderType; } var trustedValueHolderBase = generateHolderType(), byType = {}; byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase); byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase); byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase); byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase); byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]); /** * @ngdoc method * @name $sceDelegate#trustAs * * @description * Returns an object that is trusted by angular for use in specified strict * contextual escaping contexts (such as ng-bind-html, ng-include, any src * attribute interpolation, any dom event binding attribute interpolation * such as for onclick, etc.) that uses the provided value. * See {@link ng.$sce $sce} for enabling strict contextual escaping. * * @param {string} type The kind of context in which this value is safe for use. e.g. url, * resourceUrl, html, js and css. * @param {*} value The value that that should be considered trusted/safe. * @returns {*} A value that can be used to stand in for the provided `value` in places * where Angular expects a $sce.trustAs() return value. */ function trustAs(type, trustedValue) { var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null); if (!Constructor) { throw $sceMinErr('icontext', 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}', type, trustedValue); } if (trustedValue === null || trustedValue === undefined || trustedValue === '') { return trustedValue; } // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting // mutable objects, we ensure here that the value passed in is actually a string. if (typeof trustedValue !== 'string') { throw $sceMinErr('itype', 'Attempted to trust a non-string value in a content requiring a string: Context: {0}', type); } return new Constructor(trustedValue); } /** * @ngdoc method * @name $sceDelegate#valueOf * * @description * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. * * If the passed parameter is not a value that had been returned by {@link * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is. * * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} * call or anything else. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns * `value` unchanged. */ function valueOf(maybeTrusted) { if (maybeTrusted instanceof trustedValueHolderBase) { return maybeTrusted.$$unwrapTrustedValue(); } else { return maybeTrusted; } } /** * @ngdoc method * @name $sceDelegate#getTrusted * * @description * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and * returns the originally supplied value if the queried context type is a supertype of the * created type. If this condition isn't satisfied, throws an exception. * * @param {string} type The kind of context in which this value is to be used. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs * `$sceDelegate.trustAs`} call. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception. */ function getTrusted(type, maybeTrusted) { if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') { return maybeTrusted; } var constructor = (byType.hasOwnProperty(type) ? byType[type] : null); if (constructor && maybeTrusted instanceof constructor) { return maybeTrusted.$$unwrapTrustedValue(); } // If we get here, then we may only take one of two actions. // 1. sanitize the value for the requested type, or // 2. throw an exception. if (type === SCE_CONTEXTS.RESOURCE_URL) { if (isResourceUrlAllowedByPolicy(maybeTrusted)) { return maybeTrusted; } else { throw $sceMinErr('insecurl', 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}', maybeTrusted.toString()); } } else if (type === SCE_CONTEXTS.HTML) { return htmlSanitizer(maybeTrusted); } throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); } return { trustAs: trustAs, getTrusted: getTrusted, valueOf: valueOf }; }]; } /** * @ngdoc provider * @name $sceProvider * @description * * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service. * - enable/disable Strict Contextual Escaping (SCE) in a module * - override the default implementation with a custom delegate * * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}. */ /* jshint maxlen: false*/ /** * @ngdoc service * @name $sce * @kind function * * @description * * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS. * * # Strict Contextual Escaping * * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain * contexts to result in a value that is marked as safe to use for that context. One example of * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer * to these contexts as privileged or SCE contexts. * * As of version 1.2, Angular ships with SCE enabled by default. * * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow * one to execute arbitrary javascript by the use of the expression() syntax. Refer * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>` * to the top of your HTML document. * * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for * security vulnerabilities such as XSS, clickjacking, etc. a lot easier. * * Here's an example of a binding in a privileged context: * * ``` * <input ng-model="userHtml"> * <div ng-bind-html="userHtml"></div> * ``` * * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE * disabled, this application allows the user to render arbitrary HTML into the DIV. * In a more realistic example, one may be rendering user comments, blog articles, etc. via * bindings. (HTML is just one example of a context where rendering user controlled input creates * security vulnerabilities.) * * For the case of HTML, you might use a library, either on the client side, or on the server side, * to sanitize unsafe HTML before binding to the value and rendering it in the document. * * How would you ensure that every place that used these types of bindings was bound to a value that * was sanitized by your library (or returned as safe for rendering by your server?) How can you * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some * properties/fields and forgot to update the binding to the sanitized value? * * To be secure by default, you want to ensure that any such bindings are disallowed unless you can * determine that something explicitly says it's safe to use a value for binding in that * context. You can then audit your code (a simple grep would do) to ensure that this is only done * for those values that you can easily tell are safe - because they were received from your server, * sanitized by your library, etc. You can organize your codebase to help with this - perhaps * allowing only the files in a specific directory to do this. Ensuring that the internal API * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task. * * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs} * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to * obtain values that will be accepted by SCE / privileged contexts. * * * ## How does it work? * * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. * * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly * simplified): * * ``` * var ngBindHtmlDirective = ['$sce', function($sce) { * return function(scope, element, attr) { * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) { * element.html(value || ''); * }); * }; * }]; * ``` * * ## Impact on loading templates * * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as * `templateUrl`'s specified by {@link guide/directive directives}. * * By default, Angular only loads templates from the same domain and protocol as the application * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value. * * *Please note*: * The browser's * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) * policy apply in addition to this and may further restrict whether the template is successfully * loaded. This means that without the right CORS policy, loading templates from a different domain * won't work on all browsers. Also, loading templates from `file://` URL does not work on some * browsers. * * ## This feels like too much overhead * * It's important to remember that SCE only applies to interpolation expressions. * * If your expressions are constant literals, they're automatically trusted and you don't need to * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works. * * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here. * * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load * templates in `ng-include` from your application's domain without having to even know about SCE. * It blocks loading templates from other domains or loading templates over http from an https * served document. You can change these by setting your own custom {@link * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs. * * This significantly reduces the overhead. It is far easier to pay the small overhead and have an * application that's secure and can be audited to verify that with much more ease than bolting * security onto an application later. * * <a name="contexts"></a> * ## What trusted context types are supported? * * | Context | Notes | * |---------------------|----------------| * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. | * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. | * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. | * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. | * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. | * * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a> * * Each element in these arrays must be one of the following: * * - **'self'** * - The special **string**, `'self'`, can be used to match against all URLs of the **same * domain** as the application document using the **same protocol**. * - **String** (except the special value `'self'`) * - The string is matched against the full *normalized / absolute URL* of the resource * being tested (substring matches are not good enough.) * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters * match themselves. * - `*`: matches zero or more occurrences of any character other than one of the following 6 * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use * in a whitelist. * - `**`: matches zero or more occurrences of *any* character. As such, it's not * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might * not have been the intention.) Its usage at the very end of the path is ok. (e.g. * http://foo.example.com/templates/**). * - **RegExp** (*see caveat below*) * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to * accidentally introduce a bug when one updates a complex expression (imho, all regexes should * have good test coverage.). For instance, the use of `.` in the regex is correct only in a * small number of cases. A `.` character in the regex used when matching the scheme or a * subdomain could be matched against a `:` or literal `.` that was likely not intended. It * is highly recommended to use the string patterns and only fall back to regular expressions * if they as a last resort. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is * matched against the **entire** *normalized / absolute URL* of the resource being tested * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags * present on the RegExp (such as multiline, global, ignoreCase) are ignored. * - If you are generating your JavaScript from some other templating engine (not * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)), * remember to escape your regular expression (and be aware that you might need more than * one level of escaping depending on your templating engine and the way you interpolated * the value.) Do make use of your platform's escaping mechanism as it might be good * enough before coding your own. e.g. Ruby has * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape) * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape). * Javascript lacks a similar built in function for escaping. Take a look at Google * Closure library's [goog.string.regExpEscape(s)]( * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962). * * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example. * * ## Show me an example using SCE. * * <example module="mySceApp" deps="angular-sanitize.js"> * <file name="index.html"> * <div ng-controller="AppController as myCtrl"> * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br> * <b>User comments</b><br> * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when * $sanitize is available. If $sanitize isn't available, this results in an error instead of an * exploit. * <div class="well"> * <div ng-repeat="userComment in myCtrl.userComments"> * <b>{{userComment.name}}</b>: * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span> * <br> * </div> * </div> * </div> * </file> * * <file name="script.js"> * angular.module('mySceApp', ['ngSanitize']) * .controller('AppController', ['$http', '$templateCache', '$sce', * function($http, $templateCache, $sce) { * var self = this; * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) { * self.userComments = userComments; * }); * self.explicitlyTrustedHtml = $sce.trustAsHtml( * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' + * 'sanitization.&quot;">Hover over this text.</span>'); * }]); * </file> * * <file name="test_data.json"> * [ * { "name": "Alice", * "htmlComment": * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>" * }, * { "name": "Bob", * "htmlComment": "<i>Yes!</i> Am I the only other one?" * } * ] * </file> * * <file name="protractor.js" type="protractor"> * describe('SCE doc demo', function() { * it('should sanitize untrusted values', function() { * expect(element.all(by.css('.htmlComment')).first().getInnerHtml()) * .toBe('<span>Is <i>anyone</i> reading this?</span>'); * }); * * it('should NOT sanitize explicitly trusted values', function() { * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe( * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' + * 'sanitization.&quot;">Hover over this text.</span>'); * }); * }); * </file> * </example> * * * * ## Can I disable SCE completely? * * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits * for little coding overhead. It will be much harder to take an SCE disabled application and * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE * for cases where you have a lot of existing code that was written before SCE was introduced and * you're migrating them a module at a time. * * That said, here's how you can completely disable SCE: * * ``` * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) { * // Completely disable SCE. For demonstration purposes only! * // Do not use in new projects. * $sceProvider.enabled(false); * }); * ``` * */ /* jshint maxlen: 100 */ function $SceProvider() { var enabled = true; /** * @ngdoc method * @name $sceProvider#enabled * @kind function * * @param {boolean=} value If provided, then enables/disables SCE. * @return {boolean} true if SCE is enabled, false otherwise. * * @description * Enables/disables SCE and returns the current value. */ this.enabled = function(value) { if (arguments.length) { enabled = !!value; } return enabled; }; /* Design notes on the default implementation for SCE. * * The API contract for the SCE delegate * ------------------------------------- * The SCE delegate object must provide the following 3 methods: * * - trustAs(contextEnum, value) * This method is used to tell the SCE service that the provided value is OK to use in the * contexts specified by contextEnum. It must return an object that will be accepted by * getTrusted() for a compatible contextEnum and return this value. * * - valueOf(value) * For values that were not produced by trustAs(), return them as is. For values that were * produced by trustAs(), return the corresponding input value to trustAs. Basically, if * trustAs is wrapping the given values into some type, this operation unwraps it when given * such a value. * * - getTrusted(contextEnum, value) * This function should return the a value that is safe to use in the context specified by * contextEnum or throw and exception otherwise. * * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be * opaque or wrapped in some holder object. That happens to be an implementation detail. For * instance, an implementation could maintain a registry of all trusted objects by context. In * such a case, trustAs() would return the same object that was passed in. getTrusted() would * return the same object passed in if it was found in the registry under a compatible context or * throw an exception otherwise. An implementation might only wrap values some of the time based * on some criteria. getTrusted() might return a value and not throw an exception for special * constants or objects even if not wrapped. All such implementations fulfill this contract. * * * A note on the inheritance model for SCE contexts * ------------------------------------------------ * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This * is purely an implementation details. * * The contract is simply this: * * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value) * will also succeed. * * Inheritance happens to capture this in a natural way. In some future, we * may not use inheritance anymore. That is OK because no code outside of * sce.js and sceSpecs.js would need to be aware of this detail. */ this.$get = ['$parse', '$sceDelegate', function( $parse, $sceDelegate) { // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow // the "expression(javascript expression)" syntax which is insecure. if (enabled && msie < 8) { throw $sceMinErr('iequirks', 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' + 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' + 'document. See http://docs.angularjs.org/api/ng.$sce for more information.'); } var sce = shallowCopy(SCE_CONTEXTS); /** * @ngdoc method * @name $sce#isEnabled * @kind function * * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you * have to do it at module config time on {@link ng.$sceProvider $sceProvider}. * * @description * Returns a boolean indicating if SCE is enabled. */ sce.isEnabled = function() { return enabled; }; sce.trustAs = $sceDelegate.trustAs; sce.getTrusted = $sceDelegate.getTrusted; sce.valueOf = $sceDelegate.valueOf; if (!enabled) { sce.trustAs = sce.getTrusted = function(type, value) { return value; }; sce.valueOf = identity; } /** * @ngdoc method * @name $sce#parseAs * * @description * Converts Angular {@link guide/expression expression} into a function. This is like {@link * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*, * *result*)} * * @param {string} type The kind of SCE context in which this result will be used. * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. */ sce.parseAs = function sceParseAs(type, expr) { var parsed = $parse(expr); if (parsed.literal && parsed.constant) { return parsed; } else { return $parse(expr, function(value) { return sce.getTrusted(type, value); }); } }; /** * @ngdoc method * @name $sce#trustAs * * @description * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, * returns an object that is trusted by angular for use in specified strict contextual * escaping contexts (such as ng-bind-html, ng-include, any src attribute * interpolation, any dom event binding attribute interpolation such as for onclick, etc.) * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual * escaping. * * @param {string} type The kind of context in which this value is safe for use. e.g. url, * resource_url, html, js and css. * @param {*} value The value that that should be considered trusted/safe. * @returns {*} A value that can be used to stand in for the provided `value` in places * where Angular expects a $sce.trustAs() return value. */ /** * @ngdoc method * @name $sce#trustAsHtml * * @description * Shorthand method. `$sce.trustAsHtml(value)` → * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`} * * @param {*} value The value to trustAs. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives * only accept expressions that are either literal constants or are the * return value of {@link ng.$sce#trustAs $sce.trustAs}.) */ /** * @ngdoc method * @name $sce#trustAsUrl * * @description * Shorthand method. `$sce.trustAsUrl(value)` → * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`} * * @param {*} value The value to trustAs. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives * only accept expressions that are either literal constants or are the * return value of {@link ng.$sce#trustAs $sce.trustAs}.) */ /** * @ngdoc method * @name $sce#trustAsResourceUrl * * @description * Shorthand method. `$sce.trustAsResourceUrl(value)` → * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`} * * @param {*} value The value to trustAs. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives * only accept expressions that are either literal constants or are the return * value of {@link ng.$sce#trustAs $sce.trustAs}.) */ /** * @ngdoc method * @name $sce#trustAsJs * * @description * Shorthand method. `$sce.trustAsJs(value)` → * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`} * * @param {*} value The value to trustAs. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives * only accept expressions that are either literal constants or are the * return value of {@link ng.$sce#trustAs $sce.trustAs}.) */ /** * @ngdoc method * @name $sce#getTrusted * * @description * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such, * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the * originally supplied value if the queried context type is a supertype of the created type. * If this condition isn't satisfied, throws an exception. * * @param {string} type The kind of context in which this value is to be used. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`} * call. * @returns {*} The value the was originally provided to * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context. * Otherwise, throws an exception. */ /** * @ngdoc method * @name $sce#getTrustedHtml * * @description * Shorthand method. `$sce.getTrustedHtml(value)` → * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`} * * @param {*} value The value to pass to `$sce.getTrusted`. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)` */ /** * @ngdoc method * @name $sce#getTrustedCss * * @description * Shorthand method. `$sce.getTrustedCss(value)` → * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`} * * @param {*} value The value to pass to `$sce.getTrusted`. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)` */ /** * @ngdoc method * @name $sce#getTrustedUrl * * @description * Shorthand method. `$sce.getTrustedUrl(value)` → * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`} * * @param {*} value The value to pass to `$sce.getTrusted`. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)` */ /** * @ngdoc method * @name $sce#getTrustedResourceUrl * * @description * Shorthand method. `$sce.getTrustedResourceUrl(value)` → * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`} * * @param {*} value The value to pass to `$sceDelegate.getTrusted`. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)` */ /** * @ngdoc method * @name $sce#getTrustedJs * * @description * Shorthand method. `$sce.getTrustedJs(value)` → * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`} * * @param {*} value The value to pass to `$sce.getTrusted`. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)` */ /** * @ngdoc method * @name $sce#parseAsHtml * * @description * Shorthand method. `$sce.parseAsHtml(expression string)` → * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`} * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. */ /** * @ngdoc method * @name $sce#parseAsCss * * @description * Shorthand method. `$sce.parseAsCss(value)` → * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`} * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. */ /** * @ngdoc method * @name $sce#parseAsUrl * * @description * Shorthand method. `$sce.parseAsUrl(value)` → * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`} * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. */ /** * @ngdoc method * @name $sce#parseAsResourceUrl * * @description * Shorthand method. `$sce.parseAsResourceUrl(value)` → * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`} * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. */ /** * @ngdoc method * @name $sce#parseAsJs * * @description * Shorthand method. `$sce.parseAsJs(value)` → * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`} * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. */ // Shorthand delegations. var parse = sce.parseAs, getTrusted = sce.getTrusted, trustAs = sce.trustAs; forEach(SCE_CONTEXTS, function(enumValue, name) { var lName = lowercase(name); sce[camelCase("parse_as_" + lName)] = function(expr) { return parse(enumValue, expr); }; sce[camelCase("get_trusted_" + lName)] = function(value) { return getTrusted(enumValue, value); }; sce[camelCase("trust_as_" + lName)] = function(value) { return trustAs(enumValue, value); }; }); return sce; }]; } /** * !!! This is an undocumented "private" service !!! * * @name $sniffer * @requires $window * @requires $document * * @property {boolean} history Does the browser support html5 history api ? * @property {boolean} transitions Does the browser support CSS transition events ? * @property {boolean} animations Does the browser support CSS animation events ? * * @description * This is very simple implementation of testing browser's features. */ function $SnifferProvider() { this.$get = ['$window', '$document', function($window, $document) { var eventSupport = {}, android = int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]), boxee = /Boxee/i.test(($window.navigator || {}).userAgent), document = $document[0] || {}, vendorPrefix, vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/, bodyStyle = document.body && document.body.style, transitions = false, animations = false, match; if (bodyStyle) { for (var prop in bodyStyle) { if (match = vendorRegex.exec(prop)) { vendorPrefix = match[0]; vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1); break; } } if (!vendorPrefix) { vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit'; } transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle)); animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle)); if (android && (!transitions || !animations)) { transitions = isString(document.body.style.webkitTransition); animations = isString(document.body.style.webkitAnimation); } } return { // Android has history.pushState, but it does not update location correctly // so let's not use the history API at all. // http://code.google.com/p/android/issues/detail?id=17471 // https://github.com/angular/angular.js/issues/904 // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has // so let's not use the history API also // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined // jshint -W018 history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee), // jshint +W018 hasEvent: function(event) { // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have // it. In particular the event is not fired when backspace or delete key are pressed or // when cut operation is performed. // IE10+ implements 'input' event but it erroneously fires under various situations, // e.g. when placeholder changes, or a form is focused. if (event === 'input' && msie <= 11) return false; if (isUndefined(eventSupport[event])) { var divElm = document.createElement('div'); eventSupport[event] = 'on' + event in divElm; } return eventSupport[event]; }, csp: csp(), vendorPrefix: vendorPrefix, transitions: transitions, animations: animations, android: android }; }]; } var $compileMinErr = minErr('$compile'); /** * @ngdoc service * @name $templateRequest * * @description * The `$templateRequest` service downloads the provided template using `$http` and, upon success, * stores the contents inside of `$templateCache`. If the HTTP request fails or the response data * of the HTTP request is empty, a `$compile` error will be thrown (the exception can be thwarted * by setting the 2nd parameter of the function to true). * * @param {string} tpl The HTTP request template URL * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty * * @return {Promise} the HTTP Promise for the given. * * @property {number} totalPendingRequests total amount of pending template requests being downloaded. */ function $TemplateRequestProvider() { this.$get = ['$templateCache', '$http', '$q', function($templateCache, $http, $q) { function handleRequestFn(tpl, ignoreRequestError) { handleRequestFn.totalPendingRequests++; var transformResponse = $http.defaults && $http.defaults.transformResponse; if (isArray(transformResponse)) { transformResponse = transformResponse.filter(function(transformer) { return transformer !== defaultHttpResponseTransform; }); } else if (transformResponse === defaultHttpResponseTransform) { transformResponse = null; } var httpOptions = { cache: $templateCache, transformResponse: transformResponse }; return $http.get(tpl, httpOptions) .finally(function() { handleRequestFn.totalPendingRequests--; }) .then(function(response) { return response.data; }, handleError); function handleError(resp) { if (!ignoreRequestError) { throw $compileMinErr('tpload', 'Failed to load template: {0}', tpl); } return $q.reject(resp); } } handleRequestFn.totalPendingRequests = 0; return handleRequestFn; }]; } function $$TestabilityProvider() { this.$get = ['$rootScope', '$browser', '$location', function($rootScope, $browser, $location) { /** * @name $testability * * @description * The private $$testability service provides a collection of methods for use when debugging * or by automated test and debugging tools. */ var testability = {}; /** * @name $$testability#findBindings * * @description * Returns an array of elements that are bound (via ng-bind or {{}}) * to expressions matching the input. * * @param {Element} element The element root to search from. * @param {string} expression The binding expression to match. * @param {boolean} opt_exactMatch If true, only returns exact matches * for the expression. Filters and whitespace are ignored. */ testability.findBindings = function(element, expression, opt_exactMatch) { var bindings = element.getElementsByClassName('ng-binding'); var matches = []; forEach(bindings, function(binding) { var dataBinding = angular.element(binding).data('$binding'); if (dataBinding) { forEach(dataBinding, function(bindingName) { if (opt_exactMatch) { var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)'); if (matcher.test(bindingName)) { matches.push(binding); } } else { if (bindingName.indexOf(expression) != -1) { matches.push(binding); } } }); } }); return matches; }; /** * @name $$testability#findModels * * @description * Returns an array of elements that are two-way found via ng-model to * expressions matching the input. * * @param {Element} element The element root to search from. * @param {string} expression The model expression to match. * @param {boolean} opt_exactMatch If true, only returns exact matches * for the expression. */ testability.findModels = function(element, expression, opt_exactMatch) { var prefixes = ['ng-', 'data-ng-', 'ng\\:']; for (var p = 0; p < prefixes.length; ++p) { var attributeEquals = opt_exactMatch ? '=' : '*='; var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]'; var elements = element.querySelectorAll(selector); if (elements.length) { return elements; } } }; /** * @name $$testability#getLocation * * @description * Shortcut for getting the location in a browser agnostic way. Returns * the path, search, and hash. (e.g. /path?a=b#hash) */ testability.getLocation = function() { return $location.url(); }; /** * @name $$testability#setLocation * * @description * Shortcut for navigating to a location without doing a full page reload. * * @param {string} url The location url (path, search and hash, * e.g. /path?a=b#hash) to go to. */ testability.setLocation = function(url) { if (url !== $location.url()) { $location.url(url); $rootScope.$digest(); } }; /** * @name $$testability#whenStable * * @description * Calls the callback when $timeout and $http requests are completed. * * @param {function} callback */ testability.whenStable = function(callback) { $browser.notifyWhenNoOutstandingRequests(callback); }; return testability; }]; } function $TimeoutProvider() { this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler', function($rootScope, $browser, $q, $$q, $exceptionHandler) { var deferreds = {}; /** * @ngdoc service * @name $timeout * * @description * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch * block and delegates any exceptions to * {@link ng.$exceptionHandler $exceptionHandler} service. * * The return value of registering a timeout function is a promise, which will be resolved when * the timeout is reached and the timeout function is executed. * * To cancel a timeout request, call `$timeout.cancel(promise)`. * * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to * synchronously flush the queue of deferred functions. * * @param {function()} fn A function, whose execution should be delayed. * @param {number=} [delay=0] Delay in milliseconds. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this * promise will be resolved with is the return value of the `fn` function. * */ function timeout(fn, delay, invokeApply) { var skipApply = (isDefined(invokeApply) && !invokeApply), deferred = (skipApply ? $$q : $q).defer(), promise = deferred.promise, timeoutId; timeoutId = $browser.defer(function() { try { deferred.resolve(fn()); } catch (e) { deferred.reject(e); $exceptionHandler(e); } finally { delete deferreds[promise.$$timeoutId]; } if (!skipApply) $rootScope.$apply(); }, delay); promise.$$timeoutId = timeoutId; deferreds[timeoutId] = deferred; return promise; } /** * @ngdoc method * @name $timeout#cancel * * @description * Cancels a task associated with the `promise`. As a result of this, the promise will be * resolved with a rejection. * * @param {Promise=} promise Promise returned by the `$timeout` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully * canceled. */ timeout.cancel = function(promise) { if (promise && promise.$$timeoutId in deferreds) { deferreds[promise.$$timeoutId].reject('canceled'); delete deferreds[promise.$$timeoutId]; return $browser.defer.cancel(promise.$$timeoutId); } return false; }; return timeout; }]; } // NOTE: The usage of window and document instead of $window and $document here is // deliberate. This service depends on the specific behavior of anchor nodes created by the // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and // cause us to break tests. In addition, when the browser resolves a URL for XHR, it // doesn't know about mocked locations and resolves URLs to the real document - which is // exactly the behavior needed here. There is little value is mocking these out for this // service. var urlParsingNode = document.createElement("a"); var originUrl = urlResolve(window.location.href); /** * * Implementation Notes for non-IE browsers * ---------------------------------------- * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM, * results both in the normalizing and parsing of the URL. Normalizing means that a relative * URL will be resolved into an absolute URL in the context of the application document. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related * properties are all populated to reflect the normalized URL. This approach has wide * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html * * Implementation Notes for IE * --------------------------- * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other * browsers. However, the parsed components will not be set if the URL assigned did not specify * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We * work around that by performing the parsing in a 2nd step by taking a previously normalized * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the * properties such as protocol, hostname, port, etc. * * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one * uses the inner HTML approach to assign the URL as part of an HTML snippet - * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL. * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception. * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that * method and IE < 8 is unsupported. * * References: * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html * http://url.spec.whatwg.org/#urlutils * https://github.com/angular/angular.js/pull/2902 * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/ * * @kind function * @param {string} url The URL to be parsed. * @description Normalizes and parses a URL. * @returns {object} Returns the normalized URL as a dictionary. * * | member name | Description | * |---------------|----------------| * | href | A normalized version of the provided URL if it was not an absolute URL | * | protocol | The protocol including the trailing colon | * | host | The host and port (if the port is non-default) of the normalizedUrl | * | search | The search params, minus the question mark | * | hash | The hash string, minus the hash symbol * | hostname | The hostname * | port | The port, without ":" * | pathname | The pathname, beginning with "/" * */ function urlResolve(url) { var href = url; if (msie) { // Normalize before parse. Refer Implementation Notes on why this is // done in two steps on IE. urlParsingNode.setAttribute("href", href); href = urlParsingNode.href; } urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname : '/' + urlParsingNode.pathname }; } /** * Parse a request URL and determine whether this is a same-origin request as the application document. * * @param {string|object} requestUrl The url of the request as a string that will be resolved * or a parsed URL object. * @returns {boolean} Whether the request is for the same origin as the application document. */ function urlIsSameOrigin(requestUrl) { var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl; return (parsed.protocol === originUrl.protocol && parsed.host === originUrl.host); } /** * @ngdoc service * @name $window * * @description * A reference to the browser's `window` object. While `window` * is globally available in JavaScript, it causes testability problems, because * it is a global variable. In angular we always refer to it through the * `$window` service, so it may be overridden, removed or mocked for testing. * * Expressions, like the one defined for the `ngClick` directive in the example * below, are evaluated with respect to the current scope. Therefore, there is * no risk of inadvertently coding in a dependency on a global value in such an * expression. * * @example <example module="windowExample"> <file name="index.html"> <script> angular.module('windowExample', []) .controller('ExampleController', ['$scope', '$window', function($scope, $window) { $scope.greeting = 'Hello, World!'; $scope.doGreeting = function(greeting) { $window.alert(greeting); }; }]); </script> <div ng-controller="ExampleController"> <input type="text" ng-model="greeting" /> <button ng-click="doGreeting(greeting)">ALERT</button> </div> </file> <file name="protractor.js" type="protractor"> it('should display the greeting in the input box', function() { element(by.model('greeting')).sendKeys('Hello, E2E Tests'); // If we click the button it will block the test runner // element(':button').click(); }); </file> </example> */ function $WindowProvider() { this.$get = valueFn(window); } /* global currencyFilter: true, dateFilter: true, filterFilter: true, jsonFilter: true, limitToFilter: true, lowercaseFilter: true, numberFilter: true, orderByFilter: true, uppercaseFilter: true, */ /** * @ngdoc provider * @name $filterProvider * @description * * Filters are just functions which transform input to an output. However filters need to be * Dependency Injected. To achieve this a filter definition consists of a factory function which is * annotated with dependencies and is responsible for creating a filter function. * * ```js * // Filter registration * function MyModule($provide, $filterProvider) { * // create a service to demonstrate injection (not always needed) * $provide.value('greet', function(name){ * return 'Hello ' + name + '!'; * }); * * // register a filter factory which uses the * // greet service to demonstrate DI. * $filterProvider.register('greet', function(greet){ * // return the filter function which uses the greet service * // to generate salutation * return function(text) { * // filters need to be forgiving so check input validity * return text && greet(text) || text; * }; * }); * } * ``` * * The filter function is registered with the `$injector` under the filter name suffix with * `Filter`. * * ```js * it('should be the same instance', inject( * function($filterProvider) { * $filterProvider.register('reverse', function(){ * return ...; * }); * }, * function($filter, reverseFilter) { * expect($filter('reverse')).toBe(reverseFilter); * }); * ``` * * * For more information about how angular filters work, and how to create your own filters, see * {@link guide/filter Filters} in the Angular Developer Guide. */ /** * @ngdoc service * @name $filter * @kind function * @description * Filters are used for formatting data displayed to the user. * * The general syntax in templates is as follows: * * {{ expression [| filter_name[:parameter_value] ... ] }} * * @param {String} name Name of the filter function to retrieve * @return {Function} the filter function * @example <example name="$filter" module="filterExample"> <file name="index.html"> <div ng-controller="MainCtrl"> <h3>{{ originalText }}</h3> <h3>{{ filteredText }}</h3> </div> </file> <file name="script.js"> angular.module('filterExample', []) .controller('MainCtrl', function($scope, $filter) { $scope.originalText = 'hello'; $scope.filteredText = $filter('uppercase')($scope.originalText); }); </file> </example> */ $FilterProvider.$inject = ['$provide']; function $FilterProvider($provide) { var suffix = 'Filter'; /** * @ngdoc method * @name $filterProvider#register * @param {string|Object} name Name of the filter function, or an object map of filters where * the keys are the filter names and the values are the filter factories. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map * of the registered filter instances. */ function register(name, factory) { if (isObject(name)) { var filters = {}; forEach(name, function(filter, key) { filters[key] = register(key, filter); }); return filters; } else { return $provide.factory(name + suffix, factory); } } this.register = register; this.$get = ['$injector', function($injector) { return function(name) { return $injector.get(name + suffix); }; }]; //////////////////////////////////////// /* global currencyFilter: false, dateFilter: false, filterFilter: false, jsonFilter: false, limitToFilter: false, lowercaseFilter: false, numberFilter: false, orderByFilter: false, uppercaseFilter: false, */ register('currency', currencyFilter); register('date', dateFilter); register('filter', filterFilter); register('json', jsonFilter); register('limitTo', limitToFilter); register('lowercase', lowercaseFilter); register('number', numberFilter); register('orderBy', orderByFilter); register('uppercase', uppercaseFilter); } /** * @ngdoc filter * @name filter * @kind function * * @description * Selects a subset of items from `array` and returns it as a new array. * * @param {Array} array The source array. * @param {string|Object|function()} expression The predicate to be used for selecting items from * `array`. * * Can be one of: * * - `string`: The string is used for matching against the contents of the `array`. All strings or * objects with string properties in `array` that match this string will be returned. This also * applies to nested object properties. * The predicate can be negated by prefixing the string with `!`. * * - `Object`: A pattern object can be used to filter specific properties on objects contained * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items * which have property `name` containing "M" and property `phone` containing "1". A special * property name `$` can be used (as in `{$:"text"}`) to accept a match against any * property of the object or its nested object properties. That's equivalent to the simple * substring match with a `string` as described above. The predicate can be negated by prefixing * the string with `!`. * For example `{name: "!M"}` predicate will return an array of items which have property `name` * not containing "M". * * Note that a named property will match properties on the same level only, while the special * `$` property will match properties on the same level or deeper. E.g. an array item like * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but * **will** be matched by `{$: 'John'}`. * * - `function(value, index)`: A predicate function can be used to write arbitrary filters. The * function is called for each element of `array`. The final result is an array of those * elements that the predicate returned true for. * * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in * determining if the expected value (from the filter expression) and actual value (from * the object in the array) should be considered a match. * * Can be one of: * * - `function(actual, expected)`: * The function will be given the object value and the predicate value to compare and * should return true if both values should be considered equal. * * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`. * This is essentially strict comparison of expected and actual. * * - `false|undefined`: A short hand for a function which will look for a substring match in case * insensitive way. * * @example <example> <file name="index.html"> <div ng-init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {name:'Mike', phone:'555-4321'}, {name:'Adam', phone:'555-5678'}, {name:'Julie', phone:'555-8765'}, {name:'Juliette', phone:'555-5678'}]"></div> Search: <input ng-model="searchText"> <table id="searchTextResults"> <tr><th>Name</th><th>Phone</th></tr> <tr ng-repeat="friend in friends | filter:searchText"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> </tr> </table> <hr> Any: <input ng-model="search.$"> <br> Name only <input ng-model="search.name"><br> Phone only <input ng-model="search.phone"><br> Equality <input type="checkbox" ng-model="strict"><br> <table id="searchObjResults"> <tr><th>Name</th><th>Phone</th></tr> <tr ng-repeat="friendObj in friends | filter:search:strict"> <td>{{friendObj.name}}</td> <td>{{friendObj.phone}}</td> </tr> </table> </file> <file name="protractor.js" type="protractor"> var expectFriendNames = function(expectedNames, key) { element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) { arr.forEach(function(wd, i) { expect(wd.getText()).toMatch(expectedNames[i]); }); }); }; it('should search across all fields when filtering with a string', function() { var searchText = element(by.model('searchText')); searchText.clear(); searchText.sendKeys('m'); expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend'); searchText.clear(); searchText.sendKeys('76'); expectFriendNames(['John', 'Julie'], 'friend'); }); it('should search in specific fields when filtering with a predicate object', function() { var searchAny = element(by.model('search.$')); searchAny.clear(); searchAny.sendKeys('i'); expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj'); }); it('should use a equal comparison when comparator is true', function() { var searchName = element(by.model('search.name')); var strict = element(by.model('strict')); searchName.clear(); searchName.sendKeys('Julie'); strict.click(); expectFriendNames(['Julie'], 'friendObj'); }); </file> </example> */ function filterFilter() { return function(array, expression, comparator) { if (!isArray(array)) return array; var predicateFn; var matchAgainstAnyProp; switch (typeof expression) { case 'function': predicateFn = expression; break; case 'boolean': case 'number': case 'string': matchAgainstAnyProp = true; //jshint -W086 case 'object': //jshint +W086 predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp); break; default: return array; } return array.filter(predicateFn); }; } // Helper functions for `filterFilter` function createPredicateFn(expression, comparator, matchAgainstAnyProp) { var shouldMatchPrimitives = isObject(expression) && ('$' in expression); var predicateFn; if (comparator === true) { comparator = equals; } else if (!isFunction(comparator)) { comparator = function(actual, expected) { if (isObject(actual) || isObject(expected)) { // Prevent an object to be considered equal to a string like `'[object'` return false; } actual = lowercase('' + actual); expected = lowercase('' + expected); return actual.indexOf(expected) !== -1; }; } predicateFn = function(item) { if (shouldMatchPrimitives && !isObject(item)) { return deepCompare(item, expression.$, comparator, false); } return deepCompare(item, expression, comparator, matchAgainstAnyProp); }; return predicateFn; } function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) { var actualType = typeof actual; var expectedType = typeof expected; if ((expectedType === 'string') && (expected.charAt(0) === '!')) { return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp); } else if (isArray(actual)) { // In case `actual` is an array, consider it a match // if ANY of it's items matches `expected` return actual.some(function(item) { return deepCompare(item, expected, comparator, matchAgainstAnyProp); }); } switch (actualType) { case 'object': var key; if (matchAgainstAnyProp) { for (key in actual) { if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) { return true; } } return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false); } else if (expectedType === 'object') { for (key in expected) { var expectedVal = expected[key]; if (isFunction(expectedVal)) { continue; } var matchAnyProperty = key === '$'; var actualVal = matchAnyProperty ? actual : actual[key]; if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) { return false; } } return true; } else { return comparator(actual, expected); } break; case 'function': return false; default: return comparator(actual, expected); } } /** * @ngdoc filter * @name currency * @kind function * * @description * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default * symbol for current locale is used. * * @param {number} amount Input to filter. * @param {string=} symbol Currency symbol or identifier to be displayed. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale * @returns {string} Formatted number. * * * @example <example module="currencyExample"> <file name="index.html"> <script> angular.module('currencyExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.amount = 1234.56; }]); </script> <div ng-controller="ExampleController"> <input type="number" ng-model="amount"> <br> default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br> custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span> no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span> </div> </file> <file name="protractor.js" type="protractor"> it('should init with 1234.56', function() { expect(element(by.id('currency-default')).getText()).toBe('$1,234.56'); expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56'); expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235'); }); it('should update', function() { if (browser.params.browser == 'safari') { // Safari does not understand the minus key. See // https://github.com/angular/protractor/issues/481 return; } element(by.model('amount')).clear(); element(by.model('amount')).sendKeys('-1234'); expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)'); expect(element(by.id('currency-custom')).getText()).toBe('(USD$1,234.00)'); expect(element(by.id('currency-no-fractions')).getText()).toBe('(USD$1,234)'); }); </file> </example> */ currencyFilter.$inject = ['$locale']; function currencyFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(amount, currencySymbol, fractionSize) { if (isUndefined(currencySymbol)) { currencySymbol = formats.CURRENCY_SYM; } if (isUndefined(fractionSize)) { fractionSize = formats.PATTERNS[1].maxFrac; } // if null or undefined pass it through return (amount == null) ? amount : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize). replace(/\u00A4/g, currencySymbol); }; } /** * @ngdoc filter * @name number * @kind function * * @description * Formats a number as text. * * If the input is not a number an empty string is returned. * * @param {number|string} number Number to format. * @param {(number|string)=} fractionSize Number of decimal places to round the number to. * If this is not provided then the fraction size is computed from the current locale's number * formatting pattern. In the case of the default locale, it will be 3. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. * * @example <example module="numberFilterExample"> <file name="index.html"> <script> angular.module('numberFilterExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.val = 1234.56789; }]); </script> <div ng-controller="ExampleController"> Enter number: <input ng-model='val'><br> Default formatting: <span id='number-default'>{{val | number}}</span><br> No fractions: <span>{{val | number:0}}</span><br> Negative number: <span>{{-val | number:4}}</span> </div> </file> <file name="protractor.js" type="protractor"> it('should format numbers', function() { expect(element(by.id('number-default')).getText()).toBe('1,234.568'); expect(element(by.binding('val | number:0')).getText()).toBe('1,235'); expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679'); }); it('should update', function() { element(by.model('val')).clear(); element(by.model('val')).sendKeys('3374.333'); expect(element(by.id('number-default')).getText()).toBe('3,374.333'); expect(element(by.binding('val | number:0')).getText()).toBe('3,374'); expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330'); }); </file> </example> */ numberFilter.$inject = ['$locale']; function numberFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(number, fractionSize) { // if null or undefined pass it through return (number == null) ? number : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize); }; } var DECIMAL_SEP = '.'; function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { if (!isFinite(number) || isObject(number)) return ''; var isNegative = number < 0; number = Math.abs(number); var numStr = number + '', formatedText = '', parts = []; var hasExponent = false; if (numStr.indexOf('e') !== -1) { var match = numStr.match(/([\d\.]+)e(-?)(\d+)/); if (match && match[2] == '-' && match[3] > fractionSize + 1) { number = 0; } else { formatedText = numStr; hasExponent = true; } } if (!hasExponent) { var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; // determine fractionSize if it is not specified if (isUndefined(fractionSize)) { fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); } // safely round numbers in JS without hitting imprecisions of floating-point arithmetics // inspired by: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize); var fraction = ('' + number).split(DECIMAL_SEP); var whole = fraction[0]; fraction = fraction[1] || ''; var i, pos = 0, lgroup = pattern.lgSize, group = pattern.gSize; if (whole.length >= (lgroup + group)) { pos = whole.length - lgroup; for (i = 0; i < pos; i++) { if ((pos - i) % group === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } } for (i = pos; i < whole.length; i++) { if ((whole.length - i) % lgroup === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } // format fraction part. while (fraction.length < fractionSize) { fraction += '0'; } if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize); } else { if (fractionSize > 0 && number < 1) { formatedText = number.toFixed(fractionSize); number = parseFloat(formatedText); } } if (number === 0) { isNegative = false; } parts.push(isNegative ? pattern.negPre : pattern.posPre, formatedText, isNegative ? pattern.negSuf : pattern.posSuf); return parts.join(''); } function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while (num.length < digits) num = '0' + num; if (trim) num = num.substr(num.length - digits); return neg + num; } function dateGetter(name, size, offset, trim) { offset = offset || 0; return function(date) { var value = date['get' + name](); if (offset > 0 || value > -offset) value += offset; if (value === 0 && offset == -12) value = 12; return padNumber(value, size, trim); }; } function dateStrGetter(name, shortForm) { return function(date, formats) { var value = date['get' + name](); var get = uppercase(shortForm ? ('SHORT' + name) : name); return formats[get][value]; }; } function timeZoneGetter(date) { var zone = -1 * date.getTimezoneOffset(); var paddedZone = (zone >= 0) ? "+" : ""; paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) + padNumber(Math.abs(zone % 60), 2); return paddedZone; } function getFirstThursdayOfYear(year) { // 0 = index of January var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay(); // 4 = index of Thursday (+1 to account for 1st = 5) // 11 = index of *next* Thursday (+1 account for 1st = 12) return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst); } function getThursdayThisWeek(datetime) { return new Date(datetime.getFullYear(), datetime.getMonth(), // 4 = index of Thursday datetime.getDate() + (4 - datetime.getDay())); } function weekGetter(size) { return function(date) { var firstThurs = getFirstThursdayOfYear(date.getFullYear()), thisThurs = getThursdayThisWeek(date); var diff = +thisThurs - +firstThurs, result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week return padNumber(result, size); }; } function ampmGetter(date, formats) { return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; } var DATE_FORMATS = { yyyy: dateGetter('FullYear', 4), yy: dateGetter('FullYear', 2, 0, true), y: dateGetter('FullYear', 1), MMMM: dateStrGetter('Month'), MMM: dateStrGetter('Month', true), MM: dateGetter('Month', 2, 1), M: dateGetter('Month', 1, 1), dd: dateGetter('Date', 2), d: dateGetter('Date', 1), HH: dateGetter('Hours', 2), H: dateGetter('Hours', 1), hh: dateGetter('Hours', 2, -12), h: dateGetter('Hours', 1, -12), mm: dateGetter('Minutes', 2), m: dateGetter('Minutes', 1), ss: dateGetter('Seconds', 2), s: dateGetter('Seconds', 1), // while ISO 8601 requires fractions to be prefixed with `.` or `,` // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions sss: dateGetter('Milliseconds', 3), EEEE: dateStrGetter('Day'), EEE: dateStrGetter('Day', true), a: ampmGetter, Z: timeZoneGetter, ww: weekGetter(2), w: weekGetter(1) }; var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEw']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|w+))(.*)/, NUMBER_STRING = /^\-?\d+$/; /** * @ngdoc filter * @name date * @kind function * * @description * Formats `date` to a string based on the requested `format`. * * `format` string can be composed of the following elements: * * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) * * `'MMMM'`: Month in year (January-December) * * `'MMM'`: Month in year (Jan-Dec) * * `'MM'`: Month in year, padded (01-12) * * `'M'`: Month in year (1-12) * * `'dd'`: Day in month, padded (01-31) * * `'d'`: Day in month (1-31) * * `'EEEE'`: Day in Week,(Sunday-Saturday) * * `'EEE'`: Day in Week, (Sun-Sat) * * `'HH'`: Hour in day, padded (00-23) * * `'H'`: Hour in day (0-23) * * `'hh'`: Hour in AM/PM, padded (01-12) * * `'h'`: Hour in AM/PM, (1-12) * * `'mm'`: Minute in hour, padded (00-59) * * `'m'`: Minute in hour (0-59) * * `'ss'`: Second in minute, padded (00-59) * * `'s'`: Second in minute (0-59) * * `'sss'`: Millisecond in second, padded (000-999) * * `'a'`: AM/PM marker * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200) * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year * * `format` string can also be one of the following predefined * {@link guide/i18n localizable formats}: * * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale * (e.g. Sep 3, 2010 12:05:08 PM) * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM) * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale * (e.g. Friday, September 3, 2010) * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010) * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM) * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM) * * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence * (e.g. `"h 'o''clock'"`). * * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is * specified in the string input, the time is considered to be in the local timezone. * @param {string=} format Formatting rules (see Description). If not specified, * `mediumDate` is used. * @param {string=} timezone Timezone to be used for formatting. Right now, only `'UTC'` is supported. * If not specified, the timezone of the browser will be used. * @returns {string} Formatted string or the input if input is not recognized as date/millis. * * @example <example> <file name="index.html"> <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>: <span>{{1288323623006 | date:'medium'}}</span><br> <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>: <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br> <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>: <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br> <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>: <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br> </file> <file name="protractor.js" type="protractor"> it('should format date', function() { expect(element(by.binding("1288323623006 | date:'medium'")).getText()). toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()). toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/); expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()). toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()). toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/); }); </file> </example> */ dateFilter.$inject = ['$locale']; function dateFilter($locale) { var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; // 1 2 3 4 5 6 7 8 9 10 11 function jsonStringToDate(string) { var match; if (match = string.match(R_ISO8601_STR)) { var date = new Date(0), tzHour = 0, tzMin = 0, dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear, timeSetter = match[8] ? date.setUTCHours : date.setHours; if (match[9]) { tzHour = int(match[9] + match[10]); tzMin = int(match[9] + match[11]); } dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3])); var h = int(match[4] || 0) - tzHour; var m = int(match[5] || 0) - tzMin; var s = int(match[6] || 0); var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000); timeSetter.call(date, h, m, s, ms); return date; } return string; } return function(date, format, timezone) { var text = '', parts = [], fn, match; format = format || 'mediumDate'; format = $locale.DATETIME_FORMATS[format] || format; if (isString(date)) { date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date); } if (isNumber(date)) { date = new Date(date); } if (!isDate(date)) { return date; } while (format) { match = DATE_FORMATS_SPLIT.exec(format); if (match) { parts = concat(parts, match, 1); format = parts.pop(); } else { parts.push(format); format = null; } } if (timezone && timezone === 'UTC') { date = new Date(date.getTime()); date.setMinutes(date.getMinutes() + date.getTimezoneOffset()); } forEach(parts, function(value) { fn = DATE_FORMATS[value]; text += fn ? fn(date, $locale.DATETIME_FORMATS) : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); }); return text; }; } /** * @ngdoc filter * @name json * @kind function * * @description * Allows you to convert a JavaScript object into JSON string. * * This filter is mostly useful for debugging. When using the double curly {{value}} notation * the binding is automatically converted to JSON. * * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2. * @returns {string} JSON string. * * * @example <example> <file name="index.html"> <pre id="default-spacing">{{ {'name':'value'} | json }}</pre> <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre> </file> <file name="protractor.js" type="protractor"> it('should jsonify filtered objects', function() { expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/); expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/); }); </file> </example> * */ function jsonFilter() { return function(object, spacing) { if (isUndefined(spacing)) { spacing = 2; } return toJson(object, spacing); }; } /** * @ngdoc filter * @name lowercase * @kind function * @description * Converts string to lowercase. * @see angular.lowercase */ var lowercaseFilter = valueFn(lowercase); /** * @ngdoc filter * @name uppercase * @kind function * @description * Converts string to uppercase. * @see angular.uppercase */ var uppercaseFilter = valueFn(uppercase); /** * @ngdoc filter * @name limitTo * @kind function * * @description * Creates a new array or string containing only a specified number of elements. The elements * are taken from either the beginning or the end of the source array, string or number, as specified by * the value and sign (positive or negative) of `limit`. If a number is used as input, it is * converted to a string. * * @param {Array|string|number} input Source array, string or number to be limited. * @param {string|number} limit The length of the returned array or string. If the `limit` number * is positive, `limit` number of items from the beginning of the source array/string are copied. * If the number is negative, `limit` number of items from the end of the source array/string * are copied. The `limit` will be trimmed if it exceeds `array.length` * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array * had less than `limit` elements. * * @example <example module="limitToExample"> <file name="index.html"> <script> angular.module('limitToExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.numbers = [1,2,3,4,5,6,7,8,9]; $scope.letters = "abcdefghi"; $scope.longNumber = 2345432342; $scope.numLimit = 3; $scope.letterLimit = 3; $scope.longNumberLimit = 3; }]); </script> <div ng-controller="ExampleController"> Limit {{numbers}} to: <input type="number" step="1" ng-model="numLimit"> <p>Output numbers: {{ numbers | limitTo:numLimit }}</p> Limit {{letters}} to: <input type="number" step="1" ng-model="letterLimit"> <p>Output letters: {{ letters | limitTo:letterLimit }}</p> Limit {{longNumber}} to: <input type="number" step="1" ng-model="longNumberLimit"> <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p> </div> </file> <file name="protractor.js" type="protractor"> var numLimitInput = element(by.model('numLimit')); var letterLimitInput = element(by.model('letterLimit')); var longNumberLimitInput = element(by.model('longNumberLimit')); var limitedNumbers = element(by.binding('numbers | limitTo:numLimit')); var limitedLetters = element(by.binding('letters | limitTo:letterLimit')); var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit')); it('should limit the number array to first three items', function() { expect(numLimitInput.getAttribute('value')).toBe('3'); expect(letterLimitInput.getAttribute('value')).toBe('3'); expect(longNumberLimitInput.getAttribute('value')).toBe('3'); expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]'); expect(limitedLetters.getText()).toEqual('Output letters: abc'); expect(limitedLongNumber.getText()).toEqual('Output long number: 234'); }); // There is a bug in safari and protractor that doesn't like the minus key // it('should update the output when -3 is entered', function() { // numLimitInput.clear(); // numLimitInput.sendKeys('-3'); // letterLimitInput.clear(); // letterLimitInput.sendKeys('-3'); // longNumberLimitInput.clear(); // longNumberLimitInput.sendKeys('-3'); // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]'); // expect(limitedLetters.getText()).toEqual('Output letters: ghi'); // expect(limitedLongNumber.getText()).toEqual('Output long number: 342'); // }); it('should not exceed the maximum size of input array', function() { numLimitInput.clear(); numLimitInput.sendKeys('100'); letterLimitInput.clear(); letterLimitInput.sendKeys('100'); longNumberLimitInput.clear(); longNumberLimitInput.sendKeys('100'); expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]'); expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi'); expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342'); }); </file> </example> */ function limitToFilter() { return function(input, limit) { if (isNumber(input)) input = input.toString(); if (!isArray(input) && !isString(input)) return input; if (Math.abs(Number(limit)) === Infinity) { limit = Number(limit); } else { limit = int(limit); } //NaN check on limit if (limit) { return limit > 0 ? input.slice(0, limit) : input.slice(limit); } else { return isString(input) ? "" : []; } }; } /** * @ngdoc filter * @name orderBy * @kind function * * @description * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically * for strings and numerically for numbers. Note: if you notice numbers are not being sorted * correctly, make sure they are actually being saved as numbers and not strings. * * @param {Array} array The array to sort. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be * used by the comparator to determine the order of elements. * * Can be one of: * * - `function`: Getter function. The result of this function will be sorted using the * `<`, `=`, `>` operator. * - `string`: An Angular expression. The result of this expression is used to compare elements * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by * 3 first characters of a property called `name`). The result of a constant expression * is interpreted as a property name to be used in comparisons (for example `"special name"` * to sort object by the value of their `special name` property). An expression can be * optionally prefixed with `+` or `-` to control ascending or descending sort order * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array * element itself is used to compare where sorting. * - `Array`: An array of function or string predicates. The first predicate in the array * is used for sorting, but when two items are equivalent, the next predicate is used. * * If the predicate is missing or empty then it defaults to `'+'`. * * @param {boolean=} reverse Reverse the order of the array. * @returns {Array} Sorted copy of the source array. * * @example <example module="orderByExample"> <file name="index.html"> <script> angular.module('orderByExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.friends = [{name:'John', phone:'555-1212', age:10}, {name:'Mary', phone:'555-9876', age:19}, {name:'Mike', phone:'555-4321', age:21}, {name:'Adam', phone:'555-5678', age:35}, {name:'Julie', phone:'555-8765', age:29}]; $scope.predicate = '-age'; }]); </script> <div ng-controller="ExampleController"> <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre> <hr/> [ <a href="" ng-click="predicate=''">unsorted</a> ] <table class="friend"> <tr> <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a> (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th> <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th> <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th> </tr> <tr ng-repeat="friend in friends | orderBy:predicate:reverse"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> </tr> </table> </div> </file> </example> * * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the * desired parameters. * * Example: * * @example <example module="orderByExample"> <file name="index.html"> <div ng-controller="ExampleController"> <table class="friend"> <tr> <th><a href="" ng-click="reverse=false;order('name', false)">Name</a> (<a href="" ng-click="order('-name',false)">^</a>)</th> <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th> <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th> </tr> <tr ng-repeat="friend in friends"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> </tr> </table> </div> </file> <file name="script.js"> angular.module('orderByExample', []) .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) { var orderBy = $filter('orderBy'); $scope.friends = [ { name: 'John', phone: '555-1212', age: 10 }, { name: 'Mary', phone: '555-9876', age: 19 }, { name: 'Mike', phone: '555-4321', age: 21 }, { name: 'Adam', phone: '555-5678', age: 35 }, { name: 'Julie', phone: '555-8765', age: 29 } ]; $scope.order = function(predicate, reverse) { $scope.friends = orderBy($scope.friends, predicate, reverse); }; $scope.order('-age',false); }]); </file> </example> */ orderByFilter.$inject = ['$parse']; function orderByFilter($parse) { return function(array, sortPredicate, reverseOrder) { if (!(isArrayLike(array))) return array; sortPredicate = isArray(sortPredicate) ? sortPredicate : [sortPredicate]; if (sortPredicate.length === 0) { sortPredicate = ['+']; } sortPredicate = sortPredicate.map(function(predicate) { var descending = false, get = predicate || identity; if (isString(predicate)) { if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { descending = predicate.charAt(0) == '-'; predicate = predicate.substring(1); } if (predicate === '') { // Effectively no predicate was passed so we compare identity return reverseComparator(compare, descending); } get = $parse(predicate); if (get.constant) { var key = get(); return reverseComparator(function(a, b) { return compare(a[key], b[key]); }, descending); } } return reverseComparator(function(a, b) { return compare(get(a),get(b)); }, descending); }); return slice.call(array).sort(reverseComparator(comparator, reverseOrder)); function comparator(o1, o2) { for (var i = 0; i < sortPredicate.length; i++) { var comp = sortPredicate[i](o1, o2); if (comp !== 0) return comp; } return 0; } function reverseComparator(comp, descending) { return descending ? function(a, b) {return comp(b,a);} : comp; } function isPrimitive(value) { switch (typeof value) { case 'number': /* falls through */ case 'boolean': /* falls through */ case 'string': return true; default: return false; } } function objectToString(value) { if (value === null) return 'null'; if (typeof value.valueOf === 'function') { value = value.valueOf(); if (isPrimitive(value)) return value; } if (typeof value.toString === 'function') { value = value.toString(); if (isPrimitive(value)) return value; } return ''; } function compare(v1, v2) { var t1 = typeof v1; var t2 = typeof v2; if (t1 === t2 && t1 === "object") { v1 = objectToString(v1); v2 = objectToString(v2); } if (t1 === t2) { if (t1 === "string") { v1 = v1.toLowerCase(); v2 = v2.toLowerCase(); } if (v1 === v2) return 0; return v1 < v2 ? -1 : 1; } else { return t1 < t2 ? -1 : 1; } } }; } function ngDirective(directive) { if (isFunction(directive)) { directive = { link: directive }; } directive.restrict = directive.restrict || 'AC'; return valueFn(directive); } /** * @ngdoc directive * @name a * @restrict E * * @description * Modifies the default behavior of the html A tag so that the default action is prevented when * the href attribute is empty. * * This change permits the easy creation of action links with the `ngClick` directive * without changing the location or causing page reloads, e.g.: * `<a href="" ng-click="list.addItem()">Add Item</a>` */ var htmlAnchorDirective = valueFn({ restrict: 'E', compile: function(element, attr) { if (!attr.href && !attr.xlinkHref && !attr.name) { return function(scope, element) { // If the linked element is not an anchor tag anymore, do nothing if (element[0].nodeName.toLowerCase() !== 'a') return; // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ? 'xlink:href' : 'href'; element.on('click', function(event) { // if we have no href url, then don't navigate anywhere. if (!element.attr(href)) { event.preventDefault(); } }); }; } } }); /** * @ngdoc directive * @name ngHref * @restrict A * @priority 99 * * @description * Using Angular markup like `{{hash}}` in an href attribute will * make the link go to the wrong URL if the user clicks it before * Angular has a chance to replace the `{{hash}}` markup with its * value. Until Angular replaces the markup the link will be broken * and will most likely return a 404 error. The `ngHref` directive * solves this problem. * * The wrong way to write it: * ```html * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a> * ``` * * The correct way to write it: * ```html * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a> * ``` * * @element A * @param {template} ngHref any string which can contain `{{}}` markup. * * @example * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes * in links and their different behaviors: <example> <file name="index.html"> <input ng-model="value" /><br /> <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br /> <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br /> <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br /> <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br /> <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br /> <a id="link-6" ng-href="{{value}}">link</a> (link, change location) </file> <file name="protractor.js" type="protractor"> it('should execute ng-click but not reload when href without value', function() { element(by.id('link-1')).click(); expect(element(by.model('value')).getAttribute('value')).toEqual('1'); expect(element(by.id('link-1')).getAttribute('href')).toBe(''); }); it('should execute ng-click but not reload when href empty string', function() { element(by.id('link-2')).click(); expect(element(by.model('value')).getAttribute('value')).toEqual('2'); expect(element(by.id('link-2')).getAttribute('href')).toBe(''); }); it('should execute ng-click and change url when ng-href specified', function() { expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/); element(by.id('link-3')).click(); // At this point, we navigate away from an Angular page, so we need // to use browser.driver to get the base webdriver. browser.wait(function() { return browser.driver.getCurrentUrl().then(function(url) { return url.match(/\/123$/); }); }, 5000, 'page should navigate to /123'); }); xit('should execute ng-click but not reload when href empty string and name specified', function() { element(by.id('link-4')).click(); expect(element(by.model('value')).getAttribute('value')).toEqual('4'); expect(element(by.id('link-4')).getAttribute('href')).toBe(''); }); it('should execute ng-click but not reload when no href but name specified', function() { element(by.id('link-5')).click(); expect(element(by.model('value')).getAttribute('value')).toEqual('5'); expect(element(by.id('link-5')).getAttribute('href')).toBe(null); }); it('should only change url when only ng-href', function() { element(by.model('value')).clear(); element(by.model('value')).sendKeys('6'); expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/); element(by.id('link-6')).click(); // At this point, we navigate away from an Angular page, so we need // to use browser.driver to get the base webdriver. browser.wait(function() { return browser.driver.getCurrentUrl().then(function(url) { return url.match(/\/6$/); }); }, 5000, 'page should navigate to /6'); }); </file> </example> */ /** * @ngdoc directive * @name ngSrc * @restrict A * @priority 99 * * @description * Using Angular markup like `{{hash}}` in a `src` attribute doesn't * work right: The browser will fetch from the URL with the literal * text `{{hash}}` until Angular replaces the expression inside * `{{hash}}`. The `ngSrc` directive solves this problem. * * The buggy way to write it: * ```html * <img src="http://www.gravatar.com/avatar/{{hash}}"/> * ``` * * The correct way to write it: * ```html * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/> * ``` * * @element IMG * @param {template} ngSrc any string which can contain `{{}}` markup. */ /** * @ngdoc directive * @name ngSrcset * @restrict A * @priority 99 * * @description * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't * work right: The browser will fetch from the URL with the literal * text `{{hash}}` until Angular replaces the expression inside * `{{hash}}`. The `ngSrcset` directive solves this problem. * * The buggy way to write it: * ```html * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/> * ``` * * The correct way to write it: * ```html * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/> * ``` * * @element IMG * @param {template} ngSrcset any string which can contain `{{}}` markup. */ /** * @ngdoc directive * @name ngDisabled * @restrict A * @priority 100 * * @description * * We shouldn't do this, because it will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: * ```html * <div ng-init="scope = { isDisabled: false }"> * <button disabled="{{scope.isDisabled}}">Disabled</button> * </div> * ``` * * The HTML specification does not require browsers to preserve the values of boolean attributes * such as disabled. (Their presence means true and their absence means false.) * If we put an Angular interpolation expression into such an attribute then the * binding information would be lost when the browser removes the attribute. * The `ngDisabled` directive solves this problem for the `disabled` attribute. * This complementary directive is not removed by the browser and so provides * a permanent reliable place to store the binding information. * * @example <example> <file name="index.html"> Click me to toggle: <input type="checkbox" ng-model="checked"><br/> <button ng-model="button" ng-disabled="checked">Button</button> </file> <file name="protractor.js" type="protractor"> it('should toggle button', function() { expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy(); element(by.model('checked')).click(); expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy(); }); </file> </example> * * @element INPUT * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy, * then special attribute "disabled" will be set on the element */ /** * @ngdoc directive * @name ngChecked * @restrict A * @priority 100 * * @description * The HTML specification does not require browsers to preserve the values of boolean attributes * such as checked. (Their presence means true and their absence means false.) * If we put an Angular interpolation expression into such an attribute then the * binding information would be lost when the browser removes the attribute. * The `ngChecked` directive solves this problem for the `checked` attribute. * This complementary directive is not removed by the browser and so provides * a permanent reliable place to store the binding information. * @example <example> <file name="index.html"> Check me to check both: <input type="checkbox" ng-model="master"><br/> <input id="checkSlave" type="checkbox" ng-checked="master"> </file> <file name="protractor.js" type="protractor"> it('should check both checkBoxes', function() { expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy(); element(by.model('master')).click(); expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy(); }); </file> </example> * * @element INPUT * @param {expression} ngChecked If the {@link guide/expression expression} is truthy, * then special attribute "checked" will be set on the element */ /** * @ngdoc directive * @name ngReadonly * @restrict A * @priority 100 * * @description * The HTML specification does not require browsers to preserve the values of boolean attributes * such as readonly. (Their presence means true and their absence means false.) * If we put an Angular interpolation expression into such an attribute then the * binding information would be lost when the browser removes the attribute. * The `ngReadonly` directive solves this problem for the `readonly` attribute. * This complementary directive is not removed by the browser and so provides * a permanent reliable place to store the binding information. * @example <example> <file name="index.html"> Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/> <input type="text" ng-readonly="checked" value="I'm Angular"/> </file> <file name="protractor.js" type="protractor"> it('should toggle readonly attr', function() { expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy(); element(by.model('checked')).click(); expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy(); }); </file> </example> * * @element INPUT * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy, * then special attribute "readonly" will be set on the element */ /** * @ngdoc directive * @name ngSelected * @restrict A * @priority 100 * * @description * The HTML specification does not require browsers to preserve the values of boolean attributes * such as selected. (Their presence means true and their absence means false.) * If we put an Angular interpolation expression into such an attribute then the * binding information would be lost when the browser removes the attribute. * The `ngSelected` directive solves this problem for the `selected` attribute. * This complementary directive is not removed by the browser and so provides * a permanent reliable place to store the binding information. * * @example <example> <file name="index.html"> Check me to select: <input type="checkbox" ng-model="selected"><br/> <select> <option>Hello!</option> <option id="greet" ng-selected="selected">Greetings!</option> </select> </file> <file name="protractor.js" type="protractor"> it('should select Greetings!', function() { expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy(); element(by.model('selected')).click(); expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy(); }); </file> </example> * * @element OPTION * @param {expression} ngSelected If the {@link guide/expression expression} is truthy, * then special attribute "selected" will be set on the element */ /** * @ngdoc directive * @name ngOpen * @restrict A * @priority 100 * * @description * The HTML specification does not require browsers to preserve the values of boolean attributes * such as open. (Their presence means true and their absence means false.) * If we put an Angular interpolation expression into such an attribute then the * binding information would be lost when the browser removes the attribute. * The `ngOpen` directive solves this problem for the `open` attribute. * This complementary directive is not removed by the browser and so provides * a permanent reliable place to store the binding information. * @example <example> <file name="index.html"> Check me check multiple: <input type="checkbox" ng-model="open"><br/> <details id="details" ng-open="open"> <summary>Show/Hide me</summary> </details> </file> <file name="protractor.js" type="protractor"> it('should toggle open', function() { expect(element(by.id('details')).getAttribute('open')).toBeFalsy(); element(by.model('open')).click(); expect(element(by.id('details')).getAttribute('open')).toBeTruthy(); }); </file> </example> * * @element DETAILS * @param {expression} ngOpen If the {@link guide/expression expression} is truthy, * then special attribute "open" will be set on the element */ var ngAttributeAliasDirectives = {}; // boolean attrs are evaluated forEach(BOOLEAN_ATTR, function(propName, attrName) { // binding to multiple is not supported if (propName == "multiple") return; var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { restrict: 'A', priority: 100, link: function(scope, element, attr) { scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { attr.$set(attrName, !!value); }); } }; }; }); // aliased input attrs are evaluated forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) { ngAttributeAliasDirectives[ngAttr] = function() { return { priority: 100, link: function(scope, element, attr) { //special case ngPattern when a literal regular expression value //is used as the expression (this way we don't have to watch anything). if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") { var match = attr.ngPattern.match(REGEX_STRING_REGEXP); if (match) { attr.$set("ngPattern", new RegExp(match[1], match[2])); return; } } scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) { attr.$set(ngAttr, value); }); } }; }; }); // ng-src, ng-srcset, ng-href are interpolated forEach(['src', 'srcset', 'href'], function(attrName) { var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { priority: 99, // it needs to run after the attributes are interpolated link: function(scope, element, attr) { var propName = attrName, name = attrName; if (attrName === 'href' && toString.call(element.prop('href')) === '[object SVGAnimatedString]') { name = 'xlinkHref'; attr.$attr[name] = 'xlink:href'; propName = null; } attr.$observe(normalized, function(value) { if (!value) { if (attrName === 'href') { attr.$set(name, null); } return; } attr.$set(name, value); // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need // to set the property as well to achieve the desired effect. // we use attr[attrName] value since $set can sanitize the url. if (msie && propName) element.prop(propName, attr[name]); }); } }; }; }); /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true */ var nullFormCtrl = { $addControl: noop, $$renameControl: nullFormRenameControl, $removeControl: noop, $setValidity: noop, $setDirty: noop, $setPristine: noop, $setSubmitted: noop }, SUBMITTED_CLASS = 'ng-submitted'; function nullFormRenameControl(control, name) { control.$name = name; } /** * @ngdoc type * @name form.FormController * * @property {boolean} $pristine True if user has not interacted with the form yet. * @property {boolean} $dirty True if user has already interacted with the form. * @property {boolean} $valid True if all of the containing forms and controls are valid. * @property {boolean} $invalid True if at least one containing control or form is invalid. * @property {boolean} $submitted True if user has submitted the form even if its invalid. * * @property {Object} $error Is an object hash, containing references to controls or * forms with failing validators, where: * * - keys are validation tokens (error names), * - values are arrays of controls or forms that have a failing validator for given error name. * * Built-in validation tokens: * * - `email` * - `max` * - `maxlength` * - `min` * - `minlength` * - `number` * - `pattern` * - `required` * - `url` * - `date` * - `datetimelocal` * - `time` * - `week` * - `month` * * @description * `FormController` keeps track of all its controls and nested forms as well as the state of them, * such as being valid/invalid or dirty/pristine. * * Each {@link ng.directive:form form} directive creates an instance * of `FormController`. * */ //asks for $scope to fool the BC controller module FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate']; function FormController(element, attrs, $scope, $animate, $interpolate) { var form = this, controls = []; var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl; // init state form.$error = {}; form.$$success = {}; form.$pending = undefined; form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope); form.$dirty = false; form.$pristine = true; form.$valid = true; form.$invalid = false; form.$submitted = false; parentForm.$addControl(form); /** * @ngdoc method * @name form.FormController#$rollbackViewValue * * @description * Rollback all form controls pending updates to the `$modelValue`. * * Updates may be pending by a debounced event or because the input is waiting for a some future * event defined in `ng-model-options`. This method is typically needed by the reset button of * a form that uses `ng-model-options` to pend updates. */ form.$rollbackViewValue = function() { forEach(controls, function(control) { control.$rollbackViewValue(); }); }; /** * @ngdoc method * @name form.FormController#$commitViewValue * * @description * Commit all form controls pending updates to the `$modelValue`. * * Updates may be pending by a debounced event or because the input is waiting for a some future * event defined in `ng-model-options`. This method is rarely needed as `NgModelController` * usually handles calling this in response to input events. */ form.$commitViewValue = function() { forEach(controls, function(control) { control.$commitViewValue(); }); }; /** * @ngdoc method * @name form.FormController#$addControl * * @description * Register a control with the form. * * Input elements using ngModelController do this automatically when they are linked. */ form.$addControl = function(control) { // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored // and not added to the scope. Now we throw an error. assertNotHasOwnProperty(control.$name, 'input'); controls.push(control); if (control.$name) { form[control.$name] = control; } }; // Private API: rename a form control form.$$renameControl = function(control, newName) { var oldName = control.$name; if (form[oldName] === control) { delete form[oldName]; } form[newName] = control; control.$name = newName; }; /** * @ngdoc method * @name form.FormController#$removeControl * * @description * Deregister a control from the form. * * Input elements using ngModelController do this automatically when they are destroyed. */ form.$removeControl = function(control) { if (control.$name && form[control.$name] === control) { delete form[control.$name]; } forEach(form.$pending, function(value, name) { form.$setValidity(name, null, control); }); forEach(form.$error, function(value, name) { form.$setValidity(name, null, control); }); forEach(form.$$success, function(value, name) { form.$setValidity(name, null, control); }); arrayRemove(controls, control); }; /** * @ngdoc method * @name form.FormController#$setValidity * * @description * Sets the validity of a form control. * * This method will also propagate to parent forms. */ addSetValidityMethod({ ctrl: this, $element: element, set: function(object, property, controller) { var list = object[property]; if (!list) { object[property] = [controller]; } else { var index = list.indexOf(controller); if (index === -1) { list.push(controller); } } }, unset: function(object, property, controller) { var list = object[property]; if (!list) { return; } arrayRemove(list, controller); if (list.length === 0) { delete object[property]; } }, parentForm: parentForm, $animate: $animate }); /** * @ngdoc method * @name form.FormController#$setDirty * * @description * Sets the form to a dirty state. * * This method can be called to add the 'ng-dirty' class and set the form to a dirty * state (ng-dirty class). This method will also propagate to parent forms. */ form.$setDirty = function() { $animate.removeClass(element, PRISTINE_CLASS); $animate.addClass(element, DIRTY_CLASS); form.$dirty = true; form.$pristine = false; parentForm.$setDirty(); }; /** * @ngdoc method * @name form.FormController#$setPristine * * @description * Sets the form to its pristine state. * * This method can be called to remove the 'ng-dirty' class and set the form to its pristine * state (ng-pristine class). This method will also propagate to all the controls contained * in this form. * * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after * saving or resetting it. */ form.$setPristine = function() { $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS); form.$dirty = false; form.$pristine = true; form.$submitted = false; forEach(controls, function(control) { control.$setPristine(); }); }; /** * @ngdoc method * @name form.FormController#$setUntouched * * @description * Sets the form to its untouched state. * * This method can be called to remove the 'ng-touched' class and set the form controls to their * untouched state (ng-untouched class). * * Setting a form controls back to their untouched state is often useful when setting the form * back to its pristine state. */ form.$setUntouched = function() { forEach(controls, function(control) { control.$setUntouched(); }); }; /** * @ngdoc method * @name form.FormController#$setSubmitted * * @description * Sets the form to its submitted state. */ form.$setSubmitted = function() { $animate.addClass(element, SUBMITTED_CLASS); form.$submitted = true; parentForm.$setSubmitted(); }; } /** * @ngdoc directive * @name ngForm * @restrict EAC * * @description * Nestable alias of {@link ng.directive:form `form`} directive. HTML * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a * sub-group of controls needs to be determined. * * Note: the purpose of `ngForm` is to group controls, * but not to be a replacement for the `<form>` tag with all of its capabilities * (e.g. posting to the server, ...). * * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into * related scope, under this name. * */ /** * @ngdoc directive * @name form * @restrict E * * @description * Directive that instantiates * {@link form.FormController FormController}. * * If the `name` attribute is specified, the form controller is published onto the current scope under * this name. * * # Alias: {@link ng.directive:ngForm `ngForm`} * * In Angular forms can be nested. This means that the outer form is valid when all of the child * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to * `<form>` but can be nested. This allows you to have nested forms, which is very useful when * using Angular validation directives in forms that are dynamically generated using the * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name` * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an * `ngForm` directive and nest these in an outer `form` element. * * * # CSS classes * - `ng-valid` is set if the form is valid. * - `ng-invalid` is set if the form is invalid. * - `ng-pristine` is set if the form is pristine. * - `ng-dirty` is set if the form is dirty. * - `ng-submitted` is set if the form was submitted. * * Keep in mind that ngAnimate can detect each of these classes when added and removed. * * * # Submitting a form and preventing the default action * * Since the role of forms in client-side Angular applications is different than in classical * roundtrip apps, it is desirable for the browser not to translate the form submission into a full * page reload that sends the data to the server. Instead some javascript logic should be triggered * to handle the form submission in an application-specific way. * * For this reason, Angular prevents the default action (form submission to the server) unless the * `<form>` element has an `action` attribute specified. * * You can use one of the following two ways to specify what javascript method should be called when * a form is submitted: * * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element * - {@link ng.directive:ngClick ngClick} directive on the first * button or input field of type submit (input[type=submit]) * * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit} * or {@link ng.directive:ngClick ngClick} directives. * This is because of the following form submission rules in the HTML specification: * * - If a form has only one input field then hitting enter in this field triggers form submit * (`ngSubmit`) * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter * doesn't trigger submit * - if a form has one or more input fields and one or more buttons or input[type=submit] then * hitting enter in any of the input fields will trigger the click handler on the *first* button or * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`) * * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit` * to have access to the updated model. * * ## Animation Hooks * * Animations in ngForm are triggered when any of the associated CSS classes are added and removed. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any * other validations that are performed within the form. Animations in ngForm are similar to how * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well * as JS animations. * * The following example shows a simple way to utilize CSS transitions to style a form element * that has been rendered as invalid after it has been validated: * * <pre> * //be sure to include ngAnimate as a module to hook into more * //advanced animations * .my-form { * transition:0.5s linear all; * background: white; * } * .my-form.ng-invalid { * background: red; * color:white; * } * </pre> * * @example <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample"> <file name="index.html"> <script> angular.module('formExample', []) .controller('FormController', ['$scope', function($scope) { $scope.userType = 'guest'; }]); </script> <style> .my-form { -webkit-transition:all linear 0.5s; transition:all linear 0.5s; background: transparent; } .my-form.ng-invalid { background: red; } </style> <form name="myForm" ng-controller="FormController" class="my-form"> userType: <input name="input" ng-model="userType" required> <span class="error" ng-show="myForm.input.$error.required">Required!</span><br> <tt>userType = {{userType}}</tt><br> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br> </form> </file> <file name="protractor.js" type="protractor"> it('should initialize to model', function() { var userType = element(by.binding('userType')); var valid = element(by.binding('myForm.input.$valid')); expect(userType.getText()).toContain('guest'); expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { var userType = element(by.binding('userType')); var valid = element(by.binding('myForm.input.$valid')); var userInput = element(by.model('userType')); userInput.clear(); userInput.sendKeys(''); expect(userType.getText()).toEqual('userType ='); expect(valid.getText()).toContain('false'); }); </file> </example> * * @param {string=} name Name of the form. If specified, the form controller will be published into * related scope, under this name. */ var formDirectiveFactory = function(isNgForm) { return ['$timeout', function($timeout) { var formDirective = { name: 'form', restrict: isNgForm ? 'EAC' : 'E', controller: FormController, compile: function ngFormCompile(formElement) { // Setup initial state of the control formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS); return { pre: function ngFormPreLink(scope, formElement, attr, controller) { // if `action` attr is not present on the form, prevent the default action (submission) if (!('action' in attr)) { // we can't use jq events because if a form is destroyed during submission the default // action is not prevented. see #1238 // // IE 9 is not affected because it doesn't fire a submit event and try to do a full // page reload if the form was destroyed by submission of the form via a click handler // on a button in the form. Looks like an IE9 specific bug. var handleFormSubmission = function(event) { scope.$apply(function() { controller.$commitViewValue(); controller.$setSubmitted(); }); event.preventDefault(); }; addEventListenerFn(formElement[0], 'submit', handleFormSubmission); // unregister the preventDefault listener so that we don't not leak memory but in a // way that will achieve the prevention of the default action. formElement.on('$destroy', function() { $timeout(function() { removeEventListenerFn(formElement[0], 'submit', handleFormSubmission); }, 0, false); }); } var parentFormCtrl = controller.$$parentForm, alias = controller.$name; if (alias) { setter(scope, null, alias, controller, alias); attr.$observe(attr.name ? 'name' : 'ngForm', function(newValue) { if (alias === newValue) return; setter(scope, null, alias, undefined, alias); alias = newValue; setter(scope, null, alias, controller, alias); parentFormCtrl.$$renameControl(controller, alias); }); } formElement.on('$destroy', function() { parentFormCtrl.$removeControl(controller); if (alias) { setter(scope, null, alias, undefined, alias); } extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards }); } }; } }; return formDirective; }]; }; var formDirective = formDirectiveFactory(); var ngFormDirective = formDirectiveFactory(true); /* global VALID_CLASS: false, INVALID_CLASS: false, PRISTINE_CLASS: false, DIRTY_CLASS: false, UNTOUCHED_CLASS: false, TOUCHED_CLASS: false, $ngModelMinErr: false, */ // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231 var ISO_DATE_REGEXP = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/; var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i; var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/; var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/; var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/; var MONTH_REGEXP = /^(\d{4})-(\d\d)$/; var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/; var inputType = { /** * @ngdoc input * @name input[text] * * @description * Standard HTML text input with angular data binding, inherited by most of the `input` elements. * * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Adds `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of * any length. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string * that contains the regular expression body that will be converted to a regular expression * as in the ngPattern directive. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match * a RegExp found by evaluating the Angular expression given in the attribute value. * If the expression evaluates to a RegExp object then this is used directly. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$` * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. * This parameter is ignored for input[type=password] controls, which will never trim the * input. * * @example <example name="text-input-directive" module="textInputExample"> <file name="index.html"> <script> angular.module('textInputExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.example = { text: 'guest', word: /^\s*\w*\s*$/ }; }]); </script> <form name="myForm" ng-controller="ExampleController"> Single word: <input type="text" name="input" ng-model="example.text" ng-pattern="example.word" required ng-trim="false"> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.pattern"> Single word only!</span> <tt>text = {{example.text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var text = element(by.binding('example.text')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('example.text')); it('should initialize to model', function() { expect(text.getText()).toContain('guest'); expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { input.clear(); input.sendKeys(''); expect(text.getText()).toEqual('text ='); expect(valid.getText()).toContain('false'); }); it('should be invalid if multi word', function() { input.clear(); input.sendKeys('hello world'); expect(valid.getText()).toContain('false'); }); </file> </example> */ 'text': textInputType, /** * @ngdoc input * @name input[date] * * @description * Input with date validation and transformation. In browsers that do not yet support * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601 * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many * modern browsers do not yet support this input type, it is important to provide cues to users on the * expected input format via a placeholder or label. * * The model must always be a Date object, otherwise Angular will throw an error. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. * * The timezone to be used to read/write the `Date` instance in the model can be defined using * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a * valid ISO date string (yyyy-MM-dd). * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be * a valid ISO date string (yyyy-MM-dd). * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="date-input-directive" module="dateInputExample"> <file name="index.html"> <script> angular.module('dateInputExample', []) .controller('DateController', ['$scope', function($scope) { $scope.example = { value: new Date(2013, 9, 22) }; }]); </script> <form name="myForm" ng-controller="DateController as dateCtrl"> Pick a date in 2013: <input type="date" id="exampleInput" name="input" ng-model="example.value" placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required /> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.date"> Not a valid date!</span> <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var value = element(by.binding('example.value | date: "yyyy-MM-dd"')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('example.value')); // currently protractor/webdriver does not support // sending keys to all known HTML5 input controls // for various browsers (see https://github.com/angular/protractor/issues/562). function setInput(val) { // set the value of the element and force validation. var scr = "var ipt = document.getElementById('exampleInput'); " + "ipt.value = '" + val + "';" + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; browser.executeScript(scr); } it('should initialize to model', function() { expect(value.getText()).toContain('2013-10-22'); expect(valid.getText()).toContain('myForm.input.$valid = true'); }); it('should be invalid if empty', function() { setInput(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); it('should be invalid if over max', function() { setInput('2015-01-01'); expect(value.getText()).toContain(''); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); </file> </example> */ 'date': createDateInputType('date', DATE_REGEXP, createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']), 'yyyy-MM-dd'), /** * @ngdoc input * @name input[datetime-local] * * @description * Input with datetime validation and transformation. In browsers that do not yet support * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`. * * The model must always be a Date object, otherwise Angular will throw an error. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. * * The timezone to be used to read/write the `Date` instance in the model can be defined using * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="datetimelocal-input-directive" module="dateExample"> <file name="index.html"> <script> angular.module('dateExample', []) .controller('DateController', ['$scope', function($scope) { $scope.example = { value: new Date(2010, 11, 28, 14, 57) }; }]); </script> <form name="myForm" ng-controller="DateController as dateCtrl"> Pick a date between in 2013: <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value" placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required /> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.datetimelocal"> Not a valid date!</span> <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('example.value')); // currently protractor/webdriver does not support // sending keys to all known HTML5 input controls // for various browsers (https://github.com/angular/protractor/issues/562). function setInput(val) { // set the value of the element and force validation. var scr = "var ipt = document.getElementById('exampleInput'); " + "ipt.value = '" + val + "';" + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; browser.executeScript(scr); } it('should initialize to model', function() { expect(value.getText()).toContain('2010-12-28T14:57:00'); expect(valid.getText()).toContain('myForm.input.$valid = true'); }); it('should be invalid if empty', function() { setInput(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); it('should be invalid if over max', function() { setInput('2015-01-01T23:59:00'); expect(value.getText()).toContain(''); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); </file> </example> */ 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP, createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']), 'yyyy-MM-ddTHH:mm:ss.sss'), /** * @ngdoc input * @name input[time] * * @description * Input with time validation and transformation. In browsers that do not yet support * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`. * * The model must always be a Date object, otherwise Angular will throw an error. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. * * The timezone to be used to read/write the `Date` instance in the model can be defined using * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a * valid ISO time format (HH:mm:ss). * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a * valid ISO time format (HH:mm:ss). * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="time-input-directive" module="timeExample"> <file name="index.html"> <script> angular.module('timeExample', []) .controller('DateController', ['$scope', function($scope) { $scope.example = { value: new Date(1970, 0, 1, 14, 57, 0) }; }]); </script> <form name="myForm" ng-controller="DateController as dateCtrl"> Pick a between 8am and 5pm: <input type="time" id="exampleInput" name="input" ng-model="example.value" placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required /> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.time"> Not a valid date!</span> <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var value = element(by.binding('example.value | date: "HH:mm:ss"')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('example.value')); // currently protractor/webdriver does not support // sending keys to all known HTML5 input controls // for various browsers (https://github.com/angular/protractor/issues/562). function setInput(val) { // set the value of the element and force validation. var scr = "var ipt = document.getElementById('exampleInput'); " + "ipt.value = '" + val + "';" + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; browser.executeScript(scr); } it('should initialize to model', function() { expect(value.getText()).toContain('14:57:00'); expect(valid.getText()).toContain('myForm.input.$valid = true'); }); it('should be invalid if empty', function() { setInput(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); it('should be invalid if over max', function() { setInput('23:59:00'); expect(value.getText()).toContain(''); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); </file> </example> */ 'time': createDateInputType('time', TIME_REGEXP, createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']), 'HH:mm:ss.sss'), /** * @ngdoc input * @name input[week] * * @description * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 * week format (yyyy-W##), for example: `2013-W02`. * * The model must always be a Date object, otherwise Angular will throw an error. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. * * The timezone to be used to read/write the `Date` instance in the model can be defined using * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a * valid ISO week format (yyyy-W##). * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be * a valid ISO week format (yyyy-W##). * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="week-input-directive" module="weekExample"> <file name="index.html"> <script> angular.module('weekExample', []) .controller('DateController', ['$scope', function($scope) { $scope.example = { value: new Date(2013, 0, 3) }; }]); </script> <form name="myForm" ng-controller="DateController as dateCtrl"> Pick a date between in 2013: <input id="exampleInput" type="week" name="input" ng-model="example.value" placeholder="YYYY-W##" min="2012-W32" max="2013-W52" required /> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.week"> Not a valid date!</span> <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var value = element(by.binding('example.value | date: "yyyy-Www"')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('example.value')); // currently protractor/webdriver does not support // sending keys to all known HTML5 input controls // for various browsers (https://github.com/angular/protractor/issues/562). function setInput(val) { // set the value of the element and force validation. var scr = "var ipt = document.getElementById('exampleInput'); " + "ipt.value = '" + val + "';" + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; browser.executeScript(scr); } it('should initialize to model', function() { expect(value.getText()).toContain('2013-W01'); expect(valid.getText()).toContain('myForm.input.$valid = true'); }); it('should be invalid if empty', function() { setInput(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); it('should be invalid if over max', function() { setInput('2015-W01'); expect(value.getText()).toContain(''); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); </file> </example> */ 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'), /** * @ngdoc input * @name input[month] * * @description * Input with month validation and transformation. In browsers that do not yet support * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 * month format (yyyy-MM), for example: `2009-01`. * * The model must always be a Date object, otherwise Angular will throw an error. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. * If the model is not set to the first of the month, the next view to model update will set it * to the first of the month. * * The timezone to be used to read/write the `Date` instance in the model can be defined using * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be * a valid ISO month format (yyyy-MM). * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must * be a valid ISO month format (yyyy-MM). * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="month-input-directive" module="monthExample"> <file name="index.html"> <script> angular.module('monthExample', []) .controller('DateController', ['$scope', function($scope) { $scope.example = { value: new Date(2013, 9, 1) }; }]); </script> <form name="myForm" ng-controller="DateController as dateCtrl"> Pick a month in 2013: <input id="exampleInput" type="month" name="input" ng-model="example.value" placeholder="yyyy-MM" min="2013-01" max="2013-12" required /> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.month"> Not a valid month!</span> <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var value = element(by.binding('example.value | date: "yyyy-MM"')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('example.value')); // currently protractor/webdriver does not support // sending keys to all known HTML5 input controls // for various browsers (https://github.com/angular/protractor/issues/562). function setInput(val) { // set the value of the element and force validation. var scr = "var ipt = document.getElementById('exampleInput'); " + "ipt.value = '" + val + "';" + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; browser.executeScript(scr); } it('should initialize to model', function() { expect(value.getText()).toContain('2013-10'); expect(valid.getText()).toContain('myForm.input.$valid = true'); }); it('should be invalid if empty', function() { setInput(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); it('should be invalid if over max', function() { setInput('2015-01'); expect(value.getText()).toContain(''); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); </file> </example> */ 'month': createDateInputType('month', MONTH_REGEXP, createDateParser(MONTH_REGEXP, ['yyyy', 'MM']), 'yyyy-MM'), /** * @ngdoc input * @name input[number] * * @description * Text input with number validation and transformation. Sets the `number` validation * error if not a valid number. * * The model must always be a number, otherwise Angular will throw an error. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of * any length. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string * that contains the regular expression body that will be converted to a regular expression * as in the ngPattern directive. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match * a RegExp found by evaluating the Angular expression given in the attribute value. * If the expression evaluates to a RegExp object then this is used directly. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$` * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="number-input-directive" module="numberExample"> <file name="index.html"> <script> angular.module('numberExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.example = { value: 12 }; }]); </script> <form name="myForm" ng-controller="ExampleController"> Number: <input type="number" name="input" ng-model="example.value" min="0" max="99" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.number"> Not valid number!</span> <tt>value = {{example.value}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var value = element(by.binding('example.value')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('example.value')); it('should initialize to model', function() { expect(value.getText()).toContain('12'); expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { input.clear(); input.sendKeys(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('false'); }); it('should be invalid if over max', function() { input.clear(); input.sendKeys('123'); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('false'); }); </file> </example> */ 'number': numberInputType, /** * @ngdoc input * @name input[url] * * @description * Text input with URL validation. Sets the `url` validation error key if the content is not a * valid URL. * * <div class="alert alert-warning"> * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify * the built-in validators (see the {@link guide/forms Forms guide}) * </div> * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of * any length. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string * that contains the regular expression body that will be converted to a regular expression * as in the ngPattern directive. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match * a RegExp found by evaluating the Angular expression given in the attribute value. * If the expression evaluates to a RegExp object then this is used directly. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$` * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="url-input-directive" module="urlExample"> <file name="index.html"> <script> angular.module('urlExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.url = { text: 'http://google.com' }; }]); </script> <form name="myForm" ng-controller="ExampleController"> URL: <input type="url" name="input" ng-model="url.text" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.url"> Not valid url!</span> <tt>text = {{url.text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var text = element(by.binding('url.text')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('url.text')); it('should initialize to model', function() { expect(text.getText()).toContain('http://google.com'); expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { input.clear(); input.sendKeys(''); expect(text.getText()).toEqual('text ='); expect(valid.getText()).toContain('false'); }); it('should be invalid if not url', function() { input.clear(); input.sendKeys('box'); expect(valid.getText()).toContain('false'); }); </file> </example> */ 'url': urlInputType, /** * @ngdoc input * @name input[email] * * @description * Text input with email validation. Sets the `email` validation error key if not a valid email * address. * * <div class="alert alert-warning"> * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide}) * </div> * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of * any length. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string * that contains the regular expression body that will be converted to a regular expression * as in the ngPattern directive. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match * a RegExp found by evaluating the Angular expression given in the attribute value. * If the expression evaluates to a RegExp object then this is used directly. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$` * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="email-input-directive" module="emailExample"> <file name="index.html"> <script> angular.module('emailExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.email = { text: 'me@example.com' }; }]); </script> <form name="myForm" ng-controller="ExampleController"> Email: <input type="email" name="input" ng-model="email.text" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.email"> Not valid email!</span> <tt>text = {{email.text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var text = element(by.binding('email.text')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('email.text')); it('should initialize to model', function() { expect(text.getText()).toContain('me@example.com'); expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { input.clear(); input.sendKeys(''); expect(text.getText()).toEqual('text ='); expect(valid.getText()).toContain('false'); }); it('should be invalid if not email', function() { input.clear(); input.sendKeys('xxx'); expect(valid.getText()).toContain('false'); }); </file> </example> */ 'email': emailInputType, /** * @ngdoc input * @name input[radio] * * @description * HTML radio button. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string} value The value to which the expression should be set when selected. * @param {string=} name Property name of the form under which the control is published. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * @param {string} ngValue Angular expression which sets the value to which the expression should * be set when selected. * * @example <example name="radio-input-directive" module="radioExample"> <file name="index.html"> <script> angular.module('radioExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.color = { name: 'blue' }; $scope.specialValue = { "id": "12345", "value": "green" }; }]); </script> <form name="myForm" ng-controller="ExampleController"> <input type="radio" ng-model="color.name" value="red"> Red <br/> <input type="radio" ng-model="color.name" ng-value="specialValue"> Green <br/> <input type="radio" ng-model="color.name" value="blue"> Blue <br/> <tt>color = {{color.name | json}}</tt><br/> </form> Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`. </file> <file name="protractor.js" type="protractor"> it('should change state', function() { var color = element(by.binding('color.name')); expect(color.getText()).toContain('blue'); element.all(by.model('color.name')).get(0).click(); expect(color.getText()).toContain('red'); }); </file> </example> */ 'radio': radioInputType, /** * @ngdoc input * @name input[checkbox] * * @description * HTML checkbox. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {expression=} ngTrueValue The value to which the expression should be set when selected. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="checkbox-input-directive" module="checkboxExample"> <file name="index.html"> <script> angular.module('checkboxExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.checkboxModel = { value1 : true, value2 : 'YES' }; }]); </script> <form name="myForm" ng-controller="ExampleController"> Value1: <input type="checkbox" ng-model="checkboxModel.value1"> <br/> Value2: <input type="checkbox" ng-model="checkboxModel.value2" ng-true-value="'YES'" ng-false-value="'NO'"> <br/> <tt>value1 = {{checkboxModel.value1}}</tt><br/> <tt>value2 = {{checkboxModel.value2}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> it('should change state', function() { var value1 = element(by.binding('checkboxModel.value1')); var value2 = element(by.binding('checkboxModel.value2')); expect(value1.getText()).toContain('true'); expect(value2.getText()).toContain('YES'); element(by.model('checkboxModel.value1')).click(); element(by.model('checkboxModel.value2')).click(); expect(value1.getText()).toContain('false'); expect(value2.getText()).toContain('NO'); }); </file> </example> */ 'checkbox': checkboxInputType, 'hidden': noop, 'button': noop, 'submit': noop, 'reset': noop, 'file': noop }; function stringBasedInputType(ctrl) { ctrl.$formatters.push(function(value) { return ctrl.$isEmpty(value) ? value : value.toString(); }); } function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { baseInputType(scope, element, attr, ctrl, $sniffer, $browser); stringBasedInputType(ctrl); } function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) { var type = lowercase(element[0].type); // In composition mode, users are still inputing intermediate text buffer, // hold the listener until composition is done. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent if (!$sniffer.android) { var composing = false; element.on('compositionstart', function(data) { composing = true; }); element.on('compositionend', function() { composing = false; listener(); }); } var listener = function(ev) { if (timeout) { $browser.defer.cancel(timeout); timeout = null; } if (composing) return; var value = element.val(), event = ev && ev.type; // By default we will trim the value // If the attribute ng-trim exists we will avoid trimming // If input type is 'password', the value is never trimmed if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) { value = trim(value); } // If a control is suffering from bad input (due to native validators), browsers discard its // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the // control's value is the same empty value twice in a row. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) { ctrl.$setViewValue(value, event); } }; // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the // input event on backspace, delete or cut if ($sniffer.hasEvent('input')) { element.on('input', listener); } else { var timeout; var deferListener = function(ev, input, origValue) { if (!timeout) { timeout = $browser.defer(function() { timeout = null; if (!input || input.value !== origValue) { listener(ev); } }); } }; element.on('keydown', function(event) { var key = event.keyCode; // ignore // command modifiers arrows if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return; deferListener(event, this, this.value); }); // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it if ($sniffer.hasEvent('paste')) { element.on('paste cut', deferListener); } } // if user paste into input using mouse on older browser // or form autocomplete on newer browser, we need "change" event to catch it element.on('change', listener); ctrl.$render = function() { element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue); }; } function weekParser(isoWeek, existingDate) { if (isDate(isoWeek)) { return isoWeek; } if (isString(isoWeek)) { WEEK_REGEXP.lastIndex = 0; var parts = WEEK_REGEXP.exec(isoWeek); if (parts) { var year = +parts[1], week = +parts[2], hours = 0, minutes = 0, seconds = 0, milliseconds = 0, firstThurs = getFirstThursdayOfYear(year), addDays = (week - 1) * 7; if (existingDate) { hours = existingDate.getHours(); minutes = existingDate.getMinutes(); seconds = existingDate.getSeconds(); milliseconds = existingDate.getMilliseconds(); } return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds); } } return NaN; } function createDateParser(regexp, mapping) { return function(iso, date) { var parts, map; if (isDate(iso)) { return iso; } if (isString(iso)) { // When a date is JSON'ified to wraps itself inside of an extra // set of double quotes. This makes the date parsing code unable // to match the date string and parse it as a date. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') { iso = iso.substring(1, iso.length - 1); } if (ISO_DATE_REGEXP.test(iso)) { return new Date(iso); } regexp.lastIndex = 0; parts = regexp.exec(iso); if (parts) { parts.shift(); if (date) { map = { yyyy: date.getFullYear(), MM: date.getMonth() + 1, dd: date.getDate(), HH: date.getHours(), mm: date.getMinutes(), ss: date.getSeconds(), sss: date.getMilliseconds() / 1000 }; } else { map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 }; } forEach(parts, function(part, index) { if (index < mapping.length) { map[mapping[index]] = +part; } }); return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0); } } return NaN; }; } function createDateInputType(type, regexp, parseDate, format) { return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) { badInputChecker(scope, element, attr, ctrl); baseInputType(scope, element, attr, ctrl, $sniffer, $browser); var timezone = ctrl && ctrl.$options && ctrl.$options.timezone; var previousDate; ctrl.$$parserName = type; ctrl.$parsers.push(function(value) { if (ctrl.$isEmpty(value)) return null; if (regexp.test(value)) { // Note: We cannot read ctrl.$modelValue, as there might be a different // parser/formatter in the processing chain so that the model // contains some different data format! var parsedDate = parseDate(value, previousDate); if (timezone === 'UTC') { parsedDate.setMinutes(parsedDate.getMinutes() - parsedDate.getTimezoneOffset()); } return parsedDate; } return undefined; }); ctrl.$formatters.push(function(value) { if (value && !isDate(value)) { throw $ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value); } if (isValidDate(value)) { previousDate = value; if (previousDate && timezone === 'UTC') { var timezoneOffset = 60000 * previousDate.getTimezoneOffset(); previousDate = new Date(previousDate.getTime() + timezoneOffset); } return $filter('date')(value, format, timezone); } else { previousDate = null; return ''; } }); if (isDefined(attr.min) || attr.ngMin) { var minVal; ctrl.$validators.min = function(value) { return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal; }; attr.$observe('min', function(val) { minVal = parseObservedDateValue(val); ctrl.$validate(); }); } if (isDefined(attr.max) || attr.ngMax) { var maxVal; ctrl.$validators.max = function(value) { return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal; }; attr.$observe('max', function(val) { maxVal = parseObservedDateValue(val); ctrl.$validate(); }); } function isValidDate(value) { // Invalid Date: getTime() returns NaN return value && !(value.getTime && value.getTime() !== value.getTime()); } function parseObservedDateValue(val) { return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined; } }; } function badInputChecker(scope, element, attr, ctrl) { var node = element[0]; var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity); if (nativeValidation) { ctrl.$parsers.push(function(value) { var validity = element.prop(VALIDITY_STATE_PROPERTY) || {}; // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430): // - also sets validity.badInput (should only be validity.typeMismatch). // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email) // - can ignore this case as we can still read out the erroneous email... return validity.badInput && !validity.typeMismatch ? undefined : value; }); } } function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { badInputChecker(scope, element, attr, ctrl); baseInputType(scope, element, attr, ctrl, $sniffer, $browser); ctrl.$$parserName = 'number'; ctrl.$parsers.push(function(value) { if (ctrl.$isEmpty(value)) return null; if (NUMBER_REGEXP.test(value)) return parseFloat(value); return undefined; }); ctrl.$formatters.push(function(value) { if (!ctrl.$isEmpty(value)) { if (!isNumber(value)) { throw $ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value); } value = value.toString(); } return value; }); if (attr.min || attr.ngMin) { var minVal; ctrl.$validators.min = function(value) { return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal; }; attr.$observe('min', function(val) { if (isDefined(val) && !isNumber(val)) { val = parseFloat(val, 10); } minVal = isNumber(val) && !isNaN(val) ? val : undefined; // TODO(matsko): implement validateLater to reduce number of validations ctrl.$validate(); }); } if (attr.max || attr.ngMax) { var maxVal; ctrl.$validators.max = function(value) { return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal; }; attr.$observe('max', function(val) { if (isDefined(val) && !isNumber(val)) { val = parseFloat(val, 10); } maxVal = isNumber(val) && !isNaN(val) ? val : undefined; // TODO(matsko): implement validateLater to reduce number of validations ctrl.$validate(); }); } } function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { // Note: no badInputChecker here by purpose as `url` is only a validation // in browsers, i.e. we can always read out input.value even if it is not valid! baseInputType(scope, element, attr, ctrl, $sniffer, $browser); stringBasedInputType(ctrl); ctrl.$$parserName = 'url'; ctrl.$validators.url = function(modelValue, viewValue) { var value = modelValue || viewValue; return ctrl.$isEmpty(value) || URL_REGEXP.test(value); }; } function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { // Note: no badInputChecker here by purpose as `url` is only a validation // in browsers, i.e. we can always read out input.value even if it is not valid! baseInputType(scope, element, attr, ctrl, $sniffer, $browser); stringBasedInputType(ctrl); ctrl.$$parserName = 'email'; ctrl.$validators.email = function(modelValue, viewValue) { var value = modelValue || viewValue; return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value); }; } function radioInputType(scope, element, attr, ctrl) { // make the name unique, if not defined if (isUndefined(attr.name)) { element.attr('name', nextUid()); } var listener = function(ev) { if (element[0].checked) { ctrl.$setViewValue(attr.value, ev && ev.type); } }; element.on('click', listener); ctrl.$render = function() { var value = attr.value; element[0].checked = (value == ctrl.$viewValue); }; attr.$observe('value', ctrl.$render); } function parseConstantExpr($parse, context, name, expression, fallback) { var parseFn; if (isDefined(expression)) { parseFn = $parse(expression); if (!parseFn.constant) { throw minErr('ngModel')('constexpr', 'Expected constant expression for `{0}`, but saw ' + '`{1}`.', name, expression); } return parseFn(context); } return fallback; } function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) { var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true); var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false); var listener = function(ev) { ctrl.$setViewValue(element[0].checked, ev && ev.type); }; element.on('click', listener); ctrl.$render = function() { element[0].checked = ctrl.$viewValue; }; // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false` // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert // it to a boolean. ctrl.$isEmpty = function(value) { return value === false; }; ctrl.$formatters.push(function(value) { return equals(value, trueValue); }); ctrl.$parsers.push(function(value) { return value ? trueValue : falseValue; }); } /** * @ngdoc directive * @name textarea * @restrict E * * @description * HTML textarea element control with angular data-binding. The data-binding and validation * properties of this element are exactly the same as those of the * {@link ng.directive:input input element}. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any * length. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. */ /** * @ngdoc directive * @name input * @restrict E * * @description * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding, * input state control, and validation. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers. * * <div class="alert alert-warning"> * **Note:** Not every feature offered is available for all input types. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`. * </div> * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {boolean=} ngRequired Sets `required` attribute if set to true * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any * length. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. * This parameter is ignored for input[type=password] controls, which will never trim the * input. * * @example <example name="input-directive" module="inputExample"> <file name="index.html"> <script> angular.module('inputExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.user = {name: 'guest', last: 'visitor'}; }]); </script> <div ng-controller="ExampleController"> <form name="myForm"> User name: <input type="text" name="userName" ng-model="user.name" required> <span class="error" ng-show="myForm.userName.$error.required"> Required!</span><br> Last name: <input type="text" name="lastName" ng-model="user.last" ng-minlength="3" ng-maxlength="10"> <span class="error" ng-show="myForm.lastName.$error.minlength"> Too short!</span> <span class="error" ng-show="myForm.lastName.$error.maxlength"> Too long!</span><br> </form> <hr> <tt>user = {{user}}</tt><br/> <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br> <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br> <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br> <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br> <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br> <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br> </div> </file> <file name="protractor.js" type="protractor"> var user = element(by.exactBinding('user')); var userNameValid = element(by.binding('myForm.userName.$valid')); var lastNameValid = element(by.binding('myForm.lastName.$valid')); var lastNameError = element(by.binding('myForm.lastName.$error')); var formValid = element(by.binding('myForm.$valid')); var userNameInput = element(by.model('user.name')); var userLastInput = element(by.model('user.last')); it('should initialize to model', function() { expect(user.getText()).toContain('{"name":"guest","last":"visitor"}'); expect(userNameValid.getText()).toContain('true'); expect(formValid.getText()).toContain('true'); }); it('should be invalid if empty when required', function() { userNameInput.clear(); userNameInput.sendKeys(''); expect(user.getText()).toContain('{"last":"visitor"}'); expect(userNameValid.getText()).toContain('false'); expect(formValid.getText()).toContain('false'); }); it('should be valid if empty when min length is set', function() { userLastInput.clear(); userLastInput.sendKeys(''); expect(user.getText()).toContain('{"name":"guest","last":""}'); expect(lastNameValid.getText()).toContain('true'); expect(formValid.getText()).toContain('true'); }); it('should be invalid if less than required min length', function() { userLastInput.clear(); userLastInput.sendKeys('xx'); expect(user.getText()).toContain('{"name":"guest"}'); expect(lastNameValid.getText()).toContain('false'); expect(lastNameError.getText()).toContain('minlength'); expect(formValid.getText()).toContain('false'); }); it('should be invalid if longer than max length', function() { userLastInput.clear(); userLastInput.sendKeys('some ridiculously long name'); expect(user.getText()).toContain('{"name":"guest"}'); expect(lastNameValid.getText()).toContain('false'); expect(lastNameError.getText()).toContain('maxlength'); expect(formValid.getText()).toContain('false'); }); </file> </example> */ var inputDirective = ['$browser', '$sniffer', '$filter', '$parse', function($browser, $sniffer, $filter, $parse) { return { restrict: 'E', require: ['?ngModel'], link: { pre: function(scope, element, attr, ctrls) { if (ctrls[0]) { (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer, $browser, $filter, $parse); } } } }; }]; var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; /** * @ngdoc directive * @name ngValue * * @description * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`}, * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to * the bound value. * * `ngValue` is useful when dynamically generating lists of radio buttons using * {@link ngRepeat `ngRepeat`}, as shown below. * * Likewise, `ngValue` can be used to generate `<option>` elements for * the {@link select `select`} element. In that case however, only strings are supported * for the `value `attribute, so the resulting `ngModel` will always be a string. * Support for `select` models with non-string values is available via `ngOptions`. * * @element input * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute * of the `input` element * * @example <example name="ngValue-directive" module="valueExample"> <file name="index.html"> <script> angular.module('valueExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.names = ['pizza', 'unicorns', 'robots']; $scope.my = { favorite: 'unicorns' }; }]); </script> <form ng-controller="ExampleController"> <h2>Which is your favorite?</h2> <label ng-repeat="name in names" for="{{name}}"> {{name}} <input type="radio" ng-model="my.favorite" ng-value="name" id="{{name}}" name="favorite"> </label> <div>You chose {{my.favorite}}</div> </form> </file> <file name="protractor.js" type="protractor"> var favorite = element(by.binding('my.favorite')); it('should initialize to model', function() { expect(favorite.getText()).toContain('unicorns'); }); it('should bind the values to the inputs', function() { element.all(by.model('my.favorite')).get(0).click(); expect(favorite.getText()).toContain('pizza'); }); </file> </example> */ var ngValueDirective = function() { return { restrict: 'A', priority: 100, compile: function(tpl, tplAttr) { if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { return function ngValueConstantLink(scope, elm, attr) { attr.$set('value', scope.$eval(attr.ngValue)); }; } else { return function ngValueLink(scope, elm, attr) { scope.$watch(attr.ngValue, function valueWatchAction(value) { attr.$set('value', value); }); }; } } }; }; /** * @ngdoc directive * @name ngBind * @restrict AC * * @description * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element * with the value of a given expression, and to update the text content when the value of that * expression changes. * * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like * `{{ expression }}` which is similar but less verbose. * * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an * element attribute, it makes the bindings invisible to the user while the page is loading. * * An alternative solution to this problem would be using the * {@link ng.directive:ngCloak ngCloak} directive. * * * @element ANY * @param {expression} ngBind {@link guide/expression Expression} to evaluate. * * @example * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. <example module="bindExample"> <file name="index.html"> <script> angular.module('bindExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.name = 'Whirled'; }]); </script> <div ng-controller="ExampleController"> Enter name: <input type="text" ng-model="name"><br> Hello <span ng-bind="name"></span>! </div> </file> <file name="protractor.js" type="protractor"> it('should check ng-bind', function() { var nameInput = element(by.model('name')); expect(element(by.binding('name')).getText()).toBe('Whirled'); nameInput.clear(); nameInput.sendKeys('world'); expect(element(by.binding('name')).getText()).toBe('world'); }); </file> </example> */ var ngBindDirective = ['$compile', function($compile) { return { restrict: 'AC', compile: function ngBindCompile(templateElement) { $compile.$$addBindingClass(templateElement); return function ngBindLink(scope, element, attr) { $compile.$$addBindingInfo(element, attr.ngBind); element = element[0]; scope.$watch(attr.ngBind, function ngBindWatchAction(value) { element.textContent = value === undefined ? '' : value; }); }; } }; }]; /** * @ngdoc directive * @name ngBindTemplate * * @description * The `ngBindTemplate` directive specifies that the element * text content should be replaced with the interpolation of the template * in the `ngBindTemplate` attribute. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}` * expressions. This directive is needed since some HTML elements * (such as TITLE and OPTION) cannot contain SPAN elements. * * @element ANY * @param {string} ngBindTemplate template of form * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval. * * @example * Try it here: enter text in text box and watch the greeting change. <example module="bindExample"> <file name="index.html"> <script> angular.module('bindExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.salutation = 'Hello'; $scope.name = 'World'; }]); </script> <div ng-controller="ExampleController"> Salutation: <input type="text" ng-model="salutation"><br> Name: <input type="text" ng-model="name"><br> <pre ng-bind-template="{{salutation}} {{name}}!"></pre> </div> </file> <file name="protractor.js" type="protractor"> it('should check ng-bind', function() { var salutationElem = element(by.binding('salutation')); var salutationInput = element(by.model('salutation')); var nameInput = element(by.model('name')); expect(salutationElem.getText()).toBe('Hello World!'); salutationInput.clear(); salutationInput.sendKeys('Greetings'); nameInput.clear(); nameInput.sendKeys('user'); expect(salutationElem.getText()).toBe('Greetings user!'); }); </file> </example> */ var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) { return { compile: function ngBindTemplateCompile(templateElement) { $compile.$$addBindingClass(templateElement); return function ngBindTemplateLink(scope, element, attr) { var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); $compile.$$addBindingInfo(element, interpolateFn.expressions); element = element[0]; attr.$observe('ngBindTemplate', function(value) { element.textContent = value === undefined ? '' : value; }); }; } }; }]; /** * @ngdoc directive * @name ngBindHtml * * @description * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default, * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize} * in your module's dependencies, you need to include "angular-sanitize.js" in your application. * * You may also bypass sanitization for values you know are safe. To do so, bind to * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}. * * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you * will have an exception (instead of an exploit.) * * @element ANY * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate. * * @example <example module="bindHtmlExample" deps="angular-sanitize.js"> <file name="index.html"> <div ng-controller="ExampleController"> <p ng-bind-html="myHTML"></p> </div> </file> <file name="script.js"> angular.module('bindHtmlExample', ['ngSanitize']) .controller('ExampleController', ['$scope', function($scope) { $scope.myHTML = 'I am an <code>HTML</code>string with ' + '<a href="#">links!</a> and other <em>stuff</em>'; }]); </file> <file name="protractor.js" type="protractor"> it('should check ng-bind-html', function() { expect(element(by.binding('myHTML')).getText()).toBe( 'I am an HTMLstring with links! and other stuff'); }); </file> </example> */ var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) { return { restrict: 'A', compile: function ngBindHtmlCompile(tElement, tAttrs) { var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml); var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) { return (value || '').toString(); }); $compile.$$addBindingClass(tElement); return function ngBindHtmlLink(scope, element, attr) { $compile.$$addBindingInfo(element, attr.ngBindHtml); scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() { // we re-evaluate the expr because we want a TrustedValueHolderType // for $sce, not a string element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || ''); }); }; } }; }]; /** * @ngdoc directive * @name ngChange * * @description * Evaluate the given expression when the user changes the input. * The expression is evaluated immediately, unlike the JavaScript onchange event * which only triggers at the end of a change (usually, when the user leaves the * form element or presses the return key). * * The `ngChange` expression is only evaluated when a change in the input value causes * a new value to be committed to the model. * * It will not be evaluated: * * if the value returned from the `$parsers` transformation pipeline has not changed * * if the input has continued to be invalid since the model will stay `null` * * if the model is changed programmatically and not by a change to the input value * * * Note, this directive requires `ngModel` to be present. * * @element input * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change * in input value. * * @example * <example name="ngChange-directive" module="changeExample"> * <file name="index.html"> * <script> * angular.module('changeExample', []) * .controller('ExampleController', ['$scope', function($scope) { * $scope.counter = 0; * $scope.change = function() { * $scope.counter++; * }; * }]); * </script> * <div ng-controller="ExampleController"> * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" /> * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" /> * <label for="ng-change-example2">Confirmed</label><br /> * <tt>debug = {{confirmed}}</tt><br/> * <tt>counter = {{counter}}</tt><br/> * </div> * </file> * <file name="protractor.js" type="protractor"> * var counter = element(by.binding('counter')); * var debug = element(by.binding('confirmed')); * * it('should evaluate the expression if changing from view', function() { * expect(counter.getText()).toContain('0'); * * element(by.id('ng-change-example1')).click(); * * expect(counter.getText()).toContain('1'); * expect(debug.getText()).toContain('true'); * }); * * it('should not evaluate the expression if changing from model', function() { * element(by.id('ng-change-example2')).click(); * expect(counter.getText()).toContain('0'); * expect(debug.getText()).toContain('true'); * }); * </file> * </example> */ var ngChangeDirective = valueFn({ restrict: 'A', require: 'ngModel', link: function(scope, element, attr, ctrl) { ctrl.$viewChangeListeners.push(function() { scope.$eval(attr.ngChange); }); } }); function classDirective(name, selector) { name = 'ngClass' + name; return ['$animate', function($animate) { return { restrict: 'AC', link: function(scope, element, attr) { var oldVal; scope.$watch(attr[name], ngClassWatchAction, true); attr.$observe('class', function(value) { ngClassWatchAction(scope.$eval(attr[name])); }); if (name !== 'ngClass') { scope.$watch('$index', function($index, old$index) { // jshint bitwise: false var mod = $index & 1; if (mod !== (old$index & 1)) { var classes = arrayClasses(scope.$eval(attr[name])); mod === selector ? addClasses(classes) : removeClasses(classes); } }); } function addClasses(classes) { var newClasses = digestClassCounts(classes, 1); attr.$addClass(newClasses); } function removeClasses(classes) { var newClasses = digestClassCounts(classes, -1); attr.$removeClass(newClasses); } function digestClassCounts(classes, count) { var classCounts = element.data('$classCounts') || {}; var classesToUpdate = []; forEach(classes, function(className) { if (count > 0 || classCounts[className]) { classCounts[className] = (classCounts[className] || 0) + count; if (classCounts[className] === +(count > 0)) { classesToUpdate.push(className); } } }); element.data('$classCounts', classCounts); return classesToUpdate.join(' '); } function updateClasses(oldClasses, newClasses) { var toAdd = arrayDifference(newClasses, oldClasses); var toRemove = arrayDifference(oldClasses, newClasses); toAdd = digestClassCounts(toAdd, 1); toRemove = digestClassCounts(toRemove, -1); if (toAdd && toAdd.length) { $animate.addClass(element, toAdd); } if (toRemove && toRemove.length) { $animate.removeClass(element, toRemove); } } function ngClassWatchAction(newVal) { if (selector === true || scope.$index % 2 === selector) { var newClasses = arrayClasses(newVal || []); if (!oldVal) { addClasses(newClasses); } else if (!equals(newVal,oldVal)) { var oldClasses = arrayClasses(oldVal); updateClasses(oldClasses, newClasses); } } oldVal = shallowCopy(newVal); } } }; function arrayDifference(tokens1, tokens2) { var values = []; outer: for (var i = 0; i < tokens1.length; i++) { var token = tokens1[i]; for (var j = 0; j < tokens2.length; j++) { if (token == tokens2[j]) continue outer; } values.push(token); } return values; } function arrayClasses(classVal) { if (isArray(classVal)) { return classVal; } else if (isString(classVal)) { return classVal.split(' '); } else if (isObject(classVal)) { var classes = []; forEach(classVal, function(v, k) { if (v) { classes = classes.concat(k.split(' ')); } }); return classes; } return classVal; } }]; } /** * @ngdoc directive * @name ngClass * @restrict AC * * @description * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding * an expression that represents all classes to be added. * * The directive operates in three different ways, depending on which of three types the expression * evaluates to: * * 1. If the expression evaluates to a string, the string should be one or more space-delimited class * names. * * 2. If the expression evaluates to an array, each element of the array should be a string that is * one or more space-delimited class names. * * 3. If the expression evaluates to an object, then for each key-value pair of the * object with a truthy value the corresponding key is used as a class name. * * The directive won't add duplicate classes if a particular class was already set. * * When the expression changes, the previously added classes are removed and only then the * new classes are added. * * @animations * **add** - happens just before the class is applied to the elements * * **remove** - happens just before the class is removed from the element * * @element ANY * @param {expression} ngClass {@link guide/expression Expression} to eval. The result * of the evaluation can be a string representing space delimited class * names, an array, or a map of class names to boolean values. In the case of a map, the * names of the properties whose values are truthy will be added as css classes to the * element. * * @example Example that demonstrates basic bindings via ngClass directive. <example> <file name="index.html"> <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p> <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br> <input type="checkbox" ng-model="important"> important (apply "bold" class)<br> <input type="checkbox" ng-model="error"> error (apply "red" class) <hr> <p ng-class="style">Using String Syntax</p> <input type="text" ng-model="style" placeholder="Type: bold strike red"> <hr> <p ng-class="[style1, style2, style3]">Using Array Syntax</p> <input ng-model="style1" placeholder="Type: bold, strike or red"><br> <input ng-model="style2" placeholder="Type: bold, strike or red"><br> <input ng-model="style3" placeholder="Type: bold, strike or red"><br> </file> <file name="style.css"> .strike { text-decoration: line-through; } .bold { font-weight: bold; } .red { color: red; } </file> <file name="protractor.js" type="protractor"> var ps = element.all(by.css('p')); it('should let you toggle the class', function() { expect(ps.first().getAttribute('class')).not.toMatch(/bold/); expect(ps.first().getAttribute('class')).not.toMatch(/red/); element(by.model('important')).click(); expect(ps.first().getAttribute('class')).toMatch(/bold/); element(by.model('error')).click(); expect(ps.first().getAttribute('class')).toMatch(/red/); }); it('should let you toggle string example', function() { expect(ps.get(1).getAttribute('class')).toBe(''); element(by.model('style')).clear(); element(by.model('style')).sendKeys('red'); expect(ps.get(1).getAttribute('class')).toBe('red'); }); it('array example should have 3 classes', function() { expect(ps.last().getAttribute('class')).toBe(''); element(by.model('style1')).sendKeys('bold'); element(by.model('style2')).sendKeys('strike'); element(by.model('style3')).sendKeys('red'); expect(ps.last().getAttribute('class')).toBe('bold strike red'); }); </file> </example> ## Animations The example below demonstrates how to perform animations using ngClass. <example module="ngAnimate" deps="angular-animate.js" animations="true"> <file name="index.html"> <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'"> <input id="clearbtn" type="button" value="clear" ng-click="myVar=''"> <br> <span class="base-class" ng-class="myVar">Sample Text</span> </file> <file name="style.css"> .base-class { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; } .base-class.my-class { color: red; font-size:3em; } </file> <file name="protractor.js" type="protractor"> it('should check ng-class', function() { expect(element(by.css('.base-class')).getAttribute('class')).not. toMatch(/my-class/); element(by.id('setbtn')).click(); expect(element(by.css('.base-class')).getAttribute('class')). toMatch(/my-class/); element(by.id('clearbtn')).click(); expect(element(by.css('.base-class')).getAttribute('class')).not. toMatch(/my-class/); }); </file> </example> ## ngClass and pre-existing CSS3 Transitions/Animations The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure to view the step by step details of {@link ng.$animate#addClass $animate.addClass} and {@link ng.$animate#removeClass $animate.removeClass}. */ var ngClassDirective = classDirective('', true); /** * @ngdoc directive * @name ngClassOdd * @restrict AC * * @description * The `ngClassOdd` and `ngClassEven` directives work exactly as * {@link ng.directive:ngClass ngClass}, except they work in * conjunction with `ngRepeat` and take effect only on odd (even) rows. * * This directive can be applied only within the scope of an * {@link ng.directive:ngRepeat ngRepeat}. * * @element ANY * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result * of the evaluation can be a string representing space delimited class names or an array. * * @example <example> <file name="index.html"> <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng-repeat="name in names"> <span ng-class-odd="'odd'" ng-class-even="'even'"> {{name}} </span> </li> </ol> </file> <file name="style.css"> .odd { color: red; } .even { color: blue; } </file> <file name="protractor.js" type="protractor"> it('should check ng-class-odd and ng-class-even', function() { expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). toMatch(/odd/); expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). toMatch(/even/); }); </file> </example> */ var ngClassOddDirective = classDirective('Odd', 0); /** * @ngdoc directive * @name ngClassEven * @restrict AC * * @description * The `ngClassOdd` and `ngClassEven` directives work exactly as * {@link ng.directive:ngClass ngClass}, except they work in * conjunction with `ngRepeat` and take effect only on odd (even) rows. * * This directive can be applied only within the scope of an * {@link ng.directive:ngRepeat ngRepeat}. * * @element ANY * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The * result of the evaluation can be a string representing space delimited class names or an array. * * @example <example> <file name="index.html"> <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng-repeat="name in names"> <span ng-class-odd="'odd'" ng-class-even="'even'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> </file> <file name="style.css"> .odd { color: red; } .even { color: blue; } </file> <file name="protractor.js" type="protractor"> it('should check ng-class-odd and ng-class-even', function() { expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). toMatch(/odd/); expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). toMatch(/even/); }); </file> </example> */ var ngClassEvenDirective = classDirective('Even', 1); /** * @ngdoc directive * @name ngCloak * @restrict AC * * @description * The `ngCloak` directive is used to prevent the Angular html template from being briefly * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this * directive to avoid the undesirable flicker effect caused by the html template display. * * The directive can be applied to the `<body>` element, but the preferred usage is to apply * multiple `ngCloak` directives to small portions of the page to permit progressive rendering * of the browser view. * * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and * `angular.min.js`. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). * * ```css * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak { * display: none !important; * } * ``` * * When this css rule is loaded by the browser, all html elements (including their children) that * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive * during the compilation of the template it deletes the `ngCloak` element attribute, making * the compiled element visible. * * For the best result, the `angular.js` script must be loaded in the head section of the html * document; alternatively, the css rule above must be included in the external stylesheet of the * application. * * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below. * * @element ANY * * @example <example> <file name="index.html"> <div id="template1" ng-cloak>{{ 'hello' }}</div> <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div> </file> <file name="protractor.js" type="protractor"> it('should remove the template directive and css class', function() { expect($('#template1').getAttribute('ng-cloak')). toBeNull(); expect($('#template2').getAttribute('ng-cloak')). toBeNull(); }); </file> </example> * */ var ngCloakDirective = ngDirective({ compile: function(element, attr) { attr.$set('ngCloak', undefined); element.removeClass('ng-cloak'); } }); /** * @ngdoc directive * @name ngController * * @description * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular * supports the principles behind the Model-View-Controller design pattern. * * MVC components in angular: * * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties * are accessed through bindings. * * View — The template (HTML with data bindings) that is rendered into the View. * * Controller — The `ngController` directive specifies a Controller class; the class contains business * logic behind the application to decorate the scope with functions and values * * Note that you can also attach controllers to the DOM by declaring it in a route definition * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller * again using `ng-controller` in the template itself. This will cause the controller to be attached * and executed twice. * * @element ANY * @scope * @priority 500 * @param {expression} ngController Name of a constructor function registered with the current * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression} * that on the current scope evaluates to a constructor function. * * The controller instance can be published into a scope property by specifying * `ng-controller="as propertyName"`. * * If the current `$controllerProvider` is configured to use globals (via * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may * also be the name of a globally accessible constructor function (not recommended). * * @example * Here is a simple form for editing user contact information. Adding, removing, clearing, and * greeting are methods declared on the controller (see source tab). These methods can * easily be called from the angular markup. Any changes to the data are automatically reflected * in the View without the need for a manual update. * * Two different declaration styles are included below: * * * one binds methods and properties directly onto the controller using `this`: * `ng-controller="SettingsController1 as settings"` * * one injects `$scope` into the controller: * `ng-controller="SettingsController2"` * * The second option is more common in the Angular community, and is generally used in boilerplates * and in this guide. However, there are advantages to binding properties directly to the controller * and avoiding scope. * * * Using `controller as` makes it obvious which controller you are accessing in the template when * multiple controllers apply to an element. * * If you are writing your controllers as classes you have easier access to the properties and * methods, which will appear on the scope, from inside the controller code. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal * inheritance masking primitives. * * This example demonstrates the `controller as` syntax. * * <example name="ngControllerAs" module="controllerAsExample"> * <file name="index.html"> * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings"> * Name: <input type="text" ng-model="settings.name"/> * [ <a href="" ng-click="settings.greet()">greet</a> ]<br/> * Contact: * <ul> * <li ng-repeat="contact in settings.contacts"> * <select ng-model="contact.type"> * <option>phone</option> * <option>email</option> * </select> * <input type="text" ng-model="contact.value"/> * [ <a href="" ng-click="settings.clearContact(contact)">clear</a> * | <a href="" ng-click="settings.removeContact(contact)">X</a> ] * </li> * <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li> * </ul> * </div> * </file> * <file name="app.js"> * angular.module('controllerAsExample', []) * .controller('SettingsController1', SettingsController1); * * function SettingsController1() { * this.name = "John Smith"; * this.contacts = [ * {type: 'phone', value: '408 555 1212'}, * {type: 'email', value: 'john.smith@example.org'} ]; * } * * SettingsController1.prototype.greet = function() { * alert(this.name); * }; * * SettingsController1.prototype.addContact = function() { * this.contacts.push({type: 'email', value: 'yourname@example.org'}); * }; * * SettingsController1.prototype.removeContact = function(contactToRemove) { * var index = this.contacts.indexOf(contactToRemove); * this.contacts.splice(index, 1); * }; * * SettingsController1.prototype.clearContact = function(contact) { * contact.type = 'phone'; * contact.value = ''; * }; * </file> * <file name="protractor.js" type="protractor"> * it('should check controller as', function() { * var container = element(by.id('ctrl-as-exmpl')); * expect(container.element(by.model('settings.name')) * .getAttribute('value')).toBe('John Smith'); * * var firstRepeat = * container.element(by.repeater('contact in settings.contacts').row(0)); * var secondRepeat = * container.element(by.repeater('contact in settings.contacts').row(1)); * * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) * .toBe('408 555 1212'); * * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value')) * .toBe('john.smith@example.org'); * * firstRepeat.element(by.linkText('clear')).click(); * * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) * .toBe(''); * * container.element(by.linkText('add')).click(); * * expect(container.element(by.repeater('contact in settings.contacts').row(2)) * .element(by.model('contact.value')) * .getAttribute('value')) * .toBe('yourname@example.org'); * }); * </file> * </example> * * This example demonstrates the "attach to `$scope`" style of controller. * * <example name="ngController" module="controllerExample"> * <file name="index.html"> * <div id="ctrl-exmpl" ng-controller="SettingsController2"> * Name: <input type="text" ng-model="name"/> * [ <a href="" ng-click="greet()">greet</a> ]<br/> * Contact: * <ul> * <li ng-repeat="contact in contacts"> * <select ng-model="contact.type"> * <option>phone</option> * <option>email</option> * </select> * <input type="text" ng-model="contact.value"/> * [ <a href="" ng-click="clearContact(contact)">clear</a> * | <a href="" ng-click="removeContact(contact)">X</a> ] * </li> * <li>[ <a href="" ng-click="addContact()">add</a> ]</li> * </ul> * </div> * </file> * <file name="app.js"> * angular.module('controllerExample', []) * .controller('SettingsController2', ['$scope', SettingsController2]); * * function SettingsController2($scope) { * $scope.name = "John Smith"; * $scope.contacts = [ * {type:'phone', value:'408 555 1212'}, * {type:'email', value:'john.smith@example.org'} ]; * * $scope.greet = function() { * alert($scope.name); * }; * * $scope.addContact = function() { * $scope.contacts.push({type:'email', value:'yourname@example.org'}); * }; * * $scope.removeContact = function(contactToRemove) { * var index = $scope.contacts.indexOf(contactToRemove); * $scope.contacts.splice(index, 1); * }; * * $scope.clearContact = function(contact) { * contact.type = 'phone'; * contact.value = ''; * }; * } * </file> * <file name="protractor.js" type="protractor"> * it('should check controller', function() { * var container = element(by.id('ctrl-exmpl')); * * expect(container.element(by.model('name')) * .getAttribute('value')).toBe('John Smith'); * * var firstRepeat = * container.element(by.repeater('contact in contacts').row(0)); * var secondRepeat = * container.element(by.repeater('contact in contacts').row(1)); * * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) * .toBe('408 555 1212'); * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value')) * .toBe('john.smith@example.org'); * * firstRepeat.element(by.linkText('clear')).click(); * * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) * .toBe(''); * * container.element(by.linkText('add')).click(); * * expect(container.element(by.repeater('contact in contacts').row(2)) * .element(by.model('contact.value')) * .getAttribute('value')) * .toBe('yourname@example.org'); * }); * </file> *</example> */ var ngControllerDirective = [function() { return { restrict: 'A', scope: true, controller: '@', priority: 500 }; }]; /** * @ngdoc directive * @name ngCsp * * @element html * @description * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support. * * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps. * * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things). * For Angular to be CSP compatible there are only two things that we need to do differently: * * - don't use `Function` constructor to generate optimized value getters * - don't inject custom stylesheet into the document * * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp` * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will * be raised. * * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}). * To make those directives work in CSP mode, include the `angular-csp.css` manually. * * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This * autodetection however triggers a CSP error to be logged in the console: * * ``` * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of * script in the following Content Security Policy directive: "default-src 'self'". Note that * 'script-src' was not explicitly set, so 'default-src' is used as a fallback. * ``` * * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp` * directive on the root element of the application or on the `angular.js` script tag, whichever * appears first in the html document. * * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.* * * @example * This example shows how to apply the `ngCsp` directive to the `html` tag. ```html <!doctype html> <html ng-app ng-csp> ... ... </html> ``` * @example // Note: the suffix `.csp` in the example name triggers // csp mode in our http server! <example name="example.csp" module="cspExample" ng-csp="true"> <file name="index.html"> <div ng-controller="MainController as ctrl"> <div> <button ng-click="ctrl.inc()" id="inc">Increment</button> <span id="counter"> {{ctrl.counter}} </span> </div> <div> <button ng-click="ctrl.evil()" id="evil">Evil</button> <span id="evilError"> {{ctrl.evilError}} </span> </div> </div> </file> <file name="script.js"> angular.module('cspExample', []) .controller('MainController', function() { this.counter = 0; this.inc = function() { this.counter++; }; this.evil = function() { // jshint evil:true try { eval('1+2'); } catch (e) { this.evilError = e.message; } }; }); </file> <file name="protractor.js" type="protractor"> var util, webdriver; var incBtn = element(by.id('inc')); var counter = element(by.id('counter')); var evilBtn = element(by.id('evil')); var evilError = element(by.id('evilError')); function getAndClearSevereErrors() { return browser.manage().logs().get('browser').then(function(browserLog) { return browserLog.filter(function(logEntry) { return logEntry.level.value > webdriver.logging.Level.WARNING.value; }); }); } function clearErrors() { getAndClearSevereErrors(); } function expectNoErrors() { getAndClearSevereErrors().then(function(filteredLog) { expect(filteredLog.length).toEqual(0); if (filteredLog.length) { console.log('browser console errors: ' + util.inspect(filteredLog)); } }); } function expectError(regex) { getAndClearSevereErrors().then(function(filteredLog) { var found = false; filteredLog.forEach(function(log) { if (log.message.match(regex)) { found = true; } }); if (!found) { throw new Error('expected an error that matches ' + regex); } }); } beforeEach(function() { util = require('util'); webdriver = require('protractor/node_modules/selenium-webdriver'); }); // For now, we only test on Chrome, // as Safari does not load the page with Protractor's injected scripts, // and Firefox webdriver always disables content security policy (#6358) if (browser.params.browser !== 'chrome') { return; } it('should not report errors when the page is loaded', function() { // clear errors so we are not dependent on previous tests clearErrors(); // Need to reload the page as the page is already loaded when // we come here browser.driver.getCurrentUrl().then(function(url) { browser.get(url); }); expectNoErrors(); }); it('should evaluate expressions', function() { expect(counter.getText()).toEqual('0'); incBtn.click(); expect(counter.getText()).toEqual('1'); expectNoErrors(); }); it('should throw and report an error when using "eval"', function() { evilBtn.click(); expect(evilError.getText()).toMatch(/Content Security Policy/); expectError(/Content Security Policy/); }); </file> </example> */ // ngCsp is not implemented as a proper directive any more, because we need it be processed while we // bootstrap the system (before $parse is instantiated), for this reason we just have // the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc /** * @ngdoc directive * @name ngClick * * @description * The ngClick directive allows you to specify custom behavior when * an element is clicked. * * @element ANY * @priority 0 * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon * click. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-click="count = count + 1" ng-init="count=0"> Increment </button> <span> count: {{count}} </span> </file> <file name="protractor.js" type="protractor"> it('should check ng-click', function() { expect(element(by.binding('count')).getText()).toMatch('0'); element(by.css('button')).click(); expect(element(by.binding('count')).getText()).toMatch('1'); }); </file> </example> */ /* * A collection of directives that allows creation of custom event handlers that are defined as * angular expressions and are compiled and executed within the current scope. */ var ngEventDirectives = {}; // For events that might fire synchronously during DOM manipulation // we need to execute their event handlers asynchronously using $evalAsync, // so that they are not executed in an inconsistent state. var forceAsyncEvents = { 'blur': true, 'focus': true }; forEach( 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '), function(eventName) { var directiveName = directiveNormalize('ng-' + eventName); ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) { return { restrict: 'A', compile: function($element, attr) { // We expose the powerful $event object on the scope that provides access to the Window, // etc. that isn't protected by the fast paths in $parse. We explicitly request better // checks at the cost of speed since event handler expressions are not executed as // frequently as regular change detection. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true); return function ngEventHandler(scope, element) { element.on(eventName, function(event) { var callback = function() { fn(scope, {$event:event}); }; if (forceAsyncEvents[eventName] && $rootScope.$$phase) { scope.$evalAsync(callback); } else { scope.$apply(callback); } }); }; } }; }]; } ); /** * @ngdoc directive * @name ngDblclick * * @description * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event. * * @element ANY * @priority 0 * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon * a dblclick. (The Event object is available as `$event`) * * @example <example> <file name="index.html"> <button ng-dblclick="count = count + 1" ng-init="count=0"> Increment (on double click) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngMousedown * * @description * The ngMousedown directive allows you to specify custom behavior on mousedown event. * * @element ANY * @priority 0 * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon * mousedown. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-mousedown="count = count + 1" ng-init="count=0"> Increment (on mouse down) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngMouseup * * @description * Specify custom behavior on mouseup event. * * @element ANY * @priority 0 * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon * mouseup. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-mouseup="count = count + 1" ng-init="count=0"> Increment (on mouse up) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngMouseover * * @description * Specify custom behavior on mouseover event. * * @element ANY * @priority 0 * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon * mouseover. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-mouseover="count = count + 1" ng-init="count=0"> Increment (when mouse is over) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngMouseenter * * @description * Specify custom behavior on mouseenter event. * * @element ANY * @priority 0 * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-mouseenter="count = count + 1" ng-init="count=0"> Increment (when mouse enters) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngMouseleave * * @description * Specify custom behavior on mouseleave event. * * @element ANY * @priority 0 * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-mouseleave="count = count + 1" ng-init="count=0"> Increment (when mouse leaves) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngMousemove * * @description * Specify custom behavior on mousemove event. * * @element ANY * @priority 0 * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon * mousemove. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-mousemove="count = count + 1" ng-init="count=0"> Increment (when mouse moves) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngKeydown * * @description * Specify custom behavior on keydown event. * * @element ANY * @priority 0 * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) * * @example <example> <file name="index.html"> <input ng-keydown="count = count + 1" ng-init="count=0"> key down count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngKeyup * * @description * Specify custom behavior on keyup event. * * @element ANY * @priority 0 * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) * * @example <example> <file name="index.html"> <p>Typing in the input box below updates the key count</p> <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}} <p>Typing in the input box below updates the keycode</p> <input ng-keyup="event=$event"> <p>event keyCode: {{ event.keyCode }}</p> <p>event altKey: {{ event.altKey }}</p> </file> </example> */ /** * @ngdoc directive * @name ngKeypress * * @description * Specify custom behavior on keypress event. * * @element ANY * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon * keypress. ({@link guide/expression#-event- Event object is available as `$event`} * and can be interrogated for keyCode, altKey, etc.) * * @example <example> <file name="index.html"> <input ng-keypress="count = count + 1" ng-init="count=0"> key press count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngSubmit * * @description * Enables binding angular expressions to onsubmit events. * * Additionally it prevents the default action (which for form means sending the request to the * server and reloading the current page), but only if the form does not contain `action`, * `data-action`, or `x-action` attributes. * * <div class="alert alert-warning"> * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and * `ngSubmit` handlers together. See the * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation} * for a detailed discussion of when `ngSubmit` may be triggered. * </div> * * @element form * @priority 0 * @param {expression} ngSubmit {@link guide/expression Expression} to eval. * ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example module="submitExample"> <file name="index.html"> <script> angular.module('submitExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.list = []; $scope.text = 'hello'; $scope.submit = function() { if ($scope.text) { $scope.list.push(this.text); $scope.text = ''; } }; }]); </script> <form ng-submit="submit()" ng-controller="ExampleController"> Enter text and hit enter: <input type="text" ng-model="text" name="text" /> <input type="submit" id="submit" value="Submit" /> <pre>list={{list}}</pre> </form> </file> <file name="protractor.js" type="protractor"> it('should check ng-submit', function() { expect(element(by.binding('list')).getText()).toBe('list=[]'); element(by.css('#submit')).click(); expect(element(by.binding('list')).getText()).toContain('hello'); expect(element(by.model('text')).getAttribute('value')).toBe(''); }); it('should ignore empty strings', function() { expect(element(by.binding('list')).getText()).toBe('list=[]'); element(by.css('#submit')).click(); element(by.css('#submit')).click(); expect(element(by.binding('list')).getText()).toContain('hello'); }); </file> </example> */ /** * @ngdoc directive * @name ngFocus * * @description * Specify custom behavior on focus event. * * Note: As the `focus` event is executed synchronously when calling `input.focus()` * AngularJS executes the expression using `scope.$evalAsync` if the event is fired * during an `$apply` to ensure a consistent state. * * @element window, input, select, textarea, a * @priority 0 * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon * focus. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ngBlur * * @description * Specify custom behavior on blur event. * * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when * an element has lost focus. * * Note: As the `blur` event is executed synchronously also during DOM manipulations * (e.g. removing a focussed input), * AngularJS executes the expression using `scope.$evalAsync` if the event is fired * during an `$apply` to ensure a consistent state. * * @element window, input, select, textarea, a * @priority 0 * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon * blur. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ngCopy * * @description * Specify custom behavior on copy event. * * @element window, input, select, textarea, a * @priority 0 * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon * copy. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value"> copied: {{copied}} </file> </example> */ /** * @ngdoc directive * @name ngCut * * @description * Specify custom behavior on cut event. * * @element window, input, select, textarea, a * @priority 0 * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon * cut. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value"> cut: {{cut}} </file> </example> */ /** * @ngdoc directive * @name ngPaste * * @description * Specify custom behavior on paste event. * * @element window, input, select, textarea, a * @priority 0 * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon * paste. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'> pasted: {{paste}} </file> </example> */ /** * @ngdoc directive * @name ngIf * @restrict A * * @description * The `ngIf` directive removes or recreates a portion of the DOM tree based on an * {expression}. If the expression assigned to `ngIf` evaluates to a false * value then the element is removed from the DOM, otherwise a clone of the * element is reinserted into the DOM. * * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the * element in the DOM rather than changing its visibility via the `display` css property. A common * case when this difference is significant is when using css selectors that rely on an element's * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes. * * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope * is created when the element is restored. The scope created within `ngIf` inherits from * its parent scope using * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance). * An important implication of this is if `ngModel` is used within `ngIf` to bind to * a javascript primitive defined in the parent scope. In this case any modifications made to the * variable within the child scope will override (hide) the value in the parent scope. * * Also, `ngIf` recreates elements using their compiled state. An example of this behavior * is if an element's class attribute is directly modified after it's compiled, using something like * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element * the added class will be lost because the original compiled state is used to regenerate the element. * * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter` * and `leave` effects. * * @animations * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container * leave - happens just before the `ngIf` contents are removed from the DOM * * @element ANY * @scope * @priority 600 * @param {expression} ngIf If the {@link guide/expression expression} is falsy then * the element is removed from the DOM tree. If it is truthy a copy of the compiled * element is added to the DOM tree. * * @example <example module="ngAnimate" deps="angular-animate.js" animations="true"> <file name="index.html"> Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/> Show when checked: <span ng-if="checked" class="animate-if"> This is removed when the checkbox is unchecked. </span> </file> <file name="animations.css"> .animate-if { background:white; border:1px solid black; padding:10px; } .animate-if.ng-enter, .animate-if.ng-leave { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; } .animate-if.ng-enter, .animate-if.ng-leave.ng-leave-active { opacity:0; } .animate-if.ng-leave, .animate-if.ng-enter.ng-enter-active { opacity:1; } </file> </example> */ var ngIfDirective = ['$animate', function($animate) { return { multiElement: true, transclude: 'element', priority: 600, terminal: true, restrict: 'A', $$tlb: true, link: function($scope, $element, $attr, ctrl, $transclude) { var block, childScope, previousElements; $scope.$watch($attr.ngIf, function ngIfWatchAction(value) { if (value) { if (!childScope) { $transclude(function(clone, newScope) { childScope = newScope; clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' '); // Note: We only need the first/last node of the cloned nodes. // However, we need to keep the reference to the jqlite wrapper as it might be changed later // by a directive with templateUrl when its template arrives. block = { clone: clone }; $animate.enter(clone, $element.parent(), $element); }); } } else { if (previousElements) { previousElements.remove(); previousElements = null; } if (childScope) { childScope.$destroy(); childScope = null; } if (block) { previousElements = getBlockNodes(block.clone); $animate.leave(previousElements).then(function() { previousElements = null; }); block = null; } } }); } }; }]; /** * @ngdoc directive * @name ngInclude * @restrict ECA * * @description * Fetches, compiles and includes an external HTML fragment. * * By default, the template URL is restricted to the same domain and protocol as the * application document. This is done by calling {@link $sce#getTrustedResourceUrl * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link * ng.$sce Strict Contextual Escaping}. * * In addition, the browser's * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) * policy may further restrict whether the template is successfully loaded. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://` * access on some browsers. * * @animations * enter - animation is used to bring new content into the browser. * leave - animation is used to animate existing content away. * * The enter and leave animation occur concurrently. * * @scope * @priority 400 * * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant, * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`. * @param {string=} onload Expression to evaluate when a new partial is loaded. * * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll * $anchorScroll} to scroll the viewport after the content is loaded. * * - If the attribute is not set, disable scrolling. * - If the attribute is set without value, enable scrolling. * - Otherwise enable scrolling only if the expression evaluates to truthy value. * * @example <example module="includeExample" deps="angular-animate.js" animations="true"> <file name="index.html"> <div ng-controller="ExampleController"> <select ng-model="template" ng-options="t.name for t in templates"> <option value="">(blank)</option> </select> url of the template: <code>{{template.url}}</code> <hr/> <div class="slide-animate-container"> <div class="slide-animate" ng-include="template.url"></div> </div> </div> </file> <file name="script.js"> angular.module('includeExample', ['ngAnimate']) .controller('ExampleController', ['$scope', function($scope) { $scope.templates = [ { name: 'template1.html', url: 'template1.html'}, { name: 'template2.html', url: 'template2.html'} ]; $scope.template = $scope.templates[0]; }]); </file> <file name="template1.html"> Content of template1.html </file> <file name="template2.html"> Content of template2.html </file> <file name="animations.css"> .slide-animate-container { position:relative; background:white; border:1px solid black; height:40px; overflow:hidden; } .slide-animate { padding:10px; } .slide-animate.ng-enter, .slide-animate.ng-leave { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; position:absolute; top:0; left:0; right:0; bottom:0; display:block; padding:10px; } .slide-animate.ng-enter { top:-50px; } .slide-animate.ng-enter.ng-enter-active { top:0; } .slide-animate.ng-leave { top:0; } .slide-animate.ng-leave.ng-leave-active { top:50px; } </file> <file name="protractor.js" type="protractor"> var templateSelect = element(by.model('template')); var includeElem = element(by.css('[ng-include]')); it('should load template1.html', function() { expect(includeElem.getText()).toMatch(/Content of template1.html/); }); it('should load template2.html', function() { if (browser.params.browser == 'firefox') { // Firefox can't handle using selects // See https://github.com/angular/protractor/issues/480 return; } templateSelect.click(); templateSelect.all(by.css('option')).get(2).click(); expect(includeElem.getText()).toMatch(/Content of template2.html/); }); it('should change to blank', function() { if (browser.params.browser == 'firefox') { // Firefox can't handle using selects return; } templateSelect.click(); templateSelect.all(by.css('option')).get(0).click(); expect(includeElem.isPresent()).toBe(false); }); </file> </example> */ /** * @ngdoc event * @name ngInclude#$includeContentRequested * @eventType emit on the scope ngInclude was declared in * @description * Emitted every time the ngInclude content is requested. * * @param {Object} angularEvent Synthetic event object. * @param {String} src URL of content to load. */ /** * @ngdoc event * @name ngInclude#$includeContentLoaded * @eventType emit on the current ngInclude scope * @description * Emitted every time the ngInclude content is reloaded. * * @param {Object} angularEvent Synthetic event object. * @param {String} src URL of content to load. */ /** * @ngdoc event * @name ngInclude#$includeContentError * @eventType emit on the scope ngInclude was declared in * @description * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299) * * @param {Object} angularEvent Synthetic event object. * @param {String} src URL of content to load. */ var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate', '$sce', function($templateRequest, $anchorScroll, $animate, $sce) { return { restrict: 'ECA', priority: 400, terminal: true, transclude: 'element', controller: angular.noop, compile: function(element, attr) { var srcExp = attr.ngInclude || attr.src, onloadExp = attr.onload || '', autoScrollExp = attr.autoscroll; return function(scope, $element, $attr, ctrl, $transclude) { var changeCounter = 0, currentScope, previousElement, currentElement; var cleanupLastIncludeContent = function() { if (previousElement) { previousElement.remove(); previousElement = null; } if (currentScope) { currentScope.$destroy(); currentScope = null; } if (currentElement) { $animate.leave(currentElement).then(function() { previousElement = null; }); previousElement = currentElement; currentElement = null; } }; scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) { var afterAnimation = function() { if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { $anchorScroll(); } }; var thisChangeId = ++changeCounter; if (src) { //set the 2nd param to true to ignore the template request error so that the inner //contents and scope can be cleaned up. $templateRequest(src, true).then(function(response) { if (thisChangeId !== changeCounter) return; var newScope = scope.$new(); ctrl.template = response; // Note: This will also link all children of ng-include that were contained in the original // html. If that content contains controllers, ... they could pollute/change the scope. // However, using ng-include on an element with additional content does not make sense... // Note: We can't remove them in the cloneAttchFn of $transclude as that // function is called before linking the content, which would apply child // directives to non existing elements. var clone = $transclude(newScope, function(clone) { cleanupLastIncludeContent(); $animate.enter(clone, null, $element).then(afterAnimation); }); currentScope = newScope; currentElement = clone; currentScope.$emit('$includeContentLoaded', src); scope.$eval(onloadExp); }, function() { if (thisChangeId === changeCounter) { cleanupLastIncludeContent(); scope.$emit('$includeContentError', src); } }); scope.$emit('$includeContentRequested', src); } else { cleanupLastIncludeContent(); ctrl.template = null; } }); }; } }; }]; // This directive is called during the $transclude call of the first `ngInclude` directive. // It will replace and compile the content of the element with the loaded template. // We need this directive so that the element content is already filled when // the link function of another directive on the same element as ngInclude // is called. var ngIncludeFillContentDirective = ['$compile', function($compile) { return { restrict: 'ECA', priority: -400, require: 'ngInclude', link: function(scope, $element, $attr, ctrl) { if (/SVG/.test($element[0].toString())) { // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not // support innerHTML, so detect this here and try to generate the contents // specially. $element.empty(); $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope, function namespaceAdaptedClone(clone) { $element.append(clone); }, {futureParentElement: $element}); return; } $element.html(ctrl.template); $compile($element.contents())(scope); } }; }]; /** * @ngdoc directive * @name ngInit * @restrict AC * * @description * The `ngInit` directive allows you to evaluate an expression in the * current scope. * * <div class="alert alert-error"> * The only appropriate use of `ngInit` is for aliasing special properties of * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you * should use {@link guide/controller controllers} rather than `ngInit` * to initialize values on a scope. * </div> * <div class="alert alert-warning"> * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make * sure you have parenthesis for correct precedence: * <pre class="prettyprint"> * `<div ng-init="test1 = (data | orderBy:'name')"></div>` * </pre> * </div> * * @priority 450 * * @element ANY * @param {expression} ngInit {@link guide/expression Expression} to eval. * * @example <example module="initExample"> <file name="index.html"> <script> angular.module('initExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.list = [['a', 'b'], ['c', 'd']]; }]); </script> <div ng-controller="ExampleController"> <div ng-repeat="innerList in list" ng-init="outerIndex = $index"> <div ng-repeat="value in innerList" ng-init="innerIndex = $index"> <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span> </div> </div> </div> </file> <file name="protractor.js" type="protractor"> it('should alias index positions', function() { var elements = element.all(by.css('.example-init')); expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;'); expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;'); expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;'); expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;'); }); </file> </example> */ var ngInitDirective = ngDirective({ priority: 450, compile: function() { return { pre: function(scope, element, attrs) { scope.$eval(attrs.ngInit); } }; } }); /** * @ngdoc directive * @name ngList * * @description * Text input that converts between a delimited string and an array of strings. The default * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`. * * The behaviour of the directive is affected by the use of the `ngTrim` attribute. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each * list item is respected. This implies that the user of the directive is responsible for * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a * tab or newline character. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected * when joining the list items back together) and whitespace around each list item is stripped * before it is added to the model. * * ### Example with Validation * * <example name="ngList-directive" module="listExample"> * <file name="app.js"> * angular.module('listExample', []) * .controller('ExampleController', ['$scope', function($scope) { * $scope.names = ['morpheus', 'neo', 'trinity']; * }]); * </file> * <file name="index.html"> * <form name="myForm" ng-controller="ExampleController"> * List: <input name="namesInput" ng-model="names" ng-list required> * <span class="error" ng-show="myForm.namesInput.$error.required"> * Required!</span> * <br> * <tt>names = {{names}}</tt><br/> * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/> * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/> * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> * </form> * </file> * <file name="protractor.js" type="protractor"> * var listInput = element(by.model('names')); * var names = element(by.exactBinding('names')); * var valid = element(by.binding('myForm.namesInput.$valid')); * var error = element(by.css('span.error')); * * it('should initialize to model', function() { * expect(names.getText()).toContain('["morpheus","neo","trinity"]'); * expect(valid.getText()).toContain('true'); * expect(error.getCssValue('display')).toBe('none'); * }); * * it('should be invalid if empty', function() { * listInput.clear(); * listInput.sendKeys(''); * * expect(names.getText()).toContain(''); * expect(valid.getText()).toContain('false'); * expect(error.getCssValue('display')).not.toBe('none'); * }); * </file> * </example> * * ### Example - splitting on whitespace * <example name="ngList-directive-newlines"> * <file name="index.html"> * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea> * <pre>{{ list | json }}</pre> * </file> * <file name="protractor.js" type="protractor"> * it("should split the text by newlines", function() { * var listInput = element(by.model('list')); * var output = element(by.binding('list | json')); * listInput.sendKeys('abc\ndef\nghi'); * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]'); * }); * </file> * </example> * * @element input * @param {string=} ngList optional delimiter that should be used to split the value. */ var ngListDirective = function() { return { restrict: 'A', priority: 100, require: 'ngModel', link: function(scope, element, attr, ctrl) { // We want to control whitespace trimming so we use this convoluted approach // to access the ngList attribute, which doesn't pre-trim the attribute var ngList = element.attr(attr.$attr.ngList) || ', '; var trimValues = attr.ngTrim !== 'false'; var separator = trimValues ? trim(ngList) : ngList; var parse = function(viewValue) { // If the viewValue is invalid (say required but empty) it will be `undefined` if (isUndefined(viewValue)) return; var list = []; if (viewValue) { forEach(viewValue.split(separator), function(value) { if (value) list.push(trimValues ? trim(value) : value); }); } return list; }; ctrl.$parsers.push(parse); ctrl.$formatters.push(function(value) { if (isArray(value)) { return value.join(ngList); } return undefined; }); // Override the standard $isEmpty because an empty array means the input is empty. ctrl.$isEmpty = function(value) { return !value || !value.length; }; } }; }; /* global VALID_CLASS: true, INVALID_CLASS: true, PRISTINE_CLASS: true, DIRTY_CLASS: true, UNTOUCHED_CLASS: true, TOUCHED_CLASS: true, */ var VALID_CLASS = 'ng-valid', INVALID_CLASS = 'ng-invalid', PRISTINE_CLASS = 'ng-pristine', DIRTY_CLASS = 'ng-dirty', UNTOUCHED_CLASS = 'ng-untouched', TOUCHED_CLASS = 'ng-touched', PENDING_CLASS = 'ng-pending'; var $ngModelMinErr = new minErr('ngModel'); /** * @ngdoc type * @name ngModel.NgModelController * * @property {string} $viewValue Actual string value in the view. * @property {*} $modelValue The value in the model that the control is bound to. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever the control reads value from the DOM. The functions are called in array order, each passing its return value through to the next. The last return value is forwarded to the {@link ngModel.NgModelController#$validators `$validators`} collection. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue `$viewValue`}. Returning `undefined` from a parser means a parse error occurred. In that case, no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel` will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is set to `true`. The parse error is stored in `ngModel.$error.parse`. * * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever the model value changes. The functions are called in reverse array order, each passing the value through to the next. The last return value is used as the actual DOM value. Used to format / convert values for display in the control. * ```js * function formatter(value) { * if (value) { * return value.toUpperCase(); * } * } * ngModel.$formatters.push(formatter); * ``` * * @property {Object.<string, function>} $validators A collection of validators that are applied * whenever the model value changes. The key value within the object refers to the name of the * validator while the function refers to the validation operation. The validation operation is * provided with the model value as an argument and must return a true or false value depending * on the response of that validation. * * ```js * ngModel.$validators.validCharacters = function(modelValue, viewValue) { * var value = modelValue || viewValue; * return /[0-9]+/.test(value) && * /[a-z]+/.test(value) && * /[A-Z]+/.test(value) && * /\W+/.test(value); * }; * ``` * * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided * is expected to return a promise when it is run during the model validation process. Once the promise * is delivered then the validation status will be set to true when fulfilled and false when rejected. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators * will only run once all synchronous validators have passed. * * Please note that if $http is used then it is important that the server returns a success HTTP response code * in order to fulfill the validation and a status level of `4xx` in order to reject the validation. * * ```js * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) { * var value = modelValue || viewValue; * * // Lookup user by username * return $http.get('/api/users/' + value). * then(function resolved() { * //username exists, this means validation fails * return $q.reject('exists'); * }, function rejected() { * //username does not exist, therefore this validation passes * return true; * }); * }; * ``` * * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the * view value has changed. It is called with no arguments, and its return value is ignored. * This can be used in place of additional $watches against the model value. * * @property {Object} $error An object hash with all failing validator ids as keys. * @property {Object} $pending An object hash with all pending validator ids as keys. * * @property {boolean} $untouched True if control has not lost focus yet. * @property {boolean} $touched True if control has lost focus. * @property {boolean} $pristine True if user has not interacted with the control yet. * @property {boolean} $dirty True if user has already interacted with the control. * @property {boolean} $valid True if there is no error. * @property {boolean} $invalid True if at least one error on the control. * @property {string} $name The name attribute of the control. * * @description * * `NgModelController` provides API for the {@link ngModel `ngModel`} directive. * The controller contains services for data-binding, validation, CSS updates, and value formatting * and parsing. It purposefully does not contain any logic which deals with DOM rendering or * listening to DOM events. * Such DOM related logic should be provided by other directives which make use of * `NgModelController` for data-binding to control elements. * Angular provides this DOM logic for most {@link input `input`} elements. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example * custom control example} that uses `ngModelController` to bind to `contenteditable` elements. * * @example * ### Custom Control Example * This example shows how to use `NgModelController` with a custom control to achieve * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`) * collaborate together to achieve the desired result. * * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element * contents be edited in place by the user. This will not work on older browsers. * * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize} * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`). * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks * that content using the `$sce` service. * * <example name="NgModelController" module="customControl" deps="angular-sanitize.js"> <file name="style.css"> [contenteditable] { border: 1px solid black; background-color: white; min-height: 20px; } .ng-invalid { border: 1px solid red; } </file> <file name="script.js"> angular.module('customControl', ['ngSanitize']). directive('contenteditable', ['$sce', function($sce) { return { restrict: 'A', // only activate on element attribute require: '?ngModel', // get a hold of NgModelController link: function(scope, element, attrs, ngModel) { if (!ngModel) return; // do nothing if no ng-model // Specify how UI should be updated ngModel.$render = function() { element.html($sce.getTrustedHtml(ngModel.$viewValue || '')); }; // Listen for change events to enable binding element.on('blur keyup change', function() { scope.$evalAsync(read); }); read(); // initialize // Write data to the model function read() { var html = element.html(); // When we clear the content editable the browser leaves a <br> behind // If strip-br attribute is provided then we strip this out if ( attrs.stripBr && html == '<br>' ) { html = ''; } ngModel.$setViewValue(html); } } }; }]); </file> <file name="index.html"> <form name="myForm"> <div contenteditable name="myWidget" ng-model="userContent" strip-br="true" required>Change me!</div> <span ng-show="myForm.myWidget.$error.required">Required!</span> <hr> <textarea ng-model="userContent"></textarea> </form> </file> <file name="protractor.js" type="protractor"> it('should data-bind and become invalid', function() { if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') { // SafariDriver can't handle contenteditable // and Firefox driver can't clear contenteditables very well return; } var contentEditable = element(by.css('[contenteditable]')); var content = 'Change me!'; expect(contentEditable.getText()).toEqual(content); contentEditable.clear(); contentEditable.sendKeys(protractor.Key.BACK_SPACE); expect(contentEditable.getText()).toEqual(''); expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/); }); </file> * </example> * * */ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate', function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) { this.$viewValue = Number.NaN; this.$modelValue = Number.NaN; this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity. this.$validators = {}; this.$asyncValidators = {}; this.$parsers = []; this.$formatters = []; this.$viewChangeListeners = []; this.$untouched = true; this.$touched = false; this.$pristine = true; this.$dirty = false; this.$valid = true; this.$invalid = false; this.$error = {}; // keep invalid keys here this.$$success = {}; // keep valid keys here this.$pending = undefined; // keep pending keys here this.$name = $interpolate($attr.name || '', false)($scope); var parsedNgModel = $parse($attr.ngModel), parsedNgModelAssign = parsedNgModel.assign, ngModelGet = parsedNgModel, ngModelSet = parsedNgModelAssign, pendingDebounce = null, ctrl = this; this.$$setOptions = function(options) { ctrl.$options = options; if (options && options.getterSetter) { var invokeModelGetter = $parse($attr.ngModel + '()'), invokeModelSetter = $parse($attr.ngModel + '($$$p)'); ngModelGet = function($scope) { var modelValue = parsedNgModel($scope); if (isFunction(modelValue)) { modelValue = invokeModelGetter($scope); } return modelValue; }; ngModelSet = function($scope, newValue) { if (isFunction(parsedNgModel($scope))) { invokeModelSetter($scope, {$$$p: ctrl.$modelValue}); } else { parsedNgModelAssign($scope, ctrl.$modelValue); } }; } else if (!parsedNgModel.assign) { throw $ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}", $attr.ngModel, startingTag($element)); } }; /** * @ngdoc method * @name ngModel.NgModelController#$render * * @description * Called when the view needs to be updated. It is expected that the user of the ng-model * directive will implement this method. * * The `$render()` method is invoked in the following situations: * * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last * committed value then `$render()` is called to update the input control. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and * the `$viewValue` are different to last time. * * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of * `$modelValue` and `$viewValue` are actually different to their previous value. If `$modelValue` * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be * invoked if you only change a property on the objects. */ this.$render = noop; /** * @ngdoc method * @name ngModel.NgModelController#$isEmpty * * @description * This is called when we need to determine if the value of an input is empty. * * For instance, the required directive does this to work out if the input has data or not. * * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`. * * You can override this for input directives whose concept of being empty is different to the * default. The `checkboxInputType` directive does this because in its case a value of `false` * implies empty. * * @param {*} value The value of the input to check for emptiness. * @returns {boolean} True if `value` is "empty". */ this.$isEmpty = function(value) { return isUndefined(value) || value === '' || value === null || value !== value; }; var parentForm = $element.inheritedData('$formController') || nullFormCtrl, currentValidationRunId = 0; /** * @ngdoc method * @name ngModel.NgModelController#$setValidity * * @description * Change the validity state, and notify the form. * * This method can be called within $parsers/$formatters or a custom validation implementation. * However, in most cases it should be sufficient to use the `ngModel.$validators` and * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically. * * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]` * (for unfulfilled `$asyncValidators`), so that it is available for data-binding. * The `validationErrorKey` should be in camelCase and will get converted into dash-case * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` * class and can be bound to as `{{someForm.someControl.$error.myError}}` . * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined), * or skipped (null). Pending is used for unfulfilled `$asyncValidators`. * Skipped is used by Angular when validators do not run because of parse errors and * when `$asyncValidators` do not run because any of the `$validators` failed. */ addSetValidityMethod({ ctrl: this, $element: $element, set: function(object, property) { object[property] = true; }, unset: function(object, property) { delete object[property]; }, parentForm: parentForm, $animate: $animate }); /** * @ngdoc method * @name ngModel.NgModelController#$setPristine * * @description * Sets the control to its pristine state. * * This method can be called to remove the `ng-dirty` class and set the control to its pristine * state (`ng-pristine` class). A model is considered to be pristine when the control * has not been changed from when first compiled. */ this.$setPristine = function() { ctrl.$dirty = false; ctrl.$pristine = true; $animate.removeClass($element, DIRTY_CLASS); $animate.addClass($element, PRISTINE_CLASS); }; /** * @ngdoc method * @name ngModel.NgModelController#$setDirty * * @description * Sets the control to its dirty state. * * This method can be called to remove the `ng-pristine` class and set the control to its dirty * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed * from when first compiled. */ this.$setDirty = function() { ctrl.$dirty = true; ctrl.$pristine = false; $animate.removeClass($element, PRISTINE_CLASS); $animate.addClass($element, DIRTY_CLASS); parentForm.$setDirty(); }; /** * @ngdoc method * @name ngModel.NgModelController#$setUntouched * * @description * Sets the control to its untouched state. * * This method can be called to remove the `ng-touched` class and set the control to its * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched * by default, however this function can be used to restore that state if the model has * already been touched by the user. */ this.$setUntouched = function() { ctrl.$touched = false; ctrl.$untouched = true; $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS); }; /** * @ngdoc method * @name ngModel.NgModelController#$setTouched * * @description * Sets the control to its touched state. * * This method can be called to remove the `ng-untouched` class and set the control to its * touched state (`ng-touched` class). A model is considered to be touched when the user has * first focused the control element and then shifted focus away from the control (blur event). */ this.$setTouched = function() { ctrl.$touched = true; ctrl.$untouched = false; $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS); }; /** * @ngdoc method * @name ngModel.NgModelController#$rollbackViewValue * * @description * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`, * which may be caused by a pending debounced event or because the input is waiting for a some * future event. * * If you have an input that uses `ng-model-options` to set up debounced events or events such * as blur you can have a situation where there is a period when the `$viewValue` * is out of synch with the ngModel's `$modelValue`. * * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue` * programmatically before these debounced/future events have resolved/occurred, because Angular's * dirty checking mechanism is not able to tell whether the model has actually changed or not. * * The `$rollbackViewValue()` method should be called before programmatically changing the model of an * input which may have such events pending. This is important in order to make sure that the * input field will be updated with the new model value and any pending operations are cancelled. * * <example name="ng-model-cancel-update" module="cancel-update-example"> * <file name="app.js"> * angular.module('cancel-update-example', []) * * .controller('CancelUpdateController', ['$scope', function($scope) { * $scope.resetWithCancel = function(e) { * if (e.keyCode == 27) { * $scope.myForm.myInput1.$rollbackViewValue(); * $scope.myValue = ''; * } * }; * $scope.resetWithoutCancel = function(e) { * if (e.keyCode == 27) { * $scope.myValue = ''; * } * }; * }]); * </file> * <file name="index.html"> * <div ng-controller="CancelUpdateController"> * <p>Try typing something in each input. See that the model only updates when you * blur off the input. * </p> * <p>Now see what happens if you start typing then press the Escape key</p> * * <form name="myForm" ng-model-options="{ updateOn: 'blur' }"> * <p>With $rollbackViewValue()</p> * <input name="myInput1" ng-model="myValue" ng-keydown="resetWithCancel($event)"><br/> * myValue: "{{ myValue }}" * * <p>Without $rollbackViewValue()</p> * <input name="myInput2" ng-model="myValue" ng-keydown="resetWithoutCancel($event)"><br/> * myValue: "{{ myValue }}" * </form> * </div> * </file> * </example> */ this.$rollbackViewValue = function() { $timeout.cancel(pendingDebounce); ctrl.$viewValue = ctrl.$$lastCommittedViewValue; ctrl.$render(); }; /** * @ngdoc method * @name ngModel.NgModelController#$validate * * @description * Runs each of the registered validators (first synchronous validators and then * asynchronous validators). * If the validity changes to invalid, the model will be set to `undefined`, * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`. * If the validity changes to valid, it will set the model to the last available valid * modelValue, i.e. either the last parsed value or the last value set from the scope. */ this.$validate = function() { // ignore $validate before model is initialized if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) { return; } var viewValue = ctrl.$$lastCommittedViewValue; // Note: we use the $$rawModelValue as $modelValue might have been // set to undefined during a view -> model update that found validation // errors. We can't parse the view here, since that could change // the model although neither viewValue nor the model on the scope changed var modelValue = ctrl.$$rawModelValue; // Check if the there's a parse error, so we don't unset it accidentially var parserName = ctrl.$$parserName || 'parse'; var parserValid = ctrl.$error[parserName] ? false : undefined; var prevValid = ctrl.$valid; var prevModelValue = ctrl.$modelValue; var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid; ctrl.$$runValidators(parserValid, modelValue, viewValue, function(allValid) { // If there was no change in validity, don't update the model // This prevents changing an invalid modelValue to undefined if (!allowInvalid && prevValid !== allValid) { // Note: Don't check ctrl.$valid here, as we could have // external validators (e.g. calculated on the server), // that just call $setValidity and need the model value // to calculate their validity. ctrl.$modelValue = allValid ? modelValue : undefined; if (ctrl.$modelValue !== prevModelValue) { ctrl.$$writeModelToScope(); } } }); }; this.$$runValidators = function(parseValid, modelValue, viewValue, doneCallback) { currentValidationRunId++; var localValidationRunId = currentValidationRunId; // check parser error if (!processParseErrors(parseValid)) { validationDone(false); return; } if (!processSyncValidators()) { validationDone(false); return; } processAsyncValidators(); function processParseErrors(parseValid) { var errorKey = ctrl.$$parserName || 'parse'; if (parseValid === undefined) { setValidity(errorKey, null); } else { setValidity(errorKey, parseValid); if (!parseValid) { forEach(ctrl.$validators, function(v, name) { setValidity(name, null); }); forEach(ctrl.$asyncValidators, function(v, name) { setValidity(name, null); }); return false; } } return true; } function processSyncValidators() { var syncValidatorsValid = true; forEach(ctrl.$validators, function(validator, name) { var result = validator(modelValue, viewValue); syncValidatorsValid = syncValidatorsValid && result; setValidity(name, result); }); if (!syncValidatorsValid) { forEach(ctrl.$asyncValidators, function(v, name) { setValidity(name, null); }); return false; } return true; } function processAsyncValidators() { var validatorPromises = []; var allValid = true; forEach(ctrl.$asyncValidators, function(validator, name) { var promise = validator(modelValue, viewValue); if (!isPromiseLike(promise)) { throw $ngModelMinErr("$asyncValidators", "Expected asynchronous validator to return a promise but got '{0}' instead.", promise); } setValidity(name, undefined); validatorPromises.push(promise.then(function() { setValidity(name, true); }, function(error) { allValid = false; setValidity(name, false); })); }); if (!validatorPromises.length) { validationDone(true); } else { $q.all(validatorPromises).then(function() { validationDone(allValid); }, noop); } } function setValidity(name, isValid) { if (localValidationRunId === currentValidationRunId) { ctrl.$setValidity(name, isValid); } } function validationDone(allValid) { if (localValidationRunId === currentValidationRunId) { doneCallback(allValid); } } }; /** * @ngdoc method * @name ngModel.NgModelController#$commitViewValue * * @description * Commit a pending update to the `$modelValue`. * * Updates may be pending by a debounced event or because the input is waiting for a some future * event defined in `ng-model-options`. this method is rarely needed as `NgModelController` * usually handles calling this in response to input events. */ this.$commitViewValue = function() { var viewValue = ctrl.$viewValue; $timeout.cancel(pendingDebounce); // If the view value has not changed then we should just exit, except in the case where there is // a native validator on the element. In this case the validation state may have changed even though // the viewValue has stayed empty. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) { return; } ctrl.$$lastCommittedViewValue = viewValue; // change to dirty if (ctrl.$pristine) { this.$setDirty(); } this.$$parseAndValidate(); }; this.$$parseAndValidate = function() { var viewValue = ctrl.$$lastCommittedViewValue; var modelValue = viewValue; var parserValid = isUndefined(modelValue) ? undefined : true; if (parserValid) { for (var i = 0; i < ctrl.$parsers.length; i++) { modelValue = ctrl.$parsers[i](modelValue); if (isUndefined(modelValue)) { parserValid = false; break; } } } if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) { // ctrl.$modelValue has not been touched yet... ctrl.$modelValue = ngModelGet($scope); } var prevModelValue = ctrl.$modelValue; var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid; ctrl.$$rawModelValue = modelValue; if (allowInvalid) { ctrl.$modelValue = modelValue; writeToModelIfNeeded(); } // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date. // This can happen if e.g. $setViewValue is called from inside a parser ctrl.$$runValidators(parserValid, modelValue, ctrl.$$lastCommittedViewValue, function(allValid) { if (!allowInvalid) { // Note: Don't check ctrl.$valid here, as we could have // external validators (e.g. calculated on the server), // that just call $setValidity and need the model value // to calculate their validity. ctrl.$modelValue = allValid ? modelValue : undefined; writeToModelIfNeeded(); } }); function writeToModelIfNeeded() { if (ctrl.$modelValue !== prevModelValue) { ctrl.$$writeModelToScope(); } } }; this.$$writeModelToScope = function() { ngModelSet($scope, ctrl.$modelValue); forEach(ctrl.$viewChangeListeners, function(listener) { try { listener(); } catch (e) { $exceptionHandler(e); } }); }; /** * @ngdoc method * @name ngModel.NgModelController#$setViewValue * * @description * Update the view value. * * This method should be called when an input directive want to change the view value; typically, * this is done from within a DOM event handler. * * For example {@link ng.directive:input input} calls it when the value of the input changes and * {@link ng.directive:select select} calls it when an option is selected. * * If the new `value` is an object (rather than a string or a number), we should make a copy of the * object before passing it to `$setViewValue`. This is because `ngModel` does not perform a deep * watch of objects, it only looks for a change of identity. If you only change the property of * the object then ngModel will not realise that the object has changed and will not invoke the * `$parsers` and `$validators` pipelines. * * For this reason, you should not change properties of the copy once it has been passed to * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly. * * When this method is called, the new `value` will be staged for committing through the `$parsers` * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged * value sent directly for processing, finally to be applied to `$modelValue` and then the * **expression** specified in the `ng-model` attribute. * * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called. * * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn` * and the `default` trigger is not listed, all those actions will remain pending until one of the * `updateOn` events is triggered on the DOM element. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions} * directive is used with a custom debounce for this particular event. * * Note that calling this function does not trigger a `$digest`. * * @param {string} value Value from the view. * @param {string} trigger Event that triggered the update. */ this.$setViewValue = function(value, trigger) { ctrl.$viewValue = value; if (!ctrl.$options || ctrl.$options.updateOnDefault) { ctrl.$$debounceViewValueCommit(trigger); } }; this.$$debounceViewValueCommit = function(trigger) { var debounceDelay = 0, options = ctrl.$options, debounce; if (options && isDefined(options.debounce)) { debounce = options.debounce; if (isNumber(debounce)) { debounceDelay = debounce; } else if (isNumber(debounce[trigger])) { debounceDelay = debounce[trigger]; } else if (isNumber(debounce['default'])) { debounceDelay = debounce['default']; } } $timeout.cancel(pendingDebounce); if (debounceDelay) { pendingDebounce = $timeout(function() { ctrl.$commitViewValue(); }, debounceDelay); } else if ($rootScope.$$phase) { ctrl.$commitViewValue(); } else { $scope.$apply(function() { ctrl.$commitViewValue(); }); } }; // model -> value // Note: we cannot use a normal scope.$watch as we want to detect the following: // 1. scope value is 'a' // 2. user enters 'b' // 3. ng-change kicks in and reverts scope value to 'a' // -> scope value did not change since the last digest as // ng-change executes in apply phase // 4. view should be changed back to 'a' $scope.$watch(function ngModelWatch() { var modelValue = ngModelGet($scope); // if scope model value and ngModel value are out of sync // TODO(perf): why not move this to the action fn? if (modelValue !== ctrl.$modelValue) { ctrl.$modelValue = ctrl.$$rawModelValue = modelValue; var formatters = ctrl.$formatters, idx = formatters.length; var viewValue = modelValue; while (idx--) { viewValue = formatters[idx](viewValue); } if (ctrl.$viewValue !== viewValue) { ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue; ctrl.$render(); ctrl.$$runValidators(undefined, modelValue, viewValue, noop); } } return modelValue; }); }]; /** * @ngdoc directive * @name ngModel * * @element input * @priority 1 * * @description * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a * property on the scope using {@link ngModel.NgModelController NgModelController}, * which is created and exposed by this directive. * * `ngModel` is responsible for: * * - Binding the view into the model, which other directives such as `input`, `textarea` or `select` * require. * - Providing validation behavior (i.e. required, number, email, url). * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors). * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations. * - Registering the control with its parent {@link ng.directive:form form}. * * Note: `ngModel` will try to bind to the property given by evaluating the expression on the * current scope. If the property doesn't already exist on this scope, it will be created * implicitly and added to the scope. * * For best practices on using `ngModel`, see: * * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes) * * For basic examples, how to use `ngModel`, see: * * - {@link ng.directive:input input} * - {@link input[text] text} * - {@link input[checkbox] checkbox} * - {@link input[radio] radio} * - {@link input[number] number} * - {@link input[email] email} * - {@link input[url] url} * - {@link input[date] date} * - {@link input[datetime-local] datetime-local} * - {@link input[time] time} * - {@link input[month] month} * - {@link input[week] week} * - {@link ng.directive:select select} * - {@link ng.directive:textarea textarea} * * # CSS classes * The following CSS classes are added and removed on the associated input/select/textarea element * depending on the validity of the model. * * - `ng-valid`: the model is valid * - `ng-invalid`: the model is invalid * - `ng-valid-[key]`: for each valid key added by `$setValidity` * - `ng-invalid-[key]`: for each invalid key added by `$setValidity` * - `ng-pristine`: the control hasn't been interacted with yet * - `ng-dirty`: the control has been interacted with * - `ng-touched`: the control has been blurred * - `ng-untouched`: the control hasn't been blurred * - `ng-pending`: any `$asyncValidators` are unfulfilled * * Keep in mind that ngAnimate can detect each of these classes when added and removed. * * ## Animation Hooks * * Animations within models are triggered when any of the associated CSS classes are added and removed * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`, * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself. * The animations that are triggered within ngModel are similar to how they work in ngClass and * animations can be hooked into using CSS transitions, keyframes as well as JS animations. * * The following example shows a simple way to utilize CSS transitions to style an input element * that has been rendered as invalid after it has been validated: * * <pre> * //be sure to include ngAnimate as a module to hook into more * //advanced animations * .my-input { * transition:0.5s linear all; * background: white; * } * .my-input.ng-invalid { * background: red; * color:white; * } * </pre> * * @example * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample"> <file name="index.html"> <script> angular.module('inputExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.val = '1'; }]); </script> <style> .my-input { -webkit-transition:all linear 0.5s; transition:all linear 0.5s; background: transparent; } .my-input.ng-invalid { color:white; background: red; } </style> Update input to see transitions when valid/invalid. Integer is a valid value. <form name="testForm" ng-controller="ExampleController"> <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" /> </form> </file> * </example> * * ## Binding to a getter/setter * * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a * function that returns a representation of the model when called with zero arguments, and sets * the internal state of a model when called with an argument. It's sometimes useful to use this * for models that have an internal representation that's different than what the model exposes * to the view. * * <div class="alert alert-success"> * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more * frequently than other parts of your code. * </div> * * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to * a `<form>`, which will enable this behavior for all `<input>`s within it. See * {@link ng.directive:ngModelOptions `ngModelOptions`} for more. * * The following example shows how to use `ngModel` with a getter/setter: * * @example * <example name="ngModel-getter-setter" module="getterSetterExample"> <file name="index.html"> <div ng-controller="ExampleController"> <form name="userForm"> Name: <input type="text" name="userName" ng-model="user.name" ng-model-options="{ getterSetter: true }" /> </form> <pre>user.name = <span ng-bind="user.name()"></span></pre> </div> </file> <file name="app.js"> angular.module('getterSetterExample', []) .controller('ExampleController', ['$scope', function($scope) { var _name = 'Brian'; $scope.user = { name: function(newName) { if (angular.isDefined(newName)) { _name = newName; } return _name; } }; }]); </file> * </example> */ var ngModelDirective = ['$rootScope', function($rootScope) { return { restrict: 'A', require: ['ngModel', '^?form', '^?ngModelOptions'], controller: NgModelController, // Prelink needs to run before any input directive // so that we can set the NgModelOptions in NgModelController // before anyone else uses it. priority: 1, compile: function ngModelCompile(element) { // Setup initial state of the control element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS); return { pre: function ngModelPreLink(scope, element, attr, ctrls) { var modelCtrl = ctrls[0], formCtrl = ctrls[1] || nullFormCtrl; modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options); // notify others, especially parent forms formCtrl.$addControl(modelCtrl); attr.$observe('name', function(newValue) { if (modelCtrl.$name !== newValue) { formCtrl.$$renameControl(modelCtrl, newValue); } }); scope.$on('$destroy', function() { formCtrl.$removeControl(modelCtrl); }); }, post: function ngModelPostLink(scope, element, attr, ctrls) { var modelCtrl = ctrls[0]; if (modelCtrl.$options && modelCtrl.$options.updateOn) { element.on(modelCtrl.$options.updateOn, function(ev) { modelCtrl.$$debounceViewValueCommit(ev && ev.type); }); } element.on('blur', function(ev) { if (modelCtrl.$touched) return; if ($rootScope.$$phase) { scope.$evalAsync(modelCtrl.$setTouched); } else { scope.$apply(modelCtrl.$setTouched); } }); } }; } }; }]; var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/; /** * @ngdoc directive * @name ngModelOptions * * @description * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of * events that will trigger a model update and/or a debouncing delay so that the actual update only * takes place when a timer expires; this timer will be reset after another change takes place. * * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might * be different than the value in the actual model. This means that if you update the model you * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in * order to make sure it is synchronized with the model and that any debounced action is canceled. * * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`} * method is by making sure the input is placed inside a form that has a `name` attribute. This is * important because `form` controllers are published to the related scope under the name in their * `name` attribute. * * Any pending changes will take place immediately when an enclosing form is submitted via the * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit` * to have access to the updated model. * * `ngModelOptions` has an effect on the element it's declared on and its descendants. * * @param {Object} ngModelOptions options to apply to the current model. Valid keys are: * - `updateOn`: string specifying which event should the input be bound to. You can set several * events using an space delimited list. There is a special event called `default` that * matches the default events belonging of the control. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a * custom value for each event. For example: * `ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }"` * - `allowInvalid`: boolean value which indicates that the model can be set with values that did * not validate correctly instead of the default behavior of setting the model to undefined. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to `ngModel` as getters/setters. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for * `<input type="date">`, `<input type="time">`, ... . Right now, the only supported value is `'UTC'`, * otherwise the default timezone of the browser will be used. * * @example The following example shows how to override immediate updates. Changes on the inputs within the form will update the model only when the control loses focus (blur event). If `escape` key is pressed while the input field is focused, the value is reset to the value in the current model. <example name="ngModelOptions-directive-blur" module="optionsExample"> <file name="index.html"> <div ng-controller="ExampleController"> <form name="userForm"> Name: <input type="text" name="userName" ng-model="user.name" ng-model-options="{ updateOn: 'blur' }" ng-keyup="cancel($event)" /><br /> Other data: <input type="text" ng-model="user.data" /><br /> </form> <pre>user.name = <span ng-bind="user.name"></span></pre> </div> </file> <file name="app.js"> angular.module('optionsExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.user = { name: 'say', data: '' }; $scope.cancel = function(e) { if (e.keyCode == 27) { $scope.userForm.userName.$rollbackViewValue(); } }; }]); </file> <file name="protractor.js" type="protractor"> var model = element(by.binding('user.name')); var input = element(by.model('user.name')); var other = element(by.model('user.data')); it('should allow custom events', function() { input.sendKeys(' hello'); input.click(); expect(model.getText()).toEqual('say'); other.click(); expect(model.getText()).toEqual('say hello'); }); it('should $rollbackViewValue when model changes', function() { input.sendKeys(' hello'); expect(input.getAttribute('value')).toEqual('say hello'); input.sendKeys(protractor.Key.ESCAPE); expect(input.getAttribute('value')).toEqual('say'); other.click(); expect(model.getText()).toEqual('say'); }); </file> </example> This one shows how to debounce model changes. Model will be updated only 1 sec after last change. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty. <example name="ngModelOptions-directive-debounce" module="optionsExample"> <file name="index.html"> <div ng-controller="ExampleController"> <form name="userForm"> Name: <input type="text" name="userName" ng-model="user.name" ng-model-options="{ debounce: 1000 }" /> <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br /> </form> <pre>user.name = <span ng-bind="user.name"></span></pre> </div> </file> <file name="app.js"> angular.module('optionsExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.user = { name: 'say' }; }]); </file> </example> This one shows how to bind to getter/setters: <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample"> <file name="index.html"> <div ng-controller="ExampleController"> <form name="userForm"> Name: <input type="text" name="userName" ng-model="user.name" ng-model-options="{ getterSetter: true }" /> </form> <pre>user.name = <span ng-bind="user.name()"></span></pre> </div> </file> <file name="app.js"> angular.module('getterSetterExample', []) .controller('ExampleController', ['$scope', function($scope) { var _name = 'Brian'; $scope.user = { name: function(newName) { return angular.isDefined(newName) ? (_name = newName) : _name; } }; }]); </file> </example> */ var ngModelOptionsDirective = function() { return { restrict: 'A', controller: ['$scope', '$attrs', function($scope, $attrs) { var that = this; this.$options = $scope.$eval($attrs.ngModelOptions); // Allow adding/overriding bound events if (this.$options.updateOn !== undefined) { this.$options.updateOnDefault = false; // extract "default" pseudo-event from list of events that can trigger a model update this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() { that.$options.updateOnDefault = true; return ' '; })); } else { this.$options.updateOnDefault = true; } }] }; }; // helper methods function addSetValidityMethod(context) { var ctrl = context.ctrl, $element = context.$element, classCache = {}, set = context.set, unset = context.unset, parentForm = context.parentForm, $animate = context.$animate; classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS)); ctrl.$setValidity = setValidity; function setValidity(validationErrorKey, state, controller) { if (state === undefined) { createAndSet('$pending', validationErrorKey, controller); } else { unsetAndCleanup('$pending', validationErrorKey, controller); } if (!isBoolean(state)) { unset(ctrl.$error, validationErrorKey, controller); unset(ctrl.$$success, validationErrorKey, controller); } else { if (state) { unset(ctrl.$error, validationErrorKey, controller); set(ctrl.$$success, validationErrorKey, controller); } else { set(ctrl.$error, validationErrorKey, controller); unset(ctrl.$$success, validationErrorKey, controller); } } if (ctrl.$pending) { cachedToggleClass(PENDING_CLASS, true); ctrl.$valid = ctrl.$invalid = undefined; toggleValidationCss('', null); } else { cachedToggleClass(PENDING_CLASS, false); ctrl.$valid = isObjectEmpty(ctrl.$error); ctrl.$invalid = !ctrl.$valid; toggleValidationCss('', ctrl.$valid); } // re-read the state as the set/unset methods could have // combined state in ctrl.$error[validationError] (used for forms), // where setting/unsetting only increments/decrements the value, // and does not replace it. var combinedState; if (ctrl.$pending && ctrl.$pending[validationErrorKey]) { combinedState = undefined; } else if (ctrl.$error[validationErrorKey]) { combinedState = false; } else if (ctrl.$$success[validationErrorKey]) { combinedState = true; } else { combinedState = null; } toggleValidationCss(validationErrorKey, combinedState); parentForm.$setValidity(validationErrorKey, combinedState, ctrl); } function createAndSet(name, value, controller) { if (!ctrl[name]) { ctrl[name] = {}; } set(ctrl[name], value, controller); } function unsetAndCleanup(name, value, controller) { if (ctrl[name]) { unset(ctrl[name], value, controller); } if (isObjectEmpty(ctrl[name])) { ctrl[name] = undefined; } } function cachedToggleClass(className, switchValue) { if (switchValue && !classCache[className]) { $animate.addClass($element, className); classCache[className] = true; } else if (!switchValue && classCache[className]) { $animate.removeClass($element, className); classCache[className] = false; } } function toggleValidationCss(validationErrorKey, isValid) { validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true); cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false); } } function isObjectEmpty(obj) { if (obj) { for (var prop in obj) { return false; } } return true; } /** * @ngdoc directive * @name ngNonBindable * @restrict AC * @priority 1000 * * @description * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current * DOM element. This is useful if the element contains what appears to be Angular directives and * bindings but which should be ignored by Angular. This could be the case if you have a site that * displays snippets of code, for instance. * * @element ANY * * @example * In this example there are two locations where a simple interpolation binding (`{{}}`) is present, * but the one wrapped in `ngNonBindable` is left alone. * * @example <example> <file name="index.html"> <div>Normal: {{1 + 2}}</div> <div ng-non-bindable>Ignored: {{1 + 2}}</div> </file> <file name="protractor.js" type="protractor"> it('should check ng-non-bindable', function() { expect(element(by.binding('1 + 2')).getText()).toContain('3'); expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/); }); </file> </example> */ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); /** * @ngdoc directive * @name ngPluralize * @restrict EA * * @description * `ngPluralize` is a directive that displays messages according to en-US localization rules. * These rules are bundled with angular.js, but can be overridden * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive * by specifying the mappings between * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html) * and the strings to be displayed. * * # Plural categories and explicit number rules * There are two * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html) * in Angular's default en-US locale: "one" and "other". * * While a plural category may match many numbers (for example, in en-US locale, "other" can match * any number that is not 1), an explicit number rule can only match one number. For example, the * explicit number rule for "3" matches the number 3. There are examples of plural categories * and explicit number rules throughout the rest of this documentation. * * # Configuring ngPluralize * You configure ngPluralize by providing 2 attributes: `count` and `when`. * You can also provide an optional attribute, `offset`. * * The value of the `count` attribute can be either a string or an {@link guide/expression * Angular expression}; these are evaluated on the current scope for its bound value. * * The `when` attribute specifies the mappings between plural categories and the actual * string to be displayed. The value of the attribute should be a JSON object. * * The following example shows how to configure ngPluralize: * * ```html * <ng-pluralize count="personCount" when="{'0': 'Nobody is viewing.', * 'one': '1 person is viewing.', * 'other': '{} people are viewing.'}"> * </ng-pluralize> *``` * * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not * specify this rule, 0 would be matched to the "other" category and "0 people are viewing" * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for * other numbers, for example 12, so that instead of showing "12 people are viewing", you can * show "a dozen people are viewing". * * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted * into pluralized strings. In the previous example, Angular will replace `{}` with * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder * for <span ng-non-bindable>{{numberExpression}}</span>. * * # Configuring ngPluralize with offset * The `offset` attribute allows further customization of pluralized text, which can result in * a better user experience. For example, instead of the message "4 people are viewing this document", * you might display "John, Kate and 2 others are viewing this document". * The offset attribute allows you to offset a number by any desired value. * Let's take a look at an example: * * ```html * <ng-pluralize count="personCount" offset=2 * when="{'0': 'Nobody is viewing.', * '1': '{{person1}} is viewing.', * '2': '{{person1}} and {{person2}} are viewing.', * 'one': '{{person1}}, {{person2}} and one other person are viewing.', * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> * </ng-pluralize> * ``` * * Notice that we are still using two plural categories(one, other), but we added * three explicit number rules 0, 1 and 2. * When one person, perhaps John, views the document, "John is viewing" will be shown. * When three people view the document, no explicit number rule is found, so * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing" * is shown. * * Note that when you specify offsets, you must provide explicit number rules for * numbers from 0 up to and including the offset. If you use an offset of 3, for example, * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for * plural categories "one" and "other". * * @param {string|expression} count The variable to be bound to. * @param {string} when The mapping between plural category to its corresponding strings. * @param {number=} offset Offset to deduct from the total number. * * @example <example module="pluralizeExample"> <file name="index.html"> <script> angular.module('pluralizeExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.person1 = 'Igor'; $scope.person2 = 'Misko'; $scope.personCount = 1; }]); </script> <div ng-controller="ExampleController"> Person 1:<input type="text" ng-model="person1" value="Igor" /><br/> Person 2:<input type="text" ng-model="person2" value="Misko" /><br/> Number of People:<input type="text" ng-model="personCount" value="1" /><br/> <!--- Example with simple pluralization rules for en locale ---> Without Offset: <ng-pluralize count="personCount" when="{'0': 'Nobody is viewing.', 'one': '1 person is viewing.', 'other': '{} people are viewing.'}"> </ng-pluralize><br> <!--- Example with offset ---> With Offset(2): <ng-pluralize count="personCount" offset=2 when="{'0': 'Nobody is viewing.', '1': '{{person1}} is viewing.', '2': '{{person1}} and {{person2}} are viewing.', 'one': '{{person1}}, {{person2}} and one other person are viewing.', 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> </ng-pluralize> </div> </file> <file name="protractor.js" type="protractor"> it('should show correct pluralized string', function() { var withoutOffset = element.all(by.css('ng-pluralize')).get(0); var withOffset = element.all(by.css('ng-pluralize')).get(1); var countInput = element(by.model('personCount')); expect(withoutOffset.getText()).toEqual('1 person is viewing.'); expect(withOffset.getText()).toEqual('Igor is viewing.'); countInput.clear(); countInput.sendKeys('0'); expect(withoutOffset.getText()).toEqual('Nobody is viewing.'); expect(withOffset.getText()).toEqual('Nobody is viewing.'); countInput.clear(); countInput.sendKeys('2'); expect(withoutOffset.getText()).toEqual('2 people are viewing.'); expect(withOffset.getText()).toEqual('Igor and Misko are viewing.'); countInput.clear(); countInput.sendKeys('3'); expect(withoutOffset.getText()).toEqual('3 people are viewing.'); expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.'); countInput.clear(); countInput.sendKeys('4'); expect(withoutOffset.getText()).toEqual('4 people are viewing.'); expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.'); }); it('should show data-bound names', function() { var withOffset = element.all(by.css('ng-pluralize')).get(1); var personCount = element(by.model('personCount')); var person1 = element(by.model('person1')); var person2 = element(by.model('person2')); personCount.clear(); personCount.sendKeys('4'); person1.clear(); person1.sendKeys('Di'); person2.clear(); person2.sendKeys('Vojta'); expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.'); }); </file> </example> */ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) { var BRACE = /{}/g, IS_WHEN = /^when(Minus)?(.+)$/; return { restrict: 'EA', link: function(scope, element, attr) { var numberExp = attr.count, whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs offset = attr.offset || 0, whens = scope.$eval(whenExp) || {}, whensExpFns = {}, startSymbol = $interpolate.startSymbol(), endSymbol = $interpolate.endSymbol(), braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol, watchRemover = angular.noop, lastCount; forEach(attr, function(expression, attributeName) { var tmpMatch = IS_WHEN.exec(attributeName); if (tmpMatch) { var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]); whens[whenKey] = element.attr(attr.$attr[attributeName]); } }); forEach(whens, function(expression, key) { whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement)); }); scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) { var count = parseFloat(newVal); var countIsNaN = isNaN(count); if (!countIsNaN && !(count in whens)) { // If an explicit number rule such as 1, 2, 3... is defined, just use it. // Otherwise, check it against pluralization rules in $locale service. count = $locale.pluralCat(count - offset); } // If both `count` and `lastCount` are NaN, we don't need to re-register a watch. // In JS `NaN !== NaN`, so we have to exlicitly check. if ((count !== lastCount) && !(countIsNaN && isNaN(lastCount))) { watchRemover(); watchRemover = scope.$watch(whensExpFns[count], updateElementText); lastCount = count; } }); function updateElementText(newText) { element.text(newText || ''); } } }; }]; /** * @ngdoc directive * @name ngRepeat * * @description * The `ngRepeat` directive instantiates a template once per item from a collection. Each template * instance gets its own scope, where the given loop variable is set to the current collection item, * and `$index` is set to the item index or key. * * Special properties are exposed on the local scope of each template instance, including: * * | Variable | Type | Details | * |-----------|-----------------|-----------------------------------------------------------------------------| * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) | * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. | * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. | * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. | * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). | * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). | * * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}. * This may be useful when, for instance, nesting ngRepeats. * * # Iterating over object properties * * It is possible to get `ngRepeat` to iterate over the properties of an object using the following * syntax: * * ```js * <div ng-repeat="(key, value) in myObj"> ... </div> * ``` * * You need to be aware that the JavaScript specification does not define what order * it will return the keys for an object. In order to have a guaranteed deterministic order * for the keys, Angular versions up to and including 1.3 **sort the keys alphabetically**. * * If this is not desired, the recommended workaround is to convert your object into an array * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter) * or implement a `$watch` on the object yourself. * * In version 1.4 we will remove the sorting, since it seems that browsers generally follow the * strategy of providing keys in the order in which they were defined, although there are exceptions * when keys are deleted and reinstated. * * * # Special repeat start and end points * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively. * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on) * up to and including the ending HTML tag where **ng-repeat-end** is placed. * * The example below makes use of this feature: * ```html * <header ng-repeat-start="item in items"> * Header {{ item }} * </header> * <div class="body"> * Body {{ item }} * </div> * <footer ng-repeat-end> * Footer {{ item }} * </footer> * ``` * * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to: * ```html * <header> * Header A * </header> * <div class="body"> * Body A * </div> * <footer> * Footer A * </footer> * <header> * Header B * </header> * <div class="body"> * Body B * </div> * <footer> * Footer B * </footer> * ``` * * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**). * * @animations * **.enter** - when a new item is added to the list or when an item is revealed after a filter * * **.leave** - when an item is removed from the list or when an item is filtered out * * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered * * @element ANY * @scope * @priority 1000 * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These * formats are currently supported: * * * `variable in expression` – where variable is the user defined loop variable and `expression` * is a scope expression giving the collection to enumerate. * * For example: `album in artist.albums`. * * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, * and `expression` is the scope expression giving the collection to enumerate. * * For example: `(name, age) in {'adam':10, 'amalie':12}`. * * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function * which can be used to associate the objects in the collection with the DOM elements. If no tracking function * is specified the ng-repeat associates elements by identity in the collection. It is an error to have * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression, * before specifying a tracking expression. * * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements * will be associated by item identity in the array. * * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements * with the corresponding item in the array by identity. Moving the same object in array would move the DOM * element in the same way in the DOM. * * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this * case the object identity does not matter. Two objects are considered equivalent as long as their `id` * property is same. * * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter * to items in conjunction with a tracking expression. * * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message * when a filter is active on the repeater, but the filtered result set is empty. * * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after * the items have been processed through the filter. * * @example * This example initializes the scope to a list of names and * then uses `ngRepeat` to display every person: <example module="ngAnimate" deps="angular-animate.js" animations="true"> <file name="index.html"> <div ng-init="friends = [ {name:'John', age:25, gender:'boy'}, {name:'Jessie', age:30, gender:'girl'}, {name:'Johanna', age:28, gender:'girl'}, {name:'Joy', age:15, gender:'girl'}, {name:'Mary', age:28, gender:'girl'}, {name:'Peter', age:95, gender:'boy'}, {name:'Sebastian', age:50, gender:'boy'}, {name:'Erika', age:27, gender:'girl'}, {name:'Patrick', age:40, gender:'boy'}, {name:'Samantha', age:60, gender:'girl'} ]"> I have {{friends.length}} friends. They are: <input type="search" ng-model="q" placeholder="filter friends..." /> <ul class="example-animate-container"> <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results"> [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. </li> <li class="animate-repeat" ng-if="results.length == 0"> <strong>No results found...</strong> </li> </ul> </div> </file> <file name="animations.css"> .example-animate-container { background:white; border:1px solid black; list-style:none; margin:0; padding:0 10px; } .animate-repeat { line-height:40px; list-style:none; box-sizing:border-box; } .animate-repeat.ng-move, .animate-repeat.ng-enter, .animate-repeat.ng-leave { -webkit-transition:all linear 0.5s; transition:all linear 0.5s; } .animate-repeat.ng-leave.ng-leave-active, .animate-repeat.ng-move, .animate-repeat.ng-enter { opacity:0; max-height:0; } .animate-repeat.ng-leave, .animate-repeat.ng-move.ng-move-active, .animate-repeat.ng-enter.ng-enter-active { opacity:1; max-height:40px; } </file> <file name="protractor.js" type="protractor"> var friends = element.all(by.repeater('friend in friends')); it('should render initial data set', function() { expect(friends.count()).toBe(10); expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.'); expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.'); expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.'); expect(element(by.binding('friends.length')).getText()) .toMatch("I have 10 friends. They are:"); }); it('should update repeater when filter predicate changes', function() { expect(friends.count()).toBe(10); element(by.model('q')).sendKeys('ma'); expect(friends.count()).toBe(2); expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.'); expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.'); }); </file> </example> */ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { var NG_REMOVED = '$$NG_REMOVED'; var ngRepeatMinErr = minErr('ngRepeat'); var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) { // TODO(perf): generate setters to shave off ~40ms or 1-1.5% scope[valueIdentifier] = value; if (keyIdentifier) scope[keyIdentifier] = key; scope.$index = index; scope.$first = (index === 0); scope.$last = (index === (arrayLength - 1)); scope.$middle = !(scope.$first || scope.$last); // jshint bitwise: false scope.$odd = !(scope.$even = (index&1) === 0); // jshint bitwise: true }; var getBlockStart = function(block) { return block.clone[0]; }; var getBlockEnd = function(block) { return block.clone[block.clone.length - 1]; }; return { restrict: 'A', multiElement: true, transclude: 'element', priority: 1000, terminal: true, $$tlb: true, compile: function ngRepeatCompile($element, $attr) { var expression = $attr.ngRepeat; var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' '); var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/); if (!match) { throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.", expression); } var lhs = match[1]; var rhs = match[2]; var aliasAs = match[3]; var trackByExp = match[4]; match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/); if (!match) { throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.", lhs); } var valueIdentifier = match[3] || match[1]; var keyIdentifier = match[2]; if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) || /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) { throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.", aliasAs); } var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn; var hashFnLocals = {$id: hashKey}; if (trackByExp) { trackByExpGetter = $parse(trackByExp); } else { trackByIdArrayFn = function(key, value) { return hashKey(value); }; trackByIdObjFn = function(key) { return key; }; } return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) { if (trackByExpGetter) { trackByIdExpFn = function(key, value, index) { // assign key, value, and $index to the locals so that they can be used in hash functions if (keyIdentifier) hashFnLocals[keyIdentifier] = key; hashFnLocals[valueIdentifier] = value; hashFnLocals.$index = index; return trackByExpGetter($scope, hashFnLocals); }; } // Store a list of elements from previous run. This is a hash where key is the item from the // iterator, and the value is objects with following properties. // - scope: bound scope // - element: previous element. // - index: position // // We are using no-proto object so that we don't need to guard against inherited props via // hasOwnProperty. var lastBlockMap = createMap(); //watch props $scope.$watchCollection(rhs, function ngRepeatAction(collection) { var index, length, previousNode = $element[0], // node that cloned nodes should be inserted after // initialized to the comment node anchor nextNode, // Same as lastBlockMap but it has the current state. It will become the // lastBlockMap on the next iteration. nextBlockMap = createMap(), collectionLength, key, value, // key/value of iteration trackById, trackByIdFn, collectionKeys, block, // last object information {scope, element, id} nextBlockOrder, elementsToRemove; if (aliasAs) { $scope[aliasAs] = collection; } if (isArrayLike(collection)) { collectionKeys = collection; trackByIdFn = trackByIdExpFn || trackByIdArrayFn; } else { trackByIdFn = trackByIdExpFn || trackByIdObjFn; // if object, extract keys, sort them and use to determine order of iteration over obj props collectionKeys = []; for (var itemKey in collection) { if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) != '$') { collectionKeys.push(itemKey); } } collectionKeys.sort(); } collectionLength = collectionKeys.length; nextBlockOrder = new Array(collectionLength); // locate existing items for (index = 0; index < collectionLength; index++) { key = (collection === collectionKeys) ? index : collectionKeys[index]; value = collection[key]; trackById = trackByIdFn(key, value, index); if (lastBlockMap[trackById]) { // found previously seen block block = lastBlockMap[trackById]; delete lastBlockMap[trackById]; nextBlockMap[trackById] = block; nextBlockOrder[index] = block; } else if (nextBlockMap[trackById]) { // if collision detected. restore lastBlockMap and throw an error forEach(nextBlockOrder, function(block) { if (block && block.scope) lastBlockMap[block.id] = block; }); throw ngRepeatMinErr('dupes', "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}", expression, trackById, value); } else { // new never before seen block nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined}; nextBlockMap[trackById] = true; } } // remove leftover items for (var blockKey in lastBlockMap) { block = lastBlockMap[blockKey]; elementsToRemove = getBlockNodes(block.clone); $animate.leave(elementsToRemove); if (elementsToRemove[0].parentNode) { // if the element was not removed yet because of pending animation, mark it as deleted // so that we can ignore it later for (index = 0, length = elementsToRemove.length; index < length; index++) { elementsToRemove[index][NG_REMOVED] = true; } } block.scope.$destroy(); } // we are not using forEach for perf reasons (trying to avoid #call) for (index = 0; index < collectionLength; index++) { key = (collection === collectionKeys) ? index : collectionKeys[index]; value = collection[key]; block = nextBlockOrder[index]; if (block.scope) { // if we have already seen this object, then we need to reuse the // associated scope/element nextNode = previousNode; // skip nodes that are already pending removal via leave animation do { nextNode = nextNode.nextSibling; } while (nextNode && nextNode[NG_REMOVED]); if (getBlockStart(block) != nextNode) { // existing item which got moved $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode)); } previousNode = getBlockEnd(block); updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength); } else { // new item which we don't know about $transclude(function ngRepeatTransclude(clone, scope) { block.scope = scope; // http://jsperf.com/clone-vs-createcomment var endNode = ngRepeatEndComment.cloneNode(false); clone[clone.length++] = endNode; // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper? $animate.enter(clone, null, jqLite(previousNode)); previousNode = endNode; // Note: We only need the first/last node of the cloned nodes. // However, we need to keep the reference to the jqlite wrapper as it might be changed later // by a directive with templateUrl when its template arrives. block.clone = clone; nextBlockMap[block.id] = block; updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength); }); } } lastBlockMap = nextBlockMap; }); }; } }; }]; var NG_HIDE_CLASS = 'ng-hide'; var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate'; /** * @ngdoc directive * @name ngShow * * @description * The `ngShow` directive shows or hides the given HTML element based on the expression * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined * in AngularJS and sets the display style to none (using an !important flag). * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). * * ```html * <!-- when $scope.myValue is truthy (element is visible) --> * <div ng-show="myValue"></div> * * <!-- when $scope.myValue is falsy (element is hidden) --> * <div ng-show="myValue" class="ng-hide"></div> * ``` * * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed * from the element causing the element not to appear hidden. * * ## Why is !important used? * * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector * can be easily overridden by heavier selectors. For example, something as simple * as changing the display style on a HTML list item would make hidden elements appear visible. * This also becomes a bigger issue when dealing with CSS frameworks. * * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. * * ### Overriding `.ng-hide` * * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide` * class in CSS: * * ```css * .ng-hide { * /&#42; this is just another form of hiding an element &#42;/ * display: block!important; * position: absolute; * top: -9999px; * left: -9999px; * } * ``` * * By default you don't need to override in CSS anything and the animations will work around the display style. * * ## A note about animations with `ngShow` * * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression * is true and false. This system works like the animation system present with ngClass except that * you must also include the !important flag to override the display property * so that you can perform an animation when the element is hidden during the time of the animation. * * ```css * // * //a working example can be found at the bottom of this page * // * .my-element.ng-hide-add, .my-element.ng-hide-remove { * /&#42; this is required as of 1.3x to properly * apply all styling in a show/hide animation &#42;/ * transition: 0s linear all; * } * * .my-element.ng-hide-add-active, * .my-element.ng-hide-remove-active { * /&#42; the transition is defined in the active class &#42;/ * transition: 1s linear all; * } * * .my-element.ng-hide-add { ... } * .my-element.ng-hide-add.ng-hide-add-active { ... } * .my-element.ng-hide-remove { ... } * .my-element.ng-hide-remove.ng-hide-remove-active { ... } * ``` * * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display * property to block during animation states--ngAnimate will handle the style toggling automatically for you. * * @animations * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden * * @element ANY * @param {expression} ngShow If the {@link guide/expression expression} is truthy * then the element is shown or hidden respectively. * * @example <example module="ngAnimate" deps="angular-animate.js" animations="true"> <file name="index.html"> Click me: <input type="checkbox" ng-model="checked"><br/> <div> Show: <div class="check-element animate-show" ng-show="checked"> <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked. </div> </div> <div> Hide: <div class="check-element animate-show" ng-hide="checked"> <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked. </div> </div> </file> <file name="glyphicons.css"> @import url(../../components/bootstrap-3.1.1/css/bootstrap.css); </file> <file name="animations.css"> .animate-show { line-height: 20px; opacity: 1; padding: 10px; border: 1px solid black; background: white; } .animate-show.ng-hide-add.ng-hide-add-active, .animate-show.ng-hide-remove.ng-hide-remove-active { -webkit-transition: all linear 0.5s; transition: all linear 0.5s; } .animate-show.ng-hide { line-height: 0; opacity: 0; padding: 0 10px; } .check-element { padding: 10px; border: 1px solid black; background: white; } </file> <file name="protractor.js" type="protractor"> var thumbsUp = element(by.css('span.glyphicon-thumbs-up')); var thumbsDown = element(by.css('span.glyphicon-thumbs-down')); it('should check ng-show / ng-hide', function() { expect(thumbsUp.isDisplayed()).toBeFalsy(); expect(thumbsDown.isDisplayed()).toBeTruthy(); element(by.model('checked')).click(); expect(thumbsUp.isDisplayed()).toBeTruthy(); expect(thumbsDown.isDisplayed()).toBeFalsy(); }); </file> </example> */ var ngShowDirective = ['$animate', function($animate) { return { restrict: 'A', multiElement: true, link: function(scope, element, attr) { scope.$watch(attr.ngShow, function ngShowWatchAction(value) { // we're adding a temporary, animation-specific class for ng-hide since this way // we can control when the element is actually displayed on screen without having // to have a global/greedy CSS selector that breaks when other animations are run. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845 $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, { tempClasses: NG_HIDE_IN_PROGRESS_CLASS }); }); } }; }]; /** * @ngdoc directive * @name ngHide * * @description * The `ngHide` directive shows or hides the given HTML element based on the expression * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined * in AngularJS and sets the display style to none (using an !important flag). * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). * * ```html * <!-- when $scope.myValue is truthy (element is hidden) --> * <div ng-hide="myValue" class="ng-hide"></div> * * <!-- when $scope.myValue is falsy (element is visible) --> * <div ng-hide="myValue"></div> * ``` * * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed * from the element causing the element not to appear hidden. * * ## Why is !important used? * * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector * can be easily overridden by heavier selectors. For example, something as simple * as changing the display style on a HTML list item would make hidden elements appear visible. * This also becomes a bigger issue when dealing with CSS frameworks. * * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. * * ### Overriding `.ng-hide` * * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide` * class in CSS: * * ```css * .ng-hide { * /&#42; this is just another form of hiding an element &#42;/ * display: block!important; * position: absolute; * top: -9999px; * left: -9999px; * } * ``` * * By default you don't need to override in CSS anything and the animations will work around the display style. * * ## A note about animations with `ngHide` * * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide` * CSS class is added and removed for you instead of your own CSS class. * * ```css * // * //a working example can be found at the bottom of this page * // * .my-element.ng-hide-add, .my-element.ng-hide-remove { * transition: 0.5s linear all; * } * * .my-element.ng-hide-add { ... } * .my-element.ng-hide-add.ng-hide-add-active { ... } * .my-element.ng-hide-remove { ... } * .my-element.ng-hide-remove.ng-hide-remove-active { ... } * ``` * * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display * property to block during animation states--ngAnimate will handle the style toggling automatically for you. * * @animations * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible * * @element ANY * @param {expression} ngHide If the {@link guide/expression expression} is truthy then * the element is shown or hidden respectively. * * @example <example module="ngAnimate" deps="angular-animate.js" animations="true"> <file name="index.html"> Click me: <input type="checkbox" ng-model="checked"><br/> <div> Show: <div class="check-element animate-hide" ng-show="checked"> <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked. </div> </div> <div> Hide: <div class="check-element animate-hide" ng-hide="checked"> <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked. </div> </div> </file> <file name="glyphicons.css"> @import url(../../components/bootstrap-3.1.1/css/bootstrap.css); </file> <file name="animations.css"> .animate-hide { -webkit-transition: all linear 0.5s; transition: all linear 0.5s; line-height: 20px; opacity: 1; padding: 10px; border: 1px solid black; background: white; } .animate-hide.ng-hide { line-height: 0; opacity: 0; padding: 0 10px; } .check-element { padding: 10px; border: 1px solid black; background: white; } </file> <file name="protractor.js" type="protractor"> var thumbsUp = element(by.css('span.glyphicon-thumbs-up')); var thumbsDown = element(by.css('span.glyphicon-thumbs-down')); it('should check ng-show / ng-hide', function() { expect(thumbsUp.isDisplayed()).toBeFalsy(); expect(thumbsDown.isDisplayed()).toBeTruthy(); element(by.model('checked')).click(); expect(thumbsUp.isDisplayed()).toBeTruthy(); expect(thumbsDown.isDisplayed()).toBeFalsy(); }); </file> </example> */ var ngHideDirective = ['$animate', function($animate) { return { restrict: 'A', multiElement: true, link: function(scope, element, attr) { scope.$watch(attr.ngHide, function ngHideWatchAction(value) { // The comment inside of the ngShowDirective explains why we add and // remove a temporary class for the show/hide animation $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, { tempClasses: NG_HIDE_IN_PROGRESS_CLASS }); }); } }; }]; /** * @ngdoc directive * @name ngStyle * @restrict AC * * @description * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally. * * @element ANY * @param {expression} ngStyle * * {@link guide/expression Expression} which evals to an * object whose keys are CSS style names and values are corresponding values for those CSS * keys. * * Since some CSS style names are not valid keys for an object, they must be quoted. * See the 'background-color' style in the example below. * * @example <example> <file name="index.html"> <input type="button" value="set color" ng-click="myStyle={color:'red'}"> <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}"> <input type="button" value="clear" ng-click="myStyle={}"> <br/> <span ng-style="myStyle">Sample Text</span> <pre>myStyle={{myStyle}}</pre> </file> <file name="style.css"> span { color: black; } </file> <file name="protractor.js" type="protractor"> var colorSpan = element(by.css('span')); it('should check ng-style', function() { expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)'); element(by.css('input[value=\'set color\']')).click(); expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)'); element(by.css('input[value=clear]')).click(); expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)'); }); </file> </example> */ var ngStyleDirective = ngDirective(function(scope, element, attr) { scope.$watchCollection(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) { if (oldStyles && (newStyles !== oldStyles)) { forEach(oldStyles, function(val, style) { element.css(style, '');}); } if (newStyles) element.css(newStyles); }); }); /** * @ngdoc directive * @name ngSwitch * @restrict EA * * @description * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location * as specified in the template. * * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element * matches the value obtained from the evaluated expression. In other words, you define a container element * (where you place the directive), place an expression on the **`on="..."` attribute** * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default * attribute is displayed. * * <div class="alert alert-info"> * Be aware that the attribute values to match against cannot be expressions. They are interpreted * as literal string values to match against. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the * value of the expression `$scope.someVal`. * </div> * @animations * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM * * @usage * * ``` * <ANY ng-switch="expression"> * <ANY ng-switch-when="matchValue1">...</ANY> * <ANY ng-switch-when="matchValue2">...</ANY> * <ANY ng-switch-default>...</ANY> * </ANY> * ``` * * * @scope * @priority 1200 * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>. * On child elements add: * * * `ngSwitchWhen`: the case statement to match against. If match then this * case will be displayed. If the same match appears multiple times, all the * elements will be displayed. * * `ngSwitchDefault`: the default case when no other case match. If there * are multiple default cases, all of them will be displayed when no other * case match. * * * @example <example module="switchExample" deps="angular-animate.js" animations="true"> <file name="index.html"> <div ng-controller="ExampleController"> <select ng-model="selection" ng-options="item for item in items"> </select> <tt>selection={{selection}}</tt> <hr/> <div class="animate-switch-container" ng-switch on="selection"> <div class="animate-switch" ng-switch-when="settings">Settings Div</div> <div class="animate-switch" ng-switch-when="home">Home Span</div> <div class="animate-switch" ng-switch-default>default</div> </div> </div> </file> <file name="script.js"> angular.module('switchExample', ['ngAnimate']) .controller('ExampleController', ['$scope', function($scope) { $scope.items = ['settings', 'home', 'other']; $scope.selection = $scope.items[0]; }]); </file> <file name="animations.css"> .animate-switch-container { position:relative; background:white; border:1px solid black; height:40px; overflow:hidden; } .animate-switch { padding:10px; } .animate-switch.ng-animate { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; position:absolute; top:0; left:0; right:0; bottom:0; } .animate-switch.ng-leave.ng-leave-active, .animate-switch.ng-enter { top:-50px; } .animate-switch.ng-leave, .animate-switch.ng-enter.ng-enter-active { top:0; } </file> <file name="protractor.js" type="protractor"> var switchElem = element(by.css('[ng-switch]')); var select = element(by.model('selection')); it('should start in settings', function() { expect(switchElem.getText()).toMatch(/Settings Div/); }); it('should change to home', function() { select.all(by.css('option')).get(1).click(); expect(switchElem.getText()).toMatch(/Home Span/); }); it('should select default', function() { select.all(by.css('option')).get(2).click(); expect(switchElem.getText()).toMatch(/default/); }); </file> </example> */ var ngSwitchDirective = ['$animate', function($animate) { return { restrict: 'EA', require: 'ngSwitch', // asks for $scope to fool the BC controller module controller: ['$scope', function ngSwitchController() { this.cases = {}; }], link: function(scope, element, attr, ngSwitchController) { var watchExpr = attr.ngSwitch || attr.on, selectedTranscludes = [], selectedElements = [], previousLeaveAnimations = [], selectedScopes = []; var spliceFactory = function(array, index) { return function() { array.splice(index, 1); }; }; scope.$watch(watchExpr, function ngSwitchWatchAction(value) { var i, ii; for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) { $animate.cancel(previousLeaveAnimations[i]); } previousLeaveAnimations.length = 0; for (i = 0, ii = selectedScopes.length; i < ii; ++i) { var selected = getBlockNodes(selectedElements[i].clone); selectedScopes[i].$destroy(); var promise = previousLeaveAnimations[i] = $animate.leave(selected); promise.then(spliceFactory(previousLeaveAnimations, i)); } selectedElements.length = 0; selectedScopes.length = 0; if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) { forEach(selectedTranscludes, function(selectedTransclude) { selectedTransclude.transclude(function(caseElement, selectedScope) { selectedScopes.push(selectedScope); var anchor = selectedTransclude.element; caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: '); var block = { clone: caseElement }; selectedElements.push(block); $animate.enter(caseElement, anchor.parent(), anchor); }); }); } }); } }; }]; var ngSwitchWhenDirective = ngDirective({ transclude: 'element', priority: 1200, require: '^ngSwitch', multiElement: true, link: function(scope, element, attrs, ctrl, $transclude) { ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []); ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element }); } }); var ngSwitchDefaultDirective = ngDirective({ transclude: 'element', priority: 1200, require: '^ngSwitch', multiElement: true, link: function(scope, element, attr, ctrl, $transclude) { ctrl.cases['?'] = (ctrl.cases['?'] || []); ctrl.cases['?'].push({ transclude: $transclude, element: element }); } }); /** * @ngdoc directive * @name ngTransclude * @restrict EAC * * @description * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion. * * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted. * * @element ANY * * @example <example module="transcludeExample"> <file name="index.html"> <script> angular.module('transcludeExample', []) .directive('pane', function(){ return { restrict: 'E', transclude: true, scope: { title:'@' }, template: '<div style="border: 1px solid black;">' + '<div style="background-color: gray">{{title}}</div>' + '<ng-transclude></ng-transclude>' + '</div>' }; }) .controller('ExampleController', ['$scope', function($scope) { $scope.title = 'Lorem Ipsum'; $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...'; }]); </script> <div ng-controller="ExampleController"> <input ng-model="title"> <br/> <textarea ng-model="text"></textarea> <br/> <pane title="{{title}}">{{text}}</pane> </div> </file> <file name="protractor.js" type="protractor"> it('should have transcluded', function() { var titleElement = element(by.model('title')); titleElement.clear(); titleElement.sendKeys('TITLE'); var textElement = element(by.model('text')); textElement.clear(); textElement.sendKeys('TEXT'); expect(element(by.binding('title')).getText()).toEqual('TITLE'); expect(element(by.binding('text')).getText()).toEqual('TEXT'); }); </file> </example> * */ var ngTranscludeDirective = ngDirective({ restrict: 'EAC', link: function($scope, $element, $attrs, controller, $transclude) { if (!$transclude) { throw minErr('ngTransclude')('orphan', 'Illegal use of ngTransclude directive in the template! ' + 'No parent directive that requires a transclusion found. ' + 'Element: {0}', startingTag($element)); } $transclude(function(clone) { $element.empty(); $element.append(clone); }); } }); /** * @ngdoc directive * @name script * @restrict E * * @description * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the * template can be used by {@link ng.directive:ngInclude `ngInclude`}, * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be * assigned through the element's `id`, which can then be used as a directive's `templateUrl`. * * @param {string} type Must be set to `'text/ng-template'`. * @param {string} id Cache name of the template. * * @example <example> <file name="index.html"> <script type="text/ng-template" id="/tpl.html"> Content of the template. </script> <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a> <div id="tpl-content" ng-include src="currentTpl"></div> </file> <file name="protractor.js" type="protractor"> it('should load template defined inside script tag', function() { element(by.css('#tpl-link')).click(); expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/); }); </file> </example> */ var scriptDirective = ['$templateCache', function($templateCache) { return { restrict: 'E', terminal: true, compile: function(element, attr) { if (attr.type == 'text/ng-template') { var templateUrl = attr.id, text = element[0].text; $templateCache.put(templateUrl, text); } } }; }]; var ngOptionsMinErr = minErr('ngOptions'); /** * @ngdoc directive * @name select * @restrict E * * @description * HTML `SELECT` element with angular data-binding. * * # `ngOptions` * * The `ngOptions` attribute can be used to dynamically generate a list of `<option>` * elements for the `<select>` element using the array or object obtained by evaluating the * `ngOptions` comprehension expression. * * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a * similar result. However, `ngOptions` provides some benefits such as reducing memory and * increasing speed by not creating a new scope for each repeated instance, as well as providing * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound * to a non-string value. This is because an option element can only be bound to string values at * present. * * When an item in the `<select>` menu is selected, the array element or object property * represented by the selected option will be bound to the model identified by the `ngModel` * directive. * * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can * be nested into the `<select>` element. This element will then represent the `null` or "not selected" * option. See example below for demonstration. * * <div class="alert alert-warning"> * **Note:** `ngModel` compares by reference, not value. This is important when binding to an * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/). * </div> * * ## `select` **`as`** * * Using `select` **`as`** will bind the result of the `select` expression to the model, but * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources) * or property name (for object data sources) of the value within the collection. If a **`track by`** expression * is used, the result of that expression will be set as the value of the `option` and `select` elements. * * * ### `select` **`as`** and **`track by`** * * <div class="alert alert-warning"> * Do not use `select` **`as`** and **`track by`** in the same expression. They are not designed to work together. * </div> * * Consider the following example: * * ```html * <select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected"> * ``` * * ```js * $scope.values = [{ * id: 1, * label: 'aLabel', * subItem: { name: 'aSubItem' } * }, { * id: 2, * label: 'bLabel', * subItem: { name: 'bSubItem' } * }]; * * $scope.selected = { name: 'aSubItem' }; * ``` * * With the purpose of preserving the selection, the **`track by`** expression is always applied to the element * of the data source (to `item` in this example). To calculate whether an element is selected, we do the * following: * * 1. Apply **`track by`** to the elements in the array. In the example: `[1, 2]` * 2. Apply **`track by`** to the already selected value in `ngModel`. * In the example: this is not possible as **`track by`** refers to `item.id`, but the selected * value from `ngModel` is `{name: 'aSubItem'}`, so the **`track by`** expression is applied to * a wrong object, the selected element can't be found, `<select>` is always reset to the "not * selected" option. * * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required The control is considered valid only if value is entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {comprehension_expression=} ngOptions in one of the following forms: * * * for array data sources: * * `label` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`for`** `value` **`in`** `array` * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr` * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr` * (for including a filter with `track by`) * * for object data sources: * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`group by`** `group` * **`for` `(`**`key`**`,`** `value`**`) in`** `object` * * Where: * * * `array` / `object`: an expression which evaluates to an array / object to iterate over. * * `value`: local variable which will refer to each item in the `array` or each property value * of `object` during iteration. * * `key`: local variable which will refer to a property name in `object` during iteration. * * `label`: The result of this expression will be the label for `<option>` element. The * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`). * * `select`: The result of this expression will be bound to the model of the parent `<select>` * element. If not specified, `select` expression will default to `value`. * * `group`: The result of this expression will be used to group options using the `<optgroup>` * DOM element. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be * used to identify the objects in the array. The `trackexpr` will most likely refer to the * `value` variable (e.g. `value.propertyName`). With this the selection is preserved * even when the options are recreated (e.g. reloaded from the server). * * @example <example module="selectExample"> <file name="index.html"> <script> angular.module('selectExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.colors = [ {name:'black', shade:'dark'}, {name:'white', shade:'light'}, {name:'red', shade:'dark'}, {name:'blue', shade:'dark'}, {name:'yellow', shade:'light'} ]; $scope.myColor = $scope.colors[2]; // red }]); </script> <div ng-controller="ExampleController"> <ul> <li ng-repeat="color in colors"> Name: <input ng-model="color.name"> [<a href ng-click="colors.splice($index, 1)">X</a>] </li> <li> [<a href ng-click="colors.push({})">add</a>] </li> </ul> <hr/> Color (null not allowed): <select ng-model="myColor" ng-options="color.name for color in colors"></select><br> Color (null allowed): <span class="nullable"> <select ng-model="myColor" ng-options="color.name for color in colors"> <option value="">-- choose color --</option> </select> </span><br/> Color grouped by shade: <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors"> </select><br/> Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br> <hr/> Currently selected: {{ {selected_color:myColor} }} <div style="border:solid 1px black; height:20px" ng-style="{'background-color':myColor.name}"> </div> </div> </file> <file name="protractor.js" type="protractor"> it('should check ng-options', function() { expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red'); element.all(by.model('myColor')).first().click(); element.all(by.css('select[ng-model="myColor"] option')).first().click(); expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black'); element(by.css('.nullable select[ng-model="myColor"]')).click(); element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click(); expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null'); }); </file> </example> */ var ngOptionsDirective = valueFn({ restrict: 'A', terminal: true }); // jshint maxlen: false var selectDirective = ['$compile', '$parse', function($compile, $parse) { //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888 var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/, nullModelCtrl = {$setViewValue: noop}; // jshint maxlen: 100 return { restrict: 'E', require: ['select', '?ngModel'], controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) { var self = this, optionsMap = {}, ngModelCtrl = nullModelCtrl, nullOption, unknownOption; self.databound = $attrs.ngModel; self.init = function(ngModelCtrl_, nullOption_, unknownOption_) { ngModelCtrl = ngModelCtrl_; nullOption = nullOption_; unknownOption = unknownOption_; }; self.addOption = function(value, element) { assertNotHasOwnProperty(value, '"option value"'); optionsMap[value] = true; if (ngModelCtrl.$viewValue == value) { $element.val(value); if (unknownOption.parent()) unknownOption.remove(); } // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459 // Adding an <option selected="selected"> element to a <select required="required"> should // automatically select the new element if (element && element[0].hasAttribute('selected')) { element[0].selected = true; } }; self.removeOption = function(value) { if (this.hasOption(value)) { delete optionsMap[value]; if (ngModelCtrl.$viewValue === value) { this.renderUnknownOption(value); } } }; self.renderUnknownOption = function(val) { var unknownVal = '? ' + hashKey(val) + ' ?'; unknownOption.val(unknownVal); $element.prepend(unknownOption); $element.val(unknownVal); unknownOption.prop('selected', true); // needed for IE }; self.hasOption = function(value) { return optionsMap.hasOwnProperty(value); }; $scope.$on('$destroy', function() { // disable unknown option so that we don't do work when the whole select is being destroyed self.renderUnknownOption = noop; }); }], link: function(scope, element, attr, ctrls) { // if ngModel is not defined, we don't need to do anything if (!ctrls[1]) return; var selectCtrl = ctrls[0], ngModelCtrl = ctrls[1], multiple = attr.multiple, optionsExp = attr.ngOptions, nullOption = false, // if false, user will not be able to select it (used by ngOptions) emptyOption, renderScheduled = false, // we can't just jqLite('<option>') since jqLite is not smart enough // to create it in <select> and IE barfs otherwise. optionTemplate = jqLite(document.createElement('option')), optGroupTemplate =jqLite(document.createElement('optgroup')), unknownOption = optionTemplate.clone(); // find "null" option for (var i = 0, children = element.children(), ii = children.length; i < ii; i++) { if (children[i].value === '') { emptyOption = nullOption = children.eq(i); break; } } selectCtrl.init(ngModelCtrl, nullOption, unknownOption); // required validator if (multiple) { ngModelCtrl.$isEmpty = function(value) { return !value || value.length === 0; }; } if (optionsExp) setupAsOptions(scope, element, ngModelCtrl); else if (multiple) setupAsMultiple(scope, element, ngModelCtrl); else setupAsSingle(scope, element, ngModelCtrl, selectCtrl); //////////////////////////// function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) { ngModelCtrl.$render = function() { var viewValue = ngModelCtrl.$viewValue; if (selectCtrl.hasOption(viewValue)) { if (unknownOption.parent()) unknownOption.remove(); selectElement.val(viewValue); if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy } else { if (isUndefined(viewValue) && emptyOption) { selectElement.val(''); } else { selectCtrl.renderUnknownOption(viewValue); } } }; selectElement.on('change', function() { scope.$apply(function() { if (unknownOption.parent()) unknownOption.remove(); ngModelCtrl.$setViewValue(selectElement.val()); }); }); } function setupAsMultiple(scope, selectElement, ctrl) { var lastView; ctrl.$render = function() { var items = new HashMap(ctrl.$viewValue); forEach(selectElement.find('option'), function(option) { option.selected = isDefined(items.get(option.value)); }); }; // we have to do it on each watch since ngModel watches reference, but // we need to work of an array, so we need to see if anything was inserted/removed scope.$watch(function selectMultipleWatch() { if (!equals(lastView, ctrl.$viewValue)) { lastView = shallowCopy(ctrl.$viewValue); ctrl.$render(); } }); selectElement.on('change', function() { scope.$apply(function() { var array = []; forEach(selectElement.find('option'), function(option) { if (option.selected) { array.push(option.value); } }); ctrl.$setViewValue(array); }); }); } function setupAsOptions(scope, selectElement, ctrl) { var match; if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) { throw ngOptionsMinErr('iexp', "Expected expression in form of " + "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" + " but got '{0}'. Element: {1}", optionsExp, startingTag(selectElement)); } var displayFn = $parse(match[2] || match[1]), valueName = match[4] || match[6], selectAs = / as /.test(match[0]) && match[1], selectAsFn = selectAs ? $parse(selectAs) : null, keyName = match[5], groupByFn = $parse(match[3] || ''), valueFn = $parse(match[2] ? match[1] : valueName), valuesFn = $parse(match[7]), track = match[8], trackFn = track ? $parse(match[8]) : null, trackKeysCache = {}, // This is an array of array of existing option groups in DOM. // We try to reuse these if possible // - optionGroupsCache[0] is the options with no option group // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element optionGroupsCache = [[{element: selectElement, label:''}]], //re-usable object to represent option's locals locals = {}; if (nullOption) { // compile the element since there might be bindings in it $compile(nullOption)(scope); // remove the class, which is added automatically because we recompile the element and it // becomes the compilation root nullOption.removeClass('ng-scope'); // we need to remove it before calling selectElement.empty() because otherwise IE will // remove the label from the element. wtf? nullOption.remove(); } // clear contents, we'll add what's needed based on the model selectElement.empty(); selectElement.on('change', selectionChanged); ctrl.$render = render; scope.$watchCollection(valuesFn, scheduleRendering); scope.$watchCollection(getLabels, scheduleRendering); if (multiple) { scope.$watchCollection(function() { return ctrl.$modelValue; }, scheduleRendering); } // ------------------------------------------------------------------ // function callExpression(exprFn, key, value) { locals[valueName] = value; if (keyName) locals[keyName] = key; return exprFn(scope, locals); } function selectionChanged() { scope.$apply(function() { var collection = valuesFn(scope) || []; var viewValue; if (multiple) { viewValue = []; forEach(selectElement.val(), function(selectedKey) { selectedKey = trackFn ? trackKeysCache[selectedKey] : selectedKey; viewValue.push(getViewValue(selectedKey, collection[selectedKey])); }); } else { var selectedKey = trackFn ? trackKeysCache[selectElement.val()] : selectElement.val(); viewValue = getViewValue(selectedKey, collection[selectedKey]); } ctrl.$setViewValue(viewValue); render(); }); } function getViewValue(key, value) { if (key === '?') { return undefined; } else if (key === '') { return null; } else { var viewValueFn = selectAsFn ? selectAsFn : valueFn; return callExpression(viewValueFn, key, value); } } function getLabels() { var values = valuesFn(scope); var toDisplay; if (values && isArray(values)) { toDisplay = new Array(values.length); for (var i = 0, ii = values.length; i < ii; i++) { toDisplay[i] = callExpression(displayFn, i, values[i]); } return toDisplay; } else if (values) { // TODO: Add a test for this case toDisplay = {}; for (var prop in values) { if (values.hasOwnProperty(prop)) { toDisplay[prop] = callExpression(displayFn, prop, values[prop]); } } } return toDisplay; } function createIsSelectedFn(viewValue) { var selectedSet; if (multiple) { if (trackFn && isArray(viewValue)) { selectedSet = new HashMap([]); for (var trackIndex = 0; trackIndex < viewValue.length; trackIndex++) { // tracking by key selectedSet.put(callExpression(trackFn, null, viewValue[trackIndex]), true); } } else { selectedSet = new HashMap(viewValue); } } else if (trackFn) { viewValue = callExpression(trackFn, null, viewValue); } return function isSelected(key, value) { var compareValueFn; if (trackFn) { compareValueFn = trackFn; } else if (selectAsFn) { compareValueFn = selectAsFn; } else { compareValueFn = valueFn; } if (multiple) { return isDefined(selectedSet.remove(callExpression(compareValueFn, key, value))); } else { return viewValue === callExpression(compareValueFn, key, value); } }; } function scheduleRendering() { if (!renderScheduled) { scope.$$postDigest(render); renderScheduled = true; } } /** * A new labelMap is created with each render. * This function is called for each existing option with added=false, * and each new option with added=true. * - Labels that are passed to this method twice, * (once with added=true and once with added=false) will end up with a value of 0, and * will cause no change to happen to the corresponding option. * - Labels that are passed to this method only once with added=false will end up with a * value of -1 and will eventually be passed to selectCtrl.removeOption() * - Labels that are passed to this method only once with added=true will end up with a * value of 1 and will eventually be passed to selectCtrl.addOption() */ function updateLabelMap(labelMap, label, added) { labelMap[label] = labelMap[label] || 0; labelMap[label] += (added ? 1 : -1); } function render() { renderScheduled = false; // Temporary location for the option groups before we render them var optionGroups = {'':[]}, optionGroupNames = [''], optionGroupName, optionGroup, option, existingParent, existingOptions, existingOption, viewValue = ctrl.$viewValue, values = valuesFn(scope) || [], keys = keyName ? sortedKeys(values) : values, key, value, groupLength, length, groupIndex, index, labelMap = {}, selected, isSelected = createIsSelectedFn(viewValue), anySelected = false, lastElement, element, label, optionId; trackKeysCache = {}; // We now build up the list of options we need (we merge later) for (index = 0; length = keys.length, index < length; index++) { key = index; if (keyName) { key = keys[index]; if (key.charAt(0) === '$') continue; } value = values[key]; optionGroupName = callExpression(groupByFn, key, value) || ''; if (!(optionGroup = optionGroups[optionGroupName])) { optionGroup = optionGroups[optionGroupName] = []; optionGroupNames.push(optionGroupName); } selected = isSelected(key, value); anySelected = anySelected || selected; label = callExpression(displayFn, key, value); // what will be seen by the user // doing displayFn(scope, locals) || '' overwrites zero values label = isDefined(label) ? label : ''; optionId = trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index); if (trackFn) { trackKeysCache[optionId] = key; } optionGroup.push({ // either the index into array or key from object id: optionId, label: label, selected: selected // determine if we should be selected }); } if (!multiple) { if (nullOption || viewValue === null) { // insert null option if we have a placeholder, or the model is null optionGroups[''].unshift({id:'', label:'', selected:!anySelected}); } else if (!anySelected) { // option could not be found, we have to insert the undefined item optionGroups[''].unshift({id:'?', label:'', selected:true}); } } // Now we need to update the list of DOM nodes to match the optionGroups we computed above for (groupIndex = 0, groupLength = optionGroupNames.length; groupIndex < groupLength; groupIndex++) { // current option group name or '' if no group optionGroupName = optionGroupNames[groupIndex]; // list of options for that group. (first item has the parent) optionGroup = optionGroups[optionGroupName]; if (optionGroupsCache.length <= groupIndex) { // we need to grow the optionGroups existingParent = { element: optGroupTemplate.clone().attr('label', optionGroupName), label: optionGroup.label }; existingOptions = [existingParent]; optionGroupsCache.push(existingOptions); selectElement.append(existingParent.element); } else { existingOptions = optionGroupsCache[groupIndex]; existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element // update the OPTGROUP label if not the same. if (existingParent.label != optionGroupName) { existingParent.element.attr('label', existingParent.label = optionGroupName); } } lastElement = null; // start at the beginning for (index = 0, length = optionGroup.length; index < length; index++) { option = optionGroup[index]; if ((existingOption = existingOptions[index + 1])) { // reuse elements lastElement = existingOption.element; if (existingOption.label !== option.label) { updateLabelMap(labelMap, existingOption.label, false); updateLabelMap(labelMap, option.label, true); lastElement.text(existingOption.label = option.label); lastElement.prop('label', existingOption.label); } if (existingOption.id !== option.id) { lastElement.val(existingOption.id = option.id); } // lastElement.prop('selected') provided by jQuery has side-effects if (lastElement[0].selected !== option.selected) { lastElement.prop('selected', (existingOption.selected = option.selected)); if (msie) { // See #7692 // The selected item wouldn't visually update on IE without this. // Tested on Win7: IE9, IE10 and IE11. Future IEs should be tested as well lastElement.prop('selected', existingOption.selected); } } } else { // grow elements // if it's a null option if (option.id === '' && nullOption) { // put back the pre-compiled element element = nullOption; } else { // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but // in this version of jQuery on some browser the .text() returns a string // rather then the element. (element = optionTemplate.clone()) .val(option.id) .prop('selected', option.selected) .attr('selected', option.selected) .prop('label', option.label) .text(option.label); } existingOptions.push(existingOption = { element: element, label: option.label, id: option.id, selected: option.selected }); updateLabelMap(labelMap, option.label, true); if (lastElement) { lastElement.after(element); } else { existingParent.element.append(element); } lastElement = element; } } // remove any excessive OPTIONs in a group index++; // increment since the existingOptions[0] is parent element not OPTION while (existingOptions.length > index) { option = existingOptions.pop(); updateLabelMap(labelMap, option.label, false); option.element.remove(); } } // remove any excessive OPTGROUPs from select while (optionGroupsCache.length > groupIndex) { // remove all the labels in the option group optionGroup = optionGroupsCache.pop(); for (index = 1; index < optionGroup.length; ++index) { updateLabelMap(labelMap, optionGroup[index].label, false); } optionGroup[0].element.remove(); } forEach(labelMap, function(count, label) { if (count > 0) { selectCtrl.addOption(label); } else if (count < 0) { selectCtrl.removeOption(label); } }); } } } }; }]; var optionDirective = ['$interpolate', function($interpolate) { var nullSelectCtrl = { addOption: noop, removeOption: noop }; return { restrict: 'E', priority: 100, compile: function(element, attr) { if (isUndefined(attr.value)) { var interpolateFn = $interpolate(element.text(), true); if (!interpolateFn) { attr.$set('value', element.text()); } } return function(scope, element, attr) { var selectCtrlName = '$selectController', parent = element.parent(), selectCtrl = parent.data(selectCtrlName) || parent.parent().data(selectCtrlName); // in case we are in optgroup if (!selectCtrl || !selectCtrl.databound) { selectCtrl = nullSelectCtrl; } if (interpolateFn) { scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) { attr.$set('value', newVal); if (oldVal !== newVal) { selectCtrl.removeOption(oldVal); } selectCtrl.addOption(newVal, element); }); } else { selectCtrl.addOption(attr.value, element); } element.on('$destroy', function() { selectCtrl.removeOption(attr.value); }); }; } }; }]; var styleDirective = valueFn({ restrict: 'E', terminal: false }); var requiredDirective = function() { return { restrict: 'A', require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; attr.required = true; // force truthy in case we are on non input element ctrl.$validators.required = function(modelValue, viewValue) { return !attr.required || !ctrl.$isEmpty(viewValue); }; attr.$observe('required', function() { ctrl.$validate(); }); } }; }; var patternDirective = function() { return { restrict: 'A', require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; var regexp, patternExp = attr.ngPattern || attr.pattern; attr.$observe('pattern', function(regex) { if (isString(regex) && regex.length > 0) { regex = new RegExp('^' + regex + '$'); } if (regex && !regex.test) { throw minErr('ngPattern')('noregexp', 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp, regex, startingTag(elm)); } regexp = regex || undefined; ctrl.$validate(); }); ctrl.$validators.pattern = function(value) { return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value); }; } }; }; var maxlengthDirective = function() { return { restrict: 'A', require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; var maxlength = -1; attr.$observe('maxlength', function(value) { var intVal = int(value); maxlength = isNaN(intVal) ? -1 : intVal; ctrl.$validate(); }); ctrl.$validators.maxlength = function(modelValue, viewValue) { return (maxlength < 0) || ctrl.$isEmpty(modelValue) || (viewValue.length <= maxlength); }; } }; }; var minlengthDirective = function() { return { restrict: 'A', require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; var minlength = 0; attr.$observe('minlength', function(value) { minlength = int(value) || 0; ctrl.$validate(); }); ctrl.$validators.minlength = function(modelValue, viewValue) { return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength; }; } }; }; if (window.angular.bootstrap) { //AngularJS is already loaded, so we can return here... console.log('WARNING: Tried to load angular more than once.'); return; } //try to bind to jquery now so that one can write jqLite(document).ready() //but we will rebind on bootstrap again. bindJQuery(); publishExternalAPI(angular); jqLite(document).ready(function() { angularInit(document, bootstrap); }); })(window, document); !window.angular.$$csp() && window.angular.element(document).find('head').prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}</style>');
joseluisillana/api-restful-spring-jersey
erep-services/src/main/webapp/bower_components/angular/angular.js
JavaScript
gpl-2.0
952,168
/* firewall_rules_dlg.c * * $Id: firewall_dlg.c 49320 2013-05-15 22:03:14Z guy $ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* * Generate firewall ACL rules based on packet addresses and ports. * For directional rules, an outside interface is assumed. * * There may be better ways to present the information, e.g. all rules * in one huge text window, or some sort of tree view. */ /* * To add a new product, add syntax functions modify the products[] array. * * To add a new syntax function, add its prototype above the products[] * array, and add the function below with all the others. */ /* Copied from ssl-dlg.c */ #include "config.h" #include <stdio.h> #include <string.h> #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <gtk/gtk.h> #include <epan/packet.h> #include <epan/addr_resolv.h> #include <epan/epan_dissect.h> #include <epan/filesystem.h> #include <epan/dissectors/packet-ipv6.h> #include <ui/alert_box.h> #include <ui/last_open_dir.h> #include <wsutil/file_util.h> #include "ui/gtk/main.h" #include "ui/gtk/dlg_utils.h" #include "ui/gtk/file_dlg.h" #include "ui/gtk/help_dlg.h" #include "ui/gtk/gui_utils.h" #include "ui/gtk/old-gtk-compat.h" #include "ui/gtk/firewall_dlg.h" #define MAX_RULE_LEN 200 /* Rule types */ typedef enum { RT_NONE, RT_MAC_SRC, RT_MAC_DST, RT_IPv4_SRC, RT_IPv4_DST, RT_PORT_SRC, RT_PORT_DST, RT_IPv4_PORT_SRC, RT_IPv4_PORT_DST, NUM_RULE_TYPES } rule_type_t; /* Copied from packet_info struct */ typedef struct _rule_info_t { gint product; address dl_src; address dl_dst; address net_src; address net_dst; port_type ptype; guint32 srcport; guint32 destport; GtkWidget *text; GtkWidget *filter_combo_box; GtkWidget *deny_cb; GtkWidget *inbound_cb; gboolean inbound; gboolean deny; rule_type_t rule_type; } rule_info_t; /* Syntax function prototypes */ typedef void (*syntax_func)(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); static void sf_dummy(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); static void sf_ipfw_mac(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); static void sf_netfilter_mac(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); static void sf_ios_std_ipv4(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); static void sf_ios_ext_ipv4(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); static void sf_ipfilter_ipv4(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); static void sf_ipfw_ipv4(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); static void sf_netfilter_ipv4(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); static void sf_pf_ipv4(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); /* XXX - Can you addresses-only filters using WFW/netsh? */ static void sf_ios_ext_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); static void sf_ipfilter_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); static void sf_ipfw_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); static void sf_netfilter_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); static void sf_pf_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); static void sf_netsh_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); static void sf_ios_ext_ipv4_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); static void sf_ipfilter_ipv4_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); static void sf_ipfw_ipv4_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); static void sf_netfilter_ipv4_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); static void sf_pf_ipv4_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); static void sf_netsh_ipv4_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny); typedef struct _fw_product_t { const gchar *name; const gchar *comment_pfx; syntax_func mac_func; syntax_func ipv4_func; syntax_func port_func; syntax_func ipv4_port_func; gboolean does_inbound; } fw_product; static fw_product products[] = { { "Cisco IOS (standard)", "!", NULL, sf_ios_std_ipv4, NULL, NULL, FALSE }, { "Cisco IOS (extended)", "!", NULL, sf_ios_ext_ipv4, sf_ios_ext_port, sf_ios_ext_ipv4_port, TRUE }, { "IP Filter (ipfilter)", "#", NULL, sf_ipfilter_ipv4, sf_ipfilter_port, sf_ipfilter_ipv4_port, TRUE }, { "IPFirewall (ipfw)", "#", sf_ipfw_mac, sf_ipfw_ipv4, sf_ipfw_port, sf_ipfw_ipv4_port, TRUE }, { "Netfilter (iptables)", "#", sf_netfilter_mac, sf_netfilter_ipv4, sf_netfilter_port, sf_netfilter_ipv4_port, TRUE }, { "Packet Filter (pf)", "#", NULL, sf_pf_ipv4, sf_pf_port, sf_pf_ipv4_port, TRUE }, { "Windows Firewall (netsh)", "#", NULL, NULL, sf_netsh_port, sf_netsh_ipv4_port, FALSE } }; #define NUM_PRODS (sizeof(products) / sizeof(fw_product)) static void select_product(GtkWidget * win, gpointer data); static void select_filter(GtkWidget * win, gpointer data); static void toggle_inbound(GtkToggleButton *t, gpointer data); static void toggle_deny(GtkToggleButton *t, gpointer data); static void set_rule_text(rule_info_t *rule_info); static void firewall_destroy_cb(GtkWidget * win, gpointer data); static void firewall_copy_cmd_cb(GtkWidget * w, gpointer data); static void firewall_save_as_cmd_cb(GtkWidget * w, gpointer data); #define WS_RULE_INFO_KEY "rule_info_key" #if 0 /* List of "rule_info_t" structures for all rule windows. */ static GList *rule_infos; /* Remove a "rule_info_t" structure from the list. */ static void forget_rule_info(rule_info_t *rule_info) { rule_infos = g_list_remove(rule_infos, rule_info); } #endif void firewall_rule_cb(GtkWidget *w _U_, gpointer data _U_) { GtkWidget *rule_w, *vbox, *txt_scrollw, *text; GtkWidget *label, *product_combo_box; GtkWidget *hbox, *button_hbox, *button; rule_info_t *rule_info; packet_info *pinfo = &cfile.edt->pi; guint i; rule_info = g_new0(rule_info_t, 1); COPY_ADDRESS(&(rule_info->dl_src), &(pinfo->dl_src)); COPY_ADDRESS(&(rule_info->dl_dst), &(pinfo->dl_dst)); COPY_ADDRESS(&(rule_info->net_src), &(pinfo->net_src)); COPY_ADDRESS(&(rule_info->net_dst), &(pinfo->net_dst)); rule_info->ptype = pinfo->ptype; rule_info->srcport = pinfo->srcport; rule_info->destport = pinfo->destport; rule_info->inbound = TRUE; rule_info->deny = TRUE; rule_info->product = 0; rule_w = dlg_window_new("Firewall ACL Rules"); gtk_widget_set_name(rule_w, "Firewall ACL rule window"); gtk_container_set_border_width(GTK_CONTAINER(rule_w), 6); /* setup the container */ vbox = ws_gtk_box_new(GTK_ORIENTATION_VERTICAL, 6, FALSE); gtk_container_add(GTK_CONTAINER(rule_w), vbox); /* rule type selectors hbox */ hbox = ws_gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 1, FALSE); gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0); /* product selector */ label = gtk_label_new("Product"); gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0); product_combo_box = gtk_combo_box_text_new(); for (i = 0; i < NUM_PRODS; i++) { gtk_combo_box_text_append_text (GTK_COMBO_BOX_TEXT(product_combo_box), products[i].name); } g_object_set_data(G_OBJECT(product_combo_box), WS_RULE_INFO_KEY, rule_info); g_signal_connect(product_combo_box, "changed", G_CALLBACK(select_product), NULL); gtk_box_pack_start(GTK_BOX(hbox), product_combo_box, FALSE, FALSE, 5); /* type selector */ label = gtk_label_new("Filter"); gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 10); rule_info->filter_combo_box = ws_combo_box_new_text_and_pointer(); g_object_set_data(G_OBJECT(rule_info->filter_combo_box), WS_RULE_INFO_KEY, rule_info); \ g_signal_connect(rule_info->filter_combo_box, "changed", G_CALLBACK(select_filter), NULL); gtk_box_pack_start(GTK_BOX(hbox), rule_info->filter_combo_box, FALSE, FALSE, 5); /* inbound selector */ rule_info->inbound_cb = gtk_check_button_new_with_label("Inbound"); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(rule_info->inbound_cb), rule_info->inbound); gtk_box_pack_start(GTK_BOX(hbox), rule_info->inbound_cb, FALSE, FALSE, 10); g_signal_connect(rule_info->inbound_cb, "toggled", G_CALLBACK(toggle_inbound), rule_info); /* deny selector */ rule_info->deny_cb = gtk_check_button_new_with_label("Deny"); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(rule_info->deny_cb), rule_info->deny); gtk_box_pack_start(GTK_BOX(hbox), rule_info->deny_cb, FALSE, FALSE, 10); g_signal_connect(rule_info->deny_cb, "toggled", G_CALLBACK(toggle_deny), rule_info); /* create a scrolled window for the text */ txt_scrollw = scrolled_window_new(NULL, NULL); gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(txt_scrollw), GTK_SHADOW_IN); gtk_box_pack_start(GTK_BOX(vbox), txt_scrollw, TRUE, TRUE, 0); /* create a text box */ text = gtk_text_view_new(); gtk_text_view_set_editable(GTK_TEXT_VIEW(text), FALSE); gtk_container_add(GTK_CONTAINER(txt_scrollw), text); rule_info->text = text; /* Button row */ button_hbox = dlg_button_row_new(GTK_STOCK_HELP, GTK_STOCK_COPY, GTK_STOCK_SAVE, GTK_STOCK_CANCEL, NULL); gtk_box_pack_start(GTK_BOX(vbox), button_hbox, FALSE, FALSE, 0); /* Create Copy Button */ button = (GtkWidget *)g_object_get_data(G_OBJECT(button_hbox), GTK_STOCK_COPY); g_signal_connect(button, "clicked", G_CALLBACK(firewall_copy_cmd_cb), rule_info); gtk_widget_set_tooltip_text(button, "Copy rule to clipboard"); /* Create Save Button */ button = (GtkWidget *)g_object_get_data(G_OBJECT(button_hbox), GTK_STOCK_SAVE); g_signal_connect(button, "clicked", G_CALLBACK(firewall_save_as_cmd_cb), rule_info); gtk_widget_set_tooltip_text(button, "Save the rule as currently displayed"); button = (GtkWidget *)g_object_get_data(G_OBJECT(button_hbox), GTK_STOCK_CANCEL); gtk_widget_set_tooltip_text(button, "Cancel the dialog"); window_set_cancel_button(rule_w, button, window_cancel_button_cb); button = (GtkWidget *)g_object_get_data(G_OBJECT(button_hbox), GTK_STOCK_HELP); g_signal_connect(button, "clicked", G_CALLBACK(topic_cb), (gpointer)HELP_FIREWALL_DIALOG); /* Tuck away the rule_info object into the window */ g_object_set_data(G_OBJECT(rule_w), WS_RULE_INFO_KEY, rule_info); g_signal_connect(rule_w, "delete_event", G_CALLBACK(window_delete_event_cb), NULL); g_signal_connect(rule_w, "destroy", G_CALLBACK(firewall_destroy_cb), NULL); /* Make sure this widget gets destroyed if we quit the main loop, so that if we exit, we clean up any temporary files we have for "Follow SSL Stream" windows. gtk_quit_add_destroy is deprecated and should not be used in newly-written code. This function is going to be removed in GTK+ 3.0 gtk_quit_add_destroy(gtk_main_level(), GTK_OBJECT(rule_w)); */ gtk_combo_box_set_active(GTK_COMBO_BOX(product_combo_box), 0); /* invokes select_product callback */ gtk_widget_show_all(rule_w); window_present(rule_w); } /* Set the current product. */ #define ADD_TO_FILTER_MENU(rt) \ ws_combo_box_append_text_and_pointer(GTK_COMBO_BOX(rule_info->filter_combo_box), name, GUINT_TO_POINTER(rt)); \ if (rule_type == RT_NONE) { \ rule_type = rt; \ } #define NAME_TCP_UDP (rule_info->ptype == PT_TCP ? "TCP" : "UDP") static void select_product(GtkWidget *w, gpointer data _U_) { guint prod = gtk_combo_box_get_active(GTK_COMBO_BOX(w)); rule_info_t *rule_info; gchar name[MAX_RULE_LEN], addr_str[MAX_RULE_LEN]; address *addr; rule_type_t rule_type = RT_NONE; gboolean sensitive = FALSE; rule_info =(rule_info_t *)g_object_get_data(G_OBJECT(w), WS_RULE_INFO_KEY); if (prod >= NUM_PRODS || !rule_info) return; rule_info->product = prod; /* Clear the list store (ie: the como_box list items) */ ws_combo_box_clear_text_and_pointer(GTK_COMBO_BOX(rule_info->filter_combo_box)); /* Fill in valid combo_box list items (in the list store). */ if (products[prod].mac_func && rule_info->dl_src.type == AT_ETHER) { addr = &(rule_info->dl_src); address_to_str_buf(addr, name, MAX_RULE_LEN); ADD_TO_FILTER_MENU(RT_MAC_SRC); addr = &(rule_info->dl_dst); address_to_str_buf(addr, name, MAX_RULE_LEN); ADD_TO_FILTER_MENU(RT_MAC_DST); } if (products[prod].ipv4_func && rule_info->net_src.type == AT_IPv4) { addr = &(rule_info->net_src); address_to_str_buf(addr, name, MAX_RULE_LEN); ADD_TO_FILTER_MENU(RT_IPv4_SRC); addr = &(rule_info->net_dst); address_to_str_buf(addr, name, MAX_RULE_LEN); ADD_TO_FILTER_MENU(RT_IPv4_DST); } if (products[prod].port_func && (rule_info->ptype == PT_TCP || rule_info->ptype == PT_UDP)) { g_snprintf(name, MAX_RULE_LEN, "%s port %u", NAME_TCP_UDP, rule_info->srcport); ADD_TO_FILTER_MENU(RT_PORT_SRC); if (rule_info->srcport != rule_info->destport) { g_snprintf(name, MAX_RULE_LEN, "%s port %u", NAME_TCP_UDP, rule_info->destport); ADD_TO_FILTER_MENU(RT_PORT_DST); } } if (products[prod].ipv4_port_func && rule_info->net_src.type == AT_IPv4 && (rule_info->ptype == PT_TCP || rule_info->ptype == PT_UDP)) { addr = &(rule_info->net_src); address_to_str_buf(addr, addr_str, MAX_RULE_LEN); g_snprintf(name, MAX_RULE_LEN, "%s + %s port %u", addr_str, NAME_TCP_UDP, rule_info->srcport); ADD_TO_FILTER_MENU(RT_IPv4_PORT_SRC); addr = &(rule_info->net_dst); address_to_str_buf(addr, addr_str, MAX_RULE_LEN); g_snprintf(name, MAX_RULE_LEN, "%s + %s port %u", addr_str, NAME_TCP_UDP, rule_info->destport); ADD_TO_FILTER_MENU(RT_IPv4_PORT_DST); } if (rule_type != RT_NONE) { gtk_combo_box_set_active(GTK_COMBO_BOX(rule_info->filter_combo_box), 0); /* invokes select_filter callback */ sensitive = TRUE; } else { select_filter(rule_info->filter_combo_box, NULL); /* Call if RT_NONE [with nothing selected] */ } gtk_widget_set_sensitive(rule_info->filter_combo_box, sensitive); gtk_widget_set_sensitive(rule_info->inbound_cb, products[prod].does_inbound && sensitive); gtk_widget_set_sensitive(rule_info->deny_cb, sensitive); } /* Set the rule text based upon the current product and current filter. */ static void select_filter(GtkWidget *w, gpointer data _U_) { rule_type_t cur_type; rule_info_t *rule_info; gpointer ptr; rule_info = (rule_info_t *)g_object_get_data(G_OBJECT(w), WS_RULE_INFO_KEY); if (!rule_info) return; if (ws_combo_box_get_active_pointer(GTK_COMBO_BOX(w), &ptr)) cur_type = (rule_type_t)GPOINTER_TO_UINT(ptr); else cur_type = RT_NONE; /* If nothing selected (eg: nothing in filter list) */ if (cur_type >= NUM_RULE_TYPES) return; rule_info->rule_type = cur_type; set_rule_text(rule_info); } /* Set inbound/outbound */ static void toggle_inbound(GtkToggleButton *t, gpointer data) { rule_info_t *rule_info = (rule_info_t *) data; rule_info->inbound = gtk_toggle_button_get_active(t); set_rule_text(rule_info); } /* Set deny/allow. */ static void toggle_deny(GtkToggleButton *t, gpointer data) { rule_info_t *rule_info = (rule_info_t *) data; rule_info->deny = gtk_toggle_button_get_active(t); set_rule_text(rule_info); } /* Set the rule text */ #define DL_ADDR (rt == RT_MAC_SRC ? &(rule_info->dl_src) : &(rule_info->dl_dst)) #define NET_ADDR (rt == RT_IPv4_SRC ? &(rule_info->net_src) : &(rule_info->net_dst)) #define NET_PORT (rt == RT_PORT_SRC ? rule_info->srcport : rule_info->destport) static void set_rule_text(rule_info_t *rule_info) { GString *rtxt = g_string_new(""); gchar addr_str[MAX_RULE_LEN]; rule_type_t rt = rule_info->rule_type; guint prod = rule_info->product; address *addr = NULL; guint32 port = 0; syntax_func rt_func = NULL; GtkTextBuffer *buf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(rule_info->text)); if (prod < NUM_PRODS) { g_string_printf(rtxt, "%s %s\n", products[prod].comment_pfx, products[prod].name); switch(rt) { case RT_NONE: g_string_append_printf(rtxt, "%s Not supported", products[prod].comment_pfx); rt_func = sf_dummy; break; case RT_MAC_SRC: case RT_MAC_DST: addr = DL_ADDR; address_to_str_buf(addr, addr_str, MAX_RULE_LEN); rt_func = products[prod].mac_func; break; case RT_IPv4_SRC: case RT_IPv4_DST: addr = NET_ADDR; address_to_str_buf(addr, addr_str, MAX_RULE_LEN); rt_func = products[prod].ipv4_func; break; case RT_PORT_SRC: case RT_PORT_DST: port = NET_PORT; rt_func = products[prod].port_func; break; case RT_IPv4_PORT_SRC: case RT_IPv4_PORT_DST: addr = NET_ADDR; address_to_str_buf(addr, addr_str, MAX_RULE_LEN); port = NET_PORT; rt_func = products[prod].ipv4_port_func; break; default: break; } } if (rt_func) { rt_func(rtxt, addr_str, port, rule_info->ptype, rule_info->inbound, rule_info->deny); } else { g_string_append_printf(rtxt, "ERROR: Unable to create rule"); } gtk_text_buffer_set_text(buf, rtxt->str, (gint) rtxt->len); g_string_free(rtxt, TRUE); } /* Rule text functions */ /* Dummy */ static void sf_dummy(GString *rtxt _U_, gchar *addr _U_, guint32 port _U_, port_type ptype _U_, gboolean inbound _U_, gboolean deny _U_) { } /* MAC */ #define IPFW_DENY (deny ? "deny" : "allow") #define IPFW_IN (inbound ? "in" : "out") static void sf_ipfw_mac(GString *rtxt, gchar *addr, guint32 port _U_, port_type ptype _U_, gboolean inbound, gboolean deny) { g_string_append_printf(rtxt, "add %s MAC %s any %s", IPFW_DENY, addr, IPFW_IN); } #define NF_DROP (deny ? "DROP" : "ACCEPT") #define NF_INPUT (inbound ? "INPUT" : "OUTPUT") static void sf_netfilter_mac(GString *rtxt, gchar *addr, guint32 port _U_, port_type ptype _U_, gboolean inbound, gboolean deny) { g_string_append_printf(rtxt, "iptables -A %s --mac-source %s -j %s", NF_INPUT, addr, NF_DROP); } /* IPv4 */ #define IOS_DENY (deny ? "deny" : "permit") static void sf_ios_std_ipv4(GString *rtxt, gchar *addr, guint32 port _U_, port_type ptype _U_, gboolean inbound _U_, gboolean deny) { g_string_append_printf(rtxt, "access-list NUMBER %s host %s", IOS_DENY, addr); } static void sf_ios_ext_ipv4(GString *rtxt, gchar *addr, guint32 port _U_, port_type ptype _U_, gboolean inbound, gboolean deny) { if (inbound) g_string_append_printf(rtxt, "access-list NUMBER %s ip host %s any", IOS_DENY, addr); else g_string_append_printf(rtxt, "access-list NUMBER %s ip any host %s", IOS_DENY, addr); } #define IPFILTER_DENY (deny ? "block" : "pass") #define IPFILTER_IN (inbound ? "in" : "out") static void sf_ipfilter_ipv4(GString *rtxt, gchar *addr, guint32 port _U_, port_type ptype _U_, gboolean inbound, gboolean deny) { g_string_append_printf(rtxt, "%s %s on le0 from %s to any", IPFILTER_DENY, IPFILTER_IN, addr); } static void sf_ipfw_ipv4(GString *rtxt, gchar *addr, guint32 port _U_, port_type ptype _U_, gboolean inbound, gboolean deny) { g_string_append_printf(rtxt, "add %s ip from %s to any %s", IPFW_DENY, addr, IPFW_IN); } static void sf_netfilter_ipv4(GString *rtxt, gchar *addr, guint32 port _U_, port_type ptype _U_, gboolean inbound, gboolean deny) { g_string_append_printf(rtxt, "iptables -A %s -i eth0 -d %s/32 -j %s", NF_INPUT, addr, NF_DROP); } #define PF_DENY (deny ? "block" : "pass") #define PF_IN (inbound ? "in" : "out") static void sf_pf_ipv4(GString *rtxt, gchar *addr, guint32 port _U_, port_type ptype _U_, gboolean inbound, gboolean deny) { g_string_append_printf(rtxt, "%s %s quick on $ext_if from %s to any", PF_DENY, PF_IN, addr); } /* Port */ #define RT_TCP_UDP (ptype == PT_TCP ? "tcp" : "udp") static void sf_ios_ext_port(GString *rtxt, gchar *addr _U_, guint32 port, port_type ptype, gboolean inbound _U_, gboolean deny) { g_string_append_printf(rtxt, "access-list NUMBER %s %s any any eq %u", IOS_DENY, RT_TCP_UDP, port); } static void sf_ipfilter_port(GString *rtxt, gchar *addr _U_, guint32 port, port_type ptype _U_, gboolean inbound, gboolean deny) { g_string_append_printf(rtxt, "%s %s on le0 proto %s from any to any port = %u", IPFILTER_DENY, IPFILTER_IN, RT_TCP_UDP, port); } static void sf_ipfw_port(GString *rtxt, gchar *addr _U_, guint32 port, port_type ptype, gboolean inbound, gboolean deny) { g_string_append_printf(rtxt, "add %s %s from any to any %u %s", IPFW_DENY, RT_TCP_UDP, port, IPFW_IN); } static void sf_netfilter_port(GString *rtxt, gchar *addr _U_, guint32 port, port_type ptype, gboolean inbound, gboolean deny) { g_string_append_printf(rtxt, "iptables -A %s -p %s --destination-port %u -j %s", NF_INPUT, RT_TCP_UDP, port, NF_DROP); } static void sf_pf_port(GString *rtxt, gchar *addr _U_, guint32 port, port_type ptype, gboolean inbound, gboolean deny) { g_string_append_printf(rtxt, "%s %s quick on $ext_if proto %s from any to any port %u", PF_DENY, PF_IN, RT_TCP_UDP, port); } #define NETSH_DENY (deny ? "DISABLE" : "ENABLE") static void sf_netsh_port(GString *rtxt, gchar *addr _U_, guint32 port, port_type ptype, gboolean inbound _U_, gboolean deny) { g_string_append_printf(rtxt, "add portopening %s %u Wireshark %s", RT_TCP_UDP, port, NETSH_DENY); } /* IPv4 + port */ static void sf_ios_ext_ipv4_port(GString *rtxt, gchar *addr, guint32 port _U_, port_type ptype _U_, gboolean inbound, gboolean deny) { if (inbound) g_string_append_printf(rtxt, "access-list NUMBER %s %s host %s any eq %u", IOS_DENY, RT_TCP_UDP, addr, port); else g_string_append_printf(rtxt, "access-list NUMBER %s %s any host %s eq %u", IOS_DENY, RT_TCP_UDP, addr, port); } static void sf_ipfilter_ipv4_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny) { if (inbound) g_string_append_printf(rtxt, "%s %s on le0 proto %s from %s to any port = %u", IPFILTER_DENY, IPFILTER_IN, RT_TCP_UDP, addr, port); else g_string_append_printf(rtxt, "%s %s on le0 proto %s from any to %s port = %u", IPFILTER_DENY, IPFILTER_IN, RT_TCP_UDP, addr, port); } static void sf_ipfw_ipv4_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny) { g_string_append_printf(rtxt, "add %s %s from %s to any %u %s", IPFW_DENY, RT_TCP_UDP, addr, port, IPFW_IN); } static void sf_pf_ipv4_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny) { g_string_append_printf(rtxt, "%s %s quick on $ext_if proto %s from %s to any port %u", PF_DENY, PF_IN, RT_TCP_UDP, addr, port); } static void sf_netfilter_ipv4_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny) { g_string_append_printf(rtxt, "iptables -A %s -p %s -d %s/32 --destination-port %u -j %s", NF_INPUT, RT_TCP_UDP, addr, port, NF_DROP); } static void sf_netsh_ipv4_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound _U_, gboolean deny) { g_string_append_printf(rtxt, "add portopening %s %u Wireshark %s %s", RT_TCP_UDP, port, NETSH_DENY, addr); } /* The destroy call back has the responsibility of * unlinking the temporary file * and freeing the filter_out_filter */ static void firewall_destroy_cb(GtkWidget *w, gpointer data _U_) { rule_info_t *rule_info; rule_info = (rule_info_t *)g_object_get_data(G_OBJECT(w), WS_RULE_INFO_KEY); #if 0 forget_rule_info(rule_info); #endif g_free(rule_info); gtk_widget_destroy(w); } static void firewall_copy_cmd_cb(GtkWidget *w _U_, gpointer data) { rule_info_t *rule_info = (rule_info_t *)data; GtkTextIter start, end; GtkTextBuffer *buf; buf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(rule_info->text)); gtk_text_buffer_get_start_iter(buf, &start); gtk_text_buffer_get_end_iter(buf, &end); gtk_text_buffer_select_range(buf, &start, &end); gtk_text_buffer_copy_clipboard(buf, gtk_clipboard_get(GDK_SELECTION_CLIPBOARD)); } static gboolean firewall_save_as_ok_cb(char *to_name, rule_info_t *rule_info) { FILE *fh; gchar *rule; GtkTextIter start, end; GtkTextBuffer *buf; fh = ws_fopen(to_name, "w"); if (fh == NULL) { open_failure_alert_box(to_name, errno, TRUE); g_free(to_name); return FALSE; } buf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(rule_info->text)); gtk_text_buffer_get_start_iter(buf, &start); gtk_text_buffer_get_end_iter(buf, &end); rule = gtk_text_buffer_get_text(buf, &start, &end, FALSE); fputs(rule, fh); fclose(fh); return TRUE; } static char * gtk_firewall_save_as_file(GtkWidget *caller) { GtkWidget *new_win; char *pathname; new_win = file_selection_new("Wireshark: Save Firewall ACL Rule", GTK_WINDOW(caller), FILE_SELECTION_SAVE); pathname = file_selection_run(new_win); if (pathname == NULL) { /* User cancelled or closed the dialog. */ return NULL; } /* We've crosed the Rubicon; get rid of the dialog box. */ window_destroy(new_win); return pathname; } static void firewall_save_as_cmd_cb(GtkWidget *w, gpointer data) { GtkWidget *caller = gtk_widget_get_toplevel(w); rule_info_t *rule_info = (rule_info_t *)data; char *pathname; /* * Loop until the user either selects a file or gives up. */ for (;;) { pathname = gtk_firewall_save_as_file(caller); if (pathname == NULL) { /* User gave up. */ break; } if (firewall_save_as_ok_cb(pathname, rule_info)) { /* We succeeded. */ g_free(pathname); break; } /* Dump failed; let the user select another file or give up. */ g_free(pathname); } }
P1sec/LTE_monitor_c2xx
wireshark/ui/gtk/firewall_dlg.c
C
gpl-2.0
28,427
<?php /** * @package Joomla! 2.5 * @version 4.x * @author 2008-2012 (c) Denys Nosov (aka Dutch) * @author web-site: www.joomla-ua.org * @copyright This module is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 License. **/ // no direct access defined('_JEXEC') or die; $com_path = JPATH_SITE.'/components/com_content/'; require_once $com_path.'router.php'; require_once $com_path.'helpers/route.php'; JModelLegacy::addIncludePath($com_path . '/models', 'ContentModel'); abstract class modJUNewsUltraHelper { public static function getList(&$params) { $app = JFactory::getApplication(); $db = JFactory::getDbo(); $query = $db->getQuery(true); $model = JModelLegacy::getInstance('Articles', 'ContentModel', array('ignore_request' => true)); $version = new JVersion; $joomla = substr($version->getShortVersion(), 0, 3); $appParams = JFactory::getApplication()->getParams(); $model->setState('params', $appParams); // Introtext $show_intro = $params->get( 'show_intro'); $introtext_limit = intval( $params->get( 'introtext_limit') ); $li = $params->get('li'); $lmttext = $params->get('lmttext'); $clear_tag = $params->get('clear_tag'); // Fulltext $show_full = $params->get( 'show_full', 0); $fulltext_limit = intval( $params->get( 'fulltext_limit') ); $li_full = $params->get('li_full'); $lmttext_full = $params->get('lmttext_full'); $clear_tag_full = $params->get('clear_tag_full'); // Date $data_format = $params->get('data_format'); $df_d = $params->get('df_d'); $df_m = $params->get('df_m'); $df_y = $params->get('df_y'); // Image $pik = $params->def('pik'); $imageWidth = intval($params->get('imageWidth')); $imageHeight = intval($params->get('imageHeight')); $thumb_width = intval($params->get('thumb_width')); $noimage = $params->def('noimage'); $imglink = $params->def('imglink'); $link_enabled = $params->get('link_enabled', 1); $youtube_img_show = $params->def('youtube_img_show', 1); $gallery = $params->def('gallery', 1); // Set the filters based on the module params $model->setState('list.start', (int) $params->get('count_skip', 0)); $model->setState('list.limit', (int) $params->get('count', 5)); $model->setState('filter.published', 1); if($joomla >= '3.0') { $model->setState('list.select', 'a.id, a.asset_id, a.title, a.alias, a.introtext, a.fulltext, ' . 'CASE WHEN badcats.id is null THEN a.state ELSE 0 END AS state, ' . 'a.catid, a.created, a.created_by, a.created_by_alias, ' . 'CASE WHEN a.modified = ' . $db->q($db->getNullDate()) . ' THEN a.created ELSE a.modified END as modified, ' . 'a.modified_by, a.checked_out, a.checked_out_time, a.publish_up, a.publish_down, ' . 'a.images, a.urls, a.attribs, a.version, a.ordering, ' . 'a.metakey, a.metadesc, a.access, a.hits, a.metadata, a.featured, a.language, a.xreference' ); } else { $model->setState('list.select', 'a.fulltext, a.id, a.title, a.alias, a.title_alias, a.introtext, a.state, a.catid, a.created, a.created_by, a.created_by_alias,' . ' a.modified, a.modified_by, a.publish_up, a.publish_down, a.images, a.urls, a.attribs, a.metadata, a.metakey, a.metadesc, a.access,' . ' a.hits, a.featured' ); } // Access filter $access = !JComponentHelper::getParams('com_content')->get('show_noauth'); $authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id')); $model->setState('filter.access', $access); // User filter $userId = JFactory::getUser()->get('id'); switch ($params->get('user_id')) { case 'by_me': $model->setState('filter.author_id', (int) $userId); break; case 'not_me': $model->setState('filter.author_id', $userId); $model->setState('filter.author_id.include', false); break; case '0': break; default: $model->setState('filter.author_id', (int) $params->get('user_id')); break; } // Filter by language $model->setState('filter.language', $app->getLanguageFilter()); // Featured switch switch ($params->get('show_featured')) { case '1': $model->setState('filter.featured', 'only'); break; case '0': $model->setState('filter.featured', 'hide'); break; default: $model->setState('filter.featured', 'show'); break; } // Set ordering $order_map = array( 'title_asc' => 'a.title', 'title_desc' => 'a.title DESC', 'id_asc' => 'a.id', 'id_desc' => 'a.id DESC', 'hits_asc' => 'a.hits', 'hits_desc' => 'a.hits DESC', 'created_asc' => 'a.created', 'created_desc' => 'a.created DESC', 'modified_desc' => 'a.modified DESC', 'modified_created_dsc' => 'a.modified DESC, a.created', 'modified_touch_dsc' => 'CASE WHEN (a.modified = '.$db->quote($db->getNullDate()).') THEN a.created ELSE a.modified END', 'ordering_asc' => 'a.ordering', 'ordering_desc' => 'a.ordering DESC', 'rand' => 'rand()', 'publish_dsc' => 'a.publish_up', 'rating_dsc' => 'v.rating_count', ); $ordering = JArrayHelper::getValue($order_map, $params->get('ordering'), 'a.publish_up'); $dir = ''; $model->setState('list.ordering', $ordering); $model->setState('list.direction', $dir); // Select article or categories if($params->def('display_article') == 1) { // Article filter $model->setState('filter.article_id', $params->def('articleid', array())); } else { // Category filter //$catids = $params->get('catid'); $catids = $params->get('catid', array()); if($params->get('category_filtering_type') == 1) { $model->setState('filter.category_id.include', (bool) $params->get('category_filtering_type')); } if ($catids) { if ($params->get('show_child_category_articles', 0) && (int) $params->get('levels', 0) > 0) { $categories = JModelLegacy::getInstance('Categories', 'ContentModel', array('ignore_request' => true)); $categories->setState('params', $appParams); $levels = $params->get('levels', 1) ? $params->get('levels', 1) : 99999; $categories->setState('filter.get_children', $levels); $categories->setState('filter.published', 1); $categories->setState('filter.access', $access); $additional_catids = array(); foreach($catids as $catid) { $categories->setState('filter.parentId', $catid); $recursive = true; $items = $categories->getItems($recursive); if ($items) { foreach($items as $category) { $condition = (($category->level - $categories->getParent()->level) <= $levels); if ($condition) { $additional_catids[] = $category->id; } } } } $catids = array_unique(array_merge($catids, $additional_catids)); } $model->setState('filter.category_id', $catids); } $excluded_articles = $params->get('excluded_articles', ''); if ($excluded_articles) { $excluded_articles = explode("\r\n", $excluded_articles); $model->setState('filter.article_id', $excluded_articles); $model->setState('filter.article_id.include', false); // Exclude } } $date_filtering = $params->get('date_filtering', 0); $relative_date = $params->get('relative_date', 0); if ($date_filtering == 1) { $model->setState('filter.date_filtering', (($date_filtering == 1 && $relative_date == 1) ? 'range' : 'relative')); $model->setState('filter.date_field', $params->get('date_field', 'a.created')); switch ($relative_date) { case '1': $model->setState('filter.start_date_range', $params->get('start_date_range', date('Y-m-d') .' 00:00:00')); $model->setState('filter.end_date_range', $params->get('end_date_range', date('Y-m-d H:i:s'))); break; case '2': $model->setState('filter.relative_date', '7'); break; case '3': $model->setState('filter.relative_date', '14'); break; case '4': $model->setState('filter.relative_date', cal_days_in_month(CAL_GREGORIAN, date('m'), date('Y'))); break; case '5': $model->setState('filter.relative_date', '365'); break; case '6': $model->setState('filter.relative_date', $params->get('custom_days', '30')); break; case '0': default: $model->setState('filter.relative_date', '1'); break; } } $items = $model->getItems(); // JComments integration if ($params->def('JC') == 1 && count($items)) { $comments = JPATH_SITE . '/components/com_jcomments/jcomments.php'; if (file_exists($comments)) { $ids = array(); foreach($items as $item) { $ids[] = $item->id; } $db->setQuery('SELECT object_id, count(*) AS cnt FROM #__jcomments WHERE object_group = "com_content" AND object_id IN ('.implode(',', $ids).') AND published = "1"'); $commentsCount = $db->loadObjectList('object_id'); foreach($items as &$item) { $item->comments = isset($commentsCount[$item->id]) ? $commentsCount[$item->id]->cnt : 0; $item->commentslink = '#comments'; $item->commentstext = JText::plural('LINK_READ_COMMENTS', $item->comments); if ($item->comments == 0) { $item->comments = ''; $item->commentslink = '#addcomments'; $item->commentstext = JText::_('LINK_ADD_COMMENT'); } } } else { echo '<strong style="color: green;">'. JText::_('MOD_JUNEWS_JC_NOT_INSTALLED') .'</strong>'; } } foreach ($items as &$item) { $item->slug = $item->id.':'.$item->alias; $item->catslug = $item->catid.':'.$item->category_alias; if ($access || in_array($item->access, $authorised)) { $item->link = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catslug)); $catlink = JRoute::_(ContentHelperRoute::getCategoryRoute($item->catslug)); } else { $item->link = JRoute::_('index.php?option=com_users&view=login'); $catlink = $item->link; } // article title $item->title = preg_replace('#"(.*?)"#is', '«\\1»', strip_tags( $item->title )); // category title if($params->get('showcat') == 1) { $cattitle = strip_tags( $item->category_title ); if($params->get('showcatlink') == 1) { $item->cattitle = '<a href="'. $catlink .'">'. $cattitle .'</a>'; } else { $item->cattitle = $cattitle; } } if ($pik == 1) { if ($imglink == 1) { $imlink = '<a href="'. $item->link .'"'. ($params->get('tips') == 1 ? ' title="'. strip_tags( $item->title ) .'"' : '') .'>'; $imlink2 = '</a>'; } else { $imlink = ''; $imlink2 = ''; } ; $junuimgresmatche = $item->introtext . $item->fulltext; if (preg_match('/{gallery\s+(.*?)}/i', $junuimgresmatche, $junuimgsource) && $gallery == '1') { $junuimgsource = $junuimgsource[1]; $imglist = explode("|", $junuimgsource); $junuimgsource = $imglist[0]; $imglist = ''; $root = JPATH_BASE .'/'; $folder = 'images/'. $junuimgsource; $img_folder = $root . $folder; if (is_dir($img_folder)) { $files = array(); $dir = opendir($img_folder); while(($file = readdir($dir)) !== false) { if($file !== '.' && $file !== '..' && (strtolower(substr($file, -3)) === 'jpg' || strtolower(substr($file, -3)) === 'png' || strtolower(substr($file, -3)) === 'gif')) { $files[] = $file; break; } } closedir($dir); sort($files); $junuimgsource = $folder .'/'. $files[0]; } else { $junuimgsource = ''; } } elseif (preg_match('/<img(.*?)src="(.*?)"(.*?)>\s*(<\/img>)?/', $junuimgresmatche, $junuimgsource)) { $junuimgsource = $junuimgsource[2]; } // images from article parameters $images = json_decode($item->images); if( ($params->def('image_source', 0) > '0') && ((isset($images->image_intro) && !empty($images->image_intro) ) || (isset($images->image_fulltext) && !empty($images->image_fulltext) )) ) { if( $params->def('image_source', 0) == '1' ) { if( isset($images->image_intro) && !empty($images->image_intro) ) { $junuimgsource = htmlspecialchars($images->image_intro); // raw image source $item->imagesource = htmlspecialchars($images->image_intro); } elseif( isset($images->image_fulltext) && !empty($images->image_fulltext) ) { $junuimgsource = htmlspecialchars($images->image_fulltext); // raw image source $item->imagesource = htmlspecialchars($images->image_fulltext); } } elseif( $params->def('image_source', 0) == '2' && ( isset($images->image_intro) && !empty($images->image_intro) ) ) { $junuimgsource = htmlspecialchars($images->image_intro); // raw image source $item->imagesource = htmlspecialchars($images->image_intro); } elseif( $params->def('image_source', 0) == '3' && ( isset($images->image_fulltext) && !empty($images->image_fulltext) ) ) { $junuimgsource = htmlspecialchars($images->image_fulltext); // raw image source $item->imagesource = htmlspecialchars($images->image_fulltext); } } else { if( $junuimgsource ) { $junuimgsource = str_replace(JURI::base(), '', $junuimgsource); // raw image source $item->imagesource = $junuimgsource; } else { $junuimgsource = ''; } } switch ($thumb_width) { case '0': $contentimage = $imlink .'<img src="'. $junuimgsource .'" width="'. $imageWidth .'" alt="'. strip_tags( $item->title ) .'" />'. $imlink2; $blankimage = $imlink .'<img src="'. JURI::base().'/media/mod_junewsultra/' . $noimage .'" width="'. $imageWidth .'" alt="'. strip_tags( $item->title ) .'" />'. $imlink2; if($youtube_img_show == 1) { $regex1 = '%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^>"&?/ ]{11})%i'; $regex2 = '#(player.vimeo.com)/video/([0-9]+)#i'; if (preg_match($regex1, $junuimgresmatche, $match)) { $yimg = modJUNewsUltraHelper::video('http://youtu.be/'. $match[1],'hqthumb'); $item->image = $imlink .'<img src="'. $yimg .'" width="'. $imageWidth .'" alt="'. strip_tags( $item->title ) .'" />'. $imlink2; $item->imagesource = $yimg; } elseif (preg_match($regex2, $junuimgresmatche, $match)) { $yimg = modJUNewsUltraHelper::video('http://vimeo.com/'. $match[2],'hqthumb'); $item->image = $imlink .'<img src="'. $yimg .'" width="'. $imageWidth .'" alt="'. strip_tags( $item->title ) .'" />'. $imlink2; $item->imagesource = $yimg; } elseif( $junuimgsource ) { $item->image = $contentimage; } elseif($params->def('defaultimg', 1) == 1) { $item->image = $blankimage; } } elseif( $junuimgsource ) { $item->image = $contentimage; } elseif($params->def('defaultimg', 1) == 1) { $item->image = $blankimage; } break; case '1': default: $thumb_img = modJUNewsUltraHelper::RenderImage( $junuimgsource, $params, '', '', '', '' ); list($width, $height, $type, $attr) = getimagesize( $thumb_img ); $contentimage = $imlink .'<img src="'. $thumb_img .'" '. $attr .' alt="'. strip_tags( $item->title ) .'" />'. $imlink2; $blank_thumb_img = modJUNewsUltraHelper::RenderImage( 'media/mod_junewsultra/'. $noimage, $params, '', '', '', ''); list($width, $height, $type, $attr) = getimagesize( $blank_thumb_img ); $blankimage = $imlink .'<img src="'. $blank_thumb_img .'" '. $attr .' alt="'. strip_tags( $item->title ) .'" />'. $imlink2; if(($youtube_img_show == 1) && ($link_enabled == 1)) { $regex1 = '%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^>"&?/ ]{11})%i'; $regex2 = '#(player.vimeo.com)/video/([0-9]+)#i'; if (preg_match($regex1, $junuimgresmatche, $match)) { $yimg = modJUNewsUltraHelper::video('http://youtu.be/'. $match[1],'hqthumb'); $video_img = modJUNewsUltraHelper::RenderImage($yimg, $params, '', '', '', ''); list($width, $height, $type, $attr) = getimagesize( $video_img); $item->image = $imlink .'<img src="'. $video_img .'" '. $attr .' alt="'. strip_tags( $item->title ) .'" />'. $imlink2; $item->imagesource = $yimg; } elseif (preg_match($regex2, $junuimgresmatche, $match)) { $yimg = modJUNewsUltraHelper::video('http://vimeo.com/'. $match[2],'hqthumb'); $video_img = modJUNewsUltraHelper::RenderImage($yimg, $params, '', '', '', ''); list($width, $height, $type, $attr) = getimagesize( $video_img); $item->image = $imlink .'<img src="'. $video_img .'" '. $attr .' alt="'. strip_tags( $item->title ) .'" />'. $imlink2; $item->imagesource = $yimg; } elseif( $junuimgsource ) { $item->image = $contentimage; } elseif($params->def('defaultimg', 1) == 1) { $item->image = $blankimage; } } elseif( $junuimgsource ) { $item->image = $contentimage; } elseif($params->def('defaultimg', 1) == 1) { $item->image = $blankimage; } break; } } // introtext if($show_intro == '1') { if ($clear_tag == '1') { $item->introtext = preg_replace('/{([a-zA-Z0-9\-_]*)\s*(.*?)}/i', '', $item->introtext); $item->introtext = str_replace( '&nbsp;', ' ', $item->introtext ); $item->introtext = strip_tags( $item->introtext ); } else { $item->introtext = preg_replace('/{([a-zA-Z0-9\-_]*)\s*(.*?)}/i', '', $item->introtext); $item->introtext = preg_replace('/<img(.*?)>/i', '', $item->introtext); } if ($li == '1') { if ($lmttext == '1') { $item->introtext = trim(implode(" ", array_slice(explode(" ", $item->introtext), 0, $introtext_limit))); } else { $item->introtext = trim(JString::substr($item->introtext, 0, $introtext_limit)); } if (!preg_match('#(\.|\?|\!)$#ismu', $item->introtext)) { $item->introtext = preg_replace('#^\s?(\,|\;|\:|\-)#ismu', '', $item->introtext); $item->introtext = $item->introtext . '...'; } } } // fulltext if($show_full == '1') { if ($clear_tag == '1') { $item->fulltext = preg_replace('/{([a-zA-Z0-9\-_]*)\s*(.*?)}/i', '', $item->fulltext); $item->fulltext = str_replace( '&nbsp;', ' ', $item->fulltext ); $item->fulltext = strip_tags( $item->fulltext ); } else { $item->fulltext = preg_replace('/{([a-zA-Z0-9\-_]*)\s*(.*?)}/i', '', $item->fulltext); $item->fulltext = preg_replace('/<img(.*?)>/i', '', $item->fulltext); } if ($li_full == '1') { if ($lmttext_full == '1') { $item->fulltext = trim(implode(" ", array_slice(explode(" ", $item->fulltext), 0, $fulltext_limit))); } else { $item->fulltext = trim(JString::substr($item->fulltext, 0, $fulltext_limit)); } if (!preg_match('#(\.|\?|\!)$#ismu', $item->fulltext)) { $item->fulltext = preg_replace('#^\s?(\,|\;|\:|\-)#ismu', '', $item->fulltext); $item->fulltext = $item->fulltext . '...'; } } } // author if ($params->def('juauthor') == 1) { if ( $item->created_by_alias ) { $item->author = $item->created_by_alias; } else { $item->author = $item->author; } } // date if ($params->get('show_date') == 1) { $item->date = JHtml::date($item->created, $data_format); $item->df_d = JHtml::date($item->created, $df_d); $item->df_m = JHtml::date($item->created, $df_m); $item->df_y = JHtml::date($item->created, $df_y); } // hits if ($params->get('showHits') == 1) { $item->hits = $item->hits; } // rating if ($params->get('showRating') == 1) { $template = str_replace('_:', '', $params->def('template')); $starImageOn = JHTML::_('image.site', 'modules/mod_junewsultra/tmpl/'.$template.'/images/rating_star.png', null);; $starImageOff = JHtml::_('image.site','modules/mod_junewsultra/tmpl/'.$template.'/images/rating_star_blank.png', NULL, NULL, true); $img = ''; for ($i=0; $i < $item->rating; $i++) { $img .= $starImageOn; } for ($i=$item->rating; $i < 5; $i++) { $img .= $starImageOff; } $item->rating = $img; } } return $items; } public static function RenderImage($url, &$params, $nw, $nh, $nzc, $nq) { $img_cache = $params->get( 'img_cache', 'cache' ); $cache_maxfiles_img = $params->get( 'cache_maxfiles_img', '200' ); $cache_maxsize_img = $params->get( 'cache_maxsize_img', '10' ); $cache_maxage_img = $params->get( 'cache_maxage_img', '30' ); $w = ($nw ? $nw : intval($params->get( 'imageWidth' ))); $h = ($nh ? $nh : intval($params->get( 'imageHeight' ))); $zc = ($nzc ? $nzc : intval($params->get( 'Zoom_Crop', 1 ))); $q = ($nq ? $nq : '99' ); $f = $params->def( 'img_ext', 'jpg' ); $thumb_filtercolor = intval($params->get( 'thumb_filtercolor', 0 )); $colorized = $params->get( 'colorized', '25' ); $colorpicker = $params->get( 'colorpicker', '#0000ff' ); $thumb_th = $params->def( 'thumb_th', 0 ); $thumb_th_seting = $params->def( 'thumb_th_seting', 0 ); $link_enabled = $params->get( 'link_enabled', 1 ); $error_image = JPATH_BASE .'/media/mod_junewsultra/'. $params->def( 'noimage' ); $thumb_filters = $params->def( 'thumb_filters', 1 ); $usm = $params->def( 'thumb_unsharp', 1 ); $thumb_unsharp_amount = $params->def( 'thumb_unsharp_amount', 80 ); $thumb_unsharp_radius = $params->def( 'thumb_unsharp_radius', 1 ); $thumb_unsharp_threshold = $params->def( 'thumb_unsharp_threshold', 3 ); $thumb_blur = $params->def( 'thumb_blur', 0 ); $thumb_blur_seting = $params->def( 'thumb_blur_seting', 1 ); $thumb_brit = $params->def( 'thumb_brit', 0 ); $thumb_brit_seting = $params->def( 'thumb_brit_seting', 50 ); $thumb_cont = $params->def( 'thumb_cont', 0 ); $thumb_cont_seting = $params->def( 'thumb_cont_seting', 50 ); if(preg_match('#^(http|https|ftp)://#i', $url)) { $url = $url; } else { $url = (!file_exists($url) ? $error_image : JPATH_BASE .'/'. $url); } $path_parts = pathinfo($url); $imgfile = explode(".", basename($url)); $img_name = $imgfile[0]; $imgurl = str_replace(array('.', ',', '-', '_', '|', '+', '=', '%', '^', '&', '(', ')', ' ', '"', '\''), '', $img_name); $subfolder = $img_cache .'/junewsultra/'. $w.'x'.$h .'/'. substr( strtolower( MD5($path_parts['dirname'] ) ), -1); $target = $subfolder .'/junews_'. substr( strtolower( $imgurl ), 0, 150) .'-'. MD5( $url . $q . $zc . $f . $params->get('use_imagemagick') . $usm . $thumb_unsharp_amount . $thumb_unsharp_radius . $thumb_unsharp_threshold . $thumb_filtercolor . $colorized . $colorpicker . $thumb_blur . $thumb_blur_seting . $thumb_brit . $thumb_brit_seting . $thumb_cont . $thumb_cont_seting . $thumb_th . $thumb_th_seting ) .'.'. $f; if (($link_enabled == 0) && preg_match('#^(http|https|ftp)://#i', $url)) { $outpute = $error_image; return $outpute; } modJUNewsUltraHelper::MakeDirectory($dir = JPATH_BASE .'/'. $subfolder, $mode = 0777); if (file_exists(JPATH_BASE .'/'. $target)) { $outpute = JURI::base(false) . $target; } else { include_once(JPATH_BASE .'/modules/mod_junewsultra/img/phpthumb.class.php'); $phpThumb = new phpThumb(); $phpThumb->resetObject(); $phpThumb->setParameter('config_max_source_pixels', round(max(intval(ini_get('memory_limit')), intval(get_cfg_var('memory_limit'))) * 1048576 / 6) ); $phpThumb->setParameter('config_temp_directory', JPATH_BASE .'/'. $img_cache .'/junewsultra/' ); $phpThumb->setParameter('config_cache_directory', JPATH_BASE .'/'. $img_cache .'/junewsultra/' ); $phpThumb->setCacheDirectory(); $phpThumb->setParameter('config_cache_maxfiles', $cache_maxfiles_img ); $phpThumb->setParameter('config_cache_maxsize', $cache_maxsize_img * 1024 * 1024 ); $phpThumb->setParameter('config_cache_maxage', 86400 * $cache_maxage_img ); $phpThumb->setSourceFilename( $url ); if($w) { $phpThumb->setParameter( 'w', $w ); } if($h) { $phpThumb->setParameter( 'h', $h ); } if($q) { $phpThumb->setParameter( 'q', $q ); } $phpThumb->setParameter( 'f', $f ); $phpThumb->setParameter( 'zc', $zc ); $phpThumb->setParameter( 'aoe', '1' ); switch ($thumb_filtercolor) { case '1': $phpThumb->setParameter( 'fltr', 'gray' ); break; case '2': $phpThumb->setParameter( 'fltr', 'sep' ); break; case '3': $phpThumb->setParameter( 'fltr', 'th|'. $thumb_th_seting ); break; case '4': $phpThumb->setParameter( 'fltr', 'clr|'. $colorized .'|'. str_replace('#', '', $colorpicker) ); break; default: break; } if($thumb_filters == 1) { if($usm == 1) { $phpThumb->setParameter( 'fltr', 'usm|'. $thumb_unsharp_amount .'|'. $thumb_unsharp_radius .'|'. $thumb_unsharp_threshold ); } if($thumb_blur == 1) { $phpThumb->setParameter( 'fltr', 'blur|'. $thumb_blur_seting ); } if($thumb_brit == 1) { $phpThumb->setParameter( 'fltr', 'brit|'. $thumb_brit_seting ); } if($thumb_cont == 1) { $phpThumb->setParameter( 'fltr', 'cont|'. $thumb_cont_seting ); } } if($params->get('use_imagemagick') == 1) { if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') { $imagemagick = ($params->get( 'imagemagick_path' ) == '' ? 'C:/ImageMagick/convert.exe' : $params->get( 'imagemagick_path' )); } else { $imagemagick = $params->get( 'imagemagick_path', '' ); } $phpThumb->setParameter('config_imagemagick_path', $imagemagick); $phpThumb->setParameter('config_prefer_imagemagick', ($params->get('use_imagemagick') == 1 ? true : false) ); $phpThumb->setParameter('config_imagemagick_use_thumbnail', true); } if ($phpThumb->GenerateThumbnail()) { if ($phpThumb->RenderToFile( JPATH_BASE .'/'. $target )) { $outpute = JURI::base(false) . $target; } else { $outpute = ''; } } else { $outpute = ''; } } return $outpute; } public static function MakeDirectory($dir, $mode) { if (is_dir($dir) || @mkdir($dir,$mode)) return TRUE; if (!modJUNewsUltraHelper::MakeDirectory(dirname($dir),$mode)) return FALSE; return @mkdir($dir,$mode); } /* * parse_video() PHP function * Author: takien * URL: http://takien.com * * Author: takien, slaffko * URL: http://takien.com, http://slaffko.name */ public static function video($url,$return='embed',$width='',$height='',$rel=0) { $urls = parse_url($url); //url is http://vimeo.com/xxxx if($urls['host'] == 'vimeo.com'){ $vid = ltrim($urls['path'],'/'); } //url is http://youtu.be/xxxx else if($urls['host'] == 'youtu.be'){ $yid = ltrim($urls['path'],'/'); } //url is http://www.youtube.com/embed/xxxx else if(strpos($urls['path'],'embed') == 1){ $yid = end(explode('/',$urls['path'])); } //url is xxxx only else if(strpos($url,'/')===false){ $yid = $url; } //http://www.youtube.com/watch?feature=player_embedded&v=m-t4pcO99gI //url is http://www.youtube.com/watch?v=xxxx else{ parse_str($urls['query']); $yid = $v; if(!empty($feature)){ $yid = end(explode('v=',$urls['query'])); $arr = explode('&',$yid); $yid = $arr[0]; } } if($yid) { //return embed iframe if($return == 'embed'){ return '<iframe width="'.($width?$width:560).'" height="'.($height?$height:349).'" src="http://www.youtube.com/embed/'.$yid.'?rel='.$rel.'" frameborder="0" ebkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'; } //return normal thumb else if($return == 'thumb' || $return == 'thumbmed'){ return 'http://i1.ytimg.com/vi/'.$yid.'/default.jpg'; } //return hqthumb else if($return == 'hqthumb' ){ return 'http://i1.ytimg.com/vi/'.$yid.'/hqdefault.jpg'; } // else return id else{ return $yid; } } else if($vid) { $vimeoObject = json_decode(file_get_contents("http://vimeo.com/api/v2/video/".$vid.".json")); if (!empty($vimeoObject)) { //return embed iframe if($return == 'embed'){ return '<iframe width="'.($width?$width:$vimeoObject[0]->width).'" height="'.($height?$height:$vimeoObject[0]->height).'" src="http://player.vimeo.com/video/'.$vid.'?title=0&byline=0&portrait=0" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'; } //return normal thumb else if($return == 'thumb'){ return $vimeoObject[0]->thumbnail_small; } //return medium thumb else if($return == 'thumbmed'){ return $vimeoObject[0]->thumbnail_medium; } //return hqthumb else if($return == 'hqthumb'){ return $vimeoObject[0]->thumbnail_large; } // else return id else{ return $vid; } } } } }
akvlad/lemond
modules/mod_junewsultra/helper.php
PHP
gpl-2.0
36,138
#views-exposed-form-views-custom-filter-page div.throbber { display: block; } #views-exposed-form-views-custom-filter-page .ajax-progress { display: block; position: absolute; z-index: 10; } #views-exposed-form-views-custom-filter-page .ajax-progress .throbber { display: block; } #views-exposed-form-views-custom-filter-page .ajax-progress .message { display: block; font-size: 0.8em; padding-top: 0.3em; } #views-preview-wrapper .container-inline { padding-top: 0; }
NEU-DSG-archive/tapas
sites/all/modules/views_hst_filter/views_hst_filter.css
CSS
gpl-2.0
504
<?php /** * @package ZOO Category Module * @file mod_zoocategory.php * @version 2.0.0 May 2010 * @author YOOtheme http://www.yootheme.com * @copyright Copyright (C) 2007 - 2010 YOOtheme GmbH * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only */ // no direct access defined('_JEXEC') or die('Restricted access'); // load config require_once(JPATH_ADMINISTRATOR.'/components/com_zoo/config.php'); $app = YTable::getInstance('application')->get($params->get('application', 0)); // is application ? if (empty($app)) { return null; } // set one or multiple categories $categories = array(); $all_categories = $app->getCategoryTree(true); if (isset($all_categories[$params->get('category', 0)])) { $categories = $all_categories[$params->get('category', 0)]->getChildren(); } if (count($categories)) { $menu_item = $params->get('menu_item'); $itemid = $menu_item ? '&Itemid='.$menu_item : ''; $url = 'index.php?option=com_zoo&task=category'.$itemid.'&category_id='; $max_depth = $params->get('depth', 0); include(JModuleHelper::getLayoutPath('mod_zoocategory', $params->get('theme', 'default'))); }
alecerosiete/webBancaria
modules/mod_zoocategory/mod_zoocategory.php
PHP
gpl-2.0
1,178
/* Quarn OS / Manes * * Type class * * Copyright (C) 2008-2009 Pawel Dziepak * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "component.h" #include "type.h" #include "manes/error.h" #include "factory.h" #include "abstract.h" #include "libs/string.h" #include "manes/manec.h" using namespace manes; using namespace manes::cds; type::type(const component_name &_name, const component_name &_base, const delegate<p<component> > creat) : base(_base), create_impl(creat) { this->name = _name; } component_name type::get_base() const { return base; } bool type::is(const component_name &x) const { if (x == name) return true; p<type> tpe = manec::get()->get_factory()->get_component(component_name::from_path((string)"/type," + base.get_name())).cast<type>(); if (!tpe.cast<abstract>().valid()) return false; if (!tpe.valid()) return false; return tpe->is(x); } p<component> type::create_component() { assert((string)"type: attempt to create implementation of abstract type: " + name.get_name(), create_impl.null()); p<component> comp = create_impl(); comp->set(this); return comp; } bool type::operator==(const type &x) const { return x.name == name; } bool type::operator!=(const type &x) const { return !operator==(x); }
pdziepak/quarnos-old2
manes/cds/type.cpp
C++
gpl-2.0
1,946
import sys import os import arcEC def GNDBruninTOC_exe_G2N(parameters, messages): # *** Start Edtiting etc. the receiving layer # http://resources.arcgis.com/en/help/main/10.2/index.html#//00s300000008000000 # XXX Check that we are actually in an edit session ... workspace = r"C:\Users\b004218\AppData\Roaming\ESRI\Desktop10.3\ArcCatalog\EC_nis_editor@green3.sde"#\NIS.Vores_Navne" #os.path.dirname(lay_in.dataSource) lay_in = "\NIS.Vores_Navne\NIS.NamesAtest" arcEC.SetMsg(" WS : "+str(workspace), 0) edit = arcpy.da.Editor(workspace) edit.startEditing() # Edit session is started without (False) an undo/redo stack for versioned data edit.startOperation() # Start an edit operation # *** for each record: arcEC.SetMsg("\nRunning through the rows ...", 0) lst_fields_we_want = ["GST_NID","OBJNAM","NOBJNM","NIS_EDITOR_COMMENT","NAMETYPE"] lst_Fails = list() with arcpy.da.UpdateCursor(workspace+lay_in, lst_fields_we_want, "GST_NID IS NOT NULL") as cursor: for row in cursor: pass # *** Start Edtiting etc. the receiving layer edit.stopOperation() # Stop the edit operation. edit.stopEditing(True) # Stop the edit session and save the changes arcEC.SetMsg("Processed rows : "+str(num_row_count), 0) arcEC.SetMsg(" Changed rows : "+str(num_row_changed), 0) arcEC.SetMsg(" Failed rows : "+str(len(lstFails)), 0) return len(lstFails) # *** End of function GNDBruninTOC() if __name__ == "__main__": # This allows the 'executes' to be called from classic .tbx parameters = [arcpy.GetParameterAsText(0), arcpy.GetParameterAsText(1), arcpy.GetParameterAsText(2), arcpy.GetParameterAsText(3)] messages = [] result = GNDBruninTOC_exe_G2N(parameters, messages) # *** End of Script *** # Music that accompanied the coding of this script: # Kid Creole & the Coconuts - Tropical gangster
MartinHvidberg/GNDB
GNDB_exe_GNDB2NamesA.py
Python
gpl-2.0
1,978
/* * ObjManager.cpp * Nuvie * * Created by Eric Fry on Sat Mar 15 2003. * Copyright (c) 2003. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include <cassert> #include "nuvieDefs.h" #include "Configuration.h" #include "ActorManager.h" #include "EggManager.h" #include "TileManager.h" #include "ObjManager.h" #include "UseCode.h" #include "U6misc.h" #include "U6objects.h" #include "U6LList.h" #include "NuvieIOFile.h" #include "Game.h" #include "MapWindow.h" #include "Script.h" #include "MsgScroll.h" static const int obj_egg_table[5] = {0, // NUVIE_GAME_NONE 335, // NUVIE_GAME_U6 466, // NUVIE_GAME_MD 0, 230}; // NUVIE_GAME_SE static iAVLKey get_iAVLKey(const void *item) { return ((ObjTreeNode *)item)->key; } ObjManager::ObjManager(Configuration *cfg, TileManager *tm, EggManager *em) { uint8 i; std::string show_eggs_key; config = cfg; tile_manager = tm; egg_manager = em; usecode = NULL; obj_save_count = 0; load_basetile(); load_weight_table(); memset(actor_inventories,0,sizeof(actor_inventories)); for(i=0;i<64;i++) { surface[i] = iAVLAllocTree(get_iAVLKey); } for(i=0;i<5;i++) { dungeon[i] = iAVLAllocTree(get_iAVLKey); } last_obj_blk_x = 0; last_obj_blk_y = 0; last_obj_blk_z = OBJ_TEMP_INIT; config->value("config/GameType",game_type); //save the egg tile_num incase we want to switch egg display on again. egg_tile_num = get_obj_tile_num(obj_egg_table[game_type]); show_eggs_key = config_get_game_key(config); show_eggs_key.append("/show_eggs"); config->value(show_eggs_key, show_eggs); //if(!show_eggs) // show_egg_objs(false); std::string custom_tile_str; config->value(config_get_game_key(config) +"/custom_actor_tiles", custom_tile_str, "default"); if(custom_tile_str == "default") { if(Game::get_game()->is_new_style()) custom_actor_tiles = true; else custom_actor_tiles = false; } else if(custom_tile_str == "yes") custom_actor_tiles = true; else custom_actor_tiles = false; } ObjManager::~ObjManager() { clean(); unsigned int i; for(i=0;i<64;i++) iAVLFreeTree(surface[i], clean_obj_tree_node); for(i=0;i<5;i++) iAVLFreeTree(dungeon[i], clean_obj_tree_node); for(uint16 i=0; i < 256; i++) { if(actor_inventories[i]) { delete actor_inventories[i]; } } } bool ObjManager::load_basetile() { std::string filename; NuvieIOFileRead basetile; uint16 i; config_get_path(config,"basetile",filename); if(basetile.open(filename) == false) return false; for(i=0;i<1024;i++) { obj_to_tile[i] = basetile.read2(); obj_stackable[i] = (uint8)tile_manager->tile_is_stackable(obj_to_tile[i]); } // FIXME: tile_manager's tile_is_stackable is incorrect for (at least) Zu Ylem, silver snake venom. return true; } bool ObjManager::load_weight_table() { std::string filename; NuvieIOFileRead tileflag; config_get_path(config,"tileflag",filename); if(tileflag.open(filename) == false) return false; tileflag.seek(0x1000); tileflag.readToBuf(obj_weight,1024); return true; } bool ObjManager::load_super_chunk(NuvieIO *chunk_buf, uint8 level, uint8 chunk_offset) { NuvieIOFileRead file; U6LList *list; uint16 num_objs; Obj *obj; uint16 i; U6LList *inventory_list; iAVLTree *obj_tree; if(level == 0) obj_tree = surface[chunk_offset]; else obj_tree = dungeon[level - 1]; list = new U6LList(); num_objs = chunk_buf->read2(); //DEBUG(0,LEVEL_DEBUGGING,"chunk %02d number of objects: %d\n", chunk_offset, num_objs); for(i=0;i<num_objs;i++) { obj = loadObj(chunk_buf); list->add(obj); if(obj->obj_n == obj_egg_table[game_type]) { egg_manager->add_egg(obj); // set egg visibility obj->set_invisible(Game::get_game()->are_cheats_enabled() ? !show_eggs : true); } if(usecode->is_container(obj)) //object type is container, but may be empty { obj->make_container(); } if(obj->get_engine_loc() == OBJ_LOC_INV || obj->get_engine_loc() == OBJ_LOC_READIED) //triggered when object in actor's inventory OR equipped { //FIXME need to add to inventory properly!! eg set engine loc. inventory_list = get_actor_inventory(obj->x); inventory_list->add(obj); } else { if(obj->is_in_container()) //object in container { addObjToContainer(list,obj); } else { add_obj(obj); // show remaining objects /* if(show_eggs || obj->obj_n != obj_egg_table[game_type]) // show remaining objects, hiding eggs if neccecary. { add_obj(obj); // print_obj(obj,false); }*/ } } //print_obj(obj,false); } delete list; return true; } bool ObjManager::save_super_chunk(NuvieIO *save_buf, uint8 level, uint8 chunk_offset) { iAVLTree *obj_tree; ObjTreeNode *item; U6Link *link; iAVLCursor node; uint32 start_pos; uint32 finish_pos; uint16 egg_type = obj_egg_table[game_type]; if(level == 0) obj_tree = surface[chunk_offset]; else obj_tree = dungeon[level-1]; item = (ObjTreeNode *)iAVLFirst(&node, obj_tree); start_pos = save_buf->position(); //skip the 2 bytes for number of objects. save_buf->write2(0); // we'll fill this in later on. obj_save_count = 0; for(;item;) { for(link = item->obj_list->end(); link != NULL; link=link->prev) { if(((Obj *)link->data)->obj_n != egg_type) // we don't save eggs here. They are saved in save_eggs() save_obj(save_buf, (Obj *)link->data, obj_save_count); } item = (ObjTreeNode *)iAVLNext(&node); } finish_pos = save_buf->position(); save_buf->seek(start_pos); save_buf->write2(obj_save_count); save_buf->seek(finish_pos); return true; } bool ObjManager::save_eggs(NuvieIO *save_buf) { uint32 start_pos; uint32 finish_pos; std::list<Egg *> *egg_list; std::list<Egg *>::iterator egg; start_pos = save_buf->position(); //skip number of objects we will fill that in at the end. save_buf->write2(0); egg_list = egg_manager->get_egg_list(); obj_save_count = 0; for(egg = egg_list->begin(); egg != egg_list->end();egg++) save_obj(save_buf, (*egg)->obj, obj_save_count); finish_pos = save_buf->position(); save_buf->seek(start_pos); save_buf->write2(obj_save_count); save_buf->seek(finish_pos); DEBUG(0,LEVEL_DEBUGGING,"Eggs: %d\n", obj_save_count); return true; } bool ObjManager::save_inventories(NuvieIO *save_buf) { uint32 start_pos; uint32 finish_pos; U6Link *link; uint16 i; start_pos = save_buf->position(); save_buf->write2(0); obj_save_count = 0; for(i=0;i<256;i++) { if(actor_inventories[i] != NULL) { for(link=actor_inventories[i]->start(); link != NULL; link=link->next) { save_obj(save_buf, (Obj *)link->data, obj_save_count); } } } DEBUG(0,LEVEL_DEBUGGING,"Actor Inventories: %d\n", obj_save_count); finish_pos = save_buf->position(); save_buf->seek(start_pos); save_buf->write2(obj_save_count); save_buf->seek(finish_pos); return true; } bool ObjManager::save_obj(NuvieIO *save_buf, Obj *obj, uint16 parent_objblk_n) { uint8 b; U6Link *link; uint16 objblk_n; if(obj->is_in_container()) //obj is in a container { //obj->in_container(); // in container obj->x = parent_objblk_n & 0x3ff; //save 10bits in x obj->y &= 0xffc0; //clear lower 6 bits obj->y |= (parent_objblk_n >> 10); //save top 6bits } else { if(!obj->is_readied()) { obj->status &= (0xff ^ OBJ_STATUS_IN_CONTAINER); } } if(obj->is_in_inventory(OBJ_DONT_CHECK_PARENT)) obj->x = obj->get_actor_holding_obj()->get_actor_num(); //set original status location bits. obj->status &= OBJ_STATUS_MASK_SET; switch(obj->get_engine_loc()) { case OBJ_LOC_MAP : obj->status |= OBJ_STATUS_ON_MAP; break; case OBJ_LOC_CONT : obj->status |= OBJ_STATUS_IN_CONTAINER; break; case OBJ_LOC_INV : obj->status |= OBJ_STATUS_IN_INVENTORY; break; case OBJ_LOC_READIED : obj->status |= OBJ_STATUS_READIED; break; } save_buf->write1(obj->status); save_buf->write1(obj->x & 0xff); b = obj->x >> 8; b += obj->y << 2; save_buf->write1(b); b = obj->y >> 6; b += obj->z << 4; save_buf->write1(b); save_buf->write1(obj->obj_n & 0xff); b = obj->obj_n >> 8; b += obj->frame_n << 2; save_buf->write1(b); save_buf->write1((uint8)(obj->qty & 0xff)); //only save the lower byte to disk. if(is_stackable(obj)) save_buf->write1(obj->qty >> 8); else save_buf->write1(obj->quality); objblk_n = obj_save_count; obj_save_count += 1; if(obj->container) { for(link = obj->container->end(); link != NULL; link=link->prev) save_obj(save_buf, (Obj *)link->data, objblk_n); } return true; } void ObjManager::clean() { uint8 i; egg_manager->clean(Game::get_game()->are_cheats_enabled() ? show_eggs : false); //show_eggs determines wether we delete the actual Objs from egg manager. for(i=0;i<64;i++) iAVLCleanTree(surface[i], clean_obj_tree_node); for(i=0;i<5;i++) iAVLCleanTree(dungeon[i], clean_obj_tree_node); clean_actor_inventories(); // remove the temporary object list. The objects were deleted from the surface and dungeon trees. temp_obj_list.clear(); for (std::list<Obj *>::iterator it = tile_obj_list.begin(); it != tile_obj_list.end(); ++it) { delete *it; } tile_obj_list.clear(); return; } void ObjManager::clean_actor_inventories() { U6Link *link; uint16 i; for(i=0; i < 256; i++) { if(actor_inventories[i]) { for(link=actor_inventories[i]->start(); link != NULL; ) { Obj *obj = (Obj *)link->data; link=link->next; delete_obj(obj); } actor_inventories[i]->removeAll(); } } return; } /* U6LList *ObjManager::get_obj_superchunk(uint16 x, uint16 y, uint8 level) { uint16 i; if(level == 0) { i = y * 8 + x; return surface[i]; } return dungeon[level-1]; } */ bool ObjManager::is_boundary(uint16 x, uint16 y, uint8 level, uint8 boundary_type, Obj *excluded_obj) { U6Link *link; U6LList *obj_list; Obj *obj; Tile *tile, *tile1; uint16 tile_num; bool check_tile; uint16 i,j; uint16 next_x, next_y; next_x = WRAPPED_COORD(x+1,level); next_y = WRAPPED_COORD(y+1,level); for(j=y;j<=y+1;j++) { for(i=x;i<=x+1;i++) { obj_list = get_obj_list(WRAPPED_COORD(i,level), WRAPPED_COORD(j,level), level); if(obj_list != NULL) { link = obj_list->end(); for(check_tile = false;link != NULL;link = link->prev) { obj = (Obj *)link->data; if(obj == excluded_obj) continue; tile_num = get_obj_tile_num(obj->obj_n)+obj->frame_n; tile = tile_manager->get_original_tile(tile_num); if(obj->x == x && obj->y == y) { check_tile = true; } if(tile->dbl_width && obj->x == next_x && obj->y == y) { tile_num--; check_tile = true; } if(tile->dbl_height && obj->x == x && obj->y == next_y) { tile_num--; check_tile = true; } if(obj->x == next_x && obj->y == next_y && tile->dbl_width && tile->dbl_height) { tile_num -= 2; check_tile = true; } if(check_tile) { tile1 = tile_manager->get_tile(tile_num); if(tile1->flags2 & boundary_type) //either TILEFLAG_BOUNDARY or TILEFLAG_MISSILE_BOUNDARY return true; check_tile = false; } } } } } return false; } /* no longer needed. //FIX this needs to be moved magicnumbers :( bool ObjManager::is_door(Obj * obj) { //for U6 if((obj->obj_n >= 297 && obj->obj_n <= 300) || obj->obj_n == 334 || obj->obj_n == 213) //OBJ_U6_MOUSEHOLE) return true; return false; } */ uint8 ObjManager::is_passable(uint16 x, uint16 y, uint8 level) { U6Link *link; U6LList *obj_list; Obj *obj; Tile *tile, *tile1; uint16 tile_num; bool check_tile; bool object_at_location = false; uint16 i,j; uint16 x2 = WRAPPED_COORD((x+1),level); // wrap on map edge uint16 y2 = WRAPPED_COORD((y+1),level); for(i=x;;i=x2) // only checks x and x2 { for(j=y;;j=y2) // only checks y and y2 { obj_list = get_obj_list(i,j,level); if(i == x && j == y && obj_list) { if(obj_list->end() != NULL) object_at_location = true; } if(obj_list != NULL) { link = obj_list->end(); for(check_tile = false;link != NULL;link = link->prev) { obj = (Obj *)link->data; tile_num = get_obj_tile_num(obj->obj_n)+obj->frame_n; tile = tile_manager->get_original_tile(tile_num); if(obj->x == x && obj->y == y) { check_tile = true; } if(tile->dbl_width && obj->x == x2 && obj->y == y) { tile_num--; check_tile = true; } if(tile->dbl_height && obj->x == x && obj->y == y2) { tile_num--; check_tile = true; } if(obj->x == x2 && obj->y == y2 && tile->dbl_width && tile->dbl_height) { tile_num -= 3; check_tile = true; } if(check_tile) { tile1 = tile_manager->get_original_tile(tile_num); if(tile1->passable == false) return OBJ_NOT_PASSABLE; check_tile = false; } } } if(j == y) j = y2; else break; } if(i == x) i = x2; else break; } if(object_at_location) return OBJ_PASSABLE; return OBJ_NO_OBJ; } bool ObjManager::is_forced_passable(uint16 x, uint16 y, uint8 level) { U6LList *obj_list; U6Link *link; Obj *obj; Tile *tile; obj_list = get_obj_list(x,y,level); if(obj_list) { for(link=obj_list->start();link!=NULL;link=link->next) { obj = (Obj *)link->data; tile = tile_manager->get_tile(get_obj_tile_num(obj->obj_n)+obj->frame_n); if(tile->flags3 & TILEFLAG_FORCED_PASSABLE) return true; } } return false; } bool ObjManager::is_door(uint16 x, uint16 y, uint8 level) { U6LList *obj_list = get_obj_list(x, y, level); U6Link *link; Obj *obj; if (obj_list) { for (link = obj_list->start(); link != NULL; link = link->next) { obj = (Obj *)link->data; if (usecode->is_door(obj)) return true; } } return false; } bool ObjManager::is_damaging(uint16 x, uint16 y, uint8 level) { U6LList *obj_list; U6Link *link; Obj *obj; Tile *tile; obj_list = get_obj_list(x,y,level); if(obj_list) { for(link=obj_list->start();link!=NULL;link=link->next) { obj = (Obj *)link->data; tile = tile_manager->get_original_tile(get_obj_tile_num(obj->obj_n)+obj->frame_n);//get_tile(get_obj_tile_num(obj->obj_n)+obj->frame_n); if(tile->flags1 & TILEFLAG_DAMAGING) return true; } } return false; } bool ObjManager::is_stackable(Obj *obj) { // Tile *tile; if(obj == NULL) return false; if(obj->is_readied()) // readied objects cannot be stacked --SB-X return false; /* tile = tile_manager->get_tile(get_obj_tile_num(obj->obj_n)+obj->frame_n); if(tile_manager->tile_is_stackable(tile->tile_num)) return true; return false; */ if(game_type==NUVIE_GAME_U6) { switch (obj->obj_n) { case OBJ_U6_TORCH: // 0x5A, // torch if(obj->frame_n == 1) { return false; } else { return true; } case OBJ_U6_LOCK_PICK: // 0x3F, // lock pick case OBJ_U6_GEM: // 0x4D, // gem case OBJ_U6_ARROW: // 0x37, // arrow case OBJ_U6_BOLT: // 0x38, // bolt case OBJ_U6_BLACK_PEARL: // 0x41, // black pearl case OBJ_U6_BLOOD_MOSS: // 0x42, // bit of blood moss case OBJ_U6_GARLIC: // 0x43, // bulb of garlic case OBJ_U6_GINSENG: // 0x44, // ginseng root case OBJ_U6_MANDRAKE_ROOT: // 0x45, // mandrake root case OBJ_U6_NIGHTSHADE: // 0x46, // nightshade mushroom case OBJ_U6_SPIDER_SILK: // 0x47, // strand of spidersilk case OBJ_U6_SULFUROUS_ASH: // 0x48, // bit of sulfurous ash case OBJ_U6_EFFECT: // 0x151, // effect case OBJ_U6_BREAD: // 0x80, // loaf of bread case OBJ_U6_MEAT_PORTION: // 0x81, // portion of meat case OBJ_U6_FLASK_OF_OIL: // 0x53, // flask of oil case OBJ_U6_EGG: // 0x14F, // egg case OBJ_U6_GOLD_NUGGET: // 0x59, // gold nugget case OBJ_U6_ZU_YLEM: // 0x5B, // Zu Ylem case OBJ_U6_SNAKE_VENOM: // 0x5C, // silver snake venom case OBJ_U6_GOLD: // 0x58 // Gold coin return true; default: return false; } } if(game_type==NUVIE_GAME_SE) { switch (obj->obj_n) { case OBJ_SE_MAGNESIUM_RIBBON: case OBJ_SE_SPEAR: case OBJ_SE_THROWING_AXE: case OBJ_SE_POISONED_DART: case OBJ_SE_RIFLE_BULLET: case OBJ_SE_KNIFE: case OBJ_SE_ARROW: case OBJ_SE_TURTLE_BAIT: case OBJ_SE_FEATHER: case OBJ_SE_CHOCOLATL: case OBJ_SE_PINDE: case OBJ_SE_YOPO: case OBJ_SE_GOLD: case OBJ_SE_GOLD_NUGGET: case OBJ_SE_DIAMOND: case OBJ_SE_EMERALD: case OBJ_SE_RUBY: case OBJ_SE_CORN_MEAL: case OBJ_SE_TORTILLA: case OBJ_SE_MEAT_103: case OBJ_SE_BERRY: case OBJ_SE_CAKE: case OBJ_SE_CORN: case OBJ_SE_BEAN: case OBJ_SE_MEAT_110: case OBJ_SE_ORCHID: case OBJ_SE_PEPPER: case OBJ_SE_SULFUR: case OBJ_SE_CHARCOAL: case OBJ_SE_POTASSIUM_NITRATE: case OBJ_SE_SOFT_CLAY_POT: case OBJ_SE_FIRED_CLAY_POT: case OBJ_SE_CLOTH_STRIP: case OBJ_SE_GRENADE: case OBJ_SE_TAR: case OBJ_SE_WATER: case OBJ_SE_CLOTH: case OBJ_SE_TARRED_CLOTH_STRIP: case OBJ_SE_CLAY: case OBJ_SE_GUNPOWDER: case OBJ_SE_BRANCH: case OBJ_SE_TORCH: case OBJ_SE_FLAX: case OBJ_SE_RIB_BONE: case OBJ_SE_CHOP: case OBJ_SE_DEVICE: return true; default: return false; } } if(game_type == NUVIE_GAME_MD) { switch (obj->obj_n) { case OBJ_MD_PISTOL_ROUND: case OBJ_MD_SHOTGUN_SHELL: case OBJ_MD_RIFLE_ROUND: case OBJ_MD_ELEPHANT_GUN_ROUND: case OBJ_MD_SLING_STONE: case OBJ_MD_ARROW: case OBJ_MD_CAN_OF_LAMP_OIL: case OBJ_MD_MATCH: case OBJ_MD_TORCH: case OBJ_MD_BLOB_OF_OXIUM: case OBJ_MD_BERRY: case OBJ_MD_BERRY1: case OBJ_MD_BERRY2: case OBJ_MD_BERRY4: case OBJ_MD_CHIP_OF_RADIUM: case OBJ_MD_DOLLAR: case OBJ_MD_RUBLE: case OBJ_MD_WORMSBANE_SEED: case OBJ_MD_PAGE: case OBJ_MD_BERRY3: case OBJ_MD_OXYGENATED_AIR_BOTTLE: return true; default: return false; } } return (bool)obj_stackable[obj->obj_n]; } bool ObjManager::is_breakable(Obj *obj) { if(game_type==NUVIE_GAME_U6) { switch (obj->obj_n) { case OBJ_U6_FLASK_OF_OIL: case OBJ_U6_SNAKE_VENOM: case OBJ_U6_CRYSTAL_BALL: case OBJ_U6_MIRROR: case OBJ_U6_WINE: case OBJ_U6_MEAD: case OBJ_U6_ALE: case OBJ_U6_WINE_GLASS: case OBJ_U6_PLATE: case OBJ_U6_MUG: case OBJ_U6_HONEY_JAR: case OBJ_U6_JAR_OF_HONEY: case OBJ_U6_POTION: case OBJ_U6_WATER_VASE: case OBJ_U6_DRAGON_EGG: return true; default: break; } } else if(game_type==NUVIE_GAME_SE) { switch (obj->obj_n) { case OBJ_SE_MORTAR: case OBJ_SE_GRINDING_STONE: case OBJ_SE_JUG_OF_PLACHTA: case OBJ_SE_BOTTLE_OF_LIQUOR: case OBJ_SE_JAR: case OBJ_SE_FIRED_CLAY_POT: case OBJ_SE_GRENADE: case OBJ_SE_JUG: case OBJ_SE_POT: return true; default: break; } } return false; } bool ObjManager::can_store_obj(Obj *target, Obj *src) { if(target == src || !can_get_obj(src) || target == NULL) return false; if(game_type==NUVIE_GAME_U6) { if(src->obj_n == OBJ_U6_TRAP) return false; if(target->obj_n == OBJ_U6_BAG || target->obj_n == OBJ_U6_BACKPACK || target->obj_n == OBJ_U6_BASKET || (target->obj_n == OBJ_U6_CRATE && target->frame_n == 0) || (target->obj_n == OBJ_U6_BARREL && target->frame_n == 0) || (target->obj_n == OBJ_U6_CHEST && target->frame_n == 0) || (target->obj_n == OBJ_U6_SPELLBOOK && src->obj_n == OBJ_U6_SPELL && !target->find_in_container(OBJ_U6_SPELL, src->quality) && !target->find_in_container(OBJ_U6_SPELL, 255)) // this quality contains all spells || (target->obj_n == OBJ_U6_VORTEX_CUBE && src->obj_n == OBJ_U6_MOONSTONE)) return true; if((target->is_in_inventory() || Game::get_game()->doubleclick_opens_containers()) && ((target->obj_n == OBJ_U6_CHEST && target->frame_n == 1) || target->obj_n == OBJ_U6_DEAD_BODY || target->obj_n == OBJ_U6_MOUSE || target->obj_n == OBJ_U6_REMAINS || target->obj_n == OBJ_U6_DRAKE || target->obj_n == OBJ_U6_MONGBAT)) return true; if(Game::get_game()->doubleclick_opens_containers() && (target->obj_n == OBJ_U6_DESK || target->obj_n == OBJ_U6_DRAWER || target->obj_n == OBJ_U6_GRAVE || target->obj_n == OBJ_U6_REAPER || target->obj_n == OBJ_U6_DEAD_GARGOYLE || target->obj_n == OBJ_U6_DEAD_CYCLOPS)) return true; } else if(game_type==NUVIE_GAME_SE) { if(src->has_container() || usecode->is_container(src)) return false; if(target->obj_n == OBJ_SE_JUG || target->obj_n == OBJ_SE_POUCH || target->obj_n == OBJ_SE_BASKET || target->obj_n == OBJ_SE_POT) return true; if(target->obj_n == OBJ_SE_MORTAR || target->obj_n == OBJ_SE_GRINDING_STONE || target->obj_n == OBJ_SE_JAR) { switch (src->obj_n) { case OBJ_SE_MAGNESIUM_RIBBON: case OBJ_SE_CHOCOLATL: case OBJ_SE_PINDE: case OBJ_SE_YOPO: case OBJ_SE_CORN_MEAL: case OBJ_SE_CORN: case OBJ_SE_SULFUR: case OBJ_SE_CHARCOAL: case OBJ_SE_POTASSIUM_NITRATE: case OBJ_SE_GUNPOWDER: if(target->obj_n == OBJ_SE_JAR) { if(target->container_count_objects() == 0 || // only allow one object target->find_in_container(src->obj_n, src->quality)) return true; else return false; } return true; default: return false; } } } else // MD { if(src->has_container() || usecode->is_container(src)) return false; switch (target->obj_n) { case OBJ_MD_BRASS_CHEST: case OBJ_MD_OBSIDIAN_BOX: case OBJ_MD_WOODEN_CRATE: case OBJ_MD_STEAMER_TRUNK: case OBJ_MD_BARREL: case OBJ_MD_CRATE: case OBJ_MD_BRASS_TRUNK: if(target->frame_n == 0) { return true; } else return false; case OBJ_MD_BACKPACK: case OBJ_MD_LARGE_SACK: case OBJ_MD_SMALL_POUCH: case OBJ_MD_CARPET_BAG: case OBJ_MD_BAG: case OBJ_MD_LEAD_BOX: return true; default: return false; } } return false; } bool ObjManager::can_get_obj(Obj *obj) { // objects with 0 weight aren't gettable. //255 is the max weight and means an object is movable but not getable. //we can't get object that contains toptiles either. This makes dragon bits ungettable etc. // excluding container items here, we just want the object itself to // check if it weighs 0 or 255. no need to scale as we don't compare // with other weights if(obj == NULL) return false; if(Game::get_game()->get_script()->call_can_get_obj_override(obj)) return true; float weight = get_obj_weight(obj, OBJ_WEIGHT_EXCLUDE_CONTAINER_ITEMS,OBJ_WEIGHT_DONT_SCALE, OBJ_WEIGHT_EXCLUDE_QTY); if((weight != 0 && weight != 255 && has_toptile(obj) == false && (!obj->is_on_map() || !Game::get_game()->get_map_window()->tile_is_black(obj->x, obj->y, obj))) || Game::get_game()->using_hackmove()) return true; return false; } bool ObjManager::has_reduced_weight(uint16 obj_n) { // FIXME: HERE BE HARDCODED VALUES! FIXME: not sure if this list is complete! if (game_type==NUVIE_GAME_U6) // luteijn: I only know about U6... { if ( (obj_n == OBJ_U6_GOLD) || (obj_n == OBJ_U6_BLACK_PEARL) // not using range because don't want to depend on underlying magic numbers relations || (obj_n == OBJ_U6_BLOOD_MOSS) || (obj_n == OBJ_U6_GARLIC) || (obj_n == OBJ_U6_GINSENG) || (obj_n == OBJ_U6_MANDRAKE_ROOT) || (obj_n == OBJ_U6_NIGHTSHADE) || (obj_n == OBJ_U6_SPIDER_SILK) || (obj_n == OBJ_U6_SULFUROUS_ASH) ) { return true; } } else if(game_type==NUVIE_GAME_SE) { switch (obj_n) { case OBJ_SE_RIFLE_BULLET: case OBJ_SE_FEATHER: case OBJ_SE_CHOCOLATL: case OBJ_SE_PINDE: case OBJ_SE_YOPO: case OBJ_SE_GOLD: case OBJ_SE_DIAMOND: case OBJ_SE_EMERALD: case OBJ_SE_RUBY: case OBJ_SE_PEPPER: case OBJ_SE_SULFUR: case OBJ_SE_CHARCOAL: case OBJ_SE_POTASSIUM_NITRATE: case OBJ_SE_CLOTH_STRIP: return true; default: return false; } } else if(game_type==NUVIE_GAME_MD) { switch(obj_n) { case OBJ_MD_PISTOL_ROUND: case OBJ_MD_SHOTGUN_SHELL: case OBJ_MD_RIFLE_ROUND: case OBJ_MD_ELEPHANT_GUN_ROUND: case OBJ_MD_SLING_STONE: case OBJ_MD_ARROW: case OBJ_MD_POCKETWATCH: case OBJ_MD_SPECTACLES: case OBJ_MD_MASONIC_SYMBOL: case OBJ_MD_MATCH: case OBJ_MD_BLOB_OF_OXIUM: case OBJ_MD_BERRY: case OBJ_MD_BERRY1: case OBJ_MD_BERRY2: case OBJ_MD_BERRY4: case OBJ_MD_DREAMSTUFF: case OBJ_MD_DOLLAR: case OBJ_MD_RUBLE: return true; default: return false; } } return false; } bool ObjManager::has_toptile(Obj *obj) { Tile *tile; uint8 i = 1; tile = tile_manager->get_tile(get_obj_tile_num(obj->obj_n)+obj->frame_n); if(tile->dbl_width) i++; if(tile->dbl_height) i++; if(tile->dbl_width && tile->dbl_height) i++; for(; i > 0; i--) { if(tile->toptile) return true; if(i != 1) tile = tile_manager->get_tile(tile->tile_num - 1); } return false; } //gets the linked list of objects at a particular location. U6LList *ObjManager::get_obj_list(uint16 x, uint16 y, uint8 level) { iAVLTree *obj_tree; iAVLKey key; ObjTreeNode *item; WRAP_COORD(x,level); // wrap on map edge WRAP_COORD(y,level); obj_tree = get_obj_tree(x,y,level); key = get_obj_tree_key(x,y,level); item = (ObjTreeNode *)iAVLSearch(obj_tree,key); if(item) return item->obj_list; return NULL; } Tile *ObjManager::get_obj_tile(uint16 obj_n, uint8 frame_n) { return tile_manager->get_tile(get_obj_tile_num(obj_n)+frame_n); } Tile *ObjManager::get_obj_tile(uint16 x, uint16 y, uint8 level, bool top_obj) { Obj *obj; Tile *tile; uint16 tile_num; obj = get_obj(x,y,level, top_obj); if(obj == NULL) return NULL; tile_num = get_obj_tile_num(obj->obj_n)+obj->frame_n; tile = tile_manager->get_tile(tile_num); if(tile->dbl_width && obj->x == x+1 && obj->y == y) tile_num--; if(tile->dbl_height && obj->x == x && obj->y == y+1) tile_num--; if(obj->x == x+1 && obj->y == y+1 && tile->dbl_width && tile->dbl_height) tile_num -= 2; return tile_manager->get_original_tile(tile_num); } Tile *ObjManager::get_obj_dmg_tile(uint16 x, uint16 y, uint8 level) { Tile *tile; U6LList *obj_list; U6Link *link; Obj *obj = NULL; obj_list = get_obj_list(x,y,level); if(obj_list != NULL) { for(link=obj_list->end();link != NULL; link=link->prev) { obj = (Obj *)link->data; tile = tile_manager->get_original_tile(get_obj_tile_num(obj->obj_n)+obj->frame_n); if(tile->damages == true) return tile; } } return NULL; } bool ObjManager::obj_is_damaging(Obj *obj, Actor *actor) { if(!obj) return false; Tile *tile = tile_manager->get_original_tile(get_obj_tile_num(obj->obj_n)+obj->frame_n); if(tile && tile->damages == true) { if(actor) { MsgScroll *scroll = Game::get_game()->get_scroll(); scroll->display_string("\n\nNot possible\n"); Game::get_game()->get_script()->call_actor_tile_dmg(actor, tile->tile_num); actor->display_condition(); // indicate that object hurt the player scroll->display_string("\n"); scroll->display_prompt(); } return true; } else return false; } Obj *ObjManager::get_obj(uint16 x, uint16 y, uint8 level, bool top_obj, bool include_ignored_objects, Obj *excluded_obj) { Obj *obj; Tile *tile; obj = get_objBasedAt(x,y,level,top_obj,include_ignored_objects, excluded_obj); if(obj != NULL) return obj; obj = get_objBasedAt(x+1,y+1,level,top_obj,include_ignored_objects, excluded_obj); if(obj != NULL) { tile = tile_manager->get_tile(get_obj_tile_num(obj->obj_n)+obj->frame_n); if(tile->dbl_width && tile->dbl_height) return obj; } obj = get_objBasedAt(x,y+1,level,top_obj,include_ignored_objects, excluded_obj); if(obj != NULL) { tile = tile_manager->get_tile(get_obj_tile_num(obj->obj_n)+obj->frame_n); if(tile->dbl_height) return obj; } obj = get_objBasedAt(x+1,y,level,top_obj,include_ignored_objects, excluded_obj); if(obj != NULL) { tile = tile_manager->get_tile(get_obj_tile_num(obj->obj_n)+obj->frame_n); if(tile->dbl_width) return obj; } return NULL; } Obj *ObjManager::get_obj_of_type_from_location_inc_multi_tile(uint16 obj_n, uint16 x, uint16 y, uint8 z) { return get_obj_of_type_from_location_inc_multi_tile(obj_n, -1, -1, x, y, z); } Obj *ObjManager::get_obj_of_type_from_location_inc_multi_tile(uint16 obj_n, sint16 quality, sint32 qty, uint16 x, uint16 y, uint8 z) { Obj *obj; Tile *tile; obj = get_obj_of_type_from_location(obj_n, quality, qty, x, y, z); if(obj != NULL) return obj; obj = get_obj_of_type_from_location(obj_n, quality, qty, x+1, y+1, z); if(obj != NULL) { tile = tile_manager->get_tile(get_obj_tile_num(obj->obj_n)+obj->frame_n); if(tile->dbl_width && tile->dbl_height) return obj; } obj = get_obj_of_type_from_location(obj_n, quality, qty, x, y+1, z); if(obj != NULL) { tile = tile_manager->get_tile(get_obj_tile_num(obj->obj_n)+obj->frame_n); if(tile->dbl_height) return obj; } obj = get_obj_of_type_from_location(obj_n, quality, qty, x+1, y, z); if(obj != NULL) { tile = tile_manager->get_tile(get_obj_tile_num(obj->obj_n)+obj->frame_n); if(tile->dbl_width) return obj; } return NULL; } Obj *ObjManager::get_obj_of_type_from_location(uint16 obj_n, uint16 x, uint16 y, uint8 z) { return get_obj_of_type_from_location(obj_n, -1, -1, x, y, z); } Obj *ObjManager::get_obj_of_type_from_location(uint16 obj_n, sint16 quality, sint32 qty, uint16 x, uint16 y, uint8 z) { U6LList *obj_list; U6Link *link; Obj *obj; obj_list = get_obj_list(x,y,z); if(obj_list == NULL) return NULL; // start from the top of the stack for(link=obj_list->end();link != NULL; link=link->prev) { obj = (Obj *)link->data; if(obj->obj_n == obj_n) { if(quality != -1 && obj->quality != (uint8)quality) continue; if(qty != -1 && obj->qty != (uint16)qty) continue; return obj; } } return NULL; } // x, y in world coords Obj *ObjManager::get_objBasedAt(uint16 x, uint16 y, uint8 level, bool top_obj, bool include_ignored_objects, Obj *excluded_obj) { U6Link *link; U6LList *obj_list; Obj *obj; obj_list = get_obj_list(x,y,level); if(obj_list != NULL) { if(top_obj) link = obj_list->end(); else link = obj_list->start(); while(link != NULL) { obj = (Obj *)link->data; if(obj != excluded_obj) { if(include_ignored_objects) return obj; Tile *tile = get_obj_tile(obj->obj_n, obj->frame_n); if ((tile->flags3 & TILEFLAG_IGNORE) != TILEFLAG_IGNORE) return obj; } if(top_obj) link = link->prev; else link = link->next; } } return NULL; } // ObjManager keeps one instance of tile_obj per object. // SE has 3 tile objects (Trees, Yucca Plants, and Oven Fires) Obj *ObjManager::get_tile_obj(uint16 obj_n) { for (std::list<Obj *>::iterator it = tile_obj_list.begin(); it != tile_obj_list.end(); ++it) { if ((*it)->obj_n == obj_n) { return *it; } } Obj *obj = new Obj(); obj->obj_n = obj_n; obj->set_on_map(NULL); tile_obj_list.push_back(obj); return obj; } /* bool ObjManager::add_obj(Obj *obj, bool addOnTop) { return add_obj(get_obj_tree(obj->x,obj->y,obj->z), obj, addOnTop); } */ bool ObjManager::remove_obj_from_map(Obj *obj) { U6LList *obj_list; if(obj->get_engine_loc() != OBJ_LOC_MAP) return false; obj_list = (U6LList *)obj->parent; if(obj_list == NULL) return false; obj_list->remove(obj); remove_obj(obj); return true; } void ObjManager::remove_obj(Obj *obj) { if(obj->status & OBJ_STATUS_TEMPORARY) temp_obj_list_remove(obj); if(obj->obj_n == obj_egg_table[game_type]) { egg_manager->remove_egg(obj); } obj->set_noloc(); return; } // remove all objects of type obj_n from location (x,y,z) bool ObjManager::remove_obj_type_from_location(uint16 obj_n, uint16 x, uint16 y, uint8 z) { U6LList *obj_list; U6Link *link; Obj *obj; bool objects_deleted = false; obj_list = get_obj_list(x,y,z); if(obj_list != NULL) { for(link=obj_list->start();link != NULL; ) { obj = (Obj *)link->data; link=link->next; if(obj->obj_n == obj_n) { remove_obj_from_map(obj); delete_obj(obj); objects_deleted = true; } } } return objects_deleted; } Obj *ObjManager::copy_obj(Obj *obj) { Obj *new_obj; if(obj == NULL) return NULL; new_obj = new Obj(*obj); /* changed to direct copy in case we add new members to Obj --SB-X new_obj->obj_n = obj->obj_n; new_obj->frame_n = obj->frame_n; new_obj->status = obj->status; new_obj->qty = obj->qty; new_obj->quality = obj->quality; new_obj->x = obj->x; new_obj->y = obj->y; new_obj->z = obj->z;*/ // should we copy container??? new_obj->container = 0; return new_obj; } bool ObjManager::move(Obj *obj, uint16 x, uint16 y, uint8 level) { if(remove_obj_from_map(obj) == false) return false; obj->x = x; obj->y = y; obj->z = level; add_obj(obj,true); // add the object on top of the stack return true; } /* Returns an objects look-string, its general description. */ const char *ObjManager::look_obj(Obj *obj, bool show_prefix) { const char *desc; if(obj == NULL) return NULL; desc = tile_manager->lookAtTile(get_obj_tile_num(obj)+obj->frame_n,obj->qty,show_prefix); return desc; } const char *ObjManager::get_obj_name(Obj *obj) { return tile_manager->lookAtTile(get_obj_tile_num(obj->obj_n),0,false); } const char *ObjManager::get_obj_name(uint16 obj_n) { return tile_manager->lookAtTile(get_obj_tile_num(obj_n),0,false); } const char *ObjManager::get_obj_name(uint16 obj_n, uint8 frame_n) { return tile_manager->lookAtTile(get_obj_tile_num(obj_n)+frame_n,0,false); } float ObjManager::get_obj_weight(uint16 obj_n) { float weight = (float)get_obj_weight_unscaled(obj_n); if(has_reduced_weight(obj_n)) { weight /= 10; } return weight / 10; } float ObjManager::get_obj_weight(Obj *obj, bool include_container_items, bool scale, bool include_qty) { float weight; U6Link *link; weight = obj_weight[obj->obj_n]; if(is_stackable(obj)) { if(include_qty) { if(obj->qty == 0) obj->qty = 1; weight *= obj->qty; } /* luteijn: only some need to be divided by an extra 10 for a total of 100. * unfortunately can't seem to find a tileflag that controls this so would have to be hardcoded! */ if (has_reduced_weight(obj)) { weight /= 10; // luteijn: regardless of the scaling flag! } } if(obj->container != NULL && include_container_items == OBJ_WEIGHT_INCLUDE_CONTAINER_ITEMS) { for(link=obj->container->start();link != NULL;link=link->next) /* weight += get_obj_weight(reinterpret_cast<Obj*>(link->data), false);*/ //don't scale container objects yet. weight += get_obj_weight(reinterpret_cast<Obj*>(link->data), OBJ_WEIGHT_INCLUDE_CONTAINER_ITEMS, OBJ_WEIGHT_DONT_SCALE); //don't scale container objects yet. luteijn: and use the right flag to do so! } if(scale == OBJ_WEIGHT_DO_SCALE) { weight /= 10; } return weight; } uint16 ObjManager::get_obj_tile_num(uint16 obj_num) //assume obj_num is < 1024 :) { return obj_to_tile[obj_num]; } inline bool ObjManager::is_corpse(Obj *obj) { if(game_type == NUVIE_GAME_U6) { switch(obj->obj_n) { case OBJ_U6_DEAD_BODY: case OBJ_U6_DEAD_CYCLOPS: case OBJ_U6_DEAD_GARGOYLE: case OBJ_U6_DOG: // Kador id_n 135 case OBJ_U6_MOUSE: // Sherry id_n 9 case OBJ_U6_HORSE_CARCASS: // Pushme Pullyu id 130, Smith id 132 return true; default: break; } } else if(game_type == NUVIE_GAME_SE) { switch(obj->obj_n) { // TODO - add SE body obj numbers default: break; } } else { // MD switch(obj->obj_n) { // TODO - add MD body obj numbers default: break; } } return false; } uint16 ObjManager::get_obj_tile_num(Obj *obj) //assume obj_num is < 1024 :) { if(custom_actor_tiles && is_corpse(obj)) { return Game::get_game()->get_actor_manager()->get_actor(obj->quality)->get_custom_tile_num(obj->obj_n); } uint16 obj_num = obj->obj_n; // Savage Empire Tile Object (Get Tile from Map Location) if (game_type == NUVIE_GAME_SE && Game::get_game()->get_script()->call_is_tile_object(obj_num)) { return(Game::get_game()->get_game_map()->get_tile(obj->x, obj->y, obj->z)->tile_num); } return get_obj_tile_num(obj_num); } void ObjManager::set_obj_tile_num(uint16 obj_num, uint16 tile_num) { obj_to_tile[obj_num] = tile_num; return; } /* Animate all visible tiles of an object `loop_count' times. */ void ObjManager::animate_forwards(Obj *obj, uint32 loop_count) { // In U6 there is no place where one object must animate and nearby objects // of the same type don't also animate, so just forward to TileManager. tile_manager->set_anim_loop(get_obj_tile_num(obj->obj_n), loop_count, 0); } /* Animate in reverse all visible tiles of an object `loop_count' times. */ void ObjManager::animate_backwards(Obj *obj, uint32 loop_count) { tile_manager->set_anim_loop(get_obj_tile_num(obj->obj_n), loop_count, 1); } U6LList *ObjManager::get_actor_inventory(uint16 actor_num) { if(actor_num >= 256) return NULL; if(actor_inventories[actor_num] == NULL) { actor_inventories[actor_num] = new U6LList(); } return actor_inventories[actor_num]; } bool ObjManager::actor_has_inventory(uint16 actor_num) { if(actor_inventories[actor_num] != NULL) { if(actor_inventories[actor_num]->start() != NULL) return true; } return false; } Obj *ObjManager::find_next_obj(uint8 level, Obj *prev_obj, bool match_frame_n, bool match_quality) { if(prev_obj == NULL) return NULL; Obj **p = &prev_obj; return find_obj(level, prev_obj->obj_n, prev_obj->quality, match_quality, prev_obj->frame_n, match_frame_n, p); } Obj *ObjManager::find_obj(uint8 level, uint16 obj_n, uint8 quality, bool match_quality, uint16 frame_n, bool match_frame_n, Obj **prev_obj) { uint8 i; Obj *new_obj; if(level == 0) { for(i=0;i<64;i++) { new_obj = find_obj_in_tree(obj_n, quality, match_quality, frame_n, match_frame_n, prev_obj, surface[i]); if(new_obj != NULL) return new_obj; } } else { new_obj = find_obj_in_tree(obj_n, quality, match_quality, frame_n, match_frame_n, prev_obj, dungeon[level-1]); if(new_obj != NULL) return new_obj; } return NULL; } inline Obj *ObjManager::find_obj_in_tree(uint16 obj_n, uint8 quality, bool match_quality, uint8 frame_n, bool match_frame_n, Obj **prev_obj, iAVLTree *obj_tree) { iAVLCursor cursor; ObjTreeNode *node; U6Link *link; Obj *new_obj; node = (ObjTreeNode *)iAVLFirst(&cursor,obj_tree); for(;node != NULL;) { link = ((U6LList *)(node->obj_list))->start(); for(;link != NULL;link=link->next) { new_obj = (Obj *)link->data; if( new_obj->obj_n == obj_n && (match_quality == false || new_obj->quality == quality) && (match_frame_n == false || new_obj->frame_n == frame_n)) { if(prev_obj != NULL && new_obj == *prev_obj) *prev_obj = NULL; else { if(prev_obj == NULL || *prev_obj == NULL) return new_obj; } } /* Don't search containers. if(prev_obj == NULL) { new_obj = new_obj->find_in_container(obj_n, quality, match_quality, frame_n, match_frame_n, prev_obj); if(new_obj) return new_obj; } */ } node = (ObjTreeNode *)iAVLNext(&cursor); } return NULL; } bool ObjManager::add_obj(Obj *obj, bool addOnTop) { iAVLTree *obj_tree; ObjTreeNode *node; U6LList *obj_list; iAVLKey key; obj_tree = get_obj_tree(obj->x, obj->y, obj->z); key = get_obj_tree_key(obj); node = (ObjTreeNode *)iAVLSearch(obj_tree,key); if(node == NULL) { obj_list = new U6LList(); node = new ObjTreeNode; node->key = key; node->obj_list = obj_list; iAVLInsert(obj_tree, node); } else { obj_list = node->obj_list; } if(addOnTop) obj_list->add(obj); else obj_list->addAtPos(0,obj); if(obj->status & OBJ_STATUS_TEMPORARY) temp_obj_list_add(obj); obj->set_on_map(obj_list); //mark object as on map. return true; } bool ObjManager::addObjToContainer(U6LList *llist, Obj *obj) { U6Link *link; Obj *c_obj = NULL; //container object uint16 index; index = ((obj->y & 0x3f) << 10) + obj->x; //10 bits from x and 6 bits from y link = llist->gotoPos(index); if(link != NULL) c_obj = (Obj *)link->data; if(c_obj) // we've found our container. { c_obj->add(obj); //DEBUG(0,LEVEL_DEBUGGING,"Cont: %s\n", tile_manager->lookAtTile(get_obj_tile_num(c_obj->obj_n)+c_obj->frame_n,0,false)); //DEBUG(0,LEVEL_DEBUGGING,"Add to container %s", tile_manager->lookAtTile(get_obj_tile_num(obj->obj_n)+obj->frame_n,0,false)); //DEBUG(1,LEVEL_DEBUGGING," -> %s (%x,%x,%x)\n", tile_manager->lookAtTile(get_obj_tile_num(c_obj->obj_n)+c_obj->frame_n,0,false),c_obj->x,c_obj->y,c_obj->z); return true; } return false; } Obj *ObjManager::loadObj(NuvieIO *buf) { uint8 b1,b2; Obj *obj; obj = new Obj(); //obj->objblk_n = objblk_n; obj->status = buf->read1(); //set new nuvie location bits. switch(obj->status & OBJ_STATUS_MASK_GET) { case OBJ_STATUS_ON_MAP : obj->set_on_map(NULL); break;//obj->nuvie_status |= OBJ_LOC_MAP; break; case OBJ_STATUS_IN_CONTAINER : obj->set_in_container(NULL); break;//obj->nuvie_status |= OBJ_LOC_CONT; break; case OBJ_STATUS_IN_INVENTORY : obj->set_in_inventory(); break;//obj->nuvie_status |= OBJ_LOC_INV; break; case OBJ_STATUS_READIED : obj->readied(); break;//obj->nuvie_status |= OBJ_LOC_READIED; break; } obj->x = buf->read1(); // h b1 = buf->read1(); obj->x += (b1 & 0x3) << 8; obj->y = (b1 & 0xfc) >> 2; b2 = buf->read1(); obj->y += (b2 & 0xf) << 6; obj->z = (b2 & 0xf0) >> 4; b1 = buf->read1(); b2 = buf->read1(); obj->obj_n = b1; obj->obj_n += (b2 & 0x3) << 8; obj->frame_n = (b2 & 0xfc) >> 2; obj->qty = buf->read1(); obj->quality = buf->read1(); if(is_stackable(obj)) obj->qty = (uint16)(obj->quality << 8) + obj->qty; //if(obj->qty == 0) // obj->qty = 1; return obj; } iAVLTree *ObjManager::get_obj_tree(uint16 x, uint16 y, uint8 level) { if(level == 0) { x >>= 7; // x = floor(x / 128) 128 = superchunk width y >>= 7; // y = floor(y / 128) 128 = superchunk height return surface[x + y * 8]; } if(level > 5) return NULL; return dungeon[level-1]; } inline iAVLKey ObjManager::get_obj_tree_key(Obj *obj) { return get_obj_tree_key(obj->x, obj->y, obj->z); } iAVLKey ObjManager::get_obj_tree_key(uint16 x, uint16 y, uint8 level) { if(level == 0) return y * 1024 + x; else return y * 256 + x; } void ObjManager::update(uint16 x, uint16 y, uint8 z, bool teleport) { uint16 cur_blk_x, cur_blk_y; cur_blk_x = x >> 3; // x / 8; cur_blk_y = y >> 3; // y / 8; // We're changing levels so clean out all temp objects on the current level. if(last_obj_blk_z != z) { if(last_obj_blk_z != OBJ_TEMP_INIT) temp_obj_list_clean_level(last_obj_blk_z); egg_manager->spawn_eggs(x, y, z, teleport); last_obj_blk_x = cur_blk_x; last_obj_blk_y = cur_blk_y; last_obj_blk_z = z; return; } //FIX for level change. we want to remove all temps on level change. if(cur_blk_x != last_obj_blk_x || cur_blk_y != last_obj_blk_y) { last_obj_blk_x = cur_blk_x; last_obj_blk_y = cur_blk_y; temp_obj_list_clean_area(x, y); egg_manager->spawn_eggs(x, y, z, teleport); } return; } bool ObjManager::temp_obj_list_add(Obj *obj) { if(obj == NULL) return false; temp_obj_list.push_back(obj); return true; } bool ObjManager::temp_obj_list_remove(Obj *obj) { temp_obj_list.remove(obj); return true; } void ObjManager::remove_temp_obj(Obj *tmp_obj) { //FIXME MD has special temp object flag override logic. This should be implemented in lua script. if(game_type != NUVIE_GAME_MD || (tmp_obj->obj_n != OBJ_MD_DREAM_TELEPORTER && tmp_obj->frame_n != 0)) { DEBUG(0, LEVEL_DEBUGGING, "Removing obj %s.\n", tile_manager->lookAtTile(get_obj_tile_num((tmp_obj)->obj_n) + (tmp_obj)->frame_n, 0, false)); remove_obj_from_map(tmp_obj); delete_obj(tmp_obj); } } // clean objects from a whole level. void ObjManager::temp_obj_list_clean_level(uint8 z) { std::list<Obj *>::iterator obj; Obj *tmp_obj; for(obj = temp_obj_list.begin(); obj != temp_obj_list.end();) { if((*obj)->z == z) { tmp_obj = *obj++; remove_temp_obj(tmp_obj); } else obj++; } return; } // Clean objects more than 19 tiles from position void ObjManager::temp_obj_list_clean_area(uint16 x, uint16 y) { std::list<Obj *>::iterator obj; Obj *tmp_obj; sint16 dist_x, dist_y; for(obj = temp_obj_list.begin(); obj != temp_obj_list.end();) { dist_x = abs((sint16)(*obj)->x - x); dist_y = abs((sint16)(*obj)->y - y); if(dist_x > 19 || dist_y > 19) { tmp_obj = *obj++; remove_temp_obj(tmp_obj); } else obj++; } return; } /* inline U6LList *ObjManager::get_schunk_list(uint16 x, uint16 y, uint8 level) { uint16 sx, sy; if(level == 0) { sx = x / 128; sy = y / 128; return surface[sy * 8 + sx]; } return dungeon[level-1]; } */ //prints a human readable list of object number / names. void ObjManager::print_object_list() { uint16 i; DEBUG(0,LEVEL_INFORMATIONAL,"print_object_list:\n"); for(i=0;i<1024;i++) { DEBUG(1,LEVEL_INFORMATIONAL,"%04d: %s\n",i,tile_manager->lookAtTile(get_obj_tile_num(i),0,false)); } return; } void ObjManager::print_egg_list() { uint8 i; for(i=0;i < 64;i++) print_egg_tree(surface[i]); for(i=0;i < 5;i++) print_egg_tree(dungeon[i]); return; } inline void ObjManager::print_egg_tree(iAVLTree *obj_tree) { ObjTreeNode *tree_node; iAVLCursor cursor; U6LList *obj_list; U6Link *link; Obj *obj; tree_node = (ObjTreeNode *)iAVLFirst(&cursor,obj_tree); for(;tree_node != NULL;tree_node = (ObjTreeNode *)iAVLNext(&cursor) ) { obj_list = (U6LList *)tree_node->obj_list; for(link = obj_list->start(); link != NULL; link = link->next) { obj = (Obj *)link->data; if(obj->obj_n == 335) { print_obj(obj,false); } } } return; } void ObjManager::print_obj(Obj *obj, bool in_container, uint8 indent) { U6Link *link; Obj *container_obj; const CombatType *c_type=NULL; Actor *a = Game::get_game()->get_player()->get_actor(); if(a != NULL) c_type = a->get_object_combat_type(obj->obj_n); DEBUG(1,LEVEL_INFORMATIONAL,"\n"); print_indent(LEVEL_INFORMATIONAL,indent); DEBUG(1,LEVEL_INFORMATIONAL,"%s ",tile_manager->lookAtTile(get_obj_tile_num(obj->obj_n)+obj->frame_n,0,false)); if(in_container == false) DEBUG(1,LEVEL_INFORMATIONAL,"at %x, %x, %x (%d,%d,%d)",obj->x, obj->y, obj->z, obj->x, obj->y, obj->z); DEBUG(1,LEVEL_INFORMATIONAL,"\n"); print_indent(LEVEL_INFORMATIONAL,indent); DEBUG(1,LEVEL_INFORMATIONAL,"object (Obj *) %p\n", obj); print_indent(LEVEL_INFORMATIONAL,indent); DEBUG(1,LEVEL_INFORMATIONAL,"engine loc: "); switch(obj->get_engine_loc()) { case OBJ_LOC_MAP : DEBUG(1,LEVEL_INFORMATIONAL,"MAP"); break; case OBJ_LOC_CONT : DEBUG(1,LEVEL_INFORMATIONAL,"CONTAINER"); break; case OBJ_LOC_INV : DEBUG(1,LEVEL_INFORMATIONAL,"INVENTORY"); break; case OBJ_LOC_READIED : DEBUG(1,LEVEL_INFORMATIONAL,"INVENTORY READIED"); break; case OBJ_LOC_NONE : DEBUG(1,LEVEL_INFORMATIONAL,"NONE"); break; default : DEBUG(1,LEVEL_INFORMATIONAL,"**UNKNOWN**"); break; } if(obj->is_actor_obj()) DEBUG(1,LEVEL_INFORMATIONAL," (ACTOR_OBJ)"); DEBUG(1,LEVEL_INFORMATIONAL,"\n"); DEBUG(1,LEVEL_INFORMATIONAL,"parent ("); switch(obj->get_engine_loc()) { case OBJ_LOC_MAP : DEBUG(1,LEVEL_INFORMATIONAL,"U6LList"); break; case OBJ_LOC_CONT : DEBUG(1,LEVEL_INFORMATIONAL,"Obj"); break; case OBJ_LOC_INV : case OBJ_LOC_READIED : DEBUG(1,LEVEL_INFORMATIONAL,"Actor"); break; default : DEBUG(1,LEVEL_INFORMATIONAL,"void"); break; } DEBUG(1,LEVEL_INFORMATIONAL," *) %p\n", obj->parent); print_indent(LEVEL_INFORMATIONAL,indent); // DEBUG(1,LEVEL_DEBUGGING,"objblk_n: %d\n", obj->objblk_n); print_indent(LEVEL_INFORMATIONAL,indent); DEBUG(1,LEVEL_INFORMATIONAL,"obj_n: %d\n",obj->obj_n); print_indent(LEVEL_INFORMATIONAL,indent); DEBUG(1,LEVEL_INFORMATIONAL,"frame_n: %d\n",obj->frame_n); print_indent(LEVEL_INFORMATIONAL,indent); DEBUG(1,LEVEL_INFORMATIONAL,"Tile: %d\n", get_obj_tile_num(obj->obj_n)); print_indent(LEVEL_INFORMATIONAL,indent); DEBUG(1,LEVEL_INFORMATIONAL,"Status: "); print_b(LEVEL_INFORMATIONAL,obj->status); if(obj->status != 0) { DEBUG(1,LEVEL_INFORMATIONAL," ( "); if(obj->is_readied()) DEBUG(1,LEVEL_INFORMATIONAL,"POS:Ready "); else if(obj->is_in_container()) DEBUG(1,LEVEL_INFORMATIONAL,"POS:Cont "); else if(obj->is_in_inventory()) DEBUG(1,LEVEL_INFORMATIONAL,"POS:Inv "); if(obj->is_ok_to_take()) DEBUG(1,LEVEL_INFORMATIONAL,"OK "); if(obj->is_temporary()) DEBUG(1,LEVEL_INFORMATIONAL,"TEMP "); if(obj->is_invisible()) DEBUG(1,LEVEL_INFORMATIONAL,"INVIS "); if(obj->is_egg_active()) { if(obj->obj_n < 256) DEBUG(1,LEVEL_INFORMATIONAL,"MUTANT "); else DEBUG(1,LEVEL_INFORMATIONAL,"BROKEN "); } DEBUG(1,LEVEL_INFORMATIONAL,")"); } DEBUG(1,LEVEL_INFORMATIONAL,"\n"); if(in_container) { print_indent(LEVEL_INFORMATIONAL,indent); DEBUG(1,LEVEL_INFORMATIONAL,"parent_id = %d, y = %d, z = %d\n", obj->x, obj->y, obj->z); } print_indent(LEVEL_INFORMATIONAL,indent); DEBUG(1,LEVEL_INFORMATIONAL,"Quantity: %d\n",obj->qty); print_indent(LEVEL_INFORMATIONAL,indent); DEBUG(1,LEVEL_INFORMATIONAL,"Quality: %d\n",obj->quality); if(c_type!=NULL) { DEBUG(1,LEVEL_INFORMATIONAL,"attack/damage = %d, defence/defense = %d\n", c_type->damage, c_type->defense); // FIXME add the rest of the combat values } if(obj->container) { print_indent(LEVEL_INFORMATIONAL,indent); DEBUG(1,LEVEL_INFORMATIONAL,"Container\n"); print_indent(LEVEL_INFORMATIONAL,indent); DEBUG(1,LEVEL_INFORMATIONAL,"---------"); for(link = obj->container->start(); link != NULL; link = link->next) { container_obj = (Obj *)link->data; print_obj(container_obj, true, indent + 2); } print_indent(LEVEL_INFORMATIONAL,indent); DEBUG(1,LEVEL_INFORMATIONAL,"---------\n"); } if(in_container == false) DEBUG(1,LEVEL_INFORMATIONAL,"\n"); return; } Obj *new_obj(uint16 obj_n, uint8 frame_n, uint16 x, uint16 y, uint16 z) { Obj *obj; obj = new Obj(); obj->obj_n = obj_n; obj->frame_n = frame_n; obj->x = x; obj->y = y; obj->z = z; return obj; } void delete_obj(Obj *obj) { U6Link *link; if(obj->is_script_obj() == false) { if(obj->container) { for(link=obj->container->start();link != NULL; ) { Obj *cont_obj = (Obj *)link->data; link=link->next; delete_obj(cont_obj); } } if(obj->container) delete obj->container; delete obj; } return; } // add object to list, stacking with existing objects if possible // This is used for adding objects to inventory OR a container. // *It will stack onto the new object and delete the existing object!* //FIXME!!!!! We need to set on_map() etc if going to the map. bool ObjManager::list_add_obj(U6LList *llist, Obj *obj, bool stack_objects, uint32 pos) { Obj *stack_with; uint16 new_qty; U6Link *link; if(!llist || !obj) return false; assert(pos == 0 || pos < llist->count()); if(stack_objects && is_stackable(obj)) { for(link=llist->start();link != NULL; ) { stack_with = (Obj *)link->data; link = link->next; if(stack_with->obj_n == obj->obj_n && stack_with->frame_n == obj->frame_n && stack_with->quality == obj->quality && is_stackable(stack_with)) { new_qty = obj->qty + stack_with->qty; obj->qty = new_qty; llist->addAtPos(llist->findPos(stack_with), obj); llist->remove(stack_with); delete_obj(stack_with); return true; } } } llist->addAtPos(pos,obj); return true; } /* Call load usecode for all objects (after loading them). This should be in * loadObj() but that was crashing when usecode tried to use timers. */ void ObjManager::startObjs() { uint8 i; //iterate through surface chunks. for(i = 0;i < 64; i++) start_obj_usecode(surface[i]); //iterate through dungeon chunks. for(i=0;i < 5;i++) start_obj_usecode(dungeon[i]); } inline void ObjManager::start_obj_usecode(iAVLTree *obj_tree) { ObjTreeNode *tree_node; iAVLCursor cursor; U6LList *obj_list; U6Link *link; Obj *obj; tree_node = (ObjTreeNode *)iAVLFirst(&cursor,obj_tree); for(;tree_node != NULL;tree_node = (ObjTreeNode *)iAVLNext(&cursor) ) { obj_list = (U6LList *)tree_node->obj_list; for(link = obj_list->start(); link != NULL; link = link->next) { obj = (Obj *)link->data; if(usecode->has_loadcode(obj)) usecode->load_obj(obj); } } } /* Subtract an object stack with quantity set to `count' from original object * stack `obj'. * Returns a new object if a stack could be subtracted from the original, * leaving the original intact. * Returns the original if its quantity was smaller than the requested count or * it is not stackable. */ Obj *ObjManager::get_obj_from_stack(Obj *obj, uint32 count) { if(count == 0 || obj->qty <= count || !is_stackable(obj)) return(obj); // requested is over 0, original quantity is greater than requested, object // is stackable Obj *new_obj = copy_obj(obj); new_obj->qty = count; obj->qty -= count; // remove requested from original return(new_obj); } void clean_obj_tree_node(void *node) { U6Link *link; ObjTreeNode *obj_node = (ObjTreeNode *)node; for(link=obj_node->obj_list->start();link != NULL; ) { Obj *obj = (Obj *)link->data; link=link->next; delete_obj(obj); } delete obj_node->obj_list; delete obj_node; return; } bool ObjManager::unlink_from_engine(Obj *obj, bool run_usecode) { Actor *a; Obj *cont_obj; switch(obj->get_engine_loc()) { case OBJ_LOC_NONE : break; case OBJ_LOC_MAP : remove_obj_from_map(obj); break; // inventory_remove_obj unreadies case OBJ_LOC_READIED :/* a = (Actor *)obj->parent; a->remove_readied_object(obj, run_usecode); a->inventory_remove_obj(obj, run_usecode); break; */ case OBJ_LOC_INV : a = (Actor *)obj->parent; a->inventory_remove_obj(obj, run_usecode); break; case OBJ_LOC_CONT : cont_obj = obj->get_container_obj(); if(cont_obj) cont_obj->remove(obj); //remove from parent container. break; break; } return true; } bool ObjManager::moveto_map(Obj *obj, MapCoord location) { unlink_from_engine(obj); obj->x = location.x; obj->y = location.y; obj->z = location.z; add_obj(obj, OBJ_ADD_TOP); return true; } bool ObjManager::moveto_inventory(Obj *obj, uint16 actor_num) { ActorManager *am = Game::get_game()->get_actor_manager(); if(!am) return false; return moveto_inventory(obj, am->get_actor(actor_num)); } bool ObjManager::moveto_inventory(Obj *obj, Actor *actor) { unlink_from_engine(obj); actor->inventory_add_object(obj); return true; } bool ObjManager::moveto_container(Obj *obj, Obj *container_obj, bool stack) { if(obj == container_obj) return false; unlink_from_engine(obj); container_obj->add(obj, stack); if(game_type == NUVIE_GAME_SE) { if(container_obj->obj_n == OBJ_SE_JAR) { // frame changes depending on contents switch (obj->obj_n) { case OBJ_SE_CORN_MEAL: case OBJ_SE_CORN: case OBJ_SE_SULFUR: container_obj->frame_n = 1; // yellow jar break; case OBJ_SE_MAGNESIUM_RIBBON: case OBJ_SE_POTASSIUM_NITRATE: container_obj->frame_n = 2; // white jar break; default: container_obj->frame_n = 3; // black jar break; } } } return true; }
nuvie/nuvie
ObjManager.cpp
C++
gpl-2.0
58,257
/* * Copyright (c) 2004, Bull S.A.. All rights reserved. * Created by: Sebastien Decugis * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it would be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received a copy of the GNU General Public License along * with this program; if not, write the Free Software Foundation, Inc., 59 * Temple Place - Suite 330, Boston MA 02111-1307, USA. * This sample test aims to check the following assertion: * * Memory mappings created in the parent are retained in the child process. * If the mapping is MAP_PRIVATE, any modification done after the fork() * is visible only to the process doing the modification. * The steps are: * -> create two shared memory segments. * -> mmap both segment, one is MAP_SHARED and the other MAP_PRIVATE. * -> Write some data into the segment. * -> fork * -> The child checks that the data is visible in the segments, then modifies it. * -> child terminates * -> The parent checks that the modifications are visible only in the MAP_SHARED segment. * The test fails if one of the check is not verified. */ #if __APPLE__ int main() { return 0; } #elif __ANDROID__ /* Temporarily disable it until https://tracker.crystax.net/issues/1132 is fixed */ int main() { return 0; } #else /* !__ANDROID__ */ /* We are testing conformance to IEEE Std 1003.1, 2003 Edition */ #define _POSIX_C_SOURCE 200112L /********************************************************************************************/ /****************************** standard includes *****************************************/ /********************************************************************************************/ #include <pthread.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/wait.h> #include <errno.h> #include <sys/mman.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> /********************************************************************************************/ /****************************** Test framework *****************************************/ /********************************************************************************************/ #include "testfrmw.h" #include "testfrmw.c" /* This header is responsible for defining the following macros: * UNRESOLVED(ret, descr); * where descr is a description of the error and ret is an int (error code for example) * FAILED(descr); * where descr is a short text saying why the test has failed. * PASSED(); * No parameter. * * Both three macros shall terminate the calling process. * The testcase shall not terminate in any other maneer. * * The other file defines the functions * void output_init() * void output(char * string, ...) * * Those may be used to output information. */ /********************************************************************************************/ /********************************** Configuration ******************************************/ /********************************************************************************************/ #ifndef VERBOSE #define VERBOSE 1 #endif /********************************************************************************************/ /*********************************** Test case *****************************************/ /********************************************************************************************/ /* The main test function. */ int main( int argc, char * argv[] ) { int ret, status; pid_t child, ctl; int fd_s, fd_ns; void *buf_s, *buf_ns; /* Initialize output */ output_init(); /* Create the shared memory segment */ fd_s = shm_open( "/fork_16_1s", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR ); if ( fd_s == -1 ) { UNRESOLVED( errno, "Failed to open shared memory segment" ); } fd_ns = shm_open( "/fork_16_1ns", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR ); if ( fd_ns == -1 ) { UNRESOLVED( errno, "Failed to open shared memory segment" ); } /* Size the memory segment to 1 page size. */ ret = ftruncate( fd_s, sysconf( _SC_PAGESIZE ) ); if ( ret != 0 ) { UNRESOLVED( errno, "Failed to size the shared memory segment" ); } ret = ftruncate( fd_ns, sysconf( _SC_PAGESIZE ) ); if ( ret != 0 ) { UNRESOLVED( errno, "Failed to size the shared memory segment" ); } /* Map these sengments in the process memory space */ buf_s = mmap( NULL, sysconf( _SC_PAGESIZE ), PROT_READ | PROT_WRITE, MAP_SHARED, fd_s, 0 ); if ( buf_s == MAP_FAILED ) { UNRESOLVED( errno, "Failed to mmap the shared memory segment" ); } buf_ns = mmap( NULL, sysconf( _SC_PAGESIZE ), PROT_READ | PROT_WRITE, MAP_PRIVATE, fd_ns, 0 ); if ( buf_ns == MAP_FAILED ) { UNRESOLVED( errno, "Failed to mmap the shared memory segment in MAP_PRIVATE mode" ); } /* Write some data into the buffers */ *( long * ) buf_ns = 123456L; *( long * ) buf_s = 654321L; /* Create the child */ child = fork(); if ( child == ( pid_t ) - 1 ) { UNRESOLVED( errno, "Failed to fork" ); } /* child */ if ( child == ( pid_t ) 0 ) { /* Check the values are read -- so that the mappings were inherited */ if ( ( *( long * ) buf_ns != 123456L ) || ( *( long * ) buf_s != 654321L ) ) { output( "Read values: %ld, %ld\n", *( long * ) buf_ns, *( long * ) buf_s ); FAILED( "The memory mappings were not inherited by the child process" ); } /* Now modify the values */ *( long * ) buf_ns = 100000L; *( long * ) buf_s = 200000L; /* We're done */ exit( PTS_PASS ); } /* Parent joins the child */ ctl = waitpid( child, &status, 0 ); if ( ctl != child ) { UNRESOLVED( errno, "Waitpid returned the wrong PID" ); } if ( ( !WIFEXITED( status ) ) || ( WEXITSTATUS( status ) != PTS_PASS ) ) { FAILED( "Child exited abnormally" ); } /* Check that only the MAP_SHARED segment modification is visible */ if ( ( *( long * ) buf_ns != 123456L ) || ( *( long * ) buf_s != 200000L ) ) { output( "Read values: %ld, %ld\n", *( long * ) buf_ns, *( long * ) buf_s ); FAILED( "The memory mappings were not inherited by the child process" ); } /* Free resources (everything will be removed at destruction time) */ ret = shm_unlink( "/fork_16_1ns" ); if ( ret != 0 ) { UNRESOLVED( errno, "Failed to unlink the shared memory segment" ); } ret = shm_unlink( "/fork_16_1s" ); if ( ret != 0 ) { UNRESOLVED( errno, "Failed to unlink the shared memory segment" ); } /* Test passed */ #if VERBOSE > 0 output( "Test passed\n" ); #endif PASSED; } #endif /* !__ANDROID__ */
crystax/android-vendor-openpts
conformance/interfaces/fork/16-1.c
C
gpl-2.0
6,822
# makeflow(1) ## NAME **makeflow** - workflow engine for executing distributed workflows ## SYNOPSIS ****makeflow [options] <dagfile>**** ## DESCRIPTION **Makeflow** is a workflow engine for distributed computing. It accepts a specification of a large amount of work to be performed, and runs it on remote machines in parallel where possible. In addition, **Makeflow** is fault-tolerant, so you can use it to coordinate very large tasks that may run for days or weeks in the face of failures. **Makeflow** is designed to be similar to Make, so if you can write a Makefile, then you can write a **Makeflow**. You can run a **Makeflow** on your local machine to test it out. If you have a multi-core machine, then you can run multiple tasks simultaneously. If you have a Condor pool or a Sun Grid Engine batch system, then you can send your jobs there to run. If you don't already have a batch system, **Makeflow** comes with a system called Work Queue that will let you distribute the load across any collection of machines, large or small. **Makeflow** also supports execution in a Docker container, regardless of the batch system used. ## OPTIONS When **makeflow** is ran without arguments, it will attempt to execute the workflow specified by the **Makeflow** dagfile using the **local** execution engine. ### Commands - **-c ----clean <option>** Clean up: remove logfile and all targets. If option is one of [intermediates, outputs, cache], only indicated files are removed. - **-f --summary-log <file>** Write summary of workflow to file. - **-h, --help** Show this help screen. - **-v, --version** Show version string. - **-X --chdir <directory>** Chdir to enable executing the Makefile in other directory. - **--argv file** Use command line arguments from JSON file. ### Workflow Handling - **-a, --advertise** Advertise the manager information to a catalog server. - **-l --makeflow-log <logfile>** Use this file for the makeflow log. (default is X.makeflowlog) - **-L --batch-log <logfile>** Use this file for the batch system log. (default is X.<type>log) - **-m --email <email>** Email summary of workflow to address. - **-j --max-local <#>** Max number of local jobs to run at once. (default is # of cores) - **-J --max-remote <#>** Max number of remote jobs to run at once. (default is 1000 for -Twq, 100 otherwise) - **-R, --retry** Automatically retry failed batch jobs up to 100 times. - **-r --retry-count <n>** Automatically retry failed batch jobs up to n times. - **--local-cores #** Max number of cores used for local execution. - **--local-memory #** Max amount of memory used for local execution. - **--local-disk #** Max amount of disk used for local execution. OPTION_END ### Batch Options - **-B --batch-options <options>** Add these options to all batch submit files. - **--send-environment** Send all local environment variables in remote execution. - **--wait-for-files-upto #** Wait for output files to be created upto this many seconds (e.g., to deal with NFS semantics). - **-S --submission-timeout <timeout>** Time to retry failed batch job submission. (default is 3600s) - **-T --batch-type <type>** Batch system type: local, dryrun, condor, sge, pbs, torque, blue_waters, slurm, moab, cluster, wq, amazon, mesos. (default is local) - **--safe-submit-mode** Excludes resources at submission. (SLURM, TORQUE, and PBS) - **--ignore-memory-spec** Excludes memory at submission. (SLURM) - **--batch-mem-type type** Specify memory resource type. (SGE) - **--working-dir dir|url** Working directory for batch system. - **--sandbox** Run task in sandbox using bash script and task directory. - **--verbose-jobnames** Set the job name based on the command. ### JSON/JX Options - **--json** Interpret <dagfile> as a JSON format Makeflow. - **--jx** Evaluate JX expressions in <dagfile>. Implies --json. - **--jx-args args** Read variable definitions from the JX file <args>. - **--jx-define VAL=EXPR** Set the variable <VAL> to the JX expression <EXPR>. - **--jx-context ctx** Deprecated. See '--jx-args'. ### Debugging Options - **-d --debug <subsystem>** Enable debugging for this subsystem. - **-o --debug-file <file>** Write debugging output to this file. By default, debugging is sent to stderr (":stderr"). You may specify logs to be sent to stdout (":stdout") instead. - **--debug-rotate-max byte** Rotate debug file once it reaches this size. - **--verbose** Display runtime progress on stdout. ### WorkQueue Options - **-C --catalog-server <catalog>** Set catalog server to <catalog>. Format: HOSTNAME:PORT - **-F --wq-fast-abort <#>** WorkQueue fast abort multiplier. (default is deactivated) - **-M --project-name <project>** Set the project name to <project>. - **-p --port <port>** Port number to use with WorkQueue. (default is 9123, 0=arbitrary) - **-Z --port-file <file>** Select port at random and write it to this file. (default is disabled) - **-P --priority <integer>** Priority. Higher the value, higher the priority. - **-t --wq-keepalive-timeout <#>** Work Queue keepalive timeout (default: 30s) - **-u --wq-keepalive-interval <#>** Work Queue keepalive interval (default: 120s) - **-W --wq-schedule <mode>** WorkQueue scheduling algorithm. (time|files|fcfs) - **password pwfile** Password file for authenticating workers. - **--disable-cache** Disable file caching (currently only Work Queue, default is false) - **--work-queue-preferred-connection connection** Indicate preferred connection. Chose one of by_ip or by_hostname. (default is by_ip) ### Monitor Options - **--monitor dir** Enable the resource monitor, and write the monitor logs to <dir> - **--monitor-exe file** Specify resource monitor executable. - **--monitor-with-time-series** Enable monitor time series. (default is disabled) - **--monitor-with-opened-files** Enable monitoring of openened files. (default is disabled) - **--monitor-interval #** Set monitor interval to <#> seconds. (default 1 second) - **--monitor-log-fmt fmt** Format for monitor logs. (default resource-rule-%06.6d, %d -> rule number) - **--monitor-measure-dir** Monitor measures the task's current execution directory size. - **--allocation waste** When monitoring is enabled, automatically assign resource allocations to tasks. Makeflow will try to minimize **waste** or maximize **throughput**. ### Umbrella Options - **--umbrella-binary filepath** Umbrella binary for running every rule in a makeflow. - **--umbrella-log-prefix filepath** Umbrella log file prefix for running every rule in a makeflow. (default is <makefilename>.umbrella.log) - **--umbrella-mode mode** Umbrella execution mode for running every rule in a makeflow. (default is local) - **--umbrella-spec filepath** Umbrella spec for running every rule in a makeflow. ### Docker Support - **--docker image** Run each task in the Docker container with this name. The image will be obtained via "docker pull" if it is not already available. - **--docker-tar tar** Run each task in the Docker container given by this tar file. The image will be uploaded via "docker load" on each execution site. - **--docker-opt string** Specify options to be used in DSingularityocker execution. ### Singularity Support - **--singularity image** Run each task in the Singularity container with this name. The container will be created from the passed in image. - **--singularity-opt string** Specify options to be used in Singularity execution. ### Amazon Options - **--amazon-config path** Path to Amazon EC2 configuration file generated by makeflow_ec2_setup. ### Amazon Lambda Options - **--lambda-config path** Path to Amazon Lambda configuration file generated by makeflow_lambda_setup. ### Amazon Batch Options - **--amazon-batch-config path** Path to Amazon Batch configuration file generated by makeflow_amazon_batch_setup. - **--amazon-batch-img img** Specify image used for Amazon Batch execution. ### Mesos Options - **--mesos-master hostname** Indicate the host name of preferred mesos manager. - **--mesos-path filepath** Indicate the path to mesos python2 site-packages. - **--mesos-preload library** Indicate the linking libraries for running mesos.. ### Kubernetes Options - **--k8s-image docker_image** Indicate the Docker image for running pods on Kubernetes cluster. ### Mountfile Support - **--mounts mountfile** Use this file as a mountlist. Every line of a mountfile can be used to specify the source and target of each input dependency in the format of **target source** (Note there should be a space between target and source.). - **--cache cache_dir** Use this dir as the cache for file dependencies. ### Archiving Options - **--archive ** Archive results of workflow at the specified path (by default /tmp/makeflow.archive.$UID) and use outputs of any archived jobs instead of re-executing job - **--archive-dir path** Specify archive base directory. - **--archive-read path** Only check to see if jobs have been cached and use outputs if it has been - **--archive-s3 s3_bucket** Base S3 Bucket name - **--archive-s3-no-check s3_bucket** Blind upload files to S3 bucket (No existence check in bucket). - **--s3-hostname s3_hostname** Base S3 hostname. Used for AWS S3. - **--s3-keyid s3_key_id** Access Key for cloud server. Used for AWS S3. - **--s3-secretkey secret_key** Secret Key for cloud server. Used for AWS S3. ### VC3 Builder Options - **--vc3-builder** Enable VC3 Builder - **--vc3-exe file** VC3 Builder executable location - **--vc3-log file** VC3 Builder log name - **--vc3-options string** VC3 Builder option string ### Other Options - **-A, --disable-afs-check** Disable the check for AFS. (experts only) - **-z, --zero-length-error** Force failure on zero-length output files. - **-g --gc <type>** Enable garbage collection. (ref_cnt|on_demand|all) - **--gc-size int** Set disk size to trigger GC. (on_demand only) - **-G --gc-count <int>** Set number of files to trigger GC. (ref_cnt only) - **--wrapper script** Wrap all commands with this **script**. Each rule's original recipe is appended to **script** or replaces the first occurrence of **{}** in **script**. - **--wrapper-input file** Wrapper command requires this input file. This option may be specified more than once, defining an array of inputs. Additionally, each job executing a recipe has a unique integer identifier that replaces occurrences **%%** in **file**. - **--wrapper-output file** Wrapper command requires this output file. This option may be specified more than once, defining an array of outputs. Additionally, each job executing a recipe has a unique integer identifier that replaces occurrences **%%** in **file**. - **--enforcement** Use Parrot to restrict access to the given inputs/outputs. - **--parrot-path path** Path to parrot_run executable on the host system. - **--env-replace-path path** Path to env_replace executable on the host system. - **--skip-file-check** Do not check for file existence before running. - **--do-not-save-failed-output** Disable saving failed nodes to directory for later analysis. - **--shared-fs dir** Assume the given directory is a shared filesystem accessible at all execution sites. - **-X --change-directory <dir>** Change to <dir> prior to executing the workflow. ### MPI Options - **--mpi-cores #** Number of cores each MPI worker uses. - **--mpi-memory #** Amount of memory each MPI worker uses. - **--mpi-task-working-dir path** Path to the MPI tasks working directory. ## DRYRUN MODE When the batch system is set to **-T** <dryrun>, Makeflow runs as usual but does not actually execute jobs or modify the system. This is useful to check that wrappers and substitutions are applied as expected. In addition, Makeflow will write an equivalent shell script to the batch system log specified by **-L** <logfile>. This script will run the commands in serial that Makeflow would have run. This shell script format may be useful for archival purposes, since it does not depend on Makeflow. ## MPI When cctools is built with --with-mpi-path=which mpicc` configuration, Makeflow can be ran as an MPI program. To do so, run Makeflow as an argument to BOLD(mpirun)/BOLD(mpiexec) and set BOLD(-T) PARAM(mpi) as a Makeflow option. When submitting mpi, request one process per core. Makeflow will count up how many processes each node given to MPI has, and use that as the core count for the worker on that node. Makeflow will then share memory evenly amongst the cores on the node, following the following equation BOLD(worker_memory) = (BOLD(total_memory) / BOLD(total_logical_cores)) * BOLD(num_cores_for_worker). To override Makeflow sharing memory equally, or setting per-worker cores value, use OPTION_ITEM('--mpi-cores) and - **'--mpi-memory'** . Tasks can also have their own sandbox. To specify the directory for tasks to create their sandbox subdirectory in, use - **'--mpi-task-working-dir'** . ## ENVIRONMENT VARIABLES The following environment variables will affect the execution of your **Makeflow**: ### BATCH_OPTIONS This corresponds to the **-B** <options> parameter and will pass extra batch options to the underlying execution engine. ### MAKEFLOW_MAX_LOCAL_JOBS This corresponds to the **-j** <#> parameter and will set the maximum number of local batch jobs. If a **-j** <#> parameter is specified, the minimum of the argument and the environment variable is used. ### MAKEFLOW_MAX_REMOTE_JOBS This corresponds to the **-J** <#> parameter and will set the maximum number of local batch jobs. If a **-J** <#> parameter is specified, the minimum of the argument and the environment variable is used. Note that variables defined in your **Makeflow** are exported to the environment. ### TCP_LOW_PORT Inclusive low port in range used with **-p 0**. ### TCP_HIGH_PORT) Inclusive high port in range used with **-p 0**. ## EXIT STATUS On success, returns zero. On failure, returns non-zero. ## EXAMPLES Run makeflow locally with debugging: ``` makeflow -d all Makeflow ``` Run makeflow on Condor will special requirements: ``` makeflow -T condor -B "requirements = MachineGroup == 'ccl'" Makeflow ``` Run makeflow with WorkQueue using named workers: ``` makeflow -T wq -a -M project.name Makeflow ``` Create a directory containing all of the dependencies required to run the specified makeflow ``` makeflow -b bundle Makeflow ``` ## COPYRIGHT The Cooperative Computing Tools are Copyright (C) 2005-2019 The University of Notre Dame. This software is distributed under the GNU General Public License. See the file COPYING for details. ## SEE ALSO - [Cooperative Computing Tools Documentation]("../index.html") - [Makeflow User Manual]("../makeflow.html") - [makeflow(1)](makeflow.md) [makeflow_monitor(1)](makeflow_monitor.md) [makeflow_analyze(1)](makeflow_analyze.md) [makeflow_viz(1)](makeflow_viz.md) [makeflow_graph_log(1)](makeflow_graph_log.md) [starch(1)](starch.md) [makeflow_ec2_setup(1)](makeflow_ec2_setup.md) [makeflow_ec2_cleanup(1)](makeflow_ec2_cleanup.md) [makeflow_ec2_estimate(1)](makeflow_ec2_estimate.md) CCTools 8.0.0 DEVELOPMENT released on
btovar/cctools
doc/man/md/makeflow.md
Markdown
gpl-2.0
15,140
{# # This file is part of Invenio. # Copyright (C) 2013, 2014, 2015, 2016 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. #} <div class="well"> {% if current_user.is_authenticated %} {% if mycommunities %} <h2> {% if mycommunities|length > 1 %} {{ _('My ') + config.COMMUNITIES_NAME_PLURAL }} {% else %} {{ _('My ') + config.COMMUNITIES_NAME }} {% endif %} {% if permission_cadmin().can() or permission_admin.can() %} <div class="pull-right"> &nbsp;<a href="{{url_for('.new')}}" class="btn btn-primary"><i class="icon-plus-sign"></i> {{ _('New') }}</a> </div> {% endif %} </h2> <table class="table table-striped"> {% for obj in mycommunities %} <tr> <td> <a href="{{url_for('.detail', community_id=obj.id)}}">{{obj.title if obj.title else 'Untitled'}}</a> <br /> <small class="muted">{{ _('Identifier') }}: {{obj.id}}</small> </td> <td> <div class="btn-group"> <a class="btn btn-default dropdown-toggle btn-xs" data-toggle="dropdown" href="#"> {{ _('Actions') }} <span class="caret"></span> </a> <ul class="dropdown-menu"> {% if permission_read(obj).can() or permission_admin.can() %} <li><a href="{{url_for('.detail', community_id=obj.id)}}"><i class="icon fa fa-book"></i> {{ _('View') }}</a></li> {% endif %} {% if permission_curate(obj).can() or permission_admin.can() %} <li><a href="{{url_for('.curate', community_id=obj.id)}}"><i class="icon fa fa-check"></i> {{ _('Curate') }}</a></li> {% endif %} {% if permission_manage(obj).can() or permission_admin.can() %} <li><a href="{{url_for('.edit', community_id=obj.id)}}"><i class="icon fa fa-pencil"></i> {{ _('Edit') }}</a></li> <li><a href="{{url_for('.team_management', community_id=obj.id)}}"><i class="icon fa fa-users"></i> {{ _('Manage team') }}</a></li> {% endif %} </ul> </div> <!-- /.btn-group --> </td> </tr> {% endfor %} </table> {% else %} <p class="muted">{{ _('You currently have no ' + config.COMMUNITIES_NAME + '.') }}</p> {% if permission_cadmin().can() or permission_admin.can() %} <h4> <div class="pull-right"> &nbsp;<a href="{{url_for('.new')}}" class="btn btn-primary"><i class="icon-plus-sign"></i> {{ _('New') }}</a> </div> <strong>{{ _('Want your own ' + config.COMMUNITIES_NAME + '?') }}</strong> </h4> <p>{{ _('It\'s easy. Just click the button to get started.') }}</p> <ul> <li><strong>{{ _('Curate') }}</strong> &mdash; {{ _('accept/reject what goes in your ' + config.COMMUNITIES_NAME) }}</li> <li><strong>{{ _('Export') }}</strong> &mdash; {{ _('your ' + config.COMMUNITIES_NAME_PLURAL + ' is automatically exported via OAI-PMH') }}</li> <li><strong>{{ _('Upload') }}</strong> &mdash; {{ _('get custom upload link to send to people') }}</li> </ul> {% endif %} {% endif %} {% else %} <h4> <div class="pull-right"> &nbsp;<a href="{{url_for('security.register')}}" class="btn btn-warning btn-large signup">{{ _('Sign Up') }}</a> </div> <strong>{{ _('Want to be part of a ' + config.COMMUNITIES_NAME + '?') }}</strong> </h4> <p>{{ _('It\'s easy. Just click the button to get started.') }}</p> <ul> <li><strong>{{ _('Search') }}</strong> {{ _('and get better results from a filtered set.') }}</li> <li><strong>{{ _('Suggest') }}</strong> {{ _('books and participate in your ' + config.COMMUNITIES_NAME) }}</li> </ul> {% endif %} </div>
tind/invenio-communities
invenio_communities/templates/invenio_communities/mycommunities.html
HTML
gpl-2.0
4,528
<?php /** * File containing the TestInitDbCommand class. * * @copyright Copyright (C) 2013 eZ Systems AS. All rights reserved. * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 * @version //autogentag// */ namespace eZ\Bundle\EzPublishCoreBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class TestInitDbCommand extends ContainerAwareCommand { protected function configure() { $this ->setName( 'ezpublish:test:init_db' ) ->setDescription( 'Inits the configured database for test use based on existing fixtures for eZ Demo install (4.7 atm)' ) ->setHelp( <<<EOT The command <info>%command.name%</info> initializes current configured database with existing fixture data. WARNING: This command will delete all data in the configured database before filling it with fixture data. EOT ); } protected function execute( InputInterface $input, OutputInterface $output ) { $database = $this->getContainer()->get( 'ezpublish.config.resolver' )->getParameter( 'database.params' ); if ( is_array( $database ) ) { $dbType = $database['type']; $database = $database['database']; } else { $dbType = preg_replace( '(^([a-z]+).*)', '\\1', $database ); } if ( $input->isInteractive() && !$this->getHelperSet()->get( 'dialog' )->askConfirmation( $output, "<question>Are you sure you want to delete all data in '{$database}' database?</question>", false ) ) { return; } $output->writeln( "<info>Database is now being emptied and re filled with fixture data.</info>" ); // @TODO Reuse API Integration tests SetupFactory when it has been refactored to be able to use Symfony DIC $this->applyStatements( $this->getSchemaStatements( $dbType ) ); $this->insertData( $dbType ); } /** * Insert the database data * * @param string $dbType Name of Database type (mysql, sqlite, pgsql, ..) * @return void */ public function insertData( $dbType ) { // Get Initial fixture data and union with some tables that must be present but sometimes aren't $data = $this->getInitialData() + array( 'ezcontentobject_trash' => array(), 'ezurlwildcard' => array(), 'ezmedia' => array(), 'ezkeyword' => array() ); $handler = $this->getDatabaseHandler(); foreach ( $data as $table => $rows ) { // Cleanup before inserting $deleteQuery = $handler->createDeleteQuery(); $deleteQuery->deleteFrom( $handler->quoteIdentifier( $table ) ); $stmt = $deleteQuery->prepare(); $stmt->execute(); // Check that at least one row exists if ( !isset( $rows[0] ) ) { continue; } $q = $handler->createInsertQuery(); $q->insertInto( $handler->quoteIdentifier( $table ) ); // Contains the bound parameters $values = array(); // Binding the parameters foreach ( $rows[0] as $col => $val ) { $q->set( $handler->quoteIdentifier( $col ), $q->bindParam( $values[$col] ) ); } $stmt = $q->prepare(); foreach ( $rows as $row ) { try { // This CANNOT be replaced by: // $values = $row // each $values[$col] is a PHP reference which should be // kept for parameters binding to work foreach ( $row as $col => $val ) { $values[$col] = $val; } $stmt->execute(); } catch ( Exception $e ) { echo "$table ( ", implode( ', ', $row ), " )\n"; throw $e; } } } $this->applyStatements( $this->getPostInsertStatements( $dbType ) ); } /** * Returns statements to be executed after data insert * * @param string $dbType Name of Database type (mysql, sqlite, pgsql, ..) * @return string[] */ protected function getPostInsertStatements( $dbType ) { if ( $dbType === 'pgsql' ) { $setvalPath = __DIR__ . '/../../../Publish/Core/Persistence/Legacy/Tests/_fixtures/setval.pgsql.sql'; return array_filter( preg_split( '(;\\s*$)m', file_get_contents( $setvalPath ) ) ); } return array(); } /** * Returns the initial database data * * @return array */ protected function getInitialData() { return include __DIR__ . "/../../../../data/demo_data.php"; } /** * Applies the given SQL $statements to the database in use * * @param array $statements * * @return void */ protected function applyStatements( array $statements ) { $handler = $this->getDatabaseHandler(); foreach ( $statements as $statement ) { $handler->exec( $statement ); } } /** * Returns the database schema as an array of SQL statements * * @param string $dbType Name of Database type (mysql, sqlite, pgsql, ..) * @return string[] */ protected function getSchemaStatements( $dbType ) { $schemaPath = __DIR__ . "/../../../../data/{$dbType}/schema.sql"; return array_filter( preg_split( '(;\\s*$)m', file_get_contents( $schemaPath ) ) ); } /** * Returns the database handler from the service container * * @return \EzcDbHandler */ protected function getDatabaseHandler() { return $this->getContainer()->get( 'ezpublish.api.storage_engine.legacy.dbhandler' ); } }
gbentley/ezpublish-kernel
eZ/Bundle/EzPublishCoreBundle/Command/TestInitDbCommand.php
PHP
gpl-2.0
6,315
# Description: GTK Theme based on sickbox: http://box-look.org/content/show.php/Sickbox?content=118996. The metacity theme on the screenshot below is Clearlooks Revamp. # Screenshot ![](http://s13.postimg.org/opxqdhpfr/127062_1.png) # Credits to [alltiptop](http://gnome-look.org/usermanager/search.php?username=alltiptop)
sofianugraha/freeBox
README.md
Markdown
gpl-2.0
325
@rem = '--*-Perl-*-- @echo off if "%OS%" == "Windows_NT" goto WinNT perl -x -S "%0" %1 %2 %3 %4 %5 %6 %7 %8 %9 goto endofperl :WinNT perl -x -S %0 %* if NOT "%COMSPEC%" == "%SystemRoot%\system32\cmd.exe" goto endofperl if %errorlevel% == 9009 echo You do not have Perl in your PATH. if errorlevel 1 goto script_failed_so_exit_with_non_zero_val 2>nul goto endofperl @rem '; #!perl #line 15 ########################################################################## # FILE mk_distro.bat # PURPOSE General Interface for making a Windows distribution # ==================================================================== # Copyright (c) 2000-2004 CollabNet. All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://subversion.tigris.org/license-1.html. # If newer versions of this license are posted there, you may use a # newer version instead, at your option. # # This software consists of voluntary contributions made by many # individuals. For exact contribution history, see the revision # history and logs, available at http://subversion.tigris.org/. # ==================================================================== ########################################################################## # INCLUDED LIBRARY FILES use strict; use Cwd; use File::Basename; ########################################################################## # FUNCTION DECLARATIONS sub Main; ########################################################################## # PROGRAM ENTRANCE Main; ########################################################################## # FUNCTION DEFINITIONS #------------------------------------------------------------------------- # FUNCTION Main # DOES This is the program's main function sub Main { my $CurOrig=getcwd; my $DirName=dirname($0); if ($DirName eq '.') { system ("perl mk_distro.pl @ARGV"); } else { chdir $DirName; system ("perl mk_distro.pl @ARGV"); chdir $CurOrig; } } __END__ :endofperl
bdmod/extreme-subversion
BinarySourcce/subversion-1.6.17/packages/windows-innosetup/tools/mk_distro.bat
Batchfile
gpl-2.0
2,152
#include <stdafx.h> #include <vd2/system/error.h> #include <vd2/system/cpuaccel.h> #include <vd2/system/vdalloc.h> #include <vd2/system/time.h> #include <vd2/Kasumi/pixmap.h> #include <vd2/Kasumi/pixmaputils.h> #include <vd2/Kasumi/resample.h> #include <vd2/Dita/services.h> #include "ProgressDialog.h" #include "InputFile.h" #include "VideoSource.h" #include "AVIOutput.h" #include "AVIOutputFile.h" #include <vector> extern const char g_szError[]; namespace { static const uint8 ditherred[16][16]={ 35, 80,227,165, 64,199, 42,189,138, 74,238,111, 43,153, 13,211, 197,135, 20, 99,244, 4,162,105, 25,210, 38,134,225, 78,242, 87, 63,249,126,192, 50,174, 82,251,116,148, 97,176, 19,167, 52,163, 187, 30, 85,142,219, 71,194, 45,169, 11,241, 58,216,106,204, 5, 94,151,235, 9,112,155, 17,224, 91,206, 84,188,120, 36,132,233, 177, 48,124,201, 40,239,125, 66,180, 51,160, 7,152,255, 89, 56, 16,209, 72,161,121, 59,208,150, 28,248, 75,229,101, 26,140,220, 170,110,226, 22,252,139, 1,109,195,115,172, 39,200,114,191, 68, 136, 34, 96,183, 44,175, 95,234, 81, 15,143,217, 62,164, 2,237, 57,245,154, 61,203, 70,213, 37,137,243, 98, 23,179, 86,198,103, 184, 12,123,221, 6,129,156, 88,185, 53,127,228, 49,250, 31,130, 77,205, 83,145,107,247, 29,223, 10,212,159, 79,168, 73,146,232, 173, 41,240, 24,190, 54,178,102,149,118, 33,202, 8,215,119, 18, 92,158, 67,166, 76,207,133, 47,254, 65,230,100,131,157, 69,193, 253, 3,214,117,231, 14, 93,171, 21,182,144, 55,246, 27,222, 46, 141,181,104, 32,147,113,236, 60,218,122, 0,196, 90,186,128,108, }; static const uint8 dithergrn[16][16]={ 130,239, 48,211, 19,242, 33, 85,120,252, 72,207,107, 26,179, 39, 67,112,184, 92,156, 75,164,213, 17,138,188, 2,245,140, 87,225, 198,147, 11,254, 41,219,129, 60,194, 49,115,176, 95, 45,170, 15, 109, 51,177, 84,165,117, 6,247,132, 90,201, 56,155,215, 80,250, 136,229, 65,206, 28,189, 97,169, 36,223, 24,241,124, 8,181, 34, 212, 1,143,104,234, 70,220, 57,121,159,102,144, 42,232,133, 96, 71,123,246, 22,149,128, 16,137,237, 10,208, 77,191,111, 53,195, 158,187, 58,175, 44,193,110,202, 82,183, 61,255, 21,151,226, 18, 94, 32,214, 88,228, 64,249, 30,172, 47,162, 89,173, 63,106,200, 236,141, 68,166, 3,161, 93,153, 74,231, 0,216, 38,240,139, 46, 118, 13,253,114,205, 52,186, 14,199,113,142,101,192,125, 7,178, 222,103,154, 37,131,244, 79,221,134, 54,251, 27,157, 83,209, 78, 29,190, 73,217, 98, 25,174,108, 35,185, 91,210, 66,243, 50,171, 248, 55,168, 9,146,227, 69,148,238,127, 12,122,180, 20,145,116, 100,203, 86,235,119, 43,197, 5, 81,204, 99,230, 59,126,196, 4, 150, 23,163, 62,182,105,135,224,160, 31,167, 40,152,233, 76,218, }; static const uint8 ditherblu[16][16]={ 184, 97,174, 29,118,218, 69,249,152, 5,172,126, 31,120,164, 59, 135, 12,140,214, 76,161,122, 26, 93,205, 80,242,106,220, 82,250, 108,228, 91, 40,182, 1,202,142,236, 55,160, 44,167, 9,179, 34, 204, 56,128,255, 86,231, 99, 49,130,187, 20,201, 78,209, 73,158, 4,153,192, 18,170, 35,131,193, 10, 87,253,116,151, 28,245,123, 234, 43,103,212, 74,156,221, 61,230,163,102, 50,223,105,143, 68, 89,183,136, 52,243,113, 22,146,121, 30,206,132, 3,196, 48,173, 217, 25,203,119, 7,188, 92,248, 72,171, 83,240,147, 63,238, 15, 79,166, 64,235,138, 58,208, 38,197, 13,186, 36,110,177, 94,154, 251,104,190, 41,175,100,150,124, 81,219, 66,127,210, 19,222, 37, 117, 11,134,215, 24,252, 2,226,159, 27,144,246, 75,162, 88,194, 141,227, 54,114,165, 77,180, 53,115,233, 98, 8,199, 51,176, 70, 33,169, 85,239, 47,211,139, 90,195, 46,189,133,107,225, 0,244, 207,101,155, 6,185,112, 32,241, 14,168, 84,254, 42,149,129, 60, 145, 23,198,125, 62,224, 96,137,200, 57,157, 21,181, 65,191,111, 45,232, 67,247,148, 17,178, 39,109,229, 71,213, 95,237, 16,216, }; } void VDCreateTestPal8Video(VDGUIHandle h) { CPUEnableExtensions(CPUCheckForExtensions()); try { tVDInputDrivers inputDrivers; std::vector<int> xlat; VDGetInputDrivers(inputDrivers, IVDInputDriver::kF_Video); const VDStringW filter(VDMakeInputDriverFileFilter(inputDrivers, xlat)); const VDFileDialogOption opt[]={ { VDFileDialogOption::kSelectedFilter }, 0 }; int optval[1]={0}; const VDStringW srcfile(VDGetLoadFileName('pl8s', h, L"Choose source file", filter.c_str(), NULL, opt, optval)); if (srcfile.empty()) return; IVDInputDriver *pDrv; int filtidx = xlat[optval[0] - 1]; if (filtidx < 0) pDrv = VDAutoselectInputDriverForFile(srcfile.c_str(), IVDInputDriver::kF_Video); else { tVDInputDrivers::iterator itDrv(inputDrivers.begin()); std::advance(itDrv, filtidx); pDrv = *itDrv; } vdrefptr<InputFile> pIF(pDrv->CreateInputFile(0)); pIF->Init(srcfile.c_str()); const VDStringW dstfile(VDGetSaveFileName('pl8d', h, L"Choose destination 8-bit file", L"Audio-video interleaved (*.avi)\0*.avi\0All files\0*.*", L"avi", NULL, NULL)); if (dstfile.empty()) return; vdrefptr<IVDVideoSource> pVS; pIF->GetVideoSource(0, ~pVS); IVDStreamSource *pVSS = pVS->asStream(); const VDPosition frames = pVSS->getLength(); if (!pVS->setTargetFormat(nsVDPixmap::kPixFormat_XRGB8888)) throw MyError("Cannot set decompression format to 32-bit."); vdautoptr<IVDMediaOutputAVIFile> pOut(VDCreateMediaOutputAVIFile()); IVDMediaOutputStream *pVSOut = pOut->createVideoStream(); const VDPixmap& pxsrc = pVS->getTargetFormat(); const uint32 rowbytes = (pxsrc.w+3) & ~3; VDXStreamInfo si; VDXAVIStreamHeader& hdr = si.aviHeader; hdr.fccType = 'sdiv'; hdr.fccHandler = 0; hdr.dwFlags = 0; hdr.wPriority = 0; hdr.wLanguage = 0; hdr.dwScale = pVSS->getStreamInfo().dwScale; hdr.dwRate = pVSS->getStreamInfo().dwRate; hdr.dwStart = 0; hdr.dwLength = 0; hdr.dwInitialFrames = 0; hdr.dwSuggestedBufferSize = 0; hdr.dwQuality = -1; hdr.dwSampleSize = 0; hdr.rcFrame.left = 0; hdr.rcFrame.top = 0; hdr.rcFrame.right = (short)pxsrc.w; hdr.rcFrame.bottom = (short)pxsrc.h; pVSOut->setStreamInfo(si); vdstructex<BITMAPINFOHEADER> bih; bih.resize(sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD)*252); bih->biSize = sizeof(BITMAPINFOHEADER); bih->biWidth = pxsrc.w; bih->biHeight = pxsrc.h; bih->biPlanes = 1; bih->biBitCount = 8; bih->biCompression = BI_RGB; bih->biSizeImage = rowbytes*pxsrc.h; bih->biXPelsPerMeter = 0; bih->biYPelsPerMeter = 0; bih->biClrUsed = 252; bih->biClrImportant = 252; RGBQUAD *pal = (RGBQUAD *)((char *)bih.data() + sizeof(BITMAPINFOHEADER)); for(int i=0; i<252; ++i) { pal[i].rgbRed = (BYTE)((i/42)*51); pal[i].rgbGreen = (BYTE)((((i/6)%7)*85)>>1); pal[i].rgbBlue = (BYTE)((i%6)*51); pal[i].rgbReserved = 0; } pVSOut->setFormat(bih.data(), bih.size()); pOut->init(dstfile.c_str()); ProgressDialog dlg((HWND)h, "Processing video stream", "Palettizing frames", (long)frames, true); vdblock<uint8> outbuf(rowbytes * pxsrc.h); const vdpixsize w = pxsrc.w; const vdpixsize h = pxsrc.h; try { for(uint32 frame=0; frame<frames; ++frame) { pVS->getFrame(frame); const uint8 *src = (const uint8 *)pxsrc.data; ptrdiff_t srcpitch = pxsrc.pitch; uint8 *dst = &outbuf[rowbytes * (pxsrc.h - 1)]; for(int y=0; y<h; ++y) { const uint8 *dr = ditherred[y & 15]; const uint8 *dg = dithergrn[y & 15]; const uint8 *db = ditherblu[y & 15]; for(int x=0; x<w; ++x) { const uint8 b = (uint8)((((src[0] * 1286)>>8) + dr[x&15]) >> 8); const uint8 g = (uint8)((((src[1] * 1543)>>8) + dg[x&15]) >> 8); const uint8 r = (uint8)((((src[2] * 1286)>>8) + db[x&15]) >> 8); src += 4; dst[x] = (uint8)(r*42 + g*6 + b); } vdptrstep(dst, -(ptrdiff_t)rowbytes); vdptrstep(src, srcpitch - w*4); } pVSOut->write(AVIOutputStream::kFlagKeyFrame, outbuf.data(), outbuf.size(), 1); dlg.advance(frame); dlg.check(); } } catch(const MyUserAbortError&) { } pVSOut->flush(); pOut->finalize(); } catch(const MyError& e) { e.post((HWND)h, g_szError); } }
shekh/VirtualDub2
src/VirtualDub/source/test_pal8.cpp
C++
gpl-2.0
8,056
/* * ===================================================================================== * * Filename: main.c * * Description: 内核入口 * * Version: 1.0 * Created: 2013年10月12日 16时42分27秒 * Revision: none * Compiler: gcc * * Author: Nick (LiuYongkang), liuyongkanglinux@gmail.com * Company: Class 1107 of Computer Science and Technology * * ===================================================================================== */ #include "multiboot.h" #include "monitor.h" #include "gdt.h" #include "idt.h" #include "timer.h" int nx_main(struct multiboot *mboot) { init_gdt(); init_idt(); monitor_clear(); monitor_write_str("Hello world!\n"); init_timer(20); asm volatile ("sti"); return 0; }
liuyongkang/nickex
src/entry/main.c
C
gpl-2.0
795
.rule {border:none;border-top:1px solid #ddd;border-bottom:1px solid #fff;font-size:1px;line-height:0;overflow:visible;} .bold {font-weight:bold;} .underline {text-decoration:underline;} .italic {font-style:italic;} .center {text-align:center;} /*-- wp standard settings table --*/ table.form-table {margin-top:0;clear:left;width:auto;}
Click3X/000276_Friendshop
wp-content/plugins/pc-hide-pages/css/admin.css
CSS
gpl-2.0
346
/************************************************************************* solar frog attiny 13 low power experiments 28.9.08 christoph(at)roboterclub-freiburg.de 06.10.11 urbanbieri(at)gmx.ch *************************************************************************/ /************************************************************************* Hardware prozessor: ATtin13 PIN5 PORTB0/OC10 piezo controll speaker *************************************************************************/ #include <avr/io.h> #include <avr/eeprom.h> #define INITIAL_RHYTHM 0 //16 Patterns: choose between 0 and 15 #define PIEZOSPEAKER (1<<PINB0) #define SENSOR (1<<PINB3) #define BUTTON (1<<PINB1) //#define BUTTON2 (1<<PINB4) #define LOADSECONDS 60 #define HZ_1706 2 #define HZ_853 4 #define HZ_586 6 #define HZ_426 8 //GLOBAL VARIABLES uint8_t pattern[16] = {0x5b, 0xc7, 0xcd, 0xe7, 0x97, 0x59, 0x55, 0x55, 0xaa, 0xaa, 0xa5, 0xa5, 0x5a, 0x5a, 0xff, 0xfa}; uint8_t noise[33] = {240, 128, 33, 151, 163, 144, 0, 233, 102, 70, 106, 0, 97, 209, 154, 34, 174, 172, 6, 84, 13, 222, 78, 107, 139, 119, 23, 4, 67, 163, 173, 234, 120}; void init_sensor(void){ DDRB &= ~(SENSOR); //set SENSOR pin as input // Enable ADC: ADEN to 1. // Prescaler 128: ADPS2-0: set to 1 // enable the Conversion Complete Interrupt: ADIE to 1 ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0); } // sets LED-PWM value from LSR value (light sensitive resistor) uint8_t start_conversion(void){ // for 8-bit precision I select left Adjustet representation (ADLAR) so that I only have // to read the ADCH byte. REFS0=0: reference voltage VCC ADMUX = (1 << ADLAR) | (0 << REFS0) | 0x11; // 0x01 is PB2, 0x10 is PB4, 0x11 is PB3. ADCSRA |= (1 << ADSC); // Start conversion while (!(ADCSRA & (1 << ADIF))); // wait for conversion complete ADCSRA |= (1 << ADIF); // clear ADCIF return(ADCH); } void init_button(){ DDRB &= ~(BUTTON); //set pin as input (BUTTON to 0) PORTB |= (BUTTON); //turn on pull up resistor } void init_timer() { DDRB |= PIEZOSPEAKER; // Piezo as output /* frequency example TCCR0B=0x02; // internal clock source devided by 8 OCR0A=9; // Compare value // calculated frequency at 9.6MHz: 9.6e6/(2*8*(9+1))= 60kHz , Division by 2 due to toogle //TCCR0A=0x02; // CTC-Mode (clear timer on compare match) */ TCCR0A=(1<<COM0A0) | 0x02; //CTC mode and toogle OC0A port on compare match TCCR0B=(1<<CS00) ; // no prescaling, OCR0A=255; // in CTC Mode the counter counts up to OCR0A // CTC-Modefrequency calculation: f=IO_CLC/(2*N*(1+OCR0A)) N:Prescaler // e.g. IO_CLK=128KHz, N=1; OCR0A=1 ==> 64Khz // e.g. IO_CLK=128KHz, N=1; OCR0A=10 ==> f=6095Hz // e.g. IO_CLK=128KHz, N=1; OCR0A=100 ==> f=633Hz // e.g. IO_CLK=128KHz, N=1; OCR0A=200 ==> f=318Hz // e.g. IO_CLK=128KHz, N=1; OCR0A=255 ==> f=318Hz TCCR0B=(1<<CS00) ; // no prescaling, ///FAST PWM mode and set OC0A ( PB0 ) port on compare match //TCCR0A=(1<<COM0A0) | (1<<COM0A1) | (1<< WGM00 ) | (1<< WGM01 ); // TCCR0B=(1<<CS00) | (1<< WGM02 ); // no prescaling, PWM OCR0A update //TCCR0B=(1<<CS00) ; // no prescaling, //TCCR0B=0x02; // internal clock source devided by 8 //OCR0A=9; // Compare value OCR0A=255; // Counter end // caldulated frequency at 9.6MHz: 1/9.6e6/(8*(124+1))= 9600 Baud // bit time = 104,17us //TCCR0A=0x02; // CTC-Mode (clear timer on compare match) } // duration in 1ms void delay_ms(uint16_t duration) { uint16_t d; uint8_t n; uint16_t counter; counter=(3*duration); // periode duration 586us for(d=0;d<counter;d++) { for(n=0;n<1;n++) PORTB &= ~(PIEZOSPEAKER); for(n=0;n<1;n++) PORTB &= ~(PIEZOSPEAKER); } } #define SPEAKEROFF TCCR0A=(0x02) #define SPEAKERON TCCR0A=((1<<COM0A0) | 0x02) void invokeGlissando(uint8_t start, uint8_t stop, uint16_t duration){ uint8_t j; //working variable SPEAKERON; if (start<= stop){ for(j=start;j<stop;j++){ OCR0A = j; delay_ms(duration); } }else{ for(j=start;j>stop;j--){ OCR0A = j; delay_ms(duration); } } } void delay_vibrato(uint8_t with, uint8_t time, uint8_t count){ uint8_t tone = OCR0A; uint8_t i; for(i=0; i<count; i++){ invokeGlissando(tone, tone-with, time); invokeGlissando(tone-with, tone, time); } } // @pre section<62! void invokeRhythm(uint8_t section, uint16_t duration){ uint8_t j; uint16_t sDelay; for(j=0; j<4; j++){ sDelay = pattern[section]>>(j*2); sDelay = sDelay & 0x03; // sDelay = j; SPEAKEROFF; delay_ms(duration * sDelay); SPEAKERON; delay_ms(duration * sDelay); } } uint8_t magnet(uint8_t value, uint8_t amount, uint8_t magnetvalue){ if(value<magnetvalue){ if((value+amount) < magnetvalue){ value += amount; } else { value = magnetvalue; } } else { if((value-amount) > magnetvalue){ value -= amount; } else { value = magnetvalue; } } return value; } void playNoise(uint8_t pitch, uint16_t hold, uint16_t pause){ uint16_t i; for(i=255; i>0; i--){ OCR0A = magnet(noise[i%32], i, pitch); delay_ms(12); } // hold for(i=hold; i>0; i--){ OCR0A = noise[i%32]; } SPEAKEROFF; delay_ms(pause); SPEAKERON; } int main(void) { // uint8_t i=INITIAL_RHYTHM; // rhythm pattern nr. uint8_t magnetvalue = 127, k = 0; uint16_t pause = 0;// , j, tone = 3023; // Initiation OCR0A = 255; init_timer(); init_sensor(); // init_button(); SPEAKERON; while(1) { SPEAKERON; magnetvalue=noise[k]; playNoise(magnetvalue, 1400, 1000); SPEAKEROFF; delay_ms(pause); if(k==15){ k=0; } else { k++; } noise[k] = (noise[k] + start_conversion() + noise[k+1])%256; } return 0; } /************************************************************************** * (c) 2008 christoph(at)roboterclub-freiburg.de * 2011 urbanbieri(at)gmx.ch *************************************************************************** * 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 version 2 of the License, * * If you extend the program please maintain the list of authors. * * If you want to use this software for commercial purposes and you * * don't want to make it open source, please contact the authors for * * licensing. * ***************************************************************************/
schaum/solarBird
2011ParisRawVersions/Noise/nr6-slow and stable/main.c
C
gpl-2.0
6,615
package Lacuna::Role::Container; use Moose::Role; use Lacuna::Constants qw(ORE_TYPES FOOD_TYPES); use Lacuna::Util qw(format_date commify consolidate_items); requires "payload"; sub format_body_stats_for_log { my ($self, $body ) = @_; my %stats; foreach my $type (qw(water energy waste), ORE_TYPES, FOOD_TYPES) { $stats{$type} = $body->type_stored($type); $stats{food_capacity} = $body->food_capacity; $stats{water_capacity} = $body->water_capacity; $stats{waste_capacity} = $body->waste_capacity; $stats{ore_capacity} = $body->ore_capacity; $stats{energy_capacity} = $body->energy_capacity; } return \%stats; } sub unload { my ($self, $body, $withdraw) = @_; my $payload = $self->payload; if (exists $payload->{prisoners}) { foreach my $id (@{$payload->{prisoners}}) { my $prisoner = Lacuna->db->resultset('Lacuna::DB::Result::Spies')->find($id); next unless defined $prisoner; $prisoner->task('Captured'); $prisoner->on_body_id($body->id); $prisoner->update; } delete $payload->{prisoners}; } if (exists $payload->{mercenary}) { my $id = $payload->{mercenary}; my $spy = Lacuna->db->resultset('Lacuna::DB::Result::Spies')->find($id); next unless defined $spy; $spy->task('Idle'); $spy->available_on(DateTime->now); $spy->on_body_id($body->id); unless ($withdraw) { unless ($spy->empire_id == $body->empire_id) { $spy->empire_id($body->empire_id); } $spy->from_body_id($body->id); } $spy->update; delete $payload->{mercenary}; } if (exists $payload->{ships}) { foreach my $id (@{$payload->{ships}}) { my $fleet = Lacuna->db->resultset('Fleet')->find($id); next unless defined $fleet; $fleet->body_id($body->id); $fleet->task('Docked'); $fleet->land->update; } delete $payload->{ships}; } if (exists $payload->{essentia}) { $body->empire->add_essentia({ amount => $payload->{essentia}, reason => 'Trade Unloaded', }); $body->empire->update; delete $payload->{essentia}; } if (exists $payload->{resources}) { my %resources = %{$payload->{resources}}; $body->update; $body->discard_changes; foreach my $type (keys %resources) { $body->add_type($type, $resources{$type}); } $body->update; delete $payload->{resources}; } if (exists $payload->{plans}) { foreach my $plan (@{$payload->{plans}}) { $body->add_plan($plan->{class}, $plan->{level}, $plan->{extra_build_level}, $plan->{quantity}); } delete $payload->{plans}; } if (exists $payload->{glyphs}) { foreach my $glyph (@{$payload->{glyphs}}) { $body->add_glyph($glyph->{name}, $glyph->{quantity}); } delete $payload->{glyphs}; } $self->payload($payload); return $self; } sub format_description_of_payload { my ($self) = @_; my $item_arr = []; my $scratch; my $payload = $self->payload; # essentia push @{$item_arr}, sprintf('%s essentia.', commify($payload->{essentia})) if ($payload->{essentia}); # resources foreach my $resource (keys %{ $payload->{resources}}) { push @{$item_arr}, sprintf('%s %s', commify($payload->{resources}{$resource}), $resource); } # glyphs foreach my $glyph (@{$payload->{glyphs}}) { push @{$item_arr}, sprintf('%s %s glyph', commify($glyph->{quantity}), $glyph->{name}); } # ships my $fleets = Lacuna->db->resultset('Fleet'); foreach my $id (@{$payload->{fleets}}) { my $fleet = $fleets->find($id); next unless defined $fleet; my $pattern = '%s (speed: %s, stealth: %s, hold size: %s, berth: %s, combat: %s)' ; push @{$item_arr}, sprintf($pattern, $fleet->type_formatted, commify($fleet->speed), commify($fleet->stealth), commify($fleet->hold_size), commify($fleet->berth_level), commify($fleet->combat), ); } #fleets undef $scratch; foreach my $fleet (sort keys %{$payload->{fleet}}) { my $pattern = '%s (speed: %s, stealth: %s, hold size: %s, combat: %s #: %s)' ; push @{$scratch}, sprintf($pattern, $payload->{fleet}->{$fleet}->{type}, commify($payload->{fleet}->{$fleet}->{speed}), commify($payload->{fleet}->{$fleet}->{stealth}), commify($payload->{fleet}->{$fleet}->{hold_size}), commify($payload->{fleet}->{$fleet}->{combat}), commify($payload->{fleet}->{$fleet}->{quantity})); } push @{$item_arr}, @{consolidate_items($scratch)} if (defined($scratch)); # plans undef $scratch; foreach my $stats (@{ $payload->{plans}}) { my $level = $stats->{level}; if ($stats->{extra_build_level}) { $level .= '+'.$stats->{extra_build_level}; } my $pattern = '%s (%s) plan'; push @{$item_arr}, sprintf('%s %s (%s) plan', $stats->{quantity}, $stats->{class}->name, $level); } # spies undef $scratch; my $spies = Lacuna->db->resultset('Lacuna::DB::Result::Spies'); if (exists $payload->{spies}) { foreach my $id (@{$payload->{spies}}) { my $spy = $spies->find($id); next unless defined $spy; push @{$scratch}, 'Level '.$spy->level.' spy named '.$spy->name . ' (transport)'; } push @{$item_arr}, @{consolidate_items($scratch)} if (defined($scratch)); } # prisoners undef $scratch; if (exists $payload->{prisoners}) { foreach my $id (@{$payload->{prisoners}}) { my $spy = $spies->find($id); next unless defined $spy; push @{$scratch}, 'Level '.$spy->level.' spy named '.$spy->name . ' (prisoner) sentence expires '.$spy->format_available_on; } push @{$item_arr}, @{consolidate_items($scratch)} if (defined($scratch)); } # fetch spies undef $scratch; if (exists $payload->{fetch_spies}) { foreach my $id (@{$payload->{fetch_spies}}) { my $spy = $spies->find($id); next unless defined $spy; push @{$scratch}, 'Level '.$spy->level.' spy named '.$spy->name . ' (fetch upon arrival)'; } push @{$item_arr}, @{consolidate_items($scratch)} if (defined($scratch)); } return $item_arr; } 1;
plainblack/Lacuna-Server-Open
lib/Lacuna/Role/Container.pm
Perl
gpl-2.0
6,850
#!/usr/bin/env python import matplotlib.pyplot as plt # dict: {title of plot : [measure value files]} # The input data may not have a \n at file end. inputFiles = {'LibMergeSort_Sortierszenarien_im_Vergleich': ['sorted', 'shuffle', 'reverse']} # different colors of the function graphs COLORS = ['g', 'k', 'm'] print(inputFiles.items()) counter = 0 for outputFileName, fileNames in inputFiles.items(): fig = plt.figure() ax1 = fig.add_subplot(111) for fileName in fileNames: with open(fileName) as f: data = f.read() data = data.split('\n') #print(str(fileName) + str(data)) x = [row.split()[0] for row in data] y = [float(row.split()[1]) for row in data] err = [float(row.split()[2]) for row in data] ax1.plot(x, y, c=COLORS[counter], label=fileName) ax1.errorbar(x, y, yerr=err, fmt='_', ecolor=COLORS[counter], capthick=2) counter = counter + 1 # ax1.set_title(outputFileName) ax1.set_xlabel('Anzahl Elemente N') ax1.set_ylabel('Laufzeit [s]') leg = ax1.legend(loc='upper left') #leg = ax1.legend(loc='lower right') # ax1.set_yscale('log') #fig.savefig(outputFileName + '.png', format='png') fig.savefig(outputFileName + '.pdf', format='pdf') # plt.show()
rm--/matplotlib_examples
example1/evaluate1.py
Python
gpl-2.0
1,327
/******************************************************************************* * This file is part of OpenWSN, the Open Wireless Sensor Network Platform. * * Copyright (C) 2005-2010 zhangwei(TongJi University) * * OpenWSN is a free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 or (at your option) any later version. * * OpenWSN is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 59 Temple * Place, Suite 330, Boston, MA 02111-1307 USA. * * For non-opensource or commercial applications, please choose commercial license. * Refer to OpenWSN site http://code.google.com/p/openwsn/ for more detail. * * For other questions, you can contact the author through email openwsn#gmail.com * or the mailing address: Dr. Wei Zhang, Dept. of Control, Dianxin Hall, TongJi * University, 4800 Caoan Road, Shanghai, China. Zip: 201804 * ******************************************************************************/ #ifndef _SVC_NIO_FLOOD_H_4764_ #define _SVC_NIO_FLOOD_H_4764_ /******************************************************************************* * svc_nio_flood * This module implements a simple flooding mechanism in a multi-hop wireless * network. * * @author zhangwei in 2007.06 * - first created * @modified by zhangwei in 2009.07 * - revision. done * ******************************************************************************/ /* The following two macros should be defined before including "rtl_cache" in order * to be effective in rtl_cache module. Or else the rtl_cache will use its internal * configurations. */ #define CONFIG_FLOOD_CACHE_CAPACITY 1 //#define CONFIG_FLOOD_CACHE_CAPACITY 8 #define CONFIG_FLOOD_CACHE_MAX_LIFETIME 8 #ifndef CONFIG_FLOOD_MAX_COUNT #define CONFIG_FLOOD_MAX_COUNT 5 #endif #ifndef CONFIG_FLOOD_CACHE_SIZE #define CONFIG_FLOOD_CACHE_SIZE 8 #endif #include "svc_configall.h" #include "../rtl/rtl_frame.h" #include "../rtl/rtl_cache.h" #include "../rtl/rtl_framequeue.h" #include "../hal/hal_foundation.h" //#include "../hal/hal_cc2520.h" //#include "../hal/hal_cc2520.h" #include "../hal/hal_debugio.h" #include "svc_foundation.h" #include "svc_nio_aloha.h" #include "svc_nio_dispatcher.h" #define FLOOD_FRAMEOBJECT_SIZE FRAMEQUEUE_ITEMSIZE #define FLOOD_STATE_IDLE 0 #define FLOOD_STATE_WAITFOR_TXREPLY 1 #define FLOOD_PROTOCAL_IDENTIFIER 0x10 #define FLOOD_CONTROL_IDENTIFIER 0 #define FLOOD_BROADCAST_ADDRESS 0xffff #define FLOOD_MAXHOPCOUNT 5 #ifdef __cplusplus extern "C"{ #endif /** * Flood Protocol Packet Format: * [Current Hop Count 1B] [Maximum Hop Count 1B] [Sequence Id 1B] * * @todo * Suggested flooding protocol format is: * [Protocol Idenfier 1B] [Command 2B] [Sequence Id 1B] [Current Hop Count 1B] * [Maximum Hop Count 1B]{Destination Address 2B} {Source Address 2B} */ /** * _TiFloodCacheItem and _TiFloodCache * The cache is used inside flood component to improve the flood performance. In * order to shrink the memory used by the cache, it does only put the meta information * of a frame into the cache instead of put all the frame content into the cache. * * _TiFloodCache is implemented as some macros based on the TiCache component, which * is already provided in module "rtl_cache". * * _TiFloodCacheItem is used to save the meta information of a frame. * * @attention * CONFIG_FLOOD_CACHE_CAPACITY * This macro is used to configure the cache capacity. Suggested values are 4-8. * Attention don't consume all the SRAM inside the MCU. Larger value is better to * improve the performance of the flood component, but the MCU may not have enough * memory as you hoped. */ /* lifetime = 0 means this is an empty item in the cache. The bigger the lifetime, * the newer the lifetime. */ /* typedef struct{ uint16 panto; uint16 shortaddrto; uint16 panfrom; uint16 shortaddrfrom; uint8 seqid; }_TiFloodCacheItem; */ #define FLOOD_MAKEWORD(high,low) (((uint16)high<<8) | ((uint8)low)) #define FLOOD_PACKETCONTROL(pkt) FLOOD_MAKEWORD((pkt)[2],(pkt)[1]) #define FLOOD_SEQUENCEID(pkt) ((pkt)[3]) #define FLOOD_CUR_HOPCOUNT(pkt) ((pkt)[4]) #define FLOOD_MAX_HOPCOUNT(pkt) ((pkt)[5]) #define FLOOD_SHORTADDRTO(pkt) FLOOD_MAKEWORD((pkt)[7],(pkt)[6]) #define FLOOD_SHORTADDRFROM(pkt) FLOOD_MAKEWORD((pkt)[9],(pkt)[8]) #define FLOOD_SET_PROTOCAL_IDENTIFIER(pkt,value) (pkt)[0]=(value) #define FLOOD_SET_PACKETCONTROL(pkt,value) {(pkt)[1]=((uint8)(value&0xFF)); (pkt)[2]=((uint8)(value>>8));} #define FLOOD_SET_SEQUENCEID(pkt,value) (pkt)[3]=(value) #define FLOOD_SET_HOPCOUNT(pkt,value) (pkt)[4]=(value) #define FLOOD_SET_MAX_HOPCOUNT(pkt,value) (pkt)[5]=(value) #define FLOOD_SET_SHORTADDRTO(pkt,addr) {(pkt)[6]=((uint8)(addr&0xFF)); (pkt)[7]=((uint8)(addr>>8));} #define FLOOD_SET_SHORTADDRFROM(pkt,addr) {(pkt)[8]=((uint8)(addr&0xFF)); (pkt)[9]=((uint8)(addr>>8));} /* The cache item searching key contains 4 bytes, which are the flooding protocol * header. */ #define FLOOD_CACHE_ITEMSIZE 5 #define FLOOD_CACHE_HOPESIZE CACHE_HOPESIZE(FLOOD_CACHE_ITEMSIZE,CONFIG_FLOOD_CACHE_CAPACITY) #define _TiFloodCache TiCache #define flood_cache_open(mem,memsize) cache_open(mem,memsize,FLOOD_CACHE_ITEMSIZE,CONFIG_FLOOD_CACHE_CAPACITY) #define flood_cache_close(ca) cache_close(ca) #define flood_cache_hit(ca,item,pidx) cache_hit(ca,item,FLOOD_CACHE_ITEMSIZE,pidx) #define flood_cache_visit(ca,item) cache_visit(ca,item,FLOOD_CACHE_ITEMSIZE) /* TiFlootNetwork * distance The distance between current node and the tree root node. It's * measured by the minimal hopcount. For root node, the value is 0. */ #pragma pack(1) typedef struct{ uint8 state; TiNioNetLayerDispatcher * disp; uint8 distance; uint16 panto; uint16 panfrom; uint16 localaddress; uint8 seqid; TiFrame * txque; TiFrame * rxque; TiFrame * rxbuf; TiFunEventHandler listener; void * lisowner; char txque_mem[ FLOOD_FRAMEOBJECT_SIZE ]; char rxque_mem[ FLOOD_FRAMEOBJECT_SIZE ]; char rxbuf_mem[ FLOOD_FRAMEOBJECT_SIZE ]; _TiFloodCache * cache; char cache_mem[ FLOOD_CACHE_HOPESIZE ]; }TiFloodNetwork; TiFloodNetwork * flood_construct( void * mem, uint16 size ); void flood_destroy( TiFloodNetwork * net ); TiFloodNetwork * flood_open( TiFloodNetwork * net, TiNioNetLayerDispatcher * disp, TiFunEventHandler listener, void * lisowner, uint16 pan, uint16 localaddress ); void flood_close( TiFloodNetwork * net ); uint8 flood_broadcast( TiFloodNetwork * net, TiFrame * frame, uint8 option ); uint8 flood_send( TiFloodNetwork * net, uint16 shortaddrto, TiFrame * frame, uint8 option ); uint8 flood_recv( TiFloodNetwork * net, TiFrame * frame, uint8 option ); void flood_set_listener( TiFloodNetwork * net, TiFunEventHandler listener, void * owner ); void flood_evolve( void * netptr, TiEvent * e ); void flood_rxhandler(TiFloodNetwork * net,TiFrame * frame, TiFrame *fwbuf); void flood_txhandler(TiFloodNetwork * net,TiFrame * frame, TiFrame *fwbuf); #ifdef __cplusplus } #endif #endif /* _SVC_NIO_FLOOD_H_4764_ */
openwsn/node
opennode2010_keil/common/openwsn/svc/svc_nio_flood.h
C
gpl-2.0
7,609
Meteor.publish('applications-counter', function (id,skip,limit,filter,flagged) { if (flagged==false){ query = sectionQueryBuilder(filter,'sub') var cursor = Project.find({'osxcollector_section':'applications','osxcollector_incident_id':id,"$or":query}) Counts.publish(this, 'applications-counter',cursor,{noReady: true}) }else if(flagged == true && filter==""){ var cursor = Project.find({'osxcollector_section':'applications','osxcollector_incident_id':id,'flagged':true}) Counts.publish(this, 'applications-counter',cursor,{noReady: true}) }else{ query = sectionQueryBuilder(filter,'sub') var cursor = Project.find({'osxcollector_section':'applications','osxcollector_incident_id':id,"$or":query,'flagged':true}) Counts.publish(this, 'applications-counter',cursor,{noReady: true}) } }) Meteor.publish('applications', function (id,skip,limit,filter,flagged) { if (flagged==false){ query = sectionQueryBuilder(filter,'sub') return Project.find({'osxcollector_section':'applications','osxcollector_incident_id':id,"$or":query}, {limit: limit,skip: skip}) }else if (flagged==true && filter==""){ return Project.find({'osxcollector_section':'applications','osxcollector_incident_id':id,'flagged':true}, {limit: limit,skip: skip}) }else if(flagged == true && filter!=""){ query = sectionQueryBuilder(filter,'sub') return Project.find({'osxcollector_section':'applications','osxcollector_incident_id':id,"$or":query,'flagged':true}, {limit: limit,skip: skip}) }}) function sectionQueryBuilder(str,section){ var sep = str.split('::') list = [] for (var i = sep.length - 1; i >= 1; i--) { if(section=='sub'){ list.push({"osxcollector_subsection":sep[i]}) }else{ list.push({"osxcollector_section":sep[i]}) } } return list }
wfsec/osxstrata
server/pubs/applications.js
JavaScript
gpl-2.0
1,772
#ifndef __VRX218_A1PLUS_ADDR_DEF_INC #define __VRX218_A1PLUS_ADDR_DEF_INC //============================================================================= // Defines for "PPE DSL Notifications" Module //============================================================================= #define __DREG_BC0_LINK_STATUS 0x7DC0 #define __DREG_BC1_LINK_STATUS 0x7DD0 #define __DREG_MEI_STATE 0x7DC1 #define __DREG_PDBRAM_S_44K_OWN 0x7DC2 #define __DREG_SIGNATURE 0x7DC3 #define __SFSM_PGCNT0 0x741C #define __SFSM_PGCNT1 0x741D //============================================================================= // General Configuraton: 0x2000 - 0x202F // Need to be refined further //============================================================================= #define __FW_VER_ID 0x2001 #define __PP32_0_TIME 0x2002 #define __PP32_1_TIME 0x2003 #define __DSL_LINK_DOWN 0x2004 //Number of times DREG_PDBRAM_S_44K_OWN changes from S_44K_OWN_PPE to S_44K_OWN_DSL #define __PDBRAM_OWN_CHG_CNT 0x34B7 #define __CFG_WRX_HTUTS 0x2010 #define __STD_DES_CFG 0x2011 #define __CFG_STD_DATA_LEN __STD_DES_CFG #define __QOS_CFG 0x2012 #define __TX_QOS_CFG __QOS_CFG #define __QOSQ_FLOW_CTRL_CFG 0x2013 #define __CFG_TX_QOSQ_BANDWIDTH_CTRL __QOSQ_FLOW_CTRL_CFG #define __PSAVE_CFG 0x2014 #define __CFG_WRX_DMACH_ON 0x2015 #define __CFG_WTX_DMACH_ON 0x2016 #define __CFG_WRX_HUNT_BITTH 0x2017 #define __CFG_WAN_WRDES_DELAY 0x2018 #define __QOS_SHADOW_TTICK 0x201E #define __TX_QOS_CFG_SHADOW __QOS_SHADOW_TTICK #define __PP32_0_TASK_CFG 0x2020 #define __PP32_1_TASK_CFG 0x2021 #define __PP32_0_MODULE_ACTIVITY 0x2022 #define __PP32_1_MODULE_ACTIVITY 0x2023 #define __VRX218_FLOW_CTRL_CFG 0x2026 /* new */ //********************************************************************************* // MACRO to load the address to Register //********************************************************************************* #define xLDI_FW_VER_ID(__rd) ldi __rd 0 __FW_VER_ID #define xLDI_CFG_WRX_HTUTS(__rd) ldi __rd 0 __CFG_WRX_HTUTS #define xLDI_CFG_WAN_WRDES_DELAY(__rd) ldi __rd 0 __CFG_WAN_WRDES_DELAY #define xLDI_CFG_WRX_DMACH_ON(__rd) ldi __rd 0 __CFG_WRX_DMACH_ON #define xLDI_CFG_WTX_DMACH_ON(__rd) ldi __rd 0 __CFG_WTX_DMACH_ON #define xLDI_CFG_WRX_HUNT_BITTH(__rd) ldi __rd 0 __CFG_WRX_HUNT_BITTH #define xLDI_VRX218_FLOW_CTRL_CFG(__rd) ldi __rd 0 __VRX218_FLOW_CTRL_CFG //============================================================================= // Unified QoS Part //============================================================================= #define __INQ_QOS_CFG_BASE 0x2508 /* 0x2508-0x2509 2 x 1 = 2 */ #define __US_FAST_PATH_DES_LIST_BASE 0x2580 /* 0x2580-0x25FF 64 x 2 = 128 */ #define __US_CPU_PATH_DEST_LIST_BASE 0x3D00 /* 0x3D00-0x3D7F 64 x 2 = 128 */ #define __QOSQ_OVERFLOW_STATE_BMAP 0x250c /* 0x250c-0x250c 1 x 1 = 1 */ #define __QOSQ_CFG_CTXT_BASE 0x2FE0 /* 0x2FE0-0x2FFF 16 x 2 = 32 */ #define __QOSQ_PSEUDO_DES_CFG_BASE 0x2E80 /* 0x2E80-0x2EFF 16 x 8 = 128 */ #define __US_QOSQ_DES_LIST_BASE 0x2800 /* 0x2800-0x2BFF 512 x 2 = 1024 */ #define __QOSQ_PKT_CNT 0x2680 /* 0x2680-0x268f 16 x 1 = 1 */ #define __QOSQ_MIB_BASE 0x2030 /* 0x2030-0x20AF 16 x 8 = 128 */ #define __QOSQ_EVENT_MBOX_INT_CFG 0x3F10 /* 0x3F10-0x3F13 1 x 4 = 4 */ #define __SWAPQ_CFG_CTXT_BASE 0x2500 /* 0x2500-0x2501 1 * 2 = 2 */ #define __SWAPQ_DES_LIST_BASE 0x3F60 /* 0x3F60-0x3F9F 32 * 2 = 64 */ #define __DESQ_MBOX_INT_CFG 0x3F14 /* 0x3F14-0x3F1F 6 x 2 = 12 */ #define __US_FP_INQ_DES_CFG_CTXT 0x20B0 /* 0x20B0-0x20B7 1 x 8 = 8 */ #define __US_CPU_INQ_DES_CFG_CTXT 0x20B8 /* 0x20B8-0x20BF 1 x 8 = 8 */ //============================================================================= // Des Queues, eDMA copy channel mgm, des_sync (SmartPhy Part) //============================================================================= #define __US_TC_LOCAL_Q_CFG_CTXT_BASE 0x2E00 /* 0x2E00-0x2E7F 16 x 8 = 128 */ #define __US_TC_LOCAL_Q_DES_LIST_BASE 0x2360 /* 0x2360-0x238F 1 x 48= 48 */ #define __US_EDMA_COPY_CH_CFG 0x2340 /* 0x2340-0x234F 16 x 1 = 16 */ #define __US_EDMA_READ_CH_CFG_CTXT 0x2798 /* 0x2798-0x279F 1 x 8 = 8 */ #if (LLE_IN_PDBRAM == 1) // To optimize EDMA read/write performance, EDMA_LLE is moved to PDBRAM, EDMA_LLE_EXT // size is also increased to 6 to ease FW process (Apr 24, 2012) #define __US_EDMA_LLE_BASE 0x6600 /* 0x6600-0x66C5 33 x 6 = 198*/ #else #define __US_EDMA_LLE_BASE 0x2390 /* 0x2390-0x2455 33 x 6 = 198*/ #endif #define __US_EDMA_LLE_FPI_BASE 0x1E0A3800 /* 0x1E0A3800-0x1E0A3B17 33 x 24 = 792 bytes*/ #define __US_EDMA_LLE_EXT_BASE 0x3796 /* 0x3796-0x385B 33 x 6 = 198 */ #define __DS_TC_AAL5_LOCAL_Q_CFG_CTXT 0x20E0 /* 0x20E0-0x20E7 1 x 8 = 8 */ #define __DS_TC_OAM_LOCAL_Q_CFG_CTXT 0x20E8 /* 0x20E8-0x20EF 1 x 8 = 8 */ #define __DS_TC_LOCAL_AAL5Q_DES_LIST_BASE 0x3F20 /* 0x3F20-0x3F5F 32 x 2 = 64 */ #define __DS_TC_LOCAL_OAMQ_DES_LIST_BASE 0x24D0 /* 0x24D0-0x24EF 16 x 2 = 32 */ #define __DS_PKT_DESQ_CFG_CTXT 0x20F0 /* 0x20F0-0x20F7 1 x 8 = 8 */ #define __DS_PKT_DES_LIST_BASE 0x2600 /* 0x2600-0x263F 32 x 2 = 64*/ #define __DS_OAM_DESQ_CFG_CTXT 0x20F8 /* 0x20F8-0x20FF 1 x 8 = 8 */ #define __DS_OAM_DES_LIST_BASE 0x2640 /* 0x2640-0x267F 32 x 2 = 64*/ #define __DS_EDMA_COPY_CH_CFG 0x250A /* 0x250A-0x250B 2 x 1 = 2 */ #define __DS_EDMA_WRITE_CH_CFG_CTXT 0x2790 /* 0x2790-0x2798 1 x 8 = 8 */ #if (LLE_IN_PDBRAM == 1) // To optimize EDMA read/write performance, EDMA_LLE is moved to PDBRAM, EDMA_LLE_EXT // size is also increased to 6 to ease FW process (Apr 24, 2012) #define __DS_EDMA_LLE_BASE 0x6700 /* 0x6700-0x67C5 33 x 6 = 198*/ #else #define __DS_EDMA_LLE_BASE 0x3600 /* 0x3600-0x36C5 33 x 6 = 198*/ #endif #define __DS_EDMA_LLE_FPI_BASE 0x1E0A3C00 /* 0x1E0A3C00-0x1E0A3F17 33 x 24 = 792 bytes*/ #define __DS_EDMA_LLE_EXT_BASE 0x36D0 /* 0x36D0-0x3795 33 x 6 = 198 */ #define __DES_SYNC_CFG_CTXT 0x2F00 /* 0x2F00-0x2FBF 6 x 32= 192*/ #define __CDMA_DES_SYNC_DEST_LIST_BASE 0x27A0 /* 0x27A0-0x27FF 6 x 4 x 2 x 2 = 96 */ #define __EDMA_RD_CNT_SM 0x2560 /* 0x2560-0x256F 1 x 16= 16 */ // To optimize EDMA read/write performance, EDMA_LLE is moved to PDBRAM. // 0x1E0A2000-0x1E0A3FFF, (second half of PDBRAM8 0x1E0A0000-0x1E0A3FFF) // the last 2k bytes are used for EDMA_LLE // __US_EDMA_LLE_BASE: 0x6600-0x66FF (FPI: 0x1E0A3800-0x1E0A3BFF) // __US_EDMA_LLE_BASE: 0x6700-0x67FF (FPI: 0x1E0A3C00-0x1E0A3FFF) #define __EDMA_LLE_BLOCK_FPI_ADDR 0x1E0A2000 #define __EDMA_LLE_BLOCK_FPI_ADDR_Hi 0x1E0A #define __EDMA_LLE_BLOCK_FPI_ADDR_Lo 0x2000 #define xLDI_edma_lle_block_fpi_addr(__rd) \ xLDI_dword(__rd, __EDMA_LLE_BLOCK_FPI_ADDR_Hi, __EDMA_LLE_BLOCK_FPI_ADDR_Lo) #if (LLE_IN_PDBRAM == 1) #define __US_EDMA_LLE_LINK_ELEM 0x66C0 /* 0x6600-0x66C5 33 x 6 = 198*/ #define __DS_EDMA_LLE_LINK_ELEM 0x67C0 /* 0x6700-0x67C5 33 x 6 = 198*/ #else #define __US_EDMA_LLE_LINK_ELEM 0x2450 /* 0x2390-0x2455 33 x 6 = 198*/ #define __DS_EDMA_LLE_LINK_ELEM 0x36C0 /* 0x3600-0x36C5 33 x 6 = 198*/ #endif #define __EDMA_HANG_BENCH_RD_IDX 0x2510 /*0x2510-0x2511 0:write channel 1: read channel*/ #define __EDMA_HANG_DETECT_CNT 0x2512 /*0x2512-0x2513 0:write channel 1: read channel*/ #define __EDMA_HANG_DETECT_TH 0x2514 /* 1Dword*/ #define __EDMA_HANG_DETECT_MIB 0x2516 /* 1Dword*/ //---------------------------------------------------------- // Detailed Memory Allocation //---------------------------------------------------------- //********************************************** //"Unified QoS" Module Memory Allocation - START //********************************************** //2 INQs; CPU Path & Fast Path #define __INQ_QOS_CFG_BASE 0x2508 #define __INQ_QOS_CFG_END 0x2509 #define __INQ_QOS_CFG_SIZE 1 //16 QoSQs #define __QOSQ_CFG_CTXT_BASE 0x2FE0 #define __QOSQ_CFG_CTXT_END 0x2FFF #define __QOSQ_CFG_CTXT_SIZE 2 //16 QoSQs #define __QOSQ_MIB_BASE 0x2030 #define __QOSQ_MIB_END 0x20AF #define __QOSQ_MIB_SIZE 8 //#define __SWAPQ_CFG_CTXT_BASE 0x2500 #define __SWAPQ_CFG_CTXT_DW1_ADDR 0x2501 #define __SWAPQ_CFG_CTXT_END 0x2501 #define __SWAPQ_CFG_CTXT_SIZE 2 //********************************************** //"Unified QoS" Module Memory Allocation - END //********************************************** #define __DES_SYNC_CFG_CTXT_BASE __DES_SYNC_CFG_CTXT #define __DES_SYNC_CFG_CTXT_BASE_END 0x2FBF #define __DES_READ_SYNC_CFG_CTXT_BASE __DES_SYNC_CFG_CTXT_BASE #define __DES_READ_SYNC_CFG_CTXT_END __DES_SYNC_CFG_CTXT_BASE_END #define __DES_WRITE_SYNC_CFG_CTXT_BASE __DES_SYNC_CFG_CTXT_BASE #define __DES_WRITE_SYNC_CFG_CTXT_END __DES_SYNC_CFG_CTXT_BASE_END #define __EDMA_CH_CTXT_BASE __DS_EDMA_WRITE_CH_CFG_CTXT #define __EDMA_WRITE_CH_CTXT __DS_EDMA_WRITE_CH_CFG_CTXT #define __EDMA_READ_CH_CTXT __US_EDMA_READ_CH_CFG_CTXT #define __EDMA_CH_CTXT_BASE_END 0x27A0 #define __EDMA_WRITE_COPY_CH_CFG_BASE __DS_EDMA_COPY_CH_CFG #define __EDMA_WRITE_COPY_CH_CFG_END 0x250C #define __EDMA_READ_COPY_CH_CFG_BASE __US_EDMA_COPY_CH_CFG #define __EDMA_READ_COPY_CH_CFG_END 0x2350 // SB = 0x7000 #define __WRITE_CH_DOORBELL_EXT_ADDR 0x1E700980 #define __WRITE_CH_DOORBELL_EXT_ADDR_hi 0x1E70 #define __WRITE_CH_DOORBELL_EXT_ADDR_lo 0x0980 // SB = 0x7001 #define __READ_CH_DOORBELL_EXT_ADDR 0x1E709A0 #define __READ_CH_DOORBELL_EXT_ADDR_hi 0x1E70 #define __READ_CH_DOORBELL_EXT_ADDR_lo 0x09A0 //--------------------------------------------------------------- // EDMA_RD_CNT_SM related #define __EDMA_WRITE_CH_STATUS_SBADDR 0x2350 #define __EDMA_READ_CH_STATUS_SBADDR 0x2358 #define __EDMA_CH_CTXT_IDX_FPI_ADDR 0x1E700A6C #define __EDMA_CH_CTXT_IDX_FPI_hi 0x1E70 #define __EDMA_CH_CTXT_IDX_FPI_low 0x0A6C #define xLDI_edma_ch_ctxt_idx_fpi_addr(__rd) \ xLDI_dword(__rd, __EDMA_CH_CTXT_IDX_FPI_hi, __EDMA_CH_CTXT_IDX_FPI_low) #define __EDMA_LL_PTR_LOW_FPI_ADDR 0x1E700A8C #define __EDMA_LL_PTR_LOW_FPI_hi 0x1E70 #define __EDMA_LL_PTR_LOW_FPI_lo 0x0A8C #define xLDI_edma_ll_ptr_fpi_addr(__rd) \ xLDI_dword(__rd, __EDMA_LL_PTR_LOW_FPI_hi, __EDMA_LL_PTR_LOW_FPI_lo) #define __EDMA_CH_STATUS_LOW_FPI_ADDR 0x1E700A70 #define __EDMA_CH_STATUS_LOW_FPI_hi 0x1E70 #define __EDMA_CH_STATUS_LOW_FPI_lo 0x0A70 #define xLDI_edma_ch_status_fpi_addr(__rd) \ xLDI_dword(__rd, __EDMA_CH_STATUS_LOW_FPI_hi, __EDMA_CH_STATUS_LOW_FPI_lo) //============================================================================= // Extra DS packet buffer for A1Plus to avoid DS packet drop (due to no descriptors) // total 13 packets // packet size = 400 DWs = 1600 bytes //============================================================================= #define __DS_SB_PKT_DATA_PTR_0 0x2100 /* 0x2100-0x228F, size = 400DW */ #define __DS_SB_PKT_DATA_PTR_1 0x2C00 /* 0x2C00-0x2D8F, size = 400DW */ #define __DS_SB_PKT_DATA_PTR_2 0x3000 /* 0x3000-0x318F, size = 400DW */ #define __DS_SB_PKT_DATA_PTR_3 0x3190 /* 0x3190-0x331F, size = 400DW */ #define __DS_SB_PKT_DATA_PTR_4 0x3D80 /* 0x3D80-0x3F0F, size = 400DW */ #define __DS_SB_PKT_DATA_PTR_5 0x44E0 /* 0x44E0-0x466F, size = 400DW */ #define __DS_SB_PKT_DATA_PTR_6 0x4670 /* 0x4670-0x47FF, size = 400DW */ #define __DS_SB_PKT_DATA_PTR_7 0x4800 /* 0x4800-0x498F, size = 400DW */ #define __DS_SB_PKT_DATA_PTR_8 0x4990 /* 0x4990-0x4B1F, size = 400DW */ #define __DS_SB_PKT_DATA_PTR_9 0x4D40 /* 0x4D40-0x4ECF, size = 400DW */ #define __DS_SB_PKT_DATA_PTR_10 0x5B00 /* 0x5B00-0x5C8F, size = 400DW */ #define __DS_SB_PKT_DATA_PTR_11 0x5C90 /* 0x5C90-0x5E1F, size = 400DW */ #define __DS_SB_PKT_DATA_PTR_12 0x5E20 /* 0x5E20-0x5FAF, size = 400DW */ //============================================================================= // DS OAM packet in share buffer for A1Plus // total 10 packets // packet size = 32 DWs = 128 bytes //============================================================================= #define __DS_SB_OAM_DATA_PTR_0 0x3BC0 /* 0x3BC0-0x3BDF, size = 32 DW */ #define __DS_SB_OAM_DATA_PTR_1 0x3BE0 /* 0x3BE0-0x3BFF, size = 32 DW */ #define __DS_SB_OAM_DATA_PTR_2 0x3C00 /* 0x3C00-0x3C1F, size = 32 DW */ #define __DS_SB_OAM_DATA_PTR_3 0x3C20 /* 0x3C20-0x3C3F, size = 32 DW */ #define __DS_SB_OAM_DATA_PTR_4 0x3C40 /* 0x3C40-0x3C5F, size = 32 DW */ #define __DS_SB_OAM_DATA_PTR_5 0x3C60 /* 0x3C60-0x3C7F, size = 32 DW */ #define __DS_SB_OAM_DATA_PTR_6 0x3C80 /* 0x3C80-0x3C9F, size = 32 DW */ #define __DS_SB_OAM_DATA_PTR_7 0x3CA0 /* 0x3CA0-0x3CBF, size = 32 DW */ #define __DS_SB_OAM_DATA_PTR_8 0x3CC0 /* 0x3CC0-0x3CDF, size = 32 DW */ #define __DS_SB_OAM_DATA_PTR_9 0x3CE0 /* 0x3CE0-0x3CFF, size = 32 DW */ //============================================================================= // A1+ part //============================================================================= /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ S_addr E_addr Size General Context 1 5000 51FF 512 DSL WAN MIB Length 4EF0 4EFF 16 DSL WAN RX VC MIB Length (A5 Only) 4F00 4F3F 64 DSL WAN TX VC MIB Length (A5 Only) 4F40 4F7F 64 HTU table 26A0 26FF 96 WAN RX Queue Configuration/Context Length 4C00 4D3F 320 WAN RX DMA Channel Configuration/Context Length 4F80 4FB7 56 WAN TX Queue/DMA Configuration/Context Length 3A00 3BAF 432 WAN TX Port Configuration Length 4FB8 4FB9 2 SFSM 0 (pages) - Data 5200 557F 896 SFSM 0 (pages) - Ctrl 5A80 5ABF 64 FFSM 0 (pages) - Data 4000 422F 560 SFSM 1 (pages) - Data 5640 59BF 896 SFSM 1 (pages) - Ctrl 5AC0 5AFF 64 FFSM 1 (pages) - Data 42A8 44D7 560 EMA Command Buffer 5580 559F 32 EMA Data Buffer 55A0 55DF 64 WAN RX Port Context 55E0 55EF 16 WAN TX Port Context 4FBA 4FBB 2 WAN TX&RX Port Context EXT Length 55F0 55FF 16 WAN RX Descriptor Prefetch Buffer 3900 39FF 256 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ //******************************************** // detailed allocation //******************************************** //---------------------------------- // WAN RX Descriptor Prefetch Buffer // 0x5B00 - 0x5BFF // Size = 16 * 16 = 256 dwords //---------------------------------- // #define __WRX_DES_PREFETCH_BUF 0x2600 // FPI dw address for PPE sharebuffer at 0x0000 #define xLDI_PPE_SB2000H_FPI_DW_ADDR(r_d) \ ldi r_d 16 0x788 \ addi r_d r_d 0x6000 //------------------------------------ // WAN RX ALL5 Channel Descriptor List // 0x5B00 - 0x5B3F // Size = 32 * 2 = 64 dwords //------------------------------------ // #define __WRX_PKT_DES_BUF 0x2600 //------------------------------------ // WAN RX OAM Channel Descriptor List // 0x5B40 - 0x5B7F // Size = 32 * 2 = 64 dwords //------------------------------------ // #define __WRX_OAM_DES_BUF 0x2640 //--------------------------------------------- // DSL WAN MIB (0x4EF0 - 0x4EFF) //--------------------------------------------- #define __WRX_DROPHTU_CELL 0x4EF1 #define __WRX_DROPDES_PDU 0x4EF2 #define __WRX_CORRECT_PDU 0x4EF3 #define __WRX_ERR_PDU 0x4EF4 #define __WRX_DROPDES_CELL 0x4EF5 #define __WRX_CORRECT_CELL 0x4EF6 #define __WRX_ERR_CELL 0x4EF7 #define __WRX_TOTAL_BYTE 0x4EF8 #define __WTX_TOTAL_PDU 0x4EFA #define __WTX_TOTAL_CELL 0x4EFB #define __WTX_TOTAL_BYTE 0x4EFC //-------------------------- // DSL WAN RX VC MIB // 0x4F00 - 0x4F3F // Size = 16 * 4 = 64 dwords //-------------------------- #define __WRX_VC_MIB_BASE 0x4F00 #define __WRX_VC_IG_PKTS_OFF 0 #define __WRX_VC_IG_BYTES_OFF 1 //-------------------------- // DSL WAN TX VC MIB // 0x4F40 - 0x4F7F // Size = 16 * 4 = 64 dwords //-------------------------- #define __WTX_VC_MIB_BASE 0x4F40 #define __WRX_VC_EG_PKTS_OFF 1 #define __WRX_VC_EG_BYTES_OFF 2 //---------------------------- // HTU Table (0x26A0 - 0x26FF) //---------------------------- #define __HTU_ENTRY_TABLE 0x26A0 #define __HTU_MASK_TABLE 0x26C0 #define __HTU_RESULT_TABLE 0x26E0 //--------------------------------------- // WAN RX Queue (Configuration + Context) // 0x4C00 - 0x4D3F //--------------------------------------- #define __WRX_QUEUE_CONFIG 0x4C00 //--------------------------------------------- // WAN RX DMA Channel Configuration/Context // 0x4F80 - 0x4FB7 // pkt queue descriptor rdptr, wrptr // oam queue descriptor rdptr, wrptr //--------------------------------------------- #define __WRX_QUEUE_CHANNEL_CONTEXT 0x4F80 //--------------------------------------- // WAN TX Queue/DMA Configuration/Context //--------------------------------------- #define __WTX_QUEUE_CONFIG 0x3A00 //------------------------ // DSL WAN RX Port Context // 0x55E0 - 0x55EF //------------------------ #define __WRXCTXT_TC_RdPtr0 0x55E0 #define __WRXCTXT_TC_RdPtr1 0x55E1 #define __WRXCTXT_L2_RdPtr0 0x55E2 #define __WRXCTXT_L2_RdPtr1 0x55E3 #define __WRXCTXT_L2Pages0 0x55E4 #define __WRXCTXT_L2Pages1 0x55E5 #define __WRXCTXT_MatchCells0 0x55E6 #define __WRXCTXT_MatchCells1 0x55E7 #define __WRXCTXT_NoMatchCells0 0x55E8 #define __WRXCTXT_NoMatchCells1 0x55E9 #define __WRXCTXT_PortState0 0x55EA #define __WRXCTXT_PortState1 0x55EB #define __WRXCTXT_Hunt_Cnt0 0x55EC #define __WRXCTXT_Hunt_Cnt1 0x55ED //************************** //DSL WAN context definition //************************** //--------------------------------------- // WAN EMA CMD BUFFER : 0x5580 - 0x559F // EMA DATA BUFFER : 0x55A0 - 0x55DF //--------------------------------------- #define __EMA_CMD_BUF 0x5580 #define __EMA_DATA_BUF 0x55A0 #define __WAN_EMA_CMD_BUF __EMA_CMD_BUF #define __WAN_EMA_DATA_BUF __EMA_DATA_BUF //-------------------------------------- // WAN TX Port Context (0x4FBA - 0x4FBB) //-------------------------------------- #define __WTXCTXT_TC_WRPTR0 0x4FBA #define __WTXCTXT_TC_WRPTR1 0x4FBB //-------------------------------------------------- // WAN TX Port Context (extension) (0x55F0 - 0x55F1) //-------------------------------------------------- #define __WTXCTXT_WtxDBufStart0 0x55F0 #define __WTXCTXT_WtxDBufStart1 0x55F1 //-------------------------------------------------- // WAN RX Port Context (extension) (0x55FC - 0x55FF) //-------------------------------------------------- #define __WRXCTXT_WrxDBufStart0 0x55FC #define __WRXCTXT_WrxDBufStart1 0x55FD #define __WRXCTXT_WrxCBufStart0 0x55FE #define __WRXCTXT_WrxCBufStart1 0x55FF //-------------------------------------------- // WAN TX Port Configuration (0x4FB8 - 0x4FB9) //-------------------------------------------- #define __WTX_PORT_CONFIG0 0x4FB8 #define __WTX_PORT_CONFIG1 0x4FB9 //============================================= // General Context (0x5000 - 0x51FF) // 0x5000 - 0x50FF used in addr_def_vr9.inc //============================================= //Verify //---------------------------------------------------- // WAN TX ETH HEADER PREFETCH BUFFER (0x5100 - 0x513F) //---------------------------------------------------- #define __WTX_ETH_HEADER_BUF_BASE 0x5100 //--------------------------------------------- // WAN - ATM General Context (0x5140 - 0x517F) //--------------------------------------------- #define __FWGEN_BITS_WORD0 0x5140 #define __FWGEN_WRX_WREMA_PEND_DID 0x5141 #define __FWGEN_WTX_WRDES_PEND_DID 0x5142 #define __FWGEN_WRX_WRDES_PEND_DID 0x5143 #define __FWGEN_WTX_WRDES_FINAL_PEND_DID 0x5144 #define __FWGEN_WRX_WRDES_FINAL_PEND_DID 0x5145 #define __FWGEN_WTX_RDDATA_PEND_QID 0x5146 #define __FWGEN_WTX_CELLBUF_EMPTY_STATUS 0x5147 #define __FWGEN_WTX_DMACH_NONEMPTY_STATUS 0x5148 #define __FWGEN_WRX_DMACH_NONEMPTY_STATUS 0x5149 #define __FWGEN_WRX_DMACH_VLD_STATUS 0x514A #define __FWGEN_WRX_VEN 0x514B #define __FWGEN_WRX_DES_PREFETCH_DID 0x514C #define __FWGEN_WRX_DID 0x514D #define __FWGEN_EMA_CMD0 0x514E #define __FWGEN_EMA_CMD1 0x514F #define __FWGEN_WRX_CELL_TYPE 0x5150 #define __FWGEN_WRX_CELLID 0x5151 #define __FWGEN_WRX_DESBUF_NONFULL_STATUS 0x5152 #define __FWGEN_WTX_DES_PREFETCH_QID 0x5153 #define __FWGEN_WTX_DES_PREFETCH_DID 0x5154 #define __FWGEN_WTX_CURRDES_VLD_STATUS 0x5155 #define __FWGEN_WTX_DESBUF_NONFULL_STATUS 0x5156 #define __FWGEN_VAR_DES0 0x5158 #define __FWGEN_VAR_DES1 0x5159 #define __FWGEN_WRX_CELL_HEADER 0x515A //#define __FWGEN_VAR_EMADATA_WRPTR 0x515B #define __FWGEN_WRX_QID 0x515C #define __FWGEN_VAR_DWNUM 0x515D #define __FWGEN_VAR_CURR_LEN 0x515E #define __FWGEN_VAR_TRAILER_LEN 0x515F #define __FWGEN_VAR_TRAILER_UU 0x5160 #define __FWGEN_VAR_TRAILER_CPI 0x5161 #define __FWGEN_VAR_STW 0x5162 #define __FWGEN_WTX_QID 0x5163 #define __FWGEN_VAR_BMC_CMD0 0x5164 #define __FWGEN_VAR_DW_OFF 0x5165 #define __FWGEN_VAR_LAST_CELL 0x5166 #define __FWGEN_VAR_FILL_CELL 0x5167 #define __FWGEN_VAR_EXP_LEN 0x5168 #define __FWGEN_WTX_CELL_HEADER 0x5169 #define __FWGEN_VAR_BYTEOFF 0x516A #define __FWGEN_WTX_DATA_PREFETCH_QID 0x516B #define __FWGEN_WRX_PID 0x516C #define __FWGEN_WTX_PID 0x516D #define __FWGEN_CELLS_QUEUED_0 0x516E #define __FWGEN_CELLS_QUEUED_1 0x516F #define __FWGEN_SPACE_PENDING0 0x5170 #define __FWGEN_SPACE_PENDING1 0x5171 #define __FWGEN_VAR_BMC_CMD1 0x5172 #define __FWGEN_WRX_DESREQ_NONPEND_STATUS 0x5173 #define __FWGEN_WTX_DESREQ_NONPEND_STATUS 0x5174 #define __FWGEN_WTX_CELLREQ_NONPEND_STATUS 0x5175 #define __FWGEN_PREV_EMA_ISR 0x5176 #define __FWGEN_MBOX0_ISR 0x5177 #define __FWGEN_WTX_1ST_CELL_READ_FLAG0 0x5178 #define __FWGEN_WTX_1ST_CELL_READ_FLAG1 0x5179 // upstream local queue nonempty flag // bit0 to bit15 correspond to q0 to q15 // if a bit is set, the corresponding queue is nonempty #define __US_TC_LOCAL_Q_FULL_FLAG 0x517A #ifdef VR9_FIRMWARE_DESCRAMBER #define _FW_DESCRAMBER_POLY_H 0x517E #define _FW_DESCRAMBER_POLY_L 0x517F #endif //============================================= // EMA Context (0x518E-0x518F) //============================================= #define __EMA_CONTEXT_CMD_WRPTR 0x518E #define __EMA_CONTEXT_DATA_WRPTR 0x518F #define __WAN_EMA_CONTEXT_CMD_WRPTR __EMA_CONTEXT_CMD_WRPTR #define __WAN_EMA_CONTEXT_DATA_WRPTR __EMA_CONTEXT_DATA_WRPTR //----------------------------------------------------- // WAN RX Decap buffer (0x5190 - 0x51AF) //temp address //----------------------------------------------------- #define __WRX_DECAP_BUF_BASE 0x5190 #define __WRX_DECAP_BUF_BASE_HW 0x3190 //0x51B0 - 0x51BF #define __FWGEN_WTX_QSB_VC_CONTEXT_BASE 0x51B0 //-------------------------------------- // WRX General Context (0x51C0 - 0x51C8) //-------------------------------------- #define __FWGEN_WRX_2684_ORIGINAL_FLAG 0x51C0 #define __FWGEN_WRX_2684_CELL_ALIGN_OFF 0x51C1 #define __FWGEN_WRX_2684_MPOA_TYPE 0x51C2 #define __FWGEN_WRX_AAL5_CELL1_ROUNDDOWN_DWNUM 0x51C3 #define __FWGEN_WRX_DES_BYTES 0x51C4 #define __FWGEN_WRX_FIRST_CELL 0x51C5 #define __FWGEN_WRX_PKT_LEN_WO_FCS 0x51C6 #define __FWGEN_WRX_ETH_TYPE 0x51C7 #define __FWGEN_WRX_MAC_BYTE 0x51C8 //-------------------------------------- // WTX General Context (0x51C9 - 0x51DF) //-------------------------------------- #define __FWGEN_WTX_ETH_IS_VLAN 0x51C9 #define __FWGEN_WTX_MPOA_PT 0x51CA #define __FWGEN_WTX_ENCAP_PARSE_DROP 0x51CB #define __FWGEN_WTX_2684_RM_LEN 0x51CC #define __FWGEN_WTX_2684_INSERT_LEN 0x51CD #define __FWGEN_WTX_RDWNUM 0x51CE #define __FWGEN_WTX_SWOFF 0x51CF #define __FWGEN_WTX_CELL1_BYTEOFF 0x51D0 #define __FWGEN_WTX_ETH_IS_IPV4 0x51D1 #define __FWGEN_WTX_ETH_IPOFF 0x51D2 #define __FWGEN_WTX_QPKT_LEVEL_CONTROL 0x51D3 #define __FWGEN_WTX_ETH_HD_DONE 0x51D4 //--------------------------------------------------- // Task pending flag for power save in A1plus //--------------------------------------------------- #define __TASK_PENDING_FLAG_VRX318_PPA 0x51E0 #define __WAKEUP_MIB_VRX318 0x51E1 //******************************************** // Macros to LOAD above Addresses //******************************************** #define xLDI_WRX_DES_PREFETCH_BUF(__rd) ldi __rd 0 __WRX_DES_PREFETCH_BUF #define xLDI_WRX_PKT_DES_BUF(__rd) ldi __rd 0 __WRX_PKT_DES_BUF #define xLDI_WRX_OAM_DES_BUF(__rd) ldi __rd 0 __WRX_OAM_DES_BUF //--------------------------------------------- // DSL WAN MIB (total) - atm //--------------------------------------------- #define xLDI_WRX_DROPHTU_CELL(__rd) ldi __rd 0 __WRX_DROPHTU_CELL #define xLDI_WRX_DROPDES_PDU(__rd) ldi __rd 0 __WRX_DROPDES_PDU #define xLDI_WRX_CORRECT_PDU(__rd) ldi __rd 0 __WRX_CORRECT_PDU #define xLDI_WRX_ERR_PDU(__rd) ldi __rd 0 __WRX_ERR_PDU #define xLDI_WRX_DROPDES_CELL(__rd) ldi __rd 0 __WRX_DROPDES_CELL #define xLDI_WRX_CORRECT_CELL(__rd) ldi __rd 0 __WRX_CORRECT_CELL #define xLDI_WRX_ERR_CELL(__rd) ldi __rd 0 __WRX_ERR_CELL #define xLDI_WRX_TOTAL_BYTE(__rd) ldi __rd 0 __WRX_TOTAL_BYTE #define xLDI_WTX_TOTAL_PDU(__rd) ldi __rd 0 __WTX_TOTAL_PDU #define xLDI_WTX_TOTAL_CELL(__rd) ldi __rd 0 __WTX_TOTAL_CELL #define xLDI_WTX_TOTAL_BYTE(__rd) ldi __rd 0 __WTX_TOTAL_BYTE //--------------------------------------------- // DSL WAN MIB (VC) - atm //--------------------------------------------- #define xLDI_WRX_VC_MIB_BASE(__rd) ldi __rd 0 __WRX_VC_MIB_BASE //--------------------------------------------- // HTU Table //--------------------------------------------- #define xLDI_HTU_ENTRY_TABLE(__rd) ldi __rd 0 __HTU_ENTRY_TABLE #define xLDI_HTU_MASK_TABLE(__rd) ldi __rd 0 __HTU_MASK_TABLE #define xLDI_HTU_RESULT_TABLE(__rd) ldi __rd 0 __HTU_RESULT_TABLE //--------------------------------------------- // WAN RX Queue (Configuration + Context) //--------------------------------------------- #define xLDI_WRX_QUEUE_CONFIG(__rd) ldi __rd 0 __WRX_QUEUE_CONFIG #define xLDI_WRX_QUEUE_CHANNEL_CONTEXT(__rd) ldi __rd 0 __WRX_QUEUE_CHANNEL_CONTEXT //--------------------------------------------- // WAN TX Queue (Configuration + DMA + Q_Context + DES_Context) //--------------------------------------------- #define xLDI_WTX_QUEUE_CONFIG(__rd) ldi __rd 0 __WTX_QUEUE_CONFIG //--------------------------------------------- // WAN TX Port Configuration //--------------------------------------------- #define xLDI_WTX_PORT_CONFIG0(__rd) ldi __rd 0 __WTX_PORT_CONFIG0 #define xLDI_WTX_PORT_CONFIG1(__rd) ldi __rd 0 __WTX_PORT_CONFIG1 //--------------------------------------------- // WAN EMA Context //--------------------------------------------- #define xLDI_WAN_EMA_CMD_BUF(__rd) ldi __rd 0 __EMA_CMD_BUF #define xLDI_WAN_EMA_DATA_BUF(__rd) ldi __rd 0 __EMA_DATA_BUF #define xLDI_EMA_CONTEXT_CMD_WRPTR(__rd) ldi __rd 0 __EMA_CONTEXT_CMD_WRPTR #define xLDI_EMA_CONTEXT_DATA_WRPTR(__rd) ldi __rd 0 __EMA_CONTEXT_DATA_WRPTR #define xLDI_WAN_EMA_CONTEXT_CMD_WRPTR(__rd) ldi __rd 0 __WAN_EMA_CONTEXT_CMD_WRPTR #define xLDI_WAN_EMA_CONTEXT_DATA_WRPTR(__rd) ldi __rd 0 __WAN_EMA_CONTEXT_DATA_WRPTR //--------------------------------------------- // DSL WAN RX Port Context //--------------------------------------------- #define xLDI_WRXCTXT_TC_RdPtr0(__rd) ldi __rd 0 __WRXCTXT_TC_RdPtr0 #define xLDI_WRXCTXT_TC_RdPtr1(__rd) ldi __rd 0 __WRXCTXT_TC_RdPtr1 #define xLDI_WRXCTXT_L2_RdPtr0(__rd) ldi __rd 0 __WRXCTXT_L2_RdPtr0 #define xLDI_WRXCTXT_L2_RdPtr1(__rd) ldi __rd 0 __WRXCTXT_L2_RdPtr1 #define xLDI_WRXCTXT_L2Pages0(__rd) ldi __rd 0 __WRXCTXT_L2Pages0 #define xLDI_WRXCTXT_L2Pages1(__rd) ldi __rd 0 __WRXCTXT_L2Pages1 #define xLDI_WRXCTXT_MatchCells0(__rd) ldi __rd 0 __WRXCTXT_MatchCells0 #define xLDI_WRXCTXT_MatchCells1(__rd) ldi __rd 0 __WRXCTXT_MatchCells1 #define xLDI_WRXCTXT_NoMatchCells0(__rd) ldi __rd 0 __WRXCTXT_NoMatchCells0 #define xLDI_WRXCTXT_NoMatchCells1(__rd) ldi __rd 0 __WRXCTXT_NoMatchCells1 #define xLDI_WRXCTXT_PortState0(__rd) ldi __rd 0 __WRXCTXT_PortState0 #define xLDI_WRXCTXT_PortState1(__rd) ldi __rd 0 __WRXCTXT_PortState1 #define xLDI_WRXCTXT_Hunt_Cnt0(__rd) ldi __rd 0 __WRXCTXT_Hunt_Cnt0 #define xLDI_WRXCTXT_Hunt_Cnt1(__rd) ldi __rd 0 __WRXCTXT_Hunt_Cnt1 //--------------------------------------------- // WAN TX Port Context //--------------------------------------------- #define xLDI_WTXCTXT_TC_WRPTR0(__rd) ldi __rd 0 __WTXCTXT_TC_WRPTR0 #define xLDI_WTXCTXT_TC_WRPTR1(__rd) ldi __rd 0 __WTXCTXT_TC_WRPTR1 //--------------------------------------------- // WAN TX Port Context (extension) //--------------------------------------------- #define xLDI_WTXCTXT_WtxDBufStart0(__rd) ldi __rd 0 __WTXCTXT_WtxDBufStart0 #define xLDI_WTXCTXT_WtxDBufStart1(__rd) ldi __rd 0 __WTXCTXT_WtxDBufStart1 //--------------------------------------------- // WAN RX Port Context (extension) //--------------------------------------------- #define xLDI_WRXCTXT_WrxDBufStart0(__rd) ldi __rd 0 __WRXCTXT_WrxDBufStart0 #define xLDI_WRXCTXT_WrxDBufStart1(__rd) ldi __rd 0 __WRXCTXT_WrxDBufStart1 #define xLDI_WRXCTXT_WrxCBufStart0(__rd) ldi __rd 0 __WRXCTXT_WrxCBufStart0 #define xLDI_WRXCTXT_WrxCBufStart1(__rd) ldi __rd 0 __WRXCTXT_WrxCBufStart1 //--------------------------------------------- // WAN - atm General Context //--------------------------------------------- #define xLDI_FWGEN_BITS_WORD0(__rd) ldi __rd 0 __FWGEN_BITS_WORD0 #define xLDI_FWGEN_WRX_WREMA_PEND_DID(__rd) ldi __rd 0 __FWGEN_WRX_WREMA_PEND_DID #define xLDI_FWGEN_WTX_WRDES_PEND_DID(__rd) ldi __rd 0 __FWGEN_WTX_WRDES_PEND_DID #define xLDI_FWGEN_WRX_WRDES_PEND_DID(__rd) ldi __rd 0 __FWGEN_WRX_WRDES_PEND_DID #define xLDI_FWGEN_WTX_WRDES_FINAL_PEND_DID(__rd) ldi __rd 0 __FWGEN_WTX_WRDES_FINAL_PEND_DID #define xLDI_FWGEN_WRX_WRDES_FINAL_PEND_DID(__rd) ldi __rd 0 __FWGEN_WRX_WRDES_FINAL_PEND_DID #define xLDI_FWGEN_WTX_RDDATA_PEND_QID(__rd) ldi __rd 0 __FWGEN_WTX_RDDATA_PEND_QID #define xLDI_FWGEN_WTX_CELLBUF_EMPTY_STATUS(__rd) ldi __rd 0 __FWGEN_WTX_CELLBUF_EMPTY_STATUS #define xLDI_FWGEN_WTX_DMACH_NONEMPTY_STATUS(__rd) ldi __rd 0 __FWGEN_WTX_DMACH_NONEMPTY_STATUS #define xLDI_FWGEN_WRX_DMACH_NONEMPTY_STATUS(__rd) ldi __rd 0 __FWGEN_WRX_DMACH_NONEMPTY_STATUS #define xLDI_FWGEN_WRX_DMACH_VLD_STATUS(__rd) ldi __rd 0 __FWGEN_WRX_DMACH_VLD_STATUS #define xLDI_FWGEN_WRX_VEN(__rd) ldi __rd 0 __FWGEN_WRX_VEN #define xLDI_FWGEN_WRX_DES_PREFETCH_DID(__rd) ldi __rd 0 __FWGEN_WRX_DES_PREFETCH_DID #define xLDI_FWGEN_WRX_DID(__rd) ldi __rd 0 __FWGEN_WRX_DID #define xLDI_FWGEN_EMA_CMD0(__rd) ldi __rd 0 __FWGEN_EMA_CMD0 #define xLDI_FWGEN_EMA_CMD1(__rd) ldi __rd 0 __FWGEN_EMA_CMD1 #define xLDI_FWGEN_WRX_CELL_TYPE(__rd) ldi __rd 0 __FWGEN_WRX_CELL_TYPE #define xLDI_FWGEN_WRX_CELLID(__rd) ldi __rd 0 __FWGEN_WRX_CELLID #define xLDI_FWGEN_WRX_DESBUF_NONFULL_STATUS(__rd) ldi __rd 0 __FWGEN_WRX_DESBUF_NONFULL_STATUS #define xLDI_FWGEN_WTX_DES_PREFETCH_QID(__rd) ldi __rd 0 __FWGEN_WTX_DES_PREFETCH_QID #define xLDI_FWGEN_WTX_DES_PREFETCH_DID(__rd) ldi __rd 0 __FWGEN_WTX_DES_PREFETCH_DID #define xLDI_FWGEN_WTX_CURRDES_VLD_STATUS(__rd) ldi __rd 0 __FWGEN_WTX_CURRDES_VLD_STATUS #define xLDI_FWGEN_WTX_DESBUF_NONFULL_STATUS(__rd) ldi __rd 0 __FWGEN_WTX_DESBUF_NONFULL_STATUS #define xLDI_FWGEN_DES0(__rd) ldi __rd 0 __FWGEN_VAR_DES0 #define xLDI_FWGEN_DES1(__rd) ldi __rd 0 __FWGEN_VAR_DES1 #define xLDI_FWGEN_WRX_CELL_HEADER(__rd) ldi __rd 0 __FWGEN_WRX_CELL_HEADER //#define xLDI_FWGEN_VAR_EMADATA_WRPTR(__rd) ldi __rd 0 __FWGEN_VAR_EMADATA_WRPTR #define xLDI_FWGEN_WRX_QID(__rd) ldi __rd 0 __FWGEN_WRX_QID #define xLDI_FWGEN_VAR_DWNUM(__rd) ldi __rd 0 __FWGEN_VAR_DWNUM #define xLDI_FWGEN_VAR_CURR_LEN(__rd) ldi __rd 0 __FWGEN_VAR_CURR_LEN #define xLDI_FWGEN_VAR_TRAILER_LEN(__rd) ldi __rd 0 __FWGEN_VAR_TRAILER_LEN #define xLDI_FWGEN_VAR_TRAILER_UU(__rd) ldi __rd 0 __FWGEN_VAR_TRAILER_UU #define xLDI_FWGEN_VAR_TRAILER_CPI(__rd) ldi __rd 0 __FWGEN_VAR_TRAILER_CPI #define xLDI_FWGEN_VAR_STW(__rd) ldi __rd 0 __FWGEN_VAR_STW #define xLDI_FWGEN_WTX_QID(__rd) ldi __rd 0 __FWGEN_WTX_QID #define xLDI_FWGEN_VAR_BMC_CMD0(__rd) ldi __rd 0 __FWGEN_VAR_BMC_CMD0 #define xLDI_FWGEN_VAR_DW_OFF(__rd) ldi __rd 0 __FWGEN_VAR_DW_OFF #define xLDI_FWGEN_VAR_LAST_CELL(__rd) ldi __rd 0 __FWGEN_VAR_LAST_CELL #define xLDI_FWGEN_VAR_FILL_CELL(__rd) ldi __rd 0 __FWGEN_VAR_FILL_CELL #define xLDI_FWGEN_VAR_EXP_LEN(__rd) ldi __rd 0 __FWGEN_VAR_EXP_LEN #define xLDI_FWGEN_WTX_CELL_HEADER(__rd) ldi __rd 0 __FWGEN_WTX_CELL_HEADER #define xLDI_FWGEN_VAR_BYTEOFF(__rd) ldi __rd 0 __FWGEN_VAR_BYTEOFF #define xLDI_FWGEN_WTX_DATA_PREFETCH_QID(__rd) ldi __rd 0 __FWGEN_WTX_DATA_PREFETCH_QID #define xLDI_FWGEN_WRX_PID(__rd) ldi __rd 0 __FWGEN_WRX_PID #define xLDI_FWGEN_WTX_PID(__rd) ldi __rd 0 __FWGEN_WTX_PID #define xLDI_FWGEN_CELLS_QUEUED_0(__rd) ldi __rd 0 __FWGEN_CELLS_QUEUED_0 #define xLDI_FWGEN_CELLS_QUEUED_1(__rd) ldi __rd 0 __FWGEN_CELLS_QUEUED_1 #define xLDI_FWGEN_SPACE_PENDING0(__rd) ldi __rd 0 __FWGEN_SPACE_PENDING0 #define xLDI_FWGEN_SPACE_PENDING1(__rd) ldi __rd 0 __FWGEN_SPACE_PENDING1 #define xLDI_FWGEN_VAR_BMC_CMD1(__rd) ldi __rd 0 __FWGEN_VAR_BMC_CMD1 #define xLDI_FWGEN_WRX_DESREQ_NONPEND_STATUS(__rd) ldi __rd 0 __FWGEN_WRX_DESREQ_NONPEND_STATUS #define xLDI_FWGEN_WTX_DESREQ_NONPEND_STATUS(__rd) ldi __rd 0 __FWGEN_WTX_DESREQ_NONPEND_STATUS #define xLDI_FWGEN_WTX_CELLREQ_NONPEND_STATUS(__rd) ldi __rd 0 __FWGEN_WTX_CELLREQ_NONPEND_STATUS #define xLDI_FWGEN_PREV_EMA_ISR(__rd) ldi __rd 0 __FWGEN_PREV_EMA_ISR #define xLDI_FWGEN_MBOX0_ISR(__rd) ldi __rd 0 __FWGEN_MBOX0_ISR #define xLDI_FWGEN_WTX_1ST_CELL_READ_FLAG0(__rd) ldi __rd 0 __FWGEN_WTX_1ST_CELL_READ_FLAG0 #define xLDI_FWGEN_WTX_1ST_CELL_READ_FLAG1(__rd) ldi __rd 0 __FWGEN_WTX_1ST_CELL_READ_FLAG1 #define xLDI_FWGEN_WRX_2684_ORIGINAL_FLAG(__rd) ldi __rd 0 __FWGEN_WRX_2684_ORIGINAL_FLAG #define xLDI_FWGEN_WRX_2684_CELL_ALIGN_OFF(__rd) ldi __rd 0 __FWGEN_WRX_2684_CELL_ALIGN_OFF #define xLDI_FWGEN_WRX_2684_MPOA_TYPE(__rd) ldi __rd 0 __FWGEN_WRX_2684_MPOA_TYPE #define xLDI_FWGEN_WRX_AAL5_CELL1_ROUNDDOWN_DWNUM(__rd) ldi __rd 0 __FWGEN_WRX_AAL5_CELL1_ROUNDDOWN_DWNUM #define xLDI_FWGEN_WRX_DES_BYTES(__rd) ldi __rd 0 __FWGEN_WRX_DES_BYTES #define xLDI_FWGEN_WRX_FIRST_CELL(__rd) ldi __rd 0 __FWGEN_WRX_FIRST_CELL #define xLDI_FWGEN_WRX_PKT_LEN_WO_FCS(__rd) ldi __rd 0 __FWGEN_WRX_PKT_LEN_WO_FCS #define xLDI_FWGEN_WRX_ETH_TYPE(__rd) ldi __rd 0 __FWGEN_WRX_ETH_TYPE #define xLDI_FWGEN_WRX_MAC_BYTE(__rd) ldi __rd 0 __FWGEN_WRX_MAC_BYTE #define xLDI_WRX_DECAP_BUF_BASE(__rd) ldi __rd 0 __WRX_DECAP_BUF_BASE #define xLDI_WRX_DECAP_BUF_BASE_HW(__rd) ldi __rd 0 __WRX_DECAP_BUF_BASE_HW #define xLDI_FWGEN_WTX_ETH_HD_DONE(__rd) ldi __rd 0 __FWGEN_WTX_ETH_HD_DONE #define xLDI_FWGEN_WTX_2684_RM_LEN(__rd) ldi __rd 0 __FWGEN_WTX_2684_RM_LEN #define xLDI_FWGEN_WTX_2684_INSERT_LEN(__rd) ldi __rd 0 __FWGEN_WTX_2684_INSERT_LEN #define xLDI_FWGEN_WTX_ENCAP_PARSE_DROP(__rd) ldi __rd 0 __FWGEN_WTX_ENCAP_PARSE_DROP #define xLDI_FWGEN_WTX_ETH_IS_VLAN(__rd) ldi __rd 0 __FWGEN_WTX_ETH_IS_VLAN #define xLDI_FWGEN_WTX_RDWNUM(__rd) ldi __rd 0 __FWGEN_WTX_RDWNUM #define xLDI_FWGEN_WTX_SWOFFF(__rd) ldi __rd 0 __FWGEN_WTX_SWOFF #define xLDI_FWGEN_WTX_CELL1_BYTEOFF(__rd) ldi __rd 0 __FWGEN_WTX_CELL1_BYTEOFF #define xLDI_FWGEN_WTX_ETH_IS_IPV4(__rd) ldi __rd 0 __FWGEN_WTX_ETH_IS_IPV4 #define xLDI_FWGEN_WTX_ETH_IPOFF(__rd) ldi __rd 0 __FWGEN_WTX_ETH_IPOFF #define xLDI_FWGEN_WTX_QPKT_LEVEL_CONTROL(__rd) ldi __rd 0 __FWGEN_WTX_QPKT_LEVEL_CONTROL #define xLDI_FWGEN_WTX_QSB_VC_CONTEXT_BASE(__rd) ldi __rd 0 __FWGEN_WTX_QSB_VC_CONTEXT_BASE #define xLDI_WTX_ETH_HEADER_BUF_BASE(__rd) ldi __rd 0 __WTX_ETH_HEADER_BUF_BASE #define xLDI_FWGEN_WTX_MPOA_PT(__rd) ldi __rd 0 __FWGEN_WTX_MPOA_PT #define MPOA_TYPE_EOA1 0 //without FCS #define MPOA_TYPE_EOA2 1 //with FCS #define MPOA_TYPE_PPPOA_IPV4 2 #define MPOA_TYPE_IPOA_IPV4 3 #define MPOA_TYPE_PPPOA_IPV6 6 #define MPOA_TYPE_IPOA_IPV6 7 #define MPOA_TYPE_PPPOA_OTHER 10 #define MPOA_TYPE_IPOA_OTHER 11 #define BITS_OF_BUCK_DEPTH 4 #define CONST_HASH_BUCKET_SIZE 16 #define CONST_HASH_BUCKET_NO 32 #define CONST_IPV6_CNV_TBL_SIZE 64 //============================================================================== // FROM vr9 bonding //-------------- //PDMA Registers //-------------- #define __DMAL_BAR0_FIFO_STATUS 0x7600 #define __DMAL_BAR1_FIFO_STATUS 0x7601 #define __PDMA_BAR0 0x7602 #define __PDMA_BAR1 0x7603 #define __BAR0_WINDOW_SB_ADDR 0x6000 #define __BAR0_WINDOW_SB_ADDR_PLUS_1 0x6001 #define __BAR1_WINDOW_SB_ADDR 0x6800 #define __BAR1_WINDOW_SB_ADDR_PLUS_1 0x6801 // hardware registers #define __SAR_PDMA_RX_FW_DATABUF_CFG 0x7F02 #define __SAR_PDMA_TX_FW_DATABUF_CFG 0x7F03 #define __PDMA_IER 0x7A0B #endif
kbridgers/VOLTE4GFAX
target/linux/ltqcpe/files-2.6.32/drivers/net/ifxmips_ppa/platform/vrx218/smartphy/vrx218_a1plus_addr_def.h
C
gpl-2.0
44,100
/* iiimcf.h */ #ifndef _IIIMCF_H_ #define _IIIMCF_H_ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <iiimp.h> /* constants */ enum IIIMCF_VERSION_ITEMS { IIIMCF_LIBRARY_VERSION = (1 << 0), IIIMCF_PROTOCOL_VERSION = (1 << 1) }; enum IIIMCF_VERSION_CATEGORIES { IIIMCF_MAJOR_VERSION = (1 << 8), IIIMCF_MINOR_VERSION = (1 << 9) }; enum IIIMCF_UISTATE { IIIMCF_STATE_PREEDIT_CHANGED = (1 << 0), IIIMCF_STATE_LOOKUP_CHOICE_CHANGED = (1 << 1), IIIMCF_STATE_STATUS_CHANGED = (1 << 2), IIIMCF_STATE_COMMIT_REQUIRED = (1 << 3), IIIMCF_STATE_PENDING_EVENT = (1 << 4), IIIMCF_STATE_CONVERSION_MODE_CHANGED = (1 << 5), /* 5 - 15 are reserved. */ IIIMCF_STATE_INVALIDATED = (1 << 16) }; enum IIIMCF_LOOKUP_CHOICE_DIRECTION { IIIMCF_LOOKUP_CHOICE_HORIZONTAL_DIRECTION = 0, IIIMCF_LOOKUP_CHOICE_VERTICAL_DIRECTION = 1 }; enum IIIMCF_LOOKUP_CHOICE_ITEM_FLAGS { IIIMCF_LOOKUP_CHOICE_ITEM_ENABLED = (1 << 0), IIIMCF_LOOKUP_CHOICE_SELECTED_ITEM = (1 << 1) }; enum IIIMCF_ATTRS { IIIMCF_ATTR_SERVER_ADDRESS = 1, IIIMCF_ATTR_SERVER_SERVICE, IIIMCF_ATTR_USERNAME, IIIMCF_ATTR_PASSWORD, IIIMCF_ATTR_CLIENT_TYPE, IIIMCF_ATTR_DISABLE_AUTOMATIC_RESTORATION, IIIMCF_ATTR_CLIENT_X_DISPLAY_NAME, IIIMCF_ATTR_CLIENT_X_SERVER_VENDOR, IIIMCF_ATTR_INPUT_LANGUAGE = 0x1000, IIIMCF_ATTR_INPUT_METHOD, IIIMCF_ATTR_DISABLE_AUTOMATIC_TRIGGER_NOTIFY, IIIMCF_ATTR_INPUT_METHOD_NAME, /* for private use area. */ IIIMCF_ATTR_PRIVATE_START = 0x10000 }; enum IIIMCF_EVENT_TYPES { IIIMCF_EVENT_TYPE_DESTROY = -2, IIIMCF_EVENT_TYPE_RESET = -1, IIIMCF_EVENT_TYPE_EVENTLIKE = 1, IIIMCF_EVENT_TYPE_KEYEVENT = 1, IIIMCF_EVENT_TYPE_KEYEVENT_END = 0x0FFF, IIIMCF_EVENT_TYPE_TRIGGER_NOTIFY_START = 0x1000, IIIMCF_EVENT_TYPE_TRIGGER_NOTIFY = 0x1000, IIIMCF_EVENT_TYPE_TRIGGER_NOTIFY_END = 0x1FFF, IIIMCF_EVENT_TYPE_OPERATION = 0x2000, IIIMCF_EVENT_TYPE_SETICFOCUS = 0x3000, IIIMCF_EVENT_TYPE_UNSETICFOCUS = 0x3001, IIIMCF_EVENT_TYPE_EVENTLIKE_END = 0x3FFF, IIIMCF_EVENT_TYPE_UI = 0x8000, IIIMCF_EVENT_TYPE_UI_PREEDIT = 0x9000, IIIMCF_EVENT_TYPE_UI_PREEDIT_START, IIIMCF_EVENT_TYPE_UI_PREEDIT_CHANGE, IIIMCF_EVENT_TYPE_UI_PREEDIT_DONE, IIIMCF_EVENT_TYPE_UI_PREEDIT_END = 0x9FFF, IIIMCF_EVENT_TYPE_UI_LOOKUP_CHOICE = 0xA000, IIIMCF_EVENT_TYPE_UI_LOOKUP_CHOICE_START, IIIMCF_EVENT_TYPE_UI_LOOKUP_CHOICE_CHANGE, IIIMCF_EVENT_TYPE_UI_LOOKUP_CHOICE_DONE, IIIMCF_EVENT_TYPE_UI_LOOKUP_CHOICE_END = 0xAFFF, IIIMCF_EVENT_TYPE_UI_STATUS = 0xB000, IIIMCF_EVENT_TYPE_UI_STATUS_START, IIIMCF_EVENT_TYPE_UI_STATUS_CHANGE, IIIMCF_EVENT_TYPE_UI_STATUS_DONE, IIIMCF_EVENT_TYPE_UI_STATUS_END = 0xBFFF, IIIMCF_EVENT_TYPE_UI_COMMIT = 0xC000, IIIMCF_EVENT_TYPE_UI_COMMIT_END = 0xCFFF, IIIMCF_EVENT_TYPE_UI_END = 0xFFFF, IIIMCF_EVENT_TYPE_AUX = 0x80000, IIIMCF_EVENT_TYPE_AUX_START, IIIMCF_EVENT_TYPE_AUX_DRAW, IIIMCF_EVENT_TYPE_AUX_SETVALUES, IIIMCF_EVENT_TYPE_AUX_DONE, IIIMCF_EVENT_TYPE_AUX_END = 0x8FFFF }; typedef enum IIIMCF_EVENT_TYPES IIIMCF_event_type; #define IIIMCF_IS_EVENT_TYPE_BROADCAST(type) ((type) < 0) /* typedefs & structures */ /* opaque object type */ #if 1 typedef struct IIIMCF_handle_rec* IIIMCF_handle; typedef struct IIIMCF_attr_rec* IIIMCF_attr; typedef struct IIIMCF_context_rec* IIIMCF_context; typedef struct IIIMCF_text_rec* IIIMCF_text; /* typedef struct IIIMCF_text_property_value_rec* IIIMCF_text_property_value; */ typedef struct IIIMCF_lookup_choice_rec* IIIMCF_lookup_choice; typedef struct IIIMCF_language_rec* IIIMCF_language; typedef struct IIIMCF_input_method_rec* IIIMCF_input_method; typedef struct IIIMCF_event_rec* IIIMCF_event; typedef struct IIIMCF_component_rec* IIIMCF_component; typedef struct IIIMCF_downloaded_object_rec* IIIMCF_downloaded_object; #else /* In case that a compiler does not accept the above declaration without proper definition (normally that does not happen), use the following declarations instead. */ typedef void* IIIMCF_handle; typedef void* IIIMCF_attr; typedef void* IIIMCF_context; typedef void* IIIMCF_text; typedef void* IIIMCF_text_property_value; typedef void* IIIMCF_lookup_choice; typedef void* IIIMCF_language; typedef void* IIIMCF_input_method; typedef void* IIIMCF_event; typedef void* IIIMCF_component; typedef void* IIIMCF_downloaded_object; #endif /* special attr */ #define IIIMCF_ATTR_NULL ((IIIMCF_attr) (NULL)) /* transparent object typedefs & structures */ /* object descriptor */ typedef struct { int category; size_t size; int predefined_id; int dynamic_id; const IIIMP_card16 *domain; const IIIMP_card16 *hrn; const IIIMP_card16 *signature; const IIIMP_card16 *user; } IIIMCF_object_descriptor; /* keyevent */ typedef struct IIIMCF_keyevent IIIMCF_keyevent; struct IIIMCF_keyevent { IIIMP_int32 keycode; IIIMP_int32 keychar; IIIMP_int32 modifier; IIIMP_int32 time_stamp; }; /* component interface */ typedef IIIMF_status (*IIIMCF_component_interface)( IIIMCF_context context, IIIMCF_event event, IIIMCF_component current, IIIMCF_component parent ); #define IIIMCF_ROOT_COMPONENT ((IIIMCF_component) NULL) /* Functions */ #ifdef __cplusplus extern "C" { #endif /* Initialization & finalization */ extern IIIMF_status iiimcf_initialize( IIIMCF_attr attr ); extern IIIMF_status iiimcf_finalize(); /* create & destroy handle */ extern IIIMF_status iiimcf_create_handle( IIIMCF_attr attr, IIIMCF_handle *phandle ); extern IIIMF_status iiimcf_destroy_handle( IIIMCF_handle handle ); /* create & destroy context */ extern IIIMF_status iiimcf_create_context( IIIMCF_handle handle, IIIMCF_attr attr, IIIMCF_context *pcontext ); extern IIIMF_status iiimcf_destroy_context( IIIMCF_context context ); /* reset context */ extern IIIMF_status iiimcf_reset_context( IIIMCF_context context ); /* data manipulation */ /* attribute */ extern IIIMF_status iiimcf_create_attr( IIIMCF_attr *pattr ); extern IIIMF_status iiimcf_destroy_attr( IIIMCF_attr attr ); extern IIIMF_status iiimcf_attr_put_string_value( IIIMCF_attr attr, int property, const char *str ); extern IIIMF_status iiimcf_attr_get_string_value( IIIMCF_attr attr, int property, const char **pstr ); extern IIIMF_status iiimcf_attr_put_integer_value( IIIMCF_attr attr, int property, int number ); extern IIIMF_status iiimcf_attr_get_integer_value( IIIMCF_attr attr, int property, int *pnumber ); extern IIIMF_status iiimcf_attr_put_ptr_value( IIIMCF_attr attr, int property, void *ptr ); extern IIIMF_status iiimcf_attr_get_ptr_value( IIIMCF_attr attr, int property, void **pptr ); /* text */ extern IIIMF_status iiimcf_get_text_utf16string( IIIMCF_text text, const IIIMP_card16** putf16str ); extern IIIMF_status iiimcf_get_text_length( IIIMCF_text text, int *plen ); extern IIIMF_status iiimcf_get_char_with_feedback( IIIMCF_text text, int pos, IIIMP_card16 *pch, int *pnum_feedbacks, const IIIMP_card32** pfeedback_id, const IIIMP_card32** pfeedback ); extern IIIMF_status iiimcf_duplicate_text( IIIMCF_text src, IIIMCF_text *pduplicated ); extern IIIMF_status iiimcf_destroy_text( IIIMCF_text text ); /* lookup choice */ extern IIIMF_status iiimcf_get_lookup_choice_configuration( IIIMCF_lookup_choice lookup_choice, int *pchoices_per_window, int *pnumber_of_rows, int *pnumber_of_columns, int *pdirection ); extern IIIMF_status iiimcf_get_lookup_choice_size( IIIMCF_lookup_choice lookup_choice, int *psize, int *pindex_of_first_candidate, int *pindex_of_last_candidate, int *pindex_of_current_candidate ); extern IIIMF_status iiimcf_get_lookup_choice_title( IIIMCF_lookup_choice lookup_choice, IIIMCF_text *ptitle ); extern IIIMF_status iiimcf_get_lookup_choice_item( IIIMCF_lookup_choice lookup_choice, int idx, IIIMCF_text *pcandidate, IIIMCF_text *plabel, int *pflag ); /* language */ extern IIIMF_status iiimcf_get_language_id( IIIMCF_language lang, const char **plangid ); /* input method */ extern IIIMF_status iiimcf_get_input_method_desc( IIIMCF_input_method input_method, char **pinput_method_id, char **pinput_method_domain, int *pintput_method_hrn_len, IIIMP_card16** pinput_method_hrn ); extern IIIMF_status iiimcf_get_input_method_languages( IIIMCF_input_method input_method, int *pinput_method_language_size, IIIMCF_language **pplangages ); /* downloaded object */ extern IIIMF_status iiimcf_get_downloaded_object_descriptor( IIIMCF_downloaded_object object, const IIIMCF_object_descriptor **ppdesc ); extern IIIMF_status iiimcf_get_downloaded_object_filename( IIIMCF_downloaded_object object, const IIIMP_card16 **pfilename ); extern IIIMF_status iiimcf_get_downloaded_objects( IIIMCF_handle handle, int num_objs, const IIIMCF_object_descriptor **ppdesc, IIIMCF_downloaded_object *pobjs ); /* version */ extern IIIMF_status iiimcf_get_version_number( IIIMCF_handle handle, int flag, int *pversion_number ); /* state checking */ extern IIIMF_status iiimcf_is_UIstate_changed( IIIMCF_context context, int *pflag ); /* info */ extern IIIMF_status iiimcf_get_supported_languages( IIIMCF_handle handle, int *pnum_langs, IIIMCF_language **pplangs ); extern IIIMF_status iiimcf_get_supported_input_methods( IIIMCF_handle handle, int *pnum_input_methods, IIIMCF_input_method **ppinput_methods ); extern IIIMF_status iiimcf_get_object_descriptor_list( IIIMCF_handle handle, int *pnum_object_descriptors, const IIIMCF_object_descriptor **ppdesc ); extern IIIMF_status iiimcf_get_trigger_keys( IIIMCF_handle handle, int *pnum_on_keys, const IIIMCF_keyevent **pponkeys, int *pnum_off_keys, const IIIMCF_keyevent **ppoffkeys ); extern IIIMF_status iiimcf_get_current_conversion_mode( IIIMCF_context context, int *pflag ); extern IIIMF_status iiimcf_get_preedit_text( IIIMCF_context context, IIIMCF_text *ptext, int *pcaret_position ); extern IIIMF_status iiimcf_get_status_text( IIIMCF_context context, IIIMCF_text *ptext ); extern IIIMF_status iiimcf_get_lookup_choice( IIIMCF_context context, IIIMCF_lookup_choice *plookup_choice ); extern IIIMF_status iiimcf_get_committed_text( IIIMCF_context context, IIIMCF_text *ptext ); extern IIIMF_status iiimcf_get_aux_draw_data( IIIMCF_context context, const IIIMP_card16 *aux_name, IIIMP_card32 class_idx, int *pnum_intvals, const IIIMP_card32 **ppintvals, int *pnum_strvals, const IIIMP_card16 ***ppstrs ); extern IIIMF_status iiimcf_context_get_attr( IIIMCF_context context, IIIMCF_attr *pattr ); /* event */ extern IIIMF_status iiimcf_get_event_type( IIIMCF_event event, IIIMCF_event_type *pevent_type ); extern IIIMF_status iiimcf_create_keyevent( const IIIMCF_keyevent *pkeyevent, IIIMCF_event *pevent ); extern IIIMF_status iiimcf_create_trigger_notify_event( int flag, IIIMCF_event *pevent ); extern IIIMF_status iiimcf_create_seticfocus_event( IIIMCF_event *pevent ); extern IIIMF_status iiimcf_create_unseticfocus_event( IIIMCF_event *pevent ); extern IIIMF_status iiimcf_create_aux_setvalues_event( const IIIMP_card16 *aux_name, IIIMP_card32 class_idx, int num_intvals, const IIIMP_card32 *pintvals, int num_strvals, const IIIMP_card16 **pstrs, IIIMCF_event *pevent ); /* event value */ extern IIIMF_status iiimcf_get_keyevent_value( IIIMCF_event event, IIIMCF_keyevent *pkeyevent ); extern IIIMF_status iiimcf_get_trigger_notify_flag( IIIMCF_event event, int *pflag ); extern IIIMF_status iiimcf_get_aux_event_value( IIIMCF_event event, const IIIMP_card16 **paux_name, IIIMP_card32 *pclass_idx, int *pnum_intvals, const IIIMP_card32 **ppintvals, int *pnum_strvals, const IIIMP_card16 ***ppstrs ); /* event flow control */ extern IIIMF_status iiimcf_forward_event( IIIMCF_context context, IIIMCF_event event ); extern IIIMF_status iiimcf_dispatch_event( IIIMCF_context context, IIIMCF_event event ); extern IIIMF_status iiimcf_get_next_event( IIIMCF_context context, IIIMCF_event *pevent ); extern IIIMF_status iiimcf_peek_next_event( IIIMCF_context context, IIIMCF_event *pevent ); extern IIIMF_status iiimcf_ignore_event( IIIMCF_event event ); /* component management */ extern IIIMF_status iiimcf_register_component( IIIMCF_handle handle, const char* name, IIIMCF_component_interface interface, IIIMCF_component parent, IIIMCF_component* pcomp ); extern IIIMF_status iiimcf_unregister_component( IIIMCF_component component ); extern IIIMF_status iiimcf_get_component( IIIMCF_handle handle, const char *name, IIIMCF_component* pcomponent ); extern IIIMF_status iiimcf_component_get_attr( IIIMCF_component component, IIIMCF_attr* pattr ); #ifdef __cplusplus } #endif #endif /* _IIIMCF_H_ */ /* Local Variables: */ /* c-file-style: "iiim-project" */ /* End: */
chewing/iiimf-chewing
include/iiimcf.h
C
gpl-2.0
13,168
from django.contrib.auth.models import User, Permission, Group from rest_framework import serializers from apps.account.serializers.PermissionSerializer import PermissionSerializer class GroupSerializer(serializers.ModelSerializer): permissions = PermissionSerializer(instance=Permission, many=True) class Meta: model = Group fields = ('name', 'permissions')
mmmaaaxxx77/Python-Django-AdminLTE2
Demo/apps/account/serializers/GroupSerializer.py
Python
gpl-2.0
384
/* iax2_analysis.h * IAX2 analysis addition for Wireshark * * $Id$ * * based on rtp_analysis.c * Copyright 2003, Alcatel Business Systems * By Lars Ruoff <lars.ruoff@gmx.net> * * based on tap_rtp.c * Copyright 2003, Iskratel, Ltd, Kranj * By Miha Jemec <m.jemec@iskratel.si> * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef IAX2_ANALYSIS_H_INCLUDED #define IAX2_ANALYSIS_H_INCLUDED #include <glib.h> #include <epan/address.h> #include <epan/packet_info.h> /** @file * ??? * @todo what's this? */ void iax2_analysis( address *ip_src_fwd, guint16 port_src_fwd, address *ip_dst_fwd, guint16 port_dst_fwd, address *ip_src_rev, guint16 port_src_rev, address *ip_dst_rev, guint16 port_dst_rev ); /****************************************************************************/ /* structure that holds the information about the forward and reversed direction */ typedef struct _iax2_bw_history_item { double time; guint32 bytes; } iax2_bw_history_item; #define BUFF_BW 300 typedef struct _tap_iax2_stat_t { gboolean first_packet; /* do not use in code that is called after rtp_packet_analyse */ /* use (flags & STAT_FLAG_FIRST) instead */ /* all of the following fields will be initialized after rtp_packet_analyse has been called */ guint32 flags; /* see STAT_FLAG-defines below */ guint16 seq_num; guint32 timestamp; guint32 delta_timestamp; double bandwidth; iax2_bw_history_item bw_history[BUFF_BW]; guint16 bw_start_index; guint16 bw_index; guint32 total_bytes; double delta; double jitter; double diff; double time; double start_time; double max_delta; double max_jitter; double mean_jitter; guint32 max_nr; guint16 start_seq_nr; guint16 stop_seq_nr; guint32 total_nr; guint32 sequence; gboolean under; gint cycles; guint16 pt; int reg_pt; } tap_iax2_stat_t; #define PT_UNDEFINED -1 /* status flags for the flags parameter in tap_iax2_stat_t */ #define STAT_FLAG_FIRST 0x001 #define STAT_FLAG_MARKER 0x002 #define STAT_FLAG_WRONG_SEQ 0x004 #define STAT_FLAG_PT_CHANGE 0x008 #define STAT_FLAG_PT_CN 0x010 #define STAT_FLAG_FOLLOW_PT_CN 0x020 #define STAT_FLAG_REG_PT_CHANGE 0x040 #define STAT_FLAG_WRONG_TIMESTAMP 0x080 /* forward */ struct _rtp_info; /* function for analysing an RTP packet. Called from rtp_analysis and rtp_streams */ extern int iax2_packet_analyse(tap_iax2_stat_t *statinfo, packet_info *pinfo, const struct _iax2_info_t *iax2info); #endif /*IAX2_ANALYSIS_H_INCLUDED*/
nixpanic/gluster-wireshark-1.4
gtk/iax2_analysis.h
C
gpl-2.0
3,352
-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca) -- Released under the GNU GPL, see LICENSE {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, FlexibleContexts, TypeSynonymInstances, UndecidableInstances, ViewPatterns #-} module Graphics.Implicit.ObjectUtil.GetImplicit3 (getImplicit3) where import Prelude hiding (round) import Graphics.Implicit.Definitions (ℝ, ℝ2, ℝ3, (⋯/), Obj3, SymbolicObj3(Shell3, UnionR3, IntersectR3, DifferenceR3, Translate3, Scale3, Rotate3, Outset3, Rect3R, Sphere, Cylinder, Complement3, EmbedBoxedObj3, Rotate3V, ExtrudeR, ExtrudeRM, ExtrudeOnEdgeOf, RotateExtrude)) import qualified Graphics.Implicit.MathUtil as MathUtil (rmaximum, rminimum, rmax) import qualified Data.Maybe as Maybe import qualified Data.Either as Either import Data.VectorSpace import Data.Cross (cross3) import Graphics.Implicit.ObjectUtil.GetImplicit2 (getImplicit2) getImplicit3 :: SymbolicObj3 -> Obj3 -- Primitives getImplicit3 (Rect3R r (x1,y1,z1) (x2,y2,z2)) = \(x,y,z) -> MathUtil.rmaximum r [abs (x-dx/2-x1) - dx/2, abs (y-dy/2-y1) - dy/2, abs (z-dz/2-z1) - dz/2] where (dx, dy, dz) = (x2-x1, y2-y1, z2-z1) getImplicit3 (Sphere r ) = \(x,y,z) -> sqrt (x**2 + y**2 + z**2) - r getImplicit3 (Cylinder h r1 r2) = \(x,y,z) -> let d = sqrt(x^2+y^2) - ((r2-r1)/h*z+r1) θ = atan2 (r2-r1) h in max (d * cos θ) (abs(z-h/(2::ℝ)) - h/(2::ℝ)) -- (Rounded) CSG getImplicit3 (Complement3 symbObj) = let obj = getImplicit3 symbObj in \p -> - obj p getImplicit3 (UnionR3 r symbObjs) = let objs = map getImplicit3 symbObjs in if r == 0 then \p -> minimum $ map ($p) objs else \p -> MathUtil.rminimum r $ map ($p) objs getImplicit3 (IntersectR3 r symbObjs) = let objs = map getImplicit3 symbObjs in if r == 0 then \p -> maximum $ map ($p) objs else \p -> MathUtil.rmaximum r $ map ($p) objs getImplicit3 (DifferenceR3 r symbObjs) = let obj:objs = map getImplicit3 symbObjs complement obj = \p -> - obj p in if r == 0 then \p -> maximum $ map ($p) $ obj:(map complement objs) else \p -> MathUtil.rmaximum r $ map ($p) $ obj:(map complement objs) -- Simple transforms getImplicit3 (Translate3 v symbObj) = let obj = getImplicit3 symbObj in \p -> obj (p ^-^ v) getImplicit3 (Scale3 s@(sx,sy,sz) symbObj) = let obj = getImplicit3 symbObj k = (sx*sy*sz)**(1/3) in \p -> k * obj (p ⋯/ s) getImplicit3 (Rotate3 (yz, zx, xy) symbObj) = let obj = getImplicit3 symbObj rotateYZ :: ℝ -> (ℝ3 -> ℝ) -> (ℝ3 -> ℝ) rotateYZ θ obj = \(x,y,z) -> obj ( x, cos(θ)*y + sin(θ)*z, cos(θ)*z - sin(θ)*y) rotateZX :: ℝ -> (ℝ3 -> ℝ) -> (ℝ3 -> ℝ) rotateZX θ obj = \(x,y,z) -> obj ( cos(θ)*x - sin(θ)*z, y, cos(θ)*z + sin(θ)*x) rotateXY :: ℝ -> (ℝ3 -> ℝ) -> (ℝ3 -> ℝ) rotateXY θ obj = \(x,y,z) -> obj ( cos(θ)*x + sin(θ)*y, cos(θ)*y - sin(θ)*x, z) in rotateYZ yz $ rotateZX zx $ rotateXY xy $ obj getImplicit3 (Rotate3V θ axis symbObj) = let axis' = normalized axis obj = getImplicit3 symbObj in \v -> obj $ v ^* cos(θ) ^-^ (axis' `cross3` v) ^* sin(θ) ^+^ (axis' ^* (axis' <.> (v ^* (1 - cos(θ))))) -- Boundary mods getImplicit3 (Shell3 w symbObj) = let obj = getImplicit3 symbObj in \p -> abs (obj p) - w/2 getImplicit3 (Outset3 d symbObj) = let obj = getImplicit3 symbObj in \p -> obj p - d -- Misc getImplicit3 (EmbedBoxedObj3 (obj,_)) = obj -- 2D Based getImplicit3 (ExtrudeR r symbObj h) = let obj = getImplicit2 symbObj in \(x,y,z) -> MathUtil.rmax r (obj (x,y)) (abs (z - h/2) - h/2) getImplicit3 (ExtrudeRM r twist scale translate symbObj height) = let obj = getImplicit2 symbObj twist' = Maybe.fromMaybe (const 0) twist scale' = Maybe.fromMaybe (const 1) scale translate' = Maybe.fromMaybe (const (0,0)) translate height' (x,y) = case height of Left n -> n Right f -> f (x,y) scaleVec :: ℝ -> ℝ2 -> ℝ2 scaleVec s = \(x,y) -> (x/s, y/s) rotateVec :: ℝ -> ℝ2 -> ℝ2 rotateVec θ (x,y) = (x*cos(θ)+y*sin(θ), y*cos(θ)-x*sin(θ)) k = (pi :: ℝ)/(180:: ℝ) in \(x,y,z) -> let h = height' (x,y) in MathUtil.rmax r (obj . rotateVec (-k*twist' z) . scaleVec (scale' z) . (\a -> a ^-^ translate' z) $ (x,y)) (abs (z - h/2) - h/2) getImplicit3 (ExtrudeOnEdgeOf symbObj1 symbObj2) = let obj1 = getImplicit2 symbObj1 obj2 = getImplicit2 symbObj2 in \(x,y,z) -> obj1 (obj2 (x,y), z) getImplicit3 (RotateExtrude totalRotation round translate rotate symbObj) = let tau = 2 * pi k = tau / 360 totalRotation' = totalRotation*k obj = getImplicit2 symbObj capped = Maybe.isJust round round' = Maybe.fromMaybe 0 round translate' :: ℝ -> ℝ2 translate' = Either.either (\(a,b) -> \θ -> (a*θ/totalRotation', b*θ/totalRotation')) (. (/k)) translate rotate' :: ℝ -> ℝ rotate' = Either.either (\t -> \θ -> t*θ/totalRotation' ) (. (/k)) rotate twists = case rotate of Left 0 -> True _ -> False in \(x,y,z) -> minimum $ do let r = sqrt (x^2 + y^2) θ = atan2 y x ns :: [Int] ns = if capped then -- we will cap a different way, but want leeway to keep the function cont [-1 .. (ceiling (totalRotation' / tau) :: Int) + (1 :: Int)] else [0 .. floor $ (totalRotation' - θ) /tau] n <- ns let θvirt = fromIntegral n * tau + θ (rshift, zshift) = translate' θvirt twist = rotate' θvirt rz_pos = if twists then let (c,s) = (cos(twist*k), sin(twist*k)) (r',z') = (r-rshift, z-zshift) in (c*r' - s*z', c*z' + s*r') else (r - rshift, z - zshift) return $ if capped then MathUtil.rmax round' (abs (θvirt - (totalRotation' / 2)) - (totalRotation' / 2)) (obj rz_pos) else obj rz_pos
silky/ImplicitCAD
Graphics/Implicit/ObjectUtil/GetImplicit3.hs
Haskell
gpl-2.0
7,124
#include "common.h" void object_mark_fun(CLObject self, unsigned char* mark_flg) { sCLObject* object = CLOBJECT(self); sCLClass* klass = object->mClass; int i; for(i=0; i<klass->mNumFields; i++) { mark_object(object->mFields[i].mObjectValue, mark_flg); } } BOOL free_object(CLObject self) { sCLObject* object_data = CLOBJECT(self); sCLClass* klass = object_data->mClass; if(!call_finalize_method_on_free_object(klass, self)) { return FALSE; } object_data = CLOBJECT(self); MFREE(object_data->mType); int i=0; for(i=0; i<object_data->mNumFields; i++) { CLObject obj = object_data->mFields[i].mObjectValue; sCLType* field_type = klass->mFields[i].mResultType; char* field_class_name = CONS_str(&klass->mConst, field_type->mClassNameOffset); sCLClass* field_class = get_class(field_class_name, FALSE); BOOL value_is_object = !(field_class->mFlags & CLASS_FLAGS_NO_FREE_OBJECT); dec_refference_count(obj, value_is_object); } return TRUE; } static unsigned long long object_size(sCLClass* klass) { unsigned long long size; if(klass->mAllocSize > 0 && (klass->mFlags & CLASS_FLAGS_STRUCT)) { size = klass->mAllocSize; size += sizeof(sCLObject) - sizeof(CLVALUE) * DUMMY_ARRAY_SIZE; } else if(klass->mAllocSizeMethodIndex != -1) { size = 0; (void)call_alloc_size_method(klass, &size); size += sizeof(sCLObject) - sizeof(CLVALUE) * DUMMY_ARRAY_SIZE; } else { size = sizeof(sCLObject) - sizeof(CLVALUE) * DUMMY_ARRAY_SIZE; size += (unsigned int)sizeof(CLVALUE) * klass->mNumFields; unsigned int size2 = size; alignment((unsigned int*)&size2); size = size2; } return size; } static unsigned long long object_size2(int alloc_size) { unsigned long long size; size = alloc_size; size += sizeof(sCLObject) - sizeof(CLVALUE) * DUMMY_ARRAY_SIZE; return size; } CLObject create_object(sCLClass* klass, char* type, sVMInfo* info) { unsigned int size = (unsigned int)object_size(klass); alignment(&size); CLObject obj; if(klass->mFlags & CLASS_FLAGS_STRUCT) { int alloc_size = klass->mAllocSize; obj = create_object2(klass, type, alloc_size, info); } else { obj = alloc_heap_mem(size, klass, -1, info); sCLObject* object_data = CLOBJECT(obj); object_data->mType = MSTRDUP(type); } return obj; } CLObject create_object2(sCLClass* klass, char* type, int alloc_size, sVMInfo* info) { unsigned int size = (unsigned int)object_size2(alloc_size); alignment(&size); CLObject obj = alloc_heap_mem(size, klass, -1, info); sCLObject* object_data = CLOBJECT(obj); object_data->mType = MSTRDUP(type); return obj; } char* get_class_name_from_cl_type(sCLType* cl_type, sCLClass* klass) { return CONS_str(&klass->mConst, cl_type->mClassNameOffset); } static BOOL check_same_interface_of_two_methods(sCLMethod* method1, sCLClass* klass1, sCLMethod* method2, sCLClass* klass2) { char* name1 = METHOD_NAME2(klass1, method1); char* name2 = METHOD_NAME2(klass2, method2); if(strcmp(name1, name2) != 0) { return FALSE; } char* result_type1 = get_class_name_from_cl_type(method1->mResultType, klass1); char* result_type2 = get_class_name_from_cl_type(method2->mResultType, klass2); if(strcmp(result_type1, "Self") == 0) { result_type1 = CLASS_NAME(klass2); } if(strcmp(result_type1, result_type2) != 0) { return FALSE; } if(method1->mNumParams != method2->mNumParams) { return FALSE; } int i; for(i=0; i<method1->mNumParams; i++) { sCLParam* param1 = method1->mParams + i; sCLParam* param2 = method2->mParams + i; char* param1_type = get_class_name_from_cl_type(param1->mType, klass1); char* param2_type = get_class_name_from_cl_type(param2->mType, klass2); if(strcmp(param1_type, "Self") == 0) { param1_type = CLASS_NAME(klass2); } if(strcmp(param1_type, param2_type) != 0) { return FALSE; } } return TRUE; } static BOOL check_implemented_methods_for_interface_on_runtime(sCLClass* left_class, sCLClass* right_class) { if(left_class != right_class) { int i; for(i=0; i<left_class->mNumMethods; i++) { sCLMethod* method = left_class->mMethods + i; BOOL found = FALSE; int j; for(j=0; j<right_class->mNumMethods; j++) { sCLMethod* method2 = right_class->mMethods + j; if(check_same_interface_of_two_methods(method, left_class, method2, right_class)) { found = TRUE; } } if(!found) { return FALSE; } } } return TRUE; } BOOL object_implements_interface(CLObject object, sCLClass* interface) { sCLObject* object_data = CLOBJECT(object); sCLClass* klass = object_data->mClass; BOOL result = check_implemented_methods_for_interface_on_runtime(interface, klass); return result; }
ab25cq/clover2
src/object.c
C
gpl-2.0
5,252
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Pathfinder { class AiBotBetter : AiBotBase { //public override void Setup(Level lvl, Player plr) { } public int direction = 0; /* 0 *3 1 * 2 */ bool walling = false; public AiBotBetter(int x, int y) : base(x, y) { } protected override void ChooseNextGridLocation(Level level, Player plr) { Coord2 pos; if (!walling) { //move towards the player if (GridPosition.X > plr.GridPosition.X) { direction = 3; //left } else if (GridPosition.X < plr.GridPosition.X) { direction = 1; //right } else if (GridPosition.Y > plr.GridPosition.Y) { direction = 2; //down } else if (GridPosition.Y < plr.GridPosition.Y) { direction = 0; //up } pos = GridPosition; pos = move(direction); if (!level.ValidPosition(pos)) { walling = true; Random rnd = new Random(); int dir = rnd.Next(0, 2); if (dir == 0) { direction--; } else { direction++; } if (direction < 0) direction = 3; if (direction > 3) direction = 0; } } if (0 == nextToWall(level)) { walling = false; } if (2 == nextToWall(level)) { Random rnd = new Random(); int dir = rnd.Next(0, 2); if (dir == 0) { direction--; } else { direction++; } if (direction < 0) direction = 3; if (direction > 3) direction = 0; } pos = move(direction); SetNextGridPosition(pos, level); } private Coord2 move(int direction) { Coord2 pos = GridPosition; switch (direction) { case 0: pos.Y++; break; case 1: pos.X++; break; case 2: pos.Y--; break; case 3: pos.X--; break; } return pos; } int nextToWall(Level level) { int ntw = 0; Coord2 pos = GridPosition; pos.X++; if (!level.ValidPosition(pos)) { ntw++; } pos.X -= 2; if (!level.ValidPosition(pos)) { ntw++; } pos.X++; pos.Y++; if (!level.ValidPosition(pos)) { ntw++; } pos.Y -= 2; if (!level.ValidPosition(pos)) { ntw++; } return ntw; } } }
BenjaminJStock/AI-Dijkstras
Pathfinder/AiBotSimple2.cs
C#
gpl-2.0
3,806
#include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <time.h> #include <iostream> #include <sys/time.h> #include <assert.h> #include <semaphore.h> #include <netinet/tcp.h> using namespace std; typedef unsigned long long u64; typedef unsigned int u32; int main() { struct sockaddr_in serveraddr; bzero(&serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; const char *local_addr = "127.0.0.1"; //const char *local_addr = "192.168.99.85"; inet_aton(local_addr,&(serveraddr.sin_addr)); serveraddr.sin_port=ntohs(5531); int fd = socket(AF_INET, SOCK_STREAM, 0); // Disable the Nagle (TCP No Delay) algorithm /* int flag = 1; int ret = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(flag) ); if (ret == -1) { printf("Couldn't setsockopt(TCP_NODELAY)\n"); exit(-1); } */ int rslt = connect(fd, (sockaddr*)&serveraddr, sizeof(serveraddr)); if (rslt) { perror("faild:"); exit(1); } sleep(5); //char a[20004]; char a[1028]; memset(a,0, 1028); int num = 0; u32 trys = 100; //while(trys--) while(1) { write(fd, a, 4); write(fd, a, 100); //write(fd, a, 104); read(fd, a, 104); sleep(2); } close(fd); } //g++ -g client.cpp -o client.exe
diqiu50/ice-dev
Ice/example/Connection/Epoll/client.cpp
C++
gpl-2.0
1,324
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QWINDOWSURFACE_X11_P_H #define QWINDOWSURFACE_X11_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists for the convenience // of other Qt classes. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include <qglobal.h> #include "private/qwindowsurface_p.h" QT_BEGIN_NAMESPACE class QPaintDevice; class QPoint; class QRegion; class QRegion; class QSize; class QWidget; struct QX11WindowSurfacePrivate; class QX11WindowSurface : public QWindowSurface { public: QX11WindowSurface(QWidget *widget); ~QX11WindowSurface(); QPaintDevice *paintDevice(); void flush(QWidget *widget, const QRegion &region, const QPoint &offset); void beginPaint(const QRegion &rgn); void setGeometry(const QRect &rect); bool scroll(const QRegion &area, int dx, int dy); QPixmap grabWidget(const QWidget *widget, const QRect& rectangle = QRect()) const; private: QX11WindowSurfacePrivate *d_ptr; GC gc; }; QT_END_NAMESPACE #endif // QWINDOWSURFACE_X11_P_H
librelab/qtmoko-test
qtopiacore/qt/src/gui/painting/qwindowsurface_x11_p.h
C
gpl-2.0
3,058
/** * Copyright 陈延军 All rights reserved. */ package org.fairyks.im.server.util; import java.io.InputStream; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import com.google.gson.Gson; /** * <p>Copyright: Copyright (c) 2011</p> * <p>公司名称 :陈延军 </p> * <p>项目名称 : ImServer</p> * <p>创建时间 : 2016年1月4日 下午3:34:23</p> * <p>类描述 : </p> * * * @version 1.0.0 * @author <a href=" ">陈延军</a> */ public class HttpRequestUtil { private static HttpRequestUtil httpRequestUtil; private HttpRequestUtil() { } public static HttpRequestUtil getInstance() { if (httpRequestUtil != null) { return httpRequestUtil; } else { httpRequestUtil = new HttpRequestUtil(); return httpRequestUtil; } } private static final Logger logger = Logger.getLogger(HttpRequestUtil.class); public static String getRequestData(HttpServletRequest request) { try { request.setCharacterEncoding("UTF-8"); InputStream inputStream = request.getInputStream(); String requestData = IOUtils.toString(inputStream,"Utf-8"); return requestData; } catch (Exception e) { e.printStackTrace(); logger.error("fail to get RequestData,the reason is " + e.getMessage().toString()); return null; } } }
fairyks/ImServer
src/org/fairyks/im/server/util/HttpRequestUtil.java
Java
gpl-2.0
1,403
<?php function webnus_iconbox( $attributes, $content = null ) { extract(shortcode_atts(array( "type"=>'', 'icon_title'=>'', 'icon_link_url'=>'', 'icon_link_text'=>'', "icon_name"=>'', "iconbox_content"=>'', "icon_size"=>'', "icon_color"=>'', "title_color"=>'', "content_color"=>'', "link_color"=>'', "link_target"=>'self', "icon_image"=>'', ), $attributes)); ob_start(); $type = ($type==0) ? '' : $type ; $iconbox_style = ( !empty($icon_color) ) ? ' style="color: ' . $icon_color . '"' : '' ; $type17_start_wrap = $type17_end_wrap = ''; if ( $type==17 ) { $type17_start_wrap = '<div class="icon-wrap" style="background-color:'.$icon_color.'">'; $type17_end_wrap = '</div>'; } echo '<article class="icon-box' . $type . '" ' . $iconbox_style . '>'; if(!empty($icon_name) && $icon_name != 'none'): if(!empty($icon_link_url)) echo '' . $type17_start_wrap . '<a target="_'.$link_target.'" href="' . $icon_link_url . '">' . do_shortcode( "[icon name='$icon_name' size='$icon_size' color='$icon_color']" ).'</a>' . $type17_end_wrap . ''; else echo $type17_start_wrap . do_shortcode( "[icon name='$icon_name' size='$icon_size' color='$icon_color']" ) . $type17_end_wrap; elseif(!empty($icon_image)): if(is_numeric($icon_image)){ $icon_image = wp_get_attachment_url( $icon_image ); } if(!empty($icon_link_url)) echo "<a target='_".$link_target."' href='$icon_link_url'>" . '<img src="'.$icon_image.'" />' . '</a>' ; else echo '<img src="'.$icon_image.'" />'; endif; $title_style = !empty($title_color)?' style="color:'.$title_color.'"':''; echo '<h4'.$title_style.'>' . $icon_title . '</h4>'; $content_style = !empty($content_color)?' style="color:'.$content_color.'"':''; echo '<p'.$content_style.'>'.$iconbox_content .'</p>' ; $link_style = !empty($link_color)?' style="color:'.$link_color.'"':''; echo (!empty($icon_link_url) && (!empty($icon_link_text)) )?"<a target=\"_".$link_target."\" ".$link_style." class=\"magicmore\" href=\"{$icon_link_url}\">{$icon_link_text}</a>":''; echo '</article>'; $out = ob_get_contents(); ob_end_clean(); $out = str_replace('<p></p>','',$out); return $out; } add_shortcode('iconbox', 'webnus_iconbox'); ?>
arkev/IntelligentMode
wp-content/themes/florida-wp/inc/shortcodes/iconbox.php
PHP
gpl-2.0
2,299
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.3.1"/> <title>Taobao Cpp/Qt SDK: TaoApiCpp/response/SimbaCatmatchidsDeletedGetResponse.h File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Taobao Cpp/Qt SDK </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.3.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Pages</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_5ced2c06884fa9bf5c2da90298abd959.html">TaoApiCpp</a></li><li class="navelem"><a class="el" href="dir_b6b3a706edffae716cf3dcaba65ad0ec.html">response</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#nested-classes">Classes</a> </div> <div class="headertitle"> <div class="title">SimbaCatmatchidsDeletedGetResponse.h File Reference</div> </div> </div><!--header--> <div class="contents"> <div class="textblock"><code>#include &lt;<a class="el" href="TaoResponse_8h_source.html">TaoApiCpp/TaoResponse.h</a>&gt;</code><br/> <code>#include &lt;QList&gt;</code><br/> </div> <p><a href="SimbaCatmatchidsDeletedGetResponse_8h_source.html">Go to the source code of this file.</a></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a> Classes</h2></td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classSimbaCatmatchidsDeletedGetResponse.html">SimbaCatmatchidsDeletedGetResponse</a></td></tr> <tr class="memdesc:"><td class="mdescLeft">&#160;</td><td class="mdescRight">TOP RESPONSE API: 获取删除的类目出价ID. <a href="classSimbaCatmatchidsDeletedGetResponse.html#details">More...</a><br/></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Sun Apr 14 2013 16:25:37 for Taobao Cpp/Qt SDK by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.3.1 </small></address> </body> </html>
sd44/TaobaoCppQtSDK
doc/SimbaCatmatchidsDeletedGetResponse_8h.html
HTML
gpl-2.0
5,904
/*//////////////////////////////////////////////////////////////////////// Copyright (c) 1995 Electrotechnical Laboratry (ETL), AIST, MITI Permission to use, copy, modify, and distribute this material for any purpose and without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies, and that the name of ETL not be used in advertising or publicity pertaining to this material without the specific, prior written permission of an authorized representative of ETL. ETL MAKES NO REPRESENTATIONS ABOUT THE ACCURACY OR SUITABILITY OF THIS MATERIAL FOR ANY PURPOSE. IT IS PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. ///////////////////////////////////////////////////////////////////////// Content-Type: program/C; charset=US-ASCII Program: cond.c (Condition Expression Interpreter) Author: Yutaka Sato <ysato@etl.go.jp> Description: History: 950630 created //////////////////////////////////////////////////////////////////////#*/ #include <stdio.h> #include "ystring.h" #include "dglib.h" int getCondition(DGC*ctx) { return 0; } int evalCondition(DGC*ctx, int condid) { return 1; }
MewX/Psiphon3-for-Linux
delegate9.9.13/src/cond.c
C
gpl-2.0
1,162
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>Minautorus: include/TextureManager.hpp File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Minautorus </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('_texture_manager_8hpp.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="summary"> <a href="#nested-classes">Classes</a> </div> <div class="headertitle"> <div class="title">TextureManager.hpp File Reference</div> </div> </div><!--header--> <div class="contents"> <div class="textblock"><code>#include &lt;iostream&gt;</code><br /> <code>#include &lt;unordered_map&gt;</code><br /> <code>#include &lt;SFML/Graphics.hpp&gt;</code><br /> <code>#include &lt;<a class="el" href="_global_8hpp_source.html">Global.hpp</a>&gt;</code><br /> </div> <p><a href="_texture_manager_8hpp_source.html">Go to the source code of this file.</a></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a> Classes</h2></td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_texture_manager.html">TextureManager</a></td></tr> <tr class="memdesc:"><td class="mdescLeft">&#160;</td><td class="mdescRight">Texture loader. <a href="class_texture_manager.html#details">More...</a><br /></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="dir_d44c64559bbebec7f509842c48db8b23.html">include</a></li><li class="navelem"><a class="el" href="_texture_manager_8hpp.html">TextureManager.hpp</a></li> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.9.1 </li> </ul> </div> </body> </html>
DuckAndColvert/Minautorus
documentation/html/_texture_manager_8hpp.html
HTML
gpl-2.0
5,899
/* This file is part of Jedi Academy. Jedi Academy is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. Jedi Academy 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 Jedi Academy. If not, see <http://www.gnu.org/licenses/>. */ // Copyright 2001-2013 Raven Software //NPC_utils.cpp #include "b_local.h" #include "Q3_Interface.h" #include "g_navigator.h" #include "../cgame/cg_local.h" #include "g_nav.h" extern Vehicle_t *G_IsRidingVehicle( gentity_t *pEnt ); int teamNumbers[TEAM_NUM_TEAMS]; int teamStrength[TEAM_NUM_TEAMS]; int teamCounter[TEAM_NUM_TEAMS]; #define VALID_ATTACK_CONE 2.0f //Degrees void GetAnglesForDirection( const vec3_t p1, const vec3_t p2, vec3_t out ); /* void CalcEntitySpot ( gentity_t *ent, spot_t spot, vec3_t point ) Added: Uses shootAngles if a NPC has them */ extern void ViewHeightFix(const gentity_t *const ent); extern void AddLeanOfs(const gentity_t *const ent, vec3_t point); extern void SubtractLeanOfs(const gentity_t *const ent, vec3_t point); void CalcEntitySpot ( const gentity_t *ent, const spot_t spot, vec3_t point ) { vec3_t forward, up, right; vec3_t start, end; trace_t tr; if ( !ent ) { return; } ViewHeightFix(ent); switch ( spot ) { case SPOT_ORIGIN: if(VectorCompare(ent->currentOrigin, vec3_origin)) {//brush VectorSubtract(ent->absmax, ent->absmin, point);//size VectorMA(ent->absmin, 0.5, point, point); } else { VectorCopy ( ent->currentOrigin, point ); } break; case SPOT_CHEST: case SPOT_HEAD: if ( ent->client && VectorLengthSquared( ent->client->renderInfo.eyePoint ) && (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) ) {//Actual tag_head eyespot! //FIXME: Stasis aliens may have a problem here... VectorCopy( ent->client->renderInfo.eyePoint, point ); if ( ent->client->NPC_class == CLASS_ATST ) {//adjust up some point[2] += 28;//magic number :) } if ( ent->NPC ) {//always aim from the center of my bbox, so we don't wiggle when we lean forward or backwards point[0] = ent->currentOrigin[0]; point[1] = ent->currentOrigin[1]; } else if ( !ent->s.number ) { SubtractLeanOfs( ent, point ); } } else { VectorCopy ( ent->currentOrigin, point ); if ( ent->client ) { point[2] += ent->client->ps.viewheight; } } if ( spot == SPOT_CHEST && ent->client ) { if ( ent->client->NPC_class != CLASS_ATST ) {//adjust up some point[2] -= ent->maxs[2]*0.2f; } } break; case SPOT_HEAD_LEAN: if ( ent->client && VectorLengthSquared( ent->client->renderInfo.eyePoint ) && (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) ) {//Actual tag_head eyespot! //FIXME: Stasis aliens may have a problem here... VectorCopy( ent->client->renderInfo.eyePoint, point ); if ( ent->client->NPC_class == CLASS_ATST ) {//adjust up some point[2] += 28;//magic number :) } if ( ent->NPC ) {//always aim from the center of my bbox, so we don't wiggle when we lean forward or backwards point[0] = ent->currentOrigin[0]; point[1] = ent->currentOrigin[1]; } else if ( !ent->s.number ) { SubtractLeanOfs( ent, point ); } //NOTE: automatically takes leaning into account! } else { VectorCopy ( ent->currentOrigin, point ); if ( ent->client ) { point[2] += ent->client->ps.viewheight; } //AddLeanOfs ( ent, point ); } break; //FIXME: implement... //case SPOT_CHEST: //Returns point 3/4 from tag_torso to tag_head? //break; case SPOT_LEGS: VectorCopy ( ent->currentOrigin, point ); point[2] += (ent->mins[2] * 0.5); break; case SPOT_WEAPON: if( ent->NPC && !VectorCompare( ent->NPC->shootAngles, vec3_origin ) && !VectorCompare( ent->NPC->shootAngles, ent->client->ps.viewangles )) { AngleVectors( ent->NPC->shootAngles, forward, right, up ); } else { AngleVectors( ent->client->ps.viewangles, forward, right, up ); } CalcMuzzlePoint( (gentity_t*)ent, forward, right, up, point, 0 ); //NOTE: automatically takes leaning into account! break; case SPOT_GROUND: // if entity is on the ground, just use it's absmin if ( ent->s.groundEntityNum != -1 ) { VectorCopy( ent->currentOrigin, point ); point[2] = ent->absmin[2]; break; } // if it is reasonably close to the ground, give the point underneath of it VectorCopy( ent->currentOrigin, start ); start[2] = ent->absmin[2]; VectorCopy( start, end ); end[2] -= 64; gi.trace( &tr, start, ent->mins, ent->maxs, end, ent->s.number, MASK_PLAYERSOLID, (EG2_Collision)0, 0 ); if ( tr.fraction < 1.0 ) { VectorCopy( tr.endpos, point); break; } // otherwise just use the origin VectorCopy( ent->currentOrigin, point ); break; default: VectorCopy ( ent->currentOrigin, point ); break; } } //=================================================================================== /* qboolean NPC_UpdateAngles ( qboolean doPitch, qboolean doYaw ) Added: option to do just pitch or just yaw Does not include "aim" in it's calculations FIXME: stop compressing angles into shorts!!!! */ extern cvar_t *g_timescale; extern bool NPC_IsTrooper( gentity_t *ent ); qboolean NPC_UpdateAngles ( qboolean doPitch, qboolean doYaw ) { #if 1 float error; float decay; float targetPitch = 0; float targetYaw = 0; float yawSpeed; qboolean exact = qtrue; // if angle changes are locked; just keep the current angles // aimTime isn't even set anymore... so this code was never reached, but I need a way to lock NPC's yaw, so instead of making a new SCF_ flag, just use the existing render flag... - dmv if ( !NPC->enemy && ( (level.time < NPCInfo->aimTime) || NPC->client->renderInfo.renderFlags & RF_LOCKEDANGLE) ) { if(doPitch) targetPitch = NPCInfo->lockedDesiredPitch; if(doYaw) targetYaw = NPCInfo->lockedDesiredYaw; } else { // we're changing the lockedDesired Pitch/Yaw below so it's lost it's original meaning, get rid of the lock flag NPC->client->renderInfo.renderFlags &= ~RF_LOCKEDANGLE; if(doPitch) { targetPitch = NPCInfo->desiredPitch; NPCInfo->lockedDesiredPitch = NPCInfo->desiredPitch; } if(doYaw) { targetYaw = NPCInfo->desiredYaw; NPCInfo->lockedDesiredYaw = NPCInfo->desiredYaw; } } if ( NPC->s.weapon == WP_EMPLACED_GUN ) { // FIXME: this seems to do nothing, actually... yawSpeed = 20; } else { if ( NPC->client->NPC_class == CLASS_ROCKETTROOPER && !NPC->enemy ) {//just slowly lookin' around yawSpeed = 1; } else { yawSpeed = NPCInfo->stats.yawSpeed; } } if ( NPC->s.weapon == WP_SABER && NPC->client->ps.forcePowersActive&(1<<FP_SPEED) ) { yawSpeed *= 1.0f/g_timescale->value; } if (!NPC_IsTrooper(NPC) && NPC->enemy && !G_IsRidingVehicle( NPC ) && NPC->client->NPC_class != CLASS_VEHICLE ) { if (NPC->s.weapon==WP_BLASTER_PISTOL || NPC->s.weapon==WP_BLASTER || NPC->s.weapon==WP_BOWCASTER || NPC->s.weapon==WP_REPEATER || NPC->s.weapon==WP_FLECHETTE || NPC->s.weapon==WP_BRYAR_PISTOL || NPC->s.weapon==WP_NOGHRI_STICK) { yawSpeed *= 10.0f; } } if( doYaw ) { // decay yaw error error = AngleDelta ( NPC->client->ps.viewangles[YAW], targetYaw ); if( fabs(error) > MIN_ANGLE_ERROR ) { if ( error ) { exact = qfalse; decay = 60.0 + yawSpeed * 3; decay *= 50.0f / 1000.0f;//msec if ( error < 0.0 ) { error += decay; if ( error > 0.0 ) { error = 0.0; } } else { error -= decay; if ( error < 0.0 ) { error = 0.0; } } } } ucmd.angles[YAW] = ANGLE2SHORT( targetYaw + error ) - client->ps.delta_angles[YAW]; } //FIXME: have a pitchSpeed? if( doPitch ) { // decay pitch error error = AngleDelta ( NPC->client->ps.viewangles[PITCH], targetPitch ); if ( fabs(error) > MIN_ANGLE_ERROR ) { if ( error ) { exact = qfalse; decay = 60.0 + yawSpeed * 3; decay *= 50.0f / 1000.0f;//msec if ( error < 0.0 ) { error += decay; if ( error > 0.0 ) { error = 0.0; } } else { error -= decay; if ( error < 0.0 ) { error = 0.0; } } } } ucmd.angles[PITCH] = ANGLE2SHORT( targetPitch + error ) - client->ps.delta_angles[PITCH]; } ucmd.angles[ROLL] = ANGLE2SHORT ( NPC->client->ps.viewangles[ROLL] ) - client->ps.delta_angles[ROLL]; if ( exact && Q3_TaskIDPending( NPC, TID_ANGLE_FACE ) ) { Q3_TaskIDComplete( NPC, TID_ANGLE_FACE ); } return exact; #else float error; float decay; float targetPitch = 0; float targetYaw = 0; float yawSpeed; //float runningMod = NPCInfo->currentSpeed/100.0f; qboolean exact = qtrue; qboolean doSound = qfalse; // if angle changes are locked; just keep the current angles if ( level.time < NPCInfo->aimTime ) { if(doPitch) targetPitch = NPCInfo->lockedDesiredPitch; if(doYaw) targetYaw = NPCInfo->lockedDesiredYaw; } else { if(doPitch) targetPitch = NPCInfo->desiredPitch; if(doYaw) targetYaw = NPCInfo->desiredYaw; // NPCInfo->aimTime = level.time + 250; if(doPitch) NPCInfo->lockedDesiredPitch = NPCInfo->desiredPitch; if(doYaw) NPCInfo->lockedDesiredYaw = NPCInfo->desiredYaw; } yawSpeed = NPCInfo->stats.yawSpeed; if(doYaw) { // decay yaw error error = AngleDelta ( NPC->client->ps.viewangles[YAW], targetYaw ); if( fabs(error) > MIN_ANGLE_ERROR ) { /* if(NPC->client->playerTeam == TEAM_BORG&& NPCInfo->behaviorState != BS_FACE&&NPCInfo->tempBehavior!= BS_FACE) {//HACK - borg turn more jittery if ( error ) { exact = qfalse; decay = 60.0 + yawSpeed * 3; decay *= 50.0 / 1000.0;//msec //Snap to if(fabs(error) > 10) { if(random() > 0.6) { doSound = qtrue; } } if ( error < 0.0)//-10.0 ) { error += decay; if ( error > 0.0 ) { error = 0.0; } } else if ( error > 0.0)//10.0 ) { error -= decay; if ( error < 0.0 ) { error = 0.0; } } } } else*/ if ( error ) { exact = qfalse; decay = 60.0 + yawSpeed * 3; decay *= 50.0 / 1000.0;//msec if ( error < 0.0 ) { error += decay; if ( error > 0.0 ) { error = 0.0; } } else { error -= decay; if ( error < 0.0 ) { error = 0.0; } } } } ucmd.angles[YAW] = ANGLE2SHORT( targetYaw + error ) - client->ps.delta_angles[YAW]; } //FIXME: have a pitchSpeed? if(doPitch) { // decay pitch error error = AngleDelta ( NPC->client->ps.viewangles[PITCH], targetPitch ); if ( fabs(error) > MIN_ANGLE_ERROR ) { /* if(NPC->client->playerTeam == TEAM_BORG&& NPCInfo->behaviorState != BS_FACE&&NPCInfo->tempBehavior!= BS_FACE) {//HACK - borg turn more jittery if ( error ) { exact = qfalse; decay = 60.0 + yawSpeed * 3; decay *= 50.0 / 1000.0;//msec //Snap to if(fabs(error) > 10) { if(random() > 0.6) { doSound = qtrue; } } if ( error < 0.0)//-10.0 ) { error += decay; if ( error > 0.0 ) { error = 0.0; } } else if ( error > 0.0)//10.0 ) { error -= decay; if ( error < 0.0 ) { error = 0.0; } } } } else*/ if ( error ) { exact = qfalse; decay = 60.0 + yawSpeed * 3; decay *= 50.0 / 1000.0;//msec if ( error < 0.0 ) { error += decay; if ( error > 0.0 ) { error = 0.0; } } else { error -= decay; if ( error < 0.0 ) { error = 0.0; } } } } ucmd.angles[PITCH] = ANGLE2SHORT( targetPitch + error ) - client->ps.delta_angles[PITCH]; } ucmd.angles[ROLL] = ANGLE2SHORT ( NPC->client->ps.viewangles[ROLL] ) - client->ps.delta_angles[ROLL]; /* if(doSound) { G_Sound(NPC, G_SoundIndex(va("sound/enemies/borg/borgservo%d.wav", Q_irand(1, 8)))); } */ return exact; #endif } void NPC_AimWiggle( vec3_t enemy_org ) { //shoot for somewhere between the head and torso //NOTE: yes, I know this looks weird, but it works if ( NPCInfo->aimErrorDebounceTime < level.time ) { NPCInfo->aimOfs[0] = 0.3*Q_flrand(NPC->enemy->mins[0], NPC->enemy->maxs[0]); NPCInfo->aimOfs[1] = 0.3*Q_flrand(NPC->enemy->mins[1], NPC->enemy->maxs[1]); if ( NPC->enemy->maxs[2] > 0 ) { NPCInfo->aimOfs[2] = NPC->enemy->maxs[2]*Q_flrand(0.0f, -1.0f); } } VectorAdd( enemy_org, NPCInfo->aimOfs, enemy_org ); } /* qboolean NPC_UpdateFiringAngles ( qboolean doPitch, qboolean doYaw ) Includes aim when determining angles - so they don't always hit... */ qboolean NPC_UpdateFiringAngles ( qboolean doPitch, qboolean doYaw ) { #if 0 float diff; float error; float targetPitch = 0; float targetYaw = 0; qboolean exact = qtrue; if ( level.time < NPCInfo->aimTime ) { if( doPitch ) targetPitch = NPCInfo->lockedDesiredPitch; if( doYaw ) targetYaw = NPCInfo->lockedDesiredYaw; } else { if( doPitch ) { targetPitch = NPCInfo->desiredPitch; NPCInfo->lockedDesiredPitch = NPCInfo->desiredPitch; } if( doYaw ) { targetYaw = NPCInfo->desiredYaw; NPCInfo->lockedDesiredYaw = NPCInfo->desiredYaw; } } if( doYaw ) { // add yaw error based on NPCInfo->aim value error = ((float)(6 - NPCInfo->stats.aim)) * Q_flrand(-1, 1); if(Q_irand(0, 1)) error *= -1; diff = AngleDelta ( NPC->client->ps.viewangles[YAW], targetYaw ); if ( diff ) exact = qfalse; ucmd.angles[YAW] = ANGLE2SHORT( targetYaw + diff + error ) - client->ps.delta_angles[YAW]; } if( doPitch ) { // add pitch error based on NPCInfo->aim value error = ((float)(6 - NPCInfo->stats.aim)) * Q_flrand(-1, 1); diff = AngleDelta ( NPC->client->ps.viewangles[PITCH], targetPitch ); if ( diff ) exact = qfalse; ucmd.angles[PITCH] = ANGLE2SHORT( targetPitch + diff + error ) - client->ps.delta_angles[PITCH]; } ucmd.angles[ROLL] = ANGLE2SHORT ( NPC->client->ps.viewangles[ROLL] ) - client->ps.delta_angles[ROLL]; return exact; #else float error, diff; float decay; float targetPitch = 0; float targetYaw = 0; qboolean exact = qtrue; // if angle changes are locked; just keep the current angles if ( level.time < NPCInfo->aimTime ) { if(doPitch) targetPitch = NPCInfo->lockedDesiredPitch; if(doYaw) targetYaw = NPCInfo->lockedDesiredYaw; } else { if(doPitch) targetPitch = NPCInfo->desiredPitch; if(doYaw) targetYaw = NPCInfo->desiredYaw; // NPCInfo->aimTime = level.time + 250; if(doPitch) NPCInfo->lockedDesiredPitch = NPCInfo->desiredPitch; if(doYaw) NPCInfo->lockedDesiredYaw = NPCInfo->desiredYaw; } if ( NPCInfo->aimErrorDebounceTime < level.time ) { if ( Q_irand(0, 1 ) ) { NPCInfo->lastAimErrorYaw = ((float)(6 - NPCInfo->stats.aim)) * Q_flrand(-1, 1); } if ( Q_irand(0, 1 ) ) { NPCInfo->lastAimErrorPitch = ((float)(6 - NPCInfo->stats.aim)) * Q_flrand(-1, 1); } NPCInfo->aimErrorDebounceTime = level.time + Q_irand(250, 2000); } if(doYaw) { // decay yaw diff diff = AngleDelta ( NPC->client->ps.viewangles[YAW], targetYaw ); if ( diff) { exact = qfalse; decay = 60.0 + 80.0; decay *= 50.0f / 1000.0f;//msec if ( diff < 0.0 ) { diff += decay; if ( diff > 0.0 ) { diff = 0.0; } } else { diff -= decay; if ( diff < 0.0 ) { diff = 0.0; } } } // add yaw error based on NPCInfo->aim value error = NPCInfo->lastAimErrorYaw; /* if(Q_irand(0, 1)) { error *= -1; } */ ucmd.angles[YAW] = ANGLE2SHORT( targetYaw + diff + error ) - client->ps.delta_angles[YAW]; } if(doPitch) { // decay pitch diff diff = AngleDelta ( NPC->client->ps.viewangles[PITCH], targetPitch ); if ( diff) { exact = qfalse; decay = 60.0 + 80.0; decay *= 50.0f / 1000.0f;//msec if ( diff < 0.0 ) { diff += decay; if ( diff > 0.0 ) { diff = 0.0; } } else { diff -= decay; if ( diff < 0.0 ) { diff = 0.0; } } } error = NPCInfo->lastAimErrorPitch; ucmd.angles[PITCH] = ANGLE2SHORT( targetPitch + diff + error ) - client->ps.delta_angles[PITCH]; } ucmd.angles[ROLL] = ANGLE2SHORT ( NPC->client->ps.viewangles[ROLL] ) - client->ps.delta_angles[ROLL]; return exact; #endif } //=================================================================================== /* static void NPC_UpdateShootAngles (vec3_t angles, qboolean doPitch, qboolean doYaw ) Does update angles on shootAngles */ void NPC_UpdateShootAngles (vec3_t angles, qboolean doPitch, qboolean doYaw ) {//FIXME: shoot angles either not set right or not used! float error; float decay; float targetPitch = 0; float targetYaw = 0; if(doPitch) targetPitch = angles[PITCH]; if(doYaw) targetYaw = angles[YAW]; if(doYaw) { // decay yaw error error = AngleDelta ( NPCInfo->shootAngles[YAW], targetYaw ); if ( error ) { decay = 60.0 + 80.0 * NPCInfo->stats.aim; decay *= 100.0f / 1000.0f;//msec if ( error < 0.0 ) { error += decay; if ( error > 0.0 ) { error = 0.0; } } else { error -= decay; if ( error < 0.0 ) { error = 0.0; } } } NPCInfo->shootAngles[YAW] = targetYaw + error; } if(doPitch) { // decay pitch error error = AngleDelta ( NPCInfo->shootAngles[PITCH], targetPitch ); if ( error ) { decay = 60.0 + 80.0 * NPCInfo->stats.aim; decay *= 100.0f / 1000.0f;//msec if ( error < 0.0 ) { error += decay; if ( error > 0.0 ) { error = 0.0; } } else { error -= decay; if ( error < 0.0 ) { error = 0.0; } } } NPCInfo->shootAngles[PITCH] = targetPitch + error; } } /* void SetTeamNumbers (void) Sets the number of living clients on each team FIXME: Does not account for non-respawned players! FIXME: Don't include medics? */ void SetTeamNumbers (void) { gentity_t *found; int i; for( i = 0; i < TEAM_NUM_TEAMS; i++ ) { teamNumbers[i] = 0; teamStrength[i] = 0; } for( i = 0; i < 1 ; i++ ) { found = &g_entities[i]; if( found->client ) { if( found->health > 0 )//FIXME: or if a player! { teamNumbers[found->client->playerTeam]++; teamStrength[found->client->playerTeam] += found->health; } } } for( i = 0; i < TEAM_NUM_TEAMS; i++ ) {//Get the average health teamStrength[i] = floor( ((float)(teamStrength[i])) / ((float)(teamNumbers[i])) ); } } extern stringID_table_t BSTable[]; extern stringID_table_t BSETTable[]; qboolean G_ActivateBehavior (gentity_t *self, int bset ) { bState_t bSID = (bState_t)-1; char *bs_name = NULL; if ( !self ) { return qfalse; } bs_name = self->behaviorSet[bset]; if( !(VALIDSTRING( bs_name )) ) { return qfalse; } if ( self->NPC ) { bSID = (bState_t)(GetIDForString( BSTable, bs_name )); } if(bSID != (bState_t)-1) { self->NPC->tempBehavior = BS_DEFAULT; self->NPC->behaviorState = bSID; if ( bSID == BS_SEARCH || bSID == BS_WANDER ) { //FIXME: Reimplement? if( self->waypoint != WAYPOINT_NONE ) { NPC_BSSearchStart( self->waypoint, bSID ); } else { self->waypoint = NAV::GetNearestNode(self); if( self->waypoint != WAYPOINT_NONE ) { NPC_BSSearchStart( self->waypoint, bSID ); } } } } else { Quake3Game()->DebugPrint( IGameInterface::WL_VERBOSE, "%s attempting to run bSet %s (%s)\n", self->targetname, GetStringForID( BSETTable, bset ), bs_name ); Quake3Game()->RunScript( self, bs_name ); } return qtrue; } /* ============================================================================= Extended Functions ============================================================================= */ /* ------------------------- NPC_ValidEnemy ------------------------- */ qboolean G_ValidEnemy( gentity_t *self, gentity_t *enemy ) { //Must be a valid pointer if ( enemy == NULL ) return qfalse; //Must not be me if ( enemy == self ) return qfalse; //Must not be deleted if ( enemy->inuse == qfalse ) return qfalse; //Must be alive if ( enemy->health <= 0 ) return qfalse; //In case they're in notarget mode if ( enemy->flags & FL_NOTARGET ) return qfalse; //Must be an NPC if ( enemy->client == NULL ) { if ( enemy->svFlags&SVF_NONNPC_ENEMY ) {//still potentially valid if (self->client) { if ( enemy->noDamageTeam == self->client->playerTeam ) { return qfalse; } else { return qtrue; } } else { if ( enemy->noDamageTeam == self->noDamageTeam ) { return qfalse; } else { return qtrue; } } } else { return qfalse; } } if ( enemy->client->playerTeam == TEAM_FREE && enemy->s.number < MAX_CLIENTS ) {//An evil player, everyone attacks him return qtrue; } //Can't be on the same team if ( enemy->client->playerTeam == self->client->playerTeam ) { return qfalse; } //if haven't seen him in a while, give up //if ( NPCInfo->enemyLastSeenTime != 0 && level.time - NPCInfo->enemyLastSeenTime > 7000 )//FIXME: make a stat? // return qfalse; if ( enemy->client->playerTeam == self->client->enemyTeam //simplest case: they're on my enemy team || (self->client->enemyTeam == TEAM_FREE && enemy->client->NPC_class != self->client->NPC_class )//I get mad at anyone and this guy isn't the same class as me || (enemy->client->NPC_class == CLASS_WAMPA && enemy->enemy )//a rampaging wampa || (enemy->client->NPC_class == CLASS_RANCOR && enemy->enemy )//a rampaging rancor || (enemy->client->playerTeam == TEAM_FREE && enemy->client->enemyTeam == TEAM_FREE && enemy->enemy && enemy->enemy->client && (enemy->enemy->client->playerTeam == self->client->playerTeam||(enemy->enemy->client->playerTeam != TEAM_ENEMY&&self->client->playerTeam==TEAM_PLAYER))) //enemy is a rampaging non-aligned creature who is attacking someone on our team or a non-enemy (this last condition is used only if we're a good guy - in effect, we protect the innocent) ) { return qtrue; } //all other cases = false? return qfalse; } qboolean NPC_ValidEnemy( gentity_t *ent ) { return G_ValidEnemy( NPC, ent ); } /* ------------------------- NPC_TargetVisible ------------------------- */ qboolean NPC_TargetVisible( gentity_t *ent ) { //Make sure we're in a valid range if ( DistanceSquared( ent->currentOrigin, NPC->currentOrigin ) > ( NPCInfo->stats.visrange * NPCInfo->stats.visrange ) ) return qfalse; //Check our FOV if ( InFOV( ent, NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov ) == qfalse ) return qfalse; //Check for sight if ( NPC_ClearLOS( ent ) == qfalse ) return qfalse; return qtrue; } /* ------------------------- NPC_GetCheckDelta ------------------------- */ /* #define CHECK_TIME_BASE 250 #define CHECK_TIME_BASE_SQUARED ( CHECK_TIME_BASE * CHECK_TIME_BASE ) static int NPC_GetCheckDelta( void ) { if ( NPC_ValidEnemy( NPC->enemy ) == qfalse ) { int distance = DistanceSquared( NPC->currentOrigin, g_entities[0].currentOrigin ); distance /= CHECK_TIME_BASE_SQUARED; return ( CHECK_TIME_BASE * distance ); } return 0; } */ /* ------------------------- NPC_FindNearestEnemy ------------------------- */ #define MAX_RADIUS_ENTS 256 //NOTE: This can cause entities to be lost #define NEAR_DEFAULT_RADIUS 256 extern gentity_t *G_CheckControlledTurretEnemy(gentity_t *self, gentity_t *enemy, qboolean validate ); int NPC_FindNearestEnemy( gentity_t *ent ) { gentity_t *radiusEnts[ MAX_RADIUS_ENTS ]; gentity_t *nearest; vec3_t mins, maxs; int nearestEntID = -1; float nearestDist = (float)WORLD_SIZE*(float)WORLD_SIZE; float distance; int numEnts, numChecks = 0; int i; //Setup the bbox to search in for ( i = 0; i < 3; i++ ) { mins[i] = ent->currentOrigin[i] - NPCInfo->stats.visrange; maxs[i] = ent->currentOrigin[i] + NPCInfo->stats.visrange; } //Get a number of entities in a given space numEnts = gi.EntitiesInBox( mins, maxs, radiusEnts, MAX_RADIUS_ENTS ); for ( i = 0; i < numEnts; i++ ) { nearest = G_CheckControlledTurretEnemy(ent, radiusEnts[i], qtrue); //Don't consider self if ( nearest == ent ) continue; //Must be valid if ( NPC_ValidEnemy( nearest ) == qfalse ) continue; numChecks++; //Must be visible if ( NPC_TargetVisible( nearest ) == qfalse ) continue; distance = DistanceSquared( ent->currentOrigin, nearest->currentOrigin ); //Found one closer to us if ( distance < nearestDist ) { nearestEntID = nearest->s.number; nearestDist = distance; } } return nearestEntID; } /* ------------------------- NPC_PickEnemyExt ------------------------- */ gentity_t *NPC_PickEnemyExt( qboolean checkAlerts = qfalse ) { //Check for Hazard Team status and remove this check /* if ( NPC->client->playerTeam != TEAM_STARFLEET ) { //If we've found the player, return it if ( NPC_FindPlayer() ) return &g_entities[0]; } */ //If we've asked for the closest enemy int entID = NPC_FindNearestEnemy( NPC ); //If we have a valid enemy, use it if ( entID >= 0 ) return &g_entities[entID]; if ( checkAlerts ) { int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, -1, qtrue, AEL_DISCOVERED ); //There is an event to look at if ( alertEvent >= 0 ) { alertEvent_t *event = &level.alertEvents[alertEvent]; //Don't pay attention to our own alerts if ( event->owner == NPC ) return NULL; if ( event->level >= AEL_DISCOVERED ) { //If it's the player, attack him if ( event->owner == &g_entities[0] ) return event->owner; //If it's on our team, then take its enemy as well if ( ( event->owner->client ) && ( event->owner->client->playerTeam == NPC->client->playerTeam ) ) return event->owner->enemy; } } } return NULL; } /* ------------------------- NPC_FindPlayer ------------------------- */ qboolean NPC_FindPlayer( void ) { return NPC_TargetVisible( &g_entities[0] ); } /* ------------------------- NPC_CheckPlayerDistance ------------------------- */ static qboolean NPC_CheckPlayerDistance( void ) { //Make sure we have an enemy if ( NPC->enemy == NULL ) return qfalse; //Only do this for non-players if ( NPC->enemy->s.number == 0 ) return qfalse; //must be set up to get mad at player if ( !NPC->client || NPC->client->enemyTeam != TEAM_PLAYER ) return qfalse; //Must be within our FOV if ( InFOV( &g_entities[0], NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov ) == qfalse ) return qfalse; float distance = DistanceSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); if ( distance > DistanceSquared( NPC->currentOrigin, g_entities[0].currentOrigin ) ) { G_SetEnemy( NPC, &g_entities[0] ); return qtrue; } return qfalse; } /* ------------------------- NPC_FindEnemy ------------------------- */ qboolean NPC_FindEnemy( qboolean checkAlerts = qfalse ) { //We're ignoring all enemies for now if( NPC->svFlags & SVF_IGNORE_ENEMIES ) { G_ClearEnemy( NPC ); return qfalse; } //we can't pick up any enemies for now if( NPCInfo->confusionTime > level.time ) { G_ClearEnemy( NPC ); return qfalse; } //Don't want a new enemy if ( ( NPC_ValidEnemy( NPC->enemy ) ) && ( NPC->svFlags & SVF_LOCKEDENEMY ) ) return qtrue; //See if the player is closer than our current enemy if ( NPC->client->NPC_class != CLASS_RANCOR && NPC->client->NPC_class != CLASS_WAMPA && NPC->client->NPC_class != CLASS_SAND_CREATURE && NPC_CheckPlayerDistance() ) {//rancors, wampas & sand creatures don't care if player is closer, they always go with closest return qtrue; } //Otherwise, turn off the flag NPC->svFlags &= ~SVF_LOCKEDENEMY; //If we've gotten here alright, then our target it still valid if ( NPC_ValidEnemy( NPC->enemy ) ) return qtrue; gentity_t *newenemy = NPC_PickEnemyExt( checkAlerts ); //if we found one, take it as the enemy if( NPC_ValidEnemy( newenemy ) ) { G_SetEnemy( NPC, newenemy ); return qtrue; } G_ClearEnemy( NPC ); return qfalse; } /* ------------------------- NPC_CheckEnemyExt ------------------------- */ qboolean NPC_CheckEnemyExt( qboolean checkAlerts ) { //Make sure we're ready to think again /* if ( NPCInfo->enemyCheckDebounceTime > level.time ) return qfalse; //Get our next think time NPCInfo->enemyCheckDebounceTime = level.time + NPC_GetCheckDelta(); //Attempt to find an enemy return NPC_FindEnemy(); */ return NPC_FindEnemy( checkAlerts ); } /* ------------------------- NPC_FacePosition ------------------------- */ qboolean NPC_FacePosition( vec3_t position, qboolean doPitch ) { vec3_t muzzle; qboolean facing = qtrue; //Get the positions if ( NPC->client && (NPC->client->NPC_class == CLASS_RANCOR || NPC->client->NPC_class == CLASS_WAMPA || NPC->client->NPC_class == CLASS_SAND_CREATURE) ) { CalcEntitySpot( NPC, SPOT_ORIGIN, muzzle ); muzzle[2] += NPC->maxs[2] * 0.75f; } else if ( NPC->client && NPC->client->NPC_class == CLASS_GALAKMECH ) { CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); } else { CalcEntitySpot( NPC, SPOT_HEAD_LEAN, muzzle );//SPOT_HEAD if ( NPC->client->NPC_class == CLASS_ROCKETTROOPER ) {//*sigh*, look down more position[2] -= 32; } } //Find the desired angles vec3_t angles; GetAnglesForDirection( muzzle, position, angles ); NPCInfo->desiredYaw = AngleNormalize360( angles[YAW] ); NPCInfo->desiredPitch = AngleNormalize360( angles[PITCH] ); if ( NPC->enemy && NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_ATST ) { // FIXME: this is kind of dumb, but it was the easiest way to get it to look sort of ok NPCInfo->desiredYaw += Q_flrand( -5, 5 ) + sin( level.time * 0.004f ) * 7; NPCInfo->desiredPitch += Q_flrand( -2, 2 ); } //Face that yaw NPC_UpdateAngles( qtrue, qtrue ); //Find the delta between our goal and our current facing float yawDelta = AngleNormalize360( NPCInfo->desiredYaw - ( SHORT2ANGLE( ucmd.angles[YAW] + client->ps.delta_angles[YAW] ) ) ); //See if we are facing properly if ( fabs( yawDelta ) > VALID_ATTACK_CONE ) facing = qfalse; if ( doPitch ) { //Find the delta between our goal and our current facing float currentAngles = ( SHORT2ANGLE( ucmd.angles[PITCH] + client->ps.delta_angles[PITCH] ) ); float pitchDelta = NPCInfo->desiredPitch - currentAngles; //See if we are facing properly if ( fabs( pitchDelta ) > VALID_ATTACK_CONE ) facing = qfalse; } return facing; } /* ------------------------- NPC_FaceEntity ------------------------- */ qboolean NPC_FaceEntity( gentity_t *ent, qboolean doPitch ) { vec3_t entPos; //Get the positions CalcEntitySpot( ent, SPOT_HEAD_LEAN, entPos ); return NPC_FacePosition( entPos, doPitch ); } /* ------------------------- NPC_FaceEnemy ------------------------- */ qboolean NPC_FaceEnemy( qboolean doPitch ) { if ( NPC == NULL ) return qfalse; if ( NPC->enemy == NULL ) return qfalse; return NPC_FaceEntity( NPC->enemy, doPitch ); } /* ------------------------- NPC_CheckCanAttackExt ------------------------- */ qboolean NPC_CheckCanAttackExt( void ) { //We don't want them to shoot if( NPCInfo->scriptFlags & SCF_DONT_FIRE ) return qfalse; //Turn to face if ( NPC_FaceEnemy( qtrue ) == qfalse ) return qfalse; //Must have a clear line of sight to the target if ( NPC_ClearShot( NPC->enemy ) == qfalse ) return qfalse; return qtrue; } /* ------------------------- NPC_ClearLookTarget ------------------------- */ void NPC_ClearLookTarget( gentity_t *self ) { if ( !self->client ) { return; } self->client->renderInfo.lookTarget = ENTITYNUM_NONE;//ENTITYNUM_WORLD; self->client->renderInfo.lookTargetClearTime = 0; } /* ------------------------- NPC_SetLookTarget ------------------------- */ void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ) { if ( !self->client ) { return; } self->client->renderInfo.lookTarget = entNum; self->client->renderInfo.lookTargetClearTime = clearTime; } /* ------------------------- NPC_CheckLookTarget ------------------------- */ qboolean NPC_CheckLookTarget( gentity_t *self ) { if ( self->client ) { if ( self->client->renderInfo.lookTarget >= 0 && self->client->renderInfo.lookTarget < ENTITYNUM_WORLD ) {//within valid range if ( (&g_entities[self->client->renderInfo.lookTarget] == NULL) || !g_entities[self->client->renderInfo.lookTarget].inuse ) {//lookTarget not inuse or not valid anymore NPC_ClearLookTarget( self ); } else if ( self->client->renderInfo.lookTargetClearTime && self->client->renderInfo.lookTargetClearTime < level.time ) {//Time to clear lookTarget NPC_ClearLookTarget( self ); } else if ( g_entities[self->client->renderInfo.lookTarget].client && self->enemy && (&g_entities[self->client->renderInfo.lookTarget] != self->enemy) ) {//should always look at current enemy if engaged in battle... FIXME: this could override certain scripted lookTargets...??? NPC_ClearLookTarget( self ); } else { return qtrue; } } } return qfalse; } /* ------------------------- NPC_CheckCharmed ------------------------- */ extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); void G_CheckCharmed( gentity_t *self ) { if ( self && self->client && self->client->playerTeam == TEAM_PLAYER && self->NPC && self->NPC->charmedTime && (self->NPC->charmedTime < level.time ||self->health <= 0) ) {//we were charmed, set us back! //NOTE: presumptions here... team_t savTeam = self->client->enemyTeam; self->client->enemyTeam = self->client->playerTeam; self->client->playerTeam = savTeam; self->client->leader = NULL; self->NPC->charmedTime = 0; if ( self->health > 0 ) { if ( self->NPC->tempBehavior == BS_FOLLOW_LEADER ) { self->NPC->tempBehavior = BS_DEFAULT; } G_ClearEnemy( self ); //say something to let player know you've snapped out of it G_AddVoiceEvent( self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); } } } void G_GetBoltPosition( gentity_t *self, int boltIndex, vec3_t pos, int modelIndex = 0 ) { if ( !self || !self->ghoul2.size() ) { return; } mdxaBone_t boltMatrix; vec3_t result, angles={0,self->currentAngles[YAW],0}; gi.G2API_GetBoltMatrix( self->ghoul2, modelIndex, boltIndex, &boltMatrix, angles, self->currentOrigin, (cg.time?cg.time:level.time), NULL, self->s.modelScale ); if ( pos ) { gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, result ); VectorCopy( result, pos ); } } float NPC_EntRangeFromBolt( gentity_t *targEnt, int boltIndex ) { vec3_t org = { 0.0f }; if ( !targEnt ) { return Q3_INFINITE; } G_GetBoltPosition( NPC, boltIndex, org ); return (Distance( targEnt->currentOrigin, org )); } float NPC_EnemyRangeFromBolt( int boltIndex ) { return (NPC_EntRangeFromBolt( NPC->enemy, boltIndex )); } int G_GetEntsNearBolt( gentity_t *self, gentity_t **radiusEnts, float radius, int boltIndex, vec3_t boltOrg ) { vec3_t mins, maxs; int i; //get my handRBolt's position vec3_t org = { 0.0f }; G_GetBoltPosition( self, boltIndex, org ); VectorCopy( org, boltOrg ); //Setup the bbox to search in for ( i = 0; i < 3; i++ ) { mins[i] = boltOrg[i] - radius; maxs[i] = boltOrg[i] + radius; } //Get the number of entities in a given space return (gi.EntitiesInBox( mins, maxs, radiusEnts, 128 )); } int NPC_GetEntsNearBolt( gentity_t **radiusEnts, float radius, int boltIndex, vec3_t boltOrg ) { return (G_GetEntsNearBolt( NPC, radiusEnts, radius, boltIndex, boltOrg )); } extern qboolean RT_Flying( gentity_t *self ); extern void RT_FlyStart( gentity_t *self ); extern void RT_FlyStop( gentity_t *self ); extern qboolean Boba_Flying( gentity_t *self ); extern void Boba_FlyStart( gentity_t *self ); extern void Boba_FlyStop( gentity_t *self ); qboolean JET_Flying( gentity_t *self ) { if ( !self || !self->client ) { return qfalse; } if ( self->client->NPC_class == CLASS_BOBAFETT ) { return (Boba_Flying(self)); } else if ( self->client->NPC_class == CLASS_ROCKETTROOPER ) { return (RT_Flying(self)); } else { return qfalse; } } void JET_FlyStart( gentity_t *self ) { if ( !self || !self->client ) { return; } self->lastInAirTime = level.time; if ( self->client->NPC_class == CLASS_BOBAFETT ) { Boba_FlyStart( self ); } else if ( self->client->NPC_class == CLASS_ROCKETTROOPER ) { RT_FlyStart( self ); } } void JET_FlyStop( gentity_t *self ) { if ( !self || !self->client ) { return; } if ( self->client->NPC_class == CLASS_BOBAFETT ) { Boba_FlyStop( self ); } else if ( self->client->NPC_class == CLASS_ROCKETTROOPER ) { RT_FlyStop( self ); } }
BruceJohnJennerLawso/OtherJK
code/game/NPC_utils.cpp
C++
gpl-2.0
37,217
<?php /* Plugin Name: Unused Shortcodes Plugin URI: https://surpriseazwebservices.com/wordpress-plugins/wordpress-unused-shortcodes/ Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=4CZMFDE6YG95L Description: A plugin to display shortcodes that are not currently being used on a WordPress site. Version: 1.0.1 Author: Scott DeLuzio Author URI: https://surpriseazwebservices.com License: GPL2 */ /* Copyright 2013 Scott DeLuzio (email : scott (at) surpriseazwebservices.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* Add language support */ function unused_sc_lang() { load_plugin_textdomain('php_info_translate', false, dirname(plugin_basename(__FILE__)) . '/lang/'); } add_action('init', 'unused_sc_lang'); /* Settings Page */ // Hook for adding admin menus add_action('admin_menu', 'unusedshortcodes'); // action function for above hook function unusedshortcodes() { // Add a new submenu under Settings: add_options_page('Unused Shortcodes','Unused Shortcodes', 'manage_options', 'unusedshortcodes', 'unusedshortcodespage'); } add_action('admin_init', 'register_unused_shortcodes_settings'); function activate_unused_shortcodes() { add_option('find_shortcode', 'Enter Shortcode Here'); } function deactivate_unused_shortcodes() { delete_option('find_shortcode'); } register_activation_hook(__FILE__, 'activate_unused_shortcodes'); register_deactivation_hook(__FILE__, 'deactivate_unused_shortcodes'); function register_unused_shortcodes_settings() { register_setting( 'unused_shortcodes_group', 'find_shortcode'); } // Display the page content for the submenu function unusedshortcodespage() { include(WP_PLUGIN_DIR.'/unused-shortcodes/options.php'); } /* Find each available shortcode in a page or post */ function find_shortcodes($atts) { ob_start(); extract(shortcode_atts(array('find' => ''), $atts)); $string = "["; $string .= $atts['find']; $args = array('s' => $string); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) { echo '<strong>' . $string . ']</strong> '; echo _e('is currently in use in the following page(s)/post(s):', 'unused_sc_lang'); echo '<ul>'; while ( $the_query->have_posts() ) { $the_query->the_post(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> | <?php edit_post_link(); ?></li> <?php } echo '</ul>'; } else { echo _e('No posts found using the shortcode ', 'unused_sc_lang') . '<strong>' . $string . ']</strong>'; } wp_reset_postdata(); return ob_get_clean(); } add_shortcode('unusedshortcodes', 'find_shortcodes'); ?>
wp-plugins/unused-shortcodes
unused-shortcodes.php
PHP
gpl-2.0
3,379
/* * Fix up the given binary block with the reloc data */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <unistd.h> #include <ctype.h> #include <fcntl.h> #include <errno.h> #include <getopt.h> #define NBANKS 4 unsigned char buf[NBANKS][65536]; unsigned int size[NBANKS]; FILE *fptr[NBANKS]; int v = 0; static int nextfix; static int lastfix; static int stub_all; struct symbol { struct symbol *next; char *name; unsigned int val; }; struct symbol *symbols; struct stubmap { struct stubmap *next; int sbank; int dbank; uint16_t addr; uint16_t target; }; struct stubmap *stubs; static int stubct = 0; static int stubdup = 0; unsigned int resize(int b) { unsigned char *bp = buf[b] + 65535; while(*bp == 0) bp--; bp++; if (bp - buf[b] > size[b]) return bp - buf[b]; return size[b]; } void add_symbol(char *name, unsigned int val) { struct symbol *s = malloc(sizeof(struct symbol) + strlen(name) + 1); if (s == NULL) { fprintf(stderr, "Out of memory.\n"); exit(1); } s->name = (char *)(s + 1); s->val = val; strcpy(s->name, name); s->next = symbols; symbols = s; } unsigned int find_symbol(const char *name) { struct symbol *s = symbols; while (s) { if (strcmp(s->name, name) == 0) return s->val; s = s->next; } fprintf(stderr, "Symbol '%s' is missing for banked use.\n", name); exit(1); } unsigned int get_bank_function(int sbank, int dbank) { char name[32]; sprintf(name, "__bank_%d_%d", sbank, dbank); return find_symbol(name); } unsigned int get_stub_function(int sbank, int dbank) { char name[32]; sprintf(name, "__stub_%d_%d", sbank, dbank); return find_symbol(name); } int stubmap(uint16_t v, int sbank, int dbank) { struct stubmap *s = stubs; struct stubmap **p = &stubs; uint16_t da; while(s) { if (s->sbank == sbank && s->addr == v && s->dbank == dbank) { stubdup++; return s->target; } p = &s->next; s = *p; } s = malloc(sizeof(struct stubmap)); if (s == NULL) { fprintf(stderr, "Out of memory.\n"); exit(1); } *p = s; s->next = NULL; s->sbank = sbank; s->dbank = dbank; s->addr = v; s->target = nextfix; if (nextfix >= lastfix) { fprintf(stderr, "Out of fix space (%d stubs used).\n", stubct); exit(1); } /* FIXME: we could have per bank stubs in ROM and not waste precious common memory here */ da = get_stub_function(sbank, dbank); /* LD DE, targetaddr */ buf[0][nextfix++] = 0x11; buf[0][nextfix++] = v & 0xFF; buf[0][nextfix++] = v >> 8; /* JP */ buf[0][nextfix++] = 0xC3; /* stub helper */ buf[0][nextfix++] = da & 0xFF; buf[0][nextfix++] = da >> 8; stubct++; return s->target; } void code_reloc(uint8_t sbank, uint16_t ptr, uint8_t dbank) { int da; if (ptr == 0) { fprintf(stderr, "Nonsense zero based code relocation.\n"); exit(1); } if (dbank == 0 || dbank >= NBANKS) { fprintf(stderr, "Invalid bank %d\n", dbank); exit(1); } switch(buf[sbank][ptr-1]) { case 0xC3: /* JP - needs stub */ if (v) printf("Converting JP at %04x to stub\n", ptr); da = stubmap(buf[sbank][ptr] + (buf[sbank][ptr+1] << 8), sbank, dbank); buf[sbank][ptr] = da & 0xFF; buf[sbank][ptr+1] = da >> 8; break; case 0xCD: /* PUSH AF CALL POP AF */ if (buf[sbank][ptr-2] != 0xF5|| buf[sbank][ptr+2] != 0xF1) { fprintf(stderr, "Bad format for relocated long call at %04x (%02x %02x %02x %02x %02x\n", ptr, buf[sbank][ptr-2], buf[sbank][ptr-1], buf[sbank][ptr], buf[sbank][ptr+1], buf[sbank][ptr+2]); exit(1); } if (v) printf("Converting CALL at %04x from bank %d to bank %d\n", ptr, sbank, dbank); /* Turn the push af into a call */ buf[sbank][ptr-2] = 0xCD; /* Move the address along */ buf[sbank][ptr+2] = buf[sbank][ptr+1]; buf[sbank][ptr+1] = buf[sbank][ptr]; /* Fit in the actual call target */ da = get_bank_function(sbank, dbank); /* Sequence is now CALL __bank_sbank_dbank DW target */ buf[sbank][ptr-1] = da & 0xFF; buf[sbank][ptr] = da >> 8; break; default: fprintf(stderr, "Bad relocation in code (%02X)%04X: %02X\n", sbank, ptr-1, buf[sbank][ptr-1]); } } void data_reloc(uint8_t sbank, uint16_t ptr, uint8_t dbank) { int na; uint16_t n; if (dbank == 0) return; /* Get the target */ n = buf[sbank][ptr] + (buf[sbank][ptr+1]<<8); if (v) printf("Stubhooking %04x for data reference.\n", ptr); /* Find the stub for it */ na = stubmap(n, sbank, dbank); if (na == -1) { fprintf(stderr, "No stub match: stubs stale\n"); exit(1); } /* Patch in the revised destination address */ buf[sbank][ptr] = na & 255; buf[sbank][ptr+1] = na >> 8; if (v) printf("Patched %04x to %04x\n", ptr, na); } int stub_code(char *name) { if(strncmp(name, "_CODE", 5) == 0) return 1; if(strcmp(name, "_VIDEO") == 0) return 1; if(strcmp(name, "_COMMONMEM") == 0) return 1; if(strncmp(name, "_DISCARD", 8) == 0) return 1; if(strncmp(name, "_BOOT", 5) == 0) return 1; /* Data */ if(strcmp(name, "_COMMONDATA") == 0) return 0; if(strcmp(name, "_INITIALIZER") == 0) return 0; if(strncmp(name, "_DATA", 5) == 0) return 0; if(strncmp(name, "_BUFFERS", 8) == 0) return 0; if(strcmp(name, "_FONT") == 0) return 0; if(strcmp(name , "_CONST") == 0) return 0; fprintf(stderr, "Unknown bank name %s\n", name); exit(1); } static void process_stub(char *p) { int b1, b2, addr; char name[65]; char sname[65]; if (strlen(p) > 4 && !isspace(p[8])) fprintf(stderr, "Overflow: %s", p); if (sscanf(p, "%02x %04x %02x %64s %64s", &b1, &addr, &b2, name, sname) != 5) { fprintf(stderr, "Invalid relocation link %s\n", p); exit(1); } /* A data relocation into another bank of data is treated as deliberate. We can't do much else. It's not code so we can't patch it, and if it's a data pointer (as it should be) then a relocation is nonsense! */ if (!stub_code(sname) && !stub_code(name)) return; /* If we are stubbing the lot then code is handled as data is */ if (stub_code(name) && !stub_all) code_reloc(b1, addr, b2); else data_reloc(b1, addr, b2); } static void scan_symbols(FILE *f) { char buf[256]; char *sym; unsigned int addr; while(fgets(buf, 255, f)) { if (memcmp(buf, " 0000", 9)) continue; /* Looks like a symbol */ if (sscanf(buf+5, "%x", &addr) != 1) continue; /* Smells like a symbol */ sym = strtok(buf+15, " \n\t"); if (!sym) continue; /* Guess it's a symbol then */ if (v && (strstr(sym, "_bank_") || strstr(sym, "_stub_"))) printf("Add symbol %s %x\n", sym, addr); add_symbol(sym, addr); } } static void move_initializers(void) { unsigned int s_initsrc; unsigned int s_initdst; unsigned int l_init; s_initsrc = find_symbol("s__INITIALIZER"); s_initdst = find_symbol("s__INITIALIZED"); l_init = find_symbol("l__INITIALIZER"); if (v) printf("Moving %d bytes from %x to %x for initialization\n", l_init, s_initsrc, s_initdst); memcpy(buf[0] + s_initdst, buf[0] + s_initsrc, l_init); } static void zero_data(void) { unsigned int seg, len; seg = find_symbol("s__DATA"); len = find_symbol("l__DATA"); if (v) printf("Zeroing %x for %d\n", seg, len); memset(buf[0] + seg, 0, len); seg = find_symbol("s__BSS"); len = find_symbol("l__BSS"); if (v) printf("Zeroing %u for %d\n", seg, len); memset(buf[0] + seg, 0, len); } int main(int argc, char *argv[]) { FILE *r; char in[256]; char bin[64]; int banks; int sb, ss; int opt; while ((opt = getopt(argc, argv, "av")) != -1) { switch (opt) { case 'a': stub_all = 1; break; case 'v': v = 1; break; } } if (argc != optind + 1) { fprintf(stderr, "%s -v stubstart-size\n", argv[0]); exit(1); } if (sscanf(argv[optind], "%x-%x", &sb, &ss) != 2) { fprintf(stderr, "%s: invalid stub info\n", argv[0]); exit(1); } nextfix = sb; lastfix = sb + (ss & ~3); r = fopen("fuzix.map", "r"); if (r == NULL) { perror("fuzix.map"); exit(1); } scan_symbols(r); fclose(r); r = fopen("relocs.dat", "r"); if (r == NULL) { perror("relocs.dat"); exit(1); } for (banks = 0; banks < 4; banks ++) { if (banks == 0) strcpy(bin, "common.bin"); else sprintf(bin, "bank%d.bin", banks); fptr[banks] = fopen(bin, "r+"); if (fptr[banks] == NULL) { if (errno != ENOENT) { perror(bin); exit(1); } } else { size[banks] = fread(buf[banks], 1, 65536, fptr[banks]); if (size[banks] < 1) { perror(bin); exit(1); } rewind(fptr[banks]); } } while(fgets(in, 256, r)) { if (*in != 'B') { fprintf(stderr, "Bad record: %s", in); exit(1); } if (v) printf("|%s", in); process_stub(in + 1); } fclose(r); move_initializers(); zero_data(); /* For SNA mode */ for (banks = 0; banks < 4; banks++) { if (fptr[banks]) { /* Just conceivably we might reloc a trailing zero byte and need to grow the file */ size[banks] = resize(banks); if (fwrite(buf[banks], size[banks], 1, fptr[banks]) != 1) { perror("fwrite"); exit(1); } fclose(fptr[banks]); } } printf("%d stub relocations using %d bytes, %d duplicates\n", stubct, stubct * 4, stubdup); exit(0); }
jameszhan/FUZIX
Kernel/tools/binmunge.c
C
gpl-2.0
9,678
/* lgammal * * Natural logarithm of gamma function * * * * SYNOPSIS: * * long double x, y, lgammal(); * extern int sgngam; * * y = lgammal(x); * * * * DESCRIPTION: * * Returns the base e (2.718...) logarithm of the absolute * value of the gamma function of the argument. * The sign (+1 or -1) of the gamma function is returned in a * global (extern) variable named sgngam. * * The positive domain is partitioned into numerous segments for approximation. * For x > 10, * log gamma(x) = (x - 0.5) log(x) - x + log sqrt(2 pi) + 1/x R(1/x^2) * Near the minimum at x = x0 = 1.46... the approximation is * log gamma(x0 + z) = log gamma(x0) + z^2 P(z)/Q(z) * for small z. * Elsewhere between 0 and 10, * log gamma(n + z) = log gamma(n) + z P(z)/Q(z) * for various selected n and small z. * * The cosecant reflection formula is employed for negative arguments. * * * * ACCURACY: * * * arithmetic domain # trials peak rms * Relative error: * IEEE 10, 30 100000 3.9e-34 9.8e-35 * IEEE 0, 10 100000 3.8e-34 5.3e-35 * Absolute error: * IEEE -10, 0 100000 8.0e-34 8.0e-35 * IEEE -30, -10 100000 4.4e-34 1.0e-34 * IEEE -100, 100 100000 1.0e-34 * * The absolute error criterion is the same as relative error * when the function magnitude is greater than one but it is absolute * when the magnitude is less than one. * */ /* Copyright 2001 by Stephen L. Moshier <moshier@na-net.ornl.gov> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "math.h" #include "math_private.h" static const long double PIL = 3.1415926535897932384626433832795028841972E0L; static const long double MAXLGM = 1.0485738685148938358098967157129705071571E4928L; static const long double one = 1.0L; static const long double zero = 0.0L; static const long double huge = 1.0e4000L; /* log gamma(x) = ( x - 0.5 ) * log(x) - x + LS2PI + 1/x P(1/x^2) 1/x <= 0.0741 (x >= 13.495...) Peak relative error 1.5e-36 */ static const long double ls2pi = 9.1893853320467274178032973640561763986140E-1L; #define NRASY 12 static const long double RASY[NRASY + 1] = { 8.333333333333333333333333333310437112111E-2L, -2.777777777777777777777774789556228296902E-3L, 7.936507936507936507795933938448586499183E-4L, -5.952380952380952041799269756378148574045E-4L, 8.417508417507928904209891117498524452523E-4L, -1.917526917481263997778542329739806086290E-3L, 6.410256381217852504446848671499409919280E-3L, -2.955064066900961649768101034477363301626E-2L, 1.796402955865634243663453415388336954675E-1L, -1.391522089007758553455753477688592767741E0L, 1.326130089598399157988112385013829305510E1L, -1.420412699593782497803472576479997819149E2L, 1.218058922427762808938869872528846787020E3L }; /* log gamma(x+13) = log gamma(13) + x P(x)/Q(x) -0.5 <= x <= 0.5 12.5 <= x+13 <= 13.5 Peak relative error 1.1e-36 */ static const long double lgam13a = 1.9987213134765625E1L; static const long double lgam13b = 1.3608962611495173623870550785125024484248E-6L; #define NRN13 7 static const long double RN13[NRN13 + 1] = { 8.591478354823578150238226576156275285700E11L, 2.347931159756482741018258864137297157668E11L, 2.555408396679352028680662433943000804616E10L, 1.408581709264464345480765758902967123937E9L, 4.126759849752613822953004114044451046321E7L, 6.133298899622688505854211579222889943778E5L, 3.929248056293651597987893340755876578072E3L, 6.850783280018706668924952057996075215223E0L }; #define NRD13 6 static const long double RD13[NRD13 + 1] = { 3.401225382297342302296607039352935541669E11L, 8.756765276918037910363513243563234551784E10L, 8.873913342866613213078554180987647243903E9L, 4.483797255342763263361893016049310017973E8L, 1.178186288833066430952276702931512870676E7L, 1.519928623743264797939103740132278337476E5L, 7.989298844938119228411117593338850892311E2L /* 1.0E0L */ }; /* log gamma(x+12) = log gamma(12) + x P(x)/Q(x) -0.5 <= x <= 0.5 11.5 <= x+12 <= 12.5 Peak relative error 4.1e-36 */ static const long double lgam12a = 1.75023040771484375E1L; static const long double lgam12b = 3.7687254483392876529072161996717039575982E-6L; #define NRN12 7 static const long double RN12[NRN12 + 1] = { 4.709859662695606986110997348630997559137E11L, 1.398713878079497115037857470168777995230E11L, 1.654654931821564315970930093932954900867E10L, 9.916279414876676861193649489207282144036E8L, 3.159604070526036074112008954113411389879E7L, 5.109099197547205212294747623977502492861E5L, 3.563054878276102790183396740969279826988E3L, 6.769610657004672719224614163196946862747E0L }; #define NRD12 6 static const long double RD12[NRD12 + 1] = { 1.928167007860968063912467318985802726613E11L, 5.383198282277806237247492369072266389233E10L, 5.915693215338294477444809323037871058363E9L, 3.241438287570196713148310560147925781342E8L, 9.236680081763754597872713592701048455890E6L, 1.292246897881650919242713651166596478850E5L, 7.366532445427159272584194816076600211171E2L /* 1.0E0L */ }; /* log gamma(x+11) = log gamma(11) + x P(x)/Q(x) -0.5 <= x <= 0.5 10.5 <= x+11 <= 11.5 Peak relative error 1.8e-35 */ static const long double lgam11a = 1.5104400634765625E1L; static const long double lgam11b = 1.1938309890295225709329251070371882250744E-5L; #define NRN11 7 static const long double RN11[NRN11 + 1] = { 2.446960438029415837384622675816736622795E11L, 7.955444974446413315803799763901729640350E10L, 1.030555327949159293591618473447420338444E10L, 6.765022131195302709153994345470493334946E8L, 2.361892792609204855279723576041468347494E7L, 4.186623629779479136428005806072176490125E5L, 3.202506022088912768601325534149383594049E3L, 6.681356101133728289358838690666225691363E0L }; #define NRD11 6 static const long double RD11[NRD11 + 1] = { 1.040483786179428590683912396379079477432E11L, 3.172251138489229497223696648369823779729E10L, 3.806961885984850433709295832245848084614E9L, 2.278070344022934913730015420611609620171E8L, 7.089478198662651683977290023829391596481E6L, 1.083246385105903533237139380509590158658E5L, 6.744420991491385145885727942219463243597E2L /* 1.0E0L */ }; /* log gamma(x+10) = log gamma(10) + x P(x)/Q(x) -0.5 <= x <= 0.5 9.5 <= x+10 <= 10.5 Peak relative error 5.4e-37 */ static const long double lgam10a = 1.280181884765625E1L; static const long double lgam10b = 8.6324252196112077178745667061642811492557E-6L; #define NRN10 7 static const long double RN10[NRN10 + 1] = { -1.239059737177249934158597996648808363783E14L, -4.725899566371458992365624673357356908719E13L, -7.283906268647083312042059082837754850808E12L, -5.802855515464011422171165179767478794637E11L, -2.532349691157548788382820303182745897298E10L, -5.884260178023777312587193693477072061820E8L, -6.437774864512125749845840472131829114906E6L, -2.350975266781548931856017239843273049384E4L }; #define NRD10 7 static const long double RD10[NRD10 + 1] = { -5.502645997581822567468347817182347679552E13L, -1.970266640239849804162284805400136473801E13L, -2.819677689615038489384974042561531409392E12L, -2.056105863694742752589691183194061265094E11L, -8.053670086493258693186307810815819662078E9L, -1.632090155573373286153427982504851867131E8L, -1.483575879240631280658077826889223634921E6L, -4.002806669713232271615885826373550502510E3L /* 1.0E0L */ }; /* log gamma(x+9) = log gamma(9) + x P(x)/Q(x) -0.5 <= x <= 0.5 8.5 <= x+9 <= 9.5 Peak relative error 3.6e-36 */ static const long double lgam9a = 1.06045989990234375E1L; static const long double lgam9b = 3.9037218127284172274007216547549861681400E-6L; #define NRN9 7 static const long double RN9[NRN9 + 1] = { -4.936332264202687973364500998984608306189E13L, -2.101372682623700967335206138517766274855E13L, -3.615893404644823888655732817505129444195E12L, -3.217104993800878891194322691860075472926E11L, -1.568465330337375725685439173603032921399E10L, -4.073317518162025744377629219101510217761E8L, -4.983232096406156139324846656819246974500E6L, -2.036280038903695980912289722995505277253E4L }; #define NRD9 7 static const long double RD9[NRD9 + 1] = { -2.306006080437656357167128541231915480393E13L, -9.183606842453274924895648863832233799950E12L, -1.461857965935942962087907301194381010380E12L, -1.185728254682789754150068652663124298303E11L, -5.166285094703468567389566085480783070037E9L, -1.164573656694603024184768200787835094317E8L, -1.177343939483908678474886454113163527909E6L, -3.529391059783109732159524500029157638736E3L /* 1.0E0L */ }; /* log gamma(x+8) = log gamma(8) + x P(x)/Q(x) -0.5 <= x <= 0.5 7.5 <= x+8 <= 8.5 Peak relative error 2.4e-37 */ static const long double lgam8a = 8.525146484375E0L; static const long double lgam8b = 1.4876690414300165531036347125050759667737E-5L; #define NRN8 8 static const long double RN8[NRN8 + 1] = { 6.600775438203423546565361176829139703289E11L, 3.406361267593790705240802723914281025800E11L, 7.222460928505293914746983300555538432830E10L, 8.102984106025088123058747466840656458342E9L, 5.157620015986282905232150979772409345927E8L, 1.851445288272645829028129389609068641517E7L, 3.489261702223124354745894067468953756656E5L, 2.892095396706665774434217489775617756014E3L, 6.596977510622195827183948478627058738034E0L }; #define NRD8 7 static const long double RD8[NRD8 + 1] = { 3.274776546520735414638114828622673016920E11L, 1.581811207929065544043963828487733970107E11L, 3.108725655667825188135393076860104546416E10L, 3.193055010502912617128480163681842165730E9L, 1.830871482669835106357529710116211541839E8L, 5.790862854275238129848491555068073485086E6L, 9.305213264307921522842678835618803553589E4L, 6.216974105861848386918949336819572333622E2L /* 1.0E0L */ }; /* log gamma(x+7) = log gamma(7) + x P(x)/Q(x) -0.5 <= x <= 0.5 6.5 <= x+7 <= 7.5 Peak relative error 3.2e-36 */ static const long double lgam7a = 6.5792388916015625E0L; static const long double lgam7b = 1.2320408538495060178292903945321122583007E-5L; #define NRN7 8 static const long double RN7[NRN7 + 1] = { 2.065019306969459407636744543358209942213E11L, 1.226919919023736909889724951708796532847E11L, 2.996157990374348596472241776917953749106E10L, 3.873001919306801037344727168434909521030E9L, 2.841575255593761593270885753992732145094E8L, 1.176342515359431913664715324652399565551E7L, 2.558097039684188723597519300356028511547E5L, 2.448525238332609439023786244782810774702E3L, 6.460280377802030953041566617300902020435E0L }; #define NRD7 7 static const long double RD7[NRD7 + 1] = { 1.102646614598516998880874785339049304483E11L, 6.099297512712715445879759589407189290040E10L, 1.372898136289611312713283201112060238351E10L, 1.615306270420293159907951633566635172343E9L, 1.061114435798489135996614242842561967459E8L, 3.845638971184305248268608902030718674691E6L, 7.081730675423444975703917836972720495507E4L, 5.423122582741398226693137276201344096370E2L /* 1.0E0L */ }; /* log gamma(x+6) = log gamma(6) + x P(x)/Q(x) -0.5 <= x <= 0.5 5.5 <= x+6 <= 6.5 Peak relative error 6.2e-37 */ static const long double lgam6a = 4.7874908447265625E0L; static const long double lgam6b = 8.9805548349424770093452324304839959231517E-7L; #define NRN6 8 static const long double RN6[NRN6 + 1] = { -3.538412754670746879119162116819571823643E13L, -2.613432593406849155765698121483394257148E13L, -8.020670732770461579558867891923784753062E12L, -1.322227822931250045347591780332435433420E12L, -1.262809382777272476572558806855377129513E11L, -7.015006277027660872284922325741197022467E9L, -2.149320689089020841076532186783055727299E8L, -3.167210585700002703820077565539658995316E6L, -1.576834867378554185210279285358586385266E4L }; #define NRD6 8 static const long double RD6[NRD6 + 1] = { -2.073955870771283609792355579558899389085E13L, -1.421592856111673959642750863283919318175E13L, -4.012134994918353924219048850264207074949E12L, -6.013361045800992316498238470888523722431E11L, -5.145382510136622274784240527039643430628E10L, -2.510575820013409711678540476918249524123E9L, -6.564058379709759600836745035871373240904E7L, -7.861511116647120540275354855221373571536E5L, -2.821943442729620524365661338459579270561E3L /* 1.0E0L */ }; /* log gamma(x+5) = log gamma(5) + x P(x)/Q(x) -0.5 <= x <= 0.5 4.5 <= x+5 <= 5.5 Peak relative error 3.4e-37 */ static const long double lgam5a = 3.17803955078125E0L; static const long double lgam5b = 1.4279566695619646941601297055408873990961E-5L; #define NRN5 9 static const long double RN5[NRN5 + 1] = { 2.010952885441805899580403215533972172098E11L, 1.916132681242540921354921906708215338584E11L, 7.679102403710581712903937970163206882492E10L, 1.680514903671382470108010973615268125169E10L, 2.181011222911537259440775283277711588410E9L, 1.705361119398837808244780667539728356096E8L, 7.792391565652481864976147945997033946360E6L, 1.910741381027985291688667214472560023819E5L, 2.088138241893612679762260077783794329559E3L, 6.330318119566998299106803922739066556550E0L }; #define NRD5 8 static const long double RD5[NRD5 + 1] = { 1.335189758138651840605141370223112376176E11L, 1.174130445739492885895466097516530211283E11L, 4.308006619274572338118732154886328519910E10L, 8.547402888692578655814445003283720677468E9L, 9.934628078575618309542580800421370730906E8L, 6.847107420092173812998096295422311820672E7L, 2.698552646016599923609773122139463150403E6L, 5.526516251532464176412113632726150253215E4L, 4.772343321713697385780533022595450486932E2L /* 1.0E0L */ }; /* log gamma(x+4) = log gamma(4) + x P(x)/Q(x) -0.5 <= x <= 0.5 3.5 <= x+4 <= 4.5 Peak relative error 6.7e-37 */ static const long double lgam4a = 1.791748046875E0L; static const long double lgam4b = 1.1422353055000812477358380702272722990692E-5L; #define NRN4 9 static const long double RN4[NRN4 + 1] = { -1.026583408246155508572442242188887829208E13L, -1.306476685384622809290193031208776258809E13L, -7.051088602207062164232806511992978915508E12L, -2.100849457735620004967624442027793656108E12L, -3.767473790774546963588549871673843260569E11L, -4.156387497364909963498394522336575984206E10L, -2.764021460668011732047778992419118757746E9L, -1.036617204107109779944986471142938641399E8L, -1.895730886640349026257780896972598305443E6L, -1.180509051468390914200720003907727988201E4L }; #define NRD4 9 static const long double RD4[NRD4 + 1] = { -8.172669122056002077809119378047536240889E12L, -9.477592426087986751343695251801814226960E12L, -4.629448850139318158743900253637212801682E12L, -1.237965465892012573255370078308035272942E12L, -1.971624313506929845158062177061297598956E11L, -1.905434843346570533229942397763361493610E10L, -1.089409357680461419743730978512856675984E9L, -3.416703082301143192939774401370222822430E7L, -4.981791914177103793218433195857635265295E5L, -2.192507743896742751483055798411231453733E3L /* 1.0E0L */ }; /* log gamma(x+3) = log gamma(3) + x P(x)/Q(x) -0.25 <= x <= 0.5 2.75 <= x+3 <= 3.5 Peak relative error 6.0e-37 */ static const long double lgam3a = 6.93145751953125E-1L; static const long double lgam3b = 1.4286068203094172321214581765680755001344E-6L; #define NRN3 9 static const long double RN3[NRN3 + 1] = { -4.813901815114776281494823863935820876670E11L, -8.425592975288250400493910291066881992620E11L, -6.228685507402467503655405482985516909157E11L, -2.531972054436786351403749276956707260499E11L, -6.170200796658926701311867484296426831687E10L, -9.211477458528156048231908798456365081135E9L, -8.251806236175037114064561038908691305583E8L, -4.147886355917831049939930101151160447495E7L, -1.010851868928346082547075956946476932162E6L, -8.333374463411801009783402800801201603736E3L }; #define NRD3 9 static const long double RD3[NRD3 + 1] = { -5.216713843111675050627304523368029262450E11L, -8.014292925418308759369583419234079164391E11L, -5.180106858220030014546267824392678611990E11L, -1.830406975497439003897734969120997840011E11L, -3.845274631904879621945745960119924118925E10L, -4.891033385370523863288908070309417710903E9L, -3.670172254411328640353855768698287474282E8L, -1.505316381525727713026364396635522516989E7L, -2.856327162923716881454613540575964890347E5L, -1.622140448015769906847567212766206894547E3L /* 1.0E0L */ }; /* log gamma(x+2.5) = log gamma(2.5) + x P(x)/Q(x) -0.125 <= x <= 0.25 2.375 <= x+2.5 <= 2.75 */ static const long double lgam2r5a = 2.8466796875E-1L; static const long double lgam2r5b = 1.4901722919159632494669682701924320137696E-5L; #define NRN2r5 8 static const long double RN2r5[NRN2r5 + 1] = { -4.676454313888335499356699817678862233205E9L, -9.361888347911187924389905984624216340639E9L, -7.695353600835685037920815799526540237703E9L, -3.364370100981509060441853085968900734521E9L, -8.449902011848163568670361316804900559863E8L, -1.225249050950801905108001246436783022179E8L, -9.732972931077110161639900388121650470926E6L, -3.695711763932153505623248207576425983573E5L, -4.717341584067827676530426007495274711306E3L }; #define NRD2r5 8 static const long double RD2r5[NRD2r5 + 1] = { -6.650657966618993679456019224416926875619E9L, -1.099511409330635807899718829033488771623E10L, -7.482546968307837168164311101447116903148E9L, -2.702967190056506495988922973755870557217E9L, -5.570008176482922704972943389590409280950E8L, -6.536934032192792470926310043166993233231E7L, -4.101991193844953082400035444146067511725E6L, -1.174082735875715802334430481065526664020E5L, -9.932840389994157592102947657277692978511E2L /* 1.0E0L */ }; /* log gamma(x+2) = x P(x)/Q(x) -0.125 <= x <= +0.375 1.875 <= x+2 <= 2.375 Peak relative error 4.6e-36 */ #define NRN2 9 static const long double RN2[NRN2 + 1] = { -3.716661929737318153526921358113793421524E9L, -1.138816715030710406922819131397532331321E10L, -1.421017419363526524544402598734013569950E10L, -9.510432842542519665483662502132010331451E9L, -3.747528562099410197957514973274474767329E9L, -8.923565763363912474488712255317033616626E8L, -1.261396653700237624185350402781338231697E8L, -9.918402520255661797735331317081425749014E6L, -3.753996255897143855113273724233104768831E5L, -4.778761333044147141559311805999540765612E3L }; #define NRD2 9 static const long double RD2[NRD2 + 1] = { -8.790916836764308497770359421351673950111E9L, -2.023108608053212516399197678553737477486E10L, -1.958067901852022239294231785363504458367E10L, -1.035515043621003101254252481625188704529E10L, -3.253884432621336737640841276619272224476E9L, -6.186383531162456814954947669274235815544E8L, -6.932557847749518463038934953605969951466E7L, -4.240731768287359608773351626528479703758E6L, -1.197343995089189188078944689846348116630E5L, -1.004622911670588064824904487064114090920E3L /* 1.0E0 */ }; /* log gamma(x+1.75) = log gamma(1.75) + x P(x)/Q(x) -0.125 <= x <= +0.125 1.625 <= x+1.75 <= 1.875 Peak relative error 9.2e-37 */ static const long double lgam1r75a = -8.441162109375E-2L; static const long double lgam1r75b = 1.0500073264444042213965868602268256157604E-5L; #define NRN1r75 8 static const long double RN1r75[NRN1r75 + 1] = { -5.221061693929833937710891646275798251513E7L, -2.052466337474314812817883030472496436993E8L, -2.952718275974940270675670705084125640069E8L, -2.132294039648116684922965964126389017840E8L, -8.554103077186505960591321962207519908489E7L, -1.940250901348870867323943119132071960050E7L, -2.379394147112756860769336400290402208435E6L, -1.384060879999526222029386539622255797389E5L, -2.698453601378319296159355612094598695530E3L }; #define NRD1r75 8 static const long double RD1r75[NRD1r75 + 1] = { -2.109754689501705828789976311354395393605E8L, -5.036651829232895725959911504899241062286E8L, -4.954234699418689764943486770327295098084E8L, -2.589558042412676610775157783898195339410E8L, -7.731476117252958268044969614034776883031E7L, -1.316721702252481296030801191240867486965E7L, -1.201296501404876774861190604303728810836E6L, -5.007966406976106636109459072523610273928E4L, -6.155817990560743422008969155276229018209E2L /* 1.0E0L */ }; /* log gamma(x+x0) = y0 + x^2 P(x)/Q(x) -0.0867 <= x <= +0.1634 1.374932... <= x+x0 <= 1.625032... Peak relative error 4.0e-36 */ static const long double x0a = 1.4616241455078125L; static const long double x0b = 7.9994605498412626595423257213002588621246E-6L; static const long double y0a = -1.21490478515625E-1L; static const long double y0b = 4.1879797753919044854428223084178486438269E-6L; #define NRN1r5 8 static const long double RN1r5[NRN1r5 + 1] = { 6.827103657233705798067415468881313128066E5L, 1.910041815932269464714909706705242148108E6L, 2.194344176925978377083808566251427771951E6L, 1.332921400100891472195055269688876427962E6L, 4.589080973377307211815655093824787123508E5L, 8.900334161263456942727083580232613796141E4L, 9.053840838306019753209127312097612455236E3L, 4.053367147553353374151852319743594873771E2L, 5.040631576303952022968949605613514584950E0L }; #define NRD1r5 8 static const long double RD1r5[NRD1r5 + 1] = { 1.411036368843183477558773688484699813355E6L, 4.378121767236251950226362443134306184849E6L, 5.682322855631723455425929877581697918168E6L, 3.999065731556977782435009349967042222375E6L, 1.653651390456781293163585493620758410333E6L, 4.067774359067489605179546964969435858311E5L, 5.741463295366557346748361781768833633256E4L, 4.226404539738182992856094681115746692030E3L, 1.316980975410327975566999780608618774469E2L, /* 1.0E0L */ }; /* log gamma(x+1.25) = log gamma(1.25) + x P(x)/Q(x) -.125 <= x <= +.125 1.125 <= x+1.25 <= 1.375 Peak relative error = 4.9e-36 */ static const long double lgam1r25a = -9.82818603515625E-2L; static const long double lgam1r25b = 1.0023929749338536146197303364159774377296E-5L; #define NRN1r25 9 static const long double RN1r25[NRN1r25 + 1] = { -9.054787275312026472896002240379580536760E4L, -8.685076892989927640126560802094680794471E4L, 2.797898965448019916967849727279076547109E5L, 6.175520827134342734546868356396008898299E5L, 5.179626599589134831538516906517372619641E5L, 2.253076616239043944538380039205558242161E5L, 5.312653119599957228630544772499197307195E4L, 6.434329437514083776052669599834938898255E3L, 3.385414416983114598582554037612347549220E2L, 4.907821957946273805080625052510832015792E0L }; #define NRD1r25 8 static const long double RD1r25[NRD1r25 + 1] = { 3.980939377333448005389084785896660309000E5L, 1.429634893085231519692365775184490465542E6L, 2.145438946455476062850151428438668234336E6L, 1.743786661358280837020848127465970357893E6L, 8.316364251289743923178092656080441655273E5L, 2.355732939106812496699621491135458324294E5L, 3.822267399625696880571810137601310855419E4L, 3.228463206479133236028576845538387620856E3L, 1.152133170470059555646301189220117965514E2L /* 1.0E0L */ }; /* log gamma(x + 1) = x P(x)/Q(x) 0.0 <= x <= +0.125 1.0 <= x+1 <= 1.125 Peak relative error 1.1e-35 */ #define NRN1 8 static const long double RN1[NRN1 + 1] = { -9.987560186094800756471055681088744738818E3L, -2.506039379419574361949680225279376329742E4L, -1.386770737662176516403363873617457652991E4L, 1.439445846078103202928677244188837130744E4L, 2.159612048879650471489449668295139990693E4L, 1.047439813638144485276023138173676047079E4L, 2.250316398054332592560412486630769139961E3L, 1.958510425467720733041971651126443864041E2L, 4.516830313569454663374271993200291219855E0L }; #define NRD1 7 static const long double RD1[NRD1 + 1] = { 1.730299573175751778863269333703788214547E4L, 6.807080914851328611903744668028014678148E4L, 1.090071629101496938655806063184092302439E5L, 9.124354356415154289343303999616003884080E4L, 4.262071638655772404431164427024003253954E4L, 1.096981664067373953673982635805821283581E4L, 1.431229503796575892151252708527595787588E3L, 7.734110684303689320830401788262295992921E1L /* 1.0E0 */ }; /* log gamma(x + 1) = x P(x)/Q(x) -0.125 <= x <= 0 0.875 <= x+1 <= 1.0 Peak relative error 7.0e-37 */ #define NRNr9 8 static const long double RNr9[NRNr9 + 1] = { 4.441379198241760069548832023257571176884E5L, 1.273072988367176540909122090089580368732E6L, 9.732422305818501557502584486510048387724E5L, -5.040539994443998275271644292272870348684E5L, -1.208719055525609446357448132109723786736E6L, -7.434275365370936547146540554419058907156E5L, -2.075642969983377738209203358199008185741E5L, -2.565534860781128618589288075109372218042E4L, -1.032901669542994124131223797515913955938E3L, }; #define NRDr9 8 static const long double RDr9[NRDr9 + 1] = { -7.694488331323118759486182246005193998007E5L, -3.301918855321234414232308938454112213751E6L, -5.856830900232338906742924836032279404702E6L, -5.540672519616151584486240871424021377540E6L, -3.006530901041386626148342989181721176919E6L, -9.350378280513062139466966374330795935163E5L, -1.566179100031063346901755685375732739511E5L, -1.205016539620260779274902967231510804992E4L, -2.724583156305709733221564484006088794284E2L /* 1.0E0 */ }; /* Evaluate P[n] x^n + P[n-1] x^(n-1) + ... + P[0] */ static long double neval (long double x, const long double *p, int n) { long double y; p += n; y = *p--; do { y = y * x + *p--; } while (--n > 0); return y; } /* Evaluate x^n+1 + P[n] x^(n) + P[n-1] x^(n-1) + ... + P[0] */ static long double deval (long double x, const long double *p, int n) { long double y; p += n; y = x + *p--; do { y = y * x + *p--; } while (--n > 0); return y; } #ifdef __STDC__ long double __ieee754_lgammal_r (long double x, int *signgamp) #else long double __ieee754_lgammal_r (x, signgamp) long double x; int *signgamp; #endif { long double p, q, w, z, nx; int i, nn; *signgamp = 1; if (! __finitel (x)) return x * x; if (x < 0.0L) { q = -x; p = __floorl (q); if (p == q) return (one / (p - p)); i = p; if ((i & 1) == 0) *signgamp = -1; else *signgamp = 1; z = q - p; if (z > 0.5L) { p += 1.0L; z = p - q; } z = q * __sinl (PIL * z); if (z == 0.0L) return (*signgamp * huge * huge); w = __ieee754_lgammal_r (q, &i); z = __logl (PIL / z) - w; return (z); } if (x < 13.5L) { p = 0.0L; nx = __floorl (x + 0.5L); nn = nx; switch (nn) { case 0: /* log gamma (x + 1) = log(x) + log gamma(x) */ if (x <= 0.125) { p = x * neval (x, RN1, NRN1) / deval (x, RD1, NRD1); } else if (x <= 0.375) { z = x - 0.25L; p = z * neval (z, RN1r25, NRN1r25) / deval (z, RD1r25, NRD1r25); p += lgam1r25b; p += lgam1r25a; } else if (x <= 0.625) { z = x + (1.0L - x0a); z = z - x0b; p = neval (z, RN1r5, NRN1r5) / deval (z, RD1r5, NRD1r5); p = p * z * z; p = p + y0b; p = p + y0a; } else if (x <= 0.875) { z = x - 0.75L; p = z * neval (z, RN1r75, NRN1r75) / deval (z, RD1r75, NRD1r75); p += lgam1r75b; p += lgam1r75a; } else { z = x - 1.0L; p = z * neval (z, RN2, NRN2) / deval (z, RD2, NRD2); } p = p - __logl (x); break; case 1: if (x < 0.875L) { if (x <= 0.625) { z = x + (1.0L - x0a); z = z - x0b; p = neval (z, RN1r5, NRN1r5) / deval (z, RD1r5, NRD1r5); p = p * z * z; p = p + y0b; p = p + y0a; } else if (x <= 0.875) { z = x - 0.75L; p = z * neval (z, RN1r75, NRN1r75) / deval (z, RD1r75, NRD1r75); p += lgam1r75b; p += lgam1r75a; } else { z = x - 1.0L; p = z * neval (z, RN2, NRN2) / deval (z, RD2, NRD2); } p = p - __logl (x); } else if (x < 1.0L) { z = x - 1.0L; p = z * neval (z, RNr9, NRNr9) / deval (z, RDr9, NRDr9); } else if (x == 1.0L) p = 0.0L; else if (x <= 1.125L) { z = x - 1.0L; p = z * neval (z, RN1, NRN1) / deval (z, RD1, NRD1); } else if (x <= 1.375) { z = x - 1.25L; p = z * neval (z, RN1r25, NRN1r25) / deval (z, RD1r25, NRD1r25); p += lgam1r25b; p += lgam1r25a; } else { /* 1.375 <= x+x0 <= 1.625 */ z = x - x0a; z = z - x0b; p = neval (z, RN1r5, NRN1r5) / deval (z, RD1r5, NRD1r5); p = p * z * z; p = p + y0b; p = p + y0a; } break; case 2: if (x < 1.625L) { z = x - x0a; z = z - x0b; p = neval (z, RN1r5, NRN1r5) / deval (z, RD1r5, NRD1r5); p = p * z * z; p = p + y0b; p = p + y0a; } else if (x < 1.875L) { z = x - 1.75L; p = z * neval (z, RN1r75, NRN1r75) / deval (z, RD1r75, NRD1r75); p += lgam1r75b; p += lgam1r75a; } else if (x == 2.0L) p = 0.0L; else if (x < 2.375L) { z = x - 2.0L; p = z * neval (z, RN2, NRN2) / deval (z, RD2, NRD2); } else { z = x - 2.5L; p = z * neval (z, RN2r5, NRN2r5) / deval (z, RD2r5, NRD2r5); p += lgam2r5b; p += lgam2r5a; } break; case 3: if (x < 2.75) { z = x - 2.5L; p = z * neval (z, RN2r5, NRN2r5) / deval (z, RD2r5, NRD2r5); p += lgam2r5b; p += lgam2r5a; } else { z = x - 3.0L; p = z * neval (z, RN3, NRN3) / deval (z, RD3, NRD3); p += lgam3b; p += lgam3a; } break; case 4: z = x - 4.0L; p = z * neval (z, RN4, NRN4) / deval (z, RD4, NRD4); p += lgam4b; p += lgam4a; break; case 5: z = x - 5.0L; p = z * neval (z, RN5, NRN5) / deval (z, RD5, NRD5); p += lgam5b; p += lgam5a; break; case 6: z = x - 6.0L; p = z * neval (z, RN6, NRN6) / deval (z, RD6, NRD6); p += lgam6b; p += lgam6a; break; case 7: z = x - 7.0L; p = z * neval (z, RN7, NRN7) / deval (z, RD7, NRD7); p += lgam7b; p += lgam7a; break; case 8: z = x - 8.0L; p = z * neval (z, RN8, NRN8) / deval (z, RD8, NRD8); p += lgam8b; p += lgam8a; break; case 9: z = x - 9.0L; p = z * neval (z, RN9, NRN9) / deval (z, RD9, NRD9); p += lgam9b; p += lgam9a; break; case 10: z = x - 10.0L; p = z * neval (z, RN10, NRN10) / deval (z, RD10, NRD10); p += lgam10b; p += lgam10a; break; case 11: z = x - 11.0L; p = z * neval (z, RN11, NRN11) / deval (z, RD11, NRD11); p += lgam11b; p += lgam11a; break; case 12: z = x - 12.0L; p = z * neval (z, RN12, NRN12) / deval (z, RD12, NRD12); p += lgam12b; p += lgam12a; break; case 13: z = x - 13.0L; p = z * neval (z, RN13, NRN13) / deval (z, RD13, NRD13); p += lgam13b; p += lgam13a; break; } return p; } if (x > MAXLGM) return (*signgamp * huge * huge); q = ls2pi - x; q = (x - 0.5L) * __logl (x) + q; if (x > 1.0e18L) return (q); p = 1.0L / (x * x); q += neval (p, RASY, NRASY) / x; return (q); }
dtbartle/glibc-opensolaris
sysdeps/ieee754/ldbl-128/e_lgammal_r.c
C
gpl-2.0
32,152
using UnityEngine; using System.Collections; public class FloppySpin : MonoBehaviour { void Update () { transform.Rotate(new Vector3(0.0f, 1.0f, 0.0f), -90.0f * Time.deltaTime, Space.World); } }
RocketSurgery/DDRGame
Assets/Scripts/FloppySpin.cs
C#
gpl-2.0
204
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_45) on Wed Jan 07 20:17:15 CST 2015 --> <title>BranchingPoint</title> <meta name="date" content="2015-01-07"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="BranchingPoint"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/BranchingPoint.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/semanticweb/HermiT/tableau/BlockingValidatorTest.html" title="class in org.semanticweb.HermiT.tableau"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../org/semanticweb/HermiT/tableau/ClashManager.html" title="class in org.semanticweb.HermiT.tableau"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/semanticweb/HermiT/tableau/BranchingPoint.html" target="_top">Frames</a></li> <li><a href="BranchingPoint.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.semanticweb.HermiT.tableau</div> <h2 title="Class BranchingPoint" class="title">Class BranchingPoint</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.semanticweb.HermiT.tableau.BranchingPoint</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.io.Serializable</dd> </dl> <dl> <dt>Direct Known Subclasses:</dt> <dd><a href="../../../../org/semanticweb/HermiT/tableau/DisjunctionBranchingPoint.html" title="class in org.semanticweb.HermiT.tableau">DisjunctionBranchingPoint</a></dd> </dl> <hr> <br> <pre>public class <span class="strong">BranchingPoint</span> extends java.lang.Object implements java.io.Serializable</pre> <div class="block">Represents a branching point for the tableau given to the constructor.</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../serialized-form.html#org.semanticweb.HermiT.tableau.BranchingPoint">Serialized Form</a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../org/semanticweb/HermiT/tableau/BranchingPoint.html#BranchingPoint(org.semanticweb.HermiT.tableau.Tableau)">BranchingPoint</a></strong>(<a href="../../../../org/semanticweb/HermiT/tableau/Tableau.html" title="class in org.semanticweb.HermiT.tableau">Tableau</a>&nbsp;tableau)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><strong><a href="../../../../org/semanticweb/HermiT/tableau/BranchingPoint.html#getLevel()">getLevel</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../org/semanticweb/HermiT/tableau/BranchingPoint.html#startNextChoice(org.semanticweb.HermiT.tableau.Tableau, org.semanticweb.HermiT.tableau.DependencySet)">startNextChoice</a></strong>(<a href="../../../../org/semanticweb/HermiT/tableau/Tableau.html" title="class in org.semanticweb.HermiT.tableau">Tableau</a>&nbsp;tableau, <a href="../../../../org/semanticweb/HermiT/tableau/DependencySet.html" title="interface in org.semanticweb.HermiT.tableau">DependencySet</a>&nbsp;clashDepdendencySet)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="BranchingPoint(org.semanticweb.HermiT.tableau.Tableau)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>BranchingPoint</h4> <pre>public&nbsp;BranchingPoint(<a href="../../../../org/semanticweb/HermiT/tableau/Tableau.html" title="class in org.semanticweb.HermiT.tableau">Tableau</a>&nbsp;tableau)</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getLevel()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getLevel</h4> <pre>public&nbsp;int&nbsp;getLevel()</pre> </li> </ul> <a name="startNextChoice(org.semanticweb.HermiT.tableau.Tableau, org.semanticweb.HermiT.tableau.DependencySet)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>startNextChoice</h4> <pre>public&nbsp;void&nbsp;startNextChoice(<a href="../../../../org/semanticweb/HermiT/tableau/Tableau.html" title="class in org.semanticweb.HermiT.tableau">Tableau</a>&nbsp;tableau, <a href="../../../../org/semanticweb/HermiT/tableau/DependencySet.html" title="interface in org.semanticweb.HermiT.tableau">DependencySet</a>&nbsp;clashDepdendencySet)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/BranchingPoint.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/semanticweb/HermiT/tableau/BlockingValidatorTest.html" title="class in org.semanticweb.HermiT.tableau"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../org/semanticweb/HermiT/tableau/ClashManager.html" title="class in org.semanticweb.HermiT.tableau"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/semanticweb/HermiT/tableau/BranchingPoint.html" target="_top">Frames</a></li> <li><a href="BranchingPoint.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
hrsky/PIOT
src/Hermit/doc/org/semanticweb/HermiT/tableau/BranchingPoint.html
HTML
gpl-2.0
10,527
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_112) on Sat Mar 04 13:30:06 CET 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>emulib.plugins.memory (emuLib 9.0.0 API)</title> <meta name="date" content="2017-03-04"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="emulib.plugins.memory (emuLib 9.0.0 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../emulib/plugins/device/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../emulib/runtime/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?emulib/plugins/memory/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Package" class="title">Package&nbsp;emulib.plugins.memory</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Interface Summary table, listing interfaces, and an explanation"> <caption><span>Interface Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Interface</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../emulib/plugins/memory/Memory.html" title="interface in emulib.plugins.memory">Memory</a></td> <td class="colLast"> <div class="block">Main interface for memory plug-ins.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../emulib/plugins/memory/Memory.MemoryListener.html" title="interface in emulib.plugins.memory">Memory.MemoryListener</a></td> <td class="colLast"> <div class="block">The listener interface for receiving memory related events.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../emulib/plugins/memory/MemoryContext.html" title="interface in emulib.plugins.memory">MemoryContext</a>&lt;CellType&gt;</td> <td class="colLast"> <div class="block">Interface provides a context for operating memory.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../emulib/plugins/memory/AbstractMemory.html" title="class in emulib.plugins.memory">AbstractMemory</a></td> <td class="colLast"> <div class="block">Abstract memory.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../emulib/plugins/memory/AbstractMemoryContext.html" title="class in emulib.plugins.memory">AbstractMemoryContext</a>&lt;Type&gt;</td> <td class="colLast"> <div class="block">This class implements some fundamental functionality of MemoryContext interface, that can be useful in the programming of the own memory context.</div> </td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../emulib/plugins/device/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../emulib/runtime/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?emulib/plugins/memory/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2017. All rights reserved.</small></p> </body> </html>
vbmacher/emuStudio
docs/_docdevel/emulib_javadoc/emulib/plugins/memory/package-summary.html
HTML
gpl-2.0
6,625
<?php /** * @package Chunk */ get_header(); ?> <?php if ( is_archive() ) : ?> <div class="page-title"> <h2> <?php if ( is_day() ) : ?> <?php printf( __( 'Posted on %s &hellip;', 'chunk' ), '<span>' . get_the_date() . '</span>' ); ?> <?php elseif ( is_month() ) : ?> <?php printf( __( 'Posted in %s &hellip;', 'chunk' ), '<span>' . get_the_date( 'F Y' ) . '</span>' ); ?> <?php elseif ( is_year() ) : ?> <?php printf( __( 'Posted in %s &hellip;', 'chunk' ), '<span>' . get_the_date( 'Y' ) . '</span>' ); ?> <?php elseif( is_author() ) : ?> <?php printf( __( 'Posted by %s &hellip;', 'chunk' ), '<span>' . get_the_author() . '</span>' ); ?> <?php elseif ( is_category() ) : ?> <?php printf( __( 'Filed under %s &hellip;', 'chunk' ), '<span>' . single_cat_title( '', false ) . '</span>' ); ?> <?php elseif ( is_tag() ) : ?> <?php printf( __( 'Tagged with %s &hellip;', 'chunk' ), '<span>' . single_tag_title( '', false ) . '</span>' ); ?> <?php endif; ?> </h2> </div> <?php endif; ?> <?php if ( is_search() ) : ?> <div class="page-title"> <h2> <?php printf( __( 'Matches for: &ldquo;%s&rdquo; &hellip;', 'chunk' ), '<span>' . get_search_query() . '</span>' ); ?> </h2> </div> <?php endif; ?> <div id="contents"> <?php if ( have_posts() ) : ?> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> <?php endwhile; ?> <?php else : ?> <div class="hentry error404"> <div class="postbody text"> <h1><?php _e( 'Nothing Found', 'chunk' ); ?></h1> <div class="content"> <p><?php _e( 'Apologies, but no results were found for the requested archive. Perhaps searching will help find a related post.', 'chunk' ); ?></p> <?php get_search_form(); ?> </div><!-- .content --> </div><!-- .postbody --> </div> <?php endif; ?> </div><!-- #contents --> <div class="navigation"> <div class="nav-previous"><?php next_posts_link( __( '<span class="meta-nav">&larr;</span> Older posts', 'chunk' ) ); ?></div> <div class="nav-next"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">&rarr;</span>', 'chunk' ) ); ?></div> </div> <?php get_footer(); ?>
firmread/avsysblog
wp-content/themes/chunk/index.php
PHP
gpl-2.0
2,209
/* Copyright (c) 2011-2012 - Tőkés Attila This file is part of SmtpClient for Qt. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. See the LICENSE file for more details. */ #ifndef QUOTEDPRINTABLE_H #define QUOTEDPRINTABLE_H #include <QtCore/QObject> #include <QtCore/QByteArray> #include "smtpexports.h" class SMTP_EXPORT QuotedPrintable : public QObject { Q_OBJECT public: static QString encode(const QByteArray &input); static QByteArray decode(const QString &input); private: QuotedPrintable(); }; #endif // QUOTEDPRINTABLE_H
morozovvl/qbalance
src/SMTPEmail/src/quotedprintable.h
C
gpl-2.0
1,022
/* * Copyright (c) 2009 NVIDIA Corporation. All rights reserved. * * NVIDIA Corporation and its licensors retain all intellectual property * and proprietary rights in and to this software and related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA Corporation is strictly prohibited. */ #include "nvodm_tmon_adt7461.h" #include "tmon_hal.h" // TODO: Always Disable before check-in // Always debug module: 0=disable, 1=enable #define NV_ADT7461_DEBUG (0) #if (NV_DEBUG || NV_ADT7461_DEBUG) #define NVODM_ADT7461_PRINTF(x) NvOdmOsDebugPrintf x #else #define NVODM_ADT7461_PRINTF(x) #endif #define ADT7461_ALERT_DEBOUNCE (1) // ADT7461 Descrriptor static const ADT7461Info s_Adt7461Info = { // TMON device conversion channels { // Invalid channel {0}, // Local channel { ADT7461ChannelID_Local, { ADT7461_ODM_LOCAL_RATE_PROTECTED, ADT7461_ODM_LOCAL_INTR_LIMITS_PROTECTED, ADT7461_ODM_LOCAL_COMPARATOR_LIMIT_PROTECTED }, { ADT7461_LOCAL_INTR_LIMIT_HIGH_RD_ADDR, ADT7461_LOCAL_INTR_LIMIT_HIGH_WR_ADDR, }, { ADT7461_LOCAL_INTR_LIMIT_LOW_RD_ADDR, ADT7461_LOCAL_INTR_LIMIT_LOW_WR_ADDR, }, { ADT7461_LOCAL_COMPARATOR_LIMIT_ADDR, ADT7461_LOCAL_COMPARATOR_LIMIT_ADDR, }, { ADT7461_INVALID_ADDR, // Local offset does not exist ADT7461_INVALID_ADDR, }, { ADT7461_LOCAL_TDATA_RD_ADDR, ADT7461_INVALID_ADDR, }, }, // Remote channel { ADT7461ChannelID_Remote, { ADT7461_ODM_REMOTE_RATE_PROTECTED, ADT7461_ODM_REMOTE_INTR_LIMITS_PROTECTED, ADT7461_ODM_REMOTE_COMPARATOR_LIMIT_PROTECTED }, { ADT7461_REMOTE_INTR_LIMIT_HIGH_RD_ADDR, ADT7461_REMOTE_INTR_LIMIT_HIGH_WR_ADDR, }, { ADT7461_REMOTE_INTR_LIMIT_LOW_RD_ADDR, ADT7461_REMOTE_INTR_LIMIT_LOW_WR_ADDR, }, { ADT7461_REMOTE_COMPARATOR_LIMIT_ADDR, ADT7461_REMOTE_COMPARATOR_LIMIT_ADDR, }, { ADT7461_REMOTE_TOFFSET_ADDR, ADT7461_REMOTE_TOFFSET_ADDR, }, { ADT7461_REMOTE_TDATA_RD_ADDR, ADT7461_INVALID_ADDR, }, } }, // TMON device common status/control registers { ADT7461_STATUS_RD_ADDR, ADT7461_INVALID_ADDR, }, { ADT7461_CONFIG_RD_ADDR, ADT7461_CONFIG_WR_ADDR, }, { ADT7461_RATE_RD_ADDR, ADT7461_RATE_WR_ADDR, }, { ADT7461_INVALID_ADDR, ADT7461_ONE_SHOT_WR_ADDR, }, { ADT7461_COMPARATOR_HYSTERESIS_ADDR, ADT7461_COMPARATOR_HYSTERESIS_ADDR, }, { ADT7461_INTR_CNT_DELAY_ADDR, ADT7461_INTR_CNT_DELAY_ADDR, }, }; // ADT7461 sample intervals static const NvS32 s_Adt7461SampleIntervalsMS[] = { ADT7461_SAMPLE_INTERVALS_MS }; // ADT7461 converison times static const NvS32 s_Adt7461ConversionTimesMS[] = { ADT7461_CONVERSION_TIME_MS }; NV_CT_ASSERT(NV_ARRAY_SIZE(s_Adt7461SampleIntervalsMS) == NV_ARRAY_SIZE(s_Adt7461ConversionTimesMS)); /*****************************************************************************/ #define ADT7461_T_DATA_TO_VALUE(ExtRange, data) \ ( (ExtRange) ? \ ((NvS32)((NvU32)(data) - ADT7461_RANGE_EXTENDED_DATA_OFFSET)) : \ ((NvS32)((NvS8)data)) \ ) #define ADT7461_T_VALUE_TO_DATA(ExtRange, val) \ ( (ExtRange) ? \ ((NvU8)((NvU32)(val) + ADT7461_RANGE_EXTENDED_DATA_OFFSET)) : \ ((NvU8)(val)) \ ) #define ADT7461_T_RANGE_LIMIT_HIGH(ExtRange) \ ( (ExtRange) ? \ ADT7461_RANGE_EXTENDED_LIMIT_HIGH : \ ADT7461_RANGE_STANDARD_LIMIT_HIGH \ ) #define ADT7461_T_RANGE_LIMIT_LOW(ExtRange) \ ( (ExtRange) ? \ ADT7461_RANGE_EXTENDED_LIMIT_LOW : \ ADT7461_RANGE_STANDARD_LIMIT_LOW \ ) /*****************************************************************************/ static NvBool Adt7461WriteReg( ADT7461PrivData* pPrivData, const ADT7461RegisterInfo* pReg, NvU8 Data) { NvU32 i; NvU8 WriteBuffer[2]; NvOdmI2cStatus status; NvOdmI2cTransactionInfo TransactionInfo; NV_ASSERT(pPrivData && pReg); NV_ASSERT(pReg->WrAddr != ADT7461_INVALID_ADDR); for (i = 0; i < ADT7461_I2C_RETRY_CNT; i++) { WriteBuffer[0] = pReg->WrAddr; WriteBuffer[1] = Data; TransactionInfo.Address = pPrivData->DeviceI2cAddr; TransactionInfo.Buf = &WriteBuffer[0]; TransactionInfo.Flags = NVODM_I2C_IS_WRITE; TransactionInfo.NumBytes = 2; status = NvOdmI2cTransaction(pPrivData->hOdmI2C, &TransactionInfo, 1, ADT7461_I2C_SPEED_KHZ, ADT7461_I2C_TIMEOUT_MS); if (status == NvOdmI2cStatus_Success) break; } switch (status) { case NvOdmI2cStatus_Success: pPrivData->ShadowRegPtr = pReg->WrAddr; return NV_TRUE; case NvOdmI2cStatus_Timeout: NVODM_ADT7461_PRINTF(("ADT7461: WriteReg Timeout\n")); return NV_FALSE; case NvOdmI2cStatus_SlaveNotFound: default: NVODM_ADT7461_PRINTF(("ADT7461: WriteReg SlaveNotFound\n")); return NV_FALSE; } } static NvBool Adt7461ReadReg( ADT7461PrivData* pPrivData, const ADT7461RegisterInfo* pReg, NvU8* pData) { NvU32 i; NvU8 Buffer = 0; NvOdmI2cStatus status; NvOdmI2cTransactionInfo TransactionInfo[2]; NV_ASSERT(pPrivData && pReg && pData); NV_ASSERT(pReg->RdAddr != ADT7461_INVALID_ADDR); // TODO: possible optimization - is shadow pointer matches register // address, just send one read transaction (can be done only if Read/Wr // Reg routines are serialized). for (i = 0; i < ADT7461_I2C_RETRY_CNT; i++) { Buffer = pReg->RdAddr; TransactionInfo[0].Address = pPrivData->DeviceI2cAddr; TransactionInfo[0].Buf = &Buffer; TransactionInfo[0].Flags = NVODM_I2C_IS_WRITE; TransactionInfo[0].NumBytes = 1; TransactionInfo[1].Address = (pPrivData->DeviceI2cAddr | 0x1); TransactionInfo[1].Buf = &Buffer; TransactionInfo[1].Flags = 0; TransactionInfo[1].NumBytes = 1; status = NvOdmI2cTransaction(pPrivData->hOdmI2C, &TransactionInfo[0], 2, ADT7461_I2C_SPEED_KHZ, ADT7461_I2C_TIMEOUT_MS); if (status == NvOdmI2cStatus_Success) break; } switch (status) { case NvOdmI2cStatus_Success: pPrivData->ShadowRegPtr = pReg->RdAddr; *pData = Buffer; return NV_TRUE; case NvOdmI2cStatus_Timeout: NVODM_ADT7461_PRINTF(("ADT7461: ReadReg Timeout\n")); return NV_FALSE; case NvOdmI2cStatus_SlaveNotFound: default: NVODM_ADT7461_PRINTF(("ADT7461: ReadReg SlaveNotFound\n")); return NV_FALSE; } } static void Adt7461ReadAra(ADT7461PrivData* pPrivData) { NvU32 i; NvU8 Buffer = 0; NvOdmI2cStatus status; NvOdmI2cTransactionInfo TransactionInfo; NV_ASSERT(pPrivData); for (i = 0; i < ADT7461_ARA_RETRY_CNT; i++) { TransactionInfo.Address = (ADT7461_ARA | 0x1); TransactionInfo.Buf = &Buffer; TransactionInfo.Flags = 0; TransactionInfo.NumBytes = 1; status = NvOdmI2cTransaction(pPrivData->hOdmI2C, &TransactionInfo, 1, ADT7461_I2C_SPEED_KHZ, ADT7461_I2C_TIMEOUT_MS); if ((status == NvOdmI2cStatus_SlaveNotFound) || // False alarm ((status == NvOdmI2cStatus_Success) && ((Buffer & 0xFE) == (NvU8)pPrivData->DeviceI2cAddr)) // Cleared ARA ) break; } } static NvBool Adt7461ConfigureSampleInterval( ADT7461PrivData* pPrivData, NvBool OdmProtected, NvS32* pTargetMs) { NvU8 i; NvS32 Delta; const ADT7461RegisterInfo* pReg = &pPrivData->pDeviceInfo->Rate; if (OdmProtected || ((*pTargetMs) == ODM_TMON_PARAMETER_UNSPECIFIED)) { // Read ADT7461 rate register (fail the call if returned data // does not make sense) if(!Adt7461ReadReg(pPrivData, pReg, &i)) return NV_FALSE; if (i >= NV_ARRAY_SIZE(s_Adt7461SampleIntervalsMS)) return NV_FALSE; } else { // Find and set the best floor approximation of the target sample // interval. Note the descending order of sample intervals array. for (i = 0; i < NV_ARRAY_SIZE(s_Adt7461SampleIntervalsMS); i++) { Delta = (*pTargetMs) - s_Adt7461SampleIntervalsMS[i]; if(Delta >= 0) break; } if (i == NV_ARRAY_SIZE(s_Adt7461SampleIntervalsMS)) i--; // min interval is the best we can do if(!Adt7461WriteReg(pPrivData, pReg, i)) return NV_FALSE; pPrivData->ShadowRate = i; } *pTargetMs = s_Adt7461SampleIntervalsMS[i]; return NV_TRUE; } /*****************************************************************************/ static void Adt7461Isr(void* arg) { NvU8 Data; ADT7461PrivData* pPrivData = (ADT7461PrivData*)arg; NvOdmInterruptHandler volatile Callback = pPrivData->Callback; void* volatile CallbackArg = pPrivData->CallbackArg; const ADT7461RegisterInfo* pReg = NULL; if (Callback && CallbackArg) { Callback(CallbackArg); } #if ADT7461_ALERT_DEBOUNCE // New range limits set by callback are not guaranteed to take effect // before the next temperature conversion is completed, and interrupt // can not be cleared until then. Hence, the debounce delay below. NvOdmOsSleepMS(s_Adt7461SampleIntervalsMS[pPrivData->ShadowRate] + s_Adt7461ConversionTimesMS[pPrivData->ShadowRate] + 1); #endif // Read status and ARA to finish clearing interrupt after callback pReg = &pPrivData->pDeviceInfo->Status; (void)Adt7461ReadReg(pPrivData, pReg, &Data); Adt7461ReadAra(pPrivData); // Re-enable interrupt if (pPrivData->hGpioIntr) NvOdmGpioInterruptDone(pPrivData->hGpioIntr); } static void Adt7461FreePrivData(ADT7461PrivData* pPrivData) { if (pPrivData) { if (pPrivData->hGpioIntr) { NvOdmGpioInterruptUnregister( pPrivData->hGpio, pPrivData->hGpioPin, pPrivData->hGpioIntr); } NvOdmI2cClose(pPrivData->hOdmI2C); NvOdmGpioReleasePinHandle(pPrivData->hGpio, pPrivData->hGpioPin); NvOdmGpioClose(pPrivData->hGpio); NvOdmServicesPmuClose(pPrivData->hOdmPmuSevice); NvOdmOsFree(pPrivData); } } /*****************************************************************************/ NvBool Adt7461Init(NvOdmTmonDeviceHandle hTmon) { NvU8 Data; NvBool ExtRange; NvU32 i = 0; NvU32 I2cInstance = 0; NvOdmIoModule I2cModule = NvOdmIoModule_Num; // Inavlid module const ADT7461RegisterInfo* pReg = NULL; ADT7461PrivData* pPrivData = NULL; NV_ASSERT(hTmon && hTmon->pConn && hTmon->pConn->AddressList); // Allocate and clear priavte data pPrivData = (ADT7461PrivData*) NvOdmOsAlloc(sizeof(ADT7461PrivData)); if (pPrivData == NULL) { NVODM_ADT7461_PRINTF(("ADT7461: Error Allocating PrivData. \n")); return NV_FALSE; } NvOdmOsMemset(pPrivData, 0, sizeof(ADT7461PrivData)); hTmon->pPrivate = pPrivData; // Register for PMU services pPrivData->hOdmPmuSevice = NvOdmServicesPmuOpen(); if (pPrivData->hOdmPmuSevice == NULL) { NVODM_ADT7461_PRINTF(("ADT7461: Error Open PMU service. \n")); goto fail; } // Register for GPIO services pPrivData->hGpio = NvOdmGpioOpen(); if (pPrivData->hOdmPmuSevice == NULL) { NVODM_ADT7461_PRINTF(("ADT7461: Error Open GPIO service. \n")); goto fail; } /* * Parse connectivity data: turn On power to the device, acquire I2C * interface and GPIO interrupt (optional); map device channels to * thermal zones */ for (i = 0; i < hTmon->pConn->NumAddress; i ++) { const NvOdmIoAddress* pIoAddress = &hTmon->pConn->AddressList[i]; if (pIoAddress->Interface == NvOdmIoModule_I2c_Pmu) { I2cModule = NvOdmIoModule_I2c_Pmu; I2cInstance = pIoAddress->Instance; NV_ASSERT(pIoAddress->Address != 0); pPrivData->DeviceI2cAddr = pIoAddress->Address; } else if (pIoAddress->Interface == NvOdmIoModule_Tsense) { NV_ASSERT(pIoAddress->Instance < NvOdmTmonZoneID_Num); NV_ASSERT(pIoAddress->Address < ADT7461ChannelID_Num); pPrivData->ConnectivityMap[pIoAddress->Instance] = pIoAddress->Address; } else if (pIoAddress->Interface == NvOdmIoModule_Vdd) { NvU32 usec = 0; NvU32 RailAddress = pIoAddress->Address; NvOdmServicesPmuVddRailCapabilities RailCapabilities; NvOdmServicesPmuGetCapabilities( pPrivData->hOdmPmuSevice, RailAddress, &RailCapabilities); NvOdmServicesPmuSetVoltage(pPrivData->hOdmPmuSevice, RailAddress, RailCapabilities.requestMilliVolts, &usec); NvOdmOsWaitUS(usec + (ADT7461_POWERUP_DELAY_MS * 1000)); } else if (pIoAddress->Interface == NvOdmIoModule_Gpio) { NvU32 port = pIoAddress->Instance; NvU32 pin = pIoAddress->Address; pPrivData->hGpioPin = NvOdmGpioAcquirePinHandle( pPrivData->hGpio, port, pin); } } NV_ASSERT(I2cModule == NvOdmIoModule_I2c_Pmu); pPrivData->hOdmI2C = NvOdmI2cOpen(I2cModule, I2cInstance); if (pPrivData->hOdmI2C == NULL) { NVODM_ADT7461_PRINTF(("ADT7461: Error Open I2C device. \n")); goto fail; } /* * Initialize device info and configuration. Force standby mode to avoid * glitch on shutdown comparator output when temperature range and/or * comparator limit is changing during initialization. The Adt7461Run() * call from the hal that follows initialization will switch device to * run mode and re-start temperature monitoring (note that out of limit * interrupt is always masked during and after initialization) */ pPrivData->pDeviceInfo = &s_Adt7461Info; pPrivData->ShadowRegPtr = ADT7461_INVALID_ADDR; pReg = &pPrivData->pDeviceInfo->Config; if (!Adt7461ReadReg(pPrivData, pReg, &Data)) goto fail; if ((Data & ADT7461ConfigBits_ExtendedRange) != (ADT7461_INITIAL_CONFIG & ADT7461ConfigBits_ExtendedRange)) { // Only switch from standard to extended range is supported NV_ASSERT((Data & ADT7461ConfigBits_ExtendedRange) == 0); Data |= ADT7461ConfigBits_Standby; if(!Adt7461WriteReg(pPrivData, pReg, Data)) goto fail; } Data = ADT7461_INITIAL_CONFIG | ADT7461ConfigBits_Standby; if(!Adt7461WriteReg(pPrivData, pReg, Data)) goto fail; pPrivData->ShadowConfig = Data; ExtRange = ((Data & ADT7461ConfigBits_ExtendedRange) != 0); // Program shutdown comparators settings Data = ADT7461_T_VALUE_TO_DATA( ExtRange, ADT7461_ODM_LOCAL_COMPARATOR_LIMIT_VALUE); pReg = &pPrivData->pDeviceInfo->Channels[ ADT7461ChannelID_Local].ComparatorLimit; if(!Adt7461WriteReg(pPrivData, pReg, Data)) goto fail; Data = ADT7461_T_VALUE_TO_DATA( ExtRange, ADT7461_ODM_REMOTE_COMPARATOR_LIMIT_VALUE); pReg = &pPrivData->pDeviceInfo->Channels[ ADT7461ChannelID_Remote].ComparatorLimit; if(!Adt7461WriteReg(pPrivData, pReg, Data)) goto fail; // Set interrupt limits to the range boundaries to prevent out of limit // interrupt Data = ADT7461_T_VALUE_TO_DATA( ExtRange, ADT7461_T_RANGE_LIMIT_HIGH(ExtRange)); pReg = &pPrivData->pDeviceInfo->Channels[ ADT7461ChannelID_Local].IntrLimitHigh; if(!Adt7461WriteReg(pPrivData, pReg, Data)) goto fail; pReg = &pPrivData->pDeviceInfo->Channels[ ADT7461ChannelID_Remote].IntrLimitHigh; if(!Adt7461WriteReg(pPrivData, pReg, Data)) goto fail; Data = ADT7461_T_VALUE_TO_DATA( ExtRange, ADT7461_T_RANGE_LIMIT_LOW(ExtRange)); pReg = &pPrivData->pDeviceInfo->Channels[ ADT7461ChannelID_Local].IntrLimitLow; if(!Adt7461WriteReg(pPrivData, pReg, Data)) goto fail; pReg = &pPrivData->pDeviceInfo->Channels[ ADT7461ChannelID_Remote].IntrLimitLow; if(!Adt7461WriteReg(pPrivData, pReg, Data)) goto fail; // Set initial rate Data = ADT7461_INITIAL_RATE_SETTING; pReg = &pPrivData->pDeviceInfo->Rate; if(!Adt7461WriteReg(pPrivData, pReg, Data)) goto fail; pPrivData->ShadowRate = Data; // Set remote channel offset (8-bit 2's complement value for any range) Data = ((NvU8)ADT7461_ODM_REMOTE_OFFSET_VALUE); pReg = &pPrivData->pDeviceInfo->Channels[ ADT7461ChannelID_Remote].Toffset; if(!Adt7461WriteReg(pPrivData, pReg, Data)) goto fail; // Read ADT7461 status and ARA (clear pending Alert interrupt, if any) pReg = &pPrivData->pDeviceInfo->Status; if (!Adt7461ReadReg(pPrivData, pReg, &Data)) goto fail; // TODO: check open remote circuit error Adt7461ReadAra(pPrivData); return NV_TRUE; fail: Adt7461FreePrivData(pPrivData); hTmon->pPrivate = NULL; return NV_FALSE; } void Adt7461Deinit(NvOdmTmonDeviceHandle hTmon) { if (hTmon && hTmon->pPrivate) { ADT7461PrivData* pPrivData = hTmon->pPrivate; (void)Adt7461WriteReg(pPrivData, &pPrivData->pDeviceInfo->Config, ADT7461_INITIAL_CONFIG); //leave device in initial configuration // with power rail ON (forever) Adt7461FreePrivData(pPrivData); hTmon->pPrivate = NULL; } } /*****************************************************************************/ NvBool Adt7461Run(NvOdmTmonDeviceHandle hTmon, NvOdmTmonZoneID ZoneId) { NvU8 Data; NvBool IsRunning; ADT7461PrivData* pPrivData; NV_ASSERT(hTmon && hTmon->pPrivate); pPrivData = hTmon->pPrivate; IsRunning = (pPrivData->ShadowConfig & ADT7461ConfigBits_Standby) == 0; if (!IsRunning) { Data = pPrivData->ShadowConfig & (~ADT7461ConfigBits_Standby); if(!Adt7461WriteReg(pPrivData, &pPrivData->pDeviceInfo->Config, Data)) return NV_FALSE; pPrivData->ShadowConfig = Data; } pPrivData->RunRefCount++; return NV_TRUE; } NvBool Adt7461Stop(NvOdmTmonDeviceHandle hTmon, NvOdmTmonZoneID ZoneId) { NvU8 Data; NvBool IsRunning; ADT7461PrivData* pPrivData; NV_ASSERT(hTmon && hTmon->pPrivate); pPrivData = hTmon->pPrivate; IsRunning = (pPrivData->ShadowConfig & ADT7461ConfigBits_Standby) == 0; if (ADT7461_ODM_STANDBY_ENABLED && IsRunning && (pPrivData->RunRefCount == 1)) { Data = pPrivData->ShadowConfig | ADT7461ConfigBits_Standby; if(!Adt7461WriteReg(pPrivData, &pPrivData->pDeviceInfo->Config, Data)) return NV_FALSE; pPrivData->ShadowConfig = Data; } if (pPrivData->RunRefCount != 0) { pPrivData->RunRefCount--; return NV_TRUE; } NV_ASSERT(!"RunRefCount balance failed"); NVODM_ADT7461_PRINTF(("ADT7461: RunRefCount balance failed. \n")); return NV_FALSE; } /*****************************************************************************/ // ADT7461 aborts and restarts conversion cycle when temperature is read // (actually on any I2C access for that matter, but other accesses are rare). // TODO: add time stamps and implement refresh policy to make sure that // frequent temperature reads would not stall the conversion forever. NvBool Adt7461TemperatureGet( NvOdmTmonDeviceHandle hTmon, NvOdmTmonZoneID ZoneId, NvS32* pDegreesC) { NvU8 Data; NvBool ExtRange; ADT7461ChannelID ChannelId; ADT7461PrivData* pPrivData; const ADT7461RegisterInfo* pReg; NV_ASSERT(hTmon && hTmon->pPrivate && pDegreesC); pPrivData = hTmon->pPrivate; ExtRange = ((pPrivData->ShadowConfig & ADT7461ConfigBits_ExtendedRange) != 0); ChannelId = pPrivData->ConnectivityMap[ZoneId]; pReg = &pPrivData->pDeviceInfo->Channels[ChannelId].Tdata; if(!Adt7461ReadReg(pPrivData, pReg, &Data)) return NV_FALSE; *pDegreesC = ADT7461_T_DATA_TO_VALUE(ExtRange, Data); return NV_TRUE; } /*****************************************************************************/ void Adt7461CapabilitiesGet( NvOdmTmonDeviceHandle hTmon, NvOdmTmonZoneID ZoneId, NvOdmTmonCapabilities* pCaps) { NvBool ExtRange; ADT7461PrivData* pPrivData; NV_ASSERT(hTmon && hTmon->pPrivate && pCaps); pPrivData = hTmon->pPrivate; ExtRange = ((pPrivData->ShadowConfig & ADT7461ConfigBits_ExtendedRange) != 0); pCaps->Tmax = ADT7461_T_RANGE_LIMIT_HIGH(ExtRange); pCaps->Tmin = ADT7461_T_RANGE_LIMIT_LOW(ExtRange); pCaps->IntrSupported = NV_TRUE; pCaps->HwCriticalSupported = NV_TRUE; pCaps->HwCoolingSupported = NV_FALSE; } void Adt7461ParameterCapsGet( NvOdmTmonDeviceHandle hTmon, NvOdmTmonZoneID ZoneId, NvOdmTmonConfigParam ParamId, NvOdmTmonParameterCaps* pCaps) { NvBool ExtRange; ADT7461PrivData* pPrivData; const ADT7461ChannelInfo* pChannel; NV_ASSERT(hTmon && hTmon->pPrivate && pCaps); pPrivData = hTmon->pPrivate; ExtRange = ((pPrivData->ShadowConfig & ADT7461ConfigBits_ExtendedRange) != 0); pChannel = &pPrivData->pDeviceInfo->Channels[( pPrivData->ConnectivityMap[ZoneId])]; switch (ParamId) { case NvOdmTmonConfigParam_IntrLimitHigh: case NvOdmTmonConfigParam_IntrLimitLow: pCaps->OdmProtected = pChannel->ChannelPolicy.IntrLimitsOdmProtected; break; case NvOdmTmonConfigParam_HwLimitCrit: pCaps->OdmProtected = pChannel->ChannelPolicy.HwLimitCritOdmProtected; break; case NvOdmTmonConfigParam_SampleMs: // smaple intervals in descending order pCaps->MaxValue = s_Adt7461SampleIntervalsMS[0]; pCaps->MinValue = s_Adt7461SampleIntervalsMS[( NV_ARRAY_SIZE(s_Adt7461SampleIntervalsMS) - 1)]; pCaps->OdmProtected = pChannel->ChannelPolicy.RateOdmProtected; return; default: // unsupported parameter pCaps->MaxValue = ODM_TMON_PARAMETER_UNSPECIFIED; pCaps->MinValue = ODM_TMON_PARAMETER_UNSPECIFIED; pCaps->OdmProtected = NV_TRUE; return; } // Common range for limits pCaps->MaxValue = ADT7461_T_RANGE_LIMIT_HIGH(ExtRange); pCaps->MinValue = ADT7461_T_RANGE_LIMIT_LOW(ExtRange); } NvBool Adt7461ParameterConfig( NvOdmTmonDeviceHandle hTmon, NvOdmTmonZoneID ZoneId, NvOdmTmonConfigParam ParamId, NvS32* pSetting) { NvU8 Data; NvBool ExtRange, OdmProtected; ADT7461PrivData* pPrivData; const ADT7461RegisterInfo* pReg; const ADT7461ChannelInfo* pChannel; NV_ASSERT(hTmon && hTmon->pPrivate && pSetting); pPrivData = hTmon->pPrivate; ExtRange = ((pPrivData->ShadowConfig & ADT7461ConfigBits_ExtendedRange) != 0); pChannel = &pPrivData->pDeviceInfo->Channels[( pPrivData->ConnectivityMap[ZoneId])]; switch (ParamId) { case NvOdmTmonConfigParam_IntrLimitHigh: pReg = &pChannel->IntrLimitHigh; OdmProtected = pChannel->ChannelPolicy.IntrLimitsOdmProtected; break; case NvOdmTmonConfigParam_IntrLimitLow: pReg = &pChannel->IntrLimitLow; OdmProtected = pChannel->ChannelPolicy.IntrLimitsOdmProtected; break; case NvOdmTmonConfigParam_HwLimitCrit: pReg = &pChannel->ComparatorLimit; OdmProtected = pChannel->ChannelPolicy.HwLimitCritOdmProtected; break; case NvOdmTmonConfigParam_SampleMs: OdmProtected = pChannel->ChannelPolicy.RateOdmProtected; return Adt7461ConfigureSampleInterval( pPrivData, OdmProtected, pSetting); default: // unsupported parameter *pSetting = ODM_TMON_PARAMETER_UNSPECIFIED; return NV_TRUE; } // Common processing for temperature limits configuration if ((OdmProtected) || ((*pSetting) == ODM_TMON_PARAMETER_UNSPECIFIED)) { // Read ADT7461 register and convert data to current parameter value if(!Adt7461ReadReg(pPrivData, pReg, &Data)) return NV_FALSE; *pSetting = ADT7461_T_DATA_TO_VALUE(ExtRange, Data); } else { // Clip target setting to temperature range if ((*pSetting) > ADT7461_T_RANGE_LIMIT_HIGH(ExtRange)) *pSetting = ADT7461_T_RANGE_LIMIT_HIGH(ExtRange); else if ((*pSetting) < ADT7461_T_RANGE_LIMIT_LOW(ExtRange)) *pSetting = ADT7461_T_RANGE_LIMIT_LOW(ExtRange); // Convert new configuration setting and write to ADT7461 register Data = ADT7461_T_VALUE_TO_DATA(ExtRange, *pSetting); if(!Adt7461WriteReg(pPrivData, pReg, Data)) return NV_FALSE; } return NV_TRUE; } /*****************************************************************************/ NvOdmTmonIntrHandle Adt7461IntrRegister( NvOdmTmonDeviceHandle hTmon, NvOdmTmonZoneID ZoneId, NvOdmInterruptHandler Callback, void* CallbackArg) { NvU8 Data; ADT7461PrivData* pPrivData; const ADT7461ChannelInfo* pChannel; NvOdmServicesGpioIntrHandle hGpioIntr = NULL; NV_ASSERT(hTmon && hTmon->pPrivate && Callback && CallbackArg); pPrivData = hTmon->pPrivate; // No registration, if no GPIO pin available or interrupt already registred if (!pPrivData->hGpioPin || pPrivData->hGpioIntr) return NULL; // No registration for other than remote channel pChannel = &pPrivData->pDeviceInfo->Channels[( pPrivData->ConnectivityMap[ZoneId])]; if (pChannel->ChannelId != ADT7461ChannelID_Remote) return NULL; // Register GPIO interrupt (will be enabled at SoC IC, but still disabled // at ADT7461 device) pPrivData->Callback = Callback; pPrivData->CallbackArg = CallbackArg; if (!NvOdmGpioInterruptRegister( pPrivData->hGpio, &hGpioIntr, pPrivData->hGpioPin, ADT7461_ODM_INTR_POLARITY, Adt7461Isr, (void *)pPrivData, 0)) { pPrivData->Callback = NULL; pPrivData->CallbackArg = NULL; return NULL; } NV_ASSERT(hGpioIntr); pPrivData->hGpioIntr = hGpioIntr; // Finally enable ADT7461 device interrupt output (interrupt may or may // not be generated depending on temperature and limt settings). Data = pPrivData->ShadowConfig & (~ADT7461ConfigBits_IntrDisabled); if(!Adt7461WriteReg(pPrivData, &pPrivData->pDeviceInfo->Config, Data)) { NvOdmGpioInterruptUnregister( pPrivData->hGpio, pPrivData->hGpioPin, hGpioIntr); pPrivData->Callback = NULL; pPrivData->CallbackArg = NULL; pPrivData->hGpioIntr = NULL; return NULL; } pPrivData->ShadowConfig = Data; return (NvOdmTmonIntrHandle)hGpioIntr; } void Adt7461IntrUnregister( NvOdmTmonDeviceHandle hTmon, NvOdmTmonZoneID ZoneId, NvOdmTmonIntrHandle hIntr) { NvU8 Data; ADT7461PrivData* pPrivData; const ADT7461ChannelInfo* pChannel; // Ignore invalid handles if(!hIntr || !hTmon || !hTmon->pPrivate) return; pPrivData = hTmon->pPrivate; if (hIntr != ((NvOdmTmonIntrHandle)pPrivData->hGpioIntr)) return; // Ignore any channel other than remote pChannel = &pPrivData->pDeviceInfo->Channels[( pPrivData->ConnectivityMap[ZoneId])]; if (pChannel->ChannelId != ADT7461ChannelID_Remote) return; // Disable ADT7461 interrupt output Data = pPrivData->ShadowConfig | ADT7461ConfigBits_IntrDisabled; if(Adt7461WriteReg(pPrivData, &pPrivData->pDeviceInfo->Config, Data)) pPrivData->ShadowConfig = Data; // Unregister GPIO interrupt, clear callbacks and handle NvOdmGpioInterruptUnregister( pPrivData->hGpio, pPrivData->hGpioPin, pPrivData->hGpioIntr); pPrivData->Callback = NULL; pPrivData->CallbackArg = NULL; pPrivData->hGpioIntr = NULL; } /*****************************************************************************/
DmitryADP/diff_qc750
vendor/nvidia/tegra/odm/template/odm_kit/adaptations/tmon/adt7461/nvodm_tmon_adt7461.c
C
gpl-2.0
29,418
/* This file is part of the KDE libraries Copyright (C) 2002 Hans Petter bieker <bieker@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __KDATETIMEWIDGET__ #define __KDATETIMEWIDGET__ #include <tqwidget.h> #include <tqdatetime.h> #include <tdelibs_export.h> /** * @short A combination of a date and a time selection widget. * * This widget can be used to display or allow user selection of date and time. * * @see KDateWidget * * \image html kdatetimewidget.png "KDE Date Time Widget" * * @author Hans Petter Bieker <bieker@kde.org> * @version $Id$ * @since 3.2 */ class TDEUI_EXPORT KDateTimeWidget : public TQWidget { Q_OBJECT TQ_PROPERTY( TQDateTime dateTime READ dateTime WRITE setDateTime ) public: /** * Constructs a date and time selection widget. */ KDateTimeWidget(TQWidget * parent = 0, const char * name = 0); /** * Constructs a date and time selection widget with the initial date and * time set to @p datetime. */ KDateTimeWidget(const TQDateTime & datetime, TQWidget * parent = 0, const char * name = 0 ); /** * Destructs the date and time selection widget. */ virtual ~KDateTimeWidget(); /** * Returns the currently selected date and time. */ TQDateTime dateTime() const; public slots: /** * Changes the selected date and time to @p datetime. */ void setDateTime(const TQDateTime & datetime); signals: /** * Emitted whenever the date or time of the widget * is changed, either with setDateTime() or via user selection. */ void valueChanged(const TQDateTime & datetime); private: void init(); private slots: void slotValueChanged(); private: class KDateTimeWidgetPrivate; KDateTimeWidgetPrivate *d; }; #endif
Fat-Zer/tdelibs
tdeui/kdatetimewidget.h
C
gpl-2.0
2,424
/*linux/drivers/media/ts9701/cammera_ts9701.c * *Omnivision TS9701 CMOS Image Sensor driver *TianXu Wang,Copyright (c) 2010 * *This program is free software;you can redistribute it and/or modify *it under the terms of the GNU General Public Licnse version 2 as *published by the Free Software Foundation. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/i2c.h> #include <linux/i2c-id.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/io.h> #include <linux/clk.h> #include <linux/i2c.h> #include <plat/clock.h> #include <linux/i2c-dev.h> #include <plat/gpio-cfg.h> #include <plat/regs-fimc.h> #include <mach/gpio-smdkc110.h> /* gpio configurage */ //static void soc_gpio_cfg() //{ // printk("<soc5140> config gpio pin!\n"); // // s3c_gpio_cfgpin(S5PV210_GPE0(0), S5PV210_GPE0_0_CAM_A_PCLK); // s3c_gpio_cfgpin(S5PV210_GPE0(1), S5PV210_GPE0_1_CAM_A_VSYNC); // s3c_gpio_cfgpin(S5PV210_GPE0(2), S5PV210_GPE0_2_CAM_A_HREF); // s3c_gpio_cfgpin(S5PV210_GPE0(3), S5PV210_GPE0_3_CAM_A_DATA_0); // s3c_gpio_cfgpin(S5PV210_GPE0(4), S5PV210_GPE0_4_CAM_A_DATA_1); // s3c_gpio_cfgpin(S5PV210_GPE0(5), S5PV210_GPE0_5_CAM_A_DATA_2); // s3c_gpio_cfgpin(S5PV210_GPE0(6), S5PV210_GPE0_6_CAM_A_DATA_3); // s3c_gpio_cfgpin(S5PV210_GPE0(7), S5PV210_GPE0_7_CAM_A_DATA_4); // s3c_gpio_cfgpin(S5PV210_GPE1(0), S5PV210_GPE1_0_CAM_A_DATA_5); // s3c_gpio_cfgpin(S5PV210_GPE1(1), S5PV210_GPE1_1_CAM_A_DATA_6); // s3c_gpio_cfgpin(S5PV210_GPE1(2), S5PV210_GPE1_2_CAM_A_DATA_7); // s3c_gpio_cfgpin(S5PV210_GPE1(3), S5PV210_GPE1_3_CAM_A_CLKOUT); // s3c_gpio_cfgpin(S5PV210_GPE1(4), S5PV210_GPE1_4_CAM_A_FIELD); //} //reset #define CAM_SET_RESET_LOW s3c_gpio_setpull(cam_reset_pin, S3C_GPIO_PULL_DOWN)//low #define CAM_SET_RESET_HIGH s3c_gpio_setpull(cam_reset_pin, S3C_GPIO_PULL_UP)//high //power #define CAM_POWER_ON s3c_gpio_setpull(cam_power_pin,S3C_GPIO_PULL_UP)//high #define CAM_POWER_DOWN s3c_gpio_setpull(cam_power_pin, S3C_GPIO_PULL_DOWN)//low #ifndef __SOC5140_H__ #define __SOC5140_H__ #define SOC5140_REG_TERM 0xFFFF #define SOC5140_VAL_TERM 0xFF typedef struct samsung{ unsigned short addr; unsigned short val; unsigned short pam; }soc5140_short_reg; //================================================= //; //; Register Log created on Friday, January 14, 2011 : 14:01:03 //; //; //; Register Log created on Thursday, January 20, 2011 : 08:55:43 //; //[//[Register Log 01/20/11 08:55:40]] // Reset the sensor..hardware specific for demo2 board...toggles the reset pin //STATE=Sensor Reset, 1 //STATE=Sensor Reset, 0 //for devware //STATE = Num Capture Frames, 2 //DELAY = 100--------------------------------- /* soc5140_short_reg init_1[]={ {0x0010, 0x0323 ,4}, // PLL_DIVIDERS {0x0012, 0x0050 ,4}, // PLL_P_DIVIDERS {0x0014, 0x2025 ,4}, // PLL_CONTROL {0x001E, 0x0777 ,4}, // PAD_SLEW_PAD_CONFIG {0x0022, 0x01E0 ,4}, // VDD_DIS_COUNTER {0x002A, 0x7C46 ,4}, // PLL_P4_P5_P6_DIVIDERS {0x002C, 0x0000 ,4}, // PLL_P7_DIVIDER {0x002E, 0x0000 ,4}, // SENSOR_CLOCK_DIVIDER {0x0018, 0x4008 ,4}, // STANDBY_CONTROL_AND_STATUS }; //DELAY = 100------------------------------------------------------- // POLL STANDBY_CONTROL_AND_STATUS:://[0xC07F] => 0x0008 soc5140_short_reg init_2[]={ {0x30D4, 0x9080,4}, // COLUMN_CORRECTION {0x098E, 0x1000 ,4}, // LOGICAL_ADDRESS_ACCESS {0xC86C, 0x0518 ,4}, // CAM_CORE_A_OUTPUT_SIZE_WIDTH {0xC86E, 0x03D4 ,4}, // CAM_CORE_A_OUTPUT_SIZE_HEIGHT {0xC83A, 0x000C ,4}, // CAM_CORE_A_Y_ADDR_START {0xC83C, 0x0018 ,4}, // CAM_CORE_A_X_ADDR_START {0xC83E, 0x07B1 ,4}, // CAM_CORE_A_Y_ADDR_END {0xC840, 0x0A45 ,4}, // CAM_CORE_A_X_ADDR_END {0xC842, 0x0001 ,4}, // CAM_CORE_A_ROW_SPEED {0xC844, 0x0103 ,4}, // CAM_CORE_A_SKIP_X_CORE {0xC846, 0x0103 ,4}, // CAM_CORE_A_SKIP_Y_CORE {0xC848, 0x0103 ,4}, // CAM_CORE_A_SKIP_X_PIPE {0xC84A, 0x0103 ,4}, // CAM_CORE_A_SKIP_Y_PIPE {0xC84C, 0x00F6 ,4}, // CAM_CORE_A_POWER_MODE {0xC84E, 0x0001 ,4}, // CAM_CORE_A_BIN_MODE {0xC850, 0x00 ,3}, // CAM_CORE_A_ORIENTATION {0xC851, 0x00 ,3}, // CAM_CORE_A_PIXEL_ORDER {0xC852, 0x019C ,4}, // CAM_CORE_A_FINE_CORRECTION {0xC854, 0x0732 ,4}, // CAM_CORE_A_FINE_ITMIN {0xC856, 0x048E ,4}, // CAM_CORE_A_UNUSED1 {0xC858, 0x0002 ,4}, // CAM_CORE_A_COARSE_ITMIN {0xC85A, 0x0001 ,4}, // CAM_CORE_A_COARSE_ITMAX_MARGIN {0xC85C, 0x0423 ,4}, // CAM_CORE_A_MIN_FRAME_LENGTH_LINES {0xC85E, 0xFFFF ,4}, // CAM_CORE_A_MAX_FRAME_LENGTH_LINES {0xC860, 0x0423 ,4}, // CAM_CORE_A_BASE_FRAME_LENGTH_LINES {0xC862, 0x0EC1 ,4}, // CAM_CORE_A_MIN_LINE_LENGTH_PCLK {0xC864, 0xFFFE ,4}, // CAM_CORE_A_MAX_LINE_LENGTH_PCLK {0xC866, 0x7C46 ,4}, // CAM_CORE_A_P4_5_6_DIVIDER {0xC868, 0x0423 ,4}, // CAM_CORE_A_FRAME_LENGTH_LINES {0xC86A, 0x0EC1 ,4}, // CAM_CORE_A_LINE_LENGTH_PCK {0xC870, 0x0014 ,4}, // CAM_CORE_A_RX_FIFO_TRIGGER_MARK {0xC8AA, 0x0280 ,4}, // CAM_OUTPUT_0_IMAGE_WIDTH {0xC8AC, 0x01E0 ,4}, // CAM_OUTPUT_0_IMAGE_HEIGHT {0xC8AE, 0x0001 ,4}, // CAM_OUTPUT_0_OUTPUT_FORMAT {0xC8B0, 0x0000 ,4}, // CAM_OUTPUT_0_OUTPUT_FORMAT_ORDER {0xC8B8, 0x0004 ,4}, // CAM_OUTPUT_0_JPEG_CONTROL {0xC8A4, 0x0A28 ,4}, // CAM_CORE_B_OUTPUT_SIZE_WIDTH {0xC8A6, 0x07A0 ,4}, // CAM_CORE_B_OUTPUT_SIZE_HEIGHT {0xC872, 0x0010 ,4}, // CAM_CORE_B_Y_ADDR_START {0xC874, 0x001C ,4}, // CAM_CORE_B_X_ADDR_START {0xC876, 0x07AF ,4}, // CAM_CORE_B_Y_ADDR_END {0xC878, 0x0A43 ,4}, // CAM_CORE_B_X_ADDR_END {0xC87A, 0x0001 ,4}, // CAM_CORE_B_ROW_SPEED {0xC87C, 0x0101 ,4}, // CAM_CORE_B_SKIP_X_CORE {0xC87E, 0x0101 ,4}, // CAM_CORE_B_SKIP_Y_CORE {0xC880, 0x0101 ,4}, // CAM_CORE_B_SKIP_X_PIPE {0xC882, 0x0101 ,4}, // CAM_CORE_B_SKIP_Y_PIPE {0xC884, 0x00F2 ,4}, // CAM_CORE_B_POWER_MODE {0xC886, 0x0000 ,4}, // CAM_CORE_B_BIN_MODE {0xC888, 0x00 ,3}, // CAM_CORE_B_ORIENTATION {0xC889, 0x00 ,3}, // CAM_CORE_B_PIXEL_ORDER {0xC88A, 0x009C ,4}, // CAM_CORE_B_FINE_CORRECTION {0xC88C, 0x034A ,4}, // CAM_CORE_B_FINE_ITMIN {0xC88E, 0x02A6 ,4}, // CAM_CORE_B_UNUSED1 {0xC890, 0x0002 ,4}, // CAM_CORE_B_COARSE_ITMIN {0xC892, 0x0001 ,4}, // CAM_CORE_B_COARSE_ITMAX_MARGIN {0xC894, 0x07EF ,4}, // CAM_CORE_B_MIN_FRAME_LENGTH_LINES {0xC896, 0xFFFF ,4}, // CAM_CORE_B_MAX_FRAME_LENGTH_LINES {0xC898, 0x07EF ,4}, // CAM_CORE_B_BASE_FRAME_LENGTH_LINES {0xC89A, 0x2B0F ,4}, // CAM_CORE_B_MIN_LINE_LENGTH_PCLK {0xC89C, 0xFFFE ,4}, // CAM_CORE_B_MAX_LINE_LENGTH_PCLK {0xC89E, 0x7C46 ,4}, // CAM_CORE_B_P4_5_6_DIVIDER {0xC8A0, 0x07EF ,4}, // CAM_CORE_B_FRAME_LENGTH_LINES {0xC8A2, 0x2B0F ,4}, // CAM_CORE_B_LINE_LENGTH_PCK {0xC8A8, 0x0014 ,4}, // CAM_CORE_B_RX_FIFO_TRIGGER_MARK {0xC8C0, 0x0A00 ,4}, // CAM_OUTPUT_1_IMAGE_WIDTH {0xC8C2, 0x0780 ,4}, // CAM_OUTPUT_1_IMAGE_HEIGHT {0xC8C4, 0x0001 ,4}, // CAM_OUTPUT_1_OUTPUT_FORMAT {0xC8C6, 0x0000 ,4}, // CAM_OUTPUT_1_OUTPUT_FORMAT_ORDER {0xC8CE, 0x0005 ,4}, // CAM_OUTPUT_1_JPEG_CONTROL {0xA010, 0x0134 ,4}, // FD_MIN_EXPECTED50HZ_FLICKER_PERIOD {0xA012, 0x0148 ,4}, // FD_MAX_EXPECTED50HZ_FLICKER_PERIOD {0xA014, 0x00FF ,4}, // FD_MIN_EXPECTED60HZ_FLICKER_PERIOD {0xA016, 0x0113 ,4}, // FD_MAX_EXPECTED60HZ_FLICKER_PERIOD {0xA018, 0x013E ,4}, // FD_EXPECTED50HZ_FLICKER_PERIOD_IN_CONTEXT_A {0xA01A, 0x006D ,4}, // FD_EXPECTED50HZ_FLICKER_PERIOD_IN_CONTEXT_B {0xA01C, 0x0109 ,4}, // FD_EXPECTED60HZ_FLICKER_PERIOD_IN_CONTEXT_A {0xA01E, 0x005B ,4}, // FD_EXPECTED60HZ_FLICKER_PERIOD_IN_CONTEXT_B {0xDC0A, 0x06 ,3}, // SYS_SCALE_MODE {0xDC1C, 0x2710 ,4}, // SYS_ZOOM_RATIO {0xE004, 0x1068 ,4}, // IO_I2C_CLK_DIVIDER {0x8404, 0x06 ,3}, // SEQ_CMD {0x0982, 0x0000 ,4}, // ACCESS_CTL_STAT {0x098A, 0x0000 ,4}, // PHYSICAL_ADDRESS_ACCESS {0x886C, 0xC0F1 ,4}, {0x886E, 0xC5E1 ,4}, {0x8870, 0x246A ,4}, {0x8872, 0x1280 ,4}, {0x8874, 0xC4E1 ,4}, {0x8876, 0xD20F ,4}, {0x8878, 0x2069 ,4}, {0x887A, 0x0000 ,4}, {0x887C, 0x6A62 ,4}, {0x887E, 0x1303 ,4}, {0x8880, 0x0084 ,4}, {0x8882, 0x1734 ,4}, {0x8884, 0x7005 ,4}, {0x8886, 0xD801 ,4}, {0x8888, 0x8A41 ,4}, {0x888A, 0xD900 ,4}, {0x888C, 0x0D5A ,4}, {0x888E, 0x0664 ,4}, {0x8890, 0x8B61 ,4}, {0x8892, 0xE80B ,4}, {0x8894, 0x000D ,4}, {0x8896, 0x0020 ,4}, {0x8898, 0xD508 ,4}, {0x889A, 0x1504 ,4}, {0x889C, 0x1400 ,4}, {0x889E, 0x7840 ,4}, {0x88A0, 0xD007 ,4}, {0x88A2, 0x0DFB ,4}, {0x88A4, 0x9004 ,4}, {0x88A6, 0xC4C1 ,4}, {0x88A8, 0x2029 ,4}, {0x88AA, 0x0300 ,4}, {0x88AC, 0x0219 ,4}, {0x88AE, 0x06C4 ,4}, {0x88B0, 0xFF80 ,4}, {0x88B2, 0x08C4 ,4}, {0x88B4, 0xFF80 ,4}, {0x88B6, 0x086C ,4}, {0x88B8, 0xFF80 ,4}, {0x88BA, 0x08C0 ,4}, {0x88BC, 0xFF80 ,4}, {0x88BE, 0x08C4 ,4}, {0x88C0, 0xFF80 ,4}, {0x88C2, 0x097C ,4}, {0x88C4, 0x0001 ,4}, {0x88C6, 0x0005 ,4}, {0x88C8, 0x0000 ,4}, {0x88CA, 0x0000 ,4}, {0x88CC, 0xC0F1 ,4}, {0x88CE, 0x0976 ,4}, {0x88D0, 0x06C4 ,4}, {0x88D2, 0xD639 ,4}, {0x88D4, 0x7708 ,4}, {0x88D6, 0x8E01 ,4}, {0x88D8, 0x1604 ,4}, {0x88DA, 0x1091 ,4}, {0x88DC, 0x2046 ,4}, {0x88DE, 0x00C1 ,4}, {0x88E0, 0x202F ,4}, {0x88E2, 0x2047 ,4}, {0x88E4, 0xAE21 ,4}, {0x88E6, 0x0F8F ,4}, {0x88E8, 0x1440 ,4}, {0x88EA, 0x8EAA ,4}, {0x88EC, 0x8E0B ,4}, {0x88EE, 0x224A ,4}, {0x88F0, 0x2040 ,4}, {0x88F2, 0x8E2D ,4}, {0x88F4, 0xBD08 ,4}, {0x88F6, 0x7D05 ,4}, {0x88F8, 0x8E0C ,4}, {0x88FA, 0xB808 ,4}, {0x88FC, 0x7825 ,4}, {0x88FE, 0x7510 ,4}, {0x8900, 0x22C2 ,4}, {0x8902, 0x248C ,4}, {0x8904, 0x081D ,4}, {0x8906, 0x0363 ,4}, {0x8908, 0xD9FF ,4}, {0x890A, 0x2502 ,4}, {0x890C, 0x1002 ,4}, {0x890E, 0x2A05 ,4}, {0x8910, 0x03FE ,4}, {0x8912, 0x0A16 ,4}, {0x8914, 0x06E4 ,4}, {0x8916, 0x702F ,4}, {0x8918, 0x7810 ,4}, {0x891A, 0x7D02 ,4}, {0x891C, 0x7DB0 ,4}, {0x891E, 0xF00B ,4}, {0x8920, 0x78A2 ,4}, {0x8922, 0x2805 ,4}, {0x8924, 0x03FE ,4}, {0x8926, 0x0A02 ,4}, {0x8928, 0x06E4 ,4}, {0x892A, 0x702F ,4}, {0x892C, 0x7810 ,4}, {0x892E, 0x651D ,4}, {0x8930, 0x7DB0 ,4}, {0x8932, 0x7DAF ,4}, {0x8934, 0x8E08 ,4}, {0x8936, 0xBD06 ,4}, {0x8938, 0xD120 ,4}, {0x893A, 0xB8C3 ,4}, {0x893C, 0x78A5 ,4}, {0x893E, 0xB88F ,4}, {0x8940, 0x1908 ,4}, {0x8942, 0x0024 ,4}, {0x8944, 0x2841 ,4}, {0x8946, 0x0201 ,4}, {0x8948, 0x1E26 ,4}, {0x894A, 0x1042 ,4}, {0x894C, 0x0F15 ,4}, {0x894E, 0x1463 ,4}, {0x8950, 0x1E27 ,4}, {0x8952, 0x1002 ,4}, {0x8954, 0x224C ,4}, {0x8956, 0xA000 ,4}, {0x8958, 0x224A ,4}, {0x895A, 0x2040 ,4}, {0x895C, 0x22C2 ,4}, {0x895E, 0x2482 ,4}, {0x8960, 0x204F ,4}, {0x8962, 0x2040 ,4}, {0x8964, 0x224C ,4}, {0x8966, 0xA000 ,4}, {0x8968, 0xB8A2 ,4}, {0x896A, 0xF204 ,4}, {0x896C, 0x2045 ,4}, {0x896E, 0x2180 ,4}, {0x8970, 0xAE01 ,4}, {0x8972, 0x0D9E ,4}, {0x8974, 0xFFE3 ,4}, {0x8976, 0x70E9 ,4}, {0x8978, 0x0125 ,4}, {0x897A, 0x06C4 ,4}, {0x897C, 0xC0F1 ,4}, {0x897E, 0xD010 ,4}, {0x8980, 0xD110 ,4}, {0x8982, 0xD20D ,4}, {0x8984, 0xA020 ,4}, {0x8986, 0x8A00 ,4}, {0x8988, 0x0809 ,4}, {0x898A, 0x01DE ,4}, {0x898C, 0xB8A7 ,4}, {0x898E, 0xAA00 ,4}, {0x8990, 0xDBFF ,4}, {0x8992, 0x2B41 ,4}, {0x8994, 0x0200 ,4}, {0x8996, 0xAA0C ,4}, {0x8998, 0x1228 ,4}, {0x899A, 0x0080 ,4}, {0x899C, 0xAA6D ,4}, {0x899E, 0x0815 ,4}, {0x89A0, 0x01DE ,4}, {0x89A2, 0xB8A7 ,4}, {0x89A4, 0x1A28 ,4}, {0x89A6, 0x0002 ,4}, {0x89A8, 0x8123 ,4}, {0x89AA, 0x7960 ,4}, {0x89AC, 0x1228 ,4}, {0x89AE, 0x0080 ,4}, {0x89B0, 0xC0D1 ,4}, {0x89B2, 0x7EE0 ,4}, {0x89B4, 0xFF80 ,4}, {0x89B6, 0x0158 ,4}, {0x89B8, 0xFF00 ,4}, {0x89BA, 0x0618 ,4}, {0x89BC, 0x8000 ,4}, {0x89BE, 0x0008 ,4}, {0x89C0, 0xFF80 ,4}, {0x89C2, 0x0A08 ,4}, {0x89C4, 0xE280 ,4}, {0x89C6, 0x24CA ,4}, {0x89C8, 0x7082 ,4}, {0x89CA, 0x78E0 ,4}, {0x89CC, 0x20E8 ,4}, {0x89CE, 0x01A2 ,4}, {0x89D0, 0x1002 ,4}, {0x89D2, 0x0D02 ,4}, {0x89D4, 0x1902 ,4}, {0x89D6, 0x0094 ,4}, {0x89D8, 0x7FE0 ,4}, {0x89DA, 0x7028 ,4}, {0x89DC, 0x7308 ,4}, {0x89DE, 0x1000 ,4}, {0x89E0, 0x0900 ,4}, {0x89E2, 0x7904 ,4}, {0x89E4, 0x7947 ,4}, {0x89E6, 0x1B00 ,4}, {0x89E8, 0x0064 ,4}, {0x89EA, 0x7EE0 ,4}, {0x89EC, 0xE280 ,4}, {0x89EE, 0x24CA ,4}, {0x89F0, 0x7082 ,4}, {0x89F2, 0x78E0 ,4}, {0x89F4, 0x20E8 ,4}, {0x89F6, 0x01A2 ,4}, {0x89F8, 0x1102 ,4}, {0x89FA, 0x0502 ,4}, {0x89FC, 0x1802 ,4}, {0x89FE, 0x00B4 ,4}, {0x8A00, 0x7FE0 ,4}, {0x8A02, 0x7028 ,4}, {0x8A04, 0x0000 ,4}, {0x8A06, 0x0000 ,4}, {0x8A08, 0xFF80 ,4}, {0x8A0A, 0x097C ,4}, {0x8A0C, 0xFF80 ,4}, {0x8A0E, 0x08CC ,4}, {0x8A10, 0x0000 ,4}, {0x8A12, 0x08DC ,4}, {0x8A14, 0x0000 ,4}, {0x8A16, 0x0998 ,4}, {0x098E, 0x0016 ,4}, // LOGICAL_ADDRESS_ACCESS //[MON_ADDRESS_LO] {0x8016, 0x086C ,4}, // MON_ADDRESS_LO {0x8002, 0x0001 ,4}, // MON_CMD }; //DELAY = 100 //=====================================================================================ÓÀ²¨ soc5140_short_reg init_3[]={ // POLL MON_PATCH_0 => 0x00, ..., 0x01 (18 reads) {0x098E, 0xC40C ,4}, // LOGICAL_ADDRESS_ACCESS {0xC40C, 0x00FF ,4}, // AFM_POS_MAX {0xC40A, 0x0000 ,4}, // AFM_POS_MIN {0x30D4, 0x9080 ,4}, // COLUMN_CORRECTION {0x316E, 0xCAFF ,4}, // DAC_ECL {0x305E, 0x10A0 ,4}, // GLOBAL_GAIN {0x3E00, 0x0010 ,4}, // SAMP_CONTROL {0x3E02, 0xED02 ,4}, // SAMP_ADDR_EN {0x3E04, 0xC88C ,4}, // SAMP_RD1_SIG {0x3E06, 0xC88C ,4}, // SAMP_RD1_SIG_BOOST {0x3E08, 0x700A ,4}, // SAMP_RD1_RST {0x3E0A, 0x701E ,4}, // SAMP_RD1_RST_BOOST {0x3E0C, 0x00FF ,4}, // SAMP_RST1_EN {0x3E0E, 0x00FF ,4}, // SAMP_RST1_BOOST {0x3E10, 0x00FF ,4}, // SAMP_RST1_CLOOP_SH {0x3E12, 0x0000 ,4}, // SAMP_RST_BOOST_SEQ {0x3E14, 0xC78C ,4}, // SAMP_SAMP1_SIG {0x3E16, 0x6E06 ,4}, // SAMP_SAMP1_RST {0x3E18, 0xA58C ,4}, // SAMP_TX_EN {0x3E1A, 0xA58E ,4}, // SAMP_TX_BOOST {0x3E1C, 0xA58E ,4}, // SAMP_TX_CLOOP_SH {0x3E1E, 0xC0D0 ,4}, // SAMP_TX_BOOST_SEQ {0x3E20, 0xEB00 ,4}, // SAMP_VLN_EN {0x3E22, 0x00FF ,4}, // SAMP_VLN_HOLD {0x3E24, 0xEB02 ,4}, // SAMP_VCL_EN {0x3E26, 0xEA02 ,4}, // SAMP_COLCLAMP {0x3E28, 0xEB0A ,4}, // SAMP_SH_VCL {0x3E2A, 0xEC01 ,4}, // SAMP_SH_VREF {0x3E2C, 0xEB01 ,4}, // SAMP_SH_VBST {0x3E2E, 0x00FF ,4}, // SAMP_SPARE {0x3E30, 0x00F3 ,4}, // SAMP_READOUT {0x3E32, 0x3DFA ,4}, // SAMP_RESET_DONE {0x3E34, 0x00FF ,4}, // SAMP_VLN_CLAMP {0x3E36, 0x00F3 ,4}, // SAMP_ASC_INT {0x3E38, 0x0000 ,4}, // SAMP_RS_CLOOP_SH_R {0x3E3A, 0xF802 ,4}, // SAMP_RS_CLOOP_SH {0x3E3C, 0x0FFF ,4}, // SAMP_RS_BOOST_SEQ {0x3E3E, 0xEA10 ,4}, // SAMP_TXLO_GND {0x3E40, 0xEB05 ,4}, // SAMP_VLN_PER_COL {0x3E42, 0xE5C8 ,4}, // SAMP_RD2_SIG {0x3E44, 0xE5C8 ,4}, // SAMP_RD2_SIG_BOOST {0x3E46, 0x8C70 ,4}, // SAMP_RD2_RST {0x3E48, 0x8C71 ,4}, // SAMP_RD2_RST_BOOST {0x3E4A, 0x00FF ,4}, // SAMP_RST2_EN {0x3E4C, 0x00FF ,4}, // SAMP_RST2_BOOST {0x3E4E, 0x00FF ,4}, // SAMP_RST2_CLOOP_SH {0x3E50, 0xE38D ,4}, // SAMP_SAMP2_SIG {0x3E52, 0x8B0A ,4}, // SAMP_SAMP2_RST {0x3E58, 0xEB0A ,4}, // SAMP_PIX_CLAMP_EN {0x3E5C, 0x0A00 ,4}, // SAMP_PIX_PULLUP_EN {0x3E5E, 0x00FF ,4}, // SAMP_PIX_PULLDOWN_EN_R {0x3E60, 0x00FF ,4}, // SAMP_PIX_PULLDOWN_EN_S {0x3E90, 0x3C01 ,4}, // RST_ADDR_EN {0x3E92, 0x00FF ,4}, // RST_RST_EN {0x3E94, 0x00FF ,4}, // RST_RST_BOOST {0x3E96, 0x3C00 ,4}, // RST_TX_EN {0x3E98, 0x3C00 ,4}, // RST_TX_BOOST {0x3E9A, 0x3C00 ,4}, // RST_TX_CLOOP_SH {0x3E9C, 0xC0E0 ,4}, // RST_TX_BOOST_SEQ {0x3E9E, 0x00FF ,4}, // RST_RST_CLOOP_SH {0x3EA0, 0x0000 ,4}, // RST_RST_BOOST_SEQ {0x3EA6, 0x3C00 ,4}, // RST_PIX_PULLUP_EN {0x3ED8, 0x3057 ,4}, // DAC_LD_12_13 {0x316C, 0xB44F ,4}, // DAC_TXLO {0x316E, 0xCAFF ,4}, // DAC_ECL {0x3ED2, 0xEA0A ,4}, // DAC_LD_6_7 {0x3ED4, 0x00A3 ,4}, // DAC_LD_8_9 {0x3EDC, 0x6020 ,4}, // DAC_LD_16_17 {0x3EE6, 0xA541 ,4}, // DAC_LD_26_27 {0x31E0, 0x0000 ,4}, // PIX_DEF_ID {0x3ED0, 0x2409 ,4}, // DAC_LD_4_5 {0x3EDE, 0x0A49 ,4}, // DAC_LD_18_19 {0x3EE0, 0x4910 ,4}, // DAC_LD_20_21 {0x3EE2, 0x09D2 ,4}, // DAC_LD_22_23 {0x30B6, 0x0006 ,4}, // AUTOLR_CONTROL {0x8404, 0x06 ,3}, // SEQ_CMD {0x337C, 0x0006 ,4}, // YUV_YCBCR_CONTROL {0xAC01, 0xAB ,3}, // AWB_MODE {0xAC46, 0x0221 ,4}, // AWB_LEFT_CCM_0 {0xAC48, 0xFEAE ,4}, // AWB_LEFT_CCM_1 {0xAC4A, 0x0032 ,4}, // AWB_LEFT_CCM_2 {0xAC4C, 0xFFC5 ,4}, // AWB_LEFT_CCM_3 {0xAC4E, 0x0154 ,4}, // AWB_LEFT_CCM_4 {0xAC50, 0xFFE7 ,4}, // AWB_LEFT_CCM_5 {0xAC52, 0xFFB1 ,4}, // AWB_LEFT_CCM_6 {0xAC54, 0xFEC5 ,4}, // AWB_LEFT_CCM_7 {0xAC56, 0x028A ,4}, // AWB_LEFT_CCM_8 {0xAC58, 0x0130 ,4}, // AWB_LEFT_CCM_R2BRATIO {0xAC5C, 0x01CD ,4}, // AWB_RIGHT_CCM_0 {0xAC5E, 0xFF63 ,4}, // AWB_RIGHT_CCM_1 {0xAC60, 0xFFD0 ,4}, // AWB_RIGHT_CCM_2 {0xAC62, 0xFFCD ,4}, // AWB_RIGHT_CCM_3 {0xAC64, 0x013B ,4}, // AWB_RIGHT_CCM_4 {0xAC66, 0xFFF8 ,4}, // AWB_RIGHT_CCM_5 {0xAC68, 0xFFFB ,4}, // AWB_RIGHT_CCM_6 {0xAC6A, 0xFF78 ,4}, // AWB_RIGHT_CCM_7 {0xAC6C, 0x018D ,4}, // AWB_RIGHT_CCM_8 {0xAC6E, 0x0055 ,4}, // AWB_RIGHT_CCM_R2BRATIO {0xB842, 0x0037 ,4}, // STAT_AWB_GRAY_CHECKER_OFFSET_X {0xB844, 0x0044 ,4}, // STAT_AWB_GRAY_CHECKER_OFFSET_Y {0x3240, 0x0024 ,4}, // AWB_XY_SCALE {0x3240, 0x0024 ,4}, // AWB_XY_SCALE {0x3242, 0x0000 ,4}, // AWB_WEIGHT_R0 {0x3244, 0x0000 ,4}, // AWB_WEIGHT_R1 {0x3246, 0x0000 ,4}, // AWB_WEIGHT_R2 {0x3248, 0x7F00 ,4}, // AWB_WEIGHT_R3 {0x324A, 0xA500 ,4}, // AWB_WEIGHT_R4 {0x324C, 0x1540 ,4}, // AWB_WEIGHT_R5 {0x324E, 0x01AC ,4}, // AWB_WEIGHT_R6 {0x3250, 0x003E ,4}, // AWB_WEIGHT_R7 {0x8404, 0x06 ,3}, // SEQ_CMD {0xAC3C, 0x2E ,3}, // AWB_MIN_ACCEPTED_PRE_AWB_R2G_RATIO {0xAC3D, 0x84 ,3}, // AWB_MAX_ACCEPTED_PRE_AWB_R2G_RATIO {0xAC3E, 0x11 ,3}, // AWB_MIN_ACCEPTED_PRE_AWB_B2G_RATIO {0xAC3F, 0x63 ,3}, // AWB_MAX_ACCEPTED_PRE_AWB_B2G_RATIO {0xACB0, 0x2B ,3}, // AWB_RG_MIN {0xACB1, 0x84 ,3}, // AWB_RG_MAX {0xACB4, 0x11 ,3}, // AWB_BG_MIN {0xACB5, 0x63 ,3}, // AWB_BG_MAX {0xD80F, 0x04 ,3}, // JPEG_QSCALE_0 {0xD810, 0x08 ,3}, // JPEG_QSCALE_1 {0xC8D2, 0x04 ,3}, // CAM_OUTPUT_1_JPEG_QSCALE_0 {0xC8D3, 0x08 ,3}, // CAM_OUTPUT_1_JPEG_QSCALE_1 {0xC8BC, 0x04 ,3}, // CAM_OUTPUT_0_JPEG_QSCALE_0 {0xC8BD, 0x08 ,3}, // CAM_OUTPUT_0_JPEG_QSCALE_1 {0x301A, 0x10F4 ,4}, // RESET_REGISTER {0x301E, 0x0000 ,4}, // DATA_PEDESTAL {0x301A, 0x10FC ,4}, // RESET_REGISTER {0xDC33, 0x00 ,3}, // SYS_FIRST_BLACK_LEVEL {0xDC35, 0x04 ,3}, // SYS_UV_COLOR_BOOST {0x326E, 0x0006 ,4}, // LOW_PASS_YUV_FILTER {0xDC37, 0x62 ,3}, // SYS_BRIGHT_COLORKILL {0x35A4, 0x0596 ,4}, // BRIGHT_COLOR_KILL_CONTROLS {0x35A2, 0x0094 ,4}, // DARK_COLOR_KILL_CONTROLS {0xDC36, 0x23 ,3}, // SYS_DARK_COLOR_KILL {0x8404, 0x06 ,3}, // SEQ_CMD {0xBC18, 0x00 ,3}, // LL_GAMMA_CONTRAST_CURVE_0 {0xBC19, 0x11 ,3}, // LL_GAMMA_CONTRAST_CURVE_1 {0xBC1A, 0x23 ,3}, // LL_GAMMA_CONTRAST_CURVE_2 {0xBC1B, 0x3F ,3}, // LL_GAMMA_CONTRAST_CURVE_3 {0xBC1C, 0x67 ,3}, // LL_GAMMA_CONTRAST_CURVE_4 {0xBC1D, 0x85 ,3}, // LL_GAMMA_CONTRAST_CURVE_5 {0xBC1E, 0x9B ,3}, // LL_GAMMA_CONTRAST_CURVE_6 {0xBC1F, 0xAD ,3}, // LL_GAMMA_CONTRAST_CURVE_7 {0xBC20, 0xBB ,3}, // LL_GAMMA_CONTRAST_CURVE_8 {0xBC21, 0xC7 ,3}, // LL_GAMMA_CONTRAST_CURVE_9 {0xBC22, 0xD1 ,3}, // LL_GAMMA_CONTRAST_CURVE_10 {0xBC23, 0xDA ,3}, // LL_GAMMA_CONTRAST_CURVE_11 {0xBC24, 0xE1 ,3}, // LL_GAMMA_CONTRAST_CURVE_12 {0xBC25, 0xE8 ,3}, // LL_GAMMA_CONTRAST_CURVE_13 {0xBC26, 0xEE ,3}, // LL_GAMMA_CONTRAST_CURVE_14 {0xBC27, 0xF3 ,3}, // LL_GAMMA_CONTRAST_CURVE_15 {0xBC28, 0xF7 ,3}, // LL_GAMMA_CONTRAST_CURVE_16 {0xBC29, 0xFB ,3}, // LL_GAMMA_CONTRAST_CURVE_17 {0xBC2A, 0xFF ,3}, // LL_GAMMA_CONTRAST_CURVE_18 {0xBC2B, 0x00 ,3}, // LL_GAMMA_NEUTRAL_CURVE_0 {0xBC2C, 0x11 ,3}, // LL_GAMMA_NEUTRAL_CURVE_1 {0xBC2D, 0x23 ,3}, // LL_GAMMA_NEUTRAL_CURVE_2 {0xBC2E, 0x3F ,3}, // LL_GAMMA_NEUTRAL_CURVE_3 {0xBC2F, 0x67 ,3}, // LL_GAMMA_NEUTRAL_CURVE_4 {0xBC30, 0x85 ,3}, // LL_GAMMA_NEUTRAL_CURVE_5 {0xBC31, 0x9B ,3}, // LL_GAMMA_NEUTRAL_CURVE_6 {0xBC32, 0xAD ,3}, // LL_GAMMA_NEUTRAL_CURVE_7 {0xBC33, 0xBB ,3}, // LL_GAMMA_NEUTRAL_CURVE_8 {0xBC34, 0xC7 ,3}, // LL_GAMMA_NEUTRAL_CURVE_9 {0xBC35, 0xD1 ,3}, // LL_GAMMA_NEUTRAL_CURVE_10 {0xBC36, 0xDA ,3}, // LL_GAMMA_NEUTRAL_CURVE_11 {0xBC37, 0xE1 ,3}, // LL_GAMMA_NEUTRAL_CURVE_12 {0xBC38, 0xE8 ,3}, // LL_GAMMA_NEUTRAL_CURVE_13 {0xBC39, 0xEE ,3}, // LL_GAMMA_NEUTRAL_CURVE_14 {0xBC3A, 0xF3 ,3}, // LL_GAMMA_NEUTRAL_CURVE_15 {0xBC3B, 0xF7 ,3}, // LL_GAMMA_NEUTRAL_CURVE_16 {0xBC3C, 0xFB ,3}, // LL_GAMMA_NEUTRAL_CURVE_17 {0xBC3D, 0xFF ,3}, // LL_GAMMA_NEUTRAL_CURVE_18 {0xBC3E, 0x00 ,3}, // LL_GAMMA_NR_CURVE_0 {0xBC3F, 0x18 ,3}, // LL_GAMMA_NR_CURVE_1 {0xBC40, 0x25 ,3}, // LL_GAMMA_NR_CURVE_2 {0xBC41, 0x3A ,3}, // LL_GAMMA_NR_CURVE_3 {0xBC42, 0x59 ,3}, // LL_GAMMA_NR_CURVE_4 {0xBC43, 0x70 ,3}, // LL_GAMMA_NR_CURVE_5 {0xBC44, 0x81 ,3}, // LL_GAMMA_NR_CURVE_6 {0xBC45, 0x90 ,3}, // LL_GAMMA_NR_CURVE_7 {0xBC46, 0x9E ,3}, // LL_GAMMA_NR_CURVE_8 {0xBC47, 0xAB ,3}, // LL_GAMMA_NR_CURVE_9 {0xBC48, 0xB6 ,3}, // LL_GAMMA_NR_CURVE_10 {0xBC49, 0xC1 ,3}, // LL_GAMMA_NR_CURVE_11 {0xBC4A, 0xCB ,3}, // LL_GAMMA_NR_CURVE_12 {0xBC4B, 0xD5 ,3}, // LL_GAMMA_NR_CURVE_13 {0xBC4C, 0xDE ,3}, // LL_GAMMA_NR_CURVE_14 {0xBC4D, 0xE7 ,3}, // LL_GAMMA_NR_CURVE_15 {0xBC4E, 0xEF ,3}, // LL_GAMMA_NR_CURVE_16 {0xBC4F, 0xF7 ,3}, // LL_GAMMA_NR_CURVE_17 {0xBC50, 0xFF ,3}, // LL_GAMMA_NR_CURVE_18 {0x8404, 0x06 ,3}, // SEQ_CMD {0xB801, 0xE0 ,3}, // STAT_MODE {0xB862, 0x04 ,3}, // STAT_BMTRACKING_SPEED {0xB829, 0x02 ,3}, // STAT_LL_BRIGHTNESS_METRIC_DIVISOR {0xB863, 0x02 ,3}, // STAT_BM_MUL {0xB827, 0x0F ,3}, // STAT_AE_EV_SHIFT {0xA409, 0x37 ,3}, // AE_RULE_BASE_TARGET {0xBC52, 0x00C8 ,4}, // LL_START_BRIGHTNESS_METRIC {0xBC54, 0x0A28 ,4}, // LL_END_BRIGHTNESS_METRIC {0xBC58, 0x00C8 ,4}, // LL_START_GAIN_METRIC {0xBC5A, 0x12C0 ,4}, // LL_END_GAIN_METRIC {0xBC5E, 0x00FA ,4}, // LL_START_APERTURE_GAIN_BM {0xBC60, 0x0258 ,4}, // LL_END_APERTURE_GAIN_BM {0xBC66, 0x00FA ,4}, // LL_START_APERTURE_GM {0xBC68, 0x0258 ,4}, // LL_END_APERTURE_GM {0xBC86, 0x00C8 ,4}, // LL_START_FFNR_GM {0xBC88, 0x0640 ,4}, // LL_END_FFNR_GM {0xBCBC, 0x0040 ,4}, // LL_SFFB_START_GAIN {0xBCBE, 0x01FC ,4}, // LL_SFFB_END_GAIN {0xBCCC, 0x00C8 ,4}, // LL_SFFB_START_MAX_GM {0xBCCE, 0x0640 ,4}, // LL_SFFB_END_MAX_GM {0xBC90, 0x00C8 ,4}, // LL_START_GRB_GM {0xBC92, 0x0640 ,4}, // LL_END_GRB_GM {0xBC0E, 0x0001 ,4}, // LL_GAMMA_CURVE_ADJ_START_POS {0xBC10, 0x0002 ,4}, // LL_GAMMA_CURVE_ADJ_MID_POS {0xBC12, 0x02BC ,4}, // LL_GAMMA_CURVE_ADJ_END_POS {0xBCAA, 0x044C ,4}, // LL_CDC_THR_ADJ_START_POS {0xBCAC, 0x00AF ,4}, // LL_CDC_THR_ADJ_MID_POS {0xBCAE, 0x0009 ,4}, // LL_CDC_THR_ADJ_END_POS {0xBCD8, 0x00C8 ,4}, // LL_PCR_START_BM {0xBCDA, 0x0A28 ,4}, // LL_PCR_END_BM {0x3380, 0x0504 ,4}, // KERNEL_CONFIG {0xBC94, 0x0C ,3}, // LL_GB_START_THRESHOLD_0 {0xBC95, 0x08 ,3}, // LL_GB_START_THRESHOLD_1 {0xBC9C, 0x3C ,3}, // LL_GB_END_THRESHOLD_0 {0xBC9D, 0x28 ,4}, // LL_GB_END_THRESHOLD_1 {0x33B0, 0x2A16 ,4}, // FFNR_ALPHA_BETA {0xBC8A, 0x02 ,3}, // LL_START_FF_MIX_THRESH_Y {0xBC8B, 0x0F ,3}, // LL_END_FF_MIX_THRESH_Y {0xBC8C, 0xFF ,3}, // LL_START_FF_MIX_THRESH_YGAIN {0xBC8D, 0xFF ,3}, // LL_END_FF_MIX_THRESH_YGAIN {0xBC8E, 0xFF ,3}, // LL_START_FF_MIX_THRESH_GAIN {0xBC8F, 0x00 ,3}, // LL_END_FF_MIX_THRESH_GAIN {0xBCB2, 0x20 ,3}, // LL_CDC_DARK_CLUS_SLOPE {0xBCB3, 0x3A ,3}, // LL_CDC_DARK_CLUS_SATUR {0xBCB4, 0x39 ,3}, // LL_CDC_BRIGHT_CLUS_LO_LIGHT_SLOPE {0xBCB7, 0x39 ,3}, // LL_CDC_BRIGHT_CLUS_LO_LIGHT_SATUR {0xBCB5, 0x20 ,3}, // LL_CDC_BRIGHT_CLUS_MID_LIGHT_SLOPE {0xBCB8, 0x3A ,3}, // LL_CDC_BRIGHT_CLUS_MID_LIGHT_SATUR {0xBCB6, 0x80 ,3}, // LL_CDC_BRIGHT_CLUS_HI_LIGHT_SLOPE {0xBCB9, 0x24 ,3}, // LL_CDC_BRIGHT_CLUS_HI_LIGHT_SATUR {0xBCAA, 0x03E8 ,4}, // LL_CDC_THR_ADJ_START_POS {0xBCAC, 0x012C ,4}, // LL_CDC_THR_ADJ_MID_POS {0xBCAE, 0x0009 ,4}, // LL_CDC_THR_ADJ_END_POS {0x33BA, 0x0084 ,4}, // APEDGE_CONTROL {0x33BE, 0x0000 ,4}, // UA_KNEE_L {0x33C2, 0x8800 ,4}, // UA_WEIGHTS {0xBC5E, 0x0154 ,4}, // LL_START_APERTURE_GAIN_BM {0xBC60, 0x0640 ,4}, // LL_END_APERTURE_GAIN_BM {0xBC62, 0x0E ,3}, // LL_START_APERTURE_KPGAIN {0xBC63, 0x14 ,3}, // LL_END_APERTURE_KPGAIN {0xBC64, 0x0E ,3}, // LL_START_APERTURE_KNGAIN {0xBC65, 0x14 ,3}, // LL_END_APERTURE_KNGAIN {0xBCE2, 0x0A ,3}, // LL_START_POS_KNEE {0xBCE3, 0x2B ,3}, // LL_END_POS_KNEE {0xBCE4, 0x0A ,3}, // LL_START_NEG_KNEE {0xBCE5, 0x2B ,3}, // LL_END_NEG_KNEE {0x3210, 0x49B0 ,4}, // COLOR_PIPELINE_CONTROL {0xBCC0, 0x1F ,3}, // LL_SFFB_RAMP_START {0xBCC1, 0x03 ,3}, // LL_SFFB_RAMP_STOP {0xBCC2, 0x2C ,3}, // LL_SFFB_SLOPE_START {0xBCC3, 0x10 ,3}, // LL_SFFB_SLOPE_STOP {0xBCC4, 0x07 ,3}, // LL_SFFB_THSTART {0xBCC5, 0x0B ,3}, // LL_SFFB_THSTOP {0xBCBA, 0x0009 ,4}, // LL_SFFB_CONFIG {0x8404, 0x06 ,3}, // SEQ_CMD {0xBC14, 0xFFFE ,4}, // LL_GAMMA_FADE_TO_BLACK_START_POS {0xBC16, 0xFFFF ,4}, // LL_GAMMA_FADE_TO_BLACK_END_POS {0xBC66, 0x0154 ,4}, // LL_START_APERTURE_GM {0xBC68, 0x07D0 ,4}, // LL_END_APERTURE_GM {0xBC6A, 0x04 ,3}, // LL_START_APERTURE_INTEGER_GAIN {0xBC6B, 0x00 ,3}, // LL_END_APERTURE_INTEGER_GAIN {0xBC6C, 0x00 ,3}, // LL_START_APERTURE_EXP_GAIN {0xBC6D, 0x00 ,3}, // LL_END_APERTURE_EXP_GAIN {0xA81C, 0x0040 ,4}, // AE_TRACK_MIN_AGAIN {0xA820, 0x01FC ,4}, // AE_TRACK_MAX_AGAIN {0xA822, 0x0080 ,4}, // AE_TRACK_MIN_DGAIN {0xA824, 0x0100 ,4}, // AE_TRACK_MAX_DGAIN {0xBC56, 0x64 ,3}, // LL_START_CCM_SATURATION {0xBC57, 0x1E ,3}, // LL_END_CCM_SATURATION {0xBCDE, 0x03 ,3}, // LL_START_SYS_THRESHOLD {0xBCDF, 0x50 ,3}, // LL_STOP_SYS_THRESHOLD {0xBCE0, 0x08 ,3}, // LL_START_SYS_GAIN {0xBCE1, 0x03 ,3}, // LL_STOP_SYS_GAIN {0xBCD0, 0x000A ,4}, // LL_SFFB_SOBEL_FLAT_START {0xBCD2, 0x00FE ,4}, // LL_SFFB_SOBEL_FLAT_STOP {0xBCD4, 0x001E ,4}, // LL_SFFB_SOBEL_SHARP_START {0xBCD6, 0x00FF ,4}, // LL_SFFB_SOBEL_SHARP_STOP {0xBCC6, 0x00 ,3}, // LL_SFFB_SHARPENING_START {0xBCC7, 0x00 ,3}, // LL_SFFB_SHARPENING_STOP {0xBCC8, 0x20 ,3}, // LL_SFFB_FLATNESS_START {0xBCC9, 0x40 ,3}, // LL_SFFB_FLATNESS_STOP {0xBCCA, 0x04 ,3}, // LL_SFFB_TRANSITION_START {0xBCCB, 0x00 ,3}, // LL_SFFB_TRANSITION_STOP {0xBCE6, 0x03 ,3}, // LL_SFFB_ZERO_ENABLE {0xBCE6, 0x03 ,3}, // LL_SFFB_ZERO_ENABLE {0xA410, 0x04 ,3}, // AE_RULE_TARGET_AE_6 {0xA411, 0x06 ,3}, // AE_RULE_TARGET_AE_7 {0x8404, 0x06 ,3}, // SEQ_CMD {0xC8BC, 0x04 ,3}, // CAM_OUTPUT_0_JPEG_QSCALE_0 {0xC8BD, 0x0A ,3}, // CAM_OUTPUT_0_JPEG_QSCALE_1 {0xC8D2, 0x04 ,3}, // CAM_OUTPUT_1_JPEG_QSCALE_0 {0xC8D3, 0x0A ,3}, // CAM_OUTPUT_1_JPEG_QSCALE_1 {0xDC3A, 0x23 ,3}, // SYS_SEPIA_CR {0xDC3B, 0xB2 ,3}, // SYS_SEPIA_CB {0x0018, 0x2008 ,4}, // STANDBY_CONTROL_AND_STATUS }; soc5140_short_reg af[]= { //[AF] {0x098E, 0xB018 ,4}, // LOGICAL_ADDRESS_ACCESS {0xB018, 0x06 ,3}, // AF_FS_POS_0 {0xB019, 0x1E ,3}, // AF_FS_POS_1 {0xB01A, 0x36 ,3}, // AF_FS_POS_2 {0xB01B, 0x4E ,3}, // AF_FS_POS_3 {0xB01C, 0x66 ,3}, // AF_FS_POS_4 {0xB01D, 0x7E ,3}, // AF_FS_POS_5 {0xB01E, 0x96 ,3}, // AF_FS_POS_6 {0xB01F, 0xB4 ,3}, // AF_FS_POS_7 {0xB020, 0xD2 ,3}, // AF_FS_POS_8 {0xB021, 0xFF ,3}, // AF_FS_POS_9 {0xB012, 0x0A ,3}, // AF_FS_NUM_STEPS //2nd Scan Option {0x098E, 0xB013 ,4}, // LOGICAL_ADDRESS_ACCESS {0xB013, 0xAA ,3}, // AF_FS_NUM_STEPS2 {0xB014, 0x03 ,3}, // AF_FS_STEP_SIZE //[AF_WINDOWN] {0xB008, 0x0000 ,4}, // AF_ZONE_WEIGHTS_HI {0xB00A, 0x003f ,4}, // AF_ZONE_WEIGHTS_HI {0xB00C, 0x0fc3 ,4}, // AF_ZONE_WEIGHTS_LO {0xB00E, 0xf000 ,4}, // AF_ZONE_WEIGHTS_LO ////[af_xx] ////[**********section8*************] ////[Section8]//AF Features ////[SAMSUNG_VCM_Enable] //AFM_POS_APPLY_Workaround 0917 {0x098E, 0x8419 ,4}, // LOGICAL_ADDRESS_ACCESS {0x8419, 0x01 ,3}, // SEQ_STATE_CFG_1_AF //{0x8404, 0x06 ,3}, // SEQ_CMD REMOVE {0x098E, 0xB007 ,4}, // LOGICAL_ADDRESS_ACCESS {0xB007, 0x01 ,3}, // AF_BEST_LENS_POS ////[AF_VCM_Enable] // 1102 DW9716 //VAR8= 17, 0x0000, 0x88 ,4}, // AFM_ALGO {0x098E, 0xC400 ,4}, // LOGICAL_ADDRESS_ACCESS {0xC400, 0x81 ,3}, // AFM_ALGO {0x8419, 0x05 ,3}, // SEQ_STATE_CFG_1_AF {0x098E, 0x8404 ,4}, // LOGICAL_ADDRESS_ACCESS //[SEQ_CMD] {0x8404, 0x05 ,3}, // SEQ_CMD //delay=50 // //{0x098E, 0xC424 ,4}, // LOGICAL_ADDRESS_ACCESS //{0xC424, 0x18 ,3}, // AFM_SI_SLAVE_ADDR //AF settings //{0x098E, 0xB002 ,4}, // LOGICAL_ADDRESS_ACCESS //{0xB002, 0x0347 ,4}, // AF_MODE //{0xB004, 0x00C2 ,4}, // AF_ALGO //{0x098E, 0xB015 ,4}, // LOGICAL_ADDRESS_ACCESS //{0xB015, 0x05 ,3}, // AF_TH_AVE_DIFF_SHA //{0xB016, 0x0020 ,4}, // AF_TH_AVE_MAX_SHA // //AF_Window_Center {0xB008, 0x0000,4},// AF_ZONE_WEIGHTS_HI {0xB00A, 0x003f,4}, // AF_ZONE_WEIGHTS_HI {0xB00C, 0x0fc3,4}, // AF_ZONE_WEIGHTS_LO {0xB00E, 0xf000,4}, // AF_ZONE_WEIGHTS_LO {0x098E, 0xB018 ,4}, // LOGICAL_ADDRESS_ACCESS {0xB018, 0x06 ,3}, // AF_FS_POS_0 {0xB019, 0x1E ,3}, // AF_FS_POS_1 {0xB01A, 0x36 ,3}, // AF_FS_POS_2 {0xB01B, 0x4E ,3}, // AF_FS_POS_3 {0xB01C, 0x66 ,3}, // AF_FS_POS_4 {0xB01D, 0x7E ,3}, // AF_FS_POS_5 {0xB01E, 0x96 ,3}, // AF_FS_POS_6 {0xB01F, 0xB4 ,3}, // AF_FS_POS_7 {0xB020, 0xD2 ,3}, // AF_FS_POS_8 {0xB021, 0xFF ,3}, // AF_FS_POS_9 {0xB012, 0x0A ,3}, // AF_FS_NUM_STEPS //2nd Scan Option {0x098E, 0xB013 ,4}, // LOGICAL_ADDRESS_ACCESS {0xB013, 0xAA ,3}, // AF_FS_NUM_STEPS2 {0xB014, 0x03 ,3}, // AF_FS_STEP_SIZE // ////Lock AF //{0x098E, 0x3045 ,4}, // LOGICAL_ADDRESS_ACCESS //{0xB045, 0x0015 ,4}, // AF_MODE_EX // 0927 Old 4stop setting deleted // 1102 DW9716 setting // 1224 deleted //EG= 0x098E, 0xC40C ,4}, // LOGICAL_ADDRESS_ACCESS //EG= 0xC40A, 0x00c0 ,4}, // AFM_POS_MIN //EG= 0xC40C, 0x03c0 ,4}, // AFM_POS_MAX //EG= 0xC40E, 0x0000 ,4}, // AFM_CUST_CTRL //EG= 0xC425, 0x01 ,3}, // AFM_SI_NEEDS_ACK //EG= 0xC428, 0x80 ,3}, // AFM_DRIVER_CONTROL //EG= 0x098E, 0xC405 ,4}, // LOGICAL_ADDRESS_ACCESS //EG= 0xC408, 0x0F ,3}, // AFM_MACRO_POS //[AF_sound] }; //==================================================== soc5140_short_reg soc5140_init_regs1[]= { // Section 1 {0x0020,0x00,3}, //2bytes Write enable core Vdd power supply {0x0020,0x00,3}, // Section 2 {0x0010,0x0115,4}, //2bytes Write PLL_DIVIDERS {0x0012,0x0060,4}, //2bytes Write PLL_P_DIVIDERS {0x0014,0x2025,4}, //2bytes Write PLL_CONTROL {0x001E,0x0575,4}, //2bytes Write PAD_SLEW_PAD_CONFIG {0x0022,0x01E0,4}, //2bytes Write VDD_DIS_COUNTER {0x002A,0x7F7E,4}, //2bytes Write PLL_P4_P5_P6_DIVIDERS {0x002C,0x0000,4}, //2bytes Write PLL_P7_DIVIDER {0x002E,0x0000,4}, //2bytes Write SENSOR_CLOCK_DIVIDER {0x0018,0x4008,4}, //2bytes Write STANDBY_CONTROL_AND_STATUS //mdelay(10); }; soc5140_short_reg soc5140_init_regs2[]= { //--------Section 3-------/ //LSC load //Wake up OTP Memory {0x098E,0x602A,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xE02A,0x0001,4}, //2bytes Write IO_NV_MEM_COMMAND //mdelay(250); }; soc5140_short_reg soc5140_init_regs3[]= { {0x098E,0x6024,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xE024,0x00DA,4}, //2bytes Write IO_NV_MEM_ADDR {0xE02A,0xA010,4}, //2bytes Write IO_NV_MEM_COMMAND //mdelay(150); }; // ***************************************** //read regsiter 0xE026 ?= 0xDD33 then write //soc5140_init_regs4 else write soc5140_init_regs5 // ***************************************** soc5140_short_reg soc5140_init_regs4[]= { // LSC load from OTP sector0 {0xD004,0x04,3}, //1byte Write PGA_SOLUTION {0xD00C,0x03,3}, //1byte Write PGA_NO_OF_ZONES {0xD006,0x0000,4}, //2bytes Write PGA_ZONE_ADDR_0 {0xD008,0x0000,4}, //2bytes Write PGA_ZONE_ADDR_1 {0xD00A,0x0000,4}, //2bytes Write PGA_ZONE_ADDR_2 {0xD005,0x02,3}, //1byte Write PGA_CURRENT_ZONE {0xD00D,0x00,3}, //1byte Write PGA_ZONE_LOW_0 {0xD00E,0x30,3}, //1byte Write PGA_ZONE_LOW_1 {0xD00F,0x65,3}, //1byte Write PGA_ZONE_LOW_2 {0xD011,0x35,3}, //1byte Write PGA_ZONE_HIGH_0 {0xD012,0x70,3}, //1byte Write PGA_ZONE_HIGH_1 {0xD013,0xFF,3}, //1byte Write PGA_ZONE_HIGH_2 {0xD002,0x0004,4}, //2bytes Write PGA_ALGO }; soc5140_short_reg soc5140_init_regs5[]= { {0x098E,0x6024,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xE024,0x01DA,4}, //2bytes Write IO_NV_MEM_ADDR {0xE02A,0xA010,4}, //2bytes Write IO_NV_MEM_COMMAND //mdelay(150); }; // ***************************************** //read regsiter 0xE026 ?= 0xDD33 then write //soc5140_init_regs6 else write soc5140_init_regs7 // ***************************************** soc5140_short_reg soc5140_init_regs6[]= { // LSC load from OTP sector1 {0xD004,0x04,3}, //1byte Write PGA_SOLUTION {0xD00C,0x03,3}, //1byte Write PGA_NO_OF_ZONES {0xD006,0x0100,4}, //2bytes Write PGA_ZONE_ADDR_0 {0xD008,0x0100,4}, //2bytes Write PGA_ZONE_ADDR_1 {0xD00A,0x0100,4}, //2bytes Write PGA_ZONE_ADDR_2 {0xD005,0x02,3}, //1byte Write PGA_CURRENT_ZONE {0xD00D,0x00,3}, //1byte Write PGA_ZONE_LOW_0 {0xD00E,0x30,3}, //1byte Write PGA_ZONE_LOW_1 {0xD00F,0x65,3}, //1byte Write PGA_ZONE_LOW_2 {0xD011,0x35,3}, //1byte Write PGA_ZONE_HIGH_0 {0xD012,0x70,3}, //1byte Write PGA_ZONE_HIGH_1 {0xD013,0xFF,3}, //1byte Write PGA_ZONE_HIGH_2 {0xD002,0x0004,4}, //2bytes Write PGA_ALGO }; soc5140_short_reg soc5140_init_regs7[]= { //check OTP LSC sector2 {0x098E,0x6024,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xE024,0x02DA,4}, //2bytes Write IO_NV_MEM_ADDR {0xE02A,0xA010,4}, //2bytes Write IO_NV_MEM_COMMAND //mdelay(150); }; // ***************************************** //read regsiter 0xE026 ?= 0xDD33 then write //soc5140_init_regs8 else write soc5140_init_regs9 // ***************************************** soc5140_short_reg soc5140_init_regs8[]= { // LSC load from OTP sector2 {0xD004,0x04,3}, //1byte Write PGA_SOLUTION {0xD00C,0x03,3}, //1byte Write PGA_NO_OF_ZONES {0xD006,0x0200,4}, //2bytes Write PGA_ZONE_ADDR_0 {0xD008,0x0200,4}, //2bytes Write PGA_ZONE_ADDR_1 {0xD00A,0x0200,4}, //2bytes Write PGA_ZONE_ADDR_2 {0xD005,0x02,3}, //1byte Write PGA_CURRENT_ZONE {0xD00D,0x00,3}, //1byte Write PGA_ZONE_LOW_0 {0xD00E,0x30,3}, //1byte Write PGA_ZONE_LOW_1 {0xD00F,0x65,3}, //1byte Write PGA_ZONE_LOW_2 {0xD011,0x35,3}, //1byte Write PGA_ZONE_HIGH_0 {0xD012,0x70,3}, //1byte Write PGA_ZONE_HIGH_1 {0xD013,0xFF,3}, //1byte Write PGA_ZONE_HIGH_2 {0xD002,0x0004,4}, //2bytes Write PGA_ALGO }; soc5140_short_reg soc5140_init_regs9[]= { //LSC load default value [DEFAULT_LSC] {0x3640,0x0290,4}, //2bytes Write P_G1_P0Q0 {0x3642,0x0E0D,4}, //2bytes Write P_G1_P0Q1 {0x3644,0x63D1,4}, //2bytes Write P_G1_P0Q2 {0x3646,0x0C2B,4}, //2bytes Write P_G1_P0Q3 {0x3648,0xF0B0,4}, //2bytes Write P_G1_P0Q4 {0x364A,0x0570,4}, //2bytes Write P_R_P0Q0 {0x364C,0x95AE,4}, //2bytes Write P_R_P0Q1 {0x364E,0x0911,4}, //2bytes Write P_R_P0Q2 {0x3650,0x488F,4}, //2bytes Write P_R_P0Q3 {0x3652,0xD2D0,4}, //2bytes Write P_R_P0Q4 {0x3654,0x0130,4}, //2bytes Write P_B_P0Q0 {0x3656,0x0C8D,4}, //2bytes Write P_B_P0Q1 {0x3658,0x6F30,4}, //2bytes Write P_B_P0Q2 {0x365A,0xAA0D,4}, //2bytes Write P_B_P0Q3 {0x365C,0xC34F,4}, //2bytes Write P_B_P0Q4 {0x365E,0x01F0,4}, //2bytes Write P_G2_P0Q0 {0x3660,0xBC2E,4}, //2bytes Write P_G2_P0Q1 {0x3662,0x5831,4}, //2bytes Write P_G2_P0Q2 {0x3664,0x0BEE,4}, //2bytes Write P_G2_P0Q3 {0x3666,0x80B1,4}, //2bytes Write P_G2_P0Q4 {0x3680,0xD06C,4}, //2bytes Write P_G1_P1Q0 {0x3682,0xFFEE,4}, //2bytes Write P_G1_P1Q1 {0x3684,0x340D,4}, //2bytes Write P_G1_P1Q2 {0x3686,0x574E,4}, //2bytes Write P_G1_P1Q3 {0x3688,0x864D,4}, //2bytes Write P_G1_P1Q4 {0x368A,0x15AE,4}, //2bytes Write P_R_P1Q0 {0x368C,0xBC25,4}, //2bytes Write P_R_P1Q1 {0x368E,0xE0CD,4}, //2bytes Write P_R_P1Q2 {0x3690,0x0B4E,4}, //2bytes Write P_R_P1Q3 {0x3692,0x97AD,4}, //2bytes Write P_R_P1Q4 {0x3694,0xBC4C,4}, //2bytes Write P_B_P1Q0 {0x3696,0x718D,4}, //2bytes Write P_B_P1Q1 {0x3698,0x62CE,4}, //2bytes Write P_B_P1Q2 {0x369A,0xA18F,4}, //2bytes Write P_B_P1Q3 {0x369C,0x84EF,4}, //2bytes Write P_B_P1Q4 {0x369E,0xF10A,4}, //2bytes Write P_G2_P1Q0 {0x36A0,0xF06E,4}, //2bytes Write P_G2_P1Q1 {0x36A2,0x4EEF,4}, //2bytes Write P_G2_P1Q2 {0x36A4,0x1CEE,4}, //2bytes Write P_G2_P1Q3 {0x36A6,0xA630,4}, //2bytes Write P_G2_P1Q4 {0x36C0,0x6071,4}, //2bytes Write P_G1_P2Q0 {0x36C2,0x404E,4}, //2bytes Write P_G1_P2Q1 {0x36C4,0x154E,4}, //2bytes Write P_G1_P2Q2 {0x36C6,0xBBAF,4}, //2bytes Write P_G1_P2Q3 {0x36C8,0x9D8E,4}, //2bytes Write P_G1_P2Q4 {0x36CA,0x2FF1,4}, //2bytes Write P_R_P2Q0 {0x36CC,0xD68E,4}, //2bytes Write P_R_P2Q1 {0x36CE,0x250F,4}, //2bytes Write P_R_P2Q2 {0x36D0,0x4E0C,4}, //2bytes Write P_R_P2Q3 {0x36D2,0x02F0,4}, //2bytes Write P_R_P2Q4 {0x36D4,0x38F1,4}, //2bytes Write P_B_P2Q0 {0x36D6,0x46CF,4}, //2bytes Write P_B_P2Q1 {0x36D8,0x180F,4}, //2bytes Write P_B_P2Q2 {0x36DA,0xE84F,4}, //2bytes Write P_B_P2Q3 {0x36DC,0x72F0,4}, //2bytes Write P_B_P2Q4 {0x36DE,0x7951,4}, //2bytes Write P_G2_P2Q0 {0x36E0,0x8CB0,4}, //2bytes Write P_G2_P2Q1 {0x36E2,0x0EAF,4}, //2bytes Write P_G2_P2Q2 {0x36E4,0x2890,4}, //2bytes Write P_G2_P2Q3 {0x36E6,0x8BD0,4}, //2bytes Write P_G2_P2Q4 {0x3700,0xA64D,4}, //2bytes Write P_G1_P3Q0 {0x3702,0x140F,4}, //2bytes Write P_G1_P3Q1 {0x3704,0x8450,4}, //2bytes Write P_G1_P3Q2 {0x3706,0x9431,4}, //2bytes Write P_G1_P3Q3 {0x3708,0x0C52,4}, //2bytes Write P_G1_P3Q4 {0x370A,0x056E,4}, //2bytes Write P_R_P3Q0 {0x370C,0x4C4D,4}, //2bytes Write P_R_P3Q1 {0x370E,0x4BCF,4}, //2bytes Write P_R_P3Q2 {0x3710,0xA64F,4}, //2bytes Write P_R_P3Q3 {0x3712,0xB9D1,4}, //2bytes Write P_R_P3Q4 {0x3714,0xAC0F,4}, //2bytes Write P_B_P3Q0 {0x3716,0xD2AE,4}, //2bytes Write P_B_P3Q1 {0x3718,0x21F0,4}, //2bytes Write P_B_P3Q2 {0x371A,0x3D30,4}, //2bytes Write P_B_P3Q3 {0x371C,0xC26A,4}, //2bytes Write P_B_P3Q4 {0x371E,0xD88E,4}, //2bytes Write P_G2_P3Q0 {0x3720,0x7B2B,4}, //2bytes Write P_G2_P3Q1 {0x3722,0x1D0A,4}, //2bytes Write P_G2_P3Q2 {0x3724,0xA86F,4}, //2bytes Write P_G2_P3Q3 {0x3726,0x22F1,4}, //2bytes Write P_G2_P3Q4 {0x3740,0xBC0F,4}, //2bytes Write P_G1_P4Q0 {0x3742,0x3490,4}, //2bytes Write P_G1_P4Q1 {0x3744,0x9B11,4}, //2bytes Write P_G1_P4Q2 {0x3746,0xEA92,4}, //2bytes Write P_G1_P4Q3 {0x3748,0x8995,4}, //2bytes Write P_G1_P4Q4 {0x374A,0xE30F,4}, //2bytes Write P_R_P4Q0 {0x374C,0x00B0,4}, //2bytes Write P_R_P4Q1 {0x374E,0x30D2,4}, //2bytes Write P_R_P4Q2 {0x3750,0xB132,4}, //2bytes Write P_R_P4Q3 {0x3752,0x8935,4}, //2bytes Write P_R_P4Q4 {0x3754,0x98AF,4}, //2bytes Write P_B_P4Q0 {0x3756,0x264C,4}, //2bytes Write P_B_P4Q1 {0x3758,0x6751,4}, //2bytes Write P_B_P4Q2 {0x375A,0xBB31,4}, //2bytes Write P_B_P4Q3 {0x375C,0xAC15,4}, //2bytes Write P_B_P4Q4 {0x375E,0xB20F,4}, //2bytes Write P_G2_P4Q0 {0x3760,0x78D1,4}, //2bytes Write P_G2_P4Q1 {0x3762,0xBD91,4}, //2bytes Write P_G2_P4Q2 {0x3764,0xB073,4}, //2bytes Write P_G2_P4Q3 {0x3766,0xF334,4}, //2bytes Write P_G2_P4Q4 {0x3782,0x03F0,4}, //2bytes Write CENTER_ROW {0x3784,0x04B8,4}, //2bytes Write CENTER_COLUMN }; soc5140_short_reg soc5140_init_regs10[]= { // *---------[Section4]------/ //[Timing_settings] //[bin2_skip2_5140SoC_HP] //Max Framerate in Preview with High Power Mode {0x098E,0x483A,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xC83A,0x000C,4}, //2bytes Write CAM_CORE_A_Y_ADDR_START {0xC83C,0x0018,4}, //2bytes Write CAM_CORE_A_X_ADDR_START {0xC83E,0x07B1,4}, //2bytes Write CAM_CORE_A_Y_ADDR_END {0xC840,0x0A45,4}, //2bytes Write CAM_CORE_A_X_ADDR_END {0xC842,0x0001,4}, //2bytes Write CAM_CORE_A_ROW_SPEED {0xC844,0x0103,4}, //2bytes Write CAM_CORE_A_SKIP_X_CORE {0xC846,0x0103,4}, //2bytes Write CAM_CORE_A_SKIP_Y_CORE {0xC848,0x0103,4}, //2bytes Write CAM_CORE_A_SKIP_X_PIPE {0xC84A,0x0103,4}, //2bytes Write CAM_CORE_A_SKIP_Y_PIPE {0xC84C,0x0080,4}, //2bytes Write CAM_CORE_A_POWER_MODE {0xC84E,0x0001,4}, //2bytes Write CAM_CORE_A_BIN_MODE {0xC850,0x00,3}, //1byte Write CAM_CORE_A_ORIENTATION {0xC851,0x00,3}, //1byte Write CAM_CORE_A_PIXEL_ORDER {0xC852,0x019C,4}, //2bytes Write CAM_CORE_A_FINE_CORRECTION {0xC854,0x0732,4}, //2bytes Write CAM_CORE_A_FINE_ITMIN {0xC858,0x000F,4}, //2bytes Write CAM_CORE_A_COARSE_ITMIN {0xC85A,0x0001,4}, //2bytes Write CAM_CORE_A_COARSE_ITMAX_MARGIN {0xC85C,0x0423,4}, //2bytes Write CAM_CORE_A_MIN_FRAME_LENGTH_LINES {0xC85E,0xFFFF,4}, //2bytes Write CAM_CORE_A_MAX_FRAME_LENGTH_LINES {0xC860,0x0423,4}, //2bytes Write CAM_CORE_A_BASE_FRAME_LENGTH_LINES {0xC862,0x1194,4}, //2bytes Write CAM_CORE_A_MIN_LINE_LENGTH_PCLK {0xC864,0xFFFE,4}, //2bytes Write CAM_CORE_A_MAX_LINE_LENGTH_PCLK {0xC866,0x7F7A,4}, //2bytes Write CAM_CORE_A_P4_5_6_DIVIDER {0xC868,0x0423,4}, //2bytes Write CAM_CORE_A_FRAME_LENGTH_LINES {0xC86A,0x1194,4}, //2bytes Write CAM_CORE_A_LINE_LENGTH_PCK {0xC86C,0x0518,4}, //2bytes Write CAM_CORE_A_OUTPUT_SIZE_WIDTH {0xC86E,0x03D4,4}, //2bytes Write CAM_CORE_A_OUTPUT_SIZE_HEIGHT {0xC870,0x0014,4}, //2bytes Write CAM_CORE_A_RX_FIFO_TRIGGER_MARK {0xC858,0x000A,4}, //2bytes Write CAM_CORE_A_COARSE_ITMIN {0xC8B8,0x0004,4}, //2bytes Write CAM_OUTPUT_0_JPEG_CONTRO {0xC8AE,0x0001,4}, //2bytes Write CAM_OUTPUT_0_OUTPUT_FORMAT {0xC8AA,0x0280,4}, //2bytes Write CAM_OUTPUT_0_IMAGE_WIDTH {0xC8AC,0x01E0,4}, //2bytes Write CAM_OUTPUT_0_IMAGE_HEIGHT //[Full_Res_Settings_YUV_Fullspeed] //Max Framerate in Full Res {0x098E,0xC872,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xC872,0x0010,4}, //2bytes Write CAM_CORE_B_Y_ADDR_START {0xC874,0x001C,4}, //2bytes Write CAM_CORE_B_X_ADDR_START {0xC876,0x07AF,4}, //2bytes Write CAM_CORE_B_Y_ADDR_END {0xC878,0x0A43,4}, //2bytes Write CAM_CORE_B_X_ADDR_END {0xC87A,0x0001,4}, //2bytes Write CAM_CORE_B_ROW_SPEED {0xC87C,0x0101,4}, //2bytes Write CAM_CORE_B_SKIP_X_CORE {0xC87E,0x0101,4}, //2bytes Write CAM_CORE_B_SKIP_Y_CORE {0xC880,0x0101,4}, //2bytes Write CAM_CORE_B_SKIP_X_PIPE {0xC882,0x0101,4}, //2bytes Write CAM_CORE_B_SKIP_Y_PIPE {0xC884,0x0064,4}, //2bytes Write CAM_CORE_B_POWER_MODE {0xC886,0x0000,4}, //2bytes Write CAM_CORE_B_BIN_MODE {0xC888,0x00,3}, //1byte Write CAM_CORE_B_ORIENTATION {0xC889,0x00,3}, //1byte Write CAM_CORE_B_PIXEL_ORDER {0xC88A,0x009C,4}, //2bytes Write CAM_CORE_B_FINE_CORRECTION {0xC88C,0x034A,4}, //2bytes Write CAM_CORE_B_FINE_ITMIN {0xC890,0x0002,4}, //2bytes Write CAM_CORE_B_COARSE_ITMIN {0xC892,0x0001,4}, //2bytes Write CAM_CORE_B_COARSE_ITMAX_MARGIN {0xC894,0x082F,4}, //2bytes Write CAM_CORE_B_MIN_FRAME_LENGTH_LINES {0xC896,0xFFFF,4}, //2bytes Write CAM_CORE_B_MAX_FRAME_LENGTH_LINES {0xC898,0x082F,4}, //2bytes Write CAM_CORE_B_BASE_FRAME_LENGTH_LINES {0xC89C,0xFFFE,4}, //2bytes Write CAM_CORE_B_MAX_LINE_LENGTH_PCLK {0xC89E,0x7F7A,4}, //2bytes Write CAM_CORE_B_P4_5_6_DIVIDER {0xC8A0,0x082F,4}, //2bytes Write CAM_CORE_B_FRAME_LENGTH_LINES {0xC8A4,0x0A28,4}, //2bytes Write CAM_CORE_B_OUTPUT_SIZE_WIDTH {0xC8A6,0x07A0,4}, //2bytes Write CAM_CORE_B_OUTPUT_SIZE_HEIGHT {0xC8A8,0x0021,4}, //2bytes Write CAM_CORE_B_RX_FIFO_TRIGGER_MARK {0xC890,0x0002,4}, //2bytes Write CAM_CORE_B_COARSE_ITMIN {0xC8C4,0x0001,4}, //2bytes Write CAM_OUTPUT_1_OUTPUT_FORMAT {0xC8C0,0x0A00,4}, //2bytes Write CAM_OUTPUT_1_IMAGE_WIDTH {0xC8C2,0x0780,4}, //2bytes Write CAM_OUTPUT_1_IMAGE_HEIGHT {0xC89A,0x2500,4}, //2bytes Write CAM_CORE_B_MIN_LINE_LENGTH_PCLK {0xC8A2,0x2328,4}, //2bytes Write CAM_CORE_B_LINE_LENGTH_PCK {0xC8CE,0x0014,4}, //2bytes Write CAM_OUTPUT_1_JPEG_CONTROL //[Flicker_011310_YUV] {0x098E,0xA018,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xA018,0x00CC,4}, //2bytes Write FD_EXPECTED50HZ_FLICKER_PERIOD_IN_CONTEXT_A {0xA01A,0x0061,4}, //2bytes Write FD_EXPECTED50HZ_FLICKER_PERIOD_IN_CONTEXT_B {0xA01C,0x00A9,4}, //2bytes Write FD_EXPECTED60HZ_FLICKER_PERIOD_IN_CONTEXT_A {0xA01E,0x0050,4}, //2bytes Write FD_EXPECTED60HZ_FLICKER_PERIOD_IN_CONTEXT_B {0xA010,0x00B8,4}, //2bytes Write FD_MIN_EXPECTED50HZ_FLICKER_PERIOD {0xA012,0x00D6,4}, //2bytes Write FD_MAX_EXPECTED50HZ_FLICKER_PERIOD {0xA014,0x0095,4}, //2bytes Write FD_MIN_EXPECTED60HZ_FLICKER_PERIOD {0xA016,0x00B3,4}, //2bytes Write FD_MAX_EXPECTED60HZ_FLICKER_PERIOD {0x0982,0x0000,4}, //2bytes Write ACCESS_CTL_STAT //[SOC5140_REV3_patch] //k28a_rev03_patch02_RID29537_SEMCO_AWB_REV8 {0x098A,0x0000 ,4}, //2bytes Write PHYSICAL_ADDRESS_ACCESS {0x886C,0xC0F1,4}, //2bytes Write {0x886E,0xC5E1,4}, //2bytes Write {0x8870,0x246A,4}, //2bytes Write {0x8872,0x1280,4}, //2bytes Write {0x8874,0xC4E1,4}, //2bytes Write {0x8876,0xD30E,4}, //2bytes Write {0x8878,0x2069,4}, //2bytes Write {0x887A,0x0000,4}, //2bytes Write {0x887C,0x1305,4}, //2bytes Write {0x887E,0x0084,4}, //2bytes Write {0x8880,0x1730,4}, //2bytes Write {0x8882,0x7005,4}, //2bytes Write {0x8884,0xD801,4}, //2bytes Write {0x8886,0x8B41,4}, //2bytes Write {0x8888,0xD900,4}, //2bytes Write {0x888A,0x0D5E,4}, //2bytes Write {0x888C,0x0664,4}, //2bytes Write {0x888E,0x8B63,4}, //2bytes Write {0x8890,0xE809,4}, //2bytes Write {0x8892,0xD509,4}, //2bytes Write {0x8894,0xF004,4}, //2bytes Write {0x8896,0x1504,4}, //2bytes Write {0x8898,0x1400,4}, //2bytes Write {0x889A,0x7840,4}, //2bytes Write {0x889C,0xD007,4}, //2bytes Write {0x889E,0x0DFB,4}, //2bytes Write {0x88A0,0x9004,4}, //2bytes Write {0x88A2,0xC4C1,4}, //2bytes Write {0x88A4,0x2029,4}, //2bytes Write {0x88A6,0x0300,4}, //2bytes Write {0x88A8,0x021D,4}, //2bytes Write {0x88AA,0x06C4,4}, //2bytes Write {0x88AC,0xFF80,4}, //2bytes Write {0x88AE,0x08C4,4}, //2bytes Write {0x88B0,0xFF80,4}, //2bytes Write {0x88B2,0x086C,4}, //2bytes Write {0x88B4,0xFF80,4}, //2bytes Write {0x88B6,0x08BC,4}, //2bytes Write {0x88B8,0xFF80,4}, //2bytes Write {0x88BA,0x08C4,4}, //2bytes Write {0x88BC,0xFF80,4}, //2bytes Write {0x88BE,0x08CC,4}, //2bytes Write {0x88C0,0xFF80,4}, //2bytes Write {0x88C2,0x0978,4}, //2bytes Write {0x88C4,0x0002,4}, //2bytes Write {0x88C6,0x0007,4}, //2bytes Write {0x88C8,0x0000,4}, //2bytes Write {0x88CA,0x0000,4}, //2bytes Write {0x88CC,0xC0F1,4}, //2bytes Write {0x88CE,0x0986,4}, //2bytes Write {0x88D0,0x06E4,4}, //2bytes Write {0x88D2,0xDA30,4}, //2bytes Write {0x88D4,0xD138,4}, //2bytes Write {0x88D6,0xD539,4}, //2bytes Write {0x88D8,0x0F1A,4}, //2bytes Write {0x88DA,0x06A4,4}, //2bytes Write {0x88DC,0x2540,4}, //2bytes Write {0x88DE,0x1B00,4}, //2bytes Write {0x88E0,0xD037,4}, //2bytes Write {0x88E2,0x2540,4}, //2bytes Write {0x88E4,0x1B01,4}, //2bytes Write {0x88E6,0x76A9,4}, //2bytes Write {0x88E8,0xA50F,4}, //2bytes Write {0x88EA,0xD036,4}, //2bytes Write {0x88EC,0xA020,4}, //2bytes Write {0x88EE,0xD136,4}, //2bytes Write {0x88F0,0x1120,4}, //2bytes Write {0x88F2,0x0082,4}, //2bytes Write {0x88F4,0x1121,4}, //2bytes Write {0x88F6,0x0080,4}, //2bytes Write {0x88F8,0x1125,4}, //2bytes Write {0x88FA,0x0083,4}, //2bytes Write {0x88FC,0xBA08,4}, //2bytes Write {0x88FE,0x7A05,4}, //2bytes Write {0x8900,0xD032,4}, //2bytes Write {0x8902,0x18EA,4}, //2bytes Write {0x8904,0x0084,4}, //2bytes Write {0x8906,0x1124,4}, //2bytes Write {0x8908,0x0082,4}, //2bytes Write {0x890A,0x10E9,4}, //2bytes Write {0x890C,0x0081,4}, //2bytes Write {0x890E,0xBA08,4}, //2bytes Write {0x8910,0xB9A0,4}, //2bytes Write {0x8912,0x18E9,4}, //2bytes Write {0x8914,0x0042,4}, //2bytes Write {0x8916,0xD12E,4}, //2bytes Write {0x8918,0x7A65,4}, //2bytes Write {0x891A,0x18EC,4}, //2bytes Write {0x891C,0x0084,4}, //2bytes Write {0x891E,0xDB51,4}, //2bytes Write {0x8920,0x8900,4}, //2bytes Write {0x8922,0x19B2,4}, //2bytes Write {0x8924,0x00C2,4}, //2bytes Write {0x8926,0xDA08,4}, //2bytes Write {0x8928,0xDB52,4}, //2bytes Write {0x892A,0xB8A6,4}, //2bytes Write {0x892C,0xA900,4}, //2bytes Write {0x892E,0xD8F0,4}, //2bytes Write {0x8930,0x19B1,4}, //2bytes Write {0x8932,0x0002,4}, //2bytes Write {0x8934,0x19B5,4}, //2bytes Write {0x8936,0x0002,4}, //2bytes Write {0x8938,0xD855,4}, //2bytes Write {0x893A,0x19B6,4}, //2bytes Write {0x893C,0x0002,4}, //2bytes Write {0x893E,0xD856,4}, //2bytes Write {0x8940,0x19B7,4}, //2bytes Write {0x8942,0x0002,4}, //2bytes Write {0x8944,0xD896,4}, //2bytes Write {0x8946,0x19B8,4}, //2bytes Write {0x8948,0x0004,4}, //2bytes Write {0x894A,0xD814,4}, //2bytes Write {0x894C,0x19BA,4}, //2bytes Write {0x894E,0x0004,4}, //2bytes Write {0x8950,0xD805,4}, //2bytes Write {0x8952,0xB111,4}, //2bytes Write {0x8954,0x19B0,4}, //2bytes Write {0x8956,0x0082,4}, //2bytes Write {0x8958,0x19B3,4}, //2bytes Write {0x895A,0x00C2,4}, //2bytes Write {0x895C,0x19B4,4}, //2bytes Write {0x895E,0x0082,4}, //2bytes Write {0x8960,0xD11C,4}, //2bytes Write {0x8962,0x70C9,4}, //2bytes Write {0x8964,0x0E8E,4}, //2bytes Write {0x8966,0x06A4,4}, //2bytes Write {0x8968,0xDA2C,4}, //2bytes Write {0x896A,0xD01B,4}, //2bytes Write {0x896C,0xA503,4}, //2bytes Write {0x896E,0xD01B,4}, //2bytes Write {0x8970,0x014D,4}, //2bytes Write {0x894C,0x19BA,4}, //2bytes Write {0x894E,0x0004,4}, //2bytes Write {0x8950,0xD805,4}, //2bytes Write {0x8952,0xB111,4}, //2bytes Write {0x8954,0x19B0,4}, //2bytes Write {0x8956,0x0082,4}, //2bytes Write {0x8958,0x19B3,4}, //2bytes Write {0x895A,0x00C2,4}, //2bytes Write {0x895C,0x19B4,4}, //2bytes Write {0x895E,0x0082,4}, //2bytes Write {0x8960,0xD11C,4}, //2bytes Write {0x8962,0x70C9,4}, //2bytes Write {0x8964,0x0E8E,4}, //2bytes Write {0x8966,0x06A4,4}, //2bytes Write {0x8968,0xDA2C,4}, //2bytes Write {0x896A,0xD01B,4}, //2bytes Write {0x896C,0xA503,4}, //2bytes Write {0x896E,0xD01B,4}, //2bytes Write {0x8970,0x014D,4}, //2bytes Write {0x894C,0x19BA,4}, //2bytes Write {0x894E,0x0004,4}, //2bytes Write {0x8950,0xD805,4}, //2bytes Write {0x8952,0xB111,4}, //2bytes Write {0x8954,0x19B0,4}, //2bytes Write {0x8956,0x0082,4}, //2bytes Write {0x8958,0x19B3,4}, //2bytes Write {0x895A,0x00C2,4}, //2bytes Write {0x895C,0x19B4,4}, //2bytes Write {0x895E,0x0082,4}, //2bytes Write {0x8960,0xD11C,4}, //2bytes Write {0x8962,0x70C9,4}, //2bytes Write {0x8964,0x0E8E,4}, //2bytes Write {0x8966,0x06A4,4}, //2bytes Write {0x8968,0xDA2C,4}, //2bytes Write {0x896A,0xD01B,4}, //2bytes Write {0x896C,0xA503,4}, //2bytes Write {0x896E,0xD01B,4}, //2bytes Write {0x8970,0x014D,4}, //2bytes Write {0x894C,0x19BA,4}, //2bytes Write {0x894E,0x0004,4}, //2bytes Write {0x8950,0xD805,4}, //2bytes Write {0x8952,0xB111,4}, //2bytes Write {0x8954,0x19B0,4}, //2bytes Write {0x8956,0x0082,4}, //2bytes Write {0x8958,0x19B3,4}, //2bytes Write {0x895A,0x00C2,4}, //2bytes Write {0x895C,0x19B4,4}, //2bytes Write {0x895E,0x0082,4}, //2bytes Write {0x8960,0xD11C,4}, //2bytes Write {0x8962,0x70C9,4}, //2bytes Write {0x8964,0x0E8E,4}, //2bytes Write {0x8966,0x06A4,4}, //2bytes Write {0x8968,0xDA2C,4}, //2bytes Write {0x896A,0xD01B,4}, //2bytes Write {0x896C,0xA503,4}, //2bytes Write {0x896E,0xD01B,4}, //2bytes Write {0x8970,0x014D,4}, //2bytes Write {0x894C,0x19BA,4}, //2bytes Write {0x894E,0x0004,4}, //2bytes Write {0x8950,0xD805,4}, //2bytes Write {0x8952,0xB111,4}, //2bytes Write {0x8954,0x19B0,4}, //2bytes Write {0x8956,0x0082,4}, //2bytes Write {0x8958,0x19B3,4}, //2bytes Write {0x895A,0x00C2,4}, //2bytes Write {0x895C,0x19B4,4}, //2bytes Write {0x895E,0x0082,4}, //2bytes Write {0x8960,0xD11C,4}, //2bytes Write {0x8962,0x70C9,4}, //2bytes Write {0x8964,0x0E8E,4}, //2bytes Write {0x8966,0x06A4,4}, //2bytes Write {0x8968,0xDA2C,4}, //2bytes Write {0x896A,0xD01B,4}, //2bytes Write {0x896C,0xA503,4}, //2bytes Write {0x896E,0xD01B,4}, //2bytes Write {0x8970,0x014D,4}, //2bytes Write {0x8972,0x06E4,4}, //2bytes Write {0x8974,0xA0C0,4}, //2bytes Write {0x8976,0x78E0,4}, //2bytes Write {0x8978,0xC0F1,4}, //2bytes Write {0x897A,0xC5E1,4}, //2bytes Write {0x897C,0xD018,4}, //2bytes Write {0x897E,0xD219,4}, //2bytes Write {0x8980,0xD119,4}, //2bytes Write {0x8982,0xA040,4}, //2bytes Write {0x8984,0x890C,4}, //2bytes Write {0x8986,0x0811,4}, //2bytes Write {0x8988,0x01DE,4}, //2bytes Write {0x898A,0xB8A7,4}, //2bytes Write {0x898C,0x8243,4}, //2bytes Write {0x898E,0xA90C,4}, //2bytes Write {0x8972,0x06E4,4}, //2bytes Write {0x8974,0xA0C0,4}, //2bytes Write {0x8976,0x78E0,4}, //2bytes Write {0x8978,0xC0F1,4}, //2bytes Write {0x897A,0xC5E1,4}, //2bytes Write {0x897C,0xD018,4}, //2bytes Write {0x897E,0xD219,4}, //2bytes Write {0x8980,0xD119,4}, //2bytes Write {0x8982,0xA040,4}, //2bytes Write {0x8984,0x890C,4}, //2bytes Write {0x8986,0x0811,4}, //2bytes Write {0x8988,0x01DE,4}, //2bytes Write {0x898A,0xB8A7,4}, //2bytes Write {0x898C,0x8243,4}, //2bytes Write {0x898E,0xA90C,4}, //2bytes Write {0x8972,0x06E4,4}, //2bytes Write {0x8974,0xA0C0,4}, //2bytes Write {0x8976,0x78E0,4}, //2bytes Write {0x8978,0xC0F1,4}, //2bytes Write {0x897A,0xC5E1,4}, //2bytes Write {0x897C,0xD018,4}, //2bytes Write {0x897E,0xD219,4}, //2bytes Write {0x8980,0xD119,4}, //2bytes Write {0x8982,0xA040,4}, //2bytes Write {0x8984,0x890C,4}, //2bytes Write {0x8986,0x0811,4}, //2bytes Write {0x8988,0x01DE,4}, //2bytes Write {0x898A,0xB8A7,4}, //2bytes Write {0x898C,0x8243,4}, //2bytes Write {0x898E,0xA90C,4}, //2bytes Write {0x8972,0x06E4,4}, //2bytes Write {0x8974,0xA0C0,4}, //2bytes Write {0x8976,0x78E0,4}, //2bytes Write {0x8978,0xC0F1,4}, //2bytes Write {0x897A,0xC5E1,4}, //2bytes Write {0x897E,0xD219,4}, //2bytes Write {0x8980,0xD119,4}, //2bytes Write {0x8982,0xA040,4}, //2bytes Write {0x8984,0x890C,4}, //2bytes Write {0x8986,0x0811,4}, //2bytes Write {0x8988,0x01DE,4}, //2bytes Write {0x898A,0xB8A7,4}, //2bytes Write {0x898C,0x8243,4}, //2bytes Write {0x898E,0xA90C,4}, //2bytes Write {0x8972,0x06E4,4}, //2bytes Write {0x8974,0xA0C0,4}, //2bytes Write {0x8976,0x78E0,4}, //2bytes Write {0x8978,0xC0F1,4}, //2bytes Write {0x897A,0xC5E1,4}, //2bytes Write {0x897C,0xD018,4}, //2bytes Write {0x897E,0xD219,4}, //2bytes Write {0x8980,0xD119,4}, //2bytes Write {0x8982,0xA040,4}, //2bytes Write {0x8984,0x890C,4}, //2bytes Write {0x8986,0x0811,4}, //2bytes Write {0x8988,0x01DE,4}, //2bytes Write {0x898A,0xB8A7,4}, //2bytes Write {0x898C,0x8243,4}, //2bytes Write {0x898E,0xA90C,4}, //2bytes Write {0x8990,0x7A60,4}, //2bytes Write {0x8992,0x890C,4}, //2bytes Write {0x8994,0xD509,4}, //2bytes Write {0x8996,0xD115,4}, //2bytes Write {0x8998,0x2555,4}, //2bytes Write {0x899A,0x15C0,4}, //2bytes Write {0x899C,0x0E56,4}, //2bytes Write {0x899E,0x06A4,4}, //2bytes Write {0x89A0,0xDA38,4}, //2bytes Write {0x89A2,0xD013,4}, //2bytes Write {0x89A4,0x2555,4}, //2bytes Write {0x89A6,0x15C1,4}, //2bytes Write {0x89A8,0x1D80,4}, //2bytes Write {0x89AA,0x1000,4}, //2bytes Write {0x89AC,0xD011,4}, //2bytes Write {0x89AE,0x0119,4}, //2bytes Write {0x89B0,0x06E4,4}, //2bytes Write {0x89B2,0xA020,4}, //2bytes Write {0x89B4,0x0000,4}, //2bytes Write {0x89B6,0xF370,4}, //2bytes Write {0x89B8,0xFF80,4}, //2bytes Write {0x89BA,0x0F0C,4}, //2bytes Write {0x89BC,0xFF80,4}, //2bytes Write {0x89BE,0x0E10,4}, //2bytes Write {0x89C0,0x8000,4}, //2bytes Write {0x89C2,0x0038,4}, //2bytes Write {0x89C4,0xFF80,4}, //2bytes Write {0x89C6,0x0250,4}, //2bytes Write {0x89C8,0xFF80,4}, //2bytes Write {0x89CA,0x041C,4}, //2bytes Write {0x89CC,0xFF80,4}, //2bytes Write {0x89CE,0x0314,4}, //2bytes Write {0x89D0,0x0000,4}, //2bytes Write {0x89D2,0xF444,4}, //2bytes Write {0x89D4,0xFF80,4}, //2bytes Write {0x89D6,0x0CA8,4}, //2bytes Write {0x89D8,0x8000,4}, //2bytes Write {0x89DA,0x009C,4}, //2bytes Write {0x89DC,0x8000,4}, //2bytes Write {0x89DE,0x0008,4}, //2bytes Write {0x89E0,0xFF80,4}, //2bytes Write {0x89E2,0x0EFC,4}, //2bytes Write {0x89E4,0xFF80,4}, //2bytes Write {0x89E6,0x0174,4}, //2bytes Write {0x89E8,0x0000,4}, //2bytes Write {0x89EA,0xF3BC,4}, //2bytes Write {0x89EC,0xFF80,4}, //2bytes Write {0x89EE,0x0C78,4}, //2bytes Write {0x89F0,0x8000,4}, //2bytes Write {0x89F2,0x008C,4}, //2bytes Write {0x89F4,0xC0F1,4}, //2bytes Write {0x89F6,0x085A,4}, //2bytes Write {0x89F8,0x06E4,4}, //2bytes Write {0x89FA,0x7098,4}, //2bytes Write {0x89FC,0xD0F5,4}, //2bytes Write {0x89FE,0x8021,4}, //2bytes Write {0x8A00,0x1105,4}, //2bytes Write {0x8A02,0x0086,4}, //2bytes Write {0x8A04,0x2140,4}, //2bytes Write {0x8A06,0x0185,4}, //2bytes Write {0x8A08,0x890E,4}, //2bytes Write {0x8A0A,0x2642,4}, //2bytes Write {0x8A0C,0x004E,4}, //2bytes Write {0x8A0E,0x7ECD,4}, //2bytes Write {0x8A10,0xE886,4}, //2bytes Write {0x8A12,0xD801,4}, //2bytes Write {0x8A14,0xA90E,4}, //2bytes Write {0x8A16,0x2140,4}, //2bytes Write {0x8A18,0x0600,4}, //2bytes Write {0x8A1A,0xA105,4}, //2bytes Write {0x8A1C,0x8904,4}, //2bytes Write {0x8A1E,0xE080,4}, //2bytes Write {0x8A20,0x20CA,4}, //2bytes Write {0x8A22,0x0101,4}, //2bytes Write {0x8A24,0xF2BE,4}, //2bytes Write {0x8A26,0xD2EC,4}, //2bytes Write {0x8A28,0x8A02,4}, //2bytes Write {0x8A2A,0x8A63,4}, //2bytes Write {0x8A2C,0xB808,4}, //2bytes Write {0x8A2E,0x7865,4}, //2bytes Write {0x8A30,0x08EB,4}, //2bytes Write {0x8A32,0x009E,4}, //2bytes Write {0x8A34,0x8A66,4}, //2bytes Write {0x8A36,0x890C,4}, //2bytes Write {0x8A38,0xE382,4}, //2bytes Write {0x8A3A,0x20CC,4}, //2bytes Write {0x8A3C,0x8021,4}, //2bytes Write {0x8A3E,0x20CC,4}, //2bytes Write {0x8A40,0x8062,4}, //2bytes Write {0x8A42,0xF46D,4}, //2bytes Write {0x8A44,0x8A00,4}, //2bytes Write {0x8A46,0x8A61,4}, //2bytes Write {0x8A48,0xB808,4}, //2bytes Write {0x8AB0,0x0012,4}, //2bytes Write {0x8AB2,0xA165,4}, //2bytes Write {0x8AB4,0xF01A,4}, //2bytes Write {0x8AB6,0x8904,4}, //2bytes Write {0x8AB8,0x75D1,4}, //2bytes Write {0x8ABA,0xA905,4}, //2bytes Write {0x8ABC,0xD801,4}, //2bytes Write {0x8ABE,0x20CA,4}, //2bytes Write {0x8AC0,0x00A1,4}, //2bytes Write {0x8AC2,0xAA06,4}, //2bytes Write {0x8AC4,0xDE00,4}, //2bytes Write {0x8AC6,0xA9CC,4}, //2bytes Write {0x8AC8,0x8A00,4}, //2bytes Write {0x8ACA,0x8AE1,4}, //2bytes Write {0x8ACC,0xB808,4}, //2bytes Write {0x8ACE,0x78E5,4}, //2bytes Write {0x8AD0,0xB8A3,4}, //2bytes Write {0x8AD2,0x2841,4}, //2bytes Write {0x8AD4,0x020F,4}, //2bytes Write {0x8AB0,0x0012,4}, //2bytes Write {0x8AB0,0x0012,4}, //2bytes Write {0x8AB2,0xA165,4}, //2bytes Write {0x8AB4,0xF01A,4}, //2bytes Write {0x8AB6,0x8904,4}, //2bytes Write {0x8AB8,0x75D1,4}, //2bytes Write {0x8ABA,0xA905,4}, //2bytes Write {0x8ABC,0xD801,4}, //2bytes Write {0x8ABE,0x20CA,4}, //2bytes Write {0x8AC0,0x00A1,4}, //2bytes Write {0x8AC2,0xAA06,4}, //2bytes Write {0x8AC4,0xDE00,4}, //2bytes Write {0x8AC6,0xA9CC,4}, //2bytes Write {0x8AC8,0x8A00,4}, //2bytes Write {0x8ACA,0x8AE1,4}, //2bytes Write {0x8ACC,0xB808,4}, //2bytes Write {0x8ACE,0x78E5,4}, //2bytes Write {0x8AD0,0xB8A3,4}, //2bytes Write {0x8AD2,0x2841,4}, //2bytes Write {0x8AD4,0x020F,4}, //2bytes Write {0x8AB2,0xA165,4}, //2bytes Write {0x8AB4,0xF01A,4}, //2bytes Write {0x8AB6,0x8904,4}, //2bytes Write {0x8AB8,0x75D1,4}, //2bytes Write {0x8ABA,0xA905,4}, //2bytes Write {0x8ABC,0xD801,4}, //2bytes Write {0x8ABE,0x20CA,4}, //2bytes Write {0x8AC0,0x00A1,4}, //2bytes Write {0x8AC2,0xAA06,4}, //2bytes Write {0x8AC4,0xDE00,4}, //2bytes Write {0x8AC6,0xA9CC,4}, //2bytes Write {0x8AC8,0x8A00,4}, //2bytes Write {0x8ACA,0x8AE1,4}, //2bytes Write {0x8ACC,0xB808,4}, //2bytes Write {0x8ACE,0x78E5,4}, //2bytes Write {0x8AD0,0xB8A3,4}, //2bytes Write {0x8AD2,0x2841,4}, //2bytes Write {0x8AD4,0x020F,4}, //2bytes Write {0x8AB0,0x0012,4}, //2bytes Write {0x8AB2,0xA165,4}, //2bytes Write {0x8AB4,0xF01A,4}, //2bytes Write {0x8AB6,0x8904,4}, //2bytes Write {0x8AB8,0x75D1,4}, //2bytes Write {0x8ABA,0xA905,4}, //2bytes Write {0x8ABC,0xD801,4}, //2bytes Write {0x8ABE,0x20CA,4}, //2bytes Write {0x8AC0,0x00A1,4}, //2bytes Write {0x8AC2,0xAA06,4}, //2bytes Write {0x8AC4,0xDE00,4}, //2bytes Write {0x8AC6,0xA9CC,4}, //2bytes Write {0x8AC8,0x8A00,4}, //2bytes Write {0x8ACA,0x8AE1,4}, //2bytes Write {0x8ACC,0xB808,4}, //2bytes Write {0x8ACE,0x78E5,4}, //2bytes Write {0x8AD0,0xB8A3,4}, //2bytes Write {0x8AD2,0x2841,4}, //2bytes Write {0x8AD4,0x020F,4}, //2bytes Write {0x8A4A,0x7865,4}, //2bytes Write {0x8A4C,0xB883,4}, //2bytes Write {0x8A4E,0xB88C,4}, //2bytes Write {0x8A50,0x2841,4}, //2bytes Write {0x8A52,0x0203,4}, //2bytes Write {0x8A54,0xAA60,4}, //2bytes Write {0x8A56,0xAA01,4}, //2bytes Write {0x8A58,0x890C,4}, //2bytes Write {0x8A5A,0xE886,4}, //2bytes Write {0x8A5C,0x190D,4}, //2bytes Write {0x8A5E,0x0102,4}, //2bytes Write {0x8A60,0xD801,4}, //2bytes Write {0x8A62,0xA90C,4}, //2bytes Write {0x8A64,0x0E39,4}, //2bytes Write {0x8A66,0x1012,4}, //2bytes Write {0x8A68,0x70C9,4}, //2bytes Write {0x8A6A,0x780D,4}, //2bytes Write {0x8A6C,0xE001,4}, //2bytes Write {0x8A6E,0x896D,4}, //2bytes Write {0x8A70,0x709F,4}, //2bytes Write {0x8A72,0x75C9,4}, //2bytes Write {0x8A74,0x20A8,4}, //2bytes Write {0x8A76,0x04C0,4}, //2bytes Write {0x8A78,0x77CF,4}, //2bytes Write {0x8A7A,0xFF80,4}, //2bytes Write {0x8A7C,0x0158,4}, //2bytes Write {0x8A7E,0x8FE4,4}, //2bytes Write {0x8A80,0x2532,4}, //2bytes Write {0x8A82,0x0340,4}, //2bytes Write {0x8A84,0x70F1,4}, //2bytes Write {0x8A86,0x23CC,4}, //2bytes Write {0x8A88,0x800B,4}, //2bytes Write {0x8A8A,0xF68D,4}, //2bytes Write {0x8A8C,0x0B2B,4}, //2bytes Write {0x8A8E,0x0003,4}, //2bytes Write {0x8A90,0x8905,4}, //2bytes Write {0x8A92,0xBD61,4}, //2bytes Write {0x8A94,0x7DAD,4}, //2bytes Write {0x8A96,0xB861,4}, //2bytes Write {0x8A98,0xA905,4}, //2bytes Write {0x8A9A,0x76A9,4}, //2bytes Write {0x8A9C,0x7088,4}, //2bytes Write {0x8A9E,0x75C9,4}, //2bytes Write {0x8AA0,0xF024,4}, //2bytes Write {0x8AA2,0xDB02,4}, //2bytes Write {0x8AA4,0xAA66,4}, //2bytes Write {0x8AA6,0x8965,4}, //2bytes Write {0x8AA8,0xBB61,4}, //2bytes Write {0x8AAA,0xA965,4}, //2bytes Write {0x8AAC,0x8165,4}, //2bytes Write {0x8AAE,0x1B01,4}, //2bytes Write {0x8AB0,0x0012,4}, //2bytes Write {0x8AB2,0xA165,4}, //2bytes Write {0x8AB4,0xF01A,4}, //2bytes Write {0x8AB6,0x8904,4}, //2bytes Write {0x8AB8,0x75D1,4}, //2bytes Write {0x8ABA,0xA905,4}, //2bytes Write {0x8ABC,0xD801,4}, //2bytes Write {0x8ABE,0x20CA,4}, //2bytes Write {0x8AC0,0x00A1,4}, //2bytes Write {0x8AC2,0xAA06,4}, //2bytes Write {0x8AC4,0xDE00,4}, //2bytes Write {0x8AC6,0xA9CC,4}, //2bytes Write {0x8AC8,0x8A00,4}, //2bytes Write {0x8ACA,0x8AE1,4}, //2bytes Write {0x8ACC,0xB808,4}, //2bytes Write {0x8ACE,0x78E5,4}, //2bytes Write {0x8AD0,0xB8A3,4}, //2bytes Write {0x8AD2,0x2841,4}, //2bytes Write {0x8AD4,0x020F,4}, //2bytes Write {0x8AD6,0xAAE0,4}, //2bytes Write {0x8AD8,0xAA01,4}, //2bytes Write {0x8ADA,0x8105,4}, //2bytes Write {0x8ADC,0xA860,4}, //2bytes Write {0x8ADE,0x2140,4}, //2bytes Write {0x8AE0,0x0600,4}, //2bytes Write {0x8AE2,0xA105,4}, //2bytes Write {0x8AE4,0x7068,4}, //2bytes Write {0x8AE6,0xA9CE,4}, //2bytes Write {0x8AE8,0x0DB9,4}, //2bytes Write {0x8AEA,0x1013,4}, //2bytes Write {0x8AEC,0x8964,4}, //2bytes Write {0x8AEE,0x890D,4}, //2bytes Write {0x8AF0,0xA965,4}, //2bytes Write {0x8AF2,0xDB01,4}, //2bytes Write {0x8AF4,0xAA66,4}, //2bytes Write {0x8AF6,0xDB00,4}, //2bytes Write {0x8AF8,0xA96C,4}, //2bytes Write {0x8AFA,0x8AA0,4}, //2bytes Write {0x8AFC,0x8AC1,4}, //2bytes Write {0x8AFE,0xBD08,4}, //2bytes Write {0x8B00,0x7DC5,4}, //2bytes Write {0x8B02,0xBDA3,4}, //2bytes Write {0x8B04,0x2D41,4}, //2bytes Write {0x8B06,0x120C,4}, //2bytes Write {0x8B08,0xAA80,4}, //2bytes Write {0x8B0A,0xAAA1,4}, //2bytes Write {0x8B0C,0x8145,4}, //2bytes Write {0x8B0E,0xAA00,4}, //2bytes Write {0x8B10,0x2140,4}, //2bytes Write {0x8B12,0x0602,4}, //2bytes Write {0x8B14,0xA145,4}, //2bytes Write {0x8B16,0x7268,4}, //2bytes Write {0x8B18,0xF043,4}, //2bytes Write {0x8B1A,0x0E0B,4}, //2bytes Write {0x8B1C,0x1013,4}, //2bytes Write {0x8B1E,0x7088,4}, //2bytes Write {0x8B20,0xF022,4}, //2bytes Write {0x8B22,0x73C9,4}, //2bytes Write {0x8B24,0x7B6D,4}, //2bytes Write {0x8B26,0xE301,4}, //2bytes Write {0x8B28,0x89A5,4}, //2bytes Write {0x8B2A,0xF003,4}, //2bytes Write {0x8B2C,0x75D8,4}, //2bytes Write {0x8B2E,0xD7AB,4}, //2bytes Write {0x8B30,0x8FE4,4}, //2bytes Write {0x8B32,0x2532,4}, //2bytes Write {0x8B34,0x0380,4}, //2bytes Write {0x8B36,0x081B,4}, //2bytes Write {0x8B38,0x03C2,4}, //2bytes Write {0x8B3A,0x2642,4}, //2bytes Write {0x8B3C,0x004D,4}, //2bytes Write {0x8B3E,0x7DAF,4}, //2bytes Write {0x8B40,0xBB61,4}, //2bytes Write {0x8B42,0xBE61,4}, //2bytes Write {0x8B44,0x0BE9,4}, //2bytes Write {0x8B46,0x8075,4}, //2bytes Write {0x8B48,0x7ECD,4}, //2bytes Write {0x8B4A,0xA9A5,4}, //2bytes Write {0x8B4C,0xF1E9,4}, //2bytes Write {0x8B4E,0xA9A5,4}, //2bytes Write {0x8B50,0x8A66,4}, //2bytes Write {0x8B52,0xBB61,4}, //2bytes Write {0x8B54,0xAA66,4}, //2bytes Write {0x8B56,0x8965,4}, //2bytes Write {0x8B58,0xBB61,4}, //2bytes Write {0x8B5A,0xA965,4}, //2bytes Write {0x8B5C,0x8165,4}, //2bytes Write {0x8B5E,0x1B01,4}, //2bytes Write {0x8B60,0x0012,4}, //2bytes Write {0x8B62,0xA165,4}, //2bytes Write {0x8B64,0x0E3D,4}, //2bytes Write {0x8B66,0x1013,4}, //2bytes Write {0x8B6A,0xA965,4}, //2bytes Write {0x8B6C,0x8A60,4}, //2bytes Write {0x8B6E,0x8AA1,4}, //2bytes Write {0x8B70,0xBB08,4}, //2bytes Write {0x8B72,0x7BA5,4}, //2bytes Write {0x8B74,0xBBA3,4}, //2bytes Write {0x8B76,0x2B41,4}, //2bytes Write {0x8B78,0x020D,4}, //2bytes Write {0x8B7A,0xAAA0,4}, //2bytes Write {0x8B7C,0xAA61,4}, //2bytes Write {0x8B7E,0x8165,4}, //2bytes Write {0x8B80,0x1B01,4}, //2bytes Write {0x8B82,0x0012,4}, //2bytes Write {0x8B84,0xA165,4}, //2bytes Write {0x8B86,0x8A62,4}, //2bytes Write {0x8B88,0x8AA3,4}, //2bytes Write {0x8B8A,0xBB08,4}, //2bytes Write {0x8B8C,0x7BA5,4}, //2bytes Write {0x8B8E,0x0B15,4}, //2bytes Write {0x8B90,0x009F,4}, //2bytes Write {0x8B92,0x894E,4}, //2bytes Write {0x8B94,0xEA06,4}, //2bytes Write {0x8B96,0x2140,4}, //2bytes Write {0x8B98,0x0602,4}, //2bytes Write {0x8B9A,0xA145,4}, //2bytes Write {0x8B9C,0xDA00,4}, //2bytes Write {0x8B9E,0xA94E,4}, //2bytes Write {0x8BA0,0x0715,4}, //2bytes Write {0x8BA2,0x0684,4}, //2bytes Write {0x8BA4,0xC0F1,4}, //2bytes Write {0x8BA6,0x0EA2,4}, //2bytes Write {0x8BA8,0x0684,4}, //2bytes Write {0x8BAA,0xD68C,4}, //2bytes Write {0x8BAC,0x7508,4}, //2bytes Write {0x8BAE,0xD18A,4}, //2bytes Write {0x8BB0,0x8E01,4}, //2bytes Write {0x8BB2,0x1146,4}, //2bytes Write {0x8BB4,0x0082,4}, //2bytes Write {0x8BB6,0x2046,4}, //2bytes Write {0x8BB8,0x00C0,4}, //2bytes Write {0x8BBA,0xAE01,4}, //2bytes Write {0x8BBC,0x1145,4}, //2bytes Write {0x8BBE,0x0080,4}, //2bytes Write {0x8BC0,0xB808,4}, //2bytes Write {0x8BC2,0x7845,4}, //2bytes Write {0x8BC4,0x0817,4}, //2bytes Write {0x8BC6,0x001E,4}, //2bytes Write {0x8BC8,0x8900,4}, //2bytes Write {0x8BCA,0x8941,4}, //2bytes Write {0x8BCC,0xB808,4}, //2bytes Write {0x8BCE,0x7845,4}, //2bytes Write {0x8BD0,0x080B,4}, //2bytes Write {0x8BD2,0x00DE,4}, //2bytes Write {0x8BD4,0x70A9,4}, //2bytes Write {0x8BD6,0xFF88,4}, //2bytes Write {0x8BD8,0x7508,4}, //2bytes Write {0x8BDA,0x1604,4}, //2bytes Write {0x8BDC,0x1090,4}, //2bytes Write {0x8BDE,0x0D93,4}, //2bytes Write {0x8BE0,0x1400,4}, //2bytes Write {0x8BE2,0x8EEA,4}, //2bytes Write {0x8BE4,0x8E0B,4}, //2bytes Write {0x8BE6,0x214A,4}, //2bytes Write {0x8BE8,0x2040,4}, //2bytes Write {0x8BEA,0x8E2D,4}, //2bytes Write {0x8BEC,0xBF08,4}, //2bytes Write {0x8BEE,0x7F05,4}, //2bytes Write {0x8BF0,0x8E0C,4}, //2bytes Write {0x8BF2,0xB808,4}, //2bytes Write {0x8BF4,0x7825,4}, //2bytes Write {0x8BF6,0x7710,4}, //2bytes Write {0x8BF8,0x21C2,4}, //2bytes Write {0x8BFA,0x244C,4}, //2bytes Write {0x8BFC,0x081D,4}, //2bytes Write {0x8BFE,0x03E3,4}, //2bytes Write {0x8C00,0xD9FF,4}, //2bytes Write {0x8C02,0x2702,4}, //2bytes Write {0x8C04,0x1002,4}, //2bytes Write {0x8C06,0x2A05,4}, //2bytes Write {0x8C08,0x037E,4}, //2bytes Write {0x8C0A,0x0F1E,4}, //2bytes Write {0x8C0C,0x06A4,4}, //2bytes Write {0x8C0E,0x702F,4}, //2bytes Write {0x8C10,0x7810,4}, //2bytes Write {0x8C12,0x7F02,4}, //2bytes Write {0x8C14,0x7FF0,4}, //2bytes Write {0x8C16,0xF00B,4}, //2bytes Write {0x8C18,0x78E2,4}, //2bytes Write {0x8C1A,0x2805,4}, //2bytes Write {0x8C1C,0x037E,4}, //2bytes Write {0x8C1E,0x0F0A,4}, //2bytes Write {0x8C20,0x06A4,4}, //2bytes Write {0x8C22,0x702F,4}, //2bytes Write {0x8C24,0x7810,4}, //2bytes Write {0x8C26,0x671F,4}, //2bytes Write {0x8C28,0x7FF0,4}, //2bytes Write {0x8C2A,0x8E08,4}, //2bytes Write {0x8C2C,0xD16C,4}, //2bytes Write {0x8C2E,0x7FEF,4}, //2bytes Write {0x8C30,0xBF06,4}, //2bytes Write {0x8C32,0xB8C3,4}, //2bytes Write {0x8C34,0x78E5,4}, //2bytes Write {0x8C36,0xB88F,4}, //2bytes Write {0x8C38,0x1908,4}, //2bytes Write {0x8C3A,0x0024,4}, //2bytes Write {0x8C3C,0x2841,4}, //2bytes Write {0x8C3E,0x0201,4}, //2bytes Write {0x8C40,0x1E26,4}, //2bytes Write {0x8C42,0x1042,4}, //2bytes Write {0x8C44,0x0D15,4}, //2bytes Write {0x8C46,0x1423,4}, //2bytes Write {0x8C48,0x1E27,4}, //2bytes Write {0x8C4A,0x1002,4}, //2bytes Write {0x8C4C,0x214C,4}, //2bytes Write {0x8C4E,0xA000,4}, //2bytes Write {0x8C50,0x214A,4}, //2bytes Write {0x8C52,0x2040,4}, //2bytes Write {0x8C54,0x21C2,4}, //2bytes Write {0x8C56,0x2442,4}, //2bytes Write {0x8C58,0x8E21,4}, //2bytes Write {0x8C5A,0x214F,4}, //2bytes Write {0x8C5C,0x0040,4}, //2bytes Write {0x8C5E,0x090F,4}, //2bytes Write {0x8C60,0x2010,4}, //2bytes Write {0x8C62,0x2145,4}, //2bytes Write {0x8C64,0x0181,4}, //2bytes Write {0x8C66,0xAE21,4}, //2bytes Write {0x8C68,0xF003,4}, //2bytes Write {0x8C6A,0xB8A2,4}, //2bytes Write {0x8C6C,0xAE01,4}, //2bytes Write {0x8C6E,0x0AA2,4}, //2bytes Write {0x8C70,0xFFE3,4}, //2bytes Write {0x8C72,0x70A9,4}, //2bytes Write {0x8C74,0x0631,4}, //2bytes Write {0x8C76,0x0684,4}, //2bytes Write {0x8C78,0xC0F1,4}, //2bytes Write {0x8C7A,0x0DDA,4}, //2bytes Write {0x8C7C,0x0684,4}, //2bytes Write {0x8C7E,0xD556,4}, //2bytes Write {0x8C80,0x8D00,4}, //2bytes Write {0x8C82,0x8D21,4}, //2bytes Write {0x8C84,0xB808,4}, //2bytes Write {0x8C86,0x7825,4}, //2bytes Write {0x8C88,0x0DFE,4}, //2bytes Write {0x8C8A,0x0164,4}, //2bytes Write {0x8C8C,0x2044,4}, //2bytes Write {0x8C8E,0x020E,4}, //2bytes Write {0x8C90,0x8D20,4}, //2bytes Write {0x8C92,0x8D41,4}, //2bytes Write {0x8C94,0xB908,4}, //2bytes Write {0x8C96,0x7945,4}, //2bytes Write {0x8C98,0x79C5,4}, //2bytes Write {0x8C9A,0x2941,4}, //2bytes Write {0x8C9C,0x0202,4}, //2bytes Write {0x8C9E,0xAD40,4}, //2bytes Write {0x8CA0,0x061D,4}, //2bytes Write {0x8CA2,0x06A4,4}, //2bytes Write {0x8CA4,0xAD21,4}, //2bytes Write {0x8CA6,0x78E0,4}, //2bytes Write {0x8CA8,0xC0F1,4}, //2bytes Write {0x8CAA,0x0DAA,4}, //2bytes Write {0x8CAC,0x0684,4}, //2bytes Write {0x8CAE,0x1748,4}, //2bytes Write {0x8CB0,0xF60E,4}, //2bytes Write {0x8CB2,0x8E01,4}, //2bytes Write {0x8CB4,0xB8A4,4}, //2bytes Write {0x8CB6,0xAE01,4}, //2bytes Write {0x8CB8,0x8E09,4}, //2bytes Write {0x8CBA,0x2051,4}, //2bytes Write {0x8CBC,0x8000,4}, //2bytes Write {0x8CBE,0xF2A6,4}, //2bytes Write {0x8CC0,0x1741,4}, //2bytes Write {0x8CC2,0xF60D,4}, //2bytes Write {0x8CC4,0x153A,4}, //2bytes Write {0x8CC6,0x1080,4}, //2bytes Write {0x8CC8,0x153B,4}, //2bytes Write {0x8CCA,0x1081,4}, //2bytes Write {0x8CCC,0xB808,4}, //2bytes Write {0x8CCE,0x7825,4}, //2bytes Write {0x8CD0,0x16B8,4}, //2bytes Write {0x8CD2,0x1101,4}, //2bytes Write {0x8CD4,0x092B,4}, //2bytes Write {0x8CD6,0x0003,4}, //2bytes Write {0x8CD8,0x16B0,4}, //2bytes Write {0x8CDA,0x1082,4}, //2bytes Write {0x8CDC,0x1E3C,4}, //2bytes Write {0x8CDE,0x1082,4}, //2bytes Write {0x8CE0,0x16B1,4}, //2bytes Write {0x8CE2,0x1082,4}, //2bytes Write {0x8CE4,0x1E3D,4}, //2bytes Write {0x8CE6,0x1082,4}, //2bytes Write {0x8CE8,0x16B4,4}, //2bytes Write {0x8CEA,0x1082,4}, //2bytes Write {0x8CEC,0x1E3E,4}, //2bytes Write {0x8CEE,0x1082,4}, //2bytes Write {0x8CF0,0x16B5,4}, //2bytes Write {0x8CF2,0x1082,4}, //2bytes Write {0x8CF4,0x1E3F,4}, //2bytes Write {0x8CF6,0x1082,4}, //2bytes Write {0x8CF8,0x8E40,4}, //2bytes Write {0x8CFA,0xBAA6,4}, //2bytes Write {0x8CFC,0xAE40,4}, //2bytes Write {0x8CFE,0x0991,4}, //2bytes Write {0x8D00,0x0022,4}, //2bytes Write {0x8D02,0x16BA,4}, //2bytes Write {0x8D04,0x1102,4}, //2bytes Write {0x8D06,0x0A89,4}, //2bytes Write {0x8D08,0x0003,4}, //2bytes Write {0x8D0A,0x16B2,4}, //2bytes Write {0x8D0C,0x1084,4}, //2bytes Write {0x8D0E,0x0EDA,4}, //2bytes Write {0x8D10,0x0664,4}, //2bytes Write {0x8D12,0x16B0,4}, //2bytes Write {0x8D14,0x1083,4}, //2bytes Write {0x8D16,0x1E3C,4}, //2bytes Write {0x8D18,0x1002,4}, //2bytes Write {0x8D1A,0x153A,4}, //2bytes Write {0x8D1E,0x153B,4}, //2bytes Write {0x8D20,0x1081,4}, //2bytes Write {0x8D22,0x16B3,4}, //2bytes Write {0x8D24,0x1084,4}, //2bytes Write {0x8D26,0xB808,4}, //2bytes Write {0x8D28,0x7825,4}, //2bytes Write {0x8D2A,0x16B8,4}, //2bytes Write {0x8D2C,0x1101,4}, //2bytes Write {0x8D2E,0x16BA,4}, //2bytes Write {0x8D30,0x1102,4}, //2bytes Write {0x8D32,0x0EB6,4}, //2bytes Write {0x8D34,0x0664,4}, //2bytes Write {0x8D36,0x16B1,4}, //2bytes Write {0x8D38,0x1083,4}, //2bytes Write {0x8D3A,0x1E3D,4}, //2bytes Write {0x8D3C,0x1002,4}, //2bytes Write {0x8D3E,0x153A,4}, //2bytes Write {0x8D40,0x1080,4}, //2bytes Write {0x8D42,0x153B,4}, //2bytes Write {0x8D44,0x1081,4}, //2bytes Write {0x8D46,0x16B6,4}, //2bytes Write {0x8D48,0x1084,4}, //2bytes Write {0x8D4A,0xB808,4}, //2bytes Write {0x8D4C,0x7825,4}, //2bytes Write {0x8D4E,0x16B8,4}, //2bytes Write {0x8D50,0x1101,4}, //2bytes Write {0x8D52,0x16BA,4}, //2bytes Write {0x8D54,0x1102,4}, //2bytes Write {0x8D56,0x0E92,4}, //2bytes Write {0x8D58,0x0664,4}, //2bytes Write {0x8D5A,0x16B4,4}, //2bytes Write {0x8D5C,0x1083,4}, //2bytes Write {0x8D5E,0x1E3E,4}, //2bytes Write {0x8D60,0x1002,4}, //2bytes Write {0x8D62,0x153A,4}, //2bytes Write {0x8D64,0x1080,4}, //2bytes Write {0x8D66,0x153B,4}, //2bytes Write {0x8D68,0x1081,4}, //2bytes Write {0x8D6A,0x16B7,4}, //2bytes Write {0x8D6C,0x1084,4}, //2bytes Write {0x8D6E,0xB808,4}, //2bytes Write {0x8D70,0x7825,4}, //2bytes Write {0x8D72,0x16B8,4}, //2bytes Write {0x8D74,0x1101,4}, //2bytes Write {0x8D76,0x16BA,4}, //2bytes Write {0x8D78,0x1102,4}, //2bytes Write {0x8D7A,0x0E6E,4}, //2bytes Write {0x8D7C,0x0664,4}, //2bytes Write {0x8D7E,0x16B5,4}, //2bytes Write {0x8D80,0x1083,4}, //2bytes Write {0x8D82,0x1E3F,4}, //2bytes Write {0x8D84,0x1002,4}, //2bytes Write {0x8D86,0x8E00,4}, //2bytes Write {0x8D88,0xB8A6,4}, //2bytes Write {0x8D8A,0xAE00,4}, //2bytes Write {0x8D8C,0x153A,4}, //2bytes Write {0x8D8E,0x1081,4}, //2bytes Write {0x8D90,0x153B,4}, //2bytes Write {0x8D92,0x1080,4}, //2bytes Write {0x8D94,0xB908,4}, //2bytes Write {0x8D96,0x7905,4}, //2bytes Write {0x8D98,0x16BA,4}, //2bytes Write {0x8D9A,0x1100,4}, //2bytes Write {0x8D9C,0x086D,4}, //2bytes Write {0x8D9E,0x0042,4}, //2bytes Write {0x8DA0,0xD010,4}, //2bytes Write {0x8DA2,0x9E31,4}, //2bytes Write {0x8DA4,0x904D,4}, //2bytes Write {0x8DA6,0x0A41,4}, //2bytes Write {0x8DA8,0x0063,4}, //2bytes Write {0x8DAA,0x8E00,4}, //2bytes Write {0x8DAC,0x16B0,4}, //2bytes Write {0x8DAE,0x1081,4}, //2bytes Write {0x8DB0,0x1E3C,4}, //2bytes Write {0x8DB2,0x1042,4}, //2bytes Write {0x8DB4,0x16B1,4}, //2bytes Write {0x8DB6,0x1081,4}, //2bytes Write {0x8DB8,0x1E3D,4}, //2bytes Write {0x8DBA,0x1042,4}, //2bytes Write {0x8DBC,0x16B4,4}, //2bytes Write {0x8DBE,0x1081,4}, //2bytes Write {0x8DC0,0x1E3E,4}, //2bytes Write {0x8DC2,0x1042,4}, //2bytes Write {0x8DC4,0x16B5,4}, //2bytes Write {0x8DC6,0x1081,4}, //2bytes Write {0x8DC8,0x1E3F,4}, //2bytes Write {0x8DCA,0x1042,4}, //2bytes Write {0x8DCC,0xB886,4}, //2bytes Write {0x8DCE,0xF01D,4}, //2bytes Write {0x8DD0,0xFF80,4}, //2bytes Write {0x8DD2,0x0EF4,4}, //2bytes Write {0x8DD4,0xFF80,4}, //2bytes Write {0x8DD6,0x0290,4}, //2bytes Write {0x8DD8,0xFF80,4}, //2bytes Write {0x8DDA,0x0158,4}, //2bytes Write {0x8DDC,0xFF00,4}, //2bytes Write {0x8DDE,0x0618,4}, //2bytes Write {0x8DE0,0xFF80,4}, //2bytes Write {0x8DE2,0x050C,4}, //2bytes Write {0x8DE4,0x16B2,4}, //2bytes Write {0x8DE6,0x1081,4}, //2bytes Write {0x8DE8,0xB8A6,4}, //2bytes Write {0x8DEA,0x1E3C,4}, //2bytes Write {0x8DEC,0x1042,4}, //2bytes Write {0x8DEE,0x16B3,4}, //2bytes Write {0x8DF0,0x1081,4}, //2bytes Write {0x8DF2,0x1E3D,4}, //2bytes Write {0x8DF4,0x1042,4}, //2bytes Write {0x8DF6,0x16B6,4}, //2bytes Write {0x8DF8,0x1081,4}, //2bytes Write {0x8DFA,0x1E3E,4}, //2bytes Write {0x8DFC,0x1042,4}, //2bytes Write {0x8DFE,0x16B7,4}, //2bytes Write {0x8E00,0x1081,4}, //2bytes Write {0x8E02,0x1E3F,4}, //2bytes Write {0x8E04,0x1042,4}, //2bytes Write {0x8E06,0xAE00,4}, //2bytes Write {0x8E08,0x0D26,4}, //2bytes Write {0x8E0A,0x0184,4}, //2bytes Write {0x8E0C,0x04B1,4}, //2bytes Write {0x8E0E,0x0684,4}, //2bytes Write {0x8E10,0xC0F1,4}, //2bytes Write {0x8E12,0xD025,4}, //2bytes Write {0x8E14,0x8000,4}, //2bytes Write {0x8E16,0x8003,4}, //2bytes Write {0x8E18,0x7840,4}, //2bytes Write {0x8E1A,0xD224,4}, //2bytes Write {0x8E1C,0x12E9,4}, //2bytes Write {0x8E1E,0x0080,4}, //2bytes Write {0x8E20,0x0881,4}, //2bytes Write {0x8E22,0x001E,4}, //2bytes Write {0x8E24,0x12EA,4}, //2bytes Write {0x8E26,0x0103,4}, //2bytes Write {0x8E28,0xD121,4}, //2bytes Write {0x8E2A,0x2B41,4}, //2bytes Write {0x8E2C,0x0200,4}, //2bytes Write {0x8E2E,0x1920,4}, //2bytes Write {0x8E30,0x0002,4}, //2bytes Write {0x8E32,0x12EC,4}, //2bytes Write {0x8E34,0x0102,4}, //2bytes Write {0x8E36,0x1921,4}, //2bytes Write {0x8E38,0x00C2,4}, //2bytes Write {0x8E3A,0x2A41,4}, //2bytes Write {0x8E3C,0x0200,4}, //2bytes Write {0x8E3E,0x1924,4}, //2bytes Write {0x8E40,0x0002,4}, //2bytes Write {0x8E42,0xD01C,4}, //2bytes Write {0x8E44,0x880E,4}, //2bytes Write {0x8E46,0x1925,4}, //2bytes Write {0x8E48,0x0082,4}, //2bytes Write {0x8E4A,0x0853,4}, //2bytes Write {0x8E4C,0x0051,4}, //2bytes Write {0x8E4E,0x1794,4}, //2bytes Write {0x8E50,0xF000,4}, //2bytes Write {0x8E52,0x1139,4}, //2bytes Write {0x8E54,0x0083,4}, //2bytes Write {0x8E56,0x9046,4}, //2bytes Write {0x8E58,0x1138,4}, //2bytes Write {0x8E5A,0x0080,4}, //2bytes Write {0x8E5C,0xB808,4}, //2bytes Write {0x8E5E,0x7865,4}, //2bytes Write {0x8E60,0x0841,4}, //2bytes Write {0x8E62,0x0083,4}, //2bytes Write {0x8E64,0x112A,4}, //2bytes Write {0x8E66,0x0082,4}, //2bytes Write {0x8E68,0x112B,4}, //2bytes Write {0x8E6A,0x0080,4}, //2bytes Write {0x8E6C,0xBA08,4}, //2bytes Write {0x8E6E,0x7A05,4}, //2bytes Write {0x8E70,0x2A41,4}, //2bytes Write {0x8E72,0x0200,4}, //2bytes Write {0x8E74,0x1920,4}, //2bytes Write {0x8E76,0x0002,4}, //2bytes Write {0x8E78,0x1129,4}, //2bytes Write {0x8E7A,0x0080,4}, //2bytes Write {0x8E7C,0x1921,4}, //2bytes Write {0x8E7E,0x0082,4}, //2bytes Write {0x8E80,0x1128,4}, //2bytes Write {0x8E82,0x0082,4}, //2bytes Write {0x8E84,0xBA08,4}, //2bytes Write {0x8E86,0x7A05,4}, //2bytes Write {0x8E88,0x2A41,4}, //2bytes Write {0x8E8A,0x0200,4}, //2bytes Write {0x8E8C,0x1924,4}, //2bytes Write {0x8E8E,0x0002,4}, //2bytes Write {0x8E90,0x8901,4}, //2bytes Write {0x8E92,0x1925,4}, //2bytes Write {0x8E94,0x0082,4}, //2bytes Write {0x8E96,0xB886,4}, //2bytes Write {0x8E98,0xF003,4}, //2bytes Write {0x8E9A,0x8901,4}, //2bytes Write {0x8E9C,0xB8A6,4}, //2bytes Write {0x8E9E,0xA901,4}, //2bytes Write {0x8EA0,0xC0D1,4}, //2bytes Write {0x8EA2,0x7EE0,4}, //2bytes Write {0x8EA4,0x8000,4}, //2bytes Write {0x8EA6,0x00A0,4}, //2bytes Write {0x8EA8,0xFF80,4}, //2bytes Write {0x8EAA,0x041C,4}, //2bytes Write {0x8EAC,0xFF80,4}, //2bytes Write {0x8EAE,0x0250,4}, //2bytes Write {0x8EB0,0xFF80,4}, //2bytes Write {0x8EB2,0x07A8,4}, //2bytes Write {0x8EB4,0xEA0A,4}, //2bytes Write {0x8EB6,0x242F,4}, //2bytes Write {0x8EB8,0x7089,4}, //2bytes Write {0x8EBA,0x78E0,4}, //2bytes Write {0x8EBC,0x20A8,4}, //2bytes Write {0x8EBE,0x0180,4}, //2bytes Write {0x8EC0,0x1002,4}, //2bytes Write {0x8EC2,0x0D02,4}, //2bytes Write {0x8EC4,0x1902,4}, //2bytes Write {0x8EC6,0x0094,4}, //2bytes Write {0x8EC8,0x7FE0,4}, //2bytes Write {0x8ECA,0x7028,4}, //2bytes Write {0x8ECC,0x7308,4}, //2bytes Write {0x8ECE,0x1000,4}, //2bytes Write {0x8ED0,0x0900,4}, //2bytes Write {0x8ED2,0x7904,4}, //2bytes Write {0x8ED4,0x7947,4}, //2bytes Write {0x8ED6,0x1B00,4}, //2bytes Write {0x8ED8,0x0064,4}, //2bytes Write {0x8EDA,0x7EE0,4}, //2bytes Write {0x8EDC,0xEA0A,4}, //2bytes Write {0x8EDE,0x242F,4}, //2bytes Write {0x8EE0,0x7089,4}, //2bytes Write {0x8EE2,0x78E0,4}, //2bytes Write {0x8EE4,0x20A8,4}, //2bytes Write {0x8EE6,0x0180,4}, //2bytes Write {0x8EE8,0x1102,4}, //2bytes Write {0x8EEA,0x0502,4}, //2bytes Write {0x8EEC,0x1802,4}, //2bytes Write {0x8EEE,0x00B4,4}, //2bytes Write {0x8EF0,0x7FE0,4}, //2bytes Write {0x8EF2,0x7028,4}, //2bytes Write {0x8EF4,0x0000,4}, //2bytes Write {0x8EF6,0x0000,4}, //2bytes Write {0x8EF8,0xFF80,4}, //2bytes Write {0x8EFA,0x03F0,4}, //2bytes Write {0x8EFC,0xFF80,4}, //2bytes Write {0x8EFE,0x0978,4}, //2bytes Write {0x8F00,0xFF80,4}, //2bytes Write {0x8F02,0x0BA4,4}, //2bytes Write {0x8F04,0x0000,4}, //2bytes Write {0x8F06,0x08DC,4}, //2bytes Write {0x8F08,0x0000,4}, //2bytes Write {0x8F0A,0x0998,4}, //2bytes Write {0x098E,0x0016 ,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS [MON_ADDRESS_LO] {0x8016,0x086C ,4}, //2bytes Write MON_ADDRESS_LO {0x8002,0x0001 ,4}, //2bytes Write MON_CMD //mdelay(100); }; soc5140_short_reg soc5140_init_regs11[]= { //Char setting {0x30D4,0x9080,4}, //2bytes Write COLUMN_CORRECTION {0x316E,0xC400,4}, //2bytes Write DAC_ECL {0x305E,0x10A0,4}, //2bytes Write GLOBAL_GAIN {0x3E00,0x0010,4}, //2bytes Write SAMP_CONTROL {0x3E02,0xED02,4}, //2bytes Write SAMP_ADDR_EN {0x3E04,0xC88C,4}, //2bytes Write SAMP_RD1_SIG {0x3E06,0xC88C,4}, //2bytes Write SAMP_RD1_SIG_BOOST {0x3E08,0x700A,4}, //2bytes Write SAMP_RD1_RST {0x3E0A,0x701E,4}, //2bytes Write SAMP_RD1_RST_BOOST {0x3E0C,0x00FF,4}, //2bytes Write SAMP_RST1_EN {0x3E0E,0x00FF,4}, //2bytes Write SAMP_RST1_BOOST {0x3E10,0x00FF,4}, //2bytes Write SAMP_RST1_CLOOP_SH {0x3E12,0x0000,4}, //2bytes Write SAMP_RST_BOOST_SEQ {0x3E14,0xC78C,4}, //2bytes Write SAMP_SAMP1_SIG {0x3E16,0x6E06,4}, //2bytes Write SAMP_SAMP1_RST {0x3E18,0xA58C,4}, //2bytes Write SAMP_TX_EN {0x3E1A,0xA58E,4}, //2bytes Write SAMP_TX_BOOST {0x3E1C,0xA58E,4}, //2bytes Write SAMP_TX_CLOOP_SH {0x3E1E,0xC0D0,4}, //2bytes Write SAMP_TX_BOOST_SEQ {0x3E20,0xEB00,4}, //2bytes Write SAMP_VLN_EN {0x3E22,0x00FF,4}, //2bytes Write SAMP_VLN_HOLD {0x3E24,0xEB02,4}, //2bytes Write SAMP_VCL_EN {0x3E26,0xEA02,4}, //2bytes Write SAMP_COLCLAMP {0x3E28,0xEB0A,4}, //2bytes Write SAMP_SH_VCL {0x3E2A,0xEC01,4}, //2bytes Write SAMP_SH_VREF {0x3E2C,0xEB01,4}, //2bytes Write SAMP_SH_VBST {0x3E2E,0x00FF,4}, //2bytes Write SAMP_SPARE {0x3E30,0x00F3,4}, //2bytes Write SAMP_READOUT {0x3E32,0x3DFA,4}, //2bytes Write SAMP_RESET_DONE {0x3E34,0x00FF,4}, //2bytes Write SAMP_VLN_CLAMP {0x3E36,0x00F3,4}, //2bytes Write SAMP_ASC_INT {0x3E38,0x0000,4}, //2bytes Write SAMP_RS_CLOOP_SH_R {0x3E3A,0xF802,4}, //2bytes Write SAMP_RS_CLOOP_SH {0x3E3C,0x0FFF,4}, //2bytes Write SAMP_RS_BOOST_SEQ {0x3E3E,0xEA10,4}, //2bytes Write SAMP_TXLO_GND {0x3E40,0xEB05,4}, //2bytes Write SAMP_VLN_PER_COL {0x3E42,0xE5C8,4}, //2bytes Write SAMP_RD2_SIG {0x3E44,0xE5C8,4}, //2bytes Write SAMP_RD2_SIG_BOOST {0x3E46,0x8C70,4}, //2bytes Write SAMP_RD2_RST {0x3E48,0x8C71,4}, //2bytes Write SAMP_RD2_RST_BOOST {0x3E4A,0x00FF,4}, //2bytes Write SAMP_RST2_EN {0x3E4C,0x00FF,4}, //2bytes Write SAMP_RST2_BOOST {0x3E4E,0x00FF,4}, //2bytes Write SAMP_RST2_CLOOP_SH {0x3E50,0xE38D,4}, //2bytes Write SAMP_SAMP2_SIG {0x3E52,0x8B0A,4}, //2bytes Write SAMP_SAMP2_RST {0x3E58,0xEB0A,4}, //2bytes Write SAMP_PIX_CLAMP_EN {0x3E5C,0x0A00,4}, //2bytes Write SAMP_PIX_PULLUP_EN {0x3E5E,0x00FF,4}, //2bytes Write SAMP_PIX_PULLDOWN_EN_R {0x3E60,0x00FF,4}, //2bytes Write SAMP_PIX_PULLDOWN_EN_S {0x3E90,0x3C01,4}, //2bytes Write RST_ADDR_EN {0x3E92,0x00FF,4}, //2bytes Write RST_RST_EN {0x3E94,0x00FF,4}, //2bytes Write RST_RST_BOOST {0x3E96,0x3C00,4}, //2bytes Write RST_TX_EN {0x3E98,0x3C00,4}, //2bytes Write RST_TX_BOOST {0x3E9A,0x3C00,4}, //2bytes Write RST_TX_CLOOP_SH {0x3E9C,0xC0E0,4}, //2bytes Write RST_TX_BOOST_SEQ {0x3E9E,0x00FF,4}, //2bytes Write RST_RST_CLOOP_SH {0x3EA0,0x0000,4}, //2bytes Write RST_RST_BOOST_SEQ {0x3EA6,0x3C00,4}, //2bytes Write RST_PIX_PULLUP_EN {0x3ED8,0x3057,4}, //2bytes Write DAC_LD_12_13 {0x316C,0xB44F,4}, //2bytes Write DAC_TXLO {0x316E,0xC6FF,4}, //2bytes Write DAC_ECL {0x3ED2,0xEA0A,4}, //2bytes Write DAC_LD_6_7 {0x3ED4,0x00A3,4}, //2bytes Write DAC_LD_8_9 {0x3EDC,0x6020,4}, //2bytes Write DAC_LD_16_17 {0x3EE6,0xA541,4}, //2bytes Write DAC_LD_26_27 {0x31E0,0x0000,4}, //2bytes Write PIX_DEF_ID {0x3ED0,0x2409,4}, //2bytes Write DAC_LD_4_5 {0x3EDE,0x0A49,4}, //2bytes Write DAC_LD_18_19 {0x3EE0,0x4910,4}, //2bytes Write DAC_LD_20_21 {0x3EE2,0x09D2,4}, //2bytes Write DAC_LD_22_23 {0x30B6,0x0008,4}, //2bytes Write AUTOLR_CONTROL {0x337C,0x0006,4}, //2bytes Write YUV_YCBCR_CONTROL {0x3E1A,0xA582,4}, //2bytes Write SAMP_TX_BOOST {0x3E2E,0xEC05,4}, //2bytes Write SAMP_SPARE {0x3EE6,0xA5C0,4}, //2bytes Write DAC_LD_26_27 {0x316C,0xB43F,4}, //2bytes Write DAC_TXLO {0x316E,0xC6FF,4}, //2bytes Write DAC_ECL {0x3210,0x49B8,4}, //2bytes Write COLOR_PIPELINE_CONTROL // ************************************** //[Section5] AWB & CCM //[AWB_setup] //checked on 7-24-2009 // ************************************** {0x098E,0xAC01,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xAC01,0x77,3}, //1byte Write AWB_MODE // ************************************** // [Rev3_CCM] // Green boost up CCM // ************************************** {0x098E,0xAC46,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xAC46,0x0216,4}, //2bytes Write AWB_LEFT_CCM_0 {0xAC48,0xFF32,4}, //2bytes Write AWB_LEFT_CCM_1 {0xAC4A,0xFFB8,4}, //2bytes Write AWB_LEFT_CCM_2 {0xAC4C,0xFF83,4}, //2bytes Write AWB_LEFT_CCM_3 {0xAC4E,0x019B,4}, //2bytes Write AWB_LEFT_CCM_4 {0xAC50,0xFFE3,4}, //2bytes Write AWB_LEFT_CCM_5 {0xAC52,0xFFCF,4}, //2bytes Write AWB_LEFT_CCM_6 {0xAC54,0xFED0,4}, //2bytes Write AWB_LEFT_CCM_7 {0xAC56,0x0261,4}, //2bytes Write AWB_LEFT_CCM_8 {0xAC5C,0x01E7,4}, //2bytes Write AWB_RIGHT_CCM_0 {0xAC5E,0xFF5E,4}, //2bytes Write AWB_RIGHT_CCM_1 {0xAC60,0xFFD4,4}, //2bytes Write AWB_RIGHT_CCM_2 {0xAC62,0xFFD6,4}, //2bytes Write AWB_RIGHT_CCM_3 {0xAC64,0x0140,4}, //2bytes Write AWB_RIGHT_CCM_4 {0xAC66,0x0005,4}, //2bytes Write AWB_RIGHT_CCM_5 {0xAC68,0xFFFF,4}, //2bytes Write AWB_RIGHT_CCM_6 {0xAC6A,0xFF8D,4}, //2bytes Write AWB_RIGHT_CCM_7 {0xAC6C,0x018E,4}, //2bytes Write AWB_RIGHT_CCM_8 {0xAC6E,0x0066,4}, //2bytes Write AWB_RIGHT_CCM_R2BRATIO {0xAC58,0x00C8,4}, //2bytes Write AWB_LEFT_CCM_R2BRATIO // *************************************** //[Rev3_AWB] // *************************************** {0x098E,0xB842,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xB842,0x003E,4}, //2bytes Write STAT_AWB_GRAY_CHECKER_OFFSET_X {0xB844,0x0037,4}, //2bytes Write STAT_AWB_GRAY_CHECKER_OFFSET_Y {0x3240,0x0024,4}, //2bytes Write AWB_XY_SCALE {0x3242,0xCC14,4}, //2bytes Write AWB_WEIGHT_R0 {0x3244,0xADA2,4}, //2bytes Write AWB_WEIGHT_R1 {0x3246,0x617F,4}, //2bytes Write AWB_WEIGHT_R2 {0x3248,0x5F4B,4}, //2bytes Write AWB_WEIGHT_R3 {0x324A,0x9FD8,4}, //2bytes Write AWB_WEIGHT_R4 {0x324C,0xF8FF,4}, //2bytes Write AWB_WEIGHT_R5 {0x324E,0x2397,4}, //2bytes Write AWB_WEIGHT_R6 {0x3250,0x12D3,4}, //2bytes Write AWB_WEIGHT_R7 {0x098E,0xAC90,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xAC90,0x0A3A,4}, //2bytes Write AWB_BUFFERED_PRE_AWB_R2G_RATIO {0xAC92,0x0520,4}, //2bytes Write AWB_BUFFERED_PRE_AWB_B2G_RATIO {0xAC38,0x0000,4}, //2bytes Write AWB_MIN_REQUIRED_NUM_PIXELS_IN_STATS {0xAC3A,0x0001,4}, //2bytes Write {0xAC04,0x4C,3}, //2bytes Write AWB_PRE_AWB_R2G_RATIO {0xAC05,0x28,3}, //2bytes Write AWB_PRE_AWB_B2G_RATIO {0xAC08,0x20,3}, //2bytes Write AWB_CUR_CCM_POS {0xAC3C,0x37,3}, //2bytes Write AWB_MIN_ACCEPTED_PRE_AWB_R2G_RATIO {0xAC3D,0x55,3}, //2bytes Write AWB_MAX_ACCEPTED_PRE_AWB_R2G_RATIO {0xAC3E,0x25,3}, //2bytes Write AWB_MIN_ACCEPTED_PRE_AWB_B2G_RATIO {0xAC3F,0x46,3}, //2bytes Write AWB_MAX_ACCEPTED_PRE_AWB_B2G_RATIO {0xAC40,0x64,3}, //2bytes Write AWB_MIN_ACCEPTED_POST_AWB_R2G_RATIO {0xAC41,0x66,3}, //2bytes Write AWB_MAX_ACCEPTED_POST_AWB_R2G_RATIO {0xAC42,0x64,3}, //2bytes Write AWB_MIN_ACCEPTED_POST_AWB_B2G_RATIO {0xAC43,0x66,3}, //2bytes Write AWB_MAX_ACCEPTED_POST_AWB_B2G_RATIO // *************************************** //[Bright_DNP_Patch] //Enable the Patch // *************************************** {0x098E,0xAC22,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xAC22,0x0005,4}, //2bytes Write AWB_UNUSED2 {0xAC09,0x01,3}, //2bytes Write AWB_UNUSED1 {0xACB2,0x35,3}, //2bytes Write AWB_RG_MIN_BRIGHT {0xACB3,0x3B,3}, //2bytes Write AWB_RG_MAX_BRIGHT {0xACB6,0x3F,3}, //2bytes Write AWB_BG_MIN_BRIGHT {0xACB7,0x4E,3}, //2bytes Write AWB_BG_MAX_BRIGHT {0xACB8,0x0056,4}, //2bytes Write AWB_START_NUM_INT_LINES {0xACBA,0x0014,4}, //2bytes Write AWB_END_NUM_INT_LINES // **************************************** //Int Time Patch (SEMCO) variables //Enables // **************************************** {0x098E,0xBCE9,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xBCE9,0x01,3}, //2bytes Write LL_RESERVED2 //Copy Again max set {0xBCEA,0x0154,4}, //2bytes Write LL_RESERVED3 //Copy Dgain max set {0xBCEC,0x00B0,4}, //2bytes Write LL_RESERVED4 //BM Threshold for patch to kick in {0xA838,0x00B4,4}, //2bytes Write AE_TRACK_UNUSED1 // *************************************** //[jpeg_setup] //sets minimum compression //QSCALE=4 for fine //QSCALE=10 for Normal //QSCALE=13 for Economy // *************************************** {0x098E,0xD80F,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xD80F,0x04,3}, //2bytes Write JPEG_QSCALE_0 {0xD810,0x08,3}, //2bytes Write JPEG_QSCALE_1 {0xC8D2,0x04,3}, //2bytes Write CAM_OUTPUT_1_JPEG_QSCALE_0 {0xC8D3,0x08,3}, //2bytes Write CAM_OUTPUT_1_JPEG_QSCALE_1 {0xC8BC,0x04,3}, //2bytes Write CAM_OUTPUT_0_JPEG_QSCALE_0 {0xC8BD,0x08,3}, //2bytes Write CAM_OUTPUT_0_JPEG_QSCALE_1 // ************************************* //[Sys_Settings] // ************************************* {0x301A,0x10F4,4}, //2bytes Write RESET_REGISTER {0x301E,0x0084,4}, //2bytes Write DATA_PEDESTAL {0x301A,0x10FC,4}, //2bytes Write RESET_REGISTER {0x098E,0xDC33,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xDC33,0x21,3}, //2bytes Write SYS_FIRST_BLACK_LEVEL {0xA80E,0x12,3}, //2bytes Write AE_TRACK_MAX_BLACK_LEVEL {0xDC35,0x05,3}, //2bytes Write SYS_UV_COLOR_BOOST {0xDC36,0x33,3}, //2bytes Write SYS_DARK_COLOR_KILL {0xDC37,0x62,3}, //2bytes Write SYS_BRIGHT_COLORKILL {0x326E,0x00A4,4}, //2bytes Write LOW_PASS_YUV_FILTER {0x35A4,0x0596,4}, //2bytes Write BRIGHT_COLOR_KILL_CONTROLS {0x35A2,0x009B,4}, //2bytes Write DARK_COLOR_KILL_CONTROLS // ************************************** //[Gamma_Curves_REV3] //LL Gamma Curve // ************************************** {0x098E,0xBC18,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xBC18,0x02,3}, //2bytes Write LL_GAMMA_CONTRAST_CURVE_0 {0xBC19,0x17,3}, //2bytes Write LL_GAMMA_CONTRAST_CURVE_1 {0xBC1A,0x23,3}, //2bytes Write LL_GAMMA_CONTRAST_CURVE_2 {0xBC1B,0x3F,3}, //2bytes Write LL_GAMMA_CONTRAST_CURVE_3 {0xBC1C,0x67,3}, //2bytes Write LL_GAMMA_CONTRAST_CURVE_4 {0xBC1D,0x85,3}, //2bytes Write LL_GAMMA_CONTRAST_CURVE_5 {0xBC1E,0x9B,3}, //2bytes Write LL_GAMMA_CONTRAST_CURVE_6 {0xBC1F,0xAD,3}, //2bytes Write LL_GAMMA_CONTRAST_CURVE_7 {0xBC20,0xBB,3}, //2bytes Write LL_GAMMA_CONTRAST_CURVE_8 {0xBC21,0xC7,3}, //2bytes Write LL_GAMMA_CONTRAST_CURVE_9 {0xBC22,0xD1,3}, //2bytes Write LL_GAMMA_CONTRAST_CURVE_10 {0xBC23,0xDA,3}, //2bytes Write LL_GAMMA_CONTRAST_CURVE_11 {0xBC24,0xE1,3}, //2bytes Write LL_GAMMA_CONTRAST_CURVE_12 {0xBC25,0xE8,3}, //2bytes Write LL_GAMMA_CONTRAST_CURVE_13 {0xBC26,0xEE,3}, //2bytes Write LL_GAMMA_CONTRAST_CURVE_14 {0xBC27,0xF3,3}, //2bytes Write LL_GAMMA_CONTRAST_CURVE_15 {0xBC28,0xF7,3}, //2bytes Write LL_GAMMA_CONTRAST_CURVE_16 {0xBC29,0xFB,3}, //2bytes Write LL_GAMMA_CONTRAST_CURVE_17 {0xBC2A,0xFF,3}, //2bytes Write LL_GAMMA_CONTRAST_CURVE_18 {0xBC2B,0x08,3}, //2bytes Write LL_GAMMA_NEUTRAL_CURVE_0 {0xBC2C,0x12,3}, //2bytes Write LL_GAMMA_NEUTRAL_CURVE_1 {0xBC2D,0x23,3}, //2bytes Write LL_GAMMA_NEUTRAL_CURVE_2 {0xBC2E,0x3F,3}, //2bytes Write LL_GAMMA_NEUTRAL_CURVE_3 {0xBC2F,0x67,3}, //2bytes Write LL_GAMMA_NEUTRAL_CURVE_4 {0xBC30,0x85,3}, //2bytes Write LL_GAMMA_NEUTRAL_CURVE_5 {0xBC31,0x9B,3}, //2bytes Write LL_GAMMA_NEUTRAL_CURVE_6 {0xBC32,0xAD,3}, //2bytes Write LL_GAMMA_NEUTRAL_CURVE_7 {0xBC33,0xBB,3}, //2bytes Write LL_GAMMA_NEUTRAL_CURVE_8 {0xBC34,0xC7,3}, //2bytes Write LL_GAMMA_NEUTRAL_CURVE_9 {0xBC35,0xD1,3}, //2bytes Write LL_GAMMA_NEUTRAL_CURVE_10 {0xBC36,0xDA,3}, //2bytes Write LL_GAMMA_NEUTRAL_CURVE_11 {0xBC37,0xE1,3}, //2bytes Write LL_GAMMA_NEUTRAL_CURVE_12 {0xBC38,0xE8,3}, //2bytes Write LL_GAMMA_NEUTRAL_CURVE_13 {0xBC39,0xEE,3}, //2bytes Write LL_GAMMA_NEUTRAL_CURVE_14 {0xBC3A,0xF3,3}, //2bytes Write LL_GAMMA_NEUTRAL_CURVE_15 {0xBC3B,0xF7,3}, //2bytes Write LL_GAMMA_NEUTRAL_CURVE_16 {0xBC3C,0xFB,3}, //2bytes Write LL_GAMMA_NEUTRAL_CURVE_17 {0xBC3D,0xFF,3}, //2bytes Write LL_GAMMA_NEUTRAL_CURVE_18 {0xBC3E,0x12,3}, //2bytes Write LL_GAMMA_NR_CURVE_0 {0xBC3F,0x1C,3}, //2bytes Write LL_GAMMA_NR_CURVE_1 {0xBC40,0x26,3}, //2bytes Write LL_GAMMA_NR_CURVE_2 {0xBC41,0x40,3}, //2bytes Write LL_GAMMA_NR_CURVE_3 {0xBC42,0x50,3}, //2bytes Write LL_GAMMA_NR_CURVE_4 {0xBC43,0x70,3}, //2bytes Write LL_GAMMA_NR_CURVE_5 {0xBC44,0x81,3}, //2bytes Write LL_GAMMA_NR_CURVE_6 {0xBC45,0x90,3}, //2bytes Write LL_GAMMA_NR_CURVE_7 {0xBC46,0x9E,3}, //2bytes Write LL_GAMMA_NR_CURVE_8 {0xBC47,0xAB,3}, //2bytes Write LL_GAMMA_NR_CURVE_9 {0xBC48,0xB6,3}, //2bytes Write LL_GAMMA_NR_CURVE_10 {0xBC49,0xC1,3}, //2bytes Write LL_GAMMA_NR_CURVE_11 {0xBC4A,0xCB,3}, //2bytes Write LL_GAMMA_NR_CURVE_12 {0xBC4B,0xD5,3}, //2bytes Write LL_GAMMA_NR_CURVE_13 {0xBC4C,0xDE,3}, //2bytes Write LL_GAMMA_NR_CURVE_14 {0xBC4D,0xE7,3}, //2bytes Write LL_GAMMA_NR_CURVE_15 {0xBC4E,0xEF,3}, //2bytes Write LL_GAMMA_NR_CURVE_16 {0xBC4F,0xF7,3}, //2bytes Write LL_GAMMA_NR_CURVE_17 {0xBC50,0xFF,3}, //2bytes Write LL_GAMMA_NR_CURVE_18 {0x098E,0x3C0E,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xBC0E,0x0C00,4}, //2bytes Write LL_GAMMA_CURVE_ADJ_START_POS {0xBC10,0x1A30,4}, //2bytes Write LL_GAMMA_CURVE_ADJ_MID_POS {0xBC12,0x1B40,4}, //2bytes Write LL_GAMMA_CURVE_ADJ_END_POS // ****************************************** //[BM_Dampening] // ****************************************** {0x098E,0xB801,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xB801,0xE0,3}, //2bytes Write STAT_MODE {0xB862,0x04,3}, //2bytes Write STAT_BMTRACKING_SPEED // ****************************************** //[AE] //frame rate control _ shutter speed control // ****************************************** {0x098E,0xA816,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xA816,0x000A,4}, //2bytes Write AE_TRACK_MIN_INT_TIME_ROWS {0xA818,0x070B,4}, //2bytes Write AE_TRACK_TARGET_INT_TIME_ROWS {0xA81A,0x09E7,4}, //2bytes Write AE_TRACK_MAX_INT_TIME_ROWS {0xA802,0x0007,4}, //2bytes Write AE_TRACK_ALGO {0xA81C,0x0060,4}, //2bytes Write AE_TRACK_MIN_AGAIN {0xA81E,0x00DC,4}, //2bytes Write AE_TRACK_TARGET_AGAIN {0xA820,0x0154,4}, //2bytes Write AE_TRACK_MAX_AGAIN {0xA824,0x00B0,4}, //2bytes Write AE_TRACK_MAX_DGAIN {0xA822,0x0080,4}, //2bytes Write AE_TRACK_MIN_DGAIN // ************************************** //AE mode control // ************************************** {0x098E,0xA402,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xA402,0x0004,4}, //2bytes Write AE_RULE_ALGO {0xA401,0x00,3}, //2bytes Write AE_RULE_MODE {0xA409,0x3A,3}, //2bytes Write AE_RULE_BASE_TARGET {0xA801,0x01,3}, //2bytes Write AE_TRACK_MODE // *************************************** //AE sub-window number // *************************************** {0xB824,0x05,3}, //2bytes Write STAT_AE_NUM_ZONES_X {0xB825,0x05,3}, //2bytes Write STAT_AE_NUM_ZONES_Y // *************************************** //Basic // *************************************** {0x098E,0xB829,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xB829,0x02,3}, //2bytes Write STAT_LL_BRIGHTNESS_METRIC_DIVISOR {0xB863,0x02,3}, //2bytes Write STAT_BM_MUL // *************************************** //BNR Control // *************************************** {0x098E,0xBC72,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xBC72,0x0F,3}, //2bytes Write LL_START_BNR_STRENGTH {0xBC73,0x1A,3}, //2bytes Write LL_END_BNR_STRENGTH // *************************************** //[BM_GM_Start_Stop] // *************************************** {0x098E,0xBC52,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xBC52,0x02DC,4}, //2bytes Write LL_START_BRIGHTNESS_METRIC {0xBC54,0x05D8,4}, //2bytes Write LL_END_BRIGHTNESS_METRIC {0xBC58,0x00C8,4}, //2bytes Write LL_START_GAIN_METRIC {0xBC5A,0x038A,4}, //2bytes Write LL_END_GAIN_METRIC {0xBC5E,0x00FA,4}, //2bytes Write LL_START_APERTURE_GAIN_BM {0xBC60,0x088A,4}, //2bytes Write LL_END_APERTURE_GAIN_BM {0xBC66,0x00FA,4}, //2bytes Write LL_START_APERTURE_GM {0xBC68,0x038A,4}, //2bytes Write LL_END_APERTURE_GM {0xBC86,0x00C8,4}, //2bytes Write LL_START_FFNR_GM {0xBC88,0x038A,4}, //2bytes Write LL_END_FFNR_GM {0xBCBC,0x0040,4}, //2bytes Write LL_SFFB_START_GAIN {0xBCBE,0x014C,4}, //2bytes Write LL_SFFB_END_GAIN {0xBCCC,0x00C8,4}, //2bytes Write LL_SFFB_START_MAX_GM {0xBCCE,0x0340,4}, //2bytes Write LL_SFFB_END_MAX_GM {0xBC90,0x00C8,4}, //2bytes Write LL_START_GRB_GM {0xBC92,0x038A,4}, //2bytes Write LL_END_GRB_GM {0xBCAA,0x044C,4}, //2bytes Write LL_CDC_THR_ADJ_START_POS {0xBCAC,0x00AF,4}, //2bytes Write LL_CDC_THR_ADJ_MID_POS {0xBCAE,0x0009,4}, //2bytes Write LL_CDC_THR_ADJ_END_POS {0xBCD8,0x00DC,4}, //2bytes Write LL_PCR_START_BM {0xBCDA,0x0BDA,4}, //2bytes Write LL_PCR_END_BM {0xBC02,0x01F6,4}, //2bytes Write LL_ALGO {0x098E,0x3C14,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xBC14,0xFFDC,4}, //2bytes Write LL_GAMMA_FADE_TO_BLACK_START_POS {0xBC16,0xFFFF,4}, //2bytes Write LL_GAMMA_FADE_TO_BLACK_END_POS // ************************************************************************** //this tuning is based on the noise model....only change if new noise model has been completed. //[Kernel] //turns off single pixel enables 1.5 cluster // ************************************************************************** {0x3380,0x0504,4}, //2bytes Write KERNEL_CONFIG {0x098E,0xBCB2,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xBCB2,0x28,3}, //2bytes Write LL_CDC_DARK_CLUS_SLOPE {0xBCB3,0x5F,3}, //2bytes Write LL_CDC_DARK_CLUS_SATUR {0x3380,0x0584,4}, //2bytes Write KERNEL_CONFIG {0x3380,0x0586,4}, //2bytes Write KERNEL_CONFIG {0x3380,0x0505,4}, //2bytes Write KERNEL_CONFIG // ********************************* //[GRB2.2] // ********************************* {0x098E,0xBC94,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xBC94,0x12,3}, //2bytes Write LL_GB_START_THRESHOLD_0 {0xBC95,0x0C,3}, //2bytes Write LL_GB_START_THRESHOLD_1 {0xBC9C,0x37,3}, //2bytes Write LL_GB_END_THRESHOLD_0 {0xBC9D,0x24,3}, //2bytes Write LL_GB_END_THRESHOLD_1 // ****************************************** //[Demosaic_REV2.1] // ****************************************** {0x33B0,0x2A16,4}, //2bytes Write FFNR_ALPHA_BETA {0x098E,0xBC8A,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xBC8A,0x00,3}, //2bytes Write LL_START_FF_MIX_THRESH_Y {0xBC8B,0x28,3}, //2bytes Write LL_END_FF_MIX_THRESH_Y {0xBC8C,0x01,3}, //2bytes Write LL_START_FF_MIX_THRESH_YGAIN {0xBC8D,0x01,3}, //2bytes Write LL_END_FF_MIX_THRESH_YGAIN {0xBC8F,0x00,3}, //2bytes Write LL_END_FF_MIX_THRESH_GAIN // ******************************************* //[SFFB_REV2.1_noisemodel] // ******************************************* {0xBCC0,0x10,3}, //2bytes Write LL_SFFB_RAMP_START {0xBCC1,0x03,3}, //2bytes Write LL_SFFB_RAMP_STOP {0xBCC2,0x0A,3}, //2bytes Write LL_SFFB_SLOPE_START {0xBCC3,0x01,3}, //2bytes Write LL_SFFB_SLOPE_STOP {0xBCC4,0x0A,3}, //2bytes Write LL_SFFB_THSTART {0xBCC5,0x0E,3}, //2bytes Write LL_SFFB_THSTOP {0xBCBA,0x0009,4}, //2bytes Write LL_SFFB_CONFIG // ******************************************* //[Section7] PA preference // ******************************************* {0x33BA,0x006A,4}, //2bytes Write APEDGE_CONTROL {0x33BE,0x0001,4}, //2bytes Write UA_KNEE_L {0x33C2,0x1000,4}, //2bytes Write UA_WEIGHTS {0x098E,0xBC5E,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xBC5E,0x0124,4}, //2bytes Write LL_START_APERTURE_GAIN_BM {0xBC60,0x05D0,4}, //2bytes Write LL_END_APERTURE_GAIN_BM {0xBC62,0x07,3}, //2bytes Write LL_START_APERTURE_KPGAIN {0xBC64,0x05,3}, //2bytes Write LL_START_APERTURE_KNGAIN {0xBC63,0x50,3}, //2bytes Write LL_END_APERTURE_KPGAIN {0xBC65,0x50,3}, //2bytes Write LL_END_APERTURE_KNGAIN {0xBC6A,0x02,3}, //2bytes Write LL_START_APERTURE_INTEGER_GAIN {0xBC6C,0x02,3}, //2bytes Write LL_START_APERTURE_EXP_GAIN // ******************************************* //[Saturation_REV3] // ******************************************* {0xBC56,0x40,3}, //2bytes Write LL_START_CCM_SATURATION {0xBC57,0x25,3}, //2bytes Write LL_END_CCM_SATURATION // ******************************************* //[DCCM_REV3] // ******************************************* {0xBCDE,0x03,3}, //2bytes Write LL_START_SYS_THRESHOLD {0xBCDF,0x50,3}, //2bytes Write LL_STOP_SYS_THRESHOLD {0xBCE0,0x08,3}, //2bytes Write LL_START_SYS_GAIN {0xBCE1,0x03,3}, //2bytes Write LL_STOP_SYS_GAIN // ******************************************* //[Sobel_REV3] // ******************************************* {0x098E,0xBCD0,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xBCD0,0x000A,4}, //2bytes Write LL_SFFB_SOBEL_FLAT_START {0xBCD2,0x00CC,4}, //2bytes Write LL_SFFB_SOBEL_FLAT_STOP {0xBCD4,0x0014,4}, //2bytes Write LL_SFFB_SOBEL_SHARP_START {0xBCD6,0x00CD,4}, //2bytes Write LL_SFFB_SOBEL_SHARP_STOP {0xBCC6,0x00,3}, //2bytes Write LL_SFFB_SHARPENING_START {0xBCC7,0x00,3}, //2bytes Write LL_SFFB_SHARPENING_STOP {0xBCC8,0x20,3}, //2bytes Write LL_SFFB_FLATNESS_START {0xBCC9,0x40,3}, //2bytes Write LL_SFFB_FLATNESS_STOP {0xBCCA,0x04,3}, //2bytes Write LL_SFFB_TRANSITION_START {0xBCCB,0x00,3}, //2bytes Write LL_SFFB_TRANSITION_STOP // ***************************************** //[TX_SETTING] // ***************************************** {0x098E,0xC8ED,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xC8ED,0x03,3}, //2bytes Write CAM_TX_ENABLE_MODE // ***************************************** //[SAMSUNG_VCM_Enable] //AFM_POS_APPLY_Workaround 0917 // ***************************************** {0x098E,0x8419,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0x8419,0x01,3}, //2bytes Write SEQ_STATE_CFG_1_AF //1 {0x8404,0x06,3}, //2bytes Write SEQ_CMD {0x098E,0xB007,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xB007,0x01,3}, //2bytes Write AF_BEST_LENS_POS // **************************************** //[AF_VCM_Enable] // **************************************** {0x098E,0xC400,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xC400,0x81,3}, //2bytes Write AFM_ALGO {0x8419,0x05,3}, //2bytes Write SEQ_STATE_CFG_1_AF^M {0X8404,0X05,3}, //========================================================================50_wtx DELAY(); // {0x8419,0x05,3}, //2bytes Write SEQ_STATE_CFG_1_AF // {0xC424,0x08,3}, //2bytes Write AFM_ALGO // *************************************** //[AF settings] // *************************************** //1 {0x098E,0xB002,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS //1{0xB002,0x0047,4}, //2bytes Write AF_MODE //1 {0xB004,0x0002,4}, //2bytes Write AF_ALGO //1 {0x098E,0xB015,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS //1 {0xB015,0x05,3}, //2bytes Write AF_TH_AVE_DIFF_SHA //1 {0xB016,0x0020,4}, //2bytes Write AF_TH_AVE_MAX_SHA {0x098E,0xC40C,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xC40C,0x00F0,4}, //2bytes Write AFM_POS_MAX {0xC40A,0x0025,4}, //2bytes Write AFM_POS_MIN // ************************************* //Init AFM Position // ************************************* // {0x098E,0xC405,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS //{0xC408,0x03,3}, //2bytes Write AFM_MACRO_POS // ************************************** //[AF Position Settings] // ************************************** {0x098E,0xB018,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xB018,0x06,3}, //2bytes Write AF_FS_POS_0 {0xB019,0x1E,3}, //2bytes Write AF_FS_POS_1 {0xB01A,0x3C,3}, //2bytes Write AF_FS_POS_2 {0xB01B,0x5A,3}, //2bytes Write AF_FS_POS_3 {0xB01C,0x78,3}, //2bytes Write AF_FS_POS_4 {0xB01D,0x96,3}, //2bytes Write AF_FS_POS_5 {0xB01E,0xB4,3}, //2bytes Write AF_FS_POS_6 {0xB01F,0xD2,3}, //2bytes Write AF_FS_POS_7 {0xB020,0xF0,3}, //2bytes Write AF_FS_POS_8 {0xB021,0xFF,3}, //2bytes Write AF_FS_POS_9 {0xB012,0x0A,3}, //2bytes Write AF_FS_NUM_STEPS // ************************************** //[2nd Scan Option] // ************************************** {0x098E,0xB013,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xB013,0xAA,3}, //2bytes Write AF_FS_NUM_STEPS2 {0xB014,0x03,3}, //2bytes Write AF_FS_STEP_SIZE // ************************************** //Lock AF // ************************************** //1 {0x098E,0x3045,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS //1 {0xB045,0x0015,4}, //2bytes Write AF_MODE_EX // *************************************************** //[4 STOPS SEMCO ] 0916 stop test 50 70 90 B0 // *************************************************** {0xFC04,0x04,3}, //2bytes Write FS_M_SHUTTER_SMODE {0xFC05,0x04,3}, //2bytes Write FS_M_SHUTTER_SHSTATUS {0xFC06,0x50,3}, //2bytes Write FS_M_SHUTTER_MIN_IT {0xFC07,0x70,3}, //2bytes Write FS_M_SHUTTER_MIN_IT_L {0xFC08,0x90,3}, //2bytes Write FS_COARSE_INTEGRATION_TIME {0xFC09,0xB0,3}, //2bytes Write FS_COARSE_INTEGRATION_TIME_L {0xFC0A,0x00,3}, //2bytes Write FS_ANALOG_GAIN {0xFC0B,0x00,3}, //2bytes Write FS_ANALOG_GAIN_L // ****************************************** //[Refresh] // ****************************************** {0x098E,0x8404,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0x8404,0x05,3}, //2bytes Write SEQ_CMD //mdelay(50); }; soc5140_short_reg soc5140_init_regs12[]= { {0x098E,0xAC02,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0xAC02,0x00FF,4}, //2bytes Write AWB_ALGO {0xAC02,0x00FF,4}, //2bytes Write AWB_ALGO {0xACB0,0x32,3}, //2bytes Write AWB_RG_MIN {0xACB1,0x4C,3}, //2bytes Write AWB_RG_MAX {0xACB4,0x28,3}, //2bytes Write AWB_BG_MIN {0xACB5,0x4F,3}, //2bytes Write AWB_BG_MAX // ************************************ //VGPIO workaround // ************************************ {0x060E,0x00FF,4}, //2bytes Write VGPIO_DIR // ************************************ //[Refresh_Mode] // ************************************ {0x098E,0x8404,4}, //2bytes Write LOGICAL_ADDRESS_ACCESS {0x8404,0x06,3}, //2bytes Write SEQ_CMD //mdelay(50); }; soc5140_short_reg soc5140_init_regs13[]= { {0x001A,0x0218,4}, //2bytes Write RESET_AND_MISC_CONTROL {0x0018,0x6008,4}, //2bytes Write STANDBY_CONTROL_AND_STATUS //mdelay(100); }; */ // ********************************* //SOC5140 IAMGE SIZE // ********************************* enum image_size_soc5140 { SXGA , // 1296x 960 QSXGA , // 2600 x 1952 }; /* // ********************************* //Flicker setting // ********************************* soc5140_short_reg manual_50hz[]= { {0x098E,0x8417,4}, // LOGICAL_ADDRESS_ACCESS [SEQ_STATE_CFG_1_FD] {0x8417,0x01,3}, // SEQ_STATE_CFG_1_FD {0xA004,0x32,3}, // FD_EXPECTED_FLICKER_SOURCE_FREQUENCY {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg manual_60hz[]= { {0x098E,0x8417,4}, // LOGICAL_ADDRESS_ACCESS [SEQ_STATE_CFG_1_FD] {0x8417,0x01,3}, // SEQ_STATE_CFG_1_FD {0xA004,0x3C,3}, // FD_EXPECTED_FLICKER_SOURCE_FREQUENCY {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg manual_auto[]= { {0x098E,0x8417,4}, // LOGICAL_ADDRESS_ACCESS [SEQ_STATE_CFG_1_FD] {0x8417,0x02,3}, // SEQ_STATE_CFG_1_FD {0x8404,0x06,3}, // SEQ_CMD }; */ // ********************************* //Dzoom setting // ********************************* soc5140_short_reg zoomx_1[]= { {0x098E,0x5C18,4}, // LOGICAL_ADDRESS_ACCESS [SYS_ZOOM_FACTOR] {0xDC18,0x0064,4}, // SYS_ZOOM_FACTOR }; soc5140_short_reg zoomx_1_2[]= { {0x098E,0x5C18,4}, {0xDC18,0x0078,4}, }; soc5140_short_reg zoomx_1_4[]= { {0x098E,0x5C18,4}, {0xDC18,0x008C,4}, }; soc5140_short_reg zoomx_1_6[]= { {0x098E, 0x5C18,4}, {0xDC18, 0x00A0,4}, }; soc5140_short_reg zoomx_1_8[]= { {0x098E,0x5C18,4}, {0xDC18,0x00B4,4}, }; soc5140_short_reg zoomx_2[]= { {0x098E,0x5C18,4}, {0xDC18,0x00C8,4}, }; // *************************** //Effect setting // *************************** soc5140_short_reg effect_off[]= { {0x098E,0xDC38,4}, // LOGICAL_ADDRESS_ACCESS [SYS_SELECT_FX] {0xDC38,0x00,3}, // SYS_SELECT_FX {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg effect_black_white[]= { {0x098E,0xDC38,4}, // LOGICAL_ADDRESS_ACCESS [SYS_SELECT_FX] {0xDC38,0x01,3}, // SYS_SELECT_FX {0xDC3A,0x00,3}, // SYS_SEPIA_CR {0xDC3B,0x00,3}, // SYS_SEPIA_CB {0x8404,0x06,3}, // SEQ_CM }; soc5140_short_reg effect_sepia[]= { {0x098E,0xDC38,4}, // LOGICAL_ADDRESS_ACCESS [SYS_SELECT_FX] {0xDC38,0x02,3}, // SYS_SELECT_FX {0xDC3A,0x25,3}, // SYS_SEPIA_CR {0xDC3B,0xE0,3}, // SYS_SEPIA_CB {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg effect_aqua[]= { {0x098E,0xDC38,4}, // LOGICAL_ADDRESS_ACCESS [SYS_SELECT_FX] {0xDC38,0x02,3}, // SYS_SELECT_FX {0xDC3A,0xEE,3}, // SYS_SEPIA_CR {0xDC3B,0xBA,3}, // SYS_SEPIA_CB {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg effect_negative[]= { {0x098E,0xDC38,4}, // LOGICAL_ADDRESS_ACCESS [SYS_SELECT_FX] {0xDC38,0x03,3}, // SYS_SELECT_FX {0xDC3A,0x00,3}, // SYS_SEPIA_CR {0xDC3B,0x00,3}, // SYS_SEPIA_CB {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg effect_solarize[]= { {0x098E,0xDC38,4}, // LOGICAL_ADDRESS_ACCESS [SYS_SELECT_FX] {0xDC38,0x05,3}, // SYS_SELECT_FX {0xDC39,0x12,3}, // SYS_SOLARIZATION_TH {0x8404,0x06,3}, // SEQ_CMD }; // ************************* //MWB setting // ************************* soc5140_short_reg wb_cloudy[]= { {0x098E,0x8410,4}, // LOGICAL_ADDRESS_ACCESS [SEQ_STATE_CFG_0_AWB] {0x8410,0x01,3}, // SEQ_STATE_CFG_0_AWB {0x8418,0x01,3}, // SEQ_STATE_CFG_1_AWB {0x8420,0x01,3}, // SEQ_STATE_CFG_2_AWB {0xAC44,0x7F,3}, // AWB_LEFT_CCM_POS_RANGE_LIMIT {0xAC45,0x7F,3}, // AWB_RIGHT_CCM_POS_RANGE_LIMIT {0x8404,0x06,3}, // SEQ_CMD {0xAC04,0x2E,3}, // AWB_PRE_AWB_R2G_RATIO {0xAC05,0x4D,3}, // AWB_PRE_AWB_B2G_RATIO }; soc5140_short_reg wb_sunny[]= { {0x098E,0x8410,4}, // LOGICAL_ADDRESS_ACCESS [SEQ_STATE_CFG_0_AWB] {0x8410,0x01,3}, // SEQ_STATE_CFG_0_AWB {0x8418,0x01,3}, // SEQ_STATE_CFG_1_AWB {0x8420,0x01,3}, // SEQ_STATE_CFG_2_AWB {0xAC44,0x7F,3}, // AWB_LEFT_CCM_POS_RANGE_LIMIT {0xAC45,0x7F,3}, // AWB_RIGHT_CCM_POS_RANGE_LIMIT {0x8404,0x06,3}, // SEQ_CMD {0xAC04,0x39,3}, // AWB_PRE_AWB_R2G_RATIO {0xAC05,0x4D,3}, // AWB_PRE_AWB_B2G_RATIO }; soc5140_short_reg wb_flourescsant[]= { {0x098E,0x8410,4}, // LOGICAL_ADDRESS_ACCESS [SEQ_STATE_CFG_0_AWB] {0x8410,0x01,3}, // SEQ_STATE_CFG_0_AWB {0x8418,0x01,3}, // SEQ_STATE_CFG_1_AWB {0x8420,0x01,3}, // SEQ_STATE_CFG_2_AWB {0xAC44,0x50,3}, // AWB_LEFT_CCM_POS_RANGE_LIMIT {0xAC45,0x50,3}, // AWB_RIGHT_CCM_POS_RANGE_LIMIT {0x8404,0x06,3}, // SEQ_CMD {0xAC04,0x3E,3}, // AWB_PRE_AWB_R2G_RATIO {0xAC05,0x3C,3}, // AWB_PRE_AWB_B2G_RATIO }; soc5140_short_reg wb_incandescent[]= { {0x098E,0x8410,4}, // LOGICAL_ADDRESS_ACCESS [SEQ_STATE_CFG_0_AWB] {0x8410,0x01,3}, // SEQ_STATE_CFG_0_AWB {0x8418,0x01,3}, // SEQ_STATE_CFG_1_AWB {0x8420,0x01,3}, // SEQ_STATE_CFG_2_AWB {0xAC44,0x00,3}, // AWB_LEFT_CCM_POS_RANGE_LIMIT {0xAC45,0x00,3}, // AWB_RIGHT_CCM_POS_RANGE_LIMIT {0x8404,0x06,3}, // SEQ_CMD {0xAC04,0x50,3}, // AWB_PRE_AWB_R2G_RATIO {0xAC05,0x2C,3}, // AWB_PRE_AWB_B2G_RATIO }; soc5140_short_reg wb_auto[]= { {0x098E,0x8410,4}, // LOGICAL_ADDRESS_ACCESS [SEQ_STATE_CFG_0_AWB] {0x8410,0x02,3}, // SEQ_STATE_CFG_0_AWB {0x8418,0x02,3}, // SEQ_STATE_CFG_1_AWB {0x8420,0x02,3}, // SEQ_STATE_CFG_2_AWB {0xAC44,0x00,3}, // AWB_LEFT_CCM_POS_RANGE_LIMIT {0xAC45,0x7F,3}, // AWB_RIGHT_CCM_POS_RANGE_LIMIT {0x8404,0x06,3}, // SEQ_CMD {0xAC04,0x40,3}, // AWB_PRE_AWB_R2G_RATIO {0xAC05,0x4D,3}, // AWB_PRE_AWB_B2G_RATIO }; // ************************ //Contrast setting // ************************ soc5140_short_reg contrast_tbl_0[]= {//-2 {0x098E,0xBC51,4}, // LOGICAL_ADDRESS_ACCESS [LL_GAMMA_CURVE_SELECTOR] {0xBC51,0x04,3}, // LL_GAMMA_CURVE_SELECTOR {0xBC2B,0x00,3}, // LL_GAMMA_NEUTRAL_CURVE_0 {0xBC2C,0x32,3}, // LL_GAMMA_NEUTRAL_CURVE_1 {0xBC2D,0x3E,3}, // LL_GAMMA_NEUTRAL_CURVE_2 {0xBC2E,0x4F,3}, // LL_GAMMA_NEUTRAL_CURVE_3 {0xBC2F,0x67,3}, // LL_GAMMA_NEUTRAL_CURVE_4 {0xBC30,0x78,3}, // LL_GAMMA_NEUTRAL_CURVE_5 {0xBC31,0x87,3}, // LL_GAMMA_NEUTRAL_CURVE_6 {0xBC32,0x93,3}, // LL_GAMMA_NEUTRAL_CURVE_7 {0xBC33,0x9F,3}, // LL_GAMMA_NEUTRAL_CURVE_8 {0xBC34,0xA9,3}, // LL_GAMMA_NEUTRAL_CURVE_9 {0xBC35,0xB3,3}, // LL_GAMMA_NEUTRAL_CURVE_10 {0xBC36,0xBC,3}, // LL_GAMMA_NEUTRAL_CURVE_11 {0xBC37,0xC4,3}, // LL_GAMMA_NEUTRAL_CURVE_12 {0xBC38,0xCC,3}, // LL_GAMMA_NEUTRAL_CURVE_13 {0xBC39,0xD4,3}, // LL_GAMMA_NEUTRAL_CURVE_14 {0xBC3A,0xDC,3}, // LL_GAMMA_NEUTRAL_CURVE_15 {0xBC3B,0xEA,3}, // LL_GAMMA_NEUTRAL_CURVE_16 {0xBC3C,0xF8,3}, // LL_GAMMA_NEUTRAL_CURVE_17 {0xBC3D,0xFF,3}, // LL_GAMMA_NEUTRAL_CURVE_18 //{0x8404,0x05,3}, // SEQ_CMD {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg contrast_tbl_1[]= {//-1 {0x098E,0xBC51,4}, // LOGICAL_ADDRESS_ACCESS [LL_GAMMA_CURVE_SELECTOR] {0xBC51,0x04,3}, // LL_GAMMA_CURVE_SELECTOR {0xBC2B,0x00,3}, // LL_GAMMA_NEUTRAL_CURVE_0 {0xBC2C,0x26,3}, // LL_GAMMA_NEUTRAL_CURVE_1 {0xBC2D,0x34,3}, // LL_GAMMA_NEUTRAL_CURVE_2 {0xBC2E,0x48,3}, // LL_GAMMA_NEUTRAL_CURVE_3 {0xBC2F,0x63,3}, // LL_GAMMA_NEUTRAL_CURVE_4 {0xBC30,0x77,3}, // LL_GAMMA_NEUTRAL_CURVE_5 {0xBC31,0x88,3}, // LL_GAMMA_NEUTRAL_CURVE_6 {0xBC32,0x96,3}, // LL_GAMMA_NEUTRAL_CURVE_7 {0xBC33,0xA3,3}, // LL_GAMMA_NEUTRAL_CURVE_8 {0xBC34,0xAF,3}, // LL_GAMMA_NEUTRAL_CURVE_9 {0xBC35,0xBA,3}, // LL_GAMMA_NEUTRAL_CURVE_10 {0xBC36,0xC4,3}, // LL_GAMMA_NEUTRAL_CURVE_11 {0xBC37,0xCE,3}, // LL_GAMMA_NEUTRAL_CURVE_12 {0xBC38,0xD7,3}, // LL_GAMMA_NEUTRAL_CURVE_13 {0xBC39,0xE0,3}, // LL_GAMMA_NEUTRAL_CURVE_14 {0xBC3A,0xE8,3}, // LL_GAMMA_NEUTRAL_CURVE_15 {0xBC3B,0xF1,3}, // LL_GAMMA_NEUTRAL_CURVE_16 {0xBC3C,0xF9,3}, // LL_GAMMA_NEUTRAL_CURVE_17 {0xBC3D,0xFF,3}, // LL_GAMMA_NEUTRAL_CURVE_18 {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg contrast_tbl_2[]= {//default {0x098E,0xBC18,4}, {0xBC18,0x02,3}, {0xBC19,0x17,3}, {0xBC1A,0x23,3}, {0xBC1B,0x3F,3}, {0xBC1C,0x67,3}, {0xBC1D,0x85,3}, {0xBC1E,0x9B,3}, {0xBC1F,0xAD,3}, {0xBC20,0xBB,3}, {0xBC21,0xC7,3}, {0xBC22,0xD1,3}, {0xBC23,0xDA,3}, {0xBC24,0xE1,3}, {0xBC25,0xE8,3}, {0xBC26,0xEE,3}, {0xBC27,0xF3,3}, {0xBC28,0xF7,3}, {0xBC29,0xFB,3}, {0xBC2A,0xFF,3}, {0xBC2B,0x08,3}, {0xBC2C,0x12,3}, {0xBC2D,0x23,3}, {0xBC2E,0x3F,3}, {0xBC2F,0x67,3}, {0xBC30,0x85,3}, {0xBC31,0x9B,3}, {0xBC32,0xAD,3}, {0xBC33,0xBB,3}, {0xBC34,0xC7,3}, {0xBC35,0xD1,3}, {0xBC36,0xDA,3}, {0xBC37,0xE1,3}, {0xBC38,0xE8,3}, {0xBC39,0xEE,3}, {0xBC3A,0xF3,3}, {0xBC3B,0xF7,3}, {0xBC3C,0xFB,3}, {0xBC3D,0xFF,3}, {0xBC3E,0x12,3}, {0xBC3F,0x1C,3}, {0xBC40,0x26,3}, {0xBC41,0x40,3}, {0xBC42,0x50,3}, {0xBC43,0x70,3}, {0xBC44,0x81,3}, {0xBC45,0x90,3}, {0xBC46,0x9E,3}, {0xBC47,0xAB,3}, {0xBC48,0xB6,3}, {0xBC49,0xC1,3}, {0xBC4A,0xCB,3}, {0xBC4B,0xD5,3}, {0xBC4C,0xDE,3}, {0xBC4D,0xE7,3}, {0xBC4E,0xEF,3}, {0xBC4F,0xF7,3}, {0xBC50,0xFF,3}, {0x8404,0x06,3}, }; soc5140_short_reg contrast_tbl_3[]= {//+1 {0x098E,0xBC51,4}, // LOGICAL_ADDRESS_ACCESS [LL_GAMMA_CURVE_SELECTOR] {0xBC51,0x02,3}, // LL_GAMMA_CURVE_SELECTOR {0xBC18,0x00,3}, // LL_GAMMA_CONTRAST_CURVE_0 {0xBC19,0x08,3}, // LL_GAMMA_CONTRAST_CURVE_1 {0xBC1A,0x17,3}, // LL_GAMMA_CONTRAST_CURVE_2 {0xBC1B,0x2F,3}, // LL_GAMMA_CONTRAST_CURVE_3 {0xBC1C,0x50,3}, // LL_GAMMA_CONTRAST_CURVE_4 {0xBC1D,0x6D,3}, // LL_GAMMA_CONTRAST_CURVE_5 {0xBC1E,0x88,3}, // LL_GAMMA_CONTRAST_CURVE_6 {0xBC1F,0x9E,3}, // LL_GAMMA_CONTRAST_CURVE_7 {0xBC20,0xAF,3}, // LL_GAMMA_CONTRAST_CURVE_8 {0xBC21,0xBD,3}, // LL_GAMMA_CONTRAST_CURVE_9 {0xBC22,0xC9,3}, // LL_GAMMA_CONTRAST_CURVE_10 {0xBC23,0xD3,3}, // LL_GAMMA_CONTRAST_CURVE_11 {0xBC24,0xDB,3}, // LL_GAMMA_CONTRAST_CURVE_12 {0xBC25,0xE3,3}, // LL_GAMMA_CONTRAST_CURVE_13 {0xBC26,0xEA,3}, // LL_GAMMA_CONTRAST_CURVE_14 {0xBC27,0xF0,3}, // LL_GAMMA_CONTRAST_CURVE_15 {0xBC28,0xF5,3}, // LL_GAMMA_CONTRAST_CURVE_16 {0xBC29,0xFA,3}, // LL_GAMMA_CONTRAST_CURVE_17 {0xBC2A,0xFF,3}, // LL_GAMMA_CONTRAST_CURVE_18 {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg contrast_tbl_4[]= {//+2 {0x098E,0xBC51,4}, // LOGICAL_ADDRESS_ACCESS [LL_GAMMA_CURVE_SELECTOR] {0xBC51,0x02,3}, // LL_GAMMA_CURVE_SELECTOR {0xBC18,0x00,3}, // LL_GAMMA_CONTRAST_CURVE_0 {0xBC19,0x04,3}, // LL_GAMMA_CONTRAST_CURVE_1 {0xBC1A,0x0C,3}, // LL_GAMMA_CONTRAST_CURVE_2 {0xBC1B,0x1A,3}, // LL_GAMMA_CONTRAST_CURVE_3 {0xBC1C,0x32,3}, // LL_GAMMA_CONTRAST_CURVE_4 {0xBC1D,0x4C,3}, // LL_GAMMA_CONTRAST_CURVE_5 {0xBC1E,0x68,3}, // LL_GAMMA_CONTRAST_CURVE_6 {0xBC1F,0x87,3}, // LL_GAMMA_CONTRAST_CURVE_7 {0xBC20,0xA1,3}, // LL_GAMMA_CONTRAST_CURVE_8 {0xBC21,0xB5,3}, // LL_GAMMA_CONTRAST_CURVE_9 {0xBC22,0xC4,3}, // LL_GAMMA_CONTRAST_CURVE_10 {0xBC23,0xD1,3}, // LL_GAMMA_CONTRAST_CURVE_11 {0xBC24,0xDB,3}, // LL_GAMMA_CONTRAST_CURVE_12 {0xBC25,0xE3,3}, // LL_GAMMA_CONTRAST_CURVE_13 {0xBC26,0xEA,3}, // LL_GAMMA_CONTRAST_CURVE_14 {0xBC27,0xF0,3}, // LL_GAMMA_CONTRAST_CURVE_15 {0xBC28,0xF6,3}, // LL_GAMMA_CONTRAST_CURVE_16 {0xBC29,0xFA,3}, // LL_GAMMA_CONTRAST_CURVE_17 {0xBC2A,0xFF,3}, // LL_GAMMA_CONTRAST_CURVE_18 {0x8404,0x06,3}, // SEQ_CMD }; // ************************** //Brightness setting // ************************** soc5140_short_reg brightness_tbl_0[]= {//-3 {0x337E,0x0000,4}, // Y_RGB_OFFSET //{0xA805,0x04,3}, // RESERVED_AE_TRACK_05 {0xA409,0x0A,3}, // AE_RULE_BASE_TARGET {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg brightness_tbl_1[]= {//-2 {0x337E,0x0000,4}, // Y_RGB_OFFSET //{0xA805,0x04,3}, // RESERVED_AE_TRACK_05 {0xA409,0x1E,3}, // AE_RULE_BASE_TARGET {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg brightness_tbl_2[]= {//-1 {0x337E,0x0000,4}, // Y_RGB_OFFSET //{0xA805,0x04,3}, // RESERVED_AE_TRACK_05 {0xA409,0x28,3}, // AE_RULE_BASE_TARGET {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg brightness_tbl_3[]= {//default {0x337E,0x0000,4}, // Y_RGB_OFFSET //{0xA805,0xXX,3}, // RESERVED_AE_TRACK_05 {0xA409,0x3A,3}, // AE_RULE_BASE_TARGET {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg brightness_tbl_4[]= {//-1 {0x337E,0x1000,4}, // Y_RGB_OFFSET //{0xA805,0x04,3}, // RESERVED_AE_TRACK_05 {0xA409,0x3F,3}, // AE_RULE_BASE_TARGET {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg brightness_tbl_5[]= {//-2 {0x337E,0x2000,4}, // Y_RGB_OFFSET //{0xA805,0x04,3}, // RESERVED_AE_TRACK_05 {0xA409,0x3F,3}, // AE_RULE_BASE_TARGET {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg brightness_tbl_6[]= {//-3 {0x337E,0x3000,4}, // Y_RGB_OFFSET //{0xA805,0x04,3}, // RESERVED_AE_TRACK_05 {0xA409,0x3F,3}, // AE_RULE_BASE_TARGET {0x8404,0x06,3}, // SEQ_CMD }; // ********************* //Saturation setting // ********************* soc5140_short_reg saturation_tbl_0[]= {//-2 {0xBC56,0x00,3}, // LL_START_CCM_SATURATION {0xBC57,0x00,3}, // LL_END_CCM_SATURATION {0x098E,0xDC35,4}, // LOGICAL_ADDRESS_ACCESS [SYS_UV_COLOR_BOOST] {0xDC35,0x04,3}, // SYS_UV_COLOR_BOOST {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg saturation_tbl_1[]= {//-1 {0xBC56,0x40,3}, // LL_START_CCM_SATURATION {0xBC57,0x10,3}, // LL_END_CCM_SATURATION {0x098E,0xDC35,4}, // LOGICAL_ADDRESS_ACCESS [SYS_UV_COLOR_BOOST] {0xDC35,0x04,3}, // SYS_UV_COLOR_BOOST {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg saturation_tbl_2[]= {//default {0xBC56,0x40,3}, // LL_START_CCM_SATURATION {0xBC57,0x25,3}, // LL_END_CCM_SATURATION {0x098E,0xDC35,4}, // LOGICAL_ADDRESS_ACCESS [SYS_UV_COLOR_BOOST] {0xDC35,0x05,3}, // SYS_UV_COLOR_BOOST {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg saturation_tbl_3[]= {//+1 {0xBC56,0xe4,3}, // LL_START_CCM_SATURATION {0xBC57,0x60,3}, // LL_END_CCM_SATURATION {0x098E,0xDC35,3}, // LOGICAL_ADDRESS_ACCESS [SYS_UV_COLOR_BOOST] {0xDC35,0x05,3}, // SYS_UV_COLOR_BOOST {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg saturation_tbl_4[]= {//+2 {0xBC56,0xC2,3}, // LL_START_CCM_SATURATION {0xBC57,0x80,3}, // LL_END_CCM_SATURATION {0x098E,0xDC35,4}, // LOGICAL_ADDRESS_ACCESS [SYS_UV_COLOR_BOOST] {0xDC35,0x06,3}, // SYS_UV_COLOR_BOOST {0x8404,0x06,3}, // SEQ_CMD }; /* // *************************** //sharpness // *************************** soc5140_short_reg sharpnees_0[]= {//-2 {0x098E,0x33c2,4}, {0x33c2,0x0000,4}, {0x33BA,0x0000,4}, {0x8404,0x06,3}, }; soc5140_short_reg sharpnees_1[]= {//-1 {0x098E,0x33c2,4}, {0x33c2,0x0000,4}, {0x33BA,0x003A,4}, {0x8404,0x06,3}, }; soc5140_short_reg sharpnees_2[]= {//default {0x098E,0x33c2,4}, {0x33c2,0x1000,4}, {0x33BA,0x006A,4}, {0x8404,0x06,3}, }; soc5140_short_reg sharpnees_3[]= {//+1 {0x098E,0x33c2,4}, {0x33c2,0x3300,4}, {0x33BA,0x006D,4}, {0x8404,0x06,3}, }; soc5140_short_reg sharpnees_4[]= {//+2 {0x098E,0x33c2,4}, {0x33c2,0x6600,4}, {0x33BA,0x006F,4}, {0x8404,0x06,3}, }; // ************************* //JPEG setting // ************************* soc5140_short_reg jpeg_fine[]= { {0x098E,0xD80F,4}, // LOGICAL_ADDRESS_ACCESS [JPEG_QSCALE_0] {0xD80F,0x06,3}, // JPEG_QSCALE_0 {0xD810,0x06,3}, // JPEG_QSCALE_1 {0xC8D2,0x06,3}, // CAM_OUTPUT_1_JPEG_QSCALE_0 {0xC8D3,0x06,3}, // CAM_OUTPUT_1_JPEG_QSCALE_1 {0xC8BC,0x06,3}, // CAM_OUTPUT_0_JPEG_QSCALE_0 {0xC8BD,0x06,3}, // CAM_OUTPUT_0_JPEG_QSCALE_1 {0x098E,0xD80F,4}, // LOGICAL_ADDRESS_ACCESS {0xD80F,0x06,3}, // JPEG_QSCALE_0 {0xD810,0x06,3}, // JPEG_QSCALE_1 {0xC8D2,0x06,3}, // CAM_OUTPUT_1_JPEG_QSCALE_0 {0xC8D3,0x06,3}, // CAM_OUTPUT_1_JPEG_QSCALE_1 {0xC8BC,0x06,3}, // CAM_OUTPUT_0_JPEG_QSCALE_0 {0xC8BD,0x06,3}, // CAM_OUTPUT_0_JPEG_QSCALE_1 }; soc5140_short_reg jpeg_normal[]= { {0x098E,0xD80F,4}, // LOGICAL_ADDRESS_ACCESS [JPEG_QSCALE_0] {0xD80F,0x0A,3}, // JPEG_QSCALE_0 {0xD810,0x0A,3}, // JPEG_QSCALE_1 {0xC8D2,0x0A,3}, // CAM_OUTPUT_1_JPEG_QSCALE_0 {0xC8D3,0x0A,3}, // CAM_OUTPUT_1_JPEG_QSCALE_1 {0xC8BC,0x0A,3}, // CAM_OUTPUT_0_JPEG_QSCALE_0 {0xC8BD,0x0A,3}, // CAM_OUTPUT_0_JPEG_QSCALE_1 {0x098E,0xD80F,4}, // LOGICAL_ADDRESS_ACCESS {0xD80F,0x0A,3}, // JPEG_QSCALE_0 {0xD810,0x0A,3}, // JPEG_QSCALE_1 {0xC8D2,0x0A,3}, // CAM_OUTPUT_1_JPEG_QSCALE_0 {0xC8D3,0x0A,3}, // CAM_OUTPUT_1_JPEG_QSCALE_1 {0xC8BC,0x0A,3}, // CAM_OUTPUT_0_JPEG_QSCALE_0 {0xC8BD,0x0A,3}, // CAM_OUTPUT_0_JPEG_QSCALE_1 }; soc5140_short_reg jpeg_economy[]= { {0x098E,0xD80F,4}, // LOGICAL_ADDRESS_ACCESS [JPEG_QSCALE_0] {0xD80F,0x0E,3}, // JPEG_QSCALE_0 {0xD810,0x0E,3}, // JPEG_QSCALE_1 {0xC8D2,0x0E,3}, // CAM_OUTPUT_1_JPEG_QSCALE_0 {0xC8D3,0x0E,3}, // CAM_OUTPUT_1_JPEG_QSCALE_1 {0xC8BC,0x0E,3}, // CAM_OUTPUT_0_JPEG_QSCALE_0 {0xC8BD,0x0E,3}, // CAM_OUTPUT_0_JPEG_QSCALE_1 {0x098E,0xD80F,4}, // LOGICAL_ADDRESS_ACCESS {0xD80F,0x0E,3}, // JPEG_QSCALE_0 {0xD810,0x0E,3}, // JPEG_QSCALE_1 {0xC8D2,0x0E,3}, // CAM_OUTPUT_1_JPEG_QSCALE_0 {0xC8D3,0x0E,3}, // CAM_OUTPUT_1_JPEG_QSCALE_1 {0xC8BC,0x0E,3}, // CAM_OUTPUT_0_JPEG_QSCALE_0 {0xC8BD,0x0E,3}, // CAM_OUTPUT_0_JPEG_QSCALE_1 }; */ // ************************* //High ISO setting // ************************* soc5140_short_reg iso_100[]= { {0x098E,0x281C,4}, // LOGICAL_ADDRESS_ACCESS [AE_TRACK_MIN_AGAIN] {0xA81C,0x0060,4}, // AE_TRACK_MIN_AGAIN {0xA81E,0x00DC,4}, // AE_TRACK_TARGET_AGAIN {0xA820,0x0154,4}, // AE_TRACK_MAX_AGAIN {0x098E,0x8404,4}, // LOGICAL_ADDRESS_ACCESS [SEQ_CMD] {0x8404,0x06,3}, // SEQ_CMD //DELAY=300 }; soc5140_short_reg iso_200[]= { {0x098E,0x281C,4}, // LOGICAL_ADDRESS_ACCESS [AE_TRACK_MIN_AGAIN] {0xA81C,0x0080,4}, // AE_TRACK_MIN_AGAIN {0xA81E,0x00DC,4}, // AE_TRACK_TARGET_AGAIN {0xA820,0x0154,4}, // AE_TRACK_MAX_AGAIN {0x098E,0x8404,4}, // LOGICAL_ADDRESS_ACCESS [SEQ_CMD] {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg iso_400[]= { {0x098E,0x281C,4}, // LOGICAL_ADDRESS_ACCESS [AE_TRACK_MIN_AGAIN] {0xA81C,0x00B0,4}, // AE_TRACK_MIN_AGAIN {0xA81E,0x00E2,4}, // AE_TRACK_TARGET_AGAIN {0xA820,0x0164,4}, // AE_TRACK_MAX_AGAIN {0x098E,0x8404,4}, // LOGICAL_ADDRESS_ACCESS [SEQ_CMD] {0x8404,0x06,3}, // SEQ_CMD //DELAY=300 }; soc5140_short_reg iso_800[]= { {0x098E,0x281C,4}, // LOGICAL_ADDRESS_ACCESS [AE_TRACK_MIN_AGAIN] {0xA81C,0x0100,4}, // AE_TRACK_MIN_AGAIN {0xA81E,0x00EC,4}, // AE_TRACK_TARGET_AGAIN {0xA820,0x0174,4}, // AE_TRACK_MAX_AGAIN {0x098E,0x8404,4}, // LOGICAL_ADDRESS_ACCESS [SEQ_CMD] {0x8404,0x06,3}, // SEQ_CMD //DELAY=300 }; soc5140_short_reg iso_auto[]= { {0x098E,0x281C,4}, // LOGICAL_ADDRESS_ACCESS [AE_TRACK_MIN_AGAIN] {0xA81C,0x0060,4}, // AE_TRACK_MIN_AGAIN {0xA81E,0x00DC,4}, // AE_TRACK_TARGET_AGAIN {0xA81A,0x09E7,4}, {0xA820,0x0154,4}, // AE_TRACK_MAX_AGAIN {0xA82A,0x0061,4}, {0xA818,0x070B,4}, {0x098E,0x8404,4}, // LOGICAL_ADDRESS_ACCESS [SEQ_CMD] {0x8404,0x06,3}, // SEQ_CMD //DELAY=300 }; /* // ************************* //Night shot setting // ************************* soc5140_short_reg night_off[]= { {0x098E,0x281A,4}, // LOGICAL_ADDRESS_ACCESS [AE_TRACK_MAX_INT_TIME_ROWS] {0xA81A,0x09E7,4}, // AE_TRACK_MAX_INT_TIME_ROWS {0x098E,0x8404,4}, // LOGICAL_ADDRESS_ACCESS {0x8404,0x06,3}, // SEQ_CMD }; soc5140_short_reg night_on[]= { {0x098E,0x281A,4}, // LOGICAL_ADDRESS_ACCESS [AE_TRACK_MAX_INT_TIME_ROWS] {0xA81A,0x2710,4}, // AE_TRACK_MAX_INT_TIME_ROWS {0x098E,0x8404,4}, // LOGICAL_ADDRESS_ACCESS {0x8404,0x06,3}, // SEQ_CMD }; // ***************************** //AF_mode // ***************************** soc5140_short_reg macro_mode_1[]= { {0x098E,0xB018,4}, // LOGICAL_ADDRESS_ACCESS {0xB018,0x67,3}, // AF_FS_POS_0 {0xB019,0x80,3}, // AF_FS_POS_1 {0xB01A,0x99,3}, // AF_FS_POS_2 {0xB01B,0xCB,3}, // AF_FS_POS_3 {0xB01C,0xE4,3}, // AF_FS_POS_4 {0xB01D,0xFF,3}, // AF_FS_POS_5 {0xB012,0x06,3}, // AF_FS_NUM_STEPS //AFM_POS_APPLY_Workaround {0x098E,0x8419,4}, // LOGICAL_ADDRESS_ACCESS [SEQ_STATE_CFG_1_AF] {0x8419,0x01,3}, // SEQ_STATE_CFG_1_AF {0x8404,0x06,3}, // SEQ_CMD }; //DELAY=50 soc5140_short_reg macro_mode_2[]= { {0x098E,0xB007,4}, // LOGICAL_ADDRESS_ACCESS [SEQ_STATE_CFG_1_AF] {0xB007,0xFF,3}, // AF_BEST_LENS_POS {0x098E,0x8419,4}, // LOGICAL_ADDRESS_ACCESS {0x8419,0x05,3}, // SEQ_STATE_CFG_1_AF {0x8404,0x06,3}, // SEQ_CMD //DELAY=50 }; soc5140_short_reg normal_mode_1[]= { //[Normal mode] XX is initial settings {0x098E,0xB018,4}, // LOGICAL_ADDRESS_ACCESS {0xB018,0x06,3}, // AF_FS_POS_0 {0xB019,0x1E,3}, // AF_FS_POS_1 {0xB01A,0x3C,3}, // AF_FS_POS_2 {0xB01B,0x5A,3}, // AF_FS_POS_3 {0xB01C,0x78,3}, // AF_FS_POS_4 {0xB01D,0x96,3}, // AF_FS_POS_5 {0x801E,0xB4,3}, {0X801F,0xD2,3}, {0xB012,0x0A,3}, // AF_FS_NUM_STEPS //AFM_POS_APPLY_Workaround {0x098E,0x8419,4}, // LOGICAL_ADDRESS_ACCESS [SEQ_STATE_CFG_1_AF] {0x8419,0x01,3}, // SEQ_STATE_CFG_1_AF {0x8404,0x06,3}, // SEQ_CMD //DELAY=50 }; soc5140_short_reg normal_mode_2[]= { {0x098E,0xB007,4}, // LOGICAL_ADDRESS_ACCESS [SEQ_STATE_CFG_1_AF] //{0xB007,0x25,3}, // AF_BEST_LENS_POS {0x098E,0x8419,4}, // LOGICAL_ADDRESS_ACCESS {0x8419,0x05,3}, // SEQ_STATE_CFG_1_AF {0x8404,0x06,3}, // SEQ_CMD //DELAY=50 }; */ //--------------------------------------------------------------------------------------------- #define MT9P111_BURST_DATA_MODE /* sequentially write sensor registers */ #ifdef MT9P111_BURST_DATA_MODE static unsigned char burst_settings[] = { 0xC0, 0xF1, 0xC5, 0xE1, 0x24, 0x6A, 0x12, 0x80, 0xC4, 0xE1, 0xD3, 0x0E, 0x20, 0x69, 0x00, 0x00, 0x13, 0x05, 0x00, 0x84, 0x17, 0x30, 0x70, 0x05, 0xD8, 0x01, 0x8B, 0x41, 0xD9, 0x00, 0x0D, 0x5E, 0x06, 0x64, 0x8B, 0x63, 0xE8, 0x09, 0xD5, 0x09, 0xF0, 0x04, 0x15, 0x04, 0x14, 0x00, 0x78, 0x40, 0xD0, 0x07, 0x0D, 0xFB, 0x90, 0x04, 0xC4, 0xC1, 0x20, 0x29, 0x03, 0x00, 0x02, 0x1D, 0x06, 0xC4, 0xFF, 0x80, 0x08, 0xC4, 0xFF, 0x80, 0x08, 0x6C, 0xFF, 0x80, 0x08, 0xBC, 0xFF, 0x80, 0x08, 0xC4, 0xFF, 0x80, 0x08, 0xCC, 0xFF, 0x80, 0x09, 0x78, 0x00, 0x02, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xF1, 0x09, 0x86, 0x06, 0xE4, 0xDA, 0x30, 0xD1, 0x38, 0xD5, 0x39, 0x0F, 0x1A, 0x06, 0xA4, 0x25, 0x40, 0x1B, 0x00, 0xD0, 0x37, 0x25, 0x40, 0x1B, 0x01, 0x76, 0xA9, 0xA5, 0x0F, 0xD0, 0x36, 0xA0, 0x20, 0xD1, 0x36, 0x11, 0x20, 0x00, 0x82, 0x11, 0x21, 0x00, 0x80, 0x11, 0x25, 0x00, 0x83, 0xBA, 0x08, 0x7A, 0x05, 0xD0, 0x32, 0x18, 0xEA, 0x00, 0x84, 0x11, 0x24, 0x00, 0x82, 0x10, 0xE9, 0x00, 0x81, 0xBA, 0x08, 0xB9, 0xA0, 0x18, 0xE9, 0x00, 0x42, 0xD1, 0x2E, 0x7A, 0x65, 0x18, 0xEC, 0x00, 0x84, 0xDB, 0x51, 0x89, 0x00, 0x19, 0xB2, 0x00, 0xC2, 0xDA, 0x08, 0xDB, 0x52, 0xB8, 0xA6, 0xA9, 0x00, 0xD8, 0xF0, 0x19, 0xB1, 0x00, 0x02, 0x19, 0xB5, 0x00, 0x02, 0xD8, 0x55, 0x19, 0xB6, 0x00, 0x02, 0xD8, 0x56, 0x19, 0xB7, 0x00, 0x02, 0xD8, 0x96, 0x19, 0xB8, 0x00, 0x04, 0xD8, 0x14, 0x19, 0xBA, 0x00, 0x04, 0xD8, 0x05, 0xB1, 0x11, 0x19, 0xB0, 0x00, 0x82, 0x19, 0xB3, 0x00, 0xC2, 0x19, 0xB4, 0x00, 0x82, 0xD1, 0x1C, 0x70, 0xC9, 0x0E, 0x8E, 0x06, 0xA4, 0xDA, 0x2C, 0xD0, 0x1B, 0xA5, 0x03, 0xD0, 0x1B, 0x01, 0x4D, 0x06, 0xE4, 0xA0, 0xC0, 0x78, 0xE0, 0xC0, 0xF1, 0xC5, 0xE1, 0xD0, 0x18, 0xD5, 0x0F, 0xA5, 0x17, 0xD0, 0x18, 0x25, 0x55, 0x15, 0xC1, 0xA5, 0x18, 0xD0, 0x17, 0xA5, 0x19, 0xD0, 0x17, 0xA5, 0x1A, 0xD0, 0x17, 0xA0, 0x20, 0xD1, 0x17, 0x25, 0x55, 0x16, 0xC0, 0x0E, 0x56, 0x06, 0xA4, 0xDA, 0x38, 0xD0, 0x15, 0x25, 0x55, 0x16, 0xC1, 0x1D, 0x90, 0x10, 0x00, 0xD0, 0x13, 0x01, 0x19, 0x06, 0xE4, 0xA0, 0x20, 0x00, 0x00, 0xF3, 0x70, 0xFF, 0x80, 0x0F, 0x9C, 0xFF, 0x80, 0x0E, 0xAC, 0x80, 0x00, 0x00, 0x38, 0xFF, 0x80, 0x02, 0x50, 0xFF, 0x80, 0x04, 0x1C, 0xFF, 0x80, 0x03, 0x14, 0x00, 0x00, 0xF4, 0x44, 0xFF, 0x80, 0x0D, 0x28, 0x80, 0x00, 0x00, 0x9C, 0xFF, 0x80, 0x0C, 0xA0, 0x00, 0x00, 0x07, 0x0C, 0xFF, 0x80, 0x0D, 0x1C, 0x00, 0x00, 0x07, 0x44, 0x80, 0x00, 0x00, 0x08, 0x00, 0x00, 0xF3, 0xBC, 0xFF, 0x80, 0x0C, 0x70, 0x80, 0x00, 0x00, 0x8C, 0xC0, 0xF1, 0x08, 0x52, 0x06, 0xE4, 0x70, 0x98, 0xD0, 0xE2, 0x80, 0x41, 0x8A, 0xA1, 0x6A, 0xC2, 0x8A, 0x0A, 0x6D, 0x29, 0x79, 0x2D, 0xE8, 0x87, 0xD8, 0x01, 0xAA, 0x0A, 0x22, 0x40, 0x04, 0x00, 0xA2, 0x03, 0x8A, 0x00, 0xE0, 0x80, 0x20, 0xCA, 0x01, 0x01, 0xF2, 0xB9, 0xD3, 0xDA, 0x8B, 0x02, 0x8B, 0xE3, 0xB8, 0x08, 0x78, 0xE5, 0x08, 0xEB, 0x00, 0x9E, 0x8B, 0xE6, 0x8A, 0x08, 0xE7, 0x82, 0x20, 0xCC, 0x80, 0x21, 0x20, 0xCC, 0x80, 0x62, 0xF4, 0x6B, 0x8B, 0x00, 0x8B, 0xA1, 0xB8, 0x08, 0x78, 0xA5, 0xB8, 0x83, 0xB8, 0x8C, 0x28, 0x41, 0x02, 0x0D, 0xAB, 0xA0, 0xAB, 0x01, 0x8A, 0x08, 0xE8, 0x85, 0x1A, 0x09, 0x01, 0x02, 0xD8, 0x01, 0xAA, 0x08, 0x09, 0x3B, 0x00, 0x12, 0x70, 0x28, 0x78, 0x0D, 0xE0, 0x01, 0x70, 0x9F, 0x75, 0x28, 0x20, 0xA8, 0x05, 0x00, 0x77, 0xCF, 0xFF, 0x80, 0x01, 0x58, 0x66, 0xA8, 0x17, 0x04, 0x10, 0x85, 0x8A, 0xE9, 0x70, 0xB0, 0x27, 0xCC, 0x90, 0x0B, 0xF6, 0x8C, 0x0F, 0x2D, 0x10, 0x03, 0x8A, 0x01, 0xBD, 0x61, 0x7D, 0xAD, 0xB8, 0x61, 0xAA, 0x01, 0x71, 0xA9, 0x70, 0x88, 0x75, 0x28, 0xF0, 0x25, 0xD9, 0x02, 0xAB, 0x26, 0x8A, 0x21, 0xB9, 0x61, 0xAA, 0x21, 0x82, 0x23, 0x19, 0x01, 0x00, 0x12, 0xA2, 0x23, 0xF0, 0x1B, 0x8A, 0x00, 0x75, 0x30, 0xAA, 0x01, 0xD8, 0x01, 0x20, 0xCA, 0x00, 0xA1, 0xAB, 0x06, 0xD9, 0x00, 0xAA, 0x28, 0x8B, 0x00, 0x8B, 0xC1, 0xB8, 0x08, 0x78, 0xC5, 0xB8, 0xA3, 0x28, 0x41, 0x02, 0x0E, 0xAB, 0xC0, 0xAB, 0x01, 0x82, 0x03, 0xA8, 0xE0, 0x22, 0x40, 0x04, 0x00, 0xA2, 0x03, 0x70, 0xE9, 0xAA, 0x2A, 0x0D, 0xAF, 0x10, 0x13, 0x8A, 0x20, 0x8A, 0x09, 0xDD, 0x00, 0xAA, 0x21, 0xD9, 0x01, 0xAB, 0x26, 0xAA, 0xA8, 0x8B, 0x20, 0x8B, 0xC1, 0xB9, 0x08, 0x79, 0xC5, 0xB9, 0xA3, 0x29, 0x41, 0x02, 0x0C, 0xAB, 0x80, 0xAB, 0x21, 0x82, 0x23, 0xA9, 0x00, 0x22, 0x40, 0x04, 0x01, 0xA2, 0x23, 0xF0, 0x3E, 0x09, 0x2B, 0x00, 0x12, 0x70, 0x28, 0x78, 0x0D, 0x20, 0x40, 0x00, 0x7C, 0x20, 0xA8, 0x03, 0xC0, 0x77, 0xCF, 0xFF, 0x80, 0x01, 0x58, 0x8F, 0xE4, 0x66, 0x28, 0x08, 0x13, 0x03, 0xC2, 0xBD, 0x61, 0x7D, 0xAF, 0xAA, 0xA1, 0xB9, 0x61, 0x79, 0x2D, 0x70, 0x88, 0xF0, 0x0B, 0x8B, 0xA6, 0xBD, 0x61, 0xAB, 0xA6, 0x8A, 0xA1, 0xBD, 0x61, 0xAA, 0xA1, 0x82, 0xA3, 0x1D, 0x01, 0x10, 0x12, 0xA2, 0xA3, 0x09, 0x3F, 0x00, 0x13, 0x8A, 0x20, 0xAA, 0x21, 0x8B, 0x20, 0x8B, 0xA1, 0xB9, 0x08, 0x79, 0xA5, 0xB9, 0xA3, 0x29, 0x41, 0x02, 0x0D, 0xAB, 0xA0, 0xAB, 0x21, 0x82, 0x23, 0x19, 0x01, 0x00, 0x12, 0xA2, 0x23, 0x8B, 0x22, 0x8B, 0xA3, 0xB9, 0x08, 0x79, 0xA5, 0x09, 0x13, 0x00, 0x9F, 0x8A, 0x2A, 0xE9, 0x07, 0x22, 0x40, 0x04, 0x01, 0xA2, 0x23, 0xDD, 0x00, 0xAA, 0xAA, 0x07, 0x21, 0x06, 0x84, 0x78, 0xE0, 0xC0, 0xF1, 0x0E, 0xAA, 0x06, 0x84, 0xD6, 0x7D, 0x75, 0x08, 0xD1, 0x7B, 0x8E, 0x01, 0x11, 0x46, 0x00, 0x82, 0x20, 0x46, 0x00, 0xC0, 0xAE, 0x01, 0x11, 0x45, 0x00, 0x80, 0xB8, 0x08, 0x78, 0x45, 0x08, 0x17, 0x00, 0x1E, 0x89, 0x00, 0x89, 0x41, 0xB8, 0x08, 0x78, 0x45, 0x08, 0x0B, 0x00, 0xDE, 0x70, 0xA9, 0xFF, 0x8C, 0x75, 0x08, 0x16, 0x04, 0x10, 0x90, 0x0D, 0x93, 0x14, 0x00, 0x8E, 0xEA, 0x8E, 0x0B, 0x21, 0x4A, 0x20, 0x40, 0x8E, 0x2D, 0xBF, 0x08, 0x7F, 0x05, 0x8E, 0x0C, 0xB8, 0x08, 0x78, 0x25, 0x77, 0x10, 0x21, 0xC2, 0x24, 0x4C, 0x08, 0x1D, 0x03, 0xE3, 0xD9, 0xFF, 0x27, 0x02, 0x10, 0x02, 0x2A, 0x05, 0x03, 0x7E, 0x0F, 0x26, 0x06, 0xA4, 0x70, 0x2F, 0x78, 0x10, 0x7F, 0x02, 0x7F, 0xF0, 0xF0, 0x0B, 0x78, 0xE2, 0x28, 0x05, 0x03, 0x7E, 0x0F, 0x12, 0x06, 0xA4, 0x70, 0x2F, 0x78, 0x10, 0x67, 0x1F, 0x7F, 0xF0, 0x8E, 0x08, 0xD1, 0x5D, 0x7F, 0xEF, 0xBF, 0x06, 0xB8, 0xC3, 0x78, 0xE5, 0xB8, 0x8F, 0x19, 0x08, 0x00, 0x24, 0x28, 0x41, 0x02, 0x01, 0x1E, 0x26, 0x10, 0x42, 0x0D, 0x15, 0x14, 0x23, 0x1E, 0x27, 0x10, 0x02, 0x21, 0x4C, 0xA0, 0x00, 0x21, 0x4A, 0x20, 0x40, 0x21, 0xC2, 0x24, 0x42, 0x8E, 0x21, 0x21, 0x4F, 0x00, 0x40, 0x09, 0x0F, 0x20, 0x10, 0x21, 0x45, 0x01, 0x81, 0xAE, 0x21, 0xF0, 0x03, 0xB8, 0xA2, 0xAE, 0x01, 0x0A, 0xAA, 0xFF, 0xE3, 0x70, 0xA9, 0x06, 0x39, 0x06, 0x84, 0xC0, 0xF1, 0x0D, 0xE2, 0x06, 0x84, 0xD5, 0x47, 0x8D, 0x00, 0x8D, 0x21, 0xB8, 0x08, 0x78, 0x25, 0x0E, 0x06, 0x01, 0x64, 0x20, 0x44, 0x02, 0x0E, 0x8D, 0x20, 0x8D, 0x41, 0xB9, 0x08, 0x79, 0x45, 0x79, 0xC5, 0x29, 0x41, 0x02, 0x02, 0xAD, 0x40, 0x06, 0x25, 0x06, 0xA4, 0xAD, 0x21, 0x78, 0xE0, 0xC0, 0xF1, 0x0D, 0xB2, 0x06, 0x84, 0xD5, 0x3C, 0x8D, 0x00, 0x08, 0x53, 0x01, 0xDE, 0xB8, 0xA7, 0x79, 0x0F, 0x17, 0x4F, 0xF6, 0x0E, 0xAD, 0x00, 0x09, 0x27, 0x00, 0x50, 0x09, 0x2F, 0x01, 0x10, 0x09, 0x0F, 0x02, 0x10, 0xD0, 0x36, 0x09, 0xAE, 0xFF, 0xE3, 0xA6, 0x00, 0xF0, 0x11, 0xD0, 0x35, 0x17, 0x3A, 0xF6, 0x01, 0xA1, 0x18, 0xD0, 0x34, 0xA1, 0x1A, 0xD0, 0x34, 0xF0, 0x08, 0xD0, 0x34, 0x17, 0x36, 0xF6, 0x01, 0xA1, 0x18, 0xD0, 0x33, 0xF1, 0xF8, 0xD0, 0x33, 0xA6, 0x00, 0x86, 0x00, 0x80, 0x23, 0x79, 0x60, 0xD8, 0x01, 0xD8, 0x00, 0xAD, 0x05, 0x15, 0x28, 0x10, 0x80, 0x08, 0x1B, 0x01, 0xDE, 0xB8, 0xA7, 0x1D, 0x28, 0x10, 0x02, 0x17, 0x39, 0xF6, 0x00, 0x80, 0x00, 0x80, 0x23, 0x79, 0x60, 0x15, 0x28, 0x10, 0x80, 0x05, 0xA9, 0x06, 0x84, 0x78, 0xE0, 0xD2, 0x1E, 0x8A, 0x21, 0xB9, 0xA1, 0x78, 0x2F, 0x7F, 0xE0, 0xAA, 0x21, 0xC0, 0xF1, 0x0D, 0x2A, 0x06, 0x84, 0x17, 0x28, 0xF6, 0x0E, 0x8E, 0x01, 0xB8, 0xA4, 0xAE, 0x01, 0x8E, 0x09, 0x20, 0x51, 0x80, 0x00, 0xF2, 0xB3, 0x17, 0x21, 0xF6, 0x0D, 0x15, 0x3A, 0x10, 0x80, 0x15, 0x3B, 0x10, 0x81, 0xB8, 0x08, 0x78, 0x25, 0x16, 0xB8, 0x11, 0x01, 0x09, 0x2B, 0x00, 0x03, 0x16, 0xB0, 0x10, 0x82, 0x1E, 0x3C, 0x10, 0x82, 0x16, 0xB1, 0x10, 0x82, 0x1E, 0x3D, 0x10, 0x82, 0x16, 0xB4, 0x10, 0x82, 0x1E, 0x3E, 0x10, 0x82, 0x16, 0xB5, 0x10, 0x82, 0x1E, 0x3F, 0x10, 0x82, 0x8E, 0x40, 0xBA, 0xA6, 0xAE, 0x40, 0x09, 0xBF, 0x00, 0x22, 0x16, 0xBA, 0x11, 0x02, 0x0A, 0xB7, 0x00, 0x03, 0xF0, 0x18, 0xFF, 0x80, 0x0F, 0x94, 0xFF, 0x80, 0x02, 0x90, 0xFF, 0x80, 0x01, 0x58, 0xFF, 0x00, 0x06, 0x18, 0x00, 0x00, 0xF1, 0xA4, 0xFF, 0x80, 0x0B, 0x9C, 0x00, 0x00, 0x09, 0x98, 0xFF, 0x80, 0x0F, 0xF8, 0x00, 0x00, 0x07, 0x48, 0x00, 0x00, 0x08, 0x38, 0x00, 0x00, 0xF1, 0xC4, 0x16, 0xB2, 0x10, 0x84, 0x0E, 0x2A, 0x06, 0x64, 0x16, 0xB0, 0x10, 0x83, 0x1E, 0x3C, 0x10, 0x02, 0x15, 0x3A, 0x10, 0x80, 0x15, 0x3B, 0x10, 0x81, 0x16, 0xB3, 0x10, 0x84, 0xB8, 0x08, 0x78, 0x25, 0x16, 0xB8, 0x11, 0x01, 0x16, 0xBA, 0x11, 0x02, 0x0E, 0x06, 0x06, 0x64, 0x16, 0xB1, 0x10, 0x83, 0x1E, 0x3D, 0x10, 0x02, 0x15, 0x3A, 0x10, 0x80, 0x15, 0x3B, 0x10, 0x81, 0x16, 0xB6, 0x10, 0x84, 0xB8, 0x08, 0x78, 0x25, 0x16, 0xB8, 0x11, 0x01, 0x16, 0xBA, 0x11, 0x02, 0x0D, 0xE2, 0x06, 0x64, 0x16, 0xB4, 0x10, 0x83, 0x1E, 0x3E, 0x10, 0x02, 0x15, 0x3A, 0x10, 0x80, 0x15, 0x3B, 0x10, 0x81, 0x16, 0xB7, 0x10, 0x84, 0xB8, 0x08, 0x78, 0x25, 0x16, 0xB8, 0x11, 0x01, 0x16, 0xBA, 0x11, 0x02, 0x0D, 0xBE, 0x06, 0x64, 0x16, 0xB5, 0x10, 0x83, 0x1E, 0x3F, 0x10, 0x02, 0x8E, 0x00, 0xB8, 0xA6, 0xAE, 0x00, 0x15, 0x3A, 0x10, 0x81, 0x15, 0x3B, 0x10, 0x80, 0xB9, 0x08, 0x79, 0x05, 0x16, 0xBA, 0x11, 0x00, 0x08, 0x5B, 0x00, 0x42, 0xD0, 0x3D, 0x9E, 0x31, 0x90, 0x4D, 0x0A, 0x2B, 0x00, 0x63, 0x8E, 0x00, 0x16, 0xB0, 0x10, 0x81, 0x1E, 0x3C, 0x10, 0x42, 0x16, 0xB1, 0x10, 0x81, 0x1E, 0x3D, 0x10, 0x42, 0x16, 0xB4, 0x10, 0x81, 0x1E, 0x3E, 0x10, 0x42, 0x16, 0xB5, 0x10, 0x81, 0x1E, 0x3F, 0x10, 0x42, 0xB8, 0x86, 0xF0, 0x12, 0x16, 0xB2, 0x10, 0x81, 0xB8, 0xA6, 0x1E, 0x3C, 0x10, 0x42, 0x16, 0xB3, 0x10, 0x81, 0x1E, 0x3D, 0x10, 0x42, 0x16, 0xB6, 0x10, 0x81, 0x1E, 0x3E, 0x10, 0x42, 0x16, 0xB7, 0x10, 0x81, 0x1E, 0x3F, 0x10, 0x42, 0xAE, 0x00, 0x0C, 0x8E, 0x01, 0x84, 0x04, 0x19, 0x06, 0x84, 0x78, 0xE0, 0xC0, 0xF1, 0xD0, 0x26, 0x80, 0x00, 0x80, 0x03, 0x78, 0x40, 0xD2, 0x25, 0x12, 0xE9, 0x00, 0x80, 0x08, 0x7F, 0x00, 0x1E, 0x12, 0xEA, 0x01, 0x03, 0xD1, 0x22, 0x2B, 0x41, 0x02, 0x00, 0x19, 0x20, 0x00, 0x02, 0x12, 0xEC, 0x01, 0x02, 0x19, 0x21, 0x00, 0xC2, 0x2A, 0x41, 0x02, 0x00, 0x19, 0x24, 0x00, 0x02, 0xD0, 0x1D, 0x88, 0x0E, 0x19, 0x25, 0x00, 0x82, 0x08, 0x51, 0x00, 0x51, 0xD0, 0x16, 0x11, 0x39, 0x00, 0x83, 0x90, 0x46, 0x11, 0x38, 0x00, 0x80, 0xB8, 0x08, 0x78, 0x65, 0x08, 0x43, 0x00, 0x83, 0x11, 0x2A, 0x00, 0x82, 0x11, 0x2B, 0x00, 0x80, 0xBA, 0x08, 0x7A, 0x05, 0x2A, 0x41, 0x02, 0x00, 0x19, 0x20, 0x00, 0x02, 0x11, 0x29, 0x00, 0x80, 0x19, 0x21, 0x00, 0x82, 0x11, 0x28, 0x00, 0x82, 0xBA, 0x08, 0x7A, 0x05, 0x2A, 0x41, 0x02, 0x00, 0x19, 0x24, 0x00, 0x02, 0x89, 0x01, 0x19, 0x25, 0x00, 0x82, 0xB8, 0x86, 0xF0, 0x04, 0x89, 0x01, 0xB8, 0xA6, 0xA9, 0x01, 0xC0, 0xD1, 0x7E, 0xE0, 0x78, 0xE0, 0xFF, 0x80, 0x05, 0x0C, 0x80, 0x00, 0x00, 0xA0, 0xFF, 0x80, 0x04, 0x1C, 0xFF, 0x80, 0x02, 0x50, 0xFF, 0x80, 0x07, 0xA8, 0xEA, 0x0A, 0x24, 0x2F, 0x70, 0x89, 0x78, 0xE0, 0x20, 0xA8, 0x01, 0x80, 0x10, 0x02, 0x0D, 0x02, 0x19, 0x02, 0x00, 0x94, 0x7F, 0xE0, 0x70, 0x28, 0x73, 0x08, 0x10, 0x00, 0x09, 0x00, 0x79, 0x04, 0x79, 0x47, 0x1B, 0x00, 0x00, 0x64, 0x7E, 0xE0, 0xEA, 0x0A, 0x24, 0x2F, 0x70, 0x89, 0x78, 0xE0, 0x20, 0xA8, 0x01, 0x80, 0x11, 0x02, 0x05, 0x02, 0x18, 0x02, 0x00, 0xB4, 0x7F, 0xE0, 0x70, 0x28, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x80, 0x10, 0x40, }; #endif /* static unsigned short lsc_def_p0[20] = { 0x0290, 0x0E0D, 0x63D1, 0x0C2B, 0xF0B0, 0x0570, 0x95AE, 0x0911, 0x488F, 0xD2D0, 0x0130, 0x0C8D, 0x6F30, 0xAA0D, 0xC34F, 0x01F0, 0xBC2E, 0x5831, 0x0BEE, 0x80B1 }; static unsigned short lsc_def_p1[20] = { 0xD06C, 0xFFEE, 0x340D, 0x574E, 0x864D, 0x15AE, 0xBC25, 0xE0CD, 0x0B4E, 0x97AD, 0xBC4C, 0x718D, 0x62CE, 0xA18F, 0x84EF, 0xF10A, 0xF06E, 0x4EEF, 0x1CEE, 0xA630 }; static unsigned short lsc_def_p2[20] = { 0x6071, 0x404E, 0x154E, 0xBBAF, 0x9D8E, 0x2FF1, 0xD68E, 0x250F, 0x4E0C, 0x02F0, 0x38F1, 0x46CF, 0x180F, 0xE84F, 0x72F0, 0x7951, 0x8CB0, 0x0EAF, 0x2890, 0x8BD0 }; static unsigned short lsc_def_p3[20] = { 0xA64D, 0x140F, 0x8450, 0x9431, 0x0C52, 0x056E, 0x4C4D, 0x4BCF, 0xA64F, 0xB9D1, 0xAC0F, 0xD2AE, 0x21F0, 0x3D30, 0xC26A, 0xD88E, 0x7B2B, 0x1D0A, 0xA86F, 0x22F1 }; static unsigned short lsc_def_p4[20] = { 0xBC0F, 0x3490, 0x9B11, 0xEA92, 0x8995, 0xE30F, 0x00B0, 0x30D2, 0xB132, 0x8935, 0x98AF, 0x264C, 0x6751, 0xBB31, 0xAC15, 0xB20F, 0x78D1, 0xBD91, 0xB073, 0xF334 }; static unsigned short lsc_def_row_col[2] = { 0x03F0, 0x04B8 }; //--------------------------------------------------------------------------------------------- */ #endif
billy-wang/smdkc110-Gingerbread-kernel
drivers/media/video/soc5140.h
C
gpl-2.0
147,205
# ILDAview a tool for previewing ILDA files
2-2-0/ILDAview
README.md
Markdown
gpl-2.0
44
\documentclass[12pt]{article} \usepackage{sbc-template} \usepackage{graphicx,url} %\usepackage[brazil]{babel} %\usepackage[latin1]{inputenc} \usepackage[utf8x]{inputenc} \sloppy \title{Máquina de Turing Universal e sua Influência na \\ Arquitetura dos Computadores Modernos \\} \author{Tiago Augusto Engel\inst{1}, Vanderlan Dupont de Oliveira\inst{1}} \address{Acadêmicos de Ciência da Computação\\ Universidade Federal de Santa Maria -- UFSM \email{\{tengel, voliveira\}@inf.ufsm.br}} \begin{document} \maketitle \begin{resumo} Este artigo descreve a Máquina de Turing Universal. O objetivo é apresentar resumidamente o que é a máquina, quais as suas características e a sua influência na Arquitetura dos Computadores Modernos, a qual baseia-se nas idéias desenvolvidas por John Von Neumann. \end{resumo} \begin{abstract} This paper describes the Universal Turing Machine. The goal is to summarize what is the machine, which are its features and its influence on the architecture of modern computers which is based on the ideas developed by Von Neumann. \end{abstract} \section{Introdução} As primeiras ideias de computador surgiram com Alan Turing e sua ideias de “uma única máquina que pode ser usada para computar qualquer sequência computável”, depois as ideias dividiram-se em duas versões. Uma delas é britânica e foi batizada de Colossus, computador construído pela equipe de Turing no Bletchley Park para viabilizar a quebra de códigos de guerra Alemães que eram conhecidos como Códigos Enigma. A outra versão é Americana e começa com a construção do ENIAC na Universidade de Pensilvânia em 1943, e continua através da industrialização dessa tecnologia através de indústrias como Univac e IBM, que foram pioneiras na criação de um mundo o qual o computador se tornou ferramenta indispensável. Este artigo é dividido em duas seções principais. A seção dois trata de Alan Turing e sua máquina. A terceira seção trata da arquitetura de Von Neumann e como ela se relaciona com o modelo proposto por Turing. \section{Máquina de Turing} Alan Turing ousou perguntar se uma máquina pode pensar. Suas contribuições para entender e responder à essa e outras questões desafiam classificações convencionais. No final do século XX, o conceito de máquina de Turing, criado em 1936, figura não apenas na matemática e na ciência da computação, mas também na ciência cognitiva e na biologia teórica \cite{hodges1999}. Seu artigo \emph{Computing machinery and intelligence} \cite{Turing1950} no qual é descrito o assim chamando Teste de Turing, constitui um marco para a teoria da inteligência artificial. Turing desempenhou um papel decisivo no resultado da Segunda Guerra Mundial, produzindo sozinho um plano muito avançado para a construção e o uso de um computador eletrônico. Em 1936 Turing escreveu um artigo entitulado \emph{On Computable Numbers, with an Application to the Entscheidungsproblem}~\cite{Turing1936} que descrevia uma máquina hipotética a qual ele chamou "Máquina Universal de Computação", a qual ficou conhecida como "Máquina de Turing Universal". A máquina hipotética tinha um armazenamento infinito que continha instruções e dados. Esse artigo é considerado o mais importante de toda a história da computação. Uma Máquina de Turing Universal (MTU) é uma Máquina de Turing que consegue simular qualquer outra máquina de Turing a partir da descrição daquela máquina. Essencialmente, essa simulação é realizada lendo-se tanto a descrição da máquina a ser simulada quanto sua respectiva entrada representada pelo conteúdo de sua fita. \begin{figure}[!ht] \centering \includegraphics[width=.5\textwidth]{fig1.jpg} \caption{Desenho esquemático de uma Máquina de Turing} \label{fig:exampleFig1} \end{figure} Este modelo é considerado por alguns, segundo ~\cite{davis2001} como a origem do Computador com Programa Armazenado, usado por John von Neumann, denominado Arquitetura de Von Neumann. Ele se familiarizou com o trabalho de Turing que era professor visitante em Cambridge no ano de 1935. Se Neumann sabia do artigo de Turing de 1936 naquela época não é claro. Naquela época, os computadores de guerra eram programados reconstruindo-se a maquina para realizar uma tarefa diferente. Por exemplo, o computador ENIAC tomou três semanas para poder desempenhar uma tarefa diferente. A nova ideia era de que não somente os dados deveriam ser guardados em memória, mas o programa que processa aquele dado também deveria ser armazenado na mesma memória. Essa ideia significava que um computador constuído com essa arquitetura seria muito mais fácil de programar. Efetivamente, o programa em si era tratado como dado. \section{ Arquitetura de Von Neumann} A Máquina de Turing foi aprimorada por Neumann em uma arquitetura de computadores que fundamenta os computadores construídos até hoje. Assim, a Arquitetura de Von Neumann, como é conhecida, é uma arquitetura de computador que se caracteriza pela possibilidade de uma máquina digital armazenar seus programas no mesmo espaço de memória que os dados, podendo assim manipular tais programas ~\cite{vonneumann}. Essa nova arquitetura de Programa Armazenado foi comumente conhecida por Arquitetura de Von Neumann. Os fundamentos de seu trabalho foram descritas no artigo chamado \emph{First Draft of a Report on the EDVAC} \cite{von1945} em tradução literal seria "Primeiros Rascunhos de um Relatório no EDVAC". O mesmo foi escrito na primavera de 1945 e distribuída para o pessoal da Moore Escola de Engenharia. O artigo apresentou a primeira descrição escrita do conceito de programa armazenado e explicou como o programa armazenado processa informação. O relatório organizou o computador em quatro partes principais: A Unidade Central de Aritmética, Unidade Central de Controle, a Memória e os dispositivos de entrada e saída. A Unidade de Lógica era responsável por efetuar as quatro operações básicas. A Unidade de Controle oferecia a sequência apropriada de operações e fazia as unidades individuais agirem juntas para carregar uma tarefa específica programada o sistema. A Memória deveria armazenar dados numéricos e instruções codificadas numericamente. As unidade de Entrada e Saída servem de interface de interação para os usuários do computador. Um diagrama básico da organização de Neumann pode ser visto na figura \ref{fig:exampleFig2}: \begin{figure}[!ht] \centering \includegraphics[width=.3\textwidth]{fig2.jpg} \caption{Diagrama esquemático da arquitetura de Von Neumann.} \label{fig:exampleFig2} \end{figure} Essa arquitetura é utilizada ainda hoje nos computadores. As diversas unidades são conectadas por um barramento (bus) de dados. A memória de acesso randômico remete à fita da máquina de Turing, ela é randômica no sentido de que qualquer posição de memória tem o mesmo tempo de acesso. A partir do conceito de manipulação de endereços de memória surgiram os conceitos das primeiras linguagens de programação Imperativas. Isso significa que efetuar uma computação implicaria em alterar endereços de memória para chegar em algum resultado. Esse conceito é utilizado nas linguagens mais utilizadas hoje em dia, ele é possível graças à arquitetura desenvolvida. \section{Conclusão} Turing introduziu seu modelo abstrato de máquina na sua primeira grande publicação \emph{On Computable Numbers, with an Application to the Entscheidungsproblem}~\cite{Turing1936}. Esse artigo foi pioneiro da idéia essencial do computador moderno. O conceito de controlar as operações de uma máquina através de instruções codificadas armazenadas na memória se aplica em toda a computação atual. Não é citada diretamente por Neumann em seu primeiro trabalho a respeito do trabalho que tinha sido desenvolvido anteriormente por Turing. Alguns estudiosos do assunto como ~\cite{davis2001} acreditam que Neumann sabia sobre o que Turing estava desenvolvendo. O fato é que essas duas mentes são consideradas as criadoras da Computação. \bibliographystyle{sbc} \bibliography{ref} \end{document}
tiiago11/turing-machine
paper/turing-neumann.tex
TeX
gpl-2.0
8,210
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>wibble: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">wibble &#160;<span id="projectnumber">0.1.28</span> </div> </td> </tr> </tbody> </table> </div> <!-- Generated by Doxygen 1.7.6.1 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="structTestList.html">TestList</a> </li> <li class="navelem"><a class="el" href="structTestList_1_1My2.html">My2</a> </li> </ul> </div> </div> <div class="header"> <div class="headertitle"> <div class="title">TestList::My2 Member List</div> </div> </div><!--header--> <div class="contents"> This is the complete list of members for <a class="el" href="structTestList_1_1My2.html">TestList::My2</a>, including all inherited members.<table> <tr class="memlist"><td><a class="el" href="structTestList_1_1My2.html#a563a936484c3b8f831f65bb333cb9c80">empty</a>() const </td><td><a class="el" href="structTestList_1_1My2.html">TestList::My2</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="structTestList_1_1My2.html#a9d4083d5814bfa8c77dc94fff708bdbd">head</a>() const </td><td><a class="el" href="structTestList_1_1My2.html">TestList::My2</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="structTestList_1_1My2.html#a06115848c931d7e7de4b38910d25fc69">i</a></td><td><a class="el" href="structTestList_1_1My2.html">TestList::My2</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="structTestList_1_1My2.html#a9ce75dd7c810edea36938b574b5c2877">max</a></td><td><a class="el" href="structTestList_1_1My2.html">TestList::My2</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="structTestList_1_1My2.html#a01be6b252767cc5d563fb71ffdd33566">My2</a>(int j=0, int m=0, int r=0)</td><td><a class="el" href="structTestList_1_1My2.html">TestList::My2</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="structTestList_1_1My2.html#a8c20fb378b628d758ff05f43ddb8f273">rep</a></td><td><a class="el" href="structTestList_1_1My2.html">TestList::My2</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="structTestList_1_1My2.html#aa11111cf311c3a904d0d686d94799e1f">repmax</a></td><td><a class="el" href="structTestList_1_1My2.html">TestList::My2</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="structTestList_1_1My2.html#a1ad8ab85675770df0fe88ff64f1a4a83">tail</a>() const </td><td><a class="el" href="structTestList_1_1My2.html">TestList::My2</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="structTestList_1_1My2.html#ac92038ffad07753300a1a1d516cffd9a">Type</a> typedef</td><td><a class="el" href="structTestList_1_1My2.html">TestList::My2</a></td><td></td></tr> </table></div><!-- contents --> <hr class="footer"/><address class="footer"><small> Generated on Wed May 2 2012 23:57:31 for wibble by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.7.6.1 </small></address> </body> </html>
2ndy/RaspIM
usr/share/doc/libwibble-dev/html/structTestList_1_1My2-members.html
HTML
gpl-2.0
4,382
# Makefile.in generated by automake 1.11.6 from Makefile.am. # Makefile. Generated from Makefile.in by configure. # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. # FLAC - Free Lossless Audio Codec # Copyright (C) 2001-2009 Josh Coalson # Copyright (C) 2011-2013 Xiph.Org Foundation # # This file is part the FLAC project. FLAC is comprised of several # components distributed under different licenses. The codec libraries # are distributed under Xiph.Org's BSD-like license (see the file # COPYING.Xiph in this distribution). All other programs, libraries, and # plugins are distributed under the GPL (see COPYING.GPL). The documentation # is distributed under the Gnu FDL (see COPYING.FDL). Each file in the # FLAC distribution contains at the top the terms under which it may be # distributed. # # Since this particular file is relevant to all components of FLAC, # it may be distributed under the Xiph.Org license, which is the least # restrictive of those mentioned above. See the file COPYING.Xiph in this # distribution. # # automake provides the following useful targets: # # all: build all programs and libraries using the current # configuration (set by configure) # # check: build and run all self-tests # # clean: remove everything except what's required to build everything # # distclean: remove everything except what goes in the distribution # am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/flac pkgincludedir = $(includedir)/flac pkglibdir = $(libdir)/flac pkglibexecdir = $(libexecdir)/flac am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = x86_64-pc-linux-gnu host_triplet = arm-unknown-linux-androideabi subdir = . DIST_COMMON = README $(am__configure_deps) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in $(srcdir)/config.h.in \ $(top_srcdir)/configure AUTHORS ar-lib compile config.guess \ config.rpath config.sub depcomp install-sh ltmain.sh missing ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/add_cflags.m4 \ $(top_srcdir)/m4/bswap.m4 $(top_srcdir)/m4/codeset.m4 \ $(top_srcdir)/m4/gcc_version.m4 $(top_srcdir)/m4/iconv.m4 \ $(top_srcdir)/m4/lib-ld.m4 $(top_srcdir)/m4/lib-link.m4 \ $(top_srcdir)/m4/lib-prefix.m4 $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/ogg.m4 $(top_srcdir)/m4/stack_protect.m4 \ $(top_srcdir)/m4/xmms.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \ configure.lineno config.status.lineno mkinstalldirs = $(install_sh) -d CONFIG_HEADER = config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = AM_V_GEN = $(am__v_GEN_$(V)) am__v_GEN_ = $(am__v_GEN_$(AM_DEFAULT_VERBOSITY)) am__v_GEN_0 = @echo " GEN " $@; AM_V_at = $(am__v_at_$(V)) am__v_at_ = $(am__v_at_$(AM_DEFAULT_VERBOSITY)) am__v_at_0 = @ SOURCES = DIST_SOURCES = RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ html-recursive info-recursive install-data-recursive \ install-dvi-recursive install-exec-recursive \ install-html-recursive install-info-recursive \ install-pdf-recursive install-ps-recursive install-recursive \ installcheck-recursive installdirs-recursive pdf-recursive \ ps-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ distdir dist dist-all distcheck ETAGS = etags CTAGS = ctags DIST_SUBDIRS = $(SUBDIRS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) distdir = $(PACKAGE)-$(VERSION) top_distdir = $(distdir) am__remove_distdir = \ if test -d "$(distdir)"; then \ find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \ && rm -rf "$(distdir)" \ || { sleep 5 && rm -rf "$(distdir)"; }; \ else :; fi am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" GZIP_ENV = --best DIST_ARCHIVES = $(distdir).tar.xz distuninstallcheck_listfiles = find . -type f -print am__distuninstallcheck_listfiles = $(distuninstallcheck_listfiles) \ | sed 's|^\./|$(prefix)/|' | grep -v '$(infodir)/dir$$' distcleancheck_listfiles = find . -type f -print ACLOCAL = ${SHELL} /home/ddt/Documents/VLC0924/android/vlc/contrib/android/flac/missing --run aclocal-1.11 AMTAR = $${TAR-tar} AM_DEFAULT_VERBOSITY = 0 AR = arm-linux-androideabi-ar AS = gas AUTOCONF = ${SHELL} /home/ddt/Documents/VLC0924/android/vlc/contrib/android/flac/missing --run autoconf AUTOHEADER = ${SHELL} /home/ddt/Documents/VLC0924/android/vlc/contrib/android/flac/missing --run autoheader AUTOMAKE = ${SHELL} /home/ddt/Documents/VLC0924/android/vlc/contrib/android/flac/missing --run automake-1.11 AWK = mawk CC = arm-linux-androideabi-gcc --sysroot=/home/ddt/Documents/android-sdk/android-ndk-r9/platforms/android-9/arch-arm -std=gnu99 CCAS = arm-linux-androideabi-gcc --sysroot=/home/ddt/Documents/android-sdk/android-ndk-r9/platforms/android-9/arch-arm -c CCASDEPMODE = depmode=none CCASFLAGS = -g -mfpu=vfpv3-d16 -mcpu=cortex-a8 -mthumb -mfloat-abi=softfp -O2 -I/home/ddt/Documents/android-sdk/android-ndk-r9/sources/cxx-stl/gnu-libstdc++/4.8/include -I/home/ddt/Documents/android-sdk/android-ndk-r9/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include -g CCDEPMODE = depmode=none CFLAGS = -g -mfpu=vfpv3-d16 -mcpu=cortex-a8 -mthumb -mfloat-abi=softfp -O2 -I/home/ddt/Documents/android-sdk/android-ndk-r9/sources/cxx-stl/gnu-libstdc++/4.8/include -I/home/ddt/Documents/android-sdk/android-ndk-r9/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include -g -Wstrict-prototypes -Wmissing-prototypes -Waggregate-return -Wcast-align -Wnested-externs -Wshadow -Wundef -Wmissing-declarations -fvisibility=hidden -Wextra -Wdeclaration-after-statement -D_FORTIFY_SOURCE=2 CPP = arm-linux-androideabi-gcc --sysroot=/home/ddt/Documents/android-sdk/android-ndk-r9/platforms/android-9/arch-arm -std=gnu99 -E CPPFLAGS = -DNDEBUG -g -mfpu=vfpv3-d16 -mcpu=cortex-a8 -mthumb -mfloat-abi=softfp -O2 -I/home/ddt/Documents/android-sdk/android-ndk-r9/sources/cxx-stl/gnu-libstdc++/4.8/include -I/home/ddt/Documents/android-sdk/android-ndk-r9/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include -DFLAC__USE_VISIBILITY_ATTR CXX = arm-linux-androideabi-g++ --sysroot=/home/ddt/Documents/android-sdk/android-ndk-r9/platforms/android-9/arch-arm CXXCPP = arm-linux-androideabi-g++ --sysroot=/home/ddt/Documents/android-sdk/android-ndk-r9/platforms/android-9/arch-arm -E CXXDEPMODE = depmode=none CXXFLAGS = -g -mfpu=vfpv3-d16 -mcpu=cortex-a8 -mthumb -mfloat-abi=softfp -O2 -I/home/ddt/Documents/android-sdk/android-ndk-r9/sources/cxx-stl/gnu-libstdc++/4.8/include -I/home/ddt/Documents/android-sdk/android-ndk-r9/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include -g -Wcast-align -Wshadow -Wwrite-strings -Wctor-dtor-privacy -Wnon-virtual-dtor -Wreorder -Wsign-promo -Wundef -fvisibility=hidden CYGPATH_W = echo DEFS = -DHAVE_CONFIG_H DEPDIR = .deps DLLTOOL = false DOCBOOK_TO_MAN = DOXYGEN = DSYMUTIL = DUMPBIN = ECHO_C = ECHO_N = -n ECHO_T = EGREP = /bin/grep -E EXEEXT = FGREP = /bin/grep -F FLAC__TEST_LEVEL = 0 FLAC__TEST_WITH_VALGRIND = no GAS = gas GCC_MAJOR_VERSION = 4 GCC_MINOR_VERSION = 8 GCC_VERSION = 4.8 GREP = /bin/grep INSTALL = /usr/bin/install -c INSTALL_DATA = ${INSTALL} -m 644 INSTALL_PROGRAM = ${INSTALL} INSTALL_SCRIPT = ${INSTALL} INSTALL_STRIP_PROGRAM = $(install_sh) -c -s LD = arm-linux-androideabi-ld LDFLAGS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib LIBICONV = LIBOBJS = LIBS = -lm LIBTOOL = $(SHELL) $(top_builddir)/libtool LIPO = LN_S = ln -s LTLIBICONV = LTLIBOBJS = LT_NO_UNDEFINED = MAKEINFO = ${SHELL} /home/ddt/Documents/VLC0924/android/vlc/contrib/android/flac/missing --run makeinfo MANIFEST_TOOL = : MKDIR_P = /bin/mkdir -p NASM = NM = /home/ddt/Documents/android-sdk/android-ndk-r9/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin/arm-linux-androideabi-nm -B NMEDIT = OBJDUMP = arm-linux-androideabi-objdump OBJEXT = o OBJ_FORMAT = elf OGG_CFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include OGG_LIBS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -logg OGG_PACKAGE = ogg OTOOL = OTOOL64 = PACKAGE = flac PACKAGE_BUGREPORT = flac-dev@xiph.org PACKAGE_NAME = flac PACKAGE_STRING = flac 1.3.0 PACKAGE_TARNAME = flac PACKAGE_URL = https://www.xiph.org/flac/ PACKAGE_VERSION = 1.3.0 PATH_SEPARATOR = : RANLIB = arm-linux-androideabi-ranlib SED = /bin/sed SET_MAKE = SHELL = /bin/bash STRIP = arm-linux-androideabi-strip VERSION = 1.3.0 XMMS_CFLAGS = XMMS_CONFIG = XMMS_DATA_DIR = XMMS_EFFECT_PLUGIN_DIR = XMMS_GENERAL_PLUGIN_DIR = XMMS_INPUT_PLUGIN_DIR = XMMS_LIBS = XMMS_OUTPUT_PLUGIN_DIR = XMMS_PLUGIN_DIR = XMMS_VERSION = XMMS_VISUALIZATION_PLUGIN_DIR = abs_builddir = /home/ddt/Documents/VLC0924/android/vlc/contrib/android/flac abs_srcdir = /home/ddt/Documents/VLC0924/android/vlc/contrib/android/flac abs_top_builddir = /home/ddt/Documents/VLC0924/android/vlc/contrib/android/flac abs_top_srcdir = /home/ddt/Documents/VLC0924/android/vlc/contrib/android/flac ac_ct_AR = ac_ct_CC = ac_ct_CXX = ac_ct_DUMPBIN = am__include = include am__leading_dot = . am__quote = am__tar = tar --format=posix -chf - "$$tardir" am__untar = tar -xf - bindir = ${exec_prefix}/bin build = x86_64-pc-linux-gnu build_alias = x86_64-linux-gnu build_cpu = x86_64 build_os = linux-gnu build_vendor = pc builddir = . datadir = ${datarootdir} datarootdir = ${prefix}/share docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} dvidir = ${docdir} exec_prefix = ${prefix} host = arm-unknown-linux-androideabi host_alias = arm-linux-androideabi host_cpu = arm host_os = linux-androideabi host_vendor = unknown htmldir = ${docdir} includedir = ${prefix}/include infodir = ${datarootdir}/info install_sh = ${SHELL} /home/ddt/Documents/VLC0924/android/vlc/contrib/android/flac/install-sh libdir = ${exec_prefix}/lib libexecdir = ${exec_prefix}/libexec localedir = ${datarootdir}/locale localstatedir = ${prefix}/var mandir = ${datarootdir}/man mkdir_p = /bin/mkdir -p oldincludedir = /usr/include pdfdir = ${docdir} prefix = /home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi program_transform_name = s&^&& psdir = ${docdir} sbindir = ${exec_prefix}/sbin sharedstatedir = ${prefix}/com srcdir = . sysconfdir = ${prefix}/etc target_alias = arm-linux-androideabi top_build_prefix = top_builddir = . top_srcdir = . ACLOCAL_AMFLAGS = -I m4 SUBDIRS = doc include m4 man src examples test build objs EXTRA_DIST = \ COPYING.FDL \ COPYING.GPL \ COPYING.LGPL \ COPYING.Xiph \ FLAC.sln \ Makefile.lite \ autogen.sh \ config.rpath \ depcomp \ ltmain.sh \ strip_non_asm_libtool_args.sh CLEANFILES = *~ all: config.h $(MAKE) $(AM_MAKEFLAGS) all-recursive .SUFFIXES: am--refresh: Makefile @: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ echo ' cd $(srcdir) && $(AUTOMAKE) --foreign'; \ $(am__cd) $(srcdir) && $(AUTOMAKE) --foreign \ && exit 0; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ echo ' $(SHELL) ./config.status'; \ $(SHELL) ./config.status;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) $(SHELL) ./config.status --recheck $(top_srcdir)/configure: $(am__configure_deps) $(am__cd) $(srcdir) && $(AUTOCONF) $(ACLOCAL_M4): $(am__aclocal_m4_deps) $(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) $(am__aclocal_m4_deps): config.h: stamp-h1 @if test ! -f $@; then rm -f stamp-h1; else :; fi @if test ! -f $@; then $(MAKE) $(AM_MAKEFLAGS) stamp-h1; else :; fi stamp-h1: $(srcdir)/config.h.in $(top_builddir)/config.status @rm -f stamp-h1 cd $(top_builddir) && $(SHELL) ./config.status config.h $(srcdir)/config.h.in: $(am__configure_deps) ($(am__cd) $(top_srcdir) && $(AUTOHEADER)) rm -f stamp-h1 touch $@ distclean-hdr: -rm -f config.h stamp-h1 mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs distclean-libtool: -rm -f libtool config.lt # This directory's subdirectories are mostly independent; you can cd # into them and run `make' without going through this Makefile. # To change the values of `make' variables: instead of editing Makefiles, # (1) if the variable is set in `config.status', edit `config.status' # (which will cause the Makefiles to be regenerated when you run `make'); # (2) otherwise, pass the desired values on the `make' command line. $(RECURSIVE_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ list='$(SUBDIRS)'; for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" $(RECURSIVE_CLEAN_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ rev=''; for subdir in $$list; do \ if test "$$subdir" = "."; then :; else \ rev="$$subdir $$rev"; \ fi; \ done; \ rev="$$rev ."; \ target=`echo $@ | sed s/-recursive//`; \ for subdir in $$rev; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done && test -z "$$fail" tags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ done ctags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ done ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: tags-recursive $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ list='$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: ctags-recursive $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) $(am__remove_distdir) test -d "$(distdir)" || mkdir "$(distdir)" @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done -test -n "$(am__skip_mode_fix)" \ || find "$(distdir)" -type d ! -perm -755 \ -exec chmod u+rwx,go+rx {} \; -o \ ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \ ! -type d ! -perm -400 -exec chmod a+r {} \; -o \ ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \ || chmod -R a+r "$(distdir)" dist-gzip: distdir tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz $(am__remove_distdir) dist-bzip2: distdir tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2 $(am__remove_distdir) dist-lzip: distdir tardir=$(distdir) && $(am__tar) | lzip -c $${LZIP_OPT--9} >$(distdir).tar.lz $(am__remove_distdir) dist-lzma: distdir tardir=$(distdir) && $(am__tar) | lzma -9 -c >$(distdir).tar.lzma $(am__remove_distdir) dist-xz: distdir tardir=$(distdir) && $(am__tar) | XZ_OPT=$${XZ_OPT--e} xz -c >$(distdir).tar.xz $(am__remove_distdir) dist-tarZ: distdir tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z $(am__remove_distdir) dist-shar: distdir shar $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).shar.gz $(am__remove_distdir) dist-zip: distdir -rm -f $(distdir).zip zip -rq $(distdir).zip $(distdir) $(am__remove_distdir) dist dist-all: distdir tardir=$(distdir) && $(am__tar) | XZ_OPT=$${XZ_OPT--e} xz -c >$(distdir).tar.xz $(am__remove_distdir) # This target untars the dist file and tries a VPATH configuration. Then # it guarantees that the distribution is self-contained by making another # tarfile. distcheck: dist case '$(DIST_ARCHIVES)' in \ *.tar.gz*) \ GZIP=$(GZIP_ENV) gzip -dc $(distdir).tar.gz | $(am__untar) ;;\ *.tar.bz2*) \ bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\ *.tar.lzma*) \ lzma -dc $(distdir).tar.lzma | $(am__untar) ;;\ *.tar.lz*) \ lzip -dc $(distdir).tar.lz | $(am__untar) ;;\ *.tar.xz*) \ xz -dc $(distdir).tar.xz | $(am__untar) ;;\ *.tar.Z*) \ uncompress -c $(distdir).tar.Z | $(am__untar) ;;\ *.shar.gz*) \ GZIP=$(GZIP_ENV) gzip -dc $(distdir).shar.gz | unshar ;;\ *.zip*) \ unzip $(distdir).zip ;;\ esac chmod -R a-w $(distdir); chmod u+w $(distdir) mkdir $(distdir)/_build mkdir $(distdir)/_inst chmod a-w $(distdir) test -d $(distdir)/_build || exit 0; \ dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \ && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \ && am__cwd=`pwd` \ && $(am__cd) $(distdir)/_build \ && ../configure --srcdir=.. --prefix="$$dc_install_base" \ $(AM_DISTCHECK_CONFIGURE_FLAGS) \ $(DISTCHECK_CONFIGURE_FLAGS) \ && $(MAKE) $(AM_MAKEFLAGS) \ && $(MAKE) $(AM_MAKEFLAGS) dvi \ && $(MAKE) $(AM_MAKEFLAGS) check \ && $(MAKE) $(AM_MAKEFLAGS) install \ && $(MAKE) $(AM_MAKEFLAGS) installcheck \ && $(MAKE) $(AM_MAKEFLAGS) uninstall \ && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \ distuninstallcheck \ && chmod -R a-w "$$dc_install_base" \ && ({ \ (cd ../.. && umask 077 && mkdir "$$dc_destdir") \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \ distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \ } || { rm -rf "$$dc_destdir"; exit 1; }) \ && rm -rf "$$dc_destdir" \ && $(MAKE) $(AM_MAKEFLAGS) dist \ && rm -rf $(DIST_ARCHIVES) \ && $(MAKE) $(AM_MAKEFLAGS) distcleancheck \ && cd "$$am__cwd" \ || exit 1 $(am__remove_distdir) @(echo "$(distdir) archives ready for distribution: "; \ list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \ sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x' distuninstallcheck: @test -n '$(distuninstallcheck_dir)' || { \ echo 'ERROR: trying to run $@ with an empty' \ '$$(distuninstallcheck_dir)' >&2; \ exit 1; \ }; \ $(am__cd) '$(distuninstallcheck_dir)' || { \ echo 'ERROR: cannot chdir into $(distuninstallcheck_dir)' >&2; \ exit 1; \ }; \ test `$(am__distuninstallcheck_listfiles) | wc -l` -eq 0 \ || { echo "ERROR: files left after uninstall:" ; \ if test -n "$(DESTDIR)"; then \ echo " (check DESTDIR support)"; \ fi ; \ $(distuninstallcheck_listfiles) ; \ exit 1; } >&2 distcleancheck: distclean @if test '$(srcdir)' = . ; then \ echo "ERROR: distcleancheck can only run from a VPATH build" ; \ exit 1 ; \ fi @test `$(distcleancheck_listfiles) | wc -l` -eq 0 \ || { echo "ERROR: files left in build directory after distclean:" ; \ $(distcleancheck_listfiles) ; \ exit 1; } >&2 check-am: all-am check: check-recursive all-am: Makefile config.h installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-recursive -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -f Makefile distclean-am: clean-am distclean-generic distclean-hdr \ distclean-libtool distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -rf $(top_srcdir)/autom4te.cache -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) all \ ctags-recursive install-am install-strip tags-recursive .PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ all all-am am--refresh check check-am clean clean-generic \ clean-libtool ctags ctags-recursive dist dist-all dist-bzip2 \ dist-gzip dist-lzip dist-lzma dist-shar dist-tarZ dist-xz \ dist-zip distcheck distclean distclean-generic distclean-hdr \ distclean-libtool distclean-tags distcleancheck distdir \ distuninstallcheck dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ installdirs-am maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-generic mostlyclean-libtool pdf pdf-am \ ps ps-am tags tags-recursive uninstall uninstall-am fullcheck: (cd test && make fullcheck) # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT:
DDTChen/CookieVLC
vlc/contrib/android/flac/Makefile
Makefile
gpl-2.0
30,043
package models; public class Disparo { public int partida; public int jugador; public int x; public int y; }
iturrioz/izan-pirata
app/models/Disparo.java
Java
gpl-2.0
126
# webportico WebPortico - Amazing Web Gallery for your Websites. Photo Gallery Website Software.
webportico/webportico
README.md
Markdown
gpl-2.0
97
/* ***** BEGIN LICENSE BLOCK ***** * Source last modified: $Id: fio.h,v 1.3 2004/07/09 18:20:23 hubbe Exp $ * * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved. * * The contents of this file, and the files included with this file, * are subject to the current version of the RealNetworks Public * Source License (the "RPSL") available at * http://www.helixcommunity.org/content/rpsl unless you have licensed * the file under the current version of the RealNetworks Community * Source License (the "RCSL") available at * http://www.helixcommunity.org/content/rcsl, in which case the RCSL * will apply. You may also obtain the license terms directly from * RealNetworks. You may not use this file except in compliance with * the RPSL or, if you have a valid RCSL with RealNetworks applicable * to this file, the RCSL. Please see the applicable RPSL or RCSL for * the rights, obligations and limitations governing use of the * contents of the file. * * Alternatively, the contents of this file may be used under the * terms of the GNU General Public License Version 2 or later (the * "GPL") in which case the provisions of the GPL are applicable * instead of those above. If you wish to allow use of your version of * this file only under the terms of the GPL, and not to allow others * to use your version of this file under the terms of either the RPSL * or RCSL, indicate your decision by deleting the provisions above * and replace them with the notice and other provisions required by * the GPL. If you do not delete the provisions above, a recipient may * use your version of this file under the terms of any one of the * RPSL, the RCSL or the GPL. * * This file is part of the Helix DNA Technology. RealNetworks is the * developer of the Original Code and owns the copyrights in the * portions it created. * * This file, and the files included with this file, is distributed * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET * ENJOYMENT OR NON-INFRINGEMENT. * * Technology Compatibility Kit Test Suite(s) Location: * http://www.helixcommunity.org/content/tck * * Contributor(s): * * ***** END LICENSE BLOCK ***** */ #ifndef _UNIXFIO_H_ #define _UNIXFIO_H_ #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include "bio.h" #ifdef _AIX #undef MAXPATH #endif class FileIO : public IO { public: FileIO(const char* file, LONG32 flags, mode_t mode = 0666); ~FileIO(); virtual LONG32 close(); virtual LONG32 read(void* buf, LONG32 size); virtual LONG32 write(const void* buf, LONG32 size); virtual off_t seek(off_t off, LONG32 whence); virtual LONG32 error(); virtual LONG32 flags(); virtual off_t file_size(); static void local_path(char* path); static const LONG32 MAXPATH; static const char PATH_SEP; static const char* NEWLINE; /* Used to have = "\n"; but Irix CC barfed */ static int is_directory(char* path); protected: int fd; LONG32 err; LONG32 _flags; }; inline FileIO::FileIO(const char* file, LONG32 flags, mode_t mode) { err = 0; fd = -1; fd = ::open(file, flags, mode); _flags = flags; if (fd < 0) err = errno; } inline LONG32 FileIO::close() { LONG32 ret = ::close(fd); fd = -1; if (ret < 0) err = errno; return ret; } inline FileIO::~FileIO() { if (fd >= 0) close(); fd = -1; } inline off_t FileIO::seek(off_t off, LONG32 whence) { off_t ret = ::lseek(fd, off, whence); if (ret < 0) err = errno; return ret; } inline LONG32 FileIO::read(void * buf, LONG32 len) { int ret = ::read(fd, buf, len); if (ret < 0) err = errno; return ret; } inline LONG32 FileIO::write(const void * buf, LONG32 len) { LONG32 ret = ::write(fd, buf, len); if (ret < 0) err = errno; return ret; } inline off_t FileIO::file_size() { struct stat st; if (fstat(fd, &st) < 0) { err = errno; return (off_t)-1; } return st.st_size; } inline LONG32 FileIO::error() { return err; } inline LONG32 FileIO::flags() { return _flags; } inline void FileIO::local_path(char* path) { } inline int FileIO::is_directory(char* path) { struct stat st; if (stat(path, &st) < 0) { return 0; } return st.st_mode & S_IFDIR; } #endif /* _UNIXFIO_H_ */
muromec/qtopia-ezx
src/3rdparty/libraries/helix/src/common/fileio/pub/platform/unix/fio.h
C
gpl-2.0
4,618
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.7"/> <title>Affdex SDK for iOS Release 3: AFDXOrientation Class Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="mobileLogo.png"/></td> <td style="padding-left: 0.5em;"> <div id="projectname">Affdex SDK for iOS Release 3 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.7 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Enumerator</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Properties</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-methods">Instance Methods</a> &#124; <a href="#properties">Properties</a> &#124; <a href="class_a_f_d_x_orientation-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">AFDXOrientation Class Reference</div> </div> </div><!--header--> <div class="contents"> <p>This class encapsulates all of the orientation metrics for the face. <a href="interface_a_f_d_x_orientation.html#details">More...</a></p> <p><code>#import &lt;<a class="el" href="_affdex_8h_source.html">Affdex.h</a>&gt;</code></p> <div class="dynheader"> Inheritance diagram for AFDXOrientation:</div> <div class="dyncontent"> <div class="center"> <img src="interface_a_f_d_x_orientation.png" usemap="#AFDXOrientation_map" alt=""/> <map id="AFDXOrientation_map" name="AFDXOrientation_map"> </map> </div></div> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a> Instance Methods</h2></td></tr> <tr class="memitem:ae5e407c9d38bf34f6efdf835f1d8d3be"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae5e407c9d38bf34f6efdf835f1d8d3be"></a> (NSString *)&#160;</td><td class="memItemRight" valign="bottom">- <a class="el" href="interface_a_f_d_x_orientation.html#ae5e407c9d38bf34f6efdf835f1d8d3be">xmlDescription</a></td></tr> <tr class="memdesc:ae5e407c9d38bf34f6efdf835f1d8d3be"><td class="mdescLeft">&#160;</td><td class="mdescRight">Returns an XML representation of the object. <br /></td></tr> <tr class="separator:ae5e407c9d38bf34f6efdf835f1d8d3be"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a8bcc2dc0954595ceeada8baed47b0188"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a8bcc2dc0954595ceeada8baed47b0188"></a> (NSString *)&#160;</td><td class="memItemRight" valign="bottom">- <a class="el" href="interface_a_f_d_x_orientation.html#a8bcc2dc0954595ceeada8baed47b0188">jsonDescription</a></td></tr> <tr class="memdesc:a8bcc2dc0954595ceeada8baed47b0188"><td class="mdescLeft">&#160;</td><td class="mdescRight">Returns a JSON representation of the object. <br /></td></tr> <tr class="separator:a8bcc2dc0954595ceeada8baed47b0188"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="properties"></a> Properties</h2></td></tr> <tr class="memitem:a9e6fa760ae3900aba8e067584c90cd13"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a9e6fa760ae3900aba8e067584c90cd13"></a> CGFloat&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="interface_a_f_d_x_orientation.html#a9e6fa760ae3900aba8e067584c90cd13">yaw</a></td></tr> <tr class="memdesc:a9e6fa760ae3900aba8e067584c90cd13"><td class="mdescLeft">&#160;</td><td class="mdescRight">yaw is the left/right head angle (yaw) for the face (-30 degrees to 30 degrees). <br /></td></tr> <tr class="separator:a9e6fa760ae3900aba8e067584c90cd13"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a95df165dfa61b32e035f5b818af86418"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a95df165dfa61b32e035f5b818af86418"></a> CGFloat&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="interface_a_f_d_x_orientation.html#a95df165dfa61b32e035f5b818af86418">pitch</a></td></tr> <tr class="memdesc:a95df165dfa61b32e035f5b818af86418"><td class="mdescLeft">&#160;</td><td class="mdescRight">pitch is the up/down head angle (pitch) for the face (-30 degrees to 30 degrees). <br /></td></tr> <tr class="separator:a95df165dfa61b32e035f5b818af86418"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:af02c2f613308d2b628b43589c639ba30"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="af02c2f613308d2b628b43589c639ba30"></a> CGFloat&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="interface_a_f_d_x_orientation.html#af02c2f613308d2b628b43589c639ba30">roll</a></td></tr> <tr class="memdesc:af02c2f613308d2b628b43589c639ba30"><td class="mdescLeft">&#160;</td><td class="mdescRight">roll is the roll of the head angle for the face (-60 degrees to 60 degrees). <br /></td></tr> <tr class="separator:af02c2f613308d2b628b43589c639ba30"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a56b0f80081d3632a235019c5e190af47"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a56b0f80081d3632a235019c5e190af47"></a> CGFloat&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="interface_a_f_d_x_orientation.html#a56b0f80081d3632a235019c5e190af47">interocularDistance</a></td></tr> <tr class="memdesc:a56b0f80081d3632a235019c5e190af47"><td class="mdescLeft">&#160;</td><td class="mdescRight">interocularDistance is the distance between the eyes in pixels. <br /></td></tr> <tr class="separator:a56b0f80081d3632a235019c5e190af47"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>This class encapsulates all of the orientation metrics for the face. </p> </div><hr/>The documentation for this class was generated from the following file:<ul> <li>libAffdex/<a class="el" href="_affdex_8h_source.html">Affdex.h</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Wed Jan 27 2016 07:46:16 for Affdex SDK for iOS Release 3 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.7 </small></address> </body> </html>
Affectiva/developerportal
pages/platforms/v3/ios/classdocs/interface_a_f_d_x_orientation.html
HTML
gpl-2.0
9,989
// @(#)$Id: JMLMap.java-generic,v 1.34 2005/12/24 21:20:31 chalin Exp $ // Copyright (C) 2005 Iowa State University // // This file is part of the runtime library of the Java Modeling Language. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 2.1, // of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with JML; see the file LesserGPL.txt. If not, write to the Free // Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA // 02110-1301 USA. package org.jmlspecs.models; import java.util.Enumeration; /** Maps (i.e., binary relations that are functional) from non-null * elements of {@link Object} to non-null elements of {@link * JMLType}. The first type, <kbd>Object</kbd>, is called * the domain type of the map; the second type, * <kbd>JMLType</kbd>, is called the range type of the map. A * map can be seen as a set of pairs, of form <em>(dv, rv)</em>, * consisting of an element of the domain type, <em>dv</em>, and an * element of the range type, <em>rv</em>. Alternatively, it can be * seen as a function that maps each element of the domain to some of * elements of the range type. * * <p> This type is a subtype of {@link * JMLObjectToValueRelation}, and as such as can be treated as a * binary relation or a set valued function also. See the * documentation for {@link JMLObjectToValueRelation} and for the * methods inherited from this supertype for more information. * * <p> This type considers elements <kbd>val</kbd> and <kbd>dv</kbd> * of the domain type, to be distinct just when * <kbd>_val_not_equal_to_dv_</kbd>. It considers elements of * <kbd>r</kbd> and <kbd>rv</kbd> of the range type to be distinct * just when <kbd>_r_not_equal_to_rv_</kbd>. Cloning takes place for * the domain or range elements if the corresponding domain or range * type is {@link JMLType}. * * @version $Revision: 1.34 $ * @author Gary T. Leavens * @author Clyde Ruby * @see JMLCollection * @see JMLType * @see JMLObjectToValueRelation * @see JMLObjectToValueRelationEnumerator * @see JMLObjectToValueRelationImageEnumerator * @see JMLValueSet * @see JMLObjectSet * @see JMLObjectToObjectMap * @see JMLValueToObjectMap * @see JMLObjectToValueMap * @see JMLValueToValueMap * @see JMLObjectToValueRelation#toFunction() */ //-@ immutable public /*@ pure @*/ // FIXME: adapt this file to non-null-by-default and remove the following modifier. /*@ nullable_by_default @*/ class JMLObjectToValueMap extends JMLObjectToValueRelation { /*@ public invariant isaFunction(); @ public invariant_redundantly @ (\forall Object dv; isDefinedAt(dv); @ elementImage(dv).int_size() == 1); @*/ /** Initialize this map to be the empty mapping. * @see #EMPTY */ /*@ public normal_behavior @ assignable theRelation, owner, elementType, containsNull; @ ensures theRelation.equals(new JMLValueSet()); @ ensures_redundantly theRelation.isEmpty(); @*/ public JMLObjectToValueMap() { super(); } /** Initialize this map to be a mapping that maps the given domain * element to the given range element. * @see #singletonMap(Object, JMLType) * @see #JMLObjectToValueMap(JMLObjectValuePair) */ /*@ public normal_behavior @ requires dv != null && rv != null; @ assignable theRelation, owner, elementType, containsNull; @ ensures (theRelation.int_size() == 1) && elementImage(dv).has(rv); @ ensures_redundantly isDefinedAt(dv); @*/ public JMLObjectToValueMap(/*@ non_null @*/ Object dv, /*@ non_null @*/ JMLType rv) { super(dv, rv); } /** Initialize this map to be a mapping that maps the key in the * given pair to the value in that pair. * @see #singletonMap(JMLObjectValuePair) * @see #JMLObjectToValueMap(Object, JMLType) */ /*@ public normal_behavior @ requires pair != null; @ assignable theRelation, owner, elementType, containsNull; @ ensures (theRelation.int_size() == 1) @ && elementImage(pair.key).has(pair.value); @ ensures_redundantly isDefinedAt(pair.key); @*/ public JMLObjectToValueMap(/*@ non_null @*/ JMLObjectValuePair pair) { super(pair.key, pair.value); } /** Initialize this map based on the representation values given. */ //@ requires ipset != null && dom != null && 0 <= sz; //@ assignable theRelation, owner, elementType, containsNull; //@ ensures imagePairSet_ == ipset && domain_ == dom && size_ == sz; protected JMLObjectToValueMap(JMLValueSet ipset, JMLObjectSet dom, int sz) { super(ipset, dom, sz); } /** The empty JMLObjectToValueMap. * @see #JMLObjectToValueMap() */ public static final /*@ non_null @*/ JMLObjectToValueMap EMPTY = new JMLObjectToValueMap(); /** Return the singleton map containing the given association. * @see #JMLObjectToValueMap(Object, JMLType) * @see #singletonMap(JMLObjectValuePair) */ /*@ public normal_behavior @ requires dv != null && rv != null; @ ensures \result != null @ && \result.equals(new JMLObjectToValueMap(dv, rv)); @*/ public static /*@ pure @*/ /*@ non_null @*/ JMLObjectToValueMap singletonMap(/*@ non_null @*/ Object dv, /*@ non_null @*/ JMLType rv) { return new JMLObjectToValueMap(dv, rv); } /** Return the singleton map containing the association described * by the given pair. * @see #JMLObjectToValueMap(JMLObjectValuePair) * @see #singletonMap(Object, JMLType) */ /*@ public normal_behavior @ requires pair != null; @ ensures \result != null @ && \result.equals(new JMLObjectToValueMap(pair)); @*/ public static /*@ pure @*/ /*@ non_null @*/ JMLObjectToValueMap singletonMap(/*@ non_null @*/ JMLObjectValuePair pair) { return new JMLObjectToValueMap(pair); } /** Tells whether this relation is a function. */ /*@ also @ public normal_behavior @ ensures \result; @*/ //@ pure public boolean isaFunction() { return true; } /** Return the range element corresponding to dv, if there is one. * * @param dv the domain element for which an association is * sought (the key to the table). * @exception JMLNoSuchElementException when dv is not associated * to any range element by this. * @see JMLObjectToValueRelation#isDefinedAt * @see JMLObjectToValueRelation#elementImage * @see JMLObjectToValueRelation#image */ /*@ public normal_behavior @ requires isDefinedAt(dv); @ ensures elementImage(dv).has(\result); @ also @ public exceptional_behavior @ requires !isDefinedAt(dv); @ signals_only JMLNoSuchElementException; @*/ public /*@ non_null @*/ JMLType apply(Object dv) throws JMLNoSuchElementException { JMLValueSet img = elementImage(dv); if (img.int_size() == 1) { JMLType res = img.choose(); //@ assume res != null; return res; } else { throw new JMLNoSuchElementException("Map not defined at " + dv); } } //@ nowarn NonNullResult; /*@ also @ public normal_behavior @ ensures \result instanceof JMLObjectToValueMap @ && ((JMLObjectToValueMap)\result) @ .theRelation.equals(this.theRelation); @*/ //@ pure public /*@ non_null @*/ Object clone() { return new JMLObjectToValueMap(imagePairSet_, domain_, size_); } //@ nowarn Post; /** Return a new map that is like this but maps the given domain * element to the given range element. Any previously existing * mapping for the domain element is removed first. * @see JMLObjectToValueRelation#insert(JMLObjectValuePair) */ /*@ public normal_behavior @ requires dv != null && rv != null; @ requires !isDefinedAt(dv) ==> int_size() < Integer.MAX_VALUE; @ ensures \result.equals(this.removeDomainElement(dv).add(dv, rv)); @*/ public /*@ non_null @*/ JMLObjectToValueMap extend(/*@ non_null @*/ Object dv, /*@ non_null @*/ JMLType rv) { JMLObjectToValueMap newMap = this.removeDomainElement(dv); newMap = newMap.disjointUnion(new JMLObjectToValueMap(dv, rv)); return newMap; } //@ nowarn Exception; /** Return a new map that is like this but has no association for the * given domain element. * @see JMLObjectToValueRelation#removeFromDomain */ /*@ public normal_behavior @ ensures \result.equals(removeFromDomain(dv).toFunction()); @ ensures_redundantly !isDefinedAt(dv) ==> \result.equals(this); @*/ public /*@ non_null @*/ JMLObjectToValueMap removeDomainElement(Object dv) { return super.removeFromDomain(dv).toFunction(); } /** Return a new map that is the composition of this and the given * map. The composition is done in the usual order; that is, if * the given map maps x to y and this maps y to z, then the * result maps x to z. * @see #compose(JMLObjectToObjectMap) */ /*@ public normal_behavior @ requires othMap != null; @ ensures (\forall JMLValueValuePair pair; ; @ \result.theRelation.has(pair) @ == (\exists Object val; @ othMap.elementImage(pair.key).has(val); @ this.elementImage(val).has(pair.value) @ ) @ ); @*/ public /*@ non_null @*/ JMLValueToValueMap compose(/*@ non_null @*/ JMLValueToObjectMap othMap) { return super.compose(othMap).toFunction(); } /** Return a new map that is the composition of this and the given * map. The composition is done in the usual order; that is, if * the given map maps x to y and this maps y to z, then the * result maps x to z. * @see #compose(JMLValueToObjectMap) */ /*@ public normal_behavior @ requires othMap != null; @ ensures (\forall JMLObjectValuePair pair; ; @ \result.theRelation.has(pair) @ == (\exists Object val; @ othMap.elementImage(pair.key).has(val); @ this.elementImage(val).has(pair.value) @ ) @ ); @*/ public /*@ non_null @*/ JMLObjectToValueMap compose(/*@ non_null @*/ JMLObjectToObjectMap othMap) { return super.compose(othMap).toFunction(); } /** Return a new map that only maps elements in the given domain * to the corresponding range elements in this map. * @see #rangeRestrictedTo * @see JMLObjectToValueRelation#restrictDomainTo */ /*@ public normal_behavior @ requires dom != null; @ ensures (\forall JMLObjectValuePair pair; ; @ \result.theRelation.has(pair) @ == @ dom.has(pair.key) @ && elementImage(pair.key).has(pair.value) @ ); @*/ public /*@ non_null @*/ JMLObjectToValueMap restrictedTo(/*@ non_null @*/ JMLObjectSet dom) { return super.restrictDomainTo(dom).toFunction(); } /** Return a new map that is like this map but only contains * associations that map to range elements in the given set. * @see #restrictedTo * @see JMLObjectToValueRelation#restrictRangeTo */ /*@ public normal_behavior @ requires rng != null; @ ensures (\forall JMLObjectValuePair pair; ; @ \result.theRelation.has(pair) @ == @ rng.has(pair.value) @ && elementImage(pair.key).has(pair.value) @ ); @*/ public /*@ non_null @*/ JMLObjectToValueMap rangeRestrictedTo(/*@ non_null @*/ JMLValueSet rng) { return super.restrictRangeTo(rng).toFunction(); } /** Return a new map that is like the union of the given map and * this map, except that if both define a mapping for a given domain * element, then only the mapping in the given map is retained. * @see #clashReplaceUnion * @see #disjointUnion * @see JMLObjectToValueRelation#union */ /*@ public normal_behavior @ requires othMap != null; @ requires int_size() @ <= Integer.MAX_VALUE - othMap.difference(this).int_size(); @ ensures (\forall JMLObjectValuePair pair; ; @ \result.theRelation.has(pair) @ == @ othMap.elementImage(pair.key).has(pair.value) @ || (!othMap.isDefinedAt(pair.key) @ && this.elementImage(pair.key).has(pair.value)) @ ); @*/ public /*@ non_null @*/ JMLObjectToValueMap extendUnion(/*@ non_null @*/ JMLObjectToValueMap othMap) throws IllegalStateException { JMLObjectToValueMap newMap = this.restrictedTo(this.domain_.difference(othMap.domain_)); if (newMap.size_ <= Integer.MAX_VALUE - othMap.size_) { return new JMLObjectToValueMap(newMap.imagePairSet_ .union(othMap.imagePairSet_), newMap.domain_ .union(othMap.domain_), newMap.size_ + othMap.size_); } else { throw new IllegalStateException(TOO_BIG_TO_UNION); } } /** Return a new map that is like the union of the given map and * this map, except that if both define a mapping for a given * domain element, then each of these clashes is replaced by a * mapping from the domain element in question to the given range * element. * @param othMap the other map. * @param errval the range element to use when clashes occur. * @see #extendUnion * @see #disjointUnion * @see JMLObjectToValueRelation#union */ /*@ public normal_behavior @ requires othMap != null && errval != null; @ requires int_size() @ <= Integer.MAX_VALUE - othMap.difference(this).int_size(); @ ensures (\forall JMLObjectValuePair pair; ; @ \result.theRelation.has(pair) @ == @ (!othMap.isDefinedAt(pair.key) @ && this.elementImage(pair.key).has(pair.value)) @ || (!this.isDefinedAt(pair.key) @ && othMap.elementImage(pair.key) @ .has(pair.value)) @ || (this.isDefinedAt(pair.key) @ && othMap.isDefinedAt(pair.key) @ && pair.value .equals(errval)) @ ); @ implies_that @ requires othMap != null && errval != null; @*/ public /*@ non_null @*/ JMLObjectToValueMap clashReplaceUnion(JMLObjectToValueMap othMap, JMLType errval) throws IllegalStateException { JMLObjectSet overlap = this.domain_.intersection(othMap.domain_); Enumeration overlapEnum = overlap.elements(); othMap = othMap.restrictedTo(othMap.domain_.difference(overlap)); JMLObjectToValueMap newMap = this.restrictedTo(this.domain_.difference(overlap)); JMLObjectToValueRelation newRel; if (newMap.size_ <= Integer.MAX_VALUE - othMap.size_) { newRel = new JMLObjectToValueRelation(newMap.imagePairSet_ .union(othMap .imagePairSet_), newMap.domain_ .union(othMap.domain_), newMap.size_ + othMap.size_); } else { throw new IllegalStateException(TOO_BIG_TO_UNION); } Object dv; while (overlapEnum.hasMoreElements()) { //@ assume overlapEnum.moreElements; Object oo = overlapEnum.nextElement(); //@ assume oo != null && oo instanceof Object; dv = oo; newRel = newRel.add(dv, errval); } return newRel.toFunction(); } //@ nowarn Exception; /** Return a map that is the disjoint union of this and othMap. * @param othMap the other mapping * @exception JMLMapException the ranges of this and othMap have elements * in common (i.e., when they interesect). * @see #extendUnion * @see #clashReplaceUnion * @see JMLObjectToValueRelation#union */ /*@ public normal_behavior @ requires othMap != null @ && this.domain().intersection(othMap.domain()).isEmpty(); @ requires int_size() <= Integer.MAX_VALUE - othMap.int_size(); @ ensures \result.equals(this.union(othMap)); @ also @ public exceptional_behavior @ requires othMap != null @ && !this.domain().intersection(othMap.domain()).isEmpty(); @ signals_only JMLMapException; @*/ public /*@ non_null @*/ JMLObjectToValueMap disjointUnion(/*@ non_null @*/ JMLObjectToValueMap othMap) throws JMLMapException, IllegalStateException { JMLObjectSet overlappingDom = domain_.intersection(othMap.domain_); if (overlappingDom.isEmpty()) { if (this.size_ <= Integer.MAX_VALUE - othMap.size_) { return new JMLObjectToValueMap(this.imagePairSet_ .union(othMap .imagePairSet_), this.domain_ .union(othMap.domain_), this.size_ + othMap.size_); } else { throw new IllegalStateException(TOO_BIG_TO_UNION); } } else { throw new JMLMapException("Overlapping domains in " + " disjointUnion operation", overlappingDom); } } }
shunghsiyu/OpenJML_XOR
OpenJML/runtime/org/jmlspecs/models/JMLObjectToValueMap.java
Java
gpl-2.0
20,391
/*** This file is part of eudev, forked from systemd. Copyright 2010-2012 Lennart Poettering systemd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. systemd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ #pragma once int dev_setup(const char *pathprefix);
uarka/eudev
src/shared/dev-setup.h
C
gpl-2.0
796
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" /> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script src="<?php echo base_url();?>themes/poverty/js/html5placeholder.jquery.js"></script> <script language="javascript"> jQuery(function(){ jQuery(':input[placeholder]').placeholder(); $( "#dp1" ).datepicker({ showOn: "button", buttonImage: "<?php echo base_url();?>themes/poverty/images/calender_icon.gif", buttonImageOnly: true, minDate: 0, dateFormat: 'yy-mm-dd' }); }); </script> <!-- Start: Content Part --> <div id="content"> <div class="lsize"> <div class="post_a_req"> <div class="l_panel"> <ul class="list_02"> <?php if($this->session->userdata('post_request_approval')==1):?> <li class="active"><a href="<?php echo site_url('/post_a_request/');?>">Post a Request</a></li> <li><a href="<?php echo site_url('/request_published/');?>">Request Published </a></li> <?php endif;?> <?php if($this->session->userdata('dir_approval')==1):?> <li><a href="<?php echo site_url('/directory_page/submit_details/');?>">Submit Directory Listing</a></li> <li><a href="<?php echo site_url('/directory_page/manage_listing/');?>">Manage Directory LIsting </a></li> <?php endif;?> <li><a href="<?php echo site_url('/manage_account/');?>">Manage Account</a></li> <li><a href="<?php echo site_url('/notifications/');?>">Notifications</a></li> </ul> </div> <div class="r_panel"> <div class="content_bg"> <div class="bor_02"> <div class="bor_02"> <div class="bor_02"> <h3>Post a <b>request</b><br /> <span>Want to sign up fill out this form!</span></h3> <div class="text_part form"> <?php if (isset($request_form_errors)):echo "<div id='error'>".$request_form_errors."</div>";endif; ?> <form method="post" action="<?php echo site_url('/post_a_request/submit/');?>" name="frm_Post_A_Request" enctype="multipart/form-data"> <div class="col_01"> <label>Name of Request <input type="text" class="input" id="txtNameOfRequest" name="txtNameOfRequest" placeholder="e.g. A Winter Jacket For A Child" value="<?php echo set_value('txtNameOfRequest');?>" /> </label> <label>Description <textarea name="txtDescription" id="txtDescription" cols="" rows="" class="hei_02"><?php echo set_value('txtDescription');?></textarea> </label> <label>Security Code <?php echo $recaptcha_html; ?></label> </div> <div class="col_01"> <label>Photo <input type="file" size="35" tabindex="5" name="filePhoto" id="filePhoto"/> </label> <label>Quantity Required <input type="text" class="input" placeholder="Type required quantity" id="txtQuantity" name="txtQuantity" value="<?php echo set_value('txtQuantity');?>" /> </label> <label>Deadline <input type="text" class="input" readonly="readonly" name="txtDeadline" placeholder="Select last date" value="<?php echo set_value('txtDeadline');?>" style="width:80%;" id="dp1"/> </label> </div> <div class="clear"></div> <input type="Submit" value="Post a Request" /> </form> </div> </div> </div> </div> </div> </div> <div class="clear"></div> </div> <div id="social_media"> <ul> <li class="facebook"><a href="<?php echo get_setting('facebook_social_link');?>" target="_blank">Facebook</a></li> <li class="twitter"><a href="<?php echo get_setting('twitter_social_link');?>" target="_blank">Twitter</a></li> <li class="g_plus"><a href="<?php echo get_setting('google_social_link');?>" target="_blank">Google Plus</a></li> <li class="you_tube"><a href="<?php echo get_setting('youtube_social_link');?>" target="_blank">You Tube</a></li> </ul> <div class="clear"></div> </div> </div> </div> <!-- End: Content Part -->
bhupindersingh/lloh.co.uk
application/frontend/views/poverty/post_a_request.php
PHP
gpl-2.0
4,868