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 |
|---|---|---|---|---|---|
namespace dnGREP.Properties {
// This class allows you to handle specific events on the settings class:
// The SettingChanging event is raised before a setting's value is changed.
// The PropertyChanged event is raised after a setting's value is changed.
// The SettingsLoaded event is raised after the setting values are loaded.
// The SettingsSaving event is raised before the setting values are saved.
internal sealed partial class Settings {
public Settings() {
// // To add event handlers for saving and changing settings, uncomment the lines below:
//
// this.SettingChanging += this.SettingChangingEventHandler;
//
// this.SettingsSaving += this.SettingsSavingEventHandler;
//
}
private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e) {
// Add code to handle the SettingChangingEvent event here.
}
private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e) {
// Add code to handle the SettingsSaving event here.
}
}
}
| zychen63-dngrep | dnGREP.GUI/Settings.cs | C# | gpl3 | 1,255 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Security.Principal;
namespace dnGREP
{
public partial class OptionsForm : Form
{
private static string SHELL_KEY_NAME = "dnGREP";
private static string OLD_SHELL_KEY_NAME = "nGREP";
private static string SHELL_MENU_TEXT = "dnGREP...";
private bool isAdministrator = true;
public bool IsAdministrator
{
get { return isAdministrator; }
set { isAdministrator = value; changeState(); }
}
public OptionsForm()
{
InitializeComponent();
oldShellUnregister();
}
private void changeState()
{
if (!isAdministrator)
{
cbRegisterShell.Enabled = false;
toolTip.SetToolTip(cbRegisterShell, "To set shell integration run dnGREP as Administrator.");
toolTip.SetToolTip(grShell, "To set shell integration run dnGREP as Administrator.");
}
else
{
cbRegisterShell.Enabled = true;
toolTip.SetToolTip(cbRegisterShell, "Shell integration enables running an application from shell context menu.");
toolTip.SetToolTip(grShell, "");
}
if (Properties.Settings.Default.EnableUpdateChecking)
{
tbUpdateInterval.Enabled = true;
}
else
{
tbUpdateInterval.Enabled = false;
}
if (Properties.Settings.Default.ShowLinesInContext)
{
tbLinesAfter.Enabled = true;
tbLinesBefore.Enabled = true;
}
else
{
tbLinesAfter.Enabled = false;
tbLinesBefore.Enabled = false;
}
if (Properties.Settings.Default.UseCustomEditor)
{
rbSpecificEditor.Checked = true;
rbDefaultEditor.Checked = false;
tbEditorPath.Enabled = true;
btnBrowse.Enabled = true;
tbEditorArgs.Enabled = true;
}
else
{
rbSpecificEditor.Checked = false;
rbDefaultEditor.Checked = true;
tbEditorPath.Enabled = false;
btnBrowse.Enabled = false;
tbEditorArgs.Enabled = false;
}
}
private bool isShellRegistered(string location)
{
if (!isAdministrator)
return false;
string regPath = string.Format(@"{0}\shell\{1}",
location, SHELL_KEY_NAME);
try
{
return Registry.ClassesRoot.OpenSubKey(regPath) != null;
}
catch (UnauthorizedAccessException ex)
{
isAdministrator = false;
return false;
}
}
private void shellRegister(string location)
{
if (!isAdministrator)
return;
if (!isShellRegistered(location))
{
string regPath = string.Format(@"{0}\shell\{1}", location, SHELL_KEY_NAME);
// add context menu to the registry
using (RegistryKey key =
Registry.ClassesRoot.CreateSubKey(regPath))
{
key.SetValue(null, SHELL_MENU_TEXT);
}
// add command that is invoked to the registry
string menuCommand = string.Format("\"{0}\" \"%1\"",
Application.ExecutablePath);
using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(
string.Format(@"{0}\command", regPath)))
{
key.SetValue(null, menuCommand);
}
}
}
private void shellUnregister(string location)
{
if (!isAdministrator)
return;
if (isShellRegistered(location))
{
string regPath = string.Format(@"{0}\shell\{1}", location, SHELL_KEY_NAME);
Registry.ClassesRoot.DeleteSubKeyTree(regPath);
}
}
private void oldShellUnregister()
{
if (!isAdministrator)
return;
string regPath = string.Format(@"Directory\shell\{0}", OLD_SHELL_KEY_NAME);
if (Registry.ClassesRoot.OpenSubKey(regPath) != null)
{
Registry.ClassesRoot.DeleteSubKeyTree(regPath);
}
}
private void checkIfAdmin()
{
WindowsIdentity wi = WindowsIdentity.GetCurrent();
WindowsPrincipal wp = new WindowsPrincipal(wi);
if (wp.IsInRole("Administrators"))
{
isAdministrator = true;
}
else
{
isAdministrator = false;
}
}
private void OptionsForm_Load(object sender, EventArgs e)
{
checkIfAdmin();
cbRegisterShell.Checked = isShellRegistered("Directory");
cbCheckForUpdates.Checked = Properties.Settings.Default.EnableUpdateChecking;
cbShowPath.Checked = Properties.Settings.Default.ShowFilePathInResults;
cbShowContext.Checked = Properties.Settings.Default.ShowLinesInContext;
tbLinesBefore.Text = Properties.Settings.Default.ContextLinesBefore.ToString();
tbLinesAfter.Text = Properties.Settings.Default.ContextLinesAfter.ToString();
cbSearchFileNameOnly.Checked = Properties.Settings.Default.AllowSearchingForFileNamePattern;
cbPreviewResults.Checked = Properties.Settings.Default.PreviewResults;
changeState();
}
private void cbRegisterShell_CheckedChanged(object sender, EventArgs e)
{
if (cbRegisterShell.Checked)
{
shellRegister("Directory");
shellRegister("Drive");
shellRegister("*");
}
else if (!cbRegisterShell.Checked)
{
shellUnregister("Directory");
shellUnregister("Drive");
shellUnregister("*");
}
}
private void rbEditorCheckedChanged(object sender, EventArgs e)
{
if (rbDefaultEditor.Checked)
Properties.Settings.Default.UseCustomEditor = false;
else
Properties.Settings.Default.UseCustomEditor = true;
changeState();
}
private void OptionsForm_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.ContextLinesBefore = int.Parse(tbLinesBefore.Text);
Properties.Settings.Default.ContextLinesAfter = int.Parse(tbLinesAfter.Text);
Properties.Settings.Default.AllowSearchingForFileNamePattern = cbSearchFileNameOnly.Checked;
Properties.Settings.Default.PreviewResults = cbPreviewResults.Checked;
Properties.Settings.Default.Save();
}
public static string GetEditorPath(string file, int line)
{
if (!Properties.Settings.Default.UseCustomEditor)
{
return file;
}
else
{
if (!string.IsNullOrEmpty(Properties.Settings.Default.CustomEditor))
{
string path = Properties.Settings.Default.CustomEditor.Replace("%file", "\"" + file + "\"").Replace("%line", line.ToString());
return path;
}
else
{
return file;
}
}
}
private void formKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
Close();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
tbEditorPath.Text = openFileDialog.FileName;
}
}
private void cbCheckForUpdates_CheckedChanged(object sender, EventArgs e)
{
Properties.Settings.Default.EnableUpdateChecking = cbCheckForUpdates.Checked;
if (tbUpdateInterval.Text.Trim() == "")
tbUpdateInterval.Text = "1";
changeState();
}
private void cbShowPath_CheckedChanged(object sender, EventArgs e)
{
Properties.Settings.Default.ShowFilePathInResults = cbShowPath.Checked;
}
private void cbShowContext_CheckedChanged(object sender, EventArgs e)
{
Properties.Settings.Default.ShowLinesInContext = cbShowContext.Checked;
changeState();
}
}
} | zychen63-dngrep | dnGREP.GUI/OptionsForm.cs | C# | gpl3 | 7,288 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Reflection;
namespace dnGREP
{
partial class AboutForm : Form
{
public AboutForm()
{
InitializeComponent();
// Initialize the AboutBox to display the product information from the assembly information.
// Change assembly information settings for your application through either:
// - Project->Properties->Application->Assembly Information
// - AssemblyInfo.cs
this.Text = String.Format("About {0}", AssemblyTitle);
this.labelProductName.Text = AssemblyProduct;
this.labelVersion.Text = String.Format("Version {0}", AssemblyVersion);
this.labelCopyright.Text = AssemblyCopyright;
this.labelCompanyName.Text = AssemblyCompany;
this.textBoxDescription.Text = AssemblyDescription;
}
#region Assembly Attribute Accessors
public string AssemblyTitle
{
get
{
// Get all Title attributes on this assembly
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
// If there is at least one Title attribute
if (attributes.Length > 0)
{
// Select the first one
AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
// If it is not an empty string, return it
if (titleAttribute.Title != "")
return titleAttribute.Title;
}
// If there was no Title attribute, or if the Title attribute was the empty string, return the .exe name
return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
}
}
public string AssemblyVersion
{
get
{
return Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
public string AssemblyDescription
{
get
{
// Get all Description attributes on this assembly
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
// If there aren't any Description attributes, return an empty string
if (attributes.Length == 0)
return "";
// If there is a Description attribute, return its value
return ((AssemblyDescriptionAttribute)attributes[0]).Description;
}
}
public string AssemblyProduct
{
get
{
// Get all Product attributes on this assembly
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);
// If there aren't any Product attributes, return an empty string
if (attributes.Length == 0)
return "";
// If there is a Product attribute, return its value
return ((AssemblyProductAttribute)attributes[0]).Product;
}
}
public string AssemblyCopyright
{
get
{
// Get all Copyright attributes on this assembly
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
// If there aren't any Copyright attributes, return an empty string
if (attributes.Length == 0)
return "";
// If there is a Copyright attribute, return its value
return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
}
}
public string AssemblyCompany
{
get
{
// Get all Company attributes on this assembly
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
// If there aren't any Company attributes, return an empty string
if (attributes.Length == 0)
return "";
// If there is a Company attribute, return its value
return ((AssemblyCompanyAttribute)attributes[0]).Company;
}
}
#endregion
}
}
| zychen63-dngrep | dnGREP.GUI/AboutForm.cs | C# | gpl3 | 3,828 |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using NLog;
using dnGREP.Common;
namespace dnGREP
{
static class Program
{
private static Logger logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//#if DEBUG
// System.Diagnostics.Debugger.Break();
//#endif
if (args != null && args.Length > 0)
{
Properties.Settings.Default.SearchFolder = args[0];
}
try
{
Utils.DeleteTempFolder();
Application.Run(new MainForm());
}
catch (Exception ex)
{
logger.LogException(LogLevel.Error, ex.Message, ex);
}
finally
{
Utils.DeleteTempFolder();
}
}
}
} | zychen63-dngrep | dnGREP.GUI/Program.cs | C# | gpl3 | 910 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using System.Diagnostics;
using NLog;
using System.Reflection;
using dnGREP.Common;
namespace dnGREP
{
public partial class MainForm : Form
{
private List<GrepSearchResult> searchResults = new List<GrepSearchResult>();
private List<KeyValuePair<string, int>> encodings = new List<KeyValuePair<string, int>>();
private const string SEARCH_KEY = "search";
private const string REPLACE_KEY = "replace";
private static Logger logger = LogManager.GetCurrentClassLogger();
private DateTime timer = DateTime.Now;
private PublishedVersionExtractor ve = new PublishedVersionExtractor();
private List<string> treeViewExtensionList = new List<string>();
private BookmarksForm bookmarkForm = new BookmarksForm();
#region States
private int codePage = -1;
public int CodePage
{
get { return codePage; }
set { codePage = value; }
}
private bool doSearchInResults = false;
public bool DoSearchInResults
{
get { return doSearchInResults; }
set { doSearchInResults = value; }
}
private bool folderSelected = false;
public bool FolderSelected
{
get { return folderSelected; }
set
{
folderSelected = value;
changeState();
}
}
private bool searchPatternEntered = false;
public bool SearchPatternEntered
{
get { return searchPatternEntered; }
set { searchPatternEntered = value;
changeState();
}
}
private bool replacePatternEntered = false;
public bool ReplacePatternEntered
{
get { return replacePatternEntered; }
set { replacePatternEntered = value;
changeState();
}
}
private bool filesFound = false;
public bool FilesFound
{
get { return filesFound; }
set {
filesFound = value;
changeState();
}
}
private bool isAllSizes = true;
public bool IsAllSizes
{
get { return isAllSizes; }
set {
isAllSizes = value;
changeState();
}
}
private bool isSearching = false;
public bool IsSearching
{
get { return isSearching; }
set
{
isSearching = value;
changeState();
}
}
private bool isReplacing = false;
public bool IsReplacing
{
get { return isReplacing; }
set
{
isReplacing = value;
changeState();
}
}
private bool isPlainText = false;
public bool IsPlainText
{
get { return isPlainText; }
set
{
isPlainText = value;
changeState();
}
}
private bool canUndo = false;
private string undoFolder = "";
public bool CanUndo
{
get { return canUndo; }
set {
if (value && Directory.Exists(undoFolder))
canUndo = value;
else
canUndo = false;
changeState();
}
}
private bool isMultiline = false;
public bool IsMultiline
{
get { return isMultiline; }
set {
isMultiline = value;
changeState();
}
}
private void changeState()
{
//tbSearchFor
//tbReplaceWith
//splitContainer
if (IsMultiline)
{
tbSearchFor.Multiline = true;
tbReplaceWith.Multiline = true;
splitContainer.SplitterDistance = 180;
splitContainer.IsSplitterFixed = false;
}
else
{
tbSearchFor.Multiline = false;
tbReplaceWith.Multiline = false;
splitContainer.SplitterDistance = 134;
splitContainer.IsSplitterFixed = true;
}
// btnSearch
// searchInResultsToolStripMenuItem
if (FolderSelected && !IsSearching && !IsReplacing &&
(SearchPatternEntered || Properties.Settings.Default.AllowSearchingForFileNamePattern))
{
btnSearch.Enabled = true;
searchInResultsToolStripMenuItem.Enabled = true;
} else {
btnSearch.Enabled = false;
searchInResultsToolStripMenuItem.Enabled = false;
}
//btnSearch.ShowAdvance
if (searchResults.Count > 0)
{
btnSearch.ShowSplit = true;
}
else
{
btnSearch.ShowSplit = false;
}
// btnReplace
if (FolderSelected && FilesFound && !IsSearching && !IsReplacing
&& SearchPatternEntered)
{
btnReplace.Enabled = true;
} else {
btnReplace.Enabled = false;
}
//btnCancel
if (IsSearching)
{
btnCancel.Enabled = true;
}
else if (IsReplacing)
{
btnCancel.Enabled = true;
}
else
{
btnCancel.Enabled = false;
}
//undoToolStripMenuItem
if (CanUndo)
{
undoToolStripMenuItem.Enabled = true;
}
else
{
undoToolStripMenuItem.Enabled = false;
}
//cbCaseSensitive
if (rbXPathSearch.Checked)
{
cbCaseSensitive.Enabled = false;
}
else
{
cbCaseSensitive.Enabled = true;
}
//btnTest
if (!IsPlainText &&
!rbXPathSearch.Checked)
{
btnTest.Enabled = true;
}
else
{
btnTest.Enabled = false;
}
//cbMultiline
if (rbXPathSearch.Checked)
{
cbMultiline.Enabled = false;
}
else
{
cbMultiline.Enabled = true;
}
//tbFileSizeFrom
//tbFileSizeTo
if (IsAllSizes)
{
tbFileSizeFrom.Enabled = false;
tbFileSizeTo.Enabled = false;
}
else
{
tbFileSizeFrom.Enabled = true;
tbFileSizeTo.Enabled = true;
}
//copyFilesToolStripMenuItem
//moveFilesToolStripMenuItem
//deleteFilesToolStripMenuItem
//saveAsCSVToolStripMenuItem
//btnOtherActions
if (FilesFound)
{
copyFilesToolStripMenuItem.Enabled = true;
moveFilesToolStripMenuItem.Enabled = true;
deleteFilesToolStripMenuItem.Enabled = true;
saveAsCSVToolStripMenuItem.Enabled = true;
btnOtherActions.Enabled = true;
}
else
{
copyFilesToolStripMenuItem.Enabled = false;
moveFilesToolStripMenuItem.Enabled = false;
deleteFilesToolStripMenuItem.Enabled = false;
saveAsCSVToolStripMenuItem.Enabled = false;
btnOtherActions.Enabled = false;
}
}
#endregion
#region Check version
private void checkVersion()
{
try
{
if (Properties.Settings.Default.EnableUpdateChecking)
{
DateTime lastCheck = Properties.Settings.Default.LastCheckedVersion;
TimeSpan duration = DateTime.Now.Subtract(lastCheck);
if (duration.TotalDays >= Utils.ParseInt(Properties.Settings.Default.UpdateCheckInterval, 99))
{
ve.StartWebRequest();
Properties.Settings.Default.LastCheckedVersion = DateTime.Now;
}
}
}
catch (Exception ex)
{
logger.LogException(LogLevel.Error, ex.Message, ex);
}
}
void ve_RetrievedVersion(object sender, PublishedVersionExtractor.PackageVersion version)
{
try
{
if (version.Version != null)
{
string currentVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
if (PublishedVersionExtractor.IsUpdateNeeded(currentVersion, version.Version))
{
if (MessageBox.Show("New version of dnGREP (" + version.Version + ") is available for download.\nWould you like to download it now?", "New version", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information) == DialogResult.Yes)
{
System.Diagnostics.Process.Start("http://code.google.com/p/dngrep/");
}
}
}
}
catch (Exception ex)
{
logger.LogException(LogLevel.Error, ex.Message, ex);
}
}
#endregion
public MainForm()
{
InitializeComponent();
restoreSettings();
}
private void MainForm_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Properties.Settings.Default.SearchFolder))
{
tbFolderName.Text = Properties.Settings.Default.SearchFolder;
FolderSelected = true;
}
SearchPatternEntered = !string.IsNullOrEmpty(tbSearchFor.Text);
ReplacePatternEntered = !string.IsNullOrEmpty(tbReplaceWith.Text);
IsPlainText = rbTextSearch.Checked;
IsMultiline = cbMultiline.Checked;
populateEncodings();
ve.RetrievedVersion += new PublishedVersionExtractor.VersionExtractorHandler(ve_RetrievedVersion);
bookmarkForm.PropertyChanged += new PropertyChangedEventHandler(bookmarkForm_PropertyChanged);
checkVersion();
changeState();
}
void bookmarkForm_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "FilePattern")
Properties.Settings.Default.FilePattern = bookmarkForm.FilePattern;
else if (e.PropertyName == "SearchFor")
Properties.Settings.Default.SearchFor = bookmarkForm.SearchFor;
else if (e.PropertyName == "ReplaceWith")
Properties.Settings.Default.ReplaceWith = bookmarkForm.ReplaceWith;
}
private void btnSelectFolder_Click(object sender, EventArgs e)
{
fileFolderDialog.Dialog.Multiselect = true;
fileFolderDialog.SelectedPath = Utils.GetBaseFolder(tbFolderName.Text);
if (tbFolderName.Text == "")
{
string clipboard = Clipboard.GetText();
try
{
if (Path.IsPathRooted(clipboard))
fileFolderDialog.SelectedPath = clipboard;
}
catch (Exception ex)
{
// Ignore
}
}
if (fileFolderDialog.ShowDialog() == DialogResult.OK)
{
if (fileFolderDialog.SelectedPaths != null)
tbFolderName.Text = fileFolderDialog.SelectedPaths;
else
tbFolderName.Text = fileFolderDialog.SelectedPath;
}
}
private void tbFolderName_TextChanged(object sender, EventArgs e)
{
if (Utils.IsPathValid(tbFolderName.Text))
{
FolderSelected = true;
}
else
{
FolderSelected = false;
}
}
private void btnSearch_Click(object sender, EventArgs e)
{
DoSearchInResults = false;
if (!IsSearching && !workerSearchReplace.IsBusy)
{
lblStatus.Text = "Searching...";
IsSearching = true;
barProgressBar.Value = 0;
tvSearchResult.Nodes.Clear();
workerSearchReplace.RunWorkerAsync(SEARCH_KEY);
}
}
private void searchInResultsToolStripMenuItem_Click(object sender, EventArgs e)
{
DoSearchInResults = true;
if (!IsSearching && !workerSearchReplace.IsBusy)
{
lblStatus.Text = "Searching...";
IsSearching = true;
barProgressBar.Value = 0;
tvSearchResult.Nodes.Clear();
workerSearchReplace.RunWorkerAsync(SEARCH_KEY);
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
if (IsSearching || IsReplacing)
{
GrepCore.CancelProcess = true;
}
}
private void doSearchReplace(object sender, DoWorkEventArgs e)
{
try
{
if (!workerSearchReplace.CancellationPending)
{
timer = DateTime.Now;
if (e.Argument == SEARCH_KEY)
{
int sizeFrom = 0;
int sizeTo = 0;
if (!IsAllSizes)
{
sizeFrom = Utils.ParseInt(tbFileSizeFrom.Text, 0);
sizeTo = Utils.ParseInt(tbFileSizeTo.Text, 0);
}
string filePattern = "*.*";
if (rbFileRegex.Checked)
filePattern = ".*";
if (!string.IsNullOrEmpty(tbFilePattern.Text))
filePattern = tbFilePattern.Text;
if (rbFileAsterisk.Checked)
filePattern = filePattern.Replace("\\", "");
string[] files;
if (DoSearchInResults)
{
List<string> filesFromSearch = new List<string>();
foreach (GrepSearchResult result in searchResults)
{
if (!filesFromSearch.Contains(result.FileNameReal))
{
filesFromSearch.Add(result.FileNameReal);
}
}
files = filesFromSearch.ToArray();
}
else
{
files = Utils.GetFileList(tbFolderName.Text, filePattern, rbFileRegex.Checked, cbIncludeSubfolders.Checked,
cbIncludeHiddenFolders.Checked, sizeFrom, sizeTo);
}
GrepCore grep = new GrepCore();
grep.ShowLinesInContext = Properties.Settings.Default.ShowLinesInContext;
grep.LinesBefore = Properties.Settings.Default.ContextLinesBefore;
grep.LinesAfter = Properties.Settings.Default.ContextLinesAfter;
grep.PreviewFilesDuringSearch = Properties.Settings.Default.PreviewResults;
grep.ProcessedFile += new GrepCore.SearchProgressHandler(grep_ProcessedFile);
List<GrepSearchResult> results = null;
GrepSearchOption searchOptions = GrepSearchOption.None;
if (cbMultiline.Checked)
searchOptions |= GrepSearchOption.Multiline;
if (cbCaseSensitive.Checked)
searchOptions |= GrepSearchOption.CaseSensitive;
if (rbRegexSearch.Checked)
results = grep.Search(files, SearchType.Regex, tbSearchFor.Text, searchOptions, CodePage);
else if (rbXPathSearch.Checked)
results = grep.Search(files, SearchType.XPath, tbSearchFor.Text, searchOptions, CodePage);
else
results = grep.Search(files, SearchType.PlainText, tbSearchFor.Text, searchOptions, CodePage);
grep.ProcessedFile -= new GrepCore.SearchProgressHandler(grep_ProcessedFile);
if (results != null)
{
searchResults = new List<GrepSearchResult>(results);
e.Result = results.Count;
}
else
{
searchResults = new List<GrepSearchResult>();
e.Result = 0;
}
}
else
{
GrepCore grep = new GrepCore();
grep.ShowLinesInContext = Properties.Settings.Default.ShowLinesInContext;
grep.LinesBefore = Properties.Settings.Default.ContextLinesBefore;
grep.LinesAfter = Properties.Settings.Default.ContextLinesAfter;
grep.PreviewFilesDuringSearch = Properties.Settings.Default.PreviewResults;
grep.ProcessedFile += new GrepCore.SearchProgressHandler(grep_ProcessedFile);
List<string> files = new List<string>();
foreach (GrepSearchResult result in searchResults)
{
if (!result.ReadOnly)
files.Add(result.FileNameReal);
}
GrepSearchOption searchOptions = GrepSearchOption.None;
if (cbMultiline.Checked)
searchOptions |= GrepSearchOption.Multiline;
if (cbCaseSensitive.Checked)
searchOptions |= GrepSearchOption.CaseSensitive;
if (rbRegexSearch.Checked)
e.Result = grep.Replace(files.ToArray(), SearchType.Regex, Utils.GetBaseFolder(tbFolderName.Text), tbSearchFor.Text, tbReplaceWith.Text, searchOptions, CodePage);
else if (rbXPathSearch.Checked)
e.Result = grep.Replace(files.ToArray(), SearchType.XPath, Utils.GetBaseFolder(tbFolderName.Text), tbSearchFor.Text, tbReplaceWith.Text, searchOptions, CodePage);
else
e.Result = grep.Replace(files.ToArray(), SearchType.PlainText, Utils.GetBaseFolder(tbFolderName.Text), tbSearchFor.Text, tbReplaceWith.Text, searchOptions, CodePage);
grep.ProcessedFile -= new GrepCore.SearchProgressHandler(grep_ProcessedFile);
}
}
}
catch (Exception ex)
{
logger.LogException(LogLevel.Error, ex.Message, ex);
if (e.Argument == SEARCH_KEY)
MessageBox.Show("Search failed! See error log.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
MessageBox.Show("Replace failed! See error log.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
void grep_ProcessedFile(object sender, GrepCore.ProgressStatus progress)
{
workerSearchReplace.ReportProgress((int)(progress.ProcessedFiles * 100 / progress.TotalFiles), progress);
}
private void searchProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (!GrepCore.CancelProcess)
{
GrepCore.ProgressStatus progress = (GrepCore.ProgressStatus)e.UserState;
barProgressBar.Value = e.ProgressPercentage;
lblStatus.Text = "(" + progress.ProcessedFiles + " of " + progress.TotalFiles + ")";
if (progress.SearchResults != null)
{
searchResults.AddRange(progress.SearchResults);
for (int i = 0; i < progress.SearchResults.Count; i++)
{
appendResults(progress.SearchResults[i]);
}
}
}
}
private void searchComplete(object sender, RunWorkerCompletedEventArgs e)
{
if (IsSearching)
{
if (!e.Cancelled)
{
TimeSpan duration = DateTime.Now.Subtract(timer);
lblStatus.Text = "Search Complete - " + (int)e.Result + " files found in " + duration.TotalMilliseconds + "ms.";
}
else
{
lblStatus.Text = "Search Canceled";
}
barProgressBar.Value = 0;
IsSearching = false;
if (searchResults.Count > 0)
FilesFound = true;
else
FilesFound = false;
}
else if (IsReplacing)
{
if (!e.Cancelled)
{
if (e.Result == null || ((int)e.Result) == -1)
{
lblStatus.Text = "Replace Failed.";
MessageBox.Show("Replace failed! See error log.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
lblStatus.Text = "Replace Complete - " + (int)e.Result + " files replaced.";
CanUndo = true;
}
}
else
{
lblStatus.Text = "Replace Canceled";
}
barProgressBar.Value = 0;
IsReplacing = false;
searchResults.Clear();
FilesFound = false;
}
if (!Properties.Settings.Default.PreviewResults || tvSearchResult.Nodes.Count != searchResults.Count)
populateResults();
string outdatedEngines = dnGREP.Engines.GrepEngineFactory.GetListOfFailedEngines();
if (!string.IsNullOrEmpty(outdatedEngines))
{
MessageBox.Show("The following plugins failed to load:\n\n" + outdatedEngines + "\n\nDefault engine was used instead.", "Plugin Errors", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
GrepCore.CancelProcess = true;
if (workerSearchReplace.IsBusy)
workerSearchReplace.CancelAsync();
populateSettings();
Properties.Settings.Default.Save();
}
private void populateSettings()
{
Properties.Settings.Default.SearchRegex = rbRegexSearch.Checked;
Properties.Settings.Default.SearchText = rbTextSearch.Checked;
Properties.Settings.Default.SearchXPath = rbXPathSearch.Checked;
Properties.Settings.Default.FileSearchRegex = rbFileRegex.Checked;
Properties.Settings.Default.FileSearchAsterisk = rbFileAsterisk.Checked;
Properties.Settings.Default.FilterAllSizes = rbFilterAllSizes.Checked;
Properties.Settings.Default.FilterSpecificSize = rbFilterSpecificSize.Checked;
}
private void restoreSettings()
{
rbRegexSearch.Checked =Properties.Settings.Default.SearchRegex;
rbTextSearch.Checked = Properties.Settings.Default.SearchText;
rbXPathSearch.Checked = Properties.Settings.Default.SearchXPath;
rbFileRegex.Checked = Properties.Settings.Default.FileSearchRegex;
rbFileAsterisk.Checked = Properties.Settings.Default.FileSearchAsterisk;
rbFilterAllSizes.Checked = Properties.Settings.Default.FilterAllSizes;
rbFilterSpecificSize.Checked = Properties.Settings.Default.FilterSpecificSize;
}
private void appendResults(GrepSearchResult result)
{
if (result == null)
return;
// Populate icon list
string ext = Path.GetExtension(result.FileNameDisplayed);
if (!treeViewExtensionList.Contains(ext)) {
treeViewExtensionList.Add(ext);
FileIcons.LoadImageList(treeViewExtensionList.ToArray());
tvSearchResult.ImageList = FileIcons.SmallIconList;
}
bool isFileReadOnly = Utils.IsReadOnly(result);
string displayedName = Path.GetFileName(result.FileNameDisplayed);
if (Properties.Settings.Default.ShowFilePathInResults &&
result.FileNameDisplayed.Contains(Utils.GetBaseFolder(tbFolderName.Text) + "\\"))
{
displayedName = result.FileNameDisplayed.Substring(Utils.GetBaseFolder(tbFolderName.Text).Length + 1);
}
int lineCount = Utils.MatchCount(result);
if (lineCount > 0)
displayedName = string.Format("{0} ({1})", displayedName, lineCount);
if (isFileReadOnly)
displayedName = displayedName + " [read-only]";
TreeNode node = new TreeNode(displayedName);
node.Tag = result;
tvSearchResult.Nodes.Add(node);
node.ImageKey = ext;
node.SelectedImageKey = node.ImageKey;
node.StateImageKey = node.ImageKey;
if (isFileReadOnly)
{
node.ForeColor = Color.DarkGray;
}
if (result.SearchResults != null)
{
for (int i = 0; i < result.SearchResults.Count; i++ )
{
GrepSearchResult.GrepLine line = result.SearchResults[i];
string lineSummary = line.LineText.Replace("\n", "").Replace("\t", "").Replace("\r", "").Trim();
if (lineSummary.Length == 0)
lineSummary = " ";
else if (lineSummary.Length > 100)
lineSummary = lineSummary.Substring(0, 100) + "...";
string lineNumber = (line.LineNumber == -1 ? "" : line.LineNumber + ": ");
TreeNode lineNode = new TreeNode(lineNumber + lineSummary);
lineNode.ImageKey = "%line%";
lineNode.SelectedImageKey = lineNode.ImageKey;
lineNode.StateImageKey = lineNode.ImageKey;
lineNode.Tag = line.LineNumber;
if (!line.IsContext && Properties.Settings.Default.ShowLinesInContext)
{
lineNode.ForeColor = Color.Red;
}
node.Nodes.Add(lineNode);
}
}
}
private void populateResults()
{
tvSearchResult.Nodes.Clear();
if (searchResults == null)
return;
for (int i = 0; i < searchResults.Count; i++ )
{
appendResults(searchResults[i]);
}
}
private void populateEncodings()
{
KeyValuePair<string, int> defaultValue = new KeyValuePair<string,int>("Auto detection (default)",-1);
foreach (EncodingInfo ei in Encoding.GetEncodings())
{
Encoding e = ei.GetEncoding();
encodings.Add(new KeyValuePair<string, int>(e.EncodingName, e.CodePage));
}
encodings.Sort(new KeyValueComparer());
encodings.Insert(0,defaultValue);
cbEncoding.DataSource = encodings;
cbEncoding.ValueMember = "Value";
cbEncoding.DisplayMember = "Key";
cbEncoding.SelectedIndex = 0;
}
private void formKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
Close();
}
private void rbFilterSizes_CheckedChanged(object sender, EventArgs e)
{
if (rbFilterAllSizes.Checked)
IsAllSizes = true;
else
IsAllSizes = false;
}
private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
{
OptionsForm options = new OptionsForm();
options.ShowDialog();
changeState();
}
private void tvSearchResult_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (e.Button == MouseButtons.Right)
tvSearchResult.SelectedNode = e.Node;
}
private void tvSearchResult_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
{
TreeNode selectedNode = tvSearchResult.SelectedNode;
if (selectedNode != null && selectedNode.Nodes.Count == 0)
{
openToolStripMenuItem_Click(tvContextMenu, null);
}
}
private void btnReplace_Click(object sender, EventArgs e)
{
if (!IsReplacing && !IsSearching && !workerSearchReplace.IsBusy)
{
if (!ReplacePatternEntered)
{
if (MessageBox.Show("Are you sure you want to replace search pattern with empty string?", "Replace", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) != DialogResult.Yes)
return;
}
List<string> roFiles = Utils.GetReadOnlyFiles(searchResults);
if (roFiles.Count > 0)
{
StringBuilder sb = new StringBuilder("Some of the files can not be modified. If you continue, these files will be skipped.\nWould you like to continue?\n\n");
foreach (string fileName in roFiles)
{
sb.AppendLine(" - " + new FileInfo(fileName).Name);
}
if (MessageBox.Show(sb.ToString(), "Replace", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) != DialogResult.Yes)
return;
}
lblStatus.Text = "Replacing...";
IsReplacing = true;
CanUndo = false;
undoFolder = Utils.GetBaseFolder(tbFolderName.Text);
barProgressBar.Value = 0;
tvSearchResult.Nodes.Clear();
workerSearchReplace.RunWorkerAsync(REPLACE_KEY);
}
}
private void textBoxTextChanged(object sender, EventArgs e)
{
SearchPatternEntered = !string.IsNullOrEmpty(tbSearchFor.Text);
ReplacePatternEntered = !string.IsNullOrEmpty(tbReplaceWith.Text);
if (sender == tbSearchFor)
{
FilesFound = false;
}
}
private void undoToolStripMenuItem_Click(object sender, EventArgs e)
{
if (CanUndo)
{
DialogResult response = MessageBox.Show("Undo will revert modified file(s) back to their original state. Any changes made to the file(s) after the replace will be overwritten. Are you sure you want to procede?", "Undo", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button3);
if (response == DialogResult.Yes)
{
GrepCore core = new GrepCore();
core.ShowLinesInContext = Properties.Settings.Default.ShowLinesInContext;
core.LinesBefore = Properties.Settings.Default.ContextLinesBefore;
core.LinesAfter = Properties.Settings.Default.ContextLinesAfter;
core.PreviewFilesDuringSearch = Properties.Settings.Default.PreviewResults;
bool result = core.Undo(undoFolder);
if (result)
{
MessageBox.Show("Files have been successfully reverted.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
Utils.DeleteTempFolder();
}
else
{
MessageBox.Show("There was an error reverting files. Please examine the error log.", "Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
CanUndo = false;
}
}
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
AboutForm about = new AboutForm();
about.ShowDialog();
}
private void onHelpRequested(object sender, HelpEventArgs hlpevent)
{
hlpevent.Handled = false;
}
private void helpToolStripMenuItem_Click(object sender, EventArgs e)
{
Help.ShowHelp(this, helpProvider.HelpNamespace);
}
private void regexText_CheckedChanged(object sender, EventArgs e)
{
if (sender == rbTextSearch)
IsPlainText = rbTextSearch.Checked;
FilesFound = false;
}
private void cbCaseSensitive_CheckedChanged(object sender, EventArgs e)
{
FilesFound = false;
}
private void btnTest_Click(object sender, EventArgs e)
{
try
{
RegexTest rTest = new RegexTest(tbSearchFor.Text, tbReplaceWith.Text);
rTest.Show();
}
catch (Exception ex)
{
MessageBox.Show("There was an error running regex test. Please examine the error log.", "Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void cbEncoding_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbEncoding.SelectedValue != null && cbEncoding.SelectedValue is int)
CodePage = (int)cbEncoding.SelectedValue;
}
private void cbMultiline_CheckedChanged(object sender, EventArgs e)
{
IsMultiline = cbMultiline.Checked;
}
private void openToolStripMenuItem1_Click(object sender, EventArgs e)
{
bookmarkForm.Show();
}
private void btnBookmark_Click(object sender, EventArgs e)
{
BookmarkDetails bookmarkEditForm = new BookmarkDetails(CreateOrEdit.Create);
Bookmark newBookmark = new Bookmark(tbSearchFor.Text, tbReplaceWith.Text, tbFilePattern.Text, "");
bookmarkEditForm.Bookmark = newBookmark;
if (bookmarkEditForm.ShowDialog() == DialogResult.OK)
{
if (!BookmarkLibrary.Instance.Bookmarks.Contains(newBookmark))
{
BookmarkLibrary.Instance.Bookmarks.Add(newBookmark);
BookmarkLibrary.Save();
}
}
}
private void addToolStripMenuItem_Click(object sender, EventArgs e)
{
btnBookmark_Click(this, null);
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
TreeNode selectedNode = tvSearchResult.SelectedNode;
if (selectedNode != null)
{
// Line was selected
int lineNumber = 0;
if (selectedNode.Parent != null)
{
if (selectedNode.Tag != null && selectedNode.Tag is int)
{
lineNumber = (int)selectedNode.Tag;
}
selectedNode = selectedNode.Parent;
}
if (selectedNode != null && selectedNode.Tag != null)
{
GrepSearchResult result = (GrepSearchResult)selectedNode.Tag;
OpenFileArgs fileArg = new OpenFileArgs(result, lineNumber, Properties.Settings.Default.UseCustomEditor, Properties.Settings.Default.CustomEditor, Properties.Settings.Default.CustomEditorArgs);
dnGREP.Engines.GrepEngineFactory.GetSearchEngine(result.FileNameReal, false, 0, 0).OpenFile(fileArg);
if (fileArg.UseBaseEngine)
Utils.OpenFile(new OpenFileArgs(result, lineNumber, Properties.Settings.Default.UseCustomEditor, Properties.Settings.Default.CustomEditor, Properties.Settings.Default.CustomEditorArgs));
}
}
}
private void expandAllToolStripMenuItem_Click(object sender, EventArgs e)
{
tvSearchResult.ExpandAll();
}
#region Advance actions
private void copyFilesToolStripMenuItem_Click(object sender, EventArgs e)
{
if (FilesFound) {
if (folderSelectDialog.ShowDialog() == DialogResult.OK)
{
try
{
if (!Utils.CanCopyFiles(searchResults, folderSelectDialog.SelectedPath))
{
MessageBox.Show("Attention, some of the files are located in the selected directory.\nPlease select another directory and try again.", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
Utils.CopyFiles(searchResults, Utils.GetBaseFolder(tbFolderName.Text), folderSelectDialog.SelectedPath, true);
MessageBox.Show("Files have been successfully copied.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show("There was an error copying files. Please examine the error log.", "Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
CanUndo = false;
}
}
}
private void moveFilesToolStripMenuItem_Click(object sender, EventArgs e)
{
if (FilesFound)
{
if (folderSelectDialog.ShowDialog() == DialogResult.OK)
{
try
{
if (!Utils.CanCopyFiles(searchResults, folderSelectDialog.SelectedPath))
{
MessageBox.Show("Attention, some of the files are located in the selected directory.\nPlease select another directory and try again.", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
Utils.CopyFiles(searchResults, Utils.GetBaseFolder(tbFolderName.Text), folderSelectDialog.SelectedPath, true);
Utils.DeleteFiles(searchResults);
MessageBox.Show("Files have been successfully moved.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show("There was an error moving files. Please examine the error log.", "Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
CanUndo = false;
searchResults = new List<GrepSearchResult>();
populateResults();
FilesFound = false;
}
}
}
private void deleteFilesToolStripMenuItem_Click(object sender, EventArgs e)
{
if (FilesFound)
{
try
{
if (MessageBox.Show("Attention, you are about to delete files found during search.\nAre you sure you want to procede?", "Attention", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) != DialogResult.Yes)
{
return;
}
Utils.DeleteFiles(searchResults);
MessageBox.Show("Files have been successfully deleted.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show("There was an error deleting files. Please examine the error log.", "Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
CanUndo = false;
searchResults = new List<GrepSearchResult>();
populateResults();
FilesFound = false;
}
}
private void saveAsCSVToolStripMenuItem_Click(object sender, EventArgs e)
{
if (FilesFound)
{
saveFileDialog.InitialDirectory = folderSelectDialog.SelectedPath;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
Utils.SaveResultsAsCSV(searchResults, saveFileDialog.FileName);
MessageBox.Show("CSV file has been successfully created.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show("There was an error creating a CSV file. Please examine the error log.", "Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void btnOtherActions_Click(object sender, EventArgs e)
{
otherMenu.Show(btnOtherActions, new Point(0, btnOtherActions.Height));
}
#endregion
private void openContainingFolderToolStripMenuItem_Click(object sender, EventArgs e)
{
TreeNode selectedNode = tvSearchResult.SelectedNode;
if (selectedNode != null)
{
// Line was selected
int lineNumber = 0;
if (selectedNode.Parent != null)
{
if (selectedNode.Tag != null && selectedNode.Tag is int)
{
lineNumber = (int)selectedNode.Tag;
}
selectedNode = selectedNode.Parent;
}
if (selectedNode != null && selectedNode.Tag != null)
{
Utils.OpenContainingFolder(((GrepSearchResult)selectedNode.Tag).FileNameReal, lineNumber);
}
}
}
}
} | zychen63-dngrep | dnGREP.GUI/MainForm.cs | C# | gpl3 | 34,277 |
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("dnGREP")]
[assembly: AssemblyDescription("This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Denis Stankovski")]
[assembly: AssemblyProduct("dnGREP")]
[assembly: AssemblyCopyright("Copyright, 2008")]
[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("6b3239fc-566a-4a9d-bfd1-2052be85fe46")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("0.13.0.*")]
[assembly: AssemblyFileVersion("0.13.0.0")]
| zychen63-dngrep | dnGREP.GUI/Properties/AssemblyInfo.cs | C# | gpl3 | 1,514 |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Reflection;
using System.Net;
using System.Xml;
using System.Security.Permissions;
using System.Security;
using NLog;
namespace dnGREP.Common
{
public class Utils
{
private static Logger logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// Copies the folder recursively. Uses includePattern to avoid unnecessary objects
/// </summary>
/// <param name="sourceDirectory"></param>
/// <param name="destinationDirectory"></param>
/// <param name="includePattern">Regex pattern that matches file or folder to be included. If null or empty, the parameter is ignored</param>
/// <param name="excludePattern">Regex pattern that matches file or folder to be included. If null or empty, the parameter is ignored</param>
public static void CopyFiles(string sourceDirectory, string destinationDirectory, string includePattern, string excludePattern)
{
String[] files;
destinationDirectory = FixFolderName(destinationDirectory);
if (!Directory.Exists(destinationDirectory)) Directory.CreateDirectory(destinationDirectory);
files = Directory.GetFileSystemEntries(sourceDirectory);
foreach (string element in files)
{
if (!string.IsNullOrEmpty(includePattern) && File.Exists(element) && !Regex.IsMatch(element, includePattern))
continue;
if (!string.IsNullOrEmpty(excludePattern) && File.Exists(element) && Regex.IsMatch(element, excludePattern))
continue;
// Sub directories
if (Directory.Exists(element))
CopyFiles(element, destinationDirectory + Path.GetFileName(element), includePattern, excludePattern);
// Files in directory
else
CopyFile(element, destinationDirectory + Path.GetFileName(element), true);
}
}
/// <summary>
/// Copies file based on search results. If folder does not exist, creates it.
/// </summary>
/// <param name="source"></param>
/// <param name="sourceDirectory"></param>
/// <param name="destinationDirectory"></param>
/// <param name="overWrite"></param>
public static void CopyFiles(List<GrepSearchResult> source, string sourceDirectory, string destinationDirectory, bool overWrite)
{
sourceDirectory = FixFolderName(sourceDirectory);
destinationDirectory = FixFolderName(destinationDirectory);
if (!Directory.Exists(destinationDirectory)) Directory.CreateDirectory(destinationDirectory);
List<string> files = new List<string>();
foreach (GrepSearchResult result in source)
{
if (!files.Contains(result.FileNameReal) && result.FileNameDisplayed.Contains(sourceDirectory))
{
files.Add(result.FileNameReal);
FileInfo sourceFileInfo = new FileInfo(result.FileNameReal);
FileInfo destinationFileInfo = new FileInfo(destinationDirectory + result.FileNameReal.Substring(sourceDirectory.Length));
if (sourceFileInfo.FullName != destinationFileInfo.FullName)
CopyFile(sourceFileInfo.FullName, destinationFileInfo.FullName, overWrite);
}
}
}
/// <summary>
/// Returns true if destinationDirectory is not included in source files
/// </summary>
/// <param name="source"></param>
/// <param name="destinationDirectory"></param>
/// <returns></returns>
public static bool CanCopyFiles(List<GrepSearchResult> source, string destinationDirectory)
{
if (destinationDirectory == null || source == null || source.Count == 0)
return false;
destinationDirectory = FixFolderName(destinationDirectory);
List<string> files = new List<string>();
foreach (GrepSearchResult result in source)
{
if (!files.Contains(result.FileNameReal))
{
files.Add(result.FileNameReal);
FileInfo sourceFileInfo = new FileInfo(result.FileNameReal);
FileInfo destinationFileInfo = new FileInfo(destinationDirectory + Path.GetFileName(result.FileNameReal));
if (sourceFileInfo.FullName == destinationFileInfo.FullName)
return false;
}
}
return true;
}
/// <summary>
/// Creates a CSV file from search results
/// </summary>
/// <param name="source"></param>
/// <param name="destinationPath"></param>
public static void SaveResultsAsCSV(List<GrepSearchResult> source, string destinationPath)
{
if (File.Exists(destinationPath))
File.Delete(destinationPath);
StringBuilder sb = new StringBuilder();
sb.AppendLine("File Name,Line Number,String");
foreach (GrepSearchResult result in source)
{
foreach (GrepSearchResult.GrepLine line in result.SearchResults)
{
if (!line.IsContext)
sb.AppendLine("\"" + result.FileNameDisplayed + "\"," + line.LineNumber + ",\"" + line.LineText + "\"");
}
}
File.WriteAllText(destinationPath, sb.ToString());
}
/// <summary>
/// Deletes file based on search results.
/// </summary>
/// <param name="source"></param>
public static void DeleteFiles(List<GrepSearchResult> source)
{
List<string> files = new List<string>();
foreach (GrepSearchResult result in source)
{
if (!files.Contains(result.FileNameReal))
{
files.Add(result.FileNameReal);
DeleteFile(result.FileNameReal);
}
}
}
/// <summary>
/// Copies file. If folder does not exist, creates it.
/// </summary>
/// <param name="sourcePath"></param>
/// <param name="destinationPath"></param>
/// <param name="overWrite"></param>
public static void CopyFile(string sourcePath, string destinationPath, bool overWrite)
{
if (File.Exists(destinationPath) && !overWrite)
throw new IOException("File: '" + destinationPath + "' exists.");
if (!new FileInfo(destinationPath).Directory.Exists)
new FileInfo(destinationPath).Directory.Create();
File.Copy(sourcePath, destinationPath, overWrite);
}
/// <summary>
/// Deletes files even if they are read only
/// </summary>
/// <param name="path"></param>
public static void DeleteFile(string path)
{
if (File.Exists(path)) {
File.SetAttributes(path, FileAttributes.Normal);
File.Delete(path);
}
}
/// <summary>
/// Deletes folder even if it contains read only files
/// </summary>
/// <param name="path"></param>
public static void DeleteFolder(string path)
{
string[] files = GetFileList(path, "*.*", null, false, true, true, true, 0, 0);
foreach (string file in files)
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
Directory.Delete(path, true);
}
/// <summary>
/// Detects the byte order mark of a file and returns
/// an appropriate encoding for the file.
/// </summary>
/// <param name="srcFile"></param>
/// <returns></returns>
public static Encoding GetFileEncoding(string srcFile)
{
// *** Use Default of Encoding.Default (Ansi CodePage)
Encoding enc = Encoding.Default;
// *** Detect byte order mark if any - otherwise assume default
byte[] buffer = new byte[5];
using (FileStream readStream = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read))
{
readStream.Read(buffer, 0, 5);
}
if (buffer[0] == 0xef && buffer[1] == 0xbb && buffer[2] == 0xbf)
enc = Encoding.UTF8;
else if (buffer[0] == 0xfe && buffer[1] == 0xff)
enc = Encoding.Unicode;
else if (buffer[0] == 0 && buffer[1] == 0 && buffer[2] == 0xfe && buffer[3] == 0xff)
enc = Encoding.UTF32;
else if (buffer[0] == 0x2b && buffer[1] == 0x2f && buffer[2] == 0x76)
enc = Encoding.UTF7;
return enc;
}
/// <summary>
/// Returns true is file is binary. Algorithm taken from winGrep.
/// The function scans first 10KB for 0x0000 sequence
/// and if found, assumes the file to be binary
/// </summary>
/// <param name="filePath">Path to a file</param>
/// <returns>True is file is binary otherwise false</returns>
public static bool IsBinary(string srcFile)
{
byte[] buffer = new byte[1024];
int count = 0;
using (FileStream readStream = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.None))
{
count = readStream.Read(buffer, 0, buffer.Length);
}
for (int i = 0; i < count - 1; i = i + 2)
{
if (buffer[i] == 0 && buffer[i + 1] == 0)
{
return true;
}
}
return false;
}
/// <summary>
/// Add DirectorySeparatorChar to the end of the folder path if does not exist
/// </summary>
/// <param name="name">Folder path</param>
/// <returns></returns>
public static string FixFolderName(string name)
{
if (name != null && name.Length > 1 && name[name.Length - 1] != Path.DirectorySeparatorChar)
name += Path.DirectorySeparatorChar;
return name;
}
/// <summary>
/// Validates whether the path is a valid directory, file, or list of files
/// </summary>
/// <param name="path">Path to one or many files separated by semi-colon or path to a folder</param>
/// <returns>True is all paths are valid, otherwise false</returns>
public static bool IsPathValid(string path)
{
try
{
if (string.IsNullOrEmpty(path))
return false;
string[] paths = SplitPath(path);
foreach (string subPath in paths)
{
if (subPath.Trim() != "" && !File.Exists(subPath) && !Directory.Exists(subPath))
return false;
}
return true;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// Returns base folder of one or many files or folders.
/// If multiple files are passed in, takes the first one.
/// </summary>
/// <param name="path">Path to one or many files separated by semi-colon or path to a folder</param>
/// <returns>Base folder path or null if none exists</returns>
public static string GetBaseFolder(string path)
{
try
{
string[] paths = SplitPath(path);
if (paths[0].Trim() != "" && File.Exists(paths[0]))
return Path.GetDirectoryName(paths[0]);
else if (paths[0].Trim() != "" && Directory.Exists(paths[0]))
return paths[0];
else
return null;
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// Splits path into subpaths if ; or , are found in path.
/// If folder name contains ; or , returns as one path
/// </summary>
/// <param name="path">Path to split</param>
/// <returns>Array of strings. If path is null, returns null. If path is empty, returns empty array.</returns>
public static string[] SplitPath(string path)
{
if (path == null)
return null;
else if (path.Trim() == "")
return new string[0];
List<string> output = new List<string>();
string[] paths = path.Split(';',',');
int splitterIndex = -1;
for (int i = 0; i < paths.Length; i++)
{
splitterIndex += paths[i].Length + 1;
string splitter = (splitterIndex < path.Length ? path[splitterIndex].ToString() : "");
StringBuilder sb = new StringBuilder();
if (File.Exists(paths[i]) || Directory.Exists(paths[i]))
output.Add(paths[i]);
else
{
int subSplitterIndex = 0;
bool found = false;
sb.Append(paths[i] + splitter);
for (int j = i + 1; j < paths.Length; j++)
{
subSplitterIndex += paths[j].Length + 1;
sb.Append(paths[j]);
if (File.Exists(sb.ToString()) || Directory.Exists(sb.ToString()))
{
output.Add(sb.ToString());
splitterIndex += subSplitterIndex;
i = j;
found = true;
break;
}
sb.Append(splitterIndex + subSplitterIndex < path.Length ? path[splitterIndex + subSplitterIndex].ToString() : "");
}
if (!found)
output.Add(paths[i]);
}
}
return output.ToArray();
}
public static bool CancelSearch = false;
/// <summary>
/// Searches folder and it's subfolders for files that match pattern and
/// returns array of strings that contain full paths to the files.
/// If no files found returns 0 length array.
/// </summary>
/// <param name="path">Path to one or many files separated by semi-colon or path to a folder</param>
/// <param name="namePatternToInclude">File name pattern. (E.g. *.cs) or regex to include. If null returns empty array. If empty string returns all files.</param>
/// <param name="namePatternToExclude">File name pattern. (E.g. *.cs) or regex to exclude. If null or empty is ignored.</param>
/// <param name="isRegex">Whether to use regex as search pattern. Otherwise use asterisks</param>
/// <param name="includeSubfolders">Include sub folders</param>
/// <param name="includeHidden">Include hidden folders</param>
/// <param name="includeBinary">Include binary files</param>
/// <param name="sizeFrom">Size in KB</param>
/// <param name="sizeTo">Size in KB</param>
/// <returns></returns>
public static string[] GetFileList(string path, string namePatternToInclude, string namePatternToExclude, bool isRegex, bool includeSubfolders, bool includeHidden, bool includeBinary, int sizeFrom, int sizeTo)
{
if (string.IsNullOrEmpty(path) || namePatternToInclude == null)
{
return new string[0];
}
else
{
List<string> fileMatch = new List<string>();
if (namePatternToExclude == null)
namePatternToExclude = "";
if (!isRegex)
{
string[] excludePaths = SplitPath(namePatternToExclude);
StringBuilder sb = new StringBuilder();
foreach (string exPath in excludePaths)
{
if (exPath.Trim() == "")
continue;
sb.Append(wildcardToRegex(exPath) + ";");
}
namePatternToExclude = sb.ToString();
}
string[] paths = SplitPath(path);
foreach (string subPath in paths)
{
if (subPath.Trim() == "")
continue;
try
{
DirectoryInfo di = new DirectoryInfo(subPath);
if (di.Exists)
{
string[] namePatterns = SplitPath(namePatternToInclude);
foreach (string pattern in namePatterns)
{
string rxPattern = pattern.Trim();
if (!isRegex)
rxPattern = wildcardToRegex(rxPattern);
recursiveFileSearch(di.FullName, rxPattern, namePatternToExclude.Trim(), includeSubfolders, includeHidden, includeBinary, sizeFrom, sizeTo, fileMatch);
}
}
else if (File.Exists(subPath))
{
if (!fileMatch.Contains(subPath))
fileMatch.Add(subPath);
}
}
catch (Exception ex)
{
continue;
}
}
return fileMatch.ToArray();
}
}
private static void recursiveFileSearch(string pathToFolder, string namePatternToInclude, string namePatternToExclude, bool includeSubfolders, bool includeHidden, bool includeBinary, int sizeFrom, int sizeTo, List<string> files)
{
string[] fileMatch;
string[] excludePattern = SplitPath(namePatternToExclude);
if (CancelSearch)
return;
try
{
List<string> tempFileList = new List<string>();
foreach (string fileInDirectory in Directory.GetFiles(pathToFolder))
{
if (Regex.IsMatch(Path.GetFileName(fileInDirectory), namePatternToInclude, RegexOptions.IgnoreCase))
{
bool isExcluded = false;
foreach (string subPath in excludePattern)
{
if (subPath.Trim() == "")
continue;
if (Regex.IsMatch(Path.GetFileName(fileInDirectory), subPath, RegexOptions.IgnoreCase))
isExcluded = true;
}
if (!isExcluded)
tempFileList.Add(fileInDirectory);
}
}
fileMatch = tempFileList.ToArray();
for (int i = 0; i < fileMatch.Length; i++)
{
if (sizeFrom > 0 || sizeTo > 0)
{
long sizeKB = new FileInfo(fileMatch[i]).Length / 1000;
if (sizeFrom > 0 && sizeKB < sizeFrom)
{
continue;
}
if (sizeTo > 0 && sizeKB > sizeTo)
{
continue;
}
}
if (!includeBinary && IsBinary(fileMatch[i]))
continue;
if (!files.Contains(fileMatch[i]))
files.Add(fileMatch[i]);
}
if (includeSubfolders)
{
foreach (string subDir in Directory.GetDirectories(pathToFolder))
{
DirectoryInfo dirInfo = new DirectoryInfo(subDir);
if (((dirInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) && !includeHidden)
{
continue;
}
else
{
recursiveFileSearch(subDir, namePatternToInclude, namePatternToExclude, includeSubfolders, includeHidden, includeBinary, sizeFrom, sizeTo, files);
if (CancelSearch)
return;
}
}
}
}
catch (Exception ex)
{
logger.LogException(LogLevel.Error, ex.Message, ex);
}
}
/// <summary>
/// Converts unix asterisk based file pattern to regex
/// </summary>
/// <param name="wildcard">Asterisk based pattern</param>
/// <returns>Regeular expression of null is empty</returns>
private static string wildcardToRegex(string wildcard)
{
if (wildcard == null || wildcard == "") return wildcard;
StringBuilder sb = new StringBuilder();
char[] chars = wildcard.ToCharArray();
sb.Append("^");
for (int i = 0; i < chars.Length; ++i)
{
if (chars[i] == '*')
sb.Append(".*");
else if (chars[i] == '?')
sb.Append(".");
else if ("+()^$.{}|\\".IndexOf(chars[i]) != -1)
sb.Append('\\').Append(chars[i]); // prefix all metacharacters with backslash
else
sb.Append(chars[i]);
}
sb.Append("$");
return sb.ToString().ToLowerInvariant();
}
/// <summary>
/// Parses text into int
/// </summary>
/// <param name="value">String. May include null, empty srting or text with spaces before or after.</param>
/// <returns>Attempts to parse string. Otherwise returns int.MinValue</returns>
public static int ParseInt(string value)
{
return ParseInt(value, int.MinValue);
}
/// <summary>
/// Parses text into int
/// </summary>
/// <param name="value">String. May include null, empty srting or text with spaces before or after.</param>
/// <param name="defaultValue">Default value if fails to parse.</param>
/// <returns>Attempts to parse string. Otherwise returns defaultValue</returns>
public static int ParseInt(string value, int defaultValue)
{
if (value != null && value.Length != 0)
{
int output;
value = value.Trim();
if (int.TryParse(value, out output))
{
return output;
}
}
return defaultValue;
}
/// <summary>
/// Parses text into double
/// </summary>
/// <param name="value">String. May include null, empty srting or text with spaces before or after.</param>
/// <returns>Attempts to parse string. Otherwise returns double.MinValue</returns>
public static double ParseDouble(string value)
{
return ParseDouble(value, double.MinValue);
}
/// <summary>
/// Parses text into double
/// </summary>
/// <param name="value">String. May include null, empty srting or text with spaces before or after.</param>
/// <param name="defaultValue">Default value if fails to parse.</param>
/// <returns>Attempts to parse string. Otherwise returns defaultValue</returns>
public static double ParseDouble(string value, double defaultValue)
{
if (value != null && value.Length != 0)
{
double output;
value = value.Trim();
if (double.TryParse(value, out output))
{
return output;
}
}
return defaultValue;
}
/// <summary>
/// Parses text into bool
/// </summary>
/// <param name="value">String. May include null, empty srting or text with spaces before or after.
/// Text may be in the format of True/False, Yes/No, Y/N, On/Off, 1/0</param>
/// <returns></returns>
public static bool ParseBoolean(string value)
{
return ParseBoolean(value, false);
}
/// <summary>
/// Parses text into bool
/// </summary>
/// <param name="value">String. May include null, empty srting or text with spaces before or after.
/// Text may be in the format of True/False, Yes/No, Y/N, On/Off, 1/0</param>
/// <param name="defaultValue">Default value</param>
/// <returns></returns>
public static bool ParseBoolean(string value, bool defaultValue)
{
if (value != null && value.Length != 0)
{
switch (value.Trim().ToLower())
{
case "true":
case "yes":
case "y":
case "on":
case "1":
return true;
case "false":
case "no":
case "n":
case "off":
case "0":
return false;
}
}
return defaultValue;
}
/// <summary>
/// Parses text into enum
/// </summary>
/// <typeparam name="T">Type of enum</typeparam>
/// <param name="value">Value to parse</param>
/// <param name="defaultValue">Default value</param>
/// <returns></returns>
public static T ParseEnum<T>(string value, T defaultValue)
{
if (string.IsNullOrEmpty(value))
return defaultValue;
T result = defaultValue;
try
{
result = (T)Enum.Parse(defaultValue.GetType(), value);
}
catch { }
return result;
}
/// <summary>
/// Open file using either default editor or the one provided via customEditor parameter
/// </summary>
/// <param name="fileName">File to open</param>
/// <param name="line">Line number</param>
/// <param name="useCustomEditor">True if customEditor parameter is provided</param>
/// <param name="customEditor">Custom editor path</param>
/// <param name="customEditorArgs">Arguments for custom editor</param>
public static void OpenFile(OpenFileArgs args)
{
if (!args.UseCustomEditor || args.CustomEditor == null || args.CustomEditor.Trim() == "")
{
try
{
System.Diagnostics.Process.Start(@"" + args.SearchResult.FileNameDisplayed + "");
}
catch (Exception ex)
{
ProcessStartInfo info = new ProcessStartInfo("notepad.exe");
info.UseShellExecute = false;
info.CreateNoWindow = true;
info.Arguments = args.SearchResult.FileNameDisplayed;
System.Diagnostics.Process.Start(info);
}
}
else
{
ProcessStartInfo info = new ProcessStartInfo(args.CustomEditor);
info.UseShellExecute = false;
info.CreateNoWindow = true;
if (args.CustomEditorArgs == null)
args.CustomEditorArgs = "";
info.Arguments = args.CustomEditorArgs.Replace("%file", "\"" + args.SearchResult.FileNameDisplayed + "\"").Replace("%line", args.LineNumber.ToString());
System.Diagnostics.Process.Start(info);
}
}
/// <summary>
/// Returns path to a temp folder used by dnGREP (including trailing slash). If folder does not exist
/// it gets created.
/// </summary>
/// <returns></returns>
public static string GetTempFolder()
{
string tempPath = FixFolderName(GetDataFolderPath()) + "~dnGREP-Temp\\";
if (!Directory.Exists(tempPath))
{
DirectoryInfo di = Directory.CreateDirectory(tempPath);
di.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
}
return tempPath;
}
/// <summary>
/// Deletes temp folder
/// </summary>
public static void DeleteTempFolder()
{
string tempPath = FixFolderName(GetDataFolderPath()) + "~dnGREP-Temp\\";
try
{
if (Directory.Exists(tempPath))
DeleteFolder(tempPath);
}
catch (Exception ex)
{
logger.LogException(LogLevel.Error, "Failed to delete temp folder", ex);
}
}
/// <summary>
/// Open folder in explorer
/// </summary>
/// <param name="fileName"></param>
/// <param name="line"></param>
public static void OpenContainingFolder(string fileName, int line)
{
System.Diagnostics.Process.Start(@"" + Path.GetDirectoryName(fileName) + "");
}
/// <summary>
/// Returns current path of DLL without trailing slash
/// </summary>
/// <returns></returns>
public static string GetCurrentPath()
{
return GetCurrentPath(typeof(Utils));
}
private static bool? canUseCurrentFolder = null;
/// <summary>
/// Returns path to folder where user has write access to. Either current folder or user APP_DATA.
/// </summary>
/// <returns></returns>
public static string GetDataFolderPath()
{
string currentFolder = GetCurrentPath(typeof(Utils));
if (canUseCurrentFolder == null)
{
canUseCurrentFolder = hasWriteAccessToFolder(currentFolder);
}
if (canUseCurrentFolder == true)
{
return currentFolder;
}
else
{
string dataFolder = Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\dnGREP";
if (!Directory.Exists(dataFolder))
Directory.CreateDirectory(dataFolder);
return dataFolder;
}
}
private static bool hasWriteAccessToFolder(string folderPath)
{
string filename = FixFolderName(folderPath) + "~temp.dat";
bool canAccess = true;
//1. Provide early notification that the user does not have permission to write.
FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
if (!SecurityManager.IsGranted(writePermission))
{
//No permission.
canAccess = false;
}
//2. Attempt the action but handle permission changes.
if (canAccess)
{
try
{
using (FileStream fstream = new FileStream(filename, FileMode.Create))
using (TextWriter writer = new StreamWriter(fstream))
{
writer.WriteLine("sometext");
}
}
catch (UnauthorizedAccessException ex)
{
//No permission.
canAccess = false;
}
}
// Cleanup
try
{
DeleteFile(filename);
}
catch (Exception ex)
{
// Ignore
}
return canAccess;
}
/// <summary>
/// Returns current path of DLL without trailing slash
/// </summary>
/// <param name="type">Type to check</param>
/// <returns></returns>
public static string GetCurrentPath(Type type)
{
Assembly thisAssembly = Assembly.GetAssembly(type);
return Path.GetDirectoryName(thisAssembly.Location);
}
/// <summary>
/// Returns read only files
/// </summary>
/// <param name="results"></param>
/// <returns></returns>
public static List<string> GetReadOnlyFiles(List<GrepSearchResult> results)
{
List<string> files = new List<string>();
if (results == null || results.Count == 0)
return files;
foreach (GrepSearchResult result in results)
{
if (!files.Contains(result.FileNameReal))
{
if (IsReadOnly(result))
{
files.Add(result.FileNameReal);
}
}
}
return files;
}
public static bool IsReadOnly(GrepSearchResult result)
{
if (File.Exists(result.FileNameReal) && (File.GetAttributes(result.FileNameReal) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly || result.ReadOnly)
return true;
else
return false;
}
/// <summary>
/// Returns line and line number from a multiline string based on character index
/// </summary>
/// <param name="body">Multiline string</param>
/// <param name="index">Index of any character in the line</param>
/// <param name="lineNumber">Return parameter - 1-based line number or -1 if index is outside text length</param>
/// <returns>Line of text or null if index is outside text length</returns>
public static string GetLine(string body, int index, out int lineNumber)
{
if (body == null || index < 0 || index > body.Length)
{
lineNumber = -1;
return null;
}
string subBody1 = body.Substring(0, index);
string[] lines1 = subBody1.Split(new string[] { "\r\n", "\n", "\r" }, StringSplitOptions.None);
string subBody2 = body.Substring(index);
string[] lines2 = subBody2.Split(new string[] { "\r\n", "\n", "\r" }, StringSplitOptions.None);
lineNumber = lines1.Length;
return lines1[lines1.Length - 1] + lines2[0];
}
/// <summary>
/// Returns lines and line numbers from a multiline string based on character index and length
/// </summary>
/// <param name="body">Multiline string</param>
/// <param name="index">Index of any character in the line</param>
/// <param name="length">Length of a line</param>
/// <param name="lineNumbers">Return parameter - 1-based line numbers or null if index is outside text length</param>
/// <returns>Line of text or null if index is outside text length</returns>
public static List<string> GetLines(string body, int index, int length, out List<GrepSearchResult.GrepMatch> matches, out List<int> lineNumbers)
{
List<string> result = new List<string>();
lineNumbers = new List<int>();
matches = new List<GrepSearchResult.GrepMatch>();
if (body == null || index < 0 || index > body.Length || index + length > body.Length)
{
lineNumbers = null;
matches = null;
return null;
}
string subBody1 = body.Substring(0, index);
string[] lines1 = subBody1.Split(new string[] { "\r\n", "\n", "\r" }, StringSplitOptions.None);
string subBody2 = body.Substring(index, length);
string[] lines2 = subBody2.Split(new string[] { "\r\n", "\n", "\r" }, StringSplitOptions.None);
string subBody3 = body.Substring(index + length);
string[] lines3 = subBody3.Split(new string[] { "\r\n", "\n", "\r" }, StringSplitOptions.None);
for (int i = 0; i < lines2.Length; i++)
{
string line = "";
lineNumbers.Add(lines1.Length + i);
if (i == 0)
{
if (lines2.Length == 1 && lines3.Length > 0)
{
line = lines1[lines1.Length - 1] + lines2[0] + lines3[0];
}
else
{
line = lines1[lines1.Length - 1] + lines2[0];
}
matches.Add(new GrepSearchResult.GrepMatch(lines1.Length + i, index - subBody1.Length + lines1[lines1.Length - 1].Length, lines2[0].Length));
}
else if (i == lines2.Length - 1)
{
if (lines3.Length > 0)
{
line = lines2[lines2.Length - 1] + lines3[0];
}
else
{
line = lines2[lines2.Length - 1];
}
matches.Add(new GrepSearchResult.GrepMatch(lines1.Length + i, 0, lines2[lines2.Length - 1].Length));
}
else
{
line = lines2[i];
matches.Add(new GrepSearchResult.GrepMatch(lines1.Length + i, 0, lines2[i].Length));
}
result.Add(line);
}
return result;
}
/// <summary>
/// Returns a list of context GrepLines by line numbers provided in the input parameter. Matched line is not returned.
/// </summary>
/// <param name="body"></param>
/// <param name="linesBefore"></param>
/// <param name="linesAfter"></param>
/// <param name="foundLine">1 based line number</param>
/// <returns></returns>
public static List<GrepSearchResult.GrepLine> GetContextLines(string body, int linesBefore, int linesAfter, int foundLine)
{
List<GrepSearchResult.GrepLine> result = new List<GrepSearchResult.GrepLine>();
if (body == null || body.Trim() == "")
return result;
List<int> lineNumbers = new List<int>();
string[] lines = body.Split(new string[] { "\r\n", "\n", "\r" }, StringSplitOptions.None);
for (int i = foundLine - linesBefore - 1; i <= foundLine + linesAfter - 1; i++)
{
if (i >= 0 && i < lines.Length && (i + 1) != foundLine)
result.Add(new GrepSearchResult.GrepLine(i + 1, lines[i], true, null));
}
return result;
}
/// <summary>
/// Returns number of matches
/// </summary>
/// <param name="result"></param>
/// <returns></returns>
public static int MatchCount(GrepSearchResult result)
{
int counter = 0;
if (result != null && result.SearchResults != null)
{
for (int i = 0; i < result.SearchResults.Count; i++)
{
GrepSearchResult.GrepLine line = null;
if (result.SearchResults.Count >= i)
line = result.SearchResults[i];
if (!line.IsContext)
{
if (line.Matches == null || line.Matches.Count == 0)
{
counter++;
}
else
{
counter += line.Matches.Count;
}
}
}
}
return counter;
}
/// <summary>
/// Replaces unix-style linebreaks with \r\n
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string CleanLineBreaks(string text)
{
if (string.IsNullOrEmpty(text))
return text;
string textTemp = Regex.Replace(text, "(\r)([^\n])", "\r\n$2");
textTemp = Regex.Replace(textTemp, "([^\r])(\n)", "$1\r\n");
textTemp = Regex.Replace(textTemp, "(\v)", "\r\n");
return textTemp;
}
/// <summary>
/// Sorts and removes dupes
/// </summary>
/// <param name="results"></param>
public static void CleanResults(ref List<GrepSearchResult.GrepLine> results)
{
if (results == null || results.Count == 0)
return;
results.Sort();
for (int i = results.Count - 1; i >= 0; i -- )
{
for (int j = 0; j < results.Count; j ++ )
{
if (i < results.Count &&
results[i].LineNumber == results[j].LineNumber && i != j)
{
if (results[i].IsContext)
results.RemoveAt(i);
else if (results[i].IsContext == results[j].IsContext && results[i].IsContext == false && results[i].LineNumber != -1)
{
results[j].Matches.AddRange(results[i].Matches);
results.RemoveAt(i);
}
}
}
}
for (int j = 0; j < results.Count; j++)
{
results[j].Matches.Sort();
}
}
/// <summary>
/// Returns MD5 hash for string
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string GetHash(string input)
{
// step 1, calculate MD5 hash from input
System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
// step 2, convert byte array to hex string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
/// <summary>
/// Returns true if beginText end with a non-alphanumeric character. Copied from AtroGrep.
/// </summary>
/// <param name="beginText">Text to test</param>
/// <returns></returns>
public static bool IsValidBeginText(string beginText)
{
if (beginText.Equals(string.Empty) ||
beginText.EndsWith(" ") ||
beginText.EndsWith("<") ||
beginText.EndsWith(">") ||
beginText.EndsWith("$") ||
beginText.EndsWith("+") ||
beginText.EndsWith("*") ||
beginText.EndsWith("[") ||
beginText.EndsWith("{") ||
beginText.EndsWith("(") ||
beginText.EndsWith(".") ||
beginText.EndsWith("?") ||
beginText.EndsWith("!") ||
beginText.EndsWith(",") ||
beginText.EndsWith(":") ||
beginText.EndsWith(";") ||
beginText.EndsWith("-") ||
beginText.EndsWith("\\") ||
beginText.EndsWith("/") ||
beginText.EndsWith("'") ||
beginText.EndsWith("\"") ||
beginText.EndsWith(Environment.NewLine) ||
beginText.EndsWith("\r\n") ||
beginText.EndsWith("\r") ||
beginText.EndsWith("\n")
)
{
return true;
}
return false;
}
public static string ReplaceSpecialCharacters(string input)
{
string result = input.Replace("\\t", "\t")
.Replace("\\n", "\n")
.Replace("\\0", "\0")
.Replace("\\b", "\b")
.Replace("\\r", "\r");
return result;
}
/// <summary>
/// Returns true if endText starts with a non-alphanumeric character. Copied from AtroGrep.
/// </summary>
/// <param name="endText"></param>
/// <returns></returns>
public static bool IsValidEndText(string endText)
{
if (endText.Equals(string.Empty) ||
endText.StartsWith(" ") ||
endText.StartsWith("<") ||
endText.StartsWith("$") ||
endText.StartsWith("+") ||
endText.StartsWith("*") ||
endText.StartsWith("[") ||
endText.StartsWith("{") ||
endText.StartsWith("(") ||
endText.StartsWith(".") ||
endText.StartsWith("?") ||
endText.StartsWith("!") ||
endText.StartsWith(",") ||
endText.StartsWith(":") ||
endText.StartsWith(";") ||
endText.StartsWith("-") ||
endText.StartsWith(">") ||
endText.StartsWith("]") ||
endText.StartsWith("}") ||
endText.StartsWith(")") ||
endText.StartsWith("\\") ||
endText.StartsWith("/") ||
endText.StartsWith("'") ||
endText.StartsWith("\"") ||
endText.StartsWith(Environment.NewLine) ||
endText.StartsWith("\r\n") ||
endText.StartsWith("\r") ||
endText.StartsWith("\n")
)
{
return true;
}
return false;
}
}
public class KeyValueComparer : IComparer<KeyValuePair<string, int>>
{
public int Compare(KeyValuePair<string, int> x, KeyValuePair<string, int> y)
{
return x.Key.CompareTo(y.Key);
}
}
}
| zychen63-dngrep | dnGREP.Common/Utils.cs | C# | gpl3 | 39,028 |
using System;
using System.Collections.Generic;
using System.Text;
namespace dnGREP.Common
{
public class GrepSearchResult
{
public GrepSearchResult()
{}
public GrepSearchResult(string file, List<GrepLine> results)
{
fileName = file;
searchResults = results;
}
private string fileName;
public string FileNameDisplayed
{
get { return fileName; }
set { fileName = value; }
}
private string fileNameToOpen = null;
/// <summary>
/// Use this property if FileNameDisplayed is not the same as FileNameReal.
/// If null, FileNameDisplayed is used.
/// </summary>
/// <example>
/// Files in archive have the following FileNameDisplayed "c:\path-to-archive\archive.zip\file1.txt" while
/// FileNameReal is ""c:\path-to-archive\archive.zip".
/// </example>
public string FileNameReal
{
get {
if (fileNameToOpen == null)
return fileName;
else
return fileNameToOpen;
}
set { fileNameToOpen = value; }
}
private bool readOnly = false;
public bool ReadOnly
{
get { return readOnly; }
set { readOnly = value; }
}
private List<GrepLine> searchResults = new List<GrepLine>();
public List<GrepLine> SearchResults
{
get { return searchResults; }
}
public class GrepLine : IComparable<GrepLine>, IComparable
{
public GrepLine(int number, string text, bool context, List<GrepMatch> matches)
{
lineNumber = number;
lineText = text;
isContext = context;
if (matches == null)
this.matches = new List<GrepMatch>();
else
this.matches = matches;
}
private int lineNumber;
public int LineNumber
{
get { return lineNumber; }
set { lineNumber = value; }
}
private string lineText;
public string LineText
{
get { return lineText; }
}
private bool isContext = false;
public bool IsContext
{
get { return isContext; }
}
private List<GrepMatch> matches;
public List<GrepMatch> Matches
{
get { return matches; }
}
public override string ToString()
{
return string.Format("{0}. {1} ({2})", lineNumber, lineText, isContext);
}
#region IComparable<GrepLine> Members
public int CompareTo(GrepLine other)
{
if (other == null)
return 1;
else
return lineNumber.CompareTo(other.LineNumber);
}
#endregion
#region IComparable Members
public int CompareTo(object obj)
{
if (obj == null)
return 1;
if (obj is GrepLine)
return lineNumber.CompareTo(((GrepLine)obj).LineNumber);
else
return 1;
}
#endregion
}
public class GrepMatch : IComparable<GrepMatch>, IComparable
{
public GrepMatch(int line, int from, int length)
{
lineNumber = line;
startLocation = from;
this.length = length;
}
private int lineNumber = 0;
public int LineNumber
{
get { return lineNumber; }
set { lineNumber = value; }
}
private int startLocation = 0;
public int StartLocation
{
get { return startLocation; }
set { startLocation = value; }
}
private int length = 0;
public int Length
{
get { return length; }
set { length = value; }
}
#region IComparable<GrepMatch> Members
public int CompareTo(GrepMatch other)
{
if (other == null)
return 1;
else
return startLocation.CompareTo(other.StartLocation);
}
#endregion
#region IComparable Members
public int CompareTo(object obj)
{
if (obj == null)
return 1;
if (obj is GrepMatch)
return startLocation.CompareTo(((GrepMatch)obj).StartLocation);
else
return 1;
}
#endregion
}
}
}
| zychen63-dngrep | dnGREP.Common/GrepSearchResult.cs | C# | gpl3 | 4,196 |
using System;
using System.Collections.Generic;
using System.Text;
namespace dnGREP.Common
{
public class OpenFileArgs : EventArgs
{
private GrepSearchResult searchResult;
/// <summary>
/// Search result containing file name
/// </summary>
public GrepSearchResult SearchResult
{
get { return searchResult; }
set { searchResult = value; }
}
private int lineNumber;
/// <summary>
/// Line number
/// </summary>
public int LineNumber
{
get { return lineNumber; }
set { lineNumber = value; }
}
private bool useCustomEditor;
/// <summary>
/// If true, CustomEditor is used to open the file
/// </summary>
public bool UseCustomEditor
{
get { return useCustomEditor; }
set { useCustomEditor = value; }
}
private string customEditor;
/// <summary>
/// Path to custom editor (if UseCustomEditor is true)
/// </summary>
public string CustomEditor
{
get { return customEditor; }
set { customEditor = value; }
}
private string customEditorArgs;
/// <summary>
/// Command line arguments for custom editor
/// </summary>
public string CustomEditorArgs
{
get { return customEditorArgs; }
set { customEditorArgs = value; }
}
private bool useBaseEngine;
/// <summary>
/// Set to true to have base engine handle the request
/// </summary>
public bool UseBaseEngine
{
get { return useBaseEngine; }
set { useBaseEngine = value; }
}
public OpenFileArgs(GrepSearchResult searchResult, int line, bool useCustomEditor, string customEditor, string customEditorArgs)
: base()
{
this.searchResult = searchResult;
this.lineNumber = line;
this.useCustomEditor = useCustomEditor;
this.customEditor = customEditor;
this.customEditorArgs = customEditorArgs;
this.useBaseEngine = false;
}
public OpenFileArgs()
: this(null, -1, false, null, null)
{ }
}
}
| zychen63-dngrep | dnGREP.Common/OpenFileArgs.cs | C# | gpl3 | 1,975 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using NLog;
using System.Xml.Serialization;
using System.Xml;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace dnGREP.Common
{
/// <summary>
/// Singleton class used to maintain and persist application settings
/// </summary>
public class GrepSettings : SerializableDictionary<string, string>
{
public static class Key
{
public const string SearchFolder = "SearchFolder";
public const string SearchFor = "SearchFor";
public const string ReplaceWith = "ReplaceWith";
public const string IncludeHidden = "IncludeHidden";
public const string IncludeBinary = "IncludeBinary";
public const string IncludeSubfolder = "IncludeSubfolder";
public const string TypeOfSearch = "TypeOfSearch";
public const string TypeOfFileSearch = "TypeOfFileSearch";
public const string FilePattern = "FilePattern";
public const string FilePatternIgnore = "FilePatternIgnore";
public const string UseFileSizeFilter = "UseFileSizeFilter";
public const string CaseSensitive = "CaseSensitive";
public const string Multiline = "Multiline";
public const string Singleline = "Singleline";
public const string WholeWord = "WholeWord";
public const string SizeFrom = "SizeFrom";
public const string SizeTo = "SizeTo";
public const string FuzzyMatchThreshold = "FuzzyMatchThreshold";
public const string ShowLinesInContext = "ShowLinesInContext";
public const string ContextLinesBefore = "ContextLinesBefore";
public const string ContextLinesAfter = "ContextLinesAfter";
public const string EnableUpdateChecking = "EnableUpdateChecking";
public const string ShowFilePathInResults = "ShowFilePathInResults";
public const string AllowSearchingForFileNamePattern = "AllowSearchingForFileNamePattern";
public const string UseCustomEditor = "UseCustomEditor";
public const string CustomEditor = "CustomEditor";
public const string CustomEditorArgs = "CustomEditorArgs";
public const string UpdateCheckInterval = "UpdateCheckInterval";
public const string PreviewResults = "PreviewResults";
public const string ExpandResults = "ExpandResults";
public const string LastCheckedVersion = "LastCheckedVersion";
public const string IsOptionsExpanded = "IsOptionsExpanded";
public const string MainFormWidth = "MainForm.Width";
public const string MainFormHeight = "MainForm.Height";
public const string FastSearchBookmarks = "FastSearchBookmarks";
public const string FastReplaceBookmarks = "FastReplaceBookmarks";
public const string FastFileMatchBookmarks = "FastFileMatchBookmarks";
public const string FastFileNotMatchBookmarks = "FastFileNotMatchBookmarks";
public const string FastPathBookmarks = "FastPathBookmarks";
public const string TextFormatting = "TextFormatting";
}
private static GrepSettings instance;
private static Logger logger = LogManager.GetCurrentClassLogger();
private const string storageFileName = "dnGREP.Settings.dat";
private GrepSettings() { }
public static GrepSettings Instance
{
get
{
if (instance == null)
{
instance = new GrepSettings();
instance.Load();
}
return instance;
}
}
/// <summary>
/// Loads settings from default location - baseFolder\\dnGREP.Settings.dat
/// </summary>
public void Load()
{
Load(Utils.GetDataFolderPath() + "\\" + storageFileName);
}
/// <summary>
/// Load settings from location specified
/// </summary>
/// <param name="path">Path to settings file</param>
public void Load(string path)
{
try
{
if (!File.Exists(path))
return;
using (FileStream stream = File.OpenRead(path))
{
if (stream == null)
return;
XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary<string, string>));
this.Clear();
SerializableDictionary<string, string> appData = (SerializableDictionary<string, string>)serializer.Deserialize(stream);
foreach (KeyValuePair<string, string> pair in appData)
this[pair.Key] = pair.Value;
}
}
catch (Exception ex)
{
logger.LogException(LogLevel.Error, "Failed to load settings", ex);
}
}
/// <summary>
/// Saves settings to default location - baseFolder\\dnGREP.Settings.dat
/// </summary>
public void Save()
{
Save(Utils.GetDataFolderPath() + "\\" + storageFileName);
}
/// <summary>
/// Saves settings to location specified
/// </summary>
/// <param name="path">Path to settings file</param>
public void Save(string path)
{
try
{
if (!Directory.Exists(Path.GetDirectoryName(path)))
Directory.CreateDirectory(Path.GetDirectoryName(path));
lock (this)
{
// Create temp file in case save crashes
using (FileStream stream = File.OpenWrite(path + "~"))
{
if (stream == null)
return;
XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary<string, string>));
serializer.Serialize(stream, this);
}
File.Copy(path + "~", path, true);
Utils.DeleteFile(path + "~");
}
}
catch (Exception ex)
{
logger.LogException(LogLevel.Error, "Failed to load settings", ex);
}
}
public new string this[string key]
{
get { return ContainsKey(key) ? base[key] : null; }
set { base[key] = value; }
}
/// <summary>
/// Gets value of object in dictionary and deserializes it to specified type
/// </summary>
/// <typeparam name="T">Type of object to deserialize from</typeparam>
/// <param name="key">Key</param>
/// <returns></returns>
public T Get<T>(string key)
{
string value = this[key];
if (value == null)
return default(T);
try
{
if (typeof(T) == typeof(string))
{
return (T)Convert.ChangeType(value, typeof(string));
}
else if (typeof(T).IsEnum)
{
return (T)Enum.Parse(typeof(T), value);
}
else if (!typeof(T).IsPrimitive)
{
using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(value)))
{
IFormatter formatter = new BinaryFormatter();
return (T)formatter.Deserialize(stream);
}
}
else
{
return (T)Convert.ChangeType(value, typeof(T));
}
}
catch (Exception ex)
{
return default(T);
}
}
/// <summary>
/// Sets value of object in dictionary and serializes it to specified type
/// </summary>
/// <typeparam name="T">Type of object to serialize into</typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
public void Set<T>(string key, T value)
{
if (value == null)
return;
if (typeof(T) == typeof(string))
{
this[key] = value.ToString();
}
else if (typeof(T).IsEnum)
{
this[key] = value.ToString();
}
else if (!typeof(T).IsPrimitive)
{
using (MemoryStream stream = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, value);
stream.Position = 0;
this[key] = Convert.ToBase64String(stream.ToArray());
}
}
else
{
this[key] = value.ToString();
}
}
}
/// <summary>
/// Serializable generic dictionary
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue>
: Dictionary<TKey, TValue>, IXmlSerializable
{
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
return;
while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
{
reader.ReadStartElement("item");
reader.ReadStartElement("key");
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement("value");
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();
this.Add(key, value);
reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
foreach (TKey key in this.Keys)
{
writer.WriteStartElement("item");
writer.WriteStartElement("key");
keySerializer.Serialize(writer, key);
writer.WriteEndElement();
writer.WriteStartElement("value");
TValue value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
#endregion
}
}
| zychen63-dngrep | dnGREP.Common/GrepApplicationSettings.cs | C# | gpl3 | 9,302 |
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;
using System.Xml;
using NLog;
using System.Data;
namespace dnGREP.Common
{
public class BookmarkLibrary
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private static BookmarkEntity bookmarks;
public static BookmarkEntity Instance
{
get {
if (bookmarks == null)
Load();
return bookmarks;
}
}
private BookmarkLibrary() { }
private const string storageFileName = "Bookmarks";
public static void Load()
{
try
{
BookmarkEntity bookmarkLib;
XmlSerializer serializer = new XmlSerializer(typeof(BookmarkEntity));
if (!File.Exists(Utils.GetDataFolderPath() + "\\bookmarks.xml"))
{
bookmarks = new BookmarkEntity();
}
else
{
using (TextReader reader = new StreamReader(Utils.GetDataFolderPath() + "\\bookmarks.xml"))
{
bookmarkLib = (BookmarkEntity)serializer.Deserialize(reader);
bookmarks = bookmarkLib;
}
}
}
catch (Exception ex)
{
bookmarks = new BookmarkEntity();
}
}
public static void Save()
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(BookmarkEntity));
using (TextWriter writer = new StreamWriter(Utils.GetDataFolderPath() + "\\bookmarks.xml"))
{
serializer.Serialize(writer, bookmarks);
}
}
catch (Exception ex)
{
logger.LogException(LogLevel.Error, ex.Message, ex);
}
}
}
[Serializable]
public class BookmarkEntity
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private List<Bookmark> bookmarks = new List<Bookmark>();
public List<Bookmark> Bookmarks
{
get { return bookmarks; }
set { bookmarks = value; }
}
public DataTable GetDataTable()
{
DataTable bookmarkTable = new DataTable();
bookmarkTable.Columns.Add("Description", typeof(String));
bookmarkTable.Columns.Add("SearchPattern", typeof(String));
bookmarkTable.Columns.Add("ReplacePattern", typeof(String));
bookmarkTable.Columns.Add("FileNames", typeof(String));
bookmarks.Sort(new BookmarkComparer());
foreach (Bookmark b in bookmarks)
{
bookmarkTable.LoadDataRow(new string[] {b.Description, b.SearchPattern,
b.ReplacePattern, b.FileNames}, true);
}
return bookmarkTable;
}
public BookmarkEntity() { }
}
[Serializable]
public class Bookmark
{
public Bookmark() { }
public Bookmark(string pattern, string replacement, string files, string desc)
{
searchPattern = pattern;
replacePattern = replacement;
fileNames = files;
description = desc;
}
private string searchPattern;
public string SearchPattern
{
get { return searchPattern; }
set { searchPattern = value; }
}
private string replacePattern;
public string ReplacePattern
{
get { return replacePattern; }
set { replacePattern = value; }
}
private string fileNames;
public string FileNames
{
get { return fileNames; }
set { fileNames = value; }
}
private string description;
public string Description
{
get { return description; }
set { description = value; }
}
public override bool Equals(object obj)
{
if (obj == null || !(obj is Bookmark))
{
return false;
}
else
{
Bookmark otherBookmark = (Bookmark)obj;
if (this.FileNames == otherBookmark.FileNames &&
this.ReplacePattern == otherBookmark.ReplacePattern &&
this.SearchPattern == otherBookmark.SearchPattern)
return true;
else
return false;
}
}
public override int GetHashCode()
{
return (FileNames + ReplacePattern + SearchPattern).GetHashCode();
}
}
public class BookmarkComparer : IComparer<Bookmark>
{
#region IComparer<Bookmark> Members
public int Compare(Bookmark x, Bookmark y)
{
return x.SearchPattern.CompareTo(y.SearchPattern);
}
#endregion
}
}
| zychen63-dngrep | dnGREP.Common/BookmarkLibrary.cs | C# | gpl3 | 4,185 |
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("dnGREP.Common1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("BAH")]
[assembly: AssemblyProduct("dnGREP.Common1")]
[assembly: AssemblyCopyright("Copyright © BAH 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0f9a83f7-d793-477c-8d40-91293d67a793")]
// 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")]
| zychen63-dngrep | dnGREP.Common/Properties/AssemblyInfo.cs | C# | gpl3 | 1,446 |
using System;
using System.Collections.Generic;
using System.Text;
namespace dnGREP.Common
{
public enum SearchType
{
PlainText,
Regex,
XPath,
Soundex
}
public enum FileSearchType
{
Asterisk,
Regex
}
public enum FileSizeFilter
{
Yes,
No
}
[Flags]
public enum GrepSearchOption
{
None = 0,
CaseSensitive = 1,
Multiline = 2,
SingleLine = 4,
WholeWord = 8
}
public enum GrepOperation
{
Search,
SearchInResults,
Replace,
None
}
}
| zychen63-dngrep | dnGREP.Common/Enums.cs | C# | gpl3 | 560 |
using System;
using System.Collections.Generic;
using System.Text;
namespace dnGREP.Common
{
public class SearchDelegates
{
public delegate List<GrepSearchResult.GrepLine> DoSearch(string text, string searchPattern, GrepSearchOption searchOptions, bool includeContext);
public delegate string DoReplace(string text, string searchPattern, string replacePattern, GrepSearchOption searchOptions);
}
}
| zychen63-dngrep | dnGREP.Common/SearchDelegates.cs | C# | gpl3 | 430 |
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Xml;
using System.Text.RegularExpressions;
namespace dnGREP.Common
{
public class PublishedVersionExtractor
{
HttpWebRequest webRequest;
public delegate void VersionExtractorHandler(object sender, PackageVersion files);
public event VersionExtractorHandler RetrievedVersion;
public class PackageVersion
{
public PackageVersion(string version)
{
Version = version;
}
public string Version;
}
public void StartWebRequest()
{
webRequest = (HttpWebRequest)WebRequest.Create("http://code.google.com/feeds/p/dngrep/downloads/basic");
webRequest.Method = "GET";
webRequest.BeginGetResponse(new AsyncCallback(finishWebRequest), null);
}
private void finishWebRequest(IAsyncResult result)
{
XmlDocument response = new XmlDocument();
try
{
using (HttpWebResponse resp = (HttpWebResponse)webRequest.EndGetResponse(result))
{
if (resp.StatusCode == HttpStatusCode.OK)
{
XmlTextReader reader = new XmlTextReader(resp.GetResponseStream());
response.Load(reader);
reader.Close();
}
}
}
catch (Exception ex)
{
RetrievedVersion(this, new PackageVersion("0.0.0.0"));
}
if (RetrievedVersion != null)
RetrievedVersion(this, new PackageVersion(extractVersion(response)));
}
private string extractVersion(XmlDocument doc)
{
if (doc != null)
{
XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
XmlNodeList nodes = doc.GetElementsByTagName("title");
Version version = new Version();
foreach (XmlNode node in nodes)
{
Regex versionRe = new Regex(@"d?nGREP\s+(?<version>[\d\.]+)\.\w+");
if (versionRe.IsMatch(node.InnerText))
{
Version tempVersion = new Version(versionRe.Match(node.InnerText).Groups["version"].Value);
if (version == null || version.CompareTo(tempVersion) < 0)
version = tempVersion;
}
}
return version.ToString();
}
else
{
return null;
}
}
public static bool IsUpdateNeeded(string currentVersion, string publishedVersion)
{
if (string.IsNullOrEmpty(currentVersion) ||
string.IsNullOrEmpty(publishedVersion))
{
return false;
}
else
{
try
{
Version cVersion = new Version(currentVersion);
Version pVersion = new Version(publishedVersion);
if (cVersion.CompareTo(pVersion) < 0)
return true;
else
return false;
}
catch (Exception ex)
{
return false;
}
}
}
}
}
| zychen63-dngrep | dnGREP.Common/PublishedVersionExtractor.cs | C# | gpl3 | 2,701 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Globalization;
namespace dnGREP.WPF
{
public class EnumBooleanConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var ParameterString = parameter as string;
if (ParameterString == null)
return DependencyProperty.UnsetValue;
if (Enum.IsDefined(value.GetType(), value) == false)
return DependencyProperty.UnsetValue;
object paramvalue = Enum.Parse(value.GetType(), ParameterString);
if (paramvalue.Equals(value))
return true;
else
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var ParameterString = parameter as string;
if (ParameterString == null)
return DependencyProperty.UnsetValue;
return Enum.Parse(targetType, ParameterString);
}
#endregion
}
}
| zychen63-dngrep | dnGREP.WPF/EnumBooleanConverter.cs | C# | gpl3 | 1,088 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using dnGREP.Common;
using dnGREP.Engines;
using NLog;
using System.IO;
using System.Reflection;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using dnGREP.Common.UI;
using System.Text.RegularExpressions;
namespace dnGREP.WPF
{
/// <summary>
/// Interaction logic for MainForm.xaml
/// </summary>
public partial class MainForm : Window
{
private List<KeyValuePair<string, int>> encodings = new List<KeyValuePair<string, int>>();
private static Logger logger = LogManager.GetCurrentClassLogger();
private DateTime timer = DateTime.Now;
private PublishedVersionExtractor ve = new PublishedVersionExtractor();
private FileFolderDialogWin32 fileFolderDialog = new FileFolderDialogWin32();
private BackgroundWorker workerSearchReplace = new BackgroundWorker();
private MainFormState inputData = new MainFormState();
private BookmarksForm bookmarkForm;
private System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
private System.Windows.Forms.HelpProvider helpProvider = new System.Windows.Forms.HelpProvider();
public GrepSettings settings
{
get { return GrepSettings.Instance; }
}
#region Check version
private void checkVersion()
{
try
{
if (settings.Get<bool>(GrepSettings.Key.EnableUpdateChecking))
{
DateTime lastCheck = settings.Get<DateTime>(GrepSettings.Key.LastCheckedVersion);
TimeSpan duration = DateTime.Now.Subtract(lastCheck);
if (duration.TotalDays >= settings.Get<int>(GrepSettings.Key.UpdateCheckInterval));
{
ve.StartWebRequest();
settings.Set<DateTime>(GrepSettings.Key.LastCheckedVersion, DateTime.Now);
}
}
}
catch (Exception ex)
{
logger.LogException(LogLevel.Error, ex.Message, ex);
}
}
void ve_RetrievedVersion(object sender, PublishedVersionExtractor.PackageVersion version)
{
try
{
if (version.Version != null)
{
string currentVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
if (PublishedVersionExtractor.IsUpdateNeeded(currentVersion, version.Version))
{
if (MessageBox.Show("New version of dnGREP (" + version.Version + ") is available for download.\nWould you like to download it now?", "New version", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
{
System.Diagnostics.Process.Start("http://code.google.com/p/dngrep/");
}
}
}
}
catch (Exception ex)
{
logger.LogException(LogLevel.Error, ex.Message, ex);
}
}
#endregion
public void UpdateState()
{
inputData.LoadAppSettings();
inputData.UpdateState("");
}
private void winFormControlsInit()
{
this.workerSearchReplace.WorkerReportsProgress = true;
this.workerSearchReplace.WorkerSupportsCancellation = true;
this.workerSearchReplace.DoWork += new System.ComponentModel.DoWorkEventHandler(this.doSearchReplace);
this.workerSearchReplace.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.searchComplete);
this.workerSearchReplace.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.searchProgressChanged);
this.saveFileDialog.Filter = "CSV file|*.csv";
DiginesisHelpProvider.HelpNamespace = "Doc\\dnGREP.chm";
DiginesisHelpProvider.ShowHelp = true;
double width = settings.Get<double>(GrepSettings.Key.MainFormWidth);
double height = settings.Get<double>(GrepSettings.Key.MainFormHeight);
if (width > 0)
Width = width;
if (height > 0)
Height = height;
}
private void populateEncodings()
{
KeyValuePair<string, int> defaultValue = new KeyValuePair<string, int>("Auto detection (default)", -1);
foreach (EncodingInfo ei in Encoding.GetEncodings())
{
Encoding e = ei.GetEncoding();
encodings.Add(new KeyValuePair<string, int>(e.EncodingName, e.CodePage));
}
encodings.Sort(new KeyValueComparer());
encodings.Insert(0, defaultValue);
cbEncoding.ItemsSource = encodings;
cbEncoding.DisplayMemberPath = "Key";
cbEncoding.SelectedValuePath = "Value";
cbEncoding.SelectedIndex = 0;
}
public MainForm()
{
InitializeComponent();
this.DataContext = inputData;
tvSearchResult.ItemsSource = inputData.SearchResults;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
winFormControlsInit();
populateEncodings();
ve.RetrievedVersion += new PublishedVersionExtractor.VersionExtractorHandler(ve_RetrievedVersion);
checkVersion();
inputData.UpdateState("");
}
void bookmarkForm_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "FilePattern")
inputData.FilePattern = bookmarkForm.FilePattern;
else if (e.PropertyName == "SearchFor")
inputData.SearchFor = bookmarkForm.SearchFor;
else if (e.PropertyName == "ReplaceWith")
inputData.ReplaceWith = bookmarkForm.ReplaceWith;
}
private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
fileFolderDialog.Dialog.Multiselect = true;
fileFolderDialog.SelectedPath = Utils.GetBaseFolder(tbFolderName.Text);
if (tbFolderName.Text == "")
{
string clipboard = Clipboard.GetText();
try
{
if (System.IO.Path.IsPathRooted(clipboard))
fileFolderDialog.SelectedPath = clipboard;
}
catch (Exception ex)
{
// Ignore
}
}
if (fileFolderDialog.ShowDialog() == true)
{
if (fileFolderDialog.SelectedPaths != null)
inputData.FileOrFolderPath = fileFolderDialog.SelectedPaths;
else
inputData.FileOrFolderPath = fileFolderDialog.SelectedPath;
}
}
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
if (inputData.CurrentGrepOperation == GrepOperation.None && !workerSearchReplace.IsBusy)
{
inputData.CurrentGrepOperation = GrepOperation.Search;
lblStatus.Text = "Searching...";
barProgressBar.Value = 0;
inputData.SearchResults.Clear();
Dictionary<string, object> workerParames = new Dictionary<string, object>();
workerParames["State"] = inputData;
if (!settings.Get<bool>(GrepSettings.Key.PreviewResults))
tvSearchResult.ItemsSource = null;
workerSearchReplace.RunWorkerAsync(workerParames);
// Update bookmarks
if (!inputData.FastSearchBookmarks.Contains(tbSearchFor.Text))
{
inputData.FastSearchBookmarks.Insert(0, tbSearchFor.Text);
}
if (!inputData.FastFileMatchBookmarks.Contains(tbFilePattern.Text))
{
inputData.FastFileMatchBookmarks.Insert(0, tbFilePattern.Text);
}
if (!inputData.FastFileNotMatchBookmarks.Contains(tbFilePatternIgnore.Text))
{
inputData.FastFileNotMatchBookmarks.Insert(0, tbFilePatternIgnore.Text);
}
if (!inputData.FastPathBookmarks.Contains(tbFolderName.Text))
{
inputData.FastPathBookmarks.Insert(0, tbFolderName.Text);
}
}
}
private void btnSearchInResults_Click(object sender, RoutedEventArgs e)
{
if (inputData.CurrentGrepOperation == GrepOperation.None && !workerSearchReplace.IsBusy)
{
inputData.CurrentGrepOperation = GrepOperation.SearchInResults;
lblStatus.Text = "Searching...";
barProgressBar.Value = 0;
List<string> foundFiles = new List<string>();
foreach (FormattedGrepResult n in inputData.SearchResults) foundFiles.Add(n.GrepResult.FileNameReal);
Dictionary<string, object> workerParames = new Dictionary<string, object>();
workerParames["State"] = inputData;
workerParames["Files"] = foundFiles;
inputData.SearchResults.Clear();
if (!settings.Get<bool>(GrepSettings.Key.PreviewResults))
tvSearchResult.ItemsSource = null;
workerSearchReplace.RunWorkerAsync(workerParames);
// Update bookmarks
if (!inputData.FastSearchBookmarks.Contains(tbSearchFor.Text))
{
inputData.FastSearchBookmarks.Insert(0, tbSearchFor.Text);
}
if (!inputData.FastFileMatchBookmarks.Contains(tbFilePattern.Text))
{
inputData.FastFileMatchBookmarks.Insert(0, tbFilePattern.Text);
}
if (!inputData.FastFileNotMatchBookmarks.Contains(tbFilePatternIgnore.Text))
{
inputData.FastFileNotMatchBookmarks.Insert(0, tbFilePatternIgnore.Text);
}
if (!inputData.FastPathBookmarks.Contains(tbFolderName.Text))
{
inputData.FastPathBookmarks.Insert(0, tbFolderName.Text);
}
}
}
private void btnReplace_Click(object sender, RoutedEventArgs e)
{
if (inputData.CurrentGrepOperation == GrepOperation.None && !workerSearchReplace.IsBusy)
{
if (string.IsNullOrEmpty(inputData.ReplaceWith))
{
if (MessageBox.Show("Are you sure you want to replace search pattern with empty string?", "Replace", MessageBoxButton.YesNoCancel, MessageBoxImage.Question) != MessageBoxResult.Yes)
return;
}
List<string> roFiles = Utils.GetReadOnlyFiles(inputData.SearchResults.GetList());
if (roFiles.Count > 0)
{
StringBuilder sb = new StringBuilder("Some of the files can not be modified. If you continue, these files will be skipped.\nWould you like to continue?\n\n");
foreach (string fileName in roFiles)
{
sb.AppendLine(" - " + new FileInfo(fileName).Name);
}
if (MessageBox.Show(sb.ToString(), "Replace", MessageBoxButton.YesNoCancel, MessageBoxImage.Question) != MessageBoxResult.Yes)
return;
}
lblStatus.Text = "Replacing...";
inputData.CurrentGrepOperation = GrepOperation.Replace;
inputData.CanUndo = false;
inputData.UndoFolder = Utils.GetBaseFolder(tbFolderName.Text);
barProgressBar.Value = 0;
List<string> foundFiles = new List<string>();
foreach (FormattedGrepResult n in inputData.SearchResults)
{
if (!n.GrepResult.ReadOnly)
foundFiles.Add(n.GrepResult.FileNameReal);
}
Dictionary<string, object> workerParames = new Dictionary<string, object>();
workerParames["State"] = inputData;
workerParames["Files"] = foundFiles;
inputData.SearchResults.Clear();
workerSearchReplace.RunWorkerAsync(workerParames);
// Update bookmarks
if (!inputData.FastReplaceBookmarks.Contains(tbReplaceWith.Text))
{
inputData.FastReplaceBookmarks.Insert(0, tbReplaceWith.Text);
}
if (!inputData.FastFileMatchBookmarks.Contains(tbFilePattern.Text))
{
inputData.FastFileMatchBookmarks.Insert(0, tbFilePattern.Text);
}
if (!inputData.FastFileNotMatchBookmarks.Contains(tbFilePatternIgnore.Text))
{
inputData.FastFileNotMatchBookmarks.Insert(0, tbFilePatternIgnore.Text);
}
if (!inputData.FastPathBookmarks.Contains(tbFolderName.Text))
{
inputData.FastPathBookmarks.Insert(0, tbFolderName.Text);
}
}
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
if (inputData.CurrentGrepOperation != GrepOperation.None)
{
GrepCore.CancelProcess = true;
Utils.CancelSearch = true;
}
}
private void doSearchReplace(object sender, DoWorkEventArgs e)
{
try
{
if (!workerSearchReplace.CancellationPending)
{
timer = DateTime.Now;
Dictionary<string, object> workerParams = (Dictionary<string, object>)e.Argument;
MainFormState param = (MainFormState)workerParams["State"];
if (param.CurrentGrepOperation == GrepOperation.Search || param.CurrentGrepOperation == GrepOperation.SearchInResults)
{
int sizeFrom = 0;
int sizeTo = 0;
if (param.UseFileSizeFilter == FileSizeFilter.Yes)
{
sizeFrom = param.SizeFrom;
sizeTo = param.SizeTo;
}
string filePatternInclude = "*.*";
if (param.TypeOfFileSearch == FileSearchType.Regex)
filePatternInclude = ".*";
if (!string.IsNullOrEmpty(param.FilePattern))
filePatternInclude = param.FilePattern;
if (param.TypeOfFileSearch == FileSearchType.Asterisk)
filePatternInclude = filePatternInclude.Replace("\\", "");
string filePatternExclude = "";
if (!string.IsNullOrEmpty(param.FilePatternIgnore))
filePatternExclude = param.FilePatternIgnore;
if (param.TypeOfFileSearch == FileSearchType.Asterisk)
filePatternExclude = filePatternExclude.Replace("\\", "");
string[] files;
Utils.CancelSearch = false;
if (param.CurrentGrepOperation == GrepOperation.SearchInResults)
{
files = ((List<string>)workerParams["Files"]).ToArray();
}
else
{
files = Utils.GetFileList(inputData.FileOrFolderPath, filePatternInclude, filePatternExclude, param.TypeOfFileSearch == FileSearchType.Regex, param.IncludeSubfolder,
param.IncludeHidden, param.IncludeBinary, sizeFrom, sizeTo);
}
if (Utils.CancelSearch)
{
e.Result = null;
return;
}
if (param.TypeOfSearch == SearchType.Regex)
{
try
{
Regex pattern = new Regex(param.SearchFor);
}
catch (ArgumentException regException)
{
MessageBox.Show("Incorrect pattern: " + regException.Message, "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
e.Result = null;
return;
}
}
GrepCore grep = new GrepCore();
grep.SearchParams.FuzzyMatchThreshold = settings.Get<double>(GrepSettings.Key.FuzzyMatchThreshold);
grep.SearchParams.ShowLinesInContext = settings.Get<bool>(GrepSettings.Key.ShowLinesInContext);
grep.SearchParams.LinesBefore = settings.Get<int>(GrepSettings.Key.ContextLinesBefore);
grep.SearchParams.LinesAfter = settings.Get<int>(GrepSettings.Key.ContextLinesAfter);
grep.PreviewFilesDuringSearch = settings.Get<bool>(GrepSettings.Key.PreviewResults);
GrepSearchOption searchOptions = GrepSearchOption.None;
if (inputData.Multiline)
searchOptions |= GrepSearchOption.Multiline;
if (inputData.CaseSensitive)
searchOptions |= GrepSearchOption.CaseSensitive;
if (inputData.Singleline)
searchOptions |= GrepSearchOption.SingleLine;
if (inputData.WholeWord)
searchOptions |= GrepSearchOption.WholeWord;
grep.ProcessedFile += new GrepCore.SearchProgressHandler(grep_ProcessedFile);
List<GrepSearchResult> results = null;
e.Result = grep.Search(files, param.TypeOfSearch, param.SearchFor, searchOptions, param.CodePage);
grep.ProcessedFile -= new GrepCore.SearchProgressHandler(grep_ProcessedFile);
}
else
{
GrepCore grep = new GrepCore();
grep.SearchParams.FuzzyMatchThreshold = settings.Get<double>(GrepSettings.Key.FuzzyMatchThreshold);
grep.SearchParams.ShowLinesInContext = settings.Get<bool>(GrepSettings.Key.ShowLinesInContext);
grep.SearchParams.LinesBefore = settings.Get<int>(GrepSettings.Key.ContextLinesBefore);
grep.SearchParams.LinesAfter = settings.Get<int>(GrepSettings.Key.ContextLinesAfter);
grep.PreviewFilesDuringSearch = settings.Get<bool>(GrepSettings.Key.PreviewResults);
GrepSearchOption searchOptions = GrepSearchOption.None;
if (inputData.Multiline)
searchOptions |= GrepSearchOption.Multiline;
if (inputData.CaseSensitive)
searchOptions |= GrepSearchOption.CaseSensitive;
if (inputData.Singleline)
searchOptions |= GrepSearchOption.SingleLine;
if (inputData.WholeWord)
searchOptions |= GrepSearchOption.WholeWord;
grep.ProcessedFile += new GrepCore.SearchProgressHandler(grep_ProcessedFile);
string[] files = ((List<string>)workerParams["Files"]).ToArray();
e.Result = grep.Replace(files, param.TypeOfSearch, Utils.GetBaseFolder(param.FileOrFolderPath), param.SearchFor, param.ReplaceWith, searchOptions, param.CodePage);
grep.ProcessedFile -= new GrepCore.SearchProgressHandler(grep_ProcessedFile);
}
}
}
catch (Exception ex)
{
logger.LogException(LogLevel.Error, ex.Message, ex);
bool isSearch = true;
if (e.Argument is MainFormState)
{
MainFormState param = (MainFormState)e.Argument;
if (param.CurrentGrepOperation == GrepOperation.Search || param.CurrentGrepOperation == GrepOperation.SearchInResults)
isSearch = true;
else
isSearch = false;
}
if (isSearch)
MessageBox.Show("Search failed! See error log.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
else
MessageBox.Show("Replace failed! See error log.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
void grep_ProcessedFile(object sender, GrepCore.ProgressStatus progress)
{
workerSearchReplace.ReportProgress((int)(progress.ProcessedFiles * 100 / progress.TotalFiles), progress);
}
private void searchProgressChanged(object sender, ProgressChangedEventArgs e)
{
try
{
if (!GrepCore.CancelProcess)
{
GrepCore.ProgressStatus progress = (GrepCore.ProgressStatus)e.UserState;
barProgressBar.Value = e.ProgressPercentage;
lblStatus.Text = "(" + progress.ProcessedFiles + " of " + progress.TotalFiles + ")";
if (progress.SearchResults != null)
{
inputData.SearchResults.AddRange(progress.SearchResults);
}
}
}
catch (Exception ex)
{
logger.LogException(LogLevel.Error, ex.Message, ex);
MessageBox.Show("Search or replace failed! See error log.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void searchComplete(object sender, RunWorkerCompletedEventArgs e)
{
try
{
if (inputData.CurrentGrepOperation == GrepOperation.Search || inputData.CurrentGrepOperation == GrepOperation.SearchInResults)
{
List<GrepSearchResult> results = new List<GrepSearchResult>();
if (e.Result == null)
{
lblStatus.Text = "Search Canceled or Failed";
}
else if (!e.Cancelled)
{
TimeSpan duration = DateTime.Now.Subtract(timer);
results = (List<GrepSearchResult>)e.Result;
lblStatus.Text = "Search Complete - " + results.Count + " files found in " + duration.TotalMilliseconds + "ms.";
}
else
{
lblStatus.Text = "Search Canceled";
}
barProgressBar.Value = 0;
if (inputData.SearchResults.Count > 0)
inputData.FilesFound = true;
if (!settings.Get<bool>(GrepSettings.Key.PreviewResults))
{
inputData.SearchResults.AddRange(results);
tvSearchResult.ItemsSource = inputData.SearchResults;
inputData.FilesFound = true;
}
inputData.CurrentGrepOperation = GrepOperation.None;
}
else if (inputData.CurrentGrepOperation == GrepOperation.Replace)
{
if (!e.Cancelled)
{
if (e.Result == null || ((int)e.Result) == -1)
{
lblStatus.Text = "Replace Failed.";
MessageBox.Show("Replace failed! See error log.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
else
{
lblStatus.Text = "Replace Complete - " + (int)e.Result + " files replaced.";
inputData.CanUndo = true;
}
}
else
{
lblStatus.Text = "Replace Canceled";
}
barProgressBar.Value = 0;
inputData.CurrentGrepOperation = GrepOperation.None;
inputData.SearchResults.Clear();
}
string outdatedEngines = dnGREP.Engines.GrepEngineFactory.GetListOfFailedEngines();
if (!string.IsNullOrEmpty(outdatedEngines))
{
MessageBox.Show("The following plugins failed to load:\n\n" + outdatedEngines + "\n\nDefault engine was used instead.", "Plugin Errors", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
catch (Exception ex)
{
logger.LogException(LogLevel.Error, ex.Message, ex);
MessageBox.Show("Search or replace failed! See error log.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
Utils.CancelSearch = false;
inputData.UpdateState("");
}
}
private void MainForm_Closing(object sender, CancelEventArgs e)
{
GrepCore.CancelProcess = true;
if (workerSearchReplace.IsBusy)
workerSearchReplace.CancelAsync();
settings.Set<double>(GrepSettings.Key.MainFormWidth, Width);
settings.Set<double>(GrepSettings.Key.MainFormHeight, Height);
copyBookmarksToSettings();
settings.Save();
}
private void copyBookmarksToSettings()
{
//Saving bookmarks
List<string> fsb = new List<string>();
for (int i = 0; i < inputData.FastSearchBookmarks.Count && i < MainFormState.FastBookmarkCapacity; i++)
{
fsb.Add(inputData.FastSearchBookmarks[i]);
}
settings.Set<List<string>>(GrepSettings.Key.FastSearchBookmarks, fsb);
List<string> frb = new List<string>();
for (int i = 0; i < inputData.FastReplaceBookmarks.Count && i < MainFormState.FastBookmarkCapacity; i++)
{
frb.Add(inputData.FastReplaceBookmarks[i]);
}
settings.Set<List<string>>(GrepSettings.Key.FastReplaceBookmarks, frb);
List<string> ffmb = new List<string>();
for (int i = 0; i < inputData.FastFileMatchBookmarks.Count && i < MainFormState.FastBookmarkCapacity; i++)
{
ffmb.Add(inputData.FastFileMatchBookmarks[i]);
}
settings.Set<List<string>>(GrepSettings.Key.FastFileMatchBookmarks, ffmb);
List<string> ffnmb = new List<string>();
for (int i = 0; i < inputData.FastFileNotMatchBookmarks.Count && i < MainFormState.FastBookmarkCapacity; i++)
{
ffnmb.Add(inputData.FastFileNotMatchBookmarks[i]);
}
settings.Set<List<string>>(GrepSettings.Key.FastFileNotMatchBookmarks, ffnmb);
List<string> fpb = new List<string>();
for (int i = 0; i < inputData.FastPathBookmarks.Count && i < MainFormState.FastBookmarkCapacity; i++)
{
fpb.Add(inputData.FastPathBookmarks[i]);
}
settings.Set<List<string>>(GrepSettings.Key.FastPathBookmarks, fpb);
}
private void formKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
Close();
}
private void undoToolStripMenuItem_Click(object sender, RoutedEventArgs e)
{
if (inputData.CanUndo)
{
MessageBoxResult response = MessageBox.Show("Undo will revert modified file(s) back to their original state. Any changes made to the file(s) after the replace will be overwritten. Are you sure you want to procede?",
"Undo", MessageBoxButton.YesNoCancel, MessageBoxImage.Warning, MessageBoxResult.Cancel);
if (response == MessageBoxResult.Yes)
{
GrepCore core = new GrepCore();
bool result = core.Undo(inputData.UndoFolder);
if (result)
{
MessageBox.Show("Files have been successfully reverted.", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
Utils.DeleteTempFolder();
}
else
{
MessageBox.Show("There was an error reverting files. Please examine the error log.", "Failure", MessageBoxButton.OK, MessageBoxImage.Error);
}
inputData.CanUndo = false;
}
}
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
//TODO
//AboutForm about = new AboutForm();
//about.ShowDialog();
}
private void helpToolStripMenuItem_Click(object sender, RoutedEventArgs e)
{
ApplicationCommands.Help.Execute(null, helpToolStripMenuItem);
}
private void aboutToolStripMenuItem_Click(object sender, RoutedEventArgs e)
{
AboutForm aboutForm = new AboutForm();
aboutForm.ShowDialog();
}
private void cbCaseSensitive_CheckedChanged(object sender, RoutedEventArgs e)
{
inputData.FilesFound = false;
}
private void btnOptions_Click(object sender, RoutedEventArgs e)
{
string fileOrFolderPath = inputData.FileOrFolderPath;
string searchFor = inputData.SearchFor;
string replaceWith = inputData.ReplaceWith;
string filePattern = inputData.FilePattern;
string filePatternIgnore = inputData.FilePatternIgnore;
copyBookmarksToSettings();
OptionsForm optionsForm = new OptionsForm();
try
{
optionsForm.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show("There was an error saving options.", "Failure", MessageBoxButton.OK, MessageBoxImage.Error);
logger.LogException(LogLevel.Error, "Error saving options", ex);
}
inputData.LoadAppSettings();
inputData.FileOrFolderPath = fileOrFolderPath;
inputData.SearchFor = searchFor;
inputData.ReplaceWith = replaceWith;
inputData.FilePattern = filePattern;
inputData.FilePatternIgnore = filePatternIgnore;
}
private void btnTest_Click(object sender, RoutedEventArgs e)
{
try
{
TestPattern testForm = new TestPattern();
testForm.ShowDialog();
inputData.LoadAppSettings();
}
catch (Exception ex)
{
MessageBox.Show("There was an error running regex test. Please examine the error log.", "Failure", MessageBoxButton.OK, MessageBoxImage.Error);
logger.LogException(LogLevel.Error, "Error running regex", ex);
}
}
private void btnBookmarkOpen_Click(object sender, RoutedEventArgs e)
{
try
{
bookmarkForm = new BookmarksForm();
bookmarkForm.PropertyChanged += new PropertyChangedEventHandler(bookmarkForm_PropertyChanged);
bookmarkForm.ShowDialog();
}
finally
{
bookmarkForm.PropertyChanged -= new PropertyChangedEventHandler(bookmarkForm_PropertyChanged);
}
}
private void btnBookmark_Click(object sender, RoutedEventArgs e)
{
BookmarkDetails bookmarkEditForm = new BookmarkDetails(CreateOrEdit.Create);
Bookmark newBookmark = new Bookmark(tbSearchFor.Text, tbReplaceWith.Text, tbFilePattern.Text, "");
bookmarkEditForm.Bookmark = newBookmark;
if (bookmarkEditForm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (!BookmarkLibrary.Instance.Bookmarks.Contains(newBookmark))
{
BookmarkLibrary.Instance.Bookmarks.Add(newBookmark);
BookmarkLibrary.Save();
}
}
}
#region Advance actions
private void copyFilesToolStripMenuItem_Click(object sender, RoutedEventArgs e)
{
if (inputData.FilesFound)
{
if (fileFolderDialog.ShowDialog() == true)
{
try
{
if (!Utils.CanCopyFiles(inputData.SearchResults.GetList(), Utils.GetBaseFolder(fileFolderDialog.SelectedPath)))
{
MessageBox.Show("Attention, some of the files are located in the selected directory.\nPlease select another directory and try again.", "Attention", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
Utils.CopyFiles(inputData.SearchResults.GetList(), Utils.GetBaseFolder(tbFolderName.Text), Utils.GetBaseFolder(fileFolderDialog.SelectedPath), true);
MessageBox.Show("Files have been successfully copied.", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (Exception ex)
{
MessageBox.Show("There was an error copying files. Please examine the error log.", "Failure", MessageBoxButton.OK, MessageBoxImage.Error);
logger.LogException(LogLevel.Error, "Error copying files", ex);
}
inputData.CanUndo = false;
}
}
}
private void copyToClipboardToolStripMenuItem_Click(object sender, RoutedEventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach (GrepSearchResult result in inputData.SearchResults.GetList())
{
sb.AppendLine(result.FileNameReal);
}
Clipboard.SetText(sb.ToString());
}
private void moveFilesToolStripMenuItem_Click(object sender, RoutedEventArgs e)
{
if (inputData.FilesFound)
{
if (fileFolderDialog.ShowDialog() == true)
{
try
{
if (!Utils.CanCopyFiles(inputData.SearchResults.GetList(), Utils.GetBaseFolder(fileFolderDialog.SelectedPath)))
{
MessageBox.Show("Attention, some of the files are located in the selected directory.\nPlease select another directory and try again.",
"Attention", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
Utils.CopyFiles(inputData.SearchResults.GetList(), Utils.GetBaseFolder(tbFolderName.Text), Utils.GetBaseFolder(fileFolderDialog.SelectedPath), true);
Utils.DeleteFiles(inputData.SearchResults.GetList());
MessageBox.Show("Files have been successfully moved.", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (Exception ex)
{
logger.LogException(LogLevel.Error, "Error moving files", ex);
MessageBox.Show("There was an error moving files. Please examine the error log.", "Failure", MessageBoxButton.OK, MessageBoxImage.Error);
}
inputData.CanUndo = false;
inputData.SearchResults.Clear();
inputData.FilesFound = false;
}
}
}
private void deleteFilesToolStripMenuItem_Click(object sender, RoutedEventArgs e)
{
if (inputData.FilesFound)
{
try
{
if (MessageBox.Show("Attention, you are about to delete files found during search.\nAre you sure you want to procede?", "Attention", MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) != MessageBoxResult.Yes)
{
return;
}
Utils.DeleteFiles(inputData.SearchResults.GetList());
MessageBox.Show("Files have been successfully deleted.", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (Exception ex)
{
MessageBox.Show("There was an error deleting files. Please examine the error log.", "Failure", MessageBoxButton.OK, MessageBoxImage.Error);
logger.LogException(LogLevel.Error, "Error deleting files", ex);
}
inputData.CanUndo = false;
inputData.SearchResults.Clear();
inputData.FilesFound = false;
}
}
private void saveAsCSVToolStripMenuItem_Click(object sender, RoutedEventArgs e)
{
if (inputData.FilesFound)
{
saveFileDialog.InitialDirectory = Utils.GetBaseFolder(inputData.FileOrFolderPath);
if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
try
{
Utils.SaveResultsAsCSV(inputData.SearchResults.GetList(), saveFileDialog.FileName);
MessageBox.Show("CSV file has been successfully created.", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (Exception ex)
{
MessageBox.Show("There was an error creating a CSV file. Please examine the error log.", "Failure", MessageBoxButton.OK, MessageBoxImage.Error);
logger.LogException(LogLevel.Error, "Error creating CSV file", ex);
}
}
}
}
private void btnOtherActions_Click(object sender, RoutedEventArgs e)
{
btnOtherActions.ContextMenu.IsOpen = true;
}
#endregion
private void tvSearchResult_MouseDown(object sender, MouseButtonEventArgs e)
{
TreeViewItem item = sender as TreeViewItem;
if (item != null)
{
item.Focus();
e.Handled = true;
}
}
private void tvSearchResult_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (tvSearchResult.SelectedItem is FormattedGrepLine &&
e.OriginalSource is TextBlock || e.OriginalSource is Run)
{
btnOpenFile_Click(sender, new RoutedEventArgs(e.RoutedEvent));
}
}
#region Tree right click events
private void tvContexMenuOpening(object sender, RoutedEventArgs e)
{
if (tvSearchResult.SelectedItem is FormattedGrepLine)
{
btnCopyTreeItemClipboard.Header = "Line of text to clipboard";
btnCopyFileNameClipboard.Visibility = Visibility.Collapsed;
}
else if (tvSearchResult.SelectedItem is FormattedGrepResult)
{
btnCopyTreeItemClipboard.Header = "Full file path to clipboard";
btnCopyFileNameClipboard.Visibility = Visibility.Visible;
}
}
private void btnOpenFile_Click(object sender, RoutedEventArgs e)
{
try
{
if (tvSearchResult.SelectedItem is FormattedGrepLine)
{
FormattedGrepLine selectedNode = (FormattedGrepLine)tvSearchResult.SelectedItem;
// Line was selected
int lineNumber = selectedNode.GrepLine.LineNumber;
FormattedGrepResult result = selectedNode.Parent;
OpenFileArgs fileArg = new OpenFileArgs(result.GrepResult, lineNumber, settings.Get<bool>(GrepSettings.Key.UseCustomEditor), settings.Get<string>(GrepSettings.Key.CustomEditor), settings.Get<string>(GrepSettings.Key.CustomEditorArgs));
dnGREP.Engines.GrepEngineFactory.GetSearchEngine(result.GrepResult.FileNameReal, new GrepEngineInitParams(false, 0, 0, 0.5)).OpenFile(fileArg);
if (fileArg.UseBaseEngine)
Utils.OpenFile(new OpenFileArgs(result.GrepResult, lineNumber, settings.Get<bool>(GrepSettings.Key.UseCustomEditor), settings.Get<string>(GrepSettings.Key.CustomEditor), settings.Get<string>(GrepSettings.Key.CustomEditorArgs)));
}
else if (tvSearchResult.SelectedItem is FormattedGrepResult)
{
FormattedGrepResult result = (FormattedGrepResult)tvSearchResult.SelectedItem;
// Line was selected
int lineNumber = 0;
OpenFileArgs fileArg = new OpenFileArgs(result.GrepResult, lineNumber, settings.Get<bool>(GrepSettings.Key.UseCustomEditor), settings.Get<string>(GrepSettings.Key.CustomEditor), settings.Get<string>(GrepSettings.Key.CustomEditorArgs));
dnGREP.Engines.GrepEngineFactory.GetSearchEngine(result.GrepResult.FileNameReal, new GrepEngineInitParams(false, 0, 0, 0.5)).OpenFile(fileArg);
if (fileArg.UseBaseEngine)
Utils.OpenFile(new OpenFileArgs(result.GrepResult, lineNumber, settings.Get<bool>(GrepSettings.Key.UseCustomEditor), settings.Get<string>(GrepSettings.Key.CustomEditor), settings.Get<string>(GrepSettings.Key.CustomEditorArgs)));
}
}
catch (Exception ex)
{
logger.LogException(LogLevel.Error, "Failed to open file.", ex);
if (settings.Get<bool>(GrepSettings.Key.UseCustomEditor))
MessageBox.Show("There was an error opening file by custom editor. \nCheck editor path via \"Options..\".", "Failure", MessageBoxButton.OK, MessageBoxImage.Error);
else
MessageBox.Show("There was an error opening file. Please examine the error log.", "Failure", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void btnOpenContainingFolder_Click(object sender, RoutedEventArgs e)
{
if (tvSearchResult.SelectedItem is FormattedGrepLine)
{
FormattedGrepLine selectedNode = (FormattedGrepLine)tvSearchResult.SelectedItem;
//ShellIntegration.OpenFolder(selectedNode.Parent.GrepResult.FileNameReal);
Utils.OpenContainingFolder(selectedNode.Parent.GrepResult.FileNameReal, selectedNode.GrepLine.LineNumber);
}
else if (tvSearchResult.SelectedItem is FormattedGrepResult)
{
FormattedGrepResult selectedNode = (FormattedGrepResult)tvSearchResult.SelectedItem;
//ShellIntegration.OpenFolder(selectedNode.GrepResult.FileNameReal);
Utils.OpenContainingFolder(selectedNode.GrepResult.FileNameReal, -1);
}
}
private void btnShowFileProperties_Click(object sender, RoutedEventArgs e)
{
string fileName = "";
if (tvSearchResult.SelectedItem is FormattedGrepLine)
{
FormattedGrepLine selectedNode = (FormattedGrepLine)tvSearchResult.SelectedItem;
fileName = selectedNode.Parent.GrepResult.FileNameReal;
}
else if (tvSearchResult.SelectedItem is FormattedGrepResult)
{
FormattedGrepResult selectedNode = (FormattedGrepResult)tvSearchResult.SelectedItem;
fileName = selectedNode.GrepResult.FileNameReal;
}
if (fileName != "" && File.Exists(fileName))
ShellIntegration.ShowFileProperties(fileName);
}
private void btnExpandAll_Click(object sender, RoutedEventArgs e)
{
foreach (FormattedGrepResult result in tvSearchResult.Items)
{
result.IsExpanded = true;
}
}
private void btnCollapseAll_Click(object sender, RoutedEventArgs e)
{
foreach (FormattedGrepResult result in tvSearchResult.Items)
{
result.IsExpanded = false;
}
}
private void btnExclude_Click(object sender, RoutedEventArgs e)
{
if (tvSearchResult.SelectedItem is FormattedGrepLine)
{
FormattedGrepLine selectedNode = (FormattedGrepLine)tvSearchResult.SelectedItem;
inputData.SearchResults.Remove(selectedNode.Parent);
}
else if (tvSearchResult.SelectedItem is FormattedGrepResult)
{
FormattedGrepResult selectedNode = (FormattedGrepResult)tvSearchResult.SelectedItem;
inputData.SearchResults.Remove(selectedNode);
}
}
private void copyToClipboard()
{
if (tvSearchResult.SelectedItem is FormattedGrepLine)
{
FormattedGrepLine selectedNode = (FormattedGrepLine)tvSearchResult.SelectedItem;
Clipboard.SetText(selectedNode.GrepLine.LineText);
}
else if (tvSearchResult.SelectedItem is FormattedGrepResult)
{
FormattedGrepResult result = (FormattedGrepResult)tvSearchResult.SelectedItem;
Clipboard.SetText(result.GrepResult.FileNameDisplayed);
}
}
private void treeKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.C && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{
copyToClipboard();
}
}
private void btnCopyTreeItemToClipboard_Click(object sender, RoutedEventArgs e)
{
copyToClipboard();
}
private void btnCopyNameToClipboard_Click(object sender, RoutedEventArgs e)
{
if (tvSearchResult.SelectedItem is FormattedGrepLine)
{
FormattedGrepLine selectedNode = (FormattedGrepLine)tvSearchResult.SelectedItem;
Clipboard.SetText(System.IO.Path.GetFileName(selectedNode.Parent.GrepResult.FileNameDisplayed));
}
else if (tvSearchResult.SelectedItem is FormattedGrepResult)
{
FormattedGrepResult result = (FormattedGrepResult)tvSearchResult.SelectedItem;
Clipboard.SetText(System.IO.Path.GetFileName(result.GrepResult.FileNameDisplayed));
}
}
#endregion
private void TextBoxFocus(object sender, RoutedEventArgs e)
{
if (e.Source is TextBox)
{
((TextBox)e.Source).SelectAll();
}
}
private void btnSearchFastBookmarks_Click(object sender, RoutedEventArgs e)
{
cbSearchFastBookmark.IsDropDownOpen = true;
}
private void btnReplaceFastBookmarks_Click(object sender, RoutedEventArgs e)
{
cbReplaceFastBookmark.IsDropDownOpen = true;
tbReplaceWith.SelectAll();
}
#region DragDropEvents
private static UIElement _draggedElt;
private static bool _isMouseDown = false;
private static Point _dragStartPoint;
private void tvSearchResult_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// Make this the new drag source
_draggedElt = e.Source as UIElement;
_dragStartPoint = e.GetPosition(getTopContainer());
_isMouseDown = true;
}
private void tvSearchResult_PreviewMouseMove(object sender, MouseEventArgs e)
{
if (_isMouseDown && isDragGesture(e.GetPosition(getTopContainer())))
{
treeDragStarted(sender as UIElement);
}
}
private void treeDragStarted(UIElement uiElt)
{
_isMouseDown = false;
Mouse.Capture(uiElt);
DataObject data = new DataObject();
if (tvSearchResult.SelectedItem is FormattedGrepLine)
{
FormattedGrepLine selectedNode = (FormattedGrepLine)tvSearchResult.SelectedItem;
data.SetData(DataFormats.Text, selectedNode.GrepLine.LineText);
}
else if (tvSearchResult.SelectedItem is FormattedGrepResult)
{
FormattedGrepResult result = (FormattedGrepResult)tvSearchResult.SelectedItem;
StringCollection files = new StringCollection();
files.Add(result.GrepResult.FileNameReal);
data.SetFileDropList(files);
}
DragDropEffects supportedEffects = DragDropEffects.Move | DragDropEffects.Copy;
// Perform DragDrop
DragDropEffects effects = System.Windows.DragDrop.DoDragDrop(_draggedElt, data, supportedEffects);
// Clean up
Mouse.Capture(null);
_draggedElt = null;
}
private bool isDragGesture(Point point)
{
bool hGesture = Math.Abs(point.X - _dragStartPoint.X) > SystemParameters.MinimumHorizontalDragDistance;
bool vGesture = Math.Abs(point.Y - _dragStartPoint.Y) > SystemParameters.MinimumVerticalDragDistance;
return (hGesture | vGesture);
}
private UIElement getTopContainer()
{
return Application.Current.MainWindow.Content as UIElement;
}
private void tbFolderName_DragOver(object sender, DragEventArgs e)
{
e.Effects = DragDropEffects.All;
e.Handled = true;
}
private void tbFolderName_Drop(object sender, DragEventArgs e)
{
if (e.Data is System.Windows.DataObject &&
((System.Windows.DataObject)e.Data).ContainsFileDropList())
{
inputData.FileOrFolderPath = "";
StringCollection fileNames = ((System.Windows.DataObject)e.Data).GetFileDropList();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < fileNames.Count; i++)
{
sb.Append(fileNames[i]);
if (i < (fileNames.Count - 1))
sb.Append(";");
}
inputData.FileOrFolderPath = sb.ToString();
}
}
#endregion
}
}
| zychen63-dngrep | dnGREP.WPF/MainForm.xaml.cs | C# | gpl3 | 44,751 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using dnGREP.Common;
using System.Collections.Specialized;
using System.Windows.Threading;
using System.Threading;
using System.ComponentModel;
using System.Windows.Media;
namespace dnGREP.WPF
{
public class TestPatternState : INotifyPropertyChanged
{
public TestPatternState()
{
LoadAppSettings();
UpdateState("Initial");
CanSearch = true;
CanReplace = true;
CanCancel = false;
CanSearchInResults = false;
SearchButtonMode = "Button";
}
public GrepSettings settings
{
get { return GrepSettings.Instance; }
}
public void LoadAppSettings()
{
SearchFor = settings.Get<string>(GrepSettings.Key.SearchFor);
ReplaceWith = settings.Get<string>(GrepSettings.Key.ReplaceWith);
TypeOfSearch = settings.Get<SearchType>(GrepSettings.Key.TypeOfSearch);
CaseSensitive = settings.Get<bool>(GrepSettings.Key.CaseSensitive);
Multiline = settings.Get<bool>(GrepSettings.Key.Multiline);
Singleline = settings.Get<bool>(GrepSettings.Key.Singleline);
WholeWord = settings.Get<bool>(GrepSettings.Key.WholeWord);
TextFormatting = settings.Get<TextFormattingMode>(GrepSettings.Key.TextFormatting);
}
private ObservableGrepSearchResults searchResults = new ObservableGrepSearchResults();
public ObservableGrepSearchResults SearchResults
{
get
{
return searchResults;
}
}
private string _SearchFor = "";
/// <summary>
/// SearchFor property
/// </summary>
public string SearchFor
{
get { return _SearchFor; }
set
{
_SearchFor = value;
settings.Set<string>(GrepSettings.Key.SearchFor, value);
UpdateState("SearchFor");
}
}
private string _ReplaceWith = "";
/// <summary>
/// ReplaceWith property
/// </summary>
public string ReplaceWith
{
get { return _ReplaceWith; }
set
{
_ReplaceWith = value;
settings.Set<string>(GrepSettings.Key.ReplaceWith, value);
UpdateState("ReplaceWith");
}
}
private SearchType _TypeOfSearch = SearchType.PlainText;
/// <summary>
/// TypeOfSearch property
/// </summary>
public SearchType TypeOfSearch
{
get { return _TypeOfSearch; }
set
{
_TypeOfSearch = value;
settings.Set<SearchType>(GrepSettings.Key.TypeOfSearch, value);
UpdateState("TypeOfSearch");
}
}
private bool _CaseSensitive = true;
/// <summary>
/// CaseSensitive property
/// </summary>
public bool CaseSensitive
{
get { return _CaseSensitive; }
set
{
_CaseSensitive = value;
settings.Set<bool>(GrepSettings.Key.CaseSensitive, value);
UpdateState("CaseSensitive");
}
}
private bool _IsCaseSensitiveEnabled = true;
/// <summary>
/// IsCaseSensitiveEnabled property
/// </summary>
public bool IsCaseSensitiveEnabled
{
get { return _IsCaseSensitiveEnabled; }
set
{
_IsCaseSensitiveEnabled = value;
UpdateState("IsCaseSensitiveEnabled");
}
}
private bool _Multiline = false;
/// <summary>
/// Multiline property
/// </summary>
public bool Multiline
{
get { return _Multiline; }
set
{
_Multiline = value;
settings.Set<bool>(GrepSettings.Key.Multiline, value);
UpdateState("Multiline");
}
}
private bool _IsMultilineEnabled = true;
/// <summary>
/// IsMultilineEnabled property
/// </summary>
public bool IsMultilineEnabled
{
get { return _IsMultilineEnabled; }
set
{
_IsMultilineEnabled = value;
UpdateState("IsMultilineEnabled");
}
}
private bool _Singleline = false;
/// <summary>
/// Singleline property
/// </summary>
public bool Singleline
{
get { return _Singleline; }
set
{
_Singleline = value;
settings.Set<bool>(GrepSettings.Key.Singleline, value);
UpdateState("Singleline");
}
}
private bool _IsSinglelineEnables = true;
/// <summary>
/// IsSinglelineEnables property
/// </summary>
public bool IsSinglelineEnabled
{
get { return _IsSinglelineEnables; }
set
{
_IsSinglelineEnables = value;
UpdateState("IsSinglelineEnabled");
}
}
private TextFormattingMode _TextFormatting = TextFormattingMode.Display;
/// <summary>
/// IsOptionsExpanded property
/// </summary>
public TextFormattingMode TextFormatting
{
get { return _TextFormatting; }
set
{
_TextFormatting = value;
settings.Set<TextFormattingMode>(GrepSettings.Key.TextFormatting, value);
UpdateState("TextFormatting");
}
}
private bool _WholeWord = false;
/// <summary>
/// WholeWord property
/// </summary>
public bool WholeWord
{
get { return _WholeWord; }
set
{
_WholeWord = value;
settings.Set<bool>(GrepSettings.Key.WholeWord, value);
UpdateState("WholeWord");
}
}
private bool _IsWholeWordEnabled = true;
/// <summary>
/// IsWholeWordEnabled property
/// </summary>
public bool IsWholeWordEnabled
{
get { return _IsWholeWordEnabled; }
set { _IsWholeWordEnabled = value; UpdateState("IsWholeWordEnabled"); }
}
#region Derived properties
private bool _CanSearch = true;
/// <summary>
/// CanSearch property
/// </summary>
public bool CanSearch
{
get { return _CanSearch; }
set { _CanSearch = value; UpdateState("CanSearch"); }
}
private bool _CanSearchInResults = true;
/// <summary>
/// CanSearchInResults property
/// </summary>
public bool CanSearchInResults
{
get { return _CanSearchInResults; }
set { _CanSearchInResults = value; UpdateState("CanSearchInResults"); }
}
private string _SearchButtonMode = "";
/// <summary>
/// SearchButtonMode property
/// </summary>
public string SearchButtonMode
{
get { return _SearchButtonMode; }
set { _SearchButtonMode = value; UpdateState("SearchButtonMode"); }
}
private bool _CanReplace = false;
/// <summary>
/// CanReplace property
/// </summary>
public bool CanReplace
{
get { return _CanReplace; }
set { _CanReplace = value; UpdateState("CanReplace"); }
}
private bool _CanCancel = false;
/// <summary>
/// CanCancel property
/// </summary>
public bool CanCancel
{
get { return _CanCancel; }
set { _CanCancel = value; UpdateState("CanCancel"); }
}
private GrepOperation _CurrentGrepOperation = GrepOperation.None;
/// <summary>
/// CurrentGrepOperation property
/// </summary>
public GrepOperation CurrentGrepOperation
{
get { return _CurrentGrepOperation; }
set { _CurrentGrepOperation = value; UpdateState("CurrentGrepOperation"); }
}
private string _OptionsSummary = "";
/// <summary>
/// OptionsSummary property
/// </summary>
public string OptionsSummary
{
get { return _OptionsSummary; }
set { _OptionsSummary = value; UpdateState("OptionsSummary"); }
}
private string _TextBoxStyle = "";
/// <summary>
/// TextBoxStyle property
/// </summary>
public string TextBoxStyle
{
get { return _TextBoxStyle; }
set { _TextBoxStyle = value; UpdateState("TextBoxStyle"); }
}
#endregion
public void UpdateState(string name)
{
OnPropertyChanged(name);
switch (name)
{
case "Initial":
case "Multiline":
case "Singleline":
case "WholeWord":
case "CaseSensitive":
List<string> tempList = new List<string>();
if (CaseSensitive)
tempList.Add("Case sensitive");
if (Multiline)
tempList.Add("Multiline");
if (WholeWord)
tempList.Add("Whole word");
if (Singleline)
tempList.Add("Match dot as new line");
OptionsSummary = "[";
if (tempList.Count == 0)
{
OptionsSummary += "None";
}
else
{
for (int i = 0; i < tempList.Count; i++)
{
OptionsSummary += tempList[i];
if (i < tempList.Count - 1)
OptionsSummary += ", ";
}
}
OptionsSummary += "]";
if (Multiline)
TextBoxStyle = "{StaticResource ExpandedTextbox}";
else
TextBoxStyle = "";
break;
}
//Search type specific options
//Search type specific options
if (name == "TypeOfSearch")
{
if (TypeOfSearch == SearchType.XPath)
{
IsCaseSensitiveEnabled = false;
IsMultilineEnabled = false;
IsSinglelineEnabled = false;
IsWholeWordEnabled = false;
CaseSensitive = false;
Multiline = false;
Singleline = false;
WholeWord = false;
}
else if (TypeOfSearch == SearchType.PlainText)
{
IsCaseSensitiveEnabled = true;
IsMultilineEnabled = true;
IsSinglelineEnabled = false;
IsWholeWordEnabled = true;
Singleline = false;
}
else if (TypeOfSearch == SearchType.Soundex)
{
IsMultilineEnabled = true;
IsCaseSensitiveEnabled = false;
IsSinglelineEnabled = false;
IsWholeWordEnabled = true;
CaseSensitive = false;
Singleline = false;
}
else if (TypeOfSearch == SearchType.Regex)
{
IsCaseSensitiveEnabled = true;
IsMultilineEnabled = true;
IsSinglelineEnabled = true;
IsWholeWordEnabled = true;
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
#endregion
}
}
| zychen63-dngrep | dnGREP.WPF/TestPattern.State.cs | C# | gpl3 | 10,018 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using dnGREP.Common;
using System.Collections.Specialized;
using System.Windows.Threading;
using System.Threading;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Windows.Media;
namespace dnGREP.WPF
{
public class MainFormState : INotifyPropertyChanged
{
public static int FastBookmarkCapacity = 20;
public MainFormState()
{
LoadAppSettings();
UpdateState("Initial");
}
public GrepSettings settings
{
get { return GrepSettings.Instance; }
}
public void LoadAppSettings()
{
List<string> fsb = settings.Get<List<string>>(GrepSettings.Key.FastSearchBookmarks);
string _searchFor = settings.Get<string>(GrepSettings.Key.SearchFor);
FastSearchBookmarks.Clear();
if (fsb != null)
{
foreach (string bookmark in fsb)
{
if (!FastSearchBookmarks.Contains(bookmark))
FastSearchBookmarks.Add(bookmark);
}
}
settings[GrepSettings.Key.SearchFor] = _searchFor;
string _replaceWith = settings.Get<string>(GrepSettings.Key.ReplaceWith);
FastReplaceBookmarks.Clear();
List<string> frb = settings.Get<List<string>>(GrepSettings.Key.FastReplaceBookmarks);
if (frb != null)
{
foreach (string bookmark in frb)
{
if (!FastReplaceBookmarks.Contains(bookmark))
FastReplaceBookmarks.Add(bookmark);
}
}
settings[GrepSettings.Key.ReplaceWith] = _replaceWith;
string _filePattern = settings.Get<string>(GrepSettings.Key.FilePattern);
FastFileMatchBookmarks.Clear();
List<string> ffmb = settings.Get<List<string>>(GrepSettings.Key.FastFileMatchBookmarks);
if (ffmb != null)
{
foreach (string bookmark in ffmb)
{
if (!FastFileMatchBookmarks.Contains(bookmark))
FastFileMatchBookmarks.Add(bookmark);
}
}
settings[GrepSettings.Key.FilePattern] = _filePattern;
string _filePatternIgnore = settings.Get<string>(GrepSettings.Key.FilePatternIgnore);
FastFileNotMatchBookmarks.Clear();
List<string> ffnmb = settings.Get<List<string>>(GrepSettings.Key.FastFileNotMatchBookmarks);
if (ffnmb != null)
{
foreach (string bookmark in ffnmb)
{
if (!FastFileNotMatchBookmarks.Contains(bookmark))
FastFileNotMatchBookmarks.Add(bookmark);
}
}
settings[GrepSettings.Key.FilePatternIgnore] = _filePatternIgnore;
string _fileOrFolderPath = settings.Get<string>(GrepSettings.Key.SearchFolder);
FastPathBookmarks.Clear();
List<string> pb = settings.Get<List<string>>(GrepSettings.Key.FastPathBookmarks);
if (pb != null)
{
foreach (string bookmark in pb)
{
if (!FastPathBookmarks.Contains(bookmark))
FastPathBookmarks.Add(bookmark);
}
}
settings[GrepSettings.Key.SearchFolder] = _fileOrFolderPath;
FileOrFolderPath = settings.Get<string>(GrepSettings.Key.SearchFolder);
SearchFor = settings.Get<string>(GrepSettings.Key.SearchFor);
ReplaceWith = settings.Get<string>(GrepSettings.Key.ReplaceWith);
IncludeHidden = settings.Get<bool>(GrepSettings.Key.IncludeHidden);
IncludeBinary = settings.Get<bool>(GrepSettings.Key.IncludeBinary);
IncludeSubfolder = settings.Get<bool>(GrepSettings.Key.IncludeSubfolder);
TypeOfSearch = settings.Get<SearchType>(GrepSettings.Key.TypeOfSearch);
TypeOfFileSearch = settings.Get<FileSearchType>(GrepSettings.Key.TypeOfFileSearch);
FilePattern = settings.Get<string>(GrepSettings.Key.FilePattern);
FilePatternIgnore = settings.Get<string>(GrepSettings.Key.FilePatternIgnore);
UseFileSizeFilter = settings.Get<FileSizeFilter>(GrepSettings.Key.UseFileSizeFilter);
CaseSensitive = settings.Get<bool>(GrepSettings.Key.CaseSensitive);
Multiline = settings.Get<bool>(GrepSettings.Key.Multiline);
Singleline = settings.Get<bool>(GrepSettings.Key.Singleline);
WholeWord = settings.Get<bool>(GrepSettings.Key.WholeWord);
SizeFrom = settings.Get<int>(GrepSettings.Key.SizeFrom);
SizeTo = settings.Get<int>(GrepSettings.Key.SizeTo);
TextFormatting = settings.Get<TextFormattingMode>(GrepSettings.Key.TextFormatting);
IsOptionsExpanded = settings.Get<bool>(GrepSettings.Key.IsOptionsExpanded);
}
private ObservableGrepSearchResults searchResults = new ObservableGrepSearchResults();
public ObservableGrepSearchResults SearchResults
{
get {
return searchResults;
}
}
private ObservableCollection<string> fastSearchBookmarks = new ObservableCollection<string>();
public ObservableCollection<string> FastSearchBookmarks
{
get { return fastSearchBookmarks; }
}
private ObservableCollection<string> fastReplaceBookmarks = new ObservableCollection<string>();
public ObservableCollection<string> FastReplaceBookmarks
{
get { return fastReplaceBookmarks; }
}
private ObservableCollection<string> fastFileMatchBookmarks = new ObservableCollection<string>();
public ObservableCollection<string> FastFileMatchBookmarks
{
get { return fastFileMatchBookmarks; }
}
private ObservableCollection<string> fastFileNotMatchBookmarks = new ObservableCollection<string>();
public ObservableCollection<string> FastFileNotMatchBookmarks
{
get { return fastFileNotMatchBookmarks; }
}
private ObservableCollection<string> fastPathBookmarks = new ObservableCollection<string>();
public ObservableCollection<string> FastPathBookmarks
{
get { return fastPathBookmarks; }
}
private string _FileOrFolderPath = "";
/// <summary>
/// FileOrFolderPath property
/// </summary>
public string FileOrFolderPath
{
get { return _FileOrFolderPath; }
set {
_FileOrFolderPath = value;
settings.Set<string>(GrepSettings.Key.SearchFolder, value);
UpdateState("FileOrFolderPath");
}
}
private string _SearchFor = "";
/// <summary>
/// SearchFor property
/// </summary>
public string SearchFor
{
get { return _SearchFor; }
set {
_SearchFor = value;
settings.Set<string>(GrepSettings.Key.SearchFor, value);
UpdateState("SearchFor");
}
}
private string _ReplaceWith = "";
/// <summary>
/// ReplaceWith property
/// </summary>
public string ReplaceWith
{
get { return _ReplaceWith; }
set {
_ReplaceWith = value;
settings.Set<string>(GrepSettings.Key.ReplaceWith, value);
UpdateState("ReplaceWith");
}
}
private bool _IsOptionsExpanded = false;
/// <summary>
/// IsOptionsExpanded property
/// </summary>
public bool IsOptionsExpanded
{
get { return _IsOptionsExpanded; }
set
{
_IsOptionsExpanded = value;
settings.Set<bool>(GrepSettings.Key.IsOptionsExpanded, value);
UpdateState("IsOptionsExpanded");
}
}
private TextFormattingMode _TextFormatting = TextFormattingMode.Display;
/// <summary>
/// IsOptionsExpanded property
/// </summary>
public TextFormattingMode TextFormatting
{
get { return _TextFormatting; }
set
{
_TextFormatting = value;
settings.Set<TextFormattingMode>(GrepSettings.Key.TextFormatting, value);
UpdateState("TextFormatting");
}
}
private string _FilePattern = "";
/// <summary>
/// FilePattern property
/// </summary>
public string FilePattern
{
get { return _FilePattern; }
set
{
_FilePattern = value;
settings.Set<string>(GrepSettings.Key.FilePattern, value);
UpdateState("FilePattern");
}
}
private string _FilePatternIgnore = "";
/// <summary>
/// FilePatternIgnore property
/// </summary>
public string FilePatternIgnore
{
get { return _FilePatternIgnore; }
set
{
_FilePatternIgnore = value;
settings.Set<string>(GrepSettings.Key.FilePatternIgnore, value);
UpdateState("FilePatternIgnore");
}
}
private bool _IncludeSubfolder = false;
/// <summary>
/// IncludeSubfolder property
/// </summary>
public bool IncludeSubfolder
{
get { return _IncludeSubfolder; }
set
{
_IncludeSubfolder = value;
settings.Set<bool>(GrepSettings.Key.IncludeSubfolder, value);
UpdateState("IncludeSubfolder");
}
}
private bool _IncludeHidden = false;
/// <summary>
/// IncludeHidden property
/// </summary>
public bool IncludeHidden
{
get { return _IncludeHidden; }
set
{
_IncludeHidden = value;
settings.Set<bool>(GrepSettings.Key.IncludeHidden, value);
UpdateState("IncludeHidden");
}
}
private bool _IncludeBinary = false;
/// <summary>
/// IncludeBinary property
/// </summary>
public bool IncludeBinary
{
get { return _IncludeBinary; }
set {
_IncludeBinary = value;
settings.Set<bool>(GrepSettings.Key.IncludeBinary, value);
UpdateState("IncludeBinary");
}
}
private SearchType _TypeOfSearch = SearchType.PlainText;
/// <summary>
/// TypeOfSearch property
/// </summary>
public SearchType TypeOfSearch
{
get { return _TypeOfSearch; }
set
{
_TypeOfSearch = value;
settings.Set<SearchType>(GrepSettings.Key.TypeOfSearch, value);
UpdateState("TypeOfSearch");
}
}
private FileSearchType _TypeOfFileSearch = FileSearchType.Asterisk;
/// <summary>
/// TypeOfFileSearch property
/// </summary>
public FileSearchType TypeOfFileSearch
{
get { return _TypeOfFileSearch; }
set
{
_TypeOfFileSearch = value;
settings.Set<FileSearchType>(GrepSettings.Key.TypeOfFileSearch, value);
UpdateState("TypeOfFileSearch");
}
}
private FileSizeFilter _UseFileSizeFilter = FileSizeFilter.No;
/// <summary>
/// UseFileSizeFilter property
/// </summary>
public FileSizeFilter UseFileSizeFilter
{
get { return _UseFileSizeFilter; }
set
{
_UseFileSizeFilter = value;
settings.Set<FileSizeFilter>(GrepSettings.Key.UseFileSizeFilter, value);
UpdateState("UseFileSizeFilter");
}
}
private int sizeFrom = 0;
/// <summary>
/// SizeFrom property
/// </summary>
public int SizeFrom
{
get { return sizeFrom; }
set {
sizeFrom = value;
settings.Set<int>(GrepSettings.Key.SizeFrom, value);
UpdateState("SizeFrom");
}
}
private int _SizeTo = 1000;
/// <summary>
/// SizeTo property
/// </summary>
public int SizeTo
{
get { return _SizeTo; }
set
{
_SizeTo = value;
settings.Set<int>(GrepSettings.Key.SizeTo, value);
UpdateState("SizeTo");
}
}
private bool _CaseSensitive = true;
/// <summary>
/// CaseSensitive property
/// </summary>
public bool CaseSensitive
{
get { return _CaseSensitive; }
set
{
_CaseSensitive = value;
settings.Set<bool>(GrepSettings.Key.CaseSensitive, value);
UpdateState("CaseSensitive");
}
}
private bool _IsCaseSensitiveEnabled = true;
/// <summary>
/// IsCaseSensitiveEnabled property
/// </summary>
public bool IsCaseSensitiveEnabled
{
get { return _IsCaseSensitiveEnabled; }
set
{
_IsCaseSensitiveEnabled = value;
UpdateState("IsCaseSensitiveEnabled");
}
}
private bool _Multiline = false;
/// <summary>
/// Multiline property
/// </summary>
public bool Multiline
{
get { return _Multiline; }
set
{
_Multiline = value;
settings.Set<bool>(GrepSettings.Key.Multiline, value);
UpdateState("Multiline");
}
}
private bool _IsMultilineEnabled = true;
/// <summary>
/// IsMultilineEnabled property
/// </summary>
public bool IsMultilineEnabled
{
get { return _IsMultilineEnabled; }
set
{
_IsMultilineEnabled = value;
UpdateState("IsMultilineEnabled");
}
}
private bool _Singleline = false;
/// <summary>
/// Singleline property
/// </summary>
public bool Singleline
{
get { return _Singleline; }
set
{
_Singleline = value;
settings.Set<bool>(GrepSettings.Key.Singleline, value);
UpdateState("Singleline");
}
}
private bool _IsSinglelineEnables = true;
/// <summary>
/// IsSinglelineEnables property
/// </summary>
public bool IsSinglelineEnabled
{
get { return _IsSinglelineEnables; }
set
{
_IsSinglelineEnables = value;
UpdateState("IsSinglelineEnabled");
}
}
private bool _WholeWord = false;
/// <summary>
/// WholeWord property
/// </summary>
public bool WholeWord
{
get { return _WholeWord; }
set
{
_WholeWord = value;
settings.Set<bool>(GrepSettings.Key.WholeWord, value);
UpdateState("WholeWord");
}
}
private bool _IsWholeWordEnabled = true;
/// <summary>
/// IsWholeWordEnabled property
/// </summary>
public bool IsWholeWordEnabled
{
get { return _IsWholeWordEnabled; }
set { _IsWholeWordEnabled = value; UpdateState("IsWholeWordEnabled"); }
}
#region Derived properties
private bool _IsSizeFilterSet = true;
/// <summary>
/// IsSizeFilterSet property
/// </summary>
public bool IsSizeFilterSet
{
get { return _IsSizeFilterSet; }
set { _IsSizeFilterSet = value; UpdateState("IsSizeFilterSet"); }
}
private bool filesFound = false;
public bool FilesFound
{
get { return filesFound; }
set { filesFound = value; UpdateState("FilesFound"); }
}
private bool _CanSearch = true;
/// <summary>
/// CanSearch property
/// </summary>
public bool CanSearch
{
get { return _CanSearch; }
set { _CanSearch = value; UpdateState("CanSearch"); }
}
private bool _CanSearchInResults = true;
/// <summary>
/// CanSearchInResults property
/// </summary>
public bool CanSearchInResults
{
get { return _CanSearchInResults; }
set { _CanSearchInResults = value; UpdateState("CanSearchInResults"); }
}
private string _SearchButtonMode = "";
/// <summary>
/// SearchButtonMode property
/// </summary>
public string SearchButtonMode
{
get { return _SearchButtonMode; }
set { _SearchButtonMode = value; UpdateState("SearchButtonMode"); }
}
private bool _CanReplace = false;
/// <summary>
/// CanReplace property
/// </summary>
public bool CanReplace
{
get { return _CanReplace; }
set { _CanReplace = value; UpdateState("CanReplace"); }
}
private bool _CanCancel = false;
/// <summary>
/// CanCancel property
/// </summary>
public bool CanCancel
{
get { return _CanCancel; }
set { _CanCancel = value; UpdateState("CanCancel"); }
}
private GrepOperation _CurrentGrepOperation = GrepOperation.None;
/// <summary>
/// CurrentGrepOperation property
/// </summary>
public GrepOperation CurrentGrepOperation
{
get { return _CurrentGrepOperation; }
set { _CurrentGrepOperation = value; UpdateState("CurrentGrepOperation"); }
}
private string _OptionsSummary = "";
/// <summary>
/// OptionsSummary property
/// </summary>
public string OptionsSummary
{
get { return _OptionsSummary; }
set { _OptionsSummary = value; UpdateState("OptionsSummary"); }
}
private string _WindowTitle = "dnGREP";
/// <summary>
/// OptionsSummary property
/// </summary>
public string WindowTitle
{
get { return _WindowTitle; }
set { _WindowTitle = value; UpdateState("WindowTitle"); }
}
private string _TextBoxStyle = "";
/// <summary>
/// TextBoxStyle property
/// </summary>
public string TextBoxStyle
{
get { return _TextBoxStyle; }
set { _TextBoxStyle = value; UpdateState("TextBoxStyle"); }
}
private int _CodePage = 0;
/// <summary>
/// CodePage property
/// </summary>
public int CodePage
{
get { return _CodePage; }
set { _CodePage = value; UpdateState("CodePage"); }
}
private bool _CanUndo = false;
/// <summary>
/// CanUndo property
/// </summary>
public bool CanUndo
{
get { return _CanUndo; }
set { _CanUndo = value; UpdateState("CanUndo"); }
}
private string _UndoFolder = "";
/// <summary>
/// UndoFolder property
/// </summary>
public string UndoFolder
{
get { return _UndoFolder; }
set { _UndoFolder = value; UpdateState("UndoFolder"); }
}
#endregion
public virtual void UpdateState(string name)
{
OnPropertyChanged(name);
switch (name)
{
case "UseFileSizeFilter":
if (UseFileSizeFilter == FileSizeFilter.Yes)
{
IsSizeFilterSet = true;
}
else
{
IsSizeFilterSet = false;
}
break;
case "Initial":
case "Multiline":
case "Singleline":
case "WholeWord":
case "CaseSensitive":
List<string> tempList = new List<string>();
if (CaseSensitive)
tempList.Add("Case sensitive");
if (Multiline)
tempList.Add("Multiline");
if (WholeWord)
tempList.Add("Whole word");
if (Singleline)
tempList.Add("Match dot as new line");
OptionsSummary = "[";
if (tempList.Count == 0)
{
OptionsSummary += "None";
}
else
{
for (int i = 0; i < tempList.Count; i++)
{
OptionsSummary += tempList[i];
if (i < tempList.Count - 1)
OptionsSummary += ", ";
}
}
OptionsSummary += "]";
if (Multiline)
TextBoxStyle = "{StaticResource ExpandedTextbox}";
else
TextBoxStyle = "";
break;
}
//Files found
if (name == "FileOrFolderPath" || name == "SearchFor" || name == "FilePattern" || name == "FilePatternIgnore")
{
FilesFound = false;
}
//Change title
if (name == "FileOrFolderPath" || name == "SearchFor")
{
if (string.IsNullOrWhiteSpace(FileOrFolderPath))
WindowTitle = "dnGREP";
else
WindowTitle = string.Format("{0} in \"{1}\" - dnGREP", SearchFor, FileOrFolderPath);
}
//Can search
if (name == "FileOrFolderPath" || name == "CurrentGrepOperation" || name == "SearchFor")
{
if (Utils.IsPathValid(FileOrFolderPath) && CurrentGrepOperation == GrepOperation.None &&
(!string.IsNullOrEmpty(SearchFor) || settings.Get<bool>(GrepSettings.Key.AllowSearchingForFileNamePattern)))
{
CanSearch = true;
}
else
{
CanSearch = false;
}
}
//btnSearch.ShowAdvance
if (name == "CurrentGrepOperation" || name == "Initial")
{
if (searchResults.Count > 0)
{
//TODO
CanSearchInResults = true;
SearchButtonMode = "Split";
}
else
{
//TODO
CanSearchInResults = false;
SearchButtonMode = "Button";
}
}
//searchResults
searchResults.FolderPath = FileOrFolderPath;
// btnReplace
if (name == "FileOrFolderPath" || name == "FilesFound" || name == "CurrentGrepOperation" || name == "SearchFor")
{
if (Utils.IsPathValid(FileOrFolderPath) && FilesFound && CurrentGrepOperation == GrepOperation.None &&
!string.IsNullOrEmpty(SearchFor))
{
CanReplace = true;
}
else
{
CanReplace = false;
}
}
//btnCancel
if (name == "CurrentGrepOperation")
{
if (CurrentGrepOperation != GrepOperation.None)
{
CanCancel = true;
}
else
{
CanCancel = false;
}
}
//Search type specific options
if (name == "TypeOfSearch")
{
if (TypeOfSearch == SearchType.XPath)
{
IsCaseSensitiveEnabled = false;
IsMultilineEnabled = false;
IsSinglelineEnabled = false;
IsWholeWordEnabled = false;
CaseSensitive = false;
Multiline = false;
Singleline = false;
WholeWord = false;
}
else if (TypeOfSearch == SearchType.PlainText)
{
IsCaseSensitiveEnabled = true;
IsMultilineEnabled = true;
IsSinglelineEnabled = false;
IsWholeWordEnabled = true;
Singleline = false;
}
else if (TypeOfSearch == SearchType.Soundex)
{
IsMultilineEnabled = true;
IsCaseSensitiveEnabled = false;
IsSinglelineEnabled = false;
IsWholeWordEnabled = true;
CaseSensitive = false;
Singleline = false;
}
else if (TypeOfSearch == SearchType.Regex)
{
IsCaseSensitiveEnabled = true;
IsMultilineEnabled = true;
IsSinglelineEnabled = true;
IsWholeWordEnabled = true;
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
#endregion
}
}
| zychen63-dngrep | dnGREP.WPF/MainForm.State.cs | C# | gpl3 | 21,507 |
using System.Windows;
using dnGREP.Common;
using NLog;
using System;
namespace dnGREP.WPF
{
public class dnGrepApp : Application
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public MainForm MainForm { get; private set; }
public dnGrepApp()
: base()
{
this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(dnGrepApp_DispatcherUnhandledException);
Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("Styles.xaml", UriKind.Relative) });
}
void dnGrepApp_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
logger.LogException(LogLevel.Error, e.Exception.Message, e.Exception);
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Utils.DeleteTempFolder();
MainForm = new MainForm();
ProcessArgs(e.Args, true);
}
public void ProcessArgs(string[] args, bool firstInstance)
{
//Process Command Line Arguments Here
if (!firstInstance || !(args != null && args.Length > 0 && args[0] == "/hidden"))
{
if (args != null && args.Length > 0)
{
string searchPath = args[0];
if (searchPath.EndsWith(":\""))
searchPath = searchPath.Substring(0, searchPath.Length - 1) + "\\";
GrepSettings.Instance.Set<string>(GrepSettings.Key.SearchFolder, searchPath);
MainForm.UpdateState();
}
MainForm.Show();
MainForm.Activate();
}
}
protected override void OnExit(ExitEventArgs e)
{
base.OnExit(e);
Utils.DeleteTempFolder();
}
}
}
| zychen63-dngrep | dnGREP.WPF/dnGrepApp.cs | C# | gpl3 | 2,059 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Documents;
using System.Windows;
using System.Windows.Controls;
namespace dnGREP.WPF
{
public class InlineTextBlock : TextBlock
{
public InlineCollection InlineCollection
{
get
{
return (InlineCollection)GetValue(InlineCollectionProperty);
}
set
{
SetValue(InlineCollectionProperty, value);
}
}
public static readonly DependencyProperty InlineCollectionProperty = DependencyProperty.Register(
"InlineCollection",
typeof(InlineCollection),
typeof(InlineTextBlock),
new UIPropertyMetadata((PropertyChangedCallback)((sender, args) =>
{
InlineTextBlock textBlock = sender as InlineTextBlock;
if (textBlock != null)
{
textBlock.Inlines.Clear();
InlineCollection inlines = args.NewValue as InlineCollection;
if (inlines != null)
textBlock.Inlines.AddRange(inlines.ToList());
}
})));
}
}
| zychen63-dngrep | dnGREP.WPF/InlineTextBlock.cs | C# | gpl3 | 1,047 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Reflection;
namespace dnGREP.WPF
{
partial class AboutForm : Form
{
public AboutForm()
{
InitializeComponent();
// Initialize the AboutBox to display the product information from the assembly information.
// Change assembly information settings for your application through either:
// - Project->Properties->Application->Assembly Information
// - AssemblyInfo.cs
this.Text = String.Format("About {0}", AssemblyTitle);
this.labelProductName.Text = AssemblyProduct;
this.labelVersion.Text = String.Format("Version {0}", AssemblyVersion);
this.labelCopyright.Text = AssemblyCopyright;
this.labelCompanyName.Text = AssemblyCompany;
this.textBoxDescription.Text = AssemblyDescription;
}
#region Assembly Attribute Accessors
public string AssemblyTitle
{
get
{
// Get all Title attributes on this assembly
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
// If there is at least one Title attribute
if (attributes.Length > 0)
{
// Select the first one
AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
// If it is not an empty string, return it
if (titleAttribute.Title != "")
return titleAttribute.Title;
}
// If there was no Title attribute, or if the Title attribute was the empty string, return the .exe name
return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
}
}
public string AssemblyVersion
{
get
{
return Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
public string AssemblyDescription
{
get
{
// Get all Description attributes on this assembly
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
// If there aren't any Description attributes, return an empty string
if (attributes.Length == 0)
return "";
// If there is a Description attribute, return its value
return ((AssemblyDescriptionAttribute)attributes[0]).Description;
}
}
public string AssemblyProduct
{
get
{
// Get all Product attributes on this assembly
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);
// If there aren't any Product attributes, return an empty string
if (attributes.Length == 0)
return "";
// If there is a Product attribute, return its value
return ((AssemblyProductAttribute)attributes[0]).Product;
}
}
public string AssemblyCopyright
{
get
{
// Get all Copyright attributes on this assembly
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
// If there aren't any Copyright attributes, return an empty string
if (attributes.Length == 0)
return "";
// If there is a Copyright attribute, return its value
return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
}
}
public string AssemblyCompany
{
get
{
// Get all Company attributes on this assembly
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
// If there aren't any Company attributes, return an empty string
if (attributes.Length == 0)
return "";
// If there is a Company attribute, return its value
return ((AssemblyCompanyAttribute)attributes[0]).Company;
}
}
#endregion
}
}
| zychen63-dngrep | dnGREP.WPF/AboutForm.cs | C# | gpl3 | 3,832 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.Specialized;
namespace dnGREP.WPF
{
/// <summary>
/// Interaction logic for Test.xaml
/// </summary>
public partial class Test : Window
{
public Test()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
cbHistory.IsDropDownOpen = true;
}
private void cbHistory_MouseDown(object sender, MouseButtonEventArgs e)
{
textBox1.Text = sender.GetType().ToString();
}
private static UIElement _draggedElt;
private static bool _isMouseDown = false;
private static Point _dragStartPoint;
private void DragSource_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// Make this the new drag source
_draggedElt = e.Source as UIElement;
_dragStartPoint = e.GetPosition(GetTopContainer());
_isMouseDown = true;
}
private void DragSource_PreviewMouseMove(object sender, MouseEventArgs e)
{
if (_isMouseDown && IsDragGesture(e.GetPosition(GetTopContainer())))
{
DragStarted(sender as UIElement);
}
}
static void DragStarted(UIElement uiElt)
{
_isMouseDown = false;
Mouse.Capture(uiElt);
DataObject data = new DataObject();
//obj.SetData(DataFormats.Text, "Text from WPF - CrossApp example");
StringCollection files = new StringCollection();
files.Add(@"C:\Documents and Settings\528046\Desktop\crystal_project\readme.txt");
data.SetFileDropList(files);
DragDropEffects supportedEffects = DragDropEffects.Move | DragDropEffects.Copy;
// Perform DragDrop
DragDropEffects effects = System.Windows.DragDrop.DoDragDrop(_draggedElt, data, supportedEffects);
// Clean up
Mouse.Capture(null);
_draggedElt = null;
}
static bool IsDragGesture(Point point)
{
bool hGesture = Math.Abs(point.X - _dragStartPoint.X) > SystemParameters.MinimumHorizontalDragDistance;
bool vGesture = Math.Abs(point.Y - _dragStartPoint.Y) > SystemParameters.MinimumVerticalDragDistance;
return (hGesture | vGesture);
}
static UIElement GetTopContainer()
{
return Application.Current.MainWindow.Content as UIElement;
}
}
}
| zychen63-dngrep | dnGREP.WPF/Test.xaml.cs | C# | gpl3 | 2,522 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
namespace dnGREP.WPF
{
class ShellIntegration
{
public static void ShowFileProperties(string filename)
{
SHELLEXECUTEINFO info = new SHELLEXECUTEINFO();
info.Size = System.Runtime.InteropServices.Marshal.SizeOf(info);
info.Verb = "properties";
info.File = filename;
info.Show = SW_SHOW;
info.Mask = SEE_MASK_INVOKEIDLIST;
ShellExecuteEx(ref info);
}
//public static void OpenFolder(string filename)
//{
// SHELLEXECUTEINFO info = new SHELLEXECUTEINFO();
// info.Size = System.Runtime.InteropServices.Marshal.SizeOf(info);
// info.Verb = "explore";
// info.File = filename;
// info.Show = SW_SHOWNORMAL;
// info.Class = "folder";
// info.Mask = SEE_MASK_IDLIST | SEE_MASK_CLASSNAME;
// ShellExecuteEx(ref info);
//}
private const int SW_SHOW = 5;
private const int SW_SHOWNORMAL = 1;
private const uint SEE_MASK_INVOKEIDLIST = 12;
private const uint SEE_MASK_IDLIST = 4;
private const uint SEE_MASK_CLASSNAME = 1;
[DllImport("shell32.dll")]
public static extern bool ShellExecuteEx(ref SHELLEXECUTEINFO lpExecInfo);
[Serializable]
public struct SHELLEXECUTEINFO
{
public int Size;
public uint Mask;
public IntPtr hwnd;
public string Verb;
public string File;
public string Parameters;
public string Directory;
public uint Show;
public IntPtr InstApp;
public IntPtr IDList;
public string Class;
public IntPtr hkeyClass;
public uint HotKey;
public IntPtr Icon;
public IntPtr Monitor;
}
}
}
| zychen63-dngrep | dnGREP.WPF/ShellIntegration.cs | C# | gpl3 | 1,743 |
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
namespace dnGREP.WPF
{
/// <summary>
/// Source: http://social.msdn.microsoft.com/forums/en-US/wpf/thread/a7a1dfa3-29b2-48bf-a7bb-586879232f0e
/// </summary>
public static class DiginesisHelpProvider
{
#region Fields
private static string mHelpNamespace = null;
private static bool mShowHelp = false;
private static string mNotFoundTopic;
public static readonly DependencyProperty HelpStringProperty =
DependencyProperty.RegisterAttached("HelpString", typeof(string), typeof(DiginesisHelpProvider));
public static readonly DependencyProperty HelpKeywordProperty =
DependencyProperty.RegisterAttached("HelpKeyword", typeof(string), typeof(DiginesisHelpProvider));
public static readonly DependencyProperty HelpNavigatorProperty =
DependencyProperty.RegisterAttached("HelpNavigator", typeof(HelpNavigator), typeof(DiginesisHelpProvider),
new PropertyMetadata(HelpNavigator.TableOfContents));
public static readonly DependencyProperty ShowHelpProperty =
DependencyProperty.RegisterAttached("ShowHelp", typeof(bool), typeof(DiginesisHelpProvider));
#endregion
#region Constructors
static DiginesisHelpProvider()
{
CommandManager.RegisterClassCommandBinding(
typeof(FrameworkElement),
new CommandBinding(ApplicationCommands.Help, OnHelpExecuted, OnHelpCanExecute));
}
#endregion
#region Public Properties
public static string HelpNamespace
{
get { return mHelpNamespace; }
set { mHelpNamespace = value; }
}
public static bool ShowHelp
{
get { return mShowHelp; }
set { mShowHelp = value; }
}
public static string NotFoundTopic
{
get { return mNotFoundTopic; }
set { mNotFoundTopic = value; }
}
#endregion
#region Public Methods
#region HelpString
public static string GetHelpString(DependencyObject obj)
{
return (string)obj.GetValue(HelpStringProperty);
}
public static void SetHelpString(DependencyObject obj, string value)
{
obj.SetValue(HelpStringProperty, value);
}
#endregion
#region HelpKeyword
public static string GetHelpKeyword(DependencyObject obj)
{
return (string)obj.GetValue(HelpKeywordProperty);
}
public static void SetHelpKeyword(DependencyObject obj, string value)
{
obj.SetValue(HelpKeywordProperty, value);
}
#endregion
#region HelpNavigator
public static HelpNavigator GetHelpNavigator(DependencyObject obj)
{
return (HelpNavigator)obj.GetValue(HelpNavigatorProperty);
}
public static void SetHelpNavigator(DependencyObject obj, HelpNavigator value)
{
obj.SetValue(HelpNavigatorProperty, value);
}
#endregion
#region ShowHelp
public static bool GetShowHelp(DependencyObject obj)
{
return (bool)obj.GetValue(ShowHelpProperty);
}
public static void SetShowHelp(DependencyObject obj, bool value)
{
obj.SetValue(ShowHelpProperty, value);
}
#endregion
#endregion
#region Private Members
private static void OnHelpCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = CanExecuteHelp((DependencyObject)sender) || ShowHelp;
}
private static bool CanExecuteHelp(DependencyObject sender)
{
if (sender != null)
{
if (GetShowHelp(sender))
return true;
return CanExecuteHelp(VisualTreeHelper.GetParent(sender));
}
return false;
}
private static DependencyObject GetHelp(DependencyObject sender)
{
if (sender != null)
{
if (GetShowHelp(sender))
return sender;
return GetHelp(VisualTreeHelper.GetParent(sender));
}
return null;
}
private static void OnHelpExecuted(object sender, ExecutedRoutedEventArgs e)
{
DependencyObject ctl = GetHelp(sender as DependencyObject);
if (ctl != null && GetShowHelp(ctl))
{
string caption = GetHelpString(ctl);
string parameter = GetHelpKeyword(ctl);
HelpNavigator command = GetHelpNavigator(ctl);
if (Control.MouseButtons != MouseButtons.None && !string.IsNullOrEmpty(caption))
{
Point point = Mouse.GetPosition(Mouse.DirectlyOver);
Help.ShowPopup(null, caption, Control.MousePosition);
e.Handled = true;
}
if (!e.Handled && !string.IsNullOrEmpty(HelpNamespace))
{
if (!string.IsNullOrEmpty(parameter))
{
Help.ShowHelp(null, HelpNamespace, command, parameter);
e.Handled = true;
}
if (!e.Handled)
{
Help.ShowHelp(null, HelpNamespace, command);
e.Handled = true;
}
}
if (!e.Handled && !string.IsNullOrEmpty(caption))
{
Point point = Mouse.GetPosition(Mouse.DirectlyOver);
Help.ShowPopup(null, caption, new System.Drawing.Point((int)point.X, (int)point.Y));
e.Handled = true;
}
if (!e.Handled && !string.IsNullOrEmpty(HelpNamespace))
{
Help.ShowHelp(null, HelpNamespace);
e.Handled = true;
}
}
else if (ShowHelp)
{
if (!string.IsNullOrEmpty(NotFoundTopic))
Help.ShowHelp(null, HelpNamespace, NotFoundTopic);
else
Help.ShowHelp(null, HelpNamespace);
e.Handled = true;
}
}
#endregion
}
} | zychen63-dngrep | dnGREP.WPF/HelpProvider.cs | C# | gpl3 | 6,938 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using dnGREP.Common;
using System.Windows.Documents;
using System.Windows.Media;
using System.IO;
using System.Collections.Specialized;
using System.Windows.Media.Imaging;
using System.Windows;
using System.Runtime.InteropServices;
using System.ComponentModel;
using dnGREP.Common.UI;
namespace dnGREP.WPF
{
public class ObservableGrepSearchResults : ObservableCollection<FormattedGrepResult>
{
private string folderPath = "";
public string FolderPath
{
get { return folderPath; }
set { folderPath = value; }
}
public ObservableGrepSearchResults()
{
this.CollectionChanged += new NotifyCollectionChangedEventHandler(ObservableGrepSearchResults_CollectionChanged);
}
//protected override void ClearItems()
//{
// base.ClearItems();
// OnFunctionCalled("Clear");
//}
private Dictionary<string, BitmapSource> icons = new Dictionary<string, BitmapSource>();
void ObservableGrepSearchResults_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (FormattedGrepResult newEntry in e.NewItems.Cast<FormattedGrepResult>())
{
string extension = Path.GetExtension(newEntry.GrepResult.FileNameDisplayed);
if (extension.Length <= 1)
extension = ".na";
if (!icons.ContainsKey(extension))
{
System.Drawing.Bitmap bitmapIcon = IconHandler.IconFromExtensionShell(extension, IconSize.Small);
if (bitmapIcon == null)
bitmapIcon = dnGREP.Common.Properties.Resources.na_icon;
icons[extension] = GetBitmapSource(bitmapIcon);
}
newEntry.Icon = icons[extension];
}
}
}
public ObservableGrepSearchResults(List<GrepSearchResult> list) : this()
{
AddRange(list);
}
public List<GrepSearchResult> GetList()
{
List<GrepSearchResult> tempList = new List<GrepSearchResult>();
foreach (var l in this) tempList.Add(l.GrepResult);
return tempList;
}
public void AddRange(List<GrepSearchResult> list)
{
foreach (var l in list) this.Add(new FormattedGrepResult(l, folderPath));
}
[DllImport("gdi32.dll")]
static extern bool DeleteObject(IntPtr hObject);
public static BitmapSource GetBitmapSource(System.Drawing.Bitmap source)
{
IntPtr ip = source.GetHbitmap();
try
{
BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip,
IntPtr.Zero, Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
return bs;
}
finally
{
DeleteObject(ip);
}
}
//#region PropertyChanged Members
//// Create the OnPropertyChanged method to raise the event
//protected void OnFunctionCalled(string name)
//{
// FunctionCallEventHandler handler = FunctionCalled;
// if (handler != null)
// {
// handler(this, new PropertyChangedEventArgs(name));
// }
//}
//public event FunctionCallEventHandler FunctionCalled;
//public delegate void FunctionCallEventHandler(object sender, PropertyChangedEventArgs e);
//#endregion
}
public class FormattedGrepResult : INotifyPropertyChanged
{
private GrepSearchResult grepResult = new GrepSearchResult();
public GrepSearchResult GrepResult
{
get { return grepResult; }
}
private string style = "";
public string Style
{
get { return style; }
set { style = value; }
}
private string label = "";
public string Label
{
get
{
return label;
}
}
private bool isExpanded = false;
public bool IsExpanded
{
get { return isExpanded; }
set { isExpanded = value; OnPropertyChanged("IsExpanded"); }
}
private int lineNumberColumnWidth = 30;
public int LineNumberColumnWidth
{
get { return lineNumberColumnWidth; }
set { lineNumberColumnWidth = value; OnPropertyChanged("LineNumberColumnWidth"); }
}
private BitmapSource icon;
public BitmapSource Icon
{
get { return icon; }
set { icon = value; }
}
private List<FormattedGrepLine> formattedLines = new List<FormattedGrepLine>();
public List<FormattedGrepLine> FormattedLines
{
get { return formattedLines; }
}
public FormattedGrepResult(GrepSearchResult result, string folderPath)
{
grepResult = result;
if (GrepSettings.Instance.Get<bool>(GrepSettings.Key.ExpandResults))
{
IsExpanded = true;
}
bool isFileReadOnly = Utils.IsReadOnly(grepResult);
string displayedName = Path.GetFileName(grepResult.FileNameDisplayed);
if (GrepSettings.Instance.Get<bool>(GrepSettings.Key.ShowFilePathInResults) &&
grepResult.FileNameDisplayed.Contains(Utils.GetBaseFolder(folderPath) + "\\"))
{
displayedName = grepResult.FileNameDisplayed.Substring(Utils.GetBaseFolder(folderPath).Length + 1);
}
int lineCount = Utils.MatchCount(grepResult);
if (lineCount > 0)
displayedName = string.Format("{0} ({1})", displayedName, lineCount);
if (isFileReadOnly)
{
result.ReadOnly = true;
displayedName = displayedName + " [read-only]";
}
label = displayedName;
if (isFileReadOnly)
{
style = "ReadOnly";
}
if (result.SearchResults != null)
{
int currentLine = -1;
for (int i = 0; i < result.SearchResults.Count; i++)
{
GrepSearchResult.GrepLine line = result.SearchResults[i];
// Adding separator
if (formattedLines.Count > 0 && GrepSettings.Instance.Get<bool>(GrepSettings.Key.ShowLinesInContext) &&
(currentLine != line.LineNumber && currentLine + 1 != line.LineNumber))
{
GrepSearchResult.GrepLine emptyLine = new GrepSearchResult.GrepLine(-1, "", true, null);
formattedLines.Add(new FormattedGrepLine(emptyLine, this, 30));
}
currentLine = line.LineNumber;
if (currentLine <= 999 && LineNumberColumnWidth < 30)
LineNumberColumnWidth = 30;
else if (currentLine > 999 && LineNumberColumnWidth < 35)
LineNumberColumnWidth = 35;
else if (currentLine > 9999 && LineNumberColumnWidth < 47)
LineNumberColumnWidth = 47;
else if (currentLine > 99999 && LineNumberColumnWidth < 50)
LineNumberColumnWidth = 50;
formattedLines.Add(new FormattedGrepLine(line, this, LineNumberColumnWidth));
}
}
}
#region PropertyChanged Members
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
public class FormattedGrepLine : INotifyPropertyChanged
{
private GrepSearchResult.GrepLine grepLine;
public GrepSearchResult.GrepLine GrepLine
{
get { return grepLine; }
}
private string formattedLineNumber;
public string FormattedLineNumber
{
get { return formattedLineNumber; }
}
private InlineCollection formattedText;
public InlineCollection FormattedText
{
get { return formattedText; }
}
private string style = "";
public string Style
{
get { return style; }
set { style = value; }
}
private int lineNumberColumnWidth = 30;
public int LineNumberColumnWidth
{
get { return lineNumberColumnWidth; }
set { lineNumberColumnWidth = value; OnPropertyChanged("LineNumberColumnWidth"); }
}
void Parent_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "LineNumberColumnWidth")
LineNumberColumnWidth = Parent.LineNumberColumnWidth;
}
private FormattedGrepResult parent;
public FormattedGrepResult Parent
{
get { return parent; }
set { parent = value; }
}
public FormattedGrepLine(GrepSearchResult.GrepLine line, FormattedGrepResult parent, int initialColumnWidth)
{
Parent = parent;
grepLine = line;
Parent.PropertyChanged += new PropertyChangedEventHandler(Parent_PropertyChanged);
LineNumberColumnWidth = initialColumnWidth;
formattedLineNumber = (line.LineNumber == -1 ? "" : line.LineNumber.ToString());
//string fullText = lineSummary;
if (line.IsContext)
{
style = "Context";
}
if (line.LineNumber == -1 && line.LineText == "")
{
style = "Empty";
}
formattedText = formatLine(line);
}
private InlineCollection formatLine(GrepSearchResult.GrepLine line)
{
Paragraph paragraph = new Paragraph();
if (line.Matches.Count == 0)
{
Run mainRun = new Run(line.LineText);
paragraph.Inlines.Add(mainRun);
}
else
{
int counter = 0;
string fullLine = line.LineText;
GrepSearchResult.GrepMatch[] lineMatches = new GrepSearchResult.GrepMatch[line.Matches.Count];
line.Matches.CopyTo(lineMatches);
foreach (GrepSearchResult.GrepMatch m in lineMatches)
{
string regLine = fullLine.Substring(counter, m.StartLocation - counter);
string fmtLine = fullLine.Substring(m.StartLocation, m.Length);
Run regularRun = new Run(regLine);
paragraph.Inlines.Add(regularRun);
Run highlightedRun = new Run(fmtLine);
highlightedRun.Background = Brushes.Yellow;
paragraph.Inlines.Add(highlightedRun);
counter = m.StartLocation + m.Length;
}
if (counter < fullLine.Length)
{
string regLine = fullLine.Substring(counter);
Run regularRun = new Run(regLine);
paragraph.Inlines.Add(regularRun);
}
}
return paragraph.Inlines;
}
#region PropertyChanged Members
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
}
| zychen63-dngrep | dnGREP.WPF/ObservableGrepSearchResults.cs | C# | gpl3 | 11,629 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using dnGREP.Common;
using dnGREP.Engines;
using NLog;
using System.IO;
using System.Reflection;
using System.Collections.ObjectModel;
namespace dnGREP.WPF
{
/// <summary>
/// Interaction logic for TestPattern.xaml
/// </summary>
public partial class TestPattern : Window
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private TestPatternState inputData = new TestPatternState();
public TestPattern()
{
InitializeComponent();
this.DataContext = inputData;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
inputData.UpdateState("");
}
private void formKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
Close();
}
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
GrepEnginePlainText engine = new GrepEnginePlainText();
engine.Initialize(new GrepEngineInitParams(false, 0, 0, GrepSettings.Instance.Get<int>(GrepSettings.Key.FuzzyMatchThreshold)));
List<GrepSearchResult> results = new List<GrepSearchResult>();
GrepSearchOption searchOptions = GrepSearchOption.None;
if (inputData.Multiline)
searchOptions |= GrepSearchOption.Multiline;
if (inputData.CaseSensitive)
searchOptions |= GrepSearchOption.CaseSensitive;
if (inputData.Singleline)
searchOptions |= GrepSearchOption.SingleLine;
if (inputData.WholeWord)
searchOptions |= GrepSearchOption.WholeWord;
using (Stream inputStream = new MemoryStream(Encoding.Default.GetBytes(tbTestInput.Text)))
{
try
{
results = engine.Search(inputStream, "test.txt", inputData.SearchFor, inputData.TypeOfSearch,
searchOptions, Encoding.Default);
}
catch (ArgumentException ex)
{
MessageBox.Show("Incorrect pattern: " + ex.Message, "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
inputData.SearchResults.Clear();
inputData.SearchResults.AddRange(results);
tbTestOutput.Text = "";
if (inputData.SearchResults.Count == 1)
{
foreach (FormattedGrepLine line in inputData.SearchResults[0].FormattedLines)
{
// Copy children Inline to a temporary array.
Inline[] inlines = new Inline[line.FormattedText.Count];
line.FormattedText.CopyTo(inlines, 0);
foreach (Inline inline in inlines)
{
tbTestOutput.Inlines.Add(inline);
}
tbTestOutput.Inlines.Add(new LineBreak());
tbTestOutput.Inlines.Add(new Run("================================="));
tbTestOutput.Inlines.Add(new LineBreak());
}
}
else
{
tbTestOutput.Text = "No matches found";
}
}
private void btnReplace_Click(object sender, RoutedEventArgs e)
{
GrepEnginePlainText engine = new GrepEnginePlainText();
engine.Initialize(new GrepEngineInitParams(false, 0, 0, 0.5));
List<GrepSearchResult> results = new List<GrepSearchResult>();
GrepSearchOption searchOptions = GrepSearchOption.None;
if (inputData.Multiline)
searchOptions |= GrepSearchOption.Multiline;
if (inputData.CaseSensitive)
searchOptions |= GrepSearchOption.CaseSensitive;
if (inputData.Singleline)
searchOptions |= GrepSearchOption.SingleLine;
if (inputData.WholeWord)
searchOptions |= GrepSearchOption.WholeWord;
string replacedString = "";
using (Stream inputStream = new MemoryStream(Encoding.Default.GetBytes(tbTestInput.Text)))
using (Stream writeStream = new MemoryStream())
{
engine.Replace(inputStream, writeStream, inputData.SearchFor, inputData.ReplaceWith, inputData.TypeOfSearch,
searchOptions, Encoding.Default);
writeStream.Position = 0;
StreamReader reader = new StreamReader(writeStream);
replacedString = reader.ReadToEnd();
}
inputData.SearchResults.Clear();
inputData.SearchResults.AddRange(results);
tbTestOutput.Text = replacedString;
}
private void Window_Closing(object sender, CancelEventArgs e)
{
GrepSettings.Instance.Save();
}
private void btnClose_Click(object sender, RoutedEventArgs e)
{
Close();
}
}
}
| zychen63-dngrep | dnGREP.WPF/TestPattern.xaml.cs | C# | gpl3 | 5,432 |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("dnGREP")]
[assembly: AssemblyDescription("This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Denis Stankovski")]
[assembly: AssemblyProduct("dnGREP")]
[assembly: AssemblyCopyright("Copyright, 2010")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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("2.5.0.0")]
[assembly: AssemblyFileVersion("2.5.0.0")]
| zychen63-dngrep | dnGREP.WPF/Properties/AssemblyInfo.cs | C# | gpl3 | 2,528 |
using System;
using System.Linq;
using Microsoft.VisualBasic.ApplicationServices;
namespace dnGREP.WPF
{
public class Launcher : WindowsFormsApplicationBase
{
[STAThread]
public static void Main(string[] args)
{
(new Launcher()).Run(args);
}
public Launcher()
{
IsSingleInstance = true;
}
public dnGrepApp App { get; private set; }
protected override bool OnStartup(StartupEventArgs e)
{
App = new dnGrepApp();
App.Run();
return false;
}
protected override void OnStartupNextInstance(
StartupNextInstanceEventArgs eventArgs)
{
base.OnStartupNextInstance(eventArgs);
App.ProcessArgs(eventArgs.CommandLine.ToArray(), false);
}
}
}
| zychen63-dngrep | dnGREP.WPF/Launcher.cs | C# | gpl3 | 895 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Security.Principal;
using System.Windows.Forms;
using Microsoft.Win32;
using dnGREP.Common;
using System.Reflection;
namespace dnGREP.WPF
{
/// <summary>
/// Interaction logic for OptionsForm.xaml
/// </summary>
public partial class OptionsForm : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public OptionsForm()
{
InitializeComponent();
oldShellUnregister();
openFileDialog.Title = "Path to custom editor...";
DiginesisHelpProvider.HelpNamespace = "Doc\\dnGREP.chm";
DiginesisHelpProvider.ShowHelp = true;
}
public GrepSettings settings
{
get { return GrepSettings.Instance; }
}
private System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
private static string SHELL_KEY_NAME = "dnGREP";
private static string OLD_SHELL_KEY_NAME = "nGREP";
private static string SHELL_MENU_TEXT = "dnGREP...";
private bool isAdministrator = true;
public bool IsAdministrator
{
get { return isAdministrator; }
set { isAdministrator = value; UpdateState("IsAdministrator"); }
}
private void UpdateState(string name)
{
if (!isAdministrator)
{
cbRegisterShell.IsEnabled = false;
cbRegisterShell.ToolTip = "To set shell integration run dnGREP as Administrator.";
grShell.ToolTip = "To set shell integration run dnGREP as Administrator.";
}
else
{
cbRegisterShell.IsEnabled = true;
cbRegisterShell.ToolTip = "Shell integration enables running an application from shell context menu.";
grShell.ToolTip = "Shell integration enables running an application from shell context menu.";
}
if (settings.Get<bool>(GrepSettings.Key.EnableUpdateChecking))
{
tbUpdateInterval.IsEnabled = true;
}
else
{
tbUpdateInterval.IsEnabled = false;
}
if (settings.Get<bool>(GrepSettings.Key.ShowLinesInContext))
{
tbLinesAfter.IsEnabled = true;
tbLinesBefore.IsEnabled = true;
}
else
{
tbLinesAfter.IsEnabled = false;
tbLinesBefore.IsEnabled = false;
}
if (settings.Get<bool>(GrepSettings.Key.UseCustomEditor))
{
rbSpecificEditor.IsChecked = true;
rbDefaultEditor.IsChecked = false;
tbEditorPath.IsEnabled = true;
btnBrowse.IsEnabled = true;
tbEditorArgs.IsEnabled = true;
}
else
{
rbSpecificEditor.IsChecked = false;
rbDefaultEditor.IsChecked = true;
tbEditorPath.IsEnabled = false;
btnBrowse.IsEnabled = false;
tbEditorArgs.IsEnabled = false;
}
if (name == "TextFormatting" || name == "Initial")
{
TextOptions.SetTextFormattingMode(this, settings.Get<TextFormattingMode>(GrepSettings.Key.TextFormatting));
}
}
private bool isShellRegistered(string location)
{
if (!isAdministrator)
return false;
string regPath = string.Format(@"{0}\shell\{1}",
location, SHELL_KEY_NAME);
try
{
return Registry.ClassesRoot.OpenSubKey(regPath) != null;
}
catch (UnauthorizedAccessException ex)
{
isAdministrator = false;
return false;
}
}
private void shellRegister(string location)
{
if (!isAdministrator)
return;
if (!isShellRegistered(location))
{
string regPath = string.Format(@"{0}\shell\{1}", location, SHELL_KEY_NAME);
// add context menu to the registry
using (RegistryKey key =
Registry.ClassesRoot.CreateSubKey(regPath))
{
key.SetValue(null, SHELL_MENU_TEXT);
}
// add command that is invoked to the registry
string menuCommand = string.Format("\"{0}\" \"%1\"",
Assembly.GetAssembly(typeof(OptionsForm)).Location);
using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(
string.Format(@"{0}\command", regPath)))
{
key.SetValue(null, menuCommand);
}
}
}
private void shellUnregister(string location)
{
if (!isAdministrator)
return;
if (isShellRegistered(location))
{
string regPath = string.Format(@"{0}\shell\{1}", location, SHELL_KEY_NAME);
Registry.ClassesRoot.DeleteSubKeyTree(regPath);
}
}
private void oldShellUnregister()
{
if (!isAdministrator)
return;
string regPath = string.Format(@"Directory\shell\{0}", OLD_SHELL_KEY_NAME);
if (Registry.ClassesRoot.OpenSubKey(regPath) != null)
{
Registry.ClassesRoot.DeleteSubKeyTree(regPath);
}
}
private void checkIfAdmin()
{
try
{
WindowsIdentity wi = WindowsIdentity.GetCurrent();
WindowsPrincipal wp = new WindowsPrincipal(wi);
if (wp.IsInRole("Administrators"))
{
isAdministrator = true;
}
else
{
isAdministrator = false;
}
}
catch (Exception ex)
{
isAdministrator = false;
}
}
private void Window_Load(object sender, RoutedEventArgs e)
{
checkIfAdmin();
cbRegisterShell.IsChecked = isShellRegistered("Directory");
cbCheckForUpdates.IsChecked = settings.Get<bool>(GrepSettings.Key.EnableUpdateChecking);
cbShowPath.IsChecked = settings.Get<bool>(GrepSettings.Key.ShowFilePathInResults);
cbShowContext.IsChecked = settings.Get<bool>(GrepSettings.Key.ShowLinesInContext);
tbLinesBefore.Text = settings.Get<int>(GrepSettings.Key.ContextLinesBefore).ToString();
tbLinesAfter.Text = settings.Get<int>(GrepSettings.Key.ContextLinesAfter).ToString();
cbSearchFileNameOnly.IsChecked = settings.Get<bool>(GrepSettings.Key.AllowSearchingForFileNamePattern);
tbEditorPath.Text = settings.Get<string>(GrepSettings.Key.CustomEditor);
tbEditorArgs.Text = settings.Get<string>(GrepSettings.Key.CustomEditorArgs);
cbPreviewResults.IsChecked = settings.Get<bool>(GrepSettings.Key.PreviewResults);
cbExpandResult.IsChecked = settings.Get<bool>(GrepSettings.Key.ExpandResults);
cbClearType.IsChecked = settings.Get<TextFormattingMode>(GrepSettings.Key.TextFormatting) == TextFormattingMode.Ideal;
tbUpdateInterval.Text = settings.Get<int>(GrepSettings.Key.UpdateCheckInterval).ToString();
tbFuzzyMatchThreshold.Text = settings.Get<double>(GrepSettings.Key.FuzzyMatchThreshold).ToString();
UpdateState("Initial");
}
private void cbRegisterShell_CheckedChanged(object sender, RoutedEventArgs e)
{
if (cbRegisterShell.IsChecked == true)
{
shellRegister("Directory");
shellRegister("Drive");
shellRegister("*");
}
else if (!cbRegisterShell.IsChecked == true)
{
shellUnregister("Directory");
shellUnregister("Drive");
shellUnregister("*");
}
}
private void rbEditorCheckedChanged(object sender, RoutedEventArgs e)
{
if (rbDefaultEditor.IsChecked == true)
settings.Set<bool>(GrepSettings.Key.UseCustomEditor, false);
else
settings.Set<bool>(GrepSettings.Key.UseCustomEditor, true);
UpdateState("UseCustomEditor");
}
private void cbClearType_Checked(object sender, RoutedEventArgs e)
{
if (cbClearType.IsChecked == true)
settings.Set<TextFormattingMode>(GrepSettings.Key.TextFormatting, TextFormattingMode.Ideal);
else
settings.Set<TextFormattingMode>(GrepSettings.Key.TextFormatting, TextFormattingMode.Display);
UpdateState("TextFormatting");
}
private void Window_Closing(object sender, CancelEventArgs e)
{
settings.Set<int>(GrepSettings.Key.ContextLinesBefore, Utils.ParseInt(tbLinesBefore.Text, 0));
settings.Set<int>(GrepSettings.Key.ContextLinesAfter, Utils.ParseInt(tbLinesAfter.Text, 0));
settings.Set<bool>(GrepSettings.Key.AllowSearchingForFileNamePattern, cbSearchFileNameOnly.IsChecked == true);
settings.Set<string>(GrepSettings.Key.CustomEditor, tbEditorPath.Text);
settings.Set<string>(GrepSettings.Key.CustomEditorArgs, tbEditorArgs.Text);
settings.Set<bool>(GrepSettings.Key.PreviewResults, cbPreviewResults.IsChecked == true);
settings.Set<bool>(GrepSettings.Key.ExpandResults, cbExpandResult.IsChecked == true);
settings.Set<int>(GrepSettings.Key.UpdateCheckInterval, Utils.ParseInt(tbUpdateInterval.Text, 1));
double threshold = Utils.ParseDouble(tbFuzzyMatchThreshold.Text, 0.5);
if (threshold >= 0 && threshold <= 1.0)
settings.Set<double>(GrepSettings.Key.FuzzyMatchThreshold, threshold);
settings.Save();
}
public static string GetEditorPath(string file, int line)
{
if (!GrepSettings.Instance.Get<bool>(GrepSettings.Key.UseCustomEditor))
{
return file;
}
else
{
if (!string.IsNullOrEmpty(GrepSettings.Instance.Get<string>(GrepSettings.Key.CustomEditor)))
{
string path = GrepSettings.Instance.Get<string>(GrepSettings.Key.CustomEditor).Replace("%file", "\"" + file + "\"").Replace("%line", line.ToString());
return path;
}
else
{
return file;
}
}
}
private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == Key.Escape)
Close();
}
private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
tbEditorPath.Text = openFileDialog.FileName;
}
}
private void cbCheckForUpdates_CheckedChanged(object sender, RoutedEventArgs e)
{
settings.Set<bool>(GrepSettings.Key.EnableUpdateChecking, cbCheckForUpdates.IsChecked == true);
if (tbUpdateInterval.Text.Trim() == "")
tbUpdateInterval.Text = "1";
UpdateState("EnableUpdateChecking");
}
private void cbShowPath_CheckedChanged(object sender, RoutedEventArgs e)
{
settings.Set<bool>(GrepSettings.Key.ShowFilePathInResults, cbShowPath.IsChecked == true);
}
private void cbShowContext_CheckedChanged(object sender, RoutedEventArgs e)
{
settings.Set<bool>(GrepSettings.Key.ShowLinesInContext, cbShowContext.IsChecked == true);
UpdateState("ShowLinesInContext");
}
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void tbFuzzyMatchThreshold_TextChanged(object sender, TextChangedEventArgs e)
{
if (Utils.ParseDouble(tbFuzzyMatchThreshold.Text) < 0 ||
Utils.ParseDouble(tbFuzzyMatchThreshold.Text) > 1.0)
{
lblFuzzyMatchError.Visibility = Visibility.Visible;
}
else
{
lblFuzzyMatchError.Visibility = Visibility.Collapsed;
}
}
private void btnClearPreviousSearches_Click(object sender, RoutedEventArgs e)
{
settings.Set<List<string>>(GrepSettings.Key.FastFileMatchBookmarks, new List<string>());
settings.Set<List<string>>(GrepSettings.Key.FastFileNotMatchBookmarks, new List<string>());
settings.Set<List<string>>(GrepSettings.Key.FastPathBookmarks, new List<string>());
settings.Set<List<string>>(GrepSettings.Key.FastReplaceBookmarks, new List<string>());
settings.Set<List<string>>(GrepSettings.Key.FastSearchBookmarks, new List<string>());
}
}
}
| zychen63-dngrep | dnGREP.WPF/OptionsForm.xaml.cs | C# | gpl3 | 13,902 |
using System;
using System.Collections.Generic;
using System.Text;
using MbUnit.Framework;
using System.Reflection;
using System.IO;
namespace Tests
{
public class TestBase
{
public string GetDllPath()
{
Assembly thisAssembly = Assembly.GetAssembly(typeof(TestBase));
return Path.GetDirectoryName(thisAssembly.Location);
}
}
}
| zychen63-dngrep | Tests/TestBase.cs | C# | gpl3 | 364 |
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("Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("BAH")]
[assembly: AssemblyProduct("Tests")]
[assembly: AssemblyCopyright("Copyright © BAH 2008")]
[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("24f8f663-60bb-4639-9b08-3940f26c404c")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| zychen63-dngrep | Tests/Properties/AssemblyInfo.cs | C# | gpl3 | 1,387 |
public void TestGetLine(string body, string line, int index, int lineNumber)
{
int returnedLineNumber = -1;
string returnedLine = Utils.GetLine(body, index, out returnedLineNumber);
Assert.AreEqual(returnedLine, line);
Assert.AreEqual(returnedLineNumber, lineNumber);
} | zychen63-dngrep | Tests/Files/TestCase3/test-file-code.cs | C# | gpl3 | 279 |
public void TestGetLine(string body, string line, int index, int lineNumber)
{
int returnedLineNumber = -1;
string returnedLine = Utils.GetLine(body, index, out returnedLineNumber);
Assert.AreEqual(returnedLine, line);
Assert.AreEqual(returnedLineNumber, lineNumber);
} | zychen63-dngrep | Tests/Files/TestCase1/test-file-code.cs | C# | gpl3 | 279 |
public void TestGetLine(string body, string line, int index, int lineNumber)
{
int returnedLineNumber = -1;
string returnedLine = Utils.GetLine(body, index, out returnedLineNumber);
Assert.AreEqual(returnedLine, line);
Assert.AreEqual(returnedLineNumber, lineNumber);
} | zychen63-dngrep | Tests/Files/TestCase2/test-file-code.cs | C# | gpl3 | 279 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using dnGREP.Common;
namespace dnGREP.Common.UI
{
public partial class BookmarkDetails : Form
{
private CreateOrEdit action = CreateOrEdit.Edit;
private Bookmark bookmark = null;
public Bookmark Bookmark
{
get { return bookmark; }
set { bookmark = value; changeState(); }
}
private void changeState()
{
if (action == CreateOrEdit.Create)
{
btnCreateOrEdit.Text = "Create";
}
else
{
btnCreateOrEdit.Text = "Edit";
}
if (bookmark != null)
{
tbDescription.Text = bookmark.Description;
tbFileNames.Text = bookmark.FileNames;
tbReplaceWith.Text = bookmark.ReplacePattern;
tbSearchFor.Text = bookmark.SearchPattern;
}
}
public BookmarkDetails(CreateOrEdit action)
{
InitializeComponent();
this.action = action;
}
private void BookmarkDetails_Load(object sender, EventArgs e)
{
changeState();
}
private void btnCreateOrEdit_Click(object sender, EventArgs e)
{
if (bookmark == null)
bookmark = new Bookmark();
bookmark.Description = tbDescription.Text;
bookmark.FileNames = tbFileNames.Text;
bookmark.SearchPattern = tbSearchFor.Text;
bookmark.ReplacePattern = tbReplaceWith.Text;
DialogResult = DialogResult.OK;
Close();
}
private void formKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
Close();
}
}
public enum CreateOrEdit
{
Create,
Edit
}
} | zychen63-dngrep | dnGREP.Common.UI/BookmarkDetails.cs | C# | gpl3 | 1,660 |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Reflection;
using System.IO;
using System.Drawing.Imaging;
using NLog;
namespace dnGREP.Common.UI
{
public class FileIcons
{
private static ImageList smallIconList = new ImageList();
private static Logger logger = LogManager.GetCurrentClassLogger();
public static ImageList SmallIconList
{
get { return smallIconList; }
}
public static void LoadImageList(string[] extensions)
{
try
{
smallIconList.ImageSize = new Size(16, 16);
smallIconList.ColorDepth = ColorDepth.Depth32Bit;
foreach (string extension in extensions)
{
if (!FileIcons.SmallIconList.Images.ContainsKey(extension))
{
Bitmap smallIcon = IconHandler.IconFromExtension(extension, IconSize.Small);
if (smallIcon == null)
smallIcon = Properties.Resources.na_icon;
FileIcons.SmallIconList.Images.Add(extension, smallIcon);
}
}
smallIconList.Images.Add("%line%", Properties.Resources.line_icon);
}
catch (Exception ex)
{
// DO NOTHING
}
}
public static void StoreIcon(string extension, string path)
{
StoreIcon(extension, path, getMimeType(Path.GetExtension(path)));
}
public static void StoreIcon(string extension, string path, string mimeType)
{
if (!File.Exists(path))
{
try
{
if (!Directory.Exists(Path.GetDirectoryName(path)))
Directory.CreateDirectory(Path.GetDirectoryName(path));
Bitmap image = IconHandler.IconFromExtension(extension, IconSize.Small);
System.Drawing.Imaging.Encoder qualityEncoder = System.Drawing.Imaging.Encoder.Quality;
long quality = 100;
EncoderParameter ratio = new EncoderParameter(qualityEncoder, quality);
EncoderParameters codecParams = new EncoderParameters(1);
codecParams.Param[0] = ratio;
ImageCodecInfo mimeCodecInfo = null;
foreach (ImageCodecInfo codecInfo in ImageCodecInfo.GetImageEncoders())
{
if (codecInfo.MimeType == mimeType)
{
mimeCodecInfo = codecInfo;
break;
}
}
if (mimeCodecInfo != null)
image.Save(path, mimeCodecInfo, codecParams); // Save to JPG
}
catch (Exception ex)
{
logger.LogException(LogLevel.Error, "Failed to create icon", ex);
}
}
}
private static string getMimeType(string sExtension)
{
string extension = sExtension.ToLower();
RegistryKey key = Registry.ClassesRoot.OpenSubKey("MIME\\Database\\Content Type");
foreach (string keyName in key.GetSubKeyNames())
{
RegistryKey temp = key.OpenSubKey(keyName);
if (extension.Equals(temp.GetValue("Extension")))
{
return keyName;
}
}
return "";
}
}
struct SHFILEINFO
{
public IntPtr hIcon;
public IntPtr iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};
public enum IconSize : uint
{
Large = 0x0, //32x32
Small = 0x1 //16x16
}
//the function that will extract the icons from a file
public class IconHandler
{
const uint SHGFI_ICON = 0x100;
const uint SHGFI_USEFILEATTRIBUTES = 0x10;
[DllImport("Shell32", CharSet = CharSet.Auto)]
internal extern static int ExtractIconEx(
[MarshalAs(UnmanagedType.LPTStr)]
string lpszFile, //size of the icon
int nIconIndex, //index of the icon
// (in case we have more
// then 1 icon in the file
IntPtr[] phIconLarge, //32x32 icon
IntPtr[] phIconSmall, //16x16 icon
int nIcons); //how many to get
[DllImport("shell32.dll")]
static extern IntPtr SHGetFileInfo(
string pszPath, //path
uint dwFileAttributes, //attributes
ref SHFILEINFO psfi, //struct pointer
uint cbSizeFileInfo, //size
uint uFlags); //flags
[DllImport("User32.dll")]
private static extern int
DestroyIcon(System.IntPtr hIcon);
// free up the icon pointers.
//will return an array of icons
public static Icon[] IconsFromFile(string Filename, IconSize Size)
{
int IconCount = ExtractIconEx(Filename, -1,
null, null, 0); //checks how many icons.
IntPtr[] IconPtr = new IntPtr[IconCount];
//extracts the icons by the size that was selected.
if (Size == IconSize.Small)
ExtractIconEx(Filename, 0, null, IconPtr, IconCount);
else
ExtractIconEx(Filename, 0, IconPtr, null, IconCount);
Icon[] IconList = new Icon[IconCount];
//gets the icons in a list.
for (int i = 0; i < IconCount; i++)
{
IconList[i] = (Icon)Icon.FromHandle(IconPtr[i]).Clone();
DestroyIcon(IconPtr[i]);
}
return IconList;
}
//extract one selected by index icon from a file.
public static Icon IconFromFile(string Filename, IconSize Size, int Index)
{
int IconCount = ExtractIconEx(Filename, -1,
null, null, 0); //checks how many icons.
if (IconCount < Index) return null; // no icons was found.
IntPtr[] IconPtr = new IntPtr[1];
//extracts the icon that we want in the selected size.
if (Size == IconSize.Small)
ExtractIconEx(Filename, Index, null, IconPtr, 1);
else
ExtractIconEx(Filename, Index, IconPtr, null, 1);
return GetManagedIcon(IconPtr[0]);
}
//this will look throw the registry to find if the Extension have an icon.
public static Bitmap IconFromExtension(string Extension, IconSize Size)
{
try
{
//add '.' if nessesry
if (Extension[0] != '.') Extension = '.' + Extension;
//opens the registry for the wanted key.
RegistryKey Root = Registry.ClassesRoot;
RegistryKey ExtensionKey = Root.OpenSubKey(Extension);
ExtensionKey.GetValueNames();
RegistryKey ApplicationKey =
Root.OpenSubKey(ExtensionKey.GetValue("").ToString());
//gets the name of the file that have the icon.
string IconLocation =
ApplicationKey.OpenSubKey("DefaultIcon").GetValue("").ToString();
string[] IconPath = IconLocation.Split(',');
if (IconPath[1] == null) IconPath[1] = "0";
IntPtr[] Large = new IntPtr[1], Small = new IntPtr[1];
//extracts the icon from the file.
ExtractIconEx(IconPath[0],
Convert.ToInt16(IconPath[1]), Large, Small, 1);
return GetManagedIcon(Size == IconSize.Large ? Large[0] : Small[0]).ToBitmap();
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("error while" +
" trying to get icon for " +
Extension + " :" + e.Message);
return null;
}
}
public static Bitmap IconFromExtensionShell(string Extension, IconSize Size)
{
try
{
//add '.' if nessesry
if (Extension[0] != '.') Extension = '.' + Extension;
//temp struct for getting file shell info
SHFILEINFO TempFileInfo = new SHFILEINFO();
SHGetFileInfo(
Extension,
0,
ref TempFileInfo,
(uint)Marshal.SizeOf(TempFileInfo),
SHGFI_ICON | SHGFI_USEFILEATTRIBUTES | (uint)Size);
return GetManagedIcon(TempFileInfo.hIcon).ToBitmap();
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("error while" +
" trying to get icon for " + Extension +
" :" + e.Message);
return null;
}
}
public static Icon IconFromResource(string ResourceName)
{
Assembly TempAssembly = Assembly.GetCallingAssembly();
return new Icon(TempAssembly.GetManifestResourceStream(ResourceName));
}
public static void SaveIconFromImage(Image SourceImage,
string IconFilename, IconSize DestenationIconSize)
{
Size NewIconSize = DestenationIconSize ==
IconSize.Large ? new Size(32, 32) : new Size(16, 16);
Bitmap RawImage = new Bitmap(SourceImage, NewIconSize);
Icon TempIcon = Icon.FromHandle(RawImage.GetHicon());
FileStream NewIconStream = new FileStream(IconFilename,
FileMode.Create);
TempIcon.Save(NewIconStream);
NewIconStream.Close();
}
private static Icon GetManagedIcon(IntPtr hIcon)
{
Icon Clone = (Icon)Icon.FromHandle(hIcon).Clone();
DestroyIcon(hIcon);
return Clone;
}
}
}
| zychen63-dngrep | dnGREP.Common.UI/FileIcons.cs | C# | gpl3 | 9,176 |
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;
using Microsoft.Win32;
namespace dnGREP.Common.UI
{
public class FileFolderDialogWin32 : CommonDialog
{
private OpenFileDialog dialog = new OpenFileDialog();
public OpenFileDialog Dialog
{
get { return dialog; }
set { dialog = value; }
}
public override bool? ShowDialog()
{
return this.ShowDialog(null);
}
public new bool? ShowDialog(System.Windows.Window owner)
{
// Set validate names to false otherwise windows will not let you select "Folder Selection."
dialog.ValidateNames = false;
dialog.CheckFileExists = false;
dialog.CheckPathExists = true;
try
{
// Set initial directory (used when dialog.FileName is set from outside)
if (dialog.FileName != null && dialog.FileName != "")
{
if (Directory.Exists(dialog.FileName))
dialog.InitialDirectory = dialog.FileName;
else
dialog.InitialDirectory = Utils.GetBaseFolder(dialog.FileName);
}
}
catch (Exception ex)
{
// Do nothing
}
// Always default to Folder Selection.
dialog.FileName = "Folder Selection.";
if (owner == null)
return dialog.ShowDialog();
else
return dialog.ShowDialog(owner);
}
/// <summary>
// Helper property. Parses FilePath into either folder path (if Folder Selection. is set)
// or returns file path
/// </summary>
public string SelectedPath
{
get {
try
{
if (dialog.FileName != null &&
(dialog.FileName.EndsWith("Folder Selection.") || !File.Exists(dialog.FileName)) &&
!Directory.Exists(dialog.FileName))
{
return Path.GetDirectoryName(dialog.FileName);
}
else
{
return dialog.FileName;
}
}
catch (Exception ex)
{
return dialog.FileName;
}
}
set
{
if (value != null && value != "")
{
dialog.FileName = value;
}
}
}
/// <summary>
/// When multiple files are selected returns them as semi-colon seprated string
/// </summary>
public string SelectedPaths
{
get {
if (dialog.FileNames != null && dialog.FileNames.Length > 1)
{
StringBuilder sb = new StringBuilder();
foreach (string fileName in dialog.FileNames)
{
try
{
if (File.Exists(fileName))
sb.Append(fileName + ";");
}
catch (Exception ex)
{
// Go to next
}
}
return sb.ToString();
}
else
{
return null;
}
}
}
public override void Reset()
{
dialog.Reset();
}
protected override bool RunDialog(IntPtr hwndOwner)
{
return true;
}
}
}
| zychen63-dngrep | dnGREP.Common.UI/FileFolderDialog.Win32.cs | C# | gpl3 | 2,864 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using dnGREP.Common;
namespace dnGREP.Common.UI
{
public partial class BookmarksForm : Form, INotifyPropertyChanged
{
DataTable copyOfBookmarks = new DataTable();
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
private string filePattern = "";
public string FilePattern
{
get { return filePattern; }
set { filePattern = value; OnPropertyChanged("FilePattern"); }
}
private string searchFor = "";
public string SearchFor
{
get { return searchFor; }
set { searchFor = value; OnPropertyChanged("SearchFor"); }
}
private string replaceWith = "";
public string ReplaceWith
{
get { return replaceWith; }
set { replaceWith = value; OnPropertyChanged("ReplaceWith"); }
}
private void changeState()
{
if (gridBookmarks.SelectedRows.Count == 1)
{
btnEdit.Enabled = true;
btnDelete.Enabled = true;
}
else
{
btnEdit.Enabled = false;
btnDelete.Enabled = false;
}
}
private void refreshGrid()
{
copyOfBookmarks = BookmarkLibrary.Instance.GetDataTable();
gridBookmarks.DataSource = copyOfBookmarks;
gridBookmarks.Refresh();
}
public BookmarksForm()
{
InitializeComponent();
}
private void BookmarksForm_Load(object sender, EventArgs e)
{
refreshGrid();
changeState();
}
private void BookmarksForm_FormClosing(object sender, FormClosingEventArgs e)
{
BookmarkLibrary.Save();
}
private void textSearch_TextChanged(object sender, EventArgs e)
{
typeTimer.Stop();
typeTimer.Start();
}
private void gridBookmarks_SelectionChanged(object sender, EventArgs e)
{
changeState();
}
private void btnEdit_Click(object sender, EventArgs e)
{
if (gridBookmarks.SelectedRows.Count != 1)
return;
DataRowView bookmarkRow = (DataRowView)gridBookmarks.SelectedRows[0].DataBoundItem;
Bookmark oldBookmark = new Bookmark(bookmarkRow["SearchPattern"].ToString(), bookmarkRow["ReplacePattern"].ToString(),
bookmarkRow["FileNames"].ToString(), bookmarkRow["Description"].ToString());
Bookmark newBookmark = new Bookmark(bookmarkRow["SearchPattern"].ToString(), bookmarkRow["ReplacePattern"].ToString(),
bookmarkRow["FileNames"].ToString(), bookmarkRow["Description"].ToString());
BookmarkDetails editForm = new BookmarkDetails(CreateOrEdit.Edit);
editForm.Bookmark = newBookmark;
if (editForm.ShowDialog() == DialogResult.OK)
{
BookmarkLibrary.Instance.Bookmarks.Remove(oldBookmark);
BookmarkLibrary.Instance.Bookmarks.Add(newBookmark);
BookmarkLibrary.Save();
refreshGrid();
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (gridBookmarks.SelectedRows.Count != 1)
return;
DataRowView bookmarkRow = (DataRowView)gridBookmarks.SelectedRows[0].DataBoundItem;
Bookmark oldBookmark = new Bookmark(bookmarkRow["SearchPattern"].ToString(), bookmarkRow["ReplacePattern"].ToString(),
bookmarkRow["FileNames"].ToString(), bookmarkRow["Description"].ToString());
BookmarkLibrary.Instance.Bookmarks.Remove(oldBookmark);
refreshGrid();
}
private void btnAdd_Click(object sender, EventArgs e)
{
BookmarkDetails editForm = new BookmarkDetails(CreateOrEdit.Create);
if (editForm.ShowDialog() == DialogResult.OK)
{
Bookmark bookmark = editForm.Bookmark;
if (!BookmarkLibrary.Instance.Bookmarks.Contains(bookmark))
{
BookmarkLibrary.Instance.Bookmarks.Add(bookmark);
BookmarkLibrary.Save();
refreshGrid();
}
}
}
private void gridBookmarks_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
btnUse_Click(this, null);
}
private void formKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
Close();
}
private void btnUse_Click(object sender, EventArgs e)
{
if (gridBookmarks.SelectedRows.Count != 1)
return;
DataRowView bookmarkRow = (DataRowView)gridBookmarks.SelectedRows[0].DataBoundItem;
FilePattern = bookmarkRow["FileNames"].ToString();
SearchFor = bookmarkRow["SearchPattern"].ToString();
ReplaceWith = bookmarkRow["ReplacePattern"].ToString();
}
private void doSearch(object sender, EventArgs e)
{
typeTimer.Stop();
if (string.IsNullOrEmpty(textSearch.Text.Trim()))
{
refreshGrid();
return;
}
copyOfBookmarks = BookmarkLibrary.Instance.GetDataTable();
for (int i = copyOfBookmarks.Rows.Count - 1; i >= 0; i--)
{
DataRow row = copyOfBookmarks.Rows[i];
bool found = row["FileNames"].ToString().ToLower().Contains(textSearch.Text.ToLower()) ||
row["SearchPattern"].ToString().ToLower().Contains(textSearch.Text.ToLower()) ||
row["ReplacePattern"].ToString().ToLower().Contains(textSearch.Text.ToLower()) ||
row["Description"].ToString().ToLower().Contains(textSearch.Text.ToLower());
if (!found)
copyOfBookmarks.Rows.RemoveAt(i);
}
gridBookmarks.DataSource = copyOfBookmarks;
gridBookmarks.Refresh();
}
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
}
} | zychen63-dngrep | dnGREP.Common.UI/BookmarksForm.cs | C# | gpl3 | 5,663 |
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;
using System.Windows.Forms;
namespace dnGREP.Common.UI
{
public class FileFolderDialog : CommonDialog
{
private OpenFileDialog dialog = new OpenFileDialog();
public OpenFileDialog Dialog
{
get { return dialog; }
set { dialog = value; }
}
public new DialogResult ShowDialog()
{
return this.ShowDialog(null);
}
public new DialogResult ShowDialog(IWin32Window owner)
{
// Set validate names to false otherwise windows will not let you select "Folder Selection."
dialog.ValidateNames = false;
dialog.CheckFileExists = false;
dialog.CheckPathExists = true;
try
{
// Set initial directory (used when dialog.FileName is set from outside)
if (dialog.FileName != null && dialog.FileName != "")
{
if (Directory.Exists(dialog.FileName))
dialog.InitialDirectory = dialog.FileName;
else
dialog.InitialDirectory = Utils.GetBaseFolder(dialog.FileName);
}
}
catch (Exception ex)
{
// Do nothing
}
// Always default to Folder Selection.
dialog.FileName = "Folder Selection.";
if (owner == null)
return dialog.ShowDialog();
else
return dialog.ShowDialog(owner);
}
/// <summary>
// Helper property. Parses FilePath into either folder path (if Folder Selection. is set)
// or returns file path
/// </summary>
public string SelectedPath
{
get {
try
{
if (dialog.FileName != null &&
(dialog.FileName.EndsWith("Folder Selection.") || !File.Exists(dialog.FileName)) &&
!Directory.Exists(dialog.FileName))
{
return Path.GetDirectoryName(dialog.FileName);
}
else
{
return dialog.FileName;
}
}
catch (Exception ex)
{
return dialog.FileName;
}
}
set
{
if (value != null && value != "")
{
dialog.FileName = value;
}
}
}
/// <summary>
/// When multiple files are selected returns them as semi-colon seprated string
/// </summary>
public string SelectedPaths
{
get {
if (dialog.FileNames != null && dialog.FileNames.Length > 1)
{
StringBuilder sb = new StringBuilder();
foreach (string fileName in dialog.FileNames)
{
try
{
if (File.Exists(fileName))
sb.Append(fileName + ";");
}
catch (Exception ex)
{
// Go to next
}
}
return sb.ToString();
}
else
{
return null;
}
}
}
public override void Reset()
{
dialog.Reset();
}
protected override bool RunDialog(IntPtr hwndOwner)
{
return true;
}
}
}
| zychen63-dngrep | dnGREP.Common.UI/FileFolderDialog.cs | C# | gpl3 | 2,864 |
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("dnGREP.Common.UI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("BAH")]
[assembly: AssemblyProduct("dnGREP.Common.UI")]
[assembly: AssemblyCopyright("Copyright © BAH 2010")]
[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("0431bd1f-3ebf-4f2a-9acb-d322ad213934")]
// 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")]
| zychen63-dngrep | dnGREP.Common.UI/Properties/AssemblyInfo.cs | C# | gpl3 | 1,450 |
using System;
using System.Collections.Generic;
using System.Text;
using NLog;
using dnGREP.Common;
using SevenZip;
using System.IO;
namespace dnGREP.Engines.Archive
{
public class GrepEngineArchive : GrepEngineBase, IGrepEngine
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public GrepEngineArchive() : base() { }
public GrepEngineArchive(GrepEngineInitParams param)
:
base(param)
{}
public bool IsSearchOnly
{
get { return true; }
}
public string Description
{
get { return "Searches inside archive files. Archives supported include: 7z, zip, rar, gzip. Search only."; }
}
public List<string> SupportedFileExtensions
{
get { return new List<string> ( new string[] { "7z", "zip", "rar", "gzip" }); }
}
public List<GrepSearchResult> Search(string file, string searchPattern, SearchType searchType, GrepSearchOption searchOptions, Encoding encoding)
{
List<GrepSearchResult> searchResults = new List<GrepSearchResult>();
SevenZipExtractor extractor = new SevenZipExtractor(file);
GrepEnginePlainText plainTextEngine = new GrepEnginePlainText();
plainTextEngine.Initialize(new GrepEngineInitParams(showLinesInContext, linesBefore, linesAfter, fuzzyMatchThreshold));
string tempFolder = Utils.FixFolderName(Utils.GetTempFolder()) + "dnGREP-Archive\\" + Utils.GetHash(file) + "\\";
if (Directory.Exists(tempFolder))
Utils.DeleteFolder(tempFolder);
Directory.CreateDirectory(tempFolder);
try
{
extractor.ExtractArchive(tempFolder);
foreach (string archiveFileName in Directory.GetFiles(tempFolder, "*.*", SearchOption.AllDirectories))
{
IGrepEngine engine = GrepEngineFactory.GetSearchEngine(archiveFileName, new GrepEngineInitParams(showLinesInContext, linesBefore, linesAfter, fuzzyMatchThreshold));
searchResults.AddRange(engine.Search(archiveFileName, searchPattern, searchType, searchOptions, encoding));
}
foreach (GrepSearchResult result in searchResults)
{
result.FileNameDisplayed = file + "\\" + result.FileNameDisplayed.Substring(tempFolder.Length);
result.FileNameReal = file;
result.ReadOnly = true;
}
}
catch (Exception ex)
{
logger.LogException(LogLevel.Error, "Failed to search inside archive.", ex);
}
return searchResults;
}
public void Unload()
{
//Do nothing
}
public bool Replace(string sourceFile, string destinationFile, string searchPattern, string replacePattern, SearchType searchType, GrepSearchOption searchOptions, Encoding encoding)
{
throw new Exception("The method or operation is not supported.");
}
public Version FrameworkVersion
{
get
{
return new Version(1, 4, 0, 0);
}
}
public override void OpenFile(OpenFileArgs args)
{
SevenZipExtractor extractor = new SevenZipExtractor(args.SearchResult.FileNameReal);
string tempFolder = Utils.FixFolderName(Utils.GetTempFolder()) + "dnGREP-Archive\\" + Utils.GetHash(args.SearchResult.FileNameReal) + "\\";
if (!Directory.Exists(tempFolder))
{
Directory.CreateDirectory(tempFolder);
try
{
extractor.ExtractArchive(tempFolder);
}
catch (Exception ex)
{
args.UseBaseEngine = true;
}
}
GrepSearchResult newResult = new GrepSearchResult();
newResult.FileNameReal = args.SearchResult.FileNameReal;
newResult.FileNameDisplayed = args.SearchResult.FileNameDisplayed;
OpenFileArgs newArgs = new OpenFileArgs(newResult, args.LineNumber, args.UseCustomEditor, args.CustomEditor, args.CustomEditorArgs);
newArgs.SearchResult.FileNameDisplayed = tempFolder + args.SearchResult.FileNameDisplayed.Substring(args.SearchResult.FileNameReal.Length + 1);
Utils.OpenFile(newArgs);
}
}
}
| zychen63-dngrep | dnGREP.ArchiveEngine/GrepEngineArchive.cs | C# | gpl3 | 3,891 |
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("dnGREP.ArchiveEngine")]
[assembly: AssemblyDescription("This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Denis Stankovski")]
[assembly: AssemblyProduct("dnGREP.ArchiveEngine")]
[assembly: AssemblyCopyright("Copyright, 2008")]
[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("945ee555-1135-40af-8177-8ae55435b9a4")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.4.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]
| zychen63-dngrep | dnGREP.ArchiveEngine/Properties/AssemblyInfo.cs | C# | gpl3 | 1,663 |
using System;
using System.Collections.Generic;
using System.Text;
using dnGREP.Engines;
using NLog;
using dnGREP.Common;
using System.Reflection;
using System.Runtime.InteropServices;
using System.IO;
using System.Text.RegularExpressions;
using System.Diagnostics;
namespace dnGREP.Engines.Pdf
{
/// <summary>
/// Based on a MicrosoftWordPlugin class for AstroGrep by Curtis Beard. Thank you!
/// </summary>
public class GrepEnginePdf : GrepEngineBase, IGrepEngine
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private bool isAvailable;
private string pathToPdfToText = "";
#region Initialization and disposal
public GrepEnginePdf() : this(new GrepEngineInitParams(false, 0, 0, 0.5)) { }
public override bool Initialize(GrepEngineInitParams param)
{
this.showLinesInContext = param.ShowLinesInContext;
this.linesBefore = param.LinesBefore;
this.linesAfter = param.LinesAfter;
this.fuzzyMatchThreshold = param.FuzzyMatchThreshold;
try
{
// Make sure pdftotext.exe exists
pathToPdfToText = Utils.GetCurrentPath(typeof(GrepEnginePdf)) + "\\pdftotext.exe";
if (File.Exists(pathToPdfToText))
return true;
else
return false;
}
catch (Exception ex)
{
logger.LogException(LogLevel.Error, "Failed to find pdftotext.exe.", ex);
return false;
}
}
public GrepEnginePdf(GrepEngineInitParams param)
:
base(param)
{ }
#endregion
public bool IsSearchOnly
{
get { return true; }
}
public string Description
{
get { return "Searches inside Acrobat PDF files. File types supported include: pdf. Search only."; }
}
public List<string> SupportedFileExtensions
{
get { return new List<string>(new string[] { "pdf" }); }
}
public List<GrepSearchResult> Search(string file, string searchPattern, SearchType searchType, GrepSearchOption searchOptions, Encoding encoding)
{
try
{
// Extract text
string tempFile = extractText(file);
if (!File.Exists(tempFile))
throw new ApplicationException("pdftotext failed to create text file.");
IGrepEngine engine = GrepEngineFactory.GetSearchEngine(tempFile, new GrepEngineInitParams(showLinesInContext, linesBefore, linesAfter, fuzzyMatchThreshold));
List<GrepSearchResult> results = engine.Search(tempFile, searchPattern, searchType, searchOptions, encoding);
foreach (GrepSearchResult result in results)
{
result.ReadOnly = true;
result.FileNameDisplayed = file;
result.FileNameReal = file;
}
return results;
}
catch (Exception ex)
{
logger.LogException(LogLevel.Error, "Failed to search inside Pdf file", ex);
return new List<GrepSearchResult>();
}
}
private string extractText(string pdfFilePath)
{
string tempFolder = Utils.GetTempFolder() + "dnGREP-PDF\\";
if (!Directory.Exists(tempFolder))
Directory.CreateDirectory(tempFolder);
string tempFileName = tempFolder + Path.GetFileNameWithoutExtension(pdfFilePath) + ".txt";
using (Process process = new Process())
{
try
{
// use command prompt
process.StartInfo.FileName = pathToPdfToText;
process.StartInfo.Arguments = string.Format("-layout \"{0}\" \"{1}\"", pdfFilePath, tempFileName);
process.StartInfo.UseShellExecute = false;
process.StartInfo.WorkingDirectory = Utils.GetCurrentPath(typeof(GrepEnginePdf));
process.StartInfo.CreateNoWindow = true;
// start cmd prompt, execute command
process.Start();
process.WaitForExit();
if (process.ExitCode == 0)
return tempFileName;
else
throw new Exception("pdftotext process exited with error code.");
}
catch
{
throw;
}
}
}
public bool Replace(string sourceFile, string destinationFile, string searchPattern, string replacePattern, SearchType searchType, GrepSearchOption searchOptions, Encoding encoding)
{
throw new Exception("The method or operation is not implemented.");
}
public Version FrameworkVersion
{
get
{
return new Version(1, 4, 0, 0);
}
}
public void Unload()
{
//Do nothing
}
public override void OpenFile(OpenFileArgs args)
{
args.UseCustomEditor = false;
Utils.OpenFile(args);
}
}
}
| zychen63-dngrep | dnGREP.PdfEngine/GrepEnginePdf.cs | C# | gpl3 | 4,415 |
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("dnGREP.PdfEngine")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("BAH")]
[assembly: AssemblyProduct("dnGREP.PdfEngine")]
[assembly: AssemblyCopyright("Copyright © BAH 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f8a85ec0-e156-4be8-896c-a463f489d0ea")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
| zychen63-dngrep | dnGREP.PdfEngine/Properties/AssemblyInfo.cs | C# | gpl3 | 1,409 |
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=0" />
<meta content="text/html; charset=utf-8" http-equiv="Content-type">
<meta content="IE=8" http-equiv="X-UA-Compatible">
<meta content=
"Google I/O 2011 brings together thousands of developers for two days of deep technical content, focused on building the next generation of web, mobile, and enterprise applications with Google and open web technologies such as Android, Google Chrome, Google APIs, Google Web Toolkit, App Engine, and more."
name="description">
<meta content=
"event, google, i/o, programming, android, chrome, developers, moscone, san francisco" name=
"keywords">
<meta content="Google" name="author">
<title>
Google I/O 2011
</title>
<link href="map.css" media="all" rel="stylesheet">
<style type="text/css">
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
#level-select {
height: 22px;
}
</style>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
window['ioEmbed'] = true;
</script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/maplabel/src/maplabel-compiled.js"></script>
<script src="floor.js"></script>
<script src="levelcontrol.js"></script>
<script src="smartmarker.js"></script>
<script src="map.js"></script>
<script src="http://www.google.com/js/gweb/analytics/autotrack.js"></script>
<script>
new gweb.analytics.AutoTrack({
profile: 'UA-20834900-1'
});
</script>
</head>
<body>
<div id="map-canvas"></div>
</div>
</body>
</html>
| zzxxasp-key | map/embed.html | HTML | asf20 | 1,825 |
/**
* Creates a new Floor.
* @constructor
* @param {google.maps.Map=} opt_map
*/
function Floor(opt_map) {
/**
* @type Array.<google.maps.MVCObject>
*/
this.overlays_ = [];
/**
* @type boolean
*/
this.shown_ = true;
if (opt_map) {
this.setMap(opt_map);
}
}
/**
* @param {google.maps.Map} map
*/
Floor.prototype.setMap = function(map) {
this.map_ = map;
};
/**
* @param {google.maps.MVCObject} overlay For example, a Marker or MapLabel.
* Requires a setMap method.
*/
Floor.prototype.addOverlay = function(overlay) {
if (!overlay) return;
this.overlays_.push(overlay);
overlay.setMap(this.shown_ ? this.map_ : null);
};
/**
* Sets the map on all the overlays
* @param {google.maps.Map} map The map to set.
*/
Floor.prototype.setMapAll_ = function(map) {
this.shown_ = !!map;
for (var i = 0, overlay; overlay = this.overlays_[i]; i++) {
overlay.setMap(map);
}
};
/**
* Hides the floor and all associated overlays.
*/
Floor.prototype.hide = function() {
this.setMapAll_(null);
};
/**
* Shows the floor and all associated overlays.
*/
Floor.prototype.show = function() {
this.setMapAll_(this.map_);
};
| zzxxasp-key | map/floor.js | JavaScript | asf20 | 1,176 |
/**
* Creates a new level control.
* @constructor
* @param {IoMap} iomap the IO map controller.
* @param {Array.<string>} levels the levels to create switchers for.
*/
function LevelControl(iomap, levels) {
var that = this;
this.iomap_ = iomap;
this.el_ = this.initDom_(levels);
google.maps.event.addListener(iomap, 'level_changed', function() {
that.changeLevel_(iomap.get('level'));
});
}
/**
* Gets the DOM element for the control.
* @return {Element}
*/
LevelControl.prototype.getElement = function() {
return this.el_;
};
/**
* Creates the necessary DOM for the control.
* @return {Element}
*/
LevelControl.prototype.initDom_ = function(levelDefinition) {
var controlDiv = document.createElement('DIV');
controlDiv.setAttribute('id', 'levels-wrapper');
var levels = document.createElement('DIV');
levels.setAttribute('id', 'levels');
controlDiv.appendChild(levels);
var levelSelect = this.levelSelect_ = document.createElement('DIV');
levelSelect.setAttribute('id', 'level-select');
levels.appendChild(levelSelect);
this.levelDivs_ = [];
var that = this;
for (var i = 0, level; level = levelDefinition[i]; i++) {
var div = document.createElement('DIV');
div.innerHTML = 'Level ' + level;
div.setAttribute('id', 'level-' + level);
div.className = 'level';
levels.appendChild(div);
this.levelDivs_.push(div);
google.maps.event.addDomListener(div, 'click', function(e) {
var id = e.currentTarget.getAttribute('id');
var level = parseInt(id.replace('level-', ''), 10);
that.iomap_.setHash('level' + level);
});
}
controlDiv.index = 1;
return controlDiv;
};
/**
* Changes the highlighted level in the control.
* @param {number} level the level number to select.
*/
LevelControl.prototype.changeLevel_ = function(level) {
if (this.currentLevelDiv_) {
this.currentLevelDiv_.className =
this.currentLevelDiv_.className.replace(' level-selected', '');
}
var h = 25;
if (window['ioEmbed']) {
h = (window.screen.availWidth > 600) ? 34 : 24;
}
this.levelSelect_.style.top = 9 + ((level - 1) * h) + 'px';
var div = this.levelDivs_[level - 1];
div.className += ' level-selected';
this.currentLevelDiv_ = div;
};
| zzxxasp-key | map/levelcontrol.js | JavaScript | asf20 | 2,264 |
/**
* @license
*
* 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.
*/
/**
* @fileoverview SmartMarker.
*
* @author Chris Broadfoot (cbro@google.com)
*/
/**
* A google.maps.Marker that has some smarts about the zoom levels it should be
* shown.
*
* Options are the same as google.maps.Marker, with the addition of minZoom and
* maxZoom. These zoom levels are inclusive. That is, a SmartMarker with
* a minZoom and maxZoom of 13 will only be shown at zoom level 13.
* @constructor
* @extends google.maps.Marker
* @param {Object=} opts Same as MarkerOptions, plus minZoom and maxZoom.
*/
function SmartMarker(opts) {
var marker = new google.maps.Marker;
// default min/max Zoom - shows the marker all the time.
marker.setValues({
'minZoom': 0,
'maxZoom': Infinity
});
// the current listener (if any), triggered on map zoom_changed
var mapZoomListener;
google.maps.event.addListener(marker, 'map_changed', function() {
if (mapZoomListener) {
google.maps.event.removeListener(mapZoomListener);
}
var map = marker.getMap();
if (map) {
var listener = SmartMarker.newZoomListener_(marker);
mapZoomListener = google.maps.event.addListener(map, 'zoom_changed',
listener);
// Call the listener straight away. The map may already be initialized,
// so it will take user input for zoom_changed to be fired.
listener();
}
});
marker.setValues(opts);
return marker;
}
window['SmartMarker'] = SmartMarker;
/**
* Creates a new listener to be triggered on 'zoom_changed' event.
* Hides and shows the target Marker based on the map's zoom level.
* @param {google.maps.Marker} marker The target marker.
* @return Function
*/
SmartMarker.newZoomListener_ = function(marker) {
var map = marker.getMap();
return function() {
var zoom = map.getZoom();
var minZoom = Number(marker.get('minZoom'));
var maxZoom = Number(marker.get('maxZoom'));
marker.setVisible(zoom >= minZoom && zoom <= maxZoom);
};
};
| zzxxasp-key | map/smartmarker.js | JavaScript | asf20 | 2,564 |
#map-canvas {
height: 500px;
}
#levels-wrapper {
margin: 10px;
padding: 5px;
background: #fff;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.3);
-moz-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.3);
box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.3);
}
#levels {
padding: 3px;
font-family: 'Droid Sans',Arial;
font-size: 16px;
color: #205aaf;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
background: #FFFFFF;
background: -moz-linear-gradient(top, #E8E8E8 0%, #FFFFFF 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#E8E8E8), color-stop(100%,#FFFFFF));
-webkit-box-shadow: inset 0px 0px 2px rgba(0, 0, 0, 0.5);
-moz-box-shadow: inset 0px 0px 2px rgba(0, 0, 0, 0.5);
box-shadow: inset 0px 0px 2px rgba(0, 0, 0, 0.5);
}
.level {
position: relative;
z-index: 100;
padding: 3px 5px;
cursor: pointer;
}
#level-select {
position: absolute;
top: 9px;
left: 10px;
right: 10px;
height: 24px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
z-index: 1;
background: #1C72D0; /* old browsers */
background: -moz-linear-gradient(top, #1C72D0 0%, #015CB9 100%); /* firefox */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#1C72D0), color-stop(100%,#015CB9)); /* webkit */
}
@media only screen and (min-device-width:600px) {
#level-select {
height: 32px !important;
}
.level {
font-size: 24px;
}
}
.level-selected {
color: #fff;
}
.level-selected, #level-select {
-webkit-transition: all 500ms cubic-bezier(0.645, 0.045, 0.355, 1.000);
-moz-transition: all 500ms cubic-bezier(0.645, 0.045, 0.355, 1.000);
-o-transition: all 500ms cubic-bezier(0.645, 0.045, 0.355, 1.000);
transition: all 500ms cubic-bezier(0.645, 0.045, 0.355, 1.000);
-webkit-transition-timing-function: cubic-bezier(0.645, 0.045, 0.355, 1.000);
-moz-transition-timing-function: cubic-bezier(0.645, 0.045, 0.355, 1.000);
-o-transition-timing-function: cubic-bezier(0.645, 0.045, 0.355, 1.000);
transition-timing-function: cubic-bezier(0.645, 0.045, 0.355, 1.000);
}
.infowindow {
max-width: 330px;
}
.infowindow h3 {
margin: 0 0 4px 0;
padding: 0;
font-size: 13px;
color: #000;
font-family: 'Droid Sans', arial, helvetica;
text-align: left;
}
.session, .sandbox {
padding: 2px 0;
clear: both;
font-size: 13px;
font-family: 'Droid Sans', arial, helvetica;
}
.session-time {
float: left;
width: 8.1em;
color: #999;
}
.session-title, .session-products {
margin-left: 8.5em;
}
| zzxxasp-key | map/map.css | CSS | asf20 | 2,657 |
// Copyright 2011 Google
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* The Google IO Map
* @constructor
*/
var IoMap = function() {
var moscone = new google.maps.LatLng(37.78313383211993, -122.40394949913025);
/** @type {Node} */
this.mapDiv_ = document.getElementById(this.MAP_ID);
var ioStyle = [
{
'featureType': 'road',
stylers: [
{ hue: '#00aaff' },
{ gamma: 1.67 },
{ saturation: -24 },
{ lightness: -38 }
]
},{
'featureType': 'road',
'elementType': 'labels',
stylers: [
{ invert_lightness: true }
]
}];
/** @type {boolean} */
this.ready_ = false;
/** @type {google.maps.Map} */
this.map_ = new google.maps.Map(this.mapDiv_, {
zoom: 18,
center: moscone,
navigationControl: true,
mapTypeControl: false,
scaleControl: true,
mapTypeId: 'io',
streetViewControl: false
});
var style = /** @type {*} */(new google.maps.StyledMapType(ioStyle));
this.map_.mapTypes.set('io', /** @type {google.maps.MapType} */(style));
google.maps.event.addListenerOnce(this.map_, 'tilesloaded', function() {
if (window['MAP_CONTAINER'] !== undefined) {
window['MAP_CONTAINER']['onMapReady']();
}
});
/** @type {Array.<Floor>} */
this.floors_ = [];
for (var i = 0; i < this.LEVELS_.length; i++) {
this.floors_.push(new Floor(this.map_));
}
this.addLevelControl_();
this.addMapOverlay_();
this.loadMapContent_();
this.initLocationHashWatcher_();
if (!document.location.hash) {
this.showLevel(1, true);
}
}
IoMap.prototype = new google.maps.MVCObject;
/**
* The id of the Element to add the map to.
*
* @type {string}
* @const
*/
IoMap.prototype.MAP_ID = 'map-canvas';
/**
* The levels of the Moscone Center.
*
* @type {Array.<string>}
* @private
*/
IoMap.prototype.LEVELS_ = ['1', '2', '3'];
/**
* Location where the tiles are hosted.
*
* @type {string}
* @private
*/
IoMap.prototype.BASE_TILE_URL_ =
'http://www.gstatic.com/io2010maps/tiles/5/';
/**
* The minimum zoom level to show the overlay.
*
* @type {number}
* @private
*/
IoMap.prototype.MIN_ZOOM_ = 16;
/**
* The maximum zoom level to show the overlay.
*
* @type {number}
* @private
*/
IoMap.prototype.MAX_ZOOM_ = 20;
/**
* The template for loading tiles. Replace {L} with the level, {Z} with the
* zoom level, {X} and {Y} with respective tile coordinates.
*
* @type {string}
* @private
*/
IoMap.prototype.TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ +
'L{L}_{Z}_{X}_{Y}.png';
/**
* @type {string}
* @private
*/
IoMap.prototype.SIMPLE_TILE_TEMPLATE_URL_ =
IoMap.prototype.BASE_TILE_URL_ + '{Z}_{X}_{Y}.png';
/**
* The extent of the overlay at certain zoom levels.
*
* @type {Object.<string, Array.<Array.<number>>>}
* @private
*/
IoMap.prototype.RESOLUTION_BOUNDS_ = {
16: [[10484, 10485], [25328, 25329]],
17: [[20969, 20970], [50657, 50658]],
18: [[41939, 41940], [101315, 101317]],
19: [[83878, 83881], [202631, 202634]],
20: [[167757, 167763], [405263, 405269]]
};
/**
* The previous hash to compare against.
*
* @type {string?}
* @private
*/
IoMap.prototype.prevHash_ = null;
/**
* Initialise the location hash watcher.
*
* @private
*/
IoMap.prototype.initLocationHashWatcher_ = function() {
var that = this;
if ('onhashchange' in window) {
window.addEventListener('hashchange', function() {
that.parseHash_();
}, true);
} else {
var that = this
window.setInterval(function() {
that.parseHash_();
}, 100);
}
this.parseHash_();
};
/**
* Called from Android.
*
* @param {Number} x A percentage to pan left by.
*/
IoMap.prototype.panLeft = function(x) {
var div = this.map_.getDiv();
var left = div.clientWidth * x;
this.map_.panBy(left, 0);
};
IoMap.prototype['panLeft'] = IoMap.prototype.panLeft;
/**
* Adds the level switcher to the top left of the map.
*
* @private
*/
IoMap.prototype.addLevelControl_ = function() {
var control = new LevelControl(this, this.LEVELS_).getElement();
this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(control);
};
/**
* Shows a floor based on the content of location.hash.
*
* @private
*/
IoMap.prototype.parseHash_ = function() {
var hash = document.location.hash;
if (hash == this.prevHash_) {
return;
}
this.prevHash_ = hash;
var level = 1;
if (hash) {
var match = hash.match(/level(\d)(?:\:([\w-]+))?/);
if (match && match[1]) {
level = parseInt(match[1], 10);
}
}
this.showLevel(level, true);
};
/**
* Updates location.hash based on the currently shown floor.
*
* @param {string?} opt_hash
*/
IoMap.prototype.setHash = function(opt_hash) {
var hash = document.location.hash.substring(1);
if (hash == opt_hash) {
return;
}
if (opt_hash) {
document.location.hash = opt_hash;
} else {
document.location.hash = 'level' + this.get('level');
}
};
IoMap.prototype['setHash'] = IoMap.prototype.setHash;
/**
* Called from spreadsheets.
*/
IoMap.prototype.loadSandboxCallback = function(json) {
var updated = json['feed']['updated']['$t'];
var contentItems = [];
var ids = {};
var entries = json['feed']['entry'];
for (var i = 0, entry; entry = entries[i]; i++) {
var item = {};
item.companyName = entry['gsx$companyname']['$t'];
item.companyUrl = entry['gsx$companyurl']['$t'];
var p = entry['gsx$companypod']['$t'];
item.pod = p;
p = p.toLowerCase().replace(/\s+/, '');
item.sessionRoom = p;
contentItems.push(item);
};
this.sandboxItems_ = contentItems;
this.ready_ = true;
this.addMapContent_();
};
/**
* Called from spreadsheets.
*
* @param {Object} json The json feed from the spreadsheet.
*/
IoMap.prototype.loadSessionsCallback = function(json) {
var updated = json['feed']['updated']['$t'];
var contentItems = [];
var ids = {};
var entries = json['feed']['entry'];
for (var i = 0, entry; entry = entries[i]; i++) {
var item = {};
item.sessionDate = entry['gsx$sessiondate']['$t'];
item.sessionAbstract = entry['gsx$sessionabstract']['$t'];
item.sessionHashtag = entry['gsx$sessionhashtag']['$t'];
item.sessionLevel = entry['gsx$sessionlevel']['$t'];
item.sessionTitle = entry['gsx$sessiontitle']['$t'];
item.sessionTrack = entry['gsx$sessiontrack']['$t'];
item.sessionUrl = entry['gsx$sessionurl']['$t'];
item.sessionYoutubeUrl = entry['gsx$sessionyoutubeurl']['$t'];
item.sessionTime = entry['gsx$sessiontime']['$t'];
item.sessionRoom = entry['gsx$sessionroom']['$t'];
item.sessionTags = entry['gsx$sessiontags']['$t'];
item.sessionSpeakers = entry['gsx$sessionspeakers']['$t'];
if (item.sessionDate.indexOf('10') != -1) {
item.sessionDay = 10;
} else {
item.sessionDay = 11;
}
var timeParts = item.sessionTime.split('-');
item.sessionStart = this.convertTo24Hour_(timeParts[0]);
item.sessionEnd = this.convertTo24Hour_(timeParts[1]);
contentItems.push(item);
}
this.sessionItems_ = contentItems;
};
/**
* Converts the time in the spread sheet to 24 hour time.
*
* @param {string} time The time like 10:42am.
*/
IoMap.prototype.convertTo24Hour_ = function(time) {
var pm = time.indexOf('pm') != -1;
time = time.replace(/[am|pm]/ig, '');
if (pm) {
var bits = time.split(':');
var hr = parseInt(bits[0], 10);
if (hr < 12) {
time = (hr + 12) + ':' + bits[1];
}
}
return time;
};
/**
* Loads the map content from Google Spreadsheets.
*
* @private
*/
IoMap.prototype.loadMapContent_ = function() {
// Initiate a JSONP request.
var that = this;
// Add a exposed call back function
window['loadSessionsCallback'] = function(json) {
that.loadSessionsCallback(json);
}
// Add a exposed call back function
window['loadSandboxCallback'] = function(json) {
that.loadSandboxCallback(json);
}
var key = 'tmaLiaNqIWYYtuuhmIyG0uQ';
var worksheetIDs = {
sessions: 'od6',
sandbox: 'od4'
};
var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' +
key + '/' + worksheetIDs.sessions + '/public/values' +
'?alt=json-in-script&callback=loadSessionsCallback';
var script = document.createElement('script');
script.setAttribute('src', jsonpUrl);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' +
key + '/' + worksheetIDs.sandbox + '/public/values' +
'?alt=json-in-script&callback=loadSandboxCallback';
var script = document.createElement('script');
script.setAttribute('src', jsonpUrl);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
};
/**
* Called from Android.
*
* @param {string} roomId The id of the room to load.
*/
IoMap.prototype.showLocationById = function(roomId) {
var locations = this.LOCATIONS_;
for (var level in locations) {
var levelId = level.replace('LEVEL', '');
for (var loc in locations[level]) {
var room = locations[level][loc];
if (loc == roomId) {
var pos = new google.maps.LatLng(room.lat, room.lng);
this.map_.panTo(pos);
this.map_.setZoom(19);
this.showLevel(levelId);
if (room.marker_) {
room.marker_.setAnimation(google.maps.Animation.BOUNCE);
// Disable the animation after 5 seconds.
window.setTimeout(function() {
room.marker_.setAnimation();
}, 5000);
}
return;
}
}
}
};
IoMap.prototype['showLocationById'] = IoMap.prototype.showLocationById;
/**
* Called when the level is changed. Hides and shows floors.
*/
IoMap.prototype['level_changed'] = function() {
var level = this.get('level');
if (this.infoWindow_) {
this.infoWindow_.setMap(null);
}
for (var i = 1, floor; floor = this.floors_[i - 1]; i++) {
if (i == level) {
floor.show();
} else {
floor.hide();
}
}
this.setHash('level' + level);
};
/**
* Shows a particular floor.
*
* @param {string} level The level to show.
* @param {boolean=} opt_force if true, changes the floor even if it's already
* the current floor.
*/
IoMap.prototype.showLevel = function(level, opt_force) {
if (!opt_force && level == this.get('level')) {
return;
}
this.set('level', level);
};
IoMap.prototype['showLevel'] = IoMap.prototype.showLevel;
/**
* Create a marker with the content item's correct icon.
*
* @param {Object} item The content item for the marker.
* @return {google.maps.Marker} The new marker.
* @private
*/
IoMap.prototype.createContentMarker_ = function(item) {
if (!item.icon) {
item.icon = 'generic';
}
var image;
var shadow;
switch(item.icon) {
case 'generic':
case 'info':
case 'media':
var image = new google.maps.MarkerImage(
'marker-' + item.icon + '.png',
new google.maps.Size(30, 28),
new google.maps.Point(0, 0),
new google.maps.Point(13, 26));
var shadow = new google.maps.MarkerImage(
'marker-shadow.png',
new google.maps.Size(30, 28),
new google.maps.Point(0,0),
new google.maps.Point(13, 26));
break;
case 'toilets':
var image = new google.maps.MarkerImage(
item.icon + '.png',
new google.maps.Size(35, 35),
new google.maps.Point(0, 0),
new google.maps.Point(17, 17));
break;
case 'elevator':
var image = new google.maps.MarkerImage(
item.icon + '.png',
new google.maps.Size(48, 26),
new google.maps.Point(0, 0),
new google.maps.Point(24, 13));
break;
}
var inactive = item.type == 'inactive';
var latLng = new google.maps.LatLng(item.lat, item.lng);
var marker = new SmartMarker({
position: latLng,
shadow: shadow,
icon: image,
title: item.title,
minZoom: inactive ? 19 : 18,
clickable: !inactive
});
marker['type_'] = item.type;
if (!inactive) {
var that = this;
google.maps.event.addListener(marker, 'click', function() {
that.openContentInfo_(item);
});
}
return marker;
};
/**
* Create a label with the content item's title atribute, if it exists.
*
* @param {Object} item The content item for the marker.
* @return {MapLabel?} The new label.
* @private
*/
IoMap.prototype.createContentLabel_ = function(item) {
if (!item.title || item.suppressLabel) {
return null;
}
var latLng = new google.maps.LatLng(item.lat, item.lng);
return new MapLabel({
'text': item.title,
'position': latLng,
'minZoom': item.labelMinZoom || 18,
'align': item.labelAlign || 'center',
'fontColor': item.labelColor,
'fontSize': item.labelSize || 12
});
}
/**
* Open a info window a content item.
*
* @param {Object} item A content item with content and a marker.
*/
IoMap.prototype.openContentInfo_ = function(item) {
if (window['MAP_CONTAINER'] !== undefined) {
window['MAP_CONTAINER']['openContentInfo'](item.room);
return;
}
var sessionBase = 'http://www.google.com/events/io/2011/sessions.html';
var now = new Date();
var may11 = new Date('May 11, 2011');
var day = now < may11 ? 10 : 11;
var type = item.type;
var id = item.id;
var title = item.title;
var content = ['<div class="infowindow">'];
var sessions = [];
var empty = true;
if (item.type == 'session') {
if (day == 10) {
content.push('<h3>' + title + ' - Tuesday May 10</h3>');
} else {
content.push('<h3>' + title + ' - Wednesday May 11</h3>');
}
for (var i = 0, session; session = this.sessionItems_[i]; i++) {
if (session.sessionRoom == item.room && session.sessionDay == day) {
sessions.push(session);
empty = false;
}
}
sessions.sort(this.sortSessions_);
for (var i = 0, session; session = sessions[i]; i++) {
content.push('<div class="session"><div class="session-time">' +
session.sessionTime + '</div><div class="session-title"><a href="' +
session.sessionUrl + '">' +
session.sessionTitle + '</a></div></div>');
}
}
if (item.type == 'sandbox') {
var sandboxName;
for (var i = 0, sandbox; sandbox = this.sandboxItems_[i]; i++) {
if (sandbox.sessionRoom == item.room) {
if (!sandboxName) {
sandboxName = sandbox.pod;
content.push('<h3>' + sandbox.pod + '</h3>');
content.push('<div class="sandbox">');
}
content.push('<div class="sandbox-items"><a href="http://' +
sandbox.companyUrl + '">' + sandbox.companyName + '</a></div>');
empty = false;
}
}
content.push('</div>');
empty = false;
}
if (empty) {
return;
}
content.push('</div>');
var pos = new google.maps.LatLng(item.lat, item.lng);
if (!this.infoWindow_) {
this.infoWindow_ = new google.maps.InfoWindow();
}
this.infoWindow_.setContent(content.join(''));
this.infoWindow_.setPosition(pos);
this.infoWindow_.open(this.map_);
};
/**
* A custom sort function to sort the sessions by start time.
*
* @param {string} a SessionA<enter description here>.
* @param {string} b SessionB.
* @return {boolean} True if sessionA is after sessionB.
*/
IoMap.prototype.sortSessions_ = function(a, b) {
var aStart = parseInt(a.sessionStart.replace(':', ''), 10);
var bStart = parseInt(b.sessionStart.replace(':', ''), 10);
return aStart > bStart;
};
/**
* Adds all overlays (markers, labels) to the map.
*/
IoMap.prototype.addMapContent_ = function() {
if (!this.ready_) {
return;
}
for (var i = 0, level; level = this.LEVELS_[i]; i++) {
var floor = this.floors_[i];
var locations = this.LOCATIONS_['LEVEL' + level];
for (var roomId in locations) {
var room = locations[roomId];
if (room.room == undefined) {
room.room = roomId;
}
if (room.type != 'label') {
var marker = this.createContentMarker_(room);
floor.addOverlay(marker);
room.marker_ = marker;
}
var label = this.createContentLabel_(room);
floor.addOverlay(label);
}
}
};
/**
* Gets the correct tile url for the coordinates and zoom.
*
* @param {google.maps.Point} coord The coordinate of the tile.
* @param {Number} zoom The current zoom level.
* @return {string} The url to the tile.
*/
IoMap.prototype.getTileUrl = function(coord, zoom) {
// Ensure that the requested resolution exists for this tile layer.
if (this.MIN_ZOOM_ > zoom || zoom > this.MAX_ZOOM_) {
return '';
}
// Ensure that the requested tile x,y exists.
if ((this.RESOLUTION_BOUNDS_[zoom][0][0] > coord.x ||
coord.x > this.RESOLUTION_BOUNDS_[zoom][0][1]) ||
(this.RESOLUTION_BOUNDS_[zoom][1][0] > coord.y ||
coord.y > this.RESOLUTION_BOUNDS_[zoom][1][1])) {
return '';
}
var template = this.TILE_TEMPLATE_URL_;
if (16 <= zoom && zoom <= 17) {
template = this.SIMPLE_TILE_TEMPLATE_URL_;
}
return template
.replace('{L}', /** @type string */(this.get('level')))
.replace('{Z}', /** @type string */(zoom))
.replace('{X}', /** @type string */(coord.x))
.replace('{Y}', /** @type string */(coord.y));
};
/**
* Add the floor overlay to the map.
*
* @private
*/
IoMap.prototype.addMapOverlay_ = function() {
var that = this;
var overlay = new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
return that.getTileUrl(coord, zoom);
},
tileSize: new google.maps.Size(256, 256)
});
google.maps.event.addListener(this, 'level_changed', function() {
var overlays = that.map_.overlayMapTypes;
if (overlays.length) {
overlays.removeAt(0);
}
overlays.push(overlay);
});
};
/**
* All the features of the map.
* @type {Object.<string, Object.<string, Object.<string, *>>>}
*/
IoMap.prototype.LOCATIONS_ = {
'LEVEL1': {
'northentrance': {
lat: 37.78381535905965,
lng: -122.40362226963043,
title: 'Entrance',
type: 'label',
labelColor: '#006600',
labelAlign: 'left',
labelSize: 10
},
'eastentrance': {
lat: 37.78328434094279,
lng: -122.40319311618805,
title: 'Entrance',
type: 'label',
labelColor: '#006600',
labelAlign: 'left',
labelSize: 10
},
'lunchroom': {
lat: 37.783112633669575,
lng: -122.40407556295395,
title: 'Lunch Room'
},
'restroom1a': {
lat: 37.78372420652042,
lng: -122.40396961569786,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator1a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'gearpickup': {
lat: 37.78367863020862,
lng: -122.4037617444992,
title: 'Gear Pickup',
type: 'label'
},
'checkin': {
lat: 37.78334369645064,
lng: -122.40335404872894,
title: 'Check In',
type: 'label'
},
'escalators1': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left'
}
},
'LEVEL2': {
'escalators2': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left',
labelMinZoom: 19
},
'press': {
lat: 37.78316774962791,
lng: -122.40360751748085,
title: 'Press Room',
type: 'label'
},
'restroom2a': {
lat: 37.7835334217721,
lng: -122.40386635065079,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'restroom2b': {
lat: 37.78250317562106,
lng: -122.40423113107681,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator2a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'1': {
lat: 37.78346240732338,
lng: -122.40415401756763,
icon: 'media',
title: 'Room 1',
type: 'session',
room: '1'
},
'2': {
lat: 37.78335005596647,
lng: -122.40431495010853,
icon: 'media',
title: 'Room 2',
type: 'session',
room: '2'
},
'3': {
lat: 37.783215446097124,
lng: -122.404490634799,
icon: 'media',
title: 'Room 3',
type: 'session',
room: '3'
},
'4': {
lat: 37.78332461789977,
lng: -122.40381203591824,
icon: 'media',
title: 'Room 4',
type: 'session',
room: '4'
},
'5': {
lat: 37.783186828219335,
lng: -122.4039850383997,
icon: 'media',
title: 'Room 5',
type: 'session',
room: '5'
},
'6': {
lat: 37.783013000871364,
lng: -122.40420497953892,
icon: 'media',
title: 'Room 6',
type: 'session',
room: '6'
},
'7': {
lat: 37.7828783903882,
lng: -122.40438133478165,
icon: 'media',
title: 'Room 7',
type: 'session',
room: '7'
},
'8': {
lat: 37.78305009820564,
lng: -122.40378588438034,
icon: 'media',
title: 'Room 8',
type: 'session',
room: '8'
},
'9': {
lat: 37.78286673120095,
lng: -122.40402393043041,
icon: 'media',
title: 'Room 9',
type: 'session',
room: '9'
},
'10': {
lat: 37.782719401312626,
lng: -122.40420028567314,
icon: 'media',
title: 'Room 10',
type: 'session',
room: '10'
},
'appengine': {
lat: 37.783362774996625,
lng: -122.40335941314697,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'App Engine'
},
'chrome': {
lat: 37.783730566003555,
lng: -122.40378990769386,
type: 'sandbox',
icon: 'generic',
title: 'Chrome'
},
'googleapps': {
lat: 37.783303419504094,
lng: -122.40320384502411,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
title: 'Apps'
},
'geo': {
lat: 37.783365954753805,
lng: -122.40314483642578,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
title: 'Geo'
},
'accessibility': {
lat: 37.783414711013485,
lng: -122.40342646837234,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Accessibility'
},
'developertools': {
lat: 37.783457107734876,
lng: -122.40347877144814,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Dev Tools'
},
'commerce': {
lat: 37.78349102509448,
lng: -122.40351900458336,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Commerce'
},
'youtube': {
lat: 37.783537661438515,
lng: -122.40358605980873,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'YouTube'
},
'officehoursfloor2a': {
lat: 37.78249045644304,
lng: -122.40410104393959,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor2': {
lat: 37.78266852473624,
lng: -122.40387573838234,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor2b': {
lat: 37.782844472747406,
lng: -122.40365579724312,
title: 'Office Hours',
type: 'label'
}
},
'LEVEL3': {
'escalators3': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left'
},
'restroom3a': {
lat: 37.78372420652042,
lng: -122.40396961569786,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'restroom3b': {
lat: 37.78250317562106,
lng: -122.40423113107681,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator3a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'keynote': {
lat: 37.783250423488326,
lng: -122.40417748689651,
icon: 'media',
title: 'Keynote',
type: 'label'
},
'11': {
lat: 37.78283069370135,
lng: -122.40408763289452,
icon: 'media',
title: 'Room 11',
type: 'session',
room: '11'
},
'googletv': {
lat: 37.7837125474666,
lng: -122.40362092852592,
type: 'sandbox',
icon: 'generic',
title: 'Google TV'
},
'android': {
lat: 37.783530242022124,
lng: -122.40358874201775,
type: 'sandbox',
icon: 'generic',
title: 'Android'
},
'officehoursfloor3': {
lat: 37.782843412820846,
lng: -122.40365579724312,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor3a': {
lat: 37.78267170452323,
lng: -122.40387842059135,
title: 'Office Hours',
type: 'label'
}
}
};
google.maps.event.addDomListener(window, 'load', function() {
window['IoMap'] = new IoMap();
});
| zzxxasp-key | map/map.js | JavaScript | asf20 | 26,216 |
<html><head><style> body { font-family: sans-serif; } pre { background-color: #eeeeee; padding: 1em; white-space: pre-wrap; } </style></head><body>
<h3>Notices for files:</h3><ul>
<li>AbstractImmutableTableTest.java</li>
<li>AtomicInteger.java</li>
<li>ConcurrentHashMap.java</li>
<li>ConcurrentMap.java</li>
<li>CustomSerializerTest.java</li>
<li>CustomSerializerTest.java.svn-base</li>
<li>EmptyImmutableTable.java</li>
<li>EmptyImmutableTableTest.java</li>
<li>FieldAttributes.java</li>
<li>FieldAttributes.java.svn-base</li>
<li>FieldAttributesTest.java</li>
<li>FieldAttributesTest.java.svn-base</li>
<li>GwtPlatform.java</li>
<li>ImmutableTable.java</li>
<li>ImmutableTableTest.java</li>
<li>InheritanceTest.java</li>
<li>InheritanceTest.java.svn-base</li>
<li>InstanceCreatorTest.java</li>
<li>InstanceCreatorTest.java.svn-base</li>
<li>JsonParser.java</li>
<li>JsonParser.java.svn-base</li>
<li>JsonParserTest.java</li>
<li>JsonParserTest.java.svn-base</li>
<li>JsonStreamParser.java</li>
<li>JsonStreamParser.java.svn-base</li>
<li>JsonStreamParserTest.java</li>
<li>JsonStreamParserTest.java.svn-base</li>
<li>LongSerializationPolicy.java</li>
<li>LongSerializationPolicy.java.svn-base</li>
<li>LongSerializationPolicyTest.java</li>
<li>LongSerializationPolicyTest.java.svn-base</li>
<li>MinimalCollectionTest.java</li>
<li>MinimalIterableTest.java</li>
<li>MinimalSetTest.java</li>
<li>OpenJdk6ListTests.java</li>
<li>OpenJdk6MapTests.java</li>
<li>OpenJdk6QueueTests.java</li>
<li>OpenJdk6SetTests.java</li>
<li>OpenJdk6Tests.java</li>
<li>RegularImmutableTable.java</li>
<li>RegularImmutableTableTest.java</li>
<li>SingletonImmutableTable.java</li>
<li>SingletonImmutableTableTest.java</li>
<li>guava</li>
</ul>
<pre>/*
* Copyright (C) 2009 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.
*/
</pre>
<h3>Notices for files:</h3><ul>
<li>NavUtils.java</li>
<li>NotificationCompat.java</li>
<li>NotificationCompatHoneycomb.java</li>
<li>TaskStackBuilder.java</li>
<li>TaskStackBuilderHoneycomb.java</li>
</ul>
<pre>/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>AbstractBiMap.java</li>
<li>AbstractCheckedFutureTest.java</li>
<li>AbstractCollectionTest.java</li>
<li>AbstractCollectionTester.java</li>
<li>AbstractConcurrentHashMultisetTest.java</li>
<li>AbstractFuture.java</li>
<li>AbstractIterator.java</li>
<li>AbstractIteratorTest.java</li>
<li>AbstractListIndexOfTester.java</li>
<li>AbstractListMultimap.java</li>
<li>AbstractListMultimapTest.java</li>
<li>AbstractListenableFutureTest.java</li>
<li>AbstractMapBasedMultiset.java</li>
<li>AbstractMapEntry.java</li>
<li>AbstractMapEntryTest.java</li>
<li>AbstractMapTester.java</li>
<li>AbstractMultimap.java</li>
<li>AbstractMultimapTest.java</li>
<li>AbstractMultiset.java</li>
<li>AbstractMultisetTest.java</li>
<li>AbstractSetMultimap.java</li>
<li>AbstractSetMultimapTest.java</li>
<li>AbstractSetTester.java</li>
<li>AbstractSortedSetMultimap.java</li>
<li>AllowConcurrentEvents.java</li>
<li>AnEnum.java</li>
<li>AnnotatedHandlerFinder.java</li>
<li>AppendableWriterTest.java</li>
<li>ArrayListMultimap.java</li>
<li>ArrayListMultimapTest.java</li>
<li>AsyncEventBus.java</li>
<li>AsyncEventBusTest.java</li>
<li>BiMap.java</li>
<li>ByFunctionOrdering.java</li>
<li>ByteStreams.java</li>
<li>ByteStreamsTest.java</li>
<li>CharStreams.java</li>
<li>CharStreamsTest.java</li>
<li>Charsets.java</li>
<li>CharsetsTest.java</li>
<li>CheckCloseSupplier.java</li>
<li>ClassToInstanceMap.java</li>
<li>Closeables.java</li>
<li>CloseablesTest.java</li>
<li>CollectionAddAllTester.java</li>
<li>CollectionAddTester.java</li>
<li>CollectionContainsAllTester.java</li>
<li>CollectionContainsTester.java</li>
<li>CollectionEqualsTester.java</li>
<li>CollectionIsEmptyTester.java</li>
<li>CollectionSizeTester.java</li>
<li>CollectionToArrayTester.java</li>
<li>CollectionToStringTester.java</li>
<li>ComparatorOrdering.java</li>
<li>CompoundOrdering.java</li>
<li>ConcurrentHashMultiset.java</li>
<li>ConcurrentHashMultisetTest.java</li>
<li>ConcurrentHashMultisetWithChmTest.java</li>
<li>ConstrainedMapImplementsMapTest.java</li>
<li>ConstrainedMultimapAsMapImplementsMapTest.java</li>
<li>ConstrainedSetMultimapTest.java</li>
<li>Constraint.java</li>
<li>Constraints.java</li>
<li>ConstraintsTest.java</li>
<li>CountingInputStream.java</li>
<li>CountingOutputStream.java</li>
<li>CountingOutputStreamTest.java</li>
<li>DeadEvent.java</li>
<li>Defaults.java</li>
<li>DefaultsTest.java</li>
<li>EmptyImmutableList.java</li>
<li>EmptyImmutableSet.java</li>
<li>EnumBiMap.java</li>
<li>EnumBiMapTest.java</li>
<li>EnumHashBiMap.java</li>
<li>EnumHashBiMapTest.java</li>
<li>EnumMultiset.java</li>
<li>EnumMultisetTest.java</li>
<li>EqualsTester.java</li>
<li>EqualsTesterTest.java</li>
<li>EventBus.java</li>
<li>EventBusTest.java</li>
<li>EventHandler.java</li>
<li>EventHandlerTest.java</li>
<li>ExecutionList.java</li>
<li>ExecutionListTest.java</li>
<li>ExplicitOrdering.java</li>
<li>Files.java</li>
<li>FinalizablePhantomReference.java</li>
<li>FinalizableReference.java</li>
<li>FinalizableReferenceQueue.java</li>
<li>FinalizableSoftReference.java</li>
<li>FinalizableWeakReference.java</li>
<li>Flushables.java</li>
<li>ForwardingCollection.java</li>
<li>ForwardingConcurrentMap.java</li>
<li>ForwardingIterator.java</li>
<li>ForwardingList.java</li>
<li>ForwardingListIterator.java</li>
<li>ForwardingListIteratorTest.java</li>
<li>ForwardingListTest.java</li>
<li>ForwardingMap.java</li>
<li>ForwardingMapEntry.java</li>
<li>ForwardingMultimap.java</li>
<li>ForwardingMultiset.java</li>
<li>ForwardingObject.java</li>
<li>ForwardingObjectTest.java</li>
<li>ForwardingQueue.java</li>
<li>ForwardingQueueTest.java</li>
<li>ForwardingSet.java</li>
<li>ForwardingSetTest.java</li>
<li>ForwardingSortedMap.java</li>
<li>ForwardingSortedMapImplementsMapTest.java</li>
<li>ForwardingSortedMapTest.java</li>
<li>ForwardingSortedSet.java</li>
<li>ForwardingTestCase.java</li>
<li>Function.java</li>
<li>Functions.java</li>
<li>HandlerFindingStrategy.java</li>
<li>HashBiMap.java</li>
<li>HashBiMapTest.java</li>
<li>HashMultimap.java</li>
<li>HashMultimapTest.java</li>
<li>HashMultiset.java</li>
<li>HashMultisetTest.java</li>
<li>ImmutableList.java</li>
<li>ImmutableListTest.java</li>
<li>ImmutableSet.java</li>
<li>ImmutableSetTest.java</li>
<li>InputSupplier.java</li>
<li>Interner.java</li>
<li>Interners.java</li>
<li>InternersTest.java</li>
<li>IoTestCase.java</li>
<li>Iterables.java</li>
<li>IterablesTest.java</li>
<li>IteratorTester.java</li>
<li>Iterators.java</li>
<li>IteratorsTest.java</li>
<li>LexicographicalOrdering.java</li>
<li>LimitInputStream.java</li>
<li>LimitInputStreamTest.java</li>
<li>LineBuffer.java</li>
<li>LineBufferTest.java</li>
<li>LineReader.java</li>
<li>LinkedHashMultimap.java</li>
<li>LinkedHashMultimapTest.java</li>
<li>LinkedHashMultiset.java</li>
<li>LinkedHashMultisetTest.java</li>
<li>LinkedListMultimap.java</li>
<li>LinkedListMultimapTest.java</li>
<li>ListAddAllTester.java</li>
<li>ListAddTester.java</li>
<li>ListIteratorTester.java</li>
<li>ListListIteratorTester.java</li>
<li>ListMultimap.java</li>
<li>ListenableFuture.java</li>
<li>Lists.java</li>
<li>ListsTest.java</li>
<li>LittleEndianDataInputStream.java</li>
<li>LittleEndianDataInputStreamTest.java</li>
<li>LittleEndianDataOutputStream.java</li>
<li>MapConstraint.java</li>
<li>MapConstraints.java</li>
<li>MapConstraintsTest.java</li>
<li>MapCreationTester.java</li>
<li>MapDifference.java</li>
<li>MapGetTester.java</li>
<li>MapIsEmptyTester.java</li>
<li>MapPutAllTester.java</li>
<li>MapPutTester.java</li>
<li>Maps.java</li>
<li>MapsTest.java</li>
<li>MinimalCollection.java</li>
<li>MoreExecutors.java</li>
<li>MultiInputStream.java</li>
<li>MultiInputStreamTest.java</li>
<li>Multimap.java</li>
<li>Multimaps.java</li>
<li>MultimapsTest.java</li>
<li>Multiset.java</li>
<li>Multisets.java</li>
<li>MultisetsImmutableEntryTest.java</li>
<li>MultisetsTest.java</li>
<li>MutableClassToInstanceMap.java</li>
<li>MutableClassToInstanceMapTest.java</li>
<li>NaturalOrdering.java</li>
<li>NullsFirstOrdering.java</li>
<li>NullsLastOrdering.java</li>
<li>ObjectArrays.java</li>
<li>ObjectArraysTest.java</li>
<li>Objects.java</li>
<li>Ordering.java</li>
<li>OrderingTest.java</li>
<li>OutputSupplier.java</li>
<li>Platform.java</li>
<li>Preconditions.java</li>
<li>Predicate.java</li>
<li>Predicates.java</li>
<li>Primitives.java</li>
<li>PrimitivesTest.java</li>
<li>RandomAmountInputStream.java</li>
<li>ReentrantEventsTest.java</li>
<li>RegularImmutableSet.java</li>
<li>Resources.java</li>
<li>ReverseNaturalOrdering.java</li>
<li>ReverseOrdering.java</li>
<li>SerializableTester.java</li>
<li>SetAddAllTester.java</li>
<li>SetAddTester.java</li>
<li>SetMultimap.java</li>
<li>Sets.java</li>
<li>SetsTest.java</li>
<li>SimpleAbstractMultisetTest.java</li>
<li>SingletonImmutableSet.java</li>
<li>SortedSetMultimap.java</li>
<li>StringCatcher.java</li>
<li>Subscribe.java</li>
<li>Supplier.java</li>
<li>Suppliers.java</li>
<li>SuppliersTest.java</li>
<li>Synchronized.java</li>
<li>SynchronizedBiMapTest.java</li>
<li>SynchronizedEventHandler.java</li>
<li>SynchronizedMapTest.java</li>
<li>SynchronizedMultimapTest.java</li>
<li>SynchronizedSetTest.java</li>
<li>TestCharacterListGenerator.java</li>
<li>TestCollectionGenerator.java</li>
<li>TestCollidingSetGenerator.java</li>
<li>TestEnumSetGenerator.java</li>
<li>TestIntegerSetGenerator.java</li>
<li>TestListGenerator.java</li>
<li>TestSetGenerator.java</li>
<li>TestStringListGenerator.java</li>
<li>TestStringSetGenerator.java</li>
<li>Throwables.java</li>
<li>ThrowablesTest.java</li>
<li>TransformedImmutableSet.java</li>
<li>TreeMultimap.java</li>
<li>TreeMultimapExplicitTest.java</li>
<li>TreeMultimapNaturalTest.java</li>
<li>TreeMultiset.java</li>
<li>TreeMultisetTest.java</li>
<li>TypeTokenTest.java</li>
<li>UnmodifiableCollectionTests.java</li>
<li>UsingToStringOrdering.java</li>
<li>WrongType.java</li>
<li>package-info.java</li>
</ul>
<pre>/*
* Copyright (C) 2007 The Guava Authors
*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>Absent.java</li>
<li>AbstractCache.java</li>
<li>AbstractCacheTest.java</li>
<li>AbstractCompositeHashFunction.java</li>
<li>AbstractFutureTest.java</li>
<li>AbstractHasher.java</li>
<li>AbstractLoadingCache.java</li>
<li>AbstractLoadingCacheTest.java</li>
<li>AbstractNonStreamingHashFunction.java</li>
<li>AbstractNonStreamingHashFunctionTest.java</li>
<li>AbstractRangeSetTest.java</li>
<li>AbstractScheduledService.java</li>
<li>AbstractScheduledServiceTest.java</li>
<li>AbstractSortedMultiset.java</li>
<li>AbstractStreamingHashFunction.java</li>
<li>AbstractStreamingHasherTest.java</li>
<li>AsyncFunction.java</li>
<li>AtomicLongMap.java</li>
<li>AtomicLongMapTest.java</li>
<li>BigIntegerMath.java</li>
<li>BigIntegerMathTest.java</li>
<li>BloomFilter.java</li>
<li>BloomFilterStrategies.java</li>
<li>BloomFilterTest.java</li>
<li>BoundType.java</li>
<li>Cache.java</li>
<li>CacheBuilder.java</li>
<li>CacheBuilderFactory.java</li>
<li>CacheBuilderSpec.java</li>
<li>CacheBuilderSpecTest.java</li>
<li>CacheEvictionTest.java</li>
<li>CacheExpirationTest.java</li>
<li>CacheLoader.java</li>
<li>CacheLoadingTest.java</li>
<li>CacheManualTest.java</li>
<li>CacheReferencesTest.java</li>
<li>CacheRefreshTest.java</li>
<li>CacheStats.java</li>
<li>CacheStatsTest.java</li>
<li>CacheTesting.java</li>
<li>ComputingConcurrentHashMapTest.java</li>
<li>ConcurrentHashMultisetBasherTest.java</li>
<li>ContiguousSetNonGwtTest.java</li>
<li>ContiguousSetTest.java</li>
<li>Count.java</li>
<li>CountTest.java</li>
<li>DescendingImmutableSortedMultiset.java</li>
<li>DiscreteDomainsTest.java</li>
<li>DoubleMath.java</li>
<li>DoubleMathTest.java</li>
<li>DoubleUtils.java</li>
<li>DoubleUtilsTest.java</li>
<li>EmptyCachesTest.java</li>
<li>EmptyContiguousSet.java</li>
<li>EmptyImmutableSortedMultiset.java</li>
<li>Enums.java</li>
<li>EnumsTest.java</li>
<li>EquivalenceTester.java</li>
<li>EquivalenceTesterTest.java</li>
<li>ExecutionError.java</li>
<li>FilteredMultimapTest.java</li>
<li>ForwardingCache.java</li>
<li>ForwardingCheckedFuture.java</li>
<li>ForwardingCheckedFutureTest.java</li>
<li>ForwardingExecutorService.java</li>
<li>ForwardingListeningExecutorService.java</li>
<li>ForwardingLoadingCache.java</li>
<li>ForwardingNavigableMapTest.java</li>
<li>FunctionalEquivalence.java</li>
<li>Funnel.java</li>
<li>Funnels.java</li>
<li>FunnelsTest.java</li>
<li>FutureCallback.java</li>
<li>GcFinalization.java</li>
<li>GcFinalizationTest.java</li>
<li>GeneralRange.java</li>
<li>GeneralRangeTest.java</li>
<li>GwtTransient.java</li>
<li>HashCode.java</li>
<li>HashCodes.java</li>
<li>HashCodesTest.java</li>
<li>HashFunction.java</li>
<li>HashTestUtils.java</li>
<li>Hasher.java</li>
<li>Hashing.java</li>
<li>HashingTest.java</li>
<li>HostAndPort.java</li>
<li>HttpHeaders.java</li>
<li>HttpHeadersTest.java</li>
<li>ImmutableSortedMultiset.java</li>
<li>ImmutableSortedMultisetFauxverideShim.java</li>
<li>ImmutableSortedMultisetTest.java</li>
<li>IntMath.java</li>
<li>IntMathTest.java</li>
<li>InterruptionUtil.java</li>
<li>LenientSerializableTester.java</li>
<li>ListeningScheduledExecutorService.java</li>
<li>LoadingCache.java</li>
<li>LocalCacheTest.java</li>
<li>LocalLoadingCacheTest.java</li>
<li>LongMath.java</li>
<li>LongMathTest.java</li>
<li>MapMakerInternalMapTest.java</li>
<li>MapMakerTest.java</li>
<li>MapsSortedTransformValuesTest.java</li>
<li>MapsTransformValuesUnmodifiableIteratorTest.java</li>
<li>MathPreconditions.java</li>
<li>MathTesting.java</li>
<li>MediaType.java</li>
<li>MediaTypeTest.java</li>
<li>MessageDigestHashFunction.java</li>
<li>MessageDigestHashFunctionTest.java</li>
<li>MultimapsFilterEntriesAsMapTest.java</li>
<li>MultisetIteratorTester.java</li>
<li>Murmur3Hash128Test.java</li>
<li>Murmur3Hash32Test.java</li>
<li>Murmur3_128HashFunction.java</li>
<li>Murmur3_32HashFunction.java</li>
<li>NullCacheTest.java</li>
<li>Optional.java</li>
<li>OptionalTest.java</li>
<li>OutsideEventBusTest.java</li>
<li>PairwiseEquivalence.java</li>
<li>PairwiseEquivalence_CustomFieldSerializer.java</li>
<li>ParseRequest.java</li>
<li>Platform.java</li>
<li>PopulatedCachesTest.java</li>
<li>Present.java</li>
<li>PrimitiveSink.java</li>
<li>Queues.java</li>
<li>QueuesTest.java</li>
<li>RangeMap.java</li>
<li>RangeMapTest.java</li>
<li>RangesTest.java</li>
<li>RegularContiguousSet.java</li>
<li>RegularImmutableMultiset.java</li>
<li>RegularImmutableMultiset_CustomFieldSerializer.java</li>
<li>RegularImmutableSortedMultiset.java</li>
<li>RelationshipTester.java</li>
<li>RemovalCause.java</li>
<li>RemovalListener.java</li>
<li>RemovalListeners.java</li>
<li>RemovalNotification.java</li>
<li>SortedIterable.java</li>
<li>SortedIterables.java</li>
<li>SortedIterablesTest.java</li>
<li>SortedMultiset.java</li>
<li>SortedMultisets.java</li>
<li>TablesTransformValuesTest.java</li>
<li>TestPlatform.java</li>
<li>TestingCacheLoaders.java</li>
<li>TestingRemovalListeners.java</li>
<li>TestingWeighers.java</li>
<li>Ticker.java</li>
<li>TreeRangeSet.java</li>
<li>TreeRangeSetTest.java</li>
<li>TypeParameter.java</li>
<li>TypeParameterTest.java</li>
<li>Types.java</li>
<li>TypesTest.java</li>
<li>UncheckedExecutionException.java</li>
<li>Uninterruptibles.java</li>
<li>UnsignedInteger.java</li>
<li>UnsignedIntegerTest.java</li>
<li>UnsignedInts.java</li>
<li>UnsignedIntsTest.java</li>
<li>UnsignedLong.java</li>
<li>UnsignedLongTest.java</li>
<li>UnsignedLongs.java</li>
<li>UnsignedLongsTest.java</li>
<li>Weigher.java</li>
<li>WellBehavedMap.java</li>
<li>WellBehavedMapTest.java</li>
<li>package-info.java</li>
</ul>
<pre>/*
* Copyright (C) 2011 The Guava Authors
*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>abs__config.xml</li>
</ul>
<pre>/*
** Copyright 2009, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>abs__dimens.xml</li>
</ul>
<pre>/* //device/apps/common/assets/res/any/dimens.xml
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>org.eclipse.jdt.ui.prefs</li>
</ul>
<pre>/*\n * Copyright (c) 2012 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http\://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License\n * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n * or implied. See the License for the specific language governing permissions and limitations under\n * the License.\n */</pre>
<h3>Notices for files:</h3><ul>
<li>MenuItem.java</li>
</ul>
<pre>/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>AbstractAppEngineCallbackServlet.java</li>
<li>AbstractAppEngineFlowServlet.java</li>
<li>AbstractCallbackServlet.java</li>
<li>AbstractFlowUserServlet.java</li>
<li>AbstractHttpContent.java</li>
<li>AbstractHttpContentTest.java</li>
<li>AbstractInputStreamContent.java</li>
<li>AccessProtectedResourceTest.java</li>
<li>AccessTokenRequestTest.java</li>
<li>AndroidHttp.java</li>
<li>AndroidJsonFactory.java</li>
<li>AndroidJsonGenerator.java</li>
<li>AndroidJsonParser.java</li>
<li>ApacheHttpTransportTest.java</li>
<li>AppEngineServletUtils.java</li>
<li>ArrayTypeAdapter.java</li>
<li>ArrayTypeAdapter.java.svn-base</li>
<li>ArrayValueMap.java</li>
<li>AtomContent.java</li>
<li>AtomicLong.java</li>
<li>AuthorizationCodeRequestUrl.java</li>
<li>AuthorizationCodeRequestUrlTest.java</li>
<li>AuthorizationCodeResponseUrl.java</li>
<li>AuthorizationCodeResponseUrlTest.java</li>
<li>AuthorizationCodeTokenRequest.java</li>
<li>AuthorizationCodeTokenRequestTest.java</li>
<li>AuthorizationRequestUrl.java</li>
<li>AuthorizationRequestUrlTest.java</li>
<li>BackOffPolicy.java</li>
<li>BagOfPrimitives.java</li>
<li>BagOfPrimitives.java.svn-base</li>
<li>BagOfPrimitivesDeserializationBenchmark.java</li>
<li>BagOfPrimitivesDeserializationBenchmark.java.svn-base</li>
<li>BasicAuthentication.java</li>
<li>BasicAuthenticationTest.java</li>
<li>BearerToken.java</li>
<li>BrowserClientRequestUrl.java</li>
<li>BrowserClientRequestUrlTest.java</li>
<li>ByteArrayContent.java</li>
<li>ByteArrayContentTest.java</li>
<li>ByteCountingOutputStream.java</li>
<li>Callable.java</li>
<li>Cart.java</li>
<li>Cart.java.svn-base</li>
<li>ClientLoginResponseException.java</li>
<li>ClientParametersAuthentication.java</li>
<li>ClientParametersAuthenticationTest.java</li>
<li>CollectionTypeAdapterFactory.java</li>
<li>CollectionTypeAdapterFactory.java.svn-base</li>
<li>CollectionsDeserializationBenchmark.java</li>
<li>CollectionsDeserializationBenchmark.java.svn-base</li>
<li>ConstructorConstructor.java</li>
<li>ConstructorConstructor.java.svn-base</li>
<li>Credential.java</li>
<li>CredentialStoreRefreshListener.java</li>
<li>CredentialTest.java</li>
<li>Data.java</li>
<li>DataMapTest.java</li>
<li>DataTest.java</li>
<li>DateTypeAdapter.java</li>
<li>DateTypeAdapter.java.svn-base</li>
<li>DefaultInetAddressTypeAdapterTest.java</li>
<li>DefaultInetAddressTypeAdapterTest.java.svn-base</li>
<li>ExecutionException.java</li>
<li>ExponentialBackOffPolicy.java</li>
<li>ExponentialBackOffPolicyTest.java</li>
<li>ExposeAnnotationExclusionStrategyTest.java</li>
<li>ExposeAnnotationExclusionStrategyTest.java.svn-base</li>
<li>FieldNamingTest.java</li>
<li>FieldNamingTest.java.svn-base</li>
<li>FileContent.java</li>
<li>GenericJsonTest.java</li>
<li>GoogleAccessProtectedResource.java</li>
<li>GoogleAccessTokenRequest.java</li>
<li>GoogleAccessTokenRequestTest.java</li>
<li>GoogleAccountManager.java</li>
<li>GoogleAuthorizationCodeRequestUrl.java</li>
<li>GoogleAuthorizationCodeRequestUrlTest.java</li>
<li>GoogleAuthorizationCodeTokenRequest.java</li>
<li>GoogleAuthorizationCodeTokenRequestTest.java</li>
<li>GoogleAuthorizationRequestUrl.java</li>
<li>GoogleAuthorizationRequestUrlTest.java</li>
<li>GoogleBrowserClientRequestUrl.java</li>
<li>GoogleBrowserClientRequestUrlTest.java</li>
<li>GoogleClient.java</li>
<li>GoogleClientSecrets.java</li>
<li>GoogleClientTest.java</li>
<li>GoogleCredential.java</li>
<li>GoogleJsonError.java</li>
<li>GoogleJsonErrorTest.java</li>
<li>GoogleJsonResponseException.java</li>
<li>GoogleJsonResponseExceptionTest.java</li>
<li>GoogleOAuth2ThreeLeggedFlow.java</li>
<li>GoogleOAuth2ThreeLeggedFlowTest.java</li>
<li>GoogleOAuthConstants.java</li>
<li>GoogleOAuthHmacThreeLeggedFlow.java</li>
<li>GoogleRefreshTokenRequest.java</li>
<li>GraphAdapterBuilder.java</li>
<li>GraphAdapterBuilder.java.svn-base</li>
<li>GraphAdapterBuilderTest.java</li>
<li>GraphAdapterBuilderTest.java.svn-base</li>
<li>GsonFactory.java</li>
<li>GsonGenerator.java</li>
<li>GsonParser.java</li>
<li>GsonProguardExampleActivity.java</li>
<li>GsonProguardExampleActivity.java.svn-base</li>
<li>HttpRequestFactory.java</li>
<li>HttpRequestInitializer.java</li>
<li>HttpResponseExceptionTest.java</li>
<li>HttpStatusCodes.java</li>
<li>HttpTesting.java</li>
<li>InstalledApp.java</li>
<li>JdoPersistedCredential.java</li>
<li>JsonArrayTest.java</li>
<li>JsonArrayTest.java.svn-base</li>
<li>JsonElementReaderTest.java</li>
<li>JsonElementReaderTest.java.svn-base</li>
<li>JsonHttpClient.java</li>
<li>JsonHttpClientTest.java</li>
<li>JsonHttpRequest.java</li>
<li>JsonHttpRequestInitializer.java</li>
<li>JsonNullTest.java</li>
<li>JsonNullTest.java.svn-base</li>
<li>JsonReaderInternalAccess.java</li>
<li>JsonReaderInternalAccess.java.svn-base</li>
<li>JsonString.java</li>
<li>JsonTreeReader.java</li>
<li>JsonTreeReader.java.svn-base</li>
<li>JsonTreeWriter.java</li>
<li>JsonTreeWriter.java.svn-base</li>
<li>JsonTreeWriterTest.java</li>
<li>JsonTreeWriterTest.java.svn-base</li>
<li>LazilyParsedNumber.java</li>
<li>LazilyParsedNumber.java.svn-base</li>
<li>LineItem.java</li>
<li>LineItem.java.svn-base</li>
<li>LogContentTest.java</li>
<li>MapTypeAdapterFactory.java</li>
<li>MapTypeAdapterFactory.java.svn-base</li>
<li>MediaExponentialBackOffPolicy.java</li>
<li>MediaHttpUploader.java</li>
<li>MediaHttpUploaderProgressListener.java</li>
<li>MediaHttpUploaderTest.java</li>
<li>MediaUploadExponentialBackOffPolicy.java</li>
<li>MockHttpUnsuccessfulResponseHandler.java</li>
<li>MoreSpecificTypeSerializationTest.java</li>
<li>MoreSpecificTypeSerializationTest.java.svn-base</li>
<li>MultipartRelatedContent.java</li>
<li>MultipartRelatedContentTest.java</li>
<li>MultisetNavigationTester.java</li>
<li>NullValue.java</li>
<li>OAuth2Credential.java</li>
<li>OAuth2ThreeLeggedFlow.java</li>
<li>OAuthHmacCredential.java</li>
<li>OAuthHmacThreeLeggedFlow.java</li>
<li>ObjectTypeAdapter.java</li>
<li>ObjectTypeAdapter.java.svn-base</li>
<li>ObjectTypeAdapterTest.java</li>
<li>ObjectTypeAdapterTest.java.svn-base</li>
<li>ParseBenchmark.java</li>
<li>ParseBenchmark.java.svn-base</li>
<li>ProtoHttpContent.java</li>
<li>ProtoHttpContentTest.java</li>
<li>ProtoHttpParser.java</li>
<li>ProtoHttpParserTest.java</li>
<li>ProtocolBuffers.java</li>
<li>ProtocolBuffersTest.java</li>
<li>RangeSet.java</li>
<li>RawCollectionsExample.java</li>
<li>RawCollectionsExample.java.svn-base</li>
<li>ReflectiveTypeAdapterFactory.java</li>
<li>ReflectiveTypeAdapterFactory.java.svn-base</li>
<li>RefreshTokenRequest.java</li>
<li>RefreshTokenRequestTest.java</li>
<li>RuntimeTypeAdapterFactory.java</li>
<li>RuntimeTypeAdapterFactory.java.svn-base</li>
<li>RuntimeTypeAdapterFactoryTest.java</li>
<li>RuntimeTypeAdapterFactoryTest.java.svn-base</li>
<li>SerializationBenchmark.java</li>
<li>SerializationBenchmark.java.svn-base</li>
<li>SortedMultisetTestSuiteBuilder.java</li>
<li>SqlDateTypeAdapter.java</li>
<li>SqlDateTypeAdapter.java.svn-base</li>
<li>StreamingTypeAdaptersTest.java</li>
<li>StreamingTypeAdaptersTest.java.svn-base</li>
<li>StringPool.java</li>
<li>StringPool.java.svn-base</li>
<li>ThreeLeggedFlow.java</li>
<li>TimeTypeAdapter.java</li>
<li>TimeTypeAdapter.java.svn-base</li>
<li>TokenErrorResponse.java</li>
<li>TokenErrorResponseTest.java</li>
<li>TokenRequest.java</li>
<li>TokenRequestTest.java</li>
<li>TokenResponse.java</li>
<li>TokenResponseException.java</li>
<li>TokenResponseTest.java</li>
<li>TreeTypeAdapter.java</li>
<li>TreeTypeAdapter.java.svn-base</li>
<li>TreeTypeAdaptersTest.java</li>
<li>TreeTypeAdaptersTest.java.svn-base</li>
<li>TypeAdapter.java</li>
<li>TypeAdapter.java.svn-base</li>
<li>TypeAdapterFactory.java</li>
<li>TypeAdapterFactory.java.svn-base</li>
<li>TypeAdapterPrecedenceTest.java</li>
<li>TypeAdapterPrecedenceTest.java.svn-base</li>
<li>TypeAdapterRuntimeTypeWrapper.java</li>
<li>TypeAdapterRuntimeTypeWrapper.java.svn-base</li>
<li>TypeAdapters.java</li>
<li>TypeAdapters.java.svn-base</li>
<li>TypeHierarchyAdapterTest.java</li>
<li>TypeHierarchyAdapterTest.java.svn-base</li>
<li>Types.java</li>
<li>TypesTest.java</li>
<li>UnsafeAllocator.java</li>
<li>UnsafeAllocator.java.svn-base</li>
<li>UriTemplate.java</li>
<li>UriTemplateTest.java</li>
<li>UrlFetchTransportTest.java</li>
<li>Value.java</li>
<li>XmlTest.java</li>
<li>package-info.java</li>
<li>simple_proto.proto</li>
</ul>
<pre>/*
* Copyright (c) 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>NullOutputStream.java</li>
</ul>
<pre>/*
* Copyright (C) 2004 The Guava Authors
*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>abs__action_mode_bar.xml</li>
</ul>
<pre>/*
** Copyright 2010, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>AppendableWriter.java</li>
<li>CaseFormat.java</li>
<li>CaseFormatTest.java</li>
<li>FakeTimeLimiter.java</li>
<li>Futures.java</li>
<li>ObjectsTest.java</li>
<li>PatternFilenameFilter.java</li>
<li>PreconditionsTest.java</li>
<li>ReflectionTest.java</li>
<li>SimpleTimeLimiter.java</li>
<li>SimpleTimeLimiterTest.java</li>
<li>TimeLimiter.java</li>
<li>TypeToken.java</li>
<li>UncheckedTimeoutException.java</li>
<li>VisibleForTesting.java</li>
</ul>
<pre>/*
* Copyright (C) 2006 The Guava Authors
*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>MenuInflater.java</li>
</ul>
<pre>/*
* Copyright (C) 2006 The Android Open Source Project
* 2011 Jake Wharton
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>AbstractChainedListenableFutureTest.java</li>
<li>AbstractCheckedFuture.java</li>
<li>AbstractCollectionTestSuiteBuilder.java</li>
<li>AbstractContainerTester.java</li>
<li>AbstractImmutableSetTest.java</li>
<li>AbstractIteratorTester.java</li>
<li>AbstractListTester.java</li>
<li>AbstractMultimapAsMapImplementsMapTest.java</li>
<li>AbstractMultisetTester.java</li>
<li>AbstractQueueTester.java</li>
<li>AbstractTableReadTest.java</li>
<li>AbstractTableTest.java</li>
<li>AbstractTester.java</li>
<li>BiMapCollectionTest.java</li>
<li>BiMapGenerators.java</li>
<li>Booleans.java</li>
<li>BooleansTest.java</li>
<li>ByteArrayAsListTest.java</li>
<li>Bytes.java</li>
<li>BytesTest.java</li>
<li>CharArrayAsListTest.java</li>
<li>CharMatcher.java</li>
<li>CharMatcherTest.java</li>
<li>Chars.java</li>
<li>CharsTest.java</li>
<li>CheckedFuture.java</li>
<li>CollectionClearTester.java</li>
<li>CollectionCreationTester.java</li>
<li>CollectionFeature.java</li>
<li>CollectionIteratorTester.java</li>
<li>CollectionRemoveAllTester.java</li>
<li>CollectionRemoveTester.java</li>
<li>CollectionRetainAllTester.java</li>
<li>CollectionSize.java</li>
<li>CollectionTestSuiteBuilder.java</li>
<li>Collections2.java</li>
<li>Collections2Test.java</li>
<li>ConcurrentHashMultisetWithCslmTest.java</li>
<li>ConcurrentMapInterfaceTest.java</li>
<li>ConflictingRequirementsException.java</li>
<li>ConstrainedBiMapTest.java</li>
<li>CountingInputStreamTest.java</li>
<li>DerivedCollectionGenerators.java</li>
<li>DerivedIteratorTestSuiteBuilder.java</li>
<li>DerivedTestIteratorGenerator.java</li>
<li>DoubleArrayAsListTest.java</li>
<li>Doubles.java</li>
<li>DoublesTest.java</li>
<li>EmptyImmutableBiMap.java</li>
<li>EmptyImmutableListMultimap.java</li>
<li>EmptyImmutableMap.java</li>
<li>EmptyImmutableMultiset.java</li>
<li>EmptyImmutableSortedSet.java</li>
<li>FakeTicker.java</li>
<li>FakeTickerTest.java</li>
<li>Feature.java</li>
<li>FeatureSpecificTestSuiteBuilder.java</li>
<li>FeatureUtil.java</li>
<li>FileBackedOutputStream.java</li>
<li>FileBackedOutputStreamTest.java</li>
<li>Finalizer.java</li>
<li>FloatArrayAsListTest.java</li>
<li>Floats.java</li>
<li>FloatsTest.java</li>
<li>FluentIterable.java</li>
<li>ForMapMultimapAsMapImplementsMapTest.java</li>
<li>ForwardingConcurrentMapTest.java</li>
<li>FuturesTest.java</li>
<li>FuturesTransformAsyncFunctionTest.java</li>
<li>FuturesTransformTest.java</li>
<li>HashBasedTable.java</li>
<li>HashBasedTableTest.java</li>
<li>Hashing.java</li>
<li>HelpersTest.java</li>
<li>ImmutableBiMap.java</li>
<li>ImmutableBiMapTest.java</li>
<li>ImmutableCollection.java</li>
<li>ImmutableEntry.java</li>
<li>ImmutableListMultimap.java</li>
<li>ImmutableListMultimapTest.java</li>
<li>ImmutableMap.java</li>
<li>ImmutableMapEntrySet.java</li>
<li>ImmutableMapKeySet.java</li>
<li>ImmutableMapTest.java</li>
<li>ImmutableMapValues.java</li>
<li>ImmutableMultimap.java</li>
<li>ImmutableMultimapAsMapImplementsMapTest.java</li>
<li>ImmutableMultimapTest.java</li>
<li>ImmutableMultiset.java</li>
<li>ImmutableMultisetTest.java</li>
<li>ImmutableSetCollectionTest.java</li>
<li>ImmutableSortedSet.java</li>
<li>ImmutableSortedSetTest.java</li>
<li>InetAddresses.java</li>
<li>InetAddressesTest.java</li>
<li>IntArrayAsListTest.java</li>
<li>Ints.java</li>
<li>IntsTest.java</li>
<li>IteratorFeature.java</li>
<li>IteratorTestSuiteBuilder.java</li>
<li>Joiner.java</li>
<li>JoinerTest.java</li>
<li>ListAddAllAtIndexTester.java</li>
<li>ListAddAtIndexTester.java</li>
<li>ListCreationTester.java</li>
<li>ListEqualsTester.java</li>
<li>ListFeature.java</li>
<li>ListGetTester.java</li>
<li>ListHashCodeTester.java</li>
<li>ListIndexOfTester.java</li>
<li>ListLastIndexOfTester.java</li>
<li>ListRemoveAllTester.java</li>
<li>ListRemoveAtIndexTester.java</li>
<li>ListRemoveTester.java</li>
<li>ListRetainAllTester.java</li>
<li>ListSetTester.java</li>
<li>ListSubListTester.java</li>
<li>ListTestSuiteBuilder.java</li>
<li>ListToArrayTester.java</li>
<li>ListenableFutureTask.java</li>
<li>LongArrayAsListTest.java</li>
<li>Longs.java</li>
<li>LongsTest.java</li>
<li>MapClearTester.java</li>
<li>MapContainsKeyTester.java</li>
<li>MapContainsValueTester.java</li>
<li>MapEqualsTester.java</li>
<li>MapFeature.java</li>
<li>MapHashCodeTester.java</li>
<li>MapInterfaceTest.java</li>
<li>MapRemoveTester.java</li>
<li>MapSizeTester.java</li>
<li>MapTestSuiteBuilder.java</li>
<li>MapsTransformValuesTest.java</li>
<li>MinMaxPriorityQueueTest.java</li>
<li>MockFutureListener.java</li>
<li>MoreExecutorsTest.java</li>
<li>MultiReader.java</li>
<li>MultiReaderTest.java</li>
<li>MultimapCollectionTest.java</li>
<li>MultisetCollectionTest.java</li>
<li>MultisetReadsTester.java</li>
<li>MultisetTestSuiteBuilder.java</li>
<li>MultisetWritesTester.java</li>
<li>NewCustomTableTest.java</li>
<li>OneSizeGenerator.java</li>
<li>OneSizeTestContainerGenerator.java</li>
<li>PeekingIterator.java</li>
<li>PeekingIteratorTest.java</li>
<li>PerCollectionSizeTestSuiteBuilder.java</li>
<li>Platform.java</li>
<li>QueueElementTester.java</li>
<li>QueueOfferTester.java</li>
<li>QueuePeekTester.java</li>
<li>QueuePollTester.java</li>
<li>QueueRemoveTester.java</li>
<li>QueueTestSuiteBuilder.java</li>
<li>Range.java</li>
<li>RangeTest.java</li>
<li>RegularImmutableBiMap.java</li>
<li>RegularImmutableMap.java</li>
<li>ReserializingTestCollectionGenerator.java</li>
<li>ReserializingTestSetGenerator.java</li>
<li>ResourcesTest.java</li>
<li>SampleElements.java</li>
<li>Serialization.java</li>
<li>SetCreationTester.java</li>
<li>SetEqualsTester.java</li>
<li>SetFeature.java</li>
<li>SetGenerators.java</li>
<li>SetHashCodeTester.java</li>
<li>SetOperationsTest.java</li>
<li>SetRemoveTester.java</li>
<li>SetTestSuiteBuilder.java</li>
<li>ShortArrayAsListTest.java</li>
<li>Shorts.java</li>
<li>ShortsTest.java</li>
<li>SignedBytesTest.java</li>
<li>SingletonImmutableMap.java</li>
<li>StandardRowSortedTable.java</li>
<li>StandardTable.java</li>
<li>Stopwatch.java</li>
<li>StopwatchTest.java</li>
<li>Table.java</li>
<li>TableCollectionTest.java</li>
<li>Tables.java</li>
<li>TablesTest.java</li>
<li>TearDown.java</li>
<li>TearDownAccepter.java</li>
<li>TearDownStack.java</li>
<li>TestContainerGenerator.java</li>
<li>TestEnumMultisetGenerator.java</li>
<li>TestIntegerSortedSetGenerator.java</li>
<li>TestIteratorGenerator.java</li>
<li>TestLogHandler.java</li>
<li>TestMapEntrySetGenerator.java</li>
<li>TestMapGenerator.java</li>
<li>TestMultisetGenerator.java</li>
<li>TestQueueGenerator.java</li>
<li>TestStringCollectionGenerator.java</li>
<li>TestStringMapGenerator.java</li>
<li>TestStringMultisetGenerator.java</li>
<li>TestStringQueueGenerator.java</li>
<li>TestStringSortedMapGenerator.java</li>
<li>TestStringSortedSetGenerator.java</li>
<li>TestSubjectGenerator.java</li>
<li>TesterAnnotation.java</li>
<li>TesterRequirements.java</li>
<li>TransposedTableTest.java</li>
<li>TreeBasedTable.java</li>
<li>TreeBasedTableTest.java</li>
<li>UnmodifiableIterator.java</li>
<li>UnmodifiableIteratorTest.java</li>
<li>UnmodifiableMultimapAsMapImplementsMapTest.java</li>
<li>UnsignedBytesTest.java</li>
</ul>
<pre>/*
* Copyright (C) 2008 The Guava Authors
*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>JsonFactory.java</li>
</ul>
<pre>/*
* Copyright (c) 2010 Google Inc.J
*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>Absent_CustomFieldSerializer.java</li>
<li>AbstractBiMapTester.java</li>
<li>AbstractInvocationHandler.java</li>
<li>AbstractInvocationHandlerTest.java</li>
<li>AbstractMultimapTester.java</li>
<li>AllEqualOrdering.java</li>
<li>AnnotatedHandlerFinderTests.java</li>
<li>ArbitraryInstances.java</li>
<li>ArbitraryInstancesTest.java</li>
<li>BiMapClearTester.java</li>
<li>BiMapInverseTester.java</li>
<li>BiMapPutTester.java</li>
<li>BiMapRemoveTester.java</li>
<li>BiMapTestSuiteBuilder.java</li>
<li>Charset.java</li>
<li>CollectionSerializationEqualTester.java</li>
<li>CollectionSerializationTester.java</li>
<li>DerivedGenerator.java</li>
<li>DerivedGoogleCollectionGenerators.java</li>
<li>EmptyImmutableSortedMap.java</li>
<li>ForwardingDeque.java</li>
<li>ForwardingDequeTest.java</li>
<li>ForwardingImmutableList.java</li>
<li>ForwardingImmutableMap.java</li>
<li>ForwardingImmutableSet.java</li>
<li>ForwardingNavigableMap.java</li>
<li>ForwardingNavigableSet.java</li>
<li>ForwardingNavigableSetTest.java</li>
<li>IllegalCharsetNameException.java</li>
<li>ImmutableCollectionTest.java</li>
<li>ImmutableTypeToInstanceMap.java</li>
<li>ImmutableTypeToInstanceMapTest.java</li>
<li>ListMultimapTestSuiteBuilder.java</li>
<li>MapSerializationTester.java</li>
<li>MapsCollectionTest.java</li>
<li>MediumCharMatcher.java</li>
<li>MultimapContainsEntryTester.java</li>
<li>MultimapContainsKeyTester.java</li>
<li>MultimapContainsValueTester.java</li>
<li>MultimapGetTester.java</li>
<li>MultimapPutIterableTester.java</li>
<li>MultimapPutTester.java</li>
<li>MultimapRemoveAllTester.java</li>
<li>MultimapRemoveEntryTester.java</li>
<li>MultimapSizeTester.java</li>
<li>MultimapTestSuiteBuilder.java</li>
<li>MultisetSerializationTester.java</li>
<li>MutableTypeToInstanceMap.java</li>
<li>MutableTypeToInstanceMapTest.java</li>
<li>Present_CustomFieldSerializer.java</li>
<li>RegularImmutableAsList.java</li>
<li>RegularImmutableSortedMap.java</li>
<li>SetMultimapTestSuiteBuilder.java</li>
<li>SmallCharMatcher.java</li>
<li>SomeClassThatDoesNotUseNullable.java</li>
<li>SortedSetMultimapTestSuiteBuilder.java</li>
<li>TestBiMapGenerator.java</li>
<li>TestListMultimapGenerator.java</li>
<li>TestMultimapGenerator.java</li>
<li>TestSetMultimapGenerator.java</li>
<li>TestStringBiMapGenerator.java</li>
<li>TestStringListMultimapGenerator.java</li>
<li>TestStringSetMultimapGenerator.java</li>
<li>TransformedIterator.java</li>
<li>TransformedListIterator.java</li>
<li>TypeCapture.java</li>
<li>TypeToInstanceMap.java</li>
<li>UnsupportedCharsetException.java</li>
<li>package-info.java</li>
</ul>
<pre>/*
* Copyright (C) 2012 The Guava Authors
*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>AbstractExecutionThreadService.java</li>
<li>AbstractExecutionThreadServiceTest.java</li>
<li>AbstractIdleService.java</li>
<li>AbstractIdleServiceTest.java</li>
<li>AbstractIndexedListIterator.java</li>
<li>AbstractMultisetSetCountTester.java</li>
<li>AbstractService.java</li>
<li>AbstractServiceTest.java</li>
<li>AllEqualOrdering_CustomFieldSerializer.java</li>
<li>ArrayListMultimap_CustomFieldSerializer.java</li>
<li>ArrayTable.java</li>
<li>ArrayTableTest.java</li>
<li>AsynchronousComputationException.java</li>
<li>ByFunctionOrdering_CustomFieldSerializer.java</li>
<li>ByteArrayDataInput.java</li>
<li>ByteArrayDataOutput.java</li>
<li>ByteProcessor.java</li>
<li>CacheBuilder.java</li>
<li>CacheBuilderTest.java</li>
<li>Callables.java</li>
<li>CallablesTest.java</li>
<li>ClusterException.java</li>
<li>ComparatorOrdering_CustomFieldSerializer.java</li>
<li>ComparisonChain.java</li>
<li>ComparisonChainTest.java</li>
<li>CompoundOrdering_CustomFieldSerializer.java</li>
<li>ComputationException.java</li>
<li>Cut.java</li>
<li>DiscreteDomain.java</li>
<li>EmptyImmutableBiMap.java</li>
<li>EmptyImmutableBiMap_CustomFieldSerializer.java</li>
<li>EmptyImmutableList.java</li>
<li>EmptyImmutableListMultimap_CustomFieldSerializer.java</li>
<li>EmptyImmutableList_CustomFieldSerializer.java</li>
<li>EmptyImmutableMap.java</li>
<li>EmptyImmutableMap_CustomFieldSerializer.java</li>
<li>EmptyImmutableMultiset_CustomFieldSerializer.java</li>
<li>EmptyImmutableSet.java</li>
<li>EmptyImmutableSetMultimap.java</li>
<li>EmptyImmutableSetMultimap_CustomFieldSerializer.java</li>
<li>EmptyImmutableSet_CustomFieldSerializer.java</li>
<li>EmptyImmutableSortedMap_CustomFieldSerializer.java</li>
<li>EmptyImmutableSortedSet.java</li>
<li>EmptyImmutableSortedSet_CustomFieldSerializer.java</li>
<li>ExampleIteratorTester.java</li>
<li>ExplicitOrdering_CustomFieldSerializer.java</li>
<li>FauxveridesTest.java</li>
<li>FilesSimplifyPathTest.java</li>
<li>ForwardingCacheTest.java</li>
<li>ForwardingCollectionTest.java</li>
<li>ForwardingFuture.java</li>
<li>ForwardingImmutableCollection.java</li>
<li>ForwardingImmutableList.java</li>
<li>ForwardingImmutableList_CustomFieldSerializer.java</li>
<li>ForwardingImmutableMap.java</li>
<li>ForwardingImmutableSet.java</li>
<li>ForwardingImmutableSet_CustomFieldSerializer.java</li>
<li>ForwardingListenableFuture.java</li>
<li>ForwardingListenableFutureTest.java</li>
<li>ForwardingLoadingCacheTest.java</li>
<li>ForwardingMapTest.java</li>
<li>ForwardingMultimapTest.java</li>
<li>ForwardingMultisetTest.java</li>
<li>ForwardingService.java</li>
<li>ForwardingTable.java</li>
<li>ForwardingTableTest.java</li>
<li>GwtCompatible.java</li>
<li>GwtIncompatible.java</li>
<li>GwtPlatform.java</li>
<li>GwtSerializationDependencies.java</li>
<li>HashBasedTable_CustomFieldSerializer.java</li>
<li>HashMultimap_CustomFieldSerializer.java</li>
<li>HashMultiset_CustomFieldSerializer.java</li>
<li>Helpers.java</li>
<li>HostSpecifier.java</li>
<li>HostSpecifierTest.java</li>
<li>ImmutableAsList.java</li>
<li>ImmutableAsList_CustomFieldSerializer.java</li>
<li>ImmutableBiMap.java</li>
<li>ImmutableBiMap_CustomFieldSerializer.java</li>
<li>ImmutableClassToInstanceMap.java</li>
<li>ImmutableClassToInstanceMapTest.java</li>
<li>ImmutableEntry_CustomFieldSerializer.java</li>
<li>ImmutableEnumSet.java</li>
<li>ImmutableEnumSet_CustomFieldSerializer.java</li>
<li>ImmutableList.java</li>
<li>ImmutableListMultimap_CustomFieldSerializer.java</li>
<li>ImmutableList_CustomFieldSerializer.java</li>
<li>ImmutableMap.java</li>
<li>ImmutableMultiset_CustomFieldSerializer.java</li>
<li>ImmutableSet.java</li>
<li>ImmutableSetMultimap.java</li>
<li>ImmutableSetMultimapAsMapImplementsMapTest.java</li>
<li>ImmutableSetMultimapTest.java</li>
<li>ImmutableSetMultimap_CustomFieldSerializer.java</li>
<li>ImmutableSet_CustomFieldSerializer.java</li>
<li>ImmutableSortedAsList.java</li>
<li>ImmutableSortedMap.java</li>
<li>ImmutableSortedMapFauxverideShim.java</li>
<li>ImmutableSortedMapTest.java</li>
<li>ImmutableSortedMap_CustomFieldSerializer.java</li>
<li>ImmutableSortedMap_CustomFieldSerializerBase.java</li>
<li>ImmutableSortedSet.java</li>
<li>ImmutableSortedSetFauxverideShim.java</li>
<li>ImmutableSortedSet_CustomFieldSerializer.java</li>
<li>InternetDomainName.java</li>
<li>InternetDomainNameTest.java</li>
<li>JdkFutureAdapters.java</li>
<li>JdkFutureAdaptersTest.java</li>
<li>LegacyComparable.java</li>
<li>LexicographicalOrdering_CustomFieldSerializer.java</li>
<li>LineProcessor.java</li>
<li>LinkedHashMultimap_CustomFieldSerializer.java</li>
<li>LinkedHashMultiset_CustomFieldSerializer.java</li>
<li>LinkedListMultimap_CustomFieldSerializer.java</li>
<li>ListGenerators.java</li>
<li>ListenableFutureTaskTest.java</li>
<li>ListenableFutureTester.java</li>
<li>LocalCache.java</li>
<li>MapGenerators.java</li>
<li>MapMaker.java</li>
<li>MapMakerInternalMap.java</li>
<li>MinimalIterable.java</li>
<li>MinimalSet.java</li>
<li>Multimap_CustomFieldSerializerBase.java</li>
<li>MultisetSetCountConditionallyTester.java</li>
<li>MultisetSetCountUnconditionallyTester.java</li>
<li>Multiset_CustomFieldSerializerBase.java</li>
<li>NaturalOrdering_CustomFieldSerializer.java</li>
<li>NullsFirstOrdering_CustomFieldSerializer.java</li>
<li>NullsLastOrdering_CustomFieldSerializer.java</li>
<li>PatternFilenameFilterTest.java</li>
<li>Platform.java</li>
<li>RangeNonGwtTest.java</li>
<li>Ranges.java</li>
<li>RegularImmutableBiMap_CustomFieldSerializer.java</li>
<li>RegularImmutableList.java</li>
<li>RegularImmutableList_CustomFieldSerializer.java</li>
<li>RegularImmutableMap.java</li>
<li>RegularImmutableMap_CustomFieldSerializer.java</li>
<li>RegularImmutableSet.java</li>
<li>RegularImmutableSet_CustomFieldSerializer.java</li>
<li>RegularImmutableSortedMap_CustomFieldSerializer.java</li>
<li>RegularImmutableSortedSet.java</li>
<li>RegularImmutableSortedSet_CustomFieldSerializer.java</li>
<li>ReverseNaturalOrdering_CustomFieldSerializer.java</li>
<li>ReverseOrdering_CustomFieldSerializer.java</li>
<li>SerializableTesterTest.java</li>
<li>Service.java</li>
<li>SettableFuture.java</li>
<li>SettableFutureTest.java</li>
<li>SignedBytes.java</li>
<li>SingletonImmutableList.java</li>
<li>SingletonImmutableList_CustomFieldSerializer.java</li>
<li>SingletonImmutableMap.java</li>
<li>SingletonImmutableMap_CustomFieldSerializer.java</li>
<li>SingletonImmutableSet.java</li>
<li>SingletonImmutableSet_CustomFieldSerializer.java</li>
<li>SloppyTearDown.java</li>
<li>SortedMapGenerators.java</li>
<li>SortedMapInterfaceTest.java</li>
<li>Splitter.java</li>
<li>SplitterTest.java</li>
<li>SubMapMultimapAsMapImplementsMapTest.java</li>
<li>TestEnumMapGenerator.java</li>
<li>TestUnhashableCollectionGenerator.java</li>
<li>TestsForListsInJavaUtil.java</li>
<li>TestsForMapsInJavaUtil.java</li>
<li>TestsForQueuesInJavaUtil.java</li>
<li>TestsForSetsInJavaUtil.java</li>
<li>ToStringHelperTest.java</li>
<li>TreeBasedTable_CustomFieldSerializer.java</li>
<li>TreeMultimap_CustomFieldSerializer.java</li>
<li>TypeResolver.java</li>
<li>TypeTokenResolutionTest.java</li>
<li>UnhashableObject.java</li>
<li>UnsignedBytes.java</li>
<li>UsingToStringOrdering_CustomFieldSerializer.java</li>
</ul>
<pre>/*
* Copyright (C) 2009 The Guava Authors
*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>AbsActionBarView.java</li>
<li>AccessibilityDelegateCompat.java</li>
<li>AccessibilityDelegateCompatIcs.java</li>
<li>AccessibilityEventCompat.java</li>
<li>AccessibilityEventCompatIcs.java</li>
<li>AccessibilityManagerCompat.java</li>
<li>AccessibilityManagerCompatIcs.java</li>
<li>AccessibilityNodeInfoCompat.java</li>
<li>AccessibilityNodeInfoCompatIcs.java</li>
<li>AccessibilityRecordCompat.java</li>
<li>AccessibilityRecordCompatIcs.java</li>
<li>AccessibilityServiceInfoCompat.java</li>
<li>AccessibilityServiceInfoCompatIcs.java</li>
<li>ActionMenuPresenter.java</li>
<li>ActionProvider.java</li>
<li>ActivityChooserModel.java</li>
<li>ActivityChooserView.java</li>
<li>ActivityCompat.java</li>
<li>ActivityCompatHoneycomb.java</li>
<li>ActivityInfoCompat.java</li>
<li>AsyncTaskLoader.java</li>
<li>BackStackRecord.java</li>
<li>BaseMenuPresenter.java</li>
<li>CollapsibleActionView.java</li>
<li>CursorAdapter.java</li>
<li>CursorFilter.java</li>
<li>CursorLoader.java</li>
<li>DatabaseUtilsCompat.java</li>
<li>DebugUtils.java</li>
<li>DialogFragment.java</li>
<li>EdgeEffectCompat.java</li>
<li>EdgeEffectCompatIcs.java</li>
<li>Fragment.java</li>
<li>FragmentActivity.java</li>
<li>FragmentManager.java</li>
<li>FragmentPagerAdapter.java</li>
<li>FragmentStatePagerAdapter.java</li>
<li>FragmentTransaction.java</li>
<li>HCSparseArray.java</li>
<li>IntentCompat.java</li>
<li>KeyEventCompat.java</li>
<li>KeyEventCompatHoneycomb.java</li>
<li>ListFragment.java</li>
<li>Loader.java</li>
<li>LoaderManager.java</li>
<li>LocalBroadcastManager.java</li>
<li>LogWriter.java</li>
<li>LruCache.java</li>
<li>MenuCompat.java</li>
<li>MenuItemCompat.java</li>
<li>MenuItemCompatHoneycomb.java</li>
<li>MenuPresenter.java</li>
<li>ModernAsyncTask.java</li>
<li>MotionEventCompat.java</li>
<li>MotionEventCompatEclair.java</li>
<li>NoSaveStateFrameLayout.java</li>
<li>PagerAdapter.java</li>
<li>PagerTitleStrip.java</li>
<li>ParcelableCompat.java</li>
<li>ParcelableCompatCreatorCallbacks.java</li>
<li>ParcelableCompatHoneycombMR2.java</li>
<li>ResourceCursorAdapter.java</li>
<li>ScrollingTabContainerView.java</li>
<li>SearchViewCompat.java</li>
<li>SearchViewCompatHoneycomb.java</li>
<li>ServiceCompat.java</li>
<li>ShareActionProvider.java</li>
<li>ShareCompat.java</li>
<li>ShareCompatICS.java</li>
<li>SimpleCursorAdapter.java</li>
<li>SuperNotCalledException.java</li>
<li>TimeUtils.java</li>
<li>VelocityTrackerCompat.java</li>
<li>VelocityTrackerCompatHoneycomb.java</li>
<li>ViewCompat.java</li>
<li>ViewCompatGingerbread.java</li>
<li>ViewCompatICS.java</li>
<li>ViewConfigurationCompat.java</li>
<li>ViewConfigurationCompatFroyo.java</li>
<li>ViewGroupCompat.java</li>
<li>ViewGroupCompatIcs.java</li>
<li>ViewPager.java</li>
</ul>
<pre>/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>ActionBar.java</li>
<li>ActionBarContainer.java</li>
<li>ActionBarContextView.java</li>
<li>ActionBarImpl.java</li>
<li>ActionBarView.java</li>
<li>ActionMenu.java</li>
<li>ActionMenuItem.java</li>
<li>ActionMenuItemView.java</li>
<li>ActionMenuView.java</li>
<li>ActionMode.java</li>
<li>Animator.java</li>
<li>AnimatorListenerAdapter.java</li>
<li>AnimatorSet.java</li>
<li>FloatEvaluator.java</li>
<li>FloatKeyframeSet.java</li>
<li>IntEvaluator.java</li>
<li>IntKeyframeSet.java</li>
<li>Keyframe.java</li>
<li>KeyframeSet.java</li>
<li>MenuPopupHelper.java</li>
<li>ObjectAnimator.java</li>
<li>PropertyValuesHolder.java</li>
<li>StandaloneActionMode.java</li>
<li>TypeEvaluator.java</li>
<li>ValueAnimator.java</li>
</ul>
<pre>/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>Window.java</li>
</ul>
<pre>/*
* Copyright (C) 2006 The Android Open Source Project
* Copyright (C) 2011 Jake Wharton
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>FinalizableReferenceQueueClassLoaderUnloadingTest.java</li>
<li>FinalizableReferenceQueueTest.java</li>
<li>FunctionsTest.java</li>
<li>NullPointerTester.java</li>
<li>NullPointerTesterTest.java</li>
<li>PredicatesTest.java</li>
<li>Reflection.java</li>
</ul>
<pre>/*
* Copyright (C) 2005 The Guava Authors
*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>AndroidInteger.java</li>
<li>StringMap.java</li>
<li>StringMap.java.svn-base</li>
</ul>
<pre>/*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>sherlock_spinner_item.xml</li>
</ul>
<pre>/* //device/apps/common/assets/res/any/layout/simple_spinner_item.xml
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>AbstractAtomFeedParser.java</li>
<li>AbstractJsonFactoryTest.java</li>
<li>AbstractJsonFeedParser.java</li>
<li>AbstractOAuthGetToken.java</li>
<li>AbstractXmlHttpContent.java</li>
<li>AccessProtectedResource.java</li>
<li>AccessTokenErrorResponse.java</li>
<li>AccessTokenRequest.java</li>
<li>AccessTokenResponse.java</li>
<li>ApacheHttpRequest.java</li>
<li>ApacheHttpResponse.java</li>
<li>ApacheHttpTransport.java</li>
<li>ArrayMap.java</li>
<li>ArrayMapTest.java</li>
<li>Atom.java</li>
<li>AtomFeedParser.java</li>
<li>AtomParser.java</li>
<li>AtomPatchContent.java</li>
<li>AtomPatchRelativeToOriginalContent.java</li>
<li>AuthKeyValueParser.java</li>
<li>AuthorizationRequestUrl.java</li>
<li>AuthorizationRequestUrlTest.java</li>
<li>AuthorizationResponse.java</li>
<li>AuthorizationResponseTest.java</li>
<li>CharEscapers.java</li>
<li>ClassInfo.java</li>
<li>ClassInfoTest.java</li>
<li>ClientLogin.java</li>
<li>CommentsTest.java</li>
<li>CommentsTest.java.svn-base</li>
<li>ContentEntity.java</li>
<li>CustomizeJsonParser.java</li>
<li>DataMap.java</li>
<li>DateTime.java</li>
<li>DateTimeTest.java</li>
<li>Escaper.java</li>
<li>FieldInfo.java</li>
<li>FieldInfoTest.java</li>
<li>GZipContent.java</li>
<li>GenericData.java</li>
<li>GenericDataTest.java</li>
<li>GenericJson.java</li>
<li>GenericUrl.java</li>
<li>GenericUrlTest.java</li>
<li>GenericXml.java</li>
<li>GenericXmlTest.java</li>
<li>GoogleAtom.java</li>
<li>GoogleAtomTest.java</li>
<li>GoogleHeaders.java</li>
<li>GoogleJsonRpcHttpTransport.java</li>
<li>GoogleOAuthAuthorizeTemporaryTokenUrl.java</li>
<li>GoogleOAuthDomainWideDelegation.java</li>
<li>GoogleOAuthGetAccessToken.java</li>
<li>GoogleOAuthGetTemporaryToken.java</li>
<li>GoogleUrl.java</li>
<li>GsonFactoryTest.java</li>
<li>HttpContent.java</li>
<li>HttpExecuteInterceptor.java</li>
<li>HttpHeaders.java</li>
<li>HttpHeadersTest.java</li>
<li>HttpMethod.java</li>
<li>HttpParser.java</li>
<li>HttpPatch.java</li>
<li>HttpRequest.java</li>
<li>HttpRequestTest.java</li>
<li>HttpResponse.java</li>
<li>HttpResponseException.java</li>
<li>HttpResponseTest.java</li>
<li>HttpTransport.java</li>
<li>HttpUnsuccessfulResponseHandler.java</li>
<li>InputStreamContent.java</li>
<li>JacksonFactory.java</li>
<li>JacksonFactoryTest.java</li>
<li>JacksonGenerator.java</li>
<li>JacksonParser.java</li>
<li>Json.java</li>
<li>JsonCContent.java</li>
<li>JsonCParser.java</li>
<li>JsonEncoding.java</li>
<li>JsonFeedParser.java</li>
<li>JsonGenerator.java</li>
<li>JsonHttpContent.java</li>
<li>JsonHttpParser.java</li>
<li>JsonMultiKindFeedParser.java</li>
<li>JsonParser.java</li>
<li>JsonReader.java</li>
<li>JsonReader.java.svn-base</li>
<li>JsonReaderTest.java</li>
<li>JsonReaderTest.java.svn-base</li>
<li>JsonRpcRequest.java</li>
<li>JsonScope.java</li>
<li>JsonScope.java.svn-base</li>
<li>JsonSyntaxException.java</li>
<li>JsonSyntaxException.java.svn-base</li>
<li>JsonToken.java</li>
<li>JsonToken.java.svn-base</li>
<li>JsonWriter.java</li>
<li>JsonWriter.java.svn-base</li>
<li>JsonWriterTest.java</li>
<li>JsonWriterTest.java.svn-base</li>
<li>Key.java</li>
<li>LogContent.java</li>
<li>LowLevelHttpRequest.java</li>
<li>LowLevelHttpResponse.java</li>
<li>MalformedJsonException.java</li>
<li>MalformedJsonException.java.svn-base</li>
<li>MapAsArrayTypeAdapterTest.java</li>
<li>MapAsArrayTypeAdapterTest.java.svn-base</li>
<li>MethodOverride.java</li>
<li>MethodOverrideTest.java</li>
<li>MixedStreamTest.java</li>
<li>MixedStreamTest.java.svn-base</li>
<li>MockHttpContent.java</li>
<li>MockHttpTransport.java</li>
<li>MockLowLevelHttpRequest.java</li>
<li>MockLowLevelHttpResponse.java</li>
<li>MultiKindFeedParser.java</li>
<li>NetHttpRequest.java</li>
<li>NetHttpResponse.java</li>
<li>NetHttpTransport.java</li>
<li>OAuthAuthorizeTemporaryTokenUrl.java</li>
<li>OAuthCallbackUrl.java</li>
<li>OAuthCredentialsResponse.java</li>
<li>OAuthGetAccessToken.java</li>
<li>OAuthGetTemporaryToken.java</li>
<li>OAuthHmacSigner.java</li>
<li>OAuthParameters.java</li>
<li>OAuthParametersTest.java</li>
<li>OAuthRsaSigner.java</li>
<li>OAuthSigner.java</li>
<li>PercentEscaper.java</li>
<li>Platform.java</li>
<li>ProtoTypeAdapter.java</li>
<li>ProtoTypeAdapter.java.svn-base</li>
<li>ProtosWithComplexAndRepeatedFieldsTest.java</li>
<li>ProtosWithComplexAndRepeatedFieldsTest.java.svn-base</li>
<li>ProtosWithPrimitiveTypesTest.java</li>
<li>ProtosWithPrimitiveTypesTest.java.svn-base</li>
<li>RawSerializationTest.java</li>
<li>RawSerializationTest.java.svn-base</li>
<li>SafeTreeMapTest.java</li>
<li>SafeTreeSetTest.java</li>
<li>Streams.java</li>
<li>Streams.java.svn-base</li>
<li>StringUtilsTest.java</li>
<li>TearDownStackTest.java</li>
<li>TypeTokenTest.java</li>
<li>TypeTokenTest.java.svn-base</li>
<li>TypeVariableTest.java</li>
<li>TypeVariableTest.java.svn-base</li>
<li>UnicodeEscaper.java</li>
<li>UrlEncodedContent.java</li>
<li>UrlEncodedContentTest.java</li>
<li>UrlEncodedParser.java</li>
<li>UrlEncodedParserTest.java</li>
<li>UrlFetchRequest.java</li>
<li>UrlFetchResponse.java</li>
<li>UrlFetchTransport.java</li>
<li>Xml.java</li>
<li>XmlHttpContent.java</li>
<li>XmlHttpParser.java</li>
<li>XmlNamespaceDictionary.java</li>
<li>XmlNamespaceDictionaryTest.java</li>
<li>XmlObjectParser.java</li>
<li>package-info.java</li>
</ul>
<pre>/*
* Copyright (c) 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li></li>
</ul>
<pre>Google Gson
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2008-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.
</pre>
<h3>Notices for files:</h3><ul>
<li>$Gson$Preconditions.java</li>
<li>$Gson$Preconditions.java.svn-base</li>
<li>$Gson$Types.java</li>
<li>$Gson$Types.java.svn-base</li>
<li>ArrayTest.java</li>
<li>ArrayTest.java.svn-base</li>
<li>CircularReferenceTest.java</li>
<li>CircularReferenceTest.java.svn-base</li>
<li>CollectionTest.java</li>
<li>CollectionTest.java.svn-base</li>
<li>ConcurrencyTest.java</li>
<li>ConcurrencyTest.java.svn-base</li>
<li>CustomDeserializerTest.java</li>
<li>CustomDeserializerTest.java.svn-base</li>
<li>CustomTypeAdaptersTest.java</li>
<li>CustomTypeAdaptersTest.java.svn-base</li>
<li>DefaultDateTypeAdapter.java</li>
<li>DefaultDateTypeAdapter.java.svn-base</li>
<li>DefaultDateTypeAdapterTest.java</li>
<li>DefaultDateTypeAdapterTest.java.svn-base</li>
<li>DefaultMapJsonSerializerTest.java</li>
<li>DefaultMapJsonSerializerTest.java.svn-base</li>
<li>DefaultTypeAdaptersTest.java</li>
<li>DefaultTypeAdaptersTest.java.svn-base</li>
<li>EnumTest.java</li>
<li>EnumTest.java.svn-base</li>
<li>EscapingTest.java</li>
<li>EscapingTest.java.svn-base</li>
<li>Excluder.java</li>
<li>Excluder.java.svn-base</li>
<li>ExclusionStrategy.java</li>
<li>ExclusionStrategy.java.svn-base</li>
<li>ExclusionStrategyFunctionalTest.java</li>
<li>ExclusionStrategyFunctionalTest.java.svn-base</li>
<li>Expose.java</li>
<li>Expose.java.svn-base</li>
<li>ExposeFieldsTest.java</li>
<li>ExposeFieldsTest.java.svn-base</li>
<li>FeatureEnumTest.java</li>
<li>FeatureUtilTest.java</li>
<li>FieldExclusionTest.java</li>
<li>FieldExclusionTest.java.svn-base</li>
<li>FieldNamingPolicy.java</li>
<li>FieldNamingPolicy.java.svn-base</li>
<li>FieldNamingStrategy.java</li>
<li>FieldNamingStrategy.java.svn-base</li>
<li>FluentIterableTest.java</li>
<li>GenericArrayTypeTest.java</li>
<li>GenericArrayTypeTest.java.svn-base</li>
<li>Gson.java</li>
<li>Gson.java.svn-base</li>
<li>GsonBuilder.java</li>
<li>GsonBuilder.java.svn-base</li>
<li>GsonBuilderTest.java</li>
<li>GsonBuilderTest.java.svn-base</li>
<li>GsonTypeAdapterTest.java</li>
<li>GsonTypeAdapterTest.java.svn-base</li>
<li>InnerClassExclusionStrategyTest.java</li>
<li>InnerClassExclusionStrategyTest.java.svn-base</li>
<li>InstanceCreator.java</li>
<li>InstanceCreator.java.svn-base</li>
<li>InterfaceTest.java</li>
<li>InterfaceTest.java.svn-base</li>
<li>InternationalizationTest.java</li>
<li>InternationalizationTest.java.svn-base</li>
<li>IteratorTesterTest.java</li>
<li>JsonArray.java</li>
<li>JsonArray.java.svn-base</li>
<li>JsonDeserializationContext.java</li>
<li>JsonDeserializationContext.java.svn-base</li>
<li>JsonDeserializer.java</li>
<li>JsonDeserializer.java.svn-base</li>
<li>JsonElement.java</li>
<li>JsonElement.java.svn-base</li>
<li>JsonIOException.java</li>
<li>JsonIOException.java.svn-base</li>
<li>JsonNull.java</li>
<li>JsonNull.java.svn-base</li>
<li>JsonObject.java</li>
<li>JsonObject.java.svn-base</li>
<li>JsonObjectTest.java</li>
<li>JsonObjectTest.java.svn-base</li>
<li>JsonParseException.java</li>
<li>JsonParseException.java.svn-base</li>
<li>JsonParserTest.java</li>
<li>JsonParserTest.java.svn-base</li>
<li>JsonPrimitive.java</li>
<li>JsonPrimitive.java.svn-base</li>
<li>JsonPrimitiveTest.java</li>
<li>JsonPrimitiveTest.java.svn-base</li>
<li>JsonSerializationContext.java</li>
<li>JsonSerializationContext.java.svn-base</li>
<li>JsonSerializer.java</li>
<li>JsonSerializer.java.svn-base</li>
<li>MapTest.java</li>
<li>MapTest.java.svn-base</li>
<li>MapTestSuiteBuilderTests.java</li>
<li>MockExclusionStrategy.java</li>
<li>MockExclusionStrategy.java.svn-base</li>
<li>MoreAsserts.java</li>
<li>MoreAsserts.java.svn-base</li>
<li>NamingPolicyTest.java</li>
<li>NamingPolicyTest.java.svn-base</li>
<li>NullObjectAndFieldTest.java</li>
<li>NullObjectAndFieldTest.java.svn-base</li>
<li>ObjectConstructor.java</li>
<li>ObjectConstructor.java.svn-base</li>
<li>ObjectTest.java</li>
<li>ObjectTest.java.svn-base</li>
<li>ParameterizedTypeFixtures.java</li>
<li>ParameterizedTypeFixtures.java.svn-base</li>
<li>ParameterizedTypeTest.java</li>
<li>ParameterizedTypeTest.java.svn-base</li>
<li>ParameterizedTypesTest.java</li>
<li>ParameterizedTypesTest.java.svn-base</li>
<li>PerformanceTest.java</li>
<li>PerformanceTest.java.svn-base</li>
<li>PrettyPrintingTest.java</li>
<li>PrettyPrintingTest.java.svn-base</li>
<li>PrimitiveCharacterTest.java</li>
<li>PrimitiveCharacterTest.java.svn-base</li>
<li>PrimitiveTest.java</li>
<li>PrimitiveTest.java.svn-base</li>
<li>PrimitiveTypeAdapter.java</li>
<li>PrimitiveTypeAdapter.java.svn-base</li>
<li>Primitives.java</li>
<li>Primitives.java.svn-base</li>
<li>PrintFormattingTest.java</li>
<li>PrintFormattingTest.java.svn-base</li>
<li>ReadersWritersTest.java</li>
<li>ReadersWritersTest.java.svn-base</li>
<li>SecurityTest.java</li>
<li>SecurityTest.java.svn-base</li>
<li>SerializedName.java</li>
<li>SerializedName.java.svn-base</li>
<li>Since.java</li>
<li>Since.java.svn-base</li>
<li>TestLogHandlerTest.java</li>
<li>TestTypes.java</li>
<li>TestTypes.java.svn-base</li>
<li>TypeToken.java</li>
<li>TypeToken.java.svn-base</li>
<li>UncategorizedTest.java</li>
<li>UncategorizedTest.java.svn-base</li>
<li>Until.java</li>
<li>Until.java.svn-base</li>
<li>VersionExclusionStrategyTest.java</li>
<li>VersionExclusionStrategyTest.java.svn-base</li>
<li>VersioningTest.java</li>
<li>VersioningTest.java.svn-base</li>
</ul>
<pre>/*
* Copyright (C) 2008 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>jackson-core-asl.jar</li>
</ul>
<pre>/* Jackson JSON-processor.
*
* Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi
*
* Licensed under the License specified in file LICENSE, included with
* the source code and binary code bundles.
* You may not use this file except in compliance with the License.
*
* 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.
*/
------- LICENSE --------
This copy of Jackson JSON processor is licensed under the
Apache (Software) License, version 2.0 ("the License").
See the License for details about distribution rights, and the
specific rights regarding derivate works.
You may obtain a copy of the License at:
http://www.apache.org/licenses/
A copy is also included with both the the downloadable source code package
and jar that contains class bytecodes, as file "ASL 2.0". In both cases,
that file should be located next to this file: in source distribution
the location should be "release-notes/asl"; and in jar "META-INF/"
</pre>
<h3>Notices for files:</h3><ul>
<li>IcsAbsSpinner.java</li>
<li>IcsAdapterView.java</li>
<li>IcsProgressBar.java</li>
<li>ListMenuItemView.java</li>
<li>Menu.java</li>
<li>MenuBuilder.java</li>
<li>MenuItemImpl.java</li>
<li>MenuView.java</li>
<li>SubMenuBuilder.java</li>
</ul>
<pre>/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>NullOutputStreamTest.java</li>
</ul>
<pre>/*
* Copyright (C) 2002 The Guava Authors
*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>abs__bools.xml</li>
<li>abs__dialog_title_holo.xml</li>
<li>abs__screen_simple_overlay_action_mode.xml</li>
</ul>
<pre>/*
** Copyright 2011, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>sherlock_spinner_dropdown_item.xml</li>
</ul>
<pre>/* //device/apps/common/assets/res/any/layout/simple_spinner_item.xml
**
** Copyright 2008, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>AbstractAppEngineAuthorizationCodeCallbackServlet.java</li>
<li>AbstractAppEngineAuthorizationCodeServlet.java</li>
<li>AbstractAuthorizationCodeCallbackServlet.java</li>
<li>AbstractAuthorizationCodeServlet.java</li>
<li>AppEngineCredentialStore.java</li>
<li>AppIdentityCredential.java</li>
<li>AuthorizationCodeFlow.java</li>
<li>Base64.java</li>
<li>BatchCallback.java</li>
<li>BatchRequest.java</li>
<li>BatchUnparsedResponse.java</li>
<li>Clock.java</li>
<li>ClockTest.java</li>
<li>CredentialRefreshListener.java</li>
<li>CredentialStore.java</li>
<li>DelegateTypeAdapterTest.java</li>
<li>DelegateTypeAdapterTest.java.svn-base</li>
<li>FixedClock.java</li>
<li>FixedClockTest.java</li>
<li>GoogleAuthorizationCodeFlow.java</li>
<li>GoogleAuthorizationCodeFlowTest.java</li>
<li>GoogleIdToken.java</li>
<li>GoogleIdTokenVerifier.java</li>
<li>GoogleIdTokenVerifierTest.java</li>
<li>GoogleJsonErrorContainer.java</li>
<li>GoogleJsonErrorContainerTest.java</li>
<li>GoogleKeyInitializer.java</li>
<li>GoogleKeyInitializerTest.java</li>
<li>GoogleTokenResponse.java</li>
<li>HttpMediaType.java</li>
<li>HttpMediaTypeTest.java</li>
<li>IdTokenResponse.java</li>
<li>JdoCredentialStore.java</li>
<li>JsonBatchCallback.java</li>
<li>JsonHttpRequestTest.java</li>
<li>JsonObjectParser.java</li>
<li>JsonObjectParserTest.java</li>
<li>JsonParserTest.java</li>
<li>JsonWebSignature.java</li>
<li>JsonWebToken.java</li>
<li>JsonWebTokenTest.java</li>
<li>LoggingByteArrayOutputStream.java</li>
<li>LoggingInputStream.java</li>
<li>LoggingOutputStream.java</li>
<li>LongAdder.java</li>
<li>MediaHttpDownloader.java</li>
<li>MediaHttpDownloaderProgressListener.java</li>
<li>MediaHttpDownloaderTest.java</li>
<li>MemoryCredentialStore.java</li>
<li>MemoryPersistedCredential.java</li>
<li>MultipartMixedContent.java</li>
<li>MultipartMixedContentTest.java</li>
<li>NetHttpResponseTest.java</li>
<li>NetHttpTransportTest.java</li>
<li>OAuthHmacSignerTest.java</li>
<li>OAuthRsaSignerTest.java</li>
<li>ObjectParser.java</li>
<li>PrivateKeys.java</li>
<li>ProtoObjectParser.java</li>
<li>RsaSHA256Signer.java</li>
<li>RsaSHA256SignerTest.java</li>
<li>StringUtils.java</li>
<li>UrlFetchRequest.java</li>
<li>UrlFetchResponse.java</li>
<li>UrlFetchTransport.java</li>
<li>UrlFetchTransportTest.java</li>
<li>package-info.java</li>
</ul>
<pre>/*
* Copyright (c) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>abs__screen_simple.xml</li>
</ul>
<pre>/* //device/apps/common/assets/res/layout/screen_simple.xml
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>protobuf-java-lite.jar</li>
</ul>
<pre>Protocol Buffer Java API
BSD License:
Copyright (c) 2007, Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
</pre>
<h3>Notices for files:</h3><ul>
<li>AbstractLinkedIterator.java</li>
<li>AbstractSequentialIterator.java</li>
<li>AbstractSequentialIteratorTest.java</li>
<li>Ascii.java</li>
<li>AsciiTest.java</li>
<li>Atomics.java</li>
<li>AtomicsTest.java</li>
<li>BaseComparable.java</li>
<li>Beta.java</li>
<li>ComputingConcurrentHashMap.java</li>
<li>ContiguousSet.java</li>
<li>DerivedComparable.java</li>
<li>DiscreteDomains.java</li>
<li>Equivalence.java</li>
<li>Equivalences.java</li>
<li>ForwardingBlockingQueue.java</li>
<li>ForwardingListMultimap.java</li>
<li>ForwardingListMultimapTest.java</li>
<li>ForwardingSetMultimap.java</li>
<li>ForwardingSetMultimapTest.java</li>
<li>ForwardingSortedSetMultimap.java</li>
<li>ForwardingSortedSetMultimapTest.java</li>
<li>ForwardingSortedSetTest.java</li>
<li>GenericMapMaker.java</li>
<li>ListeningExecutorService.java</li>
<li>LittleEndianDataOutputStreamTest.java</li>
<li>MinMaxPriorityQueue.java</li>
<li>Monitor.java</li>
<li>MultimapsTransformValuesAsMapTest.java</li>
<li>NavigableMapNavigationTester.java</li>
<li>NavigableMapTestSuiteBuilder.java</li>
<li>NavigableSetNavigationTester.java</li>
<li>NavigableSetTestSuiteBuilder.java</li>
<li>RegularImmutableAsList_CustomFieldSerializer.java</li>
<li>RowSortedTable.java</li>
<li>SafeTreeMap.java</li>
<li>SafeTreeSet.java</li>
<li>SortedLists.java</li>
<li>SortedListsTest.java</li>
<li>SortedMapDifference.java</li>
<li>SortedMapNavigationTester.java</li>
<li>SortedMapTestSuiteBuilder.java</li>
<li>SortedSetNavigationTester.java</li>
<li>SortedSetTestSuiteBuilder.java</li>
<li>Strings.java</li>
<li>StringsTest.java</li>
<li>TestModuleEntryPoint.java</li>
<li>ThreadFactoryBuilder.java</li>
<li>ThreadFactoryBuilderTest.java</li>
<li>TransformedImmutableList.java</li>
<li>TransformedImmutableListTest.java</li>
<li>UncaughtExceptionHandlers.java</li>
<li>UncaughtExceptionHandlersTest.java</li>
<li>UnmodifiableListIterator.java</li>
<li>UnmodifiableListIteratorTest.java</li>
<li>package-info.java</li>
</ul>
<pre>/*
* Copyright (C) 2010 The Guava Authors
*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>IcsSpinner.java</li>
<li>SubMenu.java</li>
</ul>
<pre>/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>EquivalenceTest.java</li>
<li>EquivalencesTest.java</li>
</ul>
<pre>/*
* Copyright (C) 2010 The Guava Authors
*
* 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
* diOBJECTibuted under the License is diOBJECTibuted 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.
*/</pre>
</body></html>
| zzxxasp-key | android/assets/licenses.html | HTML | asf20 | 97,984 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.android.plus;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;
/**
* Stub until the release of <a href="https://developers.google.com/android/google-play-services/">
* Google Play Services.</a>
*/
public final class PlusOneButton extends Button {
public PlusOneButton(Context context) {
super(context);
}
public PlusOneButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PlusOneButton(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public void setUrl(String url) {
}
public void setSize(Size size) {
}
public enum Size {
SMALL, MEDIUM, TALL, STANDARD
}
}
| zzxxasp-key | android/src/com/google/api/android/plus/PlusOneButton.java | Java | asf20 | 1,391 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.android.plus;
import android.content.Context;
/**
* Stub until the release of <a href="https://developers.google.com/android/google-play-services/">
* Google Play Services.</a>
*/
public final class GooglePlus {
public static GooglePlus initialize(Context context, String apiKey, String clientId) {
return new GooglePlus();
}
}
| zzxxasp-key | android/src/com/google/api/android/plus/GooglePlus.java | Java | asf20 | 969 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.Room;
import com.google.android.apps.iosched.io.model.Rooms;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Handler that parses room JSON data into a list of content provider operations.
*/
public class RoomsHandler extends JSONHandler {
private static final String TAG = makeLogTag(RoomsHandler.class);
public RoomsHandler(Context context) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json) throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
Rooms roomsJson = new Gson().fromJson(json, Rooms.class);
int noOfRooms = roomsJson.rooms.length;
for (int i = 0; i < noOfRooms; i++) {
parseRoom(roomsJson.rooms[i], batch);
}
return batch;
}
private static void parseRoom(Room room, ArrayList<ContentProviderOperation> batch) {
ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Rooms.CONTENT_URI));
builder.withValue(ScheduleContract.Rooms.ROOM_ID, room.id);
builder.withValue(ScheduleContract.Rooms.ROOM_NAME, room.name);
builder.withValue(ScheduleContract.Rooms.ROOM_FLOOR, room.floor);
batch.add(builder.build());
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/RoomsHandler.java | Java | asf20 | 2,373 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
import com.google.gson.annotations.SerializedName;
public class Event {
public String room;
public String end_date;
public String level;
public String[] track;
public String start_time;
public String title;
@SerializedName("abstract")
public String _abstract;
public String start_date;
public String attending;
public String has_streaming;
public String end_time;
public String livestream_url;
public String[] youtube_url;
public String id;
public String tags;
public String[] speaker_id;
public String[] prereq;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/Event.java | Java | asf20 | 1,237 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class MyScheduleItem {
public String date;
public String time;
public String role;
public Location[] locations;
public String title;
public String session_id;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/MyScheduleItem.java | Java | asf20 | 841 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class SandboxCompany {
public String company_name;
public String company_description;
public String[] exhibitors;
public String logo_img;
public String product_description;
public String product_pod;
public String website;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/SandboxCompany.java | Java | asf20 | 908 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class AnnouncementsResponse extends GenericResponse {
public Announcement[] announcements;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/AnnouncementsResponse.java | Java | asf20 | 752 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class SearchSuggestions {
public String[] words;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/SearchSuggestions.java | Java | asf20 | 710 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Tracks {
Track[] track;
public Track[] getTrack() {
return track;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/Tracks.java | Java | asf20 | 752 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Errors {
public Error[] errors;
public String code;
public String message;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/Errors.java | Java | asf20 | 751 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Speaker {
public String display_name;
public String bio;
public String plusone_url;
public String thumbnail_url;
public String user_id;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/Speaker.java | Java | asf20 | 819 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class TimeSlot {
public String start;
public String end;
public String title;
public String type;
public String meta;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/TimeSlot.java | Java | asf20 | 795 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class EventSlots {
public Day[] day;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/EventSlots.java | Java | asf20 | 701 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Error {
public String domain;
public String reason;
public String message;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/Error.java | Java | asf20 | 751 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Location {
public String location;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/Location.java | Java | asf20 | 703 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Room {
public String id;
public String name;
public String floor;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/Room.java | Java | asf20 | 742 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
import com.google.gson.annotations.SerializedName;
public class Track {
public String name;
public String color;
@SerializedName("abstract")
public String _abstract;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/Track.java | Java | asf20 | 833 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Announcement {
public String date;
public String[] tracks;
public String title;
public String link;
public String summary;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/Announcement.java | Java | asf20 | 806 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class SessionsResult {
public Event[] events;
public String event_type;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/SessionsResult.java | Java | asf20 | 737 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
import com.google.gson.JsonElement;
public class GenericResponse {
public JsonElement error;
//
// public void checkResponseForAuthErrorsAndThrow() throws IOException {
// if (error != null && error.isJsonObject()) {
// JsonObject errorObject = error.getAsJsonObject();
// int errorCode = errorObject.get("code").getAsInt();
// String errorMessage = errorObject.get("message").getAsString();
// if (400 <= errorCode && errorCode < 500) {
// // The API currently only returns 400 unfortunately.
// throw ...
// }
// }
// }
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/GenericResponse.java | Java | asf20 | 1,282 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
import com.google.gson.annotations.SerializedName;
public class SpeakersResponse extends GenericResponse {
@SerializedName("devsite_speakers")
public Speaker[] speakers;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/SpeakersResponse.java | Java | asf20 | 830 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Day {
public String date;
public TimeSlot[] slot;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/Day.java | Java | asf20 | 721 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Rooms {
public Room[] rooms;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/Rooms.java | Java | asf20 | 697 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class ErrorResponse {
public Errors error;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/ErrorResponse.java | Java | asf20 | 705 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class MyScheduleResponse extends GenericResponse {
public MyScheduleItem[] schedule_list;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/MyScheduleResponse.java | Java | asf20 | 753 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class EditMyScheduleResponse {
public String message;
public boolean success;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/EditMyScheduleResponse.java | Java | asf20 | 745 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class SessionsResponse extends GenericResponse {
public SessionsResult[] result;
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/model/SessionsResponse.java | Java | asf20 | 743 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.MyScheduleItem;
import com.google.android.apps.iosched.io.model.MyScheduleResponse;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Handler that parses "my schedule" JSON data into a list of content provider operations.
*/
public class MyScheduleHandler extends JSONHandler {
private static final String TAG = makeLogTag(MyScheduleHandler.class);
public MyScheduleHandler(Context context) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
MyScheduleResponse response = new Gson().fromJson(json, MyScheduleResponse.class);
if (response.error == null) {
LOGI(TAG, "Updating user's schedule");
if (response.schedule_list != null) {
// Un-star all sessions first
batch.add(ContentProviderOperation
.newUpdate(ScheduleContract.addCallerIsSyncAdapterParameter(
Sessions.CONTENT_URI))
.withValue(Sessions.SESSION_STARRED, 0)
.build());
// Star only those sessions in the "my schedule" response
for (MyScheduleItem item : response.schedule_list) {
batch.add(ContentProviderOperation
.newUpdate(ScheduleContract.addCallerIsSyncAdapterParameter(
Sessions.buildSessionUri(item.session_id)))
.withValue(Sessions.SESSION_STARRED, 1)
.build());
}
}
}
return batch;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/MyScheduleHandler.java | Java | asf20 | 2,876 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.SearchSuggestions;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.app.SearchManager;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
/**
* Handler that parses search suggestions JSON data into a list of content provider operations.
*/
public class SearchSuggestHandler extends JSONHandler {
public SearchSuggestHandler(Context context) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
SearchSuggestions suggestions = new Gson().fromJson(json, SearchSuggestions.class);
if (suggestions.words != null) {
// Clear out suggestions
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.SearchSuggest.CONTENT_URI))
.build());
// Rebuild suggestions
for (String word : suggestions.words) {
batch.add(ContentProviderOperation
.newInsert(ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.SearchSuggest.CONTENT_URI))
.withValue(SearchManager.SUGGEST_COLUMN_TEXT_1, word)
.build());
}
}
return batch;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/SearchSuggestHandler.java | Java | asf20 | 2,323 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import java.io.IOException;
/**
* General {@link IOException} that indicates a problem occurred while parsing or applying a {@link
* JSONHandler}.
*/
public class HandlerException extends IOException {
public HandlerException() {
super();
}
public HandlerException(String message) {
super(message);
}
public HandlerException(String message, Throwable cause) {
super(message);
initCause(cause);
}
@Override
public String toString() {
if (getCause() != null) {
return getLocalizedMessage() + ": " + getCause();
} else {
return getLocalizedMessage();
}
}
public static class UnauthorizedException extends HandlerException {
public UnauthorizedException() {
}
public UnauthorizedException(String message) {
super(message);
}
public UnauthorizedException(String message, Throwable cause) {
super(message, cause);
}
}
public static class NoDevsiteProfileException extends HandlerException {
public NoDevsiteProfileException() {
}
public NoDevsiteProfileException(String message) {
super(message);
}
public NoDevsiteProfileException(String message, Throwable cause) {
super(message, cause);
}
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/HandlerException.java | Java | asf20 | 2,022 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.io.model.Event;
import com.google.android.apps.iosched.io.model.SessionsResponse;
import com.google.android.apps.iosched.io.model.SessionsResult;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.util.Lists;
import com.google.android.apps.iosched.util.ParserUtils;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.text.format.Time;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
import static com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers;
import static com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId;
/**
* Handler that parses session JSON data into a list of content provider operations.
*/
public class SessionsHandler extends JSONHandler {
private static final String TAG = makeLogTag(SessionsHandler.class);
private static final String BASE_SESSION_URL
= "https://developers.google.com/events/io/sessions/";
private static final String EVENT_TYPE_KEYNOTE = "keynote";
private static final String EVENT_TYPE_CODELAB = "codelab";
private static final int PARSE_FLAG_FORCE_SCHEDULE_REMOVE = 1;
private static final int PARSE_FLAG_FORCE_SCHEDULE_ADD = 2;
private static final Time sTime = new Time();
private static final Pattern sRemoveSpeakerIdPrefixPattern = Pattern.compile(".*//");
private boolean mLocal;
private boolean mThrowIfNoAuthToken;
public SessionsHandler(Context context, boolean local, boolean throwIfNoAuthToken) {
super(context);
mLocal = local;
mThrowIfNoAuthToken = throwIfNoAuthToken;
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
SessionsResponse response = new Gson().fromJson(json, SessionsResponse.class);
int numEvents = 0;
if (response.result != null) {
numEvents = response.result[0].events.length;
}
if (numEvents > 0) {
LOGI(TAG, "Updating sessions data");
// by default retain locally starred if local sync
boolean retainLocallyStarredSessions = mLocal;
if (response.error != null && response.error.isJsonPrimitive()) {
String errorMessageLower = response.error.getAsString().toLowerCase();
if (!mLocal && (errorMessageLower.contains("no profile")
|| errorMessageLower.contains("no auth token"))) {
// There was some authentication issue; retain locally starred sessions.
retainLocallyStarredSessions = true;
LOGW(TAG, "The user has no developers.google.com profile or this call is "
+ "not authenticated. Retaining locally starred sessions.");
}
if (mThrowIfNoAuthToken && errorMessageLower.contains("no auth token")) {
throw new HandlerException.UnauthorizedException("No auth token but we tried "
+ "authenticating. Need to invalidate the auth token.");
}
}
Set<String> starredSessionIds = new HashSet<String>();
if (retainLocallyStarredSessions) {
// Collect the list of current starred sessions
Cursor starredSessionsCursor = mContext.getContentResolver().query(
Sessions.CONTENT_STARRED_URI,
new String[]{ScheduleContract.Sessions.SESSION_ID},
null, null, null);
while (starredSessionsCursor.moveToNext()) {
starredSessionIds.add(starredSessionsCursor.getString(0));
}
starredSessionsCursor.close();
}
// Clear out existing sessions
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
Sessions.CONTENT_URI))
.build());
// Maintain a list of created block IDs
Set<String> blockIds = new HashSet<String>();
for (SessionsResult result : response.result) {
for (Event event : result.events) {
int flags = 0;
if (retainLocallyStarredSessions) {
flags = (starredSessionIds.contains(event.id)
? PARSE_FLAG_FORCE_SCHEDULE_ADD
: PARSE_FLAG_FORCE_SCHEDULE_REMOVE);
}
String sessionId = event.id;
if (TextUtils.isEmpty(sessionId)) {
LOGW(TAG, "Found session with empty ID in API response.");
continue;
}
// Session title
String sessionTitle = event.title;
if (EVENT_TYPE_CODELAB.equals(result.event_type)) {
sessionTitle = mContext.getString(
R.string.codelab_title_template, sessionTitle);
}
// Whether or not it's in the schedule
boolean inSchedule = "Y".equals(event.attending);
if ((flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0
|| (flags & PARSE_FLAG_FORCE_SCHEDULE_REMOVE) != 0) {
inSchedule = (flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0;
}
if (EVENT_TYPE_KEYNOTE.equals(result.event_type)) {
// Keynotes are always in your schedule.
inSchedule = true;
}
// Re-order session tracks so that Code Lab is last
if (event.track != null) {
Arrays.sort(event.track, sTracksComparator);
}
// Hashtags
String hashtags = "";
if (event.track != null) {
StringBuilder hashtagsBuilder = new StringBuilder();
for (String trackName : event.track) {
if (trackName.trim().startsWith("Code Lab")) {
trackName = "Code Labs";
}
if (trackName.contains("Keynote")) {
continue;
}
hashtagsBuilder.append(" #");
hashtagsBuilder.append(
ScheduleContract.Tracks.generateTrackId(trackName));
}
hashtags = hashtagsBuilder.toString().trim();
}
// Pre-reqs
String prereqs = "";
if (event.prereq != null && event.prereq.length > 0) {
StringBuilder sb = new StringBuilder();
for (String prereq : event.prereq) {
sb.append(prereq);
sb.append(" ");
}
prereqs = sb.toString();
if (prereqs.startsWith("<br>")) {
prereqs = prereqs.substring(4);
}
}
String youtubeUrl = null;
if (event.youtube_url != null && event.youtube_url.length > 0) {
youtubeUrl = event.youtube_url[0];
}
// Insert session info
final ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(Sessions.CONTENT_URI))
.withValue(SyncColumns.UPDATED, System.currentTimeMillis())
.withValue(Sessions.SESSION_ID, sessionId)
.withValue(Sessions.SESSION_TYPE, result.event_type)
.withValue(Sessions.SESSION_LEVEL, event.level)
.withValue(Sessions.SESSION_TITLE, sessionTitle)
.withValue(Sessions.SESSION_ABSTRACT, event._abstract)
.withValue(Sessions.SESSION_TAGS, event.tags)
.withValue(Sessions.SESSION_URL, makeSessionUrl(sessionId))
.withValue(Sessions.SESSION_LIVESTREAM_URL, event.livestream_url)
.withValue(Sessions.SESSION_REQUIREMENTS, prereqs)
.withValue(Sessions.SESSION_STARRED, inSchedule)
.withValue(Sessions.SESSION_HASHTAGS, hashtags)
.withValue(Sessions.SESSION_YOUTUBE_URL, youtubeUrl)
.withValue(Sessions.SESSION_PDF_URL, "")
.withValue(Sessions.SESSION_NOTES_URL, "")
.withValue(Sessions.ROOM_ID, sanitizeId(event.room));
long sessionStartTime = parseTime(event.start_date, event.start_time);
long sessionEndTime = parseTime(event.end_date, event.end_time);
String blockId = ScheduleContract.Blocks.generateBlockId(
sessionStartTime, sessionEndTime);
if (!blockIds.contains(blockId)) {
String blockType;
String blockTitle;
if (EVENT_TYPE_KEYNOTE.equals(result.event_type)) {
blockType = ParserUtils.BLOCK_TYPE_KEYNOTE;
blockTitle = mContext.getString(R.string.schedule_block_title_keynote);
} else if (EVENT_TYPE_CODELAB.equals(result.event_type)) {
blockType = ParserUtils.BLOCK_TYPE_CODE_LAB;
blockTitle = mContext
.getString(R.string.schedule_block_title_code_labs);
} else {
blockType = ParserUtils.BLOCK_TYPE_SESSION;
blockTitle = mContext.getString(R.string.schedule_block_title_sessions);
}
batch.add(ContentProviderOperation
.newInsert(ScheduleContract.Blocks.CONTENT_URI)
.withValue(ScheduleContract.Blocks.BLOCK_ID, blockId)
.withValue(ScheduleContract.Blocks.BLOCK_TYPE, blockType)
.withValue(ScheduleContract.Blocks.BLOCK_TITLE, blockTitle)
.withValue(ScheduleContract.Blocks.BLOCK_START, sessionStartTime)
.withValue(ScheduleContract.Blocks.BLOCK_END, sessionEndTime)
.build());
blockIds.add(blockId);
}
builder.withValue(Sessions.BLOCK_ID, blockId);
batch.add(builder.build());
// Replace all session speakers
final Uri sessionSpeakersUri = Sessions.buildSpeakersDirUri(sessionId);
batch.add(ContentProviderOperation
.newDelete(ScheduleContract
.addCallerIsSyncAdapterParameter(sessionSpeakersUri))
.build());
if (event.speaker_id != null) {
for (String speakerId : event.speaker_id) {
speakerId = sRemoveSpeakerIdPrefixPattern.matcher(speakerId).replaceAll(
"");
batch.add(ContentProviderOperation.newInsert(sessionSpeakersUri)
.withValue(SessionsSpeakers.SESSION_ID, sessionId)
.withValue(SessionsSpeakers.SPEAKER_ID, speakerId).build());
}
}
// Replace all session tracks
final Uri sessionTracksUri = ScheduleContract.addCallerIsSyncAdapterParameter(
Sessions.buildTracksDirUri(sessionId));
batch.add(ContentProviderOperation.newDelete(sessionTracksUri).build());
if (event.track != null) {
for (String trackName : event.track) {
if (trackName.contains("Code Lab")) {
trackName = "Code Labs";
}
String trackId = ScheduleContract.Tracks.generateTrackId(trackName);
batch.add(ContentProviderOperation.newInsert(sessionTracksUri)
.withValue(SessionsTracks.SESSION_ID, sessionId)
.withValue(SessionsTracks.TRACK_ID, trackId).build());
}
}
}
}
}
return batch;
}
private Comparator<String> sTracksComparator = new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
// TODO: improve performance of this comparator
return (s1.contains("Code Lab") ? "z" : s1).compareTo(
(s2.contains("Code Lab") ? "z" : s2));
}
};
private String makeSessionUrl(String sessionId) {
if (TextUtils.isEmpty(sessionId)) {
return null;
}
return BASE_SESSION_URL + sessionId;
}
private static long parseTime(String date, String time) {
//change to this format : 2011-05-10T07:00:00.000-07:00
int index = time.indexOf(":");
if (index == 1) {
time = "0" + time;
}
final String composed = String.format("%sT%s:00.000-07:00", date, time);
//return sTimeFormat.parse(composed).getTime();
sTime.parse3339(composed);
return sTime.toMillis(false);
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/SessionsHandler.java | Java | asf20 | 15,809 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.Speaker;
import com.google.android.apps.iosched.io.model.SpeakersResponse;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.provider.ScheduleContract.Speakers;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Handler that parses speaker JSON data into a list of content provider operations.
*/
public class SpeakersHandler extends JSONHandler {
private static final String TAG = makeLogTag(SpeakersHandler.class);
public SpeakersHandler(Context context, boolean local) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
SpeakersResponse response = new Gson().fromJson(json, SpeakersResponse.class);
int numEvents = 0;
if (response.speakers != null) {
numEvents = response.speakers.length;
}
if (numEvents > 0) {
LOGI(TAG, "Updating speakers data");
// Clear out existing speakers
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
Speakers.CONTENT_URI))
.build());
for (Speaker speaker : response.speakers) {
String speakerId = speaker.user_id;
// Insert speaker info
batch.add(ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(Speakers.CONTENT_URI))
.withValue(SyncColumns.UPDATED, System.currentTimeMillis())
.withValue(Speakers.SPEAKER_ID, speakerId)
.withValue(Speakers.SPEAKER_NAME, speaker.display_name)
.withValue(Speakers.SPEAKER_ABSTRACT, speaker.bio)
.withValue(Speakers.SPEAKER_IMAGE_URL, speaker.thumbnail_url)
.withValue(Speakers.SPEAKER_URL, speaker.plusone_url)
.build());
}
}
return batch;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/SpeakersHandler.java | Java | asf20 | 3,289 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
/**
* An abstract object that is in charge of parsing JSON data with a given, known structure, into
* a list of content provider operations (inserts, updates, etc.) representing the data.
*/
public abstract class JSONHandler {
protected static Context mContext;
protected JSONHandler(Context context) {
mContext = context;
}
public abstract ArrayList<ContentProviderOperation> parse(String json) throws IOException;
/**
* Loads the JSON text resource with the given ID and returns the JSON content.
*/
public static String loadResourceJson(Context context, int resource) throws IOException {
InputStream is = context.getResources().openRawResource(resource);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/JSONHandler.java | Java | asf20 | 2,074 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.io.model.SandboxCompany;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.text.TextUtils;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.provider.ScheduleContract.Vendors;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Handler that parses developer sandbox JSON data into a list of content provider operations.
*/
public class SandboxHandler extends JSONHandler {
private static final String TAG = makeLogTag(SandboxHandler.class);
private static final String BASE_LOGO_URL
= "http://commondatastorage.googleapis.com/io2012/sandbox%20logos/";
public SandboxHandler(Context context, boolean local) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
SandboxCompany[] companies = new Gson().fromJson(json, SandboxCompany[].class);
if (companies.length > 0) {
LOGI(TAG, "Updating developer sandbox data");
// Clear out existing sandbox companies
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
Vendors.CONTENT_URI))
.build());
StringBuilder companyDescription = new StringBuilder();
String exhibitorsPrefix = mContext.getString(R.string.vendor_exhibitors_prefix);
for (SandboxCompany company : companies) {
// Insert sandbox company info
String website = company.website;
if (!TextUtils.isEmpty(website) && !website.startsWith("http")) {
website = "http://" + website;
}
companyDescription.setLength(0);
if (company.exhibitors != null && company.exhibitors.length > 0) {
companyDescription.append(exhibitorsPrefix);
companyDescription.append(" ");
for (int i = 0; i < company.exhibitors.length; i++) {
companyDescription.append(company.exhibitors[i]);
if (i >= company.exhibitors.length - 1) {
break;
}
companyDescription.append(", ");
}
companyDescription.append("\n\n");
}
if (!TextUtils.isEmpty(company.company_description)) {
companyDescription.append(company.company_description);
companyDescription.append("\n\n");
}
if (!TextUtils.isEmpty(company.product_description)) {
companyDescription.append(company.product_description);
}
// Clean up logo URL
String logoUrl = null;
if (!TextUtils.isEmpty(company.logo_img)) {
logoUrl = company.logo_img.replaceAll(" ", "%20");
if (!logoUrl.startsWith("http")) {
logoUrl = BASE_LOGO_URL + logoUrl;
}
}
batch.add(ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(Vendors.CONTENT_URI))
.withValue(SyncColumns.UPDATED, System.currentTimeMillis())
.withValue(Vendors.VENDOR_ID,
Vendors.generateVendorId(company.company_name))
.withValue(Vendors.VENDOR_NAME, company.company_name)
.withValue(Vendors.VENDOR_DESC, companyDescription.toString())
.withValue(Vendors.VENDOR_PRODUCT_DESC, null) // merged into company desc
.withValue(Vendors.VENDOR_LOGO_URL, logoUrl)
.withValue(Vendors.VENDOR_URL, website)
.withValue(Vendors.TRACK_ID,
ScheduleContract.Tracks.generateTrackId(company.product_pod))
.build());
}
}
return batch;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/SandboxHandler.java | Java | asf20 | 5,369 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import com.google.android.apps.iosched.io.model.Announcement;
import com.google.android.apps.iosched.io.model.AnnouncementsResponse;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Announcements;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
/**
* Handler that parses announcements JSON data into a list of content provider operations.
*/
public class AnnouncementsHandler extends JSONHandler {
private static final String TAG = makeLogTag(AnnouncementsHandler.class);
public AnnouncementsHandler(Context context, boolean local) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
AnnouncementsResponse response = new Gson().fromJson(json, AnnouncementsResponse.class);
int numAnnouncements = 0;
if (response.announcements != null) {
numAnnouncements = response.announcements.length;
}
if (numAnnouncements > 0) {
LOGI(TAG, "Updating announcements data");
// Clear out existing announcements
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
Announcements.CONTENT_URI))
.build());
for (Announcement announcement : response.announcements) {
// Save tracks as a json array
final String tracks =
(announcement.tracks != null && announcement.tracks.length > 0)
? new Gson().toJson(announcement.tracks)
: null;
// Insert announcement info
batch.add(ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(Announcements.CONTENT_URI))
.withValue(SyncColumns.UPDATED, System.currentTimeMillis())
// TODO: better announcements ID heuristic
.withValue(Announcements.ANNOUNCEMENT_ID,
(announcement.date + announcement.title).hashCode())
.withValue(Announcements.ANNOUNCEMENT_DATE, announcement.date)
.withValue(Announcements.ANNOUNCEMENT_TITLE, announcement.title)
.withValue(Announcements.ANNOUNCEMENT_SUMMARY, announcement.summary)
.withValue(Announcements.ANNOUNCEMENT_URL, announcement.link)
.withValue(Announcements.ANNOUNCEMENT_TRACKS, tracks)
.build());
}
}
return batch;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/AnnouncementsHandler.java | Java | asf20 | 4,016 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.Day;
import com.google.android.apps.iosched.io.model.EventSlots;
import com.google.android.apps.iosched.io.model.TimeSlot;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Blocks;
import com.google.android.apps.iosched.util.Lists;
import com.google.android.apps.iosched.util.ParserUtils;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
public class BlocksHandler extends JSONHandler {
private static final String TAG = makeLogTag(BlocksHandler.class);
public BlocksHandler(Context context) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json) throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
try {
Gson gson = new Gson();
EventSlots eventSlots = gson.fromJson(json, EventSlots.class);
int numDays = eventSlots.day.length;
//2011-05-10T07:00:00.000-07:00
for (int i = 0; i < numDays; i++) {
Day day = eventSlots.day[i];
String date = day.date;
TimeSlot[] timeSlots = day.slot;
for (TimeSlot timeSlot : timeSlots) {
parseSlot(date, timeSlot, batch);
}
}
} catch (Throwable e) {
LOGE(TAG, e.toString());
}
return batch;
}
private static void parseSlot(String date, TimeSlot slot,
ArrayList<ContentProviderOperation> batch) {
ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(ScheduleContract.addCallerIsSyncAdapterParameter(Blocks.CONTENT_URI));
//LOGD(TAG, "Inside parseSlot:" + date + ", " + slot);
String start = slot.start;
String end = slot.end;
String type = "N_D";
if (slot.type != null) {
type = slot.type;
}
String title = "N_D";
if (slot.title != null) {
title = slot.title;
}
String startTime = date + "T" + start + ":00.000-07:00";
String endTime = date + "T" + end + ":00.000-07:00";
LOGV(TAG, "startTime:" + startTime);
long startTimeL = ParserUtils.parseTime(startTime);
long endTimeL = ParserUtils.parseTime(endTime);
final String blockId = Blocks.generateBlockId(startTimeL, endTimeL);
LOGV(TAG, "blockId:" + blockId);
LOGV(TAG, "title:" + title);
LOGV(TAG, "start:" + startTimeL);
builder.withValue(Blocks.BLOCK_ID, blockId);
builder.withValue(Blocks.BLOCK_TITLE, title);
builder.withValue(Blocks.BLOCK_START, startTimeL);
builder.withValue(Blocks.BLOCK_END, endTimeL);
builder.withValue(Blocks.BLOCK_TYPE, type);
builder.withValue(Blocks.BLOCK_META, slot.meta);
batch.add(builder.build());
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/BlocksHandler.java | Java | asf20 | 3,937 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.Track;
import com.google.android.apps.iosched.io.model.Tracks;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.graphics.Color;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId;
/**
* Handler that parses track JSON data into a list of content provider operations.
*/
public class TracksHandler extends JSONHandler {
private static final String TAG = makeLogTag(TracksHandler.class);
public TracksHandler(Context context) {
super(context);
}
@Override
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
batch.add(ContentProviderOperation.newDelete(
ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Tracks.CONTENT_URI)).build());
Tracks tracksJson = new Gson().fromJson(json, Tracks.class);
int noOfTracks = tracksJson.getTrack().length;
for (int i = 0; i < noOfTracks; i++) {
parseTrack(tracksJson.getTrack()[i], batch);
}
return batch;
}
private static void parseTrack(Track track, ArrayList<ContentProviderOperation> batch) {
ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(
ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Tracks.CONTENT_URI));
builder.withValue(ScheduleContract.Tracks.TRACK_ID,
ScheduleContract.Tracks.generateTrackId(track.name));
builder.withValue(ScheduleContract.Tracks.TRACK_NAME, track.name);
builder.withValue(ScheduleContract.Tracks.TRACK_COLOR, Color.parseColor(track.color));
builder.withValue(ScheduleContract.Tracks.TRACK_ABSTRACT, track._abstract);
batch.add(builder.build());
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/io/TracksHandler.java | Java | asf20 | 2,895 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.provider;
import com.google.android.apps.iosched.provider.ScheduleContract.AnnouncementsColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Blocks;
import com.google.android.apps.iosched.provider.ScheduleContract.BlocksColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Rooms;
import com.google.android.apps.iosched.provider.ScheduleContract.RoomsColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.provider.ScheduleContract.SessionsColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Speakers;
import com.google.android.apps.iosched.provider.ScheduleContract.SpeakersColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Tracks;
import com.google.android.apps.iosched.provider.ScheduleContract.TracksColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Vendors;
import com.google.android.apps.iosched.provider.ScheduleContract.VendorsColumns;
import android.app.SearchManager;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Helper for managing {@link SQLiteDatabase} that stores data for
* {@link ScheduleProvider}.
*/
public class ScheduleDatabase extends SQLiteOpenHelper {
private static final String TAG = makeLogTag(ScheduleDatabase.class);
private static final String DATABASE_NAME = "schedule.db";
// NOTE: carefully update onUpgrade() when bumping database versions to make
// sure user data is saved.
private static final int VER_LAUNCH = 25;
private static final int VER_SESSION_TYPE = 26;
private static final int DATABASE_VERSION = VER_SESSION_TYPE;
interface Tables {
String BLOCKS = "blocks";
String TRACKS = "tracks";
String ROOMS = "rooms";
String SESSIONS = "sessions";
String SPEAKERS = "speakers";
String SESSIONS_SPEAKERS = "sessions_speakers";
String SESSIONS_TRACKS = "sessions_tracks";
String VENDORS = "vendors";
String ANNOUNCEMENTS = "announcements";
String SESSIONS_SEARCH = "sessions_search";
String SEARCH_SUGGEST = "search_suggest";
String SESSIONS_JOIN_BLOCKS_ROOMS = "sessions "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SESSIONS_JOIN_ROOMS = "sessions "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String VENDORS_JOIN_TRACKS = "vendors "
+ "LEFT OUTER JOIN tracks ON vendors.track_id=tracks.track_id";
String SESSIONS_SPEAKERS_JOIN_SPEAKERS = "sessions_speakers "
+ "LEFT OUTER JOIN speakers ON sessions_speakers.speaker_id=speakers.speaker_id";
String SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_speakers "
+ "LEFT OUTER JOIN sessions ON sessions_speakers.session_id=sessions.session_id "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SESSIONS_TRACKS_JOIN_TRACKS = "sessions_tracks "
+ "LEFT OUTER JOIN tracks ON sessions_tracks.track_id=tracks.track_id";
String SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_tracks "
+ "LEFT OUTER JOIN sessions ON sessions_tracks.session_id=sessions.session_id "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_search "
+ "LEFT OUTER JOIN sessions ON sessions_search.session_id=sessions.session_id "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SESSIONS_JOIN_TRACKS_JOIN_BLOCKS = "sessions "
+ "LEFT OUTER JOIN sessions_tracks ON "
+ "sessions_tracks.session_id=sessions.session_id "
+ "LEFT OUTER JOIN tracks ON tracks.track_id=sessions_tracks.track_id "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id";
String BLOCKS_JOIN_SESSIONS = "blocks "
+ "LEFT OUTER JOIN sessions ON blocks.block_id=sessions.block_id";
}
private interface Triggers {
String SESSIONS_SEARCH_INSERT = "sessions_search_insert";
String SESSIONS_SEARCH_DELETE = "sessions_search_delete";
String SESSIONS_SEARCH_UPDATE = "sessions_search_update";
// Deletes from session_tracks when corresponding sessions are deleted.
String SESSIONS_TRACKS_DELETE = "sessions_tracks_delete";
}
public interface SessionsSpeakers {
String SESSION_ID = "session_id";
String SPEAKER_ID = "speaker_id";
}
public interface SessionsTracks {
String SESSION_ID = "session_id";
String TRACK_ID = "track_id";
}
interface SessionsSearchColumns {
String SESSION_ID = "session_id";
String BODY = "body";
}
/** Fully-qualified field names. */
private interface Qualified {
String SESSIONS_SEARCH_SESSION_ID = Tables.SESSIONS_SEARCH + "."
+ SessionsSearchColumns.SESSION_ID;
String SESSIONS_SEARCH = Tables.SESSIONS_SEARCH + "(" + SessionsSearchColumns.SESSION_ID
+ "," + SessionsSearchColumns.BODY + ")";
String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "."
+ SessionsTracks.SESSION_ID;
}
/** {@code REFERENCES} clauses. */
private interface References {
String BLOCK_ID = "REFERENCES " + Tables.BLOCKS + "(" + Blocks.BLOCK_ID + ")";
String TRACK_ID = "REFERENCES " + Tables.TRACKS + "(" + Tracks.TRACK_ID + ")";
String ROOM_ID = "REFERENCES " + Tables.ROOMS + "(" + Rooms.ROOM_ID + ")";
String SESSION_ID = "REFERENCES " + Tables.SESSIONS + "(" + Sessions.SESSION_ID + ")";
String SPEAKER_ID = "REFERENCES " + Tables.SPEAKERS + "(" + Speakers.SPEAKER_ID + ")";
String VENDOR_ID = "REFERENCES " + Tables.VENDORS + "(" + Vendors.VENDOR_ID + ")";
}
private interface Subquery {
/**
* Subquery used to build the {@link SessionsSearchColumns#BODY} string
* used for indexing {@link Sessions} content.
*/
String SESSIONS_BODY = "(new." + Sessions.SESSION_TITLE
+ "||'; '||new." + Sessions.SESSION_ABSTRACT
+ "||'; '||" + "coalesce(new." + Sessions.SESSION_TAGS + ", '')"
+ ")";
}
public ScheduleDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + Tables.BLOCKS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ BlocksColumns.BLOCK_ID + " TEXT NOT NULL,"
+ BlocksColumns.BLOCK_TITLE + " TEXT NOT NULL,"
+ BlocksColumns.BLOCK_START + " INTEGER NOT NULL,"
+ BlocksColumns.BLOCK_END + " INTEGER NOT NULL,"
+ BlocksColumns.BLOCK_TYPE + " TEXT,"
+ BlocksColumns.BLOCK_META + " TEXT,"
+ "UNIQUE (" + BlocksColumns.BLOCK_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.TRACKS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ TracksColumns.TRACK_ID + " TEXT NOT NULL,"
+ TracksColumns.TRACK_NAME + " TEXT,"
+ TracksColumns.TRACK_COLOR + " INTEGER,"
+ TracksColumns.TRACK_ABSTRACT + " TEXT,"
+ "UNIQUE (" + TracksColumns.TRACK_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.ROOMS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ RoomsColumns.ROOM_ID + " TEXT NOT NULL,"
+ RoomsColumns.ROOM_NAME + " TEXT,"
+ RoomsColumns.ROOM_FLOOR + " TEXT,"
+ "UNIQUE (" + RoomsColumns.ROOM_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.SESSIONS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ SessionsColumns.SESSION_ID + " TEXT NOT NULL,"
+ Sessions.BLOCK_ID + " TEXT " + References.BLOCK_ID + ","
+ Sessions.ROOM_ID + " TEXT " + References.ROOM_ID + ","
+ SessionsColumns.SESSION_TYPE + " TEXT,"
+ SessionsColumns.SESSION_LEVEL + " TEXT,"
+ SessionsColumns.SESSION_TITLE + " TEXT,"
+ SessionsColumns.SESSION_ABSTRACT + " TEXT,"
+ SessionsColumns.SESSION_REQUIREMENTS + " TEXT,"
+ SessionsColumns.SESSION_TAGS + " TEXT,"
+ SessionsColumns.SESSION_HASHTAGS + " TEXT,"
+ SessionsColumns.SESSION_URL + " TEXT,"
+ SessionsColumns.SESSION_YOUTUBE_URL + " TEXT,"
+ SessionsColumns.SESSION_PDF_URL + " TEXT,"
+ SessionsColumns.SESSION_NOTES_URL + " TEXT,"
+ SessionsColumns.SESSION_STARRED + " INTEGER NOT NULL DEFAULT 0,"
+ SessionsColumns.SESSION_CAL_EVENT_ID + " INTEGER,"
+ SessionsColumns.SESSION_LIVESTREAM_URL + " TEXT,"
+ "UNIQUE (" + SessionsColumns.SESSION_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.SPEAKERS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ SpeakersColumns.SPEAKER_ID + " TEXT NOT NULL,"
+ SpeakersColumns.SPEAKER_NAME + " TEXT,"
+ SpeakersColumns.SPEAKER_IMAGE_URL + " TEXT,"
+ SpeakersColumns.SPEAKER_COMPANY + " TEXT,"
+ SpeakersColumns.SPEAKER_ABSTRACT + " TEXT,"
+ SpeakersColumns.SPEAKER_URL + " TEXT,"
+ "UNIQUE (" + SpeakersColumns.SPEAKER_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.SESSIONS_SPEAKERS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SessionsSpeakers.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + ","
+ SessionsSpeakers.SPEAKER_ID + " TEXT NOT NULL " + References.SPEAKER_ID + ","
+ "UNIQUE (" + SessionsSpeakers.SESSION_ID + ","
+ SessionsSpeakers.SPEAKER_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.SESSIONS_TRACKS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SessionsTracks.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + ","
+ SessionsTracks.TRACK_ID + " TEXT NOT NULL " + References.TRACK_ID
+ ")");
db.execSQL("CREATE TABLE " + Tables.VENDORS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ VendorsColumns.VENDOR_ID + " TEXT NOT NULL,"
+ Vendors.TRACK_ID + " TEXT " + References.TRACK_ID + ","
+ VendorsColumns.VENDOR_NAME + " TEXT,"
+ VendorsColumns.VENDOR_LOCATION + " TEXT,"
+ VendorsColumns.VENDOR_DESC + " TEXT,"
+ VendorsColumns.VENDOR_URL + " TEXT,"
+ VendorsColumns.VENDOR_PRODUCT_DESC + " TEXT,"
+ VendorsColumns.VENDOR_LOGO_URL + " TEXT,"
+ VendorsColumns.VENDOR_STARRED + " INTEGER,"
+ "UNIQUE (" + VendorsColumns.VENDOR_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.ANNOUNCEMENTS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ AnnouncementsColumns.ANNOUNCEMENT_ID + " TEXT,"
+ AnnouncementsColumns.ANNOUNCEMENT_TITLE + " TEXT NOT NULL,"
+ AnnouncementsColumns.ANNOUNCEMENT_SUMMARY + " TEXT,"
+ AnnouncementsColumns.ANNOUNCEMENT_TRACKS + " TEXT,"
+ AnnouncementsColumns.ANNOUNCEMENT_URL + " TEXT,"
+ AnnouncementsColumns.ANNOUNCEMENT_DATE + " INTEGER NOT NULL)");
createSessionsSearch(db);
createSessionsDeleteTriggers(db);
db.execSQL("CREATE TABLE " + Tables.SEARCH_SUGGEST + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SearchManager.SUGGEST_COLUMN_TEXT_1 + " TEXT NOT NULL)");
}
/**
* Create triggers that automatically build {@link Tables#SESSIONS_SEARCH}
* as values are changed in {@link Tables#SESSIONS}.
*/
private static void createSessionsSearch(SQLiteDatabase db) {
// Using the "porter" tokenizer for simple stemming, so that
// "frustration" matches "frustrated."
db.execSQL("CREATE VIRTUAL TABLE " + Tables.SESSIONS_SEARCH + " USING fts3("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SessionsSearchColumns.BODY + " TEXT NOT NULL,"
+ SessionsSearchColumns.SESSION_ID
+ " TEXT NOT NULL " + References.SESSION_ID + ","
+ "UNIQUE (" + SessionsSearchColumns.SESSION_ID + ") ON CONFLICT REPLACE,"
+ "tokenize=porter)");
// TODO: handle null fields in body, which cause trigger to fail
// TODO: implement update trigger, not currently exercised
db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_INSERT + " AFTER INSERT ON "
+ Tables.SESSIONS + " BEGIN INSERT INTO " + Qualified.SESSIONS_SEARCH + " "
+ " VALUES(new." + Sessions.SESSION_ID + ", " + Subquery.SESSIONS_BODY + ");"
+ " END;");
db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_DELETE + " AFTER DELETE ON "
+ Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.SESSIONS_SEARCH + " "
+ " WHERE " + Qualified.SESSIONS_SEARCH_SESSION_ID + "=old." + Sessions.SESSION_ID
+ ";" + " END;");
db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_UPDATE
+ " AFTER UPDATE ON " + Tables.SESSIONS
+ " BEGIN UPDATE sessions_search SET " + SessionsSearchColumns.BODY + " = "
+ Subquery.SESSIONS_BODY + " WHERE session_id = old.session_id"
+ "; END;");
}
private void createSessionsDeleteTriggers(SQLiteDatabase db) {
db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_TRACKS_DELETE + " AFTER DELETE ON "
+ Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.SESSIONS_TRACKS + " "
+ " WHERE " + Qualified.SESSIONS_TRACKS_SESSION_ID + "=old." + Sessions.SESSION_ID
+ ";" + " END;");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
LOGD(TAG, "onUpgrade() from " + oldVersion + " to " + newVersion);
// NOTE: This switch statement is designed to handle cascading database
// updates, starting at the current version and falling through to all
// future upgrade cases. Only use "break;" when you want to drop and
// recreate the entire database.
int version = oldVersion;
switch (version) {
case VER_LAUNCH:
// VER_SESSION_TYPE added column for session feedback URL.
db.execSQL("ALTER TABLE " + Tables.SESSIONS + " ADD COLUMN "
+ SessionsColumns.SESSION_TYPE + " TEXT");
version = VER_SESSION_TYPE;
}
LOGD(TAG, "after upgrade logic, at version " + version);
if (version != DATABASE_VERSION) {
LOGW(TAG, "Destroying old data during upgrade");
db.execSQL("DROP TABLE IF EXISTS " + Tables.BLOCKS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.TRACKS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.ROOMS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SPEAKERS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SPEAKERS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_TRACKS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.VENDORS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.ANNOUNCEMENTS);
db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_INSERT);
db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_DELETE);
db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_UPDATE);
db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_TRACKS_DELETE);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SEARCH);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SEARCH_SUGGEST);
onCreate(db);
}
}
public static void deleteDatabase(Context context) {
context.deleteDatabase(DATABASE_NAME);
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/provider/ScheduleDatabase.java | Java | asf20 | 18,575 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.provider;
import com.google.android.apps.iosched.provider.ScheduleContract.Announcements;
import com.google.android.apps.iosched.provider.ScheduleContract.Blocks;
import com.google.android.apps.iosched.provider.ScheduleContract.Rooms;
import com.google.android.apps.iosched.provider.ScheduleContract.SearchSuggest;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.provider.ScheduleContract.Speakers;
import com.google.android.apps.iosched.provider.ScheduleContract.Tracks;
import com.google.android.apps.iosched.provider.ScheduleContract.Vendors;
import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSearchColumns;
import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers;
import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks;
import com.google.android.apps.iosched.provider.ScheduleDatabase.Tables;
import com.google.android.apps.iosched.util.SelectionBuilder;
import android.app.Activity;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.BaseColumns;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Provider that stores {@link ScheduleContract} data. Data is usually inserted
* by {@link com.google.android.apps.iosched.sync.SyncHelper}, and queried by various
* {@link Activity} instances.
*/
public class ScheduleProvider extends ContentProvider {
private static final String TAG = makeLogTag(ScheduleProvider.class);
private ScheduleDatabase mOpenHelper;
private static final UriMatcher sUriMatcher = buildUriMatcher();
private static final int BLOCKS = 100;
private static final int BLOCKS_BETWEEN = 101;
private static final int BLOCKS_ID = 102;
private static final int BLOCKS_ID_SESSIONS = 103;
private static final int BLOCKS_ID_SESSIONS_STARRED = 104;
private static final int TRACKS = 200;
private static final int TRACKS_ID = 201;
private static final int TRACKS_ID_SESSIONS = 202;
private static final int TRACKS_ID_VENDORS = 203;
private static final int ROOMS = 300;
private static final int ROOMS_ID = 301;
private static final int ROOMS_ID_SESSIONS = 302;
private static final int SESSIONS = 400;
private static final int SESSIONS_STARRED = 401;
private static final int SESSIONS_WITH_TRACK = 402;
private static final int SESSIONS_SEARCH = 403;
private static final int SESSIONS_AT = 404;
private static final int SESSIONS_ID = 405;
private static final int SESSIONS_ID_SPEAKERS = 406;
private static final int SESSIONS_ID_TRACKS = 407;
private static final int SESSIONS_ID_WITH_TRACK = 408;
private static final int SPEAKERS = 500;
private static final int SPEAKERS_ID = 501;
private static final int SPEAKERS_ID_SESSIONS = 502;
private static final int VENDORS = 600;
private static final int VENDORS_STARRED = 601;
private static final int VENDORS_SEARCH = 603;
private static final int VENDORS_ID = 604;
private static final int ANNOUNCEMENTS = 700;
private static final int ANNOUNCEMENTS_ID = 701;
private static final int SEARCH_SUGGEST = 800;
private static final String MIME_XML = "text/xml";
/**
* Build and return a {@link UriMatcher} that catches all {@link Uri}
* variations supported by this {@link ContentProvider}.
*/
private static UriMatcher buildUriMatcher() {
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = ScheduleContract.CONTENT_AUTHORITY;
matcher.addURI(authority, "blocks", BLOCKS);
matcher.addURI(authority, "blocks/between/*/*", BLOCKS_BETWEEN);
matcher.addURI(authority, "blocks/*", BLOCKS_ID);
matcher.addURI(authority, "blocks/*/sessions", BLOCKS_ID_SESSIONS);
matcher.addURI(authority, "blocks/*/sessions/starred", BLOCKS_ID_SESSIONS_STARRED);
matcher.addURI(authority, "tracks", TRACKS);
matcher.addURI(authority, "tracks/*", TRACKS_ID);
matcher.addURI(authority, "tracks/*/sessions", TRACKS_ID_SESSIONS);
matcher.addURI(authority, "tracks/*/vendors", TRACKS_ID_VENDORS);
matcher.addURI(authority, "rooms", ROOMS);
matcher.addURI(authority, "rooms/*", ROOMS_ID);
matcher.addURI(authority, "rooms/*/sessions", ROOMS_ID_SESSIONS);
matcher.addURI(authority, "sessions", SESSIONS);
matcher.addURI(authority, "sessions/starred", SESSIONS_STARRED);
matcher.addURI(authority, "sessions/with_track", SESSIONS_WITH_TRACK);
matcher.addURI(authority, "sessions/search/*", SESSIONS_SEARCH);
matcher.addURI(authority, "sessions/at/*", SESSIONS_AT);
matcher.addURI(authority, "sessions/*", SESSIONS_ID);
matcher.addURI(authority, "sessions/*/speakers", SESSIONS_ID_SPEAKERS);
matcher.addURI(authority, "sessions/*/tracks", SESSIONS_ID_TRACKS);
matcher.addURI(authority, "sessions/*/with_track", SESSIONS_ID_WITH_TRACK);
matcher.addURI(authority, "speakers", SPEAKERS);
matcher.addURI(authority, "speakers/*", SPEAKERS_ID);
matcher.addURI(authority, "speakers/*/sessions", SPEAKERS_ID_SESSIONS);
matcher.addURI(authority, "vendors", VENDORS);
matcher.addURI(authority, "vendors/starred", VENDORS_STARRED);
matcher.addURI(authority, "vendors/search/*", VENDORS_SEARCH);
matcher.addURI(authority, "vendors/*", VENDORS_ID);
matcher.addURI(authority, "announcements", ANNOUNCEMENTS);
matcher.addURI(authority, "announcements/*", ANNOUNCEMENTS_ID);
matcher.addURI(authority, "search_suggest_query", SEARCH_SUGGEST);
return matcher;
}
@Override
public boolean onCreate() {
mOpenHelper = new ScheduleDatabase(getContext());
return true;
}
private void deleteDatabase() {
// TODO: wait for content provider operations to finish, then tear down
mOpenHelper.close();
Context context = getContext();
ScheduleDatabase.deleteDatabase(context);
mOpenHelper = new ScheduleDatabase(getContext());
}
/** {@inheritDoc} */
@Override
public String getType(Uri uri) {
final int match = sUriMatcher.match(uri);
switch (match) {
case BLOCKS:
return Blocks.CONTENT_TYPE;
case BLOCKS_BETWEEN:
return Blocks.CONTENT_TYPE;
case BLOCKS_ID:
return Blocks.CONTENT_ITEM_TYPE;
case BLOCKS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case BLOCKS_ID_SESSIONS_STARRED:
return Sessions.CONTENT_TYPE;
case TRACKS:
return Tracks.CONTENT_TYPE;
case TRACKS_ID:
return Tracks.CONTENT_ITEM_TYPE;
case TRACKS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case TRACKS_ID_VENDORS:
return Vendors.CONTENT_TYPE;
case ROOMS:
return Rooms.CONTENT_TYPE;
case ROOMS_ID:
return Rooms.CONTENT_ITEM_TYPE;
case ROOMS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case SESSIONS:
return Sessions.CONTENT_TYPE;
case SESSIONS_STARRED:
return Sessions.CONTENT_TYPE;
case SESSIONS_WITH_TRACK:
return Sessions.CONTENT_TYPE;
case SESSIONS_SEARCH:
return Sessions.CONTENT_TYPE;
case SESSIONS_AT:
return Sessions.CONTENT_TYPE;
case SESSIONS_ID:
return Sessions.CONTENT_ITEM_TYPE;
case SESSIONS_ID_SPEAKERS:
return Speakers.CONTENT_TYPE;
case SESSIONS_ID_TRACKS:
return Tracks.CONTENT_TYPE;
case SESSIONS_ID_WITH_TRACK:
return Sessions.CONTENT_TYPE;
case SPEAKERS:
return Speakers.CONTENT_TYPE;
case SPEAKERS_ID:
return Speakers.CONTENT_ITEM_TYPE;
case SPEAKERS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case VENDORS:
return Vendors.CONTENT_TYPE;
case VENDORS_STARRED:
return Vendors.CONTENT_TYPE;
case VENDORS_SEARCH:
return Vendors.CONTENT_TYPE;
case VENDORS_ID:
return Vendors.CONTENT_ITEM_TYPE;
case ANNOUNCEMENTS:
return Announcements.CONTENT_TYPE;
case ANNOUNCEMENTS_ID:
return Announcements.CONTENT_ITEM_TYPE;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
/** {@inheritDoc} */
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
LOGV(TAG, "query(uri=" + uri + ", proj=" + Arrays.toString(projection) + ")");
final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
final int match = sUriMatcher.match(uri);
switch (match) {
default: {
// Most cases are handled with simple SelectionBuilder
final SelectionBuilder builder = buildExpandedSelection(uri, match);
return builder.where(selection, selectionArgs).query(db, projection, sortOrder);
}
case SEARCH_SUGGEST: {
final SelectionBuilder builder = new SelectionBuilder();
// Adjust incoming query to become SQL text match
selectionArgs[0] = selectionArgs[0] + "%";
builder.table(Tables.SEARCH_SUGGEST);
builder.where(selection, selectionArgs);
builder.map(SearchManager.SUGGEST_COLUMN_QUERY,
SearchManager.SUGGEST_COLUMN_TEXT_1);
projection = new String[] {
BaseColumns._ID,
SearchManager.SUGGEST_COLUMN_TEXT_1,
SearchManager.SUGGEST_COLUMN_QUERY
};
final String limit = uri.getQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT);
return builder.query(db, projection, null, null, SearchSuggest.DEFAULT_SORT, limit);
}
}
}
/** {@inheritDoc} */
@Override
public Uri insert(Uri uri, ContentValues values) {
LOGV(TAG, "insert(uri=" + uri + ", values=" + values.toString() + ")");
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
boolean syncToNetwork = !ScheduleContract.hasCallerIsSyncAdapterParameter(uri);
switch (match) {
case BLOCKS: {
db.insertOrThrow(Tables.BLOCKS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Blocks.buildBlockUri(values.getAsString(Blocks.BLOCK_ID));
}
case TRACKS: {
db.insertOrThrow(Tables.TRACKS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Tracks.buildTrackUri(values.getAsString(Tracks.TRACK_ID));
}
case ROOMS: {
db.insertOrThrow(Tables.ROOMS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Rooms.buildRoomUri(values.getAsString(Rooms.ROOM_ID));
}
case SESSIONS: {
db.insertOrThrow(Tables.SESSIONS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Sessions.buildSessionUri(values.getAsString(Sessions.SESSION_ID));
}
case SESSIONS_ID_SPEAKERS: {
db.insertOrThrow(Tables.SESSIONS_SPEAKERS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Speakers.buildSpeakerUri(values.getAsString(SessionsSpeakers.SPEAKER_ID));
}
case SESSIONS_ID_TRACKS: {
db.insertOrThrow(Tables.SESSIONS_TRACKS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Tracks.buildTrackUri(values.getAsString(SessionsTracks.TRACK_ID));
}
case SPEAKERS: {
db.insertOrThrow(Tables.SPEAKERS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Speakers.buildSpeakerUri(values.getAsString(Speakers.SPEAKER_ID));
}
case VENDORS: {
db.insertOrThrow(Tables.VENDORS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Vendors.buildVendorUri(values.getAsString(Vendors.VENDOR_ID));
}
case ANNOUNCEMENTS: {
db.insertOrThrow(Tables.ANNOUNCEMENTS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Announcements.buildAnnouncementUri(values
.getAsString(Announcements.ANNOUNCEMENT_ID));
}
case SEARCH_SUGGEST: {
db.insertOrThrow(Tables.SEARCH_SUGGEST, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return SearchSuggest.CONTENT_URI;
}
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
/** {@inheritDoc} */
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
LOGV(TAG, "update(uri=" + uri + ", values=" + values.toString() + ")");
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final SelectionBuilder builder = buildSimpleSelection(uri);
int retVal = builder.where(selection, selectionArgs).update(db, values);
boolean syncToNetwork = !ScheduleContract.hasCallerIsSyncAdapterParameter(uri);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return retVal;
}
/** {@inheritDoc} */
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
LOGV(TAG, "delete(uri=" + uri + ")");
if (uri == ScheduleContract.BASE_CONTENT_URI) {
// Handle whole database deletes (e.g. when signing out)
deleteDatabase();
getContext().getContentResolver().notifyChange(uri, null, false);
return 1;
}
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final SelectionBuilder builder = buildSimpleSelection(uri);
int retVal = builder.where(selection, selectionArgs).delete(db);
getContext().getContentResolver().notifyChange(uri, null,
!ScheduleContract.hasCallerIsSyncAdapterParameter(uri));
return retVal;
}
/**
* Apply the given set of {@link ContentProviderOperation}, executing inside
* a {@link SQLiteDatabase} transaction. All changes will be rolled back if
* any single one fails.
*/
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.beginTransaction();
try {
final int numOperations = operations.size();
final ContentProviderResult[] results = new ContentProviderResult[numOperations];
for (int i = 0; i < numOperations; i++) {
results[i] = operations.get(i).apply(this, results, i);
}
db.setTransactionSuccessful();
return results;
} finally {
db.endTransaction();
}
}
/**
* Build a simple {@link SelectionBuilder} to match the requested
* {@link Uri}. This is usually enough to support {@link #insert},
* {@link #update}, and {@link #delete} operations.
*/
private SelectionBuilder buildSimpleSelection(Uri uri) {
final SelectionBuilder builder = new SelectionBuilder();
final int match = sUriMatcher.match(uri);
switch (match) {
case BLOCKS: {
return builder.table(Tables.BLOCKS);
}
case BLOCKS_ID: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.BLOCKS)
.where(Blocks.BLOCK_ID + "=?", blockId);
}
case TRACKS: {
return builder.table(Tables.TRACKS);
}
case TRACKS_ID: {
final String trackId = Tracks.getTrackId(uri);
return builder.table(Tables.TRACKS)
.where(Tracks.TRACK_ID + "=?", trackId);
}
case ROOMS: {
return builder.table(Tables.ROOMS);
}
case ROOMS_ID: {
final String roomId = Rooms.getRoomId(uri);
return builder.table(Tables.ROOMS)
.where(Rooms.ROOM_ID + "=?", roomId);
}
case SESSIONS: {
return builder.table(Tables.SESSIONS);
}
case SESSIONS_ID: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS)
.where(Sessions.SESSION_ID + "=?", sessionId);
}
case SESSIONS_ID_SPEAKERS: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_SPEAKERS)
.where(Sessions.SESSION_ID + "=?", sessionId);
}
case SESSIONS_ID_TRACKS: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_TRACKS)
.where(Sessions.SESSION_ID + "=?", sessionId);
}
case SPEAKERS: {
return builder.table(Tables.SPEAKERS);
}
case SPEAKERS_ID: {
final String speakerId = Speakers.getSpeakerId(uri);
return builder.table(Tables.SPEAKERS)
.where(Speakers.SPEAKER_ID + "=?", speakerId);
}
case VENDORS: {
return builder.table(Tables.VENDORS);
}
case VENDORS_ID: {
final String vendorId = Vendors.getVendorId(uri);
return builder.table(Tables.VENDORS)
.where(Vendors.VENDOR_ID + "=?", vendorId);
}
case ANNOUNCEMENTS: {
return builder.table(Tables.ANNOUNCEMENTS);
}
case ANNOUNCEMENTS_ID: {
final String announcementId = Announcements.getAnnouncementId(uri);
return builder.table(Tables.ANNOUNCEMENTS)
.where(Announcements.ANNOUNCEMENT_ID + "=?", announcementId);
}
case SEARCH_SUGGEST: {
return builder.table(Tables.SEARCH_SUGGEST);
}
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
/**
* Build an advanced {@link SelectionBuilder} to match the requested
* {@link Uri}. This is usually only used by {@link #query}, since it
* performs table joins useful for {@link Cursor} data.
*/
private SelectionBuilder buildExpandedSelection(Uri uri, int match) {
final SelectionBuilder builder = new SelectionBuilder();
switch (match) {
case BLOCKS: {
return builder
.table(Tables.BLOCKS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.map(Blocks.STARRED_SESSION_ID, Subquery.BLOCK_STARRED_SESSION_ID)
.map(Blocks.STARRED_SESSION_TITLE, Subquery.BLOCK_STARRED_SESSION_TITLE)
.map(Blocks.STARRED_SESSION_HASHTAGS,
Subquery.BLOCK_STARRED_SESSION_HASHTAGS)
.map(Blocks.STARRED_SESSION_URL, Subquery.BLOCK_STARRED_SESSION_URL)
.map(Blocks.STARRED_SESSION_LIVESTREAM_URL,
Subquery.BLOCK_STARRED_SESSION_LIVESTREAM_URL)
.map(Blocks.STARRED_SESSION_ROOM_NAME,
Subquery.BLOCK_STARRED_SESSION_ROOM_NAME)
.map(Blocks.STARRED_SESSION_ROOM_ID, Subquery.BLOCK_STARRED_SESSION_ROOM_ID);
}
case BLOCKS_BETWEEN: {
final List<String> segments = uri.getPathSegments();
final String startTime = segments.get(2);
final String endTime = segments.get(3);
return builder.table(Tables.BLOCKS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.where(Blocks.BLOCK_START + ">=?", startTime)
.where(Blocks.BLOCK_START + "<=?", endTime);
}
case BLOCKS_ID: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.BLOCKS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.where(Blocks.BLOCK_ID + "=?", blockId);
}
case BLOCKS_ID_SESSIONS: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId);
}
case BLOCKS_ID_SESSIONS_STARRED: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId)
.where(Qualified.SESSIONS_STARRED + "=1");
}
case TRACKS: {
return builder.table(Tables.TRACKS)
.map(Tracks.SESSIONS_COUNT, Subquery.TRACK_SESSIONS_COUNT)
.map(Tracks.VENDORS_COUNT, Subquery.TRACK_VENDORS_COUNT);
}
case TRACKS_ID: {
final String trackId = Tracks.getTrackId(uri);
return builder.table(Tables.TRACKS)
.where(Tracks.TRACK_ID + "=?", trackId);
}
case TRACKS_ID_SESSIONS: {
final String trackId = Tracks.getTrackId(uri);
return builder.table(Tables.SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_TRACKS_TRACK_ID + "=?", trackId);
}
case TRACKS_ID_VENDORS: {
final String trackId = Tracks.getTrackId(uri);
return builder.table(Tables.VENDORS_JOIN_TRACKS)
.mapToTable(Vendors._ID, Tables.VENDORS)
.mapToTable(Vendors.TRACK_ID, Tables.VENDORS)
.where(Qualified.VENDORS_TRACK_ID + "=?", trackId);
}
case ROOMS: {
return builder.table(Tables.ROOMS);
}
case ROOMS_ID: {
final String roomId = Rooms.getRoomId(uri);
return builder.table(Tables.ROOMS)
.where(Rooms.ROOM_ID + "=?", roomId);
}
case ROOMS_ID_SESSIONS: {
final String roomId = Rooms.getRoomId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_ROOM_ID + "=?", roomId);
}
case SESSIONS: {
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS);
}
case SESSIONS_STARRED: {
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Sessions.SESSION_STARRED + "=1");
}
case SESSIONS_WITH_TRACK: {
return builder.table(Tables.SESSIONS_JOIN_TRACKS_JOIN_BLOCKS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Tracks.TRACK_ID, Tables.TRACKS)
.mapToTable(Tracks.TRACK_NAME, Tables.TRACKS)
.mapToTable(Blocks.BLOCK_ID, Tables.BLOCKS);
}
case SESSIONS_ID_WITH_TRACK: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_JOIN_TRACKS_JOIN_BLOCKS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Tracks.TRACK_ID, Tables.TRACKS)
.mapToTable(Tracks.TRACK_NAME, Tables.TRACKS)
.mapToTable(Blocks.BLOCK_ID, Tables.BLOCKS)
.where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId);
}
case SESSIONS_SEARCH: {
final String query = Sessions.getSearchQuery(uri);
return builder.table(Tables.SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS)
.map(Sessions.SEARCH_SNIPPET, Subquery.SESSIONS_SNIPPET)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(SessionsSearchColumns.BODY + " MATCH ?", query);
}
case SESSIONS_AT: {
final List<String> segments = uri.getPathSegments();
final String time = segments.get(2);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Sessions.BLOCK_START + "<=?", time)
.where(Sessions.BLOCK_END + ">=?", time);
}
case SESSIONS_ID: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId);
}
case SESSIONS_ID_SPEAKERS: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SPEAKERS)
.mapToTable(Speakers._ID, Tables.SPEAKERS)
.mapToTable(Speakers.SPEAKER_ID, Tables.SPEAKERS)
.where(Qualified.SESSIONS_SPEAKERS_SESSION_ID + "=?", sessionId);
}
case SESSIONS_ID_TRACKS: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_TRACKS_JOIN_TRACKS)
.mapToTable(Tracks._ID, Tables.TRACKS)
.mapToTable(Tracks.TRACK_ID, Tables.TRACKS)
.where(Qualified.SESSIONS_TRACKS_SESSION_ID + "=?", sessionId);
}
case SPEAKERS: {
return builder.table(Tables.SPEAKERS);
}
case SPEAKERS_ID: {
final String speakerId = Speakers.getSpeakerId(uri);
return builder.table(Tables.SPEAKERS)
.where(Speakers.SPEAKER_ID + "=?", speakerId);
}
case SPEAKERS_ID_SESSIONS: {
final String speakerId = Speakers.getSpeakerId(uri);
return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_SPEAKERS_SPEAKER_ID + "=?", speakerId);
}
case VENDORS: {
return builder.table(Tables.VENDORS_JOIN_TRACKS)
.mapToTable(Vendors._ID, Tables.VENDORS)
.mapToTable(Vendors.TRACK_ID, Tables.VENDORS);
}
case VENDORS_STARRED: {
return builder.table(Tables.VENDORS_JOIN_TRACKS)
.mapToTable(Vendors._ID, Tables.VENDORS)
.mapToTable(Vendors.TRACK_ID, Tables.VENDORS)
.where(Vendors.VENDOR_STARRED + "=1");
}
case VENDORS_ID: {
final String vendorId = Vendors.getVendorId(uri);
return builder.table(Tables.VENDORS_JOIN_TRACKS)
.mapToTable(Vendors._ID, Tables.VENDORS)
.mapToTable(Vendors.TRACK_ID, Tables.VENDORS)
.where(Vendors.VENDOR_ID + "=?", vendorId);
}
case ANNOUNCEMENTS: {
return builder.table(Tables.ANNOUNCEMENTS);
}
case ANNOUNCEMENTS_ID: {
final String announcementId = Announcements.getAnnouncementId(uri);
return builder.table(Tables.ANNOUNCEMENTS)
.where(Announcements.ANNOUNCEMENT_ID + "=?", announcementId);
}
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
final int match = sUriMatcher.match(uri);
switch (match) {
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
private interface Subquery {
String BLOCK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_SESSION_ID + ") FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + ")";
String BLOCK_NUM_STARRED_SESSIONS = "(SELECT COUNT(1) FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1)";
String BLOCK_STARRED_SESSION_ID = "(SELECT " + Qualified.SESSIONS_SESSION_ID + " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_TITLE = "(SELECT " + Qualified.SESSIONS_TITLE + " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_HASHTAGS = "(SELECT " + Qualified.SESSIONS_HASHTAGS + " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_URL = "(SELECT " + Qualified.SESSIONS_URL + " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_LIVESTREAM_URL = "(SELECT "
+ Qualified.SESSIONS_LIVESTREAM_URL
+ " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_ROOM_NAME = "(SELECT " + Qualified.ROOMS_ROOM_NAME + " FROM "
+ Tables.SESSIONS_JOIN_ROOMS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_ROOM_ID = "(SELECT " + Qualified.ROOMS_ROOM_ID + " FROM "
+ Tables.SESSIONS_JOIN_ROOMS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String TRACK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_TRACKS_SESSION_ID
+ ") FROM " + Tables.SESSIONS_TRACKS + " WHERE "
+ Qualified.SESSIONS_TRACKS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID + ")";
String TRACK_VENDORS_COUNT = "(SELECT COUNT(" + Qualified.VENDORS_VENDOR_ID + ") FROM "
+ Tables.VENDORS + " WHERE " + Qualified.VENDORS_TRACK_ID + "="
+ Qualified.TRACKS_TRACK_ID + ")";
String SESSIONS_SNIPPET = "snippet(" + Tables.SESSIONS_SEARCH + ",'{','}','\u2026')";
}
/**
* {@link ScheduleContract} fields that are fully qualified with a specific
* parent {@link Tables}. Used when needed to work around SQL ambiguity.
*/
private interface Qualified {
String SESSIONS_SESSION_ID = Tables.SESSIONS + "." + Sessions.SESSION_ID;
String SESSIONS_BLOCK_ID = Tables.SESSIONS + "." + Sessions.BLOCK_ID;
String SESSIONS_ROOM_ID = Tables.SESSIONS + "." + Sessions.ROOM_ID;
String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "."
+ SessionsTracks.SESSION_ID;
String SESSIONS_TRACKS_TRACK_ID = Tables.SESSIONS_TRACKS + "."
+ SessionsTracks.TRACK_ID;
String SESSIONS_SPEAKERS_SESSION_ID = Tables.SESSIONS_SPEAKERS + "."
+ SessionsSpeakers.SESSION_ID;
String SESSIONS_SPEAKERS_SPEAKER_ID = Tables.SESSIONS_SPEAKERS + "."
+ SessionsSpeakers.SPEAKER_ID;
String VENDORS_VENDOR_ID = Tables.VENDORS + "." + Vendors.VENDOR_ID;
String VENDORS_TRACK_ID = Tables.VENDORS + "." + Vendors.TRACK_ID;
String SESSIONS_STARRED = Tables.SESSIONS + "." + Sessions.SESSION_STARRED;
String SESSIONS_TITLE = Tables.SESSIONS + "." + Sessions.SESSION_TITLE;
String SESSIONS_HASHTAGS = Tables.SESSIONS + "." + Sessions.SESSION_HASHTAGS;
String SESSIONS_URL = Tables.SESSIONS + "." + Sessions.SESSION_URL;
String SESSIONS_LIVESTREAM_URL = Tables.SESSIONS + "." + Sessions.SESSION_LIVESTREAM_URL;
String ROOMS_ROOM_NAME = Tables.ROOMS + "." + Rooms.ROOM_NAME;
String ROOMS_ROOM_ID = Tables.ROOMS + "." + Rooms.ROOM_ID;
String TRACKS_TRACK_ID = Tables.TRACKS + "." + Tracks.TRACK_ID;
String BLOCKS_BLOCK_ID = Tables.BLOCKS + "." + Blocks.BLOCK_ID;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/provider/ScheduleProvider.java | Java | asf20 | 39,629 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.provider;
import com.google.android.apps.iosched.util.ParserUtils;
import android.app.SearchManager;
import android.graphics.Color;
import android.net.Uri;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.text.format.DateUtils;
import java.util.List;
/**
* Contract class for interacting with {@link ScheduleProvider}. Unless
* otherwise noted, all time-based fields are milliseconds since epoch and can
* be compared against {@link System#currentTimeMillis()}.
* <p>
* The backing {@link android.content.ContentProvider} assumes that {@link Uri}
* are generated using stronger {@link String} identifiers, instead of
* {@code int} {@link BaseColumns#_ID} values, which are prone to shuffle during
* sync.
*/
public class ScheduleContract {
/**
* Special value for {@link SyncColumns#UPDATED} indicating that an entry
* has never been updated, or doesn't exist yet.
*/
public static final long UPDATED_NEVER = -2;
/**
* Special value for {@link SyncColumns#UPDATED} indicating that the last
* update time is unknown, usually when inserted from a local file source.
*/
public static final long UPDATED_UNKNOWN = -1;
public interface SyncColumns {
/** Last time this entry was updated or synchronized. */
String UPDATED = "updated";
}
interface BlocksColumns {
/** Unique string identifying this block of time. */
String BLOCK_ID = "block_id";
/** Title describing this block of time. */
String BLOCK_TITLE = "block_title";
/** Time when this block starts. */
String BLOCK_START = "block_start";
/** Time when this block ends. */
String BLOCK_END = "block_end";
/** Type describing this block. */
String BLOCK_TYPE = "block_type";
/** Extra string metadata for the block. */
String BLOCK_META = "block_meta";
}
interface TracksColumns {
/** Unique string identifying this track. */
String TRACK_ID = "track_id";
/** Name describing this track. */
String TRACK_NAME = "track_name";
/** Color used to identify this track, in {@link Color#argb} format. */
String TRACK_COLOR = "track_color";
/** Body of text explaining this track in detail. */
String TRACK_ABSTRACT = "track_abstract";
}
interface RoomsColumns {
/** Unique string identifying this room. */
String ROOM_ID = "room_id";
/** Name describing this room. */
String ROOM_NAME = "room_name";
/** Building floor this room exists on. */
String ROOM_FLOOR = "room_floor";
}
interface SessionsColumns {
/** Unique string identifying this session. */
String SESSION_ID = "session_id";
/** The type of session (session, keynote, codelab, etc). */
String SESSION_TYPE = "session_type";
/** Difficulty level of the session. */
String SESSION_LEVEL = "session_level";
/** Title describing this track. */
String SESSION_TITLE = "session_title";
/** Body of text explaining this session in detail. */
String SESSION_ABSTRACT = "session_abstract";
/** Requirements that attendees should meet. */
String SESSION_REQUIREMENTS = "session_requirements";
/** Keywords/tags for this session. */
String SESSION_TAGS = "session_keywords";
/** Hashtag for this session. */
String SESSION_HASHTAGS = "session_hashtag";
/** Full URL to session online. */
String SESSION_URL = "session_url";
/** Full URL to YouTube. */
String SESSION_YOUTUBE_URL = "session_youtube_url";
/** Full URL to PDF. */
String SESSION_PDF_URL = "session_pdf_url";
/** Full URL to official session notes. */
String SESSION_NOTES_URL = "session_notes_url";
/** User-specific flag indicating starred status. */
String SESSION_STARRED = "session_starred";
/** Key for session Calendar event. (Used in ICS or above) */
String SESSION_CAL_EVENT_ID = "session_cal_event_id";
/** The YouTube live stream URL. */
String SESSION_LIVESTREAM_URL = "session_livestream_url";
}
interface SpeakersColumns {
/** Unique string identifying this speaker. */
String SPEAKER_ID = "speaker_id";
/** Name of this speaker. */
String SPEAKER_NAME = "speaker_name";
/** Profile photo of this speaker. */
String SPEAKER_IMAGE_URL = "speaker_image_url";
/** Company this speaker works for. */
String SPEAKER_COMPANY = "speaker_company";
/** Body of text describing this speaker in detail. */
String SPEAKER_ABSTRACT = "speaker_abstract";
/** Full URL to the speaker's profile. */
String SPEAKER_URL = "speaker_url";
}
interface VendorsColumns {
/** Unique string identifying this vendor. */
String VENDOR_ID = "vendor_id";
/** Name of this vendor. */
String VENDOR_NAME = "vendor_name";
/** Location or city this vendor is based in. */
String VENDOR_LOCATION = "vendor_location";
/** Body of text describing this vendor. */
String VENDOR_DESC = "vendor_desc";
/** Link to vendor online. */
String VENDOR_URL = "vendor_url";
/** Body of text describing the product of this vendor. */
String VENDOR_PRODUCT_DESC = "vendor_product_desc";
/** Link to vendor logo. */
String VENDOR_LOGO_URL = "vendor_logo_url";
/** User-specific flag indicating starred status. */
String VENDOR_STARRED = "vendor_starred";
}
interface AnnouncementsColumns {
/** Unique string identifying this announcment. */
String ANNOUNCEMENT_ID = "announcement_id";
/** Title of the announcement. */
String ANNOUNCEMENT_TITLE = "announcement_title";
/** Summary of the announcement. */
String ANNOUNCEMENT_SUMMARY = "announcement_summary";
/** Track announcement belongs to. */
String ANNOUNCEMENT_TRACKS = "announcement_tracks";
/** Full URL for the announcement. */
String ANNOUNCEMENT_URL = "announcement_url";
/** Date of the announcement. */
String ANNOUNCEMENT_DATE = "announcement_date";
}
public static final String CONTENT_AUTHORITY = "com.google.android.apps.iosched";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
private static final String PATH_BLOCKS = "blocks";
private static final String PATH_AT = "at";
private static final String PATH_BETWEEN = "between";
private static final String PATH_TRACKS = "tracks";
private static final String PATH_ROOMS = "rooms";
private static final String PATH_SESSIONS = "sessions";
private static final String PATH_WITH_TRACK = "with_track";
private static final String PATH_STARRED = "starred";
private static final String PATH_SPEAKERS = "speakers";
private static final String PATH_VENDORS = "vendors";
private static final String PATH_ANNOUNCEMENTS = "announcements";
private static final String PATH_SEARCH = "search";
private static final String PATH_SEARCH_SUGGEST = "search_suggest_query";
/**
* Blocks are generic timeslots that {@link Sessions} and other related
* events fall into.
*/
public static class Blocks implements BlocksColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_BLOCKS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.block";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.block";
/** Count of {@link Sessions} inside given block. */
public static final String SESSIONS_COUNT = "sessions_count";
/**
* Flag indicating the number of sessions inside this block that have
* {@link Sessions#SESSION_STARRED} set.
*/
public static final String NUM_STARRED_SESSIONS = "num_starred_sessions";
/**
* The {@link Sessions#SESSION_ID} of the first starred session in this
* block.
*/
public static final String STARRED_SESSION_ID = "starred_session_id";
/**
* The {@link Sessions#SESSION_TITLE} of the first starred session in
* this block.
*/
public static final String STARRED_SESSION_TITLE = "starred_session_title";
/**
* The {@link Sessions#SESSION_LIVESTREAM_URL} of the first starred
* session in this block.
*/
public static final String STARRED_SESSION_LIVESTREAM_URL =
"starred_session_livestream_url";
/**
* The {@link Rooms#ROOM_NAME} of the first starred session in this
* block.
*/
public static final String STARRED_SESSION_ROOM_NAME = "starred_session_room_name";
/**
* The {@link Rooms#ROOM_ID} of the first starred session in this block.
*/
public static final String STARRED_SESSION_ROOM_ID = "starred_session_room_id";
/**
* The {@link Sessions#SESSION_HASHTAGS} of the first starred session in
* this block.
*/
public static final String STARRED_SESSION_HASHTAGS = "starred_session_hashtags";
/**
* The {@link Sessions#SESSION_URL} of the first starred session in this
* block.
*/
public static final String STARRED_SESSION_URL = "starred_session_url";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC, "
+ BlocksColumns.BLOCK_END + " ASC";
public static final String EMPTY_SESSIONS_SELECTION = "(" + BLOCK_TYPE
+ " = '" + ParserUtils.BLOCK_TYPE_SESSION + "' OR " + BLOCK_TYPE
+ " = '" + ParserUtils.BLOCK_TYPE_CODE_LAB + "') AND "
+ SESSIONS_COUNT + " = 0";
/** Build {@link Uri} for requested {@link #BLOCK_ID}. */
public static Uri buildBlockUri(String blockId) {
return CONTENT_URI.buildUpon().appendPath(blockId).build();
}
/**
* Build {@link Uri} that references any {@link Sessions} associated
* with the requested {@link #BLOCK_ID}.
*/
public static Uri buildSessionsUri(String blockId) {
return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS).build();
}
/**
* Build {@link Uri} that references starred {@link Sessions} associated
* with the requested {@link #BLOCK_ID}.
*/
public static Uri buildStarredSessionsUri(String blockId) {
return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS)
.appendPath(PATH_STARRED).build();
}
/**
* Build {@link Uri} that references any {@link Blocks} that occur
* between the requested time boundaries.
*/
public static Uri buildBlocksBetweenDirUri(long startTime, long endTime) {
return CONTENT_URI.buildUpon().appendPath(PATH_BETWEEN).appendPath(
String.valueOf(startTime)).appendPath(String.valueOf(endTime)).build();
}
/** Read {@link #BLOCK_ID} from {@link Blocks} {@link Uri}. */
public static String getBlockId(Uri uri) {
return uri.getPathSegments().get(1);
}
/**
* Generate a {@link #BLOCK_ID} that will always match the requested
* {@link Blocks} details.
*/
public static String generateBlockId(long startTime, long endTime) {
startTime /= DateUtils.SECOND_IN_MILLIS;
endTime /= DateUtils.SECOND_IN_MILLIS;
return ParserUtils.sanitizeId(startTime + "-" + endTime);
}
}
/**
* Tracks are overall categories for {@link Sessions} and {@link Vendors},
* such as "Android" or "Enterprise."
*/
public static class Tracks implements TracksColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_TRACKS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.track";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.track";
/** "All tracks" ID. */
public static final String ALL_TRACK_ID = "all";
public static final String CODELABS_TRACK_ID = generateTrackId("Code Labs");
public static final String TECH_TALK_TRACK_ID = generateTrackId("Tech Talk");
/** Count of {@link Sessions} inside given track. */
public static final String SESSIONS_COUNT = "sessions_count";
/** Count of {@link Vendors} inside given track. */
public static final String VENDORS_COUNT = "vendors_count";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = TracksColumns.TRACK_NAME + " ASC";
/** Build {@link Uri} for requested {@link #TRACK_ID}. */
public static Uri buildTrackUri(String trackId) {
return CONTENT_URI.buildUpon().appendPath(trackId).build();
}
/**
* Build {@link Uri} that references any {@link Sessions} associated
* with the requested {@link #TRACK_ID}.
*/
public static Uri buildSessionsUri(String trackId) {
return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_SESSIONS).build();
}
/**
* Build {@link Uri} that references any {@link Vendors} associated with
* the requested {@link #TRACK_ID}.
*/
public static Uri buildVendorsUri(String trackId) {
return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_VENDORS).build();
}
/** Read {@link #TRACK_ID} from {@link Tracks} {@link Uri}. */
public static String getTrackId(Uri uri) {
return uri.getPathSegments().get(1);
}
/**
* Generate a {@link #TRACK_ID} that will always match the requested
* {@link Tracks} details.
*/
public static String generateTrackId(String name) {
return ParserUtils.sanitizeId(name);
}
}
/**
* Rooms are physical locations at the conference venue.
*/
public static class Rooms implements RoomsColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_ROOMS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.room";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.room";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = RoomsColumns.ROOM_FLOOR + " ASC, "
+ RoomsColumns.ROOM_NAME + " COLLATE NOCASE ASC";
/** Build {@link Uri} for requested {@link #ROOM_ID}. */
public static Uri buildRoomUri(String roomId) {
return CONTENT_URI.buildUpon().appendPath(roomId).build();
}
/**
* Build {@link Uri} that references any {@link Sessions} associated
* with the requested {@link #ROOM_ID}.
*/
public static Uri buildSessionsDirUri(String roomId) {
return CONTENT_URI.buildUpon().appendPath(roomId).appendPath(PATH_SESSIONS).build();
}
/** Read {@link #ROOM_ID} from {@link Rooms} {@link Uri}. */
public static String getRoomId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
/**
* Each session is a block of time that has a {@link Tracks}, a
* {@link Rooms}, and zero or more {@link Speakers}.
*/
public static class Sessions implements SessionsColumns, BlocksColumns, RoomsColumns,
SyncColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_SESSIONS).build();
public static final Uri CONTENT_STARRED_URI =
CONTENT_URI.buildUpon().appendPath(PATH_STARRED).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.session";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.session";
public static final String BLOCK_ID = "block_id";
public static final String ROOM_ID = "room_id";
public static final String SEARCH_SNIPPET = "search_snippet";
// TODO: shortcut primary track to offer sub-sorting here
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC,"
+ SessionsColumns.SESSION_TITLE + " COLLATE NOCASE ASC";
public static final String LIVESTREAM_SELECTION =
SESSION_LIVESTREAM_URL + " is not null AND " + SESSION_LIVESTREAM_URL + "!=''";
// Used to fetch sessions for a particular time
public static final String AT_TIME_SELECTION =
BLOCK_START + " < ? and " + BLOCK_END + " " + "> ?";
// Builds selectionArgs for {@link AT_TIME_SELECTION}
public static String[] buildAtTimeSelectionArgs(long time) {
final String timeString = String.valueOf(time);
return new String[] { timeString, timeString };
}
// Used to fetch upcoming sessions
public static final String UPCOMING_SELECTION =
BLOCK_START + " = (select min(" + BLOCK_START + ") from " +
ScheduleDatabase.Tables.BLOCKS_JOIN_SESSIONS + " where " + LIVESTREAM_SELECTION +
" and " + BLOCK_START + " >" + " ?)";
// Builds selectionArgs for {@link UPCOMING_SELECTION}
public static String[] buildUpcomingSelectionArgs(long minTime) {
return new String[] { String.valueOf(minTime) };
}
/** Build {@link Uri} for requested {@link #SESSION_ID}. */
public static Uri buildSessionUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId).build();
}
/**
* Build {@link Uri} that references any {@link Speakers} associated
* with the requested {@link #SESSION_ID}.
*/
public static Uri buildSpeakersDirUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_SPEAKERS).build();
}
/**
* Build {@link Uri} that includes track detail with list of sessions.
*/
public static Uri buildWithTracksUri() {
return CONTENT_URI.buildUpon().appendPath(PATH_WITH_TRACK).build();
}
/**
* Build {@link Uri} that includes track detail for a specific session.
*/
public static Uri buildWithTracksUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId)
.appendPath(PATH_WITH_TRACK).build();
}
/**
* Build {@link Uri} that references any {@link Tracks} associated with
* the requested {@link #SESSION_ID}.
*/
public static Uri buildTracksDirUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_TRACKS).build();
}
public static Uri buildSessionsAtDirUri(long time) {
return CONTENT_URI.buildUpon().appendPath(PATH_AT).appendPath(String.valueOf(time))
.build();
}
public static Uri buildSearchUri(String query) {
return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build();
}
public static boolean isSearchUri(Uri uri) {
List<String> pathSegments = uri.getPathSegments();
return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1));
}
/** Read {@link #SESSION_ID} from {@link Sessions} {@link Uri}. */
public static String getSessionId(Uri uri) {
return uri.getPathSegments().get(1);
}
public static String getSearchQuery(Uri uri) {
return uri.getPathSegments().get(2);
}
}
/**
* Speakers are individual people that lead {@link Sessions}.
*/
public static class Speakers implements SpeakersColumns, SyncColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_SPEAKERS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.speaker";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.speaker";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = SpeakersColumns.SPEAKER_NAME
+ " COLLATE NOCASE ASC";
/** Build {@link Uri} for requested {@link #SPEAKER_ID}. */
public static Uri buildSpeakerUri(String speakerId) {
return CONTENT_URI.buildUpon().appendPath(speakerId).build();
}
/**
* Build {@link Uri} that references any {@link Sessions} associated
* with the requested {@link #SPEAKER_ID}.
*/
public static Uri buildSessionsDirUri(String speakerId) {
return CONTENT_URI.buildUpon().appendPath(speakerId).appendPath(PATH_SESSIONS).build();
}
/** Read {@link #SPEAKER_ID} from {@link Speakers} {@link Uri}. */
public static String getSpeakerId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
/**
* Each vendor is a company appearing at the conference that may be
* associated with a specific {@link Tracks}.
*/
public static class Vendors implements VendorsColumns, SyncColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_VENDORS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.vendor";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.vendor";
/** {@link Tracks#TRACK_ID} that this vendor belongs to. */
public static final String TRACK_ID = "track_id";
public static final String SEARCH_SNIPPET = "search_snippet";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = VendorsColumns.VENDOR_NAME
+ " COLLATE NOCASE ASC";
/** Build {@link Uri} for requested {@link #VENDOR_ID}. */
public static Uri buildVendorUri(String vendorId) {
return CONTENT_URI.buildUpon().appendPath(vendorId).build();
}
public static Uri buildSearchUri(String query) {
return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build();
}
public static boolean isSearchUri(Uri uri) {
List<String> pathSegments = uri.getPathSegments();
return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1));
}
/** Read {@link #VENDOR_ID} from {@link Vendors} {@link Uri}. */
public static String getVendorId(Uri uri) {
return uri.getPathSegments().get(1);
}
public static String getSearchQuery(Uri uri) {
return uri.getPathSegments().get(2);
}
/**
* Generate a {@link #VENDOR_ID} that will always match the requested
* {@link Vendors} details.
*/
public static String generateVendorId(String companyName) {
return ParserUtils.sanitizeId(companyName);
}
}
/**
* Announcements of breaking news
*/
public static class Announcements implements AnnouncementsColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_ANNOUNCEMENTS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.announcement";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.announcement";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = AnnouncementsColumns.ANNOUNCEMENT_DATE
+ " COLLATE NOCASE ASC";
/** Build {@link Uri} for requested {@link #ANNOUNCEMENT_ID}. */
public static Uri buildAnnouncementUri(String announcementId) {
return CONTENT_URI.buildUpon().appendPath(announcementId).build();
}
/**
* Build {@link Uri} that references any {@link Announcements}
* associated with the requested {@link #ANNOUNCEMENT_ID}.
*/
public static Uri buildAnnouncementsDirUri(String announcementId) {
return CONTENT_URI.buildUpon().appendPath(announcementId)
.appendPath(PATH_ANNOUNCEMENTS).build();
}
/**
* Read {@link #ANNOUNCEMENT_ID} from {@link Announcements} {@link Uri}.
*/
public static String getAnnouncementId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
public static class SearchSuggest {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_SEARCH_SUGGEST).build();
public static final String DEFAULT_SORT = SearchManager.SUGGEST_COLUMN_TEXT_1
+ " COLLATE NOCASE ASC";
}
public static Uri addCallerIsSyncAdapterParameter(Uri uri) {
return uri.buildUpon().appendQueryParameter(
ContactsContract.CALLER_IS_SYNCADAPTER, "true").build();
}
public static boolean hasCallerIsSyncAdapterParameter(Uri uri) {
return TextUtils.equals("true",
uri.getQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER));
}
private ScheduleContract() {
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/provider/ScheduleContract.java | Java | asf20 | 27,130 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.calendar;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.AccountUtils;
import com.google.android.apps.iosched.util.UIUtils;
import android.annotation.TargetApi;
import android.app.IntentService;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.CalendarContract;
import android.text.TextUtils;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Background {@link android.app.Service} that adds or removes session Calendar events through
* the {@link CalendarContract} API available in Android 4.0 or above.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class SessionCalendarService extends IntentService {
private static final String TAG = makeLogTag(SessionCalendarService.class);
public static final String ACTION_ADD_SESSION_CALENDAR =
"com.google.android.apps.iosched.action.ADD_SESSION_CALENDAR";
public static final String ACTION_REMOVE_SESSION_CALENDAR =
"com.google.android.apps.iosched.action.REMOVE_SESSION_CALENDAR";
public static final String ACTION_UPDATE_ALL_SESSIONS_CALENDAR =
"com.google.android.apps.iosched.action.UPDATE_ALL_SESSIONS_CALENDAR";
public static final String ACTION_UPDATE_ALL_SESSIONS_CALENDAR_COMPLETED =
"com.google.android.apps.iosched.action.UPDATE_CALENDAR_COMPLETED";
public static final String ACTION_CLEAR_ALL_SESSIONS_CALENDAR =
"com.google.android.apps.iosched.action.CLEAR_ALL_SESSIONS_CALENDAR";
public static final String EXTRA_ACCOUNT_NAME =
"com.google.android.apps.iosched.extra.ACCOUNT_NAME";
public static final String EXTRA_SESSION_BLOCK_START =
"com.google.android.apps.iosched.extra.SESSION_BLOCK_START";
public static final String EXTRA_SESSION_BLOCK_END =
"com.google.android.apps.iosched.extra.SESSION_BLOCK_END";
public static final String EXTRA_SESSION_TITLE =
"com.google.android.apps.iosched.extra.SESSION_TITLE";
public static final String EXTRA_SESSION_ROOM =
"com.google.android.apps.iosched.extra.SESSION_ROOM";
private static final long INVALID_CALENDAR_ID = -1;
// TODO: localize
private static final String CALENDAR_CLEAR_SEARCH_LIKE_EXPRESSION =
"%added by Google I/O 2012%";
public SessionCalendarService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
final String action = intent.getAction();
final ContentResolver resolver = getContentResolver();
boolean isAddEvent = false;
if (ACTION_ADD_SESSION_CALENDAR.equals(action)) {
isAddEvent = true;
} else if (ACTION_REMOVE_SESSION_CALENDAR.equals(action)) {
isAddEvent = false;
} else if (ACTION_UPDATE_ALL_SESSIONS_CALENDAR.equals(action)) {
try {
getContentResolver().applyBatch(CalendarContract.AUTHORITY,
processAllSessionsCalendar(resolver, getCalendarId(intent)));
sendBroadcast(new Intent(
SessionCalendarService.ACTION_UPDATE_ALL_SESSIONS_CALENDAR_COMPLETED));
} catch (RemoteException e) {
LOGE(TAG, "Error adding all sessions to Google Calendar", e);
} catch (OperationApplicationException e) {
LOGE(TAG, "Error adding all sessions to Google Calendar", e);
}
} else if (ACTION_CLEAR_ALL_SESSIONS_CALENDAR.equals(action)) {
try {
getContentResolver().applyBatch(CalendarContract.AUTHORITY,
processClearAllSessions(resolver, getCalendarId(intent)));
} catch (RemoteException e) {
LOGE(TAG, "Error clearing all sessions from Google Calendar", e);
} catch (OperationApplicationException e) {
LOGE(TAG, "Error clearing all sessions from Google Calendar", e);
}
} else {
return;
}
final Uri uri = intent.getData();
final Bundle extras = intent.getExtras();
if (uri == null || extras == null) {
return;
}
try {
resolver.applyBatch(CalendarContract.AUTHORITY,
processSessionCalendar(resolver, getCalendarId(intent), isAddEvent, uri,
extras.getLong(EXTRA_SESSION_BLOCK_START),
extras.getLong(EXTRA_SESSION_BLOCK_END),
extras.getString(EXTRA_SESSION_TITLE),
extras.getString(EXTRA_SESSION_ROOM)));
} catch (RemoteException e) {
LOGE(TAG, "Error adding session to Google Calendar", e);
} catch (OperationApplicationException e) {
LOGE(TAG, "Error adding session to Google Calendar", e);
}
}
/**
* Gets the currently-logged in user's Google Calendar, or the Google Calendar for the user
* specified in the given intent's {@link #EXTRA_ACCOUNT_NAME}.
*/
private long getCalendarId(Intent intent) {
final String accountName;
if (intent != null && intent.hasExtra(EXTRA_ACCOUNT_NAME)) {
accountName = intent.getStringExtra(EXTRA_ACCOUNT_NAME);
} else {
accountName = AccountUtils.getChosenAccountName(this);
}
if (TextUtils.isEmpty(accountName)) {
return INVALID_CALENDAR_ID;
}
// TODO: The calendar ID should be stored in shared preferences upon choosing an account.
Cursor calendarsCursor = getContentResolver().query(
CalendarContract.Calendars.CONTENT_URI,
new String[]{"_id"},
// TODO: Handle case where the calendar is not displayed or not sync'd
"account_name = ownerAccount and account_name = ?",
new String[]{accountName},
null);
long calendarId = INVALID_CALENDAR_ID;
if (calendarsCursor != null && calendarsCursor.moveToFirst()) {
calendarId = calendarsCursor.getLong(0);
calendarsCursor.close();
}
return calendarId;
}
private String makeCalendarEventTitle(String sessionTitle) {
return sessionTitle + getResources().getString(R.string.session_calendar_suffix);
}
/**
* Processes all sessions in the
* {@link com.google.android.apps.iosched.provider.ScheduleProvider}, adding or removing
* calendar events to/from the specified Google Calendar depending on whether a session is
* in the user's schedule or not.
*/
private ArrayList<ContentProviderOperation> processAllSessionsCalendar(ContentResolver resolver,
final long calendarId) {
ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
// Unable to find the Calendar associated with the user. Stop here.
if (calendarId == INVALID_CALENDAR_ID) {
return batch;
}
// Retrieves all sessions. For each session, add to Calendar if starred and attempt to
// remove from Calendar if unstarred.
Cursor cursor = resolver.query(
ScheduleContract.Sessions.CONTENT_URI,
SessionsQuery.PROJECTION,
null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
Uri uri = ScheduleContract.Sessions.buildSessionUri(
Long.valueOf(cursor.getLong(0)).toString());
boolean isAddEvent = (cursor.getInt(SessionsQuery.SESSION_STARRED) == 1);
if (isAddEvent) {
batch.addAll(processSessionCalendar(resolver,
calendarId, isAddEvent, uri,
cursor.getLong(SessionsQuery.BLOCK_START),
cursor.getLong(SessionsQuery.BLOCK_END),
cursor.getString(SessionsQuery.SESSION_TITLE),
cursor.getString(SessionsQuery.ROOM_NAME)));
}
}
cursor.close();
}
return batch;
}
/**
* Adds or removes a single session to/from the specified Google Calendar.
*/
private ArrayList<ContentProviderOperation> processSessionCalendar(
final ContentResolver resolver,
final long calendarId, final boolean isAddEvent,
final Uri sessionUri, final long sessionBlockStart, final long sessionBlockEnd,
final String sessionTitle, final String sessionRoom) {
ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
// Unable to find the Calendar associated with the user. Stop here.
if (calendarId == INVALID_CALENDAR_ID) {
return batch;
}
final String calendarEventTitle = makeCalendarEventTitle(sessionTitle);
Cursor cursor;
ContentValues values = new ContentValues();
// Add Calendar event.
if (isAddEvent) {
if (sessionBlockStart == 0L || sessionBlockEnd == 0L || sessionTitle == null) {
LOGW(TAG, "Unable to add a Calendar event due to insufficient input parameters.");
return batch;
}
// Check if the calendar event exists first. If it does, we don't want to add a
// duplicate one.
cursor = resolver.query(
CalendarContract.Events.CONTENT_URI, // URI
new String[] {CalendarContract.Events._ID}, // Projection
CalendarContract.Events.CALENDAR_ID + "=? and " // Selection
+ CalendarContract.Events.TITLE + "=? and "
+ CalendarContract.Events.DTSTART + ">=? and "
+ CalendarContract.Events.DTEND + "<=?",
new String[]{ // Selection args
Long.valueOf(calendarId).toString(),
calendarEventTitle,
Long.toString(UIUtils.CONFERENCE_START_MILLIS),
Long.toString(UIUtils.CONFERENCE_END_MILLIS)
},
null);
long newEventId = -1;
if (cursor != null && cursor.moveToFirst()) {
// Calendar event already exists for this session.
newEventId = cursor.getLong(0);
cursor.close();
} else {
// Calendar event doesn't exist, create it.
// NOTE: we can't use batch processing here because we need the result of
// the insert.
values.clear();
values.put(CalendarContract.Events.DTSTART, sessionBlockStart);
values.put(CalendarContract.Events.DTEND, sessionBlockEnd);
values.put(CalendarContract.Events.EVENT_LOCATION, sessionRoom);
values.put(CalendarContract.Events.TITLE, calendarEventTitle);
values.put(CalendarContract.Events.CALENDAR_ID, calendarId);
values.put(CalendarContract.Events.EVENT_TIMEZONE,
UIUtils.CONFERENCE_TIME_ZONE.getID());
Uri eventUri = resolver.insert(CalendarContract.Events.CONTENT_URI, values);
String eventId = eventUri.getLastPathSegment();
if (eventId == null) {
return batch; // Should be empty at this point
}
newEventId = Long.valueOf(eventId);
// Since we're adding session reminder to system notification, we're not creating
// Calendar event reminders. If we were to create Calendar event reminders, this
// is how we would do it.
//values.put(CalendarContract.Reminders.EVENT_ID, Integer.valueOf(eventId));
//values.put(CalendarContract.Reminders.MINUTES, 10);
//values.put(CalendarContract.Reminders.METHOD,
// CalendarContract.Reminders.METHOD_ALERT); // Or default?
//cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
//values.clear();
}
// Update the session in our own provider with the newly created calendar event ID.
values.clear();
values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, newEventId);
resolver.update(sessionUri, values, null, null);
} else {
// Remove Calendar event, if exists.
// Get the event calendar id.
cursor = resolver.query(sessionUri,
new String[] {ScheduleContract.Sessions.SESSION_CAL_EVENT_ID},
null, null, null);
long calendarEventId = -1;
if (cursor != null && cursor.moveToFirst()) {
calendarEventId = cursor.getLong(0);
cursor.close();
}
// Try to remove the Calendar Event based on key. If successful, move on;
// otherwise, remove the event based on Event title.
int affectedRows = 0;
if (calendarEventId != -1) {
affectedRows = resolver.delete(
CalendarContract.Events.CONTENT_URI,
CalendarContract.Events._ID + "=?",
new String[]{Long.valueOf(calendarEventId).toString()});
}
if (affectedRows == 0) {
resolver.delete(CalendarContract.Events.CONTENT_URI,
String.format("%s=? and %s=? and %s=? and %s=?",
CalendarContract.Events.CALENDAR_ID,
CalendarContract.Events.TITLE,
CalendarContract.Events.DTSTART,
CalendarContract.Events.DTEND),
new String[]{Long.valueOf(calendarId).toString(),
calendarEventTitle,
Long.valueOf(sessionBlockStart).toString(),
Long.valueOf(sessionBlockEnd).toString()});
}
// Remove the session and calendar event association.
values.clear();
values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, (Long) null);
resolver.update(sessionUri, values, null, null);
}
return batch;
}
/**
* Removes all calendar entries associated with Google I/O 2012.
*/
private ArrayList<ContentProviderOperation> processClearAllSessions(
ContentResolver resolver, long calendarId) {
ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
// Unable to find the Calendar associated with the user. Stop here.
if (calendarId == INVALID_CALENDAR_ID) {
return batch;
}
// Delete all calendar entries matching the given title within the given time period
batch.add(ContentProviderOperation
.newDelete(CalendarContract.Events.CONTENT_URI)
.withSelection(
CalendarContract.Events.CALENDAR_ID + " = ? and "
+ CalendarContract.Events.TITLE + " LIKE ? and "
+ CalendarContract.Events.DTSTART + ">= ? and "
+ CalendarContract.Events.DTEND + "<= ?",
new String[]{
Long.toString(calendarId),
CALENDAR_CLEAR_SEARCH_LIKE_EXPRESSION,
Long.toString(UIUtils.CONFERENCE_START_MILLIS),
Long.toString(UIUtils.CONFERENCE_END_MILLIS)
})
.build());
return batch;
}
private interface SessionsQuery {
String[] PROJECTION = {
ScheduleContract.Sessions._ID,
ScheduleContract.Sessions.BLOCK_START,
ScheduleContract.Sessions.BLOCK_END,
ScheduleContract.Sessions.SESSION_TITLE,
ScheduleContract.Sessions.ROOM_NAME,
ScheduleContract.Sessions.SESSION_STARRED,
};
int _ID = 0;
int BLOCK_START = 1;
int BLOCK_END = 2;
int SESSION_TITLE = 3;
int ROOM_NAME = 4;
int SESSION_STARRED = 5;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/calendar/SessionCalendarService.java | Java | asf20 | 17,856 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.calendar;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* {@link BroadcastReceiver} to reinitialize {@link android.app.AlarmManager} for all starred
* session blocks.
*/
public class SessionAlarmReceiver extends BroadcastReceiver {
public static final String TAG = makeLogTag(SessionAlarmReceiver.class);
@Override
public void onReceive(Context context, Intent intent) {
Intent scheduleIntent = new Intent(
SessionAlarmService.ACTION_SCHEDULE_ALL_STARRED_BLOCKS,
null, context, SessionAlarmService.class);
context.startService(scheduleIntent);
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/calendar/SessionAlarmReceiver.java | Java | asf20 | 1,391 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.calendar;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.UIUtils;
import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Background service to handle scheduling of starred session notification via
* {@link android.app.AlarmManager}.
*/
public class SessionAlarmService extends IntentService {
private static final String TAG = makeLogTag(SessionAlarmService.class);
public static final String ACTION_NOTIFY_SESSION =
"com.google.android.apps.iosched.action.NOTIFY_SESSION";
public static final String ACTION_SCHEDULE_STARRED_BLOCK =
"com.google.android.apps.iosched.action.SCHEDULE_STARRED_BLOCK";
public static final String ACTION_SCHEDULE_ALL_STARRED_BLOCKS =
"com.google.android.apps.iosched.action.SCHEDULE_ALL_STARRED_BLOCKS";
public static final String EXTRA_SESSION_START =
"com.google.android.apps.iosched.extra.SESSION_START";
public static final String EXTRA_SESSION_END =
"com.google.android.apps.iosched.extra.SESSION_END";
public static final String EXTRA_SESSION_ALARM_OFFSET =
"com.google.android.apps.iosched.extra.SESSION_ALARM_OFFSET";
private static final int NOTIFICATION_ID = 100;
// pulsate every 1 second, indicating a relatively high degree of urgency
private static final int NOTIFICATION_LED_ON_MS = 100;
private static final int NOTIFICATION_LED_OFF_MS = 1000;
private static final int NOTIFICATION_ARGB_COLOR = 0xff0088ff; // cyan
private static final long ONE_MINUTE_MILLIS = 1 * 60 * 1000;
private static final long TEN_MINUTES_MILLIS = 10 * ONE_MINUTE_MILLIS;
private static final long UNDEFINED_ALARM_OFFSET = -1;
public SessionAlarmService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
final String action = intent.getAction();
if (ACTION_SCHEDULE_ALL_STARRED_BLOCKS.equals(action)) {
scheduleAllStarredBlocks();
return;
}
final long sessionStart = intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_START, -1);
if (sessionStart == -1) {
return;
}
final long sessionEnd = intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_END, -1);
if (sessionEnd == -1) {
return;
}
final long sessionAlarmOffset =
intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET,
UNDEFINED_ALARM_OFFSET);
if (ACTION_NOTIFY_SESSION.equals(action)) {
notifySession(sessionStart, sessionEnd, sessionAlarmOffset);
} else if (ACTION_SCHEDULE_STARRED_BLOCK.equals(action)) {
scheduleAlarm(sessionStart, sessionEnd, sessionAlarmOffset);
}
}
private void scheduleAlarm(final long sessionStart,
final long sessionEnd, final long alarmOffset) {
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(NOTIFICATION_ID);
final long currentTime = System.currentTimeMillis();
// If the session is already started, do not schedule system notification.
if (currentTime > sessionStart) {
return;
}
// By default, sets alarm to go off at 10 minutes before session start time. If alarm
// offset is provided, alarm is set to go off by that much time from now.
long alarmTime;
if (alarmOffset == UNDEFINED_ALARM_OFFSET) {
alarmTime = sessionStart - TEN_MINUTES_MILLIS;
} else {
alarmTime = currentTime + alarmOffset;
}
final Intent alarmIntent = new Intent(
ACTION_NOTIFY_SESSION,
null,
this,
SessionAlarmService.class);
// Setting data to ensure intent's uniqueness for different session start times.
alarmIntent.setData(
new Uri.Builder()
.authority(ScheduleContract.CONTENT_AUTHORITY)
.path(String.valueOf(sessionStart))
.build());
alarmIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart);
alarmIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd);
alarmIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, alarmOffset);
final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// Schedule an alarm to be fired to notify user of added sessions are about to begin.
am.set(AlarmManager.RTC_WAKEUP, alarmTime,
PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT));
}
/**
* Constructs and triggers system notification for when starred sessions are about to begin.
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void notifySession(final long sessionStart,
final long sessionEnd, final long alarmOffset) {
long currentTime = System.currentTimeMillis();
if (sessionStart < currentTime) {
return;
}
// Avoid repeated notifications.
if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock(
this, ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd))) {
return;
}
final ContentResolver resolver = getContentResolver();
final Uri starredBlockUri = ScheduleContract.Blocks.buildStarredSessionsUri(
ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd));
Cursor cursor = resolver.query(starredBlockUri,
new String[]{
ScheduleContract.Blocks.NUM_STARRED_SESSIONS,
ScheduleContract.Sessions.SESSION_TITLE
},
null, null, null);
int starredCount = 0;
ArrayList<String> starredSessionTitles = new ArrayList<String>();
while (cursor.moveToNext()) {
starredSessionTitles.add(cursor.getString(1));
starredCount = cursor.getInt(0);
}
if (starredCount < 1) {
return;
}
// Generates the pending intent which gets fired when the user touches on the notification.
Intent sessionIntent = new Intent(Intent.ACTION_VIEW, starredBlockUri);
sessionIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, sessionIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
final Resources res = getResources();
String contentText;
int minutesLeft = (int) (sessionStart - currentTime + 59000) / 60000;
if (minutesLeft < 1) {
minutesLeft = 1;
}
if (starredCount == 1) {
contentText = res.getString(R.string.session_notification_text_1, minutesLeft);
} else {
contentText = res.getQuantityString(R.plurals.session_notification_text,
starredCount - 1,
minutesLeft,
starredCount - 1);
}
// Construct a notification. Use Jelly Bean (API 16) rich notifications if possible.
Notification notification;
if (UIUtils.hasJellyBean()) {
// Rich notifications
Notification.Builder builder = new Notification.Builder(this)
.setContentTitle(starredSessionTitles.get(0))
.setContentText(contentText)
.setTicker(res.getQuantityString(R.plurals.session_notification_ticker,
starredCount,
starredCount))
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setLights(
SessionAlarmService.NOTIFICATION_ARGB_COLOR,
SessionAlarmService.NOTIFICATION_LED_ON_MS,
SessionAlarmService.NOTIFICATION_LED_OFF_MS)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentIntent(pi)
.setPriority(Notification.PRIORITY_MAX)
.setAutoCancel(true);
if (minutesLeft > 5) {
builder.addAction(R.drawable.ic_alarm_holo_dark,
String.format(res.getString(R.string.snooze_x_min), 5),
createSnoozeIntent(sessionStart, sessionEnd, 5));
}
Notification.InboxStyle richNotification = new Notification.InboxStyle(
builder)
.setBigContentTitle(res.getQuantityString(R.plurals.session_notification_title,
starredCount,
minutesLeft,
starredCount));
// Adds starred sessions starting at this time block to the notification.
for (int i = 0; i < starredCount; i++) {
richNotification.addLine(starredSessionTitles.get(i));
}
notification = richNotification.build();
} else {
// Pre-Jelly Bean non-rich notifications
notification = new NotificationCompat.Builder(this)
.setContentTitle(starredSessionTitles.get(0))
.setContentText(contentText)
.setTicker(res.getQuantityString(R.plurals.session_notification_ticker,
starredCount,
starredCount))
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setLights(
SessionAlarmService.NOTIFICATION_ARGB_COLOR,
SessionAlarmService.NOTIFICATION_LED_ON_MS,
SessionAlarmService.NOTIFICATION_LED_OFF_MS)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentIntent(pi)
.getNotification();
}
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(NOTIFICATION_ID, notification);
}
private PendingIntent createSnoozeIntent(final long sessionStart, final long sessionEnd,
final int snoozeMinutes) {
Intent scheduleIntent = new Intent(
SessionAlarmService.ACTION_SCHEDULE_STARRED_BLOCK,
null, this, SessionAlarmService.class);
scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart);
scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd);
scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET,
snoozeMinutes * ONE_MINUTE_MILLIS);
return PendingIntent.getService(this, 0, scheduleIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
}
private void scheduleAllStarredBlocks() {
final Cursor cursor = getContentResolver().query(
ScheduleContract.Sessions.CONTENT_STARRED_URI,
new String[] {
"distinct " + ScheduleContract.Sessions.BLOCK_START,
ScheduleContract.Sessions.BLOCK_END
},
null, null, null);
if (cursor == null) {
return;
}
while (cursor.moveToNext()) {
final long sessionStart = cursor.getLong(0);
final long sessionEnd = cursor.getLong(1);
scheduleAlarm(sessionStart, sessionEnd, UNDEFINED_ALARM_OFFSET);
}
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/calendar/SessionAlarmService.java | Java | asf20 | 12,996 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import android.graphics.Rect;
import android.graphics.RectF;
import android.view.MotionEvent;
import android.view.TouchDelegate;
import android.view.View;
/**
* {@link TouchDelegate} that gates {@link MotionEvent} instances by comparing
* then against fractional dimensions of the source view.
* <p>
* This is particularly useful when you want to define a rectangle in terms of
* the source dimensions, but when those dimensions might change due to pending
* or future layout passes.
* <p>
* One example is catching touches that occur in the top-right quadrant of
* {@code sourceParent}, and relaying them to {@code targetChild}. This could be
* done with: <code>
* FractionalTouchDelegate.setupDelegate(sourceParent, targetChild, new RectF(0.5f, 0f, 1f, 0.5f));
* </code>
*/
public class FractionalTouchDelegate extends TouchDelegate {
private View mSource;
private View mTarget;
private RectF mSourceFraction;
private Rect mScrap = new Rect();
/** Cached full dimensions of {@link #mSource}. */
private Rect mSourceFull = new Rect();
/** Cached projection of {@link #mSourceFraction} onto {@link #mSource}. */
private Rect mSourcePartial = new Rect();
private boolean mDelegateTargeted;
public FractionalTouchDelegate(View source, View target, RectF sourceFraction) {
super(new Rect(0, 0, 0, 0), target);
mSource = source;
mTarget = target;
mSourceFraction = sourceFraction;
}
/**
* Helper to create and setup a {@link FractionalTouchDelegate} between the
* given {@link View}.
*
* @param source Larger source {@link View}, usually a parent, that will be
* assigned {@link View#setTouchDelegate(TouchDelegate)}.
* @param target Smaller target {@link View} which will receive
* {@link MotionEvent} that land in requested fractional area.
* @param sourceFraction Fractional area projected onto source {@link View}
* which determines when {@link MotionEvent} will be passed to
* target {@link View}.
*/
public static void setupDelegate(View source, View target, RectF sourceFraction) {
source.setTouchDelegate(new FractionalTouchDelegate(source, target, sourceFraction));
}
/**
* Consider updating {@link #mSourcePartial} when {@link #mSource}
* dimensions have changed.
*/
private void updateSourcePartial() {
mSource.getHitRect(mScrap);
if (!mScrap.equals(mSourceFull)) {
// Copy over and calculate fractional rectangle
mSourceFull.set(mScrap);
final int width = mSourceFull.width();
final int height = mSourceFull.height();
mSourcePartial.left = (int) (mSourceFraction.left * width);
mSourcePartial.top = (int) (mSourceFraction.top * height);
mSourcePartial.right = (int) (mSourceFraction.right * width);
mSourcePartial.bottom = (int) (mSourceFraction.bottom * height);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
updateSourcePartial();
// The logic below is mostly copied from the parent class, since we
// can't update private mBounds variable.
// http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;
// f=core/java/android/view/TouchDelegate.java;hb=eclair#l98
final Rect sourcePartial = mSourcePartial;
final View target = mTarget;
int x = (int)event.getX();
int y = (int)event.getY();
boolean sendToDelegate = false;
boolean hit = true;
boolean handled = false;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (sourcePartial.contains(x, y)) {
mDelegateTargeted = true;
sendToDelegate = true;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_MOVE:
sendToDelegate = mDelegateTargeted;
if (sendToDelegate) {
if (!sourcePartial.contains(x, y)) {
hit = false;
}
}
break;
case MotionEvent.ACTION_CANCEL:
sendToDelegate = mDelegateTargeted;
mDelegateTargeted = false;
break;
}
if (sendToDelegate) {
if (hit) {
event.setLocation(target.getWidth() / 2, target.getHeight() / 2);
} else {
event.setLocation(-1, -1);
}
handled = target.dispatchTouchEvent(event);
}
return handled;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/FractionalTouchDelegate.java | Java | asf20 | 5,324 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.appwidget.MyScheduleWidgetProvider;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.sync.ScheduleUpdaterService;
import com.google.android.apps.iosched.ui.MapFragment;
import com.google.android.apps.iosched.ui.SocialStreamActivity;
import com.google.android.apps.iosched.ui.SocialStreamFragment;
import com.actionbarsherlock.view.MenuItem;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ShareCompat;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Helper class for dealing with common actions to take on a session.
*/
public final class SessionsHelper {
private static final String TAG = makeLogTag(SessionsHelper.class);
private final Activity mActivity;
public SessionsHelper(Activity activity) {
mActivity = activity;
}
public void startMapActivity(String roomId) {
Intent intent = new Intent(mActivity.getApplicationContext(),
UIUtils.getMapActivityClass(mActivity));
intent.putExtra(MapFragment.EXTRA_ROOM, roomId);
mActivity.startActivity(intent);
}
public Intent createShareIntent(int messageTemplateResId, String title, String hashtags,
String url) {
ShareCompat.IntentBuilder builder = ShareCompat.IntentBuilder.from(mActivity)
.setType("text/plain")
.setText(mActivity.getString(messageTemplateResId,
title, UIUtils.getSessionHashtagsString(hashtags), url));
return builder.getIntent();
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void tryConfigureShareMenuItem(MenuItem menuItem, int messageTemplateResId,
final String title, String hashtags, String url) {
// TODO: uncomment pending ShareActionProvider fixes for split AB
// if (UIUtils.hasICS()) {
// ActionProvider itemProvider = menuItem.getActionProvider();
// ShareActionProvider provider;
// if (!(itemProvider instanceof ShareActionProvider)) {
// provider = new ShareActionProvider(mActivity);
// } else {
// provider = (ShareActionProvider) itemProvider;
// }
// provider.setShareIntent(createShareIntent(messageTemplateResId, title, hashtags, url));
// provider.setOnShareTargetSelectedListener(new OnShareTargetSelectedListener() {
// @Override
// public boolean onShareTargetSelected(ShareActionProvider source, Intent intent) {
// EasyTracker.getTracker().trackEvent("Session", "Shared", title, 0L);
// LOGD("Tracker", "Shared: " + title);
// return false;
// }
// });
//
// menuItem.setActionProvider(provider);
// }
}
public void shareSession(Context context, int messageTemplateResId, String title,
String hashtags, String url) {
EasyTracker.getTracker().trackEvent("Session", "Shared", title, 0L);
LOGD("Tracker", "Shared: " + title);
context.startActivity(Intent.createChooser(
createShareIntent(messageTemplateResId, title, hashtags, url),
context.getString(R.string.title_share)));
}
public void setSessionStarred(Uri sessionUri, boolean starred, String title) {
LOGD(TAG, "setSessionStarred uri=" + sessionUri + " starred=" +
starred + " title=" + title);
sessionUri = ScheduleContract.addCallerIsSyncAdapterParameter(sessionUri);
final ContentValues values = new ContentValues();
values.put(ScheduleContract.Sessions.SESSION_STARRED, starred);
AsyncQueryHandler handler =
new AsyncQueryHandler(mActivity.getContentResolver()) {
};
handler.startUpdate(-1, null, sessionUri, values, null, null);
EasyTracker.getTracker().trackEvent(
"Session", starred ? "Starred" : "Unstarred", title, 0L);
// Because change listener is set to null during initialization, these
// won't fire on pageview.
final Intent refreshIntent = new Intent(mActivity, MyScheduleWidgetProvider.class);
refreshIntent.setAction(MyScheduleWidgetProvider.REFRESH_ACTION);
mActivity.sendBroadcast(refreshIntent);
// Sync to the cloud.
final Intent updateServerIntent = new Intent(mActivity, ScheduleUpdaterService.class);
updateServerIntent.putExtra(ScheduleUpdaterService.EXTRA_SESSION_ID,
ScheduleContract.Sessions.getSessionId(sessionUri));
updateServerIntent.putExtra(ScheduleUpdaterService.EXTRA_IN_SCHEDULE, starred);
mActivity.startService(updateServerIntent);
}
public void startSocialStream(String hashtags) {
Intent intent = new Intent(mActivity, SocialStreamActivity.class);
intent.putExtra(SocialStreamFragment.EXTRA_QUERY, hashtags);
mActivity.startActivity(intent);
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/SessionsHelper.java | Java | asf20 | 6,116 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import java.util.ArrayList;
import java.util.Collections;
/**
* Provides static methods for creating {@code List} instances easily, and other
* utility methods for working with lists.
*/
public class Lists {
/**
* Creates an empty {@code ArrayList} instance.
*
* <p><b>Note:</b> if you only need an <i>immutable</i> empty List, use
* {@link Collections#emptyList} instead.
*
* @return a newly-created, initially-empty {@code ArrayList}
*/
public static <E> ArrayList<E> newArrayList() {
return new ArrayList<E>();
}
/**
* Creates a resizable {@code ArrayList} instance containing the given
* elements.
*
* <p><b>Note:</b> due to a bug in javac 1.5.0_06, we cannot support the
* following:
*
* <p>{@code List<Base> list = Lists.newArrayList(sub1, sub2);}
*
* <p>where {@code sub1} and {@code sub2} are references to subtypes of
* {@code Base}, not of {@code Base} itself. To get around this, you must
* use:
*
* <p>{@code List<Base> list = Lists.<Base>newArrayList(sub1, sub2);}
*
* @param elements the elements that the list should contain, in order
* @return a newly-created {@code ArrayList} containing those elements
*/
public static <E> ArrayList<E> newArrayList(E... elements) {
int capacity = (elements.length * 110) / 100 + 5;
ArrayList<E> list = new ArrayList<E>(capacity);
Collections.addAll(list, elements);
return list;
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/Lists.java | Java | asf20 | 2,170 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import com.google.android.apps.iosched.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.TextView;
/**
* A set of helper methods for showing contextual help information in the app.
*/
public class HelpUtils {
public static boolean hasSeenTutorial(final Context context, String id) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean("seen_tutorial_" + id, false);
}
private static void setSeenTutorial(final Context context, final String id) {
//noinspection unchecked
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putBoolean("seen_tutorial_" + id, true).commit();
return null;
}
}.execute();
}
public static void maybeShowAddToScheduleTutorial(FragmentActivity activity) {
if (hasSeenTutorial(activity, "add_to_schedule")) {
return;
}
// DialogFragment.show() will take care of adding the fragment
// in a transaction. We also want to remove any currently showing
// dialog, so make our own transaction and take care of that here.
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("dialog_add_to_schedule");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
new AddToScheduleTutorialDialog().show(ft, "dialog_add_to_schedule");
setSeenTutorial(activity, "add_to_schedule");
}
public static class AddToScheduleTutorialDialog extends DialogFragment implements
Html.ImageGetter {
public AddToScheduleTutorialDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
TextView tutorialBodyView = (TextView) layoutInflater.inflate(
R.layout.dialog_tutorial_message, null);
tutorialBodyView.setText(
Html.fromHtml(getString(R.string.help_add_to_schedule), this, null));
tutorialBodyView.setContentDescription(
Html.fromHtml(getString(R.string.help_add_to_schedule_alt)));
return new AlertDialog.Builder(getActivity())
.setView(tutorialBodyView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
)
.create();
}
@Override
public Drawable getDrawable(String url) {
if ("add_to_schedule".equals(url)) {
Resources res = getActivity().getResources();
Drawable d = res.getDrawable(R.drawable.help_add_to_schedule);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
return d;
}
return null;
}
}
public static void showAbout(FragmentActivity activity) {
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("dialog_about");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
new AboutDialog().show(ft, "dialog_about");
}
public static class AboutDialog extends DialogFragment {
private static final String VERSION_UNAVAILABLE = "N/A";
public AboutDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get app version
PackageManager pm = getActivity().getPackageManager();
String packageName = getActivity().getPackageName();
String versionName;
try {
PackageInfo info = pm.getPackageInfo(packageName, 0);
versionName = info.versionName;
} catch (PackageManager.NameNotFoundException e) {
versionName = VERSION_UNAVAILABLE;
}
// Build the about body view and append the link to see OSS licenses
SpannableStringBuilder aboutBody = new SpannableStringBuilder();
aboutBody.append(Html.fromHtml(getString(R.string.about_body, versionName)));
SpannableString licensesLink = new SpannableString(getString(R.string.about_licenses));
licensesLink.setSpan(new ClickableSpan() {
@Override
public void onClick(View view) {
HelpUtils.showOpenSourceLicenses(getActivity());
}
}, 0, licensesLink.length(), 0);
aboutBody.append("\n\n");
aboutBody.append(licensesLink);
SpannableString eulaLink = new SpannableString(getString(R.string.about_eula));
eulaLink.setSpan(new ClickableSpan() {
@Override
public void onClick(View view) {
HelpUtils.showEula(getActivity());
}
}, 0, eulaLink.length(), 0);
aboutBody.append("\n\n");
aboutBody.append(eulaLink);
LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
TextView aboutBodyView = (TextView) layoutInflater.inflate(R.layout.dialog_about, null);
aboutBodyView.setText(aboutBody);
aboutBodyView.setMovementMethod(new LinkMovementMethod());
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.title_about)
.setView(aboutBodyView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
)
.create();
}
}
public static void showOpenSourceLicenses(FragmentActivity activity) {
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("dialog_licenses");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
new OpenSourceLicensesDialog().show(ft, "dialog_licenses");
}
public static class OpenSourceLicensesDialog extends DialogFragment {
public OpenSourceLicensesDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
WebView webView = new WebView(getActivity());
webView.loadUrl("file:///android_asset/licenses.html");
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.about_licenses)
.setView(webView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
)
.create();
}
}
public static void showEula(FragmentActivity activity) {
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("dialog_eula");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
new EulaDialog().show(ft, "dialog_eula");
}
public static class EulaDialog extends DialogFragment {
public EulaDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int padding = getResources().getDimensionPixelSize(R.dimen.content_padding_normal);
TextView eulaTextView = new TextView(getActivity());
eulaTextView.setText(Html.fromHtml(getString(R.string.eula_text)));
eulaTextView.setMovementMethod(LinkMovementMethod.getInstance());
eulaTextView.setPadding(padding, padding, padding, padding);
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.about_eula)
.setView(eulaTextView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
)
.create();
}
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/HelpUtils.java | Java | asf20 | 11,150 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Modifications:
* -Imported from AOSP frameworks/base/core/java/com/android/internal/content
* -Changed package name
*/
package com.google.android.apps.iosched.util;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Helper for building selection clauses for {@link SQLiteDatabase}. Each
* appended clause is combined using {@code AND}. This class is <em>not</em>
* thread safe.
*/
public class SelectionBuilder {
private static final String TAG = makeLogTag(SelectionBuilder.class);
private String mTable = null;
private Map<String, String> mProjectionMap = Maps.newHashMap();
private StringBuilder mSelection = new StringBuilder();
private ArrayList<String> mSelectionArgs = Lists.newArrayList();
/**
* Reset any internal state, allowing this builder to be recycled.
*/
public SelectionBuilder reset() {
mTable = null;
mSelection.setLength(0);
mSelectionArgs.clear();
return this;
}
/**
* Append the given selection clause to the internal state. Each clause is
* surrounded with parenthesis and combined using {@code AND}.
*/
public SelectionBuilder where(String selection, String... selectionArgs) {
if (TextUtils.isEmpty(selection)) {
if (selectionArgs != null && selectionArgs.length > 0) {
throw new IllegalArgumentException(
"Valid selection required when including arguments=");
}
// Shortcut when clause is empty
return this;
}
if (mSelection.length() > 0) {
mSelection.append(" AND ");
}
mSelection.append("(").append(selection).append(")");
if (selectionArgs != null) {
Collections.addAll(mSelectionArgs, selectionArgs);
}
return this;
}
public SelectionBuilder table(String table) {
mTable = table;
return this;
}
private void assertTable() {
if (mTable == null) {
throw new IllegalStateException("Table not specified");
}
}
public SelectionBuilder mapToTable(String column, String table) {
mProjectionMap.put(column, table + "." + column);
return this;
}
public SelectionBuilder map(String fromColumn, String toClause) {
mProjectionMap.put(fromColumn, toClause + " AS " + fromColumn);
return this;
}
/**
* Return selection string for current internal state.
*
* @see #getSelectionArgs()
*/
public String getSelection() {
return mSelection.toString();
}
/**
* Return selection arguments for current internal state.
*
* @see #getSelection()
*/
public String[] getSelectionArgs() {
return mSelectionArgs.toArray(new String[mSelectionArgs.size()]);
}
private void mapColumns(String[] columns) {
for (int i = 0; i < columns.length; i++) {
final String target = mProjectionMap.get(columns[i]);
if (target != null) {
columns[i] = target;
}
}
}
@Override
public String toString() {
return "SelectionBuilder[table=" + mTable + ", selection=" + getSelection()
+ ", selectionArgs=" + Arrays.toString(getSelectionArgs()) + "]";
}
/**
* Execute query using the current internal state as {@code WHERE} clause.
*/
public Cursor query(SQLiteDatabase db, String[] columns, String orderBy) {
return query(db, columns, null, null, orderBy, null);
}
/**
* Execute query using the current internal state as {@code WHERE} clause.
*/
public Cursor query(SQLiteDatabase db, String[] columns, String groupBy,
String having, String orderBy, String limit) {
assertTable();
if (columns != null) mapColumns(columns);
LOGV(TAG, "query(columns=" + Arrays.toString(columns) + ") " + this);
return db.query(mTable, columns, getSelection(), getSelectionArgs(), groupBy, having,
orderBy, limit);
}
/**
* Execute update using the current internal state as {@code WHERE} clause.
*/
public int update(SQLiteDatabase db, ContentValues values) {
assertTable();
LOGV(TAG, "update() " + this);
return db.update(mTable, values, getSelection(), getSelectionArgs());
}
/**
* Execute delete using the current internal state as {@code WHERE} clause.
*/
public int delete(SQLiteDatabase db) {
assertTable();
LOGV(TAG, "delete() " + this);
return db.delete(mTable, getSelection(), getSelectionArgs());
}
}
| zzxxasp-key | android/src/com/google/android/apps/iosched/util/SelectionBuilder.java | Java | asf20 | 5,630 |