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 |
|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;
namespace QuanLyNhaSach.param
{
public partial class FrmRuleObject : DevComponents.DotNetBar.Office2007Form
{
RuleObjectBUS RuleBUS;
public FrmRuleObject()
{
InitializeComponent();
RuleBUS = new RuleObjectBUS();
dtgRule.AutoGenerateColumns = false;
cmbUserGroup.DisplayMember = UserGroup.UsersGroupName.ToString();
cmbUserGroup.ValueMember = UserGroup.UsersGroupID.ToString();
}
private void FrmRuleObject_Load(object sender, EventArgs e)
{
UsersGroupBUS UserBUS = new UsersGroupBUS();
List<UsersGroupDTO> listUser = UserBUS.GetUsersGroupList();
cmbUserGroup.DataSource = listUser;
cmbUserGroup.SelectedValueChanged += new EventHandler(cmbUserGroup_SelectedIndexChanged);
this.VisibleChanged += new EventHandler(FrmRuleObject_VisibleChanged);
}
void FrmRuleObject_VisibleChanged(object sender, EventArgs e)
{
}
void cmbUserGroup_SelectedIndexChanged(object sender, EventArgs e)
{
int id = Global.intParse(cmbUserGroup.SelectedValue);
List<RuleObjectDTO> listRule = RuleBUS.GetListRuleObject(id);
dtgRule.DataSource = listRule;
Global.GenerateNumber(dtgRule, colNumber.Index);
}
private void btnUpdate_Click(object sender, EventArgs e)
{
List<RuleObjectDTO> listRule = new List<RuleObjectDTO>();
foreach (DataGridViewRow row in dtgRule.Rows)
{
RuleObjectDTO rule = new RuleObjectDTO();
rule.GroupID = Global.intParse(cmbUserGroup.SelectedValue);
rule.RuleID = Global.intParse(row.Cells[colRuleID.Index].Value);
rule.RuleName = Global.stringParse(row.Cells[colRuleName.Index].Value);
rule.Status = bool.Parse(row.Cells[colStatus.Index].Value.ToString());
listRule.Add(rule);
}
if (RuleBUS.UpdateRuleObject(listRule))
{
Global.SetMessage(lblMessage, "Phân quyền thành công!", true);
}
else
{
Global.SetMessage(lblMessage, "Có lỗi trong quá trình làm việc!", false);
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/param/FrmRuleObject.cs | C# | asf20 | 2,657 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;
namespace QuanLyNhaSach.param
{
public partial class FrmParameterList : Form
{
#region Private Variable
BindingList<ParameterDTO> listParameterBinding;
int rowIndex; //Biến lưu giá trị của dòng đang sửa hơặc vừa thêm mới
ParameterBUS parameterBUS;
#endregion Private Variable
#region Constructor
public FrmParameterList()
{
InitializeComponent();
parameterBUS = new ParameterBUS();
dtgParameterList.AutoGenerateColumns = false;
rowIndex = 0;
listParameterBinding = new BindingList<ParameterDTO>();
}
#endregion Constructor
private void FrmParameterList_Load(object sender, EventArgs e)
{
listParameterBinding = parameterBUS.GetNewBindingListParameter();
dtgParameterList.DataSource = listParameterBinding;
this.VisibleChanged += new EventHandler(FrmParameterList_VisibleChanged);
}
void FrmParameterList_VisibleChanged(object sender, EventArgs e)
{
if (this.Visible)
{
Global.GenerateNumber(dtgParameterList, colNumber.Index);
Global.GenerateEditColumn(dtgParameterList, colEdit.Index);
}
}
private void dtgParameterList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
if (e.ColumnIndex == colEdit.Index)
{
UpdateParameter(e.RowIndex);
}
}
}
private void UpdateParameter(int index)
{
rowIndex = index;
ParameterDTO parameterDTO = new ParameterDTO
{
ParameterID = int.Parse(dtgParameterList[colParameterID.Index, rowIndex].Value.ToString()),
ParameterCode = dtgParameterList[colParameterCode.Index, rowIndex].Value.ToString(),
ParameterName = dtgParameterList[colParameterName.Index, rowIndex].Value.ToString(),
Value = int.Parse( dtgParameterList[colParameterValue.Index, rowIndex].Value.ToString()),
Status = bool.Parse(dtgParameterList[colIsUse.Index, rowIndex].Value.ToString())
};
param.FrmParameterDetail frm = new FrmParameterDetail { ParameterDto = parameterDTO, Action = ActionName.Update };
frm.ShowDialog();
}
private void DeleteParameter(int paraID)
{
if (dtgParameterList.Rows.Count > 0)
{
if (parameterBUS.DeleteParameter(paraID))
{
Global.SetMessage(lblMessage, "Xóa thành công", true);
listParameterBinding.Remove(listParameterBinding.First(c => c.ParameterID == paraID));
}
else
{
Global.SetMessage(lblMessage, "Xóa không thành công", false);
}
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
UpdateParameter(dtgParameterList.CurrentRow.Index);
}
private void btnDel_Click(object sender, EventArgs e)
{
int n = dtgParameterList.SelectedRows.Count;
if (n > 0)
{
for (int i = 0; i < n; i++)
{
rowIndex = dtgParameterList.SelectedRows[0].Index;
int paramID = int.Parse(dtgParameterList[colParameterID.Index, rowIndex].Value.ToString());
DeleteParameter(paramID);
}
}
}
public void ParameterChangeAfterInsert(ParameterDTO paramDTO)
{
ParameterDTO parameterDTO = parameterBUS.GetParameterByID(paramDTO.ParameterID);
listParameterBinding.Add(parameterDTO);
rowIndex = dtgParameterList.Rows.GetLastRow(DataGridViewElementStates.None);
dtgParameterList[colEdit.Index, rowIndex].Value = Properties.Resources.edit_16;
//Global.GenerateNumber(dtgCategoryList, colNumber.Index);
if (rowIndex == 0)
{
dtgParameterList[colNumber.Index, rowIndex].Value = rowIndex + 1;
}
else
{
dtgParameterList[colNumber.Index, rowIndex].Value = (int.Parse(dtgParameterList[colNumber.Index, rowIndex - 1].Value.ToString()) + 1).ToString();
}
}
public void ParameterChanged(ParameterDTO paraDTO)
{
ParameterDTO parameterDTO = parameterBUS.GetParameterByID(paraDTO.ParameterID);
dtgParameterList[colParameterName.Index, rowIndex].Value = parameterDTO.ParameterName;
dtgParameterList[colParameterValue.Index, rowIndex].Value = parameterDTO.Value;
dtgParameterList[colIsUse.Index, rowIndex].Value = parameterDTO.Status;
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/param/FrmParameterList.cs | C# | asf20 | 5,366 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;
namespace QuanLyNhaSach.param
{
public partial class FrmLogin : DevComponents.DotNetBar.Office2007Form
{
AccountBUS AccBUS;
public FrmLogin()
{
InitializeComponent();
AccBUS = new AccountBUS();
}
private void btnLogin_Click(object sender, EventArgs e)
{
if (!CheckDataInput())
{
this.DialogResult = DialogResult.No;
return;
}
AccountDTO acc;
if (AccBUS.Login(txtUserName.Text, txtPassWord.Text, out acc))
{
Global.UserID = acc.EmployeeID;
EmployeeBUS empBUS = new EmployeeBUS();
EmployeeDTO emp = empBUS.GetEmployeeByID(acc.EmployeeID);
Global.GroupID = emp.EmployeeKindCode;
this.DialogResult = DialogResult.Yes;
}
else
{
Global.SetMessage(lblMessage, "Tên đăng nhập hoặc mật khẩu không chính xác!", false);
this.DialogResult = DialogResult.No;
}
}
private bool CheckDataInput()
{
if (string.IsNullOrEmpty(txtUserName.Text))
{
Global.SetMessage(lblMessage, "Tên đăng nhập không được để trống!", false);
txtUserName.Focus();
return false;
}
if (string.IsNullOrEmpty(txtPassWord.Text))
{
Global.SetMessage(lblMessage, "Mật khẩu không được để trống!", false);
txtPassWord.Focus();
return false;
}
return true;
}
private void btnExit_Click(object sender, EventArgs e)
{
if (DevComponents.DotNetBar.MessageBoxEx.Show("Bạn muốn thoát khỏi chương trình?", "Hỏi", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
this.DialogResult = DialogResult.Yes;
Application.Exit();
}
}
private void FrmLogin_FormClosing(object sender, FormClosingEventArgs e)
{
if (this.DialogResult != DialogResult.Yes)
{
e.Cancel = true;
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/param/FrmLogin.cs | C# | asf20 | 2,601 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;
namespace QuanLyNhaSach.param
{
public partial class FrmDocSequence : DevComponents.DotNetBar.Office2007Form
{
DocSequenceBUS _docSeqBUS;
string _oldValue;
public FrmDocSequence()
{
InitializeComponent();
dtgDocSequence.AutoGenerateColumns = false;
_docSeqBUS = new DocSequenceBUS();
}
private void FrmDocSequence_Load(object sender, EventArgs e)
{
this.VisibleChanged += new EventHandler(FrmDocSequence_VisibleChanged);
}
void FrmDocSequence_VisibleChanged(object sender, EventArgs e)
{
LoadDocSequenceList();
}
private void LoadDocSequenceList()
{
List<DocSequenceDTO> ListDocSeq = _docSeqBUS.GetListDocSequence();
dtgDocSequence.DataSource = ListDocSeq;
Global.GenerateNumber(dtgDocSequence, colNumber.Index);
}
private void dtgDocSequence_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
_oldValue = Global.stringParse( dtgDocSequence[e.ColumnIndex, e.RowIndex].Value);
}
private void dtgDocSequence_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == colStart.Index)
{
string value = Global.stringParse( dtgDocSequence[e.ColumnIndex, e.RowIndex].Value);
if (value.Length <= 0 || value.Length > 2)
{
SetMessage("Kí tự bắt đầu phải có 2 kí tự.", false);
dtgDocSequence[e.ColumnIndex, e.RowIndex].Value = _oldValue;
}
}
//else if (e.ColumnIndex == colSeparator.Index)
//{
// string value = Global.stringParse(dtgDocSequence[e.ColumnIndex, e.RowIndex].Value);
// if (value.Length != 1)
// {
// SetMessage("Dấu phân cách phải có 1 kí tự.", false);
// dtgDocSequence[e.ColumnIndex, e.RowIndex].Value = _oldValue;
// }
//}
//else if (e.ColumnIndex == colMiddle.Index)
//{
// string value = Global.stringParse(dtgDocSequence[e.ColumnIndex, e.RowIndex].Value);
// if (value.Length != 4)
// {
// SetMessage("Chuỗi ở giữa phải có 4 kí tự.", false);
// dtgDocSequence[e.ColumnIndex, e.RowIndex].Value = _oldValue;
// }
//}
else if (e.ColumnIndex == colLength.Index)
{
int num = Global.intParse(dtgDocSequence[e.ColumnIndex, e.RowIndex].Value);
if (num <= 0)
{
SetMessage("Độ dài số phải là số và lớn hơn 0.", false);
dtgDocSequence[e.ColumnIndex, e.RowIndex].Value = _oldValue;
}
}
}
private void SetMessage(string mess, bool isSuccess)
{
Global.SetMessage(lblMessage, mess, isSuccess);
}
private void dtgDocSequence_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
e.Cancel = false;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
List<DocSequenceDTO> listDocSeq = new List<DocSequenceDTO>();
foreach (DataGridViewRow row in dtgDocSequence.Rows)
{
DocSequenceDTO docSeq = new DocSequenceDTO();
docSeq.DocSequenceID = Global.intParse(row.Cells[colDocSequenceID.Index].Value);
docSeq.DocSequenceText = Global.stringParse(row.Cells[colDocSeqName.Index].Value);
docSeq.DocSequenceCode = Global.stringParse(row.Cells[colStart.Index].Value).ToUpper();
docSeq.Separator = Global.stringParse(row.Cells[colSeparator.Index].Value);
docSeq.Middle = Global.stringParse(row.Cells[colMiddle.Index].Value);
docSeq.NumLength = Global.intParse(row.Cells[colLength.Index].Value);
listDocSeq.Add(docSeq);
}
if(_docSeqBUS.UpdateDocSequence(listDocSeq))
{
SetMessage("Cập nhật mã số chứng từ thành công.",true);
}
else
{
SetMessage("Có lỗi trong quá trình làm việc, vui lòng thử lại.",false);
}
LoadDocSequenceList();
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/param/FrmDocSequence.cs | C# | asf20 | 4,923 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BUS;
using DTO;
namespace QuanLyNhaSach.param
{
public partial class FrmParameterDetail : DevComponents.DotNetBar.Office2007Form
{
ParameterBUS paramBus;
public ActionName Action { get; set; }
public ParameterDTO ParameterDto { get; set; }
public FrmParameterDetail()
{
InitializeComponent();
paramBus = new ParameterBUS();
}
private void FrmParameterDetail_Load(object sender, EventArgs e)
{
txtParameterCode.Text = ParameterDto.ParameterCode;
txtParameterName.Text = ParameterDto.ParameterName;
dbiParameterValue.Value = ParameterDto.Value;
chkIsUse.Checked = ParameterDto.Status;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (!CheckDataInput())
{
return;
}
ParameterDto.ParameterName = txtParameterName.Text;
ParameterDto.Value = dbiParameterValue.Value;
ParameterDto.Status = chkIsUse.Checked;
if (paramBus.UpdateParameter(ParameterDto))
{
Global.SetMessage(lblMessage, "Cập nhật thành công!", true);
param.FrmParameterList frmList = (param.FrmParameterList)Application.OpenForms["FrmParameterList"];
if (frmList != null)
{
frmList.ParameterChanged(ParameterDto);
}
}
else
{
Global.SetMessage(lblMessage, "Cập nhật không thành công!", false);
}
}
private bool CheckDataInput()
{
if (string.IsNullOrEmpty(txtParameterCode.Text) || string.IsNullOrEmpty(txtParameterName.Text)
|| string.IsNullOrEmpty(dbiParameterValue.Value.ToString()))
{
Global.SetMessage(lblMessage, "Các trường có (*) phải được điền đầy đủ!", false);
txtParameterName.Focus();
return false;
}
return true;
}
private void FrmParameterDetail_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
btnUpdate_Click(sender, e);
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/param/FrmParameterDetail.cs | C# | asf20 | 2,617 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace QuanLyNhaSach
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/Program.cs | C# | asf20 | 507 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;
namespace QuanLyNhaSach.MainMenu
{
public partial class FrmBookReport : DevComponents.DotNetBar.Office2007Form
{
BookBUS _bookBUS;
public FrmBookReport()
{
InitializeComponent();
dtgInvoice.AutoGenerateColumns = false;
_bookBUS = new BookBUS();
dtpFrom.Value = DateTime.Now;
dtpTo.Value = DateTime.Now;
}
private void FrmBookReport_Load(object sender, EventArgs e)
{
this.VisibleChanged += new EventHandler(FrmBookReport_VisibleChanged);
}
void FrmBookReport_VisibleChanged(object sender, EventArgs e)
{
}
private void LoadListReport()
{
}
private void btnReport_Click(object sender, EventArgs e)
{
List<BookReportDTO> listRpt = _bookBUS.GetListBookForReport(dtpFrom.Value, dtpTo.Value);
dtgInvoice.DataSource = listRpt;
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/Report/FrmBookReport.cs | C# | asf20 | 1,254 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace QuanLyNhaSach.Report
{
public partial class FrmReportDebtMoney : Form
{
public FrmReportDebtMoney()
{
InitializeComponent();
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/Report/FrmReportDebtMoney.cs | C# | asf20 | 396 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;
namespace QuanLyNhaSach.Customer
{
public partial class FrmCustomerList : Form
{
#region Private Variable
BindingList<CustomerDTO> listCustomerBinding;
int rowIndex; //Biến lưu giá trị của dòng đang sửa hơặc vừa thêm mới
CustomerBUS customerBUS;
RuleObjectBUS RuleBUS;
#endregion Private Variable
#region Constructor
public FrmCustomerList()
{
InitializeComponent();
customerBUS = new CustomerBUS();
RuleBUS = new RuleObjectBUS();
dtgCustomerList.AutoGenerateColumns = false;
rowIndex = 0;
listCustomerBinding = new BindingList<CustomerDTO>();
colCustomerBirthday.DefaultCellStyle.Format = Global.DateTimeFormat;
colCustomerBeginday.DefaultCellStyle.Format = Global.DateTimeFormat;
}
#endregion Constructor
private void dtgCustomerList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
if (e.ColumnIndex == colEdit.Index)
{
UpdateCustomer(e.RowIndex);
}
else if (e.ColumnIndex == colDel.Index)
{
if (!RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject. ActionCustomer))
{
Global.SetMessage(lblMessage, "Bạn không có quyền thực hiện thao tác này!", false);
return;
}
if (Global.ShowMessageBoxDelete("Bạn chắc chắn muốn xóa khách hàng này ?") == DialogResult.Yes)
{
int cusID = int.Parse(dtgCustomerList[colCustomerID.Index, dtgCustomerList.CurrentRow.Index].Value.ToString());
DeleteCustomer(cusID);
}
}
}
}
private void FrmCustomerList_Load(object sender, EventArgs e)
{
listCustomerBinding = customerBUS.GetNewBindingListCustomer();
dtgCustomerList.DataSource = listCustomerBinding;
this.VisibleChanged += new EventHandler(FrmCustomerList_VisibleChanged);
CheckPermission();
}
private void CheckPermission()
{
btnDel.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionAuthor);
btnUpdate.Enabled = btnDel.Enabled;
}
void FrmCustomerList_VisibleChanged(object sender, EventArgs e)
{
if (this.Visible)
{
Global.GenerateNumber(dtgCustomerList, colNumber.Index);
Global.GenerateEditColumn(dtgCustomerList, colEdit.Index);
Global.GenerateDeleteColumn(dtgCustomerList, colDel.Index);
}
}
private void UpdateCustomer(int index)
{
if (!RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionCustomer))
{
Global.SetMessage(lblMessage, "Bạn không có quyền thực hiện thao tác này!", false);
return;
}
rowIndex = index;
bool sex = false;
if(dtgCustomerList[colCustomerSex.Index,rowIndex].Value.ToString() == "Nam")
sex = true;
CustomerDTO customerDTO = new CustomerDTO
{
CustomerID = int.Parse(dtgCustomerList[colCustomerID.Index, rowIndex].Value.ToString()),
CustomerCode = dtgCustomerList[colCustomerCode.Index, rowIndex].Value.ToString(),
CustomerName = dtgCustomerList[colCustomerName.Index, rowIndex].Value.ToString(),
CustomerAddress = dtgCustomerList[colCustomerAddress.Index,rowIndex].Value.ToString(),
CustomerBeginDay = (DateTime) dtgCustomerList[colCustomerBeginday.Index,rowIndex].Value,
CustomerBirthday = (DateTime) dtgCustomerList[colCustomerBirthday.Index,rowIndex].Value,
CustomerCMND = dtgCustomerList[colCustomerCMND.Index, rowIndex].Value.ToString(),
CustomerDebtMoney = (float)dtgCustomerList[colCustomerDebtMoney.Index,rowIndex].Value,
CustomerEmail = dtgCustomerList[colCustomerEmail.Index, rowIndex].Value.ToString(),
CustomerPhone = dtgCustomerList[colCustomerPhone.Index, rowIndex].Value.ToString(),
CustomerSex = sex,
Note = dtgCustomerList[colCustomerNote.Index,rowIndex].Value.ToString()
};
Customer.FrmCustomerDetail frm = new FrmCustomerDetail { CustomerDto = customerDTO, Action = ActionName.Update };
//frm.OnCategoryChanged += new Book.FrmCategoryDetail.CategoryHasChanged(CategoryChanged);
frm.ShowDialog();
}
private void DeleteCustomer(int cusID)
{
if (dtgCustomerList.Rows.Count > 0)
{
if (customerBUS.DeleteCustomer(cusID))
{
Global.SetMessage(lblMessage, "Xóa thành công", true);
listCustomerBinding.Remove(listCustomerBinding.First(c => c.CustomerID == cusID));
}
else
{
Global.SetMessage(lblMessage, "Xóa không thành công", false);
}
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
UpdateCustomer(dtgCustomerList.CurrentRow.Index);
}
private void btnDel_Click(object sender, EventArgs e)
{
int n = dtgCustomerList.SelectedRows.Count;
if ( n > 0)
{
for (int i = 0; i < n; i++)
{
rowIndex = dtgCustomerList.SelectedRows[0].Index;
int cusID = int.Parse(dtgCustomerList[colCustomerID.Index, rowIndex].Value.ToString());
DeleteCustomer(cusID);
}
}
}
public void CustomerChangeAfterInsert(CustomerDTO cusDTO)
{
CustomerDTO customerDTO = customerBUS.GetCustomerByID(cusDTO.CustomerID);
listCustomerBinding.Add(customerDTO);
rowIndex = dtgCustomerList.Rows.GetLastRow(DataGridViewElementStates.None);
dtgCustomerList[colEdit.Index, rowIndex].Value = Properties.Resources.edit_16;
dtgCustomerList[colDel.Index, rowIndex].Value = Properties.Resources.deletered;
//Global.GenerateNumber(dtgCategoryList, colNumber.Index);
if (rowIndex == 0)
{
dtgCustomerList[colNumber.Index, rowIndex].Value = rowIndex + 1;
}
else
{
dtgCustomerList[colNumber.Index, rowIndex].Value = (int.Parse(dtgCustomerList[colNumber.Index, rowIndex - 1].Value.ToString()) + 1).ToString();
}
}
public void CustomerChanged(CustomerDTO cusDTO)
{
CustomerDTO customerDTO = customerBUS.GetCustomerByID(cusDTO.CustomerID);
dtgCustomerList[colCustomerName.Index, rowIndex].Value = customerDTO.CustomerName;
dtgCustomerList[colCustomerAddress.Index, rowIndex].Value = customerDTO.CustomerAddress;
dtgCustomerList[colCustomerBirthday.Index, rowIndex].Value = customerDTO.CustomerBirthday;
dtgCustomerList[colCustomerCMND.Index,rowIndex].Value = customerDTO.CustomerCMND;
dtgCustomerList[colCustomerEmail.Index, rowIndex].Value = customerDTO.CustomerEmail;
dtgCustomerList[colCustomerPhone.Index, rowIndex].Value = customerDTO.CustomerPhone;
dtgCustomerList[colCustomerSex.Index,rowIndex].Value = customerDTO.CustomerSexString;
dtgCustomerList[colCustomerNote.Index, rowIndex].Value = customerDTO.Note;
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/Customer/FrmCustomerList.cs | C# | asf20 | 8,430 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BUS;
using DTO;
namespace QuanLyNhaSach.Customer
{
public partial class FrmCustomerDetail : DevComponents.DotNetBar.Office2007Form
{
CustomerBUS customerBus;
public ActionName Action { get; set; }
public CustomerDTO CustomerDto { get; set; }
public FrmCustomerDetail()
{
InitializeComponent();
customerBus = new CustomerBUS();
btnUpdate.Location = btnAdd.Location;
}
private void FrmCustomerDetail_Load(object sender, EventArgs e)
{
dtpCustomerBirthday.Format = DevComponents.Editors.eDateTimePickerFormat.Custom;
dtpCustomerBeginDay.Format = DevComponents.Editors.eDateTimePickerFormat.Custom;
dtpCustomerBirthday.CustomFormat = "dd/MM/yyyy";
dtpCustomerBeginDay.CustomFormat = "dd/MM/yyyy";
dbiDebt.Enabled = false;
if (Action == ActionName.Insert)
{
DocSequenceBUS docsequenceBus = new DocSequenceBUS();
txtCustomerCode.Text = docsequenceBus.GetNextDocSequenceNumber(DocSequence.Customer.ToString());
rdbMale.Checked = true;
dtpCustomerBeginDay.Value = DateTime.Now;
txtCustomerName.Focus();
CustomerDto = new CustomerDTO();
}
else
{
txtCustomerCode.Text = CustomerDto.CustomerCode;
txtCustomerName.Text = CustomerDto.CustomerName;
dtpCustomerBirthday.Value = (DateTime)CustomerDto.CustomerBirthday;
txtCustomerAddress.Text = CustomerDto.CustomerAddress;
txtCustomerPhone.Text = CustomerDto.CustomerPhone;
txtCustomerEmail.Text = CustomerDto.CustomerEmail;
if(CustomerDto.CustomerSex)
{
rdbMale.Checked = true;
rdbFemale.Checked = false;
}
else{
rdbMale.Checked = false;
rdbFemale.Checked = true;
}
txtCustomerCMND.Text = CustomerDto.CustomerCMND;
dtpCustomerBeginDay.Value =(DateTime) CustomerDto.CustomerBeginDay;
dbiDebt.Value = CustomerDto.CustomerDebtMoney;
txtCustomerNote.Text = CustomerDto.Note;
}
ProcessButton();
}
private void ProcessButton()
{
if (Action == ActionName.Insert)
{
btnUpdate.Visible = false;
btnAdd.Visible = true;
dtpCustomerBeginDay.Enabled = true;
}
else if (Action == ActionName.Update)
{
dtpCustomerBeginDay.Enabled = false;
btnUpdate.Visible = true;
btnAdd.Visible = false;
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (!CheckDataInput())
{
return;
}
CustomerDto.CustomerCode = txtCustomerCode.Text;
CustomerDto.CustomerName = txtCustomerName.Text;
CustomerDto.CustomerBirthday = dtpCustomerBirthday.Value;
CustomerDto.CustomerAddress = txtCustomerAddress.Text;
CustomerDto.CustomerPhone = txtCustomerPhone.Text;
CustomerDto.CustomerEmail = txtCustomerEmail.Text;
CustomerDto.CustomerSex = rdbMale.Checked;
CustomerDto.CustomerCMND = txtCustomerCMND.Text;
CustomerDto.CustomerBeginDay = dtpCustomerBeginDay.Value;
CustomerDto.CustomerDebtMoney = 0;
CustomerDto.Note = txtCustomerNote.Text;
CustomerDto.Status = true;
CustomerDto.CustomerID = customerBus.InsertCustomer(CustomerDto);
if (CustomerDto.CustomerID > 0)
{
Global.SetMessage(lblMessage, "Thêm thành công!", true);
Action = ActionName.Update;
ProcessButton();
Customer.FrmCustomerList frmList = (Customer.FrmCustomerList)Application.OpenForms["FrmCustomerList"];
if (frmList != null)
{
frmList.CustomerChangeAfterInsert(CustomerDto);
}
//OnCategoryChanged(Category);
}
else
{
Global.SetMessage(lblMessage, "Thêm không thành công!", false);
}
}
private void btnAddNew_Click(object sender, EventArgs e)
{
ResetForm();
Action = ActionName.Insert;
ProcessButton();
CustomerDto = new CustomerDTO();
}
public void ResetForm()
{
DocSequenceBUS docSeqBUS = new DocSequenceBUS();
txtCustomerName.Text = string.Empty;
txtCustomerName.Focus();
txtCustomerCode.Text = docSeqBUS.GetNextDocSequenceNumber(DocSequence.Customer.ToString());
txtCustomerAddress.Text = string.Empty;
txtCustomerCMND.Text = string.Empty;
txtCustomerEmail.Text = string.Empty;
txtCustomerNote.Text = string.Empty;
txtCustomerPhone.Text = string.Empty;
dbiDebt.Value = 0;
dtpCustomerBirthday.Value = DateTime.MinValue;
dtpCustomerBeginDay.Value = DateTime.Now;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (!CheckDataInput())
{
return;
}
CustomerDto.CustomerName = txtCustomerName.Text;
CustomerDto.CustomerBirthday = dtpCustomerBirthday.Value;
CustomerDto.CustomerAddress = txtCustomerAddress.Text;
CustomerDto.CustomerPhone = txtCustomerPhone.Text;
CustomerDto.CustomerEmail = txtCustomerEmail.Text;
CustomerDto.CustomerSex = rdbMale.Checked;
CustomerDto.CustomerCMND = txtCustomerCMND.Text;
CustomerDto.Note = txtCustomerNote.Text;
CustomerDto.Status = true;
if (customerBus.UpdateCustomer(CustomerDto))
{
Global.SetMessage(lblMessage, "Cập nhật thành công!", true);
//OnCategoryChanged(Category);
Customer.FrmCustomerList frmList = (Customer.FrmCustomerList)Application.OpenForms["FrmCustomerList"];
if (frmList != null)
{
frmList.CustomerChanged(CustomerDto);
}
}
else
{
Global.SetMessage(lblMessage, "Cập nhật không thành công!", false);
}
}
private bool CheckDataInput()
{
if (string.IsNullOrEmpty(txtCustomerCode.Text) || string.IsNullOrEmpty(txtCustomerName.Text)
|| string.IsNullOrEmpty(txtCustomerAddress.Text) || dtpCustomerBirthday.IsEmpty)
{
Global.SetMessage(lblMessage, "Các trường có (*) phải được điền đầy đủ!", false);
txtCustomerName.Focus();
return false;
}
if(string.IsNullOrEmpty(txtCustomerEmail.Text) || !Global.TestEmailRegex(txtCustomerEmail.Text))
{
Global.SetMessage(lblMessage, "Email chưa hợp lệ!", false);
txtCustomerEmail.Focus();
return false;
}
if (!Global.NumberOnlyRegex(txtCustomerPhone.Text))
{
Global.SetMessage(lblMessage, "Số điện thoại chưa hợp lệ!", false);
txtCustomerPhone.Focus();
return false;
}
if (string.IsNullOrEmpty(txtCustomerCMND.Text) || !Global.NumberOnlyRegex(txtCustomerCMND.Text))
{
Global.SetMessage(lblMessage, "Số CMND chưa hợp lệ!", false);
txtCustomerCMND.Focus();
return false;
}
return true;
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/Customer/FrmCustomerDetail.cs | C# | asf20 | 8,513 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using BUS;
using DTO;
namespace QuanLyNhaSach.MainMenu
{
public partial class FrmPayMoney : DevComponents.DotNetBar.Office2007Form
{
PayMoneyBUS paymoneyBus;
public ActionName Action { get; set; }
public PayMoneyDTO PayMoneyDto { get; set; }
public FrmPayMoney()
{
InitializeComponent();
paymoneyBus = new PayMoneyBUS();
dtpCustomerBirthday.Format = DevComponents.Editors.eDateTimePickerFormat.Custom;
dtpPayMoney.Format = DevComponents.Editors.eDateTimePickerFormat.Custom;
dtpCustomerBirthday.CustomFormat = Global.DateTimeFormat;
dtpPayMoney.CustomFormat = Global.DateTimeFormat;
dtpPayMoney.Value = DateTime.Now;
btnUpdate.Location = btnAdd.Location;
DocSequenceBUS docsequenceBus = new DocSequenceBUS();
txtPayMoneyCode.Text = docsequenceBus.GetNextDocSequenceNumber(DocSequence.Payment.ToString());
PayMoneyDto = new PayMoneyDTO();
}
private void btnFillCustomer_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtCustomerCode.Text))
{
MessageBoxEx.Show("Chưa nhập Mã khách hàng!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
CustomerBUS customerBUS = new CustomerBUS();
CustomerDTO customerDTO = customerBUS.GetCustomerByCode(txtCustomerCode.Text);
if (customerDTO != null)
{
txtCustomerID.Text = customerDTO.CustomerID.ToString();
txtCustomerAddress.Text = customerDTO.CustomerAddress;
txtCustomerCMND.Text = customerDTO.CustomerCMND;
txtCustomerEmail.Text = customerDTO.CustomerEmail;
txtCustomerName.Text = customerDTO.CustomerName;
dbiDebtMoney.Value = (int)customerDTO.CustomerDebtMoney;
dtpCustomerBirthday.Value = customerDTO.CustomerBirthday;
rdbMale.Checked = customerDTO.CustomerSex;
rdbFeMale.Checked = !rdbMale.Checked;
}
else
{
txtCustomerID.Text = string.Empty;
txtCustomerAddress.Text = string.Empty;
txtCustomerCMND.Text = string.Empty;
txtCustomerEmail.Text = string.Empty;
txtCustomerName.Text = string.Empty;
dbiDebtMoney.Value = 0;
rdbMale.Checked = true;
rdbFeMale.Checked = false;
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (!CheckDataInput())
{
return;
}
PayMoneyDto.PayMoneyCode = txtPayMoneyCode.Text;
PayMoneyDto.PayMoneyCustomerID = int.Parse(txtCustomerID.Text);
PayMoneyDto.Money = dbiPayMoney.Value;
PayMoneyDto.PayMoneyCreateDate = (DateTime)dtpPayMoney.Value;
PayMoneyDto.PayMoneyUserID = Global.UserID;
PayMoneyDto.Status = true;
PayMoneyDto.PayMoneyNote = txtPayMoneyNote.Text;
PayMoneyDto.PayMoneyID = paymoneyBus.InsertPayMoney(PayMoneyDto);
if (PayMoneyDto.PayMoneyID > 0)
{
//cap nhat tien no
CustomerBUS cusBus = new CustomerBUS();
double debtMoney = dbiDebtMoney.Value - dbiPayMoney.Value;
int cusID = int.Parse(txtCustomerID.Text);
if (!cusBus.UpdateCustomerDebtMoney(cusID, debtMoney))
{
Global.SetMessage(lblMessage, "Cập nhật tiền nợ chưa thành công!", false);
return;
}
Global.SetMessage(lblMessage, "Thu tiền thành công!", true);
Action = ActionName.Update;
ProcessButton();
btnFillCustomer_Click(sender, e);
}
else
{
Global.SetMessage(lblMessage, "Thu tiền không thành công!", false);
}
}
private void ProcessButton()
{
if (Action == ActionName.Insert)
{
btnUpdate.Visible = false;
btnAdd.Visible = true;
txtCustomerCode.ReadOnly = false;
}
else if (Action == ActionName.Update)
{
btnUpdate.Visible = true;
btnAdd.Visible = false;
txtCustomerCode.ReadOnly = true;
}
}
private bool CheckDataInput()
{
if (string.IsNullOrEmpty(txtCustomerID.Text))
{
Global.SetMessage(lblMessage, "Chưa tìm kiếm khách hàng trả tiền!", false);
txtCustomerCode.Focus();
return false;
}
if (string.IsNullOrEmpty(txtPayMoneyCode.Text) || dbiPayMoney.Value == 0)
{
Global.SetMessage(lblMessage, "Tiền thu chưa nhập!", false);
dbiPayMoney.Focus();
return false;
}
if (dbiDebtMoney.Value < dbiPayMoney.Value)
{
Global.SetMessage(lblMessage, "Số tiền thu không vượt quá số tiền nợ.", false);
dtpPayMoney.Focus();
return false;
}
return true;
}
private void btnAddNew_Click(object sender, EventArgs e)
{
dtpPayMoney.Value = DateTime.Now;
DocSequenceBUS docsequenceBus = new DocSequenceBUS();
txtPayMoneyCode.Text = docsequenceBus.GetNextDocSequenceNumber(DocSequence.Payment.ToString());
txtPayMoneyNote.Text = string.Empty;
dbiPayMoney.Value = 0;
txtCustomerCode.ReadOnly = false;
txtCustomerID.Text = string.Empty;
txtCustomerCode.Text = string.Empty;
txtCustomerAddress.Text = string.Empty;
txtCustomerCMND.Text = string.Empty;
txtCustomerEmail.Text = string.Empty;
txtCustomerName.Text = string.Empty;
dbiPayMoney.Focus();
Action = ActionName.Insert;
ProcessButton();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (!CheckDataInput())
return;
PayMoneyDto.PayMoneyNote = txtPayMoneyNote.Text;
PayMoneyDto.Money = dbiPayMoney.Value;
if (paymoneyBus.UpdatePayMoney(PayMoneyDto))
Global.SetMessage(lblMessage, "Cập nhật thành công!", true);
else
{
Global.SetMessage(lblMessage, "Cập nhật không thành công!", false);
return;
}
//cap nhat tien no
CustomerBUS cusBus = new CustomerBUS();
double debtMoney = dbiDebtMoney.Value - dbiPayMoney.Value;
int cusID = int.Parse(txtCustomerID.Text);
if (!cusBus.UpdateCustomerDebtMoney(cusID, debtMoney))
{
Global.SetMessage(lblMessage, "Cập nhật tiền nợ thành công!", false);
return;
}
btnFillCustomer_Click(sender, e);
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/MainMenu/FrmPayMoney.cs | C# | asf20 | 7,882 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;
namespace QuanLyNhaSach.MainMenu
{
public partial class FrmReceivingBook : DevComponents.DotNetBar.Office2007Form
{
int _MinQuantity;
float _oldPrice;
public ActionName Action { get; set; }
ReceivingBUS receiBUS;
public FrmReceivingBook()
{
InitializeComponent();
cmbBook.DisplayMember = BookColumn.BookName.ToString();
receiBUS = new ReceivingBUS();
cmbBook.ValueMember = BookColumn.BookID.ToString();
colReceivePrice.DefaultCellStyle.Format = Global.CurrencyFormat;
dtgReceiving.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dtgReceiving_EditingControlShowing);
}
void dtgReceiving_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox cmbBox;
if (dtgReceiving.CurrentCell.ColumnIndex == cmbBook.Index)
{
cmbBox = e.Control as ComboBox;
if (cmbBox != null)
{
//cmbBox.SelectedValueChanged += new EventHandler(cmbBox_SelectedValueChanged);
cmbBox.SelectedIndexChanged += cmbBox_SelectedValueChanged;
cmbBox.DropDownStyle = ComboBoxStyle.DropDown;
cmbBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
cmbBox.AutoCompleteSource = AutoCompleteSource.ListItems;
}
}
}
void cmbBox_SelectedValueChanged(object sender, EventArgs e)
{
try
{
SetMessage(string.Empty, true);
ComboBox cmbBox = (ComboBox)sender;
cmbBox.SelectedIndexChanged -= cmbBox_SelectedValueChanged;
if (Global.intParse(cmbBox.SelectedValue) > 0)
{
int bookID = int.Parse(cmbBox.SelectedValue.ToString());
BookBUS bookBUS = new BookBUS();
BookDTO bookDto = bookBUS.GetBookByID(bookID);
ParameterBUS parameterBUS = new ParameterBUS();
if (bookDto != null)
{
_MinQuantity = parameterBUS.GetParameterValueByCode(ParameterCode.MinReceiving.ToString());
dtgReceiving.CurrentRow.Cells[colBookID.Index].Value = bookDto.BookID;
dtgReceiving.CurrentRow.Cells[colReceivePrice.Index].Value = bookDto.ReceivePrice;
dtgReceiving.CurrentRow.Cells[colAuthor.Index].Value = bookDto.AuthorName;
dtgReceiving.CurrentRow.Cells[colCategory.Index].Value = bookDto.CategoryName;
dtgReceiving.CurrentRow.Cells[colStockQuantity.Index].Value = bookDto.StockQuantity;
dtgReceiving.CurrentRow.Cells[colQuantity.Index].Value = _MinQuantity;
ComputeGrandTotal();
}
int lastRow = dtgReceiving.Rows.GetLastRow(DataGridViewElementStates.None);
if (lastRow > dtgReceiving.CurrentRow.Index &&
dtgReceiving[colBookID.Index, lastRow].Value != null)
{
dtgReceiving.Rows.Add(1);
}
else if (lastRow == dtgReceiving.CurrentRow.Index)
{
dtgReceiving.Rows.Add(1);
}
}
else
{
ClearValueGrid(dtgReceiving.CurrentRow.Index);
}
cmbBox.SelectedIndexChanged += cmbBox_SelectedValueChanged;
}
catch(FormatException ex)
{
Global.SetMessage(lblMessage, ex.Message, false);
}
}
private void ClearValueGrid(int index)
{
SetMessage(string.Empty, true);
dtgReceiving[colBookID.Index, index].Value = null;
dtgReceiving[colReceivePrice.Index, index].Value = null;
dtgReceiving[colAuthor.Index, index].Value = null;
dtgReceiving[colCategory.Index, index].Value = null;
dtgReceiving[colStockQuantity.Index, index].Value = null;
dtgReceiving[colQuantity.Index, index].Value = null;
}
private void FrmReceivingBook_Load(object sender, EventArgs e)
{
LoadDocSequenceAndCombobox();
}
private void LoadDocSequenceAndCombobox()
{
SetMessage(string.Empty, true);
DocSequenceBUS docSeqBUS = new DocSequenceBUS();
txtReceivingCode.Text = docSeqBUS.GetNextDocSequenceNumber(DocSequence.Receiving.ToString());
dtpCreateDate.Value = DateTime.Now;
txtDescription.Clear();
BookBUS bookBUS = new BookBUS();
cmbBook.DataSource = bookBUS.GetNewBindingList();
dtgReceiving.Rows.Clear();
txtGrandTotal.Clear();
dtgReceiving.Rows.Add(1);
ProcessButton();
}
private void dtgReceiving_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
dtgReceiving[colDel.Index, e.RowIndex].Value = Properties.Resources.deletered;
Global.GenerateNumber(dtgReceiving, colNumber.Index);
}
private void dtgReceiving_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
try
{
SetMessage(string.Empty, true);
if (e.ColumnIndex == colQuantity.Index)
{
if (dtgReceiving[colBookID.Index, e.RowIndex].Value != null && dtgReceiving[e.ColumnIndex, e.RowIndex].Value != null)
{
int newValue = 0;
if(int.TryParse(dtgReceiving[e.ColumnIndex, e.RowIndex].Value.ToString(),out newValue))
{
if (newValue < _MinQuantity)
{
Global.SetMessage(lblMessage, "Số lượng nhập phải lớn hơn số lượng nhập tối thiểu theo quy định", false);
dtgReceiving[e.ColumnIndex, e.RowIndex].Value = _MinQuantity;
}
ComputeGrandTotal();
}
}
}
if (e.ColumnIndex == colReceivePrice.Index)
{
if (dtgReceiving[e.ColumnIndex, e.RowIndex].Value != null)
{
float price = 0;
if(float.TryParse(dtgReceiving[e.ColumnIndex, e.RowIndex].Value.ToString(),out price))
{
if (price <= 0)
{
Global.SetMessage(lblMessage, "Giá nhập phải lớn hơn 0.", false);
dtgReceiving.CurrentCell.Value = _oldPrice.ToString(Global.CurrencyFormat);
}
else
{
dtgReceiving.CurrentCell.Value = price.ToString(Global.CurrencyFormat);
}
ComputeGrandTotal();
}
}
}
}
catch (Exception ex)
{
SetMessage(ex.Message, false);
}
}
private void ComputeGrandTotal()
{
float grandTotal = 0;
foreach (DataGridViewRow row in dtgReceiving.Rows)
{
if (row.Cells[colBookID.Index].Value != null)
{
float price = float.Parse(row.Cells[colReceivePrice.Index].Value.ToString());
int quantity = int.Parse(row.Cells[colQuantity.Index].Value.ToString());
grandTotal += price * quantity;
}
}
txtGrandTotal.Text = grandTotal.ToString(Global.CurrencyFormat);
}
private void btnAddNew_Click(object sender, EventArgs e)
{
LoadDocSequenceAndCombobox();
}
private void dtgReceiving_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
if (e.ColumnIndex == colDel.Index && dtgReceiving[colBookID.Index, e.RowIndex].Value != null)
{
if (Global.ShowMessageBoxDelete("Bạn muốn xóa dòng này ?") == DialogResult.Yes)
{
dtgReceiving.Rows.RemoveAt(e.RowIndex);
Global.GenerateNumber(dtgReceiving, colNumber.Index);
ComputeGrandTotal();
}
if (dtgReceiving.Rows.Count == 0)
{
dtgReceiving.Rows.Add(1);
}
}
}
}
private void dtgReceiving_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
e.Cancel = true;
}
private void dtgReceiving_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
if (e.ColumnIndex == colReceivePrice.Index)
{
if (dtgReceiving.CurrentCell.Value != null)
{
_oldPrice = float.Parse(dtgReceiving.CurrentCell.Value.ToString());
}
}
}
private void SetMessage(string mess, bool isSuccess)
{
Global.SetMessage(lblMessage, mess, isSuccess);
}
private void ProcessButton()
{
if (Action == ActionName.Insert)
{
btnAdd.Visible = true;
btnUpdate.Visible = false;
btnDelete.Enabled = false;
btnAdd.Enabled = true;
}
else
{
btnAdd.Visible = false;
btnUpdate.Visible = true;
btnDelete.Enabled = true;
}
dtgReceiving.ReadOnly = false;
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (!CheckQuantityReceiving())
{
SetMessage("Có sách có số lượng tồn lớn hơn quy định ( dòng màu đỏ ).", false);
return;
}
ReceivingListDTO receivingDto = new ReceivingListDTO();
receivingDto.CreatedBy = Global.UserID;
receivingDto.Description = txtDescription.Text;
receivingDto.GrandTotal = Global.floatParse(txtGrandTotal.Text);
receivingDto.ReceivingCode = txtReceivingCode.Text;
receivingDto.ReceivingDate = dtpCreateDate.Value;
receivingDto.Status = true;
receivingDto.ListReceiving = new List<ReceivingDetailDTO>();
foreach (DataGridViewRow row in dtgReceiving.Rows)
{
if (row.Cells[colBookID.Index].Value != null)
{
ReceivingDetailDTO receiDetail = new ReceivingDetailDTO();
receiDetail.UnitPrice = Global.floatParse(row.Cells[colReceivePrice.Index].Value.ToString());
receiDetail.Quantity = Global.intParse(row.Cells[colQuantity.Index].Value.ToString());
receiDetail.BookID = Global.intParse(row.Cells[colBookID.Index].Value.ToString());
receivingDto.ListReceiving.Add(receiDetail);
}
//else
//{
// dtgReceiving.Rows.Remove(row);
//}
}
if (receivingDto.ListReceiving.Count == 0)
{
SetMessage("Phiếu nhập phải có ít nhất một sách!.", false);
return;
}
if (receiBUS.InsertReceivingList(receivingDto))
{
SetMessage("Nhập sách thành công.", true);
dtgReceiving.Enabled = false;
btnAdd.Enabled = false;
}
else
{
SetMessage("Có lỗi trong quá trình làm việc, vui lòng thử lại.", false);
}
}
catch(Exception ex)
{
SetMessage(ex.Message, false);
}
}
private bool CheckQuantityReceiving()
{
try
{
bool success = true;
foreach (DataGridViewRow row in dtgReceiving.Rows)
{
if (row.Cells[colBookID.Index].Value != null)
{
int quantity = Global.intParse(row.Cells[colStockQuantity.Index].Value);
if (!receiBUS.CheckQuantityReceiving(quantity))
{
success = false;
row.DefaultCellStyle.ForeColor = Color.Red;
}
else
{
row.DefaultCellStyle.ForeColor = Color.Black;
}
}
}
return success;
}
catch (Exception ex)
{
SetMessage(ex.Message, false);
return false;
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/MainMenu/FrmReceivingBook.cs | C# | asf20 | 14,442 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;
namespace QuanLyNhaSach.MainMenu
{
public partial class FrmInvoiceBook : DevComponents.DotNetBar.Office2007Form
{
public ActionName Action { get; set; }
CustomerDTO _customer;
InvoiceBUS _invoiceBUS;
public FrmInvoiceBook()
{
InitializeComponent();
_customer = new CustomerDTO();
_invoiceBUS = new InvoiceBUS();
cmbBook.DisplayMember = BookColumn.BookName.ToString();
cmbBook.ValueMember = BookColumn.BookID.ToString();
colUnitPrice.DefaultCellStyle.Format = Global.CurrencyFormat;
dtgInvoice.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dtgInvoice_EditingControlShowing);
}
void dtgInvoice_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox cmbBox;
if (dtgInvoice.CurrentCell.ColumnIndex == cmbBook.Index)
{
cmbBox = e.Control as ComboBox;
if (cmbBox != null)
{
//cmbBox.SelectedValueChanged += new EventHandler(cmbBox_SelectedValueChanged);
cmbBox.SelectedIndexChanged += new EventHandler(cmbBox_SelectedIndexChanged);
cmbBox.DropDownStyle = ComboBoxStyle.DropDown;
cmbBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
cmbBox.AutoCompleteSource = AutoCompleteSource.ListItems;
}
}
}
void cmbBox_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
SetMessage(string.Empty, true);
ComboBox cmbBox = (ComboBox)sender;
cmbBox.SelectedIndexChanged -= cmbBox_SelectedIndexChanged;
if (Global.intParse(cmbBox.SelectedValue) > 0)
{
int bookID = int.Parse(cmbBox.SelectedValue.ToString());
BookBUS bookBUS = new BookBUS();
BookDTO bookDto = bookBUS.GetBookByID(bookID);
ParameterBUS parameterBUS = new ParameterBUS();
if (bookDto != null)
{
dtgInvoice.CurrentRow.Cells[colBookID.Index].Value = bookDto.BookID;
dtgInvoice.CurrentRow.Cells[colUnitPrice.Index].Value = bookDto.BookCost;
dtgInvoice.CurrentRow.Cells[colAuthor.Index].Value = bookDto.AuthorName;
dtgInvoice.CurrentRow.Cells[colCategory.Index].Value = bookDto.CategoryName;
dtgInvoice.CurrentRow.Cells[colStockQuantity.Index].Value = bookDto.StockQuantity;
dtgInvoice.CurrentRow.Cells[colQuantity.Index].Value = 1;
ComputeGrandTotal();
}
int lastRow = dtgInvoice.Rows.GetLastRow(DataGridViewElementStates.None);
if (lastRow > dtgInvoice.CurrentRow.Index &&
dtgInvoice[colBookID.Index, lastRow].Value != null)
{
dtgInvoice.Rows.Add(1);
}
else if (lastRow == dtgInvoice.CurrentRow.Index)
{
dtgInvoice.Rows.Add(1);
}
}
else
{
ClearValueGrid(dtgInvoice.CurrentRow.Index);
}
cmbBox.SelectedIndexChanged += cmbBox_SelectedIndexChanged;
}
catch (FormatException ex)
{
Global.SetMessage(lblMessage, ex.Message, false);
}
}
private void ComputeGrandTotal()
{
float grandTotal = 0;
foreach (DataGridViewRow row in dtgInvoice.Rows)
{
if (row.Cells[colBookID.Index].Value != null)
{
float price = float.Parse(row.Cells[colUnitPrice.Index].Value.ToString());
int quantity = int.Parse(row.Cells[colQuantity.Index].Value.ToString());
grandTotal += price * quantity;
}
}
txtGrandTotal.Text = grandTotal.ToString(Global.CurrencyFormat);
}
private void ClearValueGrid(int index)
{
SetMessage(string.Empty, true);
dtgInvoice[colBookID.Index, index].Value = null;
dtgInvoice[colUnitPrice.Index, index].Value = null;
dtgInvoice[colAuthor.Index, index].Value = null;
dtgInvoice[colCategory.Index, index].Value = null;
dtgInvoice[colStockQuantity.Index, index].Value = null;
dtgInvoice[colQuantity.Index, index].Value = null;
}
private void chkMember_CheckedChanged(object sender, EventArgs e)
{
if (chkMember.Checked)
{
txtCustomerCode.Enabled = true;
}
else
{
txtCustomerCode.Enabled = false;
}
SetMessage(string.Empty, true);
}
private void SetMessage(string mess, bool isSuccess)
{
Global.SetMessage(lblMessage, mess, isSuccess);
}
private void btnAddNew_Click(object sender, EventArgs e)
{
LoadDocSequenceAndCombobox();
}
private void LoadDocSequenceAndCombobox()
{
SetMessage(string.Empty, true);
DocSequenceBUS docSeqBUS = new DocSequenceBUS();
txtInvoiceCode.Text = docSeqBUS.GetNextDocSequenceNumber(DocSequence.Invoice.ToString());
dtpInvoiceDate.Value = DateTime.Now;
txtCustomerCode.Clear();
chkMember.Checked = true;
txtDescription.Clear();
BookBUS bookBUS = new BookBUS();
cmbBook.DataSource = bookBUS.GetNewBindingList();
dtgInvoice.Rows.Clear();
txtGrandTotal.Clear();
dtgInvoice.Rows.Add(1);
ProcessButton();
}
private void ProcessButton()
{
if (Action == ActionName.Insert)
{
btnAdd.Visible = true;
btnUpdate.Visible = false;
btnDelete.Enabled = false;
btnAdd.Enabled = true;
}
else
{
btnAdd.Visible = false;
btnUpdate.Visible = true;
btnDelete.Enabled = true;
}
dtgInvoice.ReadOnly = false;
}
private void dtgInvoice_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == colQuantity.Index)
{
int quantity = Global.intParse(dtgInvoice[e.ColumnIndex, e.RowIndex].Value);
int stockQuantity = Global.intParse(dtgInvoice[colStockQuantity.Index,e.RowIndex].Value);
if (quantity < 0)
{
SetMessage("Số lượng phải lớn hơn 0.", false);
dtgInvoice[e.ColumnIndex, e.RowIndex].Value = 1;
}
else if(quantity > stockQuantity)
{
SetMessage("Số lượng bán phải nhỏ hơn số lượng tồn.",false);
dtgInvoice[e.ColumnIndex,e.RowIndex].Value = 1;
}
ComputeGrandTotal();
}
}
private void dtgInvoice_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
dtgInvoice[colDel.Index, e.RowIndex].Value = Properties.Resources.deletered;
Global.GenerateNumber(dtgInvoice, colNumber.Index);
}
private void dtgInvoice_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
e.Cancel = true;
}
private void dtgInvoice_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
if (e.ColumnIndex == colDel.Index && dtgInvoice[colBookID.Index, e.RowIndex].Value != null)
{
if (Global.ShowMessageBoxDelete("Bạn muốn xóa dòng này ?") == DialogResult.Yes)
{
dtgInvoice.Rows.RemoveAt(e.RowIndex);
Global.GenerateNumber(dtgInvoice, colNumber.Index);
ComputeGrandTotal();
}
if (dtgInvoice.Rows.Count == 0)
{
dtgInvoice.Rows.Add(1);
}
}
}
}
private void FrmInvoiceBook_Load(object sender, EventArgs e)
{
LoadDocSequenceAndCombobox();
}
private void txtCustomerCode_Leave(object sender, EventArgs e)
{
}
private void btnEditCustomerCode_Click(object sender, EventArgs e)
{
if (chkMember.Checked)
{
if (!Global.ValidateCustomerCode(txtCustomerCode.Text))
{
SetMessage("Mã khách hàng không đúng!.", false);
txtCustomerName.Clear();
_customer = new CustomerDTO();
}
else
{
SetMessage(string.Empty, true);
CustomerBUS customerBUS = new CustomerBUS();
_customer = customerBUS.GetCustomerByCode(txtCustomerCode.Text);
if (_customer != null)
{
if (customerBUS.CheckCustomerDebt(_customer))
{
txtCustomerName.Text = _customer.CustomerName;
}
else
{
SetMessage("Khách hàng nợ quá số nợ quy định,vui lòng thanh toán trước.", false);
txtCustomerName.Clear();
return;
}
}
else
{
txtCustomerName.Clear();
SetMessage("Mã khách hàng không tồn tại!.", false);
}
}
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (_customer == null || _customer.CustomerID <= 0)
{
SetMessage("Chưa nhập mã khách hàng.", false);
return;
}
if (!CheckStockQuantityAfterSell())
{
SetMessage("Có dòng có số lượng tồn sau khi bán nhỏ hơn quy định ( dòng màu đỏ ).", false);
return;
}
//Map invoiceList and insert
InvoiceDTO invoice = new InvoiceDTO();
invoice.CreatedBy = Global.UserID;
invoice.CreatedDate = dtpInvoiceDate.Value;
invoice.CustomerID = _customer.CustomerID;
invoice.Description = txtDescription.Text;
invoice.GrandTotal = Global.floatParse(txtGrandTotal.Text);
invoice.InvoiceCode = txtInvoiceCode.Text;
invoice.ListInvoiceDetail = new List<InvoiceDetailDTO>();
invoice.Status = true;
foreach (DataGridViewRow row in dtgInvoice.Rows)
{
if (row.Cells[colBookID.Index].Value != null)
{
InvoiceDetailDTO invoiceDetail = new InvoiceDetailDTO();
invoiceDetail.BookID = Global.intParse(row.Cells[colBookID.Index].Value);
invoiceDetail.Quantity = Global.intParse(row.Cells[colQuantity.Index].Value);
invoiceDetail.Status = true;
invoiceDetail.UnitPrice = Global.floatParse(row.Cells[colUnitPrice.Index].Value);
invoice.ListInvoiceDetail.Add(invoiceDetail);
}
}
if (invoice.ListInvoiceDetail.Count <= 0)
{
SetMessage("Hóa đơn phải có ít nhất 1 dòng.", false);
return;
}
if (_invoiceBUS.InsertInvoiceList(invoice))
{
SetMessage("Lập hóa đơn thành công.", true);
dtgInvoice.Enabled = false;
btnAdd.Enabled = false;
}
else
{
SetMessage("Có lỗi trong quá trình làm việc, vui lòng thử lại.", false);
}
}
private bool CheckStockQuantityAfterSell()
{
try
{
bool success = true;
foreach (DataGridViewRow row in dtgInvoice.Rows)
{
if (row.Cells[colBookID.Index].Value != null)
{
int quantity = Global.intParse(row.Cells[colQuantity.Index].Value);
int stockQuantity = Global.intParse(row.Cells[colStockQuantity.Index].Value);
if (!_invoiceBUS.CheckQuantityStockAfterSell(stockQuantity - quantity))
{
success = false;
row.DefaultCellStyle.ForeColor = Color.Red;
}
else
{
row.DefaultCellStyle.ForeColor = Color.Black;
}
}
}
return success;
}
catch (Exception ex)
{
SetMessage(ex.Message, false);
return false;
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/MainMenu/FrmInvoiceBook.cs | C# | asf20 | 14,482 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using System.IO;
using System.Drawing;
using System.ComponentModel;
using System.Collections;
using System.Text.RegularExpressions;
using DTO;
using BUS;
namespace QuanLyNhaSach
{
static class Global
{
public static int UserID = -1;
public static int GroupID = -1;
public static string DateTimeFormat = "dd/MM/yyyy";
public static string NumberFormat = "N0";
public static string CurrencyFormat = "0,0";
public static void OpenTabPages(int key, DevComponents.DotNetBar.Office2007RibbonForm frm)
{
frmMain frmM = (frmMain)Application.OpenForms["frmMain"];
frmM.OpenTab(key,frm);
}
public static void GenerateNumber(DevComponents.DotNetBar.Controls.DataGridViewX grid, int col)
{
for (int i = 0; i < grid.Rows.Count; i++)
{
grid.Rows[i].Cells[col].Value = i + 1;
}
}
public static void GenerateEditColumn(DevComponents.DotNetBar.Controls.DataGridViewX grid, int col)
{
for (int i = 0; i < grid.Rows.Count; i++)
{
grid.Rows[i].Cells[col].Value = Properties.Resources.edit_16;
grid.Rows[i].Cells[col].ToolTipText = "Sửa";
}
}
public static void GenerateDeleteColumn(DevComponents.DotNetBar.Controls.DataGridViewX grid, int col)
{
for (int i = 0; i < grid.Rows.Count; i++)
{
grid.Rows[i].Cells[col].Value = Properties.Resources.deletered;
grid.Rows[i].Cells[col].ToolTipText = "Xóa";
}
}
public static void SetMessage(ToolStripStatusLabel label, string message, bool isSuccess)
{
if (isSuccess)
{
label.ForeColor = Color.Green;
label.Text = message;
}
else
{
label.ForeColor = Color.Red;
label.Text = message;
}
}
public static DialogResult ShowMessageBoxDelete(string mess)
{
return DevComponents.DotNetBar.MessageBoxEx.Show( mess, "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
}
public static bool TestEmailRegex(string emailAddress)
{
// string patternLenient = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
// Regex reLenient = new Regex(patternLenient);
// bool isLenientMatch = reLenient.IsMatch(emailAddress
// return isLenientMatch;
string patternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
+ @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
+ @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
+ @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
+ @"[a-zA-Z]{2,}))$";
Regex reStrict = new Regex(patternStrict);
bool isStrictMatch = reStrict.IsMatch(emailAddress);
return isStrictMatch;
}
public static bool NumberOnlyRegex(string number)
{
string patternStrict = @"[0-9]{6,15}";
Regex reStrict = new Regex(patternStrict);
bool isStrictMatch = reStrict.IsMatch(number);
return isStrictMatch;
}
public static int intParse(object obj)
{
int num = 0;
if (obj == null)
{
return 0;
}
if (int.TryParse(obj.ToString(), out num))
{
return num;
}
else
{
return 0;
}
}
public static float floatParse(object obj)
{
float f = 0;
if (obj == null)
{
return 0;
}
if (float.TryParse(obj.ToString(), out f))
{
return f;
}
else
{
return 0;
}
}
public static string stringParse(object obj)
{
string str = string.Empty;
if (obj == null)
{
return string.Empty;
}
else
{
return obj.ToString();
}
}
public static bool ValidateCustomerCode(string code)
{
DocSequenceBUS docSeqBUS = new DocSequenceBUS();
DocSequenceDTO docSeqDto = docSeqBUS.GetDocSequenceByName(DocSequence.Customer.ToString());
string format = @"[" + docSeqDto.DocSequenceCode + "]{1}[0-9]{" + docSeqDto.NumLength.ToString() + "}$";
Regex reg = new Regex(format);
return reg.IsMatch(code);
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/Global.cs | C# | asf20 | 5,108 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;
namespace QuanLyNhaSach
{
public partial class frmMain : DevComponents.DotNetBar.Office2007RibbonForm
{
#region Private Variable
Dictionary<int, DevComponents.DotNetBar.SuperTabControl> listTab;
List<DevComponents.DotNetBar.RibbonTabItem> listRbTabItem;
RuleObjectBUS RuleBUS;
#endregion Private Variable
#region Constructor
public frmMain()
{
InitializeComponent();
listTab = new Dictionary<int, DevComponents.DotNetBar.SuperTabControl>();
listRbTabItem = new List<DevComponents.DotNetBar.RibbonTabItem>();
RuleBUS = new RuleObjectBUS();
}
#endregion Constructor
#region Private Methods
private void frmMain_Load(object sender, EventArgs e)
{
LoadRbTabItem();
//OpenParentTabPages((int)RibbonTabItemIndex.indexRbTabItem, indexRbTabItem.Name, indexRbTabItem.Text, new Resource.frmTest());
tabMain.SelectedTabChanged += new EventHandler<DevComponents.DotNetBar.SuperTabStripSelectedTabChangedEventArgs>(tabMain_SelectedTabChanged);
indexRbTabItem_Click(indexRbTabItem, null);
indexRbTabItem.Select();
param.FrmLogin frm = new param.FrmLogin();
frm.ShowDialog();
if (Global.UserID > 0)
{
AccountBUS AccBUS = new AccountBUS();
AccountDTO acc = AccBUS.GetAccountByID(Global.UserID);
labelItem1.Text = string.Format("{0} , Đăng nhập lúc : {1}", acc.EmployeeName, DateTime.Now.ToString("hh:mm - dd/MM/yyyy"));
}
else
{
Application.Exit();
}
}
void tabMain_SelectedTabChanged(object sender, DevComponents.DotNetBar.SuperTabStripSelectedTabChangedEventArgs e)
{
string name = tabMain.SelectedTab.Name.Replace("tabP", "");
listRbTabItem.First(t => t.Name == name).Select();
}
private void tabMain_TabItemClose(object sender, DevComponents.DotNetBar.SuperTabStripTabItemCloseEventArgs e)
{
if (tabMain.Tabs.Count > 1)
{
int key = int.Parse(e.Tab.Tag.ToString());
listTab.Remove(key);
//tabMain.SelectedTabIndex--;
}
else
{
e.Cancel = true;
}
}
private void LoadRbTabItem()
{
listRbTabItem.Add(indexRbTabItem);
listRbTabItem.Add(mainMenuRbTabItem);
listRbTabItem.Add(bookRbTabItem);
listRbTabItem.Add(CustomerRbTabItem);
listRbTabItem.Add(EmployeeRbTabItem);
listRbTabItem.Add(ReportRbTabItem);
listRbTabItem.Add(settingRbTabItem);
}
#endregion Private Methods
#region OpenTab
public void OpenParentTabPages(int key,string pTabName, string pText,Form frm)
{
tabMain.SelectedTabChanged -= tabMain_SelectedTabChanged;
string tabParentName = "tabP" + pTabName;
if (tabMain.Tabs.Contains(tabParentName))
{
int index = tabMain.Tabs.IndexOf(tabParentName);
tabMain.SelectedTabIndex = index;
}
else
{
DevComponents.DotNetBar.SuperTabControlPanel panel = new DevComponents.DotNetBar.SuperTabControlPanel();
tabMain.Controls.Add(panel);
panel.Dock = DockStyle.Fill;
DevComponents.DotNetBar.SuperTabControl tabCtr = new DevComponents.DotNetBar.SuperTabControl();
tabCtr.Name = "tabC" + pTabName;
panel.Controls.Add(tabCtr);
tabCtr.Dock = DockStyle.Fill;
tabCtr.Show();
DevComponents.DotNetBar.SuperTabItem tab = new DevComponents.DotNetBar.SuperTabItem();
tab.Name = tabParentName;
tab.Text = pText;
tab.AttachedControl = panel;
tabMain.Tabs.Add(tab);
listTab.Add(key, tabCtr);
tabCtr.CloseButtonOnTabsVisible = true;
tab.Tag = key;
//OpenTab(key, frm);
tabMain.SelectedTabIndex = tabMain.Tabs.Count - 1;
}
tabMain.SelectedTabChanged += tabMain_SelectedTabChanged;
}
public void OpenTab(int key, Form frm)
{
DevComponents.DotNetBar.SuperTabControl tabCtr = listTab[key];
string tabName = "tabC" + frm.Name;
if (tabCtr.Tabs.Contains(tabName))
{
int index = tabCtr.Tabs.IndexOf(tabName);
tabCtr.SelectedTabIndex = index;
}
else
{
//DevComponents.DotNetBar.SuperTabControlPanel panel = new DevComponents.DotNetBar.SuperTabControlPanel();
//tabMain.Controls.Add(panel);
//panel.Dock = DockStyle.Fill;
//DevComponents.DotNetBar.SuperTabItem tabPage = new DevComponents.DotNetBar.SuperTabItem();
//tabPage.Name = tabName;
//tabPage.Text = text;
//QuanLyNhaSach.Resource.frmTest frm = new Resource.frmTest();
//frm.TopLevel = false;
//panel.Controls.Add(frm);
//tabPage.AttachedControl = panel;
//tabMain.Tabs.Add(tabPage);
//frm.Dock = DockStyle.Fill;
//frm.Show();
//tabMain.SelectedTabIndex = tabMain.Tabs.Count - 1;
DevComponents.DotNetBar.SuperTabControlPanel panel = new DevComponents.DotNetBar.SuperTabControlPanel();
tabCtr.Controls.Add(panel);
panel.Dock = DockStyle.Fill;
DevComponents.DotNetBar.SuperTabItem tabPage = new DevComponents.DotNetBar.SuperTabItem();
tabPage.Name = tabName;
tabPage.Text = frm.Text;
//QuanLyNhaSach.Resource.frmTest frm = new Resource.frmTest();
frm.TopLevel = false;
panel.Controls.Add(frm);
tabPage.AttachedControl = panel;
tabCtr.Tabs.Add(tabPage);
tabCtr.TabItemClose += new EventHandler<DevComponents.DotNetBar.SuperTabStripTabItemCloseEventArgs>(tabCtr_TabItemClose);
frm.Dock = DockStyle.Fill;
frm.Show();
tabCtr.SelectedTabIndex = tabCtr.Tabs.Count - 1;
}
}
void tabCtr_TabItemClose(object sender, DevComponents.DotNetBar.SuperTabStripTabItemCloseEventArgs e)
{
DevComponents.DotNetBar.SuperTabControl ctr = (DevComponents.DotNetBar.SuperTabControl)sender;
if(ctr.Tabs.Count <= 1)
{
e.Cancel = true;
}
}
#endregion OpenTab
#region Button Item
private void btnSellBook_Click(object sender, EventArgs e)
{
OpenTab((int)RibbonTabItemIndex.mainMenuRbTabItem, new MainMenu.FrmInvoiceBook { Action = ActionName.Insert });
}
private void btnBill_Click(object sender, EventArgs e)
{
OpenTab((int)RibbonTabItemIndex.mainMenuRbTabItem, new MainMenu.FrmPayMoney());
}
private void btnBook_Click(object sender, EventArgs e)
{
OpenTab((int)RibbonTabItemIndex.mainMenuRbTabItem, new MainMenu.FrmReceivingBook {Action = ActionName.Insert });
}
private void btnAddEmployee_Click(object sender, EventArgs e)
{
Employee.EmployeeDetail frm = new Employee.EmployeeDetail { Action = ActionName.Insert };
frm.ShowDialog();
}
#endregion Button Item
#region RibbonTabItem Click
private void indexRbTabItem_Click(object sender, EventArgs e)
{
OpenParentTabPages((int)RibbonTabItemIndex.indexRbTabItem, indexRbTabItem.Name, indexRbTabItem.Text, null);
}
private void ribbonTabItem1_Click(object sender, EventArgs e)
{
OpenParentTabPages((int)RibbonTabItemIndex.mainMenuRbTabItem, mainMenuRbTabItem.Name, mainMenuRbTabItem.Text, new Resource.frmTest());
btnSellBook.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.SellBook);
btnReceivingBook.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.Receiving);
btnPaymentDebt.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.PayDebt);
}
private void ribbonTabItem2_Click(object sender, EventArgs e)
{
OpenParentTabPages((int)RibbonTabItemIndex.bookRbTabItem, bookRbTabItem.Name, bookRbTabItem.Text, new Book.FrmBookList());
btnBookList.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.BookList);
btnInsertBook.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionBook);
btnHightSearch.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.BookList);
btnAuthorList.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject. AuthorList);
btnAddAuthor.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionAuthor);
btnCategoryList.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.CategoryList);
btnAddCategory.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionCategory);
}
private void CustomerRbTabItem_Click(object sender, EventArgs e)
{
OpenParentTabPages((int)RibbonTabItemIndex.CustomerRbTabItem, CustomerRbTabItem.Name, CustomerRbTabItem.Text, new Customer.FrmCustomerList());
btnCustomerList.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.CustomerList);
btnCustomerAdd.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionCustomer);
}
private void EmployeeRbTabItem_Click(object sender, EventArgs e)
{
OpenParentTabPages((int)RibbonTabItemIndex.EmployeeRbTabItem, EmployeeRbTabItem.Name, EmployeeRbTabItem.Text, new Employee.EmployeeList());
btnListEmployee.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.EmployeeList);
btnAddEmployee.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionEmployee);
btnUserGroup.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.UserGroup);
btnAddUserGroup.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionUserGroup);
btnAccount.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.AccountList);
btnAddAccount.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionAccount);
}
private void ReportRbTabItem_Click(object sender, EventArgs e)
{
OpenParentTabPages((int)RibbonTabItemIndex.ReportRbTabItem, ReportRbTabItem.Name, ReportRbTabItem.Text, new Resource.frmTest());
btnBookReport.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.StockReport);
btnDebtReport.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.DebtReport);
}
private void settingRbTabItem_Click(object sender, EventArgs e)
{
OpenParentTabPages((int)RibbonTabItemIndex.settingRbTabItem, settingRbTabItem.Name, settingRbTabItem.Text, new Resource.frmTest());
btnParameterList.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.Param);
btnDocSequence.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.DocSequence);
btnRuleObject.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.RuleObject);
}
#endregion RibbonTabItem Click
private void buttonItem22_Click(object sender, EventArgs e)
{
UsersGroupDTO userG = new UsersGroupDTO { Status = true, UsersGroupCode = "QL", UsersGroupName = "Quan Ly" };
UsersGroupBUS userGBUS = new UsersGroupBUS();
userGBUS.InsertUsersGroup(userG);
}
private void btnAddAuthor_Click(object sender, EventArgs e)
{
Book.FrmAuthorDetail frm = new Book.FrmAuthorDetail { Action = ActionName.Insert };
frm.ShowDialog();
}
private void btnAddCategory_Click(object sender, EventArgs e)
{
Book.FrmCategoryDetail frm = new Book.FrmCategoryDetail { Action = ActionName.Insert };
//Book.FrmCategoryList frmList = (Book.FrmCategoryList)Application.OpenForms["FrmCategoryList"];
//if (frmList != null)
//{
// frm.OnCategoryChanged += new Book.FrmCategoryDetail.CategoryHasChanged(frmList.CategoryChangeAfterInsert);
//}
frm.ShowDialog();
}
private void btnCategoryList_Click(object sender, EventArgs e)
{
OpenTab((int)RibbonTabItemIndex.bookRbTabItem,new Book.FrmCategoryList());
}
private void btnListEmployee_Click(object sender, EventArgs e)
{
OpenTab((int)RibbonTabItemIndex.EmployeeRbTabItem, new Employee.EmployeeList());
}
private void btnAuthorList_Click(object sender, EventArgs e)
{
OpenTab((int)RibbonTabItemIndex.bookRbTabItem, new Book.FrmAuthorList());
}
private void buttonItem1_Click(object sender, EventArgs e)
{
OpenTab((int)RibbonTabItemIndex.bookRbTabItem, new Book.FrmBookList());
}
private void buttonItem14_Click(object sender, EventArgs e)
{
Book.FrmBookDetail frm = new Book.FrmBookDetail { Action = ActionName.Insert };
frm.ShowDialog();
}
private void btnHightSearch_Click(object sender, EventArgs e)
{
OpenTab((int)RibbonTabItemIndex.bookRbTabItem, new Book.FrmBookListSearch());
}
private void btnCustomerList_Click(object sender, EventArgs e)
{
OpenTab((int)RibbonTabItemIndex.CustomerRbTabItem, new Customer.FrmCustomerList());
}
private void btnCustomerAdd_Click(object sender, EventArgs e)
{
Customer.FrmCustomerDetail frm = new Customer.FrmCustomerDetail { Action = ActionName.Insert };
frm.ShowDialog();
}
private void btnParameterList_Click(object sender, EventArgs e)
{
OpenTab((int)RibbonTabItemIndex.settingRbTabItem, new param.FrmParameterList());
}
private void btnInsertParameter_Click(object sender, EventArgs e)
{
}
private void btnUserGroup_Click(object sender, EventArgs e)
{
OpenTab((int)RibbonTabItemIndex.EmployeeRbTabItem, new Employee.FrmUserGroupList());
}
private void btnAddUserGroup_Click(object sender, EventArgs e)
{
Employee.FrmUsersGroupDetail frm = new Employee.FrmUsersGroupDetail { Action = ActionName.Insert };
frm.ShowDialog();
}
private void btnDocSequence_Click(object sender, EventArgs e)
{
OpenTab((int)RibbonTabItemIndex.settingRbTabItem, new param.FrmDocSequence());
}
private void btnBookReport_Click(object sender, EventArgs e)
{
OpenTab((int)RibbonTabItemIndex.ReportRbTabItem, new MainMenu.FrmBookReport());
}
private void btnAccount_Click(object sender, EventArgs e)
{
OpenTab((int)RibbonTabItemIndex.EmployeeRbTabItem, new Employee.FrmAccountList());
}
private void btnAddAccount_Click(object sender, EventArgs e)
{
Employee.FrmAccountDetail frm = new Employee.FrmAccountDetail { Action = ActionName.Insert };
frm.ShowDialog();
}
private void btnLogOut_Click(object sender, EventArgs e)
{
Global.UserID = -1;
Global.GroupID = -1;
indexRbTabItem_Click(sender,e);
frmMain_Load(sender, e);
for (int i = 1; i <= 7; i++)
{
if (listTab.ContainsKey(i))
{
DevComponents.DotNetBar.SuperTabControl ctr = listTab[i];
ctr.Tabs.Clear();
}
}
//listRbTabItem.Clear();
}
private void btnExit_Click(object sender, EventArgs e)
{
if (DevComponents.DotNetBar.MessageBoxEx.Show("Bạn muốn thoát khỏi chương trình?", "Hỏi", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Application.Exit();
}
}
private void btnRuleObject_Click(object sender, EventArgs e)
{
OpenTab((int)RibbonTabItemIndex.settingRbTabItem, new param.FrmRuleObject());
}
private void btnDebtReport_Click(object sender, EventArgs e)
{
OpenTab((int)RibbonTabItemIndex.ReportRbTabItem, new Report.FrmReportDebtMoney());
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/frmMain.cs | C# | asf20 | 17,998 |
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("QuanLyNhaSach")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("QuanLyNhaSach")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("0496b42c-3601-488e-8a35-47e29145b3ff")]
// 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")]
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/Properties/AssemblyInfo.cs | C# | asf20 | 1,438 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BUS;
using DTO;
namespace QuanLyNhaSach.Employee
{
public partial class FrmUserGroupList : DevComponents.DotNetBar.Office2007Form
{
BindingList<UsersGroupDTO> listUserBinding;
int rowIndex; //Biến lưu giá trị của dòng đang sửa hơặc vừa thêm mới
UsersGroupBUS usersGroupBUS;
RuleObjectBUS RuleBUS;
public FrmUserGroupList()
{
InitializeComponent();
dtgUsersGroupList.AutoGenerateColumns = false;
usersGroupBUS = new UsersGroupBUS();
listUserBinding = new BindingList<UsersGroupDTO>();
rowIndex = 0;
RuleBUS = new RuleObjectBUS();
}
private void FrmUserGroupList_Load(object sender, EventArgs e)
{
listUserBinding = usersGroupBUS.GetNewBindingListUsersGroup();
dtgUsersGroupList.DataSource = listUserBinding;
this.VisibleChanged += new EventHandler(UsersGroupList_VisibleChanged);
CheckPermission();
}
private void CheckPermission()
{
btnDel.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionAuthor);
btnUpdate.Enabled = btnDel.Enabled;
}
void UsersGroupList_VisibleChanged(object sender, EventArgs e)
{
if (this.Visible)
{
Global.GenerateNumber(dtgUsersGroupList, colNumber.Index);
Global.GenerateEditColumn(dtgUsersGroupList, colEdit.Index);
Global.GenerateDeleteColumn(dtgUsersGroupList, colDel.Index);
}
}
#region Public Methods
public void UsersGroupChanged(UsersGroupDTO userDTO)
{
UsersGroupDTO usersGroupDTO = usersGroupBUS.GetUsersGroupByID(userDTO.UsersGroupID);
dtgUsersGroupList[colUsersGroupName.Index, rowIndex].Value = usersGroupDTO.UsersGroupName;
dtgUsersGroupList[colUsersGroupCode.Index, rowIndex].Value = usersGroupDTO.UsersGroupCode;
}
public void UsersGroupChangeAfterInsert(UsersGroupDTO userDTO)
{
UsersGroupDTO usersGroupDTO = usersGroupBUS.GetUsersGroupByID(userDTO.UsersGroupID);
listUserBinding.Add(usersGroupDTO);
rowIndex = dtgUsersGroupList.Rows.GetLastRow(DataGridViewElementStates.None);
dtgUsersGroupList[colEdit.Index, rowIndex].Value = Properties.Resources.edit_16;
dtgUsersGroupList[colDel.Index, rowIndex].Value = Properties.Resources.deletered;
//Global.GenerateNumber(dtgCategoryList, colNumber.Index);
if (rowIndex == 0)
{
dtgUsersGroupList[colNumber.Index, rowIndex].Value = rowIndex + 1;
}
else
{
dtgUsersGroupList[colNumber.Index, rowIndex].Value = dtgUsersGroupList[colNumber.Index, rowIndex - 1].Value.ToString();
}
}
#endregion Public Methods
#region Button,Delete, Update
private void btnDel_Click(object sender, EventArgs e)
{
DeleteUsersGroup();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
UpdateUsersGroup(dtgUsersGroupList.CurrentRow.Index);
}
private void dtgUsersGroupList_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
if (e.ColumnIndex == colEdit.Index)
{
UpdateUsersGroup(e.RowIndex);
}
else if (e.ColumnIndex == colDel.Index)
{
DeleteUsersGroup();
}
}
}
private void DeleteUsersGroup()
{
if (dtgUsersGroupList.Rows.Count > 0)
{
if (!RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionUserGroup))
{
Global.SetMessage(lblMessage, "Bạn không có quyền thực hiện thao tác này!", false);
return;
}
if (Global.ShowMessageBoxDelete("Bạn chắc chắn muốn xóa thể loại này ?") == DialogResult.Yes)
{
int userID = int.Parse(dtgUsersGroupList[colUsersGroupID.Index, dtgUsersGroupList.CurrentRow.Index].Value.ToString());
if (usersGroupBUS.DeleteUsersGroup(userID))
{
Global.SetMessage(lblMessage, "Xóa thành công", true);
listUserBinding.Remove(listUserBinding.First(c => c.UsersGroupID == userID));
}
else
{
Global.SetMessage(lblMessage, "Xóa không thành công", false);
}
}
}
}
private void UpdateUsersGroup(int index)
{
if (!RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionUserGroup))
{
Global.SetMessage(lblMessage, "Bạn không có quyền thực hiện thao tác này!", false);
return;
}
rowIndex = index;
UsersGroupDTO usersGroupDTO = new UsersGroupDTO
{
UsersGroupID = int.Parse(dtgUsersGroupList[colUsersGroupID.Index, rowIndex].Value.ToString()),
UsersGroupCode = dtgUsersGroupList[colUsersGroupCode.Index, rowIndex].Value.ToString(),
UsersGroupName = dtgUsersGroupList[colUsersGroupName.Index, rowIndex].Value.ToString()
};
Employee.FrmUsersGroupDetail frm = new FrmUsersGroupDetail { UsersGroup = usersGroupDTO, Action = ActionName.Update };
//frm.OnCategoryChanged += new Book.FrmCategoryDetail.CategoryHasChanged(CategoryChanged);
frm.ShowDialog();
}
#endregion Button, Delete, Update
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/Employee/FrmUserGroupList.cs | C# | asf20 | 6,358 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BUS;
using DTO;
namespace QuanLyNhaSach.Employee
{
public partial class FrmUsersGroupDetail : DevComponents.DotNetBar.Office2007Form
{
UsersGroupBUS usersGroupBus;
public ActionName Action { get; set; }
public UsersGroupDTO UsersGroup { get; set; }
public FrmUsersGroupDetail()
{
InitializeComponent();
usersGroupBus = new UsersGroupBUS();
btnUpdate.Location = btnAdd.Location;
}
private void FrmUsersGroupDetail_Load(object sender, EventArgs e)
{
if (Action == ActionName.Insert)
{
txtUsersGroupCode.Focus();
UsersGroup = new UsersGroupDTO();
}
else
{
txtUsersGroupCode.Text = UsersGroup.UsersGroupCode;
txtUsersGroupName.Text = UsersGroup.UsersGroupName;
}
ProcessButton();
}
private void btnAdd_Click(object sender, EventArgs e)
{
UsersGroup.UsersGroupCode = txtUsersGroupCode.Text;
UsersGroup.UsersGroupName = txtUsersGroupName.Text;
UsersGroup.Status = true;
if (!CheckDataInput())
{
return;
}
UsersGroup.UsersGroupID = usersGroupBus.InsertUsersGroup(UsersGroup);
if (UsersGroup.UsersGroupID > 0)
{
Global.SetMessage(lblMessage, "Thêm thành công!", true);
Action = ActionName.Update;
ProcessButton();
Employee.FrmUserGroupList frmList = (Employee.FrmUserGroupList)Application.OpenForms["FrmUserGroupList"];
if (frmList != null)
{
frmList.UsersGroupChangeAfterInsert(UsersGroup);
}
RuleObjectBUS RuleBUS = new RuleObjectBUS();
RuleBUS.InsertRuleOfGroup(UsersGroup.UsersGroupID);
}
else
{
Global.SetMessage(lblMessage, "Thêm không thành công!", false);
}
}
private bool CheckDataInput()
{
if (string.IsNullOrEmpty(txtUsersGroupCode.Text))
{
Global.SetMessage(lblMessage, "Mã nhóm không được trống!", false);
txtUsersGroupCode.Focus();
return false;
}
else
if(string.IsNullOrEmpty(txtUsersGroupName.Text))
{
Global.SetMessage(lblMessage, "Tên nhóm không được trống!", false);
txtUsersGroupName.Focus();
return false;
}
else
if (txtUsersGroupCode.Text.Length < 2)
{
Global.SetMessage(lblMessage, "Mã nhóm phải từ 2 đến 4 kí tự!", false);
txtUsersGroupCode.Focus();
return false;
}
return true;
}
public void ResetForm()
{
txtUsersGroupName.Text = string.Empty;
txtUsersGroupCode.Text = string.Empty;
txtUsersGroupCode.Focus();
}
#region Button
private void btnAddNew_Click(object sender, EventArgs e)
{
ResetForm();
Action = ActionName.Insert;
ProcessButton();
UsersGroup = new UsersGroupDTO();
}
private void ProcessButton()
{
if (Action == ActionName.Insert)
{
btnUpdate.Visible = false;
btnAdd.Visible = true;
}
else if (Action == ActionName.Update)
{
btnUpdate.Visible = true;
btnAdd.Visible = false;
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (!CheckDataInput())
{
return;
}
UsersGroup.UsersGroupName = txtUsersGroupName.Text;
UsersGroup.UsersGroupCode = txtUsersGroupCode.Text;
if (usersGroupBus.UpdateUsersGroup(UsersGroup))
{
Global.SetMessage(lblMessage, "Cập nhật thành công!", true);
//OnCategoryChanged(Category);
Employee.FrmUserGroupList frmList = (Employee.FrmUserGroupList)Application.OpenForms["FrmUsersGroupList"];
if (frmList != null)
{
frmList.UsersGroupChanged(UsersGroup);
}
}
else
{
Global.SetMessage(lblMessage, "Cập nhật không thành công!", false);
}
}
#endregion Button
private void UsersGroupDetail_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
switch (Action)
{
case ActionName.Insert:
btnAdd_Click(sender, e);
break;
case ActionName.Update:
btnUpdate_Click(sender, e);
break;
}
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/Employee/FrmUsersGroupDetail.cs | C# | asf20 | 5,719 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;
namespace QuanLyNhaSach.Employee
{
public partial class EmployeeList : Form
{
BindingList<EmployeeDTO> listEmpBinding;
int rowIndex; //Biến lưu giá trị của dòng đang sửa hơặc vừa thêm mới
EmployeeBUS employeeBUS;
RuleObjectBUS RuleBUS;
public EmployeeList()
{
InitializeComponent();
dtgEmployeeList.AutoGenerateColumns = false;
employeeBUS = new EmployeeBUS();
listEmpBinding = new BindingList<EmployeeDTO>();
rowIndex = 0;
RuleBUS = new RuleObjectBUS();
}
private void EmployeeList_Load(object sender, EventArgs e)
{
// DocSequenceBUS docSeqBUS = new DocSequenceBUS();
listEmpBinding = employeeBUS.GetNewBindingListEmployee();
dtgEmployeeList.DataSource = listEmpBinding;
this.VisibleChanged += new EventHandler(EmployeeList_VisibleChanged);
CheckPermission();
}
private void CheckPermission()
{
btnDel.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionAuthor);
btnUpdate.Enabled = btnDel.Enabled;
}
void EmployeeList_VisibleChanged(object sender, EventArgs e)
{
if (this.Visible)
{
Global.GenerateNumber(dtgEmployeeList, colNumber.Index);
Global.GenerateEditColumn(dtgEmployeeList, ColEdit.Index);
Global.GenerateDeleteColumn(dtgEmployeeList, ColDel.Index);
}
}
#region Public Methods
public void EmployeeChanged(EmployeeDTO empDTO)
{
EmployeeDTO employeeDTO = employeeBUS.GetEmployeeByID(empDTO.EmployeeID);
dtgEmployeeList[colEmployeeName.Index, rowIndex].Value = employeeDTO.EmployeeName;
}
public void EmployeeChangeAfterInsert(EmployeeDTO empDTO)
{
EmployeeDTO employeeDTO = employeeBUS.GetEmployeeByID(empDTO.EmployeeID);
listEmpBinding.Add(employeeDTO);
rowIndex = dtgEmployeeList.Rows.GetLastRow(DataGridViewElementStates.None);
dtgEmployeeList[ColEdit.Index, rowIndex].Value = Properties.Resources.edit_16;
dtgEmployeeList[ColDel.Index, rowIndex].Value = Properties.Resources.deletered;
if (rowIndex == 0)
{
dtgEmployeeList[colNumber.Index, rowIndex].Value = rowIndex + 1;
}
else
{
dtgEmployeeList[colNumber.Index, rowIndex].Value = dtgEmployeeList[colNumber.Index, rowIndex - 1].Value.ToString();
}
}
#endregion Public Methods
#region Button,Delete, Update
private void btnDel_Click_1(object sender, EventArgs e)
{
DeleteEmployee();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (dtgEmployeeList.Rows.Count > 0)
{
UpdateEmployee(dtgEmployeeList.CurrentRow.Index);
}
}
private void dtgEmployeeList_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
if (e.ColumnIndex == ColEdit.Index)
{
UpdateEmployee(e.RowIndex);
}
else if (e.ColumnIndex == ColDel.Index)
{
DeleteEmployee();
}
}
}
private void DeleteEmployee()
{
if (dtgEmployeeList.Rows.Count > 0)
{
if (!RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionEmployee))
{
Global.SetMessage(lblMessage, "Bạn không có quyền thực hiện thao tác này!", false);
return;
}
if (Global.ShowMessageBoxDelete("Bạn chắc chắn muốn xóa nhân viên này ?") == DialogResult.Yes)
{
int empID = int.Parse(dtgEmployeeList[colEmployeeID.Index, dtgEmployeeList.CurrentRow.Index].Value.ToString());
if (employeeBUS.DeleteEmployee(empID))
{
Global.SetMessage(lblMessage, "Xóa thành công", true);
listEmpBinding.Remove(listEmpBinding.First(c => c.EmployeeID == empID));
}
else
{
Global.SetMessage(lblMessage, "Xóa không thành công", false);
}
}
}
}
private void UpdateEmployee(int index)
{
if (!RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionEmployee))
{
Global.SetMessage(lblMessage, "Bạn không có quyền thực hiện thao tác này!", false);
return;
}
rowIndex = index;
int id = int.Parse(dtgEmployeeList[colEmployeeID.Index, rowIndex].Value.ToString());
//EmployeeDTO employeeDTO = new EmployeeDTO
//{
// EmployeeID = int.Parse(dtgEmployeeList[colEmployeeID.Index, rowIndex].Value.ToString()),
// EmployeeCode = dtgEmployeeList[colEmployeeCode.Index, rowIndex].Value.ToString(),
// EmployeeName = dtgEmployeeList[colEmployeeName.Index, rowIndex].Value.ToString(),
// EmployeeBirthDay = (DateTime)dtgEmployeeList[colBirthday.Index, rowIndex].Value,
// EmployeeEmail = dtgEmployeeList[colEmail.Index, rowIndex].Value.ToString(),
// EmployeePhone = dtgEmployeeList[colPhone.Index, rowIndex].Value.ToString(),
// EmployeeCMND = dtgEmployeeList[colCMND.Index, rowIndex].Value.ToString(),
// EmployeeSex = (bool)dtgEmployeeList[ColSex.Index, rowIndex].Value,
// EmployeeSexName = dtgEmployeeList[ColSexName.Index, rowIndex].Value.ToString(),
// EmployeeAddress = dtgEmployeeList[colAddress.Index, rowIndex].Value.ToString(),
// EmployeeBeginDay = (DateTime)dtgEmployeeList[ColBeginDay.Index, rowIndex].Value,
// EmployeeKindCode = (int)dtgEmployeeList[ColKindCode.Index, rowIndex].Value,
// EmployeeStatus = (bool)dtgEmployeeList[colStatus.Index, rowIndex].Value,
// EmployeeNote = dtgEmployeeList[colNote.Index, rowIndex].Value.ToString()
//};
Employee.EmployeeDetail frm = new EmployeeDetail { EmployeeID = id, Action = ActionName.Update };
//frm.OnCategoryChanged += new Book.FrmCategoryDetail.CategoryHasChanged(CategoryChanged);
frm.ShowDialog();
}
#endregion Button, Delete, Update
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/Employee/EmployeeList.cs | C# | asf20 | 7,315 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;
namespace QuanLyNhaSach.Employee
{
public partial class FrmAccountDetail : DevComponents.DotNetBar.Office2007Form
{
public AccountDTO Account { get; set; }
public ActionName Action { get; set; }
AccountBUS AccBUS;
public FrmAccountDetail()
{
InitializeComponent();
cmbEmployee.DisplayMember = EmployeeColumn.EmployeeName.ToString();
cmbEmployee.ValueMember = EmployeeColumn.EmployeeID.ToString();
btnUpdate.Location = btnAdd.Location;
AccBUS = new AccountBUS();
}
private void FrmAccountDetail_Load(object sender, EventArgs e)
{
if (Action == ActionName.Insert)
{
txtUserName.Focus();
Account = new AccountDTO();
EmployeeBUS EmpBUS = new EmployeeBUS();
List<EmployeeDTO> listEmployee = EmpBUS.GetEmployeeListNotHasAccount();
cmbEmployee.DataSource = listEmployee;
ProcessButton();
}
else if (Action == ActionName.Update && Account != null)
{
txtUserName.Text = Account.UserName;
txtPassWord.Text = Account.Password;
txtUserName.ReadOnly = true;
List<EmployeeDTO> listEmp = new List<EmployeeDTO>();
listEmp.Add( new EmployeeDTO { EmployeeName = Account.EmployeeName, EmployeeID = Account.EmployeeID });
cmbEmployee.DataSource = listEmp;
cmbEmployee.SelectedIndex = 0;
cmbEmployee.Enabled = false;
}
}
private void ProcessButton()
{
if (Action == ActionName.Insert)
{
btnAdd.Visible = true;
btnAdd.Enabled = true;
btnUpdate.Visible = false;
cmbEmployee.Enabled = true;
txtUserName.Enabled = true;
}
else if (Action == ActionName.Update)
{
btnAdd.Visible = false;
btnUpdate.Visible = true;
cmbEmployee.Enabled = false;
txtUserName.Enabled = false;
}
}
private bool CheckDataInput()
{
if (cmbEmployee.Items.Count <= 0)
{
Global.SetMessage(lblMessage, "Toàn bộ nhân viên đã có tài khoản!", false);
return false;
}
if(string.IsNullOrEmpty(txtUserName.Text))
{
Global.SetMessage(lblMessage,"Tên đăng nhập không được trống!",false);
txtUserName.Focus();
return false;
}
if (string.IsNullOrEmpty(txtPassWord.Text) || string.IsNullOrEmpty(txtRePassword.Text))
{
Global.SetMessage(lblMessage, "Mật khẩu không được để trống!", false);
txtPassWord.Focus();
return false;
}
if (!txtPassWord.Text.Equals(txtRePassword.Text))
{
Global.SetMessage(lblMessage, "Mật khẩu xác nhận không đúng!", false);
return false;
}
return true;
}
private void btnAddNew_Click(object sender, EventArgs e)
{
Account = new AccountDTO();
EmployeeBUS EmpBUS = new EmployeeBUS();
List<EmployeeDTO> listEmployee = EmpBUS.GetEmployeeListNotHasAccount();
//cmbEmployee.DataSource.c
cmbEmployee.ResetText();
cmbEmployee.DataSource = listEmployee;
txtPassWord.Clear();
txtRePassword.Clear();
txtUserName.Clear();
txtUserName.ReadOnly = false;
Action = ActionName.Insert;
ProcessButton();
lblMessage.Text = string.Empty;
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (!CheckDataInput())
{
return;
}
Account.EmployeeID = Global.intParse( cmbEmployee.SelectedValue);
Account.UserName = txtUserName.Text;
Account.Password = txtPassWord.Text;
int result = AccBUS.InsertAccount(Account);
if (result > 0)
{
Global.SetMessage(lblMessage, "Thêm tài khoản thành công!", true);
Action = ActionName.Update;
ProcessButton();
Employee.FrmAccountList frm = (Employee.FrmAccountList)Application.OpenForms["FrmAccountList"];
if (frm != null)
{
Account = AccBUS.GetAccountByID(Account.EmployeeID);
frm.AccountAfterInsert(Account);
}
}
else if (result == -1)
{
Global.SetMessage(lblMessage, "Tên tài khoản đã tồn tại!", false);
return;
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (!CheckDataInput())
{
return;
}
Account.Password = txtPassWord.Text;
if (AccBUS.UpdateAccount(Account))
{
Global.SetMessage(lblMessage, "Thay đổi mật khẩu thành công!", true);
}
else
{
Global.SetMessage(lblMessage, "Có lỗi trong quá trình thực hiện!", false);
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/Employee/FrmAccountDetail.cs | C# | asf20 | 5,980 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;
namespace QuanLyNhaSach.Employee
{
public partial class EmployeeDetail : DevComponents.DotNetBar.Office2007Form
{
EmployeeBUS employeeBus;
public ActionName Action { get; set; }
public EmployeeDTO Employee { get; set; }
public int EmployeeID { get; set; }
DocSequenceBUS docSeqBUS;
public EmployeeDetail()
{
InitializeComponent();
docSeqBUS = new DocSequenceBUS();
employeeBus = new EmployeeBUS();
btnUpdate.Location = btnAdd.Location;
cmbEmployeeGroup.DisplayMember = UserGroup.UsersGroupName.ToString();
cmbEmployeeGroup.ValueMember = UserGroup.UsersGroupID.ToString();
dtpCreateDate.Value = DateTime.Now;
}
private void EmployeeDetail_Load(object sender, EventArgs e)
{
// txtEmployeeCode.Text = docSeqBUS.GetNextDocSequenceNumber(DocSequence.Employee.ToString());
if (Action == ActionName.Insert)
{
DocSequenceBUS docsequenceBus = new DocSequenceBUS();
txtEmployeeCode.Text = docsequenceBus.GetNextDocSequenceNumber(DocSequence.Employee.ToString());
txtEmployeeName.Focus();
Employee = new EmployeeDTO();
chkStatus.Checked = true;
rdbMale.Checked = true;
}
else
{
if (EmployeeID > 0)
{
Employee = employeeBus.GetEmployeeByID(EmployeeID);
dtpCreateDate.Value = Employee.EmployeeBeginDay;
txtEmployeeCode.Text = Employee.EmployeeCode;
txtEmployeeName.Text = Employee.EmployeeName;
dtpBirthday.Value = Employee.EmployeeBirthDay;
txtEmail.Text = Employee.EmployeeEmail;
txtPhone.Text = Employee.EmployeePhone;
txtCMND.Text = Employee.EmployeeCMND;
rdbMale.Checked = Employee.EmployeeSex;
rdbFemale.Checked = !rdbMale.Checked;
txtAddress.Text = Employee.EmployeeAddress;
chkStatus.Checked = Employee.EmployeeStatus;
cmbEmployeeGroup.SelectedValue = Employee.EmployeeKindCode;
}
}
List<UsersGroupDTO> listUserGroupDto = new List<UsersGroupDTO>();
listUserGroupDto = employeeBus.Load_UserGroup();
cmbEmployeeGroup.DataSource = listUserGroupDto;
ProcessButton();
}
private void btnAdd_Click(object sender, EventArgs e)
{
Employee.EmployeeCode = txtEmployeeCode.Text;
Employee.EmployeeName = txtEmployeeName.Text;
Employee.EmployeeBeginDay = dtpCreateDate.Value;
Employee.EmployeeBirthDay = dtpBirthday.Value;
Employee.EmployeeEmail = txtEmail.Text;
Employee.EmployeePhone = txtPhone.Text;
Employee.EmployeeCMND = txtCMND.Text;
if (rdbFemale.Checked)
{
Employee.EmployeeSex = false;
}
else
Employee.EmployeeSex = true;
Employee.EmployeeAddress = txtAddress.Text;
Employee.EmployeeKindCode = int.Parse(cmbEmployeeGroup.SelectedValue.ToString());
Employee.EmployeeStatus = true;
Employee.EmployeeNote = "";
if (!CheckDataInput())
{
return;
}
Employee.EmployeeID = employeeBus.InsertEmployee(Employee);
if (Employee.EmployeeID > 0)
{
Global.SetMessage(lblMessage, "Thêm thành công!", true);
Action = ActionName.Update;
ProcessButton();
Employee.EmployeeList frmList = (Employee.EmployeeList)Application.OpenForms["EmployeeList"];
if (frmList != null)
{
frmList.EmployeeChangeAfterInsert(Employee);
}
//OnCategoryChanged(Category);
}
else
{
Global.SetMessage(lblMessage, "Thêm không thành công!", false);
}
}
private bool CheckDataInput()
{
if (string.IsNullOrEmpty(txtEmployeeCode.Text) || string.IsNullOrEmpty(txtEmployeeName.Text))
{
Global.SetMessage(lblMessage, "Tên nhân viên không được trống!", false);
txtEmployeeName.Focus();
return false;
}
if (string.IsNullOrEmpty(dtpBirthday.Text.ToString()))
{
Global.SetMessage(lblMessage, "Chưa chọn ngày sinh", false);
dtpBirthday.Focus();
return false;
}
if (string.IsNullOrEmpty(txtCMND.Text))
{
Global.SetMessage(lblMessage, "CMND không được để trống!", false);
txtCMND.Focus();
return false;
}
return true;
}
public void ResetForm()
{
DocSequenceBUS docSeqBUS = new DocSequenceBUS();
txtEmployeeName.Text = string.Empty;
txtEmployeeCode.Text = docSeqBUS.GetNextDocSequenceNumber(DocSequence.Employee.ToString());
txtAddress.Text = string.Empty;
txtCMND.Text = string.Empty;
dtpBirthday.Text = string.Empty;
txtEmail.Text = string.Empty;
txtPhone.Text = string.Empty;
txtEmployeeName.Focus();
}
private void btnAddNew_Click(object sender, EventArgs e)
{
ResetForm();
Action = ActionName.Insert;
ProcessButton();
Employee = new EmployeeDTO();
}
private void ProcessButton()
{
if (Action == ActionName.Insert)
{
btnUpdate.Visible = false;
btnAdd.Visible = true;
dtpCreateDate.Enabled = true;
}
else if (Action == ActionName.Update)
{
btnUpdate.Visible = true;
btnAdd.Visible = false;
dtpCreateDate.Enabled = false;
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if(!CheckDataInput())
{
return;
}
Employee.EmployeeName = txtEmployeeName.Text;
Employee.EmployeeAddress = txtAddress.Text;
Employee.EmployeeBirthDay = dtpBirthday.Value;
Employee.EmployeeCMND = txtCMND.Text;
Employee.EmployeeEmail = txtEmail.Text;
Employee.EmployeeKindCode = Global.intParse( cmbEmployeeGroup.SelectedValue);
Employee.EmployeePhone = txtPhone.Text;
Employee.EmployeeSex = rdbMale.Checked;
Employee.EmployeeStatus = chkStatus.Checked;
if (employeeBus.UpdateEmployee(Employee))
{
Global.SetMessage(lblMessage, "Cập nhật thành công!", true);
//OnCategoryChanged(Category);
Employee.EmployeeList frmList = (Employee.EmployeeList)Application.OpenForms["EmployeeList"];
if (frmList != null)
{
frmList.EmployeeChanged(Employee);
}
}
else
{
Global.SetMessage(lblMessage, "Cập nhật không thành công!", false);
}
}
private void EmployeeDetail_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
switch (Action)
{
case ActionName.Insert:
btnAdd_Click(sender, e);
break;
case ActionName.Update:
btnUpdate_Click(sender, e);
break;
}
}
}
private void txtPhone_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsNumber(e.KeyChar) && !char.IsControl(e.KeyChar))
{
e.Handled = true;
}
}
private void txtCMND_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsNumber(e.KeyChar) && !char.IsControl(e.KeyChar))
{
e.Handled = true;
}
}
private void btnExit_Click(object sender, EventArgs e)
{
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/Employee/EmployeeDetail.cs | C# | asf20 | 9,180 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;
namespace QuanLyNhaSach.Employee
{
public partial class FrmAccountList : DevComponents.DotNetBar.Office2007Form
{
BindingList<AccountDTO> _ListAcc;
AccountBUS AccBUS;
RuleObjectBUS RuleBUS;
int rowIndex; //Biến lưu giá trị của dòng đang sửa hoặc vừa thêm mới
public FrmAccountList()
{
InitializeComponent();
_ListAcc = new BindingList<AccountDTO>();
AccBUS = new AccountBUS();
dtgAccountList.AutoGenerateColumns = false;
RuleBUS = new RuleObjectBUS();
}
private void FrmAccountList_Load(object sender, EventArgs e)
{
this.VisibleChanged += new EventHandler(FrmAccountList_VisibleChanged);
CheckPermission();
}
private void CheckPermission()
{
btnDel.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionAuthor);
btnUpdate.Enabled = btnDel.Enabled;
}
void FrmAccountList_VisibleChanged(object sender, EventArgs e)
{
_ListAcc = AccBUS.GetNewBindingList();
dtgAccountList.DataSource = _ListAcc;
Global.GenerateNumber(dtgAccountList, colNumber.Index);
Global.GenerateEditColumn(dtgAccountList, colEdit.Index);
Global.GenerateDeleteColumn(dtgAccountList, colDel.Index);
}
public void AccountAfterInsert(AccountDTO Acc)
{
_ListAcc.Add(Acc);
rowIndex = dtgAccountList.Rows.GetLastRow(DataGridViewElementStates.None);
dtgAccountList[colEdit.Index, rowIndex].Value = Properties.Resources.edit_16;
dtgAccountList[colDel.Index, rowIndex].Value = Properties.Resources.deletered;
if (rowIndex == 0)
{
dtgAccountList[colNumber.Index, rowIndex].Value = rowIndex + 1;
}
else
{
dtgAccountList[colNumber.Index, rowIndex].Value = Global.intParse( dtgAccountList[colNumber.Index, rowIndex - 1].Value) + 1;
}
}
private void dtgAccountList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
if (e.ColumnIndex == colEdit.Index)
{
btnUpdate_Click(sender, e);
}
else if (e.ColumnIndex == colDel.Index)
{
btnDel_Click(sender, e);
}
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (!RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionAccount))
{
Global.SetMessage(lblMessage, "Bạn không có quyền thực hiện thao tác này!", false);
return;
}
if (dtgAccountList.CurrentRow.Index >= 0)
{
AccountDTO Acc = new AccountDTO();
Acc.EmployeeID = Global.intParse(dtgAccountList.CurrentRow.Cells[colEmployeeID.Index].Value);
Acc = AccBUS.GetAccountByID(Acc.EmployeeID);
Employee.FrmAccountDetail frm = new FrmAccountDetail { Action = ActionName.Update, Account = Acc };
frm.ShowDialog();
}
}
private void btnDel_Click(object sender, EventArgs e)
{
if (dtgAccountList.CurrentRow.Index >= 0)
{
if (!RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject. ActionAccount))
{
Global.SetMessage(lblMessage, "Bạn không có quyền thực hiện thao tác này!", false);
return;
}
if (DevComponents.DotNetBar.MessageBoxEx.Show("Bạn muốn xóa tài khoản này ?", "Hỏi",MessageBoxButtons.YesNo) == DialogResult.Yes)
{
int id = Global.intParse(dtgAccountList.CurrentRow.Cells[colEmployeeID.Index].Value);
if (AccBUS.DeleteAccount(id))
{
Global.SetMessage(lblMessage, "Xóa tài khoản thành công!", true);
_ListAcc.Remove(_ListAcc.FirstOrDefault(l => l.EmployeeID == id));
Global.GenerateNumber(dtgAccountList, colNumber.Index);
}
else
{
Global.SetMessage(lblMessage, "Có lỗi trong quá trình làm việc!", false);
}
}
}
}
}
}
| 11hcbookstoremanagement | trunk/QuanLyNhaSach/QuanLyNhaSach/Employee/FrmAccountList.cs | C# | asf20 | 5,001 |
/*
* Copyright 2011 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 org.dodgybits.shuffle.client;
import com.google.web.bindery.requestfactory.shared.InstanceRequest;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.web.bindery.requestfactory.shared.RequestContext;
import com.google.web.bindery.requestfactory.shared.RequestFactory;
import com.google.web.bindery.requestfactory.shared.ServiceName;
import org.dodgybits.shuffle.shared.MessageProxy;
import org.dodgybits.shuffle.shared.RegistrationInfoProxy;
import org.dodgybits.shuffle.shared.TaskService;
public interface ShuffleRequestFactory extends RequestFactory {
@ServiceName("org.dodgybits.shuffle.server.HelloWorldService")
public interface HelloWorldRequest extends RequestContext {
/**
* Retrieve a "Hello, World" message from the server.
*/
Request<String> getMessage();
}
@ServiceName("org.dodgybits.shuffle.server.RegistrationInfo")
public interface RegistrationInfoRequest extends RequestContext {
/**
* Register a device for C2DM messages.
*/
InstanceRequest<RegistrationInfoProxy, Void> register();
/**
* Unregister a device for C2DM messages.
*/
InstanceRequest<RegistrationInfoProxy, Void> unregister();
}
@ServiceName("org.dodgybits.shuffle.server.Message")
public interface MessageRequest extends RequestContext {
/**
* Send a message to a device using C2DM.
*/
InstanceRequest<MessageProxy, String> send();
}
HelloWorldRequest helloWorldRequest();
RegistrationInfoRequest registrationInfoRequest();
MessageRequest messageRequest();
TaskService taskService();
}
| 1012607376-daihanlong | shuffle-shared/src/main/java/org/dodgybits/shuffle/client/ShuffleRequestFactory.java | Java | asf20 | 2,209 |
package org.dodgybits.shuffle.shared;
import java.util.List;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.web.bindery.requestfactory.shared.RequestContext;
import com.google.web.bindery.requestfactory.shared.ServiceName;
@ServiceName(value = "org.dodgybits.shuffle.server.service.TaskDao", locator="org.dodgybits.shuffle.server.locator.DaoServiceLocator")
public interface TaskService extends RequestContext {
Request<List<TaskProxy>> listAll();
Request<Void> save(TaskProxy newTask);
Request<TaskProxy> saveAndReturn(TaskProxy newTask);
Request<Void> deleteTask(TaskProxy task);
Request<TaskProxy> findById(Long id);
}
| 1012607376-daihanlong | shuffle-shared/src/main/java/org/dodgybits/shuffle/shared/TaskService.java | Java | asf20 | 682 |
/*
* Copyright 2011 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 org.dodgybits.shuffle.shared;
import com.google.web.bindery.requestfactory.shared.ProxyForName;
import com.google.web.bindery.requestfactory.shared.ValueProxy;
/**
* A proxy object containing a message destined for a particular
* recipient, identified by email address.
*/
@ProxyForName(value = "org.dodgybits.shuffle.server.Message",
locator = "org.dodgybits.shuffle.server.MessageLocator")
public interface MessageProxy extends ValueProxy {
String getMessage();
String getRecipient();
void setRecipient(String recipient);
void setMessage(String message);
}
| 1012607376-daihanlong | shuffle-shared/src/main/java/org/dodgybits/shuffle/shared/MessageProxy.java | Java | asf20 | 1,178 |
package org.dodgybits.shuffle.shared;
import java.util.Date;
import com.google.web.bindery.requestfactory.shared.EntityProxy;
import com.google.web.bindery.requestfactory.shared.ProxyForName;
@ProxyForName(value = "org.dodgybits.shuffle.server.model.Task", locator="org.dodgybits.shuffle.server.locator.ObjectifyLocator" )
public interface TaskProxy extends EntityProxy {
Long getId();
String getDescription();
void setDescription(String description);
String getDetails();
void setDetails(String details);
Date getCreatedDate();
void setCreatedDate(Date createdDate);
Date getModifiedDate();
void setModifiedDate(Date modifiedDate);
boolean isActive();
void setActive(boolean active);
boolean isDeleted();
void setDeleted(boolean deleted);
int getOrder();
void setOrder(int order);
boolean isComplete();
void setComplete(boolean complete);
}
| 1012607376-daihanlong | shuffle-shared/src/main/java/org/dodgybits/shuffle/shared/TaskProxy.java | Java | asf20 | 920 |
/*
* Copyright 2011 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 org.dodgybits.shuffle.shared;
import com.google.web.bindery.requestfactory.shared.ProxyForName;
import com.google.web.bindery.requestfactory.shared.ValueProxy;
/**
* A proxy object containing device registration information:
* email account name, device id, and device registration id.
*/
@ProxyForName("org.dodgybits.shuffle.server.RegistrationInfo")
public interface RegistrationInfoProxy extends ValueProxy {
String getDeviceId();
String getDeviceRegistrationId();
void setDeviceId(String deviceId);
void setDeviceRegistrationId(String deviceRegistrationId);
}
| 1012607376-daihanlong | shuffle-shared/src/main/java/org/dodgybits/shuffle/shared/RegistrationInfoProxy.java | Java | asf20 | 1,179 |
package org.dodgybits.shuffle.shared;
import com.google.web.bindery.requestfactory.shared.EntityProxy;
import com.google.web.bindery.requestfactory.shared.ProxyForName;
@ProxyForName(value = "org.dodgybits.shuffle.server.model.AppUser", locator="org.dodgybits.shuffle.server.locator.ObjectifyLocator" )
public interface AppUserProxy extends EntityProxy
{
String getEmail();
} | 1012607376-daihanlong | shuffle-shared/src/main/java/org/dodgybits/shuffle/shared/AppUserProxy.java | Java | asf20 | 379 |
{\rtf1\adeflang1025\ansi\ansicpg1252\uc1\adeff31507\deff0\stshfdbch31505\stshfloch31506\stshfhich31506\stshfbi31507\deflang1053\deflangfe1053\themelang1053\themelangfe0\themelangcs0{\fonttbl{\f0\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f0\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}
{\f37\fbidi \fswiss\fcharset0\fprq2{\*\panose 020f0502020204030204}Calibri;}{\f39\fbidi \fnil\fcharset0\fprq0{\*\panose 00000000000000000000}HelveticaNeue;}{\flomajor\f31500\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}
{\fdbmajor\f31501\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\fhimajor\f31502\fbidi \froman\fcharset0\fprq2{\*\panose 02040503050406030204}Cambria;}
{\fbimajor\f31503\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\flominor\f31504\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}
{\fdbminor\f31505\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\fhiminor\f31506\fbidi \fswiss\fcharset0\fprq2{\*\panose 020f0502020204030204}Calibri;}
{\fbiminor\f31507\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f293\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\f294\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}
{\f296\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\f297\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\f298\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\f299\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}
{\f300\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\f301\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\f293\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\f294\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}
{\f296\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\f297\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\f298\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\f299\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}
{\f300\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\f301\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\f663\fbidi \fswiss\fcharset238\fprq2 Calibri CE;}{\f664\fbidi \fswiss\fcharset204\fprq2 Calibri Cyr;}
{\f666\fbidi \fswiss\fcharset161\fprq2 Calibri Greek;}{\f667\fbidi \fswiss\fcharset162\fprq2 Calibri Tur;}{\f670\fbidi \fswiss\fcharset186\fprq2 Calibri Baltic;}{\f671\fbidi \fswiss\fcharset163\fprq2 Calibri (Vietnamese);}
{\flomajor\f31508\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\flomajor\f31509\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\flomajor\f31511\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}
{\flomajor\f31512\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\flomajor\f31513\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\flomajor\f31514\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}
{\flomajor\f31515\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\flomajor\f31516\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\fdbmajor\f31518\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}
{\fdbmajor\f31519\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\fdbmajor\f31521\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\fdbmajor\f31522\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}
{\fdbmajor\f31523\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\fdbmajor\f31524\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\fdbmajor\f31525\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}
{\fdbmajor\f31526\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\fhimajor\f31528\fbidi \froman\fcharset238\fprq2 Cambria CE;}{\fhimajor\f31529\fbidi \froman\fcharset204\fprq2 Cambria Cyr;}
{\fhimajor\f31531\fbidi \froman\fcharset161\fprq2 Cambria Greek;}{\fhimajor\f31532\fbidi \froman\fcharset162\fprq2 Cambria Tur;}{\fhimajor\f31535\fbidi \froman\fcharset186\fprq2 Cambria Baltic;}
{\fhimajor\f31536\fbidi \froman\fcharset163\fprq2 Cambria (Vietnamese);}{\fbimajor\f31538\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\fbimajor\f31539\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}
{\fbimajor\f31541\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\fbimajor\f31542\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\fbimajor\f31543\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}
{\fbimajor\f31544\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\fbimajor\f31545\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\fbimajor\f31546\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}
{\flominor\f31548\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\flominor\f31549\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\flominor\f31551\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}
{\flominor\f31552\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\flominor\f31553\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\flominor\f31554\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}
{\flominor\f31555\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\flominor\f31556\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\fdbminor\f31558\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}
{\fdbminor\f31559\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\fdbminor\f31561\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\fdbminor\f31562\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}
{\fdbminor\f31563\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\fdbminor\f31564\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\fdbminor\f31565\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}
{\fdbminor\f31566\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\fhiminor\f31568\fbidi \fswiss\fcharset238\fprq2 Calibri CE;}{\fhiminor\f31569\fbidi \fswiss\fcharset204\fprq2 Calibri Cyr;}
{\fhiminor\f31571\fbidi \fswiss\fcharset161\fprq2 Calibri Greek;}{\fhiminor\f31572\fbidi \fswiss\fcharset162\fprq2 Calibri Tur;}{\fhiminor\f31575\fbidi \fswiss\fcharset186\fprq2 Calibri Baltic;}
{\fhiminor\f31576\fbidi \fswiss\fcharset163\fprq2 Calibri (Vietnamese);}{\fbiminor\f31578\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\fbiminor\f31579\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}
{\fbiminor\f31581\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\fbiminor\f31582\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\fbiminor\f31583\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}
{\fbiminor\f31584\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\fbiminor\f31585\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\fbiminor\f31586\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}}
{\colortbl;\red0\green0\blue0;\red0\green0\blue255;\red0\green255\blue255;\red0\green255\blue0;\red255\green0\blue255;\red255\green0\blue0;\red255\green255\blue0;\red255\green255\blue255;\red0\green0\blue128;\red0\green128\blue128;\red0\green128\blue0;
\red128\green0\blue128;\red128\green0\blue0;\red128\green128\blue0;\red128\green128\blue128;\red192\green192\blue192;}{\*\defchp \fs22\loch\af31506\hich\af31506\dbch\af31505 }{\*\defpap \ql \li0\ri0\sa200\sl276\slmult1
\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 }\noqfpromote {\stylesheet{\ql \li0\ri0\sa200\sl276\slmult1\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af31507\afs22\alang1025
\ltrch\fcs0 \fs22\lang1053\langfe1053\loch\f31506\hich\af31506\dbch\af31505\cgrid\langnp1053\langfenp1053 \snext0 \sqformat \spriority0 Normal;}{\*\cs10 \additive \ssemihidden \sunhideused \spriority1 Default Paragraph Font;}{\*
\ts11\tsrowd\trftsWidthB3\trpaddl108\trpaddr108\trpaddfl3\trpaddft3\trpaddfb3\trpaddfr3\trcbpat1\trcfpat1\tblind0\tblindtype3\tsvertalt\tsbrdrt\tsbrdrl\tsbrdrb\tsbrdrr\tsbrdrdgl\tsbrdrdgr\tsbrdrh\tsbrdrv \ql \li0\ri0\sa200\sl276\slmult1
\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af31507\afs22\alang1025 \ltrch\fcs0 \fs22\lang1053\langfe1053\loch\f31506\hich\af31506\dbch\af31505\cgrid\langnp1053\langfenp1053 \snext11 \ssemihidden \sunhideused
Normal Table;}{\*\cs15 \additive \ul\cf2 \ssemihidden \sunhideused \styrsid8458154 Hyperlink;}}{\*\listtable{\list\listtemplateid685803640\listhybrid{\listlevel\levelnfc255\levelnfcn255\leveljc0\leveljcn0\levelfollow0\levelstartat0\levelspace0
\levelindent0{\leveltext\leveltemplateid-900038952\'00;}{\levelnumbers;}\rtlch\fcs1 \af0 \ltrch\fcs0 \jclisttab\tx360 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat0\levelspace0\levelindent0{\leveltext
\leveltemplateid-1033628342\'00;}{\levelnumbers;}\rtlch\fcs1 \af0 \ltrch\fcs0 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat0\levelspace0\levelindent0{\leveltext\leveltemplateid826860412\'00;}{\levelnumbers;}\rtlch\fcs1
\af0 \ltrch\fcs0 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat0\levelspace0\levelindent0{\leveltext\leveltemplateid-1236385464\'00;}{\levelnumbers;}\rtlch\fcs1 \af0 \ltrch\fcs0 }{\listlevel\levelnfc0\levelnfcn0\leveljc0
\leveljcn0\levelfollow0\levelstartat0\levelspace0\levelindent0{\leveltext\leveltemplateid-342989116\'00;}{\levelnumbers;}\rtlch\fcs1 \af0 \ltrch\fcs0 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat0\levelspace0\levelindent0
{\leveltext\leveltemplateid-2200190\'00;}{\levelnumbers;}\rtlch\fcs1 \af0 \ltrch\fcs0 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat0\levelspace0\levelindent0{\leveltext\leveltemplateid1859789434\'00;}{\levelnumbers;}
\rtlch\fcs1 \af0 \ltrch\fcs0 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat0\levelspace0\levelindent0{\leveltext\leveltemplateid486059564\'00;}{\levelnumbers;}\rtlch\fcs1 \af0 \ltrch\fcs0 }{\listlevel\levelnfc0\levelnfcn0
\leveljc0\leveljcn0\levelfollow0\levelstartat0\levelspace0\levelindent0{\leveltext\leveltemplateid989604422\'00;}{\levelnumbers;}\rtlch\fcs1 \af0 \ltrch\fcs0 }{\listname ;}\listid1}}{\*\listoverridetable{\listoverride\listid1\listoverridecount0\ls1}}
{\*\rsidtbl \rsid8458154\rsid8602282\rsid9322363}{\mmathPr\mmathFont34\mbrkBin0\mbrkBinSub0\msmallFrac0\mdispDef1\mlMargin0\mrMargin0\mdefJc1\mwrapIndent1440\mintLim0\mnaryLim1}{\info{\operator Morten Nielsen}{\creatim\yr2010\mo8\dy8\hr16\min25}
{\revtim\yr2010\mo8\dy8\hr16\min36}{\version2}{\edmins11}{\nofpages4}{\nofwords1071}{\nofchars5682}{\nofcharsws6740}{\vern49247}}{\*\xmlnstbl {\xmlns1 http://schemas.microsoft.com/office/word/2003/wordml}}
\paperw11900\paperh16840\margl1440\margr1440\margt1417\margb1417\gutter0\ltrsect
\widowctrl\ftnbj\aenddoc\hyphhotz425\trackmoves0\trackformatting1\donotembedsysfont0\relyonvml0\donotembedlingdata1\grfdocevents0\validatexml0\showplaceholdtext0\ignoremixedcontent0\saveinvalidxml0\showxmlerrors0\horzdoc\dghspace120\dgvspace120
\dghorigin1701\dgvorigin1984\dghshow0\dgvshow3\jcompress\viewkind1\viewscale100\rsidroot9322363 \fet0{\*\wgrffmtfilter 2450}\ilfomacatclnup0\ltrpar \sectd \ltrsect\linex0\sectdefaultcl\sftnbj {\*\pnseclvl1\pnucrm\pnstart1\pnindent720\pnhang {\pntxta .}}
{\*\pnseclvl2\pnucltr\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl3\pndec\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl4\pnlcltr\pnstart1\pnindent720\pnhang {\pntxta )}}{\*\pnseclvl5\pndec\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}
{\*\pnseclvl6\pnlcltr\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl7\pnlcrm\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl8\pnlcltr\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl9
\pnlcrm\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}\pard\plain \ltrpar\ql \li0\ri0\nowidctlpar\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\wrapdefault\faauto\rin0\lin0\itap0 \rtlch\fcs1
\af31507\afs22\alang1025 \ltrch\fcs0 \fs22\lang1053\langfe1053\loch\af31506\hich\af31506\dbch\af31505\cgrid\langnp1053\langfenp1053 {\rtlch\fcs1 \ab\af39\afs72 \ltrch\fcs0 \b\f39\fs72\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\hich\af39\dbch\af31505\loch\f39 Shuffle for Android}{\rtlch\fcs1 \ab\af39\afs24 \ltrch\fcs0 \b\f39\fs24\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 1.1}{\rtlch\fcs1 \ab\af39\afs72 \ltrch\fcs0
\b\f39\fs72\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\par }{\rtlch\fcs1 \ab\af39\afs24 \ltrch\fcs0 \b\f39\fs24\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Designed and implemented by Andy Bryant
\par }{\rtlch\fcs1 \ab\af39\afs38 \ltrch\fcs0 \b\f39\fs38\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\par }{\rtlch\fcs1 \ab\af39\afs48 \ltrch\fcs0 \b\f39\fs48\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Quick Start Guide}{\rtlch\fcs1 \af39\afs48 \ltrch\fcs0
\f39\fs48\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\par }{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0 \f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\par }{\rtlch\fcs1 \ab\af39\afs36 \ltrch\fcs0 \b\f39\fs36\cf9\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Introduction}{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0
\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\par }{\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Thanks for trying out Sh\hich\af39\dbch\af31505\loch\f39
uffle, a personal organizational tool, styled around the "Getting Things Done" methodology. Shuffle is a dumping ground for ideas and tasks. It lets you rapidly create and organize your actions, relieving you of the stress of trying to remember everything
\hich\af39\dbch\af31505\loch\f39 \hich\af39\dbch\af31505\loch\f39
you need to get done. Since Shuffle is a mobile application, you will have it with you where ever you are. You can always add an idea you've just had, or quickly check what's on the top of your list of actions.
\par
\par \hich\af39\dbch\af31505\loch\f39 A simple elegant workflow encourages you to \hich\af39\dbch\af31505\loch\f39
categorize your actions into projects and optionally provide a context. This structure lets you to break down formidable projects into individual achievable actions. As a project evolves over time, you can clean out old actions as they're performed, add
\hich\af39\dbch\af31505\loch\f39 n\hich\af39\dbch\af31505\loch\f39 ew actions and reorder any remaining actions depending on your current priorities.
\par
\par \hich\af39\dbch\af31505\loch\f39 Shuffle provides five different perspectives, to support the GTD workflow. All perspective support creating, editing and deleting actions. }{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0
\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\par
\par }{\rtlch\fcs1 \ab\af39\afs36 \ltrch\fcs0 \b\f39\fs36\cf9\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Inbox}{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0
\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\par }\pard \ltrpar\ql \li0\ri0\nowidctlpar\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\wrapdefault\faauto\rin0\lin0\itap0 {\rtlch\fcs1 \af39\afs28 \ltrch\fcs0
\f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 This is the best place t\hich\af39\dbch\af31505\loch\f39 o add your actions. The }{\rtlch\fcs1 \ab\ai\af39\afs28 \ltrch\fcs0
\b\i\f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Inbox}{\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\hich\af39\dbch\af31505\loch\f39
is where all actions start off before they are processed. It's a good idea to keep your Inbox as slim as possible. Doing so, does not mean you have to actually perform the actions. It simply means you've analyzed each action a
\hich\af39\dbch\af31505\loch\f39 nd done one of the following:
\par }\pard \ltrpar\ql \li0\ri0\nowidctlpar\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\wrapdefault\faauto\rin0\lin0\itap0 {\rtlch\fcs1 \af39\afs28 \ltrch\fcs0
\f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 - discard actions that no longer consider important
\par \hich\af39\dbch\af31505\loch\f39 - perform the action if it doesn't require much time
\par \hich\af39\dbch\af31505\loch\f39 - assigned the action to a project (and optionally a context)
\par \hich\af39\dbch\af31505\loch\f39 - re-categorized the action as a project, if it requires ma\hich\af39\dbch\af31505\loch\f39 ny steps to complete
\par }\pard \ltrpar\ql \li0\ri0\nowidctlpar\wrapdefault\faauto\rin0\lin0\itap0 {\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39
Once you've processed the list, select Clean up Inbox from the menu to clear out all the categorized actions from your Inbox.
\par }{\rtlch\fcs1 \ab\af39\afs30 \ltrch\fcs0 \b\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\par }\pard \ltrpar\ql \li0\ri0\nowidctlpar\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\wrapdefault\faauto\rin0\lin0\itap0 {\rtlch\fcs1 \ab\af39\afs36 \ltrch\fcs0
\b\f39\fs36\cf9\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Projects}{\rtlch\fcs1 \ab\af39\afs30 \ltrch\fcs0 \b\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\par }\pard \ltrpar\ql \li0\ri0\nowidctlpar\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\wrapdefault\faauto\rin0\lin0\itap0 {\rtlch\fcs1 \af39\afs28 \ltrch\fcs0
\f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Now that you've organized your actions, you can view them in a structured manner. The }{\rtlch\fcs1 \ab\ai\af39\afs28 \ltrch\fcs0
\b\i\f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Project}{\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\hich\af39\dbch\af31505\loch\f39
perspective lists all your projects, and allows you to drill-down into each project to view its actions. In addition to the standard adding, editing and deleting of actions, the project view also supports rearranging actions in the order you intend to co
\hich\af39\dbch\af31505\loch\f39 m\hich\af39\dbch\af31505\loch\f39 plete them. This step is important for the Next Actions perspective discussed below.
\par }\pard \ltrpar\ql \li0\ri0\nowidctlpar\wrapdefault\faauto\rin0\lin0\itap0 {\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\par \hich\af39\dbch\af31505\loch\f39 Projects, like contexts, can be viewed in two different modes: drill-down or expandable view.
\par \hich\af39\dbch\af31505\loch\f39 In drill down mode, clicking on a project takes you to another screen showi\hich\af39\dbch\af31505\loch\f39
ng the actions for that project. In expandable mode, clicking a project shows its actions on the same screen. Each view provides the same list of features, so choosing which to use (via the Preferences) is a matter of personal preference.
\par }\pard \ltrpar\ql \li0\ri0\nowidctlpar\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\wrapdefault\faauto\rin0\lin0\itap0 {\rtlch\fcs1 \af39\afs28 \ltrch\fcs0
\f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\par \hich\af39\dbch\af31505\loch\f39 In addition to a\hich\af39\dbch\af31505\loch\f39 dding, editing and deleting actions (supported by all perspectives), the project view lets you rearrange your actions in the order you wish to complete them.
\par }{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0 \f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\par }{\rtlch\fcs1 \ab\af39\afs36 \ltrch\fcs0 \b\f39\fs36\cf9\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Contexts}{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0
\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\par }{\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 You may optionally assign a context to each of your actions. }{\rtlch\fcs1 \ab\ai\af39\afs28 \ltrch\fcs0
\b\i\f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Contexts}{\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\hich\af39\dbch\af31505\loch\f39 are situations in \hich\af39\dbch\af31505\loch\f39 which you intend to perform actions. Shuffle comes with a few standard contexts to get you started: }{\rtlch\fcs1 \ai\af39\afs28 \ltrch\fcs0
\i\f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 At home}{\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\hich\af39\dbch\af31505\loch\f39 , }{\rtlch\fcs1 \ai\af39\afs28 \ltrch\fcs0 \i\f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 At work}{\rtlch\fcs1 \af39\afs28 \ltrch\fcs0
\f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 , }{\rtlch\fcs1 \ai\af39\afs28 \ltrch\fcs0 \i\f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39
Online}{\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 , }{\rtlch\fcs1 \ai\af39\afs28 \ltrch\fcs0
\i\f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Errands}{\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\hich\af39\dbch\af31505\loch\f39 , }{\rtlch\fcs1 \ai\af39\afs28 \ltrch\fcs0 \i\f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Contact}{\rtlch\fcs1 \af39\afs28 \ltrch\fcs0
\f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 and }{\rtlch\fcs1 \ai\af39\afs28 \ltrch\fcs0 \i\f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\hich\af39\dbch\af31505\loch\f39 Read}{\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39
. Feel free to modify or delete the existing contexts, or add new ones that suit your situation.
\par
\par \hich\af39\dbch\af31505\loch\f39 The co\hich\af39\dbch\af31505\loch\f39
ntext view is especially useful when you're intending on getting something done, and need to see what actions are applicable to your current situation. For instance, you're out and about in town, so you check your }{\rtlch\fcs1 \ai\af39\afs28 \ltrch\fcs0
\i\f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Errands}{\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\hich\af39\dbch\af31505\loch\f39 context and see you need to buy an umbrella and pick up the dry cleaning on your way home.
\par
\par \hich\af39\dbch\af31505\loch\f39 Like the Projects perspective, contexts can be viewed in either drill-down or expandable mode, configurable via Settings.
\par }{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0 \f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\par }{\rtlch\fcs1 \ab\af39\afs36 \ltrch\fcs0 \b\f39\fs36\cf9\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Next Actions
\par }{\rtlch\fcs1 \ab\ai\af39\afs30 \ltrch\fcs0 \b\i\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Next actions}{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0
\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 is the best p\hich\af39\dbch\af31505\loch\f39
lace to look to determine what needs to be done. It shows the the top action for each of your projects. If you've organized each of your projects actions in the order you intend to complete them, this list quickly shows you the most important actions for
\hich\af39\dbch\af31505\loch\f39 y\hich\af39\dbch\af31505\loch\f39 ou to get started on now.
\par
\par }{\rtlch\fcs1 \ab\af39\afs36 \ltrch\fcs0 \b\f39\fs36\cf9\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Due Actions
\par }{\rtlch\fcs1 \ab\ai\af39\afs30 \ltrch\fcs0 \b\i\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Due actions}{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0
\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 lets you keep track of actions you have assigned an explicit due date. There are 3 views - }{\rtlch\fcs1 \ai\af39\afs30 \ltrch\fcs0
\i\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Today}{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0 \f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39
, }{\rtlch\fcs1 \ai\af39\afs30 \ltrch\fcs0 \i\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 This Week}{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0
\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 and }{\rtlch\fcs1 \ai\af39\afs30 \ltrch\fcs0 \i\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\hich\af39\dbch\af31505\loch\f39 This Month}{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0 \f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39
each showing actions due for the given time scale. Overdue actions are shown in al\hich\af39\dbch\af31505\loch\f39 l views.
\par
\par }{\rtlch\fcs1 \ab\af39\afs36 \ltrch\fcs0 \b\f39\fs36\cf9\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Settings
\par }\pard \ltrpar\ql \li0\ri0\nowidctlpar\wrapdefault\faauto\rin0\lin0\itap0 {\rtlch\fcs1 \af39\afs30 \ltrch\fcs0 \f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39
A number of aspects of Shuffle are user-configurable. The }{\rtlch\fcs1 \ab\ai\af39\afs30 \ltrch\fcs0 \b\i\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Settings}{\rtlch\fcs1 \af39\afs30
\ltrch\fcs0 \f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 screen is available from all Perspectives via the menu.
\par }{\rtlch\fcs1 \ab\af39\afs30 \ltrch\fcs0 \b\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 List layout}{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0
\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 - Show projects and contexts in two screens (drill-down) or in a tree structure (expandable).
\par }{\rtlch\fcs1 \ab\af39\afs30 \ltrch\fcs0 \b\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Action appearance}{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0
\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 - Lets you custom what information to display for actions in each perspective.
\par }{\rtlch\fcs1 \ab\af39\afs30 \ltrch\fcs0 \b\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Clean up}{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0
\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 - Delete completed actions or delete everything.
\par }\pard \ltrpar\ql \li0\ri0\nowidctlpar\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\wrapdefault\faauto\rin0\lin0\itap0 {\rtlch\fcs1 \ab\af39\afs38 \ltrch\fcs0
\b\f39\fs38\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\par }{\rtlch\fcs1 \ab\af39\afs36 \ltrch\fcs0 \b\f39\fs36\cf9\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Tips
\par }\pard \ltrpar\ql \li0\ri0\nowidctlpar\wrapdefault\faauto\rin0\lin0\itap0 {\rtlch\fcs1 \af39\afs30 \ltrch\fcs0 \f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39
Some handy Shuffle features you may not know about:
\par {\listtext\tab}}\pard \ltrpar\ql \fi-720\li720\ri0\nowidctlpar\tx220\jclisttab\tx360\tx720\wrapdefault\faauto\ls1\rin0\lin720\itap0 {\rtlch\fcs1 \af39\afs30 \ltrch\fcs0 \f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\hich\af39\dbch\af31505\loch\f39 In any list view, long press on an item\hich\af39\dbch\af31505\loch\f39 to see a menu of options.
\par {\listtext\tab}\hich\af39\dbch\af31505\loch\f39 Hitting the Back button saves before closing.
\par {\listtext\tab}\hich\af39\dbch\af31505\loch\f39 Use the }{\rtlch\fcs1 \ai\af39\afs30 \ltrch\fcs0 \i\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Save and New}{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0
\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 menu to create a bunch of actions in one go.
\par {\listtext\tab}\hich\af39\dbch\af31505\loch\f39 You can mark an action as complete by swiping your finger over it in a list.
\par }\pard \ltrpar\ql \li0\ri0\nowidctlpar\tx220\tx720\wrapdefault\faauto\rin0\lin0\itap0\pararsid9322363 {\rtlch\fcs1 \af39\afs30 \ltrch\fcs0 \f39\fs30\lang1033\langfe1053\langnp1033\insrsid9322363
\par }{\rtlch\fcs1 \af39\afs36 \ltrch\fcs0 \b\f39\fs36\lang1033\langfe1053\langnp1033\insrsid9322363\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Synchronizing with Tracks
\par }{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0 \f39\fs30\lang1033\langfe1053\langnp1033\insrsid9322363
\par \hich\af39\dbch\af31505\loch\f39 Settings
\par \hich\af39\dbch\af31505\loch\f39 In the \hich\af39\dbch\af31505\loch\f39 settings m\hich\af39\dbch\af31505\loch\f39 enu there is an option \hich\af39\dbch\af31505\loch\f39 called \loch\af39\dbch\af31505\hich\f39 \'93\hich\af39\dbch\af31505\loch\f39 Track
\hich\af39\dbch\af31505\loch\f39 s\hich\af39\dbch\af31505\loch\f39 settings\loch\af39\dbch\af31505\hich\f39 \'94\hich\af39\dbch\af31505\loch\f39 . Pressing the Tracks settings option allows you to enter the settings required to synchroniz
\hich\af39\dbch\af31505\loch\f39 e with Tracks.
\par \hich\af39\dbch\af31505\loch\f39 To synchronize with Tracks you need to enter the URL for the \hich\af39\dbch\af31505\loch\f39 Tracks installation, your username and password.\hich\af39\dbch\af31505\loch\f39
Currently there is no support for synchronizing with Tracks over HTTPs.
\par
\par \hich\af39\dbch\af31505\loch\f39 Once you have entered the settings you can check them with \hich\af39\dbch\af31505\loch\f39 the\hich\af39\dbch\af31505\loch\f39 check settings button.
\par
\par \hich\af39\dbch\af31505\loch\f39 You can set up the synchronization t\hich\af39\dbch\af31505\loch\f39 o run as a background process. This means that Shuffle with synchronize with Tracks at the given interval.
\par \hich\af39\dbch\af31505\loch\f39 Once you have entered settings for synchronizing with Tracks, a Synchronize button appears in the menu at\hich\af39\dbch\af31505\loch\f39 the top-level menu in Shuffle, allowing you to synchronize manually.
\par
\par \hich\af39\dbch\af31505\loch\f39 Trouble-shooting
\par \hich\af39\dbch\af31505\loch\f39 If you}{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0 \f39\fs30\lang1033\langfe1053\langnp1033\insrsid8458154 \hich\af39\dbch\af31505\loch\f39 are}{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0
\f39\fs30\lang1033\langfe1053\langnp1033\insrsid9322363 \hich\af39\dbch\af31505\loch\f39 hosting \hich\af39\dbch\af31505\loch\f39 your own Tracks and you cannot authenticate}{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0
\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8458154 \hich\af39\dbch\af31505\loch\f39 with your settings, but you c\hich\af39\dbch\af31505\loch\f39 an log in \hich\af39\dbch\af31505\loch\f39
to Tracks using them. Then double check if Apache is sending the au\hich\af39\dbch\af31505\loch\f39 thentication headers to Tracks. For more information see }{\field\fldedit{\*\fldinst {\rtlch\fcs1 \af31507 \ltrch\fcs0
\lang1033\langfe1053\langnp1033\insrsid8458154\charrsid8458154 \hich\af31506\dbch\af31505\loch\f31506 \hich\af31506\dbch\af31505\loch\f31506 HYPERLINK "http://www.getontracks.org/wiki/Known-Issues/"\hich\af31506\dbch\af31505\loch\f31506 }}{\fldrslt {
\rtlch\fcs1 \af31507 \ltrch\fcs0 \cs15\ul\cf2\lang1033\langfe1053\langnp1033\insrsid8458154\charrsid8458154 \hich\af31506\dbch\af31505\loch\f31506 http://www.getontracks.org/wiki/Known-Issues/}}}\sectd \ltrsect\linex0\sectdefaultcl\sftnbj {\rtlch\fcs1
\af39\afs30 \ltrch\fcs0 \f39\fs30\lang1033\langfe1053\langnp1033\insrsid8458154
\par }{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0 \f39\fs30\lang1033\langfe1053\langnp1033\insrsid9322363\charrsid9322363
\par }\pard \ltrpar\ql \li0\ri0\nowidctlpar\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\wrapdefault\faauto\rin0\lin0\itap0 {\rtlch\fcs1 \ab\af39\afs38 \ltrch\fcs0
\b\f39\fs38\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\par }{\rtlch\fcs1 \ab\af39\afs36 \ltrch\fcs0 \b\f39\fs36\cf9\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Project source}{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0
\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\par \hich\af39\dbch\af31505\loch\f39 Shuffle will be\hich\af39\dbch\af31505\loch\f39 released as open source under the Apache License 2.0 around 16th April 2008. The project is hosted at http://code.google.com/p/android-shuffle/ }{\rtlch\fcs1 \ab\af39\afs38
\ltrch\fcs0 \b\f39\fs38\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\par
\par }{\rtlch\fcs1 \ab\af39\afs36 \ltrch\fcs0 \b\f39\fs36\cf9\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Acknowledgements}{\rtlch\fcs1 \af39\afs30 \ltrch\fcs0
\f39\fs30\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\par }{\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 Thanks to the team behind the }{\field{\*\fldinst {\rtlch\fcs1 \af39\afs28 \ltrch\fcs0
\f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 HYPERLINK "http://tango.freedesktop.org/Tango_Desktop_Project"}{\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\insrsid9322363 {\*\datafield
00d0c9ea79f9bace118c8200aa004ba90b0200000003000000e0c9ea79f9bace118c8200aa004ba90b7e00000068007400740070003a002f002f00740061006e0067006f002e0066007200650065006400650073006b0074006f0070002e006f00720067002f00540061006e0067006f005f004400650073006b0074006f00
70005f00500072006f006a006500630074000000795881f43b1d7f48af2c825dc485276300000000a5ab0000}}}{\fldrslt {\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39
Tango Desktop Project}}}\sectd \ltrsect\linex0\sectdefaultcl\sftnbj {\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39
, an open source collection of icons used in Shuffle.
\par \hich\af39\dbch\af31505\loch\f39 Thanks also to David Gibb for providing some great feedback on the design and to Gudrun for tolerating my nights and weekends spent tinkering with Android.
\par
\par }\pard \ltrpar\ql \li0\ri0\nowidctlpar\wrapdefault\faauto\rin0\lin0\itap0 {\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39
For feedback or bug reports, please check }{\field{\*\fldinst {\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39
HYPERLINK "http://code.google.com/p/android-shuffle/issues/list"}{\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\insrsid9322363 {\*\datafield
00d0c9ea79f9bace118c8200aa004ba90b0200000003000000e0c9ea79f9bace118c8200aa004ba90b8200000068007400740070003a002f002f0063006f00640065002e0067006f006f0067006c0065002e0063006f006d002f0070002f0061006e00640072006f00690064002d00730068007500660066006c0065002f00
6900730073007500650073002f006c006900730074000000795881f43b1d7f48af2c825dc485276300000000a5ab0000}}}{\fldrslt {\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39
Shuffle issues list}}}\sectd \ltrsect\linex0\sectdefaultcl\sftnbj {\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 or }{\field{\*\fldinst {\rtlch\fcs1
\af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 HYPERLINK "mailto:andy@dodgybits.org"}{\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\insrsid9322363 {\*\datafield
00d0c9ea79f9bace118c8200aa004ba90b0200000003000000e0c9ea79f9bace118c8200aa004ba90b4c0000006d00610069006c0074006f003a0061006e0064007900400064006f0064006700790062006900740073002e006f00720067000000795881f43b1d7f48af2c825dc485276300000000a5ab0000}}}{\fldrslt
{\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 \hich\af39\dbch\af31505\loch\f39 email me}}}\sectd \ltrsect\linex0\sectdefaultcl\sftnbj {\rtlch\fcs1 \af39\afs28 \ltrch\fcs0
\f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363 .}{\rtlch\fcs1 \af39\afs28 \ltrch\fcs0 \f39\fs28\lang1033\langfe1053\langnp1033\insrsid8602282\charrsid9322363
\par }{\*\themedata 504b030414000600080000002100e9de0fbfff0000001c020000130000005b436f6e74656e745f54797065735d2e786d6cac91cb4ec3301045f748fc83e52d4a
9cb2400825e982c78ec7a27cc0c8992416c9d8b2a755fbf74cd25442a820166c2cd933f79e3be372bd1f07b5c3989ca74aaff2422b24eb1b475da5df374fd9ad
5689811a183c61a50f98f4babebc2837878049899a52a57be670674cb23d8e90721f90a4d2fa3802cb35762680fd800ecd7551dc18eb899138e3c943d7e503b6
b01d583deee5f99824e290b4ba3f364eac4a430883b3c092d4eca8f946c916422ecab927f52ea42b89a1cd59c254f919b0e85e6535d135a8de20f20b8c12c3b0
0c895fcf6720192de6bf3b9e89ecdbd6596cbcdd8eb28e7c365ecc4ec1ff1460f53fe813d3cc7f5b7f020000ffff0300504b030414000600080000002100a5d6
a7e7c0000000360100000b0000005f72656c732f2e72656c73848fcf6ac3300c87ef85bd83d17d51d2c31825762fa590432fa37d00e1287f68221bdb1bebdb4f
c7060abb0884a4eff7a93dfeae8bf9e194e720169aaa06c3e2433fcb68e1763dbf7f82c985a4a725085b787086a37bdbb55fbc50d1a33ccd311ba548b6309512
0f88d94fbc52ae4264d1c910d24a45db3462247fa791715fd71f989e19e0364cd3f51652d73760ae8fa8c9ffb3c330cc9e4fc17faf2ce545046e37944c69e462
a1a82fe353bd90a865aad41ed0b5b8f9d6fd010000ffff0300504b0304140006000800000021006b799616830000008a0000001c0000007468656d652f746865
6d652f7468656d654d616e616765722e786d6c0ccc4d0ac3201040e17da17790d93763bb284562b2cbaebbf600439c1a41c7a0d29fdbd7e5e38337cedf14d59b
4b0d592c9c070d8a65cd2e88b7f07c2ca71ba8da481cc52c6ce1c715e6e97818c9b48d13df49c873517d23d59085adb5dd20d6b52bd521ef2cdd5eb9246a3d8b
4757e8d3f729e245eb2b260a0238fd010000ffff0300504b03041400060008000000210030dd4329a8060000a41b0000160000007468656d652f7468656d652f
7468656d65312e786d6cec594f6fdb3614bf0fd87720746f6327761a07758ad8b19b2d4d1bc46e871e698996d850a240d2497d1bdae38001c3ba618715d86d87
615b8116d8a5fb34d93a6c1dd0afb0475292c5585e9236d88aad3e2412f9e3fbff1e1fa9abd7eec70c1d1221294fda5efd72cd4324f1794093b0eddd1ef62fad
79482a9c0498f184b4bd2991deb58df7dfbb8ad755446282607d22d771db8b944ad79796a40fc3585ee62949606ecc458c15bc8a702910f808e8c66c69b9565b
5d8a314d3c94e018c8de1a8fa94fd05093f43672e23d06af89927ac06762a049136785c10607758d9053d965021d62d6f6804fc08f86e4bef210c352c144dbab
999fb7b4717509af678b985ab0b6b4ae6f7ed9ba6c4170b06c788a705430adf71bad2b5b057d03606a1ed7ebf5babd7a41cf00b0ef83a6569632cd467faddec9
699640f6719e76b7d6ac355c7c89feca9cccad4ea7d36c65b258a206641f1b73f8b5da6a6373d9c11b90c537e7f08dce66b7bbeae00dc8e257e7f0fd2badd586
8b37a088d1e4600ead1ddaef67d40bc898b3ed4af81ac0d76a197c86826828a24bb318f3442d8ab518dfe3a20f000d6458d104a9694ac6d88728eee2782428d6
0cf03ac1a5193be4cbb921cd0b495fd054b5bd0f530c1931a3f7eaf9f7af9e3f45c70f9e1d3ff8e9f8e1c3e3073f5a42ceaa6d9c84e5552fbffdeccfc71fa33f
9e7ef3f2d117d57859c6fffac327bffcfc793510d26726ce8b2f9ffcf6ecc98baf3efdfdbb4715f04d814765f890c644a29be408edf3181433567125272371be
15c308d3f28acd249438c19a4b05fd9e8a1cf4cd296699771c393ac4b5e01d01e5a30a787d72cf1178108989a2159c77a2d801ee72ce3a5c545a6147f32a9979
3849c26ae66252c6ed637c58c5bb8b13c7bfbd490a75330f4b47f16e441c31f7184e140e494214d273fc80900aedee52ead87597fa824b3e56e82e451d4c2b4d
32a423279a668bb6690c7e9956e90cfe766cb37b077538abd27a8b1cba48c80acc2a841f12e698f13a9e281c57911ce298950d7e03aba84ac8c154f8655c4f2a
f074481847bd804859b5e696007d4b4edfc150b12addbecba6b18b148a1e54d1bc81392f23b7f84137c2715a851dd0242a633f900710a218ed715505dfe56e86
e877f0034e16bafb0e258ebb4faf06b769e888340b103d331115bebc4eb813bf83291b63624a0d1475a756c734f9bbc2cd28546ecbe1e20a3794ca175f3fae90
fb6d2dd99bb07b55e5ccf68942bd0877b23c77b908e8db5f9db7f024d9239010f35bd4bbe2fcae387bfff9e2bc289f2fbe24cfaa301468dd8bd846dbb4ddf1c2
ae7b4c191ba8292337a469bc25ec3d411f06f53a73e224c5292c8de0516732307070a1c0660d125c7d44553488700a4d7bddd3444299910e254ab984c3a219ae
a4adf1d0f82b7bd46cea4388ad1c12ab5d1ed8e1153d9c9f350a3246aad01c6873462b9ac05999ad5cc988826eafc3acae853a33b7ba11cd1445875ba1b236b1
399483c90bd560b0b0263435085a21b0f22a9cf9356b38ec6046026d77eba3dc2dc60b17e92219e180643ed27acffba86e9c94c7ca9c225a0f1b0cfae0788ad5
4adc5a9aec1b703b8b93caec1a0bd8e5de7b132fe5113cf312503b998e2c2927274bd051db6b35979b1ef271daf6c6704e86c73805af4bdd476216c26593af84
0dfb5393d964f9cc9bad5c313709ea70f561ed3ea7b053075221d51696910d0d339585004b34272bff7213cc7a510a5454a3b349b1b206c1f0af490176745d4b
c663e2abb2b34b23da76f6352ba57ca2881844c1111ab189d8c7e07e1daaa04f40255c77988aa05fe06e4e5bdb4cb9c5394bbaf28d98c1d971ccd20867e556a7
689ec9166e0a522183792b8907ba55ca6e943bbf2a26e52f48957218ffcf54d1fb09dc3eac04da033e5c0d0b8c74a6b43d2e54c4a10aa511f5fb021a07533b20
5ae07e17a621a8e082dafc17e450ffb739676998b48643a4daa7211214f623150942f6a02c99e83b85583ddbbb2c4996113211551257a656ec1139246ca86be0
aadedb3d1441a89b6a929501833b197fee7b9641a3503739e57c732a59b1f7da1cf8a73b1f9bcca0945b874d4393dbbf10b1680f66bbaa5d6f96e77b6f59113d
316bb31a795600b3d256d0cad2fe354538e7566b2bd69cc6cbcd5c38f0e2bcc63058344429dc2121fd07f63f2a7c66bf76e80d75c8f7a1b622f878a18941d840
545fb28d07d205d20e8ea071b283369834296bdaac75d256cb37eb0bee740bbe278cad253b8bbfcf69eca23973d939b97891c6ce2cecd8da8e2d343578f6648a
c2d0383fc818c798cf64e52f597c740f1cbd05df0c264c49134cf09d4a60e8a107260f20f92d47b374e32f000000ffff0300504b030414000600080000002100
0dd1909fb60000001b010000270000007468656d652f7468656d652f5f72656c732f7468656d654d616e616765722e786d6c2e72656c73848f4d0ac2301484f7
8277086f6fd3ba109126dd88d0add40384e4350d363f2451eced0dae2c082e8761be9969bb979dc9136332de3168aa1a083ae995719ac16db8ec8e4052164e89
d93b64b060828e6f37ed1567914b284d262452282e3198720e274a939cd08a54f980ae38a38f56e422a3a641c8bbd048f7757da0f19b017cc524bd62107bd500
1996509affb3fd381a89672f1f165dfe514173d9850528a2c6cce0239baa4c04ca5bbabac4df000000ffff0300504b01022d0014000600080000002100e9de0f
bfff0000001c0200001300000000000000000000000000000000005b436f6e74656e745f54797065735d2e786d6c504b01022d0014000600080000002100a5d6
a7e7c0000000360100000b00000000000000000000000000300100005f72656c732f2e72656c73504b01022d00140006000800000021006b799616830000008a
0000001c00000000000000000000000000190200007468656d652f7468656d652f7468656d654d616e616765722e786d6c504b01022d00140006000800000021
0030dd4329a8060000a41b00001600000000000000000000000000d60200007468656d652f7468656d652f7468656d65312e786d6c504b01022d001400060008
00000021000dd1909fb60000001b0100002700000000000000000000000000b20900007468656d652f7468656d652f5f72656c732f7468656d654d616e616765722e786d6c2e72656c73504b050600000000050005005d010000ad0a00000000}
{\*\colorschememapping 3c3f786d6c2076657273696f6e3d22312e302220656e636f64696e673d225554462d3822207374616e64616c6f6e653d22796573223f3e0d0a3c613a636c724d
617020786d6c6e733a613d22687474703a2f2f736368656d61732e6f70656e786d6c666f726d6174732e6f72672f64726177696e676d6c2f323030362f6d6169
6e22206267313d226c743122207478313d22646b3122206267323d226c743222207478323d22646b322220616363656e74313d22616363656e74312220616363
656e74323d22616363656e74322220616363656e74333d22616363656e74332220616363656e74343d22616363656e74342220616363656e74353d22616363656e74352220616363656e74363d22616363656e74362220686c696e6b3d22686c696e6b2220666f6c486c696e6b3d22666f6c486c696e6b222f3e}
{\*\latentstyles\lsdstimax267\lsdlockeddef0\lsdsemihiddendef1\lsdunhideuseddef1\lsdqformatdef0\lsdprioritydef99{\lsdlockedexcept \lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority0 \lsdlocked0 Normal;
\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 1;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 2;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 3;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 4;
\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 5;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 6;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 7;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 8;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 9;
\lsdpriority39 \lsdlocked0 toc 1;\lsdpriority39 \lsdlocked0 toc 2;\lsdpriority39 \lsdlocked0 toc 3;\lsdpriority39 \lsdlocked0 toc 4;\lsdpriority39 \lsdlocked0 toc 5;\lsdpriority39 \lsdlocked0 toc 6;\lsdpriority39 \lsdlocked0 toc 7;
\lsdpriority39 \lsdlocked0 toc 8;\lsdpriority39 \lsdlocked0 toc 9;\lsdqformat1 \lsdpriority35 \lsdlocked0 caption;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority10 \lsdlocked0 Title;\lsdpriority1 \lsdlocked0 Default Paragraph Font;
\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority11 \lsdlocked0 Subtitle;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority22 \lsdlocked0 Strong;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority20 \lsdlocked0 Emphasis;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority59 \lsdlocked0 Table Grid;\lsdunhideused0 \lsdlocked0 Placeholder Text;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority1 \lsdlocked0 No Spacing;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading;\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List;\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List;\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List;\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid;\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading Accent 1;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 1;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1 Accent 1;\lsdunhideused0 \lsdlocked0 Revision;
\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority34 \lsdlocked0 List Paragraph;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority29 \lsdlocked0 Quote;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority30 \lsdlocked0 Intense Quote;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2 Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 1;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading Accent 1;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading Accent 2;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 2;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1 Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2 Accent 2;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 2;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List Accent 2;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List Accent 3;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 3;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1 Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2 Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 3;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List Accent 3;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid Accent 3;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid Accent 4;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1 Accent 4;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2 Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 4;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading Accent 4;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading Accent 5;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 5;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1 Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2 Accent 5;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 5;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List Accent 5;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List Accent 6;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 6;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1 Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2 Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 6;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List Accent 6;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid Accent 6;
\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority19 \lsdlocked0 Subtle Emphasis;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority21 \lsdlocked0 Intense Emphasis;
\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority31 \lsdlocked0 Subtle Reference;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority32 \lsdlocked0 Intense Reference;
\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority33 \lsdlocked0 Book Title;\lsdpriority37 \lsdlocked0 Bibliography;\lsdqformat1 \lsdpriority39 \lsdlocked0 TOC Heading;}}{\*\datastore 010500000200000018000000
4d73786d6c322e534158584d4c5265616465722e362e3000000000000000000000060000
d0cf11e0a1b11ae1000000000000000000000000000000003e000300feff090006000000000000000000000001000000010000000000000000100000feffffff00000000feffffff0000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
fffffffffffffffffdfffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
ffffffffffffffffffffffffffffffff52006f006f007400200045006e00740072007900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000016000500ffffffffffffffffffffffff0c6ad98892f1d411a65f0040963251e50000000000000000000000006007
a9110737cb01feffffff00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffff00000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffff0000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffff000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000105000000000000}} | 1012607376-daihanlong | shuffle-android/docs/manual.rtf | Rich Text Format | asf20 | 59,942 |
/*
* Copyright (C) 2009 Android Shuffle Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dodgybits.shuffle.android.view.activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity;
import org.dodgybits.shuffle.android.core.model.Entity;
import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister;
import org.dodgybits.shuffle.android.core.view.MenuUtils;
import roboguice.inject.InjectView;
import roboguice.util.Ln;
/**
* A generic activity for editing an item in a database. This can be used either
* to simply view an item (Intent.VIEW_ACTION), view and edit an item
* (Intent.EDIT_ACTION), or create a new item (Intent.INSERT_ACTION).
*/
public abstract class AbstractViewActivity<E extends Entity> extends
FlurryEnabledActivity implements View.OnClickListener {
private @InjectView(R.id.edit_button) Button mEditButton;
protected Uri mUri;
protected Cursor mCursor;
protected E mOriginalItem;
@Override
protected void onCreate(Bundle icicle) {
Ln.d("onCreate+");
super.onCreate(icicle);
mUri = getIntent().getData();
setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
setContentView(getContentViewResId());
Drawable icon = getResources().getDrawable(R.drawable.ic_menu_edit);
icon.setBounds(0, 0, 36, 36);
mEditButton.setCompoundDrawables(icon, null, null, null);
mEditButton.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuUtils.addPrefsHelpMenuItems(this, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (MenuUtils.checkCommonItemsSelected(item, this, MenuUtils.INBOX_ID)) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.edit_button:
doEditAction();
break;
}
}
protected void doEditAction() {
Intent editIntent = new Intent(Intent.ACTION_EDIT, mUri);
startActivity(editIntent);
finish();
}
/**
* @return id of layout for this view
*/
abstract protected int getContentViewResId();
abstract protected void updateUIFromItem(E item);
abstract protected EntityPersister<E> getPersister();
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/view/activity/AbstractViewActivity.java | Java | asf20 | 3,150 |
/*
* Copyright (C) 2009 Android Shuffle Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dodgybits.shuffle.android.view.activity;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.model.Context;
import org.dodgybits.shuffle.android.core.model.Id;
import org.dodgybits.shuffle.android.core.model.Project;
import org.dodgybits.shuffle.android.core.model.Task;
import org.dodgybits.shuffle.android.core.model.persistence.EntityCache;
import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister;
import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister;
import org.dodgybits.shuffle.android.core.util.CalendarUtils;
import org.dodgybits.shuffle.android.core.view.ContextIcon;
import org.dodgybits.shuffle.android.list.view.LabelView;
import org.dodgybits.shuffle.android.list.view.StatusView;
import org.dodgybits.shuffle.android.persistence.provider.TaskProvider;
import roboguice.inject.InjectView;
import roboguice.util.Ln;
import android.content.ContentUris;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.inject.Inject;
/**
* A generic activity for viewing a task.
*/
public class TaskViewActivity extends AbstractViewActivity<Task> {
private @InjectView(R.id.complete_toggle_button) Button mCompleteButton;
private @InjectView(R.id.project) TextView mProjectView;
private @InjectView(R.id.description) TextView mDescriptionView;
private @InjectView(R.id.context) LabelView mContextView;
private @InjectView(R.id.details_entry) View mDetailsEntry;
private @InjectView(R.id.details) TextView mDetailsView;
private @InjectView(R.id.start) TextView mStartView;
private @InjectView(R.id.due) TextView mDueView;
private @InjectView(R.id.calendar_entry) View mCalendarEntry;
private @InjectView(R.id.view_calendar_button) Button mViewCalendarButton;
// private @InjectView(R.id.reminder_entry) View mReminderEntry;
// private @InjectView(R.id.reminder) TextView mReminderView;
private @InjectView(R.id.status) StatusView mStatusView;
private @InjectView(R.id.completed) TextView mCompletedView;
private @InjectView(R.id.created) TextView mCreatedView;
private @InjectView(R.id.modified) TextView mModifiedView;
@Inject private EntityCache<Project> mProjectCache;
@Inject private EntityCache<Context> mContextCache;
@Inject private TaskPersister mPersister;
@Override
protected void onCreate(Bundle icicle) {
Ln.d("onCreate+");
super.onCreate(icicle);
loadCursors();
mCursor.moveToFirst();
mOriginalItem = mPersister.read(mCursor);
updateUIFromItem(mOriginalItem);
Drawable icon = getResources().getDrawable(R.drawable.ic_menu_view);
icon.setBounds(0, 0, 36, 36);
mViewCalendarButton.setCompoundDrawables(icon, null, null, null);
mViewCalendarButton.setOnClickListener(this);
mCompleteButton.setOnClickListener(this);
}
@Override
protected void updateUIFromItem(Task task) {
Context context = mContextCache.findById(task.getContextId());
Project project = mProjectCache.findById(task.getProjectId());
updateCompleteButton(task.isComplete());
updateProject(project);
updateDescription(task.getDescription());
updateContext(context);
updateDetails(task.getDetails());
updateScheduling(task.getStartDate(), task.getDueDate());
updateCalendar(task.getCalendarEventId());
updateExtras(task, context, project);
}
@Override
protected EntityPersister<Task> getPersister() {
return mPersister;
}
/**
* @return id of layout for this view
*/
@Override
protected int getContentViewResId() {
return R.layout.task_view;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.complete_toggle_button: {
toggleComplete();
String text = getString(R.string.itemSavedToast, getString(R.string.task_name));
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
finish();
break;
}
case R.id.view_calendar_button: {
Uri eventUri = ContentUris.appendId(
CalendarUtils.getEventContentUri().buildUpon(),
mOriginalItem.getCalendarEventId().getId()).build();
Intent viewCalendarEntry = new Intent(Intent.ACTION_VIEW, eventUri);
viewCalendarEntry.putExtra(CalendarUtils.EVENT_BEGIN_TIME, mOriginalItem.getStartDate());
viewCalendarEntry.putExtra(CalendarUtils.EVENT_END_TIME, mOriginalItem.getDueDate());
startActivity(viewCalendarEntry);
break;
}
default:
super.onClick(v);
break;
}
}
protected final void toggleComplete() {
Task updatedTask = Task.newBuilder().mergeFrom(mOriginalItem)
.setComplete(!mOriginalItem.isComplete()).build();
mPersister.update(updatedTask);
}
private void loadCursors() {
// Get the task if we're editing
mCursor = managedQuery(mUri, TaskProvider.Tasks.FULL_PROJECTION, null, null, null);
if (mCursor == null || mCursor.getCount() == 0) {
// The cursor is empty. This can happen if the event was deleted.
finish();
}
}
private void updateCompleteButton(boolean isComplete) {
String label = getString(R.string.complete_toggle_button,
isComplete ? getString(R.string.incomplete) : getString(R.string.complete));
mCompleteButton.setText(label);
}
private void updateProject(Project project) {
if (project == null) {
mProjectView.setVisibility(View.GONE);
} else {
mProjectView.setVisibility(View.VISIBLE);
mProjectView.setText(project.getName());
}
}
private void updateDescription(String description) {
mDescriptionView.setTextKeepState(description);
}
private void updateContext(Context context) {
if (context != null) {
mContextView.setVisibility(View.VISIBLE);
mContextView.setText(context.getName());
mContextView.setColourIndex(context.getColourIndex());
ContextIcon icon = ContextIcon.createIcon(context.getIconName(), getResources());
int id = icon.smallIconId;
if (id > 0) {
mContextView.setIcon(getResources().getDrawable(id));
} else {
mContextView.setIcon(null);
}
} else {
mContextView.setVisibility(View.INVISIBLE);
}
}
private void updateDetails(String details) {
if (TextUtils.isEmpty(details)) {
mDetailsEntry.setVisibility(View.GONE);
} else {
mDetailsEntry.setVisibility(View.VISIBLE);
mDetailsView.setText(details);
}
}
private void updateScheduling(long startMillis, long dueMillis) {
mStartView.setText(formatDateTime(startMillis));
mDueView.setText(formatDateTime(dueMillis));
}
private void updateCalendar(Id calendarEntry) {
if (calendarEntry.isInitialised()) {
mCalendarEntry.setVisibility(View.VISIBLE);
} else {
mCalendarEntry.setVisibility(View.GONE);
}
}
private final int cDateFormatFlags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_MONTH |
DateUtils.FORMAT_ABBREV_WEEKDAY | DateUtils.FORMAT_SHOW_TIME;
private String formatDateTime(long millis) {
String value;
if (millis > 0L) {
int flags = cDateFormatFlags;
if (DateFormat.is24HourFormat(this)) {
flags |= DateUtils.FORMAT_24HOUR;
}
value = DateUtils.formatDateTime(this, millis, flags);
} else {
value = "";
}
return value;
}
private void updateExtras(Task task, Context context, Project project) {
mStatusView.updateStatus(task, context, project, !task.isComplete());
mCompletedView.setText(task.isComplete() ? getString(R.string.completed) : "");
mCreatedView.setText(formatDateTime(task.getCreatedDate()));
mModifiedView.setText(formatDateTime(task.getModifiedDate()));
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/view/activity/TaskViewActivity.java | Java | asf20 | 9,381 |
package org.dodgybits.shuffle.android.synchronisation.tracks.service;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.activity.flurry.Analytics;
import org.dodgybits.shuffle.android.preference.model.Preferences;
import org.dodgybits.shuffle.android.preference.view.Progress;
import org.dodgybits.shuffle.android.synchronisation.tracks.ApiException;
import org.dodgybits.shuffle.android.synchronisation.tracks.SyncProgressListener;
import org.dodgybits.shuffle.android.synchronisation.tracks.TracksSynchronizer;
import org.dodgybits.shuffle.android.synchronisation.tracks.activity.SynchronizeActivity;
import roboguice.service.RoboService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.text.format.DateUtils;
import android.util.Log;
import android.widget.RemoteViews;
import com.google.inject.Inject;
/**
* This service handles synchronization in the background.
*
* @author Morten Nielsen
*/
public class SynchronizationService extends RoboService implements SyncProgressListener {
private static final String cTag = "SynchronizationService";
private NotificationManager mNotificationManager;
private Handler mHandler;
private CheckTimer mCheckTimer;
private PerformSynch mPerformSynch;
private long interval = 0;
private TracksSynchronizer synchronizer = null;
private RemoteViews contentView;
@Inject Analytics mAnalytics;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
String ns = Context.NOTIFICATION_SERVICE;
mNotificationManager = (NotificationManager) getSystemService(ns);
contentView = new RemoteViews(getPackageName(), R.layout.synchronize_notification_layout);
contentView.setProgressBar(R.id.progress_horizontal, 100, 50, true);
contentView.setImageViewResource(R.id.image, R.drawable.shuffle_icon);
mHandler = new Handler();
mCheckTimer = new CheckTimer();
mPerformSynch = new PerformSynch();
mHandler.post(mCheckTimer);
}
private class CheckTimer implements Runnable {
@Override
public void run() {
Log.d(cTag, "Checking preferences");
long newInterval = calculateIntervalInMilliseconds(
Preferences.getTracksInterval(SynchronizationService.this));
if (interval != newInterval) {
interval = newInterval;
scheduleSynchronization();
}
mHandler.postDelayed(this, 5L * DateUtils.MINUTE_IN_MILLIS);
}
private long calculateIntervalInMilliseconds(int selected) {
long result = 0L;
switch (selected) {
case 1: // 30min
result = 30L * DateUtils.MINUTE_IN_MILLIS;
break;
case 2: // 1hr
result = DateUtils.HOUR_IN_MILLIS;
break;
case 3:
result = 2L * DateUtils.HOUR_IN_MILLIS;
break;
case 4:
result = 3L * DateUtils.HOUR_IN_MILLIS;
break;
}
return result;
}
}
private class PerformSynch implements Runnable
{
@Override
public void run() {
synchronize();
}
}
private void scheduleSynchronization() {
mHandler.removeCallbacks(mPerformSynch);
if (interval != 0L) {
mHandler.post(mPerformSynch);
}
}
private void synchronize() {
Log.d(cTag, "Starting synch");
try {
synchronizer = TracksSynchronizer.getActiveSynchronizer(this, mAnalytics);
} catch (ApiException ignored) {
}
if (synchronizer != null) {
synchronizer.registerListener(this);
}
if (synchronizer != null && Preferences.validateTracksSettings(this)) {
if (synchronizer.getStatus() != AsyncTask.Status.RUNNING)
synchronizer.execute();
}
mHandler.postDelayed(mPerformSynch, interval);
}
private static final int NOTIFICATION_ID = 1;
private void createNotification() {
int icon = R.drawable.shuffle_icon;
CharSequence tickerText = this.getText(R.string.app_name);
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Intent notificationIntent = new Intent(this, SynchronizeActivity.class);
notification.contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.contentView = contentView;
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
private void clearNotification() {
mNotificationManager.cancel(NOTIFICATION_ID);
}
@Override
public void onDestroy() {
super.onDestroy();
mHandler.removeCallbacks(mCheckTimer);
mHandler.removeCallbacks(mPerformSynch);
if (synchronizer != null) {
synchronizer.unRegisterListener(this);
}
}
@Override
public void progressUpdate(Progress progress) {
if (progress.getProgressPercent() == 100) clearNotification();
if (progress.getProgressPercent() == 0) createNotification();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/service/SynchronizationService.java | Java | asf20 | 5,709 |
package org.dodgybits.shuffle.android.synchronisation.tracks.ssl;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ssl.SSLSocketFactory;
public class TrustedSSLSocketFactory extends SSLSocketFactory {
private static SSLContext sslContext = null;
private static final TrustStrategy trustStrategy = new TrustSelfSignedStrategy();
public TrustedSSLSocketFactory()
throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException, UnrecoverableKeyException {
super(null, null, null);
if (sslContext == null) {
initSSLContext();
}
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
static void initSSLContext() throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
sslContext = SSLContext.getInstance("TLS");
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(null, null); // use default key store
KeyManager[] keymanagers = kmfactory.getKeyManagers();
TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmfactory.init((KeyStore)null);
TrustManager[] trustmanagers = tmfactory.getTrustManagers();
for (int i = 0; i < trustmanagers.length; i++) {
TrustManager tm = trustmanagers[i];
if (tm instanceof X509TrustManager) {
trustmanagers[i] = new TrustManagerDecorator((X509TrustManager)tm, trustStrategy);
}
}
sslContext.init(keymanagers, trustmanagers, null);
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/ssl/TrustedSSLSocketFactory.java | Java | asf20 | 2,468 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.dodgybits.shuffle.android.synchronisation.tracks.ssl;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* A trust strategy that accepts self-signed certificates as trusted. Verification of all other
* certificates is done by the trust manager configured in the SSL context.
*
* Copy of org.apache.http.conn.ssl.TrustSelfSignedStrategy version 4.1 not yet in Android.
*/
public class TrustSelfSignedStrategy implements TrustStrategy {
public boolean isTrusted(
final X509Certificate[] chain, final String authType) throws CertificateException {
return chain.length == 1;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/ssl/TrustSelfSignedStrategy.java | Java | asf20 | 1,852 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.dodgybits.shuffle.android.synchronisation.tracks.ssl;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
/**
* Copy of org.apache.http.conn.ssl.TrustManagerDecorator version 4.1 not yet in Android.
*/
class TrustManagerDecorator implements X509TrustManager {
private final X509TrustManager trustManager;
private final TrustStrategy trustStrategy;
TrustManagerDecorator(final X509TrustManager trustManager, final TrustStrategy trustStrategy) {
super();
this.trustManager = trustManager;
this.trustStrategy = trustStrategy;
}
public void checkClientTrusted(
final X509Certificate[] chain, final String authType) throws CertificateException {
this.trustManager.checkClientTrusted(chain, authType);
}
public void checkServerTrusted(
final X509Certificate[] chain, final String authType) throws CertificateException {
if (!this.trustStrategy.isTrusted(chain, authType)) {
this.trustManager.checkServerTrusted(chain, authType);
}
}
public X509Certificate[] getAcceptedIssuers() {
return this.trustManager.getAcceptedIssuers();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/ssl/TrustManagerDecorator.java | Java | asf20 | 2,444 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.dodgybits.shuffle.android.synchronisation.tracks.ssl;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* A strategy to establish trustworthiness of certificates without consulting the trust manager
* configured in the actual SSL context. This interface can be used to override the standard
* JSSE certificate verification process.
*
* Copy of org.apache.http.conn.ssl.TrustStrategy version 4.1 not yet in Android.
*/
public interface TrustStrategy {
/**
* Determines whether the certificate chain can be trusted without consulting the trust manager
* configured in the actual SSL context. This method can be used to override the standard JSSE
* certificate verification process.
* <p>
* Please note that, if this method returns <code>false</code>, the trust manager configured
* in the actual SSL context can still clear the certificate as trusted.
*
* @param chain the peer certificate chain
* @param authType the authentication type based on the client certificate
* @return <code>true</code> if the certificate can be trusted without verification by
* the trust manager, <code>false</code> otherwise.
* @throws CertificateException thrown if the certificate is not trusted or invalid.
*/
boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException;
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/ssl/TrustStrategy.java | Java | asf20 | 2,609 |
package org.dodgybits.shuffle.android.synchronisation.tracks;
import org.apache.http.StatusLine;
public class WebResult {
private String mContent;
private StatusLine mStatus;
public WebResult(StatusLine status, String content) {
mStatus = status;
mContent = content;
}
public String getContent() {
return mContent;
}
public StatusLine getStatus() {
return mStatus;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/WebResult.java | Java | asf20 | 418 |
package org.dodgybits.shuffle.android.synchronisation.tracks;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.LinkedList;
import java.util.Map;
import org.apache.http.HttpStatus;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.activity.flurry.Analytics;
import org.dodgybits.shuffle.android.core.model.EntityBuilder;
import org.dodgybits.shuffle.android.core.model.Id;
import org.dodgybits.shuffle.android.core.model.Task;
import org.dodgybits.shuffle.android.core.model.Task.Builder;
import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister;
import org.dodgybits.shuffle.android.core.util.DateUtils;
import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.ParseResult;
import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.Parser;
import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.TaskParser;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;
import android.content.Context;
import android.util.Log;
import android.util.Xml;
/**
* @author Morten Nielsen
*/
public final class TaskSynchronizer extends Synchronizer<Task> {
private static final String cTag = "TaskSynchronizer";
private final String mTracksUrl;
private Parser<Task> mParser;
public TaskSynchronizer(
EntityPersister<Task> persister,
TracksSynchronizer tracksSynchronizer,
WebClient client,
Context context,
Analytics analytics,
int basePercent,
String tracksUrl) {
super(persister, tracksSynchronizer, client, context, basePercent);
mParser = new TaskParser(this, this, analytics);
this.mTracksUrl = tracksUrl;
}
@Override
protected EntityBuilder<Task> createBuilder() {
return Task.newBuilder();
}
@Override
protected void verifyEntitiesForSynchronization(Map<Id, Task> localEntities) {
LinkedList<Id> tasksWithoutContext = new LinkedList<Id>();
for(Task t : localEntities.values()) {
if(!t.getContextId().isInitialised()) {
tasksWithoutContext.add(t.getLocalId());
}
}
if (tasksWithoutContext.size() > 0) {
mTracksSynchronizer.postSyncMessage(R.string.cannotSyncTasksWithoutContext);
for(Id id : tasksWithoutContext) {
localEntities.remove(id);
}
}
}
@Override
protected String readingRemoteText() {
return mContext.getString(R.string.readingRemoteTasks);
}
@Override
protected String processingText() {
return mContext.getString(R.string.processingTasks);
}
@Override
protected String readingLocalText() {
return mContext.getString(R.string.readingLocalTasks);
}
@Override
protected String stageFinishedText() {
return mContext.getString(R.string.doneWithTasks);
}
protected Task createMergedLocalEntity(Task localTask, Task newTask) {
Builder builder = Task.newBuilder();
builder.mergeFrom(localTask);
builder
.setDescription(newTask.getDescription())
.setDetails(newTask.getDetails())
.setContextId(newTask.getContextId())
.setProjectId(newTask.getProjectId())
.setModifiedDate(newTask.getModifiedDate())
.setStartDate(newTask.getStartDate())
.setDeleted(newTask.isDeleted())
.setDueDate(newTask.getDueDate())
.setAllDay(newTask.isAllDay())
.setTracksId(newTask.getTracksId());
return builder.build();
}
protected String createDocumentForEntity(Task task) {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
//serializer.startDocument("UTF-8", true);
serializer.startTag("", "todo");
if (task.isComplete()) {
String completedDateStr = DateUtils.formatIso8601Date(task.getModifiedDate());
serializer.startTag("", "completed-at").attribute("", "type", "datetime").text(completedDateStr).endTag("", "completed-at");
}
Id contextId = findTracksIdByContextId(task.getContextId());
if (contextId.isInitialised()) {
serializer.startTag("", "context-id").attribute("", "type", "integer").text(contextId.toString()).endTag("", "context-id");
}
String createdDateStr = DateUtils.formatIso8601Date(task.getCreatedDate());
serializer.startTag("", "created-at").attribute("", "type", "datetime").text(createdDateStr).endTag("", "created-at");
serializer.startTag("", "description").text(task.getDescription()).endTag("", "description");
if (task.getDueDate() != 0) {
String dueDateStr = DateUtils.formatIso8601Date(task.getDueDate());
serializer.startTag("", "due").attribute("", "type", "datetime").text(dueDateStr).endTag("", "due");
}
serializer.startTag("", "notes").text(task.getDetails() != null ? task.getDetails() : "").endTag("", "notes");
Id projectId = findTracksIdByProjectId(task.getProjectId());
if (projectId.isInitialised()) {
serializer.startTag("", "project-id").attribute("", "type", "integer").text(projectId.toString()).endTag("", "project-id");
}
if (task.getStartDate() != 0L) {
serializer.startTag("", "show-from").attribute("", "type", "datetime").text(DateUtils.formatIso8601Date(task.getStartDate())).endTag("", "show-from");
}
serializer.startTag("", "state").text(task.isComplete() ? "completed" : "active").endTag("", "state");
String updatedDateStr = DateUtils.formatIso8601Date(task.getModifiedDate());
serializer.startTag("", "updated-at").attribute("", "type", "datetime").text(updatedDateStr).endTag("", "updated-at");
serializer.endTag("", "todo");
serializer.flush();
} catch (IOException ignored) {
Log.d(cTag, "Failed to serialize task", ignored);
}
Log.d(cTag, writer.toString());
return writer.toString();
}
@Override
protected String createEntityUrl(Task task) {
return mTracksUrl + "/todos/" + task.getTracksId() + ".xml";
}
@Override
protected String entityIndexUrl() {
return mTracksUrl + "/todos.xml";
}
@Override
protected Parser<Task> getEntityParser() {
return mParser;
}
@Override
protected boolean deleteEntity(Task t) {
//Avoid extra calls if the entity is already deleted or completed.
if(t.isComplete() || t.isDeleted())
return true;
WebResult result;
try {
result = mWebClient.getUrlContent(this.createEntityUrl(t));
} catch (ApiException e1) {
return false;
}
XmlPullParser parser = Xml.newPullParser();
if(result.getStatus().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
super.deleteEntity(t);
}
if(result.getStatus().getStatusCode() != HttpStatus.SC_OK) {
return false;
}
try {
parser.setInput(new StringReader(result.getContent()));
} catch (Exception e) {
return false;
}
ParseResult<Task> parseResult = getEntityParser().parseSingle(parser);
if(parseResult.isSuccess() && parseResult.getResult().isComplete()){
Task task = Task.newBuilder().mergeFrom(t).mergeFrom(parseResult.getResult()).build();
mPersister.update(task);
return true;
}
return false;
}
} | 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/TaskSynchronizer.java | Java | asf20 | 7,871 |
package org.dodgybits.shuffle.android.synchronisation.tracks;
import org.dodgybits.shuffle.android.preference.view.Progress;
/**
* Items that can receive updates about synchronization progress
*
* @author Morten Nielsen
*/
public interface SyncProgressListener {
void progressUpdate(Progress progress);
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/SyncProgressListener.java | Java | asf20 | 316 |
package org.dodgybits.shuffle.android.synchronisation.tracks;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.dodgybits.shuffle.android.synchronisation.tracks.ssl.TrustedSSLSocketFactory;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
/**
* Handles communication to the REST service
*
* @author Morten Nielsen
*/
public class WebClient {
private String sUserAgent;
private byte[] sBuffer = new byte[512];
private final String tracksUser;
private final String tracksPassword;
private final String cTag = "WebClient";
private final boolean selfSignedCert;
public WebClient(Context context, String tracksUser, String tracksPassword, boolean selfSignedCert) throws ApiException {
this.tracksUser = tracksUser;
this.tracksPassword = tracksPassword;
this.selfSignedCert = selfSignedCert;
PackageManager manager = context.getPackageManager();
PackageInfo info = null;
try {
info = manager.getPackageInfo(context.getPackageName(), 0);
} catch (PackageManager.NameNotFoundException ignored) {
}
if (info != null) {
sUserAgent = String.format("%1$s %2$s",
info.packageName, info.versionName);
}
}
protected synchronized boolean deleteUrl(String url) throws ApiException {
if (sUserAgent == null) {
throw new ApiException("User-Agent string must be prepared");
}
// Create client and set our specific user-agent string
HttpClient client = CreateClient();
java.net.URI uri = URI.create(url);
HttpHost host = GetHost(uri);
HttpDelete request = new HttpDelete(uri.getPath());
request.setHeader("User-Agent", sUserAgent);
try {
HttpResponse response = client.execute(host, request);
// Check if server response is valid
StatusLine status = response.getStatusLine();
Log.i(cTag, "delete with response " + status.toString());
return status.getStatusCode() == HttpStatus.SC_OK;
} catch (IOException e) {
throw new ApiException("Problem communicating with API", e);
}
}
private HttpClient CreateClient() {
DefaultHttpClient client;
if (selfSignedCert) {
HttpParams params = new BasicHttpParams();
SchemeRegistry sr = new SchemeRegistry();
sr.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
try {
sr.register(new Scheme("https", new TrustedSSLSocketFactory(), 443));
} catch (Exception e) {
Log.v("Shuffle", e.toString() + "");
sr.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
}
ClientConnectionManager cm = new SingleClientConnManager(params, sr);
client = new DefaultHttpClient(cm, params);
} else {
client = new DefaultHttpClient();
}
client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(tracksUser, tracksPassword));
return client;
}
public synchronized WebResult getUrlContent(String url) throws ApiException {
if (sUserAgent == null) {
throw new ApiException("User-Agent string must be prepared");
}
// Create client and set our specific user-agent string
HttpClient client = CreateClient();
java.net.URI uri = URI.create(url);
HttpHost host = GetHost(uri);
HttpGet request = new HttpGet(uri.getPath());
request.setHeader("User-Agent", sUserAgent);
try {
HttpResponse response = client.execute(host, request);
// Check if server response is valid
StatusLine status = response.getStatusLine();
Log.i(cTag, "get with response " + status.toString());
if (status.getStatusCode() != HttpStatus.SC_OK) {
return new WebResult(status, null);
}
// Pull content stream from response
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
ByteArrayOutputStream content = new ByteArrayOutputStream();
// Read response into a buffered stream
int readBytes;
while ((readBytes = inputStream.read(sBuffer)) != -1) {
content.write(sBuffer, 0, readBytes);
}
return new WebResult(status,new String(content.toByteArray()));
} catch (IOException e) {
throw new ApiException("Problem communicating with API", e);
}
}
private HttpHost GetHost(URI uri) {
HttpHost host;
int port = uri.getPort();
if (port == -1) {
port = uri.getScheme().equalsIgnoreCase("https") ? 443 : 80;
}
host = new HttpHost(uri.getHost(), port, uri.getScheme());
return host;
}
protected synchronized String postContentToUrl(String url, String content) throws ApiException {
if (sUserAgent == null) {
throw new ApiException("User-Agent string must be prepared");
}
// Create client and set our specific user-agent string
HttpClient client = CreateClient();
java.net.URI uri = URI.create(url);
HttpHost host = GetHost(uri);
HttpPost request = new HttpPost(uri.getPath());
request.setHeader("User-Agent", sUserAgent);
request.setHeader("Content-Type", "text/xml");
HttpEntity ent;
try {
ent = new StringEntity(content, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new ApiException("unsupported encoding set", e);
}
request.setEntity(ent);
try {
HttpResponse response = client.execute(host, request);
// Check if server response is valid
StatusLine status = response.getStatusLine();
Log.i(cTag, "post with response " + status.toString());
if (status.getStatusCode() != HttpStatus.SC_CREATED) {
throw new ApiException("Invalid response from server: " +
status.toString() + " for content: " + content);
}
Header[] header = response.getHeaders("Location");
if (header.length != 0) return header[0].getValue();
else return null;
} catch (IOException e) {
throw new ApiException("Problem communicating with API", e);
}
}
protected synchronized String putContentToUrl(String url, String content) throws ApiException {
if (sUserAgent == null) {
throw new ApiException("User-Agent string must be prepared");
}
// Create client and set our specific user-agent string
HttpClient client = CreateClient();
java.net.URI uri = URI.create(url);
HttpHost host = GetHost(uri);
HttpPut request = new HttpPut(uri.getPath());
request.setHeader("User-Agent", sUserAgent);
request.setHeader("Content-Type", "text/xml");
HttpEntity ent;
try {
ent = new StringEntity(content, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new ApiException("unsupported encoding", e);
}
request.setEntity(ent);
try {
HttpResponse response = client.execute(host, request);
// Check if server response is valid
StatusLine status = response.getStatusLine();
Log.i(cTag, "put with response " + status.toString());
if (status.getStatusCode() != HttpStatus.SC_OK) {
throw new ApiException("Invalid response from server: " +
status.toString());
}
// Pull returnContent stream from response
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
ByteArrayOutputStream returnContent = new ByteArrayOutputStream();
// Read response into a buffered stream
int readBytes;
while ((readBytes = inputStream.read(sBuffer)) != -1) {
returnContent.write(sBuffer, 0, readBytes);
}
return new String(returnContent.toByteArray());
} catch (IOException e) {
throw new ApiException("Problem communicating with API", e);
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/WebClient.java | Java | asf20 | 9,817 |
package org.dodgybits.shuffle.android.synchronisation.tracks;
import java.util.Map;
import org.dodgybits.shuffle.android.core.model.Id;
import org.dodgybits.shuffle.android.synchronisation.tracks.model.TracksEntity;
public class TracksEntities<E extends TracksEntity> {
private Map<Id, E> mEntities;
private boolean mErrorFree;
public TracksEntities(Map<Id, E> entities, boolean errorFree) {
mEntities = entities;
mErrorFree = errorFree;
}
public Map<Id, E> getEntities() {
return mEntities;
}
public boolean isErrorFree() {
return mErrorFree;
}
} | 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/TracksEntities.java | Java | asf20 | 658 |
package org.dodgybits.shuffle.android.synchronisation.tracks;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.activity.flurry.Analytics;
import org.dodgybits.shuffle.android.core.model.EntityBuilder;
import org.dodgybits.shuffle.android.core.model.Id;
import org.dodgybits.shuffle.android.core.model.Project;
import org.dodgybits.shuffle.android.core.model.Project.Builder;
import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister;
import org.dodgybits.shuffle.android.core.util.DateUtils;
import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.Parser;
import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.ProjectParser;
import org.xmlpull.v1.XmlSerializer;
import android.util.Log;
import android.util.Xml;
/**
* @author Morten Nielsen
*/
public final class ProjectSynchronizer extends Synchronizer<Project> {
private static final String cTag = "ProjectSynchronizer";
private final String mTracksUrl;
private Parser<Project> mParser;
public ProjectSynchronizer(
EntityPersister<Project> persister,
TracksSynchronizer tracksSynchronizer,
WebClient client,
android.content.Context context,
Analytics analytics,
int basePercent,
String tracksUrl) {
super(persister, tracksSynchronizer, client, context, basePercent);
mParser = new ProjectParser(this, analytics);
mTracksUrl = tracksUrl;
}
@Override
protected void verifyEntitiesForSynchronization(Map<Id, Project> localEntities) {
}
@Override
protected EntityBuilder<Project> createBuilder() {
return Project.newBuilder();
}
@Override
protected String readingRemoteText() {
return mContext.getString(R.string.readingRemoteProjects);
}
@Override
protected String processingText() {
return mContext.getString(R.string.processingProjects);
}
@Override
protected String readingLocalText() {
return mContext.getString(R.string.readingLocalProjects);
}
@Override
protected String stageFinishedText() {
return mContext.getString(R.string.doneWithProjects);
}
protected Project createMergedLocalEntity(Project localProject, Project remoteProject) {
Builder builder = Project.newBuilder();
builder.mergeFrom(localProject);
builder
.setName(remoteProject.getName())
.setModifiedDate(remoteProject.getModifiedDate())
.setArchived(remoteProject.isArchived())
.setDefaultContextId(remoteProject.getDefaultContextId())
.setDeleted(remoteProject.isDeleted())
.setTracksId(remoteProject.getTracksId());
return builder.build();
}
protected String createDocumentForEntity(Project project) {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
String now = DateUtils.formatIso8601Date(System.currentTimeMillis());
serializer.startTag("", "project");
serializer.startTag("", "created-at").attribute("", "type", "datetime").text(now).endTag("", "created-at");
Id contextId = findTracksIdByContextId(project.getDefaultContextId());
if(contextId.isInitialised()) {
serializer.startTag("", "default-context-id").attribute("", "type", "integer").text(contextId.toString()).endTag("", "default-context-id");
}
serializer.startTag("", "name").text(project.getName()).endTag("", "name");
serializer.startTag("", "state").text(project.isActive() ? "active" : "hidden").endTag("", "state");
serializer.startTag("", "updated-at").attribute("", "type", "datetime").text(now).endTag("", "updated-at");
serializer.endTag("", "project");
serializer.flush();
} catch (IOException ignored) {
Log.d(cTag, "Failed to serialize project", ignored);
}
return writer.toString();
}
@Override
protected String createEntityUrl(Project project) {
return mTracksUrl+ "/projects/" + project.getTracksId().getId() + ".xml";
}
@Override
protected String entityIndexUrl() {
return mTracksUrl+ "/projects.xml";
}
@Override
protected Parser<Project> getEntityParser() {
return mParser;
}
} | 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/ProjectSynchronizer.java | Java | asf20 | 4,580 |
package org.dodgybits.shuffle.android.synchronisation.tracks;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.activity.flurry.Analytics;
import org.dodgybits.shuffle.android.core.model.Context;
import org.dodgybits.shuffle.android.core.model.EntityBuilder;
import org.dodgybits.shuffle.android.core.model.Id;
import org.dodgybits.shuffle.android.core.model.Context.Builder;
import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister;
import org.dodgybits.shuffle.android.core.util.DateUtils;
import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.ContextParser;
import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.Parser;
import org.xmlpull.v1.XmlSerializer;
import android.util.Xml;
/**
* @author Morten Nielsen
*/
public class ContextSynchronizer extends Synchronizer<Context> {
private final String mTracksUrl;
private Parser<Context> mParser;
public ContextSynchronizer(
EntityPersister<Context> persister,
TracksSynchronizer tracksSynchronizer,
WebClient client,
android.content.Context context,
Analytics analytics,
int basePercent,
String tracksUrl) {
super(persister, tracksSynchronizer, client, context, basePercent);
mParser = new ContextParser(analytics);
mTracksUrl = tracksUrl;
}
@Override
protected void verifyEntitiesForSynchronization(Map<Id, Context> localEntities) {
}
@Override
protected String readingRemoteText() {
return mContext.getString(R.string.readingRemoteContexts);
}
@Override
protected String processingText() {
return mContext.getString(R.string.processingContexts);
}
@Override
protected String readingLocalText() {
return mContext.getString(R.string.readingLocalContexts);
}
@Override
protected String stageFinishedText() {
return mContext.getString(R.string.doneWithContexts);
}
@Override
protected EntityBuilder<Context> createBuilder() {
return Context.newBuilder();
}
@Override
protected Context createMergedLocalEntity(Context localContext, Context newContext) {
Builder builder = Context.newBuilder();
builder.mergeFrom(localContext);
builder
.setName(newContext.getName())
.setModifiedDate(newContext.getModifiedDate())
.setDeleted(newContext.isDeleted())
.setTracksId(newContext.getTracksId());
return builder.build();
}
@Override
protected String createDocumentForEntity(Context localContext) {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
//serializer.startDocument("UTF-8", true);
String now = DateUtils.formatIso8601Date(System.currentTimeMillis());
serializer.startTag("", "context");
serializer.startTag("", "created-at").attribute("", "type", "datetime").text(now).endTag("", "created-at");
serializer.startTag("", "hide").attribute("", "type", "boolean").text(String.valueOf(!localContext.isActive())).endTag("", "hide");
serializer.startTag("", "name").text(localContext.getName()).endTag("", "name");
serializer.startTag("", "position").attribute("", "type", "integer").text("12").endTag("", "position");
serializer.startTag("", "state").text(localContext.isDeleted() ? "hidden" : "active").endTag("", "state");
serializer.startTag("", "updated-at").attribute("", "type", "datetime").text(now).endTag("", "updated-at");
serializer.endTag("", "context");
// serializer.endDocument();
serializer.flush();
} catch (IOException ignored) {
}
return writer.toString();
}
@Override
protected String createEntityUrl(Context localContext) {
return mTracksUrl + "/contexts/" + localContext.getTracksId().getId() + ".xml";
}
@Override
protected String entityIndexUrl() {
return mTracksUrl+"/contexts.xml";
}
@Override
protected Parser<Context> getEntityParser() {
return mParser;
}
} | 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/ContextSynchronizer.java | Java | asf20 | 4,398 |
package org.dodgybits.shuffle.android.synchronisation.tracks;
@SuppressWarnings("serial")
public class ApiException extends Exception {
public ApiException(String reason) {
super(reason);
}
public ApiException(String reason, Exception e) {
super(reason, e);
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/ApiException.java | Java | asf20 | 316 |
package org.dodgybits.shuffle.android.synchronisation.tracks;
import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryTracksSyncCompletedEvent;
import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryTracksSyncError;
import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryTracksSyncStartedEvent;
import java.util.LinkedList;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.activity.flurry.Analytics;
import org.dodgybits.shuffle.android.core.model.Project;
import org.dodgybits.shuffle.android.core.model.Task;
import org.dodgybits.shuffle.android.core.model.persistence.ContextPersister;
import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister;
import org.dodgybits.shuffle.android.core.model.persistence.ProjectPersister;
import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister;
import org.dodgybits.shuffle.android.preference.model.Preferences;
import org.dodgybits.shuffle.android.preference.view.Progress;
import roboguice.inject.ContentResolverProvider;
import android.content.ContentResolver;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
/**
* This task synchronizes shuffle with a tracks service.
*
* @author Morten Nielsen
*/
public class TracksSynchronizer extends AsyncTask<String, Progress, Void> {
private static final String cTag = "TracksSynchronizer";
private static TracksSynchronizer synchronizer;
private static LinkedList<SyncProgressListener> progressListeners = new LinkedList<SyncProgressListener>();
private final Context mContext;
private final LinkedList<Integer> mMessages;
private final ContextSynchronizer mContextSynchronizer;
private final ProjectSynchronizer mProjectSynchronizer;
private final TaskSynchronizer mTaskSynchronizer;
private Analytics mAnalytics;
// TODO inject sync classes (BIG job)
public static TracksSynchronizer getActiveSynchronizer(
ContextWrapper context, Analytics analytics) throws ApiException {
TracksSynchronizer synchronizer = getSingletonSynchronizer(context, analytics);
while (synchronizer.getStatus() == Status.FINISHED) {
synchronizer = getSingletonSynchronizer(context, analytics);
}
return synchronizer;
}
private static TracksSynchronizer getSingletonSynchronizer(Context context, Analytics analytics) throws ApiException {
if (synchronizer == null || synchronizer.getStatus() == Status.FINISHED) {
synchronizer = new TracksSynchronizer(
context, analytics,
new WebClient(context, Preferences.getTracksUser(context),
Preferences.getTracksPassword(context), Preferences.isTracksSelfSignedCert(context)),
Preferences.getTracksUrl(context)
);
}
return synchronizer;
}
private TracksSynchronizer(
Context context,
Analytics analytics,
WebClient client,
String tracksUrl) {
mContext = context;
//TODO inject this
ContentResolverProvider provider = new ContentResolverProvider() {
@Override
public ContentResolver get() {
return mContext.getContentResolver();
}
};
mAnalytics = analytics;
EntityPersister<Task> taskPersister = new TaskPersister(provider, analytics);
EntityPersister<org.dodgybits.shuffle.android.core.model.Context> contextPersister = new ContextPersister(provider, analytics);
EntityPersister<Project> projectPersister = new ProjectPersister(provider, analytics);
mContextSynchronizer = new ContextSynchronizer(contextPersister, this, client, context, mAnalytics, 0, tracksUrl);
mProjectSynchronizer = new ProjectSynchronizer(projectPersister, this, client, context, mAnalytics, 33, tracksUrl);
mTaskSynchronizer = new TaskSynchronizer(taskPersister, this, client, context, mAnalytics, 66, tracksUrl);
mMessages = new LinkedList<Integer>();
}
@Override
protected void onProgressUpdate(Progress... progresses) {
for (SyncProgressListener listener : progressListeners) {
listener.progressUpdate(progresses[0]);
}
}
public void registerListener(SyncProgressListener listener) {
if (!progressListeners.contains(listener))
progressListeners.add(listener);
}
public void unRegisterListener(SyncProgressListener
listener) {
progressListeners.remove(listener);
}
@Override
protected Void doInBackground(String... strings) {
try {
mAnalytics.onEvent(cFlurryTracksSyncStartedEvent);
mContextSynchronizer.synchronize();
mProjectSynchronizer.synchronize();
mTaskSynchronizer.synchronize();
publishProgress(Progress.createProgress(100, "Synchronization Complete"));
mAnalytics.onEvent(cFlurryTracksSyncCompletedEvent);
} catch (ApiException e) {
Log.w(cTag, "Tracks call failed", e);
publishProgress(Progress.createErrorProgress(mContext.getString(R.string.web_error_message)));
mAnalytics.onError(cFlurryTracksSyncError, e.getMessage(), getClass().getName());
} catch (Exception e) {
Log.w(cTag, "Synch failed", e);
publishProgress(Progress.createErrorProgress(mContext.getString(R.string.error_message)));
mAnalytics.onError(cFlurryTracksSyncError, e.getMessage(), getClass().getName());
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if (mMessages.size() > 0) {
for (Integer textId : mMessages) {
Toast toast = Toast.makeText(mContext.getApplicationContext(), textId
, Toast.LENGTH_SHORT);
toast.show();
}
}
try {
synchronizer = getSingletonSynchronizer(mContext, mAnalytics);
} catch (ApiException ignored) {
}
}
public void reportProgress(Progress progress) {
publishProgress(progress);
}
public void postSyncMessage(int toastMessage) {
mMessages.add(toastMessage);
}
} | 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/TracksSynchronizer.java | Java | asf20 | 6,500 |
package org.dodgybits.shuffle.android.synchronisation.tracks;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.dodgybits.shuffle.android.core.model.EntityBuilder;
import org.dodgybits.shuffle.android.core.model.Id;
import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister;
import org.dodgybits.shuffle.android.persistence.provider.ContextProvider;
import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider;
import org.dodgybits.shuffle.android.preference.view.Progress;
import org.dodgybits.shuffle.android.synchronisation.tracks.ApiException;
import org.dodgybits.shuffle.android.synchronisation.tracks.model.TracksEntity;
import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.IContextLookup;
import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.IProjectLookup;
import org.dodgybits.shuffle.android.synchronisation.tracks.parsing.Parser;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;
/**
* Base class for handling synchronization, template method object.
*
* @author Morten Nielsen
*/
public abstract class Synchronizer<Entity extends TracksEntity> implements IProjectLookup,IContextLookup {
private static final String cTag = "Synchronizer";
protected EntityPersister<Entity> mPersister;
protected WebClient mWebClient;
protected android.content.Context mContext;
protected final TracksSynchronizer mTracksSynchronizer;
private int mBasePercent;
public Synchronizer(
EntityPersister<Entity> persister,
TracksSynchronizer tracksSynchronizer,
WebClient client,
android.content.Context context,
int basePercent) {
mPersister = persister;
mTracksSynchronizer = tracksSynchronizer;
mWebClient = client;
mContext = context;
mBasePercent = basePercent;
}
public void synchronize() throws ApiException {
mTracksSynchronizer.reportProgress(Progress.createProgress(mBasePercent,
readingLocalText()));
Map<Id, Entity> localEntities = getShuffleEntities();
verifyEntitiesForSynchronization(localEntities);
mTracksSynchronizer.reportProgress(Progress.createProgress(mBasePercent,
readingRemoteText()));
TracksEntities<Entity> tracksEntities = getTrackEntities();
mergeAlreadySynchronizedEntities(localEntities, tracksEntities);
addNewEntitiesToShuffle(tracksEntities);
mTracksSynchronizer.reportProgress(Progress.createProgress(
mBasePercent + 33, stageFinishedText()));
}
private void mergeAlreadySynchronizedEntities(
Map<Id, Entity> localEntities, TracksEntities<Entity> tracksEntities) {
int startCounter = localEntities.size() + 1;
int count = 0;
for (Entity localEntity : localEntities.values()) {
count++;
mTracksSynchronizer.reportProgress(Progress.createProgress(calculatePercent(startCounter, count),
processingText()));
mergeSingle(tracksEntities, localEntity);
}
}
private int calculatePercent(int startCounter, int count) {
int percent = mBasePercent
+ Math.round(((count * 100) / startCounter) * 0.33f);
return percent;
}
private void addNewEntitiesToShuffle(TracksEntities<Entity> tracksEntities) {
for (Entity remoteEntity : tracksEntities.getEntities().values()) {
insertEntity(remoteEntity);
}
}
public Id findProjectIdByTracksId(Id tracksId) {
return findEntityLocalIdByTracksId(tracksId, ProjectProvider.Projects.CONTENT_URI);
}
public Id findContextIdByTracksId(Id tracksId) {
return findEntityLocalIdByTracksId(tracksId, ContextProvider.Contexts.CONTENT_URI);
}
protected Id findTracksIdByProjectId(Id projectId) {
return findEntityTracksIdByLocalId(projectId, ProjectProvider.Projects.CONTENT_URI);
}
protected Id findTracksIdByContextId(Id contextId) {
return findEntityTracksIdByLocalId(contextId, ContextProvider.Contexts.CONTENT_URI);
}
protected abstract void verifyEntitiesForSynchronization(Map<Id, Entity> localEntities);
protected abstract String readingRemoteText();
protected abstract String processingText();
protected abstract String readingLocalText();
protected abstract String stageFinishedText();
protected abstract String entityIndexUrl();
protected abstract Entity createMergedLocalEntity(Entity localEntity,
Entity newEntity);
protected abstract String createEntityUrl(Entity localEntity);
protected abstract String createDocumentForEntity(Entity localEntity);
protected abstract EntityBuilder<Entity> createBuilder();
private TracksEntities<Entity> getTrackEntities() throws ApiException {
String tracksEntityXml;
try {
WebResult result = mWebClient.getUrlContent(entityIndexUrl());
StatusLine status = result.getStatus();
if(status.getStatusCode() == HttpStatus.SC_OK)
tracksEntityXml = result.getContent();
else
throw
new ApiException("Invalid response from server: " +
status.toString());
} catch (ApiException e) {
Log.w(cTag, e);
throw e;
}
return getEntityParser().parseDocument(tracksEntityXml);
}
protected abstract Parser<Entity> getEntityParser();
private Id findEntityLocalIdByTracksId(Id tracksId, Uri contentUri) {
Id id = Id.NONE;
Cursor cursor = mContext.getContentResolver().query(
contentUri,
new String[] { BaseColumns._ID},
"tracks_id = ?",
new String[] {tracksId.toString()},
null);
if (cursor.moveToFirst()) {
id = Id.create(cursor.getLong(0));
}
cursor.close();
return id;
}
private Id findEntityTracksIdByLocalId(Id localId, Uri contentUri) {
Id id = Id.NONE;
Cursor cursor = mContext.getContentResolver().query(
contentUri,
new String[] { "tracks_id" },
BaseColumns._ID + " = ?",
new String[] {localId.toString()},
null);
if (cursor.moveToFirst()) {
id = Id.create(cursor.getLong(0));
}
cursor.close();
return id;
}
private void insertEntity(Entity entity) {
mPersister.insert(entity);
}
private void updateEntity(Entity entity) {
mPersister.update(entity);
}
protected boolean deleteEntity(Entity entity)
{
return mPersister.updateDeletedFlag(entity.getLocalId(), true);
}
private Entity findEntityByLocalName(Collection<Entity> remoteEntities,
Entity localEntity) {
Entity foundEntity = null;
for (Entity entity : remoteEntities)
if (entity.getLocalName().equals(localEntity.getLocalName())) {
foundEntity = entity;
}
return foundEntity;
}
private void mergeSingle(TracksEntities<Entity> tracksEntities,
Entity localEntity) {
final Map<Id, Entity> remoteEntities = tracksEntities.getEntities();
if (!localEntity.getTracksId().isInitialised()) {
handleLocalEntityNotYetInTracks(localEntity, remoteEntities);
return;
}
Entity remoteEntity = remoteEntities.get(localEntity.getTracksId());
if (remoteEntity != null) {
mergeLocalAndRemoteEntityBasedOnModifiedDate(localEntity, remoteEntity);
remoteEntities.remove(remoteEntity.getTracksId());
} else if (tracksEntities.isErrorFree()){
// only delete entities if we didn't encounter errors parsing
deleteEntity(localEntity);
}
}
private void handleLocalEntityNotYetInTracks(Entity localEntity,
final Map<Id, Entity> remoteEntities) {
Entity newEntity = findEntityByLocalName(remoteEntities.values(),
localEntity);
if (newEntity != null) {
remoteEntities.remove(newEntity.getTracksId());
} else {
newEntity = createEntityInTracks(localEntity);
}
if (newEntity != null) {
updateEntity(createMergedLocalEntity(localEntity, newEntity));
}
}
private void mergeLocalAndRemoteEntityBasedOnModifiedDate(Entity localEntity, Entity remoteEntity) {
final long remoteModified = remoteEntity.getModifiedDate();
final long localModified = localEntity.getModifiedDate();
if (remoteModified == localModified && remoteEntity.isDeleted() == localEntity.isDeleted())
return;
if (remoteModified >= localModified) {
updateEntity(createMergedLocalEntity(localEntity, remoteEntity));
} else {
updateTracks(localEntity);
}
}
private void updateTracks(Entity localEntity) {
String document = createDocumentForEntity(localEntity);
try {
mWebClient.putContentToUrl(createEntityUrl(localEntity), document);
} catch (ApiException e) {
Log.w(cTag, "Failed to update entity in tracks " + localEntity + ":" + e.getMessage(), e);
}
}
private Entity createEntityInTracks(Entity entity) {
String document = createDocumentForEntity(entity);
try {
String location = mWebClient.postContentToUrl(entityIndexUrl(),
document);
if (!TextUtils.isEmpty(location.trim())) {
Id id = parseIdFromLocation(location);
EntityBuilder<Entity> builder = createBuilder();
builder.mergeFrom(entity);
builder.setTracksId(id);
entity = builder.build();
}
} catch (ApiException e) {
Log.w(cTag, "Failed to create entity in tracks " + entity + ":" + e.getMessage(), e);
}
return entity;
}
private Id parseIdFromLocation(String location) {
String[] parts = location.split("/");
String document = parts[parts.length - 1];
long id = Long.parseLong( document );
return Id.create(id);
}
private Map<Id, Entity> getShuffleEntities() {
Map<Id, Entity> list = new HashMap<Id, Entity>();
Cursor cursor = mContext.getContentResolver().query(
mPersister.getContentUri(),
mPersister.getFullProjection(),
null, null, null);
while (cursor.moveToNext()) {
Entity entity = mPersister.read(cursor);
list.put(entity.getLocalId(), entity);
}
cursor.close();
return list;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/Synchronizer.java | Java | asf20 | 11,087 |
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing;
public class ParseResult<T> {
private boolean mSuccess;
private T mResult;
public ParseResult(T result, boolean success) {
mSuccess = success;
mResult = result;
}
public ParseResult() {
mSuccess = false;
mResult = null;
}
public T getResult() {
return mResult;
}
public boolean isSuccess(){
return mSuccess;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/parsing/ParseResult.java | Java | asf20 | 436 |
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing;
public interface Applier {
boolean apply(String value);
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/parsing/Applier.java | Java | asf20 | 135 |
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing;
import java.text.ParseException;
import org.dodgybits.shuffle.android.core.activity.flurry.Analytics;
import org.dodgybits.shuffle.android.core.model.EntityBuilder;
import org.dodgybits.shuffle.android.core.model.Id;
import org.dodgybits.shuffle.android.core.model.Project;
import org.dodgybits.shuffle.android.core.model.Project.Builder;
import org.dodgybits.shuffle.android.core.util.DateUtils;
import android.text.TextUtils;
import android.util.Log;
public class ProjectParser extends Parser<Project> {
private Builder specificBuilder;
private IContextLookup mContextLookup;
public ProjectParser(IContextLookup contextLookup, Analytics analytics) {
super("project", analytics);
mContextLookup = contextLookup;
appliers.put("name",
new Applier(){
@Override
public boolean apply(String value) {
specificBuilder.setName(value);
return true;
}
});
appliers.put("state",
new Applier(){
@Override
public boolean apply(String value) {
String v = value.toLowerCase();
Log.d("projectparser",v);
if(v.equals("completed")) {
// ignore completed for now?
// specificBuilder.setDeleted(true);
return true;
}
if(v.equals("hidden")) {
specificBuilder.setActive(false);
return true;
}
if(v.equals("active")) {
specificBuilder.setActive(true);
return true;
}
return false;
}
});
appliers.put("id",
new Applier(){
@Override
public boolean apply(String value) {
Id tracksId = Id.create(Long.parseLong(value));
specificBuilder.setTracksId(tracksId);
return true;
}
});
appliers.put("updated-at",
new Applier(){
@Override
public boolean apply(String value) {
long date;
try {
date = DateUtils.parseIso8601Date(value);
specificBuilder.setModifiedDate(date);
return true;
} catch (ParseException e) {
return false;
}
}
});
appliers.put("default-context-id",
new Applier(){
@Override
public boolean apply(String value) {
if (!TextUtils.isEmpty(value)) {
Id tracksId = Id.create(Long.parseLong(value));
Id defaultContextId = mContextLookup.findContextIdByTracksId(tracksId);
if (defaultContextId.isInitialised()) {
specificBuilder.setDefaultContextId(defaultContextId);
}
}
return true;
}
});
}
@Override
protected EntityBuilder<Project> createBuilder() {
return specificBuilder = Project.newBuilder();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/parsing/ProjectParser.java | Java | asf20 | 3,070 |
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing;
import java.text.ParseException;
import org.dodgybits.shuffle.android.core.activity.flurry.Analytics;
import org.dodgybits.shuffle.android.core.model.EntityBuilder;
import org.dodgybits.shuffle.android.core.model.Id;
import org.dodgybits.shuffle.android.core.model.Task;
import org.dodgybits.shuffle.android.core.model.Task.Builder;
import org.dodgybits.shuffle.android.core.util.DateUtils;
import android.text.TextUtils;
import roboguice.util.Ln;
public class TaskParser extends Parser<Task> {
private Builder specificBuilder;
protected IContextLookup mContextLookup;
protected IProjectLookup mProjectLookup;
public TaskParser(IContextLookup contextLookup, IProjectLookup projectLookup, Analytics analytics) {
super("todo", analytics);
mContextLookup = contextLookup;
mProjectLookup = projectLookup;
appliers.put("state", new Applier() {
@Override
public boolean apply(String value) {
Ln.d("Got status %s", value);
if( value.equals("completed")) {
specificBuilder.setComplete(true);
}
return true;
}
});
appliers.put("description",
new Applier(){
@Override
public boolean apply(String value) {
specificBuilder.setDescription(value);
return true;
}
});
appliers.put("notes",
new Applier(){
@Override
public boolean apply(String value) {
specificBuilder.setDetails(value);
return true;
}
});
appliers.put("id",
new Applier(){
@Override
public boolean apply(String value) {
Id tracksId = Id.create(Long.parseLong(value));
specificBuilder.setTracksId(tracksId);
return true;
}
});
appliers.put("updated-at",
new Applier(){
@Override
public boolean apply(String value) {
long date;
try {
date = DateUtils.parseIso8601Date(value);
specificBuilder.setModifiedDate(date);
return true;
} catch (ParseException e) {
return false;
}
}
});
appliers.put("context-id",
new Applier(){
@Override
public boolean apply(String value) {
if (!TextUtils.isEmpty(value)) {
Id tracksId = Id.create(Long.parseLong(value));
Id context = mContextLookup.findContextIdByTracksId(tracksId);
if (context.isInitialised()) {
specificBuilder.setContextId(context);
}
}
return true;
}
});
appliers.put("project-id",
new Applier(){
@Override
public boolean apply(String value) {
if (!TextUtils.isEmpty(value)) {
Id tracksId = Id.create(Long.parseLong(value));
Id project = mProjectLookup.findProjectIdByTracksId(tracksId);
if (project.isInitialised()) {
specificBuilder.setProjectId(project);
}
}
return true;
}
});
appliers.put("created-at",
new Applier(){
@Override
public boolean apply(String value) {
if (!TextUtils.isEmpty(value)) {
try {
long created = DateUtils.parseIso8601Date(value);
specificBuilder.setCreatedDate(created);
} catch (ParseException e) {
// TODO Auto-generated catch block
return false;
}
}
return true;
}
});
appliers.put("due",
new Applier(){
@Override
public boolean apply(String value) {
if (!TextUtils.isEmpty(value)) {
try {
long due = DateUtils.parseIso8601Date(value);
specificBuilder.setDueDate(due);
} catch (ParseException e) {
// TODO Auto-generated catch block
return false;
}
}
return true;
}
});
appliers.put("show-from",
new Applier(){
@Override
public boolean apply(String value) {
if (!TextUtils.isEmpty(value)) {
try {
long showFrom = DateUtils.parseIso8601Date(value);
specificBuilder.setStartDate(showFrom);
} catch (ParseException e) {
// TODO Auto-generated catch block
return false;
}
}
return true;
}
});
}
@Override
protected EntityBuilder<Task> createBuilder() {
return specificBuilder = Task.newBuilder();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/parsing/TaskParser.java | Java | asf20 | 5,050 |
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing;
import java.text.ParseException;
import org.dodgybits.shuffle.android.core.activity.flurry.Analytics;
import org.dodgybits.shuffle.android.core.model.Context;
import org.dodgybits.shuffle.android.core.model.EntityBuilder;
import org.dodgybits.shuffle.android.core.model.Id;
import org.dodgybits.shuffle.android.core.model.Context.Builder;
import org.dodgybits.shuffle.android.core.util.DateUtils;
public class ContextParser extends Parser<Context> {
private Builder specificBuilder;
public ContextParser(Analytics analytics) {
super("context", analytics);
appliers.put("name",
new Applier(){
@Override
public boolean apply(String value) {
specificBuilder.setName(value);
return true;
}
});
appliers.put("hide",
new Applier(){
@Override
public boolean apply(String value) {
boolean v = Boolean.parseBoolean(value);
specificBuilder.setActive(!v);
return true;
}
});
appliers.put("id",
new Applier(){
@Override
public boolean apply(String value) {
Id tracksId = Id.create(Long.parseLong(value));
specificBuilder.setTracksId(tracksId);
return true;
}
});
appliers.put("updated-at",
new Applier(){
@Override
public boolean apply(String value) {
long date;
try {
date = DateUtils.parseIso8601Date(value);
specificBuilder.setModifiedDate(date);
return true;
} catch (ParseException e) {
return false;
}
}
});
}
@Override
protected EntityBuilder<Context> createBuilder() {
return specificBuilder = Context.newBuilder();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/parsing/ContextParser.java | Java | asf20 | 1,889 |
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing;
import org.dodgybits.shuffle.android.core.model.Id;
public interface IProjectLookup {
Id findProjectIdByTracksId(Id tracksId);
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/parsing/IProjectLookup.java | Java | asf20 | 213 |
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing;
import org.dodgybits.shuffle.android.core.model.Id;
public interface IContextLookup {
Id findContextIdByTracksId(Id tracksId);
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/parsing/IContextLookup.java | Java | asf20 | 213 |
package org.dodgybits.shuffle.android.synchronisation.tracks.parsing;
import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryTracksSyncError;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import org.dodgybits.shuffle.android.core.activity.flurry.Analytics;
import org.dodgybits.shuffle.android.core.model.EntityBuilder;
import org.dodgybits.shuffle.android.core.model.Id;
import org.dodgybits.shuffle.android.synchronisation.tracks.TracksEntities;
import org.dodgybits.shuffle.android.synchronisation.tracks.model.TracksEntity;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Log;
import android.util.Xml;
public abstract class Parser<E extends TracksEntity> {
private static final String cTag = "Parser";
protected HashMap<String, Applier> appliers;
private String mEntityName;
private Analytics mAnalytics;
public Parser(String entityName, Analytics analytics) {
appliers = new HashMap<String, Applier>();
mEntityName = entityName;
mAnalytics = analytics;
}
public TracksEntities<E> parseDocument(String tracksEntityXml) {
Map<Id, E> entities = new HashMap<Id, E>();
boolean errorFree = true;
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(new StringReader(tracksEntityXml));
int eventType = parser.getEventType();
boolean done = false;
while (eventType != XmlPullParser.END_DOCUMENT && !done) {
ParseResult<E> result = null;
try {
result = parseSingle(parser);
} catch (Exception e) {
logTracksError(e);
errorFree = false;
}
if(!result.isSuccess()) {
errorFree = false;
}
E entity = result.getResult();
if (entity != null && entity.isValid()) {
entities.put(entity.getTracksId(), entity);
}
eventType = parser.getEventType();
String name = parser.getName();
if (eventType == XmlPullParser.END_TAG &&
name.equalsIgnoreCase(endIndexTag())) {
done = true;
}
}
} catch (XmlPullParserException e) {
logTracksError(e);
errorFree = false;
}
return new TracksEntities<E>(entities, errorFree);
}
private void logTracksError(Exception e) {
Log.e(cTag, "Failed to parse " + endIndexTag() + " " + e.getMessage());
mAnalytics.onError(cFlurryTracksSyncError, e.getMessage(), getClass().getName());
}
private String endIndexTag() {
return this.mEntityName + "s";
}
public ParseResult<E> parseSingle(XmlPullParser parser) {
EntityBuilder<E> builder = createBuilder();
E entity = null;
boolean success = true;
try {
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT && entity == null) {
String name = parser.getName();
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
Applier applier = appliers.get(name);
if(applier != null) {
success &= applier.apply(parser.nextText());
}
break;
case XmlPullParser.END_TAG:
if (name.equalsIgnoreCase(mEntityName)) {
entity = builder.build();
}
break;
}
eventType = parser.next();
}
} catch (IOException e) {
Log.d("Exception", "IO EXception", e);
return new ParseResult<E>();
} catch (XmlPullParserException e) {
Log.d("Exception", "pullparser exception", e);
return new ParseResult<E>();
}
return new ParseResult<E>(entity, success);
}
protected abstract EntityBuilder<E> createBuilder();
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/parsing/Parser.java | Java | asf20 | 4,567 |
package org.dodgybits.shuffle.android.synchronisation.tracks.model;
import org.dodgybits.shuffle.android.core.model.Entity;
import org.dodgybits.shuffle.android.core.model.Id;
public interface TracksEntity extends Entity {
Id getTracksId();
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/model/TracksEntity.java | Java | asf20 | 251 |
package org.dodgybits.shuffle.android.synchronisation.tracks.activity;
import javax.annotation.Nullable;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.activity.flurry.Analytics;
import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity;
import org.dodgybits.shuffle.android.preference.model.Preferences;
import org.dodgybits.shuffle.android.preference.view.Progress;
import org.dodgybits.shuffle.android.synchronisation.tracks.ApiException;
import org.dodgybits.shuffle.android.synchronisation.tracks.SyncProgressListener;
import org.dodgybits.shuffle.android.synchronisation.tracks.TracksSynchronizer;
import roboguice.inject.InjectView;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.inject.Inject;
/**
* Activity to handle synchronization
*
* @author Morten Nielsen
*/
public class SynchronizeActivity extends FlurryEnabledActivity implements SyncProgressListener {
private TracksSynchronizer synchronizer = null;
@InjectView(R.id.info_text) @Nullable TextView mInfo;
@InjectView(R.id.progress_horizontal) @Nullable ProgressBar mProgress;
@Inject Analytics mAnalytics;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.synchronize);
setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
super.onCreate(savedInstanceState);
TextView url = (TextView) findViewById(R.id.syncUrl);
TextView user = (TextView) findViewById(R.id.syncUser);
url.setText(Preferences.getTracksUrl(this));
user.setText(Preferences.getTracksUser(this));
}
@Override
public void onResume() {
super.onResume();
try {
synchronizer = TracksSynchronizer.getActiveSynchronizer(this, mAnalytics);
} catch (ApiException ignored) {
}
if (synchronizer != null) {
synchronizer.registerListener(this);
if (synchronizer.getStatus() != AsyncTask.Status.RUNNING) {
synchronizer.execute();
}
}
}
@Override
public void onPause() {
super.onPause();
if (synchronizer != null) {
synchronizer.unRegisterListener(this);
}
}
@Override
public void progressUpdate(Progress progress) {
if (mInfo != null) {
mInfo.setText(progress.getDetails());
}
if (mProgress != null) {
mProgress.setProgress(progress.getProgressPercent());
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/tracks/activity/SynchronizeActivity.java | Java | asf20 | 2,654 |
/*
* Copyright 2011 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 org.dodgybits.shuffle.android.synchronisation.gae;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
/**
* Display a message as a notification, with an accompanying sound.
*/
public class MessageDisplay {
private MessageDisplay() {
}
/*
* App-specific methods for the sample application - 1) parse the incoming
* message; 2) generate a notification; 3) play a sound
*/
public static void displayMessage(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
String sender = (String) extras.get("sender");
String message = (String) extras.get("message");
Util.generateNotification(context, "Message from " + sender + ": " + message);
playNotificationSound(context);
}
}
private static void playNotificationSound(Context context) {
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (uri != null) {
Ringtone rt = RingtoneManager.getRingtone(context, uri);
if (rt != null) {
rt.setStreamType(AudioManager.STREAM_NOTIFICATION);
rt.play();
}
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/gae/MessageDisplay.java | Java | asf20 | 1,992 |
/*
* Copyright 2010 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 org.dodgybits.shuffle.android.synchronisation.gae;
import com.google.web.bindery.requestfactory.shared.RequestTransport;
import com.google.web.bindery.requestfactory.shared.ServerFailure;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
/**
* An implementation of RequestTransport for use between an Android client and a
* Google AppEngine server.
*/
public class AndroidRequestTransport implements RequestTransport {
private final URI uri;
private final String cookie;
/**
* Constructs an AndroidRequestTransport instance.
*
* @param uri the URI for the RequestFactory service
* @param cookie the ACSID or SACSID cookie used for authentication
*/
public AndroidRequestTransport(URI uri, String cookie) {
this.uri = uri;
this.cookie = cookie;
}
public void send(String payload, TransportReceiver receiver) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost();
post.setHeader("Content-Type", "application/json;charset=UTF-8");
post.setHeader("Cookie", cookie);
post.setURI(uri);
Throwable ex;
try {
post.setEntity(new StringEntity(payload, "UTF-8"));
HttpResponse response = client.execute(post);
if (200 == response.getStatusLine().getStatusCode()) {
String contents = readStreamAsString(response.getEntity().getContent());
receiver.onTransportSuccess(contents);
} else {
receiver.onTransportFailure(new ServerFailure(response.getStatusLine()
.getReasonPhrase()));
}
return;
} catch (UnsupportedEncodingException e) {
ex = e;
} catch (ClientProtocolException e) {
ex = e;
} catch (IOException e) {
ex = e;
}
receiver.onTransportFailure(new ServerFailure(ex.getMessage()));
}
/**
* Reads an entire input stream as a String. Closes the input stream.
*/
private String readStreamAsString(InputStream in) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int count;
do {
count = in.read(buffer);
if (count > 0) {
out.write(buffer, 0, count);
}
} while (count >= 0);
return out.toString("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("The JVM does not support the compiler's default encoding.",
e);
} catch (IOException e) {
return null;
} finally {
try {
in.close();
} catch (IOException ignored) {
}
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/gae/AndroidRequestTransport.java | Java | asf20 | 3,862 |
/*
* Copyright 2011 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 org.dodgybits.shuffle.android.synchronisation.gae;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.preference.model.Preferences;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import com.google.web.bindery.event.shared.SimpleEventBus;
import com.google.web.bindery.requestfactory.shared.RequestFactory;
import com.google.web.bindery.requestfactory.vm.RequestFactorySource;
/**
* Utility methods for getting the base URL for client-server communication.
*/
public class Util {
/**
* Tag for logging.
*/
private static final String TAG = "Util";
/*
* URL suffix for the RequestFactory servlet.
*/
public static final String RF_METHOD = "/gwtRequest";
/**
* An intent name for receiving registration/unregistration status.
*/
public static final String UPDATE_UI_INTENT = "org.dodgybits.android.shuffle.UPDATE_UI";
// End shared constants
/**
* Cache containing the base URL for a given context.
*/
private static final Map<Context, String> URL_MAP = new HashMap<Context, String>();
/**
* Display a notification containing the given string.
*/
public static void generateNotification(Context context, String message) {
int icon = R.drawable.status_icon;
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, message, when);
notification.setLatestEventInfo(context, "C2DM Example", message,
PendingIntent.getActivity(context, 0, null, PendingIntent.FLAG_CANCEL_CURRENT));
notification.flags |= Notification.FLAG_AUTO_CANCEL;
int notificatonID = Preferences.getNotificationId(context);
NotificationManager nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(notificatonID, notification);
Preferences.incrementNotificationId(context);
}
/**
* Returns the (debug or production) URL associated with the registration
* service.
*/
public static String getBaseUrl(Context context) {
String url = URL_MAP.get(context);
if (url == null) {
// if a debug_url raw resource exists, use its contents as the url
url = getDebugUrl(context);
// otherwise, use the production url
if (url == null) {
url = Setup.PROD_URL;
}
URL_MAP.put(context, url);
}
return url;
}
/**
* Creates and returns an initialized {@link RequestFactory} of the given
* type.
*/
public static <T extends RequestFactory> T getRequestFactory(Context context,
Class<T> factoryClass) {
T requestFactory = RequestFactorySource.create(factoryClass);
String authCookie = Preferences.getGoogleAuthCookie(context);
String uriString = Util.getBaseUrl(context) + RF_METHOD;
URI uri;
try {
uri = new URI(uriString);
} catch (URISyntaxException e) {
Log.w(TAG, "Bad URI: " + uriString, e);
return null;
}
requestFactory.initialize(new SimpleEventBus(),
new AndroidRequestTransport(uri, authCookie));
return requestFactory;
}
/**
* Returns true if we are running against a dev mode appengine instance.
*/
public static boolean isDebug(Context context) {
// Although this is a bit roundabout, it has the nice side effect
// of caching the result.
return !Setup.PROD_URL.equals(getBaseUrl(context));
}
/**
* Returns a debug url, or null. To set the url, create a file
* {@code assets/debugging_prefs.properties} with a line of the form
* 'url=http:/<ip address>:<port>'. A numeric IP address may be required in
* situations where the device or emulator will not be able to resolve the
* hostname for the dev mode server.
*/
private static String getDebugUrl(Context context) {
BufferedReader reader = null;
String url = null;
try {
AssetManager assetManager = context.getAssets();
InputStream is = assetManager.open("debugging_prefs.properties");
reader = new BufferedReader(new InputStreamReader(is));
while (true) {
String s = reader.readLine();
if (s == null) {
break;
}
if (s.startsWith("url=")) {
url = s.substring(4).trim();
break;
}
}
} catch (FileNotFoundException e) {
// O.K., we will use the production server
return null;
} catch (Exception e) {
Log.w(TAG, "Got exception " + e);
Log.w(TAG, Log.getStackTraceString(e));
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.w(TAG, "Got exception " + e);
Log.w(TAG, Log.getStackTraceString(e));
}
}
}
return url;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/gae/Util.java | Java | asf20 | 6,250 |
/*
* Copyright 2010 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 org.dodgybits.shuffle.android.synchronisation.gae;
import java.io.IOException;
import org.dodgybits.shuffle.android.preference.model.Preferences;
import android.content.Context;
import android.content.Intent;
import com.google.android.c2dm.C2DMBaseReceiver;
/**
* Receive a push message from the Cloud to Device Messaging (C2DM) service.
* This class should be modified to include functionality specific to your
* application. This class must have a no-arg constructor and pass the sender id
* to the superclass constructor.
*/
public class C2DMReceiver extends C2DMBaseReceiver {
public C2DMReceiver() {
super(Setup.SENDER_ID);
}
/**
* Called when a registration token has been received.
*
* @param context the Context
* @param registrationId the registration id as a String
* @throws IOException if registration cannot be performed
*/
@Override
public void onRegistered(Context context, String registration) {
DeviceRegistrar.registerOrUnregister(context, registration, true);
}
/**
* Called when the device has been unregistered.
*
* @param context the Context
*/
@Override
public void onUnregistered(Context context) {
String deviceRegistrationID = Preferences.getGooglDeviceRegistrationId(context);
DeviceRegistrar.registerOrUnregister(context, deviceRegistrationID, false);
}
/**
* Called on registration error. This is called in the context of a Service
* - no dialog or UI.
*
* @param context the Context
* @param errorId an error message, defined in {@link C2DMBaseReceiver}
*/
@Override
public void onError(Context context, String errorId) {
context.sendBroadcast(new Intent(Util.UPDATE_UI_INTENT));
}
/**
* Called when a cloud message has been received.
*/
@Override
public void onMessage(Context context, Intent intent) {
/*
* Replace this with your application-specific code
*/
MessageDisplay.displayMessage(context, intent);
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/gae/C2DMReceiver.java | Java | asf20 | 2,699 |
/*
* Copyright 2010 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 org.dodgybits.shuffle.android.synchronisation.gae;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.preference.model.Preferences;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.google.android.c2dm.C2DMessaging;
/**
* Account selections activity - handles device registration and unregistration.
*/
public class AccountsActivity extends Activity {
/**
* Tag for logging.
*/
private static final String TAG = "AccountsActivity";
/**
* Cookie name for authorization.
*/
private static final String AUTH_COOKIE_NAME = "SACSID";
/**
* The selected position in the ListView of accounts.
*/
private int mAccountSelectedPosition = 0;
/**
* True if we are waiting for App Engine authorization.
*/
private boolean mPendingAuth = false;
/**
* The current context.
*/
private Context mContext = this;
/**
* Begins the activity.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setScreenContent();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
setScreenContent();
return true;
}
/**
* Resumes the activity.
*/
@Override
protected void onResume() {
super.onResume();
if (mPendingAuth) {
mPendingAuth = false;
String regId = C2DMessaging.getRegistrationId(mContext);
if (regId != null && !"".equals(regId)) {
DeviceRegistrar.registerOrUnregister(mContext, regId, true);
} else {
C2DMessaging.register(mContext, Setup.SENDER_ID);
}
}
}
// Manage UI Screens
/**
* Sets up the 'connect' screen content.
*/
private void setConnectScreenContent() {
List<String> accounts = getGoogleAccounts();
if (accounts.size() == 0) {
// Show a dialog and invoke the "Add Account" activity if requested
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage(R.string.needs_account);
builder.setPositiveButton(R.string.add_account, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Settings.ACTION_ADD_ACCOUNT));
}
});
builder.setNegativeButton(R.string.skip, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setIcon(android.R.drawable.stat_sys_warning);
builder.setTitle(R.string.attention);
builder.show();
} else {
final ListView listView = (ListView) findViewById(R.id.select_account);
listView.setAdapter(new ArrayAdapter<String>(mContext, R.layout.account, accounts));
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setItemChecked(mAccountSelectedPosition, true);
final Button connectButton = (Button) findViewById(R.id.connect);
connectButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Register in the background and terminate the activity
mAccountSelectedPosition = listView.getCheckedItemPosition();
TextView account = (TextView) listView.getChildAt(mAccountSelectedPosition);
register((String) account.getText());
finish();
}
});
final Button exitButton = (Button) findViewById(R.id.exit);
exitButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}
/**
* Sets up the 'disconnected' screen.
*/
private void setDisconnectScreenContent() {
String accountName = Preferences.getGoogleAccountName(mContext);
// Format the disconnect message with the currently connected account
// name
TextView disconnectText = (TextView) findViewById(R.id.disconnect_text);
String message = getResources().getString(R.string.disconnect_text);
String formatted = String.format(message, accountName);
disconnectText.setText(formatted);
Button disconnectButton = (Button) findViewById(R.id.disconnect);
disconnectButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Delete the current account from shared preferences
Editor editor = Preferences.getEditor(mContext);
editor.putString(Preferences.GOOGLE_AUTH_COOKIE, null);
editor.putString(Preferences.GOOGLE_DEVICE_REGISTRATION_ID, null);
editor.commit();
// Unregister in the background and terminate the activity
C2DMessaging.unregister(mContext);
finish();
}
});
Button exitButton = (Button) findViewById(R.id.exit);
exitButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
/**
* Sets the screen content based on whether a device id is set already.
*/
private void setScreenContent() {
String deviceRegistrationID = Preferences.getGooglDeviceRegistrationId(mContext);
if (deviceRegistrationID == null) {
// Show the 'connect' screen if we are not connected
setContentView(R.layout.connect);
setConnectScreenContent();
} else {
// Show the 'disconnect' screen if we are connected
setContentView(R.layout.disconnect);
setDisconnectScreenContent();
}
}
// Register and Unregister
/**
* Registers for C2DM messaging with the given account name.
*
* @param accountName a String containing a Google account name
*/
private void register(final String accountName) {
// Store the account name in shared preferences
SharedPreferences.Editor editor = Preferences.getEditor(mContext);
editor.putString(Preferences.GOOGLE_ACCOUNT_NAME, accountName);
editor.putString(Preferences.GOOGLE_AUTH_COOKIE, null);
editor.commit();
// Obtain an auth token and register
AccountManager mgr = AccountManager.get(mContext);
Account[] accts = mgr.getAccountsByType("com.google");
for (Account acct : accts) {
if (acct.name.equals(accountName)) {
if (Util.isDebug(mContext)) {
// Use a fake cookie for the dev mode app engine server
// The cookie has the form email:isAdmin:userId
// We set the userId to be the same as the account name
String authCookie = "dev_appserver_login=" + accountName + ":false:"
+ accountName;
Preferences.getEditor(mContext).putString(Preferences.GOOGLE_AUTH_COOKIE, authCookie).commit();
C2DMessaging.register(mContext, Setup.SENDER_ID);
} else {
// Get the auth token from the AccountManager and convert
// it into a cookie for the appengine server
mgr.getAuthToken(acct, "ah", null, this, new AccountManagerCallback<Bundle>() {
public void run(AccountManagerFuture<Bundle> future) {
try {
Bundle authTokenBundle = future.getResult();
String authToken = authTokenBundle
.get(AccountManager.KEY_AUTHTOKEN).toString();
String authCookie = getAuthCookie(authToken);
Preferences.getEditor(mContext).putString(Preferences.GOOGLE_AUTH_COOKIE, authCookie).commit();
C2DMessaging.register(mContext, Setup.SENDER_ID);
} catch (AuthenticatorException e) {
Log.w(TAG, "Got AuthenticatorException " + e);
Log.w(TAG, Log.getStackTraceString(e));
} catch (IOException e) {
Log.w(TAG, "Got IOException " + Log.getStackTraceString(e));
Log.w(TAG, Log.getStackTraceString(e));
} catch (OperationCanceledException e) {
Log.w(TAG, "Got OperationCanceledException " + e);
Log.w(TAG, Log.getStackTraceString(e));
}
}
}, null);
}
break;
}
}
}
// Utility Methods
/**
* Retrieves the authorization cookie associated with the given token. This
* method should only be used when running against a production appengine
* backend (as opposed to a dev mode server).
*/
private String getAuthCookie(String authToken) {
try {
// Get SACSID cookie
DefaultHttpClient client = new DefaultHttpClient();
String continueURL = Setup.PROD_URL;
URI uri = new URI(Setup.PROD_URL + "/_ah/login?continue="
+ URLEncoder.encode(continueURL, "UTF-8") + "&auth=" + authToken);
HttpGet method = new HttpGet(uri);
final HttpParams getParams = new BasicHttpParams();
HttpClientParams.setRedirecting(getParams, false);
method.setParams(getParams);
HttpResponse res = client.execute(method);
Header[] headers = res.getHeaders("Set-Cookie");
if (res.getStatusLine().getStatusCode() != 302 || headers.length == 0) {
return null;
}
for (Cookie cookie : client.getCookieStore().getCookies()) {
if (AUTH_COOKIE_NAME.equals(cookie.getName())) {
return AUTH_COOKIE_NAME + "=" + cookie.getValue();
}
}
} catch (IOException e) {
Log.w(TAG, "Got IOException " + e);
Log.w(TAG, Log.getStackTraceString(e));
} catch (URISyntaxException e) {
Log.w(TAG, "Got URISyntaxException " + e);
Log.w(TAG, Log.getStackTraceString(e));
}
return null;
}
/**
* Returns a list of registered Google account names. If no Google accounts
* are registered on the device, a zero-length list is returned.
*/
private List<String> getGoogleAccounts() {
ArrayList<String> result = new ArrayList<String>();
Account[] accounts = AccountManager.get(mContext).getAccounts();
for (Account account : accounts) {
if (account.type.equals("com.google")) {
result.add(account.name);
}
}
return result;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/gae/AccountsActivity.java | Java | asf20 | 13,250 |
/*
* Copyright 2010 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 org.dodgybits.shuffle.android.synchronisation.gae;
import org.dodgybits.shuffle.android.preference.model.Preferences;
import org.dodgybits.shuffle.client.ShuffleRequestFactory;
import org.dodgybits.shuffle.client.ShuffleRequestFactory.RegistrationInfoRequest;
import org.dodgybits.shuffle.shared.RegistrationInfoProxy;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.provider.Settings.Secure;
import android.util.Log;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.web.bindery.requestfactory.shared.ServerFailure;
/**
* Register/unregister with the third-party App Engine server using
* RequestFactory.
*/
public class DeviceRegistrar {
public static final String STATUS_EXTRA = "Status";
public static final int REGISTERED_STATUS = 1;
public static final int UNREGISTERED_STATUS = 2;
public static final int ERROR_STATUS = 3;
private static final String TAG = "DeviceRegistrar";
public static void registerOrUnregister(final Context context,
final String deviceRegistrationId, final boolean register) {
final Intent updateUIIntent = new Intent(Util.UPDATE_UI_INTENT);
RegistrationInfoRequest request = getRequest(context);
RegistrationInfoProxy proxy = request.create(RegistrationInfoProxy.class);
proxy.setDeviceRegistrationId(deviceRegistrationId);
String deviceId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
proxy.setDeviceId(deviceId);
Request<Void> req;
if (register) {
req = request.register().using(proxy);
} else {
req = request.unregister().using(proxy);
}
req.fire(new Receiver<Void>() {
@Override
public void onFailure(ServerFailure failure) {
Log.w(TAG, "Failure, got :" + failure.getMessage());
updateUIIntent.putExtra(STATUS_EXTRA, ERROR_STATUS);
context.sendBroadcast(updateUIIntent);
}
@Override
public void onSuccess(Void response) {
SharedPreferences.Editor editor = Preferences.getEditor(context);
if (register) {
editor.putString(Preferences.GOOGLE_DEVICE_REGISTRATION_ID, deviceRegistrationId);
} else {
editor.remove(Preferences.GOOGLE_DEVICE_REGISTRATION_ID);
}
editor.commit();
updateUIIntent.putExtra(STATUS_EXTRA, register ? REGISTERED_STATUS
: UNREGISTERED_STATUS);
context.sendBroadcast(updateUIIntent);
}
});
}
private static RegistrationInfoRequest getRequest(Context context) {
ShuffleRequestFactory requestFactory = Util.getRequestFactory(context, ShuffleRequestFactory.class);
RegistrationInfoRequest request = requestFactory.registrationInfoRequest();
return request;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/gae/DeviceRegistrar.java | Java | asf20 | 3,706 |
/*
* Copyright 2010 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 org.dodgybits.shuffle.android.synchronisation.gae;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.preference.model.Preferences;
import org.dodgybits.shuffle.client.ShuffleRequestFactory;
import org.dodgybits.shuffle.client.ShuffleRequestFactory.HelloWorldRequest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.ServerFailure;
/**
* Main activity - requests "Hello, World" messages from the server and provides
* a menu item to invoke the accounts activity.
*/
public class ShuffleActivity extends Activity {
/**
* Tag for logging.
*/
private static final String TAG = "ShuffleActivity";
/**
* The current context.
*/
private Context mContext = this;
/**
* A {@link BroadcastReceiver} to receive the response from a register or
* unregister request, and to update the UI.
*/
private final BroadcastReceiver mUpdateUIReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(DeviceRegistrar.STATUS_EXTRA,
DeviceRegistrar.ERROR_STATUS);
String message = null;
if (status == DeviceRegistrar.REGISTERED_STATUS) {
message = getResources().getString(R.string.registration_succeeded);
} else if (status == DeviceRegistrar.UNREGISTERED_STATUS) {
message = getResources().getString(R.string.unregistration_succeeded);
} else {
message = getResources().getString(R.string.registration_error);
}
// Display a notification
String accountName = Preferences.getGoogleAccountName(mContext);
Util.generateNotification(mContext, String.format(message, accountName));
}
};
/**
* Begins the activity.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
setScreenContent(R.layout.hello_world);
// Register a receiver to provide register/unregister notifications
registerReceiver(mUpdateUIReceiver, new IntentFilter(Util.UPDATE_UI_INTENT));
}
/**
* Shuts down the activity.
*/
@Override
public void onDestroy() {
unregisterReceiver(mUpdateUIReceiver);
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
// Invoke the Register activity
menu.getItem(0).setIntent(new Intent(this, AccountsActivity.class));
return true;
}
// Manage UI Screens
private void setHelloWorldScreenContent() {
setContentView(R.layout.hello_world);
final TextView helloWorld = (TextView) findViewById(R.id.hello_world);
final Button sayHelloButton = (Button) findViewById(R.id.say_hello);
sayHelloButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sayHelloButton.setEnabled(false);
helloWorld.setText(R.string.contacting_server);
// Use an AsyncTask to avoid blocking the UI thread
new AsyncTask<Void, Void, String>() {
private String message;
@Override
protected String doInBackground(Void... arg0) {
ShuffleRequestFactory requestFactory = Util.getRequestFactory(mContext,
ShuffleRequestFactory.class);
final HelloWorldRequest request = requestFactory.helloWorldRequest();
String accountName = Preferences.getGoogleAccountName(mContext);
Log.i(TAG, "Sending request to server for account " + accountName);
request.getMessage().fire(new Receiver<String>() {
@Override
public void onFailure(ServerFailure error) {
message = "Failure: " + error.getMessage();
}
@Override
public void onSuccess(String result) {
message = result;
}
});
return message;
}
@Override
protected void onPostExecute(String result) {
helloWorld.setText(result);
sayHelloButton.setEnabled(true);
}
}.execute();
}
});
}
/**
* Sets the screen content based on the screen id.
*/
private void setScreenContent(int screenId) {
setContentView(screenId);
switch (screenId) {
case R.layout.hello_world:
setHelloWorldScreenContent();
break;
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/gae/ShuffleActivity.java | Java | asf20 | 6,195 |
/*
* Copyright 2011 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 org.dodgybits.shuffle.android.synchronisation.gae;
/**
* Class to be customized with app-specific data. The Eclipse plugin will set
* these values when the project is created.
*/
public class Setup {
/**
* The AppEngine app name, used to construct the production service URL
* below.
*/
private static final String APP_NAME = "android-shuffle";
/**
* The URL of the production service.
*/
public static final String PROD_URL = "https://" + APP_NAME + ".appspot.com";
/**
* The C2DM sender ID for the server. A C2DM registration with this name
* must exist for the app to function correctly.
*/
public static final String SENDER_ID = "gtd.shuffle@gmail.com";
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/synchronisation/gae/Setup.java | Java | asf20 | 1,333 |
/*
* Copyright (C) 2009 Android Shuffle Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dodgybits.shuffle.android.editor.activity;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity;
import org.dodgybits.shuffle.android.core.util.TextColours;
import org.dodgybits.shuffle.android.list.view.LabelView;
import roboguice.inject.InjectView;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;
public class ColourPickerActivity extends FlurryEnabledActivity implements
OnItemClickListener {
public static final String TYPE = "vnd.android.cursor.dir/vnd.dodgybits.colours";
@InjectView(R.id.colourGrid) GridView mGrid;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.colour_picker);
mGrid.setAdapter(new IconAdapter(this));
mGrid.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Bundle bundle = new Bundle();
bundle.putString("colour", String.valueOf(position));
Intent mIntent = new Intent();
mIntent.putExtras(bundle);
setResult(RESULT_OK, mIntent);
finish();
}
public class IconAdapter extends BaseAdapter {
private TextColours textColours;
public IconAdapter(Context context) {
textColours = TextColours.getInstance(context);
}
public View getView(int position, View convertView, ViewGroup parent) {
LabelView view;
if (convertView instanceof LabelView) {
view = (LabelView)convertView;
} else {
view = new LabelView(ColourPickerActivity.this);
view.setText("Abc");
view.setGravity(Gravity.CENTER);
}
view.setColourIndex(position);
view.setIcon(null);
return view;
}
public final int getCount() {
return textColours.getNumColours();
}
public final Object getItem(int position) {
return textColours.getTextColour(position);
}
public final long getItemId(int position) {
return position;
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/editor/activity/ColourPickerActivity.java | Java | asf20 | 2,834 |
package org.dodgybits.shuffle.android.editor.activity;
import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity;
import roboguice.util.Ln;
import android.os.Bundle;
public class TaskEditorSchedulingActivity extends FlurryEnabledActivity {
// private boolean mShowStart;
// private Time mStartTime;
// private boolean mShowDue;
// private Time mDueTime;
//
// private @InjectView(R.id.start_date) Button mStartDateButton;
// private @InjectView(R.id.due_date) Button mDueDateButton;
// private @InjectView(R.id.start_time) Button mStartTimeButton;
// private @InjectView(R.id.due_time) Button mDueTimeButton;
// private @InjectView(R.id.clear_dates) Button mClearButton;
// private @InjectView(R.id.is_all_day) CheckBox mAllDayCheckBox;
//
// private @InjectView(R.id.gcal_entry) View mUpdateCalendarEntry;
// private CheckBox mUpdateCalendarCheckBox;
// private TextView mCalendarLabel;
// private TextView mCalendarDetail;
@Override
protected void onCreate(Bundle icicle) {
Ln.d("onCreate+");
super.onCreate(icicle);
// mStartTime = new Time();
// mDueTime = new Time();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/editor/activity/TaskEditorSchedulingActivity.java | Java | asf20 | 1,191 |
/*
* Copyright (C) 2009 Android Shuffle Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dodgybits.shuffle.android.editor.activity;
import android.widget.*;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.model.Context;
import org.dodgybits.shuffle.android.core.model.Context.Builder;
import org.dodgybits.shuffle.android.core.model.encoding.EntityEncoder;
import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister;
import org.dodgybits.shuffle.android.core.util.TextColours;
import org.dodgybits.shuffle.android.core.view.ContextIcon;
import org.dodgybits.shuffle.android.core.view.DrawableUtils;
import org.dodgybits.shuffle.android.list.activity.State;
import org.dodgybits.shuffle.android.list.view.ContextView;
import org.dodgybits.shuffle.android.persistence.provider.ContextProvider;
import roboguice.inject.InjectView;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import com.google.inject.Inject;
public class ContextEditorActivity extends AbstractEditorActivity<Context> implements TextWatcher {
private static final String cTag = "ContextEditorActivity";
private static final int COLOUR_PICKER = 0;
private static final int ICON_PICKER = 1;
private int mColourIndex;
private ContextIcon mIcon;
@InjectView(R.id.name) private EditText mNameWidget;
@InjectView(R.id.colour_display) private TextView mColourWidget;
@InjectView(R.id.icon_display) private ImageView mIconWidget;
@InjectView(R.id.icon_none) private TextView mIconNoneWidget;
@InjectView(R.id.icon_clear_button) private ImageButton mClearIconButton;
@InjectView(R.id.context_preview) private ContextView mContext;
private @InjectView(R.id.deleted_entry) View mDeletedEntry;
private CheckBox mDeletedCheckBox;
private @InjectView(R.id.active_entry) View mActiveEntry;
private @InjectView(R.id.active_entry_checkbox) CheckBox mActiveCheckBox;
@Inject private EntityPersister<Context> mPersister;
@Inject private EntityEncoder<Context> mEncoder;
@Override
protected void onCreate(Bundle icicle) {
Log.d(cTag, "onCreate+");
super.onCreate(icicle);
loadCursor();
findViewsAndAddListeners();
if (mState == State.STATE_EDIT) {
// Make sure we are at the one and only row in the cursor.
mCursor.moveToFirst();
setTitle(R.string.title_edit_context);
mOriginalItem = mPersister.read(mCursor);
updateUIFromItem(mOriginalItem);
} else if (mState == State.STATE_INSERT) {
setTitle(R.string.title_new_context);
mDeletedEntry.setVisibility(View.GONE);
mDeletedCheckBox.setChecked(false);
mActiveCheckBox.setChecked(true);
Bundle extras = getIntent().getExtras();
updateUIFromExtras(extras);
}
}
@Override
protected boolean isValid() {
String name = mNameWidget.getText().toString();
return !TextUtils.isEmpty(name);
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
Log.d(cTag, "Got resultCode " + resultCode + " with data " + data);
switch (requestCode) {
case COLOUR_PICKER:
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
mColourIndex = Integer.parseInt(data.getStringExtra("colour"));
displayColour();
updatePreview();
}
}
break;
case ICON_PICKER:
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
String iconName = data.getStringExtra("iconName");
mIcon = ContextIcon.createIcon(iconName, getResources());
displayIcon();
updatePreview();
}
}
break;
default:
Log.e(cTag, "Unknown requestCode: " + requestCode);
}
}
/**
* Take care of deleting a context. Simply deletes the entry.
*/
@Override
protected void doDeleteAction() {
super.doDeleteAction();
mNameWidget.setText("");
}
/**
* @return id of layout for this view
*/
@Override
protected int getContentViewResId() {
return R.layout.context_editor;
}
@Override
protected Intent getInsertIntent() {
return new Intent(Intent.ACTION_INSERT, ContextProvider.Contexts.CONTENT_URI);
}
@Override
protected CharSequence getItemName() {
return getString(R.string.context_name);
}
@Override
protected Context createItemFromUI(boolean commitValues) {
Builder builder = Context.newBuilder();
if (mOriginalItem != null) {
builder.mergeFrom(mOriginalItem);
}
builder.setName(mNameWidget.getText().toString());
builder.setModifiedDate(System.currentTimeMillis());
builder.setColourIndex(mColourIndex);
builder.setIconName(mIcon.iconName);
builder.setDeleted(mDeletedCheckBox.isChecked());
builder.setActive(mActiveCheckBox.isChecked());
return builder.build();
}
@Override
protected void updateUIFromExtras(Bundle extras) {
if (mColourIndex == -1) {
mColourIndex = 0;
}
displayIcon();
displayColour();
updatePreview();
}
@Override
protected void updateUIFromItem(Context context) {
mNameWidget.setTextKeepState(context.getName());
mColourIndex = context.getColourIndex();
displayColour();
final String iconName = context.getIconName();
mIcon = ContextIcon.createIcon(iconName, getResources());
displayIcon();
updatePreview();
mActiveCheckBox.setChecked(context.isActive());
mDeletedEntry.setVisibility(context.isDeleted() ? View.VISIBLE : View.GONE);
mDeletedCheckBox.setChecked(context.isDeleted());
if (mOriginalItem == null) {
mOriginalItem = context;
}
}
@Override
protected EntityEncoder<Context> getEncoder() {
return mEncoder;
}
@Override
protected EntityPersister<Context> getPersister() {
return mPersister;
}
private void loadCursor() {
if (mUri != null && mState == State.STATE_EDIT)
{
mCursor = managedQuery(mUri, ContextProvider.Contexts.FULL_PROJECTION, null, null, null);
if (mCursor == null || mCursor.getCount() == 0) {
// The cursor is empty. This can happen if the event was deleted.
finish();
}
}
}
private void findViewsAndAddListeners() {
// The text view for our context description, identified by its ID in the XML file.
mNameWidget.addTextChangedListener(this);
mColourIndex = -1;
mIcon = ContextIcon.NONE;
View colourEntry = findViewById(R.id.colour_entry);
colourEntry.setOnClickListener(this);
colourEntry.setOnFocusChangeListener(this);
View iconEntry = findViewById(R.id.icon_entry);
iconEntry.setOnClickListener(this);
iconEntry.setOnFocusChangeListener(this);
mClearIconButton.setOnClickListener(this);
mClearIconButton.setOnFocusChangeListener(this);
mActiveEntry.setOnClickListener(this);
mActiveEntry.setOnFocusChangeListener(this);
mDeletedEntry.setOnClickListener(this);
mDeletedEntry.setOnFocusChangeListener(this);
mDeletedCheckBox = (CheckBox) mDeletedEntry.findViewById(R.id.deleted_entry_checkbox);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.colour_entry: {
// Launch activity to pick colour
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ColourPickerActivity.TYPE);
startActivityForResult(intent, COLOUR_PICKER);
break;
}
case R.id.icon_entry: {
// Launch activity to pick icon
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(IconPickerActivity.TYPE);
startActivityForResult(intent, ICON_PICKER);
break;
}
case R.id.icon_clear_button: {
mIcon = ContextIcon.NONE;
displayIcon();
updatePreview();
break;
}
case R.id.active_entry: {
mActiveCheckBox.toggle();
break;
}
case R.id.deleted_entry: {
mDeletedCheckBox.toggle();
break;
}
default:
super.onClick(v);
break;
}
}
private void displayColour() {
int bgColour = TextColours.getInstance(this).getBackgroundColour(mColourIndex);
GradientDrawable drawable = DrawableUtils.createGradient(bgColour, Orientation.TL_BR);
drawable.setCornerRadius(8.0f);
mColourWidget.setBackgroundDrawable(drawable);
}
private void displayIcon() {
if (mIcon == ContextIcon.NONE) {
mIconNoneWidget.setVisibility(View.VISIBLE);
mIconWidget.setVisibility(View.GONE);
mClearIconButton.setEnabled(false);
} else {
mIconNoneWidget.setVisibility(View.GONE);
mIconWidget.setImageResource(mIcon.largeIconId);
mIconWidget.setVisibility(View.VISIBLE);
mClearIconButton.setEnabled(true);
}
}
private void updatePreview() {
String name = mNameWidget.getText().toString();
if (TextUtils.isEmpty(name) || mColourIndex == -1) {
mContext.setVisibility(View.INVISIBLE);
} else {
mContext.updateView(createItemFromUI(false));
mContext.setVisibility(View.VISIBLE);
}
}
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
updatePreview();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/editor/activity/ContextEditorActivity.java | Java | asf20 | 10,872 |
/*
* Copyright (C) 2009 Android Shuffle Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dodgybits.shuffle.android.editor.activity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.TimeZone;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.model.Id;
import org.dodgybits.shuffle.android.core.model.Task;
import org.dodgybits.shuffle.android.core.model.Task.Builder;
import org.dodgybits.shuffle.android.core.model.encoding.EntityEncoder;
import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister;
import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister;
import org.dodgybits.shuffle.android.core.util.CalendarUtils;
import org.dodgybits.shuffle.android.core.util.Constants;
import org.dodgybits.shuffle.android.list.activity.State;
import org.dodgybits.shuffle.android.persistence.provider.ContextProvider;
import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider;
import org.dodgybits.shuffle.android.persistence.provider.ReminderProvider;
import org.dodgybits.shuffle.android.persistence.provider.TaskProvider;
import org.dodgybits.shuffle.android.preference.model.Preferences;
import roboguice.inject.InjectView;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import com.google.inject.Inject;
/**
* A generic activity for editing a task in the database. This can be used
* either to simply view a task (Intent.VIEW_ACTION), view and edit a task
* (Intent.EDIT_ACTION), or create a new task (Intent.INSERT_ACTION).
*/
public class TaskEditorActivity extends AbstractEditorActivity<Task>
implements CompoundButton.OnCheckedChangeListener {
private static final String cTag = "TaskEditorActivity";
private static final String[] cContextProjection = new String[] {
ContextProvider.Contexts._ID,
ContextProvider.Contexts.NAME
};
private static final String[] cProjectProjection = new String[] {
ProjectProvider.Projects._ID,
ProjectProvider.Projects.NAME
};
private static final String REMINDERS_WHERE = ReminderProvider.Reminders.TASK_ID + "=? AND (" +
ReminderProvider.Reminders.METHOD + "=" + ReminderProvider.Reminders.METHOD_ALERT +
" OR " + ReminderProvider.Reminders.METHOD + "=" + ReminderProvider.Reminders.METHOD_DEFAULT + ")";
private static final int MAX_REMINDERS = 3;
private static final int cNewContextCode = 100;
private static final int cNewProjectCode = 101;
private @InjectView(R.id.description) EditText mDescriptionWidget;
private @InjectView(R.id.context) Spinner mContextSpinner;
private @InjectView(R.id.project) Spinner mProjectSpinner;
private @InjectView(R.id.details) EditText mDetailsWidget;
private String[] mContextNames;
private long[] mContextIds;
private String[] mProjectNames;
private long[] mProjectIds;
private boolean mSchedulingExpanded;
private @InjectView(R.id.start_date) Button mStartDateButton;
private @InjectView(R.id.due_date) Button mDueDateButton;
private @InjectView(R.id.start_time) Button mStartTimeButton;
private @InjectView(R.id.due_time) Button mDueTimeButton;
private @InjectView(R.id.clear_dates) Button mClearButton;
private @InjectView(R.id.is_all_day) CheckBox mAllDayCheckBox;
private boolean mShowStart;
private Time mStartTime;
private boolean mShowDue;
private Time mDueTime;
private View mSchedulingExtra;
private TextView mSchedulingDetail;
private View mExpandButton;
private View mCollapseButton;
private @InjectView(R.id.completed_entry) View mCompleteEntry;
private CheckBox mCompletedCheckBox;
private @InjectView(R.id.deleted_entry) View mDeletedEntry;
private @InjectView(R.id.deleted_entry_checkbox) CheckBox mDeletedCheckBox;
private @InjectView(R.id.gcal_entry) View mUpdateCalendarEntry;
private CheckBox mUpdateCalendarCheckBox;
private TextView mCalendarLabel;
private TextView mCalendarDetail;
private ArrayList<Integer> mReminderValues;
private ArrayList<String> mReminderLabels;
private int mDefaultReminderMinutes;
private @InjectView(R.id.reminder_items_container) LinearLayout mRemindersContainer;
private ArrayList<Integer> mOriginalMinutes = new ArrayList<Integer>();
private ArrayList<LinearLayout> mReminderItems = new ArrayList<LinearLayout>(0);
@Inject private TaskPersister mPersister;
@Inject private EntityEncoder<Task> mEncoder;
@Override
protected void onCreate(Bundle icicle) {
Log.d(cTag, "onCreate+");
super.onCreate(icicle);
mStartTime = new Time();
mDueTime = new Time();
loadCursors();
findViewsAndAddListeners();
if (mState == State.STATE_EDIT) {
// Make sure we are at the one and only row in the cursor.
mCursor.moveToFirst();
// Modify our overall title depending on the mode we are running in.
setTitle(R.string.title_edit_task);
mCompleteEntry.setVisibility(View.VISIBLE);
mOriginalItem = mPersister.read(mCursor);
updateUIFromItem(mOriginalItem);
} else if (mState == State.STATE_INSERT) {
setTitle(R.string.title_new_task);
mCompleteEntry.setVisibility(View.GONE);
mDeletedEntry.setVisibility(View.GONE);
mDeletedCheckBox.setChecked(false);
// see if the context or project were suggested for this task
Bundle extras = getIntent().getExtras();
updateUIFromExtras(extras);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
Log.d(cTag, "Got resultCode " + resultCode + " with data " + data);
switch (requestCode) {
case cNewContextCode:
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
long newContextId = ContentUris.parseId(data.getData());
setupContextSpinner();
setSpinnerSelection(mContextSpinner, mContextIds, newContextId);
}
}
break;
case cNewProjectCode:
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
long newProjectId = ContentUris.parseId(data.getData());
setupProjectSpinner();
setSpinnerSelection(mProjectSpinner, mProjectIds, newProjectId);
}
}
break;
default:
Log.e(cTag, "Unknown requestCode: " + requestCode);
}
}
@Override
protected boolean isValid() {
String description = mDescriptionWidget.getText().toString();
return !TextUtils.isEmpty(description);
}
@Override
protected void updateUIFromExtras(Bundle extras) {
if (extras != null) {
Long contextId = extras.getLong(TaskProvider.Tasks.CONTEXT_ID);
setSpinnerSelection(mContextSpinner, mContextIds, contextId);
Long projectId = extras.getLong(TaskProvider.Tasks.PROJECT_ID);
setSpinnerSelection(mProjectSpinner, mProjectIds, projectId);
}
setWhenDefaults();
populateWhen();
setSchedulingVisibility(false);
mStartTimeButton.setVisibility(View.VISIBLE);
mDueTimeButton.setVisibility(View.VISIBLE);
updateCalendarPanel();
updateRemindersVisibility();
}
@Override
protected void updateUIFromItem(Task task) {
// If we hadn't previously retrieved the original task, do so
// now. This allows the user to revert their changes.
if (mOriginalItem == null) {
mOriginalItem = task;
}
final String details = task.getDetails();
mDetailsWidget.setTextKeepState(details == null ? "" : details);
mDescriptionWidget.setTextKeepState(task.getDescription());
final Id contextId = task.getContextId();
if (contextId.isInitialised()) {
setSpinnerSelection(mContextSpinner, mContextIds, contextId.getId());
}
final Id projectId = task.getProjectId();
if (projectId.isInitialised()) {
setSpinnerSelection(mProjectSpinner, mProjectIds, projectId.getId());
}
boolean allDay = task.isAllDay();
if (allDay) {
String tz = mStartTime.timezone;
mStartTime.timezone = Time.TIMEZONE_UTC;
mStartTime.set(task.getStartDate());
mStartTime.timezone = tz;
// Calling normalize to calculate isDst
mStartTime.normalize(true);
} else {
mStartTime.set(task.getStartDate());
}
if (allDay) {
String tz = mStartTime.timezone;
mDueTime.timezone = Time.TIMEZONE_UTC;
mDueTime.set(task.getDueDate());
mDueTime.timezone = tz;
// Calling normalize to calculate isDst
mDueTime.normalize(true);
} else {
mDueTime.set(task.getDueDate());
}
setWhenDefaults();
populateWhen();
// show scheduling section if either start or due date are set
mSchedulingExpanded = mShowStart || mShowDue;
setSchedulingVisibility(mSchedulingExpanded);
mAllDayCheckBox.setChecked(allDay);
updateTimeVisibility(!allDay);
mCompletedCheckBox.setChecked(task.isComplete());
mDeletedEntry.setVisibility(task.isDeleted() ? View.VISIBLE : View.GONE);
mDeletedCheckBox.setChecked(task.isDeleted());
updateCalendarPanel();
// Load reminders (if there are any)
if (task.hasAlarms()) {
Uri uri = ReminderProvider.Reminders.CONTENT_URI;
ContentResolver cr = getContentResolver();
Cursor reminderCursor = cr.query(uri, ReminderProvider.Reminders.cFullProjection,
REMINDERS_WHERE, new String[] {String.valueOf(task.getLocalId().getId())}, null);
try {
// First pass: collect all the custom reminder minutes (e.g.,
// a reminder of 8 minutes) into a global list.
while (reminderCursor.moveToNext()) {
int minutes = reminderCursor.getInt(ReminderProvider.Reminders.MINUTES_INDEX);
addMinutesToList(this, mReminderValues, mReminderLabels, minutes);
}
// Second pass: create the reminder spinners
reminderCursor.moveToPosition(-1);
while (reminderCursor.moveToNext()) {
int minutes = reminderCursor.getInt(ReminderProvider.Reminders.MINUTES_INDEX);
mOriginalMinutes.add(minutes);
addReminder(this, this, mReminderItems, mReminderValues,
mReminderLabels, minutes);
}
} finally {
reminderCursor.close();
}
}
updateRemindersVisibility();
}
@Override
protected Task createItemFromUI(boolean commitValues) {
Builder builder = Task.newBuilder();
if (mOriginalItem != null) {
builder.mergeFrom(mOriginalItem);
}
final String description = mDescriptionWidget.getText().toString();
final long modified = System.currentTimeMillis();
final String details = mDetailsWidget.getText().toString();
final Id contextId = getSpinnerSelectedId(mContextSpinner, mContextIds);
final Id projectId = getSpinnerSelectedId(mProjectSpinner, mProjectIds);
final boolean allDay = mAllDayCheckBox.isChecked();
final boolean complete = mCompletedCheckBox.isChecked();
final boolean hasAlarms = !mReminderItems.isEmpty();
final boolean deleted = mDeletedCheckBox.isChecked();
final boolean active = true;
builder
.setDescription(description)
.setModifiedDate(modified)
.setDetails(details)
.setContextId(contextId)
.setProjectId(projectId)
.setAllDay(allDay)
.setComplete(complete)
.setDeleted(deleted)
.setActive(active)
.setHasAlarm(hasAlarms);
// If we are creating a new task, set the creation date
if (mState == State.STATE_INSERT) {
builder.setCreatedDate(modified);
}
String timezone;
long startMillis = 0L;
long dueMillis = 0L;
if (allDay) {
// Reset start and end time, increment the monthDay by 1, and set
// the timezone to UTC, as required for all-day events.
timezone = Time.TIMEZONE_UTC;
mStartTime.hour = 0;
mStartTime.minute = 0;
mStartTime.second = 0;
mStartTime.timezone = timezone;
startMillis = mStartTime.normalize(true);
mDueTime.hour = 0;
mDueTime.minute = 0;
mDueTime.second = 0;
mDueTime.monthDay++;
mDueTime.timezone = timezone;
dueMillis = mDueTime.normalize(true);
} else {
if (mShowStart && !Time.isEpoch(mStartTime)) {
startMillis = mStartTime.toMillis(true);
}
if (mShowDue && !Time.isEpoch(mDueTime)) {
dueMillis = mDueTime.toMillis(true);
}
if (mState == State.STATE_INSERT) {
// The timezone for a new task is the currently displayed timezone
timezone = TimeZone.getDefault().getID();
}
else
{
timezone = mOriginalItem.getTimezone();
// The timezone might be null if we are changing an existing
// all-day task to a non-all-day event. We need to assign
// a timezone to the non-all-day task.
if (TextUtils.isEmpty(timezone)) {
timezone = TimeZone.getDefault().getID();
}
}
}
final int order;
if (commitValues) {
order = mPersister.calculateTaskOrder(mOriginalItem, projectId, dueMillis);
} else if (mOriginalItem == null) {
order = 0;
} else {
order = mOriginalItem.getOrder();
}
builder
.setTimezone(timezone)
.setStartDate(startMillis)
.setDueDate(dueMillis)
.setOrder(order);
Id eventId = mOriginalItem == null ? Id.NONE : mOriginalItem.getCalendarEventId();
final boolean updateCalendar = mUpdateCalendarCheckBox.isChecked();
if (updateCalendar) {
Uri calEntryUri = addOrUpdateCalendarEvent(
eventId, description, details,
projectId, contextId, timezone, startMillis,
dueMillis, allDay);
if (calEntryUri != null) {
eventId = Id.create(ContentUris.parseId(calEntryUri));
mNextIntent = new Intent(Intent.ACTION_EDIT, calEntryUri);
mNextIntent.putExtra("beginTime", startMillis);
mNextIntent.putExtra("endTime", dueMillis);
}
Log.i(cTag, "Updated calendar event " + eventId);
}
builder.setCalendarEventId(eventId);
return builder.build();
}
@Override
protected EntityEncoder<Task> getEncoder() {
return mEncoder;
}
@Override
protected EntityPersister<Task> getPersister() {
return mPersister;
}
private Uri addOrUpdateCalendarEvent(
Id calEventId, String title, String description,
Id projectId, Id contextId,
String timezone, long start, long end, boolean allDay) {
if (projectId.isInitialised()) {
String projectName = getProjectName(projectId);
title = projectName + " - " + title;
}
if (description == null) {
description = "";
}
ContentValues values = new ContentValues();
if (!TextUtils.isEmpty(timezone)) {
values.put("eventTimezone", timezone);
}
values.put("calendar_id", Preferences.getCalendarId(this));
values.put("title", title);
values.put("allDay", allDay ? 1 : 0);
if (start > 0L) {
values.put("dtstart", start); // long (start date in ms)
}
if (end > 0L) {
values.put("dtend", end); // long (end date in ms)
}
values.put("description", description);
values.put("hasAlarm", 0);
values.put("transparency", 0);
values.put("visibility", 0);
if (contextId.isInitialised()) {
String contextName = getContextName(contextId);
values.put("eventLocation", contextName);
}
Uri eventUri = null;
try {
eventUri = addCalendarEntry(values, calEventId, CalendarUtils.getEventContentUri());
} catch (Exception e) {
Log.e(cTag, "Attempt failed to create calendar entry", e);
mAnalytics.onError(Constants.cFlurryCalendarUpdateError, e.getMessage(), getClass().getName());
}
return eventUri;
}
private Uri addCalendarEntry(ContentValues values, Id oldId, Uri baseUri) {
ContentResolver cr = getContentResolver();
int updateCount = 0;
Uri eventUri = null;
if (oldId.isInitialised()) {
eventUri = ContentUris.appendId(baseUri.buildUpon(), oldId.getId()).build();
// it's possible the old event was deleted, check number of records updated
updateCount = cr.update(eventUri, values, null, null);
}
if (updateCount == 0) {
eventUri = cr.insert(baseUri, values);
}
return eventUri;
}
@Override
protected Intent getInsertIntent() {
Intent intent = new Intent(Intent.ACTION_INSERT, TaskProvider.Tasks.CONTENT_URI);
// give new task the same project and context as this one
Bundle extras = intent.getExtras();
if (extras == null) extras = new Bundle();
Id contextId = getSpinnerSelectedId(mContextSpinner, mContextIds);
if (contextId.isInitialised()) {
extras.putLong(TaskProvider.Tasks.CONTEXT_ID, contextId.getId());
}
Id projectId = getSpinnerSelectedId(mProjectSpinner, mProjectIds);
if (projectId.isInitialised()) {
extras.putLong(TaskProvider.Tasks.PROJECT_ID, projectId.getId());
}
intent.putExtras(extras);
return intent;
}
@Override
protected Uri create() {
Uri uri = super.create();
if (uri != null) {
ContentResolver cr = getContentResolver();
ArrayList<Integer> reminderMinutes = reminderItemsToMinutes(mReminderItems,
mReminderValues);
long taskId = ContentUris.parseId(uri);
saveReminders(cr, taskId, reminderMinutes, mOriginalMinutes);
}
return uri;
}
@Override
protected Uri save() {
Uri uri = super.save();
if (uri != null) {
ContentResolver cr = getContentResolver();
ArrayList<Integer> reminderMinutes = reminderItemsToMinutes(mReminderItems,
mReminderValues);
long taskId = ContentUris.parseId(uri);
saveReminders(cr, taskId, reminderMinutes, mOriginalMinutes);
}
return uri;
}
/**
* @return id of layout for this view
*/
@Override
protected int getContentViewResId() {
return R.layout.task_editor;
}
@Override
protected CharSequence getItemName() {
return getString(R.string.task_name);
}
/**
* Take care of deleting a task. Simply deletes the entry.
*/
@Override
protected void doDeleteAction() {
super.doDeleteAction();
mDescriptionWidget.setText("");
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.context_add: {
Intent addContextIntent = new Intent(Intent.ACTION_INSERT, ContextProvider.Contexts.CONTENT_URI);
startActivityForResult(addContextIntent, cNewContextCode);
break;
}
case R.id.project_add: {
Intent addProjectIntent = new Intent(Intent.ACTION_INSERT, ProjectProvider.Projects.CONTENT_URI);
startActivityForResult(addProjectIntent, cNewProjectCode);
break;
}
case R.id.scheduling_entry: {
toggleSchedulingSection();
break;
}
case R.id.completed_entry: {
mCompletedCheckBox.toggle();
break;
}
case R.id.deleted_entry: {
mDeletedCheckBox.toggle();
break;
}
case R.id.gcal_entry: {
CheckBox checkBox = (CheckBox) v.findViewById(R.id.update_calendar_checkbox);
checkBox.toggle();
break;
}
case R.id.clear_dates: {
mAllDayCheckBox.setChecked(false);
mStartTime = new Time();
mDueTime = new Time();
setWhenDefaults();
populateWhen();
updateCalendarPanel();
break;
}
case R.id.reminder_remove: {
LinearLayout reminderItem = (LinearLayout) v.getParent();
LinearLayout parent = (LinearLayout) reminderItem.getParent();
parent.removeView(reminderItem);
mReminderItems.remove(reminderItem);
updateRemindersVisibility();
break;
}
default:
super.onClick(v);
break;
}
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
if (mDueTime.hour == 0 && mDueTime.minute == 0) {
mDueTime.monthDay--;
// Do not allow an event to have an end time before the start time.
if (mDueTime.before(mStartTime)) {
mDueTime.set(mStartTime);
}
}
} else {
if (mDueTime.hour == 0 && mDueTime.minute == 0) {
mDueTime.monthDay++;
}
}
mShowStart = true;
long startMillis = mStartTime.normalize(true);
setDate(mStartDateButton, startMillis, mShowStart);
setTime(mStartTimeButton, startMillis, mShowStart);
mShowDue = true;
long dueMillis = mDueTime.normalize(true);
setDate(mDueDateButton, dueMillis, mShowDue);
setTime(mDueTimeButton, dueMillis, mShowDue);
updateTimeVisibility(!isChecked);
}
private void updateTimeVisibility(boolean showTime) {
if (showTime) {
mStartTimeButton.setVisibility(View.VISIBLE);
mDueTimeButton.setVisibility(View.VISIBLE);
} else {
mStartTimeButton.setVisibility(View.GONE);
mDueTimeButton.setVisibility(View.GONE);
}
}
private void loadCursors() {
// Get the task if we're editing
if (mUri != null && mState == State.STATE_EDIT)
{
mCursor = managedQuery(mUri, TaskProvider.Tasks.FULL_PROJECTION, null, null, null);
if (mCursor == null || mCursor.getCount() == 0) {
// The cursor is empty. This can happen if the event was deleted.
finish();
}
}
}
private void findViewsAndAddListeners() {
// The text view for our task description, identified by its ID in the XML file.
setupContextSpinner();
ImageButton addContextButton = (ImageButton) findViewById(R.id.context_add);
addContextButton.setOnClickListener(this);
addContextButton.setOnFocusChangeListener(this);
setupProjectSpinner();
ImageButton addProjectButton = (ImageButton) findViewById(R.id.project_add);
addProjectButton.setOnClickListener(this);
addProjectButton.setOnFocusChangeListener(this);
mCompleteEntry.setOnClickListener(this);
mCompleteEntry.setOnFocusChangeListener(this);
mCompletedCheckBox = (CheckBox) mCompleteEntry.findViewById(R.id.completed_entry_checkbox);
mDeletedEntry.setOnClickListener(this);
mDeletedEntry.setOnFocusChangeListener(this);
mUpdateCalendarEntry.setOnClickListener(this);
mUpdateCalendarEntry.setOnFocusChangeListener(this);
mUpdateCalendarCheckBox = (CheckBox) mUpdateCalendarEntry.findViewById(R.id.update_calendar_checkbox);
mCalendarLabel = (TextView) mUpdateCalendarEntry.findViewById(R.id.gcal_label);
mCalendarDetail = (TextView) mUpdateCalendarEntry.findViewById(R.id.gcal_detail);
mStartDateButton.setOnClickListener(new DateClickListener(mStartTime));
mStartTimeButton.setOnClickListener(new TimeClickListener(mStartTime));
mDueDateButton.setOnClickListener(new DateClickListener(mDueTime));
mDueTimeButton.setOnClickListener(new TimeClickListener(mDueTime));
mAllDayCheckBox.setOnCheckedChangeListener(this);
mClearButton.setOnClickListener(this);
ViewGroup schedulingSection = (ViewGroup) findViewById(R.id.scheduling_section);
View schedulingEntry = findViewById(R.id.scheduling_entry);
schedulingEntry.setOnClickListener(this);
schedulingEntry.setOnFocusChangeListener(this);
mSchedulingExtra = schedulingSection.findViewById(R.id.scheduling_extra);
mExpandButton = schedulingEntry.findViewById(R.id.expand);
mCollapseButton = schedulingEntry.findViewById(R.id.collapse);
mSchedulingDetail = (TextView) schedulingEntry.findViewById(R.id.scheduling_detail);
mSchedulingExpanded = mSchedulingExtra.getVisibility() == View.VISIBLE;
// Initialize the reminder values array.
Resources r = getResources();
String[] strings = r.getStringArray(R.array.reminder_minutes_values);
ArrayList<Integer> list = new ArrayList<Integer>(strings.length);
for (String numberString: strings) {
list.add(Integer.parseInt(numberString));
}
mReminderValues = list;
String[] labels = r.getStringArray(R.array.reminder_minutes_labels);
mReminderLabels = new ArrayList<String>(Arrays.asList(labels));
mDefaultReminderMinutes = Preferences.getDefaultReminderMinutes(this);
// Setup the + Add Reminder Button
ImageButton reminderAddButton = (ImageButton) findViewById(R.id.reminder_add);
reminderAddButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addReminder();
}
});
}
private void setupContextSpinner() {
Cursor contextCursor = getContentResolver().query(
ContextProvider.Contexts.CONTENT_URI, cContextProjection,
ContextProvider.Contexts.DELETED + "=0", null, ContextProvider.Contexts.NAME + " ASC");
int arraySize = contextCursor.getCount() + 1;
mContextIds = new long[arraySize];
mContextIds[0] = 0;
mContextNames = new String[arraySize];
mContextNames[0] = getText(R.string.none_empty).toString();
for (int i = 1; i < arraySize; i++) {
contextCursor.moveToNext();
mContextIds[i] = contextCursor.getLong(0);
mContextNames[i] = contextCursor.getString(1);
}
contextCursor.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, mContextNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mContextSpinner.setAdapter(adapter);
}
private void setupProjectSpinner() {
Cursor projectCursor = getContentResolver().query(
ProjectProvider.Projects.CONTENT_URI, cProjectProjection,
ProjectProvider.Projects.DELETED + " = 0", null, ProjectProvider.Projects.NAME + " ASC");
int arraySize = projectCursor.getCount() + 1;
mProjectIds = new long[arraySize];
mProjectIds[0] = 0;
mProjectNames = new String[arraySize];
mProjectNames[0] = getText(R.string.none_empty).toString();
for (int i = 1; i < arraySize; i++) {
projectCursor.moveToNext();
mProjectIds[i] = projectCursor.getLong(0);
mProjectNames[i] = projectCursor.getString(1);
}
projectCursor.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, mProjectNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mProjectSpinner.setAdapter(adapter);
}
private Id getSpinnerSelectedId(Spinner spinner, long[] ids) {
Id id = Id.NONE;
int selectedItemPosition = spinner.getSelectedItemPosition();
if (selectedItemPosition > 0) {
id = Id.create(ids[selectedItemPosition]);
}
return id;
}
private void setSpinnerSelection(Spinner spinner, long[] ids, Long id) {
if (id == null || id == 0) {
spinner.setSelection(0);
} else {
for (int i = 1; i < ids.length; i++) {
if (ids[i] == id) {
spinner.setSelection(i);
break;
}
}
}
}
private String getContextName(Id contextId) {
String name = "";
final long id = contextId.getId();
for(int i = 0; i < mContextIds.length; i++) {
long currentId = mContextIds[i];
if (currentId == id) {
name = mContextNames[i];
break;
}
}
return name;
}
private String getProjectName(Id projectId) {
String name = "";
final long id = projectId.getId();
for(int i = 0; i < mProjectIds.length; i++) {
long currentId = mProjectIds[i];
if (currentId == id) {
name = mProjectNames[i];
break;
}
}
return name;
}
private void addReminder() {
if (mDefaultReminderMinutes == 0) {
addReminder(this, this, mReminderItems, mReminderValues,
mReminderLabels, 10 /* minutes */);
} else {
addReminder(this, this, mReminderItems, mReminderValues,
mReminderLabels, mDefaultReminderMinutes);
}
updateRemindersVisibility();
}
// Adds a reminder to the displayed list of reminders.
// Returns true if successfully added reminder, false if no reminders can
// be added.
static boolean addReminder(Activity activity, View.OnClickListener listener,
ArrayList<LinearLayout> items, ArrayList<Integer> values,
ArrayList<String> labels, int minutes) {
if (items.size() >= MAX_REMINDERS) {
return false;
}
LayoutInflater inflater = activity.getLayoutInflater();
LinearLayout parent = (LinearLayout) activity.findViewById(R.id.reminder_items_container);
LinearLayout reminderItem = (LinearLayout) inflater.inflate(R.layout.edit_reminder_item, null);
parent.addView(reminderItem);
Spinner spinner = (Spinner) reminderItem.findViewById(R.id.reminder_value);
Resources res = activity.getResources();
spinner.setPrompt(res.getString(R.string.reminders_title));
int resource = android.R.layout.simple_spinner_item;
ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, resource, labels);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
ImageButton reminderRemoveButton;
reminderRemoveButton = (ImageButton) reminderItem.findViewById(R.id.reminder_remove);
reminderRemoveButton.setOnClickListener(listener);
int index = findMinutesInReminderList(values, minutes);
spinner.setSelection(index);
items.add(reminderItem);
return true;
}
private void toggleSchedulingSection() {
mSchedulingExpanded = !mSchedulingExpanded;
setSchedulingVisibility(mSchedulingExpanded);
}
private void setSchedulingVisibility(boolean visible) {
if (visible) {
mSchedulingExtra.setVisibility(View.VISIBLE);
mExpandButton.setVisibility(View.GONE);
mCollapseButton.setVisibility(View.VISIBLE);
mSchedulingDetail.setText(R.string.scheduling_expanded);
} else {
mSchedulingExtra.setVisibility(View.GONE);
mExpandButton.setVisibility(View.VISIBLE);
mCollapseButton.setVisibility(View.GONE);
mSchedulingDetail.setText(R.string.scheduling_collapsed);
}
}
private void setWhenDefaults() {
// it's possible to have:
// 1) no times set
// 2) due time set, but not start time
// 3) start and due time set
mShowStart = !Time.isEpoch(mStartTime);
mShowDue = !Time.isEpoch(mDueTime);
if (!mShowStart && !mShowDue) {
mStartTime.setToNow();
// Round the time to the nearest half hour.
mStartTime.second = 0;
int minute = mStartTime.minute;
if (minute > 0 && minute <= 30) {
mStartTime.minute = 30;
} else {
mStartTime.minute = 0;
mStartTime.hour += 1;
}
long startMillis = mStartTime.normalize(true /* ignore isDst */);
mDueTime.set(startMillis + DateUtils.HOUR_IN_MILLIS);
} else if (!mShowStart) {
// default start to same as due
mStartTime.set(mDueTime);
}
}
private void populateWhen() {
long startMillis = mStartTime.toMillis(false /* use isDst */);
long endMillis = mDueTime.toMillis(false /* use isDst */);
setDate(mStartDateButton, startMillis, mShowStart);
setDate(mDueDateButton, endMillis, mShowDue);
setTime(mStartTimeButton, startMillis, mShowStart);
setTime(mDueTimeButton, endMillis, mShowDue);
}
private void setDate(TextView view, long millis, boolean showValue) {
CharSequence value;
if (showValue) {
int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_MONTH |
DateUtils.FORMAT_ABBREV_WEEKDAY;
value = DateUtils.formatDateTime(this, millis, flags);
} else {
value = "";
}
view.setText(value);
}
private void setTime(TextView view, long millis, boolean showValue) {
CharSequence value;
if (showValue) {
int flags = DateUtils.FORMAT_SHOW_TIME;
if (DateFormat.is24HourFormat(this)) {
flags |= DateUtils.FORMAT_24HOUR;
}
value = DateUtils.formatDateTime(this, millis, flags);
} else {
value = "";
}
view.setText(value);
}
static void addMinutesToList(android.content.Context context, ArrayList<Integer> values,
ArrayList<String> labels, int minutes) {
int index = values.indexOf(minutes);
if (index != -1) {
return;
}
// The requested "minutes" does not exist in the list, so insert it
// into the list.
String label = constructReminderLabel(context, minutes, false);
int len = values.size();
for (int i = 0; i < len; i++) {
if (minutes < values.get(i)) {
values.add(i, minutes);
labels.add(i, label);
return;
}
}
values.add(minutes);
labels.add(len, label);
}
/**
* Finds the index of the given "minutes" in the "values" list.
*
* @param values the list of minutes corresponding to the spinner choices
* @param minutes the minutes to search for in the values list
* @return the index of "minutes" in the "values" list
*/
private static int findMinutesInReminderList(ArrayList<Integer> values, int minutes) {
int index = values.indexOf(minutes);
if (index == -1) {
// This should never happen.
Log.e(cTag, "Cannot find minutes (" + minutes + ") in list");
return 0;
}
return index;
}
// Constructs a label given an arbitrary number of minutes. For example,
// if the given minutes is 63, then this returns the string "63 minutes".
// As another example, if the given minutes is 120, then this returns
// "2 hours".
static String constructReminderLabel(android.content.Context context, int minutes, boolean abbrev) {
Resources resources = context.getResources();
int value, resId;
if (minutes % 60 != 0) {
value = minutes;
if (abbrev) {
resId = R.plurals.Nmins;
} else {
resId = R.plurals.Nminutes;
}
} else if (minutes % (24 * 60) != 0) {
value = minutes / 60;
resId = R.plurals.Nhours;
} else {
value = minutes / ( 24 * 60);
resId = R.plurals.Ndays;
}
String format = resources.getQuantityString(resId, value);
return String.format(format, value);
}
private void updateRemindersVisibility() {
if (mReminderItems.size() == 0) {
mRemindersContainer.setVisibility(View.GONE);
} else {
mRemindersContainer.setVisibility(View.VISIBLE);
}
}
private void updateCalendarPanel() {
boolean enabled = true;
if (mOriginalItem != null &&
mOriginalItem.getCalendarEventId().isInitialised()) {
mCalendarLabel.setText(getString(R.string.update_gcal_title));
mCalendarDetail.setText(getString(R.string.update_gcal_detail));
} else if (mShowDue && mShowStart) {
mCalendarLabel.setText(getString(R.string.add_to_gcal_title));
mCalendarDetail.setText(getString(R.string.add_to_gcal_detail));
} else {
mCalendarLabel.setText(getString(R.string.add_to_gcal_title));
mCalendarDetail.setText(getString(R.string.add_to_gcal_detail_disabled));
enabled = false;
}
mUpdateCalendarEntry.setEnabled(enabled);
mUpdateCalendarCheckBox.setEnabled(enabled);
}
static ArrayList<Integer> reminderItemsToMinutes(ArrayList<LinearLayout> reminderItems,
ArrayList<Integer> reminderValues) {
int len = reminderItems.size();
ArrayList<Integer> reminderMinutes = new ArrayList<Integer>(len);
for (int index = 0; index < len; index++) {
LinearLayout layout = reminderItems.get(index);
Spinner spinner = (Spinner) layout.findViewById(R.id.reminder_value);
int minutes = reminderValues.get(spinner.getSelectedItemPosition());
reminderMinutes.add(minutes);
}
return reminderMinutes;
}
/**
* Saves the reminders, if they changed. Returns true if the database
* was updated.
*
* @param cr the ContentResolver
* @param taskId the id of the task whose reminders are being updated
* @param reminderMinutes the array of reminders set by the user
* @param originalMinutes the original array of reminders
* @return true if the database was updated
*/
static boolean saveReminders(ContentResolver cr, long taskId,
ArrayList<Integer> reminderMinutes, ArrayList<Integer> originalMinutes
) {
// If the reminders have not changed, then don't update the database
if (reminderMinutes.equals(originalMinutes)) {
return false;
}
// Delete all the existing reminders for this event
String where = ReminderProvider.Reminders.TASK_ID + "=?";
String[] args = new String[] { Long.toString(taskId) };
cr.delete(ReminderProvider.Reminders.CONTENT_URI, where, args);
ContentValues values = new ContentValues();
int len = reminderMinutes.size();
// Insert the new reminders, if any
for (int i = 0; i < len; i++) {
int minutes = reminderMinutes.get(i);
values.clear();
values.put(ReminderProvider.Reminders.MINUTES, minutes);
values.put(ReminderProvider.Reminders.METHOD, ReminderProvider.Reminders.METHOD_ALERT);
values.put(ReminderProvider.Reminders.TASK_ID, taskId);
cr.insert(ReminderProvider.Reminders.CONTENT_URI, values);
}
return true;
}
/* This class is used to update the time buttons. */
private class TimeListener implements OnTimeSetListener {
private View mView;
public TimeListener(View view) {
mView = view;
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Cache the member variables locally to avoid inner class overhead.
Time startTime = mStartTime;
Time dueTime = mDueTime;
// Cache the start and due millis so that we limit the number
// of calls to normalize() and toMillis(), which are fairly
// expensive.
long startMillis;
long dueMillis;
if (mView == mStartTimeButton) {
// The start time was changed.
int hourDuration = dueTime.hour - startTime.hour;
int minuteDuration = dueTime.minute - startTime.minute;
startTime.hour = hourOfDay;
startTime.minute = minute;
startMillis = startTime.normalize(true);
mShowStart = true;
// Also update the due time to keep the duration constant.
dueTime.hour = hourOfDay + hourDuration;
dueTime.minute = minute + minuteDuration;
dueMillis = dueTime.normalize(true);
mShowDue = true;
} else {
// The due time was changed.
startMillis = startTime.toMillis(true);
dueTime.hour = hourOfDay;
dueTime.minute = minute;
dueMillis = dueTime.normalize(true);
mShowDue = true;
if (mShowStart) {
// Do not allow an event to have a due time before the start time.
if (dueTime.before(startTime)) {
dueTime.set(startTime);
dueMillis = startMillis;
}
} else {
// if start time is not shown, default it to be the same as due time
startTime.set(dueTime);
mShowStart = true;
}
}
// update all 4 buttons in case visibility has changed
setDate(mStartDateButton, startMillis, mShowStart);
setTime(mStartTimeButton, startMillis, mShowStart);
setDate(mDueDateButton, dueMillis, mShowDue);
setTime(mDueTimeButton, dueMillis, mShowDue);
updateCalendarPanel();
}
}
private class TimeClickListener implements View.OnClickListener {
private Time mTime;
public TimeClickListener(Time time) {
mTime = time;
}
public void onClick(View v) {
new TimePickerDialog(TaskEditorActivity.this, new TimeListener(v),
mTime.hour, mTime.minute,
DateFormat.is24HourFormat(TaskEditorActivity.this)).show();
}
}
private class DateListener implements OnDateSetListener {
View mView;
public DateListener(View view) {
mView = view;
}
public void onDateSet(DatePicker view, int year, int month, int monthDay) {
// Cache the member variables locally to avoid inner class overhead.
Time startTime = mStartTime;
Time dueTime = mDueTime;
// Cache the start and due millis so that we limit the number
// of calls to normalize() and toMillis(), which are fairly
// expensive.
long startMillis;
long dueMillis;
if (mView == mStartDateButton) {
// The start date was changed.
int yearDuration = dueTime.year - startTime.year;
int monthDuration = dueTime.month - startTime.month;
int monthDayDuration = dueTime.monthDay - startTime.monthDay;
startTime.year = year;
startTime.month = month;
startTime.monthDay = monthDay;
startMillis = startTime.normalize(true);
mShowStart = true;
// Also update the end date to keep the duration constant.
dueTime.year = year + yearDuration;
dueTime.month = month + monthDuration;
dueTime.monthDay = monthDay + monthDayDuration;
dueMillis = dueTime.normalize(true);
mShowDue = true;
} else {
// The end date was changed.
startMillis = startTime.toMillis(true);
dueTime.year = year;
dueTime.month = month;
dueTime.monthDay = monthDay;
dueMillis = dueTime.normalize(true);
mShowDue = true;
if (mShowStart) {
// Do not allow an event to have an end time before the start time.
if (dueTime.before(startTime)) {
dueTime.set(startTime);
dueMillis = startMillis;
}
} else {
// if start time is not shown, default it to be the same as due time
startTime.set(dueTime);
mShowStart = true;
}
}
// update all 4 buttons in case visibility has changed
setDate(mStartDateButton, startMillis, mShowStart);
setTime(mStartTimeButton, startMillis, mShowStart);
setDate(mDueDateButton, dueMillis, mShowDue);
setTime(mDueTimeButton, dueMillis, mShowDue);
updateCalendarPanel();
}
}
private class DateClickListener implements View.OnClickListener {
private Time mTime;
public DateClickListener(Time time) {
mTime = time;
}
public void onClick(View v) {
new DatePickerDialog(TaskEditorActivity.this, new DateListener(v), mTime.year,
mTime.month, mTime.monthDay).show();
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/editor/activity/TaskEditorActivity.java | Java | asf20 | 49,021 |
/*
* Copyright (C) 2009 Android Shuffle Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dodgybits.shuffle.android.editor.activity;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.model.Id;
import org.dodgybits.shuffle.android.core.model.Project;
import org.dodgybits.shuffle.android.core.model.Project.Builder;
import org.dodgybits.shuffle.android.core.model.encoding.EntityEncoder;
import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister;
import org.dodgybits.shuffle.android.list.activity.State;
import org.dodgybits.shuffle.android.persistence.provider.ContextProvider;
import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider;
import roboguice.inject.InjectView;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import com.google.inject.Inject;
public class ProjectEditorActivity extends AbstractEditorActivity<Project> {
private static final String cTag = "ProjectEditorActivity";
@InjectView(R.id.name) EditText mNameWidget;
@InjectView(R.id.default_context) Spinner mDefaultContextSpinner;
@InjectView(R.id.parallel_entry) RelativeLayout mParallelEntry;
@InjectView(R.id.parallel_label) TextView mParallelLabel;
@InjectView(R.id.parallel_icon) ImageView mParallelButton;
private @InjectView(R.id.active_entry) View mActiveEntry;
private @InjectView(R.id.active_entry_checkbox) CheckBox mActiveCheckBox;
private @InjectView(R.id.deleted_entry) View mDeletedEntry;
private CheckBox mDeletedCheckBox;
@Inject private EntityPersister<Project> mPersister;
@Inject private EntityEncoder<Project> mEncoder;
private String[] mContextNames;
private long[] mContextIds;
private boolean isParallel;
@Override
protected void onCreate(Bundle icicle) {
Log.d(cTag, "onCreate+");
super.onCreate(icicle);
loadCursor();
findViewsAndAddListeners();
if (mState == State.STATE_EDIT) {
// Make sure we are at the one and only row in the cursor.
mCursor.moveToFirst();
setTitle(R.string.title_edit_project);
mOriginalItem = mPersister.read(mCursor);
updateUIFromItem(mOriginalItem);
} else if (mState == State.STATE_INSERT) {
isParallel = false;
setTitle(R.string.title_new_project);
mDeletedEntry.setVisibility(View.GONE);
mDeletedCheckBox.setChecked(false);
mActiveCheckBox.setChecked(true);
Bundle extras = getIntent().getExtras();
updateUIFromExtras(extras);
}
}
private void findViewsAndAddListeners() {
Cursor contactCursor = getContentResolver().query(
ContextProvider.Contexts.CONTENT_URI,
new String[] {ContextProvider.Contexts._ID, ContextProvider.Contexts.NAME}, null, null, null);
int size = contactCursor.getCount() + 1;
mContextIds = new long[size];
mContextIds[0] = 0;
mContextNames = new String[size];
mContextNames[0] = getText(R.string.none_empty).toString();
for (int i = 1; i < size; i++) {
contactCursor.moveToNext();
mContextIds[i] = contactCursor.getLong(0);
mContextNames[i] = contactCursor.getString(1);
}
contactCursor.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, mContextNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mDefaultContextSpinner.setAdapter(adapter);
mParallelEntry.setOnClickListener(this);
mActiveEntry.setOnClickListener(this);
mActiveEntry.setOnFocusChangeListener(this);
mDeletedEntry.setOnClickListener(this);
mDeletedEntry.setOnFocusChangeListener(this);
mDeletedCheckBox = (CheckBox) mDeletedEntry.findViewById(R.id.deleted_entry_checkbox);
}
@Override
protected boolean isValid() {
String name = mNameWidget.getText().toString();
return !TextUtils.isEmpty(name);
}
@Override
protected void doDeleteAction() {
super.doDeleteAction();
mNameWidget.setText("");
}
@Override
protected Project createItemFromUI(boolean commitValues) {
Builder builder = Project.newBuilder();
if (mOriginalItem != null) {
builder.mergeFrom(mOriginalItem);
}
builder.setName(mNameWidget.getText().toString());
builder.setModifiedDate(System.currentTimeMillis());
builder.setParallel(isParallel);
Id defaultContextId = Id.NONE;
int selectedItemPosition = mDefaultContextSpinner.getSelectedItemPosition();
if (selectedItemPosition > 0) {
defaultContextId = Id.create(mContextIds[selectedItemPosition]);
}
builder.setDefaultContextId(defaultContextId);
builder.setDeleted(mDeletedCheckBox.isChecked());
builder.setActive(mActiveCheckBox.isChecked());
return builder.build();
}
@Override
protected void updateUIFromExtras(Bundle extras) {
// do nothing for now
}
@Override
protected void updateUIFromItem(Project project) {
mNameWidget.setTextKeepState(project.getName());
Id defaultContextId = project.getDefaultContextId();
if (defaultContextId.isInitialised()) {
for (int i = 1; i < mContextIds.length; i++) {
if (mContextIds[i] == defaultContextId.getId()) {
mDefaultContextSpinner.setSelection(i);
break;
}
}
} else {
mDefaultContextSpinner.setSelection(0);
}
isParallel = project.isParallel();
updateParallelSection();
mActiveCheckBox.setChecked(project.isActive());
mDeletedEntry.setVisibility(project.isDeleted() ? View.VISIBLE : View.GONE);
mDeletedCheckBox.setChecked(project.isDeleted());
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.parallel_entry: {
isParallel = !isParallel;
updateParallelSection();
break;
}
case R.id.active_entry: {
mActiveCheckBox.toggle();
break;
}
case R.id.deleted_entry: {
mDeletedCheckBox.toggle();
break;
}
default:
super.onClick(v);
break;
}
}
/**
* @return id of layout for this view
*/
@Override
protected int getContentViewResId() {
return R.layout.project_editor;
}
@Override
protected Intent getInsertIntent() {
return new Intent(Intent.ACTION_INSERT, ProjectProvider.Projects.CONTENT_URI);
}
@Override
protected CharSequence getItemName() {
return getString(R.string.project_name);
}
@Override
protected EntityEncoder<Project> getEncoder() {
return mEncoder;
}
@Override
protected EntityPersister<Project> getPersister() {
return mPersister;
}
private void loadCursor() {
if (mUri != null && mState == State.STATE_EDIT)
{
mCursor = managedQuery(mUri, ProjectProvider.Projects.FULL_PROJECTION, null, null, null);
if (mCursor == null || mCursor.getCount() == 0) {
// The cursor is empty. This can happen if the event was deleted.
finish();
return;
}
}
}
private void updateParallelSection() {
if (isParallel) {
mParallelLabel.setText(R.string.parallel_title);
mParallelButton.setImageResource(R.drawable.parallel);
} else {
mParallelLabel.setText(R.string.sequence_title);
mParallelButton.setImageResource(R.drawable.sequence);
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/editor/activity/ProjectEditorActivity.java | Java | asf20 | 8,950 |
/*
* Copyright (C) 2009 Android Shuffle Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dodgybits.shuffle.android.editor.activity;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity;
import org.dodgybits.shuffle.android.core.model.Entity;
import org.dodgybits.shuffle.android.core.model.Id;
import org.dodgybits.shuffle.android.core.model.encoding.EntityEncoder;
import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister;
import org.dodgybits.shuffle.android.core.view.MenuUtils;
import org.dodgybits.shuffle.android.list.activity.State;
import org.dodgybits.shuffle.android.preference.model.Preferences;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
/**
* A generic activity for editing an item in a database. This can be used either
* to simply view an item (Intent.VIEW_ACTION), view and edit an item
* (Intent.EDIT_ACTION), or create a new item (Intent.INSERT_ACTION).
*/
public abstract class AbstractEditorActivity<E extends Entity> extends
FlurryEnabledActivity implements View.OnClickListener,
View.OnFocusChangeListener {
private static final String cTag = "AbstractEditorActivity";
protected int mState;
protected Uri mUri;
protected Cursor mCursor;
protected E mOriginalItem;
protected Intent mNextIntent;
@Override
protected void onCreate(Bundle icicle) {
Log.d(cTag, "onCreate+");
super.onCreate(icicle);
processIntent();
setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
setContentView(getContentViewResId());
addSavePanelListeners();
Log.d(cTag, "onCreate-");
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
doSaveAction();
break;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void finish() {
if (mNextIntent != null) {
startActivity(mNextIntent);
}
super.finish();
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem item = menu.findItem(MenuUtils.SYNC_ID);
if (item != null) {
item.setVisible(Preferences.validateTracksSettings(this));
}
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuUtils.addEditorMenuItems(menu, mState);
MenuUtils.addPrefsHelpMenuItems(this, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle all of the possible menu actions.
switch (item.getItemId()) {
case MenuUtils.SAVE_ID:
doSaveAction();
break;
case MenuUtils.SAVE_AND_ADD_ID:
// create an Intent for the new item based on the current item
startActivity(getInsertIntent());
doSaveAction();
break;
case MenuUtils.DELETE_ID:
doDeleteAction();
finish();
break;
case MenuUtils.DISCARD_ID:
doRevertAction();
break;
case MenuUtils.REVERT_ID:
doRevertAction();
break;
}
if (MenuUtils.checkCommonItemsSelected(item, this, MenuUtils.INBOX_ID)) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
E item = createItemFromUI(false);
saveItem(outState, item);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
E item = restoreItem(savedInstanceState);
updateUIFromItem(item);
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
// Because we're emulating a ListView, we need to setSelected() for
// views as they are focused.
v.setSelected(hasFocus);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.saveButton:
doSaveAction();
break;
case R.id.discardButton:
doRevertAction();
break;
}
}
protected void doSaveAction() {
// Save or create the contact if needed
Uri result = null;
switch (mState) {
case State.STATE_EDIT:
result = save();
break;
case State.STATE_INSERT:
result = create();
break;
default:
Log.e(cTag, "Unknown state in doSaveAction: " + mState);
break;
}
if (result == null) {
setResult(RESULT_CANCELED);
} else {
setResult(RESULT_OK, new Intent().setData(result));
}
finish();
}
/**
* Take care of canceling work on a item. Deletes the item if we had created
* it, otherwise reverts to the original text.
*/
protected void doRevertAction() {
if (mCursor != null) {
if (mState == State.STATE_EDIT) {
// Put the original item back into the database
mCursor.close();
mCursor = null;
getPersister().update(mOriginalItem);
} else if (mState == State.STATE_INSERT) {
// if inserting, there's nothing to delete
}
}
setResult(RESULT_CANCELED);
finish();
}
/**
* Take care of deleting a item. Simply deletes the entry.
*/
protected void doDeleteAction() {
// if inserting, there's nothing to delete
if (mState == State.STATE_EDIT && mCursor != null) {
mCursor.close();
mCursor = null;
Id id = Id.create(ContentUris.parseId(mUri));
getPersister().updateDeletedFlag(id, true);
}
}
protected final void showSaveToast() {
String text;
if (mState == State.STATE_EDIT) {
text = getResources().getString(R.string.itemSavedToast,
getItemName());
} else {
text = getResources().getString(R.string.itemCreatedToast,
getItemName());
}
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
protected boolean isValid() {
return true;
}
protected Uri create() {
Uri uri = null;
if (isValid()) {
E item = createItemFromUI(true);
uri = getPersister().insert(item);
showSaveToast();
}
return uri;
}
protected Uri save() {
Uri uri = null;
if (isValid()) {
E item = createItemFromUI(true);
getPersister().update(item);
showSaveToast();
uri = mUri;
}
return uri;
}
protected final E restoreItem(Bundle icicle) {
return getEncoder().restore(icicle);
}
protected final void saveItem(Bundle outState, E item) {
getEncoder().save(outState, item);
}
/**
* @return id of layout for this view
*/
abstract protected int getContentViewResId();
abstract protected E createItemFromUI(boolean commitValues);
abstract protected void updateUIFromItem(E item);
abstract protected void updateUIFromExtras(Bundle extras);
abstract protected EntityPersister<E> getPersister();
abstract protected EntityEncoder<E> getEncoder();
abstract protected Intent getInsertIntent();
abstract protected CharSequence getItemName();
private void processIntent() {
final Intent intent = getIntent();
// Do some setup based on the action being performed.
final String action = intent.getAction();
mUri = intent.getData();
if (action.equals(Intent.ACTION_EDIT)) {
// Requested to edit: set that state, and the data being edited.
mState = State.STATE_EDIT;
} else if (action.equals(Intent.ACTION_INSERT)) {
// Requested to insert: set that state, and create a new entry
// in the container.
mState = State.STATE_INSERT;
} else {
// Whoops, unknown action! Bail.
Log.e(cTag, "Unknown action " + action + ", exiting");
finish();
return;
}
}
private void addSavePanelListeners() {
// Setup the bottom buttons
View view = findViewById(R.id.saveButton);
view.setOnClickListener(this);
view = findViewById(R.id.discardButton);
view.setOnClickListener(this);
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/editor/activity/AbstractEditorActivity.java | Java | asf20 | 8,288 |
/*
* Copyright (C) 2009 Android Shuffle Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dodgybits.shuffle.android.editor.activity;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity;
import roboguice.inject.InjectView;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
public class IconPickerActivity extends FlurryEnabledActivity implements OnItemClickListener {
@SuppressWarnings("unused")
private static final String cTag = "IconPickerActivity";
public static final String TYPE = "vnd.android.cursor.dir/vnd.dodgybits.icons";
@InjectView(R.id.iconGrid) GridView mGrid;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.icon_picker);
mGrid.setAdapter(new IconAdapter(this));
mGrid.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Bundle bundle = new Bundle();
int iconId = (Integer)mGrid.getAdapter().getItem(position);
String iconName = getResources().getResourceEntryName(iconId);
bundle.putString("iconName", iconName);
Intent mIntent = new Intent();
mIntent.putExtras(bundle);
setResult(RESULT_OK, mIntent);
finish();
}
public class IconAdapter extends BaseAdapter {
public IconAdapter(Context context) {
loadIcons();
}
private int[] mIconIds;
private void loadIcons() {
mIconIds = new int[] {
R.drawable.accessories_calculator,
R.drawable.accessories_text_editor,
R.drawable.applications_accessories,
R.drawable.applications_development,
R.drawable.applications_games,
R.drawable.applications_graphics,
R.drawable.applications_internet,
R.drawable.applications_office,
R.drawable.applications_system,
R.drawable.audio_x_generic,
R.drawable.camera_photo,
R.drawable.computer,
R.drawable.emblem_favorite,
R.drawable.emblem_important,
R.drawable.format_justify_fill,
R.drawable.go_home,
R.drawable.network_wireless,
R.drawable.office_calendar,
R.drawable.start_here,
R.drawable.system_file_manager,
R.drawable.system_search,
R.drawable.system_users,
R.drawable.utilities_terminal,
R.drawable.video_x_generic,
R.drawable.weather_showers_scattered,
R.drawable.x_office_address_book,
};
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(IconPickerActivity.this);
Integer iconId = mIconIds[position];
i.setImageResource(iconId);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
return i;
}
public final int getCount() {
return mIconIds.length;
}
public final Object getItem(int position) {
return mIconIds[position];
}
public final long getItemId(int position) {
return position;
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/editor/activity/IconPickerActivity.java | Java | asf20 | 4,138 |
/*
* Copyright (C) 2009 Android Shuffle Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dodgybits.shuffle.android.core.view;
import org.dodgybits.android.shuffle.R;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.util.Log;
public class AlertUtils {
private static final String cTag = "AlertUtils";
private AlertUtils() {
//deny
}
public static void showDeleteGroupWarning(final Context context,
final String groupName, final String childName,
final int childCount, final OnClickListener buttonListener) {
CharSequence title = context.getString(R.string.warning_title);
CharSequence message = context.getString(R.string.delete_warning,
groupName.toLowerCase(), childCount, childName.toLowerCase());
CharSequence deleteButtonText = context.getString(R.string.menu_delete);
CharSequence cancelButtonText = context.getString(R.string.cancel_button_title);
OnCancelListener cancelListener = new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
Log.d(cTag, "Cancelled delete. Do nothing.");
}
};
Builder builder = new Builder(context);
builder.setTitle(title).setIcon(R.drawable.dialog_warning)
.setMessage(message)
.setNegativeButton(cancelButtonText, buttonListener)
.setPositiveButton(deleteButtonText, buttonListener)
.setOnCancelListener(cancelListener);
builder.create().show();
}
public static void showCleanUpInboxMessage(final Context context) {
CharSequence title = context.getString(R.string.info_title);
CharSequence message = context.getString(R.string.clean_inbox_message);
CharSequence buttonText = context.getString(R.string.ok_button_title);
Builder builder = new Builder(context);
builder.setTitle(title).setIcon(R.drawable.dialog_information)
.setMessage(message)
.setPositiveButton(buttonText, null);
builder.create().show();
}
public static void showWarning(final Context context, final String message) {
CharSequence title = context.getString(R.string.warning_title);
CharSequence buttonText = context.getString(R.string.ok_button_title);
Builder builder = new Builder(context);
builder.setTitle(title).setIcon(R.drawable.dialog_warning)
.setMessage(message)
.setPositiveButton(buttonText, null);
builder.create().show();
}
public static void showFileExistsWarning(final Context context, final String filename,
final OnClickListener buttonListener, final OnCancelListener cancelListener) {
CharSequence title = context.getString(R.string.warning_title);
CharSequence message = context.getString(R.string.warning_filename_exists, filename);
CharSequence replaceButtonText = context.getString(R.string.replace_button_title);
CharSequence cancelButtonText = context.getString(R.string.cancel_button_title);
Builder builder = new Builder(context);
builder.setTitle(title).setIcon(R.drawable.dialog_warning)
.setMessage(message)
.setNegativeButton(cancelButtonText, buttonListener)
.setPositiveButton(replaceButtonText, buttonListener)
.setOnCancelListener(cancelListener);
builder.create().show();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/view/AlertUtils.java | Java | asf20 | 3,820 |
package org.dodgybits.shuffle.android.core.view;
import android.content.res.Resources;
import android.text.TextUtils;
public class ContextIcon {
private static final String cPackage = "org.dodgybits.android.shuffle";
private static final String cType = "drawable";
public static final ContextIcon NONE = new ContextIcon(null, 0, 0);
public final String iconName;
public final int largeIconId;
public final int smallIconId;
private ContextIcon(String iconName, int largeIconId, int smallIconId) {
this.iconName = iconName;
this.largeIconId = largeIconId;
this.smallIconId = smallIconId;
}
public static ContextIcon createIcon(String iconName, Resources res) {
if (TextUtils.isEmpty(iconName)) return NONE;
int largeId = res.getIdentifier(iconName, cType, cPackage);
int smallId = res.getIdentifier(iconName + "_small", cType, cPackage);
return new ContextIcon(iconName, largeId, smallId);
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/view/ContextIcon.java | Java | asf20 | 1,012 |
/*
* Copyright (C) 2009 Android Shuffle Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dodgybits.shuffle.android.core.view;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.activity.HelpActivity;
import org.dodgybits.shuffle.android.list.activity.ContextsActivity;
import org.dodgybits.shuffle.android.list.activity.ProjectsActivity;
import org.dodgybits.shuffle.android.list.activity.State;
import org.dodgybits.shuffle.android.list.activity.expandable.ExpandableContextsActivity;
import org.dodgybits.shuffle.android.list.activity.expandable.ExpandableProjectsActivity;
import org.dodgybits.shuffle.android.list.activity.task.*;
import org.dodgybits.shuffle.android.preference.activity.PreferencesActivity;
import org.dodgybits.shuffle.android.preference.model.Preferences;
import org.dodgybits.shuffle.android.synchronisation.tracks.activity.SynchronizeActivity;
public class MenuUtils {
private static final String cTag = "MenuUtils";
private MenuUtils() {
// deny
}
// Identifiers for our menu items.
public static final int SAVE_ID = Menu.FIRST;
public static final int SAVE_AND_ADD_ID = Menu.FIRST + 1;
public static final int REVERT_ID = Menu.FIRST + 2;
public static final int DISCARD_ID = Menu.FIRST + 3;
public static final int DELETE_ID = Menu.FIRST + 4;
public static final int INSERT_ID = Menu.FIRST + 5;
public static final int INSERT_CHILD_ID = Menu.FIRST + 6;
public static final int INSERT_GROUP_ID = Menu.FIRST + 7;
public static final int INBOX_ID = Menu.FIRST + 10;
public static final int CALENDAR_ID = Menu.FIRST + 11;
public static final int TOP_TASKS_ID = Menu.FIRST + 12;
public static final int PROJECT_ID = Menu.FIRST + 13;
public static final int CONTEXT_ID = Menu.FIRST + 14;
public static final int TICKLER_ID = Menu.FIRST + 15;
public static final int PREFERENCE_ID = Menu.FIRST + 20;
public static final int HELP_ID = Menu.FIRST + 21;
public static final int SYNC_ID = Menu.FIRST + 22;
public static final int SEARCH_ID = Menu.FIRST + 23;
public static final int CLEAN_INBOX_ID = Menu.FIRST + 50;
public static final int PERMANENTLY_DELETE_ID = Menu.FIRST + 51;
// Menu item for activity specific items
public static final int PUT_BACK_ID = Menu.FIRST + 100;
public static final int COMPLETE_ID = Menu.FIRST + 101;
public static final int MOVE_UP_ID = Menu.FIRST + 102;
public static final int MOVE_DOWN_ID = Menu.FIRST + 103;
// Editor menus
private static final int SAVE_ORDER = 1;
private static final int SAVE_AND_ADD_ORDER = 2;
private static final int REVERT_ORDER = 3;
private static final int DISCARD_ORDER = 3;
// Context menus
private static final int EDIT_ORDER = 1;
private static final int PUT_BACK_ORDER = 3;
private static final int COMPLETE_ORDER = 4;
private static final int MOVE_UP_ORDER = 5;
private static final int MOVE_DOWN_ORDER = 6;
private static final int DELETE_ORDER = 10;
// List menus
private static final int INSERT_ORDER = 1;
private static final int INSERT_CHILD_ORDER = 1;
private static final int INSERT_GROUP_ORDER = 2;
private static final int CLEAN_INBOX_ORDER = 101;
private static final int PERMANENTLY_DELETE_ORDER = 102;
// General menus
private static final int PERSPECTIVE_ORDER = 201;
private static final int PREFERENCE_ORDER = 202;
private static final int SYNCH_ORDER = 203;
private static final int SEARCH_ORDER = 204;
private static final int HELP_ORDER = 205;
public static void addInsertMenuItems(Menu menu, String itemName, boolean isTaskList, Context context) {
String menuName = context.getResources().getString(R.string.menu_insert, itemName);
menu.add(Menu.NONE, INSERT_ID, INSERT_ORDER, menuName)
.setIcon(android.R.drawable.ic_menu_add)
.setAlphabeticShortcut(isTaskList ? 'c' : 'a');
}
public static void addExpandableInsertMenuItems(Menu menu, String groupName, String childName, Context context) {
String menuName;
menuName = context.getResources().getString(R.string.menu_insert, childName);
menu.add(Menu.NONE, INSERT_CHILD_ID, INSERT_CHILD_ORDER, menuName)
.setIcon(android.R.drawable.ic_menu_add).setAlphabeticShortcut('c');
menuName = context.getResources().getString(R.string.menu_insert, groupName);
menu.add(Menu.NONE, INSERT_GROUP_ID, INSERT_GROUP_ORDER, menuName)
.setIcon(android.R.drawable.ic_menu_add).setAlphabeticShortcut('a');
}
public static void addViewMenuItems(Menu menu, int currentViewMenuId) {
SubMenu viewMenu = menu.addSubMenu(Menu.NONE, Menu.NONE, PERSPECTIVE_ORDER, R.string.menu_view)
.setIcon(R.drawable.preferences_system_windows);
viewMenu.add(Menu.NONE, INBOX_ID, 0, R.string.title_inbox)
.setChecked(INBOX_ID == currentViewMenuId);
viewMenu.add(Menu.NONE, CALENDAR_ID, 1, R.string.title_due_tasks)
.setChecked(CALENDAR_ID == currentViewMenuId);
viewMenu.add(Menu.NONE, TOP_TASKS_ID, 2, R.string.title_next_tasks)
.setChecked(TOP_TASKS_ID == currentViewMenuId);
viewMenu.add(Menu.NONE, PROJECT_ID, 3, R.string.title_project)
.setChecked(PROJECT_ID == currentViewMenuId);
viewMenu.add(Menu.NONE, CONTEXT_ID, 4, R.string.title_context)
.setChecked(CONTEXT_ID == currentViewMenuId);
viewMenu.add(Menu.NONE, TICKLER_ID, 5, R.string.title_tickler)
.setChecked(TICKLER_ID == currentViewMenuId);
}
public static void addEditorMenuItems(Menu menu, int state) {
menu.add(Menu.NONE, SAVE_ID, SAVE_ORDER, R.string.menu_save)
.setIcon(android.R.drawable.ic_menu_save).setAlphabeticShortcut('s');
menu.add(Menu.NONE, SAVE_AND_ADD_ID, SAVE_AND_ADD_ORDER, R.string.menu_save_and_add)
.setIcon(android.R.drawable.ic_menu_save);
// Build the menus that are shown when editing.
if (state == State.STATE_EDIT) {
menu.add(Menu.NONE, REVERT_ID, REVERT_ORDER, R.string.menu_revert)
.setIcon(android.R.drawable.ic_menu_revert).setAlphabeticShortcut('r');
menu.add(Menu.NONE, DELETE_ID, DELETE_ORDER, R.string.menu_delete)
.setIcon(android.R.drawable.ic_menu_delete).setAlphabeticShortcut('d');
// Build the menus that are shown when inserting.
} else {
menu.add(Menu.NONE, DISCARD_ID, DISCARD_ORDER, R.string.menu_discard)
.setIcon(android.R.drawable.ic_menu_close_clear_cancel).setAlphabeticShortcut('d');
}
}
public static void addPrefsHelpMenuItems(Context context, Menu menu) {
menu.add(Menu.NONE, PREFERENCE_ID, PREFERENCE_ORDER, R.string.menu_preferences)
.setIcon(android.R.drawable.ic_menu_preferences).setAlphabeticShortcut('p');
menu.add(Menu.NONE, HELP_ID, HELP_ORDER, R.string.menu_help)
.setIcon(android.R.drawable.ic_menu_help).setAlphabeticShortcut('h');
}
public static void addSyncMenuItem(Context context, Menu menu) {
menu.add(Menu.NONE, SYNC_ID, SYNCH_ORDER, R.string.menu_sync)
.setIcon(android.R.drawable.ic_menu_rotate).setVisible(Preferences.validateTracksSettings(context));
}
public static void addSearchMenuItem(Context context, Menu menu) {
menu.add(Menu.NONE, SEARCH_ID, SEARCH_ORDER, R.string.menu_search)
.setIcon(android.R.drawable.ic_menu_search).setAlphabeticShortcut('s');
}
public static void addSelectedAlternativeMenuItems(Menu menu, Uri uri, boolean includeView) {
// Build menu... always starts with the EDIT action...
int viewIndex = 0;
int editIndex = (includeView ? 1 : 0);
Intent[] specifics = new Intent[editIndex + 1];
MenuItem[] items = new MenuItem[editIndex + 1];
if (includeView) {
specifics[viewIndex] = new Intent(Intent.ACTION_VIEW, uri);
}
specifics[editIndex] = new Intent(Intent.ACTION_EDIT, uri);
// ... is followed by whatever other actions are available...
Intent intent = new Intent(null, uri);
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, Menu.NONE, EDIT_ORDER, null, specifics,
intent, 0, items);
// Give a shortcut to the edit action.
if (items[editIndex] != null) {
items[editIndex].setAlphabeticShortcut('e');
items[editIndex].setIcon(android.R.drawable.ic_menu_edit);
}
if (includeView && items[viewIndex] != null) {
items[viewIndex].setAlphabeticShortcut('v');
items[viewIndex].setIcon(android.R.drawable.ic_menu_view);
}
}
public static void addPutBackMenuItem(Menu menu) {
menu.add(Menu.CATEGORY_ALTERNATIVE, PUT_BACK_ID, PUT_BACK_ORDER, R.string.menu_put_back);
}
public static void addCompleteMenuItem(Menu menu, boolean isComplete) {
int labelId = isComplete ? R.string.menu_incomplete : R.string.menu_complete;
menu.add(Menu.CATEGORY_ALTERNATIVE, COMPLETE_ID, COMPLETE_ORDER, labelId)
.setIcon(R.drawable.btn_check_on).setAlphabeticShortcut('x');
}
public static void addDeleteMenuItem(Menu menu, boolean isDeleted) {
int labelId = isDeleted ? R.string.menu_undelete : R.string.menu_delete;
menu.add(Menu.CATEGORY_ALTERNATIVE, DELETE_ID, DELETE_ORDER, labelId)
.setIcon(android.R.drawable.ic_menu_delete).setAlphabeticShortcut('d');
}
public static void addCleanInboxMenuItem(Menu menu) {
menu.add(Menu.NONE, CLEAN_INBOX_ID, CLEAN_INBOX_ORDER, R.string.clean_inbox_button_title)
.setIcon(R.drawable.edit_clear).setAlphabeticShortcut('i');
}
public static void addPermanentlyDeleteMenuItem(Menu menu) {
menu.add(Menu.NONE, PERMANENTLY_DELETE_ID, PERMANENTLY_DELETE_ORDER, R.string.permanently_delete_button_title)
.setIcon(R.drawable.icon_delete);
}
public static void addMoveMenuItems(Menu menu, boolean enableUp, boolean enableDown) {
if (enableUp) {
menu.add(Menu.CATEGORY_ALTERNATIVE, MOVE_UP_ID, MOVE_UP_ORDER, R.string.menu_move_up)
.setIcon(R.drawable.go_up).setAlphabeticShortcut('k');
}
if (enableDown) {
menu.add(Menu.CATEGORY_ALTERNATIVE, MOVE_DOWN_ID, MOVE_DOWN_ORDER, R.string.menu_move_down)
.setIcon(R.drawable.go_down).setAlphabeticShortcut('j');
}
}
public static boolean checkCommonItemsSelected(MenuItem item, Activity activity, int currentViewMenuId) {
return checkCommonItemsSelected(item.getItemId(), activity, currentViewMenuId, true);
}
public static boolean checkCommonItemsSelected(int menuItemId, Activity activity, int currentViewMenuId) {
return checkCommonItemsSelected(menuItemId, activity, currentViewMenuId, true);
}
public static boolean checkCommonItemsSelected(int menuItemId, Activity activity, int currentViewMenuId, boolean finishCurrentActivity) {
switch (menuItemId) {
case MenuUtils.INBOX_ID:
if (currentViewMenuId != INBOX_ID) {
Log.d(cTag, "Switching to inbox");
activity.startActivity(new Intent(activity, InboxActivity.class));
if (finishCurrentActivity) activity.finish();
}
return true;
case MenuUtils.CALENDAR_ID:
if (currentViewMenuId != CALENDAR_ID) {
Log.d(cTag, "Switching to calendar");
activity.startActivity(new Intent(activity, TabbedDueActionsActivity.class));
if (finishCurrentActivity) activity.finish();
}
return true;
case MenuUtils.TOP_TASKS_ID:
if (currentViewMenuId != TOP_TASKS_ID) {
Log.d(cTag, "Switching to top tasks");
activity.startActivity(new Intent(activity, TopTasksActivity.class));
if (finishCurrentActivity) activity.finish();
}
return true;
case MenuUtils.PROJECT_ID:
if (currentViewMenuId != PROJECT_ID) {
Log.d(cTag, "Switching to project list");
Class<? extends Activity> activityClass = null;
if (Preferences.isProjectViewExpandable(activity)) {
activityClass = ExpandableProjectsActivity.class;
} else {
activityClass = ProjectsActivity.class;
}
activity.startActivity(new Intent(activity, activityClass));
if (finishCurrentActivity) activity.finish();
}
return true;
case CONTEXT_ID:
if (currentViewMenuId != CONTEXT_ID) {
Log.d(cTag, "Switching to context list");
Class<? extends Activity> activityClass = null;
if (Preferences.isContextViewExpandable(activity)) {
activityClass = ExpandableContextsActivity.class;
} else {
activityClass = ContextsActivity.class;
}
activity.startActivity(new Intent(activity, activityClass));
if (finishCurrentActivity) activity.finish();
}
return true;
case TICKLER_ID:
Log.d(cTag, "Switching to tickler list");
activity.startActivity(new Intent(activity, TicklerActivity.class));
return true;
case PREFERENCE_ID:
Log.d(cTag, "Bringing up preferences");
activity.startActivity(new Intent(activity, PreferencesActivity.class));
return true;
case HELP_ID:
Log.d(cTag, "Bringing up help");
Intent intent = new Intent(activity, HelpActivity.class);
intent.putExtra(HelpActivity.cHelpPage, getHelpScreen(currentViewMenuId));
activity.startActivity(intent);
return true;
case SYNC_ID:
Log.d(cTag, "starting sync");
activity.startActivity(new Intent(activity, SynchronizeActivity.class));
return true;
case SEARCH_ID:
Log.d(cTag, "starting search");
activity.onSearchRequested();
return true;
}
return false;
}
private static int getHelpScreen(int currentViewMenuId) {
int result = 0;
switch (currentViewMenuId) {
case INBOX_ID:
result = 1;
break;
case PROJECT_ID:
result = 2;
break;
case CONTEXT_ID:
result = 3;
break;
case TOP_TASKS_ID:
result = 4;
break;
case CALENDAR_ID:
result = 5;
break;
}
return result;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/view/MenuUtils.java | Java | asf20 | 15,259 |
package org.dodgybits.shuffle.android.core.view;
import org.dodgybits.android.shuffle.R;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class IconArrayAdapter extends ArrayAdapter<CharSequence> {
private Integer[] mIconIds;
public IconArrayAdapter(
Context context, int resource,
int textViewResourceId, CharSequence[] objects,
Integer[] iconIds) {
super(context, resource, textViewResourceId, objects);
mIconIds = iconIds;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView nameView = (TextView) view.findViewById(R.id.name);
// don't use toString in order to preserve colour change
nameView.setText(getItem(position));
Integer iconId = null;
if (position < mIconIds.length) {
iconId = mIconIds[position];
if (iconId != null) {
nameView.setCompoundDrawablesWithIntrinsicBounds(
getContext().getResources().getDrawable(iconId), null, null, null);
}
}
return view;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/view/IconArrayAdapter.java | Java | asf20 | 1,214 |
/*
* Copyright (C) 2009 Android Shuffle Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dodgybits.shuffle.android.core.view;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
public class DrawableUtils {
private DrawableUtils() {
//deny
}
public static GradientDrawable createGradient(int colour, Orientation orientation) {
return createGradient(colour, orientation, 1.1f, 0.9f);
}
public static GradientDrawable createGradient(int colour, Orientation orientation, float startOffset, float endOffset) {
int[] colours = new int[2];
float[] hsv1 = new float[3];
float[] hsv2 = new float[3];
Color.colorToHSV(colour, hsv1);
Color.colorToHSV(colour, hsv2);
hsv1[2] *= startOffset;
hsv2[2] *= endOffset;
colours[0] = Color.HSVToColor(hsv1);
colours[1] = Color.HSVToColor(hsv2);
return new GradientDrawable(orientation, colours);
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/view/DrawableUtils.java | Java | asf20 | 1,533 |
package org.dodgybits.shuffle.android.core.configuration;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.model.Context;
import org.dodgybits.shuffle.android.core.model.Project;
import org.dodgybits.shuffle.android.core.model.Task;
import org.dodgybits.shuffle.android.core.model.encoding.ContextEncoder;
import org.dodgybits.shuffle.android.core.model.encoding.EntityEncoder;
import org.dodgybits.shuffle.android.core.model.encoding.ProjectEncoder;
import org.dodgybits.shuffle.android.core.model.encoding.TaskEncoder;
import org.dodgybits.shuffle.android.core.model.persistence.ContextPersister;
import org.dodgybits.shuffle.android.core.model.persistence.DefaultEntityCache;
import org.dodgybits.shuffle.android.core.model.persistence.EntityCache;
import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister;
import org.dodgybits.shuffle.android.core.model.persistence.ProjectPersister;
import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister;
import org.dodgybits.shuffle.android.core.model.persistence.selector.Flag;
import org.dodgybits.shuffle.android.core.view.MenuUtils;
import org.dodgybits.shuffle.android.list.annotation.ContextTasks;
import org.dodgybits.shuffle.android.list.annotation.Contexts;
import org.dodgybits.shuffle.android.list.annotation.DueTasks;
import org.dodgybits.shuffle.android.list.annotation.ExpandableContexts;
import org.dodgybits.shuffle.android.list.annotation.ExpandableProjects;
import org.dodgybits.shuffle.android.list.annotation.Inbox;
import org.dodgybits.shuffle.android.list.annotation.ProjectTasks;
import org.dodgybits.shuffle.android.list.annotation.Projects;
import org.dodgybits.shuffle.android.list.annotation.Tickler;
import org.dodgybits.shuffle.android.list.annotation.TopTasks;
import org.dodgybits.shuffle.android.list.config.AbstractTaskListConfig;
import org.dodgybits.shuffle.android.list.config.ContextListConfig;
import org.dodgybits.shuffle.android.list.config.ContextTasksListConfig;
import org.dodgybits.shuffle.android.list.config.DueActionsListConfig;
import org.dodgybits.shuffle.android.list.config.ProjectListConfig;
import org.dodgybits.shuffle.android.list.config.ProjectTasksListConfig;
import org.dodgybits.shuffle.android.list.config.StandardTaskQueries;
import org.dodgybits.shuffle.android.list.config.TaskListConfig;
import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings;
import android.content.ContextWrapper;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.TypeLiteral;
public class ShuffleModule extends AbstractModule {
@Override
protected void configure() {
addCaches();
addPersisters();
addEncoders();
addListPreferenceSettings();
addListConfig();
}
private void addCaches() {
bind(new TypeLiteral<EntityCache<Context>>() {}).to(new TypeLiteral<DefaultEntityCache<Context>>() {});
bind(new TypeLiteral<EntityCache<Project>>() {}).to(new TypeLiteral<DefaultEntityCache<Project>>() {});
}
private void addPersisters() {
bind(new TypeLiteral<EntityPersister<Context>>() {}).to(ContextPersister.class);
bind(new TypeLiteral<EntityPersister<Project>>() {}).to(ProjectPersister.class);
bind(new TypeLiteral<EntityPersister<Task>>() {}).to(TaskPersister.class);
}
private void addEncoders() {
bind(new TypeLiteral<EntityEncoder<Context>>() {}).to(ContextEncoder.class);
bind(new TypeLiteral<EntityEncoder<Project>>() {}).to(ProjectEncoder.class);
bind(new TypeLiteral<EntityEncoder<Task>>() {}).to(TaskEncoder.class);
}
private void addListPreferenceSettings() {
bind(ListPreferenceSettings.class).annotatedWith(Inbox.class).toInstance(
new ListPreferenceSettings(StandardTaskQueries.cInbox));
bind(ListPreferenceSettings.class).annotatedWith(TopTasks.class).toInstance(
new ListPreferenceSettings(StandardTaskQueries.cNextTasks)
.setDefaultCompleted(Flag.no)
.disableCompleted()
.disableDeleted()
.disableActive());
ListPreferenceSettings projectSettings = new ListPreferenceSettings(StandardTaskQueries.cProjectFilterPrefs);
bind(ListPreferenceSettings.class).annotatedWith(ProjectTasks.class).toInstance(projectSettings);
bind(ListPreferenceSettings.class).annotatedWith(Projects.class).toInstance(projectSettings);
bind(ListPreferenceSettings.class).annotatedWith(ExpandableProjects.class).toInstance(projectSettings);
ListPreferenceSettings contextSettings = new ListPreferenceSettings(StandardTaskQueries.cContextFilterPrefs);
bind(ListPreferenceSettings.class).annotatedWith(ContextTasks.class).toInstance(contextSettings);
bind(ListPreferenceSettings.class).annotatedWith(Contexts.class).toInstance(contextSettings);
bind(ListPreferenceSettings.class).annotatedWith(ExpandableContexts.class).toInstance(contextSettings);
bind(ListPreferenceSettings.class).annotatedWith(DueTasks.class).toInstance(
new ListPreferenceSettings(StandardTaskQueries.cDueTasksFilterPrefs).setDefaultCompleted(Flag.no));
bind(ListPreferenceSettings.class).annotatedWith(Tickler.class).toInstance(
new ListPreferenceSettings(StandardTaskQueries.cTickler)
.setDefaultCompleted(Flag.no)
.setDefaultActive(Flag.no));
}
private void addListConfig() {
bind(DueActionsListConfig.class).annotatedWith(DueTasks.class).to(DueActionsListConfig.class);
bind(ContextTasksListConfig.class).annotatedWith(ContextTasks.class).to(ContextTasksListConfig.class);
bind(ProjectTasksListConfig.class).annotatedWith(ProjectTasks.class).to(ProjectTasksListConfig.class);
bind(ProjectListConfig.class).annotatedWith(Projects.class).to(ProjectListConfig.class);
bind(ContextListConfig.class).annotatedWith(Contexts.class).to(ContextListConfig.class);
}
@Provides @Inbox
TaskListConfig providesInboxTaskListConfig(TaskPersister taskPersister, @Inbox ListPreferenceSettings settings) {
return new AbstractTaskListConfig(
StandardTaskQueries.getQuery(StandardTaskQueries.cInbox),
taskPersister, settings) {
public int getCurrentViewMenuId() {
return MenuUtils.INBOX_ID;
}
public String createTitle(ContextWrapper context)
{
return context.getString(R.string.title_inbox);
}
};
}
@Provides @TopTasks
TaskListConfig providesTopTasksTaskListConfig(TaskPersister taskPersister, @TopTasks ListPreferenceSettings settings) {
return new AbstractTaskListConfig(
StandardTaskQueries.getQuery(StandardTaskQueries.cNextTasks),
taskPersister, settings) {
public int getCurrentViewMenuId() {
return MenuUtils.TOP_TASKS_ID;
}
public String createTitle(ContextWrapper context)
{
return context.getString(R.string.title_next_tasks);
}
};
}
@Provides @Tickler
TaskListConfig providesTicklerTaskListConfig(TaskPersister taskPersister, @Tickler ListPreferenceSettings settings) {
return new AbstractTaskListConfig(
StandardTaskQueries.getQuery(StandardTaskQueries.cTickler),
taskPersister, settings) {
public int getCurrentViewMenuId() {
return MenuUtils.INBOX_ID;
}
public String createTitle(ContextWrapper context)
{
return context.getString(R.string.title_tickler);
}
};
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/configuration/ShuffleModule.java | Java | asf20 | 7,887 |
package org.dodgybits.shuffle.android.core.util;
import java.lang.reflect.Field;
import android.os.Build;
public class OSUtils {
public static boolean osAtLeastFroyo() {
boolean isFroyoOrAbove = false;
try {
Field field = Build.VERSION.class.getDeclaredField("SDK_INT");
int version = field.getInt(null);
isFroyoOrAbove = version >= Build.VERSION_CODES.FROYO;
} catch (Exception e) {
// ignore exception - field not available
}
return isFroyoOrAbove;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/util/OSUtils.java | Java | asf20 | 565 |
package org.dodgybits.shuffle.android.core.util;
import java.util.List;
public class StringUtils {
public static String repeat(int count, String token) {
return repeat(count, token, "");
}
public static String repeat(int count, String token, String delim) {
StringBuilder builder = new StringBuilder();
for (int i = 1; i <= count; i++) {
builder.append(token);
if (i < count) {
builder.append(delim);
}
}
return builder.toString();
}
public static String join(List<String> items, String delim) {
StringBuilder result = new StringBuilder();
final int len = items.size();
for(int i = 0; i < len; i++) {
result.append(items.get(i));
if (i < len - 1) {
result.append(delim);
}
}
return result.toString();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/util/StringUtils.java | Java | asf20 | 839 |
/*
* Copyright (C) 2009 Android Shuffle Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dodgybits.shuffle.android.core.util;
import static android.text.format.DateUtils.FORMAT_ABBREV_MONTH;
import static android.text.format.DateUtils.FORMAT_ABBREV_TIME;
import static android.text.format.DateUtils.FORMAT_SHOW_DATE;
import static android.text.format.DateUtils.FORMAT_SHOW_TIME;
import java.lang.ref.SoftReference;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.content.Context;
import android.text.format.Time;
public class DateUtils {
/**
* Lazily create date format objects, one per thread. Use soft references so format
* may be collected when low on memory.
*/
private static final ThreadLocal<SoftReference<DateFormat>> cDateFormat =
new ThreadLocal<SoftReference<DateFormat>>() {
private SoftReference<DateFormat> createValue() {
return new SoftReference<DateFormat>(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"));
}
@Override
public SoftReference<DateFormat> get() {
SoftReference<DateFormat> value = super.get();
if (value == null || value.get() == null) {
value = createValue();
set(value);
}
return value;
}
};
/**
* Accepts strings in ISO 8601 format. This includes the following cases:
* <ul>
* <li>2009-08-15T12:50:03+01:00</li>
* <li>2009-08-15T12:50:03+0200</li>
* <li>2010-04-07T04:00:00Z</li>
* </ul>
*/
public static long parseIso8601Date(String dateStr) throws ParseException {
// normalize timezone first
String timezone = dateStr.substring(19);
timezone = timezone.replaceAll(":", "");
if ("Z".equals(timezone)) {
// Z indicates UTC, so convert to standard representation
timezone = "+0000";
}
String cleanedDateStr = dateStr.substring(0, 19) + timezone;
DateFormat f = cDateFormat.get().get();
Date d = f.parse(cleanedDateStr);
return d.getTime();
}
public static String formatIso8601Date(long ms) {
DateFormat f = cDateFormat.get().get();
String dateStr = f.format(new Date(ms));
if (dateStr.length() == 24) {
dateStr = dateStr.substring(0, 22) + ":" + dateStr.substring(22);
}
return dateStr;
}
public static boolean isSameDay(long millisX, long millisY) {
return Time.getJulianDay(millisX, 0) == Time.getJulianDay(millisY, 0);
}
public static CharSequence displayDateRange(Context context, long startMs, long endMs, boolean includeTime) {
CharSequence result = "";
final boolean includeStart = startMs > 0L;
final boolean includeEnd = endMs > 0L;
if (includeStart) {
if (includeEnd) {
int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
if (includeTime) {
flags |= FORMAT_SHOW_TIME | FORMAT_ABBREV_TIME;
}
result = android.text.format.DateUtils.formatDateRange(
context, startMs, endMs, flags);
} else {
result = displayShortDateTime(context, startMs);
}
} else if (includeEnd) {
result = displayShortDateTime(context, endMs);
}
return result;
}
/**
* Display date time in short format using the user's date format settings
* as a guideline.
*
* For epoch, display nothing.
* For today, only show the time.
* Otherwise, only show the day and month.
*
* @param context
* @param timeInMs datetime to display
* @return locale specific representation
*/
public static CharSequence displayShortDateTime(Context context, long timeInMs) {
long now = System.currentTimeMillis();
CharSequence result;
if (timeInMs == 0L) {
result = "";
} else {
int flags;
if (isSameDay(timeInMs, now)) {
flags = FORMAT_SHOW_TIME | FORMAT_ABBREV_TIME;
} else {
flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
}
result = android.text.format.DateUtils.formatDateRange(
context, timeInMs, timeInMs, flags);
}
return result;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/util/DateUtils.java | Java | asf20 | 5,036 |
package org.dodgybits.shuffle.android.core.util;
import android.net.Uri;
public class CalendarUtils {
// We can't use the constants from the provider since it's not a public portion of the SDK.
private static final Uri CALENDAR_CONTENT_URI =
Uri.parse("content://calendar/calendars"); // Calendars.CONTENT_URI
private static final Uri CALENDAR_CONTENT_URI_FROYO_PLUS =
Uri.parse("content://com.android.calendar/calendars"); // Calendars.CONTENT_URI
private static final Uri EVENT_CONTENT_URI =
Uri.parse("content://calendar/events"); // Calendars.CONTENT_URI
private static final Uri EVENT_CONTENT_URI_FROYO_PLUS =
Uri.parse("content://com.android.calendar/events"); // Calendars.CONTENT_URI
public static final String EVENT_BEGIN_TIME = "beginTime"; // android.provider.Calendar.EVENT_BEGIN_TIME
public static final String EVENT_END_TIME = "endTime"; // android.provider.Calendar.EVENT_END_TIME
public static Uri getCalendarContentUri() {
Uri uri;
if(OSUtils.osAtLeastFroyo()) {
uri = CALENDAR_CONTENT_URI_FROYO_PLUS;
} else {
uri = CALENDAR_CONTENT_URI;
}
return uri;
}
public static Uri getEventContentUri() {
Uri uri;
if(OSUtils.osAtLeastFroyo()) {
uri = EVENT_CONTENT_URI_FROYO_PLUS;
} else {
uri = EVENT_CONTENT_URI;
}
return uri;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/util/CalendarUtils.java | Java | asf20 | 1,459 |
package org.dodgybits.shuffle.android.core.util;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import android.util.Log;
/**
* Generic in-memory cache based on Romain Guy's suggestion.
* See http://code.google.com/events/io/2009/sessions/TurboChargeUiAndroidFast.html
*/
public class ItemCache<K,V> {
private static final String cTag = "ItemCache";
private final HashMap<K, SoftReference<V>> mCache;
private final ValueBuilder<K,V> mBuilder;
public ItemCache(ValueBuilder<K,V> builder) {
mCache = new HashMap<K, SoftReference<V>>();
mBuilder = builder;
}
public void put(K key, V value) {
mCache.put(key, new SoftReference<V>(value));
}
public V get(K key) {
V value = null;
SoftReference<V> reference = mCache.get(key);
if (reference != null) {
value = reference.get();
}
// not in cache or gc'd
if (value == null) {
Log.d(cTag, "Cache miss for " + key);
value = mBuilder.build(key);
put(key, value);
}
return value;
}
public void remove(K key) {
mCache.remove(key);
}
public void clear() {
mCache.clear();
}
public interface ValueBuilder<K,V> {
V build(K key);
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/util/ItemCache.java | Java | asf20 | 1,382 |
package org.dodgybits.shuffle.android.core.util;
public final class Constants {
private Constants() {
//deny
}
public static final String cPackage = "org.dodgybits.android.shuffle";
public static final int cVersion = 40;
public static final String cFlurryApiKey = "T7KF1PCGVU6V2FS8LILF";
public static final String cFlurryCreateEntityEvent = "createEntity";
public static final String cFlurryUpdateEntityEvent = "updateEntity";
public static final String cFlurryDeleteEntityEvent = "deleteEntity";
public static final String cFlurryReorderTasksEvent = "reorderTasks";
public static final String cFlurryCompleteTaskEvent = "completeTask";
public static final String cFlurryTracksSyncStartedEvent = "tracsSyncStarted";
public static final String cFlurryTracksSyncCompletedEvent = "tracsSyncCompleted";
public static final String cFlurryTracksSyncError = "tracksSyncError";
public static final String cFlurryCountParam = "count";
public static final String cFlurryEntityTypeParam = "entityType";
public static final String cFlurryCalendarUpdateError = "calendarUpdateError";
public static final String cIdType = "id";
public static final String cStringType = "string";
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/util/Constants.java | Java | asf20 | 1,292 |
/*
* Copyright (C) 2009 Android Shuffle Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dodgybits.shuffle.android.core.util;
import org.dodgybits.android.shuffle.R;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
public class TextColours {
private static final String cTag = "TextColours";
private static TextColours instance = null;
private int[] textColours;
private int[] bgColours;
public static TextColours getInstance(Context context) {
if (instance == null) {
instance = new TextColours(context);
}
return instance;
}
private TextColours(Context context) {
Log.d(cTag, "Fetching colours");
String[] colourStrings = context.getResources().getStringArray(R.array.text_colours);
Log.d(cTag, "Fetched colours");
textColours = parseColourString(colourStrings);
colourStrings = context.getResources().getStringArray(R.array.background_colours);
bgColours = parseColourString(colourStrings);
}
private int[] parseColourString(String[] colourStrings) {
int[] colours = new int[colourStrings.length];
for (int i = 0; i < colourStrings.length; i++) {
String colourString = '#' + colourStrings[i].substring(1);
Log.d(cTag, "Parsing " + colourString);
colours[i] = Color.parseColor(colourString);
}
return colours;
}
public int getNumColours() {
return textColours.length;
}
public int getTextColour(int position) {
return textColours[position];
}
public int getBackgroundColour(int position) {
return bgColours[position];
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/util/TextColours.java | Java | asf20 | 2,088 |
package org.dodgybits.shuffle.android.core.model.protocol;
import java.util.HashMap;
import java.util.Map;
import org.dodgybits.shuffle.android.core.model.Id;
public class HashEntityDirectory<Entity> implements EntityDirectory<Entity> {
private Map<String,Entity> mItemsByName;
private Map<Id, Entity> mItemsById;
public HashEntityDirectory() {
mItemsByName = new HashMap<String,Entity>();
mItemsById = new HashMap<Id,Entity>();
}
public void addItem(Id id, String name, Entity item) {
mItemsById.put(id, item);
mItemsByName.put(name, item);
}
@Override
public Entity findById(Id id) {
return mItemsById.get(id);
}
@Override
public Entity findByName(String name) {
return mItemsByName.get(name);
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/protocol/HashEntityDirectory.java | Java | asf20 | 736 |
package org.dodgybits.shuffle.android.core.model.protocol;
import org.dodgybits.shuffle.android.core.model.Context;
import org.dodgybits.shuffle.android.core.model.Id;
import org.dodgybits.shuffle.android.core.model.Project;
import org.dodgybits.shuffle.dto.ShuffleProtos.Project.Builder;
public class ProjectProtocolTranslator implements EntityProtocolTranslator<Project, org.dodgybits.shuffle.dto.ShuffleProtos.Project> {
private EntityDirectory<Context> mContextDirectory;
public ProjectProtocolTranslator(EntityDirectory<Context> contextDirectory) {
mContextDirectory = contextDirectory;
}
public org.dodgybits.shuffle.dto.ShuffleProtos.Project toMessage(Project project) {
Builder builder = org.dodgybits.shuffle.dto.ShuffleProtos.Project.newBuilder();
builder
.setId(project.getLocalId().getId())
.setName((project.getName()))
.setModified(ProtocolUtil.toDate(project.getModifiedDate()))
.setParallel(project.isParallel())
.setActive(project.isActive())
.setDeleted(project.isDeleted());
final Id defaultContextId = project.getDefaultContextId();
if (defaultContextId.isInitialised()) {
builder.setDefaultContextId(defaultContextId.getId());
}
final Id tracksId = project.getTracksId();
if (tracksId.isInitialised()) {
builder.setTracksId(tracksId.getId());
}
return builder.build();
}
public Project fromMessage(
org.dodgybits.shuffle.dto.ShuffleProtos.Project dto) {
Project.Builder builder = Project.newBuilder();
builder
.setLocalId(Id.create(dto.getId()))
.setName(dto.getName())
.setModifiedDate(ProtocolUtil.fromDate(dto.getModified()))
.setParallel(dto.getParallel());
if (dto.hasActive()) {
builder.setActive(dto.getActive());
} else {
builder.setActive(true);
}
if (dto.hasDeleted()) {
builder.setDeleted(dto.getDeleted());
} else {
builder.setDeleted(false);
}
if (dto.hasDefaultContextId()) {
Id defaultContextId = Id.create(dto.getDefaultContextId());
Context context = mContextDirectory.findById(defaultContextId);
// it's possible the default context no longer exists so check for it
builder.setDefaultContextId(context == null ? Id.NONE : context.getLocalId());
}
if (dto.hasTracksId()) {
builder.setTracksId(Id.create(dto.getTracksId()));
}
return builder.build();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/protocol/ProjectProtocolTranslator.java | Java | asf20 | 2,709 |
package org.dodgybits.shuffle.android.core.model.protocol;
import org.dodgybits.shuffle.android.core.model.Id;
/**
* A lookup service for entities. Useful when matching up entities from different
* sources that may have conflicting ids (e.g. backup or remote synching).
*/
public interface EntityDirectory<Entity> {
public Entity findById(Id id);
public Entity findByName(String name);
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/protocol/EntityDirectory.java | Java | asf20 | 398 |
package org.dodgybits.shuffle.android.core.model.protocol;
import org.dodgybits.shuffle.android.core.model.Context;
import org.dodgybits.shuffle.android.core.model.Id;
import org.dodgybits.shuffle.dto.ShuffleProtos.Context.Builder;
public class ContextProtocolTranslator implements EntityProtocolTranslator<Context , org.dodgybits.shuffle.dto.ShuffleProtos.Context>{
public org.dodgybits.shuffle.dto.ShuffleProtos.Context toMessage(Context context) {
Builder builder = org.dodgybits.shuffle.dto.ShuffleProtos.Context.newBuilder();
builder
.setId(context.getLocalId().getId())
.setName((context.getName()))
.setModified(ProtocolUtil.toDate(context.getModifiedDate()))
.setColourIndex(context.getColourIndex())
.setActive(context.isActive())
.setDeleted(context.isDeleted());
final Id tracksId = context.getTracksId();
if (tracksId.isInitialised()) {
builder.setTracksId(tracksId.getId());
}
final String iconName = context.getIconName();
if (iconName != null) {
builder.setIcon(iconName);
}
return builder.build();
}
public Context fromMessage(
org.dodgybits.shuffle.dto.ShuffleProtos.Context dto) {
Context.Builder builder = Context.newBuilder();
builder
.setLocalId(Id.create(dto.getId()))
.setName(dto.getName())
.setModifiedDate(ProtocolUtil.fromDate(dto.getModified()))
.setColourIndex(dto.getColourIndex());
if (dto.hasActive()) {
builder.setActive(dto.getActive());
} else {
builder.setActive(true);
}
if (dto.hasDeleted()) {
builder.setDeleted(dto.getDeleted());
} else {
builder.setDeleted(false);
}
if (dto.hasTracksId()) {
builder.setTracksId(Id.create(dto.getTracksId()));
}
if (dto.hasIcon()) {
builder.setIconName(dto.getIcon());
}
return builder.build();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/protocol/ContextProtocolTranslator.java | Java | asf20 | 2,145 |
package org.dodgybits.shuffle.android.core.model.protocol;
import org.dodgybits.shuffle.dto.ShuffleProtos.Date;
public final class ProtocolUtil {
private ProtocolUtil() {
// deny
}
public static Date toDate(long millis) {
return Date.newBuilder()
.setMillis(millis)
.build();
}
public static long fromDate(Date date) {
long millis = 0L;
if (date != null) {
millis = date.getMillis();
}
return millis;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/protocol/ProtocolUtil.java | Java | asf20 | 536 |
package org.dodgybits.shuffle.android.core.model.protocol;
import com.google.protobuf.MessageLite;
public interface EntityProtocolTranslator<E,M extends MessageLite> {
E fromMessage(M message);
M toMessage(E entity);
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/protocol/EntityProtocolTranslator.java | Java | asf20 | 240 |
package org.dodgybits.shuffle.android.core.model.protocol;
import org.dodgybits.shuffle.android.core.model.Context;
import org.dodgybits.shuffle.android.core.model.Id;
import org.dodgybits.shuffle.android.core.model.Project;
import org.dodgybits.shuffle.android.core.model.Task;
import org.dodgybits.shuffle.dto.ShuffleProtos.Task.Builder;
public class TaskProtocolTranslator implements EntityProtocolTranslator<Task, org.dodgybits.shuffle.dto.ShuffleProtos.Task> {
private final EntityDirectory<Context> mContextDirectory;
private final EntityDirectory<Project> mProjectDirectory;
public TaskProtocolTranslator(
EntityDirectory<Context> contextDirectory,
EntityDirectory<Project> projectDirectory) {
mContextDirectory = contextDirectory;
mProjectDirectory = projectDirectory;
}
public org.dodgybits.shuffle.dto.ShuffleProtos.Task toMessage(Task task) {
Builder builder = org.dodgybits.shuffle.dto.ShuffleProtos.Task.newBuilder();
builder
.setId(task.getLocalId().getId())
.setDescription(task.getDescription())
.setCreated(ProtocolUtil.toDate(task.getCreatedDate()))
.setModified(ProtocolUtil.toDate(task.getModifiedDate()))
.setStartDate(ProtocolUtil.toDate(task.getStartDate()))
.setDueDate(ProtocolUtil.toDate(task.getDueDate()))
.setAllDay(task.isAllDay())
.setOrder(task.getOrder())
.setComplete(task.isComplete())
.setActive(task.isActive())
.setDeleted(task.isDeleted());
final String details = task.getDetails();
if (details != null) {
builder.setDetails(details);
}
final Id contextId = task.getContextId();
if (contextId.isInitialised()) {
builder.setContextId(contextId.getId());
}
final Id projectId = task.getProjectId();
if (projectId.isInitialised()) {
builder.setProjectId(projectId.getId());
}
final String timezone = task.getTimezone();
if (timezone != null) {
builder.setTimezone(timezone);
}
final Id calEventId = task.getCalendarEventId();
if (calEventId.isInitialised()) {
builder.setCalEventId(calEventId.getId());
}
final Id tracksId = task.getTracksId();
if (tracksId.isInitialised()) {
builder.setTracksId(tracksId.getId());
}
return builder.build();
}
public Task fromMessage(
org.dodgybits.shuffle.dto.ShuffleProtos.Task dto) {
Task.Builder builder = Task.newBuilder();
builder
.setLocalId(Id.create(dto.getId()))
.setDescription(dto.getDescription())
.setDetails(dto.getDetails())
.setCreatedDate(ProtocolUtil.fromDate(dto.getCreated()))
.setModifiedDate(ProtocolUtil.fromDate(dto.getModified()))
.setStartDate(ProtocolUtil.fromDate(dto.getStartDate()))
.setDueDate(ProtocolUtil.fromDate(dto.getDueDate()))
.setTimezone(dto.getTimezone())
.setAllDay(dto.getAllDay())
.setHasAlarm(false)
.setOrder(dto.getOrder())
.setComplete(dto.getComplete());
if (dto.hasActive()) {
builder.setActive(dto.getActive());
} else {
builder.setActive(true);
}
if (dto.hasDeleted()) {
builder.setDeleted(dto.getDeleted());
} else {
builder.setDeleted(false);
}
if (dto.hasContextId()) {
Id contextId = Id.create(dto.getContextId());
Context context = mContextDirectory.findById(contextId);
builder.setContextId(context == null ? Id.NONE : context.getLocalId());
}
if (dto.hasProjectId()) {
Id projectId = Id.create(dto.getProjectId());
Project project = mProjectDirectory.findById(projectId);
builder.setProjectId(project == null ? Id.NONE : project.getLocalId());
}
if (dto.hasCalEventId()) {
builder.setCalendarEventId(Id.create(dto.getCalEventId()));
}
if (dto.hasTracksId()) {
builder.setTracksId(Id.create(dto.getTracksId()));
}
return builder.build();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/protocol/TaskProtocolTranslator.java | Java | asf20 | 4,393 |
/*
* Copyright (C) 2009 Android Shuffle Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dodgybits.shuffle.android.core.model;
import org.dodgybits.shuffle.android.synchronisation.tracks.model.TracksEntity;
import android.text.TextUtils;
public class Project implements TracksEntity {
private Id mLocalId = Id.NONE;
private String mName;
private Id mDefaultContextId = Id.NONE;
private long mModifiedDate;
private boolean mParallel;
private boolean mArchived;
private Id mTracksId = Id.NONE;
private boolean mDeleted;
private boolean mActive = true;
private Project() {
};
public final Id getLocalId() {
return mLocalId;
}
public final String getName() {
return mName;
}
public final Id getDefaultContextId() {
return mDefaultContextId;
}
public final long getModifiedDate() {
return mModifiedDate;
}
public final boolean isParallel() {
return mParallel;
}
public final boolean isArchived() {
return mArchived;
}
public final Id getTracksId() {
return mTracksId;
}
public final String getLocalName() {
return mName;
}
@Override
public final boolean isDeleted() {
return mDeleted;
}
public final boolean isValid() {
if (TextUtils.isEmpty(mName)) {
return false;
}
return true;
}
@Override
public boolean isActive() {
return mActive;
}
@Override
public final String toString() {
return String.format(
"[Project id=%1$s name='%2$s' defaultContextId='%3$s' " +
"parallel=%4$s archived=%5$s tracksId='%6$s' deleted=%7$s active=%8$s]",
mLocalId, mName, mDefaultContextId,
mParallel, mArchived, mTracksId, mDeleted, mActive);
}
public static Builder newBuilder() {
return Builder.create();
}
public static class Builder implements EntityBuilder<Project> {
private Builder() {
}
private Project result;
private static Builder create() {
Builder builder = new Builder();
builder.result = new Project();
return builder;
}
public Id getLocalId() {
return result.mLocalId;
}
public Builder setLocalId(Id value) {
assert value != null;
result.mLocalId = value;
return this;
}
public String getName() {
return result.mName;
}
public Builder setName(String value) {
result.mName = value;
return this;
}
public Id getDefaultContextId() {
return result.mDefaultContextId;
}
public Builder setDefaultContextId(Id value) {
assert value != null;
result.mDefaultContextId = value;
return this;
}
public long getModifiedDate() {
return result.mModifiedDate;
}
public Builder setModifiedDate(long value) {
result.mModifiedDate = value;
return this;
}
public boolean isParallel() {
return result.mParallel;
}
public Builder setParallel(boolean value) {
result.mParallel = value;
return this;
}
public boolean isArchived() {
return result.mArchived;
}
public Builder setArchived(boolean value) {
result.mArchived = value;
return this;
}
public Id getTracksId() {
return result.mTracksId;
}
public Builder setTracksId(Id value) {
assert value != null;
result.mTracksId = value;
return this;
}
public boolean isActive() {
return result.mActive;
}
@Override
public Builder setActive(boolean value) {
result.mActive = value;
return this;
}
public boolean isDeleted() {
return result.mDeleted;
}
@Override
public Builder setDeleted(boolean value) {
result.mDeleted = value;
return this;
}
public final boolean isInitialized() {
return result.isValid();
}
public Project build() {
if (result == null) {
throw new IllegalStateException(
"build() has already been called on this Builder.");
}
Project returnMe = result;
result = null;
return returnMe;
}
public Builder mergeFrom(Project project) {
setLocalId(project.mLocalId);
setName(project.mName);
setDefaultContextId(project.mDefaultContextId);
setModifiedDate(project.mModifiedDate);
setParallel(project.mParallel);
setArchived(project.mArchived);
setTracksId(project.mTracksId);
setDeleted(project.mDeleted);
setActive(project.mActive);
return this;
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/Project.java | Java | asf20 | 5,810 |
package org.dodgybits.shuffle.android.core.model.encoding;
import android.os.Bundle;
public interface EntityEncoder<Entity> {
void save(Bundle icicle, Entity e);
Entity restore(Bundle icicle);
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/encoding/EntityEncoder.java | Java | asf20 | 211 |
package org.dodgybits.shuffle.android.core.model.encoding;
import static android.provider.BaseColumns._ID;
import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.COLOUR;
import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.ICON;
import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.MODIFIED_DATE;
import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.NAME;
import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.TRACKS_ID;
import org.dodgybits.shuffle.android.core.model.Context;
import org.dodgybits.shuffle.android.core.model.Context.Builder;
import android.os.Bundle;
import com.google.inject.Singleton;
@Singleton
public class ContextEncoder extends AbstractEntityEncoder implements EntityEncoder<Context> {
@Override
public void save(Bundle icicle, Context context) {
putId(icicle, _ID, context.getLocalId());
putId(icicle, TRACKS_ID, context.getTracksId());
icicle.putLong(MODIFIED_DATE, context.getModifiedDate());
putString(icicle, NAME, context.getName());
icicle.putInt(COLOUR, context.getColourIndex());
putString(icicle, ICON, context.getIconName());
}
@Override
public Context restore(Bundle icicle) {
if (icicle == null) return null;
Builder builder = Context.newBuilder();
builder.setLocalId(getId(icicle, _ID));
builder.setModifiedDate(icicle.getLong(MODIFIED_DATE, 0L));
builder.setTracksId(getId(icicle, TRACKS_ID));
builder.setName(getString(icicle, NAME));
builder.setColourIndex(icicle.getInt(COLOUR));
builder.setIconName(getString(icicle, ICON));
return builder.build();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/encoding/ContextEncoder.java | Java | asf20 | 1,843 |
package org.dodgybits.shuffle.android.core.model.encoding;
import static android.provider.BaseColumns._ID;
import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.ARCHIVED;
import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.DEFAULT_CONTEXT_ID;
import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.MODIFIED_DATE;
import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.NAME;
import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.PARALLEL;
import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.TRACKS_ID;
import org.dodgybits.shuffle.android.core.model.Project;
import org.dodgybits.shuffle.android.core.model.Project.Builder;
import android.os.Bundle;
import com.google.inject.Singleton;
@Singleton
public class ProjectEncoder extends AbstractEntityEncoder implements EntityEncoder<Project> {
@Override
public void save(Bundle icicle, Project project) {
putId(icicle, _ID, project.getLocalId());
putId(icicle, TRACKS_ID, project.getTracksId());
icicle.putLong(MODIFIED_DATE, project.getModifiedDate());
putString(icicle, NAME, project.getName());
putId(icicle, DEFAULT_CONTEXT_ID, project.getDefaultContextId());
icicle.putBoolean(ARCHIVED, project.isArchived());
icicle.putBoolean(PARALLEL, project.isParallel());
}
@Override
public Project restore(Bundle icicle) {
if (icicle == null) return null;
Builder builder = Project.newBuilder();
builder.setLocalId(getId(icicle, _ID));
builder.setModifiedDate(icicle.getLong(MODIFIED_DATE, 0L));
builder.setTracksId(getId(icicle, TRACKS_ID));
builder.setName(getString(icicle, NAME));
builder.setDefaultContextId(getId(icicle, DEFAULT_CONTEXT_ID));
builder.setArchived(icicle.getBoolean(ARCHIVED));
builder.setParallel(icicle.getBoolean(PARALLEL));
return builder.build();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/encoding/ProjectEncoder.java | Java | asf20 | 2,124 |
package org.dodgybits.shuffle.android.core.model.encoding;
import org.dodgybits.shuffle.android.core.model.Id;
import android.os.Bundle;
public abstract class AbstractEntityEncoder {
protected static Id getId(Bundle icicle, String key) {
Id result = Id.NONE;
if (icicle.containsKey(key)) {
result = Id.create(icicle.getLong(key));
}
return result;
}
protected static void putId(Bundle icicle, String key, Id value) {
if (value.isInitialised()) {
icicle.putLong(key, value.getId());
}
}
protected static String getString(Bundle icicle, String key) {
String result = null;
if (icicle.containsKey(key)) {
result = icicle.getString(key);
}
return result;
}
protected static void putString(Bundle icicle, String key, String value) {
if (value != null) {
icicle.putString(key, value);
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/encoding/AbstractEntityEncoder.java | Java | asf20 | 990 |
package org.dodgybits.shuffle.android.core.model.encoding;
import static android.provider.BaseColumns._ID;
import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.ALL_DAY;
import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.CAL_EVENT_ID;
import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.COMPLETE;
import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.CONTEXT_ID;
import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.CREATED_DATE;
import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DESCRIPTION;
import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DETAILS;
import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DISPLAY_ORDER;
import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DUE_DATE;
import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.HAS_ALARM;
import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.MODIFIED_DATE;
import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.PROJECT_ID;
import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.START_DATE;
import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.TIMEZONE;
import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.TRACKS_ID;
import org.dodgybits.shuffle.android.core.model.Task;
import org.dodgybits.shuffle.android.core.model.Task.Builder;
import android.os.Bundle;
import com.google.inject.Singleton;
@Singleton
public class TaskEncoder extends AbstractEntityEncoder implements
EntityEncoder<Task> {
@Override
public void save(Bundle icicle, Task task) {
putId(icicle, _ID, task.getLocalId());
putId(icicle, TRACKS_ID, task.getTracksId());
icicle.putLong(MODIFIED_DATE, task.getModifiedDate());
putString(icicle, DESCRIPTION, task.getDescription());
putString(icicle, DETAILS, task.getDetails());
putId(icicle, CONTEXT_ID, task.getContextId());
putId(icicle, PROJECT_ID, task.getProjectId());
icicle.putLong(CREATED_DATE, task.getCreatedDate());
icicle.putLong(START_DATE, task.getStartDate());
icicle.putLong(DUE_DATE, task.getDueDate());
putString(icicle, TIMEZONE, task.getTimezone());
putId(icicle, CAL_EVENT_ID, task.getCalendarEventId());
icicle.putBoolean(ALL_DAY, task.isAllDay());
icicle.putBoolean(HAS_ALARM, task.hasAlarms());
icicle.putInt(DISPLAY_ORDER, task.getOrder());
icicle.putBoolean(COMPLETE, task.isComplete());
}
@Override
public Task restore(Bundle icicle) {
if (icicle == null) return null;
Builder builder = Task.newBuilder();
builder.setLocalId(getId(icicle, _ID));
builder.setModifiedDate(icicle.getLong(MODIFIED_DATE, 0L));
builder.setTracksId(getId(icicle, TRACKS_ID));
builder.setDescription(getString(icicle, DESCRIPTION));
builder.setDetails(getString(icicle, DETAILS));
builder.setContextId(getId(icicle, CONTEXT_ID));
builder.setProjectId(getId(icicle, PROJECT_ID));
builder.setCreatedDate(icicle.getLong(CREATED_DATE, 0L));
builder.setStartDate(icicle.getLong(START_DATE, 0L));
builder.setDueDate(icicle.getLong(DUE_DATE, 0L));
builder.setTimezone(getString(icicle, TIMEZONE));
builder.setCalendarEventId(getId(icicle, CAL_EVENT_ID));
builder.setAllDay(icicle.getBoolean(ALL_DAY));
builder.setHasAlarm(icicle.getBoolean(HAS_ALARM));
builder.setOrder(icicle.getInt(DISPLAY_ORDER));
builder.setComplete(icicle.getBoolean(COMPLETE));
return builder.build();
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/encoding/TaskEncoder.java | Java | asf20 | 3,943 |
package org.dodgybits.shuffle.android.core.model;
public interface EntityBuilder<E> {
EntityBuilder<E> mergeFrom(E e);
EntityBuilder<E> setLocalId(Id id);
EntityBuilder<E> setModifiedDate(long ms);
EntityBuilder<E> setTracksId(Id id);
EntityBuilder<E> setActive(boolean value);
EntityBuilder<E> setDeleted(boolean value);
E build();
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/EntityBuilder.java | Java | asf20 | 370 |
package org.dodgybits.shuffle.android.core.model;
public final class Id {
private final long mId;
public static final Id NONE = new Id(0L);
private Id(long id) {
mId = id;
}
public long getId() {
return mId;
}
public boolean isInitialised() {
return mId != 0L;
}
@Override
public String toString() {
return isInitialised() ? String.valueOf(mId) : "";
}
@Override
public boolean equals(Object o) {
boolean result = false;
if (o instanceof Id) {
result = ((Id)o).mId == mId;
}
return result;
}
@Override
public int hashCode() {
return (int)mId;
}
public static Id create(long id) {
Id result = NONE;
if (id != 0L) {
result = new Id(id);
}
return result;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/Id.java | Java | asf20 | 907 |
/*
* Copyright (C) 2009 Android Shuffle Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dodgybits.shuffle.android.core.model;
import org.dodgybits.shuffle.android.synchronisation.tracks.model.TracksEntity;
import android.text.TextUtils;
public class Context implements TracksEntity {
private Id mLocalId = Id.NONE;
private String mName;
private int mColourIndex;
private String mIconName;
private long mModifiedDate;
private boolean mDeleted;
private boolean mActive = true;
private Id mTracksId = Id.NONE;
private Context() {
};
public final Id getLocalId() {
return mLocalId;
}
public final String getName() {
return mName;
}
public final int getColourIndex() {
return mColourIndex;
}
public final String getIconName() {
return mIconName;
}
public final long getModifiedDate() {
return mModifiedDate;
}
public final Id getTracksId() {
return mTracksId;
}
public final String getLocalName() {
return mName;
}
@Override
public boolean isDeleted() {
return mDeleted;
}
@Override
public boolean isActive() {
return mActive;
}
public final boolean isValid() {
if (TextUtils.isEmpty(mName)) {
return false;
}
return true;
}
@Override
public final String toString() {
return String.format(
"[Context id=%1$s name='%2$s' colourIndex='%3$s' " +
"iconName=%4$s tracksId='%5$s' active=%6$s deleted=%7$s]",
mLocalId, mName, mColourIndex,
mIconName, mTracksId, mActive, mDeleted);
}
public static Builder newBuilder() {
return Builder.create();
}
public static class Builder implements EntityBuilder<Context> {
private Builder() {
}
private Context result;
private static Builder create() {
Builder builder = new Builder();
builder.result = new Context();
return builder;
}
public Id getLocalId() {
return result.mLocalId;
}
public Builder setLocalId(Id value) {
assert value != null;
result.mLocalId = value;
return this;
}
public String getName() {
return result.mName;
}
public Builder setName(String value) {
result.mName = value;
return this;
}
public int getColourIndex() {
return result.mColourIndex;
}
public Builder setColourIndex(int value) {
result.mColourIndex = value;
return this;
}
public String getIconName() {
return result.mIconName;
}
public Builder setIconName(String value) {
result.mIconName = value;
return this;
}
public long getModifiedDate() {
return result.mModifiedDate;
}
public Builder setModifiedDate(long value) {
result.mModifiedDate = value;
return this;
}
public Id getTracksId() {
return result.mTracksId;
}
public Builder setTracksId(Id value) {
assert value != null;
result.mTracksId = value;
return this;
}
public boolean isActive() {
return result.mActive;
}
public Builder setActive(boolean value) {
result.mActive = value;
return this;
}
public boolean isDeleted() {
return result.mDeleted;
}
@Override
public Builder setDeleted(boolean value) {
result.mDeleted = value;
return this;
}
public final boolean isInitialized() {
return result.isValid();
}
public Context build() {
if (result == null) {
throw new IllegalStateException(
"build() has already been called on this Builder.");
}
Context returnMe = result;
result = null;
return returnMe;
}
public Builder mergeFrom(Context context) {
setLocalId(context.mLocalId);
setName(context.mName);
setColourIndex(context.mColourIndex);
setIconName(context.mIconName);
setModifiedDate(context.mModifiedDate);
setTracksId(context.mTracksId);
setDeleted(context.mDeleted);
setActive(context.mActive);
return this;
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/core/model/Context.java | Java | asf20 | 5,328 |