code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.internal.view.menu;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import com.actionbarsherlock.view.ActionProvider;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
/**
* @hide
*/
public class ActionMenuItem implements MenuItem {
private final int mId;
private final int mGroup;
//UNUSED private final int mCategoryOrder;
private final int mOrdering;
private CharSequence mTitle;
private CharSequence mTitleCondensed;
private Intent mIntent;
private char mShortcutNumericChar;
private char mShortcutAlphabeticChar;
private Drawable mIconDrawable;
//UNUSED private int mIconResId = NO_ICON;
private Context mContext;
private MenuItem.OnMenuItemClickListener mClickListener;
//UNUSED private static final int NO_ICON = 0;
private int mFlags = ENABLED;
private static final int CHECKABLE = 0x00000001;
private static final int CHECKED = 0x00000002;
private static final int EXCLUSIVE = 0x00000004;
private static final int HIDDEN = 0x00000008;
private static final int ENABLED = 0x00000010;
public ActionMenuItem(Context context, int group, int id, int categoryOrder, int ordering,
CharSequence title) {
mContext = context;
mId = id;
mGroup = group;
//UNUSED mCategoryOrder = categoryOrder;
mOrdering = ordering;
mTitle = title;
}
public char getAlphabeticShortcut() {
return mShortcutAlphabeticChar;
}
public int getGroupId() {
return mGroup;
}
public Drawable getIcon() {
return mIconDrawable;
}
public Intent getIntent() {
return mIntent;
}
public int getItemId() {
return mId;
}
public ContextMenuInfo getMenuInfo() {
return null;
}
public char getNumericShortcut() {
return mShortcutNumericChar;
}
public int getOrder() {
return mOrdering;
}
public SubMenu getSubMenu() {
return null;
}
public CharSequence getTitle() {
return mTitle;
}
public CharSequence getTitleCondensed() {
return mTitleCondensed;
}
public boolean hasSubMenu() {
return false;
}
public boolean isCheckable() {
return (mFlags & CHECKABLE) != 0;
}
public boolean isChecked() {
return (mFlags & CHECKED) != 0;
}
public boolean isEnabled() {
return (mFlags & ENABLED) != 0;
}
public boolean isVisible() {
return (mFlags & HIDDEN) == 0;
}
public MenuItem setAlphabeticShortcut(char alphaChar) {
mShortcutAlphabeticChar = alphaChar;
return this;
}
public MenuItem setCheckable(boolean checkable) {
mFlags = (mFlags & ~CHECKABLE) | (checkable ? CHECKABLE : 0);
return this;
}
public ActionMenuItem setExclusiveCheckable(boolean exclusive) {
mFlags = (mFlags & ~EXCLUSIVE) | (exclusive ? EXCLUSIVE : 0);
return this;
}
public MenuItem setChecked(boolean checked) {
mFlags = (mFlags & ~CHECKED) | (checked ? CHECKED : 0);
return this;
}
public MenuItem setEnabled(boolean enabled) {
mFlags = (mFlags & ~ENABLED) | (enabled ? ENABLED : 0);
return this;
}
public MenuItem setIcon(Drawable icon) {
mIconDrawable = icon;
//UNUSED mIconResId = NO_ICON;
return this;
}
public MenuItem setIcon(int iconRes) {
//UNUSED mIconResId = iconRes;
mIconDrawable = mContext.getResources().getDrawable(iconRes);
return this;
}
public MenuItem setIntent(Intent intent) {
mIntent = intent;
return this;
}
public MenuItem setNumericShortcut(char numericChar) {
mShortcutNumericChar = numericChar;
return this;
}
public MenuItem setOnMenuItemClickListener(OnMenuItemClickListener menuItemClickListener) {
mClickListener = menuItemClickListener;
return this;
}
public MenuItem setShortcut(char numericChar, char alphaChar) {
mShortcutNumericChar = numericChar;
mShortcutAlphabeticChar = alphaChar;
return this;
}
public MenuItem setTitle(CharSequence title) {
mTitle = title;
return this;
}
public MenuItem setTitle(int title) {
mTitle = mContext.getResources().getString(title);
return this;
}
public MenuItem setTitleCondensed(CharSequence title) {
mTitleCondensed = title;
return this;
}
public MenuItem setVisible(boolean visible) {
mFlags = (mFlags & HIDDEN) | (visible ? 0 : HIDDEN);
return this;
}
public boolean invoke() {
if (mClickListener != null && mClickListener.onMenuItemClick(this)) {
return true;
}
if (mIntent != null) {
mContext.startActivity(mIntent);
return true;
}
return false;
}
public void setShowAsAction(int show) {
// Do nothing. ActionMenuItems always show as action buttons.
}
public MenuItem setActionView(View actionView) {
throw new UnsupportedOperationException();
}
public View getActionView() {
return null;
}
@Override
public MenuItem setActionView(int resId) {
throw new UnsupportedOperationException();
}
@Override
public ActionProvider getActionProvider() {
return null;
}
@Override
public MenuItem setActionProvider(ActionProvider actionProvider) {
throw new UnsupportedOperationException();
}
@Override
public MenuItem setShowAsActionFlags(int actionEnum) {
setShowAsAction(actionEnum);
return this;
}
@Override
public boolean expandActionView() {
return false;
}
@Override
public boolean collapseActionView() {
return false;
}
@Override
public boolean isActionViewExpanded() {
return false;
}
@Override
public MenuItem setOnActionExpandListener(OnActionExpandListener listener) {
// No need to save the listener; ActionMenuItem does not support collapsing items.
return this;
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/internal/view/menu/ActionMenuItem.java | Java | asf20 | 7,075 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.internal.view.menu;
import java.util.ArrayList;
import android.content.Context;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Base class for MenuPresenters that have a consistent container view and item
* views. Behaves similarly to an AdapterView in that existing item views will
* be reused if possible when items change.
*/
public abstract class BaseMenuPresenter implements MenuPresenter {
private static final boolean IS_HONEYCOMB = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
protected Context mSystemContext;
protected Context mContext;
protected MenuBuilder mMenu;
protected LayoutInflater mSystemInflater;
protected LayoutInflater mInflater;
private Callback mCallback;
private int mMenuLayoutRes;
private int mItemLayoutRes;
protected MenuView mMenuView;
private int mId;
/**
* Construct a new BaseMenuPresenter.
*
* @param context Context for generating system-supplied views
* @param menuLayoutRes Layout resource ID for the menu container view
* @param itemLayoutRes Layout resource ID for a single item view
*/
public BaseMenuPresenter(Context context, int menuLayoutRes, int itemLayoutRes) {
mSystemContext = context;
mSystemInflater = LayoutInflater.from(context);
mMenuLayoutRes = menuLayoutRes;
mItemLayoutRes = itemLayoutRes;
}
@Override
public void initForMenu(Context context, MenuBuilder menu) {
mContext = context;
mInflater = LayoutInflater.from(mContext);
mMenu = menu;
}
@Override
public MenuView getMenuView(ViewGroup root) {
if (mMenuView == null) {
mMenuView = (MenuView) mSystemInflater.inflate(mMenuLayoutRes, root, false);
mMenuView.initialize(mMenu);
updateMenuView(true);
}
return mMenuView;
}
/**
* Reuses item views when it can
*/
public void updateMenuView(boolean cleared) {
final ViewGroup parent = (ViewGroup) mMenuView;
if (parent == null) return;
int childIndex = 0;
if (mMenu != null) {
mMenu.flagActionItems();
ArrayList<MenuItemImpl> visibleItems = mMenu.getVisibleItems();
final int itemCount = visibleItems.size();
for (int i = 0; i < itemCount; i++) {
MenuItemImpl item = visibleItems.get(i);
if (shouldIncludeItem(childIndex, item)) {
final View convertView = parent.getChildAt(childIndex);
final MenuItemImpl oldItem = convertView instanceof MenuView.ItemView ?
((MenuView.ItemView) convertView).getItemData() : null;
final View itemView = getItemView(item, convertView, parent);
if (item != oldItem) {
// Don't let old states linger with new data.
itemView.setPressed(false);
if (IS_HONEYCOMB) itemView.jumpDrawablesToCurrentState();
}
if (itemView != convertView) {
addItemView(itemView, childIndex);
}
childIndex++;
}
}
}
// Remove leftover views.
while (childIndex < parent.getChildCount()) {
if (!filterLeftoverView(parent, childIndex)) {
childIndex++;
}
}
}
/**
* Add an item view at the given index.
*
* @param itemView View to add
* @param childIndex Index within the parent to insert at
*/
protected void addItemView(View itemView, int childIndex) {
final ViewGroup currentParent = (ViewGroup) itemView.getParent();
if (currentParent != null) {
currentParent.removeView(itemView);
}
((ViewGroup) mMenuView).addView(itemView, childIndex);
}
/**
* Filter the child view at index and remove it if appropriate.
* @param parent Parent to filter from
* @param childIndex Index to filter
* @return true if the child view at index was removed
*/
protected boolean filterLeftoverView(ViewGroup parent, int childIndex) {
parent.removeViewAt(childIndex);
return true;
}
public void setCallback(Callback cb) {
mCallback = cb;
}
/**
* Create a new item view that can be re-bound to other item data later.
*
* @return The new item view
*/
public MenuView.ItemView createItemView(ViewGroup parent) {
return (MenuView.ItemView) mSystemInflater.inflate(mItemLayoutRes, parent, false);
}
/**
* Prepare an item view for use. See AdapterView for the basic idea at work here.
* This may require creating a new item view, but well-behaved implementations will
* re-use the view passed as convertView if present. The returned view will be populated
* with data from the item parameter.
*
* @param item Item to present
* @param convertView Existing view to reuse
* @param parent Intended parent view - use for inflation.
* @return View that presents the requested menu item
*/
public View getItemView(MenuItemImpl item, View convertView, ViewGroup parent) {
MenuView.ItemView itemView;
if (convertView instanceof MenuView.ItemView) {
itemView = (MenuView.ItemView) convertView;
} else {
itemView = createItemView(parent);
}
bindItemView(item, itemView);
return (View) itemView;
}
/**
* Bind item data to an existing item view.
*
* @param item Item to bind
* @param itemView View to populate with item data
*/
public abstract void bindItemView(MenuItemImpl item, MenuView.ItemView itemView);
/**
* Filter item by child index and item data.
*
* @param childIndex Indended presentation index of this item
* @param item Item to present
* @return true if this item should be included in this menu presentation; false otherwise
*/
public boolean shouldIncludeItem(int childIndex, MenuItemImpl item) {
return true;
}
public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
if (mCallback != null) {
mCallback.onCloseMenu(menu, allMenusAreClosing);
}
}
public boolean onSubMenuSelected(SubMenuBuilder menu) {
if (mCallback != null) {
return mCallback.onOpenSubMenu(menu);
}
return false;
}
public boolean flagActionItems() {
return false;
}
public boolean expandItemActionView(MenuBuilder menu, MenuItemImpl item) {
return false;
}
public boolean collapseItemActionView(MenuBuilder menu, MenuItemImpl item) {
return false;
}
public int getId() {
return mId;
}
public void setId(int id) {
mId = id;
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/internal/view/menu/BaseMenuPresenter.java | Java | asf20 | 7,727 |
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.internal.view.menu;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewDebug;
import android.widget.LinearLayout;
import com.actionbarsherlock.view.ActionProvider;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
/**
* @hide
*/
public final class MenuItemImpl implements MenuItem {
private static final String TAG = "MenuItemImpl";
private static final int SHOW_AS_ACTION_MASK = SHOW_AS_ACTION_NEVER |
SHOW_AS_ACTION_IF_ROOM |
SHOW_AS_ACTION_ALWAYS;
private final int mId;
private final int mGroup;
private final int mCategoryOrder;
private final int mOrdering;
private CharSequence mTitle;
private CharSequence mTitleCondensed;
private Intent mIntent;
private char mShortcutNumericChar;
private char mShortcutAlphabeticChar;
/** The icon's drawable which is only created as needed */
private Drawable mIconDrawable;
/**
* The icon's resource ID which is used to get the Drawable when it is
* needed (if the Drawable isn't already obtained--only one of the two is
* needed).
*/
private int mIconResId = NO_ICON;
/** The menu to which this item belongs */
private MenuBuilder mMenu;
/** If this item should launch a sub menu, this is the sub menu to launch */
private SubMenuBuilder mSubMenu;
private Runnable mItemCallback;
private MenuItem.OnMenuItemClickListener mClickListener;
private int mFlags = ENABLED;
private static final int CHECKABLE = 0x00000001;
private static final int CHECKED = 0x00000002;
private static final int EXCLUSIVE = 0x00000004;
private static final int HIDDEN = 0x00000008;
private static final int ENABLED = 0x00000010;
private static final int IS_ACTION = 0x00000020;
private int mShowAsAction = SHOW_AS_ACTION_NEVER;
private View mActionView;
private ActionProvider mActionProvider;
private OnActionExpandListener mOnActionExpandListener;
private boolean mIsActionViewExpanded = false;
/** Used for the icon resource ID if this item does not have an icon */
static final int NO_ICON = 0;
/**
* Current use case is for context menu: Extra information linked to the
* View that added this item to the context menu.
*/
private ContextMenuInfo mMenuInfo;
private static String sPrependShortcutLabel;
private static String sEnterShortcutLabel;
private static String sDeleteShortcutLabel;
private static String sSpaceShortcutLabel;
/**
* Instantiates this menu item.
*
* @param menu
* @param group Item ordering grouping control. The item will be added after
* all other items whose order is <= this number, and before any
* that are larger than it. This can also be used to define
* groups of items for batch state changes. Normally use 0.
* @param id Unique item ID. Use 0 if you do not need a unique ID.
* @param categoryOrder The ordering for this item.
* @param title The text to display for the item.
*/
MenuItemImpl(MenuBuilder menu, int group, int id, int categoryOrder, int ordering,
CharSequence title, int showAsAction) {
/* TODO if (sPrependShortcutLabel == null) {
// This is instantiated from the UI thread, so no chance of sync issues
sPrependShortcutLabel = menu.getContext().getResources().getString(
com.android.internal.R.string.prepend_shortcut_label);
sEnterShortcutLabel = menu.getContext().getResources().getString(
com.android.internal.R.string.menu_enter_shortcut_label);
sDeleteShortcutLabel = menu.getContext().getResources().getString(
com.android.internal.R.string.menu_delete_shortcut_label);
sSpaceShortcutLabel = menu.getContext().getResources().getString(
com.android.internal.R.string.menu_space_shortcut_label);
}*/
mMenu = menu;
mId = id;
mGroup = group;
mCategoryOrder = categoryOrder;
mOrdering = ordering;
mTitle = title;
mShowAsAction = showAsAction;
}
/**
* Invokes the item by calling various listeners or callbacks.
*
* @return true if the invocation was handled, false otherwise
*/
public boolean invoke() {
if (mClickListener != null &&
mClickListener.onMenuItemClick(this)) {
return true;
}
if (mMenu.dispatchMenuItemSelected(mMenu.getRootMenu(), this)) {
return true;
}
if (mItemCallback != null) {
mItemCallback.run();
return true;
}
if (mIntent != null) {
try {
mMenu.getContext().startActivity(mIntent);
return true;
} catch (ActivityNotFoundException e) {
Log.e(TAG, "Can't find activity to handle intent; ignoring", e);
}
}
if (mActionProvider != null && mActionProvider.onPerformDefaultAction()) {
return true;
}
return false;
}
public boolean isEnabled() {
return (mFlags & ENABLED) != 0;
}
public MenuItem setEnabled(boolean enabled) {
if (enabled) {
mFlags |= ENABLED;
} else {
mFlags &= ~ENABLED;
}
mMenu.onItemsChanged(false);
return this;
}
public int getGroupId() {
return mGroup;
}
@ViewDebug.CapturedViewProperty
public int getItemId() {
return mId;
}
public int getOrder() {
return mCategoryOrder;
}
public int getOrdering() {
return mOrdering;
}
public Intent getIntent() {
return mIntent;
}
public MenuItem setIntent(Intent intent) {
mIntent = intent;
return this;
}
Runnable getCallback() {
return mItemCallback;
}
public MenuItem setCallback(Runnable callback) {
mItemCallback = callback;
return this;
}
public char getAlphabeticShortcut() {
return mShortcutAlphabeticChar;
}
public MenuItem setAlphabeticShortcut(char alphaChar) {
if (mShortcutAlphabeticChar == alphaChar) return this;
mShortcutAlphabeticChar = Character.toLowerCase(alphaChar);
mMenu.onItemsChanged(false);
return this;
}
public char getNumericShortcut() {
return mShortcutNumericChar;
}
public MenuItem setNumericShortcut(char numericChar) {
if (mShortcutNumericChar == numericChar) return this;
mShortcutNumericChar = numericChar;
mMenu.onItemsChanged(false);
return this;
}
public MenuItem setShortcut(char numericChar, char alphaChar) {
mShortcutNumericChar = numericChar;
mShortcutAlphabeticChar = Character.toLowerCase(alphaChar);
mMenu.onItemsChanged(false);
return this;
}
/**
* @return The active shortcut (based on QWERTY-mode of the menu).
*/
char getShortcut() {
return (mMenu.isQwertyMode() ? mShortcutAlphabeticChar : mShortcutNumericChar);
}
/**
* @return The label to show for the shortcut. This includes the chording
* key (for example 'Menu+a'). Also, any non-human readable
* characters should be human readable (for example 'Menu+enter').
*/
String getShortcutLabel() {
char shortcut = getShortcut();
if (shortcut == 0) {
return "";
}
StringBuilder sb = new StringBuilder(sPrependShortcutLabel);
switch (shortcut) {
case '\n':
sb.append(sEnterShortcutLabel);
break;
case '\b':
sb.append(sDeleteShortcutLabel);
break;
case ' ':
sb.append(sSpaceShortcutLabel);
break;
default:
sb.append(shortcut);
break;
}
return sb.toString();
}
/**
* @return Whether this menu item should be showing shortcuts (depends on
* whether the menu should show shortcuts and whether this item has
* a shortcut defined)
*/
boolean shouldShowShortcut() {
// Show shortcuts if the menu is supposed to show shortcuts AND this item has a shortcut
return mMenu.isShortcutsVisible() && (getShortcut() != 0);
}
public SubMenu getSubMenu() {
return mSubMenu;
}
public boolean hasSubMenu() {
return mSubMenu != null;
}
void setSubMenu(SubMenuBuilder subMenu) {
mSubMenu = subMenu;
subMenu.setHeaderTitle(getTitle());
}
@ViewDebug.CapturedViewProperty
public CharSequence getTitle() {
return mTitle;
}
/**
* Gets the title for a particular {@link ItemView}
*
* @param itemView The ItemView that is receiving the title
* @return Either the title or condensed title based on what the ItemView
* prefers
*/
CharSequence getTitleForItemView(MenuView.ItemView itemView) {
return ((itemView != null) && itemView.prefersCondensedTitle())
? getTitleCondensed()
: getTitle();
}
public MenuItem setTitle(CharSequence title) {
mTitle = title;
mMenu.onItemsChanged(false);
if (mSubMenu != null) {
mSubMenu.setHeaderTitle(title);
}
return this;
}
public MenuItem setTitle(int title) {
return setTitle(mMenu.getContext().getString(title));
}
public CharSequence getTitleCondensed() {
return mTitleCondensed != null ? mTitleCondensed : mTitle;
}
public MenuItem setTitleCondensed(CharSequence title) {
mTitleCondensed = title;
// Could use getTitle() in the loop below, but just cache what it would do here
if (title == null) {
title = mTitle;
}
mMenu.onItemsChanged(false);
return this;
}
public Drawable getIcon() {
if (mIconDrawable != null) {
return mIconDrawable;
}
if (mIconResId != NO_ICON) {
return mMenu.getResources().getDrawable(mIconResId);
}
return null;
}
public MenuItem setIcon(Drawable icon) {
mIconResId = NO_ICON;
mIconDrawable = icon;
mMenu.onItemsChanged(false);
return this;
}
public MenuItem setIcon(int iconResId) {
mIconDrawable = null;
mIconResId = iconResId;
// If we have a view, we need to push the Drawable to them
mMenu.onItemsChanged(false);
return this;
}
public boolean isCheckable() {
return (mFlags & CHECKABLE) == CHECKABLE;
}
public MenuItem setCheckable(boolean checkable) {
final int oldFlags = mFlags;
mFlags = (mFlags & ~CHECKABLE) | (checkable ? CHECKABLE : 0);
if (oldFlags != mFlags) {
mMenu.onItemsChanged(false);
}
return this;
}
public void setExclusiveCheckable(boolean exclusive) {
mFlags = (mFlags & ~EXCLUSIVE) | (exclusive ? EXCLUSIVE : 0);
}
public boolean isExclusiveCheckable() {
return (mFlags & EXCLUSIVE) != 0;
}
public boolean isChecked() {
return (mFlags & CHECKED) == CHECKED;
}
public MenuItem setChecked(boolean checked) {
if ((mFlags & EXCLUSIVE) != 0) {
// Call the method on the Menu since it knows about the others in this
// exclusive checkable group
mMenu.setExclusiveItemChecked(this);
} else {
setCheckedInt(checked);
}
return this;
}
void setCheckedInt(boolean checked) {
final int oldFlags = mFlags;
mFlags = (mFlags & ~CHECKED) | (checked ? CHECKED : 0);
if (oldFlags != mFlags) {
mMenu.onItemsChanged(false);
}
}
public boolean isVisible() {
return (mFlags & HIDDEN) == 0;
}
/**
* Changes the visibility of the item. This method DOES NOT notify the
* parent menu of a change in this item, so this should only be called from
* methods that will eventually trigger this change. If unsure, use {@link #setVisible(boolean)}
* instead.
*
* @param shown Whether to show (true) or hide (false).
* @return Whether the item's shown state was changed
*/
boolean setVisibleInt(boolean shown) {
final int oldFlags = mFlags;
mFlags = (mFlags & ~HIDDEN) | (shown ? 0 : HIDDEN);
return oldFlags != mFlags;
}
public MenuItem setVisible(boolean shown) {
// Try to set the shown state to the given state. If the shown state was changed
// (i.e. the previous state isn't the same as given state), notify the parent menu that
// the shown state has changed for this item
if (setVisibleInt(shown)) mMenu.onItemVisibleChanged(this);
return this;
}
public MenuItem setOnMenuItemClickListener(MenuItem.OnMenuItemClickListener clickListener) {
mClickListener = clickListener;
return this;
}
@Override
public String toString() {
return mTitle.toString();
}
void setMenuInfo(ContextMenuInfo menuInfo) {
mMenuInfo = menuInfo;
}
public ContextMenuInfo getMenuInfo() {
return mMenuInfo;
}
public void actionFormatChanged() {
mMenu.onItemActionRequestChanged(this);
}
/**
* @return Whether the menu should show icons for menu items.
*/
public boolean shouldShowIcon() {
return mMenu.getOptionalIconsVisible();
}
public boolean isActionButton() {
return (mFlags & IS_ACTION) == IS_ACTION;
}
public boolean requestsActionButton() {
return (mShowAsAction & SHOW_AS_ACTION_IF_ROOM) == SHOW_AS_ACTION_IF_ROOM;
}
public boolean requiresActionButton() {
return (mShowAsAction & SHOW_AS_ACTION_ALWAYS) == SHOW_AS_ACTION_ALWAYS;
}
public void setIsActionButton(boolean isActionButton) {
if (isActionButton) {
mFlags |= IS_ACTION;
} else {
mFlags &= ~IS_ACTION;
}
}
public boolean showsTextAsAction() {
return (mShowAsAction & SHOW_AS_ACTION_WITH_TEXT) == SHOW_AS_ACTION_WITH_TEXT;
}
public void setShowAsAction(int actionEnum) {
switch (actionEnum & SHOW_AS_ACTION_MASK) {
case SHOW_AS_ACTION_ALWAYS:
case SHOW_AS_ACTION_IF_ROOM:
case SHOW_AS_ACTION_NEVER:
// Looks good!
break;
default:
// Mutually exclusive options selected!
throw new IllegalArgumentException("SHOW_AS_ACTION_ALWAYS, SHOW_AS_ACTION_IF_ROOM,"
+ " and SHOW_AS_ACTION_NEVER are mutually exclusive.");
}
mShowAsAction = actionEnum;
mMenu.onItemActionRequestChanged(this);
}
public MenuItem setActionView(View view) {
mActionView = view;
mActionProvider = null;
if (view != null && view.getId() == View.NO_ID && mId > 0) {
view.setId(mId);
}
mMenu.onItemActionRequestChanged(this);
return this;
}
public MenuItem setActionView(int resId) {
final Context context = mMenu.getContext();
final LayoutInflater inflater = LayoutInflater.from(context);
setActionView(inflater.inflate(resId, new LinearLayout(context), false));
return this;
}
public View getActionView() {
if (mActionView != null) {
return mActionView;
} else if (mActionProvider != null) {
mActionView = mActionProvider.onCreateActionView();
return mActionView;
} else {
return null;
}
}
public ActionProvider getActionProvider() {
return mActionProvider;
}
public MenuItem setActionProvider(ActionProvider actionProvider) {
mActionView = null;
mActionProvider = actionProvider;
mMenu.onItemsChanged(true); // Measurement can be changed
return this;
}
@Override
public MenuItem setShowAsActionFlags(int actionEnum) {
setShowAsAction(actionEnum);
return this;
}
@Override
public boolean expandActionView() {
if ((mShowAsAction & SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW) == 0 || mActionView == null) {
return false;
}
if (mOnActionExpandListener == null ||
mOnActionExpandListener.onMenuItemActionExpand(this)) {
return mMenu.expandItemActionView(this);
}
return false;
}
@Override
public boolean collapseActionView() {
if ((mShowAsAction & SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW) == 0) {
return false;
}
if (mActionView == null) {
// We're already collapsed if we have no action view.
return true;
}
if (mOnActionExpandListener == null ||
mOnActionExpandListener.onMenuItemActionCollapse(this)) {
return mMenu.collapseItemActionView(this);
}
return false;
}
@Override
public MenuItem setOnActionExpandListener(OnActionExpandListener listener) {
mOnActionExpandListener = listener;
return this;
}
public boolean hasCollapsibleActionView() {
return (mShowAsAction & SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW) != 0 && mActionView != null;
}
public void setActionViewExpanded(boolean isExpanded) {
mIsActionViewExpanded = isExpanded;
mMenu.onItemsChanged(false);
}
public boolean isActionViewExpanded() {
return mIsActionViewExpanded;
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/internal/view/menu/MenuItemImpl.java | Java | asf20 | 18,924 |
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.internal.view.menu;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
/**
* The model for a sub menu, which is an extension of the menu. Most methods are proxied to
* the parent menu.
*/
public class SubMenuBuilder extends MenuBuilder implements SubMenu {
private MenuBuilder mParentMenu;
private MenuItemImpl mItem;
public SubMenuBuilder(Context context, MenuBuilder parentMenu, MenuItemImpl item) {
super(context);
mParentMenu = parentMenu;
mItem = item;
}
@Override
public void setQwertyMode(boolean isQwerty) {
mParentMenu.setQwertyMode(isQwerty);
}
@Override
public boolean isQwertyMode() {
return mParentMenu.isQwertyMode();
}
@Override
public void setShortcutsVisible(boolean shortcutsVisible) {
mParentMenu.setShortcutsVisible(shortcutsVisible);
}
@Override
public boolean isShortcutsVisible() {
return mParentMenu.isShortcutsVisible();
}
public Menu getParentMenu() {
return mParentMenu;
}
public MenuItem getItem() {
return mItem;
}
@Override
public void setCallback(Callback callback) {
mParentMenu.setCallback(callback);
}
@Override
public MenuBuilder getRootMenu() {
return mParentMenu;
}
@Override
boolean dispatchMenuItemSelected(MenuBuilder menu, MenuItem item) {
return super.dispatchMenuItemSelected(menu, item) ||
mParentMenu.dispatchMenuItemSelected(menu, item);
}
public SubMenu setIcon(Drawable icon) {
mItem.setIcon(icon);
return this;
}
public SubMenu setIcon(int iconRes) {
mItem.setIcon(iconRes);
return this;
}
public SubMenu setHeaderIcon(Drawable icon) {
return (SubMenu) super.setHeaderIconInt(icon);
}
public SubMenu setHeaderIcon(int iconRes) {
return (SubMenu) super.setHeaderIconInt(iconRes);
}
public SubMenu setHeaderTitle(CharSequence title) {
return (SubMenu) super.setHeaderTitleInt(title);
}
public SubMenu setHeaderTitle(int titleRes) {
return (SubMenu) super.setHeaderTitleInt(titleRes);
}
public SubMenu setHeaderView(View view) {
return (SubMenu) super.setHeaderViewInt(view);
}
@Override
public boolean expandItemActionView(MenuItemImpl item) {
return mParentMenu.expandItemActionView(item);
}
@Override
public boolean collapseItemActionView(MenuItemImpl item) {
return mParentMenu.collapseItemActionView(item);
}
@Override
public String getActionViewStatesKey() {
final int itemId = mItem != null ? mItem.getItemId() : 0;
if (itemId == 0) {
return null;
}
return super.getActionViewStatesKey() + ":" + itemId;
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/internal/view/menu/SubMenuBuilder.java | Java | asf20 | 3,669 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.internal.view.menu;
import static com.actionbarsherlock.internal.ResourcesCompat.getResources_getInteger;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.SparseBooleanArray;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.ImageButton;
import com.actionbarsherlock.R;
import com.actionbarsherlock.internal.view.View_HasStateListenerSupport;
import com.actionbarsherlock.internal.view.View_OnAttachStateChangeListener;
import com.actionbarsherlock.internal.view.menu.ActionMenuView.ActionMenuChildView;
import com.actionbarsherlock.view.ActionProvider;
import com.actionbarsherlock.view.MenuItem;
/**
* MenuPresenter for building action menus as seen in the action bar and action modes.
*/
public class ActionMenuPresenter extends BaseMenuPresenter
implements ActionProvider.SubUiVisibilityListener {
//UNUSED private static final String TAG = "ActionMenuPresenter";
private View mOverflowButton;
private boolean mReserveOverflow;
private boolean mReserveOverflowSet;
private int mWidthLimit;
private int mActionItemWidthLimit;
private int mMaxItems;
private boolean mMaxItemsSet;
private boolean mStrictWidthLimit;
private boolean mWidthLimitSet;
private boolean mExpandedActionViewsExclusive;
private int mMinCellSize;
// Group IDs that have been added as actions - used temporarily, allocated here for reuse.
private final SparseBooleanArray mActionButtonGroups = new SparseBooleanArray();
private View mScrapActionButtonView;
private OverflowPopup mOverflowPopup;
private ActionButtonSubmenu mActionButtonPopup;
private OpenOverflowRunnable mPostedOpenRunnable;
final PopupPresenterCallback mPopupPresenterCallback = new PopupPresenterCallback();
int mOpenSubMenuId;
public ActionMenuPresenter(Context context) {
super(context, R.layout.abs__action_menu_layout,
R.layout.abs__action_menu_item_layout);
}
@Override
public void initForMenu(Context context, MenuBuilder menu) {
super.initForMenu(context, menu);
final Resources res = context.getResources();
if (!mReserveOverflowSet) {
mReserveOverflow = reserveOverflow(mContext);
}
if (!mWidthLimitSet) {
mWidthLimit = res.getDisplayMetrics().widthPixels / 2;
}
// Measure for initial configuration
if (!mMaxItemsSet) {
mMaxItems = getResources_getInteger(context, R.integer.abs__max_action_buttons);
}
int width = mWidthLimit;
if (mReserveOverflow) {
if (mOverflowButton == null) {
mOverflowButton = new OverflowMenuButton(mSystemContext);
final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
mOverflowButton.measure(spec, spec);
}
width -= mOverflowButton.getMeasuredWidth();
} else {
mOverflowButton = null;
}
mActionItemWidthLimit = width;
mMinCellSize = (int) (ActionMenuView.MIN_CELL_SIZE * res.getDisplayMetrics().density);
// Drop a scrap view as it may no longer reflect the proper context/config.
mScrapActionButtonView = null;
}
public static boolean reserveOverflow(Context context) {
//Check for theme-forced overflow action item
TypedArray a = context.getTheme().obtainStyledAttributes(R.styleable.SherlockTheme);
boolean result = a.getBoolean(R.styleable.SherlockTheme_absForceOverflow, false);
a.recycle();
if (result) {
return true;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB);
} else {
return !HasPermanentMenuKey.get(context);
}
}
private static class HasPermanentMenuKey {
public static boolean get(Context context) {
return ViewConfiguration.get(context).hasPermanentMenuKey();
}
}
public void onConfigurationChanged(Configuration newConfig) {
if (!mMaxItemsSet) {
mMaxItems = getResources_getInteger(mContext,
R.integer.abs__max_action_buttons);
if (mMenu != null) {
mMenu.onItemsChanged(true);
}
}
}
public void setWidthLimit(int width, boolean strict) {
mWidthLimit = width;
mStrictWidthLimit = strict;
mWidthLimitSet = true;
}
public void setReserveOverflow(boolean reserveOverflow) {
mReserveOverflow = reserveOverflow;
mReserveOverflowSet = true;
}
public void setItemLimit(int itemCount) {
mMaxItems = itemCount;
mMaxItemsSet = true;
}
public void setExpandedActionViewsExclusive(boolean isExclusive) {
mExpandedActionViewsExclusive = isExclusive;
}
@Override
public MenuView getMenuView(ViewGroup root) {
MenuView result = super.getMenuView(root);
((ActionMenuView) result).setPresenter(this);
return result;
}
@Override
public View getItemView(MenuItemImpl item, View convertView, ViewGroup parent) {
View actionView = item.getActionView();
if (actionView == null || item.hasCollapsibleActionView()) {
if (!(convertView instanceof ActionMenuItemView)) {
convertView = null;
}
actionView = super.getItemView(item, convertView, parent);
}
actionView.setVisibility(item.isActionViewExpanded() ? View.GONE : View.VISIBLE);
final ActionMenuView menuParent = (ActionMenuView) parent;
final ViewGroup.LayoutParams lp = actionView.getLayoutParams();
if (!menuParent.checkLayoutParams(lp)) {
actionView.setLayoutParams(menuParent.generateLayoutParams(lp));
}
return actionView;
}
@Override
public void bindItemView(MenuItemImpl item, MenuView.ItemView itemView) {
itemView.initialize(item, 0);
final ActionMenuView menuView = (ActionMenuView) mMenuView;
ActionMenuItemView actionItemView = (ActionMenuItemView) itemView;
actionItemView.setItemInvoker(menuView);
}
@Override
public boolean shouldIncludeItem(int childIndex, MenuItemImpl item) {
return item.isActionButton();
}
@Override
public void updateMenuView(boolean cleared) {
super.updateMenuView(cleared);
if (mMenu != null) {
final ArrayList<MenuItemImpl> actionItems = mMenu.getActionItems();
final int count = actionItems.size();
for (int i = 0; i < count; i++) {
final ActionProvider provider = actionItems.get(i).getActionProvider();
if (provider != null) {
provider.setSubUiVisibilityListener(this);
}
}
}
final ArrayList<MenuItemImpl> nonActionItems = mMenu != null ?
mMenu.getNonActionItems() : null;
boolean hasOverflow = false;
if (mReserveOverflow && nonActionItems != null) {
final int count = nonActionItems.size();
if (count == 1) {
hasOverflow = !nonActionItems.get(0).isActionViewExpanded();
} else {
hasOverflow = count > 0;
}
}
if (hasOverflow) {
if (mOverflowButton == null) {
mOverflowButton = new OverflowMenuButton(mSystemContext);
}
ViewGroup parent = (ViewGroup) mOverflowButton.getParent();
if (parent != mMenuView) {
if (parent != null) {
parent.removeView(mOverflowButton);
}
ActionMenuView menuView = (ActionMenuView) mMenuView;
menuView.addView(mOverflowButton, menuView.generateOverflowButtonLayoutParams());
}
} else if (mOverflowButton != null && mOverflowButton.getParent() == mMenuView) {
((ViewGroup) mMenuView).removeView(mOverflowButton);
}
((ActionMenuView) mMenuView).setOverflowReserved(mReserveOverflow);
}
@Override
public boolean filterLeftoverView(ViewGroup parent, int childIndex) {
if (parent.getChildAt(childIndex) == mOverflowButton) return false;
return super.filterLeftoverView(parent, childIndex);
}
public boolean onSubMenuSelected(SubMenuBuilder subMenu) {
if (!subMenu.hasVisibleItems()) return false;
SubMenuBuilder topSubMenu = subMenu;
while (topSubMenu.getParentMenu() != mMenu) {
topSubMenu = (SubMenuBuilder) topSubMenu.getParentMenu();
}
View anchor = findViewForItem(topSubMenu.getItem());
if (anchor == null) {
if (mOverflowButton == null) return false;
anchor = mOverflowButton;
}
mOpenSubMenuId = subMenu.getItem().getItemId();
mActionButtonPopup = new ActionButtonSubmenu(mContext, subMenu);
mActionButtonPopup.setAnchorView(anchor);
mActionButtonPopup.show();
super.onSubMenuSelected(subMenu);
return true;
}
private View findViewForItem(MenuItem item) {
final ViewGroup parent = (ViewGroup) mMenuView;
if (parent == null) return null;
final int count = parent.getChildCount();
for (int i = 0; i < count; i++) {
final View child = parent.getChildAt(i);
if (child instanceof MenuView.ItemView &&
((MenuView.ItemView) child).getItemData() == item) {
return child;
}
}
return null;
}
/**
* Display the overflow menu if one is present.
* @return true if the overflow menu was shown, false otherwise.
*/
public boolean showOverflowMenu() {
if (mReserveOverflow && !isOverflowMenuShowing() && mMenu != null && mMenuView != null &&
mPostedOpenRunnable == null && !mMenu.getNonActionItems().isEmpty()) {
OverflowPopup popup = new OverflowPopup(mContext, mMenu, mOverflowButton, true);
mPostedOpenRunnable = new OpenOverflowRunnable(popup);
// Post this for later; we might still need a layout for the anchor to be right.
((View) mMenuView).post(mPostedOpenRunnable);
// ActionMenuPresenter uses null as a callback argument here
// to indicate overflow is opening.
super.onSubMenuSelected(null);
return true;
}
return false;
}
/**
* Hide the overflow menu if it is currently showing.
*
* @return true if the overflow menu was hidden, false otherwise.
*/
public boolean hideOverflowMenu() {
if (mPostedOpenRunnable != null && mMenuView != null) {
((View) mMenuView).removeCallbacks(mPostedOpenRunnable);
mPostedOpenRunnable = null;
return true;
}
MenuPopupHelper popup = mOverflowPopup;
if (popup != null) {
popup.dismiss();
return true;
}
return false;
}
/**
* Dismiss all popup menus - overflow and submenus.
* @return true if popups were dismissed, false otherwise. (This can be because none were open.)
*/
public boolean dismissPopupMenus() {
boolean result = hideOverflowMenu();
result |= hideSubMenus();
return result;
}
/**
* Dismiss all submenu popups.
*
* @return true if popups were dismissed, false otherwise. (This can be because none were open.)
*/
public boolean hideSubMenus() {
if (mActionButtonPopup != null) {
mActionButtonPopup.dismiss();
return true;
}
return false;
}
/**
* @return true if the overflow menu is currently showing
*/
public boolean isOverflowMenuShowing() {
return mOverflowPopup != null && mOverflowPopup.isShowing();
}
/**
* @return true if space has been reserved in the action menu for an overflow item.
*/
public boolean isOverflowReserved() {
return mReserveOverflow;
}
public boolean flagActionItems() {
final ArrayList<MenuItemImpl> visibleItems = mMenu.getVisibleItems();
final int itemsSize = visibleItems.size();
int maxActions = mMaxItems;
int widthLimit = mActionItemWidthLimit;
final int querySpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
final ViewGroup parent = (ViewGroup) mMenuView;
int requiredItems = 0;
int requestedItems = 0;
int firstActionWidth = 0;
boolean hasOverflow = false;
for (int i = 0; i < itemsSize; i++) {
MenuItemImpl item = visibleItems.get(i);
if (item.requiresActionButton()) {
requiredItems++;
} else if (item.requestsActionButton()) {
requestedItems++;
} else {
hasOverflow = true;
}
if (mExpandedActionViewsExclusive && item.isActionViewExpanded()) {
// Overflow everything if we have an expanded action view and we're
// space constrained.
maxActions = 0;
}
}
// Reserve a spot for the overflow item if needed.
if (mReserveOverflow &&
(hasOverflow || requiredItems + requestedItems > maxActions)) {
maxActions--;
}
maxActions -= requiredItems;
final SparseBooleanArray seenGroups = mActionButtonGroups;
seenGroups.clear();
int cellSize = 0;
int cellsRemaining = 0;
if (mStrictWidthLimit) {
cellsRemaining = widthLimit / mMinCellSize;
final int cellSizeRemaining = widthLimit % mMinCellSize;
cellSize = mMinCellSize + cellSizeRemaining / cellsRemaining;
}
// Flag as many more requested items as will fit.
for (int i = 0; i < itemsSize; i++) {
MenuItemImpl item = visibleItems.get(i);
if (item.requiresActionButton()) {
View v = getItemView(item, mScrapActionButtonView, parent);
if (mScrapActionButtonView == null) {
mScrapActionButtonView = v;
}
if (mStrictWidthLimit) {
cellsRemaining -= ActionMenuView.measureChildForCells(v,
cellSize, cellsRemaining, querySpec, 0);
} else {
v.measure(querySpec, querySpec);
}
final int measuredWidth = v.getMeasuredWidth();
widthLimit -= measuredWidth;
if (firstActionWidth == 0) {
firstActionWidth = measuredWidth;
}
final int groupId = item.getGroupId();
if (groupId != 0) {
seenGroups.put(groupId, true);
}
item.setIsActionButton(true);
} else if (item.requestsActionButton()) {
// Items in a group with other items that already have an action slot
// can break the max actions rule, but not the width limit.
final int groupId = item.getGroupId();
final boolean inGroup = seenGroups.get(groupId);
boolean isAction = (maxActions > 0 || inGroup) && widthLimit > 0 &&
(!mStrictWidthLimit || cellsRemaining > 0);
if (isAction) {
View v = getItemView(item, mScrapActionButtonView, parent);
if (mScrapActionButtonView == null) {
mScrapActionButtonView = v;
}
if (mStrictWidthLimit) {
final int cells = ActionMenuView.measureChildForCells(v,
cellSize, cellsRemaining, querySpec, 0);
cellsRemaining -= cells;
if (cells == 0) {
isAction = false;
}
} else {
v.measure(querySpec, querySpec);
}
final int measuredWidth = v.getMeasuredWidth();
widthLimit -= measuredWidth;
if (firstActionWidth == 0) {
firstActionWidth = measuredWidth;
}
if (mStrictWidthLimit) {
isAction &= widthLimit >= 0;
} else {
// Did this push the entire first item past the limit?
isAction &= widthLimit + firstActionWidth > 0;
}
}
if (isAction && groupId != 0) {
seenGroups.put(groupId, true);
} else if (inGroup) {
// We broke the width limit. Demote the whole group, they all overflow now.
seenGroups.put(groupId, false);
for (int j = 0; j < i; j++) {
MenuItemImpl areYouMyGroupie = visibleItems.get(j);
if (areYouMyGroupie.getGroupId() == groupId) {
// Give back the action slot
if (areYouMyGroupie.isActionButton()) maxActions++;
areYouMyGroupie.setIsActionButton(false);
}
}
}
if (isAction) maxActions--;
item.setIsActionButton(isAction);
}
}
return true;
}
@Override
public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
dismissPopupMenus();
super.onCloseMenu(menu, allMenusAreClosing);
}
@Override
public Parcelable onSaveInstanceState() {
SavedState state = new SavedState();
state.openSubMenuId = mOpenSubMenuId;
return state;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState saved = (SavedState) state;
if (saved.openSubMenuId > 0) {
MenuItem item = mMenu.findItem(saved.openSubMenuId);
if (item != null) {
SubMenuBuilder subMenu = (SubMenuBuilder) item.getSubMenu();
onSubMenuSelected(subMenu);
}
}
}
@Override
public void onSubUiVisibilityChanged(boolean isVisible) {
if (isVisible) {
// Not a submenu, but treat it like one.
super.onSubMenuSelected(null);
} else {
mMenu.close(false);
}
}
private static class SavedState implements Parcelable {
public int openSubMenuId;
SavedState() {
}
SavedState(Parcel in) {
openSubMenuId = in.readInt();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(openSubMenuId);
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<SavedState> CREATOR
= new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
private class OverflowMenuButton extends ImageButton implements ActionMenuChildView, View_HasStateListenerSupport {
private final Set<View_OnAttachStateChangeListener> mListeners = new HashSet<View_OnAttachStateChangeListener>();
public OverflowMenuButton(Context context) {
super(context, null, R.attr.actionOverflowButtonStyle);
setClickable(true);
setFocusable(true);
setVisibility(VISIBLE);
setEnabled(true);
}
@Override
public boolean performClick() {
if (super.performClick()) {
return true;
}
playSoundEffect(SoundEffectConstants.CLICK);
showOverflowMenu();
return true;
}
public boolean needsDividerBefore() {
return false;
}
public boolean needsDividerAfter() {
return false;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
for (View_OnAttachStateChangeListener listener : mListeners) {
listener.onViewAttachedToWindow(this);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
for (View_OnAttachStateChangeListener listener : mListeners) {
listener.onViewDetachedFromWindow(this);
}
}
@Override
public void addOnAttachStateChangeListener(View_OnAttachStateChangeListener listener) {
mListeners.add(listener);
}
@Override
public void removeOnAttachStateChangeListener(View_OnAttachStateChangeListener listener) {
mListeners.remove(listener);
}
}
private class OverflowPopup extends MenuPopupHelper {
public OverflowPopup(Context context, MenuBuilder menu, View anchorView,
boolean overflowOnly) {
super(context, menu, anchorView, overflowOnly);
setCallback(mPopupPresenterCallback);
}
@Override
public void onDismiss() {
super.onDismiss();
mMenu.close();
mOverflowPopup = null;
}
}
private class ActionButtonSubmenu extends MenuPopupHelper {
//UNUSED private SubMenuBuilder mSubMenu;
public ActionButtonSubmenu(Context context, SubMenuBuilder subMenu) {
super(context, subMenu);
//UNUSED mSubMenu = subMenu;
MenuItemImpl item = (MenuItemImpl) subMenu.getItem();
if (!item.isActionButton()) {
// Give a reasonable anchor to nested submenus.
setAnchorView(mOverflowButton == null ? (View) mMenuView : mOverflowButton);
}
setCallback(mPopupPresenterCallback);
boolean preserveIconSpacing = false;
final int count = subMenu.size();
for (int i = 0; i < count; i++) {
MenuItem childItem = subMenu.getItem(i);
if (childItem.isVisible() && childItem.getIcon() != null) {
preserveIconSpacing = true;
break;
}
}
setForceShowIcon(preserveIconSpacing);
}
@Override
public void onDismiss() {
super.onDismiss();
mActionButtonPopup = null;
mOpenSubMenuId = 0;
}
}
private class PopupPresenterCallback implements MenuPresenter.Callback {
@Override
public boolean onOpenSubMenu(MenuBuilder subMenu) {
if (subMenu == null) return false;
mOpenSubMenuId = ((SubMenuBuilder) subMenu).getItem().getItemId();
return false;
}
@Override
public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
if (menu instanceof SubMenuBuilder) {
((SubMenuBuilder) menu).getRootMenu().close(false);
}
}
}
private class OpenOverflowRunnable implements Runnable {
private OverflowPopup mPopup;
public OpenOverflowRunnable(OverflowPopup popup) {
mPopup = popup;
}
public void run() {
mMenu.changeMenuMode();
final View menuView = (View) mMenuView;
if (menuView != null && menuView.getWindowToken() != null && mPopup.tryShow()) {
mOverflowPopup = mPopup;
}
mPostedOpenRunnable = null;
}
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter.java | Java | asf20 | 25,319 |
package com.actionbarsherlock.internal.view.menu;
import android.graphics.drawable.Drawable;
import android.view.View;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
public class SubMenuWrapper extends MenuWrapper implements SubMenu {
private final android.view.SubMenu mNativeSubMenu;
private MenuItem mItem = null;
public SubMenuWrapper(android.view.SubMenu nativeSubMenu) {
super(nativeSubMenu);
mNativeSubMenu = nativeSubMenu;
}
@Override
public SubMenu setHeaderTitle(int titleRes) {
mNativeSubMenu.setHeaderTitle(titleRes);
return this;
}
@Override
public SubMenu setHeaderTitle(CharSequence title) {
mNativeSubMenu.setHeaderTitle(title);
return this;
}
@Override
public SubMenu setHeaderIcon(int iconRes) {
mNativeSubMenu.setHeaderIcon(iconRes);
return this;
}
@Override
public SubMenu setHeaderIcon(Drawable icon) {
mNativeSubMenu.setHeaderIcon(icon);
return this;
}
@Override
public SubMenu setHeaderView(View view) {
mNativeSubMenu.setHeaderView(view);
return this;
}
@Override
public void clearHeader() {
mNativeSubMenu.clearHeader();
}
@Override
public SubMenu setIcon(int iconRes) {
mNativeSubMenu.setIcon(iconRes);
return this;
}
@Override
public SubMenu setIcon(Drawable icon) {
mNativeSubMenu.setIcon(icon);
return this;
}
@Override
public MenuItem getItem() {
if (mItem == null) {
mItem = new MenuItemWrapper(mNativeSubMenu.getItem());
}
return mItem;
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/internal/view/menu/SubMenuWrapper.java | Java | asf20 | 1,722 |
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.internal.view.menu;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.SparseArray;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import com.actionbarsherlock.R;
import com.actionbarsherlock.view.ActionProvider;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
/**
* Implementation of the {@link android.view.Menu} interface for creating a
* standard menu UI.
*/
public class MenuBuilder implements Menu {
//UNUSED private static final String TAG = "MenuBuilder";
private static final String PRESENTER_KEY = "android:menu:presenters";
private static final String ACTION_VIEW_STATES_KEY = "android:menu:actionviewstates";
private static final String EXPANDED_ACTION_VIEW_ID = "android:menu:expandedactionview";
private static final int[] sCategoryToOrder = new int[] {
1, /* No category */
4, /* CONTAINER */
5, /* SYSTEM */
3, /* SECONDARY */
2, /* ALTERNATIVE */
0, /* SELECTED_ALTERNATIVE */
};
private final Context mContext;
private final Resources mResources;
/**
* Whether the shortcuts should be qwerty-accessible. Use isQwertyMode()
* instead of accessing this directly.
*/
private boolean mQwertyMode;
/**
* Whether the shortcuts should be visible on menus. Use isShortcutsVisible()
* instead of accessing this directly.
*/
private boolean mShortcutsVisible;
/**
* Callback that will receive the various menu-related events generated by
* this class. Use getCallback to get a reference to the callback.
*/
private Callback mCallback;
/** Contains all of the items for this menu */
private ArrayList<MenuItemImpl> mItems;
/** Contains only the items that are currently visible. This will be created/refreshed from
* {@link #getVisibleItems()} */
private ArrayList<MenuItemImpl> mVisibleItems;
/**
* Whether or not the items (or any one item's shown state) has changed since it was last
* fetched from {@link #getVisibleItems()}
*/
private boolean mIsVisibleItemsStale;
/**
* Contains only the items that should appear in the Action Bar, if present.
*/
private ArrayList<MenuItemImpl> mActionItems;
/**
* Contains items that should NOT appear in the Action Bar, if present.
*/
private ArrayList<MenuItemImpl> mNonActionItems;
/**
* Whether or not the items (or any one item's action state) has changed since it was
* last fetched.
*/
private boolean mIsActionItemsStale;
/**
* Default value for how added items should show in the action list.
*/
private int mDefaultShowAsAction = MenuItem.SHOW_AS_ACTION_NEVER;
/**
* Current use case is Context Menus: As Views populate the context menu, each one has
* extra information that should be passed along. This is the current menu info that
* should be set on all items added to this menu.
*/
private ContextMenuInfo mCurrentMenuInfo;
/** Header title for menu types that have a header (context and submenus) */
CharSequence mHeaderTitle;
/** Header icon for menu types that have a header and support icons (context) */
Drawable mHeaderIcon;
/** Header custom view for menu types that have a header and support custom views (context) */
View mHeaderView;
/**
* Contains the state of the View hierarchy for all menu views when the menu
* was frozen.
*/
//UNUSED private SparseArray<Parcelable> mFrozenViewStates;
/**
* Prevents onItemsChanged from doing its junk, useful for batching commands
* that may individually call onItemsChanged.
*/
private boolean mPreventDispatchingItemsChanged = false;
private boolean mItemsChangedWhileDispatchPrevented = false;
private boolean mOptionalIconsVisible = false;
private boolean mIsClosing = false;
private ArrayList<MenuItemImpl> mTempShortcutItemList = new ArrayList<MenuItemImpl>();
private CopyOnWriteArrayList<WeakReference<MenuPresenter>> mPresenters =
new CopyOnWriteArrayList<WeakReference<MenuPresenter>>();
/**
* Currently expanded menu item; must be collapsed when we clear.
*/
private MenuItemImpl mExpandedItem;
/**
* Called by menu to notify of close and selection changes.
*/
public interface Callback {
/**
* Called when a menu item is selected.
* @param menu The menu that is the parent of the item
* @param item The menu item that is selected
* @return whether the menu item selection was handled
*/
public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item);
/**
* Called when the mode of the menu changes (for example, from icon to expanded).
*
* @param menu the menu that has changed modes
*/
public void onMenuModeChange(MenuBuilder menu);
}
/**
* Called by menu items to execute their associated action
*/
public interface ItemInvoker {
public boolean invokeItem(MenuItemImpl item);
}
public MenuBuilder(Context context) {
mContext = context;
mResources = context.getResources();
mItems = new ArrayList<MenuItemImpl>();
mVisibleItems = new ArrayList<MenuItemImpl>();
mIsVisibleItemsStale = true;
mActionItems = new ArrayList<MenuItemImpl>();
mNonActionItems = new ArrayList<MenuItemImpl>();
mIsActionItemsStale = true;
setShortcutsVisibleInner(true);
}
public MenuBuilder setDefaultShowAsAction(int defaultShowAsAction) {
mDefaultShowAsAction = defaultShowAsAction;
return this;
}
/**
* Add a presenter to this menu. This will only hold a WeakReference;
* you do not need to explicitly remove a presenter, but you can using
* {@link #removeMenuPresenter(MenuPresenter)}.
*
* @param presenter The presenter to add
*/
public void addMenuPresenter(MenuPresenter presenter) {
mPresenters.add(new WeakReference<MenuPresenter>(presenter));
presenter.initForMenu(mContext, this);
mIsActionItemsStale = true;
}
/**
* Remove a presenter from this menu. That presenter will no longer
* receive notifications of updates to this menu's data.
*
* @param presenter The presenter to remove
*/
public void removeMenuPresenter(MenuPresenter presenter) {
for (WeakReference<MenuPresenter> ref : mPresenters) {
final MenuPresenter item = ref.get();
if (item == null || item == presenter) {
mPresenters.remove(ref);
}
}
}
private void dispatchPresenterUpdate(boolean cleared) {
if (mPresenters.isEmpty()) return;
stopDispatchingItemsChanged();
for (WeakReference<MenuPresenter> ref : mPresenters) {
final MenuPresenter presenter = ref.get();
if (presenter == null) {
mPresenters.remove(ref);
} else {
presenter.updateMenuView(cleared);
}
}
startDispatchingItemsChanged();
}
private boolean dispatchSubMenuSelected(SubMenuBuilder subMenu) {
if (mPresenters.isEmpty()) return false;
boolean result = false;
for (WeakReference<MenuPresenter> ref : mPresenters) {
final MenuPresenter presenter = ref.get();
if (presenter == null) {
mPresenters.remove(ref);
} else if (!result) {
result = presenter.onSubMenuSelected(subMenu);
}
}
return result;
}
private void dispatchSaveInstanceState(Bundle outState) {
if (mPresenters.isEmpty()) return;
SparseArray<Parcelable> presenterStates = new SparseArray<Parcelable>();
for (WeakReference<MenuPresenter> ref : mPresenters) {
final MenuPresenter presenter = ref.get();
if (presenter == null) {
mPresenters.remove(ref);
} else {
final int id = presenter.getId();
if (id > 0) {
final Parcelable state = presenter.onSaveInstanceState();
if (state != null) {
presenterStates.put(id, state);
}
}
}
}
outState.putSparseParcelableArray(PRESENTER_KEY, presenterStates);
}
private void dispatchRestoreInstanceState(Bundle state) {
SparseArray<Parcelable> presenterStates = state.getSparseParcelableArray(PRESENTER_KEY);
if (presenterStates == null || mPresenters.isEmpty()) return;
for (WeakReference<MenuPresenter> ref : mPresenters) {
final MenuPresenter presenter = ref.get();
if (presenter == null) {
mPresenters.remove(ref);
} else {
final int id = presenter.getId();
if (id > 0) {
Parcelable parcel = presenterStates.get(id);
if (parcel != null) {
presenter.onRestoreInstanceState(parcel);
}
}
}
}
}
public void savePresenterStates(Bundle outState) {
dispatchSaveInstanceState(outState);
}
public void restorePresenterStates(Bundle state) {
dispatchRestoreInstanceState(state);
}
public void saveActionViewStates(Bundle outStates) {
SparseArray<Parcelable> viewStates = null;
final int itemCount = size();
for (int i = 0; i < itemCount; i++) {
final MenuItem item = getItem(i);
final View v = item.getActionView();
if (v != null && v.getId() != View.NO_ID) {
if (viewStates == null) {
viewStates = new SparseArray<Parcelable>();
}
v.saveHierarchyState(viewStates);
if (item.isActionViewExpanded()) {
outStates.putInt(EXPANDED_ACTION_VIEW_ID, item.getItemId());
}
}
if (item.hasSubMenu()) {
final SubMenuBuilder subMenu = (SubMenuBuilder) item.getSubMenu();
subMenu.saveActionViewStates(outStates);
}
}
if (viewStates != null) {
outStates.putSparseParcelableArray(getActionViewStatesKey(), viewStates);
}
}
public void restoreActionViewStates(Bundle states) {
if (states == null) {
return;
}
SparseArray<Parcelable> viewStates = states.getSparseParcelableArray(
getActionViewStatesKey());
final int itemCount = size();
for (int i = 0; i < itemCount; i++) {
final MenuItem item = getItem(i);
final View v = item.getActionView();
if (v != null && v.getId() != View.NO_ID) {
v.restoreHierarchyState(viewStates);
}
if (item.hasSubMenu()) {
final SubMenuBuilder subMenu = (SubMenuBuilder) item.getSubMenu();
subMenu.restoreActionViewStates(states);
}
}
final int expandedId = states.getInt(EXPANDED_ACTION_VIEW_ID);
if (expandedId > 0) {
MenuItem itemToExpand = findItem(expandedId);
if (itemToExpand != null) {
itemToExpand.expandActionView();
}
}
}
protected String getActionViewStatesKey() {
return ACTION_VIEW_STATES_KEY;
}
public void setCallback(Callback cb) {
mCallback = cb;
}
/**
* Adds an item to the menu. The other add methods funnel to this.
*/
private MenuItem addInternal(int group, int id, int categoryOrder, CharSequence title) {
final int ordering = getOrdering(categoryOrder);
final MenuItemImpl item = new MenuItemImpl(this, group, id, categoryOrder,
ordering, title, mDefaultShowAsAction);
if (mCurrentMenuInfo != null) {
// Pass along the current menu info
item.setMenuInfo(mCurrentMenuInfo);
}
mItems.add(findInsertIndex(mItems, ordering), item);
onItemsChanged(true);
return item;
}
public MenuItem add(CharSequence title) {
return addInternal(0, 0, 0, title);
}
public MenuItem add(int titleRes) {
return addInternal(0, 0, 0, mResources.getString(titleRes));
}
public MenuItem add(int group, int id, int categoryOrder, CharSequence title) {
return addInternal(group, id, categoryOrder, title);
}
public MenuItem add(int group, int id, int categoryOrder, int title) {
return addInternal(group, id, categoryOrder, mResources.getString(title));
}
public SubMenu addSubMenu(CharSequence title) {
return addSubMenu(0, 0, 0, title);
}
public SubMenu addSubMenu(int titleRes) {
return addSubMenu(0, 0, 0, mResources.getString(titleRes));
}
public SubMenu addSubMenu(int group, int id, int categoryOrder, CharSequence title) {
final MenuItemImpl item = (MenuItemImpl) addInternal(group, id, categoryOrder, title);
final SubMenuBuilder subMenu = new SubMenuBuilder(mContext, this, item);
item.setSubMenu(subMenu);
return subMenu;
}
public SubMenu addSubMenu(int group, int id, int categoryOrder, int title) {
return addSubMenu(group, id, categoryOrder, mResources.getString(title));
}
public int addIntentOptions(int group, int id, int categoryOrder, ComponentName caller,
Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) {
PackageManager pm = mContext.getPackageManager();
final List<ResolveInfo> lri =
pm.queryIntentActivityOptions(caller, specifics, intent, 0);
final int N = lri != null ? lri.size() : 0;
if ((flags & FLAG_APPEND_TO_GROUP) == 0) {
removeGroup(group);
}
for (int i=0; i<N; i++) {
final ResolveInfo ri = lri.get(i);
Intent rintent = new Intent(
ri.specificIndex < 0 ? intent : specifics[ri.specificIndex]);
rintent.setComponent(new ComponentName(
ri.activityInfo.applicationInfo.packageName,
ri.activityInfo.name));
final MenuItem item = add(group, id, categoryOrder, ri.loadLabel(pm))
.setIcon(ri.loadIcon(pm))
.setIntent(rintent);
if (outSpecificItems != null && ri.specificIndex >= 0) {
outSpecificItems[ri.specificIndex] = item;
}
}
return N;
}
public void removeItem(int id) {
removeItemAtInt(findItemIndex(id), true);
}
public void removeGroup(int group) {
final int i = findGroupIndex(group);
if (i >= 0) {
final int maxRemovable = mItems.size() - i;
int numRemoved = 0;
while ((numRemoved++ < maxRemovable) && (mItems.get(i).getGroupId() == group)) {
// Don't force update for each one, this method will do it at the end
removeItemAtInt(i, false);
}
// Notify menu views
onItemsChanged(true);
}
}
/**
* Remove the item at the given index and optionally forces menu views to
* update.
*
* @param index The index of the item to be removed. If this index is
* invalid an exception is thrown.
* @param updateChildrenOnMenuViews Whether to force update on menu views.
* Please make sure you eventually call this after your batch of
* removals.
*/
private void removeItemAtInt(int index, boolean updateChildrenOnMenuViews) {
if ((index < 0) || (index >= mItems.size())) return;
mItems.remove(index);
if (updateChildrenOnMenuViews) onItemsChanged(true);
}
public void removeItemAt(int index) {
removeItemAtInt(index, true);
}
public void clearAll() {
mPreventDispatchingItemsChanged = true;
clear();
clearHeader();
mPreventDispatchingItemsChanged = false;
mItemsChangedWhileDispatchPrevented = false;
onItemsChanged(true);
}
public void clear() {
if (mExpandedItem != null) {
collapseItemActionView(mExpandedItem);
}
mItems.clear();
onItemsChanged(true);
}
void setExclusiveItemChecked(MenuItem item) {
final int group = item.getGroupId();
final int N = mItems.size();
for (int i = 0; i < N; i++) {
MenuItemImpl curItem = mItems.get(i);
if (curItem.getGroupId() == group) {
if (!curItem.isExclusiveCheckable()) continue;
if (!curItem.isCheckable()) continue;
// Check the item meant to be checked, uncheck the others (that are in the group)
curItem.setCheckedInt(curItem == item);
}
}
}
public void setGroupCheckable(int group, boolean checkable, boolean exclusive) {
final int N = mItems.size();
for (int i = 0; i < N; i++) {
MenuItemImpl item = mItems.get(i);
if (item.getGroupId() == group) {
item.setExclusiveCheckable(exclusive);
item.setCheckable(checkable);
}
}
}
public void setGroupVisible(int group, boolean visible) {
final int N = mItems.size();
// We handle the notification of items being changed ourselves, so we use setVisibleInt rather
// than setVisible and at the end notify of items being changed
boolean changedAtLeastOneItem = false;
for (int i = 0; i < N; i++) {
MenuItemImpl item = mItems.get(i);
if (item.getGroupId() == group) {
if (item.setVisibleInt(visible)) changedAtLeastOneItem = true;
}
}
if (changedAtLeastOneItem) onItemsChanged(true);
}
public void setGroupEnabled(int group, boolean enabled) {
final int N = mItems.size();
for (int i = 0; i < N; i++) {
MenuItemImpl item = mItems.get(i);
if (item.getGroupId() == group) {
item.setEnabled(enabled);
}
}
}
public boolean hasVisibleItems() {
final int size = size();
for (int i = 0; i < size; i++) {
MenuItemImpl item = mItems.get(i);
if (item.isVisible()) {
return true;
}
}
return false;
}
public MenuItem findItem(int id) {
final int size = size();
for (int i = 0; i < size; i++) {
MenuItemImpl item = mItems.get(i);
if (item.getItemId() == id) {
return item;
} else if (item.hasSubMenu()) {
MenuItem possibleItem = item.getSubMenu().findItem(id);
if (possibleItem != null) {
return possibleItem;
}
}
}
return null;
}
public int findItemIndex(int id) {
final int size = size();
for (int i = 0; i < size; i++) {
MenuItemImpl item = mItems.get(i);
if (item.getItemId() == id) {
return i;
}
}
return -1;
}
public int findGroupIndex(int group) {
return findGroupIndex(group, 0);
}
public int findGroupIndex(int group, int start) {
final int size = size();
if (start < 0) {
start = 0;
}
for (int i = start; i < size; i++) {
final MenuItemImpl item = mItems.get(i);
if (item.getGroupId() == group) {
return i;
}
}
return -1;
}
public int size() {
return mItems.size();
}
/** {@inheritDoc} */
public MenuItem getItem(int index) {
return mItems.get(index);
}
public boolean isShortcutKey(int keyCode, KeyEvent event) {
return findItemWithShortcutForKey(keyCode, event) != null;
}
public void setQwertyMode(boolean isQwerty) {
mQwertyMode = isQwerty;
onItemsChanged(false);
}
/**
* Returns the ordering across all items. This will grab the category from
* the upper bits, find out how to order the category with respect to other
* categories, and combine it with the lower bits.
*
* @param categoryOrder The category order for a particular item (if it has
* not been or/add with a category, the default category is
* assumed).
* @return An ordering integer that can be used to order this item across
* all the items (even from other categories).
*/
private static int getOrdering(int categoryOrder) {
final int index = (categoryOrder & CATEGORY_MASK) >> CATEGORY_SHIFT;
if (index < 0 || index >= sCategoryToOrder.length) {
throw new IllegalArgumentException("order does not contain a valid category.");
}
return (sCategoryToOrder[index] << CATEGORY_SHIFT) | (categoryOrder & USER_MASK);
}
/**
* @return whether the menu shortcuts are in qwerty mode or not
*/
boolean isQwertyMode() {
return mQwertyMode;
}
/**
* Sets whether the shortcuts should be visible on menus. Devices without hardware
* key input will never make shortcuts visible even if this method is passed 'true'.
*
* @param shortcutsVisible Whether shortcuts should be visible (if true and a
* menu item does not have a shortcut defined, that item will
* still NOT show a shortcut)
*/
public void setShortcutsVisible(boolean shortcutsVisible) {
if (mShortcutsVisible == shortcutsVisible) return;
setShortcutsVisibleInner(shortcutsVisible);
onItemsChanged(false);
}
private void setShortcutsVisibleInner(boolean shortcutsVisible) {
mShortcutsVisible = shortcutsVisible
&& mResources.getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS
&& mResources.getBoolean(
R.bool.abs__config_showMenuShortcutsWhenKeyboardPresent);
}
/**
* @return Whether shortcuts should be visible on menus.
*/
public boolean isShortcutsVisible() {
return mShortcutsVisible;
}
Resources getResources() {
return mResources;
}
public Context getContext() {
return mContext;
}
boolean dispatchMenuItemSelected(MenuBuilder menu, MenuItem item) {
return mCallback != null && mCallback.onMenuItemSelected(menu, item);
}
/**
* Dispatch a mode change event to this menu's callback.
*/
public void changeMenuMode() {
if (mCallback != null) {
mCallback.onMenuModeChange(this);
}
}
private static int findInsertIndex(ArrayList<MenuItemImpl> items, int ordering) {
for (int i = items.size() - 1; i >= 0; i--) {
MenuItemImpl item = items.get(i);
if (item.getOrdering() <= ordering) {
return i + 1;
}
}
return 0;
}
public boolean performShortcut(int keyCode, KeyEvent event, int flags) {
final MenuItemImpl item = findItemWithShortcutForKey(keyCode, event);
boolean handled = false;
if (item != null) {
handled = performItemAction(item, flags);
}
if ((flags & FLAG_ALWAYS_PERFORM_CLOSE) != 0) {
close(true);
}
return handled;
}
/*
* This function will return all the menu and sub-menu items that can
* be directly (the shortcut directly corresponds) and indirectly
* (the ALT-enabled char corresponds to the shortcut) associated
* with the keyCode.
*/
@SuppressWarnings("deprecation")
void findItemsWithShortcutForKey(List<MenuItemImpl> items, int keyCode, KeyEvent event) {
final boolean qwerty = isQwertyMode();
final int metaState = event.getMetaState();
final KeyCharacterMap.KeyData possibleChars = new KeyCharacterMap.KeyData();
// Get the chars associated with the keyCode (i.e using any chording combo)
final boolean isKeyCodeMapped = event.getKeyData(possibleChars);
// The delete key is not mapped to '\b' so we treat it specially
if (!isKeyCodeMapped && (keyCode != KeyEvent.KEYCODE_DEL)) {
return;
}
// Look for an item whose shortcut is this key.
final int N = mItems.size();
for (int i = 0; i < N; i++) {
MenuItemImpl item = mItems.get(i);
if (item.hasSubMenu()) {
((MenuBuilder)item.getSubMenu()).findItemsWithShortcutForKey(items, keyCode, event);
}
final char shortcutChar = qwerty ? item.getAlphabeticShortcut() : item.getNumericShortcut();
if (((metaState & (KeyEvent.META_SHIFT_ON | KeyEvent.META_SYM_ON)) == 0) &&
(shortcutChar != 0) &&
(shortcutChar == possibleChars.meta[0]
|| shortcutChar == possibleChars.meta[2]
|| (qwerty && shortcutChar == '\b' &&
keyCode == KeyEvent.KEYCODE_DEL)) &&
item.isEnabled()) {
items.add(item);
}
}
}
/*
* We want to return the menu item associated with the key, but if there is no
* ambiguity (i.e. there is only one menu item corresponding to the key) we want
* to return it even if it's not an exact match; this allow the user to
* _not_ use the ALT key for example, making the use of shortcuts slightly more
* user-friendly. An example is on the G1, '!' and '1' are on the same key, and
* in Gmail, Menu+1 will trigger Menu+! (the actual shortcut).
*
* On the other hand, if two (or more) shortcuts corresponds to the same key,
* we have to only return the exact match.
*/
@SuppressWarnings("deprecation")
MenuItemImpl findItemWithShortcutForKey(int keyCode, KeyEvent event) {
// Get all items that can be associated directly or indirectly with the keyCode
ArrayList<MenuItemImpl> items = mTempShortcutItemList;
items.clear();
findItemsWithShortcutForKey(items, keyCode, event);
if (items.isEmpty()) {
return null;
}
final int metaState = event.getMetaState();
final KeyCharacterMap.KeyData possibleChars = new KeyCharacterMap.KeyData();
// Get the chars associated with the keyCode (i.e using any chording combo)
event.getKeyData(possibleChars);
// If we have only one element, we can safely returns it
final int size = items.size();
if (size == 1) {
return items.get(0);
}
final boolean qwerty = isQwertyMode();
// If we found more than one item associated with the key,
// we have to return the exact match
for (int i = 0; i < size; i++) {
final MenuItemImpl item = items.get(i);
final char shortcutChar = qwerty ? item.getAlphabeticShortcut() :
item.getNumericShortcut();
if ((shortcutChar == possibleChars.meta[0] &&
(metaState & KeyEvent.META_ALT_ON) == 0)
|| (shortcutChar == possibleChars.meta[2] &&
(metaState & KeyEvent.META_ALT_ON) != 0)
|| (qwerty && shortcutChar == '\b' &&
keyCode == KeyEvent.KEYCODE_DEL)) {
return item;
}
}
return null;
}
public boolean performIdentifierAction(int id, int flags) {
// Look for an item whose identifier is the id.
return performItemAction(findItem(id), flags);
}
public boolean performItemAction(MenuItem item, int flags) {
MenuItemImpl itemImpl = (MenuItemImpl) item;
if (itemImpl == null || !itemImpl.isEnabled()) {
return false;
}
boolean invoked = itemImpl.invoke();
if (itemImpl.hasCollapsibleActionView()) {
invoked |= itemImpl.expandActionView();
if (invoked) close(true);
} else if (item.hasSubMenu()) {
close(false);
final SubMenuBuilder subMenu = (SubMenuBuilder) item.getSubMenu();
final ActionProvider provider = item.getActionProvider();
if (provider != null && provider.hasSubMenu()) {
provider.onPrepareSubMenu(subMenu);
}
invoked |= dispatchSubMenuSelected(subMenu);
if (!invoked) close(true);
} else {
if ((flags & FLAG_PERFORM_NO_CLOSE) == 0) {
close(true);
}
}
return invoked;
}
/**
* Closes the visible menu.
*
* @param allMenusAreClosing Whether the menus are completely closing (true),
* or whether there is another menu coming in this menu's place
* (false). For example, if the menu is closing because a
* sub menu is about to be shown, <var>allMenusAreClosing</var>
* is false.
*/
final void close(boolean allMenusAreClosing) {
if (mIsClosing) return;
mIsClosing = true;
for (WeakReference<MenuPresenter> ref : mPresenters) {
final MenuPresenter presenter = ref.get();
if (presenter == null) {
mPresenters.remove(ref);
} else {
presenter.onCloseMenu(this, allMenusAreClosing);
}
}
mIsClosing = false;
}
/** {@inheritDoc} */
public void close() {
close(true);
}
/**
* Called when an item is added or removed.
*
* @param structureChanged true if the menu structure changed,
* false if only item properties changed.
* (Visibility is a structural property since it affects layout.)
*/
void onItemsChanged(boolean structureChanged) {
if (!mPreventDispatchingItemsChanged) {
if (structureChanged) {
mIsVisibleItemsStale = true;
mIsActionItemsStale = true;
}
dispatchPresenterUpdate(structureChanged);
} else {
mItemsChangedWhileDispatchPrevented = true;
}
}
/**
* Stop dispatching item changed events to presenters until
* {@link #startDispatchingItemsChanged()} is called. Useful when
* many menu operations are going to be performed as a batch.
*/
public void stopDispatchingItemsChanged() {
if (!mPreventDispatchingItemsChanged) {
mPreventDispatchingItemsChanged = true;
mItemsChangedWhileDispatchPrevented = false;
}
}
public void startDispatchingItemsChanged() {
mPreventDispatchingItemsChanged = false;
if (mItemsChangedWhileDispatchPrevented) {
mItemsChangedWhileDispatchPrevented = false;
onItemsChanged(true);
}
}
/**
* Called by {@link MenuItemImpl} when its visible flag is changed.
* @param item The item that has gone through a visibility change.
*/
void onItemVisibleChanged(MenuItemImpl item) {
// Notify of items being changed
mIsVisibleItemsStale = true;
onItemsChanged(true);
}
/**
* Called by {@link MenuItemImpl} when its action request status is changed.
* @param item The item that has gone through a change in action request status.
*/
void onItemActionRequestChanged(MenuItemImpl item) {
// Notify of items being changed
mIsActionItemsStale = true;
onItemsChanged(true);
}
ArrayList<MenuItemImpl> getVisibleItems() {
if (!mIsVisibleItemsStale) return mVisibleItems;
// Refresh the visible items
mVisibleItems.clear();
final int itemsSize = mItems.size();
MenuItemImpl item;
for (int i = 0; i < itemsSize; i++) {
item = mItems.get(i);
if (item.isVisible()) mVisibleItems.add(item);
}
mIsVisibleItemsStale = false;
mIsActionItemsStale = true;
return mVisibleItems;
}
/**
* This method determines which menu items get to be 'action items' that will appear
* in an action bar and which items should be 'overflow items' in a secondary menu.
* The rules are as follows:
*
* <p>Items are considered for inclusion in the order specified within the menu.
* There is a limit of mMaxActionItems as a total count, optionally including the overflow
* menu button itself. This is a soft limit; if an item shares a group ID with an item
* previously included as an action item, the new item will stay with its group and become
* an action item itself even if it breaks the max item count limit. This is done to
* limit the conceptual complexity of the items presented within an action bar. Only a few
* unrelated concepts should be presented to the user in this space, and groups are treated
* as a single concept.
*
* <p>There is also a hard limit of consumed measurable space: mActionWidthLimit. This
* limit may be broken by a single item that exceeds the remaining space, but no further
* items may be added. If an item that is part of a group cannot fit within the remaining
* measured width, the entire group will be demoted to overflow. This is done to ensure room
* for navigation and other affordances in the action bar as well as reduce general UI clutter.
*
* <p>The space freed by demoting a full group cannot be consumed by future menu items.
* Once items begin to overflow, all future items become overflow items as well. This is
* to avoid inadvertent reordering that may break the app's intended design.
*/
public void flagActionItems() {
if (!mIsActionItemsStale) {
return;
}
// Presenters flag action items as needed.
boolean flagged = false;
for (WeakReference<MenuPresenter> ref : mPresenters) {
final MenuPresenter presenter = ref.get();
if (presenter == null) {
mPresenters.remove(ref);
} else {
flagged |= presenter.flagActionItems();
}
}
if (flagged) {
mActionItems.clear();
mNonActionItems.clear();
ArrayList<MenuItemImpl> visibleItems = getVisibleItems();
final int itemsSize = visibleItems.size();
for (int i = 0; i < itemsSize; i++) {
MenuItemImpl item = visibleItems.get(i);
if (item.isActionButton()) {
mActionItems.add(item);
} else {
mNonActionItems.add(item);
}
}
} else {
// Nobody flagged anything, everything is a non-action item.
// (This happens during a first pass with no action-item presenters.)
mActionItems.clear();
mNonActionItems.clear();
mNonActionItems.addAll(getVisibleItems());
}
mIsActionItemsStale = false;
}
ArrayList<MenuItemImpl> getActionItems() {
flagActionItems();
return mActionItems;
}
ArrayList<MenuItemImpl> getNonActionItems() {
flagActionItems();
return mNonActionItems;
}
public void clearHeader() {
mHeaderIcon = null;
mHeaderTitle = null;
mHeaderView = null;
onItemsChanged(false);
}
private void setHeaderInternal(final int titleRes, final CharSequence title, final int iconRes,
final Drawable icon, final View view) {
final Resources r = getResources();
if (view != null) {
mHeaderView = view;
// If using a custom view, then the title and icon aren't used
mHeaderTitle = null;
mHeaderIcon = null;
} else {
if (titleRes > 0) {
mHeaderTitle = r.getText(titleRes);
} else if (title != null) {
mHeaderTitle = title;
}
if (iconRes > 0) {
mHeaderIcon = r.getDrawable(iconRes);
} else if (icon != null) {
mHeaderIcon = icon;
}
// If using the title or icon, then a custom view isn't used
mHeaderView = null;
}
// Notify of change
onItemsChanged(false);
}
/**
* Sets the header's title. This replaces the header view. Called by the
* builder-style methods of subclasses.
*
* @param title The new title.
* @return This MenuBuilder so additional setters can be called.
*/
protected MenuBuilder setHeaderTitleInt(CharSequence title) {
setHeaderInternal(0, title, 0, null, null);
return this;
}
/**
* Sets the header's title. This replaces the header view. Called by the
* builder-style methods of subclasses.
*
* @param titleRes The new title (as a resource ID).
* @return This MenuBuilder so additional setters can be called.
*/
protected MenuBuilder setHeaderTitleInt(int titleRes) {
setHeaderInternal(titleRes, null, 0, null, null);
return this;
}
/**
* Sets the header's icon. This replaces the header view. Called by the
* builder-style methods of subclasses.
*
* @param icon The new icon.
* @return This MenuBuilder so additional setters can be called.
*/
protected MenuBuilder setHeaderIconInt(Drawable icon) {
setHeaderInternal(0, null, 0, icon, null);
return this;
}
/**
* Sets the header's icon. This replaces the header view. Called by the
* builder-style methods of subclasses.
*
* @param iconRes The new icon (as a resource ID).
* @return This MenuBuilder so additional setters can be called.
*/
protected MenuBuilder setHeaderIconInt(int iconRes) {
setHeaderInternal(0, null, iconRes, null, null);
return this;
}
/**
* Sets the header's view. This replaces the title and icon. Called by the
* builder-style methods of subclasses.
*
* @param view The new view.
* @return This MenuBuilder so additional setters can be called.
*/
protected MenuBuilder setHeaderViewInt(View view) {
setHeaderInternal(0, null, 0, null, view);
return this;
}
public CharSequence getHeaderTitle() {
return mHeaderTitle;
}
public Drawable getHeaderIcon() {
return mHeaderIcon;
}
public View getHeaderView() {
return mHeaderView;
}
/**
* Gets the root menu (if this is a submenu, find its root menu).
* @return The root menu.
*/
public MenuBuilder getRootMenu() {
return this;
}
/**
* Sets the current menu info that is set on all items added to this menu
* (until this is called again with different menu info, in which case that
* one will be added to all subsequent item additions).
*
* @param menuInfo The extra menu information to add.
*/
public void setCurrentMenuInfo(ContextMenuInfo menuInfo) {
mCurrentMenuInfo = menuInfo;
}
void setOptionalIconsVisible(boolean visible) {
mOptionalIconsVisible = visible;
}
boolean getOptionalIconsVisible() {
return mOptionalIconsVisible;
}
public boolean expandItemActionView(MenuItemImpl item) {
if (mPresenters.isEmpty()) return false;
boolean expanded = false;
stopDispatchingItemsChanged();
for (WeakReference<MenuPresenter> ref : mPresenters) {
final MenuPresenter presenter = ref.get();
if (presenter == null) {
mPresenters.remove(ref);
} else if ((expanded = presenter.expandItemActionView(this, item))) {
break;
}
}
startDispatchingItemsChanged();
if (expanded) {
mExpandedItem = item;
}
return expanded;
}
public boolean collapseItemActionView(MenuItemImpl item) {
if (mPresenters.isEmpty() || mExpandedItem != item) return false;
boolean collapsed = false;
stopDispatchingItemsChanged();
for (WeakReference<MenuPresenter> ref : mPresenters) {
final MenuPresenter presenter = ref.get();
if (presenter == null) {
mPresenters.remove(ref);
} else if ((collapsed = presenter.collapseItemActionView(this, item))) {
break;
}
}
startDispatchingItemsChanged();
if (collapsed) {
mExpandedItem = null;
}
return collapsed;
}
public MenuItemImpl getExpandedItem() {
return mExpandedItem;
}
public boolean bindNativeOverflow(android.view.Menu menu, android.view.MenuItem.OnMenuItemClickListener listener, HashMap<android.view.MenuItem, MenuItemImpl> map) {
final List<MenuItemImpl> nonActionItems = getNonActionItems();
if (nonActionItems == null || nonActionItems.size() == 0) {
return false;
}
boolean visible = false;
menu.clear();
for (MenuItemImpl nonActionItem : nonActionItems) {
if (!nonActionItem.isVisible()) {
continue;
}
visible = true;
android.view.MenuItem nativeItem;
if (nonActionItem.hasSubMenu()) {
android.view.SubMenu nativeSub = menu.addSubMenu(nonActionItem.getGroupId(), nonActionItem.getItemId(),
nonActionItem.getOrder(), nonActionItem.getTitle());
SubMenuBuilder subMenu = (SubMenuBuilder)nonActionItem.getSubMenu();
for (MenuItemImpl subItem : subMenu.getVisibleItems()) {
android.view.MenuItem nativeSubItem = nativeSub.add(subItem.getGroupId(), subItem.getItemId(),
subItem.getOrder(), subItem.getTitle());
nativeSubItem.setIcon(subItem.getIcon());
nativeSubItem.setOnMenuItemClickListener(listener);
nativeSubItem.setEnabled(subItem.isEnabled());
nativeSubItem.setIntent(subItem.getIntent());
nativeSubItem.setNumericShortcut(subItem.getNumericShortcut());
nativeSubItem.setAlphabeticShortcut(subItem.getAlphabeticShortcut());
nativeSubItem.setTitleCondensed(subItem.getTitleCondensed());
nativeSubItem.setCheckable(subItem.isCheckable());
nativeSubItem.setChecked(subItem.isChecked());
if (subItem.isExclusiveCheckable()) {
nativeSub.setGroupCheckable(subItem.getGroupId(), true, true);
}
map.put(nativeSubItem, subItem);
}
nativeItem = nativeSub.getItem();
} else {
nativeItem = menu.add(nonActionItem.getGroupId(), nonActionItem.getItemId(),
nonActionItem.getOrder(), nonActionItem.getTitle());
}
nativeItem.setIcon(nonActionItem.getIcon());
nativeItem.setOnMenuItemClickListener(listener);
nativeItem.setEnabled(nonActionItem.isEnabled());
nativeItem.setIntent(nonActionItem.getIntent());
nativeItem.setNumericShortcut(nonActionItem.getNumericShortcut());
nativeItem.setAlphabeticShortcut(nonActionItem.getAlphabeticShortcut());
nativeItem.setTitleCondensed(nonActionItem.getTitleCondensed());
nativeItem.setCheckable(nonActionItem.isCheckable());
nativeItem.setChecked(nonActionItem.isChecked());
if (nonActionItem.isExclusiveCheckable()) {
menu.setGroupCheckable(nonActionItem.getGroupId(), true, true);
}
map.put(nativeItem, nonActionItem);
}
return visible;
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/internal/view/menu/MenuBuilder.java | Java | asf20 | 45,959 |
package com.actionbarsherlock.internal.view.menu;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import com.actionbarsherlock.internal.view.ActionProviderWrapper;
import com.actionbarsherlock.view.ActionProvider;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
public class MenuItemWrapper implements MenuItem, android.view.MenuItem.OnMenuItemClickListener {
private final android.view.MenuItem mNativeItem;
private SubMenu mSubMenu = null;
private OnMenuItemClickListener mMenuItemClickListener = null;
private OnActionExpandListener mActionExpandListener = null;
private android.view.MenuItem.OnActionExpandListener mNativeActionExpandListener = null;
public MenuItemWrapper(android.view.MenuItem nativeItem) {
if (nativeItem == null) {
throw new IllegalStateException("Wrapped menu item cannot be null.");
}
mNativeItem = nativeItem;
}
@Override
public int getItemId() {
return mNativeItem.getItemId();
}
@Override
public int getGroupId() {
return mNativeItem.getGroupId();
}
@Override
public int getOrder() {
return mNativeItem.getOrder();
}
@Override
public MenuItem setTitle(CharSequence title) {
mNativeItem.setTitle(title);
return this;
}
@Override
public MenuItem setTitle(int title) {
mNativeItem.setTitle(title);
return this;
}
@Override
public CharSequence getTitle() {
return mNativeItem.getTitle();
}
@Override
public MenuItem setTitleCondensed(CharSequence title) {
mNativeItem.setTitleCondensed(title);
return this;
}
@Override
public CharSequence getTitleCondensed() {
return mNativeItem.getTitleCondensed();
}
@Override
public MenuItem setIcon(Drawable icon) {
mNativeItem.setIcon(icon);
return this;
}
@Override
public MenuItem setIcon(int iconRes) {
mNativeItem.setIcon(iconRes);
return this;
}
@Override
public Drawable getIcon() {
return mNativeItem.getIcon();
}
@Override
public MenuItem setIntent(Intent intent) {
mNativeItem.setIntent(intent);
return this;
}
@Override
public Intent getIntent() {
return mNativeItem.getIntent();
}
@Override
public MenuItem setShortcut(char numericChar, char alphaChar) {
mNativeItem.setShortcut(numericChar, alphaChar);
return this;
}
@Override
public MenuItem setNumericShortcut(char numericChar) {
mNativeItem.setNumericShortcut(numericChar);
return this;
}
@Override
public char getNumericShortcut() {
return mNativeItem.getNumericShortcut();
}
@Override
public MenuItem setAlphabeticShortcut(char alphaChar) {
mNativeItem.setAlphabeticShortcut(alphaChar);
return this;
}
@Override
public char getAlphabeticShortcut() {
return mNativeItem.getAlphabeticShortcut();
}
@Override
public MenuItem setCheckable(boolean checkable) {
mNativeItem.setCheckable(checkable);
return this;
}
@Override
public boolean isCheckable() {
return mNativeItem.isCheckable();
}
@Override
public MenuItem setChecked(boolean checked) {
mNativeItem.setChecked(checked);
return this;
}
@Override
public boolean isChecked() {
return mNativeItem.isChecked();
}
@Override
public MenuItem setVisible(boolean visible) {
mNativeItem.setVisible(visible);
return this;
}
@Override
public boolean isVisible() {
return mNativeItem.isVisible();
}
@Override
public MenuItem setEnabled(boolean enabled) {
mNativeItem.setEnabled(enabled);
return this;
}
@Override
public boolean isEnabled() {
return mNativeItem.isEnabled();
}
@Override
public boolean hasSubMenu() {
return mNativeItem.hasSubMenu();
}
@Override
public SubMenu getSubMenu() {
if (hasSubMenu() && (mSubMenu == null)) {
mSubMenu = new SubMenuWrapper(mNativeItem.getSubMenu());
}
return mSubMenu;
}
@Override
public MenuItem setOnMenuItemClickListener(OnMenuItemClickListener menuItemClickListener) {
mMenuItemClickListener = menuItemClickListener;
//Register ourselves as the listener to proxy
mNativeItem.setOnMenuItemClickListener(this);
return this;
}
@Override
public boolean onMenuItemClick(android.view.MenuItem item) {
if (mMenuItemClickListener != null) {
return mMenuItemClickListener.onMenuItemClick(this);
}
return false;
}
@Override
public ContextMenuInfo getMenuInfo() {
return mNativeItem.getMenuInfo();
}
@Override
public void setShowAsAction(int actionEnum) {
mNativeItem.setShowAsAction(actionEnum);
}
@Override
public MenuItem setShowAsActionFlags(int actionEnum) {
mNativeItem.setShowAsActionFlags(actionEnum);
return this;
}
@Override
public MenuItem setActionView(View view) {
mNativeItem.setActionView(view);
return this;
}
@Override
public MenuItem setActionView(int resId) {
mNativeItem.setActionView(resId);
return this;
}
@Override
public View getActionView() {
return mNativeItem.getActionView();
}
@Override
public MenuItem setActionProvider(ActionProvider actionProvider) {
mNativeItem.setActionProvider(new ActionProviderWrapper(actionProvider));
return this;
}
@Override
public ActionProvider getActionProvider() {
android.view.ActionProvider nativeProvider = mNativeItem.getActionProvider();
if (nativeProvider != null && nativeProvider instanceof ActionProviderWrapper) {
return ((ActionProviderWrapper)nativeProvider).unwrap();
}
return null;
}
@Override
public boolean expandActionView() {
return mNativeItem.expandActionView();
}
@Override
public boolean collapseActionView() {
return mNativeItem.collapseActionView();
}
@Override
public boolean isActionViewExpanded() {
return mNativeItem.isActionViewExpanded();
}
@Override
public MenuItem setOnActionExpandListener(OnActionExpandListener listener) {
mActionExpandListener = listener;
if (mNativeActionExpandListener == null) {
mNativeActionExpandListener = new android.view.MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(android.view.MenuItem menuItem) {
if (mActionExpandListener != null) {
return mActionExpandListener.onMenuItemActionExpand(MenuItemWrapper.this);
}
return false;
}
@Override
public boolean onMenuItemActionCollapse(android.view.MenuItem menuItem) {
if (mActionExpandListener != null) {
return mActionExpandListener.onMenuItemActionCollapse(MenuItemWrapper.this);
}
return false;
}
};
//Register our inner-class as the listener to proxy method calls
mNativeItem.setOnActionExpandListener(mNativeActionExpandListener);
}
return this;
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/internal/view/menu/MenuItemWrapper.java | Java | asf20 | 7,751 |
package com.actionbarsherlock.internal.view.menu;
import java.util.WeakHashMap;
import android.content.ComponentName;
import android.content.Intent;
import android.view.KeyEvent;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
public class MenuWrapper implements Menu {
private final android.view.Menu mNativeMenu;
private final WeakHashMap<android.view.MenuItem, MenuItem> mNativeMap =
new WeakHashMap<android.view.MenuItem, MenuItem>();
public MenuWrapper(android.view.Menu nativeMenu) {
mNativeMenu = nativeMenu;
}
public android.view.Menu unwrap() {
return mNativeMenu;
}
private MenuItem addInternal(android.view.MenuItem nativeItem) {
MenuItem item = new MenuItemWrapper(nativeItem);
mNativeMap.put(nativeItem, item);
return item;
}
@Override
public MenuItem add(CharSequence title) {
return addInternal(mNativeMenu.add(title));
}
@Override
public MenuItem add(int titleRes) {
return addInternal(mNativeMenu.add(titleRes));
}
@Override
public MenuItem add(int groupId, int itemId, int order, CharSequence title) {
return addInternal(mNativeMenu.add(groupId, itemId, order, title));
}
@Override
public MenuItem add(int groupId, int itemId, int order, int titleRes) {
return addInternal(mNativeMenu.add(groupId, itemId, order, titleRes));
}
private SubMenu addInternal(android.view.SubMenu nativeSubMenu) {
SubMenu subMenu = new SubMenuWrapper(nativeSubMenu);
android.view.MenuItem nativeItem = nativeSubMenu.getItem();
MenuItem item = subMenu.getItem();
mNativeMap.put(nativeItem, item);
return subMenu;
}
@Override
public SubMenu addSubMenu(CharSequence title) {
return addInternal(mNativeMenu.addSubMenu(title));
}
@Override
public SubMenu addSubMenu(int titleRes) {
return addInternal(mNativeMenu.addSubMenu(titleRes));
}
@Override
public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) {
return addInternal(mNativeMenu.addSubMenu(groupId, itemId, order, title));
}
@Override
public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) {
return addInternal(mNativeMenu.addSubMenu(groupId, itemId, order, titleRes));
}
@Override
public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) {
android.view.MenuItem[] nativeOutItems = new android.view.MenuItem[outSpecificItems.length];
int result = mNativeMenu.addIntentOptions(groupId, itemId, order, caller, specifics, intent, flags, nativeOutItems);
for (int i = 0, length = outSpecificItems.length; i < length; i++) {
outSpecificItems[i] = new MenuItemWrapper(nativeOutItems[i]);
}
return result;
}
@Override
public void removeItem(int id) {
mNativeMenu.removeItem(id);
}
@Override
public void removeGroup(int groupId) {
mNativeMenu.removeGroup(groupId);
}
@Override
public void clear() {
mNativeMap.clear();
mNativeMenu.clear();
}
@Override
public void setGroupCheckable(int group, boolean checkable, boolean exclusive) {
mNativeMenu.setGroupCheckable(group, checkable, exclusive);
}
@Override
public void setGroupVisible(int group, boolean visible) {
mNativeMenu.setGroupVisible(group, visible);
}
@Override
public void setGroupEnabled(int group, boolean enabled) {
mNativeMenu.setGroupEnabled(group, enabled);
}
@Override
public boolean hasVisibleItems() {
return mNativeMenu.hasVisibleItems();
}
@Override
public MenuItem findItem(int id) {
android.view.MenuItem nativeItem = mNativeMenu.findItem(id);
return findItem(nativeItem);
}
public MenuItem findItem(android.view.MenuItem nativeItem) {
if (nativeItem == null) {
return null;
}
MenuItem wrapped = mNativeMap.get(nativeItem);
if (wrapped != null) {
return wrapped;
}
return addInternal(nativeItem);
}
@Override
public int size() {
return mNativeMenu.size();
}
@Override
public MenuItem getItem(int index) {
android.view.MenuItem nativeItem = mNativeMenu.getItem(index);
return findItem(nativeItem);
}
@Override
public void close() {
mNativeMenu.close();
}
@Override
public boolean performShortcut(int keyCode, KeyEvent event, int flags) {
return mNativeMenu.performShortcut(keyCode, event, flags);
}
@Override
public boolean isShortcutKey(int keyCode, KeyEvent event) {
return mNativeMenu.isShortcutKey(keyCode, event);
}
@Override
public boolean performIdentifierAction(int id, int flags) {
return mNativeMenu.performIdentifierAction(id, flags);
}
@Override
public void setQwertyMode(boolean isQwerty) {
mNativeMenu.setQwertyMode(isQwerty);
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/internal/view/menu/MenuWrapper.java | Java | asf20 | 5,283 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.internal.view.menu;
import java.util.HashSet;
import java.util.Set;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.actionbarsherlock.R;
import com.actionbarsherlock.internal.view.View_HasStateListenerSupport;
import com.actionbarsherlock.internal.view.View_OnAttachStateChangeListener;
import com.actionbarsherlock.internal.widget.CapitalizingButton;
import static com.actionbarsherlock.internal.ResourcesCompat.getResources_getBoolean;
/**
* @hide
*/
public class ActionMenuItemView extends LinearLayout
implements MenuView.ItemView, View.OnClickListener, View.OnLongClickListener,
ActionMenuView.ActionMenuChildView, View_HasStateListenerSupport {
//UNUSED private static final String TAG = "ActionMenuItemView";
private MenuItemImpl mItemData;
private CharSequence mTitle;
private MenuBuilder.ItemInvoker mItemInvoker;
private ImageButton mImageButton;
private CapitalizingButton mTextButton;
private boolean mAllowTextWithIcon;
private boolean mExpandedFormat;
private int mMinWidth;
private final Set<View_OnAttachStateChangeListener> mListeners = new HashSet<View_OnAttachStateChangeListener>();
public ActionMenuItemView(Context context) {
this(context, null);
}
public ActionMenuItemView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ActionMenuItemView(Context context, AttributeSet attrs, int defStyle) {
//TODO super(context, attrs, defStyle);
super(context, attrs);
mAllowTextWithIcon = getResources_getBoolean(context,
R.bool.abs__config_allowActionMenuItemTextWithIcon);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.SherlockActionMenuItemView, 0, 0);
mMinWidth = a.getDimensionPixelSize(
R.styleable.SherlockActionMenuItemView_android_minWidth, 0);
a.recycle();
}
@Override
public void addOnAttachStateChangeListener(View_OnAttachStateChangeListener listener) {
mListeners.add(listener);
}
@Override
public void removeOnAttachStateChangeListener(View_OnAttachStateChangeListener listener) {
mListeners.remove(listener);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
for (View_OnAttachStateChangeListener listener : mListeners) {
listener.onViewAttachedToWindow(this);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
for (View_OnAttachStateChangeListener listener : mListeners) {
listener.onViewDetachedFromWindow(this);
}
}
@Override
public void onFinishInflate() {
mImageButton = (ImageButton) findViewById(R.id.abs__imageButton);
mTextButton = (CapitalizingButton) findViewById(R.id.abs__textButton);
mImageButton.setOnClickListener(this);
mTextButton.setOnClickListener(this);
mImageButton.setOnLongClickListener(this);
setOnClickListener(this);
setOnLongClickListener(this);
}
public MenuItemImpl getItemData() {
return mItemData;
}
public void initialize(MenuItemImpl itemData, int menuType) {
mItemData = itemData;
setIcon(itemData.getIcon());
setTitle(itemData.getTitleForItemView(this)); // Title only takes effect if there is no icon
setId(itemData.getItemId());
setVisibility(itemData.isVisible() ? View.VISIBLE : View.GONE);
setEnabled(itemData.isEnabled());
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
mImageButton.setEnabled(enabled);
mTextButton.setEnabled(enabled);
}
public void onClick(View v) {
if (mItemInvoker != null) {
mItemInvoker.invokeItem(mItemData);
}
}
public void setItemInvoker(MenuBuilder.ItemInvoker invoker) {
mItemInvoker = invoker;
}
public boolean prefersCondensedTitle() {
return true;
}
public void setCheckable(boolean checkable) {
// TODO Support checkable action items
}
public void setChecked(boolean checked) {
// TODO Support checkable action items
}
public void setExpandedFormat(boolean expandedFormat) {
if (mExpandedFormat != expandedFormat) {
mExpandedFormat = expandedFormat;
if (mItemData != null) {
mItemData.actionFormatChanged();
}
}
}
private void updateTextButtonVisibility() {
boolean visible = !TextUtils.isEmpty(mTextButton.getText());
visible &= mImageButton.getDrawable() == null ||
(mItemData.showsTextAsAction() && (mAllowTextWithIcon || mExpandedFormat));
mTextButton.setVisibility(visible ? VISIBLE : GONE);
}
public void setIcon(Drawable icon) {
mImageButton.setImageDrawable(icon);
if (icon != null) {
mImageButton.setVisibility(VISIBLE);
} else {
mImageButton.setVisibility(GONE);
}
updateTextButtonVisibility();
}
public boolean hasText() {
return mTextButton.getVisibility() != GONE;
}
public void setShortcut(boolean showShortcut, char shortcutKey) {
// Action buttons don't show text for shortcut keys.
}
public void setTitle(CharSequence title) {
mTitle = title;
mTextButton.setTextCompat(mTitle);
setContentDescription(mTitle);
updateTextButtonVisibility();
}
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
onPopulateAccessibilityEvent(event);
return true;
}
@Override
public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
super.onPopulateAccessibilityEvent(event);
}
final CharSequence cdesc = getContentDescription();
if (!TextUtils.isEmpty(cdesc)) {
event.getText().add(cdesc);
}
}
@Override
public boolean dispatchHoverEvent(MotionEvent event) {
// Don't allow children to hover; we want this to be treated as a single component.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return onHoverEvent(event);
}
return false;
}
public boolean showsIcon() {
return true;
}
public boolean needsDividerBefore() {
return hasText() && mItemData.getIcon() == null;
}
public boolean needsDividerAfter() {
return hasText();
}
@Override
public boolean onLongClick(View v) {
if (hasText()) {
// Don't show the cheat sheet for items that already show text.
return false;
}
final int[] screenPos = new int[2];
final Rect displayFrame = new Rect();
getLocationOnScreen(screenPos);
getWindowVisibleDisplayFrame(displayFrame);
final Context context = getContext();
final int width = getWidth();
final int height = getHeight();
final int midy = screenPos[1] + height / 2;
final int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
Toast cheatSheet = Toast.makeText(context, mItemData.getTitle(), Toast.LENGTH_SHORT);
if (midy < displayFrame.height()) {
// Show along the top; follow action buttons
cheatSheet.setGravity(Gravity.TOP | Gravity.RIGHT,
screenWidth - screenPos[0] - width / 2, height);
} else {
// Show along the bottom center
cheatSheet.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, height);
}
cheatSheet.show();
return true;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final int specSize = MeasureSpec.getSize(widthMeasureSpec);
final int oldMeasuredWidth = getMeasuredWidth();
final int targetWidth = widthMode == MeasureSpec.AT_MOST ? Math.min(specSize, mMinWidth)
: mMinWidth;
if (widthMode != MeasureSpec.EXACTLY && mMinWidth > 0 && oldMeasuredWidth < targetWidth) {
// Remeasure at exactly the minimum width.
super.onMeasure(MeasureSpec.makeMeasureSpec(targetWidth, MeasureSpec.EXACTLY),
heightMeasureSpec);
}
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/internal/view/menu/ActionMenuItemView.java | Java | asf20 | 9,784 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.internal.view.menu;
import java.util.ArrayList;
import java.util.List;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.view.KeyEvent;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
/**
* @hide
*/
public class ActionMenu implements Menu {
private Context mContext;
private boolean mIsQwerty;
private ArrayList<ActionMenuItem> mItems;
public ActionMenu(Context context) {
mContext = context;
mItems = new ArrayList<ActionMenuItem>();
}
public Context getContext() {
return mContext;
}
public MenuItem add(CharSequence title) {
return add(0, 0, 0, title);
}
public MenuItem add(int titleRes) {
return add(0, 0, 0, titleRes);
}
public MenuItem add(int groupId, int itemId, int order, int titleRes) {
return add(groupId, itemId, order, mContext.getResources().getString(titleRes));
}
public MenuItem add(int groupId, int itemId, int order, CharSequence title) {
ActionMenuItem item = new ActionMenuItem(getContext(),
groupId, itemId, 0, order, title);
mItems.add(order, item);
return item;
}
public int addIntentOptions(int groupId, int itemId, int order,
ComponentName caller, Intent[] specifics, Intent intent, int flags,
MenuItem[] outSpecificItems) {
PackageManager pm = mContext.getPackageManager();
final List<ResolveInfo> lri =
pm.queryIntentActivityOptions(caller, specifics, intent, 0);
final int N = lri != null ? lri.size() : 0;
if ((flags & FLAG_APPEND_TO_GROUP) == 0) {
removeGroup(groupId);
}
for (int i=0; i<N; i++) {
final ResolveInfo ri = lri.get(i);
Intent rintent = new Intent(
ri.specificIndex < 0 ? intent : specifics[ri.specificIndex]);
rintent.setComponent(new ComponentName(
ri.activityInfo.applicationInfo.packageName,
ri.activityInfo.name));
final MenuItem item = add(groupId, itemId, order, ri.loadLabel(pm))
.setIcon(ri.loadIcon(pm))
.setIntent(rintent);
if (outSpecificItems != null && ri.specificIndex >= 0) {
outSpecificItems[ri.specificIndex] = item;
}
}
return N;
}
public SubMenu addSubMenu(CharSequence title) {
// TODO Implement submenus
return null;
}
public SubMenu addSubMenu(int titleRes) {
// TODO Implement submenus
return null;
}
public SubMenu addSubMenu(int groupId, int itemId, int order,
CharSequence title) {
// TODO Implement submenus
return null;
}
public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) {
// TODO Implement submenus
return null;
}
public void clear() {
mItems.clear();
}
public void close() {
}
private int findItemIndex(int id) {
final ArrayList<ActionMenuItem> items = mItems;
final int itemCount = items.size();
for (int i = 0; i < itemCount; i++) {
if (items.get(i).getItemId() == id) {
return i;
}
}
return -1;
}
public MenuItem findItem(int id) {
return mItems.get(findItemIndex(id));
}
public MenuItem getItem(int index) {
return mItems.get(index);
}
public boolean hasVisibleItems() {
final ArrayList<ActionMenuItem> items = mItems;
final int itemCount = items.size();
for (int i = 0; i < itemCount; i++) {
if (items.get(i).isVisible()) {
return true;
}
}
return false;
}
private ActionMenuItem findItemWithShortcut(int keyCode, KeyEvent event) {
// TODO Make this smarter.
final boolean qwerty = mIsQwerty;
final ArrayList<ActionMenuItem> items = mItems;
final int itemCount = items.size();
for (int i = 0; i < itemCount; i++) {
ActionMenuItem item = items.get(i);
final char shortcut = qwerty ? item.getAlphabeticShortcut() :
item.getNumericShortcut();
if (keyCode == shortcut) {
return item;
}
}
return null;
}
public boolean isShortcutKey(int keyCode, KeyEvent event) {
return findItemWithShortcut(keyCode, event) != null;
}
public boolean performIdentifierAction(int id, int flags) {
final int index = findItemIndex(id);
if (index < 0) {
return false;
}
return mItems.get(index).invoke();
}
public boolean performShortcut(int keyCode, KeyEvent event, int flags) {
ActionMenuItem item = findItemWithShortcut(keyCode, event);
if (item == null) {
return false;
}
return item.invoke();
}
public void removeGroup(int groupId) {
final ArrayList<ActionMenuItem> items = mItems;
int itemCount = items.size();
int i = 0;
while (i < itemCount) {
if (items.get(i).getGroupId() == groupId) {
items.remove(i);
itemCount--;
} else {
i++;
}
}
}
public void removeItem(int id) {
mItems.remove(findItemIndex(id));
}
public void setGroupCheckable(int group, boolean checkable,
boolean exclusive) {
final ArrayList<ActionMenuItem> items = mItems;
final int itemCount = items.size();
for (int i = 0; i < itemCount; i++) {
ActionMenuItem item = items.get(i);
if (item.getGroupId() == group) {
item.setCheckable(checkable);
item.setExclusiveCheckable(exclusive);
}
}
}
public void setGroupEnabled(int group, boolean enabled) {
final ArrayList<ActionMenuItem> items = mItems;
final int itemCount = items.size();
for (int i = 0; i < itemCount; i++) {
ActionMenuItem item = items.get(i);
if (item.getGroupId() == group) {
item.setEnabled(enabled);
}
}
}
public void setGroupVisible(int group, boolean visible) {
final ArrayList<ActionMenuItem> items = mItems;
final int itemCount = items.size();
for (int i = 0; i < itemCount; i++) {
ActionMenuItem item = items.get(i);
if (item.getGroupId() == group) {
item.setVisible(visible);
}
}
}
public void setQwertyMode(boolean isQwerty) {
mIsQwerty = isQwerty;
}
public int size() {
return mItems.size();
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/internal/view/menu/ActionMenu.java | Java | asf20 | 7,699 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.internal.view.menu;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.os.Build;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.widget.LinearLayout;
import com.actionbarsherlock.internal.widget.IcsLinearLayout;
/**
* @hide
*/
public class ActionMenuView extends IcsLinearLayout implements MenuBuilder.ItemInvoker, MenuView {
//UNUSED private static final String TAG = "ActionMenuView";
private static final boolean IS_FROYO = Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
static final int MIN_CELL_SIZE = 56; // dips
static final int GENERATED_ITEM_PADDING = 4; // dips
private MenuBuilder mMenu;
private boolean mReserveOverflow;
private ActionMenuPresenter mPresenter;
private boolean mFormatItems;
private int mFormatItemsWidth;
private int mMinCellSize;
private int mGeneratedItemPadding;
//UNUSED private int mMeasuredExtraWidth;
private boolean mFirst = true;
public ActionMenuView(Context context) {
this(context, null);
}
public ActionMenuView(Context context, AttributeSet attrs) {
super(context, attrs);
setBaselineAligned(false);
final float density = context.getResources().getDisplayMetrics().density;
mMinCellSize = (int) (MIN_CELL_SIZE * density);
mGeneratedItemPadding = (int) (GENERATED_ITEM_PADDING * density);
}
public void setPresenter(ActionMenuPresenter presenter) {
mPresenter = presenter;
}
public boolean isExpandedFormat() {
return mFormatItems;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
if (IS_FROYO) {
super.onConfigurationChanged(newConfig);
}
mPresenter.updateMenuView(false);
if (mPresenter != null && mPresenter.isOverflowMenuShowing()) {
mPresenter.hideOverflowMenu();
mPresenter.showOverflowMenu();
}
}
@Override
protected void onDraw(Canvas canvas) {
//Need to trigger a relayout since we may have been added extremely
//late in the initial rendering (e.g., when contained in a ViewPager).
//See: https://github.com/JakeWharton/ActionBarSherlock/issues/272
if (!IS_FROYO && mFirst) {
mFirst = false;
requestLayout();
return;
}
super.onDraw(canvas);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// If we've been given an exact size to match, apply special formatting during layout.
final boolean wasFormatted = mFormatItems;
mFormatItems = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY;
if (wasFormatted != mFormatItems) {
mFormatItemsWidth = 0; // Reset this when switching modes
}
// Special formatting can change whether items can fit as action buttons.
// Kick the menu and update presenters when this changes.
final int widthSize = MeasureSpec.getMode(widthMeasureSpec);
if (mFormatItems && mMenu != null && widthSize != mFormatItemsWidth) {
mFormatItemsWidth = widthSize;
mMenu.onItemsChanged(true);
}
if (mFormatItems) {
onMeasureExactFormat(widthMeasureSpec, heightMeasureSpec);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
private void onMeasureExactFormat(int widthMeasureSpec, int heightMeasureSpec) {
// We already know the width mode is EXACTLY if we're here.
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
final int widthPadding = getPaddingLeft() + getPaddingRight();
final int heightPadding = getPaddingTop() + getPaddingBottom();
widthSize -= widthPadding;
// Divide the view into cells.
final int cellCount = widthSize / mMinCellSize;
final int cellSizeRemaining = widthSize % mMinCellSize;
if (cellCount == 0) {
// Give up, nothing fits.
setMeasuredDimension(widthSize, 0);
return;
}
final int cellSize = mMinCellSize + cellSizeRemaining / cellCount;
int cellsRemaining = cellCount;
int maxChildHeight = 0;
int maxCellsUsed = 0;
int expandableItemCount = 0;
int visibleItemCount = 0;
boolean hasOverflow = false;
// This is used as a bitfield to locate the smallest items present. Assumes childCount < 64.
long smallestItemsAt = 0;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) continue;
final boolean isGeneratedItem = child instanceof ActionMenuItemView;
visibleItemCount++;
if (isGeneratedItem) {
// Reset padding for generated menu item views; it may change below
// and views are recycled.
child.setPadding(mGeneratedItemPadding, 0, mGeneratedItemPadding, 0);
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
lp.expanded = false;
lp.extraPixels = 0;
lp.cellsUsed = 0;
lp.expandable = false;
lp.leftMargin = 0;
lp.rightMargin = 0;
lp.preventEdgeOffset = isGeneratedItem && ((ActionMenuItemView) child).hasText();
// Overflow always gets 1 cell. No more, no less.
final int cellsAvailable = lp.isOverflowButton ? 1 : cellsRemaining;
final int cellsUsed = measureChildForCells(child, cellSize, cellsAvailable,
heightMeasureSpec, heightPadding);
maxCellsUsed = Math.max(maxCellsUsed, cellsUsed);
if (lp.expandable) expandableItemCount++;
if (lp.isOverflowButton) hasOverflow = true;
cellsRemaining -= cellsUsed;
maxChildHeight = Math.max(maxChildHeight, child.getMeasuredHeight());
if (cellsUsed == 1) smallestItemsAt |= (1 << i);
}
// When we have overflow and a single expanded (text) item, we want to try centering it
// visually in the available space even though overflow consumes some of it.
final boolean centerSingleExpandedItem = hasOverflow && visibleItemCount == 2;
// Divide space for remaining cells if we have items that can expand.
// Try distributing whole leftover cells to smaller items first.
boolean needsExpansion = false;
while (expandableItemCount > 0 && cellsRemaining > 0) {
int minCells = Integer.MAX_VALUE;
long minCellsAt = 0; // Bit locations are indices of relevant child views
int minCellsItemCount = 0;
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
// Don't try to expand items that shouldn't.
if (!lp.expandable) continue;
// Mark indices of children that can receive an extra cell.
if (lp.cellsUsed < minCells) {
minCells = lp.cellsUsed;
minCellsAt = 1 << i;
minCellsItemCount = 1;
} else if (lp.cellsUsed == minCells) {
minCellsAt |= 1 << i;
minCellsItemCount++;
}
}
// Items that get expanded will always be in the set of smallest items when we're done.
smallestItemsAt |= minCellsAt;
if (minCellsItemCount > cellsRemaining) break; // Couldn't expand anything evenly. Stop.
// We have enough cells, all minimum size items will be incremented.
minCells++;
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if ((minCellsAt & (1 << i)) == 0) {
// If this item is already at our small item count, mark it for later.
if (lp.cellsUsed == minCells) smallestItemsAt |= 1 << i;
continue;
}
if (centerSingleExpandedItem && lp.preventEdgeOffset && cellsRemaining == 1) {
// Add padding to this item such that it centers.
child.setPadding(mGeneratedItemPadding + cellSize, 0, mGeneratedItemPadding, 0);
}
lp.cellsUsed++;
lp.expanded = true;
cellsRemaining--;
}
needsExpansion = true;
}
// Divide any space left that wouldn't divide along cell boundaries
// evenly among the smallest items
final boolean singleItem = !hasOverflow && visibleItemCount == 1;
if (cellsRemaining > 0 && smallestItemsAt != 0 &&
(cellsRemaining < visibleItemCount - 1 || singleItem || maxCellsUsed > 1)) {
float expandCount = Long.bitCount(smallestItemsAt);
if (!singleItem) {
// The items at the far edges may only expand by half in order to pin to either side.
if ((smallestItemsAt & 1) != 0) {
LayoutParams lp = (LayoutParams) getChildAt(0).getLayoutParams();
if (!lp.preventEdgeOffset) expandCount -= 0.5f;
}
if ((smallestItemsAt & (1 << (childCount - 1))) != 0) {
LayoutParams lp = ((LayoutParams) getChildAt(childCount - 1).getLayoutParams());
if (!lp.preventEdgeOffset) expandCount -= 0.5f;
}
}
final int extraPixels = expandCount > 0 ?
(int) (cellsRemaining * cellSize / expandCount) : 0;
for (int i = 0; i < childCount; i++) {
if ((smallestItemsAt & (1 << i)) == 0) continue;
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (child instanceof ActionMenuItemView) {
// If this is one of our views, expand and measure at the larger size.
lp.extraPixels = extraPixels;
lp.expanded = true;
if (i == 0 && !lp.preventEdgeOffset) {
// First item gets part of its new padding pushed out of sight.
// The last item will get this implicitly from layout.
lp.leftMargin = -extraPixels / 2;
}
needsExpansion = true;
} else if (lp.isOverflowButton) {
lp.extraPixels = extraPixels;
lp.expanded = true;
lp.rightMargin = -extraPixels / 2;
needsExpansion = true;
} else {
// If we don't know what it is, give it some margins instead
// and let it center within its space. We still want to pin
// against the edges.
if (i != 0) {
lp.leftMargin = extraPixels / 2;
}
if (i != childCount - 1) {
lp.rightMargin = extraPixels / 2;
}
}
}
cellsRemaining = 0;
}
// Remeasure any items that have had extra space allocated to them.
if (needsExpansion) {
int heightSpec = MeasureSpec.makeMeasureSpec(heightSize - heightPadding, heightMode);
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (!lp.expanded) continue;
final int width = lp.cellsUsed * cellSize + lp.extraPixels;
child.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), heightSpec);
}
}
if (heightMode != MeasureSpec.EXACTLY) {
heightSize = maxChildHeight;
}
setMeasuredDimension(widthSize, heightSize);
//UNUSED mMeasuredExtraWidth = cellsRemaining * cellSize;
}
/**
* Measure a child view to fit within cell-based formatting. The child's width
* will be measured to a whole multiple of cellSize.
*
* <p>Sets the expandable and cellsUsed fields of LayoutParams.
*
* @param child Child to measure
* @param cellSize Size of one cell
* @param cellsRemaining Number of cells remaining that this view can expand to fill
* @param parentHeightMeasureSpec MeasureSpec used by the parent view
* @param parentHeightPadding Padding present in the parent view
* @return Number of cells this child was measured to occupy
*/
static int measureChildForCells(View child, int cellSize, int cellsRemaining,
int parentHeightMeasureSpec, int parentHeightPadding) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int childHeightSize = MeasureSpec.getSize(parentHeightMeasureSpec) -
parentHeightPadding;
final int childHeightMode = MeasureSpec.getMode(parentHeightMeasureSpec);
final int childHeightSpec = MeasureSpec.makeMeasureSpec(childHeightSize, childHeightMode);
int cellsUsed = 0;
if (cellsRemaining > 0) {
final int childWidthSpec = MeasureSpec.makeMeasureSpec(
cellSize * cellsRemaining, MeasureSpec.AT_MOST);
child.measure(childWidthSpec, childHeightSpec);
final int measuredWidth = child.getMeasuredWidth();
cellsUsed = measuredWidth / cellSize;
if (measuredWidth % cellSize != 0) cellsUsed++;
}
final ActionMenuItemView itemView = child instanceof ActionMenuItemView ?
(ActionMenuItemView) child : null;
final boolean expandable = !lp.isOverflowButton && itemView != null && itemView.hasText();
lp.expandable = expandable;
lp.cellsUsed = cellsUsed;
final int targetWidth = cellsUsed * cellSize;
child.measure(MeasureSpec.makeMeasureSpec(targetWidth, MeasureSpec.EXACTLY),
childHeightSpec);
return cellsUsed;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
if (!mFormatItems) {
super.onLayout(changed, left, top, right, bottom);
return;
}
final int childCount = getChildCount();
final int midVertical = (top + bottom) / 2;
final int dividerWidth = 0;//getDividerWidth();
int overflowWidth = 0;
//UNUSED int nonOverflowWidth = 0;
int nonOverflowCount = 0;
int widthRemaining = right - left - getPaddingRight() - getPaddingLeft();
boolean hasOverflow = false;
for (int i = 0; i < childCount; i++) {
final View v = getChildAt(i);
if (v.getVisibility() == GONE) {
continue;
}
LayoutParams p = (LayoutParams) v.getLayoutParams();
if (p.isOverflowButton) {
overflowWidth = v.getMeasuredWidth();
if (hasDividerBeforeChildAt(i)) {
overflowWidth += dividerWidth;
}
int height = v.getMeasuredHeight();
int r = getWidth() - getPaddingRight() - p.rightMargin;
int l = r - overflowWidth;
int t = midVertical - (height / 2);
int b = t + height;
v.layout(l, t, r, b);
widthRemaining -= overflowWidth;
hasOverflow = true;
} else {
final int size = v.getMeasuredWidth() + p.leftMargin + p.rightMargin;
//UNUSED nonOverflowWidth += size;
widthRemaining -= size;
//if (hasDividerBeforeChildAt(i)) {
//UNUSED nonOverflowWidth += dividerWidth;
//}
nonOverflowCount++;
}
}
if (childCount == 1 && !hasOverflow) {
// Center a single child
final View v = getChildAt(0);
final int width = v.getMeasuredWidth();
final int height = v.getMeasuredHeight();
final int midHorizontal = (right - left) / 2;
final int l = midHorizontal - width / 2;
final int t = midVertical - height / 2;
v.layout(l, t, l + width, t + height);
return;
}
final int spacerCount = nonOverflowCount - (hasOverflow ? 0 : 1);
final int spacerSize = Math.max(0, spacerCount > 0 ? widthRemaining / spacerCount : 0);
int startLeft = getPaddingLeft();
for (int i = 0; i < childCount; i++) {
final View v = getChildAt(i);
final LayoutParams lp = (LayoutParams) v.getLayoutParams();
if (v.getVisibility() == GONE || lp.isOverflowButton) {
continue;
}
startLeft += lp.leftMargin;
int width = v.getMeasuredWidth();
int height = v.getMeasuredHeight();
int t = midVertical - height / 2;
v.layout(startLeft, t, startLeft + width, t + height);
startLeft += width + lp.rightMargin + spacerSize;
}
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
mPresenter.dismissPopupMenus();
}
public boolean isOverflowReserved() {
return mReserveOverflow;
}
public void setOverflowReserved(boolean reserveOverflow) {
mReserveOverflow = reserveOverflow;
}
@Override
protected LayoutParams generateDefaultLayoutParams() {
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER_VERTICAL;
return params;
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
@Override
protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
if (p instanceof LayoutParams) {
LayoutParams result = new LayoutParams((LayoutParams) p);
if (result.gravity <= Gravity.NO_GRAVITY) {
result.gravity = Gravity.CENTER_VERTICAL;
}
return result;
}
return generateDefaultLayoutParams();
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p != null && p instanceof LayoutParams;
}
public LayoutParams generateOverflowButtonLayoutParams() {
LayoutParams result = generateDefaultLayoutParams();
result.isOverflowButton = true;
return result;
}
public boolean invokeItem(MenuItemImpl item) {
return mMenu.performItemAction(item, 0);
}
public int getWindowAnimations() {
return 0;
}
public void initialize(MenuBuilder menu) {
mMenu = menu;
}
//@Override
protected boolean hasDividerBeforeChildAt(int childIndex) {
final View childBefore = getChildAt(childIndex - 1);
final View child = getChildAt(childIndex);
boolean result = false;
if (childIndex < getChildCount() && childBefore instanceof ActionMenuChildView) {
result |= ((ActionMenuChildView) childBefore).needsDividerAfter();
}
if (childIndex > 0 && child instanceof ActionMenuChildView) {
result |= ((ActionMenuChildView) child).needsDividerBefore();
}
return result;
}
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
return false;
}
public interface ActionMenuChildView {
public boolean needsDividerBefore();
public boolean needsDividerAfter();
}
public static class LayoutParams extends LinearLayout.LayoutParams {
public boolean isOverflowButton;
public int cellsUsed;
public int extraPixels;
public boolean expandable;
public boolean preventEdgeOffset;
public boolean expanded;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
public LayoutParams(LayoutParams other) {
super((LinearLayout.LayoutParams) other);
isOverflowButton = other.isOverflowButton;
}
public LayoutParams(int width, int height) {
super(width, height);
isOverflowButton = false;
}
public LayoutParams(int width, int height, boolean isOverflowButton) {
super(width, height);
this.isOverflowButton = isOverflowButton;
}
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/internal/view/menu/ActionMenuView.java | Java | asf20 | 22,112 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.internal.view.menu;
import android.content.Context;
import android.os.Parcelable;
import android.view.ViewGroup;
/**
* A MenuPresenter is responsible for building views for a Menu object.
* It takes over some responsibility from the old style monolithic MenuBuilder class.
*/
public interface MenuPresenter {
/**
* Called by menu implementation to notify another component of open/close events.
*/
public interface Callback {
/**
* Called when a menu is closing.
* @param menu
* @param allMenusAreClosing
*/
public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing);
/**
* Called when a submenu opens. Useful for notifying the application
* of menu state so that it does not attempt to hide the action bar
* while a submenu is open or similar.
*
* @param subMenu Submenu currently being opened
* @return true if the Callback will handle presenting the submenu, false if
* the presenter should attempt to do so.
*/
public boolean onOpenSubMenu(MenuBuilder subMenu);
}
/**
* Initialize this presenter for the given context and menu.
* This method is called by MenuBuilder when a presenter is
* added. See {@link MenuBuilder#addMenuPresenter(MenuPresenter)}
*
* @param context Context for this presenter; used for view creation and resource management
* @param menu Menu to host
*/
public void initForMenu(Context context, MenuBuilder menu);
/**
* Retrieve a MenuView to display the menu specified in
* {@link #initForMenu(Context, Menu)}.
*
* @param root Intended parent of the MenuView.
* @return A freshly created MenuView.
*/
public MenuView getMenuView(ViewGroup root);
/**
* Update the menu UI in response to a change. Called by
* MenuBuilder during the normal course of operation.
*
* @param cleared true if the menu was entirely cleared
*/
public void updateMenuView(boolean cleared);
/**
* Set a callback object that will be notified of menu events
* related to this specific presentation.
* @param cb Callback that will be notified of future events
*/
public void setCallback(Callback cb);
/**
* Called by Menu implementations to indicate that a submenu item
* has been selected. An active Callback should be notified, and
* if applicable the presenter should present the submenu.
*
* @param subMenu SubMenu being opened
* @return true if the the event was handled, false otherwise.
*/
public boolean onSubMenuSelected(SubMenuBuilder subMenu);
/**
* Called by Menu implementations to indicate that a menu or submenu is
* closing. Presenter implementations should close the representation
* of the menu indicated as necessary and notify a registered callback.
*
* @param menu Menu or submenu that is closing.
* @param allMenusAreClosing True if all associated menus are closing.
*/
public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing);
/**
* Called by Menu implementations to flag items that will be shown as actions.
* @return true if this presenter changed the action status of any items.
*/
public boolean flagActionItems();
/**
* Called when a menu item with a collapsable action view should expand its action view.
*
* @param menu Menu containing the item to be expanded
* @param item Item to be expanded
* @return true if this presenter expanded the action view, false otherwise.
*/
public boolean expandItemActionView(MenuBuilder menu, MenuItemImpl item);
/**
* Called when a menu item with a collapsable action view should collapse its action view.
*
* @param menu Menu containing the item to be collapsed
* @param item Item to be collapsed
* @return true if this presenter collapsed the action view, false otherwise.
*/
public boolean collapseItemActionView(MenuBuilder menu, MenuItemImpl item);
/**
* Returns an ID for determining how to save/restore instance state.
* @return a valid ID value.
*/
public int getId();
/**
* Returns a Parcelable describing the current state of the presenter.
* It will be passed to the {@link #onRestoreInstanceState(Parcelable)}
* method of the presenter sharing the same ID later.
* @return The saved instance state
*/
public Parcelable onSaveInstanceState();
/**
* Supplies the previously saved instance state to be restored.
* @param state The previously saved instance state
*/
public void onRestoreInstanceState(Parcelable state);
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/internal/view/menu/MenuPresenter.java | Java | asf20 | 5,462 |
package com.actionbarsherlock.internal.view;
public interface View_HasStateListenerSupport {
void addOnAttachStateChangeListener(View_OnAttachStateChangeListener listener);
void removeOnAttachStateChangeListener(View_OnAttachStateChangeListener listener);
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/internal/view/View_HasStateListenerSupport.java | Java | asf20 | 267 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.internal.view;
import android.content.Context;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import java.lang.ref.WeakReference;
import com.actionbarsherlock.internal.view.menu.MenuBuilder;
import com.actionbarsherlock.internal.view.menu.MenuPopupHelper;
import com.actionbarsherlock.internal.view.menu.SubMenuBuilder;
import com.actionbarsherlock.internal.widget.ActionBarContextView;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public class StandaloneActionMode extends ActionMode implements MenuBuilder.Callback {
private Context mContext;
private ActionBarContextView mContextView;
private ActionMode.Callback mCallback;
private WeakReference<View> mCustomView;
private boolean mFinished;
private boolean mFocusable;
private MenuBuilder mMenu;
public StandaloneActionMode(Context context, ActionBarContextView view,
ActionMode.Callback callback, boolean isFocusable) {
mContext = context;
mContextView = view;
mCallback = callback;
mMenu = new MenuBuilder(context).setDefaultShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
mMenu.setCallback(this);
mFocusable = isFocusable;
}
@Override
public void setTitle(CharSequence title) {
mContextView.setTitle(title);
}
@Override
public void setSubtitle(CharSequence subtitle) {
mContextView.setSubtitle(subtitle);
}
@Override
public void setTitle(int resId) {
setTitle(mContext.getString(resId));
}
@Override
public void setSubtitle(int resId) {
setSubtitle(mContext.getString(resId));
}
@Override
public void setCustomView(View view) {
mContextView.setCustomView(view);
mCustomView = view != null ? new WeakReference<View>(view) : null;
}
@Override
public void invalidate() {
mCallback.onPrepareActionMode(this, mMenu);
}
@Override
public void finish() {
if (mFinished) {
return;
}
mFinished = true;
mContextView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
mCallback.onDestroyActionMode(this);
}
@Override
public Menu getMenu() {
return mMenu;
}
@Override
public CharSequence getTitle() {
return mContextView.getTitle();
}
@Override
public CharSequence getSubtitle() {
return mContextView.getSubtitle();
}
@Override
public View getCustomView() {
return mCustomView != null ? mCustomView.get() : null;
}
@Override
public MenuInflater getMenuInflater() {
return new MenuInflater(mContext);
}
public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
return mCallback.onActionItemClicked(this, item);
}
public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
}
public boolean onSubMenuSelected(SubMenuBuilder subMenu) {
if (!subMenu.hasVisibleItems()) {
return true;
}
new MenuPopupHelper(mContext, subMenu).show();
return true;
}
public void onCloseSubMenu(SubMenuBuilder menu) {
}
public void onMenuModeChange(MenuBuilder menu) {
invalidate();
mContextView.showOverflowMenu();
}
public boolean isUiFocusable() {
return mFocusable;
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/internal/view/StandaloneActionMode.java | Java | asf20 | 4,190 |
package com.actionbarsherlock.internal.view;
import com.actionbarsherlock.internal.view.menu.SubMenuWrapper;
import com.actionbarsherlock.view.ActionProvider;
import android.view.View;
public class ActionProviderWrapper extends android.view.ActionProvider {
private final ActionProvider mProvider;
public ActionProviderWrapper(ActionProvider provider) {
super(null/*TODO*/); //XXX this *should* be unused
mProvider = provider;
}
public ActionProvider unwrap() {
return mProvider;
}
@Override
public View onCreateActionView() {
return mProvider.onCreateActionView();
}
@Override
public boolean hasSubMenu() {
return mProvider.hasSubMenu();
}
@Override
public boolean onPerformDefaultAction() {
return mProvider.onPerformDefaultAction();
}
@Override
public void onPrepareSubMenu(android.view.SubMenu subMenu) {
mProvider.onPrepareSubMenu(new SubMenuWrapper(subMenu));
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/internal/view/ActionProviderWrapper.java | Java | asf20 | 1,004 |
package com.actionbarsherlock.internal;
import com.actionbarsherlock.ActionBarSherlock;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.internal.app.ActionBarWrapper;
import com.actionbarsherlock.internal.view.menu.MenuWrapper;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.MenuInflater;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
@ActionBarSherlock.Implementation(api = 14)
public class ActionBarSherlockNative extends ActionBarSherlock {
private ActionBarWrapper mActionBar;
private ActionModeWrapper mActionMode;
private MenuWrapper mMenu;
public ActionBarSherlockNative(Activity activity, int flags) {
super(activity, flags);
}
@Override
public ActionBar getActionBar() {
if (DEBUG) Log.d(TAG, "[getActionBar]");
initActionBar();
return mActionBar;
}
private void initActionBar() {
if (mActionBar != null || mActivity.getActionBar() == null) {
return;
}
mActionBar = new ActionBarWrapper(mActivity);
}
@Override
public void dispatchInvalidateOptionsMenu() {
if (DEBUG) Log.d(TAG, "[dispatchInvalidateOptionsMenu]");
mActivity.getWindow().invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
}
@Override
public boolean dispatchCreateOptionsMenu(android.view.Menu menu) {
if (DEBUG) Log.d(TAG, "[dispatchCreateOptionsMenu] menu: " + menu);
if (mMenu == null || menu != mMenu.unwrap()) {
mMenu = new MenuWrapper(menu);
}
final boolean result = callbackCreateOptionsMenu(mMenu);
if (DEBUG) Log.d(TAG, "[dispatchCreateOptionsMenu] returning " + result);
return result;
}
@Override
public boolean dispatchPrepareOptionsMenu(android.view.Menu menu) {
if (DEBUG) Log.d(TAG, "[dispatchPrepareOptionsMenu] menu: " + menu);
final boolean result = callbackPrepareOptionsMenu(mMenu);
if (DEBUG) Log.d(TAG, "[dispatchPrepareOptionsMenu] returning " + result);
return result;
}
@Override
public boolean dispatchOptionsItemSelected(android.view.MenuItem item) {
if (DEBUG) Log.d(TAG, "[dispatchOptionsItemSelected] item: " + item.getTitleCondensed());
final boolean result = callbackOptionsItemSelected(mMenu.findItem(item));
if (DEBUG) Log.d(TAG, "[dispatchOptionsItemSelected] returning " + result);
return result;
}
@Override
public boolean hasFeature(int feature) {
if (DEBUG) Log.d(TAG, "[hasFeature] feature: " + feature);
final boolean result = mActivity.getWindow().hasFeature(feature);
if (DEBUG) Log.d(TAG, "[hasFeature] returning " + result);
return result;
}
@Override
public boolean requestFeature(int featureId) {
if (DEBUG) Log.d(TAG, "[requestFeature] featureId: " + featureId);
final boolean result = mActivity.getWindow().requestFeature(featureId);
if (DEBUG) Log.d(TAG, "[requestFeature] returning " + result);
return result;
}
@Override
public void setUiOptions(int uiOptions) {
if (DEBUG) Log.d(TAG, "[setUiOptions] uiOptions: " + uiOptions);
mActivity.getWindow().setUiOptions(uiOptions);
}
@Override
public void setUiOptions(int uiOptions, int mask) {
if (DEBUG) Log.d(TAG, "[setUiOptions] uiOptions: " + uiOptions + ", mask: " + mask);
mActivity.getWindow().setUiOptions(uiOptions, mask);
}
@Override
public void setContentView(int layoutResId) {
if (DEBUG) Log.d(TAG, "[setContentView] layoutResId: " + layoutResId);
mActivity.getWindow().setContentView(layoutResId);
initActionBar();
}
@Override
public void setContentView(View view, LayoutParams params) {
if (DEBUG) Log.d(TAG, "[setContentView] view: " + view + ", params: " + params);
mActivity.getWindow().setContentView(view, params);
initActionBar();
}
@Override
public void addContentView(View view, LayoutParams params) {
if (DEBUG) Log.d(TAG, "[addContentView] view: " + view + ", params: " + params);
mActivity.getWindow().addContentView(view, params);
initActionBar();
}
@Override
public void setTitle(CharSequence title) {
if (DEBUG) Log.d(TAG, "[setTitle] title: " + title);
mActivity.getWindow().setTitle(title);
}
@Override
public void setProgressBarVisibility(boolean visible) {
if (DEBUG) Log.d(TAG, "[setProgressBarVisibility] visible: " + visible);
mActivity.setProgressBarVisibility(visible);
}
@Override
public void setProgressBarIndeterminateVisibility(boolean visible) {
if (DEBUG) Log.d(TAG, "[setProgressBarIndeterminateVisibility] visible: " + visible);
mActivity.setProgressBarIndeterminateVisibility(visible);
}
@Override
public void setProgressBarIndeterminate(boolean indeterminate) {
if (DEBUG) Log.d(TAG, "[setProgressBarIndeterminate] indeterminate: " + indeterminate);
mActivity.setProgressBarIndeterminate(indeterminate);
}
@Override
public void setProgress(int progress) {
if (DEBUG) Log.d(TAG, "[setProgress] progress: " + progress);
mActivity.setProgress(progress);
}
@Override
public void setSecondaryProgress(int secondaryProgress) {
if (DEBUG) Log.d(TAG, "[setSecondaryProgress] secondaryProgress: " + secondaryProgress);
mActivity.setSecondaryProgress(secondaryProgress);
}
@Override
protected Context getThemedContext() {
Context context = mActivity;
TypedValue outValue = new TypedValue();
mActivity.getTheme().resolveAttribute(android.R.attr.actionBarWidgetTheme, outValue, true);
if (outValue.resourceId != 0) {
//We are unable to test if this is the same as our current theme
//so we just wrap it and hope that if the attribute was specified
//then the user is intentionally specifying an alternate theme.
context = new ContextThemeWrapper(context, outValue.resourceId);
}
return context;
}
@Override
public ActionMode startActionMode(com.actionbarsherlock.view.ActionMode.Callback callback) {
if (DEBUG) Log.d(TAG, "[startActionMode] callback: " + callback);
if (mActionMode != null) {
mActionMode.finish();
}
ActionModeCallbackWrapper wrapped = null;
if (callback != null) {
wrapped = new ActionModeCallbackWrapper(callback);
}
//Calling this will trigger the callback wrapper's onCreate which
//is where we will set the new instance to mActionMode since we need
//to pass it through to the sherlock callbacks and the call below
//will not have returned yet to store its value.
mActivity.startActionMode(wrapped);
return mActionMode;
}
private class ActionModeCallbackWrapper implements android.view.ActionMode.Callback {
private final ActionMode.Callback mCallback;
public ActionModeCallbackWrapper(ActionMode.Callback callback) {
mCallback = callback;
}
@Override
public boolean onCreateActionMode(android.view.ActionMode mode, android.view.Menu menu) {
//See ActionBarSherlockNative#startActionMode
mActionMode = new ActionModeWrapper(mode);
return mCallback.onCreateActionMode(mActionMode, mActionMode.getMenu());
}
@Override
public boolean onPrepareActionMode(android.view.ActionMode mode, android.view.Menu menu) {
return mCallback.onPrepareActionMode(mActionMode, mActionMode.getMenu());
}
@Override
public boolean onActionItemClicked(android.view.ActionMode mode, android.view.MenuItem item) {
return mCallback.onActionItemClicked(mActionMode, mActionMode.getMenu().findItem(item));
}
@Override
public void onDestroyActionMode(android.view.ActionMode mode) {
mCallback.onDestroyActionMode(mActionMode);
}
}
private class ActionModeWrapper extends ActionMode {
private final android.view.ActionMode mActionMode;
private MenuWrapper mMenu = null;
ActionModeWrapper(android.view.ActionMode actionMode) {
mActionMode = actionMode;
}
@Override
public void setTitle(CharSequence title) {
mActionMode.setTitle(title);
}
@Override
public void setTitle(int resId) {
mActionMode.setTitle(resId);
}
@Override
public void setSubtitle(CharSequence subtitle) {
mActionMode.setSubtitle(subtitle);
}
@Override
public void setSubtitle(int resId) {
mActionMode.setSubtitle(resId);
}
@Override
public void setCustomView(View view) {
mActionMode.setCustomView(view);
}
@Override
public void invalidate() {
mActionMode.invalidate();
}
@Override
public void finish() {
mActionMode.finish();
}
@Override
public MenuWrapper getMenu() {
if (mMenu == null) {
mMenu = new MenuWrapper(mActionMode.getMenu());
}
return mMenu;
}
@Override
public CharSequence getTitle() {
return mActionMode.getTitle();
}
@Override
public CharSequence getSubtitle() {
return mActionMode.getSubtitle();
}
@Override
public View getCustomView() {
return mActionMode.getCustomView();
}
@Override
public MenuInflater getMenuInflater() {
return ActionBarSherlockNative.this.getMenuInflater();
}
@Override
public void setTag(Object tag) {
mActionMode.setTag(tag);
}
@Override
public Object getTag() {
return mActionMode.getTag();
}
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/internal/ActionBarSherlockNative.java | Java | asf20 | 10,409 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.widget;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.database.DataSetObservable;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
/**
* <p>
* This class represents a data model for choosing a component for handing a
* given {@link Intent}. The model is responsible for querying the system for
* activities that can handle the given intent and order found activities
* based on historical data of previous choices. The historical data is stored
* in an application private file. If a client does not want to have persistent
* choice history the file can be omitted, thus the activities will be ordered
* based on historical usage for the current session.
* <p>
* </p>
* For each backing history file there is a singleton instance of this class. Thus,
* several clients that specify the same history file will share the same model. Note
* that if multiple clients are sharing the same model they should implement semantically
* equivalent functionality since setting the model intent will change the found
* activities and they may be inconsistent with the functionality of some of the clients.
* For example, choosing a share activity can be implemented by a single backing
* model and two different views for performing the selection. If however, one of the
* views is used for sharing but the other for importing, for example, then each
* view should be backed by a separate model.
* </p>
* <p>
* The way clients interact with this class is as follows:
* </p>
* <p>
* <pre>
* <code>
* // Get a model and set it to a couple of clients with semantically similar function.
* ActivityChooserModel dataModel =
* ActivityChooserModel.get(context, "task_specific_history_file_name.xml");
*
* ActivityChooserModelClient modelClient1 = getActivityChooserModelClient1();
* modelClient1.setActivityChooserModel(dataModel);
*
* ActivityChooserModelClient modelClient2 = getActivityChooserModelClient2();
* modelClient2.setActivityChooserModel(dataModel);
*
* // Set an intent to choose a an activity for.
* dataModel.setIntent(intent);
* <pre>
* <code>
* </p>
* <p>
* <strong>Note:</strong> This class is thread safe.
* </p>
*
* @hide
*/
class ActivityChooserModel extends DataSetObservable {
/**
* Client that utilizes an {@link ActivityChooserModel}.
*/
public interface ActivityChooserModelClient {
/**
* Sets the {@link ActivityChooserModel}.
*
* @param dataModel The model.
*/
public void setActivityChooserModel(ActivityChooserModel dataModel);
}
/**
* Defines a sorter that is responsible for sorting the activities
* based on the provided historical choices and an intent.
*/
public interface ActivitySorter {
/**
* Sorts the <code>activities</code> in descending order of relevance
* based on previous history and an intent.
*
* @param intent The {@link Intent}.
* @param activities Activities to be sorted.
* @param historicalRecords Historical records.
*/
// This cannot be done by a simple comparator since an Activity weight
// is computed from history. Note that Activity implements Comparable.
public void sort(Intent intent, List<ActivityResolveInfo> activities,
List<HistoricalRecord> historicalRecords);
}
/**
* Listener for choosing an activity.
*/
public interface OnChooseActivityListener {
/**
* Called when an activity has been chosen. The client can decide whether
* an activity can be chosen and if so the caller of
* {@link ActivityChooserModel#chooseActivity(int)} will receive and {@link Intent}
* for launching it.
* <p>
* <strong>Note:</strong> Modifying the intent is not permitted and
* any changes to the latter will be ignored.
* </p>
*
* @param host The listener's host model.
* @param intent The intent for launching the chosen activity.
* @return Whether the intent is handled and should not be delivered to clients.
*
* @see ActivityChooserModel#chooseActivity(int)
*/
public boolean onChooseActivity(ActivityChooserModel host, Intent intent);
}
/**
* Flag for selecting debug mode.
*/
private static final boolean DEBUG = false;
/**
* Tag used for logging.
*/
private static final String LOG_TAG = ActivityChooserModel.class.getSimpleName();
/**
* The root tag in the history file.
*/
private static final String TAG_HISTORICAL_RECORDS = "historical-records";
/**
* The tag for a record in the history file.
*/
private static final String TAG_HISTORICAL_RECORD = "historical-record";
/**
* Attribute for the activity.
*/
private static final String ATTRIBUTE_ACTIVITY = "activity";
/**
* Attribute for the choice time.
*/
private static final String ATTRIBUTE_TIME = "time";
/**
* Attribute for the choice weight.
*/
private static final String ATTRIBUTE_WEIGHT = "weight";
/**
* The default name of the choice history file.
*/
public static final String DEFAULT_HISTORY_FILE_NAME =
"activity_choser_model_history.xml";
/**
* The default maximal length of the choice history.
*/
public static final int DEFAULT_HISTORY_MAX_LENGTH = 50;
/**
* The amount with which to inflate a chosen activity when set as default.
*/
private static final int DEFAULT_ACTIVITY_INFLATION = 5;
/**
* Default weight for a choice record.
*/
private static final float DEFAULT_HISTORICAL_RECORD_WEIGHT = 1.0f;
/**
* The extension of the history file.
*/
private static final String HISTORY_FILE_EXTENSION = ".xml";
/**
* An invalid item index.
*/
private static final int INVALID_INDEX = -1;
/**
* Lock to guard the model registry.
*/
private static final Object sRegistryLock = new Object();
/**
* This the registry for data models.
*/
private static final Map<String, ActivityChooserModel> sDataModelRegistry =
new HashMap<String, ActivityChooserModel>();
/**
* Lock for synchronizing on this instance.
*/
private final Object mInstanceLock = new Object();
/**
* List of activities that can handle the current intent.
*/
private final List<ActivityResolveInfo> mActivites = new ArrayList<ActivityResolveInfo>();
/**
* List with historical choice records.
*/
private final List<HistoricalRecord> mHistoricalRecords = new ArrayList<HistoricalRecord>();
/**
* Context for accessing resources.
*/
private final Context mContext;
/**
* The name of the history file that backs this model.
*/
private final String mHistoryFileName;
/**
* The intent for which a activity is being chosen.
*/
private Intent mIntent;
/**
* The sorter for ordering activities based on intent and past choices.
*/
private ActivitySorter mActivitySorter = new DefaultSorter();
/**
* The maximal length of the choice history.
*/
private int mHistoryMaxSize = DEFAULT_HISTORY_MAX_LENGTH;
/**
* Flag whether choice history can be read. In general many clients can
* share the same data model and {@link #readHistoricalData()} may be called
* by arbitrary of them any number of times. Therefore, this class guarantees
* that the very first read succeeds and subsequent reads can be performed
* only after a call to {@link #persistHistoricalData()} followed by change
* of the share records.
*/
private boolean mCanReadHistoricalData = true;
/**
* Flag whether the choice history was read. This is used to enforce that
* before calling {@link #persistHistoricalData()} a call to
* {@link #persistHistoricalData()} has been made. This aims to avoid a
* scenario in which a choice history file exits, it is not read yet and
* it is overwritten. Note that always all historical records are read in
* full and the file is rewritten. This is necessary since we need to
* purge old records that are outside of the sliding window of past choices.
*/
private boolean mReadShareHistoryCalled = false;
/**
* Flag whether the choice records have changed. In general many clients can
* share the same data model and {@link #persistHistoricalData()} may be called
* by arbitrary of them any number of times. Therefore, this class guarantees
* that choice history will be persisted only if it has changed.
*/
private boolean mHistoricalRecordsChanged = true;
/**
* Hander for scheduling work on client tread.
*/
private final Handler mHandler = new Handler();
/**
* Policy for controlling how the model handles chosen activities.
*/
private OnChooseActivityListener mActivityChoserModelPolicy;
/**
* Gets the data model backed by the contents of the provided file with historical data.
* Note that only one data model is backed by a given file, thus multiple calls with
* the same file name will return the same model instance. If no such instance is present
* it is created.
* <p>
* <strong>Note:</strong> To use the default historical data file clients should explicitly
* pass as file name {@link #DEFAULT_HISTORY_FILE_NAME}. If no persistence of the choice
* history is desired clients should pass <code>null</code> for the file name. In such
* case a new model is returned for each invocation.
* </p>
*
* <p>
* <strong>Always use difference historical data files for semantically different actions.
* For example, sharing is different from importing.</strong>
* </p>
*
* @param context Context for loading resources.
* @param historyFileName File name with choice history, <code>null</code>
* if the model should not be backed by a file. In this case the activities
* will be ordered only by data from the current session.
*
* @return The model.
*/
public static ActivityChooserModel get(Context context, String historyFileName) {
synchronized (sRegistryLock) {
ActivityChooserModel dataModel = sDataModelRegistry.get(historyFileName);
if (dataModel == null) {
dataModel = new ActivityChooserModel(context, historyFileName);
sDataModelRegistry.put(historyFileName, dataModel);
}
dataModel.readHistoricalData();
return dataModel;
}
}
/**
* Creates a new instance.
*
* @param context Context for loading resources.
* @param historyFileName The history XML file.
*/
private ActivityChooserModel(Context context, String historyFileName) {
mContext = context.getApplicationContext();
if (!TextUtils.isEmpty(historyFileName)
&& !historyFileName.endsWith(HISTORY_FILE_EXTENSION)) {
mHistoryFileName = historyFileName + HISTORY_FILE_EXTENSION;
} else {
mHistoryFileName = historyFileName;
}
}
/**
* Sets an intent for which to choose a activity.
* <p>
* <strong>Note:</strong> Clients must set only semantically similar
* intents for each data model.
* <p>
*
* @param intent The intent.
*/
public void setIntent(Intent intent) {
synchronized (mInstanceLock) {
if (mIntent == intent) {
return;
}
mIntent = intent;
loadActivitiesLocked();
}
}
/**
* Gets the intent for which a activity is being chosen.
*
* @return The intent.
*/
public Intent getIntent() {
synchronized (mInstanceLock) {
return mIntent;
}
}
/**
* Gets the number of activities that can handle the intent.
*
* @return The activity count.
*
* @see #setIntent(Intent)
*/
public int getActivityCount() {
synchronized (mInstanceLock) {
return mActivites.size();
}
}
/**
* Gets an activity at a given index.
*
* @return The activity.
*
* @see ActivityResolveInfo
* @see #setIntent(Intent)
*/
public ResolveInfo getActivity(int index) {
synchronized (mInstanceLock) {
return mActivites.get(index).resolveInfo;
}
}
/**
* Gets the index of a the given activity.
*
* @param activity The activity index.
*
* @return The index if found, -1 otherwise.
*/
public int getActivityIndex(ResolveInfo activity) {
List<ActivityResolveInfo> activities = mActivites;
final int activityCount = activities.size();
for (int i = 0; i < activityCount; i++) {
ActivityResolveInfo currentActivity = activities.get(i);
if (currentActivity.resolveInfo == activity) {
return i;
}
}
return INVALID_INDEX;
}
/**
* Chooses a activity to handle the current intent. This will result in
* adding a historical record for that action and construct intent with
* its component name set such that it can be immediately started by the
* client.
* <p>
* <strong>Note:</strong> By calling this method the client guarantees
* that the returned intent will be started. This intent is returned to
* the client solely to let additional customization before the start.
* </p>
*
* @return An {@link Intent} for launching the activity or null if the
* policy has consumed the intent.
*
* @see HistoricalRecord
* @see OnChooseActivityListener
*/
public Intent chooseActivity(int index) {
ActivityResolveInfo chosenActivity = mActivites.get(index);
ComponentName chosenName = new ComponentName(
chosenActivity.resolveInfo.activityInfo.packageName,
chosenActivity.resolveInfo.activityInfo.name);
Intent choiceIntent = new Intent(mIntent);
choiceIntent.setComponent(chosenName);
if (mActivityChoserModelPolicy != null) {
// Do not allow the policy to change the intent.
Intent choiceIntentCopy = new Intent(choiceIntent);
final boolean handled = mActivityChoserModelPolicy.onChooseActivity(this,
choiceIntentCopy);
if (handled) {
return null;
}
}
HistoricalRecord historicalRecord = new HistoricalRecord(chosenName,
System.currentTimeMillis(), DEFAULT_HISTORICAL_RECORD_WEIGHT);
addHisoricalRecord(historicalRecord);
return choiceIntent;
}
/**
* Sets the listener for choosing an activity.
*
* @param listener The listener.
*/
public void setOnChooseActivityListener(OnChooseActivityListener listener) {
mActivityChoserModelPolicy = listener;
}
/**
* Gets the default activity, The default activity is defined as the one
* with highest rank i.e. the first one in the list of activities that can
* handle the intent.
*
* @return The default activity, <code>null</code> id not activities.
*
* @see #getActivity(int)
*/
public ResolveInfo getDefaultActivity() {
synchronized (mInstanceLock) {
if (!mActivites.isEmpty()) {
return mActivites.get(0).resolveInfo;
}
}
return null;
}
/**
* Sets the default activity. The default activity is set by adding a
* historical record with weight high enough that this activity will
* become the highest ranked. Such a strategy guarantees that the default
* will eventually change if not used. Also the weight of the record for
* setting a default is inflated with a constant amount to guarantee that
* it will stay as default for awhile.
*
* @param index The index of the activity to set as default.
*/
public void setDefaultActivity(int index) {
ActivityResolveInfo newDefaultActivity = mActivites.get(index);
ActivityResolveInfo oldDefaultActivity = mActivites.get(0);
final float weight;
if (oldDefaultActivity != null) {
// Add a record with weight enough to boost the chosen at the top.
weight = oldDefaultActivity.weight - newDefaultActivity.weight
+ DEFAULT_ACTIVITY_INFLATION;
} else {
weight = DEFAULT_HISTORICAL_RECORD_WEIGHT;
}
ComponentName defaultName = new ComponentName(
newDefaultActivity.resolveInfo.activityInfo.packageName,
newDefaultActivity.resolveInfo.activityInfo.name);
HistoricalRecord historicalRecord = new HistoricalRecord(defaultName,
System.currentTimeMillis(), weight);
addHisoricalRecord(historicalRecord);
}
/**
* Reads the history data from the backing file if the latter
* was provided. Calling this method more than once before a call
* to {@link #persistHistoricalData()} has been made has no effect.
* <p>
* <strong>Note:</strong> Historical data is read asynchronously and
* as soon as the reading is completed any registered
* {@link DataSetObserver}s will be notified. Also no historical
* data is read until this method is invoked.
* <p>
*/
private void readHistoricalData() {
synchronized (mInstanceLock) {
if (!mCanReadHistoricalData || !mHistoricalRecordsChanged) {
return;
}
mCanReadHistoricalData = false;
mReadShareHistoryCalled = true;
if (!TextUtils.isEmpty(mHistoryFileName)) {
/*AsyncTask.*/SERIAL_EXECUTOR.execute(new HistoryLoader());
}
}
}
private static final SerialExecutor SERIAL_EXECUTOR = new SerialExecutor();
private static class SerialExecutor implements Executor {
final LinkedList<Runnable> mTasks = new LinkedList<Runnable>();
Runnable mActive;
public synchronized void execute(final Runnable r) {
mTasks.offer(new Runnable() {
public void run() {
try {
r.run();
} finally {
scheduleNext();
}
}
});
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
mActive.run();
}
}
}
/**
* Persists the history data to the backing file if the latter
* was provided. Calling this method before a call to {@link #readHistoricalData()}
* throws an exception. Calling this method more than one without choosing an
* activity has not effect.
*
* @throws IllegalStateException If this method is called before a call to
* {@link #readHistoricalData()}.
*/
private void persistHistoricalData() {
synchronized (mInstanceLock) {
if (!mReadShareHistoryCalled) {
throw new IllegalStateException("No preceding call to #readHistoricalData");
}
if (!mHistoricalRecordsChanged) {
return;
}
mHistoricalRecordsChanged = false;
mCanReadHistoricalData = true;
if (!TextUtils.isEmpty(mHistoryFileName)) {
/*AsyncTask.*/SERIAL_EXECUTOR.execute(new HistoryPersister());
}
}
}
/**
* Sets the sorter for ordering activities based on historical data and an intent.
*
* @param activitySorter The sorter.
*
* @see ActivitySorter
*/
public void setActivitySorter(ActivitySorter activitySorter) {
synchronized (mInstanceLock) {
if (mActivitySorter == activitySorter) {
return;
}
mActivitySorter = activitySorter;
sortActivities();
}
}
/**
* Sorts the activities based on history and an intent. If
* a sorter is not specified this a default implementation is used.
*
* @see #setActivitySorter(ActivitySorter)
*/
private void sortActivities() {
synchronized (mInstanceLock) {
if (mActivitySorter != null && !mActivites.isEmpty()) {
mActivitySorter.sort(mIntent, mActivites,
Collections.unmodifiableList(mHistoricalRecords));
notifyChanged();
}
}
}
/**
* Sets the maximal size of the historical data. Defaults to
* {@link #DEFAULT_HISTORY_MAX_LENGTH}
* <p>
* <strong>Note:</strong> Setting this property will immediately
* enforce the specified max history size by dropping enough old
* historical records to enforce the desired size. Thus, any
* records that exceed the history size will be discarded and
* irreversibly lost.
* </p>
*
* @param historyMaxSize The max history size.
*/
public void setHistoryMaxSize(int historyMaxSize) {
synchronized (mInstanceLock) {
if (mHistoryMaxSize == historyMaxSize) {
return;
}
mHistoryMaxSize = historyMaxSize;
pruneExcessiveHistoricalRecordsLocked();
sortActivities();
}
}
/**
* Gets the history max size.
*
* @return The history max size.
*/
public int getHistoryMaxSize() {
synchronized (mInstanceLock) {
return mHistoryMaxSize;
}
}
/**
* Gets the history size.
*
* @return The history size.
*/
public int getHistorySize() {
synchronized (mInstanceLock) {
return mHistoricalRecords.size();
}
}
/**
* Adds a historical record.
*
* @param historicalRecord The record to add.
* @return True if the record was added.
*/
private boolean addHisoricalRecord(HistoricalRecord historicalRecord) {
synchronized (mInstanceLock) {
final boolean added = mHistoricalRecords.add(historicalRecord);
if (added) {
mHistoricalRecordsChanged = true;
pruneExcessiveHistoricalRecordsLocked();
persistHistoricalData();
sortActivities();
}
return added;
}
}
/**
* Prunes older excessive records to guarantee {@link #mHistoryMaxSize}.
*/
private void pruneExcessiveHistoricalRecordsLocked() {
List<HistoricalRecord> choiceRecords = mHistoricalRecords;
final int pruneCount = choiceRecords.size() - mHistoryMaxSize;
if (pruneCount <= 0) {
return;
}
mHistoricalRecordsChanged = true;
for (int i = 0; i < pruneCount; i++) {
HistoricalRecord prunedRecord = choiceRecords.remove(0);
if (DEBUG) {
Log.i(LOG_TAG, "Pruned: " + prunedRecord);
}
}
}
/**
* Loads the activities.
*/
private void loadActivitiesLocked() {
mActivites.clear();
if (mIntent != null) {
List<ResolveInfo> resolveInfos =
mContext.getPackageManager().queryIntentActivities(mIntent, 0);
final int resolveInfoCount = resolveInfos.size();
for (int i = 0; i < resolveInfoCount; i++) {
ResolveInfo resolveInfo = resolveInfos.get(i);
mActivites.add(new ActivityResolveInfo(resolveInfo));
}
sortActivities();
} else {
notifyChanged();
}
}
/**
* Represents a record in the history.
*/
public final static class HistoricalRecord {
/**
* The activity name.
*/
public final ComponentName activity;
/**
* The choice time.
*/
public final long time;
/**
* The record weight.
*/
public final float weight;
/**
* Creates a new instance.
*
* @param activityName The activity component name flattened to string.
* @param time The time the activity was chosen.
* @param weight The weight of the record.
*/
public HistoricalRecord(String activityName, long time, float weight) {
this(ComponentName.unflattenFromString(activityName), time, weight);
}
/**
* Creates a new instance.
*
* @param activityName The activity name.
* @param time The time the activity was chosen.
* @param weight The weight of the record.
*/
public HistoricalRecord(ComponentName activityName, long time, float weight) {
this.activity = activityName;
this.time = time;
this.weight = weight;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((activity == null) ? 0 : activity.hashCode());
result = prime * result + (int) (time ^ (time >>> 32));
result = prime * result + Float.floatToIntBits(weight);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
HistoricalRecord other = (HistoricalRecord) obj;
if (activity == null) {
if (other.activity != null) {
return false;
}
} else if (!activity.equals(other.activity)) {
return false;
}
if (time != other.time) {
return false;
}
if (Float.floatToIntBits(weight) != Float.floatToIntBits(other.weight)) {
return false;
}
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("[");
builder.append("; activity:").append(activity);
builder.append("; time:").append(time);
builder.append("; weight:").append(new BigDecimal(weight));
builder.append("]");
return builder.toString();
}
}
/**
* Represents an activity.
*/
public final class ActivityResolveInfo implements Comparable<ActivityResolveInfo> {
/**
* The {@link ResolveInfo} of the activity.
*/
public final ResolveInfo resolveInfo;
/**
* Weight of the activity. Useful for sorting.
*/
public float weight;
/**
* Creates a new instance.
*
* @param resolveInfo activity {@link ResolveInfo}.
*/
public ActivityResolveInfo(ResolveInfo resolveInfo) {
this.resolveInfo = resolveInfo;
}
@Override
public int hashCode() {
return 31 + Float.floatToIntBits(weight);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ActivityResolveInfo other = (ActivityResolveInfo) obj;
if (Float.floatToIntBits(weight) != Float.floatToIntBits(other.weight)) {
return false;
}
return true;
}
public int compareTo(ActivityResolveInfo another) {
return Float.floatToIntBits(another.weight) - Float.floatToIntBits(weight);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("[");
builder.append("resolveInfo:").append(resolveInfo.toString());
builder.append("; weight:").append(new BigDecimal(weight));
builder.append("]");
return builder.toString();
}
}
/**
* Default activity sorter implementation.
*/
private final class DefaultSorter implements ActivitySorter {
private static final float WEIGHT_DECAY_COEFFICIENT = 0.95f;
private final Map<String, ActivityResolveInfo> mPackageNameToActivityMap =
new HashMap<String, ActivityResolveInfo>();
public void sort(Intent intent, List<ActivityResolveInfo> activities,
List<HistoricalRecord> historicalRecords) {
Map<String, ActivityResolveInfo> packageNameToActivityMap =
mPackageNameToActivityMap;
packageNameToActivityMap.clear();
final int activityCount = activities.size();
for (int i = 0; i < activityCount; i++) {
ActivityResolveInfo activity = activities.get(i);
activity.weight = 0.0f;
String packageName = activity.resolveInfo.activityInfo.packageName;
packageNameToActivityMap.put(packageName, activity);
}
final int lastShareIndex = historicalRecords.size() - 1;
float nextRecordWeight = 1;
for (int i = lastShareIndex; i >= 0; i--) {
HistoricalRecord historicalRecord = historicalRecords.get(i);
String packageName = historicalRecord.activity.getPackageName();
ActivityResolveInfo activity = packageNameToActivityMap.get(packageName);
if (activity != null) {
activity.weight += historicalRecord.weight * nextRecordWeight;
nextRecordWeight = nextRecordWeight * WEIGHT_DECAY_COEFFICIENT;
}
}
Collections.sort(activities);
if (DEBUG) {
for (int i = 0; i < activityCount; i++) {
Log.i(LOG_TAG, "Sorted: " + activities.get(i));
}
}
}
}
/**
* Command for reading the historical records from a file off the UI thread.
*/
private final class HistoryLoader implements Runnable {
public void run() {
FileInputStream fis = null;
try {
fis = mContext.openFileInput(mHistoryFileName);
} catch (FileNotFoundException fnfe) {
if (DEBUG) {
Log.i(LOG_TAG, "Could not open historical records file: " + mHistoryFileName);
}
return;
}
try {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(fis, null);
int type = XmlPullParser.START_DOCUMENT;
while (type != XmlPullParser.END_DOCUMENT && type != XmlPullParser.START_TAG) {
type = parser.next();
}
if (!TAG_HISTORICAL_RECORDS.equals(parser.getName())) {
throw new XmlPullParserException("Share records file does not start with "
+ TAG_HISTORICAL_RECORDS + " tag.");
}
List<HistoricalRecord> readRecords = new ArrayList<HistoricalRecord>();
while (true) {
type = parser.next();
if (type == XmlPullParser.END_DOCUMENT) {
break;
}
if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
continue;
}
String nodeName = parser.getName();
if (!TAG_HISTORICAL_RECORD.equals(nodeName)) {
throw new XmlPullParserException("Share records file not well-formed.");
}
String activity = parser.getAttributeValue(null, ATTRIBUTE_ACTIVITY);
final long time =
Long.parseLong(parser.getAttributeValue(null, ATTRIBUTE_TIME));
final float weight =
Float.parseFloat(parser.getAttributeValue(null, ATTRIBUTE_WEIGHT));
HistoricalRecord readRecord = new HistoricalRecord(activity, time,
weight);
readRecords.add(readRecord);
if (DEBUG) {
Log.i(LOG_TAG, "Read " + readRecord.toString());
}
}
if (DEBUG) {
Log.i(LOG_TAG, "Read " + readRecords.size() + " historical records.");
}
synchronized (mInstanceLock) {
Set<HistoricalRecord> uniqueShareRecords =
new LinkedHashSet<HistoricalRecord>(readRecords);
// Make sure no duplicates. Example: Read a file with
// one record, add one record, persist the two records,
// add a record, read the persisted records - the
// read two records should not be added again.
List<HistoricalRecord> historicalRecords = mHistoricalRecords;
final int historicalRecordsCount = historicalRecords.size();
for (int i = historicalRecordsCount - 1; i >= 0; i--) {
HistoricalRecord historicalRecord = historicalRecords.get(i);
uniqueShareRecords.add(historicalRecord);
}
if (historicalRecords.size() == uniqueShareRecords.size()) {
return;
}
// Make sure the oldest records go to the end.
historicalRecords.clear();
historicalRecords.addAll(uniqueShareRecords);
mHistoricalRecordsChanged = true;
// Do this on the client thread since the client may be on the UI
// thread, wait for data changes which happen during sorting, and
// perform UI modification based on the data change.
mHandler.post(new Runnable() {
public void run() {
pruneExcessiveHistoricalRecordsLocked();
sortActivities();
}
});
}
} catch (XmlPullParserException xppe) {
Log.e(LOG_TAG, "Error reading historical recrod file: " + mHistoryFileName, xppe);
} catch (IOException ioe) {
Log.e(LOG_TAG, "Error reading historical recrod file: " + mHistoryFileName, ioe);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException ioe) {
/* ignore */
}
}
}
}
}
/**
* Command for persisting the historical records to a file off the UI thread.
*/
private final class HistoryPersister implements Runnable {
public void run() {
FileOutputStream fos = null;
List<HistoricalRecord> records = null;
synchronized (mInstanceLock) {
records = new ArrayList<HistoricalRecord>(mHistoricalRecords);
}
try {
fos = mContext.openFileOutput(mHistoryFileName, Context.MODE_PRIVATE);
} catch (FileNotFoundException fnfe) {
Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, fnfe);
return;
}
XmlSerializer serializer = Xml.newSerializer();
try {
serializer.setOutput(fos, null);
serializer.startDocument("UTF-8", true);
serializer.startTag(null, TAG_HISTORICAL_RECORDS);
final int recordCount = records.size();
for (int i = 0; i < recordCount; i++) {
HistoricalRecord record = records.remove(0);
serializer.startTag(null, TAG_HISTORICAL_RECORD);
serializer.attribute(null, ATTRIBUTE_ACTIVITY, record.activity.flattenToString());
serializer.attribute(null, ATTRIBUTE_TIME, String.valueOf(record.time));
serializer.attribute(null, ATTRIBUTE_WEIGHT, String.valueOf(record.weight));
serializer.endTag(null, TAG_HISTORICAL_RECORD);
if (DEBUG) {
Log.i(LOG_TAG, "Wrote " + record.toString());
}
}
serializer.endTag(null, TAG_HISTORICAL_RECORDS);
serializer.endDocument();
if (DEBUG) {
Log.i(LOG_TAG, "Wrote " + recordCount + " historical records.");
}
} catch (IllegalArgumentException iae) {
Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, iae);
} catch (IllegalStateException ise) {
Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, ise);
} catch (IOException ioe) {
Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, ioe);
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
/* ignore */
}
}
}
}
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/widget/ActivityChooserModel.java | Java | asf20 | 39,792 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.widget;
import android.os.Build;
import com.actionbarsherlock.R;
import com.actionbarsherlock.internal.widget.IcsLinearLayout;
import com.actionbarsherlock.internal.widget.IcsListPopupWindow;
import com.actionbarsherlock.view.ActionProvider;
import com.actionbarsherlock.widget.ActivityChooserModel.ActivityChooserModelClient;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
/**
* This class is a view for choosing an activity for handling a given {@link Intent}.
* <p>
* The view is composed of two adjacent buttons:
* <ul>
* <li>
* The left button is an immediate action and allows one click activity choosing.
* Tapping this button immediately executes the intent without requiring any further
* user input. Long press on this button shows a popup for changing the default
* activity.
* </li>
* <li>
* The right button is an overflow action and provides an optimized menu
* of additional activities. Tapping this button shows a popup anchored to this
* view, listing the most frequently used activities. This list is initially
* limited to a small number of items in frequency used order. The last item,
* "Show all..." serves as an affordance to display all available activities.
* </li>
* </ul>
* </p>
*
* @hide
*/
class ActivityChooserView extends ViewGroup implements ActivityChooserModelClient {
/**
* An adapter for displaying the activities in an {@link AdapterView}.
*/
private final ActivityChooserViewAdapter mAdapter;
/**
* Implementation of various interfaces to avoid publishing them in the APIs.
*/
private final Callbacks mCallbacks;
/**
* The content of this view.
*/
private final IcsLinearLayout mActivityChooserContent;
/**
* Stores the background drawable to allow hiding and latter showing.
*/
private final Drawable mActivityChooserContentBackground;
/**
* The expand activities action button;
*/
private final FrameLayout mExpandActivityOverflowButton;
/**
* The image for the expand activities action button;
*/
private final ImageView mExpandActivityOverflowButtonImage;
/**
* The default activities action button;
*/
private final FrameLayout mDefaultActivityButton;
/**
* The image for the default activities action button;
*/
private final ImageView mDefaultActivityButtonImage;
/**
* The maximal width of the list popup.
*/
private final int mListPopupMaxWidth;
/**
* The ActionProvider hosting this view, if applicable.
*/
ActionProvider mProvider;
/**
* Observer for the model data.
*/
private final DataSetObserver mModelDataSetOberver = new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
mAdapter.notifyDataSetChanged();
}
@Override
public void onInvalidated() {
super.onInvalidated();
mAdapter.notifyDataSetInvalidated();
}
};
private final OnGlobalLayoutListener mOnGlobalLayoutListener = new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (isShowingPopup()) {
if (!isShown()) {
getListPopupWindow().dismiss();
} else {
getListPopupWindow().show();
if (mProvider != null) {
mProvider.subUiVisibilityChanged(true);
}
}
}
}
};
/**
* Popup window for showing the activity overflow list.
*/
private IcsListPopupWindow mListPopupWindow;
/**
* Listener for the dismissal of the popup/alert.
*/
private PopupWindow.OnDismissListener mOnDismissListener;
/**
* Flag whether a default activity currently being selected.
*/
private boolean mIsSelectingDefaultActivity;
/**
* The count of activities in the popup.
*/
private int mInitialActivityCount = ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_DEFAULT;
/**
* Flag whether this view is attached to a window.
*/
private boolean mIsAttachedToWindow;
/**
* String resource for formatting content description of the default target.
*/
private int mDefaultActionButtonContentDescription;
private final Context mContext;
/**
* Create a new instance.
*
* @param context The application environment.
*/
public ActivityChooserView(Context context) {
this(context, null);
}
/**
* Create a new instance.
*
* @param context The application environment.
* @param attrs A collection of attributes.
*/
public ActivityChooserView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
/**
* Create a new instance.
*
* @param context The application environment.
* @param attrs A collection of attributes.
* @param defStyle The default style to apply to this view.
*/
public ActivityChooserView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
TypedArray attributesArray = context.obtainStyledAttributes(attrs,
R.styleable.SherlockActivityChooserView, defStyle, 0);
mInitialActivityCount = attributesArray.getInt(
R.styleable.SherlockActivityChooserView_initialActivityCount,
ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_DEFAULT);
Drawable expandActivityOverflowButtonDrawable = attributesArray.getDrawable(
R.styleable.SherlockActivityChooserView_expandActivityOverflowButtonDrawable);
attributesArray.recycle();
LayoutInflater inflater = LayoutInflater.from(mContext);
inflater.inflate(R.layout.abs__activity_chooser_view, this, true);
mCallbacks = new Callbacks();
mActivityChooserContent = (IcsLinearLayout) findViewById(R.id.abs__activity_chooser_view_content);
mActivityChooserContentBackground = mActivityChooserContent.getBackground();
mDefaultActivityButton = (FrameLayout) findViewById(R.id.abs__default_activity_button);
mDefaultActivityButton.setOnClickListener(mCallbacks);
mDefaultActivityButton.setOnLongClickListener(mCallbacks);
mDefaultActivityButtonImage = (ImageView) mDefaultActivityButton.findViewById(R.id.abs__image);
mExpandActivityOverflowButton = (FrameLayout) findViewById(R.id.abs__expand_activities_button);
mExpandActivityOverflowButton.setOnClickListener(mCallbacks);
mExpandActivityOverflowButtonImage =
(ImageView) mExpandActivityOverflowButton.findViewById(R.id.abs__image);
mExpandActivityOverflowButtonImage.setImageDrawable(expandActivityOverflowButtonDrawable);
mAdapter = new ActivityChooserViewAdapter();
mAdapter.registerDataSetObserver(new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
updateAppearance();
}
});
Resources resources = context.getResources();
mListPopupMaxWidth = Math.max(resources.getDisplayMetrics().widthPixels / 2,
resources.getDimensionPixelSize(R.dimen.abs__config_prefDialogWidth));
}
/**
* {@inheritDoc}
*/
public void setActivityChooserModel(ActivityChooserModel dataModel) {
mAdapter.setDataModel(dataModel);
if (isShowingPopup()) {
dismissPopup();
showPopup();
}
}
/**
* Sets the background for the button that expands the activity
* overflow list.
*
* <strong>Note:</strong> Clients would like to set this drawable
* as a clue about the action the chosen activity will perform. For
* example, if a share activity is to be chosen the drawable should
* give a clue that sharing is to be performed.
*
* @param drawable The drawable.
*/
public void setExpandActivityOverflowButtonDrawable(Drawable drawable) {
mExpandActivityOverflowButtonImage.setImageDrawable(drawable);
}
/**
* Sets the content description for the button that expands the activity
* overflow list.
*
* description as a clue about the action performed by the button.
* For example, if a share activity is to be chosen the content
* description should be something like "Share with".
*
* @param resourceId The content description resource id.
*/
public void setExpandActivityOverflowButtonContentDescription(int resourceId) {
CharSequence contentDescription = mContext.getString(resourceId);
mExpandActivityOverflowButtonImage.setContentDescription(contentDescription);
}
/**
* Set the provider hosting this view, if applicable.
* @hide Internal use only
*/
public void setProvider(ActionProvider provider) {
mProvider = provider;
}
/**
* Shows the popup window with activities.
*
* @return True if the popup was shown, false if already showing.
*/
public boolean showPopup() {
if (isShowingPopup() || !mIsAttachedToWindow) {
return false;
}
mIsSelectingDefaultActivity = false;
showPopupUnchecked(mInitialActivityCount);
return true;
}
/**
* Shows the popup no matter if it was already showing.
*
* @param maxActivityCount The max number of activities to display.
*/
private void showPopupUnchecked(int maxActivityCount) {
if (mAdapter.getDataModel() == null) {
throw new IllegalStateException("No data model. Did you call #setDataModel?");
}
getViewTreeObserver().addOnGlobalLayoutListener(mOnGlobalLayoutListener);
final boolean defaultActivityButtonShown =
mDefaultActivityButton.getVisibility() == VISIBLE;
final int activityCount = mAdapter.getActivityCount();
final int maxActivityCountOffset = defaultActivityButtonShown ? 1 : 0;
if (maxActivityCount != ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_UNLIMITED
&& activityCount > maxActivityCount + maxActivityCountOffset) {
mAdapter.setShowFooterView(true);
mAdapter.setMaxActivityCount(maxActivityCount - 1);
} else {
mAdapter.setShowFooterView(false);
mAdapter.setMaxActivityCount(maxActivityCount);
}
IcsListPopupWindow popupWindow = getListPopupWindow();
if (!popupWindow.isShowing()) {
if (mIsSelectingDefaultActivity || !defaultActivityButtonShown) {
mAdapter.setShowDefaultActivity(true, defaultActivityButtonShown);
} else {
mAdapter.setShowDefaultActivity(false, false);
}
final int contentWidth = Math.min(mAdapter.measureContentWidth(), mListPopupMaxWidth);
popupWindow.setContentWidth(contentWidth);
popupWindow.show();
if (mProvider != null) {
mProvider.subUiVisibilityChanged(true);
}
popupWindow.getListView().setContentDescription(mContext.getString(
R.string.abs__activitychooserview_choose_application));
}
}
/**
* Dismisses the popup window with activities.
*
* @return True if dismissed, false if already dismissed.
*/
public boolean dismissPopup() {
if (isShowingPopup()) {
getListPopupWindow().dismiss();
ViewTreeObserver viewTreeObserver = getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.removeGlobalOnLayoutListener(mOnGlobalLayoutListener);
}
}
return true;
}
/**
* Gets whether the popup window with activities is shown.
*
* @return True if the popup is shown.
*/
public boolean isShowingPopup() {
return getListPopupWindow().isShowing();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
ActivityChooserModel dataModel = mAdapter.getDataModel();
if (dataModel != null) {
dataModel.registerObserver(mModelDataSetOberver);
}
mIsAttachedToWindow = true;
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
ActivityChooserModel dataModel = mAdapter.getDataModel();
if (dataModel != null) {
dataModel.unregisterObserver(mModelDataSetOberver);
}
ViewTreeObserver viewTreeObserver = getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.removeGlobalOnLayoutListener(mOnGlobalLayoutListener);
}
mIsAttachedToWindow = false;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
View child = mActivityChooserContent;
// If the default action is not visible we want to be as tall as the
// ActionBar so if this widget is used in the latter it will look as
// a normal action button.
if (mDefaultActivityButton.getVisibility() != VISIBLE) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec),
MeasureSpec.EXACTLY);
}
measureChild(child, widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(child.getMeasuredWidth(), child.getMeasuredHeight());
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
mActivityChooserContent.layout(0, 0, right - left, bottom - top);
if (getListPopupWindow().isShowing()) {
showPopupUnchecked(mAdapter.getMaxActivityCount());
} else {
dismissPopup();
}
}
public ActivityChooserModel getDataModel() {
return mAdapter.getDataModel();
}
/**
* Sets a listener to receive a callback when the popup is dismissed.
*
* @param listener The listener to be notified.
*/
public void setOnDismissListener(PopupWindow.OnDismissListener listener) {
mOnDismissListener = listener;
}
/**
* Sets the initial count of items shown in the activities popup
* i.e. the items before the popup is expanded. This is an upper
* bound since it is not guaranteed that such number of intent
* handlers exist.
*
* @param itemCount The initial popup item count.
*/
public void setInitialActivityCount(int itemCount) {
mInitialActivityCount = itemCount;
}
/**
* Sets a content description of the default action button. This
* resource should be a string taking one formatting argument and
* will be used for formatting the content description of the button
* dynamically as the default target changes. For example, a resource
* pointing to the string "share with %1$s" will result in a content
* description "share with Bluetooth" for the Bluetooth activity.
*
* @param resourceId The resource id.
*/
public void setDefaultActionButtonContentDescription(int resourceId) {
mDefaultActionButtonContentDescription = resourceId;
}
/**
* Gets the list popup window which is lazily initialized.
*
* @return The popup.
*/
private IcsListPopupWindow getListPopupWindow() {
if (mListPopupWindow == null) {
mListPopupWindow = new IcsListPopupWindow(getContext());
mListPopupWindow.setAdapter(mAdapter);
mListPopupWindow.setAnchorView(ActivityChooserView.this);
mListPopupWindow.setModal(true);
mListPopupWindow.setOnItemClickListener(mCallbacks);
mListPopupWindow.setOnDismissListener(mCallbacks);
}
return mListPopupWindow;
}
/**
* Updates the buttons state.
*/
private void updateAppearance() {
// Expand overflow button.
if (mAdapter.getCount() > 0) {
mExpandActivityOverflowButton.setEnabled(true);
} else {
mExpandActivityOverflowButton.setEnabled(false);
}
// Default activity button.
final int activityCount = mAdapter.getActivityCount();
final int historySize = mAdapter.getHistorySize();
if (activityCount > 0 && historySize > 0) {
mDefaultActivityButton.setVisibility(VISIBLE);
ResolveInfo activity = mAdapter.getDefaultActivity();
PackageManager packageManager = mContext.getPackageManager();
mDefaultActivityButtonImage.setImageDrawable(activity.loadIcon(packageManager));
if (mDefaultActionButtonContentDescription != 0) {
CharSequence label = activity.loadLabel(packageManager);
String contentDescription = mContext.getString(
mDefaultActionButtonContentDescription, label);
mDefaultActivityButton.setContentDescription(contentDescription);
}
} else {
mDefaultActivityButton.setVisibility(View.GONE);
}
// Activity chooser content.
if (mDefaultActivityButton.getVisibility() == VISIBLE) {
mActivityChooserContent.setBackgroundDrawable(mActivityChooserContentBackground);
} else {
mActivityChooserContent.setBackgroundDrawable(null);
}
}
/**
* Interface implementation to avoid publishing them in the APIs.
*/
private class Callbacks implements AdapterView.OnItemClickListener,
View.OnClickListener, View.OnLongClickListener, PopupWindow.OnDismissListener {
// AdapterView#OnItemClickListener
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ActivityChooserViewAdapter adapter = (ActivityChooserViewAdapter) parent.getAdapter();
final int itemViewType = adapter.getItemViewType(position);
switch (itemViewType) {
case ActivityChooserViewAdapter.ITEM_VIEW_TYPE_FOOTER: {
showPopupUnchecked(ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_UNLIMITED);
} break;
case ActivityChooserViewAdapter.ITEM_VIEW_TYPE_ACTIVITY: {
dismissPopup();
if (mIsSelectingDefaultActivity) {
// The item at position zero is the default already.
if (position > 0) {
mAdapter.getDataModel().setDefaultActivity(position);
}
} else {
// If the default target is not shown in the list, the first
// item in the model is default action => adjust index
position = mAdapter.getShowDefaultActivity() ? position : position + 1;
Intent launchIntent = mAdapter.getDataModel().chooseActivity(position);
if (launchIntent != null) {
mContext.startActivity(launchIntent);
}
}
} break;
default:
throw new IllegalArgumentException();
}
}
// View.OnClickListener
public void onClick(View view) {
if (view == mDefaultActivityButton) {
dismissPopup();
ResolveInfo defaultActivity = mAdapter.getDefaultActivity();
final int index = mAdapter.getDataModel().getActivityIndex(defaultActivity);
Intent launchIntent = mAdapter.getDataModel().chooseActivity(index);
if (launchIntent != null) {
mContext.startActivity(launchIntent);
}
} else if (view == mExpandActivityOverflowButton) {
mIsSelectingDefaultActivity = false;
showPopupUnchecked(mInitialActivityCount);
} else {
throw new IllegalArgumentException();
}
}
// OnLongClickListener#onLongClick
@Override
public boolean onLongClick(View view) {
if (view == mDefaultActivityButton) {
if (mAdapter.getCount() > 0) {
mIsSelectingDefaultActivity = true;
showPopupUnchecked(mInitialActivityCount);
}
} else {
throw new IllegalArgumentException();
}
return true;
}
// PopUpWindow.OnDismissListener#onDismiss
public void onDismiss() {
notifyOnDismissListener();
if (mProvider != null) {
mProvider.subUiVisibilityChanged(false);
}
}
private void notifyOnDismissListener() {
if (mOnDismissListener != null) {
mOnDismissListener.onDismiss();
}
}
}
private static class SetActivated {
public static void invoke(View view, boolean activated) {
view.setActivated(activated);
}
}
private static final boolean IS_HONEYCOMB = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
/**
* Adapter for backing the list of activities shown in the popup.
*/
private class ActivityChooserViewAdapter extends BaseAdapter {
public static final int MAX_ACTIVITY_COUNT_UNLIMITED = Integer.MAX_VALUE;
public static final int MAX_ACTIVITY_COUNT_DEFAULT = 4;
private static final int ITEM_VIEW_TYPE_ACTIVITY = 0;
private static final int ITEM_VIEW_TYPE_FOOTER = 1;
private static final int ITEM_VIEW_TYPE_COUNT = 3;
private ActivityChooserModel mDataModel;
private int mMaxActivityCount = MAX_ACTIVITY_COUNT_DEFAULT;
private boolean mShowDefaultActivity;
private boolean mHighlightDefaultActivity;
private boolean mShowFooterView;
public void setDataModel(ActivityChooserModel dataModel) {
ActivityChooserModel oldDataModel = mAdapter.getDataModel();
if (oldDataModel != null && isShown()) {
oldDataModel.unregisterObserver(mModelDataSetOberver);
}
mDataModel = dataModel;
if (dataModel != null && isShown()) {
dataModel.registerObserver(mModelDataSetOberver);
}
notifyDataSetChanged();
}
@Override
public int getItemViewType(int position) {
if (mShowFooterView && position == getCount() - 1) {
return ITEM_VIEW_TYPE_FOOTER;
} else {
return ITEM_VIEW_TYPE_ACTIVITY;
}
}
@Override
public int getViewTypeCount() {
return ITEM_VIEW_TYPE_COUNT;
}
public int getCount() {
int count = 0;
int activityCount = mDataModel.getActivityCount();
if (!mShowDefaultActivity && mDataModel.getDefaultActivity() != null) {
activityCount--;
}
count = Math.min(activityCount, mMaxActivityCount);
if (mShowFooterView) {
count++;
}
return count;
}
public Object getItem(int position) {
final int itemViewType = getItemViewType(position);
switch (itemViewType) {
case ITEM_VIEW_TYPE_FOOTER:
return null;
case ITEM_VIEW_TYPE_ACTIVITY:
if (!mShowDefaultActivity && mDataModel.getDefaultActivity() != null) {
position++;
}
return mDataModel.getActivity(position);
default:
throw new IllegalArgumentException();
}
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final int itemViewType = getItemViewType(position);
switch (itemViewType) {
case ITEM_VIEW_TYPE_FOOTER:
if (convertView == null || convertView.getId() != ITEM_VIEW_TYPE_FOOTER) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.abs__activity_chooser_view_list_item, parent, false);
convertView.setId(ITEM_VIEW_TYPE_FOOTER);
TextView titleView = (TextView) convertView.findViewById(R.id.abs__title);
titleView.setText(mContext.getString(
R.string.abs__activity_chooser_view_see_all));
}
return convertView;
case ITEM_VIEW_TYPE_ACTIVITY:
if (convertView == null || convertView.getId() != R.id.abs__list_item) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.abs__activity_chooser_view_list_item, parent, false);
}
PackageManager packageManager = mContext.getPackageManager();
// Set the icon
ImageView iconView = (ImageView) convertView.findViewById(R.id.abs__icon);
ResolveInfo activity = (ResolveInfo) getItem(position);
iconView.setImageDrawable(activity.loadIcon(packageManager));
// Set the title.
TextView titleView = (TextView) convertView.findViewById(R.id.abs__title);
titleView.setText(activity.loadLabel(packageManager));
if (IS_HONEYCOMB) {
// Highlight the default.
if (mShowDefaultActivity && position == 0 && mHighlightDefaultActivity) {
SetActivated.invoke(convertView, true);
} else {
SetActivated.invoke(convertView, false);
}
}
return convertView;
default:
throw new IllegalArgumentException();
}
}
public int measureContentWidth() {
// The user may have specified some of the target not to be shown but we
// want to measure all of them since after expansion they should fit.
final int oldMaxActivityCount = mMaxActivityCount;
mMaxActivityCount = MAX_ACTIVITY_COUNT_UNLIMITED;
int contentWidth = 0;
View itemView = null;
final int widthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
final int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
final int count = getCount();
for (int i = 0; i < count; i++) {
itemView = getView(i, itemView, null);
itemView.measure(widthMeasureSpec, heightMeasureSpec);
contentWidth = Math.max(contentWidth, itemView.getMeasuredWidth());
}
mMaxActivityCount = oldMaxActivityCount;
return contentWidth;
}
public void setMaxActivityCount(int maxActivityCount) {
if (mMaxActivityCount != maxActivityCount) {
mMaxActivityCount = maxActivityCount;
notifyDataSetChanged();
}
}
public ResolveInfo getDefaultActivity() {
return mDataModel.getDefaultActivity();
}
public void setShowFooterView(boolean showFooterView) {
if (mShowFooterView != showFooterView) {
mShowFooterView = showFooterView;
notifyDataSetChanged();
}
}
public int getActivityCount() {
return mDataModel.getActivityCount();
}
public int getHistorySize() {
return mDataModel.getHistorySize();
}
public int getMaxActivityCount() {
return mMaxActivityCount;
}
public ActivityChooserModel getDataModel() {
return mDataModel;
}
public void setShowDefaultActivity(boolean showDefaultActivity,
boolean highlightDefaultActivity) {
if (mShowDefaultActivity != showDefaultActivity
|| mHighlightDefaultActivity != highlightDefaultActivity) {
mShowDefaultActivity = showDefaultActivity;
mHighlightDefaultActivity = highlightDefaultActivity;
notifyDataSetChanged();
}
}
public boolean getShowDefaultActivity() {
return mShowDefaultActivity;
}
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/widget/ActivityChooserView.java | Java | asf20 | 30,395 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.widget;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
import android.view.View;
import com.actionbarsherlock.R;
import com.actionbarsherlock.view.ActionProvider;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
import com.actionbarsherlock.view.SubMenu;
import com.actionbarsherlock.widget.ActivityChooserModel.OnChooseActivityListener;
/**
* This is a provider for a share action. It is responsible for creating views
* that enable data sharing and also to show a sub menu with sharing activities
* if the hosting item is placed on the overflow menu.
* <p>
* Here is how to use the action provider with custom backing file in a {@link MenuItem}:
* </p>
* <p>
* <pre>
* <code>
* // In Activity#onCreateOptionsMenu
* public boolean onCreateOptionsMenu(Menu menu) {
* // Get the menu item.
* MenuItem menuItem = menu.findItem(R.id.my_menu_item);
* // Get the provider and hold onto it to set/change the share intent.
* mShareActionProvider = (ShareActionProvider) menuItem.getActionProvider();
* // Set history different from the default before getting the action
* // view since a call to {@link MenuItem#getActionView() MenuItem.getActionView()} calls
* // {@link ActionProvider#onCreateActionView()} which uses the backing file name. Omit this
* // line if using the default share history file is desired.
* mShareActionProvider.setShareHistoryFileName("custom_share_history.xml");
* . . .
* }
*
* // Somewhere in the application.
* public void doShare(Intent shareIntent) {
* // When you want to share set the share intent.
* mShareActionProvider.setShareIntent(shareIntent);
* }
* </pre>
* </code>
* </p>
* <p>
* <strong>Note:</strong> While the sample snippet demonstrates how to use this provider
* in the context of a menu item, the use of the provider is not limited to menu items.
* </p>
*
* @see ActionProvider
*/
public class ShareActionProvider extends ActionProvider {
/**
* Listener for the event of selecting a share target.
*/
public interface OnShareTargetSelectedListener {
/**
* Called when a share target has been selected. The client can
* decide whether to handle the intent or rely on the default
* behavior which is launching it.
* <p>
* <strong>Note:</strong> Modifying the intent is not permitted and
* any changes to the latter will be ignored.
* </p>
*
* @param source The source of the notification.
* @param intent The intent for launching the chosen share target.
* @return Whether the client has handled the intent.
*/
public boolean onShareTargetSelected(ShareActionProvider source, Intent intent);
}
/**
* The default for the maximal number of activities shown in the sub-menu.
*/
private static final int DEFAULT_INITIAL_ACTIVITY_COUNT = 4;
/**
* The the maximum number activities shown in the sub-menu.
*/
private int mMaxShownActivityCount = DEFAULT_INITIAL_ACTIVITY_COUNT;
/**
* Listener for handling menu item clicks.
*/
private final ShareMenuItemOnMenuItemClickListener mOnMenuItemClickListener =
new ShareMenuItemOnMenuItemClickListener();
/**
* The default name for storing share history.
*/
public static final String DEFAULT_SHARE_HISTORY_FILE_NAME = "share_history.xml";
/**
* Context for accessing resources.
*/
private final Context mContext;
/**
* The name of the file with share history data.
*/
private String mShareHistoryFileName = DEFAULT_SHARE_HISTORY_FILE_NAME;
private OnShareTargetSelectedListener mOnShareTargetSelectedListener;
private OnChooseActivityListener mOnChooseActivityListener;
/**
* Creates a new instance.
*
* @param context Context for accessing resources.
*/
public ShareActionProvider(Context context) {
super(context);
mContext = context;
}
/**
* Sets a listener to be notified when a share target has been selected.
* The listener can optionally decide to handle the selection and
* not rely on the default behavior which is to launch the activity.
* <p>
* <strong>Note:</strong> If you choose the backing share history file
* you will still be notified in this callback.
* </p>
* @param listener The listener.
*/
public void setOnShareTargetSelectedListener(OnShareTargetSelectedListener listener) {
mOnShareTargetSelectedListener = listener;
setActivityChooserPolicyIfNeeded();
}
/**
* {@inheritDoc}
*/
@Override
public View onCreateActionView() {
// Create the view and set its data model.
ActivityChooserModel dataModel = ActivityChooserModel.get(mContext, mShareHistoryFileName);
ActivityChooserView activityChooserView = new ActivityChooserView(mContext);
activityChooserView.setActivityChooserModel(dataModel);
// Lookup and set the expand action icon.
TypedValue outTypedValue = new TypedValue();
mContext.getTheme().resolveAttribute(R.attr.actionModeShareDrawable, outTypedValue, true);
Drawable drawable = mContext.getResources().getDrawable(outTypedValue.resourceId);
activityChooserView.setExpandActivityOverflowButtonDrawable(drawable);
activityChooserView.setProvider(this);
// Set content description.
activityChooserView.setDefaultActionButtonContentDescription(
R.string.abs__shareactionprovider_share_with_application);
activityChooserView.setExpandActivityOverflowButtonContentDescription(
R.string.abs__shareactionprovider_share_with);
return activityChooserView;
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasSubMenu() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public void onPrepareSubMenu(SubMenu subMenu) {
// Clear since the order of items may change.
subMenu.clear();
ActivityChooserModel dataModel = ActivityChooserModel.get(mContext, mShareHistoryFileName);
PackageManager packageManager = mContext.getPackageManager();
final int expandedActivityCount = dataModel.getActivityCount();
final int collapsedActivityCount = Math.min(expandedActivityCount, mMaxShownActivityCount);
// Populate the sub-menu with a sub set of the activities.
for (int i = 0; i < collapsedActivityCount; i++) {
ResolveInfo activity = dataModel.getActivity(i);
subMenu.add(0, i, i, activity.loadLabel(packageManager))
.setIcon(activity.loadIcon(packageManager))
.setOnMenuItemClickListener(mOnMenuItemClickListener);
}
if (collapsedActivityCount < expandedActivityCount) {
// Add a sub-menu for showing all activities as a list item.
SubMenu expandedSubMenu = subMenu.addSubMenu(Menu.NONE, collapsedActivityCount,
collapsedActivityCount,
mContext.getString(R.string.abs__activity_chooser_view_see_all));
for (int i = 0; i < expandedActivityCount; i++) {
ResolveInfo activity = dataModel.getActivity(i);
expandedSubMenu.add(0, i, i, activity.loadLabel(packageManager))
.setIcon(activity.loadIcon(packageManager))
.setOnMenuItemClickListener(mOnMenuItemClickListener);
}
}
}
/**
* Sets the file name of a file for persisting the share history which
* history will be used for ordering share targets. This file will be used
* for all view created by {@link #onCreateActionView()}. Defaults to
* {@link #DEFAULT_SHARE_HISTORY_FILE_NAME}. Set to <code>null</code>
* if share history should not be persisted between sessions.
* <p>
* <strong>Note:</strong> The history file name can be set any time, however
* only the action views created by {@link #onCreateActionView()} after setting
* the file name will be backed by the provided file.
* <p>
*
* @param shareHistoryFile The share history file name.
*/
public void setShareHistoryFileName(String shareHistoryFile) {
mShareHistoryFileName = shareHistoryFile;
setActivityChooserPolicyIfNeeded();
}
/**
* Sets an intent with information about the share action. Here is a
* sample for constructing a share intent:
* <p>
* <pre>
* <code>
* Intent shareIntent = new Intent(Intent.ACTION_SEND);
* shareIntent.setType("image/*");
* Uri uri = Uri.fromFile(new File(getFilesDir(), "foo.jpg"));
* shareIntent.putExtra(Intent.EXTRA_STREAM, uri.toString());
* </pre>
* </code>
* </p>
*
* @param shareIntent The share intent.
*
* @see Intent#ACTION_SEND
* @see Intent#ACTION_SEND_MULTIPLE
*/
public void setShareIntent(Intent shareIntent) {
ActivityChooserModel dataModel = ActivityChooserModel.get(mContext,
mShareHistoryFileName);
dataModel.setIntent(shareIntent);
}
/**
* Reusable listener for handling share item clicks.
*/
private class ShareMenuItemOnMenuItemClickListener implements OnMenuItemClickListener {
@Override
public boolean onMenuItemClick(MenuItem item) {
ActivityChooserModel dataModel = ActivityChooserModel.get(mContext,
mShareHistoryFileName);
final int itemId = item.getItemId();
Intent launchIntent = dataModel.chooseActivity(itemId);
if (launchIntent != null) {
mContext.startActivity(launchIntent);
}
return true;
}
}
/**
* Set the activity chooser policy of the model backed by the current
* share history file if needed which is if there is a registered callback.
*/
private void setActivityChooserPolicyIfNeeded() {
if (mOnShareTargetSelectedListener == null) {
return;
}
if (mOnChooseActivityListener == null) {
mOnChooseActivityListener = new ShareAcitivityChooserModelPolicy();
}
ActivityChooserModel dataModel = ActivityChooserModel.get(mContext, mShareHistoryFileName);
dataModel.setOnChooseActivityListener(mOnChooseActivityListener);
}
/**
* Policy that delegates to the {@link OnShareTargetSelectedListener}, if such.
*/
private class ShareAcitivityChooserModelPolicy implements OnChooseActivityListener {
@Override
public boolean onChooseActivity(ActivityChooserModel host, Intent intent) {
if (mOnShareTargetSelectedListener != null) {
return mOnShareTargetSelectedListener.onShareTargetSelected(
ShareActionProvider.this, intent);
}
return false;
}
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/widget/ShareActionProvider.java | Java | asf20 | 12,014 |
package com.actionbarsherlock;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Iterator;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.internal.ActionBarSherlockCompat;
import com.actionbarsherlock.internal.ActionBarSherlockNative;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
/**
* <p>Helper for implementing the action bar design pattern across all versions
* of Android.</p>
*
* <p>This class will manage interaction with a custom action bar based on the
* Android 4.0 source code. The exposed API mirrors that of its native
* counterpart and you should refer to its documentation for instruction.</p>
*
* @author Jake Wharton <jakewharton@gmail.com>
*/
public abstract class ActionBarSherlock {
protected static final String TAG = "ActionBarSherlock";
protected static final boolean DEBUG = false;
private static final Class<?>[] CONSTRUCTOR_ARGS = new Class[] { Activity.class, int.class };
private static final HashMap<Implementation, Class<? extends ActionBarSherlock>> IMPLEMENTATIONS =
new HashMap<Implementation, Class<? extends ActionBarSherlock>>();
static {
//Register our two built-in implementations
registerImplementation(ActionBarSherlockCompat.class);
registerImplementation(ActionBarSherlockNative.class);
}
/**
* <p>Denotes an implementation of ActionBarSherlock which provides an
* action bar-enhanced experience.</p>
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Implementation {
static final int DEFAULT_API = -1;
static final int DEFAULT_DPI = -1;
int api() default DEFAULT_API;
int dpi() default DEFAULT_DPI;
}
/** Activity interface for menu creation callback. */
public interface OnCreatePanelMenuListener {
public boolean onCreatePanelMenu(int featureId, Menu menu);
}
/** Activity interface for menu creation callback. */
public interface OnCreateOptionsMenuListener {
public boolean onCreateOptionsMenu(Menu menu);
}
/** Activity interface for menu item selection callback. */
public interface OnMenuItemSelectedListener {
public boolean onMenuItemSelected(int featureId, MenuItem item);
}
/** Activity interface for menu item selection callback. */
public interface OnOptionsItemSelectedListener {
public boolean onOptionsItemSelected(MenuItem item);
}
/** Activity interface for menu preparation callback. */
public interface OnPreparePanelListener {
public boolean onPreparePanel(int featureId, View view, Menu menu);
}
/** Activity interface for menu preparation callback. */
public interface OnPrepareOptionsMenuListener {
public boolean onPrepareOptionsMenu(Menu menu);
}
/** Activity interface for action mode finished callback. */
public interface OnActionModeFinishedListener {
public void onActionModeFinished(ActionMode mode);
}
/** Activity interface for action mode started callback. */
public interface OnActionModeStartedListener {
public void onActionModeStarted(ActionMode mode);
}
/**
* If set, the logic in these classes will assume that an {@link Activity}
* is dispatching all of the required events to the class. This flag should
* only be used internally or if you are creating your own base activity
* modeled after one of the included types (e.g., {@code SherlockActivity}).
*/
public static final int FLAG_DELEGATE = 1;
/**
* Register an ActionBarSherlock implementation.
*
* @param implementationClass Target implementation class which extends
* {@link ActionBarSherlock}. This class must also be annotated with
* {@link Implementation}.
*/
public static void registerImplementation(Class<? extends ActionBarSherlock> implementationClass) {
if (!implementationClass.isAnnotationPresent(Implementation.class)) {
throw new IllegalArgumentException("Class " + implementationClass.getSimpleName() + " is not annotated with @Implementation");
} else if (IMPLEMENTATIONS.containsValue(implementationClass)) {
if (DEBUG) Log.w(TAG, "Class " + implementationClass.getSimpleName() + " already registered");
return;
}
Implementation impl = implementationClass.getAnnotation(Implementation.class);
if (DEBUG) Log.i(TAG, "Registering " + implementationClass.getSimpleName() + " with qualifier " + impl);
IMPLEMENTATIONS.put(impl, implementationClass);
}
/**
* Unregister an ActionBarSherlock implementation. <strong>This should be
* considered very volatile and you should only use it if you know what
* you are doing.</strong> You have been warned.
*
* @param implementationClass Target implementation class.
* @return Boolean indicating whether the class was removed.
*/
public static boolean unregisterImplementation(Class<? extends ActionBarSherlock> implementationClass) {
return IMPLEMENTATIONS.values().remove(implementationClass);
}
/**
* Wrap an activity with an action bar abstraction which will enable the
* use of a custom implementation on platforms where a native version does
* not exist.
*
* @param activity Activity to wrap.
* @return Instance to interact with the action bar.
*/
public static ActionBarSherlock wrap(Activity activity) {
return wrap(activity, 0);
}
/**
* Wrap an activity with an action bar abstraction which will enable the
* use of a custom implementation on platforms where a native version does
* not exist.
*
* @param activity Owning activity.
* @param flags Option flags to control behavior.
* @return Instance to interact with the action bar.
*/
public static ActionBarSherlock wrap(Activity activity, int flags) {
//Create a local implementation map we can modify
HashMap<Implementation, Class<? extends ActionBarSherlock>> impls =
new HashMap<Implementation, Class<? extends ActionBarSherlock>>(IMPLEMENTATIONS);
boolean hasQualfier;
/* DPI FILTERING */
hasQualfier = false;
for (Implementation key : impls.keySet()) {
//Only honor TVDPI as a specific qualifier
if (key.dpi() == DisplayMetrics.DENSITY_TV) {
hasQualfier = true;
break;
}
}
if (hasQualfier) {
final boolean isTvDpi = activity.getResources().getDisplayMetrics().densityDpi == DisplayMetrics.DENSITY_TV;
for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) {
int keyDpi = keys.next().dpi();
if ((isTvDpi && keyDpi != DisplayMetrics.DENSITY_TV)
|| (!isTvDpi && keyDpi == DisplayMetrics.DENSITY_TV)) {
keys.remove();
}
}
}
/* API FILTERING */
hasQualfier = false;
for (Implementation key : impls.keySet()) {
if (key.api() != Implementation.DEFAULT_API) {
hasQualfier = true;
break;
}
}
if (hasQualfier) {
final int runtimeApi = Build.VERSION.SDK_INT;
int bestApi = 0;
for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) {
int keyApi = keys.next().api();
if (keyApi > runtimeApi) {
keys.remove();
} else if (keyApi > bestApi) {
bestApi = keyApi;
}
}
for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) {
if (keys.next().api() != bestApi) {
keys.remove();
}
}
}
if (impls.size() > 1) {
throw new IllegalStateException("More than one implementation matches configuration.");
}
if (impls.isEmpty()) {
throw new IllegalStateException("No implementations match configuration.");
}
Class<? extends ActionBarSherlock> impl = impls.values().iterator().next();
if (DEBUG) Log.i(TAG, "Using implementation: " + impl.getSimpleName());
try {
Constructor<? extends ActionBarSherlock> ctor = impl.getConstructor(CONSTRUCTOR_ARGS);
return ctor.newInstance(activity, flags);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
/** Activity which is displaying the action bar. Also used for context. */
protected final Activity mActivity;
/** Whether delegating actions for the activity or managing ourselves. */
protected final boolean mIsDelegate;
/** Reference to our custom menu inflater which supports action items. */
protected MenuInflater mMenuInflater;
protected ActionBarSherlock(Activity activity, int flags) {
if (DEBUG) Log.d(TAG, "[<ctor>] activity: " + activity + ", flags: " + flags);
mActivity = activity;
mIsDelegate = (flags & FLAG_DELEGATE) != 0;
}
/**
* Get the current action bar instance.
*
* @return Action bar instance.
*/
public abstract ActionBar getActionBar();
///////////////////////////////////////////////////////////////////////////
// Lifecycle and interaction callbacks when delegating
///////////////////////////////////////////////////////////////////////////
/**
* Notify action bar of a configuration change event. Should be dispatched
* after the call to the superclass implementation.
*
* <blockquote><pre>
* @Override
* public void onConfigurationChanged(Configuration newConfig) {
* super.onConfigurationChanged(newConfig);
* mSherlock.dispatchConfigurationChanged(newConfig);
* }
* </pre></blockquote>
*
* @param newConfig The new device configuration.
*/
public void dispatchConfigurationChanged(Configuration newConfig) {}
/**
* Notify the action bar that the activity has finished its resuming. This
* should be dispatched after the call to the superclass implementation.
*
* <blockquote><pre>
* @Override
* protected void onPostResume() {
* super.onPostResume();
* mSherlock.dispatchPostResume();
* }
* </pre></blockquote>
*/
public void dispatchPostResume() {}
/**
* Notify the action bar that the activity is pausing. This should be
* dispatched before the call to the superclass implementation.
*
* <blockquote><pre>
* @Override
* protected void onPause() {
* mSherlock.dispatchPause();
* super.onPause();
* }
* </pre></blockquote>
*/
public void dispatchPause() {}
/**
* Notify the action bar that the activity is stopping. This should be
* called before the superclass implementation.
*
* <blockquote><p>
* @Override
* protected void onStop() {
* mSherlock.dispatchStop();
* super.onStop();
* }
* </p></blockquote>
*/
public void dispatchStop() {}
/**
* Indicate that the menu should be recreated by calling
* {@link OnCreateOptionsMenuListener#onCreateOptionsMenu(com.actionbarsherlock.view.Menu)}.
*/
public abstract void dispatchInvalidateOptionsMenu();
/**
* Notify the action bar that it should display its overflow menu if it is
* appropriate for the device. The implementation should conditionally
* call the superclass method only if this method returns {@code false}.
*
* <blockquote><p>
* @Override
* public void openOptionsMenu() {
* if (!mSherlock.dispatchOpenOptionsMenu()) {
* super.openOptionsMenu();
* }
* }
* </p></blockquote>
*
* @return {@code true} if the opening of the menu was handled internally.
*/
public boolean dispatchOpenOptionsMenu() {
return false;
}
/**
* Notify the action bar that it should close its overflow menu if it is
* appropriate for the device. This implementation should conditionally
* call the superclass method only if this method returns {@code false}.
*
* <blockquote><pre>
* @Override
* public void closeOptionsMenu() {
* if (!mSherlock.dispatchCloseOptionsMenu()) {
* super.closeOptionsMenu();
* }
* }
* </pre></blockquote>
*
* @return {@code true} if the closing of the menu was handled internally.
*/
public boolean dispatchCloseOptionsMenu() {
return false;
}
/**
* Notify the class that the activity has finished its creation. This
* should be called after the superclass implementation.
*
* <blockquote><pre>
* @Override
* protected void onPostCreate(Bundle savedInstanceState) {
* mSherlock.dispatchPostCreate(savedInstanceState);
* super.onPostCreate(savedInstanceState);
* }
* </pre></blockquote>
*
* @param savedInstanceState If the activity is being re-initialized after
* previously being shut down then this Bundle
* contains the data it most recently supplied in
* {@link Activity#}onSaveInstanceState(Bundle)}.
* <strong>Note: Otherwise it is null.</strong>
*/
public void dispatchPostCreate(Bundle savedInstanceState) {}
/**
* Notify the action bar that the title has changed and the action bar
* should be updated to reflect the change. This should be called before
* the superclass implementation.
*
* <blockquote><pre>
* @Override
* protected void onTitleChanged(CharSequence title, int color) {
* mSherlock.dispatchTitleChanged(title, color);
* super.onTitleChanged(title, color);
* }
* </pre></blockquote>
*
* @param title New activity title.
* @param color New activity color.
*/
public void dispatchTitleChanged(CharSequence title, int color) {}
/**
* Notify the action bar the user has created a key event. This is used to
* toggle the display of the overflow action item with the menu key and to
* close the action mode or expanded action item with the back key.
*
* <blockquote><pre>
* @Override
* public boolean dispatchKeyEvent(KeyEvent event) {
* if (mSherlock.dispatchKeyEvent(event)) {
* return true;
* }
* return super.dispatchKeyEvent(event);
* }
* </pre></blockquote>
*
* @param event Description of the key event.
* @return {@code true} if the event was handled.
*/
public boolean dispatchKeyEvent(KeyEvent event) {
return false;
}
/**
* Notify the action bar that the Activity has triggered a menu creation
* which should happen on the conclusion of {@link Activity#onCreate}. This
* will be used to gain a reference to the native menu for native and
* overflow binding as well as to indicate when compatibility create should
* occur for the first time.
*
* @param menu Activity native menu.
* @return {@code true} since we always want to say that we have a native
*/
public abstract boolean dispatchCreateOptionsMenu(android.view.Menu menu);
/**
* Notify the action bar that the Activity has triggered a menu preparation
* which usually means that the user has requested the overflow menu via a
* hardware menu key. You should return the result of this method call and
* not call the superclass implementation.
*
* <blockquote><p>
* @Override
* public final boolean onPrepareOptionsMenu(android.view.Menu menu) {
* return mSherlock.dispatchPrepareOptionsMenu(menu);
* }
* </p></blockquote>
*
* @param menu Activity native menu.
* @return {@code true} if menu display should proceed.
*/
public abstract boolean dispatchPrepareOptionsMenu(android.view.Menu menu);
/**
* Notify the action bar that a native options menu item has been selected.
* The implementation should return the result of this method call.
*
* <blockquote><p>
* @Override
* public final boolean onOptionsItemSelected(android.view.MenuItem item) {
* return mSherlock.dispatchOptionsItemSelected(item);
* }
* </p></blockquote>
*
* @param item Options menu item.
* @return @{code true} if the selection was handled.
*/
public abstract boolean dispatchOptionsItemSelected(android.view.MenuItem item);
/**
* Notify the action bar that the overflow menu has been opened. The
* implementation should conditionally return {@code true} if this method
* returns {@code true}, otherwise return the result of the superclass
* method.
*
* <blockquote><p>
* @Override
* public final boolean onMenuOpened(int featureId, android.view.Menu menu) {
* if (mSherlock.dispatchMenuOpened(featureId, menu)) {
* return true;
* }
* return super.onMenuOpened(featureId, menu);
* }
* </p></blockquote>
*
* @param featureId Window feature which triggered the event.
* @param menu Activity native menu.
* @return {@code true} if the event was handled by this method.
*/
public boolean dispatchMenuOpened(int featureId, android.view.Menu menu) {
return false;
}
/**
* Notify the action bar that the overflow menu has been closed. This
* method should be called before the superclass implementation.
*
* <blockquote><p>
* @Override
* public void onPanelClosed(int featureId, android.view.Menu menu) {
* mSherlock.dispatchPanelClosed(featureId, menu);
* super.onPanelClosed(featureId, menu);
* }
* </p></blockquote>
*
* @param featureId
* @param menu
*/
public void dispatchPanelClosed(int featureId, android.view.Menu menu) {}
/**
* Notify the action bar that the activity has been destroyed. This method
* should be called before the superclass implementation.
*
* <blockquote><p>
* @Override
* public void onDestroy() {
* mSherlock.dispatchDestroy();
* super.onDestroy();
* }
* </p></blockquote>
*/
public void dispatchDestroy() {}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/**
* Internal method to trigger the menu creation process.
*
* @return {@code true} if menu creation should proceed.
*/
protected final boolean callbackCreateOptionsMenu(Menu menu) {
if (DEBUG) Log.d(TAG, "[callbackCreateOptionsMenu] menu: " + menu);
boolean result = true;
if (mActivity instanceof OnCreatePanelMenuListener) {
OnCreatePanelMenuListener listener = (OnCreatePanelMenuListener)mActivity;
result = listener.onCreatePanelMenu(Window.FEATURE_OPTIONS_PANEL, menu);
} else if (mActivity instanceof OnCreateOptionsMenuListener) {
OnCreateOptionsMenuListener listener = (OnCreateOptionsMenuListener)mActivity;
result = listener.onCreateOptionsMenu(menu);
}
if (DEBUG) Log.d(TAG, "[callbackCreateOptionsMenu] returning " + result);
return result;
}
/**
* Internal method to trigger the menu preparation process.
*
* @return {@code true} if menu preparation should proceed.
*/
protected final boolean callbackPrepareOptionsMenu(Menu menu) {
if (DEBUG) Log.d(TAG, "[callbackPrepareOptionsMenu] menu: " + menu);
boolean result = true;
if (mActivity instanceof OnPreparePanelListener) {
OnPreparePanelListener listener = (OnPreparePanelListener)mActivity;
result = listener.onPreparePanel(Window.FEATURE_OPTIONS_PANEL, null, menu);
} else if (mActivity instanceof OnPrepareOptionsMenuListener) {
OnPrepareOptionsMenuListener listener = (OnPrepareOptionsMenuListener)mActivity;
result = listener.onPrepareOptionsMenu(menu);
}
if (DEBUG) Log.d(TAG, "[callbackPrepareOptionsMenu] returning " + result);
return result;
}
/**
* Internal method for dispatching options menu selection to the owning
* activity callback.
*
* @param item Selected options menu item.
* @return {@code true} if the item selection was handled in the callback.
*/
protected final boolean callbackOptionsItemSelected(MenuItem item) {
if (DEBUG) Log.d(TAG, "[callbackOptionsItemSelected] item: " + item.getTitleCondensed());
boolean result = false;
if (mActivity instanceof OnMenuItemSelectedListener) {
OnMenuItemSelectedListener listener = (OnMenuItemSelectedListener)mActivity;
result = listener.onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, item);
} else if (mActivity instanceof OnOptionsItemSelectedListener) {
OnOptionsItemSelectedListener listener = (OnOptionsItemSelectedListener)mActivity;
result = listener.onOptionsItemSelected(item);
}
if (DEBUG) Log.d(TAG, "[callbackOptionsItemSelected] returning " + result);
return result;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/**
* Query for the availability of a certain feature.
*
* @param featureId The feature ID to check.
* @return {@code true} if feature is enabled, {@code false} otherwise.
*/
public abstract boolean hasFeature(int featureId);
/**
* Enable extended screen features. This must be called before
* {@code setContentView()}. May be called as many times as desired as long
* as it is before {@code setContentView()}. If not called, no extended
* features will be available. You can not turn off a feature once it is
* requested.
*
* @param featureId The desired features, defined as constants by Window.
* @return Returns true if the requested feature is supported and now
* enabled.
*/
public abstract boolean requestFeature(int featureId);
/**
* Set extra options that will influence the UI for this window.
*
* @param uiOptions Flags specifying extra options for this window.
*/
public abstract void setUiOptions(int uiOptions);
/**
* Set extra options that will influence the UI for this window. Only the
* bits filtered by mask will be modified.
*
* @param uiOptions Flags specifying extra options for this window.
* @param mask Flags specifying which options should be modified. Others
* will remain unchanged.
*/
public abstract void setUiOptions(int uiOptions, int mask);
/**
* Set the content of the activity inside the action bar.
*
* @param layoutResId Layout resource ID.
*/
public abstract void setContentView(int layoutResId);
/**
* Set the content of the activity inside the action bar.
*
* @param view The desired content to display.
*/
public void setContentView(View view) {
if (DEBUG) Log.d(TAG, "[setContentView] view: " + view);
setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
}
/**
* Set the content of the activity inside the action bar.
*
* @param view The desired content to display.
* @param params Layout parameters to apply to the view.
*/
public abstract void setContentView(View view, ViewGroup.LayoutParams params);
/**
* Variation on {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
* to add an additional content view to the screen. Added after any
* existing ones on the screen -- existing views are NOT removed.
*
* @param view The desired content to display.
* @param params Layout parameters for the view.
*/
public abstract void addContentView(View view, ViewGroup.LayoutParams params);
/**
* Change the title associated with this activity.
*/
public abstract void setTitle(CharSequence title);
/**
* Change the title associated with this activity.
*/
public void setTitle(int resId) {
if (DEBUG) Log.d(TAG, "[setTitle] resId: " + resId);
setTitle(mActivity.getString(resId));
}
/**
* Sets the visibility of the progress bar in the title.
* <p>
* In order for the progress bar to be shown, the feature must be requested
* via {@link #requestWindowFeature(int)}.
*
* @param visible Whether to show the progress bars in the title.
*/
public abstract void setProgressBarVisibility(boolean visible);
/**
* Sets the visibility of the indeterminate progress bar in the title.
* <p>
* In order for the progress bar to be shown, the feature must be requested
* via {@link #requestWindowFeature(int)}.
*
* @param visible Whether to show the progress bars in the title.
*/
public abstract void setProgressBarIndeterminateVisibility(boolean visible);
/**
* Sets whether the horizontal progress bar in the title should be indeterminate (the circular
* is always indeterminate).
* <p>
* In order for the progress bar to be shown, the feature must be requested
* via {@link #requestWindowFeature(int)}.
*
* @param indeterminate Whether the horizontal progress bar should be indeterminate.
*/
public abstract void setProgressBarIndeterminate(boolean indeterminate);
/**
* Sets the progress for the progress bars in the title.
* <p>
* In order for the progress bar to be shown, the feature must be requested
* via {@link #requestWindowFeature(int)}.
*
* @param progress The progress for the progress bar. Valid ranges are from
* 0 to 10000 (both inclusive). If 10000 is given, the progress
* bar will be completely filled and will fade out.
*/
public abstract void setProgress(int progress);
/**
* Sets the secondary progress for the progress bar in the title. This
* progress is drawn between the primary progress (set via
* {@link #setProgress(int)} and the background. It can be ideal for media
* scenarios such as showing the buffering progress while the default
* progress shows the play progress.
* <p>
* In order for the progress bar to be shown, the feature must be requested
* via {@link #requestWindowFeature(int)}.
*
* @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
* 0 to 10000 (both inclusive).
*/
public abstract void setSecondaryProgress(int secondaryProgress);
/**
* Get a menu inflater instance which supports the newer menu attributes.
*
* @return Menu inflater instance.
*/
public MenuInflater getMenuInflater() {
if (DEBUG) Log.d(TAG, "[getMenuInflater]");
// Make sure that action views can get an appropriate theme.
if (mMenuInflater == null) {
if (getActionBar() != null) {
mMenuInflater = new MenuInflater(getThemedContext());
} else {
mMenuInflater = new MenuInflater(mActivity);
}
}
return mMenuInflater;
}
protected abstract Context getThemedContext();
/**
* Start an action mode.
*
* @param callback Callback that will manage lifecycle events for this
* context mode.
* @return The ContextMode that was started, or null if it was canceled.
* @see ActionMode
*/
public abstract ActionMode startActionMode(ActionMode.Callback callback);
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/ActionBarSherlock.java | Java | asf20 | 30,369 |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.view;
import android.graphics.drawable.Drawable;
import android.view.View;
/**
* Subclass of {@link Menu} for sub menus.
* <p>
* Sub menus do not support item icons, or nested sub menus.
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For information about creating menus, read the
* <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide.</p>
* </div>
*/
public interface SubMenu extends Menu {
/**
* Sets the submenu header's title to the title given in <var>titleRes</var>
* resource identifier.
*
* @param titleRes The string resource identifier used for the title.
* @return This SubMenu so additional setters can be called.
*/
public SubMenu setHeaderTitle(int titleRes);
/**
* Sets the submenu header's title to the title given in <var>title</var>.
*
* @param title The character sequence used for the title.
* @return This SubMenu so additional setters can be called.
*/
public SubMenu setHeaderTitle(CharSequence title);
/**
* Sets the submenu header's icon to the icon given in <var>iconRes</var>
* resource id.
*
* @param iconRes The resource identifier used for the icon.
* @return This SubMenu so additional setters can be called.
*/
public SubMenu setHeaderIcon(int iconRes);
/**
* Sets the submenu header's icon to the icon given in <var>icon</var>
* {@link Drawable}.
*
* @param icon The {@link Drawable} used for the icon.
* @return This SubMenu so additional setters can be called.
*/
public SubMenu setHeaderIcon(Drawable icon);
/**
* Sets the header of the submenu to the {@link View} given in
* <var>view</var>. This replaces the header title and icon (and those
* replace this).
*
* @param view The {@link View} used for the header.
* @return This SubMenu so additional setters can be called.
*/
public SubMenu setHeaderView(View view);
/**
* Clears the header of the submenu.
*/
public void clearHeader();
/**
* Change the icon associated with this submenu's item in its parent menu.
*
* @see MenuItem#setIcon(int)
* @param iconRes The new icon (as a resource ID) to be displayed.
* @return This SubMenu so additional setters can be called.
*/
public SubMenu setIcon(int iconRes);
/**
* Change the icon associated with this submenu's item in its parent menu.
*
* @see MenuItem#setIcon(Drawable)
* @param icon The new icon (as a Drawable) to be displayed.
* @return This SubMenu so additional setters can be called.
*/
public SubMenu setIcon(Drawable icon);
/**
* Gets the {@link MenuItem} that represents this submenu in the parent
* menu. Use this for setting additional item attributes.
*
* @return The {@link MenuItem} that launches the submenu when invoked.
*/
public MenuItem getItem();
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/view/SubMenu.java | Java | asf20 | 3,646 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.view;
/**
* When a {@link View} implements this interface it will receive callbacks
* when expanded or collapsed as an action view alongside the optional,
* app-specified callbacks to {@link OnActionExpandListener}.
*
* <p>See {@link MenuItem} for more information about action views.
* See {@link android.app.ActionBar} for more information about the action bar.
*/
public interface CollapsibleActionView {
/**
* Called when this view is expanded as an action view.
* See {@link MenuItem#expandActionView()}.
*/
public void onActionViewExpanded();
/**
* Called when this view is collapsed as an action view.
* See {@link MenuItem#collapseActionView()}.
*/
public void onActionViewCollapsed();
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/view/CollapsibleActionView.java | Java | asf20 | 1,402 |
/*
* Copyright (C) 2006 The Android Open Source Project
* 2011 Jake Wharton
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.view;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.util.Xml;
import android.view.InflateException;
import android.view.View;
import com.actionbarsherlock.R;
import com.actionbarsherlock.internal.view.menu.MenuItemImpl;
/**
* This class is used to instantiate menu XML files into Menu objects.
* <p>
* For performance reasons, menu inflation relies heavily on pre-processing of
* XML files that is done at build time. Therefore, it is not currently possible
* to use MenuInflater with an XmlPullParser over a plain XML file at runtime;
* it only works with an XmlPullParser returned from a compiled resource (R.
* <em>something</em> file.)
*/
public class MenuInflater {
private static final String LOG_TAG = "MenuInflater";
/** Menu tag name in XML. */
private static final String XML_MENU = "menu";
/** Group tag name in XML. */
private static final String XML_GROUP = "group";
/** Item tag name in XML. */
private static final String XML_ITEM = "item";
private static final int NO_ID = 0;
private static final Class<?>[] ACTION_VIEW_CONSTRUCTOR_SIGNATURE = new Class[] {Context.class};
private static final Class<?>[] ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE = ACTION_VIEW_CONSTRUCTOR_SIGNATURE;
private final Object[] mActionViewConstructorArguments;
private final Object[] mActionProviderConstructorArguments;
private Context mContext;
/**
* Constructs a menu inflater.
*
* @see Activity#getMenuInflater()
*/
public MenuInflater(Context context) {
mContext = context;
mActionViewConstructorArguments = new Object[] {context};
mActionProviderConstructorArguments = mActionViewConstructorArguments;
}
/**
* Inflate a menu hierarchy from the specified XML resource. Throws
* {@link InflateException} if there is an error.
*
* @param menuRes Resource ID for an XML layout resource to load (e.g.,
* <code>R.menu.main_activity</code>)
* @param menu The Menu to inflate into. The items and submenus will be
* added to this Menu.
*/
public void inflate(int menuRes, Menu menu) {
XmlResourceParser parser = null;
try {
parser = mContext.getResources().getLayout(menuRes);
AttributeSet attrs = Xml.asAttributeSet(parser);
parseMenu(parser, attrs, menu);
} catch (XmlPullParserException e) {
throw new InflateException("Error inflating menu XML", e);
} catch (IOException e) {
throw new InflateException("Error inflating menu XML", e);
} finally {
if (parser != null) parser.close();
}
}
/**
* Called internally to fill the given menu. If a sub menu is seen, it will
* call this recursively.
*/
private void parseMenu(XmlPullParser parser, AttributeSet attrs, Menu menu)
throws XmlPullParserException, IOException {
MenuState menuState = new MenuState(menu);
int eventType = parser.getEventType();
String tagName;
boolean lookingForEndOfUnknownTag = false;
String unknownTagName = null;
// This loop will skip to the menu start tag
do {
if (eventType == XmlPullParser.START_TAG) {
tagName = parser.getName();
if (tagName.equals(XML_MENU)) {
// Go to next tag
eventType = parser.next();
break;
}
throw new RuntimeException("Expecting menu, got " + tagName);
}
eventType = parser.next();
} while (eventType != XmlPullParser.END_DOCUMENT);
boolean reachedEndOfMenu = false;
while (!reachedEndOfMenu) {
switch (eventType) {
case XmlPullParser.START_TAG:
if (lookingForEndOfUnknownTag) {
break;
}
tagName = parser.getName();
if (tagName.equals(XML_GROUP)) {
menuState.readGroup(attrs);
} else if (tagName.equals(XML_ITEM)) {
menuState.readItem(attrs);
} else if (tagName.equals(XML_MENU)) {
// A menu start tag denotes a submenu for an item
SubMenu subMenu = menuState.addSubMenuItem();
// Parse the submenu into returned SubMenu
parseMenu(parser, attrs, subMenu);
} else {
lookingForEndOfUnknownTag = true;
unknownTagName = tagName;
}
break;
case XmlPullParser.END_TAG:
tagName = parser.getName();
if (lookingForEndOfUnknownTag && tagName.equals(unknownTagName)) {
lookingForEndOfUnknownTag = false;
unknownTagName = null;
} else if (tagName.equals(XML_GROUP)) {
menuState.resetGroup();
} else if (tagName.equals(XML_ITEM)) {
// Add the item if it hasn't been added (if the item was
// a submenu, it would have been added already)
if (!menuState.hasAddedItem()) {
if (menuState.itemActionProvider != null &&
menuState.itemActionProvider.hasSubMenu()) {
menuState.addSubMenuItem();
} else {
menuState.addItem();
}
}
} else if (tagName.equals(XML_MENU)) {
reachedEndOfMenu = true;
}
break;
case XmlPullParser.END_DOCUMENT:
throw new RuntimeException("Unexpected end of document");
}
eventType = parser.next();
}
}
private static class InflatedOnMenuItemClickListener
implements MenuItem.OnMenuItemClickListener {
private static final Class<?>[] PARAM_TYPES = new Class[] { MenuItem.class };
private Context mContext;
private Method mMethod;
public InflatedOnMenuItemClickListener(Context context, String methodName) {
mContext = context;
Class<?> c = context.getClass();
try {
mMethod = c.getMethod(methodName, PARAM_TYPES);
} catch (Exception e) {
InflateException ex = new InflateException(
"Couldn't resolve menu item onClick handler " + methodName +
" in class " + c.getName());
ex.initCause(e);
throw ex;
}
}
public boolean onMenuItemClick(MenuItem item) {
try {
if (mMethod.getReturnType() == Boolean.TYPE) {
return (Boolean) mMethod.invoke(mContext, item);
} else {
mMethod.invoke(mContext, item);
return true;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
/**
* State for the current menu.
* <p>
* Groups can not be nested unless there is another menu (which will have
* its state class).
*/
private class MenuState {
private Menu menu;
/*
* Group state is set on items as they are added, allowing an item to
* override its group state. (As opposed to set on items at the group end tag.)
*/
private int groupId;
private int groupCategory;
private int groupOrder;
private int groupCheckable;
private boolean groupVisible;
private boolean groupEnabled;
private boolean itemAdded;
private int itemId;
private int itemCategoryOrder;
private CharSequence itemTitle;
private CharSequence itemTitleCondensed;
private int itemIconResId;
private char itemAlphabeticShortcut;
private char itemNumericShortcut;
/**
* Sync to attrs.xml enum:
* - 0: none
* - 1: all
* - 2: exclusive
*/
private int itemCheckable;
private boolean itemChecked;
private boolean itemVisible;
private boolean itemEnabled;
/**
* Sync to attrs.xml enum, values in MenuItem:
* - 0: never
* - 1: ifRoom
* - 2: always
* - -1: Safe sentinel for "no value".
*/
private int itemShowAsAction;
private int itemActionViewLayout;
private String itemActionViewClassName;
private String itemActionProviderClassName;
private String itemListenerMethodName;
private ActionProvider itemActionProvider;
private static final int defaultGroupId = NO_ID;
private static final int defaultItemId = NO_ID;
private static final int defaultItemCategory = 0;
private static final int defaultItemOrder = 0;
private static final int defaultItemCheckable = 0;
private static final boolean defaultItemChecked = false;
private static final boolean defaultItemVisible = true;
private static final boolean defaultItemEnabled = true;
public MenuState(final Menu menu) {
this.menu = menu;
resetGroup();
}
public void resetGroup() {
groupId = defaultGroupId;
groupCategory = defaultItemCategory;
groupOrder = defaultItemOrder;
groupCheckable = defaultItemCheckable;
groupVisible = defaultItemVisible;
groupEnabled = defaultItemEnabled;
}
/**
* Called when the parser is pointing to a group tag.
*/
public void readGroup(AttributeSet attrs) {
TypedArray a = mContext.obtainStyledAttributes(attrs,
R.styleable.SherlockMenuGroup);
groupId = a.getResourceId(R.styleable.SherlockMenuGroup_android_id, defaultGroupId);
groupCategory = a.getInt(R.styleable.SherlockMenuGroup_android_menuCategory, defaultItemCategory);
groupOrder = a.getInt(R.styleable.SherlockMenuGroup_android_orderInCategory, defaultItemOrder);
groupCheckable = a.getInt(R.styleable.SherlockMenuGroup_android_checkableBehavior, defaultItemCheckable);
groupVisible = a.getBoolean(R.styleable.SherlockMenuGroup_android_visible, defaultItemVisible);
groupEnabled = a.getBoolean(R.styleable.SherlockMenuGroup_android_enabled, defaultItemEnabled);
a.recycle();
}
/**
* Called when the parser is pointing to an item tag.
*/
public void readItem(AttributeSet attrs) {
TypedArray a = mContext.obtainStyledAttributes(attrs,
R.styleable.SherlockMenuItem);
// Inherit attributes from the group as default value
itemId = a.getResourceId(R.styleable.SherlockMenuItem_android_id, defaultItemId);
final int category = a.getInt(R.styleable.SherlockMenuItem_android_menuCategory, groupCategory);
final int order = a.getInt(R.styleable.SherlockMenuItem_android_orderInCategory, groupOrder);
itemCategoryOrder = (category & Menu.CATEGORY_MASK) | (order & Menu.USER_MASK);
itemTitle = a.getText(R.styleable.SherlockMenuItem_android_title);
itemTitleCondensed = a.getText(R.styleable.SherlockMenuItem_android_titleCondensed);
itemIconResId = a.getResourceId(R.styleable.SherlockMenuItem_android_icon, 0);
itemAlphabeticShortcut =
getShortcut(a.getString(R.styleable.SherlockMenuItem_android_alphabeticShortcut));
itemNumericShortcut =
getShortcut(a.getString(R.styleable.SherlockMenuItem_android_numericShortcut));
if (a.hasValue(R.styleable.SherlockMenuItem_android_checkable)) {
// Item has attribute checkable, use it
itemCheckable = a.getBoolean(R.styleable.SherlockMenuItem_android_checkable, false) ? 1 : 0;
} else {
// Item does not have attribute, use the group's (group can have one more state
// for checkable that represents the exclusive checkable)
itemCheckable = groupCheckable;
}
itemChecked = a.getBoolean(R.styleable.SherlockMenuItem_android_checked, defaultItemChecked);
itemVisible = a.getBoolean(R.styleable.SherlockMenuItem_android_visible, groupVisible);
itemEnabled = a.getBoolean(R.styleable.SherlockMenuItem_android_enabled, groupEnabled);
TypedValue value = new TypedValue();
a.getValue(R.styleable.SherlockMenuItem_android_showAsAction, value);
itemShowAsAction = value.type == TypedValue.TYPE_INT_HEX ? value.data : -1;
itemListenerMethodName = a.getString(R.styleable.SherlockMenuItem_android_onClick);
itemActionViewLayout = a.getResourceId(R.styleable.SherlockMenuItem_android_actionLayout, 0);
itemActionViewClassName = a.getString(R.styleable.SherlockMenuItem_android_actionViewClass);
itemActionProviderClassName = a.getString(R.styleable.SherlockMenuItem_android_actionProviderClass);
final boolean hasActionProvider = itemActionProviderClassName != null;
if (hasActionProvider && itemActionViewLayout == 0 && itemActionViewClassName == null) {
itemActionProvider = newInstance(itemActionProviderClassName,
ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE,
mActionProviderConstructorArguments);
} else {
if (hasActionProvider) {
Log.w(LOG_TAG, "Ignoring attribute 'actionProviderClass'."
+ " Action view already specified.");
}
itemActionProvider = null;
}
a.recycle();
itemAdded = false;
}
private char getShortcut(String shortcutString) {
if (shortcutString == null) {
return 0;
} else {
return shortcutString.charAt(0);
}
}
private void setItem(MenuItem item) {
item.setChecked(itemChecked)
.setVisible(itemVisible)
.setEnabled(itemEnabled)
.setCheckable(itemCheckable >= 1)
.setTitleCondensed(itemTitleCondensed)
.setIcon(itemIconResId)
.setAlphabeticShortcut(itemAlphabeticShortcut)
.setNumericShortcut(itemNumericShortcut);
if (itemShowAsAction >= 0) {
item.setShowAsAction(itemShowAsAction);
}
if (itemListenerMethodName != null) {
if (mContext.isRestricted()) {
throw new IllegalStateException("The android:onClick attribute cannot "
+ "be used within a restricted context");
}
item.setOnMenuItemClickListener(
new InflatedOnMenuItemClickListener(mContext, itemListenerMethodName));
}
if (itemCheckable >= 2) {
if (item instanceof MenuItemImpl) {
MenuItemImpl impl = (MenuItemImpl) item;
impl.setExclusiveCheckable(true);
} else {
menu.setGroupCheckable(groupId, true, true);
}
}
boolean actionViewSpecified = false;
if (itemActionViewClassName != null) {
View actionView = (View) newInstance(itemActionViewClassName,
ACTION_VIEW_CONSTRUCTOR_SIGNATURE, mActionViewConstructorArguments);
item.setActionView(actionView);
actionViewSpecified = true;
}
if (itemActionViewLayout > 0) {
if (!actionViewSpecified) {
item.setActionView(itemActionViewLayout);
actionViewSpecified = true;
} else {
Log.w(LOG_TAG, "Ignoring attribute 'itemActionViewLayout'."
+ " Action view already specified.");
}
}
if (itemActionProvider != null) {
item.setActionProvider(itemActionProvider);
}
}
public void addItem() {
itemAdded = true;
setItem(menu.add(groupId, itemId, itemCategoryOrder, itemTitle));
}
public SubMenu addSubMenuItem() {
itemAdded = true;
SubMenu subMenu = menu.addSubMenu(groupId, itemId, itemCategoryOrder, itemTitle);
setItem(subMenu.getItem());
return subMenu;
}
public boolean hasAddedItem() {
return itemAdded;
}
@SuppressWarnings("unchecked")
private <T> T newInstance(String className, Class<?>[] constructorSignature,
Object[] arguments) {
try {
Class<?> clazz = mContext.getClassLoader().loadClass(className);
Constructor<?> constructor = clazz.getConstructor(constructorSignature);
return (T) constructor.newInstance(arguments);
} catch (Exception e) {
Log.w(LOG_TAG, "Cannot instantiate class: " + className, e);
}
return null;
}
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/view/MenuInflater.java | Java | asf20 | 19,430 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.view;
import android.content.Context;
import android.view.View;
/**
* This class is a mediator for accomplishing a given task, for example sharing a file.
* It is responsible for creating a view that performs an action that accomplishes the task.
* This class also implements other functions such a performing a default action.
* <p>
* An ActionProvider can be optionally specified for a {@link MenuItem} and in such a
* case it will be responsible for creating the action view that appears in the
* {@link android.app.ActionBar} as a substitute for the menu item when the item is
* displayed as an action item. Also the provider is responsible for performing a
* default action if a menu item placed on the overflow menu of the ActionBar is
* selected and none of the menu item callbacks has handled the selection. For this
* case the provider can also optionally provide a sub-menu for accomplishing the
* task at hand.
* </p>
* <p>
* There are two ways for using an action provider for creating and handling of action views:
* <ul>
* <li>
* Setting the action provider on a {@link MenuItem} directly by calling
* {@link MenuItem#setActionProvider(ActionProvider)}.
* </li>
* <li>
* Declaring the action provider in the menu XML resource. For example:
* <pre>
* <code>
* <item android:id="@+id/my_menu_item"
* android:title="Title"
* android:icon="@drawable/my_menu_item_icon"
* android:showAsAction="ifRoom"
* android:actionProviderClass="foo.bar.SomeActionProvider" />
* </code>
* </pre>
* </li>
* </ul>
* </p>
*
* @see MenuItem#setActionProvider(ActionProvider)
* @see MenuItem#getActionProvider()
*/
public abstract class ActionProvider {
private SubUiVisibilityListener mSubUiVisibilityListener;
/**
* Creates a new instance.
*
* @param context Context for accessing resources.
*/
public ActionProvider(Context context) {
}
/**
* Factory method for creating new action views.
*
* @return A new action view.
*/
public abstract View onCreateActionView();
/**
* Performs an optional default action.
* <p>
* For the case of an action provider placed in a menu item not shown as an action this
* method is invoked if previous callbacks for processing menu selection has handled
* the event.
* </p>
* <p>
* A menu item selection is processed in the following order:
* <ul>
* <li>
* Receiving a call to {@link MenuItem.OnMenuItemClickListener#onMenuItemClick
* MenuItem.OnMenuItemClickListener.onMenuItemClick}.
* </li>
* <li>
* Receiving a call to {@link android.app.Activity#onOptionsItemSelected(MenuItem)
* Activity.onOptionsItemSelected(MenuItem)}
* </li>
* <li>
* Receiving a call to {@link android.app.Fragment#onOptionsItemSelected(MenuItem)
* Fragment.onOptionsItemSelected(MenuItem)}
* </li>
* <li>
* Launching the {@link android.content.Intent} set via
* {@link MenuItem#setIntent(android.content.Intent) MenuItem.setIntent(android.content.Intent)}
* </li>
* <li>
* Invoking this method.
* </li>
* </ul>
* </p>
* <p>
* The default implementation does not perform any action and returns false.
* </p>
*/
public boolean onPerformDefaultAction() {
return false;
}
/**
* Determines if this ActionProvider has a submenu associated with it.
*
* <p>Associated submenus will be shown when an action view is not. This
* provider instance will receive a call to {@link #onPrepareSubMenu(SubMenu)}
* after the call to {@link #onPerformDefaultAction()} and before a submenu is
* displayed to the user.
*
* @return true if the item backed by this provider should have an associated submenu
*/
public boolean hasSubMenu() {
return false;
}
/**
* Called to prepare an associated submenu for the menu item backed by this ActionProvider.
*
* <p>if {@link #hasSubMenu()} returns true, this method will be called when the
* menu item is selected to prepare the submenu for presentation to the user. Apps
* may use this to create or alter submenu content right before display.
*
* @param subMenu Submenu that will be displayed
*/
public void onPrepareSubMenu(SubMenu subMenu) {
}
/**
* Notify the system that the visibility of an action view's sub-UI such as
* an anchored popup has changed. This will affect how other system
* visibility notifications occur.
*
* @hide Pending future API approval
*/
public void subUiVisibilityChanged(boolean isVisible) {
if (mSubUiVisibilityListener != null) {
mSubUiVisibilityListener.onSubUiVisibilityChanged(isVisible);
}
}
/**
* @hide Internal use only
*/
public void setSubUiVisibilityListener(SubUiVisibilityListener listener) {
mSubUiVisibilityListener = listener;
}
/**
* @hide Internal use only
*/
public interface SubUiVisibilityListener {
public void onSubUiVisibilityChanged(boolean isVisible);
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/view/ActionProvider.java | Java | asf20 | 5,865 |
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.view;
import android.content.ComponentName;
import android.content.Intent;
import android.view.KeyEvent;
/**
* Interface for managing the items in a menu.
* <p>
* By default, every Activity supports an options menu of actions or options.
* You can add items to this menu and handle clicks on your additions. The
* easiest way of adding menu items is inflating an XML file into the
* {@link Menu} via {@link MenuInflater}. The easiest way of attaching code to
* clicks is via {@link Activity#onOptionsItemSelected(MenuItem)} and
* {@link Activity#onContextItemSelected(MenuItem)}.
* <p>
* Different menu types support different features:
* <ol>
* <li><b>Context menus</b>: Do not support item shortcuts and item icons.
* <li><b>Options menus</b>: The <b>icon menus</b> do not support item check
* marks and only show the item's
* {@link MenuItem#setTitleCondensed(CharSequence) condensed title}. The
* <b>expanded menus</b> (only available if six or more menu items are visible,
* reached via the 'More' item in the icon menu) do not show item icons, and
* item check marks are discouraged.
* <li><b>Sub menus</b>: Do not support item icons, or nested sub menus.
* </ol>
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For more information about creating menus, read the
* <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide.</p>
* </div>
*/
public interface Menu {
/**
* This is the part of an order integer that the user can provide.
* @hide
*/
static final int USER_MASK = 0x0000ffff;
/**
* Bit shift of the user portion of the order integer.
* @hide
*/
static final int USER_SHIFT = 0;
/**
* This is the part of an order integer that supplies the category of the
* item.
* @hide
*/
static final int CATEGORY_MASK = 0xffff0000;
/**
* Bit shift of the category portion of the order integer.
* @hide
*/
static final int CATEGORY_SHIFT = 16;
/**
* Value to use for group and item identifier integers when you don't care
* about them.
*/
static final int NONE = 0;
/**
* First value for group and item identifier integers.
*/
static final int FIRST = 1;
// Implementation note: Keep these CATEGORY_* in sync with the category enum
// in attrs.xml
/**
* Category code for the order integer for items/groups that are part of a
* container -- or/add this with your base value.
*/
static final int CATEGORY_CONTAINER = 0x00010000;
/**
* Category code for the order integer for items/groups that are provided by
* the system -- or/add this with your base value.
*/
static final int CATEGORY_SYSTEM = 0x00020000;
/**
* Category code for the order integer for items/groups that are
* user-supplied secondary (infrequently used) options -- or/add this with
* your base value.
*/
static final int CATEGORY_SECONDARY = 0x00030000;
/**
* Category code for the order integer for items/groups that are
* alternative actions on the data that is currently displayed -- or/add
* this with your base value.
*/
static final int CATEGORY_ALTERNATIVE = 0x00040000;
/**
* Flag for {@link #addIntentOptions}: if set, do not automatically remove
* any existing menu items in the same group.
*/
static final int FLAG_APPEND_TO_GROUP = 0x0001;
/**
* Flag for {@link #performShortcut}: if set, do not close the menu after
* executing the shortcut.
*/
static final int FLAG_PERFORM_NO_CLOSE = 0x0001;
/**
* Flag for {@link #performShortcut(int, KeyEvent, int)}: if set, always
* close the menu after executing the shortcut. Closing the menu also resets
* the prepared state.
*/
static final int FLAG_ALWAYS_PERFORM_CLOSE = 0x0002;
/**
* Add a new item to the menu. This item displays the given title for its
* label.
*
* @param title The text to display for the item.
* @return The newly added menu item.
*/
public MenuItem add(CharSequence title);
/**
* Add a new item to the menu. This item displays the given title for its
* label.
*
* @param titleRes Resource identifier of title string.
* @return The newly added menu item.
*/
public MenuItem add(int titleRes);
/**
* Add a new item to the menu. This item displays the given title for its
* label.
*
* @param groupId The group identifier that this item should be part of.
* This can be used to define groups of items for batch state
* changes. Normally use {@link #NONE} if an item should not be in a
* group.
* @param itemId Unique item ID. Use {@link #NONE} if you do not need a
* unique ID.
* @param order The order for the item. Use {@link #NONE} if you do not care
* about the order. See {@link MenuItem#getOrder()}.
* @param title The text to display for the item.
* @return The newly added menu item.
*/
public MenuItem add(int groupId, int itemId, int order, CharSequence title);
/**
* Variation on {@link #add(int, int, int, CharSequence)} that takes a
* string resource identifier instead of the string itself.
*
* @param groupId The group identifier that this item should be part of.
* This can also be used to define groups of items for batch state
* changes. Normally use {@link #NONE} if an item should not be in a
* group.
* @param itemId Unique item ID. Use {@link #NONE} if you do not need a
* unique ID.
* @param order The order for the item. Use {@link #NONE} if you do not care
* about the order. See {@link MenuItem#getOrder()}.
* @param titleRes Resource identifier of title string.
* @return The newly added menu item.
*/
public MenuItem add(int groupId, int itemId, int order, int titleRes);
/**
* Add a new sub-menu to the menu. This item displays the given title for
* its label. To modify other attributes on the submenu's menu item, use
* {@link SubMenu#getItem()}.
*
* @param title The text to display for the item.
* @return The newly added sub-menu
*/
SubMenu addSubMenu(final CharSequence title);
/**
* Add a new sub-menu to the menu. This item displays the given title for
* its label. To modify other attributes on the submenu's menu item, use
* {@link SubMenu#getItem()}.
*
* @param titleRes Resource identifier of title string.
* @return The newly added sub-menu
*/
SubMenu addSubMenu(final int titleRes);
/**
* Add a new sub-menu to the menu. This item displays the given
* <var>title</var> for its label. To modify other attributes on the
* submenu's menu item, use {@link SubMenu#getItem()}.
*<p>
* Note that you can only have one level of sub-menus, i.e. you cannnot add
* a subMenu to a subMenu: An {@link UnsupportedOperationException} will be
* thrown if you try.
*
* @param groupId The group identifier that this item should be part of.
* This can also be used to define groups of items for batch state
* changes. Normally use {@link #NONE} if an item should not be in a
* group.
* @param itemId Unique item ID. Use {@link #NONE} if you do not need a
* unique ID.
* @param order The order for the item. Use {@link #NONE} if you do not care
* about the order. See {@link MenuItem#getOrder()}.
* @param title The text to display for the item.
* @return The newly added sub-menu
*/
SubMenu addSubMenu(final int groupId, final int itemId, int order, final CharSequence title);
/**
* Variation on {@link #addSubMenu(int, int, int, CharSequence)} that takes
* a string resource identifier for the title instead of the string itself.
*
* @param groupId The group identifier that this item should be part of.
* This can also be used to define groups of items for batch state
* changes. Normally use {@link #NONE} if an item should not be in a group.
* @param itemId Unique item ID. Use {@link #NONE} if you do not need a unique ID.
* @param order The order for the item. Use {@link #NONE} if you do not care about the
* order. See {@link MenuItem#getOrder()}.
* @param titleRes Resource identifier of title string.
* @return The newly added sub-menu
*/
SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes);
/**
* Add a group of menu items corresponding to actions that can be performed
* for a particular Intent. The Intent is most often configured with a null
* action, the data that the current activity is working with, and includes
* either the {@link Intent#CATEGORY_ALTERNATIVE} or
* {@link Intent#CATEGORY_SELECTED_ALTERNATIVE} to find activities that have
* said they would like to be included as optional action. You can, however,
* use any Intent you want.
*
* <p>
* See {@link android.content.pm.PackageManager#queryIntentActivityOptions}
* for more * details on the <var>caller</var>, <var>specifics</var>, and
* <var>intent</var> arguments. The list returned by that function is used
* to populate the resulting menu items.
*
* <p>
* All of the menu items of possible options for the intent will be added
* with the given group and id. You can use the group to control ordering of
* the items in relation to other items in the menu. Normally this function
* will automatically remove any existing items in the menu in the same
* group and place a divider above and below the added items; this behavior
* can be modified with the <var>flags</var> parameter. For each of the
* generated items {@link MenuItem#setIntent} is called to associate the
* appropriate Intent with the item; this means the activity will
* automatically be started for you without having to do anything else.
*
* @param groupId The group identifier that the items should be part of.
* This can also be used to define groups of items for batch state
* changes. Normally use {@link #NONE} if the items should not be in
* a group.
* @param itemId Unique item ID. Use {@link #NONE} if you do not need a
* unique ID.
* @param order The order for the items. Use {@link #NONE} if you do not
* care about the order. See {@link MenuItem#getOrder()}.
* @param caller The current activity component name as defined by
* queryIntentActivityOptions().
* @param specifics Specific items to place first as defined by
* queryIntentActivityOptions().
* @param intent Intent describing the kinds of items to populate in the
* list as defined by queryIntentActivityOptions().
* @param flags Additional options controlling how the items are added.
* @param outSpecificItems Optional array in which to place the menu items
* that were generated for each of the <var>specifics</var> that were
* requested. Entries may be null if no activity was found for that
* specific action.
* @return The number of menu items that were added.
*
* @see #FLAG_APPEND_TO_GROUP
* @see MenuItem#setIntent
* @see android.content.pm.PackageManager#queryIntentActivityOptions
*/
public int addIntentOptions(int groupId, int itemId, int order,
ComponentName caller, Intent[] specifics,
Intent intent, int flags, MenuItem[] outSpecificItems);
/**
* Remove the item with the given identifier.
*
* @param id The item to be removed. If there is no item with this
* identifier, nothing happens.
*/
public void removeItem(int id);
/**
* Remove all items in the given group.
*
* @param groupId The group to be removed. If there are no items in this
* group, nothing happens.
*/
public void removeGroup(int groupId);
/**
* Remove all existing items from the menu, leaving it empty as if it had
* just been created.
*/
public void clear();
/**
* Control whether a particular group of items can show a check mark. This
* is similar to calling {@link MenuItem#setCheckable} on all of the menu items
* with the given group identifier, but in addition you can control whether
* this group contains a mutually-exclusive set items. This should be called
* after the items of the group have been added to the menu.
*
* @param group The group of items to operate on.
* @param checkable Set to true to allow a check mark, false to
* disallow. The default is false.
* @param exclusive If set to true, only one item in this group can be
* checked at a time; checking an item will automatically
* uncheck all others in the group. If set to false, each
* item can be checked independently of the others.
*
* @see MenuItem#setCheckable
* @see MenuItem#setChecked
*/
public void setGroupCheckable(int group, boolean checkable, boolean exclusive);
/**
* Show or hide all menu items that are in the given group.
*
* @param group The group of items to operate on.
* @param visible If true the items are visible, else they are hidden.
*
* @see MenuItem#setVisible
*/
public void setGroupVisible(int group, boolean visible);
/**
* Enable or disable all menu items that are in the given group.
*
* @param group The group of items to operate on.
* @param enabled If true the items will be enabled, else they will be disabled.
*
* @see MenuItem#setEnabled
*/
public void setGroupEnabled(int group, boolean enabled);
/**
* Return whether the menu currently has item items that are visible.
*
* @return True if there is one or more item visible,
* else false.
*/
public boolean hasVisibleItems();
/**
* Return the menu item with a particular identifier.
*
* @param id The identifier to find.
*
* @return The menu item object, or null if there is no item with
* this identifier.
*/
public MenuItem findItem(int id);
/**
* Get the number of items in the menu. Note that this will change any
* times items are added or removed from the menu.
*
* @return The item count.
*/
public int size();
/**
* Gets the menu item at the given index.
*
* @param index The index of the menu item to return.
* @return The menu item.
* @exception IndexOutOfBoundsException
* when {@code index < 0 || >= size()}
*/
public MenuItem getItem(int index);
/**
* Closes the menu, if open.
*/
public void close();
/**
* Execute the menu item action associated with the given shortcut
* character.
*
* @param keyCode The keycode of the shortcut key.
* @param event Key event message.
* @param flags Additional option flags or 0.
*
* @return If the given shortcut exists and is shown, returns
* true; else returns false.
*
* @see #FLAG_PERFORM_NO_CLOSE
*/
public boolean performShortcut(int keyCode, KeyEvent event, int flags);
/**
* Is a keypress one of the defined shortcut keys for this window.
* @param keyCode the key code from {@link KeyEvent} to check.
* @param event the {@link KeyEvent} to use to help check.
*/
boolean isShortcutKey(int keyCode, KeyEvent event);
/**
* Execute the menu item action associated with the given menu identifier.
*
* @param id Identifier associated with the menu item.
* @param flags Additional option flags or 0.
*
* @return If the given identifier exists and is shown, returns
* true; else returns false.
*
* @see #FLAG_PERFORM_NO_CLOSE
*/
public boolean performIdentifierAction(int id, int flags);
/**
* Control whether the menu should be running in qwerty mode (alphabetic
* shortcuts) or 12-key mode (numeric shortcuts).
*
* @param isQwerty If true the menu will use alphabetic shortcuts; else it
* will use numeric shortcuts.
*/
public void setQwertyMode(boolean isQwerty);
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/view/Menu.java | Java | asf20 | 17,460 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.view;
import android.view.View;
/**
* Represents a contextual mode of the user interface. Action modes can be used for
* modal interactions with content and replace parts of the normal UI until finished.
* Examples of good action modes include selection modes, search, content editing, etc.
*/
public abstract class ActionMode {
private Object mTag;
/**
* Set a tag object associated with this ActionMode.
*
* <p>Like the tag available to views, this allows applications to associate arbitrary
* data with an ActionMode for later reference.
*
* @param tag Tag to associate with this ActionMode
*
* @see #getTag()
*/
public void setTag(Object tag) {
mTag = tag;
}
/**
* Retrieve the tag object associated with this ActionMode.
*
* <p>Like the tag available to views, this allows applications to associate arbitrary
* data with an ActionMode for later reference.
*
* @return Tag associated with this ActionMode
*
* @see #setTag(Object)
*/
public Object getTag() {
return mTag;
}
/**
* Set the title of the action mode. This method will have no visible effect if
* a custom view has been set.
*
* @param title Title string to set
*
* @see #setTitle(int)
* @see #setCustomView(View)
*/
public abstract void setTitle(CharSequence title);
/**
* Set the title of the action mode. This method will have no visible effect if
* a custom view has been set.
*
* @param resId Resource ID of a string to set as the title
*
* @see #setTitle(CharSequence)
* @see #setCustomView(View)
*/
public abstract void setTitle(int resId);
/**
* Set the subtitle of the action mode. This method will have no visible effect if
* a custom view has been set.
*
* @param subtitle Subtitle string to set
*
* @see #setSubtitle(int)
* @see #setCustomView(View)
*/
public abstract void setSubtitle(CharSequence subtitle);
/**
* Set the subtitle of the action mode. This method will have no visible effect if
* a custom view has been set.
*
* @param resId Resource ID of a string to set as the subtitle
*
* @see #setSubtitle(CharSequence)
* @see #setCustomView(View)
*/
public abstract void setSubtitle(int resId);
/**
* Set a custom view for this action mode. The custom view will take the place of
* the title and subtitle. Useful for things like search boxes.
*
* @param view Custom view to use in place of the title/subtitle.
*
* @see #setTitle(CharSequence)
* @see #setSubtitle(CharSequence)
*/
public abstract void setCustomView(View view);
/**
* Invalidate the action mode and refresh menu content. The mode's
* {@link ActionMode.Callback} will have its
* {@link Callback#onPrepareActionMode(ActionMode, Menu)} method called.
* If it returns true the menu will be scanned for updated content and any relevant changes
* will be reflected to the user.
*/
public abstract void invalidate();
/**
* Finish and close this action mode. The action mode's {@link ActionMode.Callback} will
* have its {@link Callback#onDestroyActionMode(ActionMode)} method called.
*/
public abstract void finish();
/**
* Returns the menu of actions that this action mode presents.
* @return The action mode's menu.
*/
public abstract Menu getMenu();
/**
* Returns the current title of this action mode.
* @return Title text
*/
public abstract CharSequence getTitle();
/**
* Returns the current subtitle of this action mode.
* @return Subtitle text
*/
public abstract CharSequence getSubtitle();
/**
* Returns the current custom view for this action mode.
* @return The current custom view
*/
public abstract View getCustomView();
/**
* Returns a {@link MenuInflater} with the ActionMode's context.
*/
public abstract MenuInflater getMenuInflater();
/**
* Returns whether the UI presenting this action mode can take focus or not.
* This is used by internal components within the framework that would otherwise
* present an action mode UI that requires focus, such as an EditText as a custom view.
*
* @return true if the UI used to show this action mode can take focus
* @hide Internal use only
*/
public boolean isUiFocusable() {
return true;
}
/**
* Callback interface for action modes. Supplied to
* {@link View#startActionMode(Callback)}, a Callback
* configures and handles events raised by a user's interaction with an action mode.
*
* <p>An action mode's lifecycle is as follows:
* <ul>
* <li>{@link Callback#onCreateActionMode(ActionMode, Menu)} once on initial
* creation</li>
* <li>{@link Callback#onPrepareActionMode(ActionMode, Menu)} after creation
* and any time the {@link ActionMode} is invalidated</li>
* <li>{@link Callback#onActionItemClicked(ActionMode, MenuItem)} any time a
* contextual action button is clicked</li>
* <li>{@link Callback#onDestroyActionMode(ActionMode)} when the action mode
* is closed</li>
* </ul>
*/
public interface Callback {
/**
* Called when action mode is first created. The menu supplied will be used to
* generate action buttons for the action mode.
*
* @param mode ActionMode being created
* @param menu Menu used to populate action buttons
* @return true if the action mode should be created, false if entering this
* mode should be aborted.
*/
public boolean onCreateActionMode(ActionMode mode, Menu menu);
/**
* Called to refresh an action mode's action menu whenever it is invalidated.
*
* @param mode ActionMode being prepared
* @param menu Menu used to populate action buttons
* @return true if the menu or action mode was updated, false otherwise.
*/
public boolean onPrepareActionMode(ActionMode mode, Menu menu);
/**
* Called to report a user click on an action button.
*
* @param mode The current ActionMode
* @param item The item that was clicked
* @return true if this callback handled the event, false if the standard MenuItem
* invocation should continue.
*/
public boolean onActionItemClicked(ActionMode mode, MenuItem item);
/**
* Called when an action mode is about to be exited and destroyed.
*
* @param mode The current ActionMode being destroyed
*/
public void onDestroyActionMode(ActionMode mode);
}
} | 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/view/ActionMode.java | Java | asf20 | 7,820 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.view;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
/**
* Interface for direct access to a previously created menu item.
* <p>
* An Item is returned by calling one of the {@link android.view.Menu#add}
* methods.
* <p>
* For a feature set of specific menu types, see {@link Menu}.
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For information about creating menus, read the
* <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide.</p>
* </div>
*/
public interface MenuItem {
/*
* These should be kept in sync with attrs.xml enum constants for showAsAction
*/
/** Never show this item as a button in an Action Bar. */
public static final int SHOW_AS_ACTION_NEVER = android.view.MenuItem.SHOW_AS_ACTION_NEVER;
/** Show this item as a button in an Action Bar if the system decides there is room for it. */
public static final int SHOW_AS_ACTION_IF_ROOM = android.view.MenuItem.SHOW_AS_ACTION_IF_ROOM;
/**
* Always show this item as a button in an Action Bar.
* Use sparingly! If too many items are set to always show in the Action Bar it can
* crowd the Action Bar and degrade the user experience on devices with smaller screens.
* A good rule of thumb is to have no more than 2 items set to always show at a time.
*/
public static final int SHOW_AS_ACTION_ALWAYS = android.view.MenuItem.SHOW_AS_ACTION_ALWAYS;
/**
* When this item is in the action bar, always show it with a text label even if
* it also has an icon specified.
*/
public static final int SHOW_AS_ACTION_WITH_TEXT = android.view.MenuItem.SHOW_AS_ACTION_WITH_TEXT;
/**
* This item's action view collapses to a normal menu item.
* When expanded, the action view temporarily takes over
* a larger segment of its container.
*/
public static final int SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW = android.view.MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW;
/**
* Interface definition for a callback to be invoked when a menu item is
* clicked.
*
* @see Activity#onContextItemSelected(MenuItem)
* @see Activity#onOptionsItemSelected(MenuItem)
*/
public interface OnMenuItemClickListener {
/**
* Called when a menu item has been invoked. This is the first code
* that is executed; if it returns true, no other callbacks will be
* executed.
*
* @param item The menu item that was invoked.
*
* @return Return true to consume this click and prevent others from
* executing.
*/
public boolean onMenuItemClick(MenuItem item);
}
/**
* Interface definition for a callback to be invoked when a menu item
* marked with {@link MenuItem#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW} is
* expanded or collapsed.
*
* @see MenuItem#expandActionView()
* @see MenuItem#collapseActionView()
* @see MenuItem#setShowAsActionFlags(int)
*/
public interface OnActionExpandListener {
/**
* Called when a menu item with {@link MenuItem#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}
* is expanded.
* @param item Item that was expanded
* @return true if the item should expand, false if expansion should be suppressed.
*/
public boolean onMenuItemActionExpand(MenuItem item);
/**
* Called when a menu item with {@link MenuItem#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}
* is collapsed.
* @param item Item that was collapsed
* @return true if the item should collapse, false if collapsing should be suppressed.
*/
public boolean onMenuItemActionCollapse(MenuItem item);
}
/**
* Return the identifier for this menu item. The identifier can not
* be changed after the menu is created.
*
* @return The menu item's identifier.
*/
public int getItemId();
/**
* Return the group identifier that this menu item is part of. The group
* identifier can not be changed after the menu is created.
*
* @return The menu item's group identifier.
*/
public int getGroupId();
/**
* Return the category and order within the category of this item. This
* item will be shown before all items (within its category) that have
* order greater than this value.
* <p>
* An order integer contains the item's category (the upper bits of the
* integer; set by or/add the category with the order within the
* category) and the ordering of the item within that category (the
* lower bits). Example categories are {@link Menu#CATEGORY_SYSTEM},
* {@link Menu#CATEGORY_SECONDARY}, {@link Menu#CATEGORY_ALTERNATIVE},
* {@link Menu#CATEGORY_CONTAINER}. See {@link Menu} for a full list.
*
* @return The order of this item.
*/
public int getOrder();
/**
* Change the title associated with this item.
*
* @param title The new text to be displayed.
* @return This Item so additional setters can be called.
*/
public MenuItem setTitle(CharSequence title);
/**
* Change the title associated with this item.
* <p>
* Some menu types do not sufficient space to show the full title, and
* instead a condensed title is preferred. See {@link Menu} for more
* information.
*
* @param title The resource id of the new text to be displayed.
* @return This Item so additional setters can be called.
* @see #setTitleCondensed(CharSequence)
*/
public MenuItem setTitle(int title);
/**
* Retrieve the current title of the item.
*
* @return The title.
*/
public CharSequence getTitle();
/**
* Change the condensed title associated with this item. The condensed
* title is used in situations where the normal title may be too long to
* be displayed.
*
* @param title The new text to be displayed as the condensed title.
* @return This Item so additional setters can be called.
*/
public MenuItem setTitleCondensed(CharSequence title);
/**
* Retrieve the current condensed title of the item. If a condensed
* title was never set, it will return the normal title.
*
* @return The condensed title, if it exists.
* Otherwise the normal title.
*/
public CharSequence getTitleCondensed();
/**
* Change the icon associated with this item. This icon will not always be
* shown, so the title should be sufficient in describing this item. See
* {@link Menu} for the menu types that support icons.
*
* @param icon The new icon (as a Drawable) to be displayed.
* @return This Item so additional setters can be called.
*/
public MenuItem setIcon(Drawable icon);
/**
* Change the icon associated with this item. This icon will not always be
* shown, so the title should be sufficient in describing this item. See
* {@link Menu} for the menu types that support icons.
* <p>
* This method will set the resource ID of the icon which will be used to
* lazily get the Drawable when this item is being shown.
*
* @param iconRes The new icon (as a resource ID) to be displayed.
* @return This Item so additional setters can be called.
*/
public MenuItem setIcon(int iconRes);
/**
* Returns the icon for this item as a Drawable (getting it from resources if it hasn't been
* loaded before).
*
* @return The icon as a Drawable.
*/
public Drawable getIcon();
/**
* Change the Intent associated with this item. By default there is no
* Intent associated with a menu item. If you set one, and nothing
* else handles the item, then the default behavior will be to call
* {@link android.content.Context#startActivity} with the given Intent.
*
* <p>Note that setIntent() can not be used with the versions of
* {@link Menu#add} that take a Runnable, because {@link Runnable#run}
* does not return a value so there is no way to tell if it handled the
* item. In this case it is assumed that the Runnable always handles
* the item, and the intent will never be started.
*
* @see #getIntent
* @param intent The Intent to associated with the item. This Intent
* object is <em>not</em> copied, so be careful not to
* modify it later.
* @return This Item so additional setters can be called.
*/
public MenuItem setIntent(Intent intent);
/**
* Return the Intent associated with this item. This returns a
* reference to the Intent which you can change as desired to modify
* what the Item is holding.
*
* @see #setIntent
* @return Returns the last value supplied to {@link #setIntent}, or
* null.
*/
public Intent getIntent();
/**
* Change both the numeric and alphabetic shortcut associated with this
* item. Note that the shortcut will be triggered when the key that
* generates the given character is pressed alone or along with with the alt
* key. Also note that case is not significant and that alphabetic shortcut
* characters will be displayed in lower case.
* <p>
* See {@link Menu} for the menu types that support shortcuts.
*
* @param numericChar The numeric shortcut key. This is the shortcut when
* using a numeric (e.g., 12-key) keyboard.
* @param alphaChar The alphabetic shortcut key. This is the shortcut when
* using a keyboard with alphabetic keys.
* @return This Item so additional setters can be called.
*/
public MenuItem setShortcut(char numericChar, char alphaChar);
/**
* Change the numeric shortcut associated with this item.
* <p>
* See {@link Menu} for the menu types that support shortcuts.
*
* @param numericChar The numeric shortcut key. This is the shortcut when
* using a 12-key (numeric) keyboard.
* @return This Item so additional setters can be called.
*/
public MenuItem setNumericShortcut(char numericChar);
/**
* Return the char for this menu item's numeric (12-key) shortcut.
*
* @return Numeric character to use as a shortcut.
*/
public char getNumericShortcut();
/**
* Change the alphabetic shortcut associated with this item. The shortcut
* will be triggered when the key that generates the given character is
* pressed alone or along with with the alt key. Case is not significant and
* shortcut characters will be displayed in lower case. Note that menu items
* with the characters '\b' or '\n' as shortcuts will get triggered by the
* Delete key or Carriage Return key, respectively.
* <p>
* See {@link Menu} for the menu types that support shortcuts.
*
* @param alphaChar The alphabetic shortcut key. This is the shortcut when
* using a keyboard with alphabetic keys.
* @return This Item so additional setters can be called.
*/
public MenuItem setAlphabeticShortcut(char alphaChar);
/**
* Return the char for this menu item's alphabetic shortcut.
*
* @return Alphabetic character to use as a shortcut.
*/
public char getAlphabeticShortcut();
/**
* Control whether this item can display a check mark. Setting this does
* not actually display a check mark (see {@link #setChecked} for that);
* rather, it ensures there is room in the item in which to display a
* check mark.
* <p>
* See {@link Menu} for the menu types that support check marks.
*
* @param checkable Set to true to allow a check mark, false to
* disallow. The default is false.
* @see #setChecked
* @see #isCheckable
* @see Menu#setGroupCheckable
* @return This Item so additional setters can be called.
*/
public MenuItem setCheckable(boolean checkable);
/**
* Return whether the item can currently display a check mark.
*
* @return If a check mark can be displayed, returns true.
*
* @see #setCheckable
*/
public boolean isCheckable();
/**
* Control whether this item is shown with a check mark. Note that you
* must first have enabled checking with {@link #setCheckable} or else
* the check mark will not appear. If this item is a member of a group that contains
* mutually-exclusive items (set via {@link Menu#setGroupCheckable(int, boolean, boolean)},
* the other items in the group will be unchecked.
* <p>
* See {@link Menu} for the menu types that support check marks.
*
* @see #setCheckable
* @see #isChecked
* @see Menu#setGroupCheckable
* @param checked Set to true to display a check mark, false to hide
* it. The default value is false.
* @return This Item so additional setters can be called.
*/
public MenuItem setChecked(boolean checked);
/**
* Return whether the item is currently displaying a check mark.
*
* @return If a check mark is displayed, returns true.
*
* @see #setChecked
*/
public boolean isChecked();
/**
* Sets the visibility of the menu item. Even if a menu item is not visible,
* it may still be invoked via its shortcut (to completely disable an item,
* set it to invisible and {@link #setEnabled(boolean) disabled}).
*
* @param visible If true then the item will be visible; if false it is
* hidden.
* @return This Item so additional setters can be called.
*/
public MenuItem setVisible(boolean visible);
/**
* Return the visibility of the menu item.
*
* @return If true the item is visible; else it is hidden.
*/
public boolean isVisible();
/**
* Sets whether the menu item is enabled. Disabling a menu item will not
* allow it to be invoked via its shortcut. The menu item will still be
* visible.
*
* @param enabled If true then the item will be invokable; if false it is
* won't be invokable.
* @return This Item so additional setters can be called.
*/
public MenuItem setEnabled(boolean enabled);
/**
* Return the enabled state of the menu item.
*
* @return If true the item is enabled and hence invokable; else it is not.
*/
public boolean isEnabled();
/**
* Check whether this item has an associated sub-menu. I.e. it is a
* sub-menu of another menu.
*
* @return If true this item has a menu; else it is a
* normal item.
*/
public boolean hasSubMenu();
/**
* Get the sub-menu to be invoked when this item is selected, if it has
* one. See {@link #hasSubMenu()}.
*
* @return The associated menu if there is one, else null
*/
public SubMenu getSubMenu();
/**
* Set a custom listener for invocation of this menu item. In most
* situations, it is more efficient and easier to use
* {@link Activity#onOptionsItemSelected(MenuItem)} or
* {@link Activity#onContextItemSelected(MenuItem)}.
*
* @param menuItemClickListener The object to receive invokations.
* @return This Item so additional setters can be called.
* @see Activity#onOptionsItemSelected(MenuItem)
* @see Activity#onContextItemSelected(MenuItem)
*/
public MenuItem setOnMenuItemClickListener(MenuItem.OnMenuItemClickListener menuItemClickListener);
/**
* Gets the extra information linked to this menu item. This extra
* information is set by the View that added this menu item to the
* menu.
*
* @see OnCreateContextMenuListener
* @return The extra information linked to the View that added this
* menu item to the menu. This can be null.
*/
public ContextMenuInfo getMenuInfo();
/**
* Sets how this item should display in the presence of an Action Bar.
* The parameter actionEnum is a flag set. One of {@link #SHOW_AS_ACTION_ALWAYS},
* {@link #SHOW_AS_ACTION_IF_ROOM}, or {@link #SHOW_AS_ACTION_NEVER} should
* be used, and you may optionally OR the value with {@link #SHOW_AS_ACTION_WITH_TEXT}.
* SHOW_AS_ACTION_WITH_TEXT requests that when the item is shown as an action,
* it should be shown with a text label.
*
* @param actionEnum How the item should display. One of
* {@link #SHOW_AS_ACTION_ALWAYS}, {@link #SHOW_AS_ACTION_IF_ROOM}, or
* {@link #SHOW_AS_ACTION_NEVER}. SHOW_AS_ACTION_NEVER is the default.
*
* @see android.app.ActionBar
* @see #setActionView(View)
*/
public void setShowAsAction(int actionEnum);
/**
* Sets how this item should display in the presence of an Action Bar.
* The parameter actionEnum is a flag set. One of {@link #SHOW_AS_ACTION_ALWAYS},
* {@link #SHOW_AS_ACTION_IF_ROOM}, or {@link #SHOW_AS_ACTION_NEVER} should
* be used, and you may optionally OR the value with {@link #SHOW_AS_ACTION_WITH_TEXT}.
* SHOW_AS_ACTION_WITH_TEXT requests that when the item is shown as an action,
* it should be shown with a text label.
*
* <p>Note: This method differs from {@link #setShowAsAction(int)} only in that it
* returns the current MenuItem instance for call chaining.
*
* @param actionEnum How the item should display. One of
* {@link #SHOW_AS_ACTION_ALWAYS}, {@link #SHOW_AS_ACTION_IF_ROOM}, or
* {@link #SHOW_AS_ACTION_NEVER}. SHOW_AS_ACTION_NEVER is the default.
*
* @see android.app.ActionBar
* @see #setActionView(View)
* @return This MenuItem instance for call chaining.
*/
public MenuItem setShowAsActionFlags(int actionEnum);
/**
* Set an action view for this menu item. An action view will be displayed in place
* of an automatically generated menu item element in the UI when this item is shown
* as an action within a parent.
* <p>
* <strong>Note:</strong> Setting an action view overrides the action provider
* set via {@link #setActionProvider(ActionProvider)}.
* </p>
*
* @param view View to use for presenting this item to the user.
* @return This Item so additional setters can be called.
*
* @see #setShowAsAction(int)
*/
public MenuItem setActionView(View view);
/**
* Set an action view for this menu item. An action view will be displayed in place
* of an automatically generated menu item element in the UI when this item is shown
* as an action within a parent.
* <p>
* <strong>Note:</strong> Setting an action view overrides the action provider
* set via {@link #setActionProvider(ActionProvider)}.
* </p>
*
* @param resId Layout resource to use for presenting this item to the user.
* @return This Item so additional setters can be called.
*
* @see #setShowAsAction(int)
*/
public MenuItem setActionView(int resId);
/**
* Returns the currently set action view for this menu item.
*
* @return This item's action view
*
* @see #setActionView(View)
* @see #setShowAsAction(int)
*/
public View getActionView();
/**
* Sets the {@link ActionProvider} responsible for creating an action view if
* the item is placed on the action bar. The provider also provides a default
* action invoked if the item is placed in the overflow menu.
* <p>
* <strong>Note:</strong> Setting an action provider overrides the action view
* set via {@link #setActionView(int)} or {@link #setActionView(View)}.
* </p>
*
* @param actionProvider The action provider.
* @return This Item so additional setters can be called.
*
* @see ActionProvider
*/
public MenuItem setActionProvider(ActionProvider actionProvider);
/**
* Gets the {@link ActionProvider}.
*
* @return The action provider.
*
* @see ActionProvider
* @see #setActionProvider(ActionProvider)
*/
public ActionProvider getActionProvider();
/**
* Expand the action view associated with this menu item.
* The menu item must have an action view set, as well as
* the showAsAction flag {@link #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}.
* If a listener has been set using {@link #setOnActionExpandListener(OnActionExpandListener)}
* it will have its {@link OnActionExpandListener#onMenuItemActionExpand(MenuItem)}
* method invoked. The listener may return false from this method to prevent expanding
* the action view.
*
* @return true if the action view was expanded, false otherwise.
*/
public boolean expandActionView();
/**
* Collapse the action view associated with this menu item.
* The menu item must have an action view set, as well as the showAsAction flag
* {@link #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}. If a listener has been set using
* {@link #setOnActionExpandListener(OnActionExpandListener)} it will have its
* {@link OnActionExpandListener#onMenuItemActionCollapse(MenuItem)} method invoked.
* The listener may return false from this method to prevent collapsing the action view.
*
* @return true if the action view was collapsed, false otherwise.
*/
public boolean collapseActionView();
/**
* Returns true if this menu item's action view has been expanded.
*
* @return true if the item's action view is expanded, false otherwise.
*
* @see #expandActionView()
* @see #collapseActionView()
* @see #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
* @see OnActionExpandListener
*/
public boolean isActionViewExpanded();
/**
* Set an {@link OnActionExpandListener} on this menu item to be notified when
* the associated action view is expanded or collapsed. The menu item must
* be configured to expand or collapse its action view using the flag
* {@link #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}.
*
* @param listener Listener that will respond to expand/collapse events
* @return This menu item instance for call chaining
*/
public MenuItem setOnActionExpandListener(OnActionExpandListener listener);
} | 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/view/MenuItem.java | Java | asf20 | 23,294 |
/*
* Copyright (C) 2006 The Android Open Source Project
* Copyright (C) 2011 Jake Wharton
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.actionbarsherlock.view;
import android.content.Context;
/**
* <p>Abstract base class for a top-level window look and behavior policy. An
* instance of this class should be used as the top-level view added to the
* window manager. It provides standard UI policies such as a background, title
* area, default key processing, etc.</p>
*
* <p>The only existing implementation of this abstract class is
* android.policy.PhoneWindow, which you should instantiate when needing a
* Window. Eventually that class will be refactored and a factory method added
* for creating Window instances without knowing about a particular
* implementation.</p>
*/
public abstract class Window extends android.view.Window {
public static final long FEATURE_ACTION_BAR = android.view.Window.FEATURE_ACTION_BAR;
public static final long FEATURE_ACTION_BAR_OVERLAY = android.view.Window.FEATURE_ACTION_BAR_OVERLAY;
public static final long FEATURE_ACTION_MODE_OVERLAY = android.view.Window.FEATURE_ACTION_MODE_OVERLAY;
public static final long FEATURE_NO_TITLE = android.view.Window.FEATURE_NO_TITLE;
public static final long FEATURE_PROGRESS = android.view.Window.FEATURE_PROGRESS;
public static final long FEATURE_INDETERMINATE_PROGRESS = android.view.Window.FEATURE_INDETERMINATE_PROGRESS;
/**
* Create a new instance for a context.
*
* @param context Context.
*/
private Window(Context context) {
super(context);
}
public interface Callback {
/**
* Called when a panel's menu item has been selected by the user.
*
* @param featureId The panel that the menu is in.
* @param item The menu item that was selected.
*
* @return boolean Return true to finish processing of selection, or
* false to perform the normal menu handling (calling its
* Runnable or sending a Message to its target Handler).
*/
public boolean onMenuItemSelected(int featureId, MenuItem item);
}
}
| 10mlfeng-iosched123 | libprojects/abs/src/com/actionbarsherlock/view/Window.java | Java | asf20 | 2,778 |
public class main {
int a;
int b;
public main() {
a = 10;
b = 20;
}
}
| 0692022svn | branches/a/06SVN/src/main.java | Java | asf20 | 96 |
public class svnTest {
public svnTest() {
; // 11
; // 22
int a;
}
}
| 0692022svn | src/svnTest.java | Java | asf20 | 88 |
public class main {
int a;
int b;
int sum;
public main() {
a = 10;
b = 20;
sum = 0;
}
public void add() {
sum = a + b;
this.sum = sum;
}
}
| 0692022svn | 06SVN/src/main.java | Java | asf20 | 190 |
public class SVNTest {
}
| 0692022svn | SVNTest/src/SVNTest.java | Java | asf20 | 31 |
<?php
//require section
require_once dirname(__FILE__) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'check_session.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_tickets.php';
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_redirect.php';
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_pager.php';
$title = 'Book Preview';
$ticket_quantity = filter_input(INPUT_POST, "txt_tickets_quantity");
$city_id = filter_input(INPUT_POST, "ddl_city");
//$cinema_id = filter_input(INPUT_POST, "ddl_cinema");
$movie_id = filter_input(INPUT_POST, "ddl_movie");
$show_date = filter_input(INPUT_POST, "ddl_show_date");
//$time_start = filter_input(INPUT_POST, "ddl_time_start");
if (!empty($ticket_quantity) && !empty($city_id)
&& !empty($movie_id) && !empty($show_date)) {
$_SESSION['book_info']['status'] = "started";
$_SESSION['book_info']['ticket_quantity'] = $ticket_quantity;
$_SESSION['book_info']['city_id'] = $city_id;
$_SESSION['book_info']['movie_id'] = $movie_id;
$_SESSION['book_info']['show_date'] = $show_date;
$user_id = $_SESSION['user_info']['id'];
$_SESSION['book_info']['user_id'] = $user_id;
}
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'check_inside_booking.php';
$ticket = api_tickets::get_ticket_by_ticket_booking(
$_SESSION['book_info']['city_id'], 0,
$_SESSION['book_info']['movie_id'],
$_SESSION['book_info']['show_date'], "");
$ticket['ticket_quantity'] = $_SESSION['book_info']['ticket_quantity'];
?>
<!DOCTYPE html>
<html>
<head>
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'head.php';
?>
<script type="text/javascript">
function accept(id) {
$.ajax({
type: "POST",
url: "<?php echo LINK_ROOT . DIR_AJAX; ?>accept_cinema_and_time_start.php",
data: "ticket_id="+id,
success: function (result) {
$("#your_choice").html(result);
$('#accepted').modal('show');
$('#accepted_content').html('Your choice now is: '+result);
}
});
}
</script>
</head>
<body>
<div class="ts-body-container">
<div class="ts-wrapper">
<div class="padding-top-large row">
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'header.php';
?>
</div>
<div class="ui grid">
<div class="row">
<div class="column">
<!-- Step -->
<div id='booking_step' class="ui four steps margin-top-normal">
<div class="ui active step">
Choose Cinema & Time Start
</div>
<div class="ui disabled step">
Choose Seats
</div>
<div class="ui disabled step">
Choose Combo
</div>
<div class="ui disabled step">
Coupon Code & Finish
</div>
</div>
<!-- End Step -->
<h1>Choose Cinema & Time Start</h1>
<?php
?>
<form id="form_tickets_quantity" action="" method="post" name="form_tickets_quantity">
<table class="ui orange table segment">
<tr>
<th style="width: 30em;">City:</th>
<td><?php echo $ticket['city_name']; ?></td>
</tr>
<tr>
<th>Movie:</th>
<td><?php echo $ticket['movie_title']; ?></td>
</tr>
<tr>
<th>Date:</th>
<?php
$date = date_create($ticket["show_date"]);
$date_str = date_format($date, "d/m/Y");
?>
<td><?php echo $date_str; ?></td>
</tr>
<tr>
<th>Tickets Quantity:</th>
<td class="ui left icon input">
<?php echo $ticket['ticket_quantity']; ?>
</td>
</tr>
</table>
<h2>Cinema & Time Start List</h2>
<table class="ui table segment">
<thead>
<tr><th>Name</th>
<th>Cinema</th>
<th>Time Start</th>
<th>Available Seats</th>
<th>Price (USD)</th>
<!-- <th>Total Seats</th>-->
<th>Accept Actions</th>
</tr></thead>
<tbody>
<?php
$list = api_tickets::get_all_tickets_by_ticket_booking(
$ticket['ticket_quantity'], $ticket['city_id'], $ticket['movie_id'], $ticket['show_date']);
if (empty($list) || count($list) == 0) {
echo "<tr><td>No item found.</td></tr>";
} else {
$current_page = 1;
if (!empty($_GET['p'])) {
$current_page = $_GET['p'];
}
$list_total = $list;
$page_size = 10;
$lib_pager = new lib_pager($list_total, $page_size);
$total_page = $lib_pager->get_total_page();
$current_page_list = $lib_pager->get_current_page_list($current_page);
foreach ($current_page_list as $item) {?>
<tr>
<td><?php echo $item['name']; ?></td>
<td><strong><?php echo $item['cinema_name']; ?></strong></td>
<td>
<strong>
<?php
$date = date_create($item["time_start"]);
echo date_format($date, "H:i");
?>
</strong>
</td>
<td><strong><?php echo $item['available_seats']; ?></strong></td>
<td><?php echo $item['price']; ?></td>
<!--<td><?php echo $item['total_seats']; ?></td>-->
<td>
<div onclick="accept(<?php echo $item['id']; ?>);" class="ui icon button">
<img src="<?php echo LINK_ROOT . DIR_SHARED_LAYOUT_IMAGES_ICONS; ?>accept.png"></img>
</div>
</td>
</tr>
<?php
}
}?>
</tbody>
<tfoot>
<tr><th colspan="10">
<label>Your Choice: </label>
<div id="your_choice" class="ui input">
<?php
$text = "No chosen.";
if (!empty($list) && count($list)) {
$_SESSION['book_info']['ticket_id'] = $list[0]['id'];
$date = date_create($list[0]['time_start']);
$text = $list[0]['cinema_name'] . " - " . date_format($date, "H:i");
}
echo $text;
?>
</div>
<table class="paging-footer">
<tbody>
<tr>
<?php
if (!empty($total_page) && count($total_page) > 0) {
echo "<td>Page </td>";
for ($page = 1; $page <= $total_page; $page++) { ?>
<td>
<span>
<a href="?p=<?php echo $page; ?>" <?php if ($current_page != $page) echo 'style="color:Black;"'; ?>><?php echo $page; ?></a>
</span>
</td>
<?php }
}?>
</tr>
</tbody>
</table>
</th>
</tr></tfoot>
</table>
<div class="ui orange segment">
<div class="ts-center">
<div class="ui buttons">
<!--<div class="ui green button">Back</div>-->
<a href="index.php" class="ui purple button">Exit</a>
<div class="or"></div>
<!--<div class="ui orange button">Next</div>-->
<a href="seat.php" class="ui orange button">Next</a>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- ACCEPT MODAL -->
<div id="accepted" class="ui modal">
<i class="close icon"></i>
<div class="header">
Accepted
</div>
<div id="accepted_content" class="content">
</div>
<div class="actions">
<div class="ui orange button">
OK
</div>
</div>
</div>
<!-- END ACCEPT MODAL -->
<div class="row">
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'footer.php';
?>
</div>
</div>
</div>
</body>
</html> | 09-movie | trunk/tickets_quantity.php | PHP | gpl3 | 12,492 |
<?php
session_start();
require_once dirname(dirname(__FILE__)) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_booking.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_tickets.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_seats.php';
$payment_method = filter_input(INPUT_POST, "payment_method"); // need change to status of checkout
$book_info = $_SESSION['book_info'];
$coupon_id = 0;
if (!empty($book_info['coupon_id'])) {
$coupon_id = $book_info['coupon_id'];
}
$booking_code = api_booking::finalize_booking(
$book_info['booking_id'],
$book_info['user_id'],
$book_info['ticket_id'],
$book_info['ticket_quantity'],
$coupon_id,
$book_info['combo_id'],
$book_info['combo_quantity'],
0);
if (!empty($payment_method) && $payment_method === "skrill") {
$_SESSION['book_info']['status'] = "wait_skrill_payment";
} else if (!empty($payment_method) && $payment_method === "easypaisa") {
$_SESSION['book_info']['status'] = "wait_easypaisa_payment";
$total = api_booking::calculate_total_money(
$_SESSION['book_info']['ticket_id'],
$_SESSION['book_info']['ticket_quantity'],
$_SESSION['book_info']['combo_id'],
$_SESSION['book_info']['combo_quantity'],
$_SESSION['book_info']['combo_id']);
// send mail to user cinema
$email_sent_to = api_tickets::get_user_cinema_email($_SESSION['book_info']['ticket_id']);
$message = "A client (email: ".$_SESSION['user_info']['email'].") have booked. \n"
. "Booking ID: ".$book_info['booking_id']." \n"
. "This is booking code: ".$booking_code." \n"
. "Total client have to pay: " . $total . " USD \n"
. "After the money transfered, you need to change the status of booking to PAID.";
mail($email_sent_to, "Client booking successfully and wait for user payment via Easypaisa.", $message);
// send mail to client
$email_sent_to = $_SESSION['user_info']['email'];
$message = "This is your booking code: ".$booking_code." \n"
. "Please pay for the booking, and remember to write down your booking code when you transfer money. \n"
. "Total you have to pay: " . $total . " USD";
mail($email_sent_to, "Congratulations, Booking successfully and need to payment via Easypaisa", $message);
} | 09-movie | trunk/ajax/finalize_booking.php | PHP | gpl3 | 2,551 |
<?php
require_once dirname(dirname(__FILE__)) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_booking.php';
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'head_script.php';
$ticket_quantity = filter_input(INPUT_POST, "ticket_quantity");
$city_id = filter_input(INPUT_POST, "city_id");
?>
<label>Cinema</label>
<?php
$list = api_booking::get_all_cinemas_by_filter($ticket_quantity, $city_id);
?>
<div class="ui fluid selection dropdown">
<div class="text">--Not Selected--</div>
<i class="dropdown icon"></i>
<input name="ddl_cinema" onchange="filter_change_for_cinema()" type="hidden" value="0">
<div class="menu">
<div class="item" data-value="0">--Not Selected--</div>
<?php
foreach ($list as $item) {
?>
<div class="item" data-value="<?php echo $item['id']; ?>"><?php echo $item['name']; ?></div>
<?php
}?>
</div>
</div>
| 09-movie | trunk/ajax/load_cinema_filter.php | PHP | gpl3 | 967 |
<?php
require_once dirname(dirname(__FILE__)) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_booking.php';
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'head_script.php';
$empty_load = filter_input(INPUT_POST, "empty_load");
$ticket_quantity = filter_input(INPUT_POST, "ticket_quantity");
$city_id = filter_input(INPUT_POST, "city_id");
$cinema_id = filter_input(INPUT_POST, "cinema_id");
$movie_id = filter_input(INPUT_POST, "movie_id");
?>
<label>Show Date</label>
<?php
if (empty($empty_load)) {
$list = api_booking::get_all_show_date_by_filter($ticket_quantity, $city_id, $cinema_id, $movie_id);
}
?>
<div class="ui fluid selection dropdown">
<div class="text">--Not Selected--</div>
<i class="dropdown icon"></i>
<input name="ddl_show_date" onchange="filter_change_for_show_date()" type="hidden" value="0">
<div class="menu">
<div class="item" data-value="0">--Not Selected--</div>
<?php
if (!empty($list) && count($list) > 0) {
foreach ($list as $item) {
?>
<div class="item" data-value="<?php echo $item; ?>"><?php echo $item; ?></div>
<?php
}
}?>
</div>
</div>
| 09-movie | trunk/ajax/load_show_date_filter.php | PHP | gpl3 | 1,252 |
<?php
session_start();
require_once dirname(dirname(__FILE__)) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_tickets.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_coupons.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_booking.php';
$coupon_code = filter_input(INPUT_POST, "coupon_code");
$coupon = api_coupons::get_coupon_by_coupon_code($coupon_code);
$_SESSION['book_info']['coupon_code'] = $coupon_code;
$_SESSION['book_info']['coupon_id'] = 0;
if (!empty($coupon['id'])) {
$_SESSION['book_info']['coupon_id'] = $coupon['id'];
}
$total = api_booking::calculate_total_money(
$_SESSION['book_info']['ticket_id'],
$_SESSION['book_info']['ticket_quantity'],
$_SESSION['book_info']['combo_id'],
$_SESSION['book_info']['combo_quantity'],
$_SESSION['book_info']['coupon_id']);
$result = array();
if (!empty($coupon['id'])) {
$result['successful'] = TRUE;
$result['total'] = "$".$total;
$result['info'] = "Coupon code accepted.";
} else {
$result['sucessful'] = FALSE;
$result['info'] = "Coupon code invalid.";
}
echo json_encode($result); | 09-movie | trunk/ajax/accept_coupon_code.php | PHP | gpl3 | 1,170 |
<?php
require_once dirname(dirname(__FILE__)) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_movies.php';
$number = filter_input(INPUT_POST, "number");
?>
<script type="text/javascript">
$(document).ready(function() {
$('.ui .item').on('click', function() {
$('.ui .item').removeClass('active');
$(this).addClass('active');
});
$('.ui.dropdown').dropdown({
on: 'hover'
});
});
</script>
<form name="form_add_data" id="form_add_data" method="POST" action="?" enctype="multipart/form-data">
<?php
for ($index = 0; $index < $number; $index++) {?>
<div class="ui form segment form-background">
<input type="hidden" name="index<?php echo $index; ?>" value="1" />
<div class="field">
<label for="Title">Title <span class="required">*</span></label>
<input id="Title" name="Title<?php echo $index; ?>" value="" placeholder="Title" type="text">
</div>
<div class="field">
<label for="Status">Status</label>
<div class="ui selection dropdown">
<input type="hidden" name="Status<?php echo $index; ?>" value="">
<?php
$status = api_movies::get_default_movie_statuses();
?>
<div class="text"><?php echo $status; ?></div>
<i class="dropdown icon"></i>
<div class="menu ui transition hidden">
<?php
$list = api_movies::get_all_movie_statuses();
$text = "";
if (!empty($list) && count($list) > 0) {
foreach ($list as $item) {?>
<div class="item"><?php echo $item['name']; ?></div>
<?php
}
}?>
</div>
</div>
</div>
<div class="field">
<label for="Description">Description <span class="required">*</span></label>
<textarea id="Description" name="Description<?php echo $index; ?>" placeholder="Description" class="form-control" rows="3"></textarea>
</div>
<div class="field">
<label for="Poster">Poster <span class="required">*</span></label>
<input type="file" name="File_Poster<?php echo $index; ?>" />
</div>
</div>
<br/>
<?php
}
?>
<div class="ui form segment form-background">
<input type="hidden" name="Action" value="">
<div class="ui buttons">
<a href="?"><div class="ui button">Cancel</div></a>
<div class="or"></div>
<div id="action-add-button" class="ui orange button" onclick="submit_add_data();">Add All</div>
</div>
</div>
</form>
| 09-movie | trunk/ajax/add_popup_movies.php | PHP | gpl3 | 2,921 |
<?php
session_start();
require_once dirname(dirname(__FILE__)) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_tickets.php';
$ticket_id = filter_input(INPUT_POST, "ticket_id");
$_SESSION['book_info']['ticket_id'] = $ticket_id;
$ticket = api_tickets::get_ticket_by_id($ticket_id);
$text = "No chosen.";
if (!empty($ticket)) {
$date = date_create($ticket['time_start']);
$text = $ticket['cinema_name'] . " - " . date_format($date, "H:i");
}
echo $text; | 09-movie | trunk/ajax/accept_cinema_and_time_start.php | PHP | gpl3 | 512 |
<?php
require_once dirname(dirname(__FILE__)) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_tickets.php';
$number = filter_input(INPUT_POST, "number");
?>
<script type="text/javascript">
$(document).ready(function() {
$('.ui .item').on('click', function() {
$('.ui .item').removeClass('active');
$(this).addClass('active');
});
$('.ui.dropdown').dropdown({
on: 'hover'
});
});
</script>
<form name="form_add_data" id="form_add_data" method="POST" action="?" enctype="multipart/form-data">
<?php
for ($index = 0; $index < $number; $index++) {?>
<div class="ui form segment form-background">
<input type="hidden" name="index<?php echo $index; ?>" value="1" />
<div class="field">
<label for="Name">Name <span class="required">*</span></label>
<input name="txt_name<?php echo $index; ?>" type="text" value="" placeholder="e.g: ticket 1" />
</div>
<div class="field">
<label for="Status">Movie <span class="required">*</span></label>
<div class="ui selection dropdown">
<?php $movie = api_tickets::get_default_movie(); ?>
<input type="hidden" name="ddl_movie<?php echo $index; ?>" value="<?php echo $movie; ?>">
<div class="text"><?php echo $movie; ?></div>
<i class="dropdown icon"></i>
<div class="menu ui transition hidden">
<?php
$list = api_tickets::get_all_movies();
if (!empty($list) && count($list) > 0) {
foreach ($list as $item) {?>
<div class="item"><?php echo $item['title']; ?></div>
<?php
}
}?>
</div>
</div>
</div>
<div class="field">
<label for="Status">Cinema <span class="required">*</span></label>
<div class="ui selection dropdown">
<?php $cinema = api_tickets::get_default_cinema(); ?>
<input type="hidden" name="ddl_cinema<?php echo $index; ?>" value="<?php echo $cinema; ?>">
<div class="text"><?php echo $cinema; ?></div>
<i class="dropdown icon"></i>
<div class="menu ui transition hidden">
<?php
$list = api_tickets::get_all_cinemas();
if (!empty($list) && count($list) > 0) {
foreach ($list as $item) {?>
<div class="item"><?php echo $item['name']; ?></div>
<?php
}
}?>
</div>
</div>
</div>
<div class="field">
<script type="text/javascript">
$(document).ready(function() {
jQuery('#dtp_show_date<?php echo $index; ?>').datetimepicker({
timepicker:false,
format:'d/m/Y'
});
});
</script>
<label for="Status">Date <span class="required">*</span></label>
<input name="dtp_show_date<?php echo $index; ?>" value="" type="text" id="dtp_show_date<?php echo $index; ?>" placeholder="e.g: 25/05/2014" style="width:200px;">
</div>
<div class="field">
<script type="text/javascript">
$(document).ready(function() {
jQuery('#dtp_time_start<?php echo $index; ?>').datetimepicker({
datepicker:false,
// allowTimes:[
// '12:00', '13:00', '15:00',
// '17:00', '17:05', '17:20', '19:00', '20:00'
// ],
format:'H:i'
});
});
</script>
<label for="Status">Time Start <span class="required">*</span></label>
<input name="dtp_time_start<?php echo $index; ?>" value="" type="text" id="dtp_time_start<?php echo $index; ?>" placeholder="e.g: 21:30" style="width:200px;">
</div>
<div class="field">
<label for="Name">Duration (min) <span class="required">*</span></label>
<input name="txt_duration<?php echo $index; ?>" value="" type="text" placeholder="e.g: 60 (min)" />
</div>
<div class="field">
<label for="Name">Price (USD) <span class="required">*</span></label>
<input name="txt_price<?php echo $index; ?>" value="" type="text" placeholder="e.g: 50 (USD)" />
</div>
</div>
<br/>
<?php
}
?>
<div class="ui form segment form-background">
<input type="hidden" name="Action" value="">
<div class="ui buttons">
<a href="?"><div class="ui button">Cancel</div></a>
<div class="or"></div>
<div id="action-add-button" class="ui orange button" onclick="submit_add_data();">Add All</div>
</div>
</div>
</form>
| 09-movie | trunk/ajax/add_popup_tickets.php | PHP | gpl3 | 6,985 |
<?php
require_once dirname(dirname(__FILE__)) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_cinemas.php';
$number = filter_input(INPUT_POST, "number");
?>
<script type="text/javascript">
$(document).ready(function() {
$('.ui .item').on('click', function() {
$('.ui .item').removeClass('active');
$(this).addClass('active');
});
$('.ui.dropdown').dropdown({
on: 'hover'
});
});
</script>
<form name="form_add_data" id="form_add_data" method="POST" action="?" enctype="multipart/form-data">
<?php
for ($index = 0; $index < $number; $index++) {?>
<div class="ui form segment form-background">
<input type="hidden" name="index<?php echo $index; ?>" value="1" />
<div class="field">
<label for="Name">Title <span class="required">*</span></label>
<input name="txt_name<?php echo $index; ?>" value="" placeholder="Name" type="text">
</div>
<div class="field">
<label for="Address">Address <span class="required">*</span></label>
<input name="txt_address<?php echo $index; ?>" value="" placeholder="Address" type="text">
</div>
<div class="field">
<label for="Status">City <span class="required">*</span></label>
<div class="ui selection dropdown">
<?php
$city = api_cinemas::get_default_city();
?>
<input type="hidden" name="ddl_city<?php echo $index; ?>" value="<?php echo $city; ?>">
<div class="text"><?php echo $city; ?></div>
<i class="dropdown icon"></i>
<div class="menu ui transition hidden">
<?php
$list = api_cinemas::get_all_cities();
$text = "";
if (!empty($list) && count($list) > 0) {
foreach ($list as $item) {?>
<div class="item"><?php echo $item['name']; ?></div>
<?php
}
}?>
</div>
</div>
</div>
<div class="field">
<label for="Latitude">Latitude <span class="required">*</span></label>
<input id="txt_latitude" name="txt_latitude" value="" placeholder="Latitude" type="text">
</div>
<div class="field">
<label for="Longitude">Longitude <span class="required">*</span></label>
<input id="txt_longitude" name="txt_longitude" value="" placeholder="Longitude" type="text">
</div>
<div class="field">
<label for="Image">Image <span class="required">*</span></label>
<input type="file" name="f_image<?php echo $index; ?>" />
</div>
</div>
<br/>
<?php
}
?>
<div class="ui form segment form-background">
<input type="hidden" name="Action" value="">
<div class="ui buttons">
<a href="?"><div class="ui button">Cancel</div></a>
<div class="or"></div>
<div id="action-add-button" class="ui orange button" onclick="submit_add_data();">Add All</div>
</div>
</div>
</form>
| 09-movie | trunk/ajax/add_popup_cinemas.php | PHP | gpl3 | 4,347 |
<?php
require_once dirname(dirname(__FILE__)) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_booking.php';
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'head_script.php';
$empty_load = filter_input(INPUT_POST, "empty_load");
$ticket_quantity = filter_input(INPUT_POST, "ticket_quantity");
$city_id = filter_input(INPUT_POST, "city_id");
$cinema_id = filter_input(INPUT_POST, "cinema_id");
?>
<label>Movie</label>
<?php
if (empty($empty_load)) {
$list = api_booking::get_all_movies_by_filter($ticket_quantity, $city_id, $cinema_id);
}
?>
<div class="ui fluid selection dropdown">
<div class="text">--Not Selected--</div>
<i class="dropdown icon"></i>
<input name="ddl_movie" onchange="filter_change_for_movie()" type="hidden" value="0">
<div class="menu">
<div class="item" data-value="0">--Not Selected--</div>
<?php
if (!empty($list) && count($list) > 0) {
foreach ($list as $item) {
?>
<div class="item" data-value="<?php echo $item['id']; ?>"><?php echo $item['title']; ?></div>
<?php
}
}?>
</div>
</div>
| 09-movie | trunk/ajax/load_movie_filter.php | PHP | gpl3 | 1,194 |
<?php
require_once dirname(dirname(__FILE__)) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_booking.php';
$ticket_id = filter_input(INPUT_POST, "ticket_id");
$row = filter_input(INPUT_POST, "row");
$column = filter_input(INPUT_POST, "column");
$book_quantity = filter_input(INPUT_POST, "book_quantity");
$booking_id = filter_input(INPUT_POST, "booking_id");
$result = api_booking::book_seat($ticket_id, $row, $column, $book_quantity, $booking_id);
//$out = array_values($result);
echo json_encode($result);
| 09-movie | trunk/ajax/seat_selection.php | PHP | gpl3 | 562 |
<?php
require_once dirname(__FILE__) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'check_session.php';
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'check_outside_booking.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_security.php';
api_security::logout(); | 09-movie | trunk/logout.php | PHP | gpl3 | 300 |
<?php
session_start();
//require section
require_once dirname(dirname(__FILE__)) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_booking.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_config.php';
$total = api_booking::calculate_total_money(
$_SESSION['book_info']['ticket_id'],
$_SESSION['book_info']['ticket_quantity'],
$_SESSION['book_info']['combo_id'],
$_SESSION['book_info']['combo_quantity'],
$_SESSION['book_info']['combo_id']);
$user_info = $_SESSION['user_info'];
// $seller_email = 'vietanh.pd1@gmail.com';
$seller_email = api_config::get_skrill_email();
$buyer_email = $user_info['email'];
$return_url = LINK_ROOT . '/coupon_finish.php?payment=successful';
$cancel_url = LINK_ROOT . '/coupon_finish.php';
$status_url = LINK_ROOT . DIR_SKRILL_PAYMENT . '/skrill_status.php';
$language_code = 'EN';
$price = $total;
$money_code = 'USD';
$amount_description = "Book ticket from website";
$fname = $user_info['first_name'];
$lname = $user_info['last_name'];
$buyer_address = '';
$buyer_city = '';
$buyer_state = '';
$buyer_postal_code = '';
$buyer_country = 'Pakistan';
$product_name = 'Booking ID: ' . $_SESSION['book_info']['booking_id'];
$transaction_id = $_SESSION['book_info']['booking_id'];
$product_description = 'Pay for Booking ID('.$_SESSION['book_info']['booking_id'].') at '.LINK_ROOT;
?>
<!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/html;charset=utf-8"/>
<title>Skrill Payment Gateway</title>
</head>
<body>
<div id="wrap">
<div id="contentwrap">
<div id="header">
<h2 align="center">Redirecting to Skrill payment Gateway </h2>
</div>
<div id="content">
<div class="columns">
<div id="page" class="span12 spaceR">
<form action="https://www.moneybookers.com/app/payment.pl" method="post" target="_self" name="Moneybookers">
<input type="hidden" name="pay_to_email" value="<?php echo $seller_email; ?>">
<input type="hidden" name="pay_from_email" value="<?php echo $buyer_email; ?>">
<input type="hidden" name="return_url" value="<?php echo $return_url; ?>">
<!-- Redirect to success Page -->
<input type="hidden" name="cancel_url" value="<?php echo $cancel_url; ?>">
<!-- Redirect To cancel Page-->
<input type="hidden" name="status_url" value="<?php echo $status_url; ?>">
<!-- Callback purl (backend call) -->
<input type="hidden" name="language" value="<?php echo $language_code ?>"> <!-- Language -->
<input type="hidden" name="transaction_id" value="<?php echo $transaction_id; ?>">
<input type="hidden" name="hide_login" value="1">
<!-- show the login form -->
<!-- target in which the return_url value will be called on successful payment -->
<!-- 1 = '_top', 2 = '_parent', 3 = '_self', 4= '_blank' -->
<input type="hidden" name="return_url_target" value="4">
<input type="hidden" name="cancel_url_target" value="4">
<!-- Custom fields for your own needs -->
<!-- <input type="hidden" name="merchant_fields" value="name, username, order_amount, user_id">-->
<!-- List all your custom fields here (comma separated, max 5)-->
<!-- <input type="hidden" name="name" value="name of user">-->
<!-- <input type="hidden" name="username" value="user name">-->
<input type="hidden" name="order_amount" value="<?php echo $price; ?>">
<!-- <input type="hidden" name="user_id" value="userid or unique id">-->
<input type="hidden" name="amount_description" value="<?php echo $amount_description; ?>">
<input type="hidden" name="amount" value="<?php echo $price; ?>">
<input type="hidden" name="currency" value="<?php echo $money_code; ?>">
<input type="hidden" name="firstname" value="<?php echo $fname; ?>">
<input type="hidden" name="lastname" value="<?php echo $lname; ?>">
<input type="hidden" name="email" value="<?php echo $buyer_email; ?>">
<input type="hidden" name="address" value="<?php echo $buyer_address; ?>">
<input type="hidden" name="city" value="<?php echo $buyer_city; ?>">
<input type="hidden" name="state" value="<?php echo $buyer_state; ?>">
<input type="hidden" name="postal_code" value="<?php echo $buyer_postal_code; ?>">
<input type="hidden" name="country" value="<?php echo $buyer_country; ?>">
<input type="hidden" name="detail1_description" value="<?php echo $product_name; ?>">
<input type="hidden" name="detail1_text" value="<?php echo $product_description; ?>">
<input type="hidden" name="confirmation_note" value="Your payment is Success">
</form>
</div>
</div>
</div>
</div>
</div>
<script>
document.Moneybookers.submit();
</script>
</body>
</html> | 09-movie | trunk/skrill_payment/skrill.php | PHP | gpl3 | 6,038 |
<?php
session_start();
//require section
require_once dirname(dirname(__FILE__)) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_tickets.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_booking.php';
$booking_id = $_POST['transaction_id'];
// Validate the Moneybookers signature
$concatFields = $_POST['merchant_id']
.$_POST['transaction_id']
.strtoupper(md5('movie'))
.$_POST['mb_amount']
.$_POST['mb_currency']
.$_POST['status'];
$MBEmail = api_config::get_skrill_email();
// Ensure the signature is valid, the status code == 2,
// and that the money is going to you
if (strtoupper(md5($concatFields)) === $_POST['md5sig']
&& $_POST['status'] == 2
&& $_POST['pay_to_email'] === $MBEmail)
{
// api_config::set_easypaisa_detail("concat:" . md5($concatFields) . ", md5sig:" . $_POST['md5sig']
// . ", status:" . $_POST['status'] . ", pay_to_email" . $_POST['pay_to_email']
// . ", MBE:" . $MBEmail);
// Valid transaction.
//TODO: generate the product keys and
// send them to your customer.
//
api_booking::update_paid($booking_id);
$booking = api_booking::get_booking_by_id($booking_id);
$user_email = api_booking::get_user_email_from_booking_id($booking_id);
// send mail to user cinema
$email_sent_to = api_tickets::get_user_cinema_email($booking['ticket_id']);
$message = "A client (email: ".$user_email.") have booked. \n"
. "Booking ID: ".$booking_id." \n"
. "This is booking code: ".$booking['generated_code']." \n";
mail($email_sent_to, "Client booking successfully and paid by Skrill.", $message);
// send mail to client
$email_sent_to = $user_email;
$message = "This is your booking code: ".$booking['generated_code']." \n"
. "Remember your code when you come cinema, have fun. \n";
mail($email_sent_to, "Congratulations, Booking successfully!", $message);
}
else
{
// Invalid transaction. Bail out
api_booking::delete_booking($booking_id);
exit;
} | 09-movie | trunk/skrill_payment/skrill_status.php | PHP | gpl3 | 2,284 |
<?php
session_start();
require_once dirname(__FILE__) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_date.php';
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_pager.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_security.php';
$title = 'Home Page';
$email = filter_input(INPUT_GET, "email");
$activate_code = filter_input(INPUT_GET, "activate_code");
if (!api_security::activate($email, $activate_code)) {
$error_show = "Sorry, this email $email maybe have already registered or not found in our system.";
} else {
$success_info = "Activate Successully! You are now a member.";
}
?>
<!DOCTYPE html>
<!-- IE SECTION -->
<!--[if lt IE 7]>
<html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>
<html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>
<html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js"> <!--<![endif]-->
<!-- END IE SECTION -->
<html>
<head>
<?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'head.php' ?>
</head>
<body>
<div class="ts-body-container">
<div class="ts-wrapper">
<div class="padding-top-large row">
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'header.php';
?>
<div class="ui segment breadcrumb" style="margin-top: 25px; margin-left: 20px;">
<a class="section" href="index.php">Home</a>
<i class="right arrow icon divider"></i>
<a class="active section">Login</a>
</div>
</div>
<div class="ui grid">
<div class="row">
<div class="column">
<h1>Verify Account</h1>
<?php if (!empty($error_show)) { ?>
<div class="ui error message">
<i class="close icon"></i>
<div class="header">
Please correct these wrongs.
</div>
<ul class="list">
<?php echo $error_show; ?>
</ul>
</div>
<?php } else if (!empty($success_info)) {
?>
<div class="ui success message">
<i class="close icon"></i>
<div class="header">
<?php echo $success_info; ?>
</div>
</div>
<?php
}
?>
</div>
</div>
</div>
<div class="row">
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'footer.php';
?>
</div>
</div>
</div>
</body>
</html> | 09-movie | trunk/verify_account.php | PHP | gpl3 | 3,319 |
<?php
//require section
require_once dirname(__FILE__) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'check_session.php';
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'check_outside_booking.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_combos.php';
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_pager.php';
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'general_functions.php';
$title = 'Combos';
if (!empty($_POST)) {
}
?>
<!DOCTYPE html>
<html>
<head>
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'head.php';
?>
</head>
<body>
<div class="ts-body-container">
<div class="ts-wrapper">
<!--<div class="ui grid">-->
<div class="padding-top-large row">
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'header.php';
?>
<div class="ui segment breadcrumb" style="margin-top: 25px; margin-left: 20px;">
<a class="section" href="index.php">Home</a>
<i class="right arrow icon divider"></i>
<div class="active section">Combos</div>
</div>
</div>
<div class="ui grid">
<div class="row">
<div class="column">
<h1>Combos</h1>
<div class="ui basic segment">
<div class="ui stackable items">
<?php
$list = api_combos::get_all_combos();
$current_page = 1;
if (!empty($_GET['p'])) {
$current_page = $_GET['p'];
}
$list_total = $list;
$page_size = 8;
$lib_pager = new lib_pager($list_total, $page_size);
$total_page = $lib_pager->get_total_page();
$current_page_list = $lib_pager->get_current_page_list($current_page);
if (empty($current_page_list) || count($current_page_list) == 0) {
echo "No movie found.";
} else {
echo '<div class="row">';
foreach ($current_page_list as $key => $item) {
if ($key > 0 && $key % 4 == 0) {
echo '</div>';
echo '<div class="row">';
}
show_combo($item);
}
echo '</div>';
}
?>
</div>
</div>
<div class="ts-center">
<div class="ui borderless pagination menu">
<?php if (!empty($total_page) && count($total_page) > 0) { ?>
<a class="item" <?php
if ($current_page <= 1) {
echo "onclick='return false'";
}
?>
href="?p=<?php echo $current_page - 1; ?>">
<i class="left arrow icon"></i> Previous
</a>
<?php for ($page = 1; $page <= $total_page; $page++) { ?>
<a class="item" href="?p=<?php echo $page; ?>"><?php echo $page; ?></a>
<?php }
?>
<a class="item" <?php
if ($current_page >= $total_page) {
echo "onclick='return false'";
}
?>
href="?p=<?php echo $current_page + 1; ?>">
Next <i class="icon right arrow"></i>
</a>
<?php }
?>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'footer.php';
?>
</div>
<!--</div>-->
</div>
</div>
</body>
</html> | 09-movie | trunk/combo.php | PHP | gpl3 | 5,273 |
<?php
//require section
require_once dirname(__FILE__) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'check_session.php';
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'check_outside_booking.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_cinemas.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_movies.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_booking.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_seats.php';
$title = 'Home Page';
?>
<!DOCTYPE html>
<html>
<head>
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'head.php';
?>
<?php
if (!empty($skrill_payment)) {
?>
<script type="text/javascript">
$(document).ready(function() {
$('#skrill').modal('show');
});
</script>
<?php
}
?>
</head>
<body>
<div class="ts-body-container">
<div class="ts-wrapper">
<!--<div class="ui grid">-->
<div class="padding-top-large row">
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'header.php';
?>
<div class="ui segment breadcrumb" style="margin-top: 25px; margin-left: 20px;">
<a class="active section" href="index.php">Home</a>
</div>
</div>
<div class="ui grid">
<div class="row">
<?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'book_ticket.php'; ?>
<div class="twelve wide column">
<h1>Now Showing</h1>
<div class="ui orange segment">
<div class="ui stackable items">
<div class="row">
<?php
$list = api_movies::get_all_movies_with_now_showing_and_number(3);
if (empty($list) || count($list) == 0) {
echo "Not movie found.";
} else {
foreach ($list as $item) {
?>
<div class="item" onclick="window.location = 'movie_detail.php?m_id=<?php echo $item['id'] ?>#container'">
<div class="image">
<img src="<?php echo LINK_ROOT . DIR_SHARED_UPLOAD_IMAGES_POSTERS . $item['poster']; ?>">
</div>
<div class="content">
<div class="name"><?php echo $item['title']; ?></div>
<p class="description">
<?php
if (strlen($item['description']) < 100) {
echo $item['description'];
} else {
echo substr($item['description'], 0, 100) . '<span class="ts-red">....[more]</span>';
}
?>
</p>
</div>
</div>
<?php
}
} ?>
</div>
</div>
</div>
<h1>Coming Soon</h1>
<div class="ui orange segment">
<div class="ui stackable items">
<div class="row">
<?php
$list = api_movies::get_all_movies_with_comming_soon_and_number(3);
if (empty($list) || count($list) == 0) {
echo "Not movie found.";
} else {
foreach ($list as $item) {
?>
<div class="item" onclick="window.location = 'movie_detail.php?m_id=<?php echo $item['id'] ?>#container'">
<div class="image">
<img src="<?php echo LINK_ROOT . DIR_SHARED_UPLOAD_IMAGES_POSTERS . $item['poster']; ?>">
</div>
<div class="content">
<div class="name"><?php echo $item['title']; ?></div>
<p class="description"><?php
if (strlen($item['description']) < 100) {
echo $item['description'];
} else {
echo substr($item['description'], 0, 100) . '<span class="ts-red">....[more]</span>';
}
?></p>
</div>
</div>
<?php
}
} ?>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- SKRILL MODAL -->
<div id="skrill" class="ui modal">
<i class="close icon"></i>
<?php
if (!empty($skrill_payment) && $skrill_payment === "paid") {
?>
<div class="header">
SKRILL Payment Successfully & Finished
</div>
<div class="content">
Congratulations, Booking successfully! Now, a booking code is sent to your email and phone number. Remember your code when you come to cinema.
</div>
<?php
} else {
?>
<div class="header">
SKRILL Payment Failed
</div>
<div class="content">
We haven't received your payment. Please booking again!
</div>
<?php
}
?>
<div class="actions">
<div class="ui orange button">
OK
</div>
</div>
</div>
<!-- END SKRILL MODAL -->
<div class="row">
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'footer.php';
?>
</div>
<!--</div>-->
</div>
</div>
</body>
</html> | 09-movie | trunk/index.php | PHP | gpl3 | 6,951 |
<?php
//require section
require_once dirname(__FILE__) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'check_session.php';
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'check_inside_booking.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_tickets.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_combos.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_booking.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_redirect.php';
$title = 'Coupon Code & Finish';
$payment = filter_input(INPUT_GET, "payment");
$cb_enable_combo = filter_input(INPUT_POST, "cb_enable_combo");
$combo_quantity = filter_input(INPUT_POST, "txt_combo_quantity");
$combo_id = filter_input(INPUT_POST, "ddl_combo");
$_SESSION['book_info']['combo_quantity'] = 0;
$_SESSION['book_info']['combo_id'] = 0;
if (!empty($combo_id) && !empty($combo_quantity)) {
$_SESSION['book_info']['combo_quantity'] = $combo_quantity;
$_SESSION['book_info']['combo_id'] = $combo_id;
}
?>
<!DOCTYPE html>
<html>
<head>
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'head.php';
?>
<script type="text/javascript">
function add_coupon_code() {
var coupon_code = $('input[name="txt_coupon_code"]').val();
$.ajax({
type: "POST",
url: "<?php echo LINK_ROOT . DIR_AJAX; ?>accept_coupon_code.php",
data: "coupon_code="+coupon_code,
success: function (result) {
var data_json = jQuery.parseJSON( result );
var info_com = $("#coupon_code_info");
if (data_json.successful) {
$("#td_total").html(data_json.total);
$('input[name="txt_coupon_code"]').attr('disabled', 'disabled');
$("#btn_add_coupon_code").hide();
$("#td_coupon_code").removeClass();
$("#td_coupon_code").addClass("ui three column row");
info_com.removeClass();
info_com.addClass("ui green label");
} else {
info_com.removeClass();
info_com.addClass("ui orange label");
}
info_com.html(data_json.info);
}
});
}
function checkout() {
$('#checkout').modal('show');
}
function finalize_booking(payment_method) {
$.ajax({
type: "POST",
data: "payment_method="+payment_method,
url: "<?php echo LINK_ROOT . DIR_AJAX; ?>finalize_booking.php",
success: function (result) {
if (payment_method === "skrill") {
window.location.href = "<?php echo LINK_ROOT . DIR_SKRILL_PAYMENT; ?>skrill.php";
}
}
});
}
function easypaisa() {
finalize_booking("easypaisa");
$('#easypaisa').modal('setting', {
closable : false,
onHidden : function() {
window.location.href = "<?php echo LINK_ROOT; ?>/index.php";
}
}).modal('show');
$('#btn_cancel').click();
}
function skrill() {
finalize_booking("skrill");
// $('#btn_cancel').click();
}
</script>
</head>
<body>
<div class="ts-body-container">
<div class="ts-wrapper">
<div class="padding-top-large row">
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'header.php';
?>
</div>
<div class="ui grid">
<div class="row">
<div class="column">
<!-- Step -->
<div id='booking_step' class="ui four steps margin-top-normal">
<div class="ui disabled step">
Choose Cinema & Time Start
</div>
<div class="ui disabled step">
Choose Seats
</div>
<div class="ui disabled step">
Choose Combo
</div>
<div class="ui active step">
Coupon Code & Finish
</div>
</div>
<!-- End Step -->
<h1>Coupon Code & Finish</h1>
<?php
$ticket = api_tickets::get_ticket_by_id($_SESSION['book_info']['ticket_id']);
if (!empty($_SESSION['book_info']['combo_id'])) {
$combo = api_combos::get_combo_by_id($_SESSION['book_info']['combo_id']);
}
?>
<form id="form_finish" action="" method="post" name="form_finish">
<table class="ui orange table segment">
<tr>
<th>Movie:</th>
<td><?php echo $ticket['movie_title']; ?></td>
</tr>
<tr>
<th>Cinema:</th>
<td><?php echo $ticket['cinema_name']; ?></td>
</tr>
<tr>
<th>Date:</th>
<?php
$date = date_create($ticket["show_date"]);
$date_str = date_format($date, "d/m/Y");
?>
<td><?php echo $date_str; ?></td>
</tr>
<tr>
<th>Time:</th>
<?php
$date = date_create($ticket["time_start"]);
$date_str = date_format($date, "H:i");
?>
<td><?php echo $date_str; ?></td>
</tr>
<tr>
<th>Ticket Quantity:</th>
<td><?php echo $_SESSION['book_info']['ticket_quantity']; ?></td>
</tr>
<tr>
<th>Seat:</th>
<?php
$list = api_booking::get_all_booking_lines_by_booking_id(
$_SESSION['book_info']['booking_id'],
$_SESSION['book_info']['user_id']);
?>
<td>
<?php
if (empty($list) || count($list) == 0) {
echo "-";
} else {
echo $list[0]['row_pos'] . $list[0]['column_pos'];
for ($index = 1; $index < count($list); $index++) {
echo ", " . $list[$index]['row_pos'] . $list[$index]['column_pos'];
}
}
?>
</td>
</tr>
<tr>
<th>Combo:</th>
<?php
$text = "-";
if (!empty($combo['name'])) {
$text = $combo['name'];
}
?>
<td><?php echo $text; ?></td>
</tr>
<tr>
<th>Combo Quantity:</th>
<?php
$text = "-";
if (!empty($_SESSION['book_info']['combo_quantity'])) {
$text = $_SESSION['book_info']['combo_quantity'];
}
?>
<td><?php echo $text; ?></td>
</tr>
<tr>
<th>Total:</th>
<?php
$total = api_booking::calculate_total_money(
$ticket['id'],
$_SESSION['book_info']['ticket_quantity'],
$_SESSION['book_info']['combo_id'],
$_SESSION['book_info']['combo_quantity'],
$_SESSION['book_info']['combo_id']);
?>
<td id="td_total" style="font-weight: bold;">$<?php echo $total; ?></td>
</tr>
<tr>
<?php
if (!empty($_SESSION['book_info']['coupon_id'])) {
$coupon_id = $_SESSION['book_info']['coupon_id'];
}
$coupon_code = "";
if (!empty($coupon_id)) {
$coupon_code = $_SESSION['book_info']['coupon_code'];
}
?>
<th>Coupon Code:</th>
<?php
if (!empty($coupon_id)) {
?>
<td class="ui three column row">
<input name="txt_coupon_code" type="text" value="<?php echo $coupon_code; ?>" placeholder="A1123D" disabled="disabled"/>
<div id="btn_add_coupon_code" onclick="add_coupon_code();" class="ui orange button" style="display: none;">Add</div>
<div id="coupon_code_info" class="ui green label">Coupon code accepted.</div>
</td>
<?php
} else {
?>
<td id="td_coupon_code" class="ui action input">
<input name="txt_coupon_code" type="text" placeholder="A1123D" />
<div id="btn_add_coupon_code" onclick="add_coupon_code();" class="ui orange button">Add</div>
<div id="coupon_code_info"></div>
</td>
<?php
}
?>
</tr>
</table>
<div class="ui orange segment">
<div class="ts-center">
<div class="ui buttons">
<!--<div class="ui green button">Back</div>-->
<a href="choose_combo.php#booking_step" class="ui purple button">Back</a>
<div class="or"></div>
<!--<div class="ui orange button">Next</div>-->
<div onclick="checkout();" class="ui orange button">Checkout</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- BEGIN CHECKOUT MODAL -->
<div id="checkout" class="ui modal">
<i class="close icon"></i>
<div class="header">
Checkout
</div>
<div class="content">
<div class="left ts-center">
<div class="field">
<img width="100%" src="<?php echo LINK_ROOT . DIR_SHARED_LAYOUT_IMAGES_ICONS; ?>skrill.png" />
</div>
<div class="ui buttons">
<div onclick="skrill();" class="ui orange button">Pay via SKRILL</div>
</div>
</div>
<div class="right ts-center">
<div class="field">
<img width="100%" src="<?php echo LINK_ROOT . DIR_SHARED_LAYOUT_IMAGES_ICONS; ?>easypaisa.png" />
</div>
<div class="ui buttons">
<div onclick="easypaisa();" class="ui green button">Private Transfer</div>
</div>
</div>
</div>
<div class="actions">
<div id="btn_cancel" class="ui button">
Cancel
</div>
</div>
</div>
<!-- END OF CHECKOUT MODAL -->
<!-- EASYPAISA MODAL -->
<div id="easypaisa" class="ui modal">
<i class="close icon"></i>
<div class="header">
EASYPAISA Finish
</div>
<div class="content">
<p>Congratulations, Booking successfully! Now, a booking code is sent to your email and phone number. </p>
<p>You have to use the code to active your booking via easypaisa payment. (please fill the booking code in your payment.)</p>
<br/>
<p><strong>Please pay for our Easypaisa's account</strong></p>
<p><?php echo api_config::get_easypaisa_detail(); ?></p>
</div>
<div class="actions">
<div class="ui positive button">
OK
</div>
</div>
</div>
<!-- END EASYPAISA MODAL -->
<div class="row">
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'footer.php';
?>
</div>
</div>
</div>
</body>
</html> | 09-movie | trunk/coupon_finish.php | PHP | gpl3 | 16,354 |
<?php
//require section
require_once dirname(__FILE__) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'check_session.php';
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'check_outside_booking.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_security.php';
$title = 'Register New Account';
$first_name = "";
$last_name = "";
$phone_number = "";
$email = "";
$password = "";
$password_confirm = "";
if (!empty($_POST)) {
if (!empty($_POST['txt_first_name'])) {
$first_name = $_POST['txt_first_name'];
}
if (!empty($_POST['txt_last_name'])) {
$last_name = $_POST['txt_last_name'];
}
if (!empty($_POST['txt_phone_number'])) {
$phone_number = $_POST['txt_phone_number'];
}
if (!empty($_POST['txt_email'])) {
$email = $_POST['txt_email'];
}
if (!empty($_POST['txt_password'])) {
$password = $_POST['txt_password'];
}
if (!empty($_POST['txt_password_confirm'])) {
$password_confirm = $_POST['txt_password_confirm'];
}
$error_show = api_security::validate_register($first_name, $last_name,
$phone_number, $email, $password, $password_confirm);
if (empty($error_show)) {
$activate_code = api_security::register($email, $password, $last_name, $first_name, $phone_number);
if (!empty($activate_code)) {
$email_sent_to = $email;
$url_to_activate = LINK_ROOT . "/verify_account.php?email=$email&activate_code=$activate_code";
$message = "Recently, you have registered the email: $email. Please go here to activate you account: $url_to_activate \n";
mail($email_sent_to, "Confirm Registration | Movie Websites", $message);
$success_info = "Congratulations, Register Successfully, Please go to your email $email to active your account.";
}
$first_name = "";
$last_name = "";
$phone_number = "";
$email = "";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'head.php';
?>
</head>
<body>
<div class="ts-body-container">
<div class="ts-wrapper">
<div class="padding-top-large row">
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'header.php';
?>
<div class="ui segment breadcrumb" style="margin-top: 25px; margin-left: 20px;">
<a class="section" href="index.php">Home</a>
<i class="right arrow icon divider"></i>
<a class="active section">Register</a>
</div>
</div>
<div class="ui grid margin-top">
<div class="row">
<div class="column">
<h1>Register Now</h1>
<form name="form_register" id="form_register" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<?php if (!empty($error_show)) { ?>
<div class="ui error message">
<i class="close icon"></i>
<div class="header">
Please correct these wrongs.
</div>
<ul class="list">
<?php echo $error_show; ?>
</ul>
</div>
<?php } else if (!empty($success_info)) {
?>
<div class="ui success message">
<i class="close icon"></i>
<div class="header">
<?php echo $success_info; ?>
</div>
</div>
<?php
}
?>
<div class="ui form segment">
<div class="two fields">
<div class="field">
<label for="FirstName">First Name</label>
<input id="txt_first_name" name="txt_first_name" class="small input" value="<?php echo $first_name; ?>" placeholder="First Name" type="text" />
</div>
<div class="field">
<label for="LastName">Last Name</label>
<input id="txt_last_name" name="txt_last_name" value="<?php echo $last_name; ?>" placeholder="Last Name" type="text">
</div>
</div>
<div class="field">
<label for="PhoneNumber">Phone Number (please fill correctly, we'll use this to verify your booking)</label>
<input type="text" placeholder="e.g: 0988549089" id="txt_phone_number" name="txt_phone_number" value="<?php echo $phone_number; ?>">
</div>
<div class="field">
<label for="Email">Email (please fill correctly, we'll use this to verify your booking)</label>
<input id="txt_email" name="txt_email" value="<?php echo $email; ?>" placeholder="e.g: your_name@example.com" type="text">
</div>
<div class="field">
<label for="Password">Password</label>
<input id="txt_password" name="txt_password" type="password">
</div>
<div class="field">
<label for="PasswordConfirm">Password Confirm</label>
<input id="txt_password_confirm" name="txt_password_confirm" value="" type="password">
</div>
<div class="large animated fade ui orange button" onclick="submitRegister();">
<div class="visible content">Submit</div>
<div class="hidden content"><i class="ok sign icon"></i></div>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="row">
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'footer.php';
?>
</div>
</div>
</div>
</div>
</body>
</html> | 09-movie | trunk/register.php | PHP | gpl3 | 7,327 |
<?php
//require section
require_once dirname(__FILE__) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'check_session.php';
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'check_inside_booking.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_combos.php';
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_redirect.php';
$title = 'Choose Combo';
$_SESSION['book_info']['coupon_id'] = 0;
$_SESSION['book_info']['coupon_code'] = "";
?>
<!DOCTYPE html>
<html>
<head>
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'head.php';
?>
<script>
$(document).ready(function() {
$('#txt_combo_quantity').attr('disabled','disabled');
$('input[name="ddl_combo"]').attr('disabled','disabled');
$("#cb_enable_combo").val("on");
$( "#togg" ).on( "click", function() {
var enabled = $("#cb_enable_combo").val();
if (enabled === "on") {
$('#txt_combo_quantity').removeAttr('disabled');
$('input[name="ddl_combo"]').removeAttr('disabled');
$("#cb_enable_combo").val("off");
} else {
$('#txt_combo_quantity').attr('disabled','disabled');
$('input[name="ddl_combo"]').attr('disabled','disabled');
$("#cb_enable_combo").val("on");
}
});
});
</script>
</head>
<body>
<div class="ts-body-container">
<div class="ts-wrapper">
<div class="padding-top-large row">
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'header.php';
?>
</div>
<div class="ui grid">
<div class="row">
<div class="column">
<!-- Step -->
<div id='booking_step' class="ui four steps margin-top-normal">
<div class="ui disabled step">
Choose Cinema & Time Start
</div>
<div class="ui disabled step">
Choose Seats
</div>
<div class="ui active step">
Choose Combo
</div>
<div class="ui disabled step">
Coupon Code & Finish
</div>
</div>
<!-- End Step -->
<h1>Choose Combo</h1>
<form id="form_choose_combo" action="coupon_finish.php" method="post" name="form_choose_combo">
<div class="ui orange segment">
<table style="width: 50%; margin-left: auto; margin-right: auto;">
<tr>
<td style="text-align: right; padding-right: 5px; font-weight: bold;">Enable Combo:</td>
<td style="margin-left: 10px;" class="ui left icon input">
<div class="inline field">
<div id="togg" class="ui toggle checkbox">
<input id="cb_enable_combo" name="cb_enable_combo" type="checkbox" >
<label for="a"><span style="color: #D95C5C;">Disabled</span> / <span style="color: #A1CF64;">Enabled</span></label>
</div>
</div>
</td>
</tr>
<tr>
<td style="text-align: right; padding: 15px 0; font-weight: bold;">Select Combo:</td>
<td style="margin: 15px 0 15px 10px;" class="ui left icon input">
<?php
$list = api_combos::get_all_combos();
$item_id = 0;
$item_name = "-";
if (!empty($list) && count($list) > 0) {
$item_id = $list[0]['id'];
$item_name = $list[0]['name'];
}
?>
<div class="ui orange selection dropdown">
<input name="ddl_combo" type="hidden" value="<?php echo $item_id; ?>">
<div class="default text"><?php echo $item_name; ?></div>
<i class="dropdown icon"></i>
<div class="menu">
<?php
foreach ($list as $item) {
?>
<div class="item" data-value="<?php echo $item['id']; ?>"><?php echo $item['name']; ?></div>
<?php
}?>
</div>
</div>
</td>
</tr>
<tr>
<td style="text-align: right; padding-right: 5px; font-weight: bold;">Combo Quantity:</td>
<td style="margin-left: 10px;" class="ui left icon input">
<input name="txt_combo_quantity" id="txt_combo_quantity" type="text" placeholder="0">
<i class="inverted list icon"></i>
</td>
</tr>
</table>
</div>
<div class="ui orange segment">
<div class="ts-center">
<div class="ui buttons">
<!--<div class="ui green button">Back</div>-->
<a href="seat.php#booking_step" class="ui purple button">Back</a>
<div class="or"></div>
<!--<div class="ui orange button">Next</div>-->
<div onclick="submit_choose_combo();" class="ui orange button">Next</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="row">
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'footer.php';
?>
</div>
</div>
</div>
</body>
</html> | 09-movie | trunk/choose_combo.php | PHP | gpl3 | 8,017 |
<?php
//require section
require_once dirname(__FILE__) . '/shared/config/config.php';
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'check_session.php';
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'check_outside_booking.php';
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_pager.php';
require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_movies.php';
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'general_functions.php';
$title = 'Now Showing';
if (!empty($_POST)) {
}
?>
<!DOCTYPE html>
<html>
<head>
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'head.php';
?>
</head>
<body>
<div class="ts-body-container">
<div class="ts-wrapper">
<!--<div class="ui grid">-->
<div class="padding-top-large row">
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'header.php';
?>
<div class="ui segment breadcrumb" style="margin-top: 25px; margin-left: 20px;">
<a class="section" href="index.php">Home</a>
<i class="right arrow icon divider"></i>
<a class="section" href="now_showing.php">Movies</a>
<i class="right arrow icon divider"></i>
<div class="active section">Now Showing</div>
</div>
</div>
<div class="ui grid">
<div class="row">
<?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'book_ticket.php'; ?>
<div class="twelve wide column">
<h1>Now Showing</h1>
<div class="ui orange segment">
<div class="ui stackable items">
<?php
$list = api_movies::get_all_movies_with_now_showing();
$current_page = 1;
if (!empty($_GET['p'])) {
$current_page = $_GET['p'];
}
$list_total = $list;
$page_size = 9;
$lib_pager = new lib_pager($list_total, $page_size);
$total_page = $lib_pager->get_total_page();
$current_page_list = $lib_pager->get_current_page_list($current_page);
if (empty($current_page_list) || count($current_page_list) == 0) {
echo "No movie found.";
} else {
echo '<div class="row">';
foreach ($current_page_list as $key => $item) {
if ($key > 0 && $key % 3 == 0) {
echo '</div>';
echo '<div class="row">';
}
show_movie($item);
}
echo '</div>';
}?>
</div>
</div>
<div class="ts-center">
<div class="ui pagination menu">
<?php
if (!empty($total_page) && count($total_page) > 0) {?>
<a class="item" <?php if($current_page<=1){echo "onclick='return false'";} ?>
href="?p=<?php echo $current_page - 1;?>">
<i class="left arrow icon"></i> Previous
</a>
<?php
for ($page = 1; $page <= $total_page; $page++) { ?>
<a class="item" href="?p=<?php echo $page; ?>"><?php echo $page; ?></a>
<?php
}?>
<a class="item" <?php if($current_page>=$total_page){echo "onclick='return false'";} ?>
href="?p=<?php echo $current_page + 1;?>">
Next <i class="icon right arrow"></i>
</a>
<?php
} ?>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<?php
require_once DOCUMENT_ROOT . DIR_INCLUDE . 'footer.php';
?>
</div>
<!--</div>-->
</div>
</div>
</body>
</html> | 09-movie | trunk/now_showing.php | PHP | gpl3 | 5,243 |
<?php
// define('LINK_ROOT', 'http://'. $_SERVER['HTTP_HOST']);
// define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT']);
define('LINK_ROOT', 'http://' . $_SERVER['HTTP_HOST'] . '/09_movie');
define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT'] . '/09_movie');
define('DIR_ADMIN', '/admin/');
define('DIR_ADMIN_INCLUDE', '/admin/include/');
define('DIR_INCLUDE', '/include/');
define('DIR_AJAX', '/ajax/');
define('DIR_SKRILL_PAYMENT', '/skrill_payment/');
define('DIR_SHARED_LAYOUT', '/shared/layout/');
define('DIR_SHARED_LAYOUT_CSS', '/shared/layout/css/');
define('DIR_SHARED_LAYOUT_JS', '/shared/layout/js/');
define('DIR_SHARED_LAYOUT_IMAGES', '/shared/layout/images/');
define('DIR_SHARED_LAYOUT_IMAGES_TICKET', '/shared/layout/images/ticket/');
define('DIR_SHARED_LAYOUT_IMAGES_ICONS', '/shared/layout/images/icons/');
define('DIR_SHARED_LAYOUT_IMAGES_SLIDESHOW', '/shared/layout/images/slideshow/');
define('DIR_SHARED_LAYOUT_SEMANTIC', '/shared/layout/semantic/');
define('DIR_SHARED_LAYOUT_SEMANTIC_CSS', '/shared/layout/semantic/css/');
define('DIR_SHARED_LAYOUT_SEMANTIC_JS', '/shared/layout/semantic/javascript/');
define('DIR_SHARED_LAYOUT_BOOTSTRAP', '/shared/layout/bootstrap/');
define('DIR_SHARED_LAYOUT_BOOTSTRAP_CSS', '/shared/layout/bootstrap/css/');
define('DIR_SHARED_LAYOUT_BOOTSTRAP_JS', '/shared/layout/bootstrap/js/');
define('DIR_SHARED_LAYOUT_UIKIT', '/shared/layout/uikit/');
define('DIR_SHARED_LAYOUT_UIKIT_CSS', '/shared/layout/uikit/css/');
define('DIR_SHARED_LAYOUT_UIKIT_JS', '/shared/layout/uikit/js/');
define('DIR_SHARED_PLUGIN_WOWSLIDER', '/shared/plugin/wowslider/');
define('DIR_SHARED_PLUGIN_WOWSLIDER_CSS', '/shared/plugin/wowslider/css/');
define('DIR_SHARED_PLUGIN_WOWSLIDER_JS', '/shared/plugin/wowslider/js/');
define('DIR_SHARED_PLUGIN_DATETIMEPICKERMASTER', '/shared/plugin/datetimepicker-master/');
define('DIR_SHARED', '/shared/');
define('DIR_SHARED_CONFIG', '/shared/config/');
define('DIR_SHARED_API', '/shared/api/');
define('DIR_SHARED_DAO', '/shared/dao/');
define('DIR_SHARED_LIBRARIES', '/shared/libraries/');
define('DIR_SHARED_PLUGIN', '/shared/plugin/');
define('DIR_SHARED_UPLOAD', '/shared/upload/');
define('DIR_SHARED_UPLOAD_DOCUMENTS', '/shared/upload/documents/');
define('DIR_SHARED_UPLOAD_IMAGES', '/shared/upload/images/');
define('DIR_SHARED_UPLOAD_IMAGES_POSTERS', '/shared/upload/images/posters/');
define('DIR_SHARED_UPLOAD_IMAGES_CINEMAS', '/shared/upload/images/cinemas/');
define('DIR_SHARED_UPLOAD_IMAGES_COMBOS', '/shared/upload/images/combos/');
class config {
private $db_name = '09_movie';
private $db_host = 'localhost';
private $db_user = 'root';
private $db_pass = '';
public function get_db_name() {
return $this->db_name;
}
public function get_db_host() {
return $this->db_host;
}
public function get_db_user() {
return $this->db_user;
}
public function get_db_pass() {
return $this->db_pass;
}
}
| 09-movie | trunk/shared/config/config.php | PHP | gpl3 | 3,050 |
<?php
require_once dirname(__FILE__) . '/config.php';
class connection {
public $con;
public function __construct() {
}
public function open_connect() {
$config = new config();
$db_host = $config->get_db_host();
$db_user = $config->get_db_user();
$db_pass = $config->get_db_pass();
$db_name = $config->get_db_name();
$this->con = new mysqli($db_host, $db_user, $db_pass, $db_name) or die("Can't connect to database");
$this->con->set_charset("utf8");
return $this->con;
}
public function close_connect() {
mysqli_close($this->con);
}
}
| 09-movie | trunk/shared/config/connection.php | PHP | gpl3 | 674 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php';
class dao_booking {
//Methods
public function __construct() {
}
public function get_all_paid() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT ms.email AS user_email, CONCAT_WS(' ', ms.first_name, ms.last_name) AS user_full_name, "
. "tk.name AS ticket_name, cp.coupon_code AS coupon_code, "
. "cb.name AS combo_name, m.* "
. "FROM tbl_booking m LEFT JOIN tbl_user ms ON m.user_id = ms.id "
. "LEFT JOIN tbl_ticket tk ON m.ticket_id = tk.id "
. "LEFT JOIN tbl_coupon cp ON m.coupon_id = cp.id "
. "LEFT JOIN tbl_combo cb ON m.combo_id = cb.id "
. "WHERE is_paid = 1";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function get_all() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT ms.email AS user_email, CONCAT_WS(' ', ms.first_name, ms.last_name) AS user_full_name, "
. "tk.name AS ticket_name, cp.coupon_code AS coupon_code, "
. "cb.name AS combo_name, m.* "
. "FROM tbl_booking m LEFT JOIN tbl_user ms ON m.user_id = ms.id "
. "LEFT JOIN tbl_ticket tk ON m.ticket_id = tk.id "
. "LEFT JOIN tbl_coupon cp ON m.coupon_id = cp.id "
. "LEFT JOIN tbl_combo cb ON m.combo_id = cb.id";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function get_all_by_status_id($status_id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT ms.name AS status_name, m.* "
. "FROM tbl_booking m LEFT JOIN tbl_booking_status ms ON m.status_id = ms.id "
. "WHERE ms.id = " . $status_id;
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function update_generated_code($id, $code) {
$db = new connection();
$con = $db->open_connect();
$query = "UPDATE tbl_booking SET "
. "generated_code = '" . $code . "' "
. "WHERE id = " . $id;
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function update_paid($id) {
$db = new connection();
$con = $db->open_connect();
$query = "UPDATE tbl_booking SET "
. "is_paid = 1 "
. "WHERE id = " . $id;
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function save($id, $user_id, $ticket_id,
$ticket_quantity_solve, $coupon_id, $combo_id,
$combo_quantity_solve, $total_money, $paid) {
$db = new connection();
$con = $db->open_connect();
if ($id == 0) {
$query = "INSERT INTO tbl_booking(user_id, ticket_id, ticket_quantity, coupon_id, combo_id, combo_quantity, total_money, is_paid) VALUES (
" . $user_id . "," . $ticket_id . "," . $ticket_quantity_solve . "," . $coupon_id . "," . $combo_id . "," . $combo_quantity_solve . "," . $total_money . "," . $paid . ")";
} else {
$query = "UPDATE tbl_booking SET "
. "user_id = '" . $user_id . "',"
. "ticket_id = " . $ticket_id . ","
. "ticket_quantity = '" . $ticket_quantity_solve . "',"
. "coupon_id = '" . $coupon_id . "',"
. "combo_id = '" . $combo_id . "',"
. "combo_quantity = '" . $combo_quantity_solve . "',"
. "total_money = '" . $total_money . "', "
. "is_paid = " . $paid . " "
. "WHERE id = " . $id;
}
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$inserted_id = TRUE;
if ($id == 0) {
$inserted_id = mysqli_insert_id($db->con);
}
$db->close_connect();
return $inserted_id;
}
public function get_by_id($id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT ms.email AS user_email, CONCAT_WS(' ', ms.first_name, ms.last_name) AS user_full_name, "
. "tk.name AS ticket_name, cp.coupon_code AS coupon_code, "
. "cb.name AS combo_name, m.* "
. "FROM tbl_booking m LEFT JOIN tbl_user ms ON m.user_id = ms.id "
. "LEFT JOIN tbl_ticket tk ON m.ticket_id = tk.id "
. "LEFT JOIN tbl_coupon cp ON m.coupon_id = cp.id "
. "LEFT JOIN tbl_combo cb ON m.combo_id = cb.id WHERE m.id = " . $id;
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function delete($id) {
$db = new connection();
$con = $db->open_connect();
$query = "DELETE FROM tbl_booking WHERE id = " . $id;
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_by_code($code) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * "
. "FROM tbl_booking "
. "WHERE generated_code = '" . $code . "'";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
}
| 09-movie | trunk/shared/dao/dao_booking.php | PHP | gpl3 | 6,763 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php';
class dao_discount_type {
//Methods
public function __construct() {
}
public function get_all() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * "
. "FROM tbl_discount_type";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function get_all_by_status_id($status_id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT ms.name AS status_name, m.* "
. "FROM tbl_discount_type m LEFT JOIN tbl_discount_type_status ms ON m.status_id = ms.id "
. "WHERE ms.id = " . $status_id;
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function save($id, $name, $address, $image, $city_id) {
$db = new connection();
$con = $db->open_connect();
if ($id == 0) {
$query = "INSERT INTO tbl_discount_type(name, address, image, city_id) VALUES (
'" . $name . "','" . $address . "','" . $image . "'," . $city_id . ")";
} else {
$query = "UPDATE tbl_discount_type SET "
. "name = '" . $name . "',"
. "address = '" . $address . "',"
. "image = '" . $image . "',"
. "city_id = " . $city_id . " "
. "WHERE id = " . $id;
}
echo $query;
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_by_id($id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT ms.name AS status_name, m.* FROM tbl_discount_type m LEFT JOIN tbl_discount_type_status ms ON m.status_id = ms.id WHERE m.id = " . $id;
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function get_first() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * FROM tbl_discount_type LIMIT 0, 1";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function delete($id) {
$db = new connection();
$con = $db->open_connect();
$query = "DELETE FROM tbl_discount_type WHERE id = " . $id;
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_id_by_name($name) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT id FROM tbl_discount_type WHERE UPPER(name) = UPPER('" . $name ."') LIMIT 0, 1";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
}
| 09-movie | trunk/shared/dao/dao_discount_type.php | PHP | gpl3 | 3,816 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php';
class dao_city {
//Methods
public function __construct() {
}
public function get_all() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * "
. "FROM tbl_city";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function get_all_by_status_id($status_id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT ms.name AS status_name, m.* "
. "FROM tbl_city m LEFT JOIN tbl_city_status ms ON m.status_id = ms.id "
. "WHERE ms.id = " . $status_id;
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function save($id, $title, $status_id, $description, $poster) {
$db = new connection();
$con = $db->open_connect();
if ($id == 0) {
$query = "INSERT INTO tbl_city(title, status_id, description, poster) VALUES (
'" . $title . "'," . $status_id . ",'" . $description . "','" . $poster . "')";
} else {
$query = "UPDATE tbl_city SET "
. "title = '" . $title . "',"
. "status_id = " . $status_id . ","
. "description = '" . $description . "',"
. "poster = '" . $poster . "' "
. "WHERE id = " . $id;
}
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_by_id($id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * FROM tbl_city WHERE id = " . $id;
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function get_id_by_name($name) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT id "
. "FROM tbl_city "
. "WHERE UPPER(name) = UPPER('" . $name ."') LIMIT 0, 1";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function delete($id) {
$db = new connection();
$con = $db->open_connect();
$query = "DELETE FROM tbl_city WHERE id = " . $id;
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_first() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * FROM tbl_city LIMIT 0, 1";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
}
| 09-movie | trunk/shared/dao/dao_city.php | PHP | gpl3 | 3,645 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php';
class dao_combo {
//Methods
public function __construct() {
}
public function get_all() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * "
. "FROM tbl_combo m";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function get_all_by_status_id($status_id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT ms.name AS status_name, m.* "
. "FROM tbl_combo m LEFT JOIN tbl_combo_status ms ON m.status_id = ms.id "
. "WHERE ms.id = " . $status_id;
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function save($id, $name, $description, $price, $image) {
$db = new connection();
$con = $db->open_connect();
if ($id == 0) {
$query = "INSERT INTO tbl_combo(name, description, price, image) VALUES (
'" . $name . "','" . $description . "'," . $price . ",'" . $image . "')";
} else {
$query = "UPDATE tbl_combo SET "
. "name = '" . $name . "',"
. "description = '" . $description . "',"
. "price = " . $price . ","
. "image = '" . $image . "' "
. "WHERE id = " . $id;
}
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_by_id($id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * "
. "FROM tbl_combo m WHERE m.id = " . $id;
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function delete($id) {
$db = new connection();
$con = $db->open_connect();
$query = "DELETE FROM tbl_combo WHERE id = " . $id;
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_first() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * FROM tbl_combo LIMIT 0, 1";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function get_id_by_name($name) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT id FROM tbl_combo WHERE UPPER(name) = UPPER('" . $name ."') LIMIT 0, 1";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
}
| 09-movie | trunk/shared/dao/dao_combo.php | PHP | gpl3 | 3,661 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php';
class dao_seat {
//Methods
public function __construct() {
}
public function get_all() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * "
. "FROM tbl_seat ";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row_pos = mysqli_fetch_array($result)) {
array_push($list, $row_pos);
}
$db->close_connect();
return $list;
}
public function get_all_columns($ticket_id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT distinct s.column_pos "
. "FROM tbl_seat s "
. "WHERE s.ticket_id = " . $ticket_id . " "
. "ORDER BY s.column_pos ASC";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row_pos = mysqli_fetch_array($result)) {
array_push($list, $row_pos);
}
$db->close_connect();
return $list;
}
public function get_all_rows($ticket_id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT distinct row_pos "
. "FROM tbl_seat "
. "WHERE ticket_id = " . $ticket_id . " "
. "ORDER BY row_pos ASC";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row_pos = mysqli_fetch_array($result)) {
array_push($list, $row_pos);
}
$db->close_connect();
return $list;
}
public function save($id, $row_pos, $column_pos, $ticket_id, $seat_status_id, $is_wheelchair) {
$db = new connection();
$con = $db->open_connect();
if ($id == 0) {
$query = "INSERT INTO tbl_seat(row_pos, column_pos, ticket_id, seat_status_id, is_wheelchair) VALUES (
'" . $row_pos . "','" . $column_pos . "'," . $ticket_id . "," . $seat_status_id . "," . $is_wheelchair . ")";
} else { // no update is_wheelchair
$query = "UPDATE tbl_seat SET "
. "row_pos = '" . $row_pos . "',"
. "column_pos = '" . $column_pos . "',"
. "ticket_id = " . $ticket_id . ","
. "seat_status_id = " . $seat_status_id . " "
. "WHERE id = " . $id;
}
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function update_seat_status($id, $seat_status_id) {
$db = new connection();
$con = $db->open_connect();
if ($id != 0) {
$query = "UPDATE tbl_seat SET "
. "seat_status_id = " . $seat_status_id . " "
. "WHERE id = " . $id;
}
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_by_id($id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * "
. "FROM tbl_seat "
. "WHERE id = " . $id;
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row_pos = mysqli_fetch_array($result);
$db->close_connect();
return $row_pos;
}
public function get_by_position($ticket_id, $row_pos, $column_pos) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT s.*, ss.image AS seat_status_image, ss.id AS seat_status_id "
. "FROM tbl_seat s LEFT JOIN tbl_seat_status ss ON s.seat_status_id = ss.id "
. "WHERE s.ticket_id = " . $ticket_id . " "
. "AND s.row_pos = '" . $row_pos . "' "
. "AND s.column_pos = '" . $column_pos . "' ";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row_pos = mysqli_fetch_array($result);
$db->close_connect();
return $row_pos;
}
public function delete($id) {
$db = new connection();
$con = $db->open_connect();
$query = "DELETE FROM tbl_seat WHERE id = " . $id;
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
}
| 09-movie | trunk/shared/dao/dao_seat.php | PHP | gpl3 | 4,912 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php';
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_date.php';
class dao_ticket {
//Methods
public function __construct() {
}
public function get_all_dead() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT cn.city_id AS city_id, ms.title AS movie_title, cn.name AS cinema_name, m.* "
. "FROM tbl_ticket m LEFT JOIN tbl_movie ms ON m.movie_id = ms.id "
. "LEFT JOIN tbl_cinema cn ON m.cinema_id = cn.id "
. "WHERE 1 ";
$now = lib_date::get_now();
$date = lib_date::convert_to_sql_date($now, "Y-m-d H:i:s");
$time = lib_date::convert_to_sql_time($now, "Y-m-d H:i:s");
$query .= "AND NOT ("
. "m.show_date > '" . $date . "' "
. "OR (m.show_date = '" . $date . "' AND m.time_start > '" . $time . "') "
. ") ";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function get_all_live() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT cn.city_id AS city_id, ms.title AS movie_title, cn.name AS cinema_name, m.* "
. "FROM tbl_ticket m LEFT JOIN tbl_movie ms ON m.movie_id = ms.id "
. "LEFT JOIN tbl_cinema cn ON m.cinema_id = cn.id "
. "WHERE 1 ";
$now = lib_date::get_now();
$date = lib_date::convert_to_sql_date($now, "Y-m-d H:i:s");
$time = lib_date::convert_to_sql_time($now, "Y-m-d H:i:s");
$query .= "AND ("
. "m.show_date > '" . $date . "' "
. "OR (m.show_date = '" . $date . "' AND m.time_start > '" . $time . "') "
. ") ";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function get_all() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT cn.city_id AS city_id, ms.title AS movie_title, cn.name AS cinema_name, m.* "
. "FROM tbl_ticket m LEFT JOIN tbl_movie ms ON m.movie_id = ms.id "
. "LEFT JOIN tbl_cinema cn ON m.cinema_id = cn.id";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function get_all_by_filters($ticket_quantity, $city_id, $cinema_id, $movie_id, $show_date, $time_start) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT cn.city_id AS city_id, ci.name AS city_name, ms.title AS movie_title, cn.name AS cinema_name, m.* "
. "FROM tbl_ticket m LEFT JOIN tbl_movie ms ON m.movie_id = ms.id "
. "LEFT JOIN tbl_cinema cn ON m.cinema_id = cn.id "
. "LEFT JOIN tbl_city ci ON cn.city_id = ci.id "
. "WHERE 1 ";
$now = lib_date::get_now();
$date = lib_date::convert_to_sql_date($now, "Y-m-d H:i:s");
$time = lib_date::convert_to_sql_time($now, "Y-m-d H:i:s");
$query .= "AND ("
. "m.show_date > '" . $date . "' "
. "OR (m.show_date = '" . $date . "' AND m.time_start > '" . $time . "') "
. ") ";
if (!empty($ticket_quantity) && $ticket_quantity > 0) {
$query .= "AND m.available_seats >= " . $ticket_quantity . " ";
}
if (!empty($city_id) && $city_id > 0) {
$query .= "AND cn.city_id = " . $city_id . " ";
}
if (!empty($cinema_id) && $cinema_id > 0) {
$query .= "AND m.cinema_id = " . $cinema_id . " ";
}
if (!empty($movie_id) && $movie_id > 0) {
$query .= "AND m.movie_id = " . $movie_id . " ";
}
if (!empty($show_date)) {
$query .= "AND m.show_date = '" . $show_date . "' ";
}
if (!empty($time_start)) {
$query .= "AND m.time_start = '" . $time_start . "' ";
}
$query .= "ORDER BY m.cinema_id ASC, m.time_start ASC ";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function get_all_by_status_id($status_id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT ms.name AS status_name, m.* "
. "FROM tbl_ticket m LEFT JOIN tbl_ticket_status ms ON m.status_id = ms.id "
. "WHERE ms.id = " . $status_id;
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function update_available($id, $available) {
$db = new connection();
$con = $db->open_connect();
if ($id != 0) {
$query = "UPDATE tbl_ticket SET "
. "available_seats = '" . $available . "' "
. "WHERE id = " . $id;
}
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function save($id, $name, $show_date,
$time_start, $duration, $movie_id, $cinema_id, $price, $total_seats, $available_seats) {
$db = new connection();
$con = $db->open_connect();
if ($id == 0) {
$query = "INSERT INTO tbl_ticket(name, show_date, time_start, duration, movie_id, cinema_id, price, total_seats, available_seats) VALUES (
'" . $name . "','" . $show_date . "','" . $time_start . "'," . $duration . "," . $movie_id . "," . $cinema_id . "," . $price . "," . $total_seats . "," . $available_seats . ")";
} else {// no update $total_seats, $available_seats
$query = "UPDATE tbl_ticket SET "
. "name = '" . $name . "',"
. "show_date = '" . $show_date . "',"
. "time_start = '" . $time_start . "',"
. "duration = " . $duration . ","
. "movie_id = " . $movie_id . ","
. "cinema_id = " . $cinema_id . ","
. "price = " . $price . " "
. "WHERE id = " . $id;
}
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$inserted_id = mysqli_insert_id($db->con);
$db->close_connect();
return $inserted_id;
}
public function get_by_id($id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT ms.title AS movie_title, cn.name AS cinema_name, m.* "
. "FROM tbl_ticket m LEFT JOIN tbl_movie ms ON m.movie_id = ms.id "
. "LEFT JOIN tbl_cinema cn ON m.cinema_id = cn.id WHERE m.id = " . $id;
// echo $query;
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function delete($id) {
$db = new connection();
$con = $db->open_connect();
$query = "DELETE FROM tbl_ticket WHERE id = " . $id;
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_first() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * FROM tbl_ticket LIMIT 0, 1";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function get_id_by_name($name) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT id FROM tbl_ticket WHERE UPPER(name) = UPPER('" . $name ."') LIMIT 0, 1";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
}
| 09-movie | trunk/shared/dao/dao_ticket.php | PHP | gpl3 | 9,413 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php';
class dao_booking_line {
//Methods
public function __construct() {
}
public function get_all() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * "
. "FROM tbl_booking_line ";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function save($id, $booking_id, $row_pos,
$column_pos) {
$db = new connection();
$con = $db->open_connect();
if ($id == 0) {
$query = "INSERT INTO tbl_booking_line(booking_id, row_pos, column_pos) VALUES (
" . $booking_id . ",'" . $row_pos . "','" . $column_pos . "')";
} else {
$query = "UPDATE tbl_booking_line SET "
. "booking_id = '" . $booking_id . "',"
. "row_pos = " . $row_pos . ","
. "column_pos = '" . $column_pos . "' "
. "WHERE id = " . $id;
}
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$inserted_id = TRUE;
if ($id == 0) {
$inserted_id = mysqli_insert_id($db->con);
}
$db->close_connect();
return $inserted_id;
}
public function get_by_id($id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * "
. "FROM tbl_booking_line "
. "WHERE id = " . $id;
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function get_all_by_booking_id($booking_id, $user_id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT bl.* "
. "FROM tbl_booking_line bl "
. "LEFT JOIN tbl_booking b ON bl.booking_id = b.id "
. "WHERE booking_id = " . $booking_id . " "
. "AND b.user_id = " . $user_id;
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function get_by_position($booking_id, $row_pos, $column_pos) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * "
. "FROM tbl_booking_line "
. "WHERE booking_id = " . $booking_id . " "
. "AND row_pos = '" . $row_pos . "' "
. "AND column_pos = '" . $column_pos . "' ";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function delete($id) {
$db = new connection();
$con = $db->open_connect();
$query = "DELETE FROM tbl_booking_line WHERE id = " . $id;
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function delete_by_booking_id($booking_id) {
$db = new connection();
$con = $db->open_connect();
$query = "DELETE FROM tbl_booking_line "
. "WHERE booking_id = " . $booking_id . " ";
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
}
| 09-movie | trunk/shared/dao/dao_booking_line.php | PHP | gpl3 | 4,108 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php';
class dao_user {
//Methods
public function __construct() {
}
public function get_all() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT u.*, c.name AS cinema_name "
. "FROM tbl_user u "
. "LEFT JOIN tbl_cinema c ON u.cinema_id = c.id "
. "WHERE u.role_id = 2 ";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function active($id) {
$db = new connection();
$con = $db->open_connect();
$query = "UPDATE tbl_user SET "
. "status_id = 2 "
. "WHERE id = " . $id;
// echo $query;
// exit();
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_by_activate_code($email, $activate_code) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * FROM tbl_user "
. "WHERE role_id = 2 "
. "AND email = '" . $email . "' "
. "AND activate_code = '" . $activate_code . "' ";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function save($user_id, $first_name,
$last_name, $phone_number, $email, $password, $role_id,
$user_cinema_id, $activate_code) {
$db = new connection();
$con = $db->open_connect();
if ($user_id == 0) {
$query = "INSERT INTO tbl_user(email, password, role_id,
first_name, last_name, phone_number, cinema_id, activate_code) VALUES (
'" . $email . "','" . md5($password) . "'," . $role_id . ",'" . $first_name . "','" . $last_name . "','" . $phone_number . "','" . $user_cinema_id . "','$activate_code')";
} else {
$query = "UPDATE tbl_user SET "
. "email = '" . $email . "',"
. "password = '" . md5($password) . "',"
. "role_id = " . $role_id . ","
. "first_name = '" . $first_name . "',"
. "last_name = '" . $last_name . "',"
. "phone_number = '" . $phone_number . "', "
. "cinema_id = " . $user_cinema_id . ", "
. "activate_code = '" . $activate_code . "' "
. "WHERE id = " . $user_id;
}
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$inserted_id = TRUE;
if ($user_id == 0) {
$inserted_id = mysqli_insert_id($db->con);
}
$db->close_connect();
return $inserted_id;
}
public function get_cinema_user($cinema_id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * FROM tbl_user "
. "WHERE role_id = 2 "
. "AND cinema_id = " . $cinema_id;
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function get_by_id($id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * FROM tbl_user WHERE role_id = 2 AND id = " . $id;
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function delete($id) {
$db = new connection();
$con = $db->open_connect();
$query = "DELETE FROM tbl_user WHERE id = " . $id;
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_by_login_info($email, $password) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * FROM tbl_user u JOIN tbl_role r ON u.role_id = r.id "
. "WHERE email = '" . $email . "' "
. "AND password = '" . md5($password) . "' "
. "AND status_id = 2 ";
$result = mysqli_query($con, $query);
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
return mysqli_fetch_array($result);
}
public function get_by_email($email) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * FROM tbl_user u JOIN tbl_role r ON u.role_id = r.id "
. "WHERE email = '" . $email . "'";
$result = mysqli_query($con, $query);
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
return mysqli_fetch_array($result);
}
public function get_first() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * FROM tbl_user "
. "WHERE role_id = 2 "
. "LIMIT 0, 1";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
}
| 09-movie | trunk/shared/dao/dao_user.php | PHP | gpl3 | 6,014 |
<?php
/**
* User: Viet Anh
* Date: 10/06/2014
* Time: 23:31
*/
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php';
class dao_option
{
public function __construct()
{
}
public function get_option_value($name)
{
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * FROM tbl_option WHERE name = '$name'";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row['value'];
}
public function set_option_value($name, $value)
{
$db = new connection();
$con = $db->open_connect();
$query = "UPDATE tbl_option SET value = '$value' WHERE name = '$name'";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
} | 09-movie | trunk/shared/dao/dao_option.php | PHP | gpl3 | 1,201 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php';
class dao_seat_status {
//Methods
public function __construct() {
}
public function get_all() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * "
. "FROM tbl_seat_status ";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function save($id, $seat_status_code, $discount_type_id, $discount_number) {
$db = new connection();
$con = $db->open_connect();
if ($id == 0) {
$query = "INSERT INTO tbl_seat_status(seat_status_code, discount_type_id, discount_number) VALUES (
'" . $seat_status_code . "'," . $discount_type_id . "," . $discount_number . ")";
} else {
$query = "UPDATE tbl_seat_status SET "
. "seat_status_code = '" . $seat_status_code . "',"
. "discount_type_id = " . $discount_type_id . ","
. "discount_number = " . $discount_number . " "
. "WHERE id = " . $id;
}
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_by_id($id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * "
. "FROM tbl_seat_status "
. "WHERE id = " . $id;
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function delete($id) {
$db = new connection();
$con = $db->open_connect();
$query = "DELETE FROM tbl_seat_status WHERE id = " . $id;
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
}
| 09-movie | trunk/shared/dao/dao_seat_status.php | PHP | gpl3 | 2,349 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php';
class dao_movie_status {
//Methods
public function __construct() {
}
public function get_all() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * FROM tbl_movie_status";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function save($id, $name) {
$db = new connection();
$con = $db->open_connect();
if ($id == 0) {
$query = "INSERT INTO tbl_movie_status(name) VALUES (
'" . $name . "')";
} else {
$query = "UPDATE tbl_movie_status SET "
. "name = '" . $name . "' "
. "WHERE id = " . $id;
}
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_by_id($id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * FROM tbl_movie_status WHERE id = " . $id;
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function delete($id) {
$db = new connection();
$con = $db->open_connect();
$query = "DELETE FROM tbl_movie_status WHERE id = " . $id;
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_first() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * FROM tbl_movie_status LIMIT 0, 1";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function get_id_by_name($name) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT id FROM tbl_movie_status WHERE UPPER(name) = UPPER('" . $name ."') LIMIT 0, 1";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
}
| 09-movie | trunk/shared/dao/dao_movie_status.php | PHP | gpl3 | 2,762 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php';
class dao_movie {
//Methods
public function __construct() {
}
public function get_all() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT ms.name AS status_name, m.* FROM tbl_movie m LEFT JOIN tbl_movie_status ms ON m.status_id = ms.id";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function get_all_by_status_id($status_id, $entry_number) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT ms.name AS status_name, m.* "
. "FROM tbl_movie m LEFT JOIN tbl_movie_status ms ON m.status_id = ms.id "
. "WHERE ms.id = " . $status_id . " ";
if (!empty($entry_number) && $entry_number > 0) {
$query .= "LIMIT 0, " . $entry_number;
}
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function save($id, $title, $status_id, $description, $poster) {
$db = new connection();
$con = $db->open_connect();
if ($id == 0) {
$query = "INSERT INTO tbl_movie(title, status_id, description, poster) VALUES (
'" . $title . "'," . $status_id . ",'" . $description . "','" . $poster . "')";
} else {
$query = "UPDATE tbl_movie SET "
. "title = '" . $title . "',"
. "status_id = " . $status_id . ","
. "description = '" . $description . "',"
. "poster = '" . $poster . "' "
. "WHERE id = " . $id;
}
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_by_id($id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT ms.name AS status_name, m.* FROM tbl_movie m LEFT JOIN tbl_movie_status ms ON m.status_id = ms.id WHERE m.id = " . $id;
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function get_first() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * FROM tbl_movie LIMIT 0, 1";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function delete($id) {
$db = new connection();
$con = $db->open_connect();
$query = "DELETE FROM tbl_movie WHERE id = " . $id;
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_id_by_title($title) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT id FROM tbl_movie WHERE UPPER(title) = UPPER('" . $title ."') LIMIT 0, 1";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
}
| 09-movie | trunk/shared/dao/dao_movie.php | PHP | gpl3 | 3,948 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php';
class dao_cinema {
//Methods
public function __construct() {
}
public function get_all() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT ms.name AS city_name, m.* FROM tbl_cinema m LEFT JOIN tbl_city ms ON m.city_id = ms.id";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function get_all_by_status_id($status_id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT ms.name AS status_name, m.* "
. "FROM tbl_cinema m LEFT JOIN tbl_cinema_status ms ON m.status_id = ms.id "
. "WHERE ms.id = " . $status_id;
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function save($id, $name, $address, $image, $city_id, $latitude, $longitude) {
$db = new connection();
$con = $db->open_connect();
if ($id == 0) {
$query = "INSERT INTO tbl_cinema(name, address, image, city_id, latitude, longitude) VALUES (
'" . $name . "','" . $address . "','" . $image . "'," . $city_id . "," . $latitude . "," . $longitude . ")";
} else {
$query = "UPDATE tbl_cinema SET "
. "name = '" . $name . "',"
. "address = '" . $address . "',"
. "image = '" . $image . "',"
. "latitude = '" . $latitude . "',"
. "longitude = '" . $longitude . "',"
. "city_id = " . $city_id . " "
. "WHERE id = " . $id;
}
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_by_id($id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT ms.name AS city_name, m.* FROM tbl_cinema m LEFT JOIN tbl_city ms ON m.city_id = ms.id WHERE m.id = " . $id;
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function get_first() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * FROM tbl_cinema LIMIT 0, 1";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function delete($id) {
$db = new connection();
$con = $db->open_connect();
$query = "DELETE FROM tbl_cinema WHERE id = " . $id;
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_id_by_name($name) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT id FROM tbl_cinema WHERE UPPER(name) = UPPER('" . $name ."') LIMIT 0, 1";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
}
| 09-movie | trunk/shared/dao/dao_cinema.php | PHP | gpl3 | 3,896 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php';
class dao_seat_template {
//Methods
public function __construct() {
}
public function get_all() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * "
. "FROM tbl_seat_template ";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function save($id, $seat_status_code, $discount_type_id, $discount_number) {
$db = new connection();
$con = $db->open_connect();
if ($id == 0) {
$query = "INSERT INTO tbl_seat_template(seat_status_code, discount_type_id, discount_number) VALUES (
'" . $seat_status_code . "'," . $discount_type_id . "," . $discount_number . ")";
} else {
$query = "UPDATE tbl_seat_template SET "
. "seat_status_code = '" . $seat_status_code . "',"
. "discount_type_id = " . $discount_type_id . ","
. "discount_number = " . $discount_number . " "
. "WHERE id = " . $id;
}
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_by_id($id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * "
. "FROM tbl_seat_template "
. "WHERE id = " . $id;
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function delete($id) {
$db = new connection();
$con = $db->open_connect();
$query = "DELETE FROM tbl_seat_template WHERE id = " . $id;
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function count_all() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * "
. "FROM tbl_seat_template ";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$db->close_connect();
return mysqli_num_rows($result);
}
}
| 09-movie | trunk/shared/dao/dao_seat_template.php | PHP | gpl3 | 2,744 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php';
class dao_coupon {
//Methods
public function __construct() {
}
public function get_all() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT cp.*, dt.name AS type_name, dt.unit AS type_unit "
. "FROM tbl_coupon cp LEFT JOIN tbl_discount_type dt ON cp.discount_type_id = dt.id";
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function get_all_by_status_id($status_id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT ms.name AS status_name, m.* "
. "FROM tbl_coupon m LEFT JOIN tbl_coupon_status ms ON m.status_id = ms.id "
. "WHERE ms.id = " . $status_id;
$result = mysqli_query($con, $query)
or die("Query fail: " . mysqli_error());
$list = array();
while ($row = mysqli_fetch_array($result)) {
array_push($list, $row);
}
$db->close_connect();
return $list;
}
public function save($id, $coupon_code, $discount_type_id, $discount_number) {
$db = new connection();
$con = $db->open_connect();
if ($id == 0) {
$query = "INSERT INTO tbl_coupon(coupon_code, discount_type_id, discount_number) VALUES (
'" . $coupon_code . "'," . $discount_type_id . "," . $discount_number . ")";
} else {
$query = "UPDATE tbl_coupon SET "
. "coupon_code = '" . $coupon_code . "',"
. "discount_type_id = " . $discount_type_id . ","
. "discount_number = " . $discount_number . " "
. "WHERE id = " . $id;
}
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_by_id($id) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT cp.*, dt.name AS type_name, dt.unit AS type_unit "
. "FROM tbl_coupon cp LEFT JOIN tbl_discount_type dt ON cp.discount_type_id = dt.id "
. "WHERE cp.id = " . $id;
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function delete($id) {
$db = new connection();
$con = $db->open_connect();
$query = "DELETE FROM tbl_coupon WHERE id = " . $id;
mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$db->close_connect();
return TRUE;
}
public function get_first() {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT * FROM tbl_coupon LIMIT 0, 1";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
public function get_id_by_coupon_code($coupon_code) {
$db = new connection();
$con = $db->open_connect();
$query = "SELECT id FROM tbl_coupon WHERE UPPER(coupon_code) = UPPER('" . $coupon_code ."') LIMIT 0, 1";
$result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());
$row = mysqli_fetch_array($result);
$db->close_connect();
return $row;
}
}
| 09-movie | trunk/shared/dao/dao_coupon.php | PHP | gpl3 | 3,965 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
class lib_redirect {
// public static function Redirect($redirect_link, $permanent = false) {
// if (headers_sent() === false) {
// header('Location: ' . LINK_ROOT . $redirect_link, true, ($permanent === true) ? 301 : 302);
// }
// exit();
// }
//
// public static function redirect_with_html($redirect_link) {
// $redirect = "<script type='text/javascript'>window.location='" . LINK_ROOT . $redirect_link . "'</script>";
// echo $redirect;
// }
public static function Redirect($url) {
if (!headers_sent()) {
header('Location: ' . LINK_ROOT . $url);
exit;
} else {
echo '<script type="text/javascript">';
echo 'window.location.href="' . LINK_ROOT . $url . '";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url=' . LINK_ROOT . $url . '" />';
echo '</noscript>';
exit;
}
}
}
| 09-movie | trunk/shared/libraries/lib_redirect.php | PHP | gpl3 | 1,117 |
<?php
class lib_upload {
public $input_control_name;
public $upload_location;
public function __construct() {
}
public function upload_file($input_control_name, $upload_location) {
$name = $_FILES[$input_control_name]['name'];
$tmp_name = $_FILES[$input_control_name]['tmp_name'];
$upload_location .= $name;
move_uploaded_file($tmp_name, $upload_location) or die('Upload file failed!');
return true;
}
}
| 09-movie | trunk/shared/libraries/lib_upload.php | PHP | gpl3 | 502 |
<?php
class lib_code_generator {
public function __construct() {
}
public static function generate_random_string($length = 8) {
$characters = '0123456789abcdefghijklmnopqrst uvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$string = '';
for ($p = 0; $p < $length; $p++) {
$num = strlen($characters) - 1;
$m = mt_rand(0, $num);
$string .= $characters[$m];
}
return $string;
}
}
| 09-movie | trunk/shared/libraries/lib_code_generator.php | PHP | gpl3 | 488 |
<?php
class lib_pager {
public $total_page;
public $current_page;
public $page_size;
public $total_list;
public function __construct($total_list, $page_size) {
$this->total_list = $total_list;
$this->page_size = $page_size;
$this->total_page = ceil((count($total_list) / $page_size));
}
public function get_total_page() {
return $this->total_page;
}
public function get_current_page_list($current_page) {
$skip = ($current_page - 1) * $this->page_size; // skip = 0
$current_list = array_slice($this->total_list, $skip, $this->page_size);
return $current_list;
}
}
| 09-movie | trunk/shared/libraries/lib_pager.php | PHP | gpl3 | 690 |
<?php
class lib_data_input {
public $data;
public function __construct() {
}
public function data_input($data) {
$data1 = trim($data);
$data2 = stripslashes($data1);
$data3 = htmlspecialchars($data2);
return $data3;
}
}
| 09-movie | trunk/shared/libraries/lib_data_input.php | PHP | gpl3 | 304 |
<?php
class lib_sql_convert {
const SINGLE_QUOTES = '&squo;';
public function __construct() {
}
public static function get_converted_string($sql_string) {
return str_replace("'", self::SINGLE_QUOTES, $sql_string);
}
public static function get_sql_string($converted_string) {
return str_replace(self::SINGLE_QUOTES, "'", $converted_string);
}
}
| 09-movie | trunk/shared/libraries/lib_sql_convert.php | PHP | gpl3 | 414 |
<?php
class lib_date {
public function __construct() {
}
public static function get_now() {
return date("Y-m-d H:i:s");
}
public static function convert_to_sql_date($date, $format) {
$temp = DateTime::createFromFormat($format, $date);
return date_format($temp, "Y-m-d");
}
public static function convert_to_sql_time($time, $format) {
$temp = DateTime::createFromFormat($format, $time);
return date_format($temp, "H:i:s");
}
public static function convert_to_sql_date_time($date_time, $format) {
$temp = DateTime::createFromFormat($format, $date_time);
return date_format($temp, "Y-m-d H:i:s");
}
}
| 09-movie | trunk/shared/libraries/lib_date.php | PHP | gpl3 | 740 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_ticket.php";
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_movie.php";
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_seat.php";
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_seat_template.php";
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_cinema.php";
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_sql_convert.php';
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_date.php';
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of api_security
*
* @author Thien
*/
class api_tickets {
public static function save_ticket($ticket_id, $name, $show_date,
$time_start, $duration, $movie_id, $cinema_id, $price) {
$dao_ticket = new dao_ticket();
$dao_seat_template = new dao_seat_template();
$count_seats = $dao_seat_template->count_all();
$inserted_id = $dao_ticket->save($ticket_id, $name, lib_date::convert_to_sql_date($show_date, "d/m/Y"),
lib_date::convert_to_sql_time($time_start, "H:i"), $duration, $movie_id, $cinema_id, $price,
$count_seats, $count_seats);
if ($ticket_id == 0) {
$dao_seat = new dao_seat();
$template = $dao_seat_template->get_all();
foreach ($template as $item) {
$is_wheelchair = 0;
if ($item['seat_status_id'] == 3) {
$is_wheelchair = 1;
}
$dao_seat->save(0, $item['row_pos'],
$item['column_pos'], $inserted_id, $item['seat_status_id'],
$is_wheelchair);
}
}
return TRUE;
}
public static function delete_ticket($ticket_id) {
$dao_ticket = new dao_ticket();
return $dao_ticket->delete($ticket_id);
}
public static function get_user_cinema_email($ticket_id) {
$dao_ticket = new dao_ticket();
$ticket = $dao_ticket->get_by_id($ticket_id);
$dao_user = new dao_user();
$user = $dao_user->get_cinema_user($ticket['cinema_id']);
return $user['email'];
}
public static function get_ticket_by_ticket_booking($city_id, $cinema_id, $movie_id, $show_date, $time_start) {
$dao_ticket = new dao_ticket();
$ticket = $dao_ticket->get_all_by_filters(0, $city_id, $cinema_id, $movie_id, $show_date, $time_start);
if (!empty($ticket) && $ticket > 0) {
return $ticket[0];
}
}
public static function get_all_tickets_by_ticket_booking($ticket_quantity, $city_id, $movie_id, $show_date) {
$dao_ticket = new dao_ticket();
$tickets = $dao_ticket->get_all_by_filters($ticket_quantity, $city_id, 0, $movie_id, $show_date, "");
// var_dump($tickets);
// exit()
$list = array();
if (!empty($tickets) && count($tickets) > 0) {
$list[0] = $tickets[0];
for ($index = 1; $index < count($tickets); $index++) {
if ($tickets[$index]['cinema_name'] !== $tickets[$index - 1]['cinema_name']
|| $tickets[$index]['time_start'] !== $tickets[$index - 1]['time_start']) {
$list[count($list)] = $tickets[$index];
}
}
}
return $list;
}
public static function get_ticket_by_id($ticket_id) {
$dao_ticket = new dao_ticket();
return $dao_ticket->get_by_id($ticket_id);
}
public static function get_all_tickets() {
$dao_ticket = new dao_ticket();
return $dao_ticket->get_all();
}
public static function get_all_tickets_live() {
$dao_ticket = new dao_ticket();
$list = $dao_ticket->get_all_live();
for ($index = 0; $index < count($list); $index++) {
$list[$index]['out_of_date'] = "-";
}
return $list;
}
public static function get_all_tickets_dead() {
$dao_ticket = new dao_ticket();
$list = $dao_ticket->get_all_dead();
for ($index = 0; $index < count($list); $index++) {
$list[$index]['out_of_date'] = "OUT OF DATE!";
}
return $list;
}
public static function get_all_live_first_dead_later() {
$result = array_merge((self::get_all_tickets_live()), self::get_all_tickets_dead());
return $result;
}
public static function get_all_movies() {
$dao_movie = new dao_movie();
return $dao_movie->get_all();
}
public static function get_all_cinemas() {
$dao_cinema = new dao_cinema();
return $dao_cinema->get_all();
}
public static function get_all_tickets_with_now_showing() {
$dao_ticket = new dao_ticket();
$status_id = 2; //for now showing
return $dao_ticket->get_all_by_status_id($status_id);
}
public static function get_all_tickets_with_comming_soon() {
$dao_ticket = new dao_ticket();
$status_id = 1; //for comming soon
return $dao_ticket->get_all_by_status_id($status_id);
}
public static function get_all_ticket_statuses() {
$dao_ticket_status = new dao_ticket_status();
return $dao_ticket_status->get_all();
}
public static function get_default_movie() {
$dao_movie = new dao_movie();
$movie = $dao_movie->get_first();
if (!empty($movie['title'])) {
return $movie['title'];
}
return "";
}
public static function get_default_cinema() {
$dao_cinema = new dao_cinema();
$cinema = $dao_cinema->get_first();
if (!empty($cinema['name'])) {
return $cinema['name'];
}
return "";
}
public static function get_movie_id_from_title($title) {
$dao_movie = new dao_movie();
$movie = $dao_movie->get_id_by_title($title);
return $movie['id'];
}
public static function get_cinema_id_from_name($name) {
$dao_cinema = new dao_cinema();
$cinema = $dao_cinema->get_id_by_name($name);
return $cinema['id'];
}
public static function validate_ticket_fields($name, $show_date,
$time_start, $duration, $movie, $cinema, $price) {
$error_show = "";
if (empty($name)) {
$error_show .= "<li>Please fill Name.</li>";
}
if (empty($movie)) {
$error_show .= "<li>Please choose a Movie.</li>";
}
if (empty($cinema)) {
$error_show .= "<li>Please choose a Cinema.</li>";
}
if (empty($show_date)) {
$error_show .= "<li>Please fill Show Date.</li>";
}
if (empty($time_start)) {
$error_show .= "<li>Please fill Time Start.</li>";
}
if (empty($duration)) {
$error_show .= "<li>Please fill Duration.</li>";
}
if (empty($price)) {
$error_show .= "<li>Please fill Price.</li>";
}
return $error_show;
}
}
| 09-movie | trunk/shared/api/api_tickets.php | PHP | gpl3 | 7,522 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_coupon.php";
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_discount_type.php";
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_sql_convert.php';
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of api_security
*
* @author Thien
*/
class api_coupons {
public static function save_coupon($coupon_id, $coupon_code, $discount_type_id, $discount_number) {
$dao_coupon = new dao_coupon();
return $dao_coupon->save($coupon_id, $coupon_code, $discount_type_id, $discount_number);
}
public static function get_coupon_by_coupon_code($coupon_code) {
$dao_coupon = new dao_coupon();
return $dao_coupon->get_id_by_coupon_code($coupon_code);
}
public static function delete_coupon($coupon_id) {
$dao_coupon = new dao_coupon();
return $dao_coupon->delete($coupon_id);
}
public static function get_coupon_by_id($coupon_id) {
$dao_coupon = new dao_coupon();
return $dao_coupon->get_by_id($coupon_id);
}
public static function get_all_coupons() {
$dao_coupon = new dao_coupon();
return $dao_coupon->get_all();
}
public static function get_all_discount_types() {
$dao_discount_type = new dao_discount_type();
return $dao_discount_type->get_all();
}
public static function get_all_coupons_with_now_showing() {
$dao_coupon = new dao_coupon();
$status_id = 2; //for now showing
return $dao_coupon->get_all_by_status_id($status_id);
}
public static function get_all_coupons_with_comming_soon() {
$dao_coupon = new dao_coupon();
$status_id = 1; //for comming soon
return $dao_coupon->get_all_by_status_id($status_id);
}
public static function get_all_coupon_statuses() {
$dao_coupon_status = new dao_coupon_status();
return $dao_coupon_status->get_all();
}
public static function get_default_discount_type() {
$dao_discount_type = new dao_discount_type();
$coupon = $dao_discount_type->get_first();
if (!empty($coupon['name'])) {
return $coupon['name'];
}
return "";
}
public static function get_discount_type_id_from_name($name) {
$dao_discount_type = new dao_discount_type();
$discount_type = $dao_discount_type->get_id_by_name($name);
return $discount_type['id'];
}
public static function validate_coupon_fields($coupon_code, $description, $discount_type) {
$error_show = "";
if (empty($coupon_code)) {
$error_show .= "<li>Please fill Name.</li>";
}
if (empty($description)) {
$error_show .= "<li>Please fill Description.</li>";
}
if (empty($discount_type)) {
$error_show .= "<li>Please choose a Discount Type.</li>";
}
return $error_show;
}
}
| 09-movie | trunk/shared/api/api_coupons.php | PHP | gpl3 | 3,313 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_cinema.php";
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_city.php";
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_cinema.php";
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_sql_convert.php';
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of api_security
*
* @author Thien
*/
class api_cinemas {
public static function save_cinema($cinema_id, $name, $address, $image, $city_id, $latitude, $longitude) {
$dao_cinema = new dao_cinema();
return $dao_cinema->save($cinema_id, $name, $address, $image, $city_id, $latitude, $longitude);
}
public static function delete_cinema($cinema_id) {
$dao_cinema = new dao_cinema();
return $dao_cinema->delete($cinema_id);
}
public static function get_cinema_by_id($cinema_id) {
$dao_cinema = new dao_cinema();
return $dao_cinema->get_by_id($cinema_id);
}
public static function get_all_cinemas() {
$dao_cinema = new dao_cinema();
return $dao_cinema->get_all();
}
public static function get_all_cinemas_with_now_showing() {
$dao_cinema = new dao_cinema();
$status_id = 2; //for now showing
return $dao_cinema->get_all_by_status_id($status_id);
}
public static function get_all_cinemas_with_comming_soon() {
$dao_cinema = new dao_cinema();
$status_id = 1; //for comming soon
return $dao_cinema->get_all_by_status_id($status_id);
}
public static function get_all_cities() {
$dao_city = new dao_city();
return $dao_city->get_all();
}
public static function get_city_id_from_name($name) {
$dao_city = new dao_city();
$city = $dao_city->get_id_by_name($name);
return $city['id'];
}
public static function get_city_by_id($city_id) {
$dao_city = new dao_city();
$city = $dao_city->get_by_id($city_id);
return $city;
}
public static function validate_cinema_fields($name_save, $address_save, $image_save, $city_save, $latitude_save, $longitude_save) {
$error_show = "";
if (empty($name_save)) {
$error_show .= "<li>Please fill a Name.</li>";
}
if (empty($address_save)) {
$error_show .= "<li>Please fill a Address.</li>";
}
if (empty($city_save)) {
$error_show .= "<li>Please choose a City.</li>";
}
if (empty($latitude_save)) {
$error_show .= "<li>Please upload a Latitude.</li>";
}
if (empty($longitude_save)) {
$error_show .= "<li>Please upload a Longitude.</li>";
}
if (empty($image_save)) {
$error_show .= "<li>Please upload a Image.</li>";
}
return $error_show;
}
public static function get_default_city() {
$dao_city = new dao_city();
$city = $dao_city->get_first();
if (!empty($city['name'])) {
return $city['name'];
}
return "";
}
}
| 09-movie | trunk/shared/api/api_cinemas.php | PHP | gpl3 | 3,430 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_combo.php";
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_sql_convert.php';
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of api_security
*
* @author Thien
*/
class api_combos {
public static function save_combo($combo_id, $name, $description, $price, $image) {
$dao_combo = new dao_combo();
return $dao_combo->save($combo_id, $name, $description, $price, $image);
}
public static function delete_combo($combo_id) {
$dao_combo = new dao_combo();
return $dao_combo->delete($combo_id);
}
public static function get_combo_by_id($combo_id) {
$dao_combo = new dao_combo();
return $dao_combo->get_by_id($combo_id);
}
public static function get_all_combos() {
$dao_combo = new dao_combo();
return $dao_combo->get_all();
}
public static function get_all_combos_with_now_showing() {
$dao_combo = new dao_combo();
$status_id = 2; //for now showing
return $dao_combo->get_all_by_status_id($status_id);
}
public static function get_all_combos_with_comming_soon() {
$dao_combo = new dao_combo();
$status_id = 1; //for comming soon
return $dao_combo->get_all_by_status_id($status_id);
}
public static function get_all_combo_statuses() {
$dao_combo_status = new dao_combo_status();
return $dao_combo_status->get_all();
}
public static function get_default_combo_statuses() {
$dao_combo_status = new dao_combo_status();
$status = $dao_combo_status->get_first();
if (!empty($status['name'])) {
return $status['name'];
}
return "";
}
public static function get_status_id_from_name($name) {
$dao_combo_status = new dao_combo_status();
$status = $dao_combo_status->get_id_by_name($name);
return $status['id'];
}
public static function validate_combo_fields($name, $description, $price, $image) {
$error_show = "";
if (empty($name)) {
$error_show .= "<li>Please fill Name.</li>";
}
if (empty($description)) {
$error_show .= "<li>Please fill Description.</li>";
}
if (empty($price)) {
$error_show .= "<li>Please fill Price.</li>";
}
if (empty($image)) {
$error_show .= "<li>Please fill Image.</li>";
}
return $error_show;
}
}
| 09-movie | trunk/shared/api/api_combos.php | PHP | gpl3 | 2,856 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_seat.php";
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_seat_status.php";
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_sql_convert.php';
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of api_security
*
* @author Thien
*/
class api_seats {
public static function get_all_seat_statuses() {
$dao_seat_status = new dao_seat_status();
return $dao_seat_status->get_all();
}
public static function get_seat_status_by_status_id($seat_status_id) {
$dao_seat_status = new dao_seat_status();
return $dao_seat_status->get_by_id($seat_status_id);
}
public static function get_all_columns($ticket_id) {
$dao_seat = new dao_seat();
return $dao_seat->get_all_columns($ticket_id);
}
public static function get_all_rows($ticket_id) {
$dao_seat = new dao_seat();
return $dao_seat->get_all_rows($ticket_id);
}
public static function get_seat($ticket_id, $row, $column) {
$dao_seat = new dao_seat();
return $dao_seat->get_by_position($ticket_id, $row, $column);
}
public static function get_seat_by_id($seat_id) {
$dao_seat = new dao_seat();
return $dao_seat->get_by_id($seat_id);
}
public static function unchoose_seat($seat_id) {
$dao_seat = new dao_seat();
$seat = self::get_seat_by_id($seat_id);
if ($seat['is_wheelchair']) {
self::update_seat_status($seat_id, 3);
} else {
self::update_seat_status($seat_id, 2);
}
return $dao_seat->get_by_id($seat_id);
}
public static function update_seat_status_to_sold($ticket_id, $row, $column) {
$dao_seat = new dao_seat();
$seat = self::get_seat($ticket_id, $row, $column);
$dao_seat->update_seat_status($seat['id'], 4);
return $dao_seat->get_by_position($ticket_id, $row, $column);
}
public static function update_seat_status($seat_id, $seat_status_id) {
$dao_seat = new dao_seat();
$seat = $dao_seat->get_by_id($seat_id);
if ($seat_status_id == 1 || $seat_status_id == 4) {
api_booking::decrease_available($seat['ticket_id'], 1);
} else if ($seat_status_id == 2 || $seat_status_id == 3) {
api_booking::increase_available($seat['ticket_id'], 1);
}
$dao_seat->update_seat_status($seat_id, $seat_status_id);
}
}
| 09-movie | trunk/shared/api/api_seats.php | PHP | gpl3 | 2,832 |
<?php
/**
* User: Viet Anh
* Date: 10/06/2014
* Time: 23:36
*/
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_option.php";
class api_config
{
public static function get_easypaisa_detail()
{
$dao_option = new dao_option();
return $dao_option->get_option_value('easypaisa_description');
}
public static function get_skrill_email()
{
$dao_option = new dao_option();
return $dao_option->get_option_value('skrill_merchant_email');
}
public static function set_easypaisa_detail($detail)
{
$dao_option = new dao_option();
return $dao_option->set_option_value('easypaisa_description', $detail);
}
public static function set_skrill_email($email)
{
$dao_option = new dao_option();
return $dao_option->set_option_value('skrill_merchant_email', $email);
}
} | 09-movie | trunk/shared/api/api_config.php | PHP | gpl3 | 1,095 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_movie.php";
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_movie_status.php";
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_sql_convert.php';
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of api_security
*
* @author Thien
*/
class api_movies {
public static function save_movie($movie_id, $title, $status_id, $description, $poster) {
$dao_movie = new dao_movie();
return $dao_movie->save($movie_id, lib_sql_convert::get_converted_string($title),
$status_id, lib_sql_convert::get_converted_string($description), $poster);
}
public static function delete_movie($movie_id) {
$dao_movie = new dao_movie();
return $dao_movie->delete($movie_id);
}
public static function get_movie_by_id($movie_id) {
$dao_movie = new dao_movie();
return $dao_movie->get_by_id($movie_id);
}
public static function get_all_movies() {
$dao_movie = new dao_movie();
return $dao_movie->get_all();
}
public static function get_all_movies_with_now_showing_and_number($entry_number) {
$dao_movie = new dao_movie();
$status_id = 2; //for now showing
return $dao_movie->get_all_by_status_id($status_id, $entry_number);
}
public static function get_all_movies_with_now_showing() {
$dao_movie = new dao_movie();
$status_id = 2; //for now showing
return $dao_movie->get_all_by_status_id($status_id, 0);
}
public static function get_all_movies_with_comming_soon_and_number($entry_number) {
$dao_movie = new dao_movie();
$status_id = 1; //for comming soon
return $dao_movie->get_all_by_status_id($status_id, $entry_number);
}
public static function get_all_movies_with_comming_soon() {
$dao_movie = new dao_movie();
$status_id = 1; //for comming soon
return $dao_movie->get_all_by_status_id($status_id, 0);
}
public static function get_all_movie_statuses() {
$dao_movie_status = new dao_movie_status();
return $dao_movie_status->get_all();
}
public static function get_default_movie_statuses() {
$dao_movie_status = new dao_movie_status();
$status = $dao_movie_status->get_first();
if (!empty($status['name'])) {
return $status['name'];
}
return "";
}
public static function get_status_id_from_name($name) {
$dao_movie_status = new dao_movie_status();
$status = $dao_movie_status->get_id_by_name($name);
return $status['id'];
}
public static function validate_movie_fields($title, $description, $poster) {
$error_show = "";
if (empty($title)) {
$error_show .= "<li>Please fill Title.</li>";
}
if (empty($description)) {
$error_show .= "<li>Please fill Description.</li>";
}
if (empty($poster)) {
$error_show .= "<li>Please upload a Poster.</li>";
}
return $error_show;
}
}
| 09-movie | trunk/shared/api/api_movies.php | PHP | gpl3 | 3,465 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_user.php";
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_user.php";
require_once DOCUMENT_ROOT . DIR_SHARED_API . "api_security.php";
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_sql_convert.php';
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of api_security
*
* @author Thien
*/
class api_users {
public static function save_user($id, $first_name,
$last_name, $phone_number, $email, $password,
$user_cinema_id) {
$dao_user = new dao_user();
if (empty($user_cinema_id)) {
$user_cinema_id = 0;
}
$inserted_id = $dao_user->save($id, $first_name,
$last_name, $phone_number, $email, $password, 2, $user_cinema_id, "Admin Created");
return $dao_user->active($inserted_id);
}
public static function delete_user($user_id) {
$dao_user = new dao_user();
return $dao_user->delete($user_id);
}
public static function get_user_by_id($user_id) {
$dao_user = new dao_user();
return $dao_user->get_by_id($user_id);
}
public static function get_all_users() {
$dao_user = new dao_user();
return $dao_user->get_all();
}
public static function get_all_users_with_now_showing() {
$dao_user = new dao_user();
$status_id = 2; //for now showing
return $dao_user->get_all_by_status_id($status_id);
}
public static function get_all_users_with_comming_soon() {
$dao_user = new dao_user();
$status_id = 1; //for comming soon
return $dao_user->get_all_by_status_id($status_id);
}
public static function get_all_user_statuses() {
$dao_user_status = new dao_user_status();
return $dao_user_status->get_all();
}
public static function get_default_user_statuses() {
$dao_user_status = new dao_user_status();
$status = $dao_user_status->get_first();
if (!empty($status['name'])) {
return $status['name'];
}
return "";
}
public static function get_status_id_from_name($name) {
$dao_user_status = new dao_user_status();
$status = $dao_user_status->get_id_by_name($name);
return $status['id'];
}
public static function validate_user_fields($user_id, $first_name,
$last_name, $phone_number, $email, $password,
$password_confirm) {
$error_show = "";
if (empty($first_name)) {
$error_show .= "<li>Please fill First Name.</li>";
}
if (empty($last_name)) {
$error_show .= "<li>Please fill Last Name.</li>";
}
if (empty($phone_number)) {
$error_show .= "<li>Please fill Phone Number.</li>";
}
if (empty($email)) {
$error_show .= "<li>Please fill Email.</li>";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error_show .= "<li>Email invalid.</li>";
}
if (api_security::email_exists($email) && $user_id == 0) {
$error_show .= "<li>Email already exists.</li>";
}
if (empty($password)) {
$error_show .= "<li>Please fill Password.</li>";
}
if (empty($password_confirm) || $password_confirm !== $password) { //match password
$error_show .= "<li>You have to confirm password exactly!</li>";
}
return $error_show;
}
}
| 09-movie | trunk/shared/api/api_users.php | PHP | gpl3 | 3,906 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_booking.php";
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_user.php";
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_combo.php";
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_coupon.php";
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_ticket.php";
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_seat.php";
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_seat_status.php";
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_booking_line.php";
require_once DOCUMENT_ROOT . DIR_SHARED_API . "api_cinemas.php";
require_once DOCUMENT_ROOT . DIR_SHARED_API . "api_movies.php";
require_once DOCUMENT_ROOT . DIR_SHARED_API . "api_seats.php";
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_sql_convert.php';
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_code_generator.php';
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of api_security
*
* @author Thien
*/
class api_booking {
public static function save_booking($booking_id, $user_id, $ticket_id,
$ticket_quantity_solve, $coupon_id, $combo_id, $combo_quantity_solve, $paid) {
$dao_booking = new dao_booking();
$total_money = self::calculate_total_money($ticket_id, $ticket_quantity_solve,
$combo_id, $combo_quantity_solve, $coupon_id);
return $dao_booking->save($booking_id, $user_id, $ticket_id,
$ticket_quantity_solve, $coupon_id, $combo_id, $combo_quantity_solve, $total_money, $paid);
}
public static function finalize_booking(
$booking_id,
$user_id,
$ticket_id,
$ticket_quantity,
$coupon_id,
$combo_id,
$combo_quantity,
$paid) {
self::save_booking(
$booking_id,
$user_id,
$ticket_id,
$ticket_quantity,
$coupon_id,
$combo_id,
$combo_quantity,
$paid);
$booking_code = self::generate_code($booking_id);
$lines = self::get_all_booking_lines_by_booking_id(
$booking_id, $user_id);
foreach ($lines as $item) {
api_seats::update_seat_status_to_sold($ticket_id, $item['row_pos'], $item['column_pos']);
}
return $booking_code;
}
public static function get_user_email_from_booking_id($booking_id) {
$dao_booking = new dao_booking();
$booking = $dao_booking->get_by_id($booking_id);
return $booking['user_email'];
}
public static function calculate_total_money($ticket_id, $ticket_quantity_solve,
$combo_id, $combo_quantity_solve, $coupon_id) {
$total_money = 0;
$dao_ticket = new dao_ticket();
$ticket = $dao_ticket->get_by_id($ticket_id);
$ticket_price = $ticket['price'];
$total_ticket_money = $ticket_price * $ticket_quantity_solve;
$dao_combo = new dao_combo();
$combo = $dao_combo->get_by_id($combo_id);
$combo_price = $combo['price'];
$total_combo_money = $combo_price * $combo_quantity_solve;
$discount_amount = 0;
$dao_coupon = new dao_coupon();
$coupon = $dao_coupon->get_by_id($coupon_id);
if ($coupon['discount_type_id'] == 1) { // == Percentage
$discount_amount = ($total_combo_money * $coupon['discount_number'] / 100);
} else if ($coupon['discount_type_id'] == 2) { // == Amount
if ($coupon['discount_number'] <= $total_combo_money) {
$discount_amount = $coupon['discount_number'];
} else {
$discount_amount = $total_combo_money;
}
}
$total_money += $total_ticket_money + $total_combo_money - $discount_amount;
return $total_money;
}
public static function is_existing_code($booking_code) {
$dao_booking = new dao_booking();
$booking = $dao_booking->get_by_code($booking_code);
if (empty($booking)) {
return FALSE;
}
return TRUE;
}
public static function search_existing_code($booking_code) {
$dao_booking = new dao_booking();
$booking = $dao_booking->get_by_code($booking_code);
if (empty($booking) || empty($booking['is_paid'])) {
return FALSE;
}
return TRUE;
}
public static function update_paid($booking_id) {
$dao_booking = new dao_booking();
$dao_booking->update_paid($booking_id);
return TRUE;
}
public static function get_booking_code($booking_id) {
$dao_booking = new dao_booking();
$booking = $dao_booking->get_by_id($booking_id);
return $booking['generated_code'];
}
public static function generate_code($booking_id) {
$dao_booking = new dao_booking();
$code = lib_code_generator::generate_random_string();
while (self::is_existing_code($code)) {
$code = lib_code_generator::generate_random_string();
}
$dao_booking->update_generated_code($booking_id, $code);
return $code;
}
public static function book_seat($ticket_id, $row, $column, $book_quantity, $booking_id) {
$dao_seat = new dao_seat();
$dao_ticket = new dao_ticket();
$seat = $dao_seat->get_by_position($ticket_id, $row, $column);
$result = array();
$result['success'] = TRUE;
if ($seat['seat_status_id'] == 1) { // your seat
if (self::is_your_seat_available($booking_id, $row, $column)) {
self::delete_booking_line($booking_id, $row, $column);
$change_status_id = 2;
if ($seat['is_wheelchair']) {
$change_status_id = 3;
}
$dao_seat->save($seat['id'], $row, $column, $ticket_id, $change_status_id, 0, 0);
self::increase_available($ticket_id, 1);
$result['next_seat_info'] = self::get_seat_with_image_url($seat, $change_status_id);
$result['changed'] = TRUE;
$book_quantity++;
} else {
$result['changed'] = FALSE;
$result['notify'] = "This seat is sold, please choose an other.";
}
} else if ($seat['seat_status_id'] == 2) { // available
if ($book_quantity > 0) {
$change_status_id = 1;
$dao_seat->save($seat['id'], $row, $column, $ticket_id, $change_status_id, 0, 0);
self::decrease_available($ticket_id, 1);
$result['next_seat_info'] = self::get_seat_with_image_url($seat, $change_status_id);
$result['changed'] = TRUE;
self::save_booking_line($booking_id, $row, $column);
$book_quantity--;
} else {
$result['changed'] = FALSE;
$result['notify'] = "Remove your last book to book this, please.";
}
} else if ($seat['seat_status_id'] == 3) { // wheelchair
if ($book_quantity > 0) {
$change_status_id = 1;
$dao_seat->save($seat['id'], $row, $column, $ticket_id, $change_status_id, 0, 0);
self::decrease_available($ticket_id, 1);
$result['next_seat_info'] = self::get_seat_with_image_url($seat, $change_status_id);
$result['changed'] = TRUE;
self::save_booking_line($booking_id, $row, $column);
$book_quantity--;
} else {
$result['changed'] = FALSE;
$result['notify'] = "Remove your last book to book this, please.";
}
} else if ($seat['seat_status_id'] == 4) { // sold
$result['changed'] = FALSE;
$result['notify'] = "This seat is sold, please choose an other.";
} else {
$result['success'] = FALSE;
}
$result['book_quantity'] = $book_quantity;
return $result;
}
public static function is_your_seat_available($booking_id, $row, $column) {
$dao_booking_line = new dao_booking_line();
$item = $dao_booking_line->get_by_position($booking_id, $row, $column);
// var_dump($item);
if (!empty($item)) {
return TRUE;
}
return FALSE;
}
public static function delete_booking_line($booking_id, $row_pos, $column_pos) {
$dao_booking_line = new dao_booking_line();
$item = $dao_booking_line->get_by_position($booking_id, $row_pos, $column_pos);
if (!empty($item)) {
$id = $item['id'];
$dao_booking_line->delete($id);
}
}
public static function delete_booking_line_by_booking_id($booking_id) {
$dao_booking_line = new dao_booking_line();
$dao_booking_line->delete_by_booking_id($booking_id);
}
public static function get_all_booking_lines_by_booking_id($booking_id, $user_id) {
$dao_booking_line = new dao_booking_line();
$list = $dao_booking_line->get_all_by_booking_id($booking_id, $user_id);
return $list;
}
public static function save_booking_line($booking_id, $row_pos, $column_pos) {
$dao_booking_line = new dao_booking_line();
$item = $dao_booking_line->get_by_position($booking_id, $row_pos, $column_pos);
$id = 0;
if (!empty($item)) {
$id = $item['id'];
}
$dao_booking_line->save($id, $booking_id, $row_pos, $column_pos);
}
public static function decrease_available($ticket_id, $decrease_number) {
$dao_ticket = new dao_ticket();
$ticket = $dao_ticket->get_by_id($ticket_id);
$available = $ticket['available_seats'];
$available -= $decrease_number;
$dao_ticket->update_available($ticket_id, $available);
}
public static function increase_available($ticket_id, $increase_number) {
$dao_ticket = new dao_ticket();
$ticket = $dao_ticket->get_by_id($ticket_id);
$available = $ticket['available_seats'];
$available += $increase_number;
$dao_ticket->update_available($ticket_id, $available);
}
public static function get_seat_with_image_url($seat, $seat_status_id) {
$dao_seat_status = new dao_seat_status();
$seat_status = $dao_seat_status->get_by_id($seat_status_id);
$seat['image_url'] = LINK_ROOT . DIR_SHARED_LAYOUT_IMAGES_TICKET . $seat_status['image'];
return $seat;
}
public static function get_all_cities_by_filter($ticket_quantity) {
$dao_ticket = new dao_ticket();
$tickets = $dao_ticket->get_all_by_filters($ticket_quantity, 0, 0, 0, "", "");
$list = array();
$id_list = array();
foreach ($tickets as $ticket) {
$item_id = $ticket['city_id'];
if (!in_array($item_id,$id_list)) {
$item = api_cinemas::get_city_by_id($item_id);
$list[count($list)] = $item;
$id_list[count($id_list)] = $item_id;
}
}
return $list;
}
public static function get_all_cinemas_by_filter($ticket_quantity, $city_id) {
$dao_ticket = new dao_ticket();
$tickets = $dao_ticket->get_all_by_filters($ticket_quantity, $city_id, 0, 0, "", "");
$list = array();
$id_list = array();
foreach ($tickets as $ticket) {
$item_id = $ticket['cinema_id'];
if (!in_array($item_id,$id_list)) {
$item = api_cinemas::get_cinema_by_id($item_id);
$list[count($list)] = $item;
$id_list[count($id_list)] = $item_id;
}
}
return $list;
}
public static function get_all_movies_by_filter($ticket_quantity, $city_id, $cinema_id) {
$dao_ticket = new dao_ticket();
$tickets = $dao_ticket->get_all_by_filters($ticket_quantity, $city_id, $cinema_id, 0, "", "");
$list = array();
$id_list = array();
foreach ($tickets as $ticket) {
$item_id = $ticket['movie_id'];
if (!in_array($item_id,$id_list)) {
$item = api_movies::get_movie_by_id($item_id);
$list[count($list)] = $item;
$id_list[count($id_list)] = $item_id;
}
}
return $list;
}
public static function get_all_show_date_by_filter($ticket_quantity, $city_id, $cinema_id, $movie_id) {
$dao_ticket = new dao_ticket();
$tickets = $dao_ticket->get_all_by_filters($ticket_quantity, $city_id, $cinema_id, $movie_id, "", "");
$list = array();
$same_list = array();
foreach ($tickets as $ticket) {
$item = $ticket['show_date'];
if (!in_array($item,$same_list)) {
$list[count($list)] = $item;
$same_list[count($same_list)] = $item;
}
}
return $list;
}
public static function get_all_time_start_by_filter($ticket_quantity, $city_id, $cinema_id, $movie_id, $show_date) {
$dao_ticket = new dao_ticket();
$tickets = $dao_ticket->get_all_by_filters($ticket_quantity, $city_id, $cinema_id, $movie_id, $show_date, "");
$list = array();
$same_list = array();
foreach ($tickets as $ticket) {
$item = $ticket['time_start'];
if (!in_array($item,$same_list)) {
$list[count($list)] = $item;
$same_list[count($same_list)] = $item;
}
}
return $list;
}
public static function is_paid($booking_id) {
$dao_booking = new dao_booking();
$booking = $dao_booking->get_by_id($booking_id);
if (!empty($booking['is_paid']) && $booking['is_paid'] == 1) {
return TRUE;
}
return FALSE;
}
public static function delete_booking($booking_id) {
$dao_booking = new dao_booking();
$booking = self::get_booking_by_id($booking_id);
$lines = self::get_all_booking_lines_by_booking_id($booking_id,
$booking['user_id']);
foreach ($lines as $item) {
$seat = api_seats::get_seat($booking['ticket_id'], $item['row_pos'], $item['column_pos']);
api_seats::unchoose_seat($seat['id']);
}
self::delete_booking_line_by_booking_id($booking_id);
return $dao_booking->delete($booking_id);
}
public static function get_booking_by_id($booking_id) {
$dao_booking = new dao_booking();
return $dao_booking->get_by_id($booking_id);
}
public static function get_all_booking() {
$dao_booking = new dao_booking();
return $dao_booking->get_all();
}
public static function get_all_booking_paid() {
$dao_booking = new dao_booking();
return $dao_booking->get_all_paid();
}
public static function get_all_bookings_with_now_showing() {
$dao_booking = new dao_booking();
$status_id = 2; //for now showing
return $dao_booking->get_all_by_status_id($status_id);
}
public static function get_all_bookings_with_comming_soon() {
$dao_booking = new dao_booking();
$status_id = 1; //for comming soon
return $dao_booking->get_all_by_status_id($status_id);
}
public static function get_all_booking_statuses() {
$dao_booking_status = new dao_booking_status();
return $dao_booking_status->get_all();
}
public static function get_default_user_email() {
$dao_user = new dao_user();
$user = $dao_user->get_first();
if (!empty($user['email'])) {
return $user['email'];
}
return "";
}
public static function get_default_coupon_code() {
$dao_coupon = new dao_coupon();
$coupon = $dao_coupon->get_first();
if (!empty($coupon['coupon_code'])) {
return $coupon['coupon_code'];
}
return "";
}
public static function get_default_combo() {
$dao_combo = new dao_combo();
$combo = $dao_combo->get_first();
if (!empty($combo['name'])) {
return $combo['name'];
}
return "";
}
public static function get_default_ticket() {
$dao_ticket = new dao_ticket();
$ticket = $dao_ticket->get_first();
if (!empty($ticket['name'])) {
return $ticket['name'];
}
return "";
}
public static function get_ticket_id_from_name($name) {
$dao_ticket = new dao_ticket();
$item = $dao_ticket->get_id_by_name($name);
return $item['id'];
}
public static function get_user_id_from_email($email) {
$dao_user = new dao_user();
$item = $dao_user->get_by_email($email);
return $item['id'];
}
public static function get_coupon_id_from_coupon_code($coupon_code) {
$dao_coupon = new dao_coupon();
$item = $dao_coupon->get_id_by_coupon_code($coupon_code);
return $item['id'];
}
public static function get_combo_id_from_name($name) {
$dao_combo = new dao_combo();
$item = $dao_combo->get_id_by_name($name);
return $item['id'];
}
public static function validate_booking_fields($email, $ticket,
$ticket_quantity_solve, $coupon_code, $combo, $combo_quantity_solve) {
$error_show = "";
if (empty($email)) {
$error_show .= "<li>Please choose Email.</li>";
}
if (empty($ticket)) {
$error_show .= "<li>Please choose Ticket.</li>";
}
if (empty($ticket_quantity_solve)) {
$error_show .= "<li>Please fill Ticket Quantity.</li>";
}
if (empty($coupon_code)) {
$error_show .= "<li>Please choose Coupon Code.</li>";
}
if (empty($combo)) {
$error_show .= "<li>Please choose Combo.</li>";
}
if (empty($combo_quantity_solve)) {
$error_show .= "<li>Please fill Combo Quantity.</li>";
}
return $error_show;
}
}
| 09-movie | trunk/shared/api/api_booking.php | PHP | gpl3 | 19,039 |
<?php
require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_user.php";
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_redirect.php';
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_code_generator.php';
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of api_security
*
* @author Thien
*/
class api_security {
public static function login($email, $password) {
$result = array();
$result['user_login'] = 'failed';
$user_access = new dao_user();
$user = $user_access->get_by_login_info($email, $password);
if (!empty($user)) {
$result = $user;
$result['user_login'] = 'logined';
}
return $result;
}
public static function activate($username, $activate_code) {
$user_access = new dao_user();
$user = $user_access->get_by_activate_code($username, $activate_code);
if (!empty($user)) {
$user_access->active($user['id']);
return TRUE;
}
return FALSE;
}
public static function logout() {
session_start();
$_SESSION['user_login'] = '';
lib_redirect::Redirect('/index.php');
}
public static function register($email, $password,
$first_name, $last_name, $phone_number) {
$user_access = new dao_user();
$activate_code = lib_code_generator::generate_random_string();
$user_access->save(0,$first_name,$last_name,$phone_number,$email,$password,2,0,$activate_code);
return $activate_code;
}
public static function validate_register($first_name, $last_name,
$phone_number, $email, $password, $password_confirm) {
$error_show = "";
if (empty($first_name)) {
$error_show .= "<li>Please fill First Name.</li>";
}
if (empty($last_name)) {
$error_show .= "<li>Please fill Last Name.</li>";
}
if (empty($phone_number)) {
$error_show .= "<li>Please fill Phone Number.</li>";
}
if (empty($email)) {
$error_show .= "<li>Please fill Email.</li>";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error_show .= "<li>Email invalid.</li>";
}
if (self::email_exists($email)) {
$error_show .= "<li>Email already exists.</li>";
}
if (empty($password)) {
$error_show .= "<li>Please fill Password.</li>";
}
if (empty($password_confirm) || $password_confirm !== $password) { //match password
$error_show .= "<li>You have to confirm password exactly!</li>";
}
return $error_show;
}
public static function email_exists($email) {
$dao_user = new dao_user();
$list = $dao_user->get_by_email($email);
if (!empty($list) && count($list) > 0) {
return TRUE;
}
return FALSE;
}
public static function get_all_users() {
$user_access = new dao_user();
return $user_access->get_all();
}
}
| 09-movie | trunk/shared/api/api_security.php | PHP | gpl3 | 3,439 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" type="text/css" href="./jquery.datetimepicker.css"/>
</head>
<body>
<p><a href="http://xdsoft.net/jqplugins/datetimepicker/">Homepage</a></p>
<h3>DateTimePicker</h3>
<input type="text" value="2014/03/15 05:06" id="datetimepicker"/><br><br>
<h3>Mask DateTimePicker</h3>
<input type="text" value="" id="datetimepicker_mask"/><br><br>
<h3>TimePicker</h3>
<input type="text" id="datetimepicker1"/><br><br>
<h3>DatePicker</h3>
<input type="text" id="datetimepicker2"/><br><br>
<h3>Inline DateTimePicker</h3>
<input type="text" id="datetimepicker3"/><input type="button" onclick="$('#datetimepicker3').datetimepicker({value:'2011/12/11 12:00'})" value="set inline value 2011/12/11 12:00"/><br><br>
<h3>Button Trigger</h3>
<input type="text" value="2013/12/03 18:00" id="datetimepicker4"/><input id="open" type="button" value="open"/><input id="close" type="button" value="close"/><input id="reset" type="button" value="reset"/>
<h3>TimePicker allows time</h3>
<input type="text" id="datetimepicker5"/><br><br>
<h3>Destroy DateTimePicker</h3>
<input type="text" id="datetimepicker6"/><input id="destroy" type="button" value="destroy"/>
<h3>Set options runtime DateTimePicker</h3>
<input type="text" id="datetimepicker7"/>
<p>If select day is Saturday, the minimum set 11:00, otherwise 8:00</p>
<h3>onGenerate</h3>
<input type="text" id="datetimepicker8"/>
<h3>disable all weekend</h3>
<input type="text" id="datetimepicker9"/>
<h3>Show inline</h3>
<a href="javascript:var si = document.getElementById('show_inline').style; si.display = (si.display=='none')?'block':'none';return false; ">Show/Hide</a>
<div id="show_inline" style="display:none">
<input type="text" id="datetimepicker10"/>
</div>
<h3>Date Time Picker start time</h3>
<input type="text" id="datetimepicker_start_time"/>
<h3>Date Time Picker from unixtime</h3>
<input type="text" id="datetimepicker_unixtime"/>
<h3>Date Time Picker with day of year and week of year</h3>
<input type="text" id="datetimepicker11"/>
</body>
<script type="text/javascript" src="./jquery.js"></script>
<script type="text/javascript" src="./jquery.datetimepicker.js"></script>
<script type="text/javascript">
$('#datetimepicker').datetimepicker()
.datetimepicker({value:'2015/04/15 05:03',step:10});
$('#datetimepicker_mask').datetimepicker({
mask:'9999/19/39 29:59'
});
$('#datetimepicker1').datetimepicker({
datepicker:false,
format:'H:i',
step:5
});
$('#datetimepicker2').datetimepicker({
yearOffset:222,
lang:'ch',
timepicker:false,
format:'d/m/Y',
formatDate:'Y/m/d',
minDate:'-1970/01/02', // yesterday is minimum date
maxDate:'+1970/01/02' // and tommorow is maximum date calendar
});
$('#datetimepicker3').datetimepicker({
inline:true
});
$('#datetimepicker4').datetimepicker();
$('#open').click(function(){
$('#datetimepicker4').datetimepicker('show');
});
$('#close').click(function(){
$('#datetimepicker4').datetimepicker('hide');
});
$('#reset').click(function(){
$('#datetimepicker4').datetimepicker('reset');
});
$('#datetimepicker5').datetimepicker({
datepicker:false,
allowTimes:['12:00','13:00','15:00','17:00','17:05','17:20','19:00','20:00']
});
$('#datetimepicker6').datetimepicker();
$('#destroy').click(function(){
if( $('#datetimepicker6').data('xdsoft_datetimepicker') ){
$('#datetimepicker6').datetimepicker('destroy');
this.value = 'create';
}else{
$('#datetimepicker6').datetimepicker();
this.value = 'destroy';
}
});
var logic = function( currentDateTime ){
if( currentDateTime ){
if( currentDateTime.getDay()==6 ){
this.setOptions({
minTime:'11:00'
});
}else
this.setOptions({
minTime:'8:00'
});
}
};
$('#datetimepicker7').datetimepicker({
onChangeDateTime:logic,
onShow:logic
});
$('#datetimepicker8').datetimepicker({
onGenerate:function( ct ){
$(this).find('.xdsoft_date')
.toggleClass('xdsoft_disabled');
},
minDate:'-1970/01/2',
maxDate:'+1970/01/2',
timepicker:false
});
$('#datetimepicker9').datetimepicker({
onGenerate:function( ct ){
$(this).find('.xdsoft_date.xdsoft_weekend')
.addClass('xdsoft_disabled');
},
weekends:['01.01.2014','02.01.2014','03.01.2014','04.01.2014','05.01.2014','06.01.2014'],
timepicker:false
});
$('#datetimepicker10').datetimepicker({
step:5,
inline:true
});
$('#datetimepicker_start_time').datetimepicker({
startDate:'+1970/05/01'
});
$('#datetimepicker_unixtime').datetimepicker({
format:'unixtime'
});
$('#datetimepicker11').datetimepicker({
hours12: false,
format: 'Y-z H:i W',
step: 1,
opened: false,
validateOnBlur: false,
closeOnDateSelect: false,
closeOnTimeSelect: false
});
</script>
</html>
| 09-movie | trunk/shared/plugin/datetimepicker-master/index.html | HTML | gpl3 | 4,964 |
/**
* @preserve jQuery DateTimePicker plugin v2.2.8
* @homepage http://xdsoft.net/jqplugins/datetimepicker/
* (c) 2014, Chupurnov Valeriy.
*/
(function( $ ) {
'use strict';
var default_options = {
i18n:{
bg:{ // Bulgarian
months:[
"Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември"
],
dayOfWeek:[
"Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
]
},
fa:{ // Persian/Farsi
months:[
'فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'
],
dayOfWeek:[
'یکشنبه', 'دوشنبه', 'سه شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه'
]
},
ru:{ // Russian
months:[
'Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'
],
dayOfWeek:[
"Вск", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
]
},
en:{ // English
months: [
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
],
dayOfWeek: [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
]
},
el:{ // Ελληνικά
months: [
"Ιανουάριος", "Φεβρουάριος", "Μάρτιος", "Απρίλιος", "Μάιος", "Ιούνιος", "Ιούλιος", "Αύγουστος", "Σεπτέμβριος", "Οκτώβριος", "Νοέμβριος", "Δεκέμβριος"
],
dayOfWeek: [
"Κυρ", "Δευ", "Τρι", "Τετ", "Πεμ", "Παρ", "Σαβ"
]
},
de:{ // German
months:[
'Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'
],
dayOfWeek:[
"So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"
]
},
nl:{ // Dutch
months:[
"januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"
],
dayOfWeek:[
"zo", "ma", "di", "wo", "do", "vr", "za"
]
},
tr:{ // Turkish
months:[
"Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"
],
dayOfWeek:[
"Paz", "Pts", "Sal", "Çar", "Per", "Cum", "Cts"
]
},
fr:{ //French
months:[
"Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"
],
dayOfWeek:[
"Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"
]
},
es:{ // Spanish
months: [
"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"
],
dayOfWeek: [
"Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb"
]
},
th:{ // Thai
months:[
'มกราคม','กุมภาพันธ์','มีนาคม','เมษายน','พฤษภาคม','มิถุนายน','กรกฎาคม','สิงหาคม','กันยายน','ตุลาคม','พฤศจิกายน','ธันวาคม'
],
dayOfWeek:[
'อา.','จ.','อ.','พ.','พฤ.','ศ.','ส.'
]
},
pl:{ // Polish
months: [
"styczeń", "luty", "marzec", "kwiecień", "maj", "czerwiec", "lipiec", "sierpień", "wrzesień", "październik", "listopad", "grudzień"
],
dayOfWeek: [
"nd", "pn", "wt", "śr", "cz", "pt", "sb"
]
},
pt:{ // Portuguese
months: [
"Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
],
dayOfWeek: [
"Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab"
]
},
ch:{ // Simplified Chinese
months: [
"一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"
],
dayOfWeek: [
"日", "一","二","三","四","五","六"
]
},
se:{ // Swedish
months: [
"Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September","Oktober", "November", "December"
],
dayOfWeek: [
"Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"
]
},
kr:{ // Korean
months: [
"1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"
],
dayOfWeek: [
"일", "월", "화", "수", "목", "금", "토"
]
},
it:{ // Italian
months: [
"Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"
],
dayOfWeek: [
"Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"
]
},
da:{ // Dansk
months: [
"January", "Februar", "Marts", "April", "Maj", "Juni", "July", "August", "September", "Oktober", "November", "December"
],
dayOfWeek: [
"Søn", "Man", "Tir", "ons", "Tor", "Fre", "lør"
]
},
ja:{ // Japanese
months: [
"1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"
],
dayOfWeek: [
"日", "月", "火", "水", "木", "金", "土"
]
},
vi:{ // Vietnamese
months: [
"Tháng 1", "Tháng 2", "Tháng 3", "Tháng 4", "Tháng 5", "Tháng 6", "Tháng 7", "Tháng 8", "Tháng 9", "Tháng 10", "Tháng 11", "Tháng 12"
],
dayOfWeek: [
"CN", "T2", "T3", "T4", "T5", "T6", "T7"
]
},
sl:{ // Slovenščina
months: [
"Januar", "Februar", "Marec", "April", "Maj", "Junij", "Julij", "Avgust", "September", "Oktober", "November", "December"
],
dayOfWeek: [
"Ned", "Pon", "Tor", "Sre", "Čet", "Pet", "Sob"
]
}
},
value:'',
lang:'en',
format: 'Y/m/d H:i',
formatTime: 'H:i',
formatDate: 'Y/m/d',
startDate: false, // new Date(), '1986/12/08', '-1970/01/05','-1970/01/05',
step:60,
monthChangeSpinner:true,
closeOnDateSelect:false,
closeOnWithoutClick:true,
timepicker:true,
datepicker:true,
minDate:false,
maxDate:false,
minTime:false,
maxTime:false,
allowTimes:[],
opened:false,
initTime:true,
inline:false,
onSelectDate:function() {},
onSelectTime:function() {},
onChangeMonth:function() {},
onChangeDateTime:function() {},
onShow:function() {},
onClose:function() {},
onGenerate:function() {},
withoutCopyright:true,
inverseButton:false,
hours12:false,
next: 'xdsoft_next',
prev : 'xdsoft_prev',
dayOfWeekStart:0,
timeHeightInTimePicker:25,
timepickerScrollbar:true,
todayButton:true, // 2.1.0
defaultSelect:true, // 2.1.0
scrollMonth:true,
scrollTime:true,
scrollInput:true,
lazyInit:false,
mask:false,
validateOnBlur:true,
allowBlank:true,
yearStart:1950,
yearEnd:2050,
style:'',
id:'',
roundTime:'round', // ceil, floor
className:'',
weekends : [],
yearOffset:0
};
// fix for ie8
if ( !Array.prototype.indexOf ) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
}
};
Date.prototype.countDaysInMonth = function(){
return new Date(this.getFullYear(), this.getMonth()+1, 0).getDate();
};
$.fn.xdsoftScroller = function( _percent ) {
return this.each(function() {
var timeboxparent = $(this);
if( !$(this).hasClass('xdsoft_scroller_box') ) {
var pointerEventToXY = function( e ) {
var out = {x:0, y:0};
if( e.type == 'touchstart' || e.type == 'touchmove' || e.type == 'touchend' || e.type == 'touchcancel' ) {
var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
out.x = touch.pageX;
out.y = touch.pageY;
}else if (e.type == 'mousedown' || e.type == 'mouseup' || e.type == 'mousemove' || e.type == 'mouseover'|| e.type=='mouseout' || e.type=='mouseenter' || e.type=='mouseleave') {
out.x = e.pageX;
out.y = e.pageY;
}
return out;
},
move = 0,
timebox = timeboxparent.children().eq(0),
parentHeight = timeboxparent[0].clientHeight,
height = timebox[0].offsetHeight,
scrollbar = $('<div class="xdsoft_scrollbar"></div>'),
scroller = $('<div class="xdsoft_scroller"></div>'),
maximumOffset = 100,
start = false;
scrollbar.append(scroller);
timeboxparent.addClass('xdsoft_scroller_box').append(scrollbar);
scroller.on('mousedown.xdsoft_scroller',function ( event ) {
if( !parentHeight )
timeboxparent.trigger('resize_scroll.xdsoft_scroller',[_percent]);
var pageY = event.pageY,
top = parseInt(scroller.css('margin-top')),
h1 = scrollbar[0].offsetHeight;
$(document.body).addClass('xdsoft_noselect');
$([document.body,window]).on('mouseup.xdsoft_scroller',function arguments_callee() {
$([document.body,window]).off('mouseup.xdsoft_scroller',arguments_callee)
.off('mousemove.xdsoft_scroller',move)
.removeClass('xdsoft_noselect');
});
$(document.body).on('mousemove.xdsoft_scroller',move = function(event) {
var offset = event.pageY-pageY+top;
if( offset<0 )
offset = 0;
if( offset+scroller[0].offsetHeight>h1 )
offset = h1-scroller[0].offsetHeight;
timeboxparent.trigger('scroll_element.xdsoft_scroller',[maximumOffset?offset/maximumOffset:0]);
});
});
timeboxparent
.on('scroll_element.xdsoft_scroller',function( event,percent ) {
if( !parentHeight )
timeboxparent.trigger('resize_scroll.xdsoft_scroller',[percent,true]);
percent = percent>1?1:(percent<0||isNaN(percent))?0:percent;
scroller.css('margin-top',maximumOffset*percent);
timebox.css('marginTop',-parseInt((height-parentHeight)*percent))
})
.on('resize_scroll.xdsoft_scroller',function( event,_percent,noTriggerScroll ) {
parentHeight = timeboxparent[0].clientHeight;
height = timebox[0].offsetHeight;
var percent = parentHeight/height,
sh = percent*scrollbar[0].offsetHeight;
if( percent>1 )
scroller.hide();
else{
scroller.show();
scroller.css('height',parseInt(sh>10?sh:10));
maximumOffset = scrollbar[0].offsetHeight-scroller[0].offsetHeight;
if( noTriggerScroll!==true )
timeboxparent.trigger('scroll_element.xdsoft_scroller',[_percent?_percent:Math.abs(parseInt(timebox.css('marginTop')))/(height-parentHeight)]);
}
});
timeboxparent.mousewheel&&timeboxparent.mousewheel(function(event, delta, deltaX, deltaY) {
var top = Math.abs(parseInt(timebox.css('marginTop')));
timeboxparent.trigger('scroll_element.xdsoft_scroller',[(top-delta*20)/(height-parentHeight)]);
event.stopPropagation();
return false;
});
timeboxparent.on('touchstart',function( event ) {
start = pointerEventToXY(event);
});
timeboxparent.on('touchmove',function( event ) {
if( start ) {
var coord = pointerEventToXY(event), top = Math.abs(parseInt(timebox.css('marginTop')));
timeboxparent.trigger('scroll_element.xdsoft_scroller',[(top-(coord.y-start.y))/(height-parentHeight)]);
event.stopPropagation();
event.preventDefault();
};
});
timeboxparent.on('touchend touchcancel',function( event ) {
start = false;
});
}
timeboxparent.trigger('resize_scroll.xdsoft_scroller',[_percent]);
});
};
$.fn.datetimepicker = function( opt ) {
var KEY0 = 48,
KEY9 = 57,
_KEY0 = 96,
_KEY9 = 105,
CTRLKEY = 17,
DEL = 46,
ENTER = 13,
ESC = 27,
BACKSPACE = 8,
ARROWLEFT = 37,
ARROWUP = 38,
ARROWRIGHT = 39,
ARROWDOWN = 40,
TAB = 9,
F5 = 116,
AKEY = 65,
CKEY = 67,
VKEY = 86,
ZKEY = 90,
YKEY = 89,
ctrlDown = false,
options = ($.isPlainObject(opt)||!opt)?$.extend(true,{},default_options,opt):$.extend({},default_options),
lazyInitTimer = 0,
lazyInit = function( input ){
input
.on('open.xdsoft focusin.xdsoft mousedown.xdsoft',function initOnActionCallback(event) {
if( input.is(':disabled')||input.is(':hidden')||!input.is(':visible')||input.data( 'xdsoft_datetimepicker') )
return;
clearTimeout(lazyInitTimer);
lazyInitTimer = setTimeout(function() {
if( !input.data( 'xdsoft_datetimepicker') )
createDateTimePicker(input);
input
.off('open.xdsoft focusin.xdsoft mousedown.xdsoft',initOnActionCallback)
.trigger('open.xdsoft');
},100);
});
},
createDateTimePicker = function( input ) {
var datetimepicker = $('<div '+(options.id?'id="'+options.id+'"':'')+' '+(options.style?'style="'+options.style+'"':'')+' class="xdsoft_datetimepicker xdsoft_noselect '+options.className+'"></div>'),
xdsoft_copyright = $('<div class="xdsoft_copyright"><a target="_blank" href="http://xdsoft.net/jqplugins/datetimepicker/">xdsoft.net</a></div>'),
datepicker = $('<div class="xdsoft_datepicker active"></div>'),
mounth_picker = $('<div class="xdsoft_mounthpicker"><button type="button" class="xdsoft_prev"></button><button type="button" class="xdsoft_today_button"></button><div class="xdsoft_label xdsoft_month"><span></span></div><div class="xdsoft_label xdsoft_year"><span></span></div><button type="button" class="xdsoft_next"></button></div>'),
calendar = $('<div class="xdsoft_calendar"></div>'),
timepicker = $('<div class="xdsoft_timepicker active"><button type="button" class="xdsoft_prev"></button><div class="xdsoft_time_box"></div><button type="button" class="xdsoft_next"></button></div>'),
timeboxparent = timepicker.find('.xdsoft_time_box').eq(0),
timebox = $('<div class="xdsoft_time_variant"></div>'),
scrollbar = $('<div class="xdsoft_scrollbar"></div>'),
scroller = $('<div class="xdsoft_scroller"></div>'),
monthselect =$('<div class="xdsoft_select xdsoft_monthselect"><div></div></div>'),
yearselect =$('<div class="xdsoft_select xdsoft_yearselect"><div></div></div>');
//constructor lego
mounth_picker
.find('.xdsoft_month span')
.after(monthselect);
mounth_picker
.find('.xdsoft_year span')
.after(yearselect);
mounth_picker
.find('.xdsoft_month,.xdsoft_year')
.on('mousedown.xdsoft',function(event) {
mounth_picker
.find('.xdsoft_select')
.hide();
var select = $(this).find('.xdsoft_select').eq(0),
val = 0,
top = 0;
if( _xdsoft_datetime.currentTime )
val = _xdsoft_datetime.currentTime[$(this).hasClass('xdsoft_month')?'getMonth':'getFullYear']();
select.show();
for(var items = select.find('div.xdsoft_option'),i = 0;i<items.length;i++) {
if( items.eq(i).data('value')==val ) {
break;
}else top+=items[0].offsetHeight;
}
select.xdsoftScroller(top/(select.children()[0].offsetHeight-(select[0].clientHeight)));
event.stopPropagation();
return false;
});
mounth_picker
.find('.xdsoft_select')
.xdsoftScroller()
.on('mousedown.xdsoft',function( event ) {
event.stopPropagation();
event.preventDefault();
})
.on('mousedown.xdsoft','.xdsoft_option',function( event ) {
if( _xdsoft_datetime&&_xdsoft_datetime.currentTime )
_xdsoft_datetime.currentTime[$(this).parent().parent().hasClass('xdsoft_monthselect')?'setMonth':'setFullYear']($(this).data('value'));
$(this).parent().parent().hide();
datetimepicker.trigger('xchange.xdsoft');
options.onChangeMonth&&options.onChangeMonth.call&&options.onChangeMonth.call(datetimepicker,_xdsoft_datetime.currentTime,datetimepicker.data('input'));
});
// set options
datetimepicker.setOptions = function( _options ) {
options = $.extend(true,{},options,_options);
if( _options.allowTimes && $.isArray(_options.allowTimes) && _options.allowTimes.length ){
options['allowTimes'] = $.extend(true,[],_options.allowTimes);
}
if( _options.weekends && $.isArray(_options.weekends) && _options.weekends.length ){
options['weekends'] = $.extend(true,[],_options.weekends);
}
if( (options.open||options.opened)&&(!options.inline) ) {
input.trigger('open.xdsoft');
}
if( options.inline ) {
triggerAfterOpen = true;
datetimepicker.addClass('xdsoft_inline');
input.after(datetimepicker).hide();
}
if( options.inverseButton ) {
options.next = 'xdsoft_prev';
options.prev = 'xdsoft_next';
}
if( options.datepicker )
datepicker.addClass('active');
else
datepicker.removeClass('active');
if( options.timepicker )
timepicker.addClass('active');
else
timepicker.removeClass('active');
if( options.value ){
input&&input.val&&input.val(options.value);
_xdsoft_datetime.setCurrentTime(options.value);
}
if( isNaN(options.dayOfWeekStart)||parseInt(options.dayOfWeekStart)<0||parseInt(options.dayOfWeekStart)>6 )
options.dayOfWeekStart = 0;
else
options.dayOfWeekStart = parseInt(options.dayOfWeekStart);
if( !options.timepickerScrollbar )
scrollbar.hide();
if( options.minDate && /^-(.*)$/.test(options.minDate) ){
options.minDate = _xdsoft_datetime.strToDateTime(options.minDate).dateFormat( options.formatDate );
}
if( options.maxDate && /^\+(.*)$/.test(options.maxDate) ) {
options.maxDate = _xdsoft_datetime.strToDateTime(options.maxDate).dateFormat( options.formatDate );
}
mounth_picker
.find('.xdsoft_today_button')
.css('visibility',!options.todayButton?'hidden':'visible');
if( options.mask ) {
var e,
getCaretPos = function ( input ) {
try{
if ( document.selection && document.selection.createRange ) {
var range = document.selection.createRange();
return range.getBookmark().charCodeAt(2) - 2;
}else
if ( input.setSelectionRange )
return input.selectionStart;
}catch(e) {
return 0;
}
},
setCaretPos = function ( node,pos ) {
var node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node;
if(!node) {
return false;
}else if(node.createTextRange) {
var textRange = node.createTextRange();
textRange.collapse(true);
textRange.moveEnd(pos);
textRange.moveStart(pos);
textRange.select();
return true;
}else if(node.setSelectionRange) {
node.setSelectionRange(pos,pos);
return true;
}
return false;
},
isValidValue = function ( mask,value ) {
var reg = mask
.replace(/([\[\]\/\{\}\(\)\-\.\+]{1})/g,'\\$1')
.replace(/_/g,'{digit+}')
.replace(/([0-9]{1})/g,'{digit$1}')
.replace(/\{digit([0-9]{1})\}/g,'[0-$1_]{1}')
.replace(/\{digit[\+]\}/g,'[0-9_]{1}');
return RegExp(reg).test(value);
};
input.off('keydown.xdsoft');
switch(true) {
case ( options.mask===true ):
options.mask = options.format
.replace(/Y/g,'9999')
.replace(/F/g,'9999')
.replace(/m/g,'19')
.replace(/d/g,'39')
.replace(/H/g,'29')
.replace(/i/g,'59')
.replace(/s/g,'59');
case ( $.type(options.mask) == 'string' ):
if( !isValidValue( options.mask,input.val() ) )
input.val(options.mask.replace(/[0-9]/g,'_'));
input.on('keydown.xdsoft',function( event ) {
var val = this.value,
key = event.which;
switch(true) {
case (( key>=KEY0&&key<=KEY9 )||( key>=_KEY0&&key<=_KEY9 ))||(key==BACKSPACE||key==DEL):
var pos = getCaretPos(this),
digit = ( key!=BACKSPACE&&key!=DEL )?String.fromCharCode((_KEY0 <= key && key <= _KEY9)? key-KEY0 : key):'_';
if( (key==BACKSPACE||key==DEL)&&pos ) {
pos--;
digit='_';
}
while( /[^0-9_]/.test(options.mask.substr(pos,1))&&pos<options.mask.length&&pos>0 )
pos+=( key==BACKSPACE||key==DEL )?-1:1;
val = val.substr(0,pos)+digit+val.substr(pos+1);
if( $.trim(val)=='' ){
val = options.mask.replace(/[0-9]/g,'_');
}else{
if( pos==options.mask.length )
break;
}
pos+=(key==BACKSPACE||key==DEL)?0:1;
while( /[^0-9_]/.test(options.mask.substr(pos,1))&&pos<options.mask.length&&pos>0 )
pos+=(key==BACKSPACE||key==DEL)?-1:1;
if( isValidValue( options.mask,val ) ) {
this.value = val;
setCaretPos(this,pos);
}else if( $.trim(val)=='' )
this.value = options.mask.replace(/[0-9]/g,'_');
else{
input.trigger('error_input.xdsoft');
}
break;
case ( !!~([AKEY,CKEY,VKEY,ZKEY,YKEY].indexOf(key))&&ctrlDown ):
case !!~([ESC,ARROWUP,ARROWDOWN,ARROWLEFT,ARROWRIGHT,F5,CTRLKEY,TAB,ENTER].indexOf(key)):
return true;
}
event.preventDefault();
return false;
});
break;
}
}
if( options.validateOnBlur ) {
input
.off('blur.xdsoft')
.on('blur.xdsoft', function() {
if( options.allowBlank && !$.trim($(this).val()).length ) {
$(this).val(null);
datetimepicker.data('xdsoft_datetime').empty();
}else if( !Date.parseDate( $(this).val(), options.format ) ) {
$(this).val((_xdsoft_datetime.now()).dateFormat( options.format ));
datetimepicker.data('xdsoft_datetime').setCurrentTime($(this).val());
}
else{
datetimepicker.data('xdsoft_datetime').setCurrentTime($(this).val());
}
datetimepicker.trigger('changedatetime.xdsoft');
});
}
options.dayOfWeekStartPrev = (options.dayOfWeekStart==0)?6:options.dayOfWeekStart-1;
datetimepicker
.trigger('xchange.xdsoft')
.trigger('afterOpen.xdsoft')
};
datetimepicker
.data('options',options)
.on('mousedown.xdsoft',function( event ) {
event.stopPropagation();
event.preventDefault();
yearselect.hide();
monthselect.hide();
return false;
});
var scroll_element = timepicker.find('.xdsoft_time_box');
scroll_element.append(timebox);
scroll_element.xdsoftScroller();
datetimepicker.on('afterOpen.xdsoft',function() {
scroll_element.xdsoftScroller();
});
datetimepicker
.append(datepicker)
.append(timepicker);
if( options.withoutCopyright!==true )
datetimepicker
.append(xdsoft_copyright);
datepicker
.append(mounth_picker)
.append(calendar);
$('body').append(datetimepicker);
var _xdsoft_datetime = new function() {
var _this = this;
_this.now = function() {
var d = new Date();
if( options.yearOffset )
d.setFullYear(d.getFullYear()+options.yearOffset);
return d;
};
_this.currentTime = this.now();
_this.isValidDate = function (d) {
if ( Object.prototype.toString.call(d) !== "[object Date]" )
return false;
return !isNaN(d.getTime());
};
_this.setCurrentTime = function( dTime) {
_this.currentTime = (typeof dTime == 'string')? _this.strToDateTime(dTime) : _this.isValidDate(dTime) ? dTime: _this.now();
datetimepicker.trigger('xchange.xdsoft');
};
_this.empty = function() {
_this.currentTime = null;
};
_this.getCurrentTime = function( dTime) {
return _this.currentTime;
};
_this.nextMonth = function() {
var month = _this.currentTime.getMonth()+1;
if( month==12 ) {
_this.currentTime.setFullYear(_this.currentTime.getFullYear()+1);
month = 0;
}
_this.currentTime.setDate(
Math.min(
Date.daysInMonth[month],
_this.currentTime.getDate()
)
);
_this.currentTime.setMonth(month);
options.onChangeMonth&&options.onChangeMonth.call&&options.onChangeMonth.call(datetimepicker,_xdsoft_datetime.currentTime,datetimepicker.data('input'));
datetimepicker.trigger('xchange.xdsoft');
return month;
};
_this.prevMonth = function() {
var month = _this.currentTime.getMonth()-1;
if( month==-1 ) {
_this.currentTime.setFullYear(_this.currentTime.getFullYear()-1);
month = 11;
}
_this.currentTime.setDate(
Math.min(
Date.daysInMonth[month],
_this.currentTime.getDate()
)
);
_this.currentTime.setMonth(month);
options.onChangeMonth&&options.onChangeMonth.call&&options.onChangeMonth.call(datetimepicker,_xdsoft_datetime.currentTime,datetimepicker.data('input'));
datetimepicker.trigger('xchange.xdsoft');
return month;
};
_this.strToDateTime = function( sDateTime ) {
var tmpDate = [],timeOffset,currentTime;
if( ( tmpDate = /^(\+|\-)(.*)$/.exec(sDateTime) ) && ( tmpDate[2]=Date.parseDate(tmpDate[2], options.formatDate) ) ) {
timeOffset = tmpDate[2].getTime()-(tmpDate[2].getTimezoneOffset())*60000;
currentTime = new Date((_xdsoft_datetime.now()).getTime()+parseInt(tmpDate[1]+'1')*timeOffset);
}else
currentTime = sDateTime?Date.parseDate(sDateTime, options.format):_this.now();
if( !_this.isValidDate(currentTime) )
currentTime = _this.now();
return currentTime;
};
_this.strtodate = function( sDate ) {
var currentTime = sDate?Date.parseDate(sDate, options.formatDate):_this.now();
if( !_this.isValidDate(currentTime) )
currentTime = _this.now();
return currentTime;
};
_this.strtotime = function( sTime ) {
var currentTime = sTime?Date.parseDate(sTime, options.formatTime):_this.now();
if( !_this.isValidDate(currentTime) )
currentTime = _this.now();
return currentTime;
};
_this.str = function() {
return _this.currentTime.dateFormat(options.format);
};
};
mounth_picker
.find('.xdsoft_today_button')
.on('mousedown.xdsoft',function() {
datetimepicker.data('changed',true);
_xdsoft_datetime.setCurrentTime(0);
datetimepicker.trigger('afterOpen.xdsoft');
}).on('dblclick.xdsoft',function(){
input.val( _xdsoft_datetime.str() );
datetimepicker.trigger('close.xdsoft');
});
mounth_picker
.find('.xdsoft_prev,.xdsoft_next')
.on('mousedown.xdsoft',function() {
var $this = $(this),
timer = 0,
stop = false;
(function arguments_callee1(v) {
var month = _xdsoft_datetime.currentTime.getMonth();
if( $this.hasClass( options.next ) ) {
_xdsoft_datetime.nextMonth();
}else if( $this.hasClass( options.prev ) ) {
_xdsoft_datetime.prevMonth();
}
if (options.monthChangeSpinner) {
!stop&&(timer = setTimeout(arguments_callee1,v?v:100));
}
})(500);
$([document.body,window]).on('mouseup.xdsoft',function arguments_callee2() {
clearTimeout(timer);
stop = true;
$([document.body,window]).off('mouseup.xdsoft',arguments_callee2);
});
});
timepicker
.find('.xdsoft_prev,.xdsoft_next')
.on('mousedown.xdsoft',function() {
var $this = $(this),
timer = 0,
stop = false,
period = 110;
(function arguments_callee4(v) {
var pheight = timeboxparent[0].clientHeight,
height = timebox[0].offsetHeight,
top = Math.abs(parseInt(timebox.css('marginTop')));
if( $this.hasClass(options.next) && (height-pheight)- options.timeHeightInTimePicker>=top ) {
timebox.css('marginTop','-'+(top+options.timeHeightInTimePicker)+'px')
}else if( $this.hasClass(options.prev) && top-options.timeHeightInTimePicker>=0 ) {
timebox.css('marginTop','-'+(top-options.timeHeightInTimePicker)+'px')
}
timeboxparent.trigger('scroll_element.xdsoft_scroller',[Math.abs(parseInt(timebox.css('marginTop'))/(height-pheight))]);
period= ( period>10 )?10:period-10;
!stop&&(timer = setTimeout(arguments_callee4,v?v:period));
})(500);
$([document.body,window]).on('mouseup.xdsoft',function arguments_callee5() {
clearTimeout(timer);
stop = true;
$([document.body,window])
.off('mouseup.xdsoft',arguments_callee5);
});
});
var xchangeTimer = 0;
// base handler - generating a calendar and timepicker
datetimepicker
.on('xchange.xdsoft',function( event ) {
clearTimeout(xchangeTimer);
xchangeTimer = setTimeout(function(){
var table = '',
start = new Date(_xdsoft_datetime.currentTime.getFullYear(),_xdsoft_datetime.currentTime.getMonth(),1, 12, 0, 0),
i = 0,
today = _xdsoft_datetime.now();
while( start.getDay()!=options.dayOfWeekStart )
start.setDate(start.getDate()-1);
//generate calendar
table+='<table><thead><tr>';
// days
for(var j = 0; j<7; j++) {
table+='<th>'+options.i18n[options.lang].dayOfWeek[(j+options.dayOfWeekStart)>6?0:j+options.dayOfWeekStart]+'</th>';
}
table+='</tr></thead>';
table+='<tbody><tr>';
var maxDate = false, minDate = false;
if( options.maxDate!==false ) {
maxDate = _xdsoft_datetime.strtodate(options.maxDate);
maxDate = new Date(maxDate.getFullYear(),maxDate.getMonth(),maxDate.getDate(),23,59,59,999);
}
if( options.minDate!==false ) {
minDate = _xdsoft_datetime.strtodate(options.minDate);
minDate = new Date(minDate.getFullYear(),minDate.getMonth(),minDate.getDate());
}
var d,y,m,classes = [];
while( i<_xdsoft_datetime.currentTime.countDaysInMonth()||start.getDay()!=options.dayOfWeekStart||_xdsoft_datetime.currentTime.getMonth()==start.getMonth() ) {
classes = [];
i++;
d = start.getDate(); y = start.getFullYear(); m = start.getMonth();
classes.push('xdsoft_date');
if( ( maxDate!==false && start > maxDate )||( minDate!==false && start < minDate ) ){
classes.push('xdsoft_disabled');
}
if( _xdsoft_datetime.currentTime.getMonth()!=m ){
classes.push('xdsoft_other_month');
}
if( (options.defaultSelect||datetimepicker.data('changed')) && _xdsoft_datetime.currentTime.dateFormat( options.formatDate )==start.dateFormat( options.formatDate ) ) {
classes.push('xdsoft_current');
}
if( today.dateFormat( options.formatDate )==start.dateFormat( options.formatDate ) ) {
classes.push('xdsoft_today');
}
if( start.getDay()==0||start.getDay()==6||~options.weekends.indexOf(start.dateFormat( options.formatDate )) ) {
classes.push('xdsoft_weekend');
}
if(options.beforeShowDay && typeof options.beforeShowDay == 'function')
{
classes.push(options.beforeShowDay(start))
}
table+='<td data-date="'+d+'" data-month="'+m+'" data-year="'+y+'"'+' class="xdsoft_date xdsoft_day_of_week'+start.getDay()+' '+ classes.join(' ')+'">'+
'<div>'+d+'</div>'+
'</td>';
if( start.getDay()==options.dayOfWeekStartPrev ) {
table+='</tr>';
}
start.setDate(d+1);
}
table+='</tbody></table>';
calendar.html(table);
mounth_picker.find('.xdsoft_label span').eq(0).text(options.i18n[options.lang].months[_xdsoft_datetime.currentTime.getMonth()]);
mounth_picker.find('.xdsoft_label span').eq(1).text(_xdsoft_datetime.currentTime.getFullYear());
// generate timebox
var time = '',
h = '',
m ='',
line_time = function line_time( h,m ) {
var now = _xdsoft_datetime.now();
now.setHours(h);
h = parseInt(now.getHours());
now.setMinutes(m);
m = parseInt(now.getMinutes());
classes = [];
if( (options.maxTime!==false&&_xdsoft_datetime.strtotime(options.maxTime).getTime()<now.getTime())||(options.minTime!==false&&_xdsoft_datetime.strtotime(options.minTime).getTime()>now.getTime()))
classes.push('xdsoft_disabled');
if( (options.initTime||options.defaultSelect||datetimepicker.data('changed')) && parseInt(_xdsoft_datetime.currentTime.getHours())==parseInt(h)&&(options.step>59||Math[options.roundTime](_xdsoft_datetime.currentTime.getMinutes()/options.step)*options.step==parseInt(m))) {
if( options.defaultSelect||datetimepicker.data('changed')) {
classes.push('xdsoft_current');
} else if( options.initTime ) {
classes.push('xdsoft_init_time');
}
}
if( parseInt(today.getHours())==parseInt(h)&&parseInt(today.getMinutes())==parseInt(m))
classes.push('xdsoft_today');
time+= '<div class="xdsoft_time '+classes.join(' ')+'" data-hour="'+h+'" data-minute="'+m+'">'+now.dateFormat(options.formatTime)+'</div>';
};
if( !options.allowTimes || !$.isArray(options.allowTimes) || !options.allowTimes.length ) {
for( var i=0,j=0;i<(options.hours12?12:24);i++ ) {
for( j=0;j<60;j+=options.step ) {
h = (i<10?'0':'')+i;
m = (j<10?'0':'')+j;
line_time( h,m );
}
}
}else{
for( var i=0;i<options.allowTimes.length;i++ ) {
h = _xdsoft_datetime.strtotime(options.allowTimes[i]).getHours();
m = _xdsoft_datetime.strtotime(options.allowTimes[i]).getMinutes();
line_time( h,m );
}
}
timebox.html(time);
var opt = '',
i = 0;
for( i = parseInt(options.yearStart,10)+options.yearOffset;i<= parseInt(options.yearEnd,10)+options.yearOffset;i++ ) {
opt+='<div class="xdsoft_option '+(_xdsoft_datetime.currentTime.getFullYear()==i?'xdsoft_current':'')+'" data-value="'+i+'">'+i+'</div>';
}
yearselect.children().eq(0)
.html(opt);
for( i = 0,opt = '';i<= 11;i++ ) {
opt+='<div class="xdsoft_option '+(_xdsoft_datetime.currentTime.getMonth()==i?'xdsoft_current':'')+'" data-value="'+i+'">'+options.i18n[options.lang].months[i]+'</div>';
}
monthselect.children().eq(0).html(opt);
$(datetimepicker)
.trigger('generate.xdsoft');
},10);
event.stopPropagation();
})
.on('afterOpen.xdsoft',function() {
if( options.timepicker ) {
var classType;
if( timebox.find('.xdsoft_current').length ) {
classType = '.xdsoft_current';
} else if( timebox.find('.xdsoft_init_time').length ) {
classType = '.xdsoft_init_time';
}
if( classType ) {
var pheight = timeboxparent[0].clientHeight,
height = timebox[0].offsetHeight,
top = timebox.find(classType).index()*options.timeHeightInTimePicker+1;
if( (height-pheight)<top )
top = height-pheight;
timeboxparent.trigger('scroll_element.xdsoft_scroller',[parseInt(top)/(height-pheight)]);
}else{
timeboxparent.trigger('scroll_element.xdsoft_scroller',[0]);
}
}
});
var timerclick = 0;
calendar
.on('click.xdsoft', 'td', function (xdevent) {
xdevent.stopPropagation(); // Prevents closing of Pop-ups, Modals and Flyouts in Bootstrap
timerclick++;
var $this = $(this),
currentTime = _xdsoft_datetime.currentTime;
if( $this.hasClass('xdsoft_disabled') )
return false;
currentTime.setDate( 1 );
currentTime.setFullYear( $this.data('year') );
currentTime.setMonth( $this.data('month') );
currentTime.setDate( $this.data('date') );
datetimepicker.trigger('select.xdsoft',[currentTime]);
input.val( _xdsoft_datetime.str() );
if( (timerclick>1||(options.closeOnDateSelect===true||( options.closeOnDateSelect===0&&!options.timepicker )))&&!options.inline ) {
datetimepicker.trigger('close.xdsoft');
}
if( options.onSelectDate && options.onSelectDate.call ) {
options.onSelectDate.call(datetimepicker,_xdsoft_datetime.currentTime,datetimepicker.data('input'));
}
datetimepicker.data('changed',true);
datetimepicker.trigger('xchange.xdsoft');
datetimepicker.trigger('changedatetime.xdsoft');
setTimeout(function(){
timerclick = 0;
},200);
});
timebox
.on('click.xdsoft', 'div', function (xdevent) {
xdevent.stopPropagation(); // NAJ: Prevents closing of Pop-ups, Modals and Flyouts
var $this = $(this),
currentTime = _xdsoft_datetime.currentTime;
if( $this.hasClass('xdsoft_disabled') )
return false;
currentTime.setHours($this.data('hour'));
currentTime.setMinutes($this.data('minute'));
datetimepicker.trigger('select.xdsoft',[currentTime]);
datetimepicker.data('input').val( _xdsoft_datetime.str() );
!options.inline&&datetimepicker.trigger('close.xdsoft');
if( options.onSelectTime&&options.onSelectTime.call ) {
options.onSelectTime.call(datetimepicker,_xdsoft_datetime.currentTime,datetimepicker.data('input'));
}
datetimepicker.data('changed',true);
datetimepicker.trigger('xchange.xdsoft');
datetimepicker.trigger('changedatetime.xdsoft');
});
datetimepicker.mousewheel&&datepicker.mousewheel(function(event, delta, deltaX, deltaY) {
if( !options.scrollMonth )
return true;
if( delta<0 )
_xdsoft_datetime.nextMonth();
else
_xdsoft_datetime.prevMonth();
return false;
});
datetimepicker.mousewheel&&timeboxparent.unmousewheel().mousewheel(function(event, delta, deltaX, deltaY) {
if( !options.scrollTime )
return true;
var pheight = timeboxparent[0].clientHeight,
height = timebox[0].offsetHeight,
top = Math.abs(parseInt(timebox.css('marginTop'))),
fl = true;
if( delta<0 && (height-pheight)-options.timeHeightInTimePicker>=top ) {
timebox.css('marginTop','-'+(top+options.timeHeightInTimePicker)+'px');
fl = false;
}else if( delta>0&&top-options.timeHeightInTimePicker>=0 ) {
timebox.css('marginTop','-'+(top-options.timeHeightInTimePicker)+'px');
fl = false;
}
timeboxparent.trigger('scroll_element.xdsoft_scroller',[Math.abs(parseInt(timebox.css('marginTop'))/(height-pheight))]);
event.stopPropagation();
return fl;
});
var triggerAfterOpen = false;
datetimepicker
.on('changedatetime.xdsoft',function() {
if( options.onChangeDateTime&&options.onChangeDateTime.call ) {
var $input = datetimepicker.data('input');
options.onChangeDateTime.call(datetimepicker, _xdsoft_datetime.currentTime, $input);
$input.trigger('change');
}
})
.on('generate.xdsoft',function() {
if( options.onGenerate&&options.onGenerate.call )
options.onGenerate.call(datetimepicker,_xdsoft_datetime.currentTime,datetimepicker.data('input'));
if( triggerAfterOpen ){
datetimepicker.trigger('afterOpen.xdsoft');
triggerAfterOpen = false;
}
})
.on( 'click.xdsoft', function( xdevent )
{
xdevent.stopPropagation(); // Prevents closing of Pop-ups, Modals and Flyouts in Bootstrap
});
var current_time_index = 0;
input.mousewheel&&input.mousewheel(function( event, delta, deltaX, deltaY ) {
if( !options.scrollInput )
return true;
if( !options.datepicker && options.timepicker ) {
current_time_index = timebox.find('.xdsoft_current').length?timebox.find('.xdsoft_current').eq(0).index():0;
if( current_time_index+delta>=0&¤t_time_index+delta<timebox.children().length )
current_time_index+=delta;
timebox.children().eq(current_time_index).length&&timebox.children().eq(current_time_index).trigger('mousedown');
return false;
}else if( options.datepicker && !options.timepicker ) {
datepicker.trigger( event, [delta, deltaX, deltaY]);
input.val&&input.val( _xdsoft_datetime.str() );
datetimepicker.trigger('changedatetime.xdsoft');
return false;
}
});
var setPos = function() {
var offset = datetimepicker.data('input').offset(), top = offset.top+datetimepicker.data('input')[0].offsetHeight-1, left = offset.left;
if( top+datetimepicker[0].offsetHeight>$(window).height()+$(window).scrollTop() )
top = offset.top-datetimepicker[0].offsetHeight+1;
if (top < 0)
top = 0;
if( left+datetimepicker[0].offsetWidth>$(window).width() )
left = offset.left-datetimepicker[0].offsetWidth+datetimepicker.data('input')[0].offsetWidth;
datetimepicker.css({
left:left,
top:top
});
};
datetimepicker
.on('open.xdsoft', function() {
var onShow = true;
if( options.onShow&&options.onShow.call) {
onShow = options.onShow.call(datetimepicker,_xdsoft_datetime.currentTime,datetimepicker.data('input'));
}
if( onShow!==false ) {
datetimepicker.show();
setPos();
$(window)
.off('resize.xdsoft',setPos)
.on('resize.xdsoft',setPos);
if( options.closeOnWithoutClick ) {
$([document.body,window]).on('mousedown.xdsoft',function arguments_callee6() {
datetimepicker.trigger('close.xdsoft');
$([document.body,window]).off('mousedown.xdsoft',arguments_callee6);
});
}
}
})
.on('close.xdsoft', function( event ) {
var onClose = true;
if( options.onClose&&options.onClose.call ) {
onClose=options.onClose.call(datetimepicker,_xdsoft_datetime.currentTime,datetimepicker.data('input'));
}
if( onClose!==false&&!options.opened&&!options.inline ) {
datetimepicker.hide();
}
event.stopPropagation();
})
.data('input',input);
var timer = 0,
timer1 = 0;
datetimepicker.data('xdsoft_datetime',_xdsoft_datetime);
datetimepicker.setOptions(options);
function getCurrentValue(){
var ct = options.value?options.value:(input&&input.val&&input.val())?input.val():'';
if( ct && _xdsoft_datetime.isValidDate(ct = Date.parseDate(ct, options.format)) ) {
datetimepicker.data('changed',true);
}else
ct = '';
if( !ct && options.startDate!==false ){
ct = _xdsoft_datetime.strToDateTime(options.startDate);
}
return ct?ct:0;
}
_xdsoft_datetime.setCurrentTime( getCurrentValue() );
input
.data( 'xdsoft_datetimepicker',datetimepicker )
.on('open.xdsoft focusin.xdsoft mousedown.xdsoft',function(event) {
if( input.is(':disabled')||input.is(':hidden')||!input.is(':visible') )
return;
clearTimeout(timer);
timer = setTimeout(function() {
if( input.is(':disabled')||input.is(':hidden')||!input.is(':visible') )
return;
triggerAfterOpen = true;
_xdsoft_datetime.setCurrentTime(getCurrentValue());
datetimepicker.trigger('open.xdsoft');
},100);
})
.on('keydown.xdsoft',function( event ) {
var val = this.value,
key = event.which;
switch(true) {
case !!~([ENTER].indexOf(key)):
var elementSelector = $("input:visible,textarea:visible");
datetimepicker.trigger('close.xdsoft');
elementSelector.eq(elementSelector.index(this) + 1).focus();
return false;
case !!~[TAB].indexOf(key):
datetimepicker.trigger('close.xdsoft');
return true;
}
});
},
destroyDateTimePicker = function( input ) {
var datetimepicker = input.data('xdsoft_datetimepicker');
if( datetimepicker ) {
datetimepicker.data('xdsoft_datetime',null);
datetimepicker.remove();
input
.data( 'xdsoft_datetimepicker',null )
.off( 'open.xdsoft focusin.xdsoft focusout.xdsoft mousedown.xdsoft blur.xdsoft keydown.xdsoft' );
$(window).off('resize.xdsoft');
$([window,document.body]).off('mousedown.xdsoft');
input.unmousewheel&&input.unmousewheel();
}
};
$(document)
.off('keydown.xdsoftctrl keyup.xdsoftctrl')
.on('keydown.xdsoftctrl',function(e) {
if ( e.keyCode == CTRLKEY )
ctrlDown = true;
})
.on('keyup.xdsoftctrl',function(e) {
if ( e.keyCode == CTRLKEY )
ctrlDown = false;
});
return this.each(function() {
var datetimepicker;
if( datetimepicker = $(this).data('xdsoft_datetimepicker') ) {
if( $.type(opt) === 'string' ) {
switch(opt) {
case 'show':
$(this).select().focus();
datetimepicker.trigger( 'open.xdsoft' );
break;
case 'hide':
datetimepicker.trigger('close.xdsoft');
break;
case 'destroy':
destroyDateTimePicker($(this));
break;
case 'reset':
this.value = this.defaultValue;
if(!this.value || !datetimepicker.data('xdsoft_datetime').isValidDate(Date.parseDate(this.value, options.format)))
datetimepicker.data('changed',false);
datetimepicker.data('xdsoft_datetime').setCurrentTime(this.value);
break;
}
}else{
datetimepicker
.setOptions(opt);
}
return 0;
}else
if( ($.type(opt) !== 'string') ){
if( !options.lazyInit||options.open||options.inline ){
createDateTimePicker($(this));
}else
lazyInit($(this));
}
});
};
})( jQuery );
/*
* Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
*
* Licensed under the MIT License (LICENSE.txt).
*
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
* Thanks to: Seamus Leahy for adding deltaX and deltaY
*
* Version: 3.1.3
*
* Requires: 1.2.2+
*/
(function(factory) {if(typeof define==='function'&&define.amd) {define(['jquery'],factory)}else if(typeof exports==='object') {module.exports=factory}else{factory(jQuery)}}(function($) {var toFix=['wheel','mousewheel','DOMMouseScroll','MozMousePixelScroll'];var toBind='onwheel'in document||document.documentMode>=9?['wheel']:['mousewheel','DomMouseScroll','MozMousePixelScroll'];var lowestDelta,lowestDeltaXY;if($.event.fixHooks) {for(var i=toFix.length;i;) {$.event.fixHooks[toFix[--i]]=$.event.mouseHooks}}$.event.special.mousewheel={setup:function() {if(this.addEventListener) {for(var i=toBind.length;i;) {this.addEventListener(toBind[--i],handler,false)}}else{this.onmousewheel=handler}},teardown:function() {if(this.removeEventListener) {for(var i=toBind.length;i;) {this.removeEventListener(toBind[--i],handler,false)}}else{this.onmousewheel=null}}};$.fn.extend({mousewheel:function(fn) {return fn?this.bind("mousewheel",fn):this.trigger("mousewheel")},unmousewheel:function(fn) {return this.unbind("mousewheel",fn)}});function handler(event) {var orgEvent=event||window.event,args=[].slice.call(arguments,1),delta=0,deltaX=0,deltaY=0,absDelta=0,absDeltaXY=0,fn;event=$.event.fix(orgEvent);event.type="mousewheel";if(orgEvent.wheelDelta) {delta=orgEvent.wheelDelta}if(orgEvent.detail) {delta=orgEvent.detail*-1}if(orgEvent.deltaY) {deltaY=orgEvent.deltaY*-1;delta=deltaY}if(orgEvent.deltaX) {deltaX=orgEvent.deltaX;delta=deltaX*-1}if(orgEvent.wheelDeltaY!==undefined) {deltaY=orgEvent.wheelDeltaY}if(orgEvent.wheelDeltaX!==undefined) {deltaX=orgEvent.wheelDeltaX*-1}absDelta=Math.abs(delta);if(!lowestDelta||absDelta<lowestDelta) {lowestDelta=absDelta}absDeltaXY=Math.max(Math.abs(deltaY),Math.abs(deltaX));if(!lowestDeltaXY||absDeltaXY<lowestDeltaXY) {lowestDeltaXY=absDeltaXY}fn=delta>0?'floor':'ceil';delta=Math[fn](delta/lowestDelta);deltaX=Math[fn](deltaX/lowestDeltaXY);deltaY=Math[fn](deltaY/lowestDeltaXY);args.unshift(event,delta,deltaX,deltaY);return($.event.dispatch||$.event.handle).apply(this,args)}}));
// Parse and Format Library
//http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
/*
* Copyright (C) 2004 Baron Schwartz <baron at sequent dot org>
*
* 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, version 2.1.
*
* 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.
*/
Date.parseFunctions={count:0};Date.parseRegexes=[];Date.formatFunctions={count:0};Date.prototype.dateFormat=function(b){if(b=="unixtime"){return parseInt(this.getTime()/1000);}if(Date.formatFunctions[b]==null){Date.createNewFormat(b);}var a=Date.formatFunctions[b];return this[a]();};Date.createNewFormat=function(format){var funcName="format"+Date.formatFunctions.count++;Date.formatFunctions[format]=funcName;var code="Date.prototype."+funcName+" = function() {return ";var special=false;var ch="";for(var i=0;i<format.length;++i){ch=format.charAt(i);if(!special&&ch=="\\"){special=true;}else{if(special){special=false;code+="'"+String.escape(ch)+"' + ";}else{code+=Date.getFormatCode(ch);}}}eval(code.substring(0,code.length-3)+";}");};Date.getFormatCode=function(a){switch(a){case"d":return"String.leftPad(this.getDate(), 2, '0') + ";case"D":return"Date.dayNames[this.getDay()].substring(0, 3) + ";case"j":return"this.getDate() + ";case"l":return"Date.dayNames[this.getDay()] + ";case"S":return"this.getSuffix() + ";case"w":return"this.getDay() + ";case"z":return"this.getDayOfYear() + ";case"W":return"this.getWeekOfYear() + ";case"F":return"Date.monthNames[this.getMonth()] + ";case"m":return"String.leftPad(this.getMonth() + 1, 2, '0') + ";case"M":return"Date.monthNames[this.getMonth()].substring(0, 3) + ";case"n":return"(this.getMonth() + 1) + ";case"t":return"this.getDaysInMonth() + ";case"L":return"(this.isLeapYear() ? 1 : 0) + ";case"Y":return"this.getFullYear() + ";case"y":return"('' + this.getFullYear()).substring(2, 4) + ";case"a":return"(this.getHours() < 12 ? 'am' : 'pm') + ";case"A":return"(this.getHours() < 12 ? 'AM' : 'PM') + ";case"g":return"((this.getHours() %12) ? this.getHours() % 12 : 12) + ";case"G":return"this.getHours() + ";case"h":return"String.leftPad((this.getHours() %12) ? this.getHours() % 12 : 12, 2, '0') + ";case"H":return"String.leftPad(this.getHours(), 2, '0') + ";case"i":return"String.leftPad(this.getMinutes(), 2, '0') + ";case"s":return"String.leftPad(this.getSeconds(), 2, '0') + ";case"O":return"this.getGMTOffset() + ";case"T":return"this.getTimezone() + ";case"Z":return"(this.getTimezoneOffset() * -60) + ";default:return"'"+String.escape(a)+"' + ";}};Date.parseDate=function(a,c){if(c=="unixtime"){return new Date(!isNaN(parseInt(a))?parseInt(a)*1000:0);}if(Date.parseFunctions[c]==null){Date.createParser(c);}var b=Date.parseFunctions[c];return Date[b](a);};Date.createParser=function(format){var funcName="parse"+Date.parseFunctions.count++;var regexNum=Date.parseRegexes.length;var currentGroup=1;Date.parseFunctions[format]=funcName;var code="Date."+funcName+" = function(input) {\nvar y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, z = -1;\nvar d = new Date();\ny = d.getFullYear();\nm = d.getMonth();\nd = d.getDate();\nvar results = input.match(Date.parseRegexes["+regexNum+"]);\nif (results && results.length > 0) {";var regex="";var special=false;var ch="";for(var i=0;i<format.length;++i){ch=format.charAt(i);if(!special&&ch=="\\"){special=true;}else{if(special){special=false;regex+=String.escape(ch);}else{obj=Date.formatCodeToRegex(ch,currentGroup);currentGroup+=obj.g;regex+=obj.s;if(obj.g&&obj.c){code+=obj.c;}}}}code+="if (y > 0 && z > 0){\nvar doyDate = new Date(y,0);\ndoyDate.setDate(z);\nm = doyDate.getMonth();\nd = doyDate.getDate();\n}";code+="if (y > 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n{return new Date(y, m, d, h, i, s);}\nelse if (y > 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n{return new Date(y, m, d, h, i);}\nelse if (y > 0 && m >= 0 && d > 0 && h >= 0)\n{return new Date(y, m, d, h);}\nelse if (y > 0 && m >= 0 && d > 0)\n{return new Date(y, m, d);}\nelse if (y > 0 && m >= 0)\n{return new Date(y, m);}\nelse if (y > 0)\n{return new Date(y);}\n}return null;}";Date.parseRegexes[regexNum]=new RegExp("^"+regex+"$");eval(code);};Date.formatCodeToRegex=function(b,a){switch(b){case"D":return{g:0,c:null,s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};case"j":case"d":return{g:1,c:"d = parseInt(results["+a+"], 10);\n",s:"(\\d{1,2})"};case"l":return{g:0,c:null,s:"(?:"+Date.dayNames.join("|")+")"};case"S":return{g:0,c:null,s:"(?:st|nd|rd|th)"};case"w":return{g:0,c:null,s:"\\d"};case"z":return{g:1,c:"z = parseInt(results["+a+"], 10);\n",s:"(\\d{1,3})"};case"W":return{g:0,c:null,s:"(?:\\d{2})"};case"F":return{g:1,c:"m = parseInt(Date.monthNumbers[results["+a+"].substring(0, 3)], 10);\n",s:"("+Date.monthNames.join("|")+")"};case"M":return{g:1,c:"m = parseInt(Date.monthNumbers[results["+a+"]], 10);\n",s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};case"n":case"m":return{g:1,c:"m = parseInt(results["+a+"], 10) - 1;\n",s:"(\\d{1,2})"};case"t":return{g:0,c:null,s:"\\d{1,2}"};case"L":return{g:0,c:null,s:"(?:1|0)"};case"Y":return{g:1,c:"y = parseInt(results["+a+"], 10);\n",s:"(\\d{4})"};case"y":return{g:1,c:"var ty = parseInt(results["+a+"], 10);\ny = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",s:"(\\d{1,2})"};case"a":return{g:1,c:"if (results["+a+"] == 'am') {\nif (h == 12) { h = 0; }\n} else { if (h < 12) { h += 12; }}",s:"(am|pm)"};case"A":return{g:1,c:"if (results["+a+"] == 'AM') {\nif (h == 12) { h = 0; }\n} else { if (h < 12) { h += 12; }}",s:"(AM|PM)"};case"g":case"G":case"h":case"H":return{g:1,c:"h = parseInt(results["+a+"], 10);\n",s:"(\\d{1,2})"};case"i":return{g:1,c:"i = parseInt(results["+a+"], 10);\n",s:"(\\d{2})"};case"s":return{g:1,c:"s = parseInt(results["+a+"], 10);\n",s:"(\\d{2})"};case"O":return{g:0,c:null,s:"[+-]\\d{4}"};case"T":return{g:0,c:null,s:"[A-Z]{3}"};case"Z":return{g:0,c:null,s:"[+-]\\d{1,5}"};default:return{g:0,c:null,s:String.escape(b)};}};Date.prototype.getTimezone=function(){return this.toString().replace(/^.*? ([A-Z]{3}) [0-9]{4}.*$/,"$1").replace(/^.*?\(([A-Z])[a-z]+ ([A-Z])[a-z]+ ([A-Z])[a-z]+\)$/,"$1$2$3");};Date.prototype.getGMTOffset=function(){return(this.getTimezoneOffset()>0?"-":"+")+String.leftPad(Math.floor(Math.abs(this.getTimezoneOffset())/60),2,"0")+String.leftPad(Math.abs(this.getTimezoneOffset())%60,2,"0");};Date.prototype.getDayOfYear=function(){var a=0;Date.daysInMonth[1]=this.isLeapYear()?29:28;for(var b=0;b<this.getMonth();++b){a+=Date.daysInMonth[b];}return a+this.getDate();};Date.prototype.getWeekOfYear=function(){var b=this.getDayOfYear()+(4-this.getDay());var a=new Date(this.getFullYear(),0,1);var c=(7-a.getDay()+4);return String.leftPad(Math.ceil((b-c)/7)+1,2,"0");};Date.prototype.isLeapYear=function(){var a=this.getFullYear();return((a&3)==0&&(a%100||(a%400==0&&a)));};Date.prototype.getFirstDayOfMonth=function(){var a=(this.getDay()-(this.getDate()-1))%7;return(a<0)?(a+7):a;};Date.prototype.getLastDayOfMonth=function(){var a=(this.getDay()+(Date.daysInMonth[this.getMonth()]-this.getDate()))%7;return(a<0)?(a+7):a;};Date.prototype.getDaysInMonth=function(){Date.daysInMonth[1]=this.isLeapYear()?29:28;return Date.daysInMonth[this.getMonth()];};Date.prototype.getSuffix=function(){switch(this.getDate()){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th";}};String.escape=function(a){return a.replace(/('|\\)/g,"\\$1");};String.leftPad=function(d,b,c){var a=new String(d);if(c==null){c=" ";}while(a.length<b){a=c+a;}return a;};Date.daysInMonth=[31,28,31,30,31,30,31,31,30,31,30,31];Date.monthNames=["January","February","March","April","May","June","July","August","September","October","November","December"];Date.dayNames=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];Date.y2kYear=50;Date.monthNumbers={Jan:0,Feb:1,Mar:2,Apr:3,May:4,Jun:5,Jul:6,Aug:7,Sep:8,Oct:9,Nov:10,Dec:11};Date.patterns={ISO8601LongPattern:"Y-m-d H:i:s",ISO8601ShortPattern:"Y-m-d",ShortDatePattern:"n/j/Y",LongDatePattern:"l, F d, Y",FullDateTimePattern:"l, F d, Y g:i:s A",MonthDayPattern:"F d",ShortTimePattern:"g:i A",LongTimePattern:"g:i:s A",SortableDateTimePattern:"Y-m-d\\TH:i:s",UniversalSortableDateTimePattern:"Y-m-d H:i:sO",YearMonthPattern:"F, Y"};
| 09-movie | trunk/shared/plugin/datetimepicker-master/jquery.datetimepicker.js | JavaScript | gpl3 | 57,666 |
.xdsoft_datetimepicker{
box-shadow: 0px 5px 15px -5px rgba(0, 0, 0, 0.506);
background: #FFFFFF;
border-bottom: 1px solid #BBBBBB;
border-left: 1px solid #CCCCCC;
border-right: 1px solid #CCCCCC;
border-top: 1px solid #CCCCCC;
color: #333333;
display: block;
font-family: "Helvetica Neue", "Helvetica", "Arial", sans-serif;
padding: 8px;
padding-left: 0px;
padding-top: 2px;
position: absolute;
z-index: 9999;
-moz-box-sizing: border-box;
box-sizing: border-box;
display:none;
}
.xdsoft_datetimepicker iframe {
position: absolute;
left: 0;
top: 0;
width: 75px;
height: 210px;
background: transparent;
border:none;
}
/*For IE8 or lower*/
.xdsoft_datetimepicker button {
border:none !important;
}
.xdsoft_noselect{
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
}
.xdsoft_noselect::selection { background: transparent; }
.xdsoft_noselect::-moz-selection { background: transparent; }
.xdsoft_datetimepicker.xdsoft_inline{
display: inline-block;
position: static;
box-shadow: none;
}
.xdsoft_datetimepicker *{
-moz-box-sizing: border-box;
box-sizing: border-box;
padding:0px;
margin:0px;
}
.xdsoft_datetimepicker .xdsoft_datepicker, .xdsoft_datetimepicker .xdsoft_timepicker{
display:none;
}
.xdsoft_datetimepicker .xdsoft_datepicker.active, .xdsoft_datetimepicker .xdsoft_timepicker.active{
display:block;
}
.xdsoft_datetimepicker .xdsoft_datepicker{
width: 224px;
float:left;
margin-left:8px;
}
.xdsoft_datetimepicker .xdsoft_timepicker{
width: 58px;
float:left;
text-align:center;
margin-left:8px;
margin-top:0px;
}
.xdsoft_datetimepicker .xdsoft_datepicker.active+.xdsoft_timepicker{
margin-top:8px;
margin-bottom:3px
}
.xdsoft_datetimepicker .xdsoft_mounthpicker{
position: relative;
text-align: center;
}
.xdsoft_datetimepicker .xdsoft_prev, .xdsoft_datetimepicker .xdsoft_next,.xdsoft_datetimepicker .xdsoft_today_button{
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFoAAAAeCAYAAACsYQl4AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA2ZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDozQjRCQjRGREU4MkNFMzExQjRDQkIyRDJDOTdBRUI1MCIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpCQjg0OUYyNTZDODAxMUUzQjMwM0IwMERBNUU0ODQ5NSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpCQjg0OUYyNDZDODAxMUUzQjMwM0IwMERBNUU0ODQ5NSIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M2IChXaW5kb3dzKSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkI5NzE3MjFBN0E2Q0UzMTFBQjJEQjgzMDk5RTNBNTdBIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjNCNEJCNEZERTgyQ0UzMTFCNENCQjJEMkM5N0FFQjUwIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+aQvATgAAAfVJREFUeNrsmr1OwzAQxzGtkPjYEAuvVGAvfQIGRKADE49gdLwDDwBiZ2RhQUKwICQkWLsgFiRQuIBTucFJ/XFp4+hO+quqnZ4uvzj2nV2RpukCW/22yAgYNINmc7du7DcghCjrkqgOKjF1znpt6rZ0AGWQj7TvCU8d9UM+QAGDrhdyc2Bnc1WVVPBev9V8lBnY+rDwncWZThG4xk4lmxtJy2AHgoY/FySgbSBPwPZ8mEXbQx3aDERb0EbYAYFC7pcAtAvkMWwC0D3NX58S9D/YnoGC7nPWr3Dg9JTbtuHhDShBT8D2CBSK/iIEvVXxpuxSgh7DdgwUTL4iA92zmJb6lKB/YTsECmV+IgK947AGDIqgQ/LojsO135Hn51l2cWlov0JdGNrPUceueXRwilSVgkUyom9Rd6gbLfYTDeO+1v6orn0InTogYDGUkYLO3/wc9BdqqTCKP1Tfi+oTIaCBIL2TES+GTyruT9S61p6BHam+99DFEAgLFklYsIBHwSI9QY80H5ta+1rB/6ovaKihBJeEJbgLbBlQgl+j3lDPqA2tfQV1j3pVn8s+oKHGTSVJ+FqDLeR5bCqJ2E/BCycsoLZETXaKGs7rhKVt+9HZScrZNMi88V8P7LlDbvOZYaJVpMMmBCT4n0o8dTBoNgbdWPsRYACs3r7XyNfbnAAAAABJRU5ErkJggg==');
}
.xdsoft_datetimepicker .xdsoft_prev{
float: left;
background-position:-20px 0px;
}
.xdsoft_datetimepicker .xdsoft_today_button{
float: left;
background-position:-70px 0px;
margin-left:5px;
}
.xdsoft_datetimepicker .xdsoft_next{
float: right;
background-position:0px 0px;
}
.xdsoft_datetimepicker .xdsoft_next:active,.xdsoft_datetimepicker .xdsoft_prev:active{
}
.xdsoft_datetimepicker .xdsoft_next,.xdsoft_datetimepicker .xdsoft_prev ,.xdsoft_datetimepicker .xdsoft_today_button{
background-color: transparent;
background-repeat: no-repeat;
border: 0px none currentColor;
cursor: pointer;
display: block;
height: 30px;
opacity: 0.5;
outline: medium none currentColor;
overflow: hidden;
padding: 0px;
position: relative;
text-indent: 100%;
white-space: nowrap;
width: 20px;
}
.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_prev,
.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_next{
float:none;
background-position:-40px -15px;
height: 15px;
width: 30px;
display: block;
margin-left:14px;
margin-top:7px;
}
.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_prev{
background-position:-40px 0px;
margin-bottom:7px;
margin-top:0px;
}
.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_time_box{
height:151px;
overflow:hidden;
border-bottom:1px solid #DDDDDD;
}
.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_time_box >div >div{
background: #F5F5F5;
border-top:1px solid #DDDDDD;
color: #666666;
font-size: 12px;
text-align: center;
border-collapse:collapse;
cursor:pointer;
border-bottom-width:0px;
height:25px;
line-height:25px;
}
.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_time_box >div > div:first-child{
border-top-width:0px;
}
.xdsoft_datetimepicker .xdsoft_today_button:hover,
.xdsoft_datetimepicker .xdsoft_next:hover,
.xdsoft_datetimepicker .xdsoft_prev:hover {
opacity: 1;
}
.xdsoft_datetimepicker .xdsoft_label{
display: inline;
position: relative;
z-index: 9999;
margin: 0;
padding: 5px 3px;
font-size: 14px;
line-height: 20px;
font-weight: bold;
background-color: #fff;
float:left;
width:182px;
text-align:center;
cursor:pointer;
}
.xdsoft_datetimepicker .xdsoft_label:hover{
text-decoration:underline;
}
.xdsoft_datetimepicker .xdsoft_label > .xdsoft_select{
border:1px solid #ccc;
position:absolute;
display:block;
right:0px;
top:30px;
z-index:101;
display:none;
background:#fff;
max-height:160px;
overflow-y:hidden;
}
.xdsoft_datetimepicker .xdsoft_label > .xdsoft_select.xdsoft_monthselect{right:-7px;}
.xdsoft_datetimepicker .xdsoft_label > .xdsoft_select.xdsoft_yearselect{right:2px;}
.xdsoft_datetimepicker .xdsoft_label > .xdsoft_select > div > .xdsoft_option:hover{
color: #fff;
background: #ff8000;
}
.xdsoft_datetimepicker .xdsoft_label > .xdsoft_select > div > .xdsoft_option{
padding:2px 10px 2px 5px;
}
.xdsoft_datetimepicker .xdsoft_label > .xdsoft_select > div > .xdsoft_option.xdsoft_current{
background: #33AAFF;
box-shadow: #178FE5 0px 1px 3px 0px inset;
color:#fff;
font-weight: 700;
}
.xdsoft_datetimepicker .xdsoft_month{
width:90px;
text-align:right;
}
.xdsoft_datetimepicker .xdsoft_calendar{
clear:both;
}
.xdsoft_datetimepicker .xdsoft_year{
width:56px;
}
.xdsoft_datetimepicker .xdsoft_calendar table{
border-collapse:collapse;
width:100%;
}
.xdsoft_datetimepicker .xdsoft_calendar td > div{
padding-right:5px;
}
.xdsoft_datetimepicker .xdsoft_calendar th{
height: 25px;
}
.xdsoft_datetimepicker .xdsoft_calendar td,.xdsoft_datetimepicker .xdsoft_calendar th{
width:14.2857142%;
text-align:center;
background: #F5F5F5;
border:1px solid #DDDDDD;
color: #666666;
font-size: 12px;
text-align: right;
padding:0px;
border-collapse:collapse;
cursor:pointer;
height: 25px;
}
.xdsoft_datetimepicker .xdsoft_calendar th{
background: #F1F1F1;
}
.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_today{
color:#33AAFF;
}
.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_default,
.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_current,
.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_time_box >div >div.xdsoft_current{
background: #33AAFF;
box-shadow: #178FE5 0px 1px 3px 0px inset;
color:#fff;
font-weight: 700;
}
.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_other_month,
.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_disabled,
.xdsoft_datetimepicker .xdsoft_time_box >div >div.xdsoft_disabled{
opacity:0.5;
}
.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_other_month.xdsoft_disabled{
opacity:0.2;
}
.xdsoft_datetimepicker .xdsoft_calendar td:hover,
.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_time_box >div >div:hover{
color: #fff !important;
background: #ff8000 !important;
box-shadow: none !important;
}
.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_disabled:hover,
.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_time_box >div >div.xdsoft_disabled:hover{
color: inherit !important;
background: inherit !important;
box-shadow: inherit !important;
}
.xdsoft_datetimepicker .xdsoft_calendar th{
font-weight: 700;
text-align: center;
color: #999;
cursor:default;
}
.xdsoft_datetimepicker .xdsoft_copyright{ color:#ccc !important; font-size:10px;clear:both;float:none;margin-left:8px;}
.xdsoft_datetimepicker .xdsoft_copyright a{ color:#eee !important;}
.xdsoft_datetimepicker .xdsoft_copyright a:hover{ color:#aaa !important;}
.xdsoft_time_box{
position:relative;
border:1px solid #ccc;
}
.xdsoft_scrollbar >.xdsoft_scroller{
background:#ccc !important;
height:20px;
border-radius:3px;
}
.xdsoft_scrollbar{
position:absolute;
width:7px;
width:7px;
right:0px;
top:0px;
bottom:0px;
cursor:pointer;
}
.xdsoft_scroller_box{
position:relative;
} | 09-movie | trunk/shared/plugin/datetimepicker-master/jquery.datetimepicker.css | CSS | gpl3 | 9,802 |
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
body
{
/* Font */
font-family: sans-serif, Arial, Verdana, "Trebuchet MS";
font-size: 12px;
/* Text color */
color: #333;
/* Remove the background color to make it transparent */
background-color: #fff;
margin: 20px;
}
.cke_editable
{
font-size: 13px;
line-height: 1.6;
}
blockquote
{
font-style: italic;
font-family: Georgia, Times, "Times New Roman", serif;
padding: 2px 0;
border-style: solid;
border-color: #ccc;
border-width: 0;
}
.cke_contents_ltr blockquote
{
padding-left: 20px;
padding-right: 8px;
border-left-width: 5px;
}
.cke_contents_rtl blockquote
{
padding-left: 8px;
padding-right: 20px;
border-right-width: 5px;
}
a
{
color: #0782C1;
}
ol,ul,dl
{
/* IE7: reset rtl list margin. (#7334) */
*margin-right: 0px;
/* preserved spaces for list items with text direction other than the list. (#6249,#8049)*/
padding: 0 40px;
}
h1,h2,h3,h4,h5,h6
{
font-weight: normal;
line-height: 1.2;
}
hr
{
border: 0px;
border-top: 1px solid #ccc;
}
img.right
{
border: 1px solid #ccc;
float: right;
margin-left: 15px;
padding: 5px;
}
img.left
{
border: 1px solid #ccc;
float: left;
margin-right: 15px;
padding: 5px;
}
pre
{
white-space: pre-wrap; /* CSS 2.1 */
word-wrap: break-word; /* IE7 */
}
.marker
{
background-color: Yellow;
}
span[lang]
{
font-style: italic;
}
figure
{
text-align: center;
border: solid 1px #ccc;
border-radius: 2px;
background: rgba(0,0,0,0.05);
padding: 10px;
margin: 10px 20px;
display: inline-block;
}
figure > figcaption
{
text-align: center;
display: block; /* For IE8 */
}
a > img {
padding: 1px;
margin: 1px;
outline: 1px solid #0782C1;
}
| 09-movie | trunk/shared/plugin/ckeditor/contents.css | CSS | gpl3 | 1,918 |
/**
* @license Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
/**
* This file was added automatically by CKEditor builder.
* You may re-use it at any time to build CKEditor again.
*
* If you would like to build CKEditor online again
* (for example to upgrade), visit one the following links:
*
* (1) http://ckeditor.com/builder
* Visit online builder to build CKEditor from scratch.
*
* (2) http://ckeditor.com/builder/0ebaeed5189874e28f9af28caed38f94
* Visit online builder to build CKEditor, starting with the same setup as before.
*
* (3) http://ckeditor.com/builder/download/0ebaeed5189874e28f9af28caed38f94
* Straight download link to the latest version of CKEditor (Optimized) with the same setup as before.
*
* NOTE:
* This file is not used by CKEditor, you may remove it.
* Changing this file will not change your CKEditor configuration.
*/
var CKBUILDER_CONFIG = {
skin: 'moonocolor',
preset: 'standard',
ignore: [
'dev',
'.gitignore',
'.gitattributes',
'README.md',
'.mailmap'
],
plugins : {
'basicstyles' : 1,
'blockquote' : 1,
'clipboard' : 1,
'contextmenu' : 1,
'elementspath' : 1,
'enterkey' : 1,
'entities' : 1,
'filebrowser' : 1,
'floatingspace' : 1,
'format' : 1,
'horizontalrule' : 1,
'htmlwriter' : 1,
'image' : 1,
'indentlist' : 1,
'link' : 1,
'list' : 1,
'magicline' : 1,
'maximize' : 1,
'pastefromword' : 1,
'pastetext' : 1,
'removeformat' : 1,
'resize' : 1,
'scayt' : 1,
'showborders' : 1,
'sourcearea' : 1,
'specialchar' : 1,
'stylescombo' : 1,
'tab' : 1,
'table' : 1,
'tabletools' : 1,
'toolbar' : 1,
'undo' : 1,
'wsc' : 1,
'wysiwygarea' : 1
},
languages : {
'en' : 1
}
}; | 09-movie | trunk/shared/plugin/ckeditor/build-config.js | JavaScript | gpl3 | 1,861 |
/**
* @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config ) {
// Define changes to default configuration here.
// For complete reference see:
// http://docs.ckeditor.com/#!/api/CKEDITOR.config
// The toolbar groups arrangement, optimized for two toolbar rows.
config.toolbarGroups = [
{ name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
{ name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] },
{ name: 'links' },
{ name: 'insert' },
{ name: 'forms' },
{ name: 'tools' },
{ name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
{ name: 'others' },
'/',
{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
{ name: 'styles' },
{ name: 'colors' },
{ name: 'about' }
];
// Remove some buttons provided by the standard plugins, which are
// not needed in the Standard(s) toolbar.
config.removeButtons = 'Underline,Subscript,Superscript';
// Set the most common block elements.
config.format_tags = 'p;h1;h2;h3;pre';
// Simplify the dialog windows.
config.removeDialogTabs = 'image:advanced;link:advanced';
};
| 09-movie | trunk/shared/plugin/ckeditor/config.js | JavaScript | gpl3 | 1,323 |
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
| 09-movie | trunk/shared/plugin/ckeditor/plugins/dialog/dialogDefinition.js | JavaScript | gpl3 | 148 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<!--
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
-->
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function doLoadScript( url )
{
if ( !url )
return false ;
var s = document.createElement( "script" ) ;
s.type = "text/javascript" ;
s.src = url ;
document.getElementsByTagName( "head" )[ 0 ].appendChild( s ) ;
return true ;
}
var opener;
function tryLoad()
{
opener = window.parent;
// get access to global parameters
var oParams = window.opener.oldFramesetPageParams;
// make frameset rows string prepare
var sFramesetRows = ( parseInt( oParams.firstframeh, 10 ) || '30') + ",*," + ( parseInt( oParams.thirdframeh, 10 ) || '150' ) + ',0' ;
document.getElementById( 'itFrameset' ).rows = sFramesetRows ;
// dynamic including init frames and crossdomain transport code
// from config sproxy_js_frameset url
var addScriptUrl = oParams.sproxy_js_frameset ;
doLoadScript( addScriptUrl ) ;
}
</script>
</head>
<frameset id="itFrameset" onload="tryLoad();" border="0" rows="30,*,*,0">
<frame scrolling="no" framespacing="0" frameborder="0" noresize="noresize" marginheight="0" marginwidth="2" src="" name="navbar"></frame>
<frame scrolling="auto" framespacing="0" frameborder="0" noresize="noresize" marginheight="0" marginwidth="0" src="" name="mid"></frame>
<frame scrolling="no" framespacing="0" frameborder="0" noresize="noresize" marginheight="1" marginwidth="1" src="" name="bot"></frame>
<frame scrolling="no" framespacing="0" frameborder="0" noresize="noresize" marginheight="1" marginwidth="1" src="" name="spellsuggestall"></frame>
</frameset>
</html>
| 09-movie | trunk/shared/plugin/ckeditor/plugins/wsc/dialogs/tmpFrameset.html | HTML | gpl3 | 1,935 |
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
html, body
{
background-color: transparent;
margin: 0px;
padding: 0px;
}
body
{
padding: 10px;
}
body, td, input, select, textarea
{
font-size: 11px;
font-family: 'Microsoft Sans Serif' , Arial, Helvetica, Verdana;
}
.midtext
{
padding:0px;
margin:10px;
}
.midtext p
{
padding:0px;
margin:10px;
}
.Button
{
border: #737357 1px solid;
color: #3b3b1f;
background-color: #c7c78f;
}
.PopupTabArea
{
color: #737357;
background-color: #e3e3c7;
}
.PopupTitleBorder
{
border-bottom: #d5d59d 1px solid;
}
.PopupTabEmptyArea
{
padding-left: 10px;
border-bottom: #d5d59d 1px solid;
}
.PopupTab, .PopupTabSelected
{
border-right: #d5d59d 1px solid;
border-top: #d5d59d 1px solid;
border-left: #d5d59d 1px solid;
padding: 3px 5px 3px 5px;
color: #737357;
}
.PopupTab
{
margin-top: 1px;
border-bottom: #d5d59d 1px solid;
cursor: pointer;
}
.PopupTabSelected
{
font-weight: bold;
cursor: default;
padding-top: 4px;
border-bottom: #f1f1e3 1px solid;
background-color: #f1f1e3;
}
| 09-movie | trunk/shared/plugin/ckeditor/plugins/wsc/dialogs/wsc.css | CSS | gpl3 | 1,232 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<!--
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
-->
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function gup( name )
{
name = name.replace( /[\[]/, '\\\[' ).replace( /[\]]/, '\\\]' ) ;
var regexS = '[\\?&]' + name + '=([^&#]*)' ;
var regex = new RegExp( regexS ) ;
var results = regex.exec( window.location.href ) ;
if ( results )
return results[ 1 ] ;
else
return '' ;
}
var interval;
function sendData2Master()
{
var destination = window.parent.parent ;
try
{
if ( destination.XDTMaster )
{
var t = destination.XDTMaster.read( [ gup( 'cmd' ), gup( 'data' ) ] ) ;
window.clearInterval( interval ) ;
}
}
catch (e) {}
}
function OnMessage (event) {
var message = event.data;
var destination = window.parent.parent;
destination.XDTMaster.read( [ 'end', message, 'fpm' ] ) ;
}
function listenPostMessage() {
if (window.addEventListener) { // all browsers except IE before version 9
window.addEventListener ("message", OnMessage, false);
}else {
if (window.attachEvent) { // IE before version 9
window.attachEvent("onmessage", OnMessage);
}
}
}
function onLoad()
{
interval = window.setInterval( sendData2Master, 100 );
listenPostMessage();
}
</script>
</head>
<body onload="onLoad()"><p></p></body>
</html>
| 09-movie | trunk/shared/plugin/ckeditor/plugins/wsc/dialogs/ciframe.html | HTML | gpl3 | 1,690 |
a
{
text-decoration:none;
padding: 2px 4px 4px 6px;
display : block;
border-width: 1px;
border-style: solid;
margin : 0px;
}
a.cke_scayt_toogle:hover,
a.cke_scayt_toogle:focus,
a.cke_scayt_toogle:active
{
border-color: #316ac5;
background-color: #dff1ff;
color : #000;
cursor: pointer;
margin : 0px;
}
a.cke_scayt_toogle {
color : #316ac5;
border-color: #fff;
}
.scayt_enabled a.cke_scayt_item {
color : #316ac5;
border-color: #fff;
margin : 0px;
}
.scayt_disabled a.cke_scayt_item {
color : gray;
border-color : #fff;
}
.scayt_enabled a.cke_scayt_item:hover,
.scayt_enabled a.cke_scayt_item:focus,
.scayt_enabled a.cke_scayt_item:active
{
border-color: #316ac5;
background-color: #dff1ff;
color : #000;
cursor: pointer;
}
.scayt_disabled a.cke_scayt_item:hover,
.scayt_disabled a.cke_scayt_item:focus,
.scayt_disabled a.cke_scayt_item:active
{
border-color: gray;
background-color: #dff1ff;
color : gray;
cursor: no-drop;
}
.cke_scayt_set_on, .cke_scayt_set_off
{
display: none;
}
.scayt_enabled .cke_scayt_set_on
{
display: none;
}
.scayt_disabled .cke_scayt_set_on
{
display: inline;
}
.scayt_disabled .cke_scayt_set_off
{
display: none;
}
.scayt_enabled .cke_scayt_set_off
{
display: inline;
}
| 09-movie | trunk/shared/plugin/ckeditor/plugins/scayt/dialogs/toolbar.css | CSS | gpl3 | 1,302 |
/**
* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
// This file contains style definitions that can be used by CKEditor plugins.
//
// The most common use for it is the "stylescombo" plugin, which shows a combo
// in the editor toolbar, containing all styles. Other plugins instead, like
// the div plugin, use a subset of the styles on their feature.
//
// If you don't have plugins that depend on this file, you can simply ignore it.
// Otherwise it is strongly recommended to customize this file to match your
// website requirements and design properly.
CKEDITOR.stylesSet.add( 'default', [
/* Block Styles */
// These styles are already available in the "Format" combo ("format" plugin),
// so they are not needed here by default. You may enable them to avoid
// placing the "Format" combo in the toolbar, maintaining the same features.
/*
{ name: 'Paragraph', element: 'p' },
{ name: 'Heading 1', element: 'h1' },
{ name: 'Heading 2', element: 'h2' },
{ name: 'Heading 3', element: 'h3' },
{ name: 'Heading 4', element: 'h4' },
{ name: 'Heading 5', element: 'h5' },
{ name: 'Heading 6', element: 'h6' },
{ name: 'Preformatted Text',element: 'pre' },
{ name: 'Address', element: 'address' },
*/
{ name: 'Italic Title', element: 'h2', styles: { 'font-style': 'italic' } },
{ name: 'Subtitle', element: 'h3', styles: { 'color': '#aaa', 'font-style': 'italic' } },
{
name: 'Special Container',
element: 'div',
styles: {
padding: '5px 10px',
background: '#eee',
border: '1px solid #ccc'
}
},
/* Inline Styles */
// These are core styles available as toolbar buttons. You may opt enabling
// some of them in the Styles combo, removing them from the toolbar.
// (This requires the "stylescombo" plugin)
/*
{ name: 'Strong', element: 'strong', overrides: 'b' },
{ name: 'Emphasis', element: 'em' , overrides: 'i' },
{ name: 'Underline', element: 'u' },
{ name: 'Strikethrough', element: 'strike' },
{ name: 'Subscript', element: 'sub' },
{ name: 'Superscript', element: 'sup' },
*/
{ name: 'Marker', element: 'span', attributes: { 'class': 'marker' } },
{ name: 'Big', element: 'big' },
{ name: 'Small', element: 'small' },
{ name: 'Typewriter', element: 'tt' },
{ name: 'Computer Code', element: 'code' },
{ name: 'Keyboard Phrase', element: 'kbd' },
{ name: 'Sample Text', element: 'samp' },
{ name: 'Variable', element: 'var' },
{ name: 'Deleted Text', element: 'del' },
{ name: 'Inserted Text', element: 'ins' },
{ name: 'Cited Work', element: 'cite' },
{ name: 'Inline Quotation', element: 'q' },
{ name: 'Language: RTL', element: 'span', attributes: { 'dir': 'rtl' } },
{ name: 'Language: LTR', element: 'span', attributes: { 'dir': 'ltr' } },
/* Object Styles */
{
name: 'Styled image (left)',
element: 'img',
attributes: { 'class': 'left' }
},
{
name: 'Styled image (right)',
element: 'img',
attributes: { 'class': 'right' }
},
{
name: 'Compact table',
element: 'table',
attributes: {
cellpadding: '5',
cellspacing: '0',
border: '1',
bordercolor: '#ccc'
},
styles: {
'border-collapse': 'collapse'
}
},
{ name: 'Borderless Table', element: 'table', styles: { 'border-style': 'hidden', 'background-color': '#E6E6FA' } },
{ name: 'Square Bulleted List', element: 'ul', styles: { 'list-style-type': 'square' } }
] );
| 09-movie | trunk/shared/plugin/ckeditor/styles.js | JavaScript | gpl3 | 3,595 |